From 6b18b6730b1f3c95bd1f6bc0ee0e4c0e87bb93f2 Mon Sep 17 00:00:00 2001 From: David Blass Date: Wed, 25 Mar 2026 19:35:31 +0000 Subject: [PATCH] live todo tracking, collapsible task list in final progress, hide set_output outside standalone (#492) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix false "without reporting progress" error + live todo tracking clean up orphaned progress comments when review is skipped or only set_output is used, preventing the false positive in handleAgentResult. parse todowrite events from OpenCode's NDJSON stream and render a live markdown checklist in the PR progress comment (2s debounce). agent's explicit report_progress always takes priority. Made-with: Cursor * fix contradictory review/progress prompting align Review and IncrementalReview mode prompts with their guidance — mode prompts said "always submit" while guidance said "skip if clean." remove the empty-approval submission that was silently dropped by the tool. make progress comment lifecycle explicit: created on first call, updated in place, removed after review submission. Made-with: Cursor * centralize todo tracking into shared TodoTracker module extract inline todo tracking logic (~95 lines) from opentoad.ts into action/utils/todoTracking.ts. the tracker is created once in main.ts and passed to agents via AgentRunContext.todoTracker, making it agent-agnostic and reusable for future agent implementations. Made-with: Cursor * fix todoTracker optional type to match file convention add | undefined to todoTracker in AgentRunContext, matching every other optional property in the same interface. Made-with: Cursor * instruct agents to always maintain a task list for live progress system prompt now tells agents to create an internal task list at the start of every run. the tracker renders it to the progress comment automatically. report_progress is reserved for final results only — no more intermediate "Checking..." messages that cancel the tracker and leave stale text on the comment. Made-with: Cursor * require report_progress summary at end of every run agents must always call report_progress with a final summary — the completed task list should never be the end state of the progress comment. updated all review mode prompts to call report_progress after submitting (or not submitting) a review. Made-with: Cursor * keep progress comment after review with final summary stop deleting the progress comment after review submission — the agent now always calls report_progress with a summary at the end, and that summary should persist as a record of what was done. Made-with: Cursor * harden stranded progress comment cleanup - main.ts: detect when tracker was last writer (agent never called report_progress) and delete the stranded checklist instead of leaving it as the final comment state - postCleanup.ts: expand stuck-comment detection to also catch stranded todo checklists (regex match for checklist patterns) when the process is killed before normal cleanup runs - modes.ts + selectMode.ts: add report_progress step to Summarize and SummaryUpdate modes (only modes that were missing it) Made-with: Cursor * fix stale comments, typo, and build mode redundancy - comment.ts: update deleteProgressComment docstring and inline comment to reflect current usage (stranded-comment cleanup, not post-review) - modes.ts: merge duplicate report_progress steps (8 + 10) into single step 9, fix "optimizatfixons" typo - wiki/post-cleanup.md: document checklist detection regex Made-with: Cursor * collapsible completed todos in final progress, hide set_output outside standalone mode - add renderCollapsible() to TodoTracker, append completed task list as
section when agent calls report_progress - cancel tracker after agent's final report_progress so it doesn't overwrite with raw checklist - conditionally register SetOutputTool only in standalone mode or when output_schema is provided - remove unconditional set_output instruction from orchestrator task section - update Summarize/SummaryUpdate mode guidance to not reference set_output Made-with: Cursor * show completion count in collapsible task list summary Made-with: Cursor * only count completed (not cancelled) in collapsible task list summary Made-with: Cursor * reinforce concise summary prompting across system prompt, modes, and tool description Made-with: Cursor * address review feedback: wasUpdated bypass, tracker false-positive, race condition - remove wasUpdated=true from cleanup paths so handleAgentResult correctly detects genuinely silent runs - add hadProgressComment to ToolState as immutable snapshot for the safety check - use todoTracker.hasPublished instead of enabled for stranded-comment cleanup - serialize onUpdate calls via inflightPromise chain with post-cancel guard - add settled() to wait for in-flight updates before writing final summary Made-with: Cursor * address round-2 review: hasPublished after success, finalSummaryWritten flag - set hasPublished only after onUpdate resolves (not before) so failed writes are not counted as published - add finalSummaryWritten flag to ToolState, set after successful non-plan reportProgress; decouple cleanup detection from todoTracker.enabled so it survives API failures where cancel() ran but the write didn't succeed Made-with: Cursor --- agents/opentoad.ts | 21 + agents/shared.ts | 2 + entry | 41364 ++++++++++++++++++++------------------- main.ts | 38 +- mcp/comment.ts | 31 +- mcp/review.ts | 1 + mcp/selectMode.ts | 20 +- mcp/server.ts | 15 +- modes.ts | 33 +- post | 7 +- utils/instructions.ts | 10 +- utils/postCleanup.ts | 11 +- utils/reviewCleanup.ts | 3 - utils/run.ts | 2 +- utils/todoTracking.ts | 154 + 15 files changed, 21063 insertions(+), 20649 deletions(-) create mode 100644 utils/todoTracking.ts diff --git a/agents/opentoad.ts b/agents/opentoad.ts index 616551d..6033ff9 100644 --- a/agents/opentoad.ts +++ b/agents/opentoad.ts @@ -21,6 +21,7 @@ import { log } from "../utils/cli.ts"; import { installFromNpmTarball } from "../utils/install.ts"; import { spawn } from "../utils/subprocess.ts"; import { ThinkingTimer } from "../utils/timer.ts"; +import type { TodoTracker } from "../utils/todoTracking.ts"; import { type AgentResult, type AgentRunContext, type AgentUsage, agent } from "./shared.ts"; // pinned CLI version @@ -294,6 +295,7 @@ type RunParams = { args: string[]; cwd: string; env: Record; + todoTracker?: TodoTracker | undefined; }; async function runOpenCode(params: RunParams): Promise { @@ -394,6 +396,17 @@ async function runOpenCode(params: RunParams): Promise { if (event.part?.state?.status === "completed" && event.part.state.output) { log.debug(` output: ${event.part.state.output}`); } + + // agent's explicit MCP report_progress takes priority over todo tracking + if (toolName.includes("report_progress") && params.todoTracker) { + log.debug("» report_progress detected, disabling todo tracking"); + params.todoTracker.cancel(); + } + + // parse todowrite events for live progress tracking + if (toolName === "todowrite" && params.todoTracker?.enabled) { + params.todoTracker.update(event.part?.state?.input); + } }, tool_result: (event: OpenCodeToolResultEvent) => { const toolId = event.part?.callID || event.tool_id; @@ -535,6 +548,12 @@ async function runOpenCode(params: RunParams): Promise { }, }); + if (result.exitCode === 0) { + await params.todoTracker?.flush(); + } else { + params.todoTracker?.cancel(); + } + const duration = performance.now() - startTime; log.info( `» ${params.label} completed in ${Math.round(duration)}ms with exit code ${result.exitCode}` @@ -588,6 +607,7 @@ async function runOpenCode(params: RunParams): Promise { return { success: true, output: finalOutput || output, usage }; } catch (error) { + params.todoTracker?.cancel(); const duration = performance.now() - startTime; const errorMessage = error instanceof Error ? error.message : String(error); const isActivityTimeout = errorMessage.includes("activity timeout"); @@ -659,6 +679,7 @@ export const opentoad = agent({ args, cwd: repoDir, env, + todoTracker: ctx.todoTracker, }); }, }); diff --git a/agents/shared.ts b/agents/shared.ts index a55a444..0f3db38 100644 --- a/agents/shared.ts +++ b/agents/shared.ts @@ -1,6 +1,7 @@ import { log } from "../utils/cli.ts"; import type { ResolvedInstructions } from "../utils/instructions.ts"; import type { ResolvedPayload } from "../utils/payload.ts"; +import type { TodoTracker } from "../utils/todoTracking.ts"; /** * token/cost usage data from a single agent run @@ -33,6 +34,7 @@ export interface AgentRunContext { mcpServerUrl: string; tmpdir: string; instructions: ResolvedInstructions; + todoTracker?: TodoTracker | undefined; } export interface Agent { diff --git a/entry b/entry index 552f5f2..efd25f0 100755 --- a/entry +++ b/entry @@ -19866,6 +19866,7105 @@ Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); } }); +// node_modules/.pnpm/ansi-regex@5.0.1/node_modules/ansi-regex/index.js +var require_ansi_regex = __commonJS({ + "node_modules/.pnpm/ansi-regex@5.0.1/node_modules/ansi-regex/index.js"(exports, module) { + "use strict"; + module.exports = ({ onlyFirst = false } = {}) => { + const pattern = [ + "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)", + "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))" + ].join("|"); + return new RegExp(pattern, onlyFirst ? void 0 : "g"); + }; + } +}); + +// node_modules/.pnpm/strip-ansi@6.0.1/node_modules/strip-ansi/index.js +var require_strip_ansi = __commonJS({ + "node_modules/.pnpm/strip-ansi@6.0.1/node_modules/strip-ansi/index.js"(exports, module) { + "use strict"; + var ansiRegex = require_ansi_regex(); + module.exports = (string6) => typeof string6 === "string" ? string6.replace(ansiRegex(), "") : string6; + } +}); + +// node_modules/.pnpm/is-fullwidth-code-point@3.0.0/node_modules/is-fullwidth-code-point/index.js +var require_is_fullwidth_code_point = __commonJS({ + "node_modules/.pnpm/is-fullwidth-code-point@3.0.0/node_modules/is-fullwidth-code-point/index.js"(exports, module) { + "use strict"; + var isFullwidthCodePoint = (codePoint) => { + if (Number.isNaN(codePoint)) { + return false; + } + if (codePoint >= 4352 && (codePoint <= 4447 || // Hangul Jamo + codePoint === 9001 || // LEFT-POINTING ANGLE BRACKET + codePoint === 9002 || // RIGHT-POINTING ANGLE BRACKET + // CJK Radicals Supplement .. Enclosed CJK Letters and Months + 11904 <= codePoint && codePoint <= 12871 && codePoint !== 12351 || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A + 12880 <= codePoint && codePoint <= 19903 || // CJK Unified Ideographs .. Yi Radicals + 19968 <= codePoint && codePoint <= 42182 || // Hangul Jamo Extended-A + 43360 <= codePoint && codePoint <= 43388 || // Hangul Syllables + 44032 <= codePoint && codePoint <= 55203 || // CJK Compatibility Ideographs + 63744 <= codePoint && codePoint <= 64255 || // Vertical Forms + 65040 <= codePoint && codePoint <= 65049 || // CJK Compatibility Forms .. Small Form Variants + 65072 <= codePoint && codePoint <= 65131 || // Halfwidth and Fullwidth Forms + 65281 <= codePoint && codePoint <= 65376 || 65504 <= codePoint && codePoint <= 65510 || // Kana Supplement + 110592 <= codePoint && codePoint <= 110593 || // Enclosed Ideographic Supplement + 127488 <= codePoint && codePoint <= 127569 || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane + 131072 <= codePoint && codePoint <= 262141)) { + return true; + } + return false; + }; + module.exports = isFullwidthCodePoint; + module.exports.default = isFullwidthCodePoint; + } +}); + +// node_modules/.pnpm/emoji-regex@8.0.0/node_modules/emoji-regex/index.js +var require_emoji_regex = __commonJS({ + "node_modules/.pnpm/emoji-regex@8.0.0/node_modules/emoji-regex/index.js"(exports, module) { + "use strict"; + module.exports = function() { + return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; + }; + } +}); + +// node_modules/.pnpm/string-width@4.2.3/node_modules/string-width/index.js +var require_string_width = __commonJS({ + "node_modules/.pnpm/string-width@4.2.3/node_modules/string-width/index.js"(exports, module) { + "use strict"; + var stripAnsi = require_strip_ansi(); + var isFullwidthCodePoint = require_is_fullwidth_code_point(); + var emojiRegex3 = require_emoji_regex(); + var stringWidth = (string6) => { + if (typeof string6 !== "string" || string6.length === 0) { + return 0; + } + string6 = stripAnsi(string6); + if (string6.length === 0) { + return 0; + } + string6 = string6.replace(emojiRegex3(), " "); + let width = 0; + for (let i = 0; i < string6.length; i++) { + const code = string6.codePointAt(i); + if (code <= 31 || code >= 127 && code <= 159) { + continue; + } + if (code >= 768 && code <= 879) { + continue; + } + if (code > 65535) { + i++; + } + width += isFullwidthCodePoint(code) ? 2 : 1; + } + return width; + }; + module.exports = stringWidth; + module.exports.default = stringWidth; + } +}); + +// node_modules/.pnpm/astral-regex@2.0.0/node_modules/astral-regex/index.js +var require_astral_regex = __commonJS({ + "node_modules/.pnpm/astral-regex@2.0.0/node_modules/astral-regex/index.js"(exports, module) { + "use strict"; + var regex4 = "[\uD800-\uDBFF][\uDC00-\uDFFF]"; + var astralRegex = (options) => options && options.exact ? new RegExp(`^${regex4}$`) : new RegExp(regex4, "g"); + module.exports = astralRegex; + } +}); + +// node_modules/.pnpm/color-name@1.1.4/node_modules/color-name/index.js +var require_color_name = __commonJS({ + "node_modules/.pnpm/color-name@1.1.4/node_modules/color-name/index.js"(exports, module) { + "use strict"; + module.exports = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] + }; + } +}); + +// node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/conversions.js +var require_conversions = __commonJS({ + "node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/conversions.js"(exports, module) { + var cssKeywords = require_color_name(); + var reverseKeywords = {}; + for (const key of Object.keys(cssKeywords)) { + reverseKeywords[cssKeywords[key]] = key; + } + var convert = { + rgb: { channels: 3, labels: "rgb" }, + hsl: { channels: 3, labels: "hsl" }, + hsv: { channels: 3, labels: "hsv" }, + hwb: { channels: 3, labels: "hwb" }, + cmyk: { channels: 4, labels: "cmyk" }, + xyz: { channels: 3, labels: "xyz" }, + lab: { channels: 3, labels: "lab" }, + lch: { channels: 3, labels: "lch" }, + hex: { channels: 1, labels: ["hex"] }, + keyword: { channels: 1, labels: ["keyword"] }, + ansi16: { channels: 1, labels: ["ansi16"] }, + ansi256: { channels: 1, labels: ["ansi256"] }, + hcg: { channels: 3, labels: ["h", "c", "g"] }, + apple: { channels: 3, labels: ["r16", "g16", "b16"] }, + gray: { channels: 1, labels: ["gray"] } + }; + module.exports = convert; + for (const model of Object.keys(convert)) { + if (!("channels" in convert[model])) { + throw new Error("missing channels property: " + model); + } + if (!("labels" in convert[model])) { + throw new Error("missing channel labels property: " + model); + } + if (convert[model].labels.length !== convert[model].channels) { + throw new Error("channel and label counts mismatch: " + model); + } + const { channels, labels } = convert[model]; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], "channels", { value: channels }); + Object.defineProperty(convert[model], "labels", { value: labels }); + } + convert.rgb.hsl = function(rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const min = Math.min(r, g, b); + const max = Math.max(r, g, b); + const delta = max - min; + let h; + let s; + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; + } + h = Math.min(h * 60, 360); + if (h < 0) { + h += 360; + } + const l = (min + max) / 2; + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } + return [h, s * 100, l * 100]; + }; + convert.rgb.hsv = function(rgb) { + let rdif; + let gdif; + let bdif; + let h; + let s; + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const v = Math.max(r, g, b); + const diff = v - Math.min(r, g, b); + const diffc = function(c) { + return (v - c) / 6 / diff + 1 / 2; + }; + if (diff === 0) { + h = 0; + s = 0; + } else { + s = diff / v; + rdif = diffc(r); + gdif = diffc(g); + bdif = diffc(b); + if (r === v) { + h = bdif - gdif; + } else if (g === v) { + h = 1 / 3 + rdif - bdif; + } else if (b === v) { + h = 2 / 3 + gdif - rdif; + } + if (h < 0) { + h += 1; + } else if (h > 1) { + h -= 1; + } + } + return [ + h * 360, + s * 100, + v * 100 + ]; + }; + convert.rgb.hwb = function(rgb) { + const r = rgb[0]; + const g = rgb[1]; + let b = rgb[2]; + const h = convert.rgb.hsl(rgb)[0]; + const w = 1 / 255 * Math.min(r, Math.min(g, b)); + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); + return [h, w * 100, b * 100]; + }; + convert.rgb.cmyk = function(rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const k = Math.min(1 - r, 1 - g, 1 - b); + const c = (1 - r - k) / (1 - k) || 0; + const m = (1 - g - k) / (1 - k) || 0; + const y = (1 - b - k) / (1 - k) || 0; + return [c * 100, m * 100, y * 100, k * 100]; + }; + function comparativeDistance(x, y) { + return (x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 + (x[2] - y[2]) ** 2; + } + convert.rgb.keyword = function(rgb) { + const reversed = reverseKeywords[rgb]; + if (reversed) { + return reversed; + } + let currentClosestDistance = Infinity; + let currentClosestKeyword; + for (const keyword of Object.keys(cssKeywords)) { + const value2 = cssKeywords[keyword]; + const distance = comparativeDistance(rgb, value2); + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + return currentClosestKeyword; + }; + convert.keyword.rgb = function(keyword) { + return cssKeywords[keyword]; + }; + convert.rgb.xyz = function(rgb) { + let r = rgb[0] / 255; + let g = rgb[1] / 255; + let b = rgb[2] / 255; + r = r > 0.04045 ? ((r + 0.055) / 1.055) ** 2.4 : r / 12.92; + g = g > 0.04045 ? ((g + 0.055) / 1.055) ** 2.4 : g / 12.92; + b = b > 0.04045 ? ((b + 0.055) / 1.055) ** 2.4 : b / 12.92; + const x = r * 0.4124 + g * 0.3576 + b * 0.1805; + const y = r * 0.2126 + g * 0.7152 + b * 0.0722; + const z2 = r * 0.0193 + g * 0.1192 + b * 0.9505; + return [x * 100, y * 100, z2 * 100]; + }; + convert.rgb.lab = function(rgb) { + const xyz = convert.rgb.xyz(rgb); + let x = xyz[0]; + let y = xyz[1]; + let z2 = xyz[2]; + x /= 95.047; + y /= 100; + z2 /= 108.883; + x = x > 8856e-6 ? x ** (1 / 3) : 7.787 * x + 16 / 116; + y = y > 8856e-6 ? y ** (1 / 3) : 7.787 * y + 16 / 116; + z2 = z2 > 8856e-6 ? z2 ** (1 / 3) : 7.787 * z2 + 16 / 116; + const l = 116 * y - 16; + const a = 500 * (x - y); + const b = 200 * (y - z2); + return [l, a, b]; + }; + convert.hsl.rgb = function(hsl) { + const h = hsl[0] / 360; + const s = hsl[1] / 100; + const l = hsl[2] / 100; + let t2; + let t3; + let val; + if (s === 0) { + val = l * 255; + return [val, val, val]; + } + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } + const t1 = 2 * l - t2; + const rgb = [0, 0, 0]; + for (let i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + if (t3 < 0) { + t3++; + } + if (t3 > 1) { + t3--; + } + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + val = t2; + } else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + val = t1; + } + rgb[i] = val * 255; + } + return rgb; + }; + convert.hsl.hsv = function(hsl) { + const h = hsl[0]; + let s = hsl[1] / 100; + let l = hsl[2] / 100; + let smin = s; + const lmin = Math.max(l, 0.01); + l *= 2; + s *= l <= 1 ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + const v = (l + s) / 2; + const sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s); + return [h, sv * 100, v * 100]; + }; + convert.hsv.rgb = function(hsv) { + const h = hsv[0] / 60; + const s = hsv[1] / 100; + let v = hsv[2] / 100; + const hi = Math.floor(h) % 6; + const f = h - Math.floor(h); + const p = 255 * v * (1 - s); + const q = 255 * v * (1 - s * f); + const t = 255 * v * (1 - s * (1 - f)); + v *= 255; + switch (hi) { + case 0: + return [v, t, p]; + case 1: + return [q, v, p]; + case 2: + return [p, v, t]; + case 3: + return [p, q, v]; + case 4: + return [t, p, v]; + case 5: + return [v, p, q]; + } + }; + convert.hsv.hsl = function(hsv) { + const h = hsv[0]; + const s = hsv[1] / 100; + const v = hsv[2] / 100; + const vmin = Math.max(v, 0.01); + let sl; + let l; + l = (2 - s) * v; + const lmin = (2 - s) * vmin; + sl = s * vmin; + sl /= lmin <= 1 ? lmin : 2 - lmin; + sl = sl || 0; + l /= 2; + return [h, sl * 100, l * 100]; + }; + convert.hwb.rgb = function(hwb) { + const h = hwb[0] / 360; + let wh = hwb[1] / 100; + let bl = hwb[2] / 100; + const ratio = wh + bl; + let f; + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + const i = Math.floor(6 * h); + const v = 1 - bl; + f = 6 * h - i; + if ((i & 1) !== 0) { + f = 1 - f; + } + const n = wh + f * (v - wh); + let r; + let g; + let b; + switch (i) { + default: + case 6: + case 0: + r = v; + g = n; + b = wh; + break; + case 1: + r = n; + g = v; + b = wh; + break; + case 2: + r = wh; + g = v; + b = n; + break; + case 3: + r = wh; + g = n; + b = v; + break; + case 4: + r = n; + g = wh; + b = v; + break; + case 5: + r = v; + g = wh; + b = n; + break; + } + return [r * 255, g * 255, b * 255]; + }; + convert.cmyk.rgb = function(cmyk) { + const c = cmyk[0] / 100; + const m = cmyk[1] / 100; + const y = cmyk[2] / 100; + const k = cmyk[3] / 100; + const r = 1 - Math.min(1, c * (1 - k) + k); + const g = 1 - Math.min(1, m * (1 - k) + k); + const b = 1 - Math.min(1, y * (1 - k) + k); + return [r * 255, g * 255, b * 255]; + }; + convert.xyz.rgb = function(xyz) { + const x = xyz[0] / 100; + const y = xyz[1] / 100; + const z2 = xyz[2] / 100; + let r; + let g; + let b; + r = x * 3.2406 + y * -1.5372 + z2 * -0.4986; + g = x * -0.9689 + y * 1.8758 + z2 * 0.0415; + b = x * 0.0557 + y * -0.204 + z2 * 1.057; + r = r > 31308e-7 ? 1.055 * r ** (1 / 2.4) - 0.055 : r * 12.92; + g = g > 31308e-7 ? 1.055 * g ** (1 / 2.4) - 0.055 : g * 12.92; + b = b > 31308e-7 ? 1.055 * b ** (1 / 2.4) - 0.055 : b * 12.92; + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b = Math.min(Math.max(0, b), 1); + return [r * 255, g * 255, b * 255]; + }; + convert.xyz.lab = function(xyz) { + let x = xyz[0]; + let y = xyz[1]; + let z2 = xyz[2]; + x /= 95.047; + y /= 100; + z2 /= 108.883; + x = x > 8856e-6 ? x ** (1 / 3) : 7.787 * x + 16 / 116; + y = y > 8856e-6 ? y ** (1 / 3) : 7.787 * y + 16 / 116; + z2 = z2 > 8856e-6 ? z2 ** (1 / 3) : 7.787 * z2 + 16 / 116; + const l = 116 * y - 16; + const a = 500 * (x - y); + const b = 200 * (y - z2); + return [l, a, b]; + }; + convert.lab.xyz = function(lab) { + const l = lab[0]; + const a = lab[1]; + const b = lab[2]; + let x; + let y; + let z2; + y = (l + 16) / 116; + x = a / 500 + y; + z2 = y - b / 200; + const y2 = y ** 3; + const x2 = x ** 3; + const z22 = z2 ** 3; + y = y2 > 8856e-6 ? y2 : (y - 16 / 116) / 7.787; + x = x2 > 8856e-6 ? x2 : (x - 16 / 116) / 7.787; + z2 = z22 > 8856e-6 ? z22 : (z2 - 16 / 116) / 7.787; + x *= 95.047; + y *= 100; + z2 *= 108.883; + return [x, y, z2]; + }; + convert.lab.lch = function(lab) { + const l = lab[0]; + const a = lab[1]; + const b = lab[2]; + let h; + const hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; + if (h < 0) { + h += 360; + } + const c = Math.sqrt(a * a + b * b); + return [l, c, h]; + }; + convert.lch.lab = function(lch) { + const l = lch[0]; + const c = lch[1]; + const h = lch[2]; + const hr = h / 360 * 2 * Math.PI; + const a = c * Math.cos(hr); + const b = c * Math.sin(hr); + return [l, a, b]; + }; + convert.rgb.ansi16 = function(args2, saturation = null) { + const [r, g, b] = args2; + let value2 = saturation === null ? convert.rgb.hsv(args2)[2] : saturation; + value2 = Math.round(value2 / 50); + if (value2 === 0) { + return 30; + } + let ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255)); + if (value2 === 2) { + ansi += 60; + } + return ansi; + }; + convert.hsv.ansi16 = function(args2) { + return convert.rgb.ansi16(convert.hsv.rgb(args2), args2[2]); + }; + convert.rgb.ansi256 = function(args2) { + const r = args2[0]; + const g = args2[1]; + const b = args2[2]; + if (r === g && g === b) { + if (r < 8) { + return 16; + } + if (r > 248) { + return 231; + } + return Math.round((r - 8) / 247 * 24) + 232; + } + const ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5); + return ansi; + }; + convert.ansi16.rgb = function(args2) { + let color = args2 % 10; + if (color === 0 || color === 7) { + if (args2 > 50) { + color += 3.5; + } + color = color / 10.5 * 255; + return [color, color, color]; + } + const mult = (~~(args2 > 50) + 1) * 0.5; + const r = (color & 1) * mult * 255; + const g = (color >> 1 & 1) * mult * 255; + const b = (color >> 2 & 1) * mult * 255; + return [r, g, b]; + }; + convert.ansi256.rgb = function(args2) { + if (args2 >= 232) { + const c = (args2 - 232) * 10 + 8; + return [c, c, c]; + } + args2 -= 16; + let rem; + const r = Math.floor(args2 / 36) / 5 * 255; + const g = Math.floor((rem = args2 % 36) / 6) / 5 * 255; + const b = rem % 6 / 5 * 255; + return [r, g, b]; + }; + convert.rgb.hex = function(args2) { + const integer4 = ((Math.round(args2[0]) & 255) << 16) + ((Math.round(args2[1]) & 255) << 8) + (Math.round(args2[2]) & 255); + const string6 = integer4.toString(16).toUpperCase(); + return "000000".substring(string6.length) + string6; + }; + convert.hex.rgb = function(args2) { + const match3 = args2.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + if (!match3) { + return [0, 0, 0]; + } + let colorString = match3[0]; + if (match3[0].length === 3) { + colorString = colorString.split("").map((char) => { + return char + char; + }).join(""); + } + const integer4 = parseInt(colorString, 16); + const r = integer4 >> 16 & 255; + const g = integer4 >> 8 & 255; + const b = integer4 & 255; + return [r, g, b]; + }; + convert.rgb.hcg = function(rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const max = Math.max(Math.max(r, g), b); + const min = Math.min(Math.min(r, g), b); + const chroma = max - min; + let grayscale; + let hue; + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; + } + if (chroma <= 0) { + hue = 0; + } else if (max === r) { + hue = (g - b) / chroma % 6; + } else if (max === g) { + hue = 2 + (b - r) / chroma; + } else { + hue = 4 + (r - g) / chroma; + } + hue /= 6; + hue %= 1; + return [hue * 360, chroma * 100, grayscale * 100]; + }; + convert.hsl.hcg = function(hsl) { + const s = hsl[1] / 100; + const l = hsl[2] / 100; + const c = l < 0.5 ? 2 * s * l : 2 * s * (1 - l); + let f = 0; + if (c < 1) { + f = (l - 0.5 * c) / (1 - c); + } + return [hsl[0], c * 100, f * 100]; + }; + convert.hsv.hcg = function(hsv) { + const s = hsv[1] / 100; + const v = hsv[2] / 100; + const c = s * v; + let f = 0; + if (c < 1) { + f = (v - c) / (1 - c); + } + return [hsv[0], c * 100, f * 100]; + }; + convert.hcg.rgb = function(hcg) { + const h = hcg[0] / 360; + const c = hcg[1] / 100; + const g = hcg[2] / 100; + if (c === 0) { + return [g * 255, g * 255, g * 255]; + } + const pure = [0, 0, 0]; + const hi = h % 1 * 6; + const v = hi % 1; + const w = 1 - v; + let mg = 0; + switch (Math.floor(hi)) { + case 0: + pure[0] = 1; + pure[1] = v; + pure[2] = 0; + break; + case 1: + pure[0] = w; + pure[1] = 1; + pure[2] = 0; + break; + case 2: + pure[0] = 0; + pure[1] = 1; + pure[2] = v; + break; + case 3: + pure[0] = 0; + pure[1] = w; + pure[2] = 1; + break; + case 4: + pure[0] = v; + pure[1] = 0; + pure[2] = 1; + break; + default: + pure[0] = 1; + pure[1] = 0; + pure[2] = w; + } + mg = (1 - c) * g; + return [ + (c * pure[0] + mg) * 255, + (c * pure[1] + mg) * 255, + (c * pure[2] + mg) * 255 + ]; + }; + convert.hcg.hsv = function(hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + const v = c + g * (1 - c); + let f = 0; + if (v > 0) { + f = c / v; + } + return [hcg[0], f * 100, v * 100]; + }; + convert.hcg.hsl = function(hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + const l = g * (1 - c) + 0.5 * c; + let s = 0; + if (l > 0 && l < 0.5) { + s = c / (2 * l); + } else if (l >= 0.5 && l < 1) { + s = c / (2 * (1 - l)); + } + return [hcg[0], s * 100, l * 100]; + }; + convert.hcg.hwb = function(hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + const v = c + g * (1 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; + }; + convert.hwb.hcg = function(hwb) { + const w = hwb[1] / 100; + const b = hwb[2] / 100; + const v = 1 - b; + const c = v - w; + let g = 0; + if (c < 1) { + g = (v - c) / (1 - c); + } + return [hwb[0], c * 100, g * 100]; + }; + convert.apple.rgb = function(apple) { + return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255]; + }; + convert.rgb.apple = function(rgb) { + return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535]; + }; + convert.gray.rgb = function(args2) { + return [args2[0] / 100 * 255, args2[0] / 100 * 255, args2[0] / 100 * 255]; + }; + convert.gray.hsl = function(args2) { + return [0, 0, args2[0]]; + }; + convert.gray.hsv = convert.gray.hsl; + convert.gray.hwb = function(gray) { + return [0, 100, gray[0]]; + }; + convert.gray.cmyk = function(gray) { + return [0, 0, 0, gray[0]]; + }; + convert.gray.lab = function(gray) { + return [gray[0], 0, 0]; + }; + convert.gray.hex = function(gray) { + const val = Math.round(gray[0] / 100 * 255) & 255; + const integer4 = (val << 16) + (val << 8) + val; + const string6 = integer4.toString(16).toUpperCase(); + return "000000".substring(string6.length) + string6; + }; + convert.rgb.gray = function(rgb) { + const val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; + }; + } +}); + +// node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/route.js +var require_route = __commonJS({ + "node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/route.js"(exports, module) { + var conversions = require_conversions(); + function buildGraph() { + const graph = {}; + const models = Object.keys(conversions); + for (let len = models.length, i = 0; i < len; i++) { + graph[models[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + return graph; + } + function deriveBFS(fromModel) { + const graph = buildGraph(); + const queue = [fromModel]; + graph[fromModel].distance = 0; + while (queue.length) { + const current = queue.pop(); + const adjacents = Object.keys(conversions[current]); + for (let len = adjacents.length, i = 0; i < len; i++) { + const adjacent = adjacents[i]; + const node2 = graph[adjacent]; + if (node2.distance === -1) { + node2.distance = graph[current].distance + 1; + node2.parent = current; + queue.unshift(adjacent); + } + } + } + return graph; + } + function link(from, to) { + return function(args2) { + return to(from(args2)); + }; + } + function wrapConversion(toModel, graph) { + const path3 = [graph[toModel].parent, toModel]; + let fn2 = conversions[graph[toModel].parent][toModel]; + let cur = graph[toModel].parent; + while (graph[cur].parent) { + path3.unshift(graph[cur].parent); + fn2 = link(conversions[graph[cur].parent][cur], fn2); + cur = graph[cur].parent; + } + fn2.conversion = path3; + return fn2; + } + module.exports = function(fromModel) { + const graph = deriveBFS(fromModel); + const conversion = {}; + const models = Object.keys(graph); + for (let len = models.length, i = 0; i < len; i++) { + const toModel = models[i]; + const node2 = graph[toModel]; + if (node2.parent === null) { + continue; + } + conversion[toModel] = wrapConversion(toModel, graph); + } + return conversion; + }; + } +}); + +// node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/index.js +var require_color_convert = __commonJS({ + "node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/index.js"(exports, module) { + var conversions = require_conversions(); + var route = require_route(); + var convert = {}; + var models = Object.keys(conversions); + function wrapRaw(fn2) { + const wrappedFn = function(...args2) { + const arg0 = args2[0]; + if (arg0 === void 0 || arg0 === null) { + return arg0; + } + if (arg0.length > 1) { + args2 = arg0; + } + return fn2(args2); + }; + if ("conversion" in fn2) { + wrappedFn.conversion = fn2.conversion; + } + return wrappedFn; + } + function wrapRounded(fn2) { + const wrappedFn = function(...args2) { + const arg0 = args2[0]; + if (arg0 === void 0 || arg0 === null) { + return arg0; + } + if (arg0.length > 1) { + args2 = arg0; + } + const result = fn2(args2); + if (typeof result === "object") { + for (let len = result.length, i = 0; i < len; i++) { + result[i] = Math.round(result[i]); + } + } + return result; + }; + if ("conversion" in fn2) { + wrappedFn.conversion = fn2.conversion; + } + return wrappedFn; + } + models.forEach((fromModel) => { + convert[fromModel] = {}; + Object.defineProperty(convert[fromModel], "channels", { value: conversions[fromModel].channels }); + Object.defineProperty(convert[fromModel], "labels", { value: conversions[fromModel].labels }); + const routes = route(fromModel); + const routeModels = Object.keys(routes); + routeModels.forEach((toModel) => { + const fn2 = routes[toModel]; + convert[fromModel][toModel] = wrapRounded(fn2); + convert[fromModel][toModel].raw = wrapRaw(fn2); + }); + }); + module.exports = convert; + } +}); + +// node_modules/.pnpm/ansi-styles@4.3.0/node_modules/ansi-styles/index.js +var require_ansi_styles = __commonJS({ + "node_modules/.pnpm/ansi-styles@4.3.0/node_modules/ansi-styles/index.js"(exports, module) { + "use strict"; + var wrapAnsi16 = (fn2, offset) => (...args2) => { + const code = fn2(...args2); + return `\x1B[${code + offset}m`; + }; + var wrapAnsi256 = (fn2, offset) => (...args2) => { + const code = fn2(...args2); + return `\x1B[${38 + offset};5;${code}m`; + }; + var wrapAnsi16m = (fn2, offset) => (...args2) => { + const rgb = fn2(...args2); + return `\x1B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; + }; + var ansi2ansi = (n) => n; + var rgb2rgb = (r, g, b) => [r, g, b]; + var setLazyProperty = (object5, property, get2) => { + Object.defineProperty(object5, property, { + get: () => { + const value2 = get2(); + Object.defineProperty(object5, property, { + value: value2, + enumerable: true, + configurable: true + }); + return value2; + }, + enumerable: true, + configurable: true + }); + }; + var colorConvert; + var makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { + if (colorConvert === void 0) { + colorConvert = require_color_convert(); + } + const offset = isBackground ? 10 : 0; + const styles = {}; + for (const [sourceSpace, suite] of Object.entries(colorConvert)) { + const name = sourceSpace === "ansi16" ? "ansi" : sourceSpace; + if (sourceSpace === targetSpace) { + styles[name] = wrap(identity, offset); + } else if (typeof suite === "object") { + styles[name] = wrap(suite[targetSpace], offset); + } + } + return styles; + }; + function assembleStyles() { + const codes = /* @__PURE__ */ new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + // Bright color + blackBright: [90, 39], + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; + styles.color.gray = styles.color.blackBright; + styles.bgColor.bgGray = styles.bgColor.bgBlackBright; + styles.color.grey = styles.color.blackBright; + styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; + for (const [groupName, group2] of Object.entries(styles)) { + for (const [styleName, style] of Object.entries(group2)) { + styles[styleName] = { + open: `\x1B[${style[0]}m`, + close: `\x1B[${style[1]}m` + }; + group2[styleName] = styles[styleName]; + codes.set(style[0], style[1]); + } + Object.defineProperty(styles, groupName, { + value: group2, + enumerable: false + }); + } + Object.defineProperty(styles, "codes", { + value: codes, + enumerable: false + }); + styles.color.close = "\x1B[39m"; + styles.bgColor.close = "\x1B[49m"; + setLazyProperty(styles.color, "ansi", () => makeDynamicStyles(wrapAnsi16, "ansi16", ansi2ansi, false)); + setLazyProperty(styles.color, "ansi256", () => makeDynamicStyles(wrapAnsi256, "ansi256", ansi2ansi, false)); + setLazyProperty(styles.color, "ansi16m", () => makeDynamicStyles(wrapAnsi16m, "rgb", rgb2rgb, false)); + setLazyProperty(styles.bgColor, "ansi", () => makeDynamicStyles(wrapAnsi16, "ansi16", ansi2ansi, true)); + setLazyProperty(styles.bgColor, "ansi256", () => makeDynamicStyles(wrapAnsi256, "ansi256", ansi2ansi, true)); + setLazyProperty(styles.bgColor, "ansi16m", () => makeDynamicStyles(wrapAnsi16m, "rgb", rgb2rgb, true)); + return styles; + } + Object.defineProperty(module, "exports", { + enumerable: true, + get: assembleStyles + }); + } +}); + +// node_modules/.pnpm/slice-ansi@4.0.0/node_modules/slice-ansi/index.js +var require_slice_ansi = __commonJS({ + "node_modules/.pnpm/slice-ansi@4.0.0/node_modules/slice-ansi/index.js"(exports, module) { + "use strict"; + var isFullwidthCodePoint = require_is_fullwidth_code_point(); + var astralRegex = require_astral_regex(); + var ansiStyles = require_ansi_styles(); + var ESCAPES = [ + "\x1B", + "\x9B" + ]; + var wrapAnsi = (code) => `${ESCAPES[0]}[${code}m`; + var checkAnsi = (ansiCodes, isEscapes, endAnsiCode) => { + let output = []; + ansiCodes = [...ansiCodes]; + for (let ansiCode of ansiCodes) { + const ansiCodeOrigin = ansiCode; + if (ansiCode.includes(";")) { + ansiCode = ansiCode.split(";")[0][0] + "0"; + } + const item = ansiStyles.codes.get(Number.parseInt(ansiCode, 10)); + if (item) { + const indexEscape = ansiCodes.indexOf(item.toString()); + if (indexEscape === -1) { + output.push(wrapAnsi(isEscapes ? item : ansiCodeOrigin)); + } else { + ansiCodes.splice(indexEscape, 1); + } + } else if (isEscapes) { + output.push(wrapAnsi(0)); + break; + } else { + output.push(wrapAnsi(ansiCodeOrigin)); + } + } + if (isEscapes) { + output = output.filter((element, index) => output.indexOf(element) === index); + if (endAnsiCode !== void 0) { + const fistEscapeCode = wrapAnsi(ansiStyles.codes.get(Number.parseInt(endAnsiCode, 10))); + output = output.reduce((current, next2) => next2 === fistEscapeCode ? [next2, ...current] : [...current, next2], []); + } + } + return output.join(""); + }; + module.exports = (string6, begin, end) => { + const characters = [...string6]; + const ansiCodes = []; + let stringEnd = typeof end === "number" ? end : characters.length; + let isInsideEscape = false; + let ansiCode; + let visible = 0; + let output = ""; + for (const [index, character] of characters.entries()) { + let leftEscape = false; + if (ESCAPES.includes(character)) { + const code = /\d[^m]*/.exec(string6.slice(index, index + 18)); + ansiCode = code && code.length > 0 ? code[0] : void 0; + if (visible < stringEnd) { + isInsideEscape = true; + if (ansiCode !== void 0) { + ansiCodes.push(ansiCode); + } + } + } else if (isInsideEscape && character === "m") { + isInsideEscape = false; + leftEscape = true; + } + if (!isInsideEscape && !leftEscape) { + visible++; + } + if (!astralRegex({ exact: true }).test(character) && isFullwidthCodePoint(character.codePointAt())) { + visible++; + if (typeof end !== "number") { + stringEnd++; + } + } + if (visible > begin && visible <= stringEnd) { + output += character; + } else if (visible === begin && !isInsideEscape && ansiCode !== void 0) { + output = checkAnsi(ansiCodes); + } else if (visible >= stringEnd) { + output += checkAnsi(ansiCodes, true, ansiCode); + break; + } + } + return output; + }; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/getBorderCharacters.js +var require_getBorderCharacters = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/getBorderCharacters.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getBorderCharacters = void 0; + var getBorderCharacters = (name) => { + if (name === "honeywell") { + return { + topBody: "\u2550", + topJoin: "\u2564", + topLeft: "\u2554", + topRight: "\u2557", + bottomBody: "\u2550", + bottomJoin: "\u2567", + bottomLeft: "\u255A", + bottomRight: "\u255D", + bodyLeft: "\u2551", + bodyRight: "\u2551", + bodyJoin: "\u2502", + headerJoin: "\u252C", + joinBody: "\u2500", + joinLeft: "\u255F", + joinRight: "\u2562", + joinJoin: "\u253C", + joinMiddleDown: "\u252C", + joinMiddleUp: "\u2534", + joinMiddleLeft: "\u2524", + joinMiddleRight: "\u251C" + }; + } + if (name === "norc") { + return { + topBody: "\u2500", + topJoin: "\u252C", + topLeft: "\u250C", + topRight: "\u2510", + bottomBody: "\u2500", + bottomJoin: "\u2534", + bottomLeft: "\u2514", + bottomRight: "\u2518", + bodyLeft: "\u2502", + bodyRight: "\u2502", + bodyJoin: "\u2502", + headerJoin: "\u252C", + joinBody: "\u2500", + joinLeft: "\u251C", + joinRight: "\u2524", + joinJoin: "\u253C", + joinMiddleDown: "\u252C", + joinMiddleUp: "\u2534", + joinMiddleLeft: "\u2524", + joinMiddleRight: "\u251C" + }; + } + if (name === "ramac") { + return { + topBody: "-", + topJoin: "+", + topLeft: "+", + topRight: "+", + bottomBody: "-", + bottomJoin: "+", + bottomLeft: "+", + bottomRight: "+", + bodyLeft: "|", + bodyRight: "|", + bodyJoin: "|", + headerJoin: "+", + joinBody: "-", + joinLeft: "|", + joinRight: "|", + joinJoin: "|", + joinMiddleDown: "+", + joinMiddleUp: "+", + joinMiddleLeft: "+", + joinMiddleRight: "+" + }; + } + if (name === "void") { + return { + topBody: "", + topJoin: "", + topLeft: "", + topRight: "", + bottomBody: "", + bottomJoin: "", + bottomLeft: "", + bottomRight: "", + bodyLeft: "", + bodyRight: "", + bodyJoin: "", + headerJoin: "", + joinBody: "", + joinLeft: "", + joinRight: "", + joinJoin: "", + joinMiddleDown: "", + joinMiddleUp: "", + joinMiddleLeft: "", + joinMiddleRight: "" + }; + } + throw new Error('Unknown border template "' + name + '".'); + }; + exports.getBorderCharacters = getBorderCharacters; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/utils.js +var require_utils3 = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/utils.js"(exports) { + "use strict"; + var __importDefault = exports && exports.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isCellInRange = exports.areCellEqual = exports.calculateRangeCoordinate = exports.flatten = exports.extractTruncates = exports.sumArray = exports.sequence = exports.distributeUnevenly = exports.countSpaceSequence = exports.groupBySizes = exports.makeBorderConfig = exports.splitAnsi = exports.normalizeString = void 0; + var slice_ansi_1 = __importDefault(require_slice_ansi()); + var string_width_1 = __importDefault(require_string_width()); + var strip_ansi_1 = __importDefault(require_strip_ansi()); + var getBorderCharacters_1 = require_getBorderCharacters(); + var normalizeString = (input) => { + return input.replace(/\r\n/g, "\n"); + }; + exports.normalizeString = normalizeString; + var splitAnsi = (input) => { + const lengths = (0, strip_ansi_1.default)(input).split("\n").map(string_width_1.default); + const result = []; + let startIndex = 0; + lengths.forEach((length) => { + result.push(length === 0 ? "" : (0, slice_ansi_1.default)(input, startIndex, startIndex + length)); + startIndex += length + 1; + }); + return result; + }; + exports.splitAnsi = splitAnsi; + var makeBorderConfig = (border) => { + return { + ...(0, getBorderCharacters_1.getBorderCharacters)("honeywell"), + ...border + }; + }; + exports.makeBorderConfig = makeBorderConfig; + var groupBySizes = (array3, sizes) => { + let startIndex = 0; + return sizes.map((size) => { + const group2 = array3.slice(startIndex, startIndex + size); + startIndex += size; + return group2; + }); + }; + exports.groupBySizes = groupBySizes; + var countSpaceSequence = (input) => { + var _a2, _b; + return (_b = (_a2 = input.match(/\s+/g)) === null || _a2 === void 0 ? void 0 : _a2.length) !== null && _b !== void 0 ? _b : 0; + }; + exports.countSpaceSequence = countSpaceSequence; + var distributeUnevenly = (sum, length) => { + const result = Array.from({ length }).fill(Math.floor(sum / length)); + return result.map((element, index) => { + return element + (index < sum % length ? 1 : 0); + }); + }; + exports.distributeUnevenly = distributeUnevenly; + var sequence = (start, end) => { + return Array.from({ length: end - start + 1 }, (_, index) => { + return index + start; + }); + }; + exports.sequence = sequence; + var sumArray = (array3) => { + return array3.reduce((accumulator, element) => { + return accumulator + element; + }, 0); + }; + exports.sumArray = sumArray; + var extractTruncates = (config3) => { + return config3.columns.map(({ truncate }) => { + return truncate; + }); + }; + exports.extractTruncates = extractTruncates; + var flatten = (array3) => { + return [].concat(...array3); + }; + exports.flatten = flatten; + var calculateRangeCoordinate = (spanningCellConfig) => { + const { row, col, colSpan = 1, rowSpan = 1 } = spanningCellConfig; + return { + bottomRight: { + col: col + colSpan - 1, + row: row + rowSpan - 1 + }, + topLeft: { + col, + row + } + }; + }; + exports.calculateRangeCoordinate = calculateRangeCoordinate; + var areCellEqual = (cell1, cell2) => { + return cell1.row === cell2.row && cell1.col === cell2.col; + }; + exports.areCellEqual = areCellEqual; + var isCellInRange = (cell, { topLeft, bottomRight }) => { + return topLeft.row <= cell.row && cell.row <= bottomRight.row && topLeft.col <= cell.col && cell.col <= bottomRight.col; + }; + exports.isCellInRange = isCellInRange; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/alignString.js +var require_alignString = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/alignString.js"(exports) { + "use strict"; + var __importDefault = exports && exports.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.alignString = void 0; + var string_width_1 = __importDefault(require_string_width()); + var utils_1 = require_utils3(); + var alignLeft = (subject, width) => { + return subject + " ".repeat(width); + }; + var alignRight = (subject, width) => { + return " ".repeat(width) + subject; + }; + var alignCenter = (subject, width) => { + return " ".repeat(Math.floor(width / 2)) + subject + " ".repeat(Math.ceil(width / 2)); + }; + var alignJustify = (subject, width) => { + const spaceSequenceCount = (0, utils_1.countSpaceSequence)(subject); + if (spaceSequenceCount === 0) { + return alignLeft(subject, width); + } + const addingSpaces = (0, utils_1.distributeUnevenly)(width, spaceSequenceCount); + if (Math.max(...addingSpaces) > 3) { + return alignLeft(subject, width); + } + let spaceSequenceIndex = 0; + return subject.replace(/\s+/g, (groupSpace) => { + return groupSpace + " ".repeat(addingSpaces[spaceSequenceIndex++]); + }); + }; + var alignString = (subject, containerWidth, alignment) => { + const subjectWidth = (0, string_width_1.default)(subject); + if (subjectWidth === containerWidth) { + return subject; + } + if (subjectWidth > containerWidth) { + throw new Error("Subject parameter value width cannot be greater than the container width."); + } + if (subjectWidth === 0) { + return " ".repeat(containerWidth); + } + const availableWidth = containerWidth - subjectWidth; + if (alignment === "left") { + return alignLeft(subject, availableWidth); + } + if (alignment === "right") { + return alignRight(subject, availableWidth); + } + if (alignment === "justify") { + return alignJustify(subject, availableWidth); + } + return alignCenter(subject, availableWidth); + }; + exports.alignString = alignString; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/alignTableData.js +var require_alignTableData = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/alignTableData.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.alignTableData = void 0; + var alignString_1 = require_alignString(); + var alignTableData = (rows, config3) => { + return rows.map((row, rowIndex) => { + return row.map((cell, cellIndex) => { + var _a2; + const { width, alignment } = config3.columns[cellIndex]; + const containingRange = (_a2 = config3.spanningCellManager) === null || _a2 === void 0 ? void 0 : _a2.getContainingRange({ + col: cellIndex, + row: rowIndex + }, { mapped: true }); + if (containingRange) { + return cell; + } + return (0, alignString_1.alignString)(cell, width, alignment); + }); + }); + }; + exports.alignTableData = alignTableData; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/wrapString.js +var require_wrapString = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/wrapString.js"(exports) { + "use strict"; + var __importDefault = exports && exports.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.wrapString = void 0; + var slice_ansi_1 = __importDefault(require_slice_ansi()); + var string_width_1 = __importDefault(require_string_width()); + var wrapString = (subject, size) => { + let subjectSlice = subject; + const chunks = []; + do { + chunks.push((0, slice_ansi_1.default)(subjectSlice, 0, size)); + subjectSlice = (0, slice_ansi_1.default)(subjectSlice, size).trim(); + } while ((0, string_width_1.default)(subjectSlice)); + return chunks; + }; + exports.wrapString = wrapString; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/wrapWord.js +var require_wrapWord = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/wrapWord.js"(exports) { + "use strict"; + var __importDefault = exports && exports.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.wrapWord = void 0; + var slice_ansi_1 = __importDefault(require_slice_ansi()); + var strip_ansi_1 = __importDefault(require_strip_ansi()); + var calculateStringLengths = (input, size) => { + let subject = (0, strip_ansi_1.default)(input); + const chunks = []; + const re = new RegExp("(^.{1," + String(Math.max(size, 1)) + "}(\\s+|$))|(^.{1," + String(Math.max(size - 1, 1)) + "}(\\\\|/|_|\\.|,|;|-))"); + do { + let chunk; + const match3 = re.exec(subject); + if (match3) { + chunk = match3[0]; + subject = subject.slice(chunk.length); + const trimmedLength = chunk.trim().length; + const offset = chunk.length - trimmedLength; + chunks.push([trimmedLength, offset]); + } else { + chunk = subject.slice(0, size); + subject = subject.slice(size); + chunks.push([chunk.length, 0]); + } + } while (subject.length); + return chunks; + }; + var wrapWord = (input, size) => { + const result = []; + let startIndex = 0; + calculateStringLengths(input, size).forEach(([length, offset]) => { + result.push((0, slice_ansi_1.default)(input, startIndex, startIndex + length)); + startIndex += length + offset; + }); + return result; + }; + exports.wrapWord = wrapWord; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/wrapCell.js +var require_wrapCell = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/wrapCell.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.wrapCell = void 0; + var utils_1 = require_utils3(); + var wrapString_1 = require_wrapString(); + var wrapWord_1 = require_wrapWord(); + var wrapCell = (cellValue, cellWidth, useWrapWord) => { + const cellLines = (0, utils_1.splitAnsi)(cellValue); + for (let lineNr = 0; lineNr < cellLines.length; ) { + let lineChunks; + if (useWrapWord) { + lineChunks = (0, wrapWord_1.wrapWord)(cellLines[lineNr], cellWidth); + } else { + lineChunks = (0, wrapString_1.wrapString)(cellLines[lineNr], cellWidth); + } + cellLines.splice(lineNr, 1, ...lineChunks); + lineNr += lineChunks.length; + } + return cellLines; + }; + exports.wrapCell = wrapCell; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/calculateCellHeight.js +var require_calculateCellHeight = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/calculateCellHeight.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.calculateCellHeight = void 0; + var wrapCell_1 = require_wrapCell(); + var calculateCellHeight = (value2, columnWidth, useWrapWord = false) => { + return (0, wrapCell_1.wrapCell)(value2, columnWidth, useWrapWord).length; + }; + exports.calculateCellHeight = calculateCellHeight; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/calculateRowHeights.js +var require_calculateRowHeights = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/calculateRowHeights.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.calculateRowHeights = void 0; + var calculateCellHeight_1 = require_calculateCellHeight(); + var utils_1 = require_utils3(); + var calculateRowHeights = (rows, config3) => { + const rowHeights = []; + for (const [rowIndex, row] of rows.entries()) { + let rowHeight = 1; + row.forEach((cell, cellIndex) => { + var _a2; + const containingRange = (_a2 = config3.spanningCellManager) === null || _a2 === void 0 ? void 0 : _a2.getContainingRange({ + col: cellIndex, + row: rowIndex + }); + if (!containingRange) { + const cellHeight = (0, calculateCellHeight_1.calculateCellHeight)(cell, config3.columns[cellIndex].width, config3.columns[cellIndex].wrapWord); + rowHeight = Math.max(rowHeight, cellHeight); + return; + } + const { topLeft, bottomRight, height } = containingRange; + if (rowIndex === bottomRight.row) { + const totalOccupiedSpanningCellHeight = (0, utils_1.sumArray)(rowHeights.slice(topLeft.row)); + const totalHorizontalBorderHeight = bottomRight.row - topLeft.row; + const totalHiddenHorizontalBorderHeight = (0, utils_1.sequence)(topLeft.row + 1, bottomRight.row).filter((horizontalBorderIndex) => { + var _a3; + return !((_a3 = config3.drawHorizontalLine) === null || _a3 === void 0 ? void 0 : _a3.call(config3, horizontalBorderIndex, rows.length)); + }).length; + const cellHeight = height - totalOccupiedSpanningCellHeight - totalHorizontalBorderHeight + totalHiddenHorizontalBorderHeight; + rowHeight = Math.max(rowHeight, cellHeight); + } + }); + rowHeights.push(rowHeight); + } + return rowHeights; + }; + exports.calculateRowHeights = calculateRowHeights; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/drawContent.js +var require_drawContent = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/drawContent.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.drawContent = void 0; + var drawContent = (parameters) => { + const { contents, separatorGetter, drawSeparator, spanningCellManager, rowIndex, elementType } = parameters; + const contentSize = contents.length; + const result = []; + if (drawSeparator(0, contentSize)) { + result.push(separatorGetter(0, contentSize)); + } + contents.forEach((content, contentIndex) => { + if (!elementType || elementType === "border" || elementType === "row") { + result.push(content); + } + if (elementType === "cell" && rowIndex === void 0) { + result.push(content); + } + if (elementType === "cell" && rowIndex !== void 0) { + const containingRange = spanningCellManager === null || spanningCellManager === void 0 ? void 0 : spanningCellManager.getContainingRange({ + col: contentIndex, + row: rowIndex + }); + if (!containingRange || contentIndex === containingRange.topLeft.col) { + result.push(content); + } + } + if (contentIndex + 1 < contentSize && drawSeparator(contentIndex + 1, contentSize)) { + const separator2 = separatorGetter(contentIndex + 1, contentSize); + if (elementType === "cell" && rowIndex !== void 0) { + const currentCell = { + col: contentIndex + 1, + row: rowIndex + }; + const containingRange = spanningCellManager === null || spanningCellManager === void 0 ? void 0 : spanningCellManager.getContainingRange(currentCell); + if (!containingRange || containingRange.topLeft.col === currentCell.col) { + result.push(separator2); + } + } else { + result.push(separator2); + } + } + }); + if (drawSeparator(contentSize, contentSize)) { + result.push(separatorGetter(contentSize, contentSize)); + } + return result.join(""); + }; + exports.drawContent = drawContent; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/drawBorder.js +var require_drawBorder = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/drawBorder.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createTableBorderGetter = exports.drawBorderBottom = exports.drawBorderJoin = exports.drawBorderTop = exports.drawBorder = exports.createSeparatorGetter = exports.drawBorderSegments = void 0; + var drawContent_1 = require_drawContent(); + var drawBorderSegments = (columnWidths, parameters) => { + const { separator: separator2, horizontalBorderIndex, spanningCellManager } = parameters; + return columnWidths.map((columnWidth, columnIndex) => { + const normalSegment = separator2.body.repeat(columnWidth); + if (horizontalBorderIndex === void 0) { + return normalSegment; + } + const range2 = spanningCellManager === null || spanningCellManager === void 0 ? void 0 : spanningCellManager.getContainingRange({ + col: columnIndex, + row: horizontalBorderIndex + }); + if (!range2) { + return normalSegment; + } + const { topLeft } = range2; + if (horizontalBorderIndex === topLeft.row) { + return normalSegment; + } + if (columnIndex !== topLeft.col) { + return ""; + } + return range2.extractBorderContent(horizontalBorderIndex); + }); + }; + exports.drawBorderSegments = drawBorderSegments; + var createSeparatorGetter = (dependencies) => { + const { separator: separator2, spanningCellManager, horizontalBorderIndex, rowCount } = dependencies; + return (verticalBorderIndex, columnCount) => { + const inSameRange = spanningCellManager === null || spanningCellManager === void 0 ? void 0 : spanningCellManager.inSameRange; + if (horizontalBorderIndex !== void 0 && inSameRange) { + const topCell = { + col: verticalBorderIndex, + row: horizontalBorderIndex - 1 + }; + const leftCell = { + col: verticalBorderIndex - 1, + row: horizontalBorderIndex + }; + const oppositeCell = { + col: verticalBorderIndex - 1, + row: horizontalBorderIndex - 1 + }; + const currentCell = { + col: verticalBorderIndex, + row: horizontalBorderIndex + }; + const pairs = [ + [oppositeCell, topCell], + [topCell, currentCell], + [currentCell, leftCell], + [leftCell, oppositeCell] + ]; + if (verticalBorderIndex === 0) { + if (inSameRange(currentCell, topCell) && separator2.bodyJoinOuter) { + return separator2.bodyJoinOuter; + } + return separator2.left; + } + if (verticalBorderIndex === columnCount) { + if (inSameRange(oppositeCell, leftCell) && separator2.bodyJoinOuter) { + return separator2.bodyJoinOuter; + } + return separator2.right; + } + if (horizontalBorderIndex === 0) { + if (inSameRange(currentCell, leftCell)) { + return separator2.body; + } + return separator2.join; + } + if (horizontalBorderIndex === rowCount) { + if (inSameRange(topCell, oppositeCell)) { + return separator2.body; + } + return separator2.join; + } + const sameRangeCount = pairs.map((pair) => { + return inSameRange(...pair); + }).filter(Boolean).length; + if (sameRangeCount === 0) { + return separator2.join; + } + if (sameRangeCount === 4) { + return ""; + } + if (sameRangeCount === 2) { + if (inSameRange(...pairs[1]) && inSameRange(...pairs[3]) && separator2.bodyJoinInner) { + return separator2.bodyJoinInner; + } + return separator2.body; + } + if (sameRangeCount === 1) { + if (!separator2.joinRight || !separator2.joinLeft || !separator2.joinUp || !separator2.joinDown) { + throw new Error(`Can not get border separator for position [${horizontalBorderIndex}, ${verticalBorderIndex}]`); + } + if (inSameRange(...pairs[0])) { + return separator2.joinDown; + } + if (inSameRange(...pairs[1])) { + return separator2.joinLeft; + } + if (inSameRange(...pairs[2])) { + return separator2.joinUp; + } + return separator2.joinRight; + } + throw new Error("Invalid case"); + } + if (verticalBorderIndex === 0) { + return separator2.left; + } + if (verticalBorderIndex === columnCount) { + return separator2.right; + } + return separator2.join; + }; + }; + exports.createSeparatorGetter = createSeparatorGetter; + var drawBorder = (columnWidths, parameters) => { + const borderSegments = (0, exports.drawBorderSegments)(columnWidths, parameters); + const { drawVerticalLine, horizontalBorderIndex, spanningCellManager } = parameters; + return (0, drawContent_1.drawContent)({ + contents: borderSegments, + drawSeparator: drawVerticalLine, + elementType: "border", + rowIndex: horizontalBorderIndex, + separatorGetter: (0, exports.createSeparatorGetter)(parameters), + spanningCellManager + }) + "\n"; + }; + exports.drawBorder = drawBorder; + var drawBorderTop = (columnWidths, parameters) => { + const { border } = parameters; + const result = (0, exports.drawBorder)(columnWidths, { + ...parameters, + separator: { + body: border.topBody, + join: border.topJoin, + left: border.topLeft, + right: border.topRight + } + }); + if (result === "\n") { + return ""; + } + return result; + }; + exports.drawBorderTop = drawBorderTop; + var drawBorderJoin = (columnWidths, parameters) => { + const { border } = parameters; + return (0, exports.drawBorder)(columnWidths, { + ...parameters, + separator: { + body: border.joinBody, + bodyJoinInner: border.bodyJoin, + bodyJoinOuter: border.bodyLeft, + join: border.joinJoin, + joinDown: border.joinMiddleDown, + joinLeft: border.joinMiddleLeft, + joinRight: border.joinMiddleRight, + joinUp: border.joinMiddleUp, + left: border.joinLeft, + right: border.joinRight + } + }); + }; + exports.drawBorderJoin = drawBorderJoin; + var drawBorderBottom = (columnWidths, parameters) => { + const { border } = parameters; + return (0, exports.drawBorder)(columnWidths, { + ...parameters, + separator: { + body: border.bottomBody, + join: border.bottomJoin, + left: border.bottomLeft, + right: border.bottomRight + } + }); + }; + exports.drawBorderBottom = drawBorderBottom; + var createTableBorderGetter = (columnWidths, parameters) => { + return (index, size) => { + const drawBorderParameters = { + ...parameters, + horizontalBorderIndex: index + }; + if (index === 0) { + return (0, exports.drawBorderTop)(columnWidths, drawBorderParameters); + } else if (index === size) { + return (0, exports.drawBorderBottom)(columnWidths, drawBorderParameters); + } + return (0, exports.drawBorderJoin)(columnWidths, drawBorderParameters); + }; + }; + exports.createTableBorderGetter = createTableBorderGetter; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/drawRow.js +var require_drawRow = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/drawRow.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.drawRow = void 0; + var drawContent_1 = require_drawContent(); + var drawRow = (row, config3) => { + const { border, drawVerticalLine, rowIndex, spanningCellManager } = config3; + return (0, drawContent_1.drawContent)({ + contents: row, + drawSeparator: drawVerticalLine, + elementType: "cell", + rowIndex, + separatorGetter: (index, columnCount) => { + if (index === 0) { + return border.bodyLeft; + } + if (index === columnCount) { + return border.bodyRight; + } + return border.bodyJoin; + }, + spanningCellManager + }) + "\n"; + }; + exports.drawRow = drawRow; + } +}); + +// node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js +var require_fast_deep_equal = __commonJS({ + "node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js"(exports, module) { + "use strict"; + module.exports = function equal(a, b) { + if (a === b) return true; + if (a && b && typeof a == "object" && typeof b == "object") { + if (a.constructor !== b.constructor) return false; + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0; ) + if (!equal(a[i], b[i])) return false; + return true; + } + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + for (i = length; i-- !== 0; ) + if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + for (i = length; i-- !== 0; ) { + var key = keys[i]; + if (!equal(a[key], b[key])) return false; + } + return true; + } + return a !== a && b !== b; + }; + } +}); + +// node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/runtime/equal.js +var require_equal = __commonJS({ + "node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/runtime/equal.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var equal = require_fast_deep_equal(); + equal.code = 'require("ajv/dist/runtime/equal").default'; + exports.default = equal; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/generated/validators.js +var require_validators = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/generated/validators.js"(exports) { + "use strict"; + exports["config.json"] = validate43; + var schema13 = { + "$id": "config.json", + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "properties": { + "border": { + "$ref": "shared.json#/definitions/borders" + }, + "header": { + "type": "object", + "properties": { + "content": { + "type": "string" + }, + "alignment": { + "$ref": "shared.json#/definitions/alignment" + }, + "wrapWord": { + "type": "boolean" + }, + "truncate": { + "type": "integer" + }, + "paddingLeft": { + "type": "integer" + }, + "paddingRight": { + "type": "integer" + } + }, + "required": ["content"], + "additionalProperties": false + }, + "columns": { + "$ref": "shared.json#/definitions/columns" + }, + "columnDefault": { + "$ref": "shared.json#/definitions/column" + }, + "drawVerticalLine": { + "typeof": "function" + }, + "drawHorizontalLine": { + "typeof": "function" + }, + "singleLine": { + "typeof": "boolean" + }, + "spanningCells": { + "type": "array", + "items": { + "type": "object", + "properties": { + "col": { + "type": "integer", + "minimum": 0 + }, + "row": { + "type": "integer", + "minimum": 0 + }, + "colSpan": { + "type": "integer", + "minimum": 1 + }, + "rowSpan": { + "type": "integer", + "minimum": 1 + }, + "alignment": { + "$ref": "shared.json#/definitions/alignment" + }, + "verticalAlignment": { + "$ref": "shared.json#/definitions/verticalAlignment" + }, + "wrapWord": { + "type": "boolean" + }, + "truncate": { + "type": "integer" + }, + "paddingLeft": { + "type": "integer" + }, + "paddingRight": { + "type": "integer" + } + }, + "required": ["row", "col"], + "additionalProperties": false + } + } + }, + "additionalProperties": false + }; + var schema15 = { + "type": "object", + "properties": { + "topBody": { + "$ref": "#/definitions/border" + }, + "topJoin": { + "$ref": "#/definitions/border" + }, + "topLeft": { + "$ref": "#/definitions/border" + }, + "topRight": { + "$ref": "#/definitions/border" + }, + "bottomBody": { + "$ref": "#/definitions/border" + }, + "bottomJoin": { + "$ref": "#/definitions/border" + }, + "bottomLeft": { + "$ref": "#/definitions/border" + }, + "bottomRight": { + "$ref": "#/definitions/border" + }, + "bodyLeft": { + "$ref": "#/definitions/border" + }, + "bodyRight": { + "$ref": "#/definitions/border" + }, + "bodyJoin": { + "$ref": "#/definitions/border" + }, + "headerJoin": { + "$ref": "#/definitions/border" + }, + "joinBody": { + "$ref": "#/definitions/border" + }, + "joinLeft": { + "$ref": "#/definitions/border" + }, + "joinRight": { + "$ref": "#/definitions/border" + }, + "joinJoin": { + "$ref": "#/definitions/border" + }, + "joinMiddleUp": { + "$ref": "#/definitions/border" + }, + "joinMiddleDown": { + "$ref": "#/definitions/border" + }, + "joinMiddleLeft": { + "$ref": "#/definitions/border" + }, + "joinMiddleRight": { + "$ref": "#/definitions/border" + } + }, + "additionalProperties": false + }; + var func8 = Object.prototype.hasOwnProperty; + function validate46(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + let vErrors = null; + let errors = 0; + if (typeof data !== "string") { + const err0 = { + instancePath, + schemaPath: "#/type", + keyword: "type", + params: { + type: "string" + }, + message: "must be string" + }; + if (vErrors === null) { + vErrors = [err0]; + } else { + vErrors.push(err0); + } + errors++; + } + validate46.errors = vErrors; + return errors === 0; + } + function validate45(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + let vErrors = null; + let errors = 0; + if (data && typeof data == "object" && !Array.isArray(data)) { + for (const key0 in data) { + if (!func8.call(schema15.properties, key0)) { + const err0 = { + instancePath, + schemaPath: "#/additionalProperties", + keyword: "additionalProperties", + params: { + additionalProperty: key0 + }, + message: "must NOT have additional properties" + }; + if (vErrors === null) { + vErrors = [err0]; + } else { + vErrors.push(err0); + } + errors++; + } + } + if (data.topBody !== void 0) { + if (!validate46(data.topBody, { + instancePath: instancePath + "/topBody", + parentData: data, + parentDataProperty: "topBody", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.topJoin !== void 0) { + if (!validate46(data.topJoin, { + instancePath: instancePath + "/topJoin", + parentData: data, + parentDataProperty: "topJoin", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.topLeft !== void 0) { + if (!validate46(data.topLeft, { + instancePath: instancePath + "/topLeft", + parentData: data, + parentDataProperty: "topLeft", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.topRight !== void 0) { + if (!validate46(data.topRight, { + instancePath: instancePath + "/topRight", + parentData: data, + parentDataProperty: "topRight", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.bottomBody !== void 0) { + if (!validate46(data.bottomBody, { + instancePath: instancePath + "/bottomBody", + parentData: data, + parentDataProperty: "bottomBody", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.bottomJoin !== void 0) { + if (!validate46(data.bottomJoin, { + instancePath: instancePath + "/bottomJoin", + parentData: data, + parentDataProperty: "bottomJoin", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.bottomLeft !== void 0) { + if (!validate46(data.bottomLeft, { + instancePath: instancePath + "/bottomLeft", + parentData: data, + parentDataProperty: "bottomLeft", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.bottomRight !== void 0) { + if (!validate46(data.bottomRight, { + instancePath: instancePath + "/bottomRight", + parentData: data, + parentDataProperty: "bottomRight", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.bodyLeft !== void 0) { + if (!validate46(data.bodyLeft, { + instancePath: instancePath + "/bodyLeft", + parentData: data, + parentDataProperty: "bodyLeft", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.bodyRight !== void 0) { + if (!validate46(data.bodyRight, { + instancePath: instancePath + "/bodyRight", + parentData: data, + parentDataProperty: "bodyRight", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.bodyJoin !== void 0) { + if (!validate46(data.bodyJoin, { + instancePath: instancePath + "/bodyJoin", + parentData: data, + parentDataProperty: "bodyJoin", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.headerJoin !== void 0) { + if (!validate46(data.headerJoin, { + instancePath: instancePath + "/headerJoin", + parentData: data, + parentDataProperty: "headerJoin", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinBody !== void 0) { + if (!validate46(data.joinBody, { + instancePath: instancePath + "/joinBody", + parentData: data, + parentDataProperty: "joinBody", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinLeft !== void 0) { + if (!validate46(data.joinLeft, { + instancePath: instancePath + "/joinLeft", + parentData: data, + parentDataProperty: "joinLeft", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinRight !== void 0) { + if (!validate46(data.joinRight, { + instancePath: instancePath + "/joinRight", + parentData: data, + parentDataProperty: "joinRight", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinJoin !== void 0) { + if (!validate46(data.joinJoin, { + instancePath: instancePath + "/joinJoin", + parentData: data, + parentDataProperty: "joinJoin", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinMiddleUp !== void 0) { + if (!validate46(data.joinMiddleUp, { + instancePath: instancePath + "/joinMiddleUp", + parentData: data, + parentDataProperty: "joinMiddleUp", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinMiddleDown !== void 0) { + if (!validate46(data.joinMiddleDown, { + instancePath: instancePath + "/joinMiddleDown", + parentData: data, + parentDataProperty: "joinMiddleDown", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinMiddleLeft !== void 0) { + if (!validate46(data.joinMiddleLeft, { + instancePath: instancePath + "/joinMiddleLeft", + parentData: data, + parentDataProperty: "joinMiddleLeft", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinMiddleRight !== void 0) { + if (!validate46(data.joinMiddleRight, { + instancePath: instancePath + "/joinMiddleRight", + parentData: data, + parentDataProperty: "joinMiddleRight", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + } else { + const err1 = { + instancePath, + schemaPath: "#/type", + keyword: "type", + params: { + type: "object" + }, + message: "must be object" + }; + if (vErrors === null) { + vErrors = [err1]; + } else { + vErrors.push(err1); + } + errors++; + } + validate45.errors = vErrors; + return errors === 0; + } + var schema17 = { + "type": "string", + "enum": ["left", "right", "center", "justify"] + }; + var func0 = require_equal().default; + function validate68(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + let vErrors = null; + let errors = 0; + if (typeof data !== "string") { + const err0 = { + instancePath, + schemaPath: "#/type", + keyword: "type", + params: { + type: "string" + }, + message: "must be string" + }; + if (vErrors === null) { + vErrors = [err0]; + } else { + vErrors.push(err0); + } + errors++; + } + if (!(data === "left" || data === "right" || data === "center" || data === "justify")) { + const err1 = { + instancePath, + schemaPath: "#/enum", + keyword: "enum", + params: { + allowedValues: schema17.enum + }, + message: "must be equal to one of the allowed values" + }; + if (vErrors === null) { + vErrors = [err1]; + } else { + vErrors.push(err1); + } + errors++; + } + validate68.errors = vErrors; + return errors === 0; + } + var pattern0 = new RegExp("^[0-9]+$", "u"); + function validate72(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + let vErrors = null; + let errors = 0; + if (typeof data !== "string") { + const err0 = { + instancePath, + schemaPath: "#/type", + keyword: "type", + params: { + type: "string" + }, + message: "must be string" + }; + if (vErrors === null) { + vErrors = [err0]; + } else { + vErrors.push(err0); + } + errors++; + } + if (!(data === "left" || data === "right" || data === "center" || data === "justify")) { + const err1 = { + instancePath, + schemaPath: "#/enum", + keyword: "enum", + params: { + allowedValues: schema17.enum + }, + message: "must be equal to one of the allowed values" + }; + if (vErrors === null) { + vErrors = [err1]; + } else { + vErrors.push(err1); + } + errors++; + } + validate72.errors = vErrors; + return errors === 0; + } + var schema21 = { + "type": "string", + "enum": ["top", "middle", "bottom"] + }; + function validate74(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + let vErrors = null; + let errors = 0; + if (typeof data !== "string") { + const err0 = { + instancePath, + schemaPath: "#/type", + keyword: "type", + params: { + type: "string" + }, + message: "must be string" + }; + if (vErrors === null) { + vErrors = [err0]; + } else { + vErrors.push(err0); + } + errors++; + } + if (!(data === "top" || data === "middle" || data === "bottom")) { + const err1 = { + instancePath, + schemaPath: "#/enum", + keyword: "enum", + params: { + allowedValues: schema21.enum + }, + message: "must be equal to one of the allowed values" + }; + if (vErrors === null) { + vErrors = [err1]; + } else { + vErrors.push(err1); + } + errors++; + } + validate74.errors = vErrors; + return errors === 0; + } + function validate71(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + let vErrors = null; + let errors = 0; + if (data && typeof data == "object" && !Array.isArray(data)) { + for (const key0 in data) { + if (!(key0 === "alignment" || key0 === "verticalAlignment" || key0 === "width" || key0 === "wrapWord" || key0 === "truncate" || key0 === "paddingLeft" || key0 === "paddingRight")) { + const err0 = { + instancePath, + schemaPath: "#/additionalProperties", + keyword: "additionalProperties", + params: { + additionalProperty: key0 + }, + message: "must NOT have additional properties" + }; + if (vErrors === null) { + vErrors = [err0]; + } else { + vErrors.push(err0); + } + errors++; + } + } + if (data.alignment !== void 0) { + if (!validate72(data.alignment, { + instancePath: instancePath + "/alignment", + parentData: data, + parentDataProperty: "alignment", + rootData + })) { + vErrors = vErrors === null ? validate72.errors : vErrors.concat(validate72.errors); + errors = vErrors.length; + } + } + if (data.verticalAlignment !== void 0) { + if (!validate74(data.verticalAlignment, { + instancePath: instancePath + "/verticalAlignment", + parentData: data, + parentDataProperty: "verticalAlignment", + rootData + })) { + vErrors = vErrors === null ? validate74.errors : vErrors.concat(validate74.errors); + errors = vErrors.length; + } + } + if (data.width !== void 0) { + let data2 = data.width; + if (!(typeof data2 == "number" && (!(data2 % 1) && !isNaN(data2)) && isFinite(data2))) { + const err1 = { + instancePath: instancePath + "/width", + schemaPath: "#/properties/width/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err1]; + } else { + vErrors.push(err1); + } + errors++; + } + if (typeof data2 == "number" && isFinite(data2)) { + if (data2 < 1 || isNaN(data2)) { + const err2 = { + instancePath: instancePath + "/width", + schemaPath: "#/properties/width/minimum", + keyword: "minimum", + params: { + comparison: ">=", + limit: 1 + }, + message: "must be >= 1" + }; + if (vErrors === null) { + vErrors = [err2]; + } else { + vErrors.push(err2); + } + errors++; + } + } + } + if (data.wrapWord !== void 0) { + if (typeof data.wrapWord !== "boolean") { + const err3 = { + instancePath: instancePath + "/wrapWord", + schemaPath: "#/properties/wrapWord/type", + keyword: "type", + params: { + type: "boolean" + }, + message: "must be boolean" + }; + if (vErrors === null) { + vErrors = [err3]; + } else { + vErrors.push(err3); + } + errors++; + } + } + if (data.truncate !== void 0) { + let data4 = data.truncate; + if (!(typeof data4 == "number" && (!(data4 % 1) && !isNaN(data4)) && isFinite(data4))) { + const err4 = { + instancePath: instancePath + "/truncate", + schemaPath: "#/properties/truncate/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err4]; + } else { + vErrors.push(err4); + } + errors++; + } + } + if (data.paddingLeft !== void 0) { + let data5 = data.paddingLeft; + if (!(typeof data5 == "number" && (!(data5 % 1) && !isNaN(data5)) && isFinite(data5))) { + const err5 = { + instancePath: instancePath + "/paddingLeft", + schemaPath: "#/properties/paddingLeft/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err5]; + } else { + vErrors.push(err5); + } + errors++; + } + } + if (data.paddingRight !== void 0) { + let data6 = data.paddingRight; + if (!(typeof data6 == "number" && (!(data6 % 1) && !isNaN(data6)) && isFinite(data6))) { + const err6 = { + instancePath: instancePath + "/paddingRight", + schemaPath: "#/properties/paddingRight/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err6]; + } else { + vErrors.push(err6); + } + errors++; + } + } + } else { + const err7 = { + instancePath, + schemaPath: "#/type", + keyword: "type", + params: { + type: "object" + }, + message: "must be object" + }; + if (vErrors === null) { + vErrors = [err7]; + } else { + vErrors.push(err7); + } + errors++; + } + validate71.errors = vErrors; + return errors === 0; + } + function validate70(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + let vErrors = null; + let errors = 0; + const _errs0 = errors; + let valid0 = false; + let passing0 = null; + const _errs1 = errors; + if (data && typeof data == "object" && !Array.isArray(data)) { + for (const key0 in data) { + if (!pattern0.test(key0)) { + const err0 = { + instancePath, + schemaPath: "#/oneOf/0/additionalProperties", + keyword: "additionalProperties", + params: { + additionalProperty: key0 + }, + message: "must NOT have additional properties" + }; + if (vErrors === null) { + vErrors = [err0]; + } else { + vErrors.push(err0); + } + errors++; + } + } + for (const key1 in data) { + if (pattern0.test(key1)) { + if (!validate71(data[key1], { + instancePath: instancePath + "/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), + parentData: data, + parentDataProperty: key1, + rootData + })) { + vErrors = vErrors === null ? validate71.errors : vErrors.concat(validate71.errors); + errors = vErrors.length; + } + } + } + } else { + const err1 = { + instancePath, + schemaPath: "#/oneOf/0/type", + keyword: "type", + params: { + type: "object" + }, + message: "must be object" + }; + if (vErrors === null) { + vErrors = [err1]; + } else { + vErrors.push(err1); + } + errors++; + } + var _valid0 = _errs1 === errors; + if (_valid0) { + valid0 = true; + passing0 = 0; + } + const _errs5 = errors; + if (Array.isArray(data)) { + const len0 = data.length; + for (let i0 = 0; i0 < len0; i0++) { + if (!validate71(data[i0], { + instancePath: instancePath + "/" + i0, + parentData: data, + parentDataProperty: i0, + rootData + })) { + vErrors = vErrors === null ? validate71.errors : vErrors.concat(validate71.errors); + errors = vErrors.length; + } + } + } else { + const err2 = { + instancePath, + schemaPath: "#/oneOf/1/type", + keyword: "type", + params: { + type: "array" + }, + message: "must be array" + }; + if (vErrors === null) { + vErrors = [err2]; + } else { + vErrors.push(err2); + } + errors++; + } + var _valid0 = _errs5 === errors; + if (_valid0 && valid0) { + valid0 = false; + passing0 = [passing0, 1]; + } else { + if (_valid0) { + valid0 = true; + passing0 = 1; + } + } + if (!valid0) { + const err3 = { + instancePath, + schemaPath: "#/oneOf", + keyword: "oneOf", + params: { + passingSchemas: passing0 + }, + message: "must match exactly one schema in oneOf" + }; + if (vErrors === null) { + vErrors = [err3]; + } else { + vErrors.push(err3); + } + errors++; + } else { + errors = _errs0; + if (vErrors !== null) { + if (_errs0) { + vErrors.length = _errs0; + } else { + vErrors = null; + } + } + } + validate70.errors = vErrors; + return errors === 0; + } + function validate79(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + let vErrors = null; + let errors = 0; + if (data && typeof data == "object" && !Array.isArray(data)) { + for (const key0 in data) { + if (!(key0 === "alignment" || key0 === "verticalAlignment" || key0 === "width" || key0 === "wrapWord" || key0 === "truncate" || key0 === "paddingLeft" || key0 === "paddingRight")) { + const err0 = { + instancePath, + schemaPath: "#/additionalProperties", + keyword: "additionalProperties", + params: { + additionalProperty: key0 + }, + message: "must NOT have additional properties" + }; + if (vErrors === null) { + vErrors = [err0]; + } else { + vErrors.push(err0); + } + errors++; + } + } + if (data.alignment !== void 0) { + if (!validate72(data.alignment, { + instancePath: instancePath + "/alignment", + parentData: data, + parentDataProperty: "alignment", + rootData + })) { + vErrors = vErrors === null ? validate72.errors : vErrors.concat(validate72.errors); + errors = vErrors.length; + } + } + if (data.verticalAlignment !== void 0) { + if (!validate74(data.verticalAlignment, { + instancePath: instancePath + "/verticalAlignment", + parentData: data, + parentDataProperty: "verticalAlignment", + rootData + })) { + vErrors = vErrors === null ? validate74.errors : vErrors.concat(validate74.errors); + errors = vErrors.length; + } + } + if (data.width !== void 0) { + let data2 = data.width; + if (!(typeof data2 == "number" && (!(data2 % 1) && !isNaN(data2)) && isFinite(data2))) { + const err1 = { + instancePath: instancePath + "/width", + schemaPath: "#/properties/width/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err1]; + } else { + vErrors.push(err1); + } + errors++; + } + if (typeof data2 == "number" && isFinite(data2)) { + if (data2 < 1 || isNaN(data2)) { + const err2 = { + instancePath: instancePath + "/width", + schemaPath: "#/properties/width/minimum", + keyword: "minimum", + params: { + comparison: ">=", + limit: 1 + }, + message: "must be >= 1" + }; + if (vErrors === null) { + vErrors = [err2]; + } else { + vErrors.push(err2); + } + errors++; + } + } + } + if (data.wrapWord !== void 0) { + if (typeof data.wrapWord !== "boolean") { + const err3 = { + instancePath: instancePath + "/wrapWord", + schemaPath: "#/properties/wrapWord/type", + keyword: "type", + params: { + type: "boolean" + }, + message: "must be boolean" + }; + if (vErrors === null) { + vErrors = [err3]; + } else { + vErrors.push(err3); + } + errors++; + } + } + if (data.truncate !== void 0) { + let data4 = data.truncate; + if (!(typeof data4 == "number" && (!(data4 % 1) && !isNaN(data4)) && isFinite(data4))) { + const err4 = { + instancePath: instancePath + "/truncate", + schemaPath: "#/properties/truncate/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err4]; + } else { + vErrors.push(err4); + } + errors++; + } + } + if (data.paddingLeft !== void 0) { + let data5 = data.paddingLeft; + if (!(typeof data5 == "number" && (!(data5 % 1) && !isNaN(data5)) && isFinite(data5))) { + const err5 = { + instancePath: instancePath + "/paddingLeft", + schemaPath: "#/properties/paddingLeft/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err5]; + } else { + vErrors.push(err5); + } + errors++; + } + } + if (data.paddingRight !== void 0) { + let data6 = data.paddingRight; + if (!(typeof data6 == "number" && (!(data6 % 1) && !isNaN(data6)) && isFinite(data6))) { + const err6 = { + instancePath: instancePath + "/paddingRight", + schemaPath: "#/properties/paddingRight/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err6]; + } else { + vErrors.push(err6); + } + errors++; + } + } + } else { + const err7 = { + instancePath, + schemaPath: "#/type", + keyword: "type", + params: { + type: "object" + }, + message: "must be object" + }; + if (vErrors === null) { + vErrors = [err7]; + } else { + vErrors.push(err7); + } + errors++; + } + validate79.errors = vErrors; + return errors === 0; + } + function validate84(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + let vErrors = null; + let errors = 0; + if (typeof data !== "string") { + const err0 = { + instancePath, + schemaPath: "#/type", + keyword: "type", + params: { + type: "string" + }, + message: "must be string" + }; + if (vErrors === null) { + vErrors = [err0]; + } else { + vErrors.push(err0); + } + errors++; + } + if (!(data === "top" || data === "middle" || data === "bottom")) { + const err1 = { + instancePath, + schemaPath: "#/enum", + keyword: "enum", + params: { + allowedValues: schema21.enum + }, + message: "must be equal to one of the allowed values" + }; + if (vErrors === null) { + vErrors = [err1]; + } else { + vErrors.push(err1); + } + errors++; + } + validate84.errors = vErrors; + return errors === 0; + } + function validate43(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + ; + let vErrors = null; + let errors = 0; + if (data && typeof data == "object" && !Array.isArray(data)) { + for (const key0 in data) { + if (!(key0 === "border" || key0 === "header" || key0 === "columns" || key0 === "columnDefault" || key0 === "drawVerticalLine" || key0 === "drawHorizontalLine" || key0 === "singleLine" || key0 === "spanningCells")) { + const err0 = { + instancePath, + schemaPath: "#/additionalProperties", + keyword: "additionalProperties", + params: { + additionalProperty: key0 + }, + message: "must NOT have additional properties" + }; + if (vErrors === null) { + vErrors = [err0]; + } else { + vErrors.push(err0); + } + errors++; + } + } + if (data.border !== void 0) { + if (!validate45(data.border, { + instancePath: instancePath + "/border", + parentData: data, + parentDataProperty: "border", + rootData + })) { + vErrors = vErrors === null ? validate45.errors : vErrors.concat(validate45.errors); + errors = vErrors.length; + } + } + if (data.header !== void 0) { + let data1 = data.header; + if (data1 && typeof data1 == "object" && !Array.isArray(data1)) { + if (data1.content === void 0) { + const err1 = { + instancePath: instancePath + "/header", + schemaPath: "#/properties/header/required", + keyword: "required", + params: { + missingProperty: "content" + }, + message: "must have required property 'content'" + }; + if (vErrors === null) { + vErrors = [err1]; + } else { + vErrors.push(err1); + } + errors++; + } + for (const key1 in data1) { + if (!(key1 === "content" || key1 === "alignment" || key1 === "wrapWord" || key1 === "truncate" || key1 === "paddingLeft" || key1 === "paddingRight")) { + const err2 = { + instancePath: instancePath + "/header", + schemaPath: "#/properties/header/additionalProperties", + keyword: "additionalProperties", + params: { + additionalProperty: key1 + }, + message: "must NOT have additional properties" + }; + if (vErrors === null) { + vErrors = [err2]; + } else { + vErrors.push(err2); + } + errors++; + } + } + if (data1.content !== void 0) { + if (typeof data1.content !== "string") { + const err3 = { + instancePath: instancePath + "/header/content", + schemaPath: "#/properties/header/properties/content/type", + keyword: "type", + params: { + type: "string" + }, + message: "must be string" + }; + if (vErrors === null) { + vErrors = [err3]; + } else { + vErrors.push(err3); + } + errors++; + } + } + if (data1.alignment !== void 0) { + if (!validate68(data1.alignment, { + instancePath: instancePath + "/header/alignment", + parentData: data1, + parentDataProperty: "alignment", + rootData + })) { + vErrors = vErrors === null ? validate68.errors : vErrors.concat(validate68.errors); + errors = vErrors.length; + } + } + if (data1.wrapWord !== void 0) { + if (typeof data1.wrapWord !== "boolean") { + const err4 = { + instancePath: instancePath + "/header/wrapWord", + schemaPath: "#/properties/header/properties/wrapWord/type", + keyword: "type", + params: { + type: "boolean" + }, + message: "must be boolean" + }; + if (vErrors === null) { + vErrors = [err4]; + } else { + vErrors.push(err4); + } + errors++; + } + } + if (data1.truncate !== void 0) { + let data5 = data1.truncate; + if (!(typeof data5 == "number" && (!(data5 % 1) && !isNaN(data5)) && isFinite(data5))) { + const err5 = { + instancePath: instancePath + "/header/truncate", + schemaPath: "#/properties/header/properties/truncate/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err5]; + } else { + vErrors.push(err5); + } + errors++; + } + } + if (data1.paddingLeft !== void 0) { + let data6 = data1.paddingLeft; + if (!(typeof data6 == "number" && (!(data6 % 1) && !isNaN(data6)) && isFinite(data6))) { + const err6 = { + instancePath: instancePath + "/header/paddingLeft", + schemaPath: "#/properties/header/properties/paddingLeft/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err6]; + } else { + vErrors.push(err6); + } + errors++; + } + } + if (data1.paddingRight !== void 0) { + let data7 = data1.paddingRight; + if (!(typeof data7 == "number" && (!(data7 % 1) && !isNaN(data7)) && isFinite(data7))) { + const err7 = { + instancePath: instancePath + "/header/paddingRight", + schemaPath: "#/properties/header/properties/paddingRight/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err7]; + } else { + vErrors.push(err7); + } + errors++; + } + } + } else { + const err8 = { + instancePath: instancePath + "/header", + schemaPath: "#/properties/header/type", + keyword: "type", + params: { + type: "object" + }, + message: "must be object" + }; + if (vErrors === null) { + vErrors = [err8]; + } else { + vErrors.push(err8); + } + errors++; + } + } + if (data.columns !== void 0) { + if (!validate70(data.columns, { + instancePath: instancePath + "/columns", + parentData: data, + parentDataProperty: "columns", + rootData + })) { + vErrors = vErrors === null ? validate70.errors : vErrors.concat(validate70.errors); + errors = vErrors.length; + } + } + if (data.columnDefault !== void 0) { + if (!validate79(data.columnDefault, { + instancePath: instancePath + "/columnDefault", + parentData: data, + parentDataProperty: "columnDefault", + rootData + })) { + vErrors = vErrors === null ? validate79.errors : vErrors.concat(validate79.errors); + errors = vErrors.length; + } + } + if (data.drawVerticalLine !== void 0) { + if (typeof data.drawVerticalLine != "function") { + const err9 = { + instancePath: instancePath + "/drawVerticalLine", + schemaPath: "#/properties/drawVerticalLine/typeof", + keyword: "typeof", + params: {}, + message: 'must pass "typeof" keyword validation' + }; + if (vErrors === null) { + vErrors = [err9]; + } else { + vErrors.push(err9); + } + errors++; + } + } + if (data.drawHorizontalLine !== void 0) { + if (typeof data.drawHorizontalLine != "function") { + const err10 = { + instancePath: instancePath + "/drawHorizontalLine", + schemaPath: "#/properties/drawHorizontalLine/typeof", + keyword: "typeof", + params: {}, + message: 'must pass "typeof" keyword validation' + }; + if (vErrors === null) { + vErrors = [err10]; + } else { + vErrors.push(err10); + } + errors++; + } + } + if (data.singleLine !== void 0) { + if (typeof data.singleLine != "boolean") { + const err11 = { + instancePath: instancePath + "/singleLine", + schemaPath: "#/properties/singleLine/typeof", + keyword: "typeof", + params: {}, + message: 'must pass "typeof" keyword validation' + }; + if (vErrors === null) { + vErrors = [err11]; + } else { + vErrors.push(err11); + } + errors++; + } + } + if (data.spanningCells !== void 0) { + let data13 = data.spanningCells; + if (Array.isArray(data13)) { + const len0 = data13.length; + for (let i0 = 0; i0 < len0; i0++) { + let data14 = data13[i0]; + if (data14 && typeof data14 == "object" && !Array.isArray(data14)) { + if (data14.row === void 0) { + const err12 = { + instancePath: instancePath + "/spanningCells/" + i0, + schemaPath: "#/properties/spanningCells/items/required", + keyword: "required", + params: { + missingProperty: "row" + }, + message: "must have required property 'row'" + }; + if (vErrors === null) { + vErrors = [err12]; + } else { + vErrors.push(err12); + } + errors++; + } + if (data14.col === void 0) { + const err13 = { + instancePath: instancePath + "/spanningCells/" + i0, + schemaPath: "#/properties/spanningCells/items/required", + keyword: "required", + params: { + missingProperty: "col" + }, + message: "must have required property 'col'" + }; + if (vErrors === null) { + vErrors = [err13]; + } else { + vErrors.push(err13); + } + errors++; + } + for (const key2 in data14) { + if (!func8.call(schema13.properties.spanningCells.items.properties, key2)) { + const err14 = { + instancePath: instancePath + "/spanningCells/" + i0, + schemaPath: "#/properties/spanningCells/items/additionalProperties", + keyword: "additionalProperties", + params: { + additionalProperty: key2 + }, + message: "must NOT have additional properties" + }; + if (vErrors === null) { + vErrors = [err14]; + } else { + vErrors.push(err14); + } + errors++; + } + } + if (data14.col !== void 0) { + let data15 = data14.col; + if (!(typeof data15 == "number" && (!(data15 % 1) && !isNaN(data15)) && isFinite(data15))) { + const err15 = { + instancePath: instancePath + "/spanningCells/" + i0 + "/col", + schemaPath: "#/properties/spanningCells/items/properties/col/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err15]; + } else { + vErrors.push(err15); + } + errors++; + } + if (typeof data15 == "number" && isFinite(data15)) { + if (data15 < 0 || isNaN(data15)) { + const err16 = { + instancePath: instancePath + "/spanningCells/" + i0 + "/col", + schemaPath: "#/properties/spanningCells/items/properties/col/minimum", + keyword: "minimum", + params: { + comparison: ">=", + limit: 0 + }, + message: "must be >= 0" + }; + if (vErrors === null) { + vErrors = [err16]; + } else { + vErrors.push(err16); + } + errors++; + } + } + } + if (data14.row !== void 0) { + let data16 = data14.row; + if (!(typeof data16 == "number" && (!(data16 % 1) && !isNaN(data16)) && isFinite(data16))) { + const err17 = { + instancePath: instancePath + "/spanningCells/" + i0 + "/row", + schemaPath: "#/properties/spanningCells/items/properties/row/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err17]; + } else { + vErrors.push(err17); + } + errors++; + } + if (typeof data16 == "number" && isFinite(data16)) { + if (data16 < 0 || isNaN(data16)) { + const err18 = { + instancePath: instancePath + "/spanningCells/" + i0 + "/row", + schemaPath: "#/properties/spanningCells/items/properties/row/minimum", + keyword: "minimum", + params: { + comparison: ">=", + limit: 0 + }, + message: "must be >= 0" + }; + if (vErrors === null) { + vErrors = [err18]; + } else { + vErrors.push(err18); + } + errors++; + } + } + } + if (data14.colSpan !== void 0) { + let data17 = data14.colSpan; + if (!(typeof data17 == "number" && (!(data17 % 1) && !isNaN(data17)) && isFinite(data17))) { + const err19 = { + instancePath: instancePath + "/spanningCells/" + i0 + "/colSpan", + schemaPath: "#/properties/spanningCells/items/properties/colSpan/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err19]; + } else { + vErrors.push(err19); + } + errors++; + } + if (typeof data17 == "number" && isFinite(data17)) { + if (data17 < 1 || isNaN(data17)) { + const err20 = { + instancePath: instancePath + "/spanningCells/" + i0 + "/colSpan", + schemaPath: "#/properties/spanningCells/items/properties/colSpan/minimum", + keyword: "minimum", + params: { + comparison: ">=", + limit: 1 + }, + message: "must be >= 1" + }; + if (vErrors === null) { + vErrors = [err20]; + } else { + vErrors.push(err20); + } + errors++; + } + } + } + if (data14.rowSpan !== void 0) { + let data18 = data14.rowSpan; + if (!(typeof data18 == "number" && (!(data18 % 1) && !isNaN(data18)) && isFinite(data18))) { + const err21 = { + instancePath: instancePath + "/spanningCells/" + i0 + "/rowSpan", + schemaPath: "#/properties/spanningCells/items/properties/rowSpan/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err21]; + } else { + vErrors.push(err21); + } + errors++; + } + if (typeof data18 == "number" && isFinite(data18)) { + if (data18 < 1 || isNaN(data18)) { + const err22 = { + instancePath: instancePath + "/spanningCells/" + i0 + "/rowSpan", + schemaPath: "#/properties/spanningCells/items/properties/rowSpan/minimum", + keyword: "minimum", + params: { + comparison: ">=", + limit: 1 + }, + message: "must be >= 1" + }; + if (vErrors === null) { + vErrors = [err22]; + } else { + vErrors.push(err22); + } + errors++; + } + } + } + if (data14.alignment !== void 0) { + if (!validate68(data14.alignment, { + instancePath: instancePath + "/spanningCells/" + i0 + "/alignment", + parentData: data14, + parentDataProperty: "alignment", + rootData + })) { + vErrors = vErrors === null ? validate68.errors : vErrors.concat(validate68.errors); + errors = vErrors.length; + } + } + if (data14.verticalAlignment !== void 0) { + if (!validate84(data14.verticalAlignment, { + instancePath: instancePath + "/spanningCells/" + i0 + "/verticalAlignment", + parentData: data14, + parentDataProperty: "verticalAlignment", + rootData + })) { + vErrors = vErrors === null ? validate84.errors : vErrors.concat(validate84.errors); + errors = vErrors.length; + } + } + if (data14.wrapWord !== void 0) { + if (typeof data14.wrapWord !== "boolean") { + const err23 = { + instancePath: instancePath + "/spanningCells/" + i0 + "/wrapWord", + schemaPath: "#/properties/spanningCells/items/properties/wrapWord/type", + keyword: "type", + params: { + type: "boolean" + }, + message: "must be boolean" + }; + if (vErrors === null) { + vErrors = [err23]; + } else { + vErrors.push(err23); + } + errors++; + } + } + if (data14.truncate !== void 0) { + let data22 = data14.truncate; + if (!(typeof data22 == "number" && (!(data22 % 1) && !isNaN(data22)) && isFinite(data22))) { + const err24 = { + instancePath: instancePath + "/spanningCells/" + i0 + "/truncate", + schemaPath: "#/properties/spanningCells/items/properties/truncate/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err24]; + } else { + vErrors.push(err24); + } + errors++; + } + } + if (data14.paddingLeft !== void 0) { + let data23 = data14.paddingLeft; + if (!(typeof data23 == "number" && (!(data23 % 1) && !isNaN(data23)) && isFinite(data23))) { + const err25 = { + instancePath: instancePath + "/spanningCells/" + i0 + "/paddingLeft", + schemaPath: "#/properties/spanningCells/items/properties/paddingLeft/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err25]; + } else { + vErrors.push(err25); + } + errors++; + } + } + if (data14.paddingRight !== void 0) { + let data24 = data14.paddingRight; + if (!(typeof data24 == "number" && (!(data24 % 1) && !isNaN(data24)) && isFinite(data24))) { + const err26 = { + instancePath: instancePath + "/spanningCells/" + i0 + "/paddingRight", + schemaPath: "#/properties/spanningCells/items/properties/paddingRight/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err26]; + } else { + vErrors.push(err26); + } + errors++; + } + } + } else { + const err27 = { + instancePath: instancePath + "/spanningCells/" + i0, + schemaPath: "#/properties/spanningCells/items/type", + keyword: "type", + params: { + type: "object" + }, + message: "must be object" + }; + if (vErrors === null) { + vErrors = [err27]; + } else { + vErrors.push(err27); + } + errors++; + } + } + } else { + const err28 = { + instancePath: instancePath + "/spanningCells", + schemaPath: "#/properties/spanningCells/type", + keyword: "type", + params: { + type: "array" + }, + message: "must be array" + }; + if (vErrors === null) { + vErrors = [err28]; + } else { + vErrors.push(err28); + } + errors++; + } + } + } else { + const err29 = { + instancePath, + schemaPath: "#/type", + keyword: "type", + params: { + type: "object" + }, + message: "must be object" + }; + if (vErrors === null) { + vErrors = [err29]; + } else { + vErrors.push(err29); + } + errors++; + } + validate43.errors = vErrors; + return errors === 0; + } + exports["streamConfig.json"] = validate86; + function validate87(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + let vErrors = null; + let errors = 0; + if (data && typeof data == "object" && !Array.isArray(data)) { + for (const key0 in data) { + if (!func8.call(schema15.properties, key0)) { + const err0 = { + instancePath, + schemaPath: "#/additionalProperties", + keyword: "additionalProperties", + params: { + additionalProperty: key0 + }, + message: "must NOT have additional properties" + }; + if (vErrors === null) { + vErrors = [err0]; + } else { + vErrors.push(err0); + } + errors++; + } + } + if (data.topBody !== void 0) { + if (!validate46(data.topBody, { + instancePath: instancePath + "/topBody", + parentData: data, + parentDataProperty: "topBody", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.topJoin !== void 0) { + if (!validate46(data.topJoin, { + instancePath: instancePath + "/topJoin", + parentData: data, + parentDataProperty: "topJoin", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.topLeft !== void 0) { + if (!validate46(data.topLeft, { + instancePath: instancePath + "/topLeft", + parentData: data, + parentDataProperty: "topLeft", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.topRight !== void 0) { + if (!validate46(data.topRight, { + instancePath: instancePath + "/topRight", + parentData: data, + parentDataProperty: "topRight", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.bottomBody !== void 0) { + if (!validate46(data.bottomBody, { + instancePath: instancePath + "/bottomBody", + parentData: data, + parentDataProperty: "bottomBody", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.bottomJoin !== void 0) { + if (!validate46(data.bottomJoin, { + instancePath: instancePath + "/bottomJoin", + parentData: data, + parentDataProperty: "bottomJoin", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.bottomLeft !== void 0) { + if (!validate46(data.bottomLeft, { + instancePath: instancePath + "/bottomLeft", + parentData: data, + parentDataProperty: "bottomLeft", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.bottomRight !== void 0) { + if (!validate46(data.bottomRight, { + instancePath: instancePath + "/bottomRight", + parentData: data, + parentDataProperty: "bottomRight", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.bodyLeft !== void 0) { + if (!validate46(data.bodyLeft, { + instancePath: instancePath + "/bodyLeft", + parentData: data, + parentDataProperty: "bodyLeft", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.bodyRight !== void 0) { + if (!validate46(data.bodyRight, { + instancePath: instancePath + "/bodyRight", + parentData: data, + parentDataProperty: "bodyRight", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.bodyJoin !== void 0) { + if (!validate46(data.bodyJoin, { + instancePath: instancePath + "/bodyJoin", + parentData: data, + parentDataProperty: "bodyJoin", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.headerJoin !== void 0) { + if (!validate46(data.headerJoin, { + instancePath: instancePath + "/headerJoin", + parentData: data, + parentDataProperty: "headerJoin", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinBody !== void 0) { + if (!validate46(data.joinBody, { + instancePath: instancePath + "/joinBody", + parentData: data, + parentDataProperty: "joinBody", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinLeft !== void 0) { + if (!validate46(data.joinLeft, { + instancePath: instancePath + "/joinLeft", + parentData: data, + parentDataProperty: "joinLeft", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinRight !== void 0) { + if (!validate46(data.joinRight, { + instancePath: instancePath + "/joinRight", + parentData: data, + parentDataProperty: "joinRight", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinJoin !== void 0) { + if (!validate46(data.joinJoin, { + instancePath: instancePath + "/joinJoin", + parentData: data, + parentDataProperty: "joinJoin", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinMiddleUp !== void 0) { + if (!validate46(data.joinMiddleUp, { + instancePath: instancePath + "/joinMiddleUp", + parentData: data, + parentDataProperty: "joinMiddleUp", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinMiddleDown !== void 0) { + if (!validate46(data.joinMiddleDown, { + instancePath: instancePath + "/joinMiddleDown", + parentData: data, + parentDataProperty: "joinMiddleDown", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinMiddleLeft !== void 0) { + if (!validate46(data.joinMiddleLeft, { + instancePath: instancePath + "/joinMiddleLeft", + parentData: data, + parentDataProperty: "joinMiddleLeft", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + if (data.joinMiddleRight !== void 0) { + if (!validate46(data.joinMiddleRight, { + instancePath: instancePath + "/joinMiddleRight", + parentData: data, + parentDataProperty: "joinMiddleRight", + rootData + })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + } + } else { + const err1 = { + instancePath, + schemaPath: "#/type", + keyword: "type", + params: { + type: "object" + }, + message: "must be object" + }; + if (vErrors === null) { + vErrors = [err1]; + } else { + vErrors.push(err1); + } + errors++; + } + validate87.errors = vErrors; + return errors === 0; + } + function validate109(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + let vErrors = null; + let errors = 0; + const _errs0 = errors; + let valid0 = false; + let passing0 = null; + const _errs1 = errors; + if (data && typeof data == "object" && !Array.isArray(data)) { + for (const key0 in data) { + if (!pattern0.test(key0)) { + const err0 = { + instancePath, + schemaPath: "#/oneOf/0/additionalProperties", + keyword: "additionalProperties", + params: { + additionalProperty: key0 + }, + message: "must NOT have additional properties" + }; + if (vErrors === null) { + vErrors = [err0]; + } else { + vErrors.push(err0); + } + errors++; + } + } + for (const key1 in data) { + if (pattern0.test(key1)) { + if (!validate71(data[key1], { + instancePath: instancePath + "/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), + parentData: data, + parentDataProperty: key1, + rootData + })) { + vErrors = vErrors === null ? validate71.errors : vErrors.concat(validate71.errors); + errors = vErrors.length; + } + } + } + } else { + const err1 = { + instancePath, + schemaPath: "#/oneOf/0/type", + keyword: "type", + params: { + type: "object" + }, + message: "must be object" + }; + if (vErrors === null) { + vErrors = [err1]; + } else { + vErrors.push(err1); + } + errors++; + } + var _valid0 = _errs1 === errors; + if (_valid0) { + valid0 = true; + passing0 = 0; + } + const _errs5 = errors; + if (Array.isArray(data)) { + const len0 = data.length; + for (let i0 = 0; i0 < len0; i0++) { + if (!validate71(data[i0], { + instancePath: instancePath + "/" + i0, + parentData: data, + parentDataProperty: i0, + rootData + })) { + vErrors = vErrors === null ? validate71.errors : vErrors.concat(validate71.errors); + errors = vErrors.length; + } + } + } else { + const err2 = { + instancePath, + schemaPath: "#/oneOf/1/type", + keyword: "type", + params: { + type: "array" + }, + message: "must be array" + }; + if (vErrors === null) { + vErrors = [err2]; + } else { + vErrors.push(err2); + } + errors++; + } + var _valid0 = _errs5 === errors; + if (_valid0 && valid0) { + valid0 = false; + passing0 = [passing0, 1]; + } else { + if (_valid0) { + valid0 = true; + passing0 = 1; + } + } + if (!valid0) { + const err3 = { + instancePath, + schemaPath: "#/oneOf", + keyword: "oneOf", + params: { + passingSchemas: passing0 + }, + message: "must match exactly one schema in oneOf" + }; + if (vErrors === null) { + vErrors = [err3]; + } else { + vErrors.push(err3); + } + errors++; + } else { + errors = _errs0; + if (vErrors !== null) { + if (_errs0) { + vErrors.length = _errs0; + } else { + vErrors = null; + } + } + } + validate109.errors = vErrors; + return errors === 0; + } + function validate113(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + let vErrors = null; + let errors = 0; + if (data && typeof data == "object" && !Array.isArray(data)) { + for (const key0 in data) { + if (!(key0 === "alignment" || key0 === "verticalAlignment" || key0 === "width" || key0 === "wrapWord" || key0 === "truncate" || key0 === "paddingLeft" || key0 === "paddingRight")) { + const err0 = { + instancePath, + schemaPath: "#/additionalProperties", + keyword: "additionalProperties", + params: { + additionalProperty: key0 + }, + message: "must NOT have additional properties" + }; + if (vErrors === null) { + vErrors = [err0]; + } else { + vErrors.push(err0); + } + errors++; + } + } + if (data.alignment !== void 0) { + if (!validate72(data.alignment, { + instancePath: instancePath + "/alignment", + parentData: data, + parentDataProperty: "alignment", + rootData + })) { + vErrors = vErrors === null ? validate72.errors : vErrors.concat(validate72.errors); + errors = vErrors.length; + } + } + if (data.verticalAlignment !== void 0) { + if (!validate74(data.verticalAlignment, { + instancePath: instancePath + "/verticalAlignment", + parentData: data, + parentDataProperty: "verticalAlignment", + rootData + })) { + vErrors = vErrors === null ? validate74.errors : vErrors.concat(validate74.errors); + errors = vErrors.length; + } + } + if (data.width !== void 0) { + let data2 = data.width; + if (!(typeof data2 == "number" && (!(data2 % 1) && !isNaN(data2)) && isFinite(data2))) { + const err1 = { + instancePath: instancePath + "/width", + schemaPath: "#/properties/width/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err1]; + } else { + vErrors.push(err1); + } + errors++; + } + if (typeof data2 == "number" && isFinite(data2)) { + if (data2 < 1 || isNaN(data2)) { + const err2 = { + instancePath: instancePath + "/width", + schemaPath: "#/properties/width/minimum", + keyword: "minimum", + params: { + comparison: ">=", + limit: 1 + }, + message: "must be >= 1" + }; + if (vErrors === null) { + vErrors = [err2]; + } else { + vErrors.push(err2); + } + errors++; + } + } + } + if (data.wrapWord !== void 0) { + if (typeof data.wrapWord !== "boolean") { + const err3 = { + instancePath: instancePath + "/wrapWord", + schemaPath: "#/properties/wrapWord/type", + keyword: "type", + params: { + type: "boolean" + }, + message: "must be boolean" + }; + if (vErrors === null) { + vErrors = [err3]; + } else { + vErrors.push(err3); + } + errors++; + } + } + if (data.truncate !== void 0) { + let data4 = data.truncate; + if (!(typeof data4 == "number" && (!(data4 % 1) && !isNaN(data4)) && isFinite(data4))) { + const err4 = { + instancePath: instancePath + "/truncate", + schemaPath: "#/properties/truncate/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err4]; + } else { + vErrors.push(err4); + } + errors++; + } + } + if (data.paddingLeft !== void 0) { + let data5 = data.paddingLeft; + if (!(typeof data5 == "number" && (!(data5 % 1) && !isNaN(data5)) && isFinite(data5))) { + const err5 = { + instancePath: instancePath + "/paddingLeft", + schemaPath: "#/properties/paddingLeft/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err5]; + } else { + vErrors.push(err5); + } + errors++; + } + } + if (data.paddingRight !== void 0) { + let data6 = data.paddingRight; + if (!(typeof data6 == "number" && (!(data6 % 1) && !isNaN(data6)) && isFinite(data6))) { + const err6 = { + instancePath: instancePath + "/paddingRight", + schemaPath: "#/properties/paddingRight/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err6]; + } else { + vErrors.push(err6); + } + errors++; + } + } + } else { + const err7 = { + instancePath, + schemaPath: "#/type", + keyword: "type", + params: { + type: "object" + }, + message: "must be object" + }; + if (vErrors === null) { + vErrors = [err7]; + } else { + vErrors.push(err7); + } + errors++; + } + validate113.errors = vErrors; + return errors === 0; + } + function validate86(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { + ; + let vErrors = null; + let errors = 0; + if (data && typeof data == "object" && !Array.isArray(data)) { + if (data.columnDefault === void 0) { + const err0 = { + instancePath, + schemaPath: "#/required", + keyword: "required", + params: { + missingProperty: "columnDefault" + }, + message: "must have required property 'columnDefault'" + }; + if (vErrors === null) { + vErrors = [err0]; + } else { + vErrors.push(err0); + } + errors++; + } + if (data.columnCount === void 0) { + const err1 = { + instancePath, + schemaPath: "#/required", + keyword: "required", + params: { + missingProperty: "columnCount" + }, + message: "must have required property 'columnCount'" + }; + if (vErrors === null) { + vErrors = [err1]; + } else { + vErrors.push(err1); + } + errors++; + } + for (const key0 in data) { + if (!(key0 === "border" || key0 === "columns" || key0 === "columnDefault" || key0 === "columnCount" || key0 === "drawVerticalLine")) { + const err2 = { + instancePath, + schemaPath: "#/additionalProperties", + keyword: "additionalProperties", + params: { + additionalProperty: key0 + }, + message: "must NOT have additional properties" + }; + if (vErrors === null) { + vErrors = [err2]; + } else { + vErrors.push(err2); + } + errors++; + } + } + if (data.border !== void 0) { + if (!validate87(data.border, { + instancePath: instancePath + "/border", + parentData: data, + parentDataProperty: "border", + rootData + })) { + vErrors = vErrors === null ? validate87.errors : vErrors.concat(validate87.errors); + errors = vErrors.length; + } + } + if (data.columns !== void 0) { + if (!validate109(data.columns, { + instancePath: instancePath + "/columns", + parentData: data, + parentDataProperty: "columns", + rootData + })) { + vErrors = vErrors === null ? validate109.errors : vErrors.concat(validate109.errors); + errors = vErrors.length; + } + } + if (data.columnDefault !== void 0) { + if (!validate113(data.columnDefault, { + instancePath: instancePath + "/columnDefault", + parentData: data, + parentDataProperty: "columnDefault", + rootData + })) { + vErrors = vErrors === null ? validate113.errors : vErrors.concat(validate113.errors); + errors = vErrors.length; + } + } + if (data.columnCount !== void 0) { + let data3 = data.columnCount; + if (!(typeof data3 == "number" && (!(data3 % 1) && !isNaN(data3)) && isFinite(data3))) { + const err3 = { + instancePath: instancePath + "/columnCount", + schemaPath: "#/properties/columnCount/type", + keyword: "type", + params: { + type: "integer" + }, + message: "must be integer" + }; + if (vErrors === null) { + vErrors = [err3]; + } else { + vErrors.push(err3); + } + errors++; + } + if (typeof data3 == "number" && isFinite(data3)) { + if (data3 < 1 || isNaN(data3)) { + const err4 = { + instancePath: instancePath + "/columnCount", + schemaPath: "#/properties/columnCount/minimum", + keyword: "minimum", + params: { + comparison: ">=", + limit: 1 + }, + message: "must be >= 1" + }; + if (vErrors === null) { + vErrors = [err4]; + } else { + vErrors.push(err4); + } + errors++; + } + } + } + if (data.drawVerticalLine !== void 0) { + if (typeof data.drawVerticalLine != "function") { + const err5 = { + instancePath: instancePath + "/drawVerticalLine", + schemaPath: "#/properties/drawVerticalLine/typeof", + keyword: "typeof", + params: {}, + message: 'must pass "typeof" keyword validation' + }; + if (vErrors === null) { + vErrors = [err5]; + } else { + vErrors.push(err5); + } + errors++; + } + } + } else { + const err6 = { + instancePath, + schemaPath: "#/type", + keyword: "type", + params: { + type: "object" + }, + message: "must be object" + }; + if (vErrors === null) { + vErrors = [err6]; + } else { + vErrors.push(err6); + } + errors++; + } + validate86.errors = vErrors; + return errors === 0; + } + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/validateConfig.js +var require_validateConfig = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/validateConfig.js"(exports) { + "use strict"; + var __importDefault = exports && exports.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateConfig = void 0; + var validators_1 = __importDefault(require_validators()); + var validateConfig = (schemaId, config3) => { + const validate2 = validators_1.default[schemaId]; + if (!validate2(config3) && validate2.errors) { + const errors = validate2.errors.map((error49) => { + return { + message: error49.message, + params: error49.params, + schemaPath: error49.schemaPath + }; + }); + console.log("config", config3); + console.log("errors", errors); + throw new Error("Invalid config."); + } + }; + exports.validateConfig = validateConfig; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/makeStreamConfig.js +var require_makeStreamConfig = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/makeStreamConfig.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.makeStreamConfig = void 0; + var utils_1 = require_utils3(); + var validateConfig_1 = require_validateConfig(); + var makeColumnsConfig = (columnCount, columns = {}, columnDefault) => { + return Array.from({ length: columnCount }).map((_, index) => { + return { + alignment: "left", + paddingLeft: 1, + paddingRight: 1, + truncate: Number.POSITIVE_INFINITY, + verticalAlignment: "top", + wrapWord: false, + ...columnDefault, + ...columns[index] + }; + }); + }; + var makeStreamConfig = (config3) => { + (0, validateConfig_1.validateConfig)("streamConfig.json", config3); + if (config3.columnDefault.width === void 0) { + throw new Error("Must provide config.columnDefault.width when creating a stream."); + } + return { + drawVerticalLine: () => { + return true; + }, + ...config3, + border: (0, utils_1.makeBorderConfig)(config3.border), + columns: makeColumnsConfig(config3.columnCount, config3.columns, config3.columnDefault) + }; + }; + exports.makeStreamConfig = makeStreamConfig; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/mapDataUsingRowHeights.js +var require_mapDataUsingRowHeights = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/mapDataUsingRowHeights.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.mapDataUsingRowHeights = exports.padCellVertically = void 0; + var utils_1 = require_utils3(); + var wrapCell_1 = require_wrapCell(); + var createEmptyStrings = (length) => { + return new Array(length).fill(""); + }; + var padCellVertically = (lines, rowHeight, verticalAlignment) => { + const availableLines = rowHeight - lines.length; + if (verticalAlignment === "top") { + return [...lines, ...createEmptyStrings(availableLines)]; + } + if (verticalAlignment === "bottom") { + return [...createEmptyStrings(availableLines), ...lines]; + } + return [ + ...createEmptyStrings(Math.floor(availableLines / 2)), + ...lines, + ...createEmptyStrings(Math.ceil(availableLines / 2)) + ]; + }; + exports.padCellVertically = padCellVertically; + var mapDataUsingRowHeights = (unmappedRows, rowHeights, config3) => { + const nColumns = unmappedRows[0].length; + const mappedRows = unmappedRows.map((unmappedRow, unmappedRowIndex) => { + const outputRowHeight = rowHeights[unmappedRowIndex]; + const outputRow = Array.from({ length: outputRowHeight }, () => { + return new Array(nColumns).fill(""); + }); + unmappedRow.forEach((cell, cellIndex) => { + var _a2; + const containingRange = (_a2 = config3.spanningCellManager) === null || _a2 === void 0 ? void 0 : _a2.getContainingRange({ + col: cellIndex, + row: unmappedRowIndex + }); + if (containingRange) { + containingRange.extractCellContent(unmappedRowIndex).forEach((cellLine, cellLineIndex) => { + outputRow[cellLineIndex][cellIndex] = cellLine; + }); + return; + } + const cellLines = (0, wrapCell_1.wrapCell)(cell, config3.columns[cellIndex].width, config3.columns[cellIndex].wrapWord); + const paddedCellLines = (0, exports.padCellVertically)(cellLines, outputRowHeight, config3.columns[cellIndex].verticalAlignment); + paddedCellLines.forEach((cellLine, cellLineIndex) => { + outputRow[cellLineIndex][cellIndex] = cellLine; + }); + }); + return outputRow; + }); + return (0, utils_1.flatten)(mappedRows); + }; + exports.mapDataUsingRowHeights = mapDataUsingRowHeights; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/padTableData.js +var require_padTableData = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/padTableData.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.padTableData = exports.padString = void 0; + var padString = (input, paddingLeft, paddingRight) => { + return " ".repeat(paddingLeft) + input + " ".repeat(paddingRight); + }; + exports.padString = padString; + var padTableData = (rows, config3) => { + return rows.map((cells, rowIndex) => { + return cells.map((cell, cellIndex) => { + var _a2; + const containingRange = (_a2 = config3.spanningCellManager) === null || _a2 === void 0 ? void 0 : _a2.getContainingRange({ + col: cellIndex, + row: rowIndex + }, { mapped: true }); + if (containingRange) { + return cell; + } + const { paddingLeft, paddingRight } = config3.columns[cellIndex]; + return (0, exports.padString)(cell, paddingLeft, paddingRight); + }); + }); + }; + exports.padTableData = padTableData; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/stringifyTableData.js +var require_stringifyTableData = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/stringifyTableData.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.stringifyTableData = void 0; + var utils_1 = require_utils3(); + var stringifyTableData = (rows) => { + return rows.map((cells) => { + return cells.map((cell) => { + return (0, utils_1.normalizeString)(String(cell)); + }); + }); + }; + exports.stringifyTableData = stringifyTableData; + } +}); + +// node_modules/.pnpm/lodash.truncate@4.4.2/node_modules/lodash.truncate/index.js +var require_lodash = __commonJS({ + "node_modules/.pnpm/lodash.truncate@4.4.2/node_modules/lodash.truncate/index.js"(exports, module) { + var DEFAULT_TRUNC_LENGTH = 30; + var DEFAULT_TRUNC_OMISSION = "..."; + var INFINITY2 = 1 / 0; + var MAX_INTEGER = 17976931348623157e292; + var NAN = 0 / 0; + var regexpTag = "[object RegExp]"; + var symbolTag = "[object Symbol]"; + var reTrim = /^\s+|\s+$/g; + var reFlags = /\w*$/; + var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + var reIsBinary = /^0b[01]+$/i; + var reIsOctal = /^0o[0-7]+$/i; + var rsAstralRange = "\\ud800-\\udfff"; + var rsComboMarksRange = "\\u0300-\\u036f\\ufe20-\\ufe23"; + var rsComboSymbolsRange = "\\u20d0-\\u20f0"; + var rsVarRange = "\\ufe0e\\ufe0f"; + var rsAstral = "[" + rsAstralRange + "]"; + var rsCombo = "[" + rsComboMarksRange + rsComboSymbolsRange + "]"; + var rsFitz = "\\ud83c[\\udffb-\\udfff]"; + var rsModifier = "(?:" + rsCombo + "|" + rsFitz + ")"; + var rsNonAstral = "[^" + rsAstralRange + "]"; + var rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}"; + var rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]"; + var rsZWJ = "\\u200d"; + var reOptMod = rsModifier + "?"; + var rsOptVar = "[" + rsVarRange + "]?"; + var rsOptJoin = "(?:" + rsZWJ + "(?:" + [rsNonAstral, rsRegional, rsSurrPair].join("|") + ")" + rsOptVar + reOptMod + ")*"; + var rsSeq = rsOptVar + reOptMod + rsOptJoin; + var rsSymbol = "(?:" + [rsNonAstral + rsCombo + "?", rsCombo, rsRegional, rsSurrPair, rsAstral].join("|") + ")"; + var reUnicode = RegExp(rsFitz + "(?=" + rsFitz + ")|" + rsSymbol + rsSeq, "g"); + var reHasUnicode = RegExp("[" + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + "]"); + var freeParseInt = parseInt; + var freeGlobal = typeof global == "object" && global && global.Object === Object && global; + var freeSelf = typeof self == "object" && self && self.Object === Object && self; + var root = freeGlobal || freeSelf || Function("return this")(); + var freeExports = typeof exports == "object" && exports && !exports.nodeType && exports; + var freeModule = freeExports && typeof module == "object" && module && !module.nodeType && module; + var moduleExports = freeModule && freeModule.exports === freeExports; + var freeProcess = moduleExports && freeGlobal.process; + var nodeUtil = (function() { + try { + return freeProcess && freeProcess.binding("util"); + } catch (e) { + } + })(); + var nodeIsRegExp = nodeUtil && nodeUtil.isRegExp; + var asciiSize = baseProperty("length"); + function asciiToArray(string6) { + return string6.split(""); + } + function baseProperty(key) { + return function(object5) { + return object5 == null ? void 0 : object5[key]; + }; + } + function baseUnary(func) { + return function(value2) { + return func(value2); + }; + } + function hasUnicode(string6) { + return reHasUnicode.test(string6); + } + function stringSize(string6) { + return hasUnicode(string6) ? unicodeSize(string6) : asciiSize(string6); + } + function stringToArray(string6) { + return hasUnicode(string6) ? unicodeToArray(string6) : asciiToArray(string6); + } + function unicodeSize(string6) { + var result = reUnicode.lastIndex = 0; + while (reUnicode.test(string6)) { + result++; + } + return result; + } + function unicodeToArray(string6) { + return string6.match(reUnicode) || []; + } + var objectProto = Object.prototype; + var objectToString = objectProto.toString; + var Symbol2 = root.Symbol; + var symbolProto = Symbol2 ? Symbol2.prototype : void 0; + var symbolToString = symbolProto ? symbolProto.toString : void 0; + function baseIsRegExp(value2) { + return isObject5(value2) && objectToString.call(value2) == regexpTag; + } + function baseSlice(array3, start, end) { + var index = -1, length = array3.length; + if (start < 0) { + start = -start > length ? 0 : length + start; + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : end - start >>> 0; + start >>>= 0; + var result = Array(length); + while (++index < length) { + result[index] = array3[index + start]; + } + return result; + } + function baseToString2(value2) { + if (typeof value2 == "string") { + return value2; + } + if (isSymbol(value2)) { + return symbolToString ? symbolToString.call(value2) : ""; + } + var result = value2 + ""; + return result == "0" && 1 / value2 == -INFINITY2 ? "-0" : result; + } + function castSlice(array3, start, end) { + var length = array3.length; + end = end === void 0 ? length : end; + return !start && end >= length ? array3 : baseSlice(array3, start, end); + } + function isObject5(value2) { + var type2 = typeof value2; + return !!value2 && (type2 == "object" || type2 == "function"); + } + function isObjectLike2(value2) { + return !!value2 && typeof value2 == "object"; + } + var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; + function isSymbol(value2) { + return typeof value2 == "symbol" || isObjectLike2(value2) && objectToString.call(value2) == symbolTag; + } + function toFinite(value2) { + if (!value2) { + return value2 === 0 ? value2 : 0; + } + value2 = toNumber(value2); + if (value2 === INFINITY2 || value2 === -INFINITY2) { + var sign = value2 < 0 ? -1 : 1; + return sign * MAX_INTEGER; + } + return value2 === value2 ? value2 : 0; + } + function toInteger(value2) { + var result = toFinite(value2), remainder = result % 1; + return result === result ? remainder ? result - remainder : result : 0; + } + function toNumber(value2) { + if (typeof value2 == "number") { + return value2; + } + if (isSymbol(value2)) { + return NAN; + } + if (isObject5(value2)) { + var other = typeof value2.valueOf == "function" ? value2.valueOf() : value2; + value2 = isObject5(other) ? other + "" : other; + } + if (typeof value2 != "string") { + return value2 === 0 ? value2 : +value2; + } + value2 = value2.replace(reTrim, ""); + var isBinary = reIsBinary.test(value2); + return isBinary || reIsOctal.test(value2) ? freeParseInt(value2.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value2) ? NAN : +value2; + } + function toString2(value2) { + return value2 == null ? "" : baseToString2(value2); + } + function truncate(string6, options) { + var length = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION; + if (isObject5(options)) { + var separator2 = "separator" in options ? options.separator : separator2; + length = "length" in options ? toInteger(options.length) : length; + omission = "omission" in options ? baseToString2(options.omission) : omission; + } + string6 = toString2(string6); + var strLength = string6.length; + if (hasUnicode(string6)) { + var strSymbols = stringToArray(string6); + strLength = strSymbols.length; + } + if (length >= strLength) { + return string6; + } + var end = length - stringSize(omission); + if (end < 1) { + return omission; + } + var result = strSymbols ? castSlice(strSymbols, 0, end).join("") : string6.slice(0, end); + if (separator2 === void 0) { + return result + omission; + } + if (strSymbols) { + end += result.length - end; + } + if (isRegExp(separator2)) { + if (string6.slice(end).search(separator2)) { + var match3, substring = result; + if (!separator2.global) { + separator2 = RegExp(separator2.source, toString2(reFlags.exec(separator2)) + "g"); + } + separator2.lastIndex = 0; + while (match3 = separator2.exec(substring)) { + var newEnd = match3.index; + } + result = result.slice(0, newEnd === void 0 ? end : newEnd); + } + } else if (string6.indexOf(baseToString2(separator2), end) != end) { + var index = result.lastIndexOf(separator2); + if (index > -1) { + result = result.slice(0, index); + } + } + return result + omission; + } + module.exports = truncate; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/truncateTableData.js +var require_truncateTableData = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/truncateTableData.js"(exports) { + "use strict"; + var __importDefault = exports && exports.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.truncateTableData = exports.truncateString = void 0; + var lodash_truncate_1 = __importDefault(require_lodash()); + var truncateString = (input, length) => { + return (0, lodash_truncate_1.default)(input, { + length, + omission: "\u2026" + }); + }; + exports.truncateString = truncateString; + var truncateTableData = (rows, truncates) => { + return rows.map((cells) => { + return cells.map((cell, cellIndex) => { + return (0, exports.truncateString)(cell, truncates[cellIndex]); + }); + }); + }; + exports.truncateTableData = truncateTableData; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/createStream.js +var require_createStream = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/createStream.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createStream = void 0; + var alignTableData_1 = require_alignTableData(); + var calculateRowHeights_1 = require_calculateRowHeights(); + var drawBorder_1 = require_drawBorder(); + var drawRow_1 = require_drawRow(); + var makeStreamConfig_1 = require_makeStreamConfig(); + var mapDataUsingRowHeights_1 = require_mapDataUsingRowHeights(); + var padTableData_1 = require_padTableData(); + var stringifyTableData_1 = require_stringifyTableData(); + var truncateTableData_1 = require_truncateTableData(); + var utils_1 = require_utils3(); + var prepareData = (data, config3) => { + let rows = (0, stringifyTableData_1.stringifyTableData)(data); + rows = (0, truncateTableData_1.truncateTableData)(rows, (0, utils_1.extractTruncates)(config3)); + const rowHeights = (0, calculateRowHeights_1.calculateRowHeights)(rows, config3); + rows = (0, mapDataUsingRowHeights_1.mapDataUsingRowHeights)(rows, rowHeights, config3); + rows = (0, alignTableData_1.alignTableData)(rows, config3); + rows = (0, padTableData_1.padTableData)(rows, config3); + return rows; + }; + var create = (row, columnWidths, config3) => { + const rows = prepareData([row], config3); + const body = rows.map((literalRow) => { + return (0, drawRow_1.drawRow)(literalRow, config3); + }).join(""); + let output; + output = ""; + output += (0, drawBorder_1.drawBorderTop)(columnWidths, config3); + output += body; + output += (0, drawBorder_1.drawBorderBottom)(columnWidths, config3); + output = output.trimEnd(); + process.stdout.write(output); + }; + var append2 = (row, columnWidths, config3) => { + const rows = prepareData([row], config3); + const body = rows.map((literalRow) => { + return (0, drawRow_1.drawRow)(literalRow, config3); + }).join(""); + let output = ""; + const bottom = (0, drawBorder_1.drawBorderBottom)(columnWidths, config3); + if (bottom !== "\n") { + output = "\r\x1B[K"; + } + output += (0, drawBorder_1.drawBorderJoin)(columnWidths, config3); + output += body; + output += bottom; + output = output.trimEnd(); + process.stdout.write(output); + }; + var createStream = (userConfig) => { + const config3 = (0, makeStreamConfig_1.makeStreamConfig)(userConfig); + const columnWidths = Object.values(config3.columns).map((column) => { + return column.width + column.paddingLeft + column.paddingRight; + }); + let empty = true; + return { + write: (row) => { + if (row.length !== config3.columnCount) { + throw new Error("Row cell count does not match the config.columnCount."); + } + if (empty) { + empty = false; + create(row, columnWidths, config3); + } else { + append2(row, columnWidths, config3); + } + } + }; + }; + exports.createStream = createStream; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/calculateOutputColumnWidths.js +var require_calculateOutputColumnWidths = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/calculateOutputColumnWidths.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.calculateOutputColumnWidths = void 0; + var calculateOutputColumnWidths = (config3) => { + return config3.columns.map((col) => { + return col.paddingLeft + col.width + col.paddingRight; + }); + }; + exports.calculateOutputColumnWidths = calculateOutputColumnWidths; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/drawTable.js +var require_drawTable = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/drawTable.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.drawTable = void 0; + var drawBorder_1 = require_drawBorder(); + var drawContent_1 = require_drawContent(); + var drawRow_1 = require_drawRow(); + var utils_1 = require_utils3(); + var drawTable = (rows, outputColumnWidths, rowHeights, config3) => { + const { drawHorizontalLine, singleLine } = config3; + const contents = (0, utils_1.groupBySizes)(rows, rowHeights).map((group2, groupIndex) => { + return group2.map((row) => { + return (0, drawRow_1.drawRow)(row, { + ...config3, + rowIndex: groupIndex + }); + }).join(""); + }); + return (0, drawContent_1.drawContent)({ + contents, + drawSeparator: (index, size) => { + if (index === 0 || index === size) { + return drawHorizontalLine(index, size); + } + return !singleLine && drawHorizontalLine(index, size); + }, + elementType: "row", + rowIndex: -1, + separatorGetter: (0, drawBorder_1.createTableBorderGetter)(outputColumnWidths, { + ...config3, + rowCount: contents.length + }), + spanningCellManager: config3.spanningCellManager + }); + }; + exports.drawTable = drawTable; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/injectHeaderConfig.js +var require_injectHeaderConfig = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/injectHeaderConfig.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.injectHeaderConfig = void 0; + var injectHeaderConfig = (rows, config3) => { + var _a2; + let spanningCellConfig = (_a2 = config3.spanningCells) !== null && _a2 !== void 0 ? _a2 : []; + const headerConfig = config3.header; + const adjustedRows = [...rows]; + if (headerConfig) { + spanningCellConfig = spanningCellConfig.map(({ row, ...rest }) => { + return { + ...rest, + row: row + 1 + }; + }); + const { content, ...headerStyles } = headerConfig; + spanningCellConfig.unshift({ + alignment: "center", + col: 0, + colSpan: rows[0].length, + paddingLeft: 1, + paddingRight: 1, + row: 0, + wrapWord: false, + ...headerStyles + }); + adjustedRows.unshift([content, ...Array.from({ length: rows[0].length - 1 }).fill("")]); + } + return [ + adjustedRows, + spanningCellConfig + ]; + }; + exports.injectHeaderConfig = injectHeaderConfig; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/calculateMaximumColumnWidths.js +var require_calculateMaximumColumnWidths = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/calculateMaximumColumnWidths.js"(exports) { + "use strict"; + var __importDefault = exports && exports.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.calculateMaximumColumnWidths = exports.calculateMaximumCellWidth = void 0; + var string_width_1 = __importDefault(require_string_width()); + var utils_1 = require_utils3(); + var calculateMaximumCellWidth = (cell) => { + return Math.max(...cell.split("\n").map(string_width_1.default)); + }; + exports.calculateMaximumCellWidth = calculateMaximumCellWidth; + var calculateMaximumColumnWidths = (rows, spanningCellConfigs = []) => { + const columnWidths = new Array(rows[0].length).fill(0); + const rangeCoordinates = spanningCellConfigs.map(utils_1.calculateRangeCoordinate); + const isSpanningCell = (rowIndex, columnIndex) => { + return rangeCoordinates.some((rangeCoordinate) => { + return (0, utils_1.isCellInRange)({ + col: columnIndex, + row: rowIndex + }, rangeCoordinate); + }); + }; + rows.forEach((row, rowIndex) => { + row.forEach((cell, cellIndex) => { + if (isSpanningCell(rowIndex, cellIndex)) { + return; + } + columnWidths[cellIndex] = Math.max(columnWidths[cellIndex], (0, exports.calculateMaximumCellWidth)(cell)); + }); + }); + return columnWidths; + }; + exports.calculateMaximumColumnWidths = calculateMaximumColumnWidths; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/alignSpanningCell.js +var require_alignSpanningCell = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/alignSpanningCell.js"(exports) { + "use strict"; + var __importDefault = exports && exports.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.alignVerticalRangeContent = exports.wrapRangeContent = void 0; + var string_width_1 = __importDefault(require_string_width()); + var alignString_1 = require_alignString(); + var mapDataUsingRowHeights_1 = require_mapDataUsingRowHeights(); + var padTableData_1 = require_padTableData(); + var truncateTableData_1 = require_truncateTableData(); + var utils_1 = require_utils3(); + var wrapCell_1 = require_wrapCell(); + var wrapRangeContent = (rangeConfig, rangeWidth, context) => { + const { topLeft, paddingRight, paddingLeft, truncate, wrapWord, alignment } = rangeConfig; + const originalContent = context.rows[topLeft.row][topLeft.col]; + const contentWidth = rangeWidth - paddingLeft - paddingRight; + return (0, wrapCell_1.wrapCell)((0, truncateTableData_1.truncateString)(originalContent, truncate), contentWidth, wrapWord).map((line) => { + const alignedLine = (0, alignString_1.alignString)(line, contentWidth, alignment); + return (0, padTableData_1.padString)(alignedLine, paddingLeft, paddingRight); + }); + }; + exports.wrapRangeContent = wrapRangeContent; + var alignVerticalRangeContent = (range2, content, context) => { + const { rows, drawHorizontalLine, rowHeights } = context; + const { topLeft, bottomRight, verticalAlignment } = range2; + if (rowHeights.length === 0) { + return []; + } + const totalCellHeight = (0, utils_1.sumArray)(rowHeights.slice(topLeft.row, bottomRight.row + 1)); + const totalBorderHeight = bottomRight.row - topLeft.row; + const hiddenHorizontalBorderCount = (0, utils_1.sequence)(topLeft.row + 1, bottomRight.row).filter((horizontalBorderIndex) => { + return !drawHorizontalLine(horizontalBorderIndex, rows.length); + }).length; + const availableRangeHeight = totalCellHeight + totalBorderHeight - hiddenHorizontalBorderCount; + return (0, mapDataUsingRowHeights_1.padCellVertically)(content, availableRangeHeight, verticalAlignment).map((line) => { + if (line.length === 0) { + return " ".repeat((0, string_width_1.default)(content[0])); + } + return line; + }); + }; + exports.alignVerticalRangeContent = alignVerticalRangeContent; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/calculateSpanningCellWidth.js +var require_calculateSpanningCellWidth = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/calculateSpanningCellWidth.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.calculateSpanningCellWidth = void 0; + var utils_1 = require_utils3(); + var calculateSpanningCellWidth = (rangeConfig, dependencies) => { + const { columnsConfig, drawVerticalLine } = dependencies; + const { topLeft, bottomRight } = rangeConfig; + const totalWidth = (0, utils_1.sumArray)(columnsConfig.slice(topLeft.col, bottomRight.col + 1).map(({ width }) => { + return width; + })); + const totalPadding = topLeft.col === bottomRight.col ? columnsConfig[topLeft.col].paddingRight + columnsConfig[bottomRight.col].paddingLeft : (0, utils_1.sumArray)(columnsConfig.slice(topLeft.col, bottomRight.col + 1).map(({ paddingLeft, paddingRight }) => { + return paddingLeft + paddingRight; + })); + const totalBorderWidths = bottomRight.col - topLeft.col; + const totalHiddenVerticalBorders = (0, utils_1.sequence)(topLeft.col + 1, bottomRight.col).filter((verticalBorderIndex) => { + return !drawVerticalLine(verticalBorderIndex, columnsConfig.length); + }).length; + return totalWidth + totalPadding + totalBorderWidths - totalHiddenVerticalBorders; + }; + exports.calculateSpanningCellWidth = calculateSpanningCellWidth; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/makeRangeConfig.js +var require_makeRangeConfig = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/makeRangeConfig.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.makeRangeConfig = void 0; + var utils_1 = require_utils3(); + var makeRangeConfig = (spanningCellConfig, columnsConfig) => { + var _a2; + const { topLeft, bottomRight } = (0, utils_1.calculateRangeCoordinate)(spanningCellConfig); + const cellConfig = { + ...columnsConfig[topLeft.col], + ...spanningCellConfig, + paddingRight: (_a2 = spanningCellConfig.paddingRight) !== null && _a2 !== void 0 ? _a2 : columnsConfig[bottomRight.col].paddingRight + }; + return { + ...cellConfig, + bottomRight, + topLeft + }; + }; + exports.makeRangeConfig = makeRangeConfig; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/spanningCellManager.js +var require_spanningCellManager = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/spanningCellManager.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createSpanningCellManager = void 0; + var alignSpanningCell_1 = require_alignSpanningCell(); + var calculateSpanningCellWidth_1 = require_calculateSpanningCellWidth(); + var makeRangeConfig_1 = require_makeRangeConfig(); + var utils_1 = require_utils3(); + var findRangeConfig = (cell, rangeConfigs) => { + return rangeConfigs.find((rangeCoordinate) => { + return (0, utils_1.isCellInRange)(cell, rangeCoordinate); + }); + }; + var getContainingRange = (rangeConfig, context) => { + const width = (0, calculateSpanningCellWidth_1.calculateSpanningCellWidth)(rangeConfig, context); + const wrappedContent = (0, alignSpanningCell_1.wrapRangeContent)(rangeConfig, width, context); + const alignedContent = (0, alignSpanningCell_1.alignVerticalRangeContent)(rangeConfig, wrappedContent, context); + const getCellContent = (rowIndex) => { + const { topLeft } = rangeConfig; + const { drawHorizontalLine, rowHeights } = context; + const totalWithinHorizontalBorderHeight = rowIndex - topLeft.row; + const totalHiddenHorizontalBorderHeight = (0, utils_1.sequence)(topLeft.row + 1, rowIndex).filter((index) => { + return !(drawHorizontalLine === null || drawHorizontalLine === void 0 ? void 0 : drawHorizontalLine(index, rowHeights.length)); + }).length; + const offset = (0, utils_1.sumArray)(rowHeights.slice(topLeft.row, rowIndex)) + totalWithinHorizontalBorderHeight - totalHiddenHorizontalBorderHeight; + return alignedContent.slice(offset, offset + rowHeights[rowIndex]); + }; + const getBorderContent = (borderIndex) => { + const { topLeft } = rangeConfig; + const offset = (0, utils_1.sumArray)(context.rowHeights.slice(topLeft.row, borderIndex)) + (borderIndex - topLeft.row - 1); + return alignedContent[offset]; + }; + return { + ...rangeConfig, + extractBorderContent: getBorderContent, + extractCellContent: getCellContent, + height: wrappedContent.length, + width + }; + }; + var inSameRange = (cell1, cell2, ranges) => { + const range1 = findRangeConfig(cell1, ranges); + const range2 = findRangeConfig(cell2, ranges); + if (range1 && range2) { + return (0, utils_1.areCellEqual)(range1.topLeft, range2.topLeft); + } + return false; + }; + var hashRange = (range2) => { + const { row, col } = range2.topLeft; + return `${row}/${col}`; + }; + var createSpanningCellManager = (parameters) => { + const { spanningCellConfigs, columnsConfig } = parameters; + const ranges = spanningCellConfigs.map((config3) => { + return (0, makeRangeConfig_1.makeRangeConfig)(config3, columnsConfig); + }); + const rangeCache = {}; + let rowHeights = []; + let rowIndexMapping = []; + return { + getContainingRange: (cell, options) => { + var _a2; + const originalRow = (options === null || options === void 0 ? void 0 : options.mapped) ? rowIndexMapping[cell.row] : cell.row; + const range2 = findRangeConfig({ + ...cell, + row: originalRow + }, ranges); + if (!range2) { + return void 0; + } + if (rowHeights.length === 0) { + return getContainingRange(range2, { + ...parameters, + rowHeights + }); + } + const hash2 = hashRange(range2); + (_a2 = rangeCache[hash2]) !== null && _a2 !== void 0 ? _a2 : rangeCache[hash2] = getContainingRange(range2, { + ...parameters, + rowHeights + }); + return rangeCache[hash2]; + }, + inSameRange: (cell1, cell2) => { + return inSameRange(cell1, cell2, ranges); + }, + rowHeights, + rowIndexMapping, + setRowHeights: (_rowHeights) => { + rowHeights = _rowHeights; + }, + setRowIndexMapping: (mappedRowHeights) => { + rowIndexMapping = (0, utils_1.flatten)(mappedRowHeights.map((height, index) => { + return Array.from({ length: height }, () => { + return index; + }); + })); + } + }; + }; + exports.createSpanningCellManager = createSpanningCellManager; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/validateSpanningCellConfig.js +var require_validateSpanningCellConfig = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/validateSpanningCellConfig.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateSpanningCellConfig = void 0; + var utils_1 = require_utils3(); + var inRange = (start, end, value2) => { + return start <= value2 && value2 <= end; + }; + var validateSpanningCellConfig = (rows, configs) => { + const [nRow, nCol] = [rows.length, rows[0].length]; + configs.forEach((config3, configIndex) => { + const { colSpan, rowSpan } = config3; + if (colSpan === void 0 && rowSpan === void 0) { + throw new Error(`Expect at least colSpan or rowSpan is provided in config.spanningCells[${configIndex}]`); + } + if (colSpan !== void 0 && colSpan < 1) { + throw new Error(`Expect colSpan is not equal zero, instead got: ${colSpan} in config.spanningCells[${configIndex}]`); + } + if (rowSpan !== void 0 && rowSpan < 1) { + throw new Error(`Expect rowSpan is not equal zero, instead got: ${rowSpan} in config.spanningCells[${configIndex}]`); + } + }); + const rangeCoordinates = configs.map(utils_1.calculateRangeCoordinate); + rangeCoordinates.forEach(({ topLeft, bottomRight }, rangeIndex) => { + if (!inRange(0, nCol - 1, topLeft.col) || !inRange(0, nRow - 1, topLeft.row) || !inRange(0, nCol - 1, bottomRight.col) || !inRange(0, nRow - 1, bottomRight.row)) { + throw new Error(`Some cells in config.spanningCells[${rangeIndex}] are out of the table`); + } + }); + const configOccupy = Array.from({ length: nRow }, () => { + return Array.from({ length: nCol }); + }); + rangeCoordinates.forEach(({ topLeft, bottomRight }, rangeIndex) => { + (0, utils_1.sequence)(topLeft.row, bottomRight.row).forEach((row) => { + (0, utils_1.sequence)(topLeft.col, bottomRight.col).forEach((col) => { + if (configOccupy[row][col] !== void 0) { + throw new Error(`Spanning cells in config.spanningCells[${configOccupy[row][col]}] and config.spanningCells[${rangeIndex}] are overlap each other`); + } + configOccupy[row][col] = rangeIndex; + }); + }); + }); + }; + exports.validateSpanningCellConfig = validateSpanningCellConfig; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/makeTableConfig.js +var require_makeTableConfig = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/makeTableConfig.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.makeTableConfig = void 0; + var calculateMaximumColumnWidths_1 = require_calculateMaximumColumnWidths(); + var spanningCellManager_1 = require_spanningCellManager(); + var utils_1 = require_utils3(); + var validateConfig_1 = require_validateConfig(); + var validateSpanningCellConfig_1 = require_validateSpanningCellConfig(); + var makeColumnsConfig = (rows, columns, columnDefault, spanningCellConfigs) => { + const columnWidths = (0, calculateMaximumColumnWidths_1.calculateMaximumColumnWidths)(rows, spanningCellConfigs); + return rows[0].map((_, columnIndex) => { + return { + alignment: "left", + paddingLeft: 1, + paddingRight: 1, + truncate: Number.POSITIVE_INFINITY, + verticalAlignment: "top", + width: columnWidths[columnIndex], + wrapWord: false, + ...columnDefault, + ...columns === null || columns === void 0 ? void 0 : columns[columnIndex] + }; + }); + }; + var makeTableConfig = (rows, config3 = {}, injectedSpanningCellConfig) => { + var _a2, _b, _c, _d, _e; + (0, validateConfig_1.validateConfig)("config.json", config3); + (0, validateSpanningCellConfig_1.validateSpanningCellConfig)(rows, (_a2 = config3.spanningCells) !== null && _a2 !== void 0 ? _a2 : []); + const spanningCellConfigs = (_b = injectedSpanningCellConfig !== null && injectedSpanningCellConfig !== void 0 ? injectedSpanningCellConfig : config3.spanningCells) !== null && _b !== void 0 ? _b : []; + const columnsConfig = makeColumnsConfig(rows, config3.columns, config3.columnDefault, spanningCellConfigs); + const drawVerticalLine = (_c = config3.drawVerticalLine) !== null && _c !== void 0 ? _c : (() => { + return true; + }); + const drawHorizontalLine = (_d = config3.drawHorizontalLine) !== null && _d !== void 0 ? _d : (() => { + return true; + }); + return { + ...config3, + border: (0, utils_1.makeBorderConfig)(config3.border), + columns: columnsConfig, + drawHorizontalLine, + drawVerticalLine, + singleLine: (_e = config3.singleLine) !== null && _e !== void 0 ? _e : false, + spanningCellManager: (0, spanningCellManager_1.createSpanningCellManager)({ + columnsConfig, + drawHorizontalLine, + drawVerticalLine, + rows, + spanningCellConfigs + }) + }; + }; + exports.makeTableConfig = makeTableConfig; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/validateTableData.js +var require_validateTableData = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/validateTableData.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateTableData = void 0; + var utils_1 = require_utils3(); + var validateTableData = (rows) => { + if (!Array.isArray(rows)) { + throw new TypeError("Table data must be an array."); + } + if (rows.length === 0) { + throw new Error("Table must define at least one row."); + } + if (rows[0].length === 0) { + throw new Error("Table must define at least one column."); + } + const columnNumber = rows[0].length; + for (const row of rows) { + if (!Array.isArray(row)) { + throw new TypeError("Table row data must be an array."); + } + if (row.length !== columnNumber) { + throw new Error("Table must have a consistent number of cells."); + } + for (const cell of row) { + if (/[\u0001-\u0006\u0008\u0009\u000B-\u001A]/.test((0, utils_1.normalizeString)(String(cell)))) { + throw new Error("Table data must not contain control characters."); + } + } + } + }; + exports.validateTableData = validateTableData; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/table.js +var require_table = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/table.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.table = void 0; + var alignTableData_1 = require_alignTableData(); + var calculateOutputColumnWidths_1 = require_calculateOutputColumnWidths(); + var calculateRowHeights_1 = require_calculateRowHeights(); + var drawTable_1 = require_drawTable(); + var injectHeaderConfig_1 = require_injectHeaderConfig(); + var makeTableConfig_1 = require_makeTableConfig(); + var mapDataUsingRowHeights_1 = require_mapDataUsingRowHeights(); + var padTableData_1 = require_padTableData(); + var stringifyTableData_1 = require_stringifyTableData(); + var truncateTableData_1 = require_truncateTableData(); + var utils_1 = require_utils3(); + var validateTableData_1 = require_validateTableData(); + var table2 = (data, userConfig = {}) => { + (0, validateTableData_1.validateTableData)(data); + let rows = (0, stringifyTableData_1.stringifyTableData)(data); + const [injectedRows, injectedSpanningCellConfig] = (0, injectHeaderConfig_1.injectHeaderConfig)(rows, userConfig); + const config3 = (0, makeTableConfig_1.makeTableConfig)(injectedRows, userConfig, injectedSpanningCellConfig); + rows = (0, truncateTableData_1.truncateTableData)(injectedRows, (0, utils_1.extractTruncates)(config3)); + const rowHeights = (0, calculateRowHeights_1.calculateRowHeights)(rows, config3); + config3.spanningCellManager.setRowHeights(rowHeights); + config3.spanningCellManager.setRowIndexMapping(rowHeights); + rows = (0, mapDataUsingRowHeights_1.mapDataUsingRowHeights)(rows, rowHeights, config3); + rows = (0, alignTableData_1.alignTableData)(rows, config3); + rows = (0, padTableData_1.padTableData)(rows, config3); + const outputColumnWidths = (0, calculateOutputColumnWidths_1.calculateOutputColumnWidths)(config3); + return (0, drawTable_1.drawTable)(rows, outputColumnWidths, rowHeights, config3); + }; + exports.table = table2; + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/types/api.js +var require_api2 = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/types/api.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + } +}); + +// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/index.js +var require_src = __commonJS({ + "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/index.js"(exports) { + "use strict"; + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { + return m[k]; + } }); + }) : (function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + })); + var __exportStar = exports && exports.__exportStar || function(m, exports2) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getBorderCharacters = exports.createStream = exports.table = void 0; + var createStream_1 = require_createStream(); + Object.defineProperty(exports, "createStream", { enumerable: true, get: function() { + return createStream_1.createStream; + } }); + var getBorderCharacters_1 = require_getBorderCharacters(); + Object.defineProperty(exports, "getBorderCharacters", { enumerable: true, get: function() { + return getBorderCharacters_1.getBorderCharacters; + } }); + var table_1 = require_table(); + Object.defineProperty(exports, "table", { enumerable: true, get: function() { + return table_1.table; + } }); + __exportStar(require_api2(), exports); + } +}); + +// node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/light.js +var require_light = __commonJS({ + "node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/light.js"(exports, module) { + (function(global2, factory) { + typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && define.amd ? define(factory) : global2.Bottleneck = factory(); + })(exports, (function() { + "use strict"; + var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {}; + function getCjsExportFromNamespace(n) { + return n && n["default"] || n; + } + var load = function(received, defaults, onto = {}) { + var k, ref, v; + for (k in defaults) { + v = defaults[k]; + onto[k] = (ref = received[k]) != null ? ref : v; + } + return onto; + }; + var overwrite = function(received, defaults, onto = {}) { + var k, v; + for (k in received) { + v = received[k]; + if (defaults[k] !== void 0) { + onto[k] = v; + } + } + return onto; + }; + var parser = { + load, + overwrite + }; + var DLList; + DLList = class DLList { + constructor(incr, decr) { + this.incr = incr; + this.decr = decr; + this._first = null; + this._last = null; + this.length = 0; + } + push(value2) { + var node2; + this.length++; + if (typeof this.incr === "function") { + this.incr(); + } + node2 = { + value: value2, + prev: this._last, + next: null + }; + if (this._last != null) { + this._last.next = node2; + this._last = node2; + } else { + this._first = this._last = node2; + } + return void 0; + } + shift() { + var value2; + if (this._first == null) { + return; + } else { + this.length--; + if (typeof this.decr === "function") { + this.decr(); + } + } + value2 = this._first.value; + if ((this._first = this._first.next) != null) { + this._first.prev = null; + } else { + this._last = null; + } + return value2; + } + first() { + if (this._first != null) { + return this._first.value; + } + } + getArray() { + var node2, ref, results; + node2 = this._first; + results = []; + while (node2 != null) { + results.push((ref = node2, node2 = node2.next, ref.value)); + } + return results; + } + forEachShift(cb) { + var node2; + node2 = this.shift(); + while (node2 != null) { + cb(node2), node2 = this.shift(); + } + return void 0; + } + debug() { + var node2, ref, ref1, ref2, results; + node2 = this._first; + results = []; + while (node2 != null) { + results.push((ref = node2, node2 = node2.next, { + value: ref.value, + prev: (ref1 = ref.prev) != null ? ref1.value : void 0, + next: (ref2 = ref.next) != null ? ref2.value : void 0 + })); + } + return results; + } + }; + var DLList_1 = DLList; + var Events; + Events = class Events { + constructor(instance) { + this.instance = instance; + this._events = {}; + if (this.instance.on != null || this.instance.once != null || this.instance.removeAllListeners != null) { + throw new Error("An Emitter already exists for this object"); + } + this.instance.on = (name, cb) => { + return this._addListener(name, "many", cb); + }; + this.instance.once = (name, cb) => { + return this._addListener(name, "once", cb); + }; + this.instance.removeAllListeners = (name = null) => { + if (name != null) { + return delete this._events[name]; + } else { + return this._events = {}; + } + }; + } + _addListener(name, status, cb) { + var base; + if ((base = this._events)[name] == null) { + base[name] = []; + } + this._events[name].push({ cb, status }); + return this.instance; + } + listenerCount(name) { + if (this._events[name] != null) { + return this._events[name].length; + } else { + return 0; + } + } + async trigger(name, ...args2) { + var e, promises; + try { + if (name !== "debug") { + this.trigger("debug", `Event triggered: ${name}`, args2); + } + if (this._events[name] == null) { + return; + } + this._events[name] = this._events[name].filter(function(listener) { + return listener.status !== "none"; + }); + promises = this._events[name].map(async (listener) => { + var e2, returned; + if (listener.status === "none") { + return; + } + if (listener.status === "once") { + listener.status = "none"; + } + try { + returned = typeof listener.cb === "function" ? listener.cb(...args2) : void 0; + if (typeof (returned != null ? returned.then : void 0) === "function") { + return await returned; + } else { + return returned; + } + } catch (error49) { + e2 = error49; + { + this.trigger("error", e2); + } + return null; + } + }); + return (await Promise.all(promises)).find(function(x) { + return x != null; + }); + } catch (error49) { + e = error49; + { + this.trigger("error", e); + } + return null; + } + } + }; + var Events_1 = Events; + var DLList$1, Events$1, Queues; + DLList$1 = DLList_1; + Events$1 = Events_1; + Queues = class Queues { + constructor(num_priorities) { + var i; + this.Events = new Events$1(this); + this._length = 0; + this._lists = (function() { + var j, ref, results; + results = []; + for (i = j = 1, ref = num_priorities; 1 <= ref ? j <= ref : j >= ref; i = 1 <= ref ? ++j : --j) { + results.push(new DLList$1((() => { + return this.incr(); + }), (() => { + return this.decr(); + }))); + } + return results; + }).call(this); + } + incr() { + if (this._length++ === 0) { + return this.Events.trigger("leftzero"); + } + } + decr() { + if (--this._length === 0) { + return this.Events.trigger("zero"); + } + } + push(job) { + return this._lists[job.options.priority].push(job); + } + queued(priority) { + if (priority != null) { + return this._lists[priority].length; + } else { + return this._length; + } + } + shiftAll(fn2) { + return this._lists.forEach(function(list) { + return list.forEachShift(fn2); + }); + } + getFirst(arr = this._lists) { + var j, len, list; + for (j = 0, len = arr.length; j < len; j++) { + list = arr[j]; + if (list.length > 0) { + return list; + } + } + return []; + } + shiftLastFrom(priority) { + return this.getFirst(this._lists.slice(priority).reverse()).shift(); + } + }; + var Queues_1 = Queues; + var BottleneckError; + BottleneckError = class BottleneckError extends Error { + }; + var BottleneckError_1 = BottleneckError; + var BottleneckError$1, DEFAULT_PRIORITY, Job, NUM_PRIORITIES, parser$1; + NUM_PRIORITIES = 10; + DEFAULT_PRIORITY = 5; + parser$1 = parser; + BottleneckError$1 = BottleneckError_1; + Job = class Job { + constructor(task, args2, options, jobDefaults, rejectOnDrop, Events2, _states, Promise2) { + this.task = task; + this.args = args2; + this.rejectOnDrop = rejectOnDrop; + this.Events = Events2; + this._states = _states; + this.Promise = Promise2; + this.options = parser$1.load(options, jobDefaults); + this.options.priority = this._sanitizePriority(this.options.priority); + if (this.options.id === jobDefaults.id) { + this.options.id = `${this.options.id}-${this._randomIndex()}`; + } + this.promise = new this.Promise((_resolve, _reject) => { + this._resolve = _resolve; + this._reject = _reject; + }); + this.retryCount = 0; + } + _sanitizePriority(priority) { + var sProperty; + sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority; + if (sProperty < 0) { + return 0; + } else if (sProperty > NUM_PRIORITIES - 1) { + return NUM_PRIORITIES - 1; + } else { + return sProperty; + } + } + _randomIndex() { + return Math.random().toString(36).slice(2); + } + doDrop({ error: error49, message = "This job has been dropped by Bottleneck" } = {}) { + if (this._states.remove(this.options.id)) { + if (this.rejectOnDrop) { + this._reject(error49 != null ? error49 : new BottleneckError$1(message)); + } + this.Events.trigger("dropped", { args: this.args, options: this.options, task: this.task, promise: this.promise }); + return true; + } else { + return false; + } + } + _assertStatus(expected) { + var status; + status = this._states.jobStatus(this.options.id); + if (!(status === expected || expected === "DONE" && status === null)) { + throw new BottleneckError$1(`Invalid job status ${status}, expected ${expected}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`); + } + } + doReceive() { + this._states.start(this.options.id); + return this.Events.trigger("received", { args: this.args, options: this.options }); + } + doQueue(reachedHWM, blocked) { + this._assertStatus("RECEIVED"); + this._states.next(this.options.id); + return this.Events.trigger("queued", { args: this.args, options: this.options, reachedHWM, blocked }); + } + doRun() { + if (this.retryCount === 0) { + this._assertStatus("QUEUED"); + this._states.next(this.options.id); + } else { + this._assertStatus("EXECUTING"); + } + return this.Events.trigger("scheduled", { args: this.args, options: this.options }); + } + async doExecute(chained, clearGlobalState, run2, free) { + var error49, eventInfo, passed; + if (this.retryCount === 0) { + this._assertStatus("RUNNING"); + this._states.next(this.options.id); + } else { + this._assertStatus("EXECUTING"); + } + eventInfo = { args: this.args, options: this.options, retryCount: this.retryCount }; + this.Events.trigger("executing", eventInfo); + try { + passed = await (chained != null ? chained.schedule(this.options, this.task, ...this.args) : this.task(...this.args)); + if (clearGlobalState()) { + this.doDone(eventInfo); + await free(this.options, eventInfo); + this._assertStatus("DONE"); + return this._resolve(passed); + } + } catch (error1) { + error49 = error1; + return this._onFailure(error49, eventInfo, clearGlobalState, run2, free); + } + } + doExpire(clearGlobalState, run2, free) { + var error49, eventInfo; + if (this._states.jobStatus(this.options.id === "RUNNING")) { + this._states.next(this.options.id); + } + this._assertStatus("EXECUTING"); + eventInfo = { args: this.args, options: this.options, retryCount: this.retryCount }; + error49 = new BottleneckError$1(`This job timed out after ${this.options.expiration} ms.`); + return this._onFailure(error49, eventInfo, clearGlobalState, run2, free); + } + async _onFailure(error49, eventInfo, clearGlobalState, run2, free) { + var retry2, retryAfter; + if (clearGlobalState()) { + retry2 = await this.Events.trigger("failed", error49, eventInfo); + if (retry2 != null) { + retryAfter = ~~retry2; + this.Events.trigger("retry", `Retrying ${this.options.id} after ${retryAfter} ms`, eventInfo); + this.retryCount++; + return run2(retryAfter); + } else { + this.doDone(eventInfo); + await free(this.options, eventInfo); + this._assertStatus("DONE"); + return this._reject(error49); + } + } + } + doDone(eventInfo) { + this._assertStatus("EXECUTING"); + this._states.next(this.options.id); + return this.Events.trigger("done", eventInfo); + } + }; + var Job_1 = Job; + var BottleneckError$2, LocalDatastore, parser$2; + parser$2 = parser; + BottleneckError$2 = BottleneckError_1; + LocalDatastore = class LocalDatastore { + constructor(instance, storeOptions, storeInstanceOptions) { + this.instance = instance; + this.storeOptions = storeOptions; + this.clientId = this.instance._randomIndex(); + parser$2.load(storeInstanceOptions, storeInstanceOptions, this); + this._nextRequest = this._lastReservoirRefresh = this._lastReservoirIncrease = Date.now(); + this._running = 0; + this._done = 0; + this._unblockTime = 0; + this.ready = this.Promise.resolve(); + this.clients = {}; + this._startHeartbeat(); + } + _startHeartbeat() { + var base; + if (this.heartbeat == null && (this.storeOptions.reservoirRefreshInterval != null && this.storeOptions.reservoirRefreshAmount != null || this.storeOptions.reservoirIncreaseInterval != null && this.storeOptions.reservoirIncreaseAmount != null)) { + return typeof (base = this.heartbeat = setInterval(() => { + var amount, incr, maximum, now, reservoir; + now = Date.now(); + if (this.storeOptions.reservoirRefreshInterval != null && now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) { + this._lastReservoirRefresh = now; + this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount; + this.instance._drainAll(this.computeCapacity()); + } + if (this.storeOptions.reservoirIncreaseInterval != null && now >= this._lastReservoirIncrease + this.storeOptions.reservoirIncreaseInterval) { + ({ + reservoirIncreaseAmount: amount, + reservoirIncreaseMaximum: maximum, + reservoir + } = this.storeOptions); + this._lastReservoirIncrease = now; + incr = maximum != null ? Math.min(amount, maximum - reservoir) : amount; + if (incr > 0) { + this.storeOptions.reservoir += incr; + return this.instance._drainAll(this.computeCapacity()); + } + } + }, this.heartbeatInterval)).unref === "function" ? base.unref() : void 0; + } else { + return clearInterval(this.heartbeat); + } + } + async __publish__(message) { + await this.yieldLoop(); + return this.instance.Events.trigger("message", message.toString()); + } + async __disconnect__(flush) { + await this.yieldLoop(); + clearInterval(this.heartbeat); + return this.Promise.resolve(); + } + yieldLoop(t = 0) { + return new this.Promise(function(resolve2, reject) { + return setTimeout(resolve2, t); + }); + } + computePenalty() { + var ref; + return (ref = this.storeOptions.penalty) != null ? ref : 15 * this.storeOptions.minTime || 5e3; + } + async __updateSettings__(options) { + await this.yieldLoop(); + parser$2.overwrite(options, options, this.storeOptions); + this._startHeartbeat(); + this.instance._drainAll(this.computeCapacity()); + return true; + } + async __running__() { + await this.yieldLoop(); + return this._running; + } + async __queued__() { + await this.yieldLoop(); + return this.instance.queued(); + } + async __done__() { + await this.yieldLoop(); + return this._done; + } + async __groupCheck__(time4) { + await this.yieldLoop(); + return this._nextRequest + this.timeout < time4; + } + computeCapacity() { + var maxConcurrent, reservoir; + ({ maxConcurrent, reservoir } = this.storeOptions); + if (maxConcurrent != null && reservoir != null) { + return Math.min(maxConcurrent - this._running, reservoir); + } else if (maxConcurrent != null) { + return maxConcurrent - this._running; + } else if (reservoir != null) { + return reservoir; + } else { + return null; + } + } + conditionsCheck(weight) { + var capacity; + capacity = this.computeCapacity(); + return capacity == null || weight <= capacity; + } + async __incrementReservoir__(incr) { + var reservoir; + await this.yieldLoop(); + reservoir = this.storeOptions.reservoir += incr; + this.instance._drainAll(this.computeCapacity()); + return reservoir; + } + async __currentReservoir__() { + await this.yieldLoop(); + return this.storeOptions.reservoir; + } + isBlocked(now) { + return this._unblockTime >= now; + } + check(weight, now) { + return this.conditionsCheck(weight) && this._nextRequest - now <= 0; + } + async __check__(weight) { + var now; + await this.yieldLoop(); + now = Date.now(); + return this.check(weight, now); + } + async __register__(index, weight, expiration) { + var now, wait; + await this.yieldLoop(); + now = Date.now(); + if (this.conditionsCheck(weight)) { + this._running += weight; + if (this.storeOptions.reservoir != null) { + this.storeOptions.reservoir -= weight; + } + wait = Math.max(this._nextRequest - now, 0); + this._nextRequest = now + wait + this.storeOptions.minTime; + return { + success: true, + wait, + reservoir: this.storeOptions.reservoir + }; + } else { + return { + success: false + }; + } + } + strategyIsBlock() { + return this.storeOptions.strategy === 3; + } + async __submit__(queueLength, weight) { + var blocked, now, reachedHWM; + await this.yieldLoop(); + if (this.storeOptions.maxConcurrent != null && weight > this.storeOptions.maxConcurrent) { + throw new BottleneckError$2(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${this.storeOptions.maxConcurrent}`); + } + now = Date.now(); + reachedHWM = this.storeOptions.highWater != null && queueLength === this.storeOptions.highWater && !this.check(weight, now); + blocked = this.strategyIsBlock() && (reachedHWM || this.isBlocked(now)); + if (blocked) { + this._unblockTime = now + this.computePenalty(); + this._nextRequest = this._unblockTime + this.storeOptions.minTime; + this.instance._dropAllQueued(); + } + return { + reachedHWM, + blocked, + strategy: this.storeOptions.strategy + }; + } + async __free__(index, weight) { + await this.yieldLoop(); + this._running -= weight; + this._done += weight; + this.instance._drainAll(this.computeCapacity()); + return { + running: this._running + }; + } + }; + var LocalDatastore_1 = LocalDatastore; + var BottleneckError$3, States; + BottleneckError$3 = BottleneckError_1; + States = class States { + constructor(status1) { + this.status = status1; + this._jobs = {}; + this.counts = this.status.map(function() { + return 0; + }); + } + next(id) { + var current, next2; + current = this._jobs[id]; + next2 = current + 1; + if (current != null && next2 < this.status.length) { + this.counts[current]--; + this.counts[next2]++; + return this._jobs[id]++; + } else if (current != null) { + this.counts[current]--; + return delete this._jobs[id]; + } + } + start(id) { + var initial; + initial = 0; + this._jobs[id] = initial; + return this.counts[initial]++; + } + remove(id) { + var current; + current = this._jobs[id]; + if (current != null) { + this.counts[current]--; + delete this._jobs[id]; + } + return current != null; + } + jobStatus(id) { + var ref; + return (ref = this.status[this._jobs[id]]) != null ? ref : null; + } + statusJobs(status) { + var k, pos, ref, results, v; + if (status != null) { + pos = this.status.indexOf(status); + if (pos < 0) { + throw new BottleneckError$3(`status must be one of ${this.status.join(", ")}`); + } + ref = this._jobs; + results = []; + for (k in ref) { + v = ref[k]; + if (v === pos) { + results.push(k); + } + } + return results; + } else { + return Object.keys(this._jobs); + } + } + statusCounts() { + return this.counts.reduce(((acc, v, i) => { + acc[this.status[i]] = v; + return acc; + }), {}); + } + }; + var States_1 = States; + var DLList$2, Sync; + DLList$2 = DLList_1; + Sync = class Sync { + constructor(name, Promise2) { + this.schedule = this.schedule.bind(this); + this.name = name; + this.Promise = Promise2; + this._running = 0; + this._queue = new DLList$2(); + } + isEmpty() { + return this._queue.length === 0; + } + async _tryToRun() { + var args2, cb, error49, reject, resolve2, returned, task; + if (this._running < 1 && this._queue.length > 0) { + this._running++; + ({ task, args: args2, resolve: resolve2, reject } = this._queue.shift()); + cb = await (async function() { + try { + returned = await task(...args2); + return function() { + return resolve2(returned); + }; + } catch (error1) { + error49 = error1; + return function() { + return reject(error49); + }; + } + })(); + this._running--; + this._tryToRun(); + return cb(); + } + } + schedule(task, ...args2) { + var promise2, reject, resolve2; + resolve2 = reject = null; + promise2 = new this.Promise(function(_resolve, _reject) { + resolve2 = _resolve; + return reject = _reject; + }); + this._queue.push({ task, args: args2, resolve: resolve2, reject }); + this._tryToRun(); + return promise2; + } + }; + var Sync_1 = Sync; + var version3 = "2.19.5"; + var version$1 = { + version: version3 + }; + var version$2 = /* @__PURE__ */ Object.freeze({ + version: version3, + default: version$1 + }); + var require$$2 = () => console.log("You must import the full version of Bottleneck in order to use this feature."); + var require$$3 = () => console.log("You must import the full version of Bottleneck in order to use this feature."); + var require$$4 = () => console.log("You must import the full version of Bottleneck in order to use this feature."); + var Events$2, Group, IORedisConnection$1, RedisConnection$1, Scripts$1, parser$3; + parser$3 = parser; + Events$2 = Events_1; + RedisConnection$1 = require$$2; + IORedisConnection$1 = require$$3; + Scripts$1 = require$$4; + Group = (function() { + class Group2 { + constructor(limiterOptions = {}) { + this.deleteKey = this.deleteKey.bind(this); + this.limiterOptions = limiterOptions; + parser$3.load(this.limiterOptions, this.defaults, this); + this.Events = new Events$2(this); + this.instances = {}; + this.Bottleneck = Bottleneck_1; + this._startAutoCleanup(); + this.sharedConnection = this.connection != null; + if (this.connection == null) { + if (this.limiterOptions.datastore === "redis") { + this.connection = new RedisConnection$1(Object.assign({}, this.limiterOptions, { Events: this.Events })); + } else if (this.limiterOptions.datastore === "ioredis") { + this.connection = new IORedisConnection$1(Object.assign({}, this.limiterOptions, { Events: this.Events })); + } + } + } + key(key = "") { + var ref; + return (ref = this.instances[key]) != null ? ref : (() => { + var limiter; + limiter = this.instances[key] = new this.Bottleneck(Object.assign(this.limiterOptions, { + id: `${this.id}-${key}`, + timeout: this.timeout, + connection: this.connection + })); + this.Events.trigger("created", limiter, key); + return limiter; + })(); + } + async deleteKey(key = "") { + var deleted, instance; + instance = this.instances[key]; + if (this.connection) { + deleted = await this.connection.__runCommand__(["del", ...Scripts$1.allKeys(`${this.id}-${key}`)]); + } + if (instance != null) { + delete this.instances[key]; + await instance.disconnect(); + } + return instance != null || deleted > 0; + } + limiters() { + var k, ref, results, v; + ref = this.instances; + results = []; + for (k in ref) { + v = ref[k]; + results.push({ + key: k, + limiter: v + }); + } + return results; + } + keys() { + return Object.keys(this.instances); + } + async clusterKeys() { + var cursor, end, found, i, k, keys, len, next2, start; + if (this.connection == null) { + return this.Promise.resolve(this.keys()); + } + keys = []; + cursor = null; + start = `b_${this.id}-`.length; + end = "_settings".length; + while (cursor !== 0) { + [next2, found] = await this.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", `b_${this.id}-*_settings`, "count", 1e4]); + cursor = ~~next2; + for (i = 0, len = found.length; i < len; i++) { + k = found[i]; + keys.push(k.slice(start, -end)); + } + } + return keys; + } + _startAutoCleanup() { + var base; + clearInterval(this.interval); + return typeof (base = this.interval = setInterval(async () => { + var e, k, ref, results, time4, v; + time4 = Date.now(); + ref = this.instances; + results = []; + for (k in ref) { + v = ref[k]; + try { + if (await v._store.__groupCheck__(time4)) { + results.push(this.deleteKey(k)); + } else { + results.push(void 0); + } + } catch (error49) { + e = error49; + results.push(v.Events.trigger("error", e)); + } + } + return results; + }, this.timeout / 2)).unref === "function" ? base.unref() : void 0; + } + updateSettings(options = {}) { + parser$3.overwrite(options, this.defaults, this); + parser$3.overwrite(options, options, this.limiterOptions); + if (options.timeout != null) { + return this._startAutoCleanup(); + } + } + disconnect(flush = true) { + var ref; + if (!this.sharedConnection) { + return (ref = this.connection) != null ? ref.disconnect(flush) : void 0; + } + } + } + Group2.prototype.defaults = { + timeout: 1e3 * 60 * 5, + connection: null, + Promise, + id: "group-key" + }; + return Group2; + }).call(commonjsGlobal); + var Group_1 = Group; + var Batcher, Events$3, parser$4; + parser$4 = parser; + Events$3 = Events_1; + Batcher = (function() { + class Batcher2 { + constructor(options = {}) { + this.options = options; + parser$4.load(this.options, this.defaults, this); + this.Events = new Events$3(this); + this._arr = []; + this._resetPromise(); + this._lastFlush = Date.now(); + } + _resetPromise() { + return this._promise = new this.Promise((res, rej) => { + return this._resolve = res; + }); + } + _flush() { + clearTimeout(this._timeout); + this._lastFlush = Date.now(); + this._resolve(); + this.Events.trigger("batch", this._arr); + this._arr = []; + return this._resetPromise(); + } + add(data) { + var ret; + this._arr.push(data); + ret = this._promise; + if (this._arr.length === this.maxSize) { + this._flush(); + } else if (this.maxTime != null && this._arr.length === 1) { + this._timeout = setTimeout(() => { + return this._flush(); + }, this.maxTime); + } + return ret; + } + } + Batcher2.prototype.defaults = { + maxTime: null, + maxSize: null, + Promise + }; + return Batcher2; + }).call(commonjsGlobal); + var Batcher_1 = Batcher; + var require$$4$1 = () => console.log("You must import the full version of Bottleneck in order to use this feature."); + var require$$8 = getCjsExportFromNamespace(version$2); + var Bottleneck, DEFAULT_PRIORITY$1, Events$4, Job$1, LocalDatastore$1, NUM_PRIORITIES$1, Queues$1, RedisDatastore$1, States$1, Sync$1, parser$5, splice = [].splice; + NUM_PRIORITIES$1 = 10; + DEFAULT_PRIORITY$1 = 5; + parser$5 = parser; + Queues$1 = Queues_1; + Job$1 = Job_1; + LocalDatastore$1 = LocalDatastore_1; + RedisDatastore$1 = require$$4$1; + Events$4 = Events_1; + States$1 = States_1; + Sync$1 = Sync_1; + Bottleneck = (function() { + class Bottleneck2 { + constructor(options = {}, ...invalid) { + var storeInstanceOptions, storeOptions; + this._addToQueue = this._addToQueue.bind(this); + this._validateOptions(options, invalid); + parser$5.load(options, this.instanceDefaults, this); + this._queues = new Queues$1(NUM_PRIORITIES$1); + this._scheduled = {}; + this._states = new States$1(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : [])); + this._limiter = null; + this.Events = new Events$4(this); + this._submitLock = new Sync$1("submit", this.Promise); + this._registerLock = new Sync$1("register", this.Promise); + storeOptions = parser$5.load(options, this.storeDefaults, {}); + this._store = (function() { + if (this.datastore === "redis" || this.datastore === "ioredis" || this.connection != null) { + storeInstanceOptions = parser$5.load(options, this.redisStoreDefaults, {}); + return new RedisDatastore$1(this, storeOptions, storeInstanceOptions); + } else if (this.datastore === "local") { + storeInstanceOptions = parser$5.load(options, this.localStoreDefaults, {}); + return new LocalDatastore$1(this, storeOptions, storeInstanceOptions); + } else { + throw new Bottleneck2.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`); + } + }).call(this); + this._queues.on("leftzero", () => { + var ref; + return (ref = this._store.heartbeat) != null ? typeof ref.ref === "function" ? ref.ref() : void 0 : void 0; + }); + this._queues.on("zero", () => { + var ref; + return (ref = this._store.heartbeat) != null ? typeof ref.unref === "function" ? ref.unref() : void 0 : void 0; + }); + } + _validateOptions(options, invalid) { + if (!(options != null && typeof options === "object" && invalid.length === 0)) { + throw new Bottleneck2.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1."); + } + } + ready() { + return this._store.ready; + } + clients() { + return this._store.clients; + } + channel() { + return `b_${this.id}`; + } + channel_client() { + return `b_${this.id}_${this._store.clientId}`; + } + publish(message) { + return this._store.__publish__(message); + } + disconnect(flush = true) { + return this._store.__disconnect__(flush); + } + chain(_limiter) { + this._limiter = _limiter; + return this; + } + queued(priority) { + return this._queues.queued(priority); + } + clusterQueued() { + return this._store.__queued__(); + } + empty() { + return this.queued() === 0 && this._submitLock.isEmpty(); + } + running() { + return this._store.__running__(); + } + done() { + return this._store.__done__(); + } + jobStatus(id) { + return this._states.jobStatus(id); + } + jobs(status) { + return this._states.statusJobs(status); + } + counts() { + return this._states.statusCounts(); + } + _randomIndex() { + return Math.random().toString(36).slice(2); + } + check(weight = 1) { + return this._store.__check__(weight); + } + _clearGlobalState(index) { + if (this._scheduled[index] != null) { + clearTimeout(this._scheduled[index].expiration); + delete this._scheduled[index]; + return true; + } else { + return false; + } + } + async _free(index, job, options, eventInfo) { + var e, running; + try { + ({ running } = await this._store.__free__(index, options.weight)); + this.Events.trigger("debug", `Freed ${options.id}`, eventInfo); + if (running === 0 && this.empty()) { + return this.Events.trigger("idle"); + } + } catch (error1) { + e = error1; + return this.Events.trigger("error", e); + } + } + _run(index, job, wait) { + var clearGlobalState, free, run2; + job.doRun(); + clearGlobalState = this._clearGlobalState.bind(this, index); + run2 = this._run.bind(this, index, job); + free = this._free.bind(this, index, job); + return this._scheduled[index] = { + timeout: setTimeout(() => { + return job.doExecute(this._limiter, clearGlobalState, run2, free); + }, wait), + expiration: job.options.expiration != null ? setTimeout(function() { + return job.doExpire(clearGlobalState, run2, free); + }, wait + job.options.expiration) : void 0, + job + }; + } + _drainOne(capacity) { + return this._registerLock.schedule(() => { + var args2, index, next2, options, queue; + if (this.queued() === 0) { + return this.Promise.resolve(null); + } + queue = this._queues.getFirst(); + ({ options, args: args2 } = next2 = queue.first()); + if (capacity != null && options.weight > capacity) { + return this.Promise.resolve(null); + } + this.Events.trigger("debug", `Draining ${options.id}`, { args: args2, options }); + index = this._randomIndex(); + return this._store.__register__(index, options.weight, options.expiration).then(({ success: success2, wait, reservoir }) => { + var empty; + this.Events.trigger("debug", `Drained ${options.id}`, { success: success2, args: args2, options }); + if (success2) { + queue.shift(); + empty = this.empty(); + if (empty) { + this.Events.trigger("empty"); + } + if (reservoir === 0) { + this.Events.trigger("depleted", empty); + } + this._run(index, next2, wait); + return this.Promise.resolve(options.weight); + } else { + return this.Promise.resolve(null); + } + }); + }); + } + _drainAll(capacity, total = 0) { + return this._drainOne(capacity).then((drained) => { + var newCapacity; + if (drained != null) { + newCapacity = capacity != null ? capacity - drained : capacity; + return this._drainAll(newCapacity, total + drained); + } else { + return this.Promise.resolve(total); + } + }).catch((e) => { + return this.Events.trigger("error", e); + }); + } + _dropAllQueued(message) { + return this._queues.shiftAll(function(job) { + return job.doDrop({ message }); + }); + } + stop(options = {}) { + var done, waitForExecuting; + options = parser$5.load(options, this.stopDefaults); + waitForExecuting = (at) => { + var finished; + finished = () => { + var counts; + counts = this._states.counts; + return counts[0] + counts[1] + counts[2] + counts[3] === at; + }; + return new this.Promise((resolve2, reject) => { + if (finished()) { + return resolve2(); + } else { + return this.on("done", () => { + if (finished()) { + this.removeAllListeners("done"); + return resolve2(); + } + }); + } + }); + }; + done = options.dropWaitingJobs ? (this._run = function(index, next2) { + return next2.doDrop({ + message: options.dropErrorMessage + }); + }, this._drainOne = () => { + return this.Promise.resolve(null); + }, this._registerLock.schedule(() => { + return this._submitLock.schedule(() => { + var k, ref, v; + ref = this._scheduled; + for (k in ref) { + v = ref[k]; + if (this.jobStatus(v.job.options.id) === "RUNNING") { + clearTimeout(v.timeout); + clearTimeout(v.expiration); + v.job.doDrop({ + message: options.dropErrorMessage + }); + } + } + this._dropAllQueued(options.dropErrorMessage); + return waitForExecuting(0); + }); + })) : this.schedule({ + priority: NUM_PRIORITIES$1 - 1, + weight: 0 + }, () => { + return waitForExecuting(1); + }); + this._receive = function(job) { + return job._reject(new Bottleneck2.prototype.BottleneckError(options.enqueueErrorMessage)); + }; + this.stop = () => { + return this.Promise.reject(new Bottleneck2.prototype.BottleneckError("stop() has already been called")); + }; + return done; + } + async _addToQueue(job) { + var args2, blocked, error49, options, reachedHWM, shifted, strategy; + ({ args: args2, options } = job); + try { + ({ reachedHWM, blocked, strategy } = await this._store.__submit__(this.queued(), options.weight)); + } catch (error1) { + error49 = error1; + this.Events.trigger("debug", `Could not queue ${options.id}`, { args: args2, options, error: error49 }); + job.doDrop({ error: error49 }); + return false; + } + if (blocked) { + job.doDrop(); + return true; + } else if (reachedHWM) { + shifted = strategy === Bottleneck2.prototype.strategy.LEAK ? this._queues.shiftLastFrom(options.priority) : strategy === Bottleneck2.prototype.strategy.OVERFLOW_PRIORITY ? this._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck2.prototype.strategy.OVERFLOW ? job : void 0; + if (shifted != null) { + shifted.doDrop(); + } + if (shifted == null || strategy === Bottleneck2.prototype.strategy.OVERFLOW) { + if (shifted == null) { + job.doDrop(); + } + return reachedHWM; + } + } + job.doQueue(reachedHWM, blocked); + this._queues.push(job); + await this._drainAll(); + return reachedHWM; + } + _receive(job) { + if (this._states.jobStatus(job.options.id) != null) { + job._reject(new Bottleneck2.prototype.BottleneckError(`A job with the same id already exists (id=${job.options.id})`)); + return false; + } else { + job.doReceive(); + return this._submitLock.schedule(this._addToQueue, job); + } + } + submit(...args2) { + var cb, fn2, job, options, ref, ref1, task; + if (typeof args2[0] === "function") { + ref = args2, [fn2, ...args2] = ref, [cb] = splice.call(args2, -1); + options = parser$5.load({}, this.jobDefaults); + } else { + ref1 = args2, [options, fn2, ...args2] = ref1, [cb] = splice.call(args2, -1); + options = parser$5.load(options, this.jobDefaults); + } + task = (...args3) => { + return new this.Promise(function(resolve2, reject) { + return fn2(...args3, function(...args4) { + return (args4[0] != null ? reject : resolve2)(args4); + }); + }); + }; + job = new Job$1(task, args2, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); + job.promise.then(function(args3) { + return typeof cb === "function" ? cb(...args3) : void 0; + }).catch(function(args3) { + if (Array.isArray(args3)) { + return typeof cb === "function" ? cb(...args3) : void 0; + } else { + return typeof cb === "function" ? cb(args3) : void 0; + } + }); + return this._receive(job); + } + schedule(...args2) { + var job, options, task; + if (typeof args2[0] === "function") { + [task, ...args2] = args2; + options = {}; + } else { + [options, task, ...args2] = args2; + } + job = new Job$1(task, args2, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); + this._receive(job); + return job.promise; + } + wrap(fn2) { + var schedule, wrapped; + schedule = this.schedule.bind(this); + wrapped = function(...args2) { + return schedule(fn2.bind(this), ...args2); + }; + wrapped.withOptions = function(options, ...args2) { + return schedule(options, fn2, ...args2); + }; + return wrapped; + } + async updateSettings(options = {}) { + await this._store.__updateSettings__(parser$5.overwrite(options, this.storeDefaults)); + parser$5.overwrite(options, this.instanceDefaults, this); + return this; + } + currentReservoir() { + return this._store.__currentReservoir__(); + } + incrementReservoir(incr = 0) { + return this._store.__incrementReservoir__(incr); + } + } + Bottleneck2.default = Bottleneck2; + Bottleneck2.Events = Events$4; + Bottleneck2.version = Bottleneck2.prototype.version = require$$8.version; + Bottleneck2.strategy = Bottleneck2.prototype.strategy = { + LEAK: 1, + OVERFLOW: 2, + OVERFLOW_PRIORITY: 4, + BLOCK: 3 + }; + Bottleneck2.BottleneckError = Bottleneck2.prototype.BottleneckError = BottleneckError_1; + Bottleneck2.Group = Bottleneck2.prototype.Group = Group_1; + Bottleneck2.RedisConnection = Bottleneck2.prototype.RedisConnection = require$$2; + Bottleneck2.IORedisConnection = Bottleneck2.prototype.IORedisConnection = require$$3; + Bottleneck2.Batcher = Bottleneck2.prototype.Batcher = Batcher_1; + Bottleneck2.prototype.jobDefaults = { + priority: DEFAULT_PRIORITY$1, + weight: 1, + expiration: null, + id: "" + }; + Bottleneck2.prototype.storeDefaults = { + maxConcurrent: null, + minTime: 0, + highWater: null, + strategy: Bottleneck2.prototype.strategy.LEAK, + penalty: null, + reservoir: null, + reservoirRefreshInterval: null, + reservoirRefreshAmount: null, + reservoirIncreaseInterval: null, + reservoirIncreaseAmount: null, + reservoirIncreaseMaximum: null + }; + Bottleneck2.prototype.localStoreDefaults = { + Promise, + timeout: null, + heartbeatInterval: 250 + }; + Bottleneck2.prototype.redisStoreDefaults = { + Promise, + timeout: null, + heartbeatInterval: 5e3, + clientTimeout: 1e4, + Redis: null, + clientOptions: {}, + clusterNodes: null, + clearDatastore: false, + connection: null + }; + Bottleneck2.prototype.instanceDefaults = { + datastore: "local", + connection: null, + id: "", + rejectOnDrop: true, + trackDoneStatus: false, + Promise + }; + Bottleneck2.prototype.stopDefaults = { + enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.", + dropWaitingJobs: true, + dropErrorMessage: "This limiter has been stopped." + }; + return Bottleneck2; + }).call(commonjsGlobal); + var Bottleneck_1 = Bottleneck; + var lib = Bottleneck_1; + return lib; + })); + } +}); + +// node_modules/.pnpm/fast-content-type-parse@3.0.0/node_modules/fast-content-type-parse/index.js +var require_fast_content_type_parse = __commonJS({ + "node_modules/.pnpm/fast-content-type-parse@3.0.0/node_modules/fast-content-type-parse/index.js"(exports, module) { + "use strict"; + var NullObject = function NullObject2() { + }; + NullObject.prototype = /* @__PURE__ */ Object.create(null); + var paramRE = /; *([!#$%&'*+.^\w`|~-]+)=("(?:[\v\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\v\u0020-\u00ff])*"|[!#$%&'*+.^\w`|~-]+) */gu; + var quotedPairRE = /\\([\v\u0020-\u00ff])/gu; + var mediaTypeRE = /^[!#$%&'*+.^\w|~-]+\/[!#$%&'*+.^\w|~-]+$/u; + var defaultContentType = { type: "", parameters: new NullObject() }; + Object.freeze(defaultContentType.parameters); + Object.freeze(defaultContentType); + function parse5(header) { + if (typeof header !== "string") { + throw new TypeError("argument header is required and must be a string"); + } + let index = header.indexOf(";"); + const type2 = index !== -1 ? header.slice(0, index).trim() : header.trim(); + if (mediaTypeRE.test(type2) === false) { + throw new TypeError("invalid media type"); + } + const result = { + type: type2.toLowerCase(), + parameters: new NullObject() + }; + if (index === -1) { + return result; + } + let key; + let match3; + let value2; + paramRE.lastIndex = index; + while (match3 = paramRE.exec(header)) { + if (match3.index !== index) { + throw new TypeError("invalid parameter format"); + } + index += match3[0].length; + key = match3[1].toLowerCase(); + value2 = match3[2]; + if (value2[0] === '"') { + value2 = value2.slice(1, value2.length - 1); + quotedPairRE.test(value2) && (value2 = value2.replace(quotedPairRE, "$1")); + } + result.parameters[key] = value2; + } + if (index !== header.length) { + throw new TypeError("invalid parameter format"); + } + return result; + } + function safeParse5(header) { + if (typeof header !== "string") { + return defaultContentType; + } + let index = header.indexOf(";"); + const type2 = index !== -1 ? header.slice(0, index).trim() : header.trim(); + if (mediaTypeRE.test(type2) === false) { + return defaultContentType; + } + const result = { + type: type2.toLowerCase(), + parameters: new NullObject() + }; + if (index === -1) { + return result; + } + let key; + let match3; + let value2; + paramRE.lastIndex = index; + while (match3 = paramRE.exec(header)) { + if (match3.index !== index) { + return defaultContentType; + } + index += match3[0].length; + key = match3[1].toLowerCase(); + value2 = match3[2]; + if (value2[0] === '"') { + value2 = value2.slice(1, value2.length - 1); + quotedPairRE.test(value2) && (value2 = value2.replace(quotedPairRE, "$1")); + } + result.parameters[key] = value2; + } + if (index !== header.length) { + return defaultContentType; + } + return result; + } + module.exports.default = { parse: parse5, safeParse: safeParse5 }; + module.exports.parse = parse5; + module.exports.safeParse = safeParse5; + module.exports.defaultContentType = defaultContentType; + } +}); + // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v3/helpers/util.js var util, objectUtil, ZodParsedType, getParsedType; var init_util = __esm({ @@ -23925,18 +31024,18 @@ __export(util_exports, { getParsedType: () => getParsedType2, getSizableOrigin: () => getSizableOrigin, hexToUint8Array: () => hexToUint8Array, - isObject: () => isObject, - isPlainObject: () => isPlainObject, + isObject: () => isObject2, + isPlainObject: () => isPlainObject4, issue: () => issue, joinValues: () => joinValues, jsonStringifyReplacer: () => jsonStringifyReplacer, - merge: () => merge, + merge: () => merge2, mergeDefs: () => mergeDefs, normalizeParams: () => normalizeParams, nullish: () => nullish, numKeys: () => numKeys, objectClone: () => objectClone, - omit: () => omit2, + omit: () => omit3, optionalKeys: () => optionalKeys, parsedType: () => parsedType, partial: () => partial, @@ -24092,11 +31191,11 @@ function esc(str) { function slugify(input) { return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); } -function isObject(data) { +function isObject2(data) { return typeof data === "object" && data !== null && !Array.isArray(data); } -function isPlainObject(o) { - if (isObject(o) === false) +function isPlainObject4(o) { + if (isObject2(o) === false) return false; const ctor = o.constructor; if (ctor === void 0) @@ -24104,7 +31203,7 @@ function isPlainObject(o) { if (typeof ctor !== "function") return true; const prot = ctor.prototype; - if (isObject(prot) === false) + if (isObject2(prot) === false) return false; if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { return false; @@ -24112,7 +31211,7 @@ function isPlainObject(o) { return true; } function shallowClone(o) { - if (isPlainObject(o)) + if (isPlainObject4(o)) return { ...o }; if (Array.isArray(o)) return [...o]; @@ -24222,7 +31321,7 @@ function pick(schema2, mask) { }); return clone(schema2, def); } -function omit2(schema2, mask) { +function omit3(schema2, mask) { const currDef = schema2._zod.def; const checks = currDef.checks; const hasChecks = checks && checks.length > 0; @@ -24248,7 +31347,7 @@ function omit2(schema2, mask) { return clone(schema2, def); } function extend(schema2, shape) { - if (!isPlainObject(shape)) { + if (!isPlainObject4(shape)) { throw new Error("Invalid input to extend: expected a plain object"); } const checks = schema2._zod.def.checks; @@ -24271,7 +31370,7 @@ function extend(schema2, shape) { return clone(schema2, def); } function safeExtend(schema2, shape) { - if (!isPlainObject(shape)) { + if (!isPlainObject4(shape)) { throw new Error("Invalid input to safeExtend: expected a plain object"); } const def = mergeDefs(schema2._zod.def, { @@ -24283,7 +31382,7 @@ function safeExtend(schema2, shape) { }); return clone(schema2, def); } -function merge(a, b) { +function merge2(a, b) { const def = mergeDefs(a._zod.def, { get shape() { const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; @@ -24718,7 +31817,7 @@ var init_errors2 = __esm({ }); // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/parse.js -var _parse, parse, _parseAsync, parseAsync, _safeParse, safeParse, _safeParseAsync, safeParseAsync, _encode, encode, _decode, decode, _encodeAsync, encodeAsync, _decodeAsync, decodeAsync, _safeEncode, safeEncode, _safeDecode, safeDecode, _safeEncodeAsync, safeEncodeAsync, _safeDecodeAsync, safeDecodeAsync; +var _parse, parse2, _parseAsync, parseAsync, _safeParse, safeParse2, _safeParseAsync, safeParseAsync, _encode, encode2, _decode, decode, _encodeAsync, encodeAsync, _decodeAsync, decodeAsync, _safeEncode, safeEncode, _safeDecode, safeDecode, _safeEncodeAsync, safeEncodeAsync, _safeDecodeAsync, safeDecodeAsync; var init_parse = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/parse.js"() { init_core(); @@ -24737,7 +31836,7 @@ var init_parse = __esm({ } return result.value; }; - parse = /* @__PURE__ */ _parse($ZodRealError); + parse2 = /* @__PURE__ */ _parse($ZodRealError); _parseAsync = (_Err) => async (schema2, value2, _ctx, params) => { const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; let result = schema2._zod.run({ value: value2, issues: [] }, ctx); @@ -24762,7 +31861,7 @@ var init_parse = __esm({ error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) } : { success: true, data: result.value }; }; - safeParse = /* @__PURE__ */ _safeParse($ZodRealError); + safeParse2 = /* @__PURE__ */ _safeParse($ZodRealError); _safeParseAsync = (_Err) => async (schema2, value2, _ctx) => { const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; let result = schema2._zod.run({ value: value2, issues: [] }, ctx); @@ -24778,7 +31877,7 @@ var init_parse = __esm({ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; return _parse(_Err)(schema2, value2, ctx); }; - encode = /* @__PURE__ */ _encode($ZodRealError); + encode2 = /* @__PURE__ */ _encode($ZodRealError); _decode = (_Err) => (schema2, value2, _ctx) => { return _parse(_Err)(schema2, value2, _ctx); }; @@ -24816,7 +31915,7 @@ var init_parse = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/regexes.js var regexes_exports = {}; __export(regexes_exports, { - base64: () => base64, + base64: () => base642, base64url: () => base64url, bigint: () => bigint, boolean: () => boolean, @@ -24830,15 +31929,15 @@ __export(regexes_exports, { domain: () => domain, duration: () => duration, e164: () => e164, - email: () => email, + email: () => email2, emoji: () => emoji, extendedDuration: () => extendedDuration, guid: () => guid, - hex: () => hex, + hex: () => hex2, hostname: () => hostname, html5Email: () => html5Email, idnEmail: () => idnEmail, - integer: () => integer, + integer: () => integer2, ipv4: () => ipv4, ipv6: () => ipv6, ksuid: () => ksuid, @@ -24849,7 +31948,7 @@ __export(regexes_exports, { md5_hex: () => md5_hex, nanoid: () => nanoid, null: () => _null, - number: () => number, + number: () => number2, rfc5322Email: () => rfc5322Email, sha1_base64: () => sha1_base64, sha1_base64url: () => sha1_base64url, @@ -24863,13 +31962,13 @@ __export(regexes_exports, { sha512_base64: () => sha512_base64, sha512_base64url: () => sha512_base64url, sha512_hex: () => sha512_hex, - string: () => string, + string: () => string2, time: () => time, ulid: () => ulid, undefined: () => _undefined, unicodeEmail: () => unicodeEmail, uppercase: () => uppercase, - uuid: () => uuid, + uuid: () => uuid2, uuid4: () => uuid4, uuid6: () => uuid6, uuid7: () => uuid7, @@ -24902,7 +32001,7 @@ function fixedBase64(bodyLength, padding) { function fixedBase64url(length) { return new RegExp(`^[A-Za-z0-9_-]{${length}}$`); } -var cuid, cuid2, ulid, xid, ksuid, nanoid, duration, extendedDuration, guid, uuid, uuid4, uuid6, uuid7, email, html5Email, rfc5322Email, unicodeEmail, idnEmail, browserEmail, _emoji, ipv4, ipv6, mac, cidrv4, cidrv6, base64, base64url, hostname, domain, e164, dateSource, date, string, bigint, integer, number, boolean, _null, _undefined, lowercase, uppercase, hex, md5_hex, md5_base64, md5_base64url, sha1_hex, sha1_base64, sha1_base64url, sha256_hex, sha256_base64, sha256_base64url, sha384_hex, sha384_base64, sha384_base64url, sha512_hex, sha512_base64, sha512_base64url; +var cuid, cuid2, ulid, xid, ksuid, nanoid, duration, extendedDuration, guid, uuid2, uuid4, uuid6, uuid7, email2, html5Email, rfc5322Email, unicodeEmail, idnEmail, browserEmail, _emoji, ipv4, ipv6, mac, cidrv4, cidrv6, base642, base64url, hostname, domain, e164, dateSource, date, string2, bigint, integer2, number2, boolean, _null, _undefined, lowercase, uppercase, hex2, md5_hex, md5_base64, md5_base64url, sha1_hex, sha1_base64, sha1_base64url, sha256_hex, sha256_base64, sha256_base64url, sha384_hex, sha384_base64, sha384_base64url, sha512_hex, sha512_base64, sha512_base64url; var init_regexes = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/core/regexes.js"() { init_util2(); @@ -24915,15 +32014,15 @@ var init_regexes = __esm({ duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; - uuid = (version3) => { + uuid2 = (version3) => { if (!version3) return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/; return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version3}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); }; - uuid4 = /* @__PURE__ */ uuid(4); - uuid6 = /* @__PURE__ */ uuid(6); - uuid7 = /* @__PURE__ */ uuid(7); - email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; + uuid4 = /* @__PURE__ */ uuid2(4); + uuid6 = /* @__PURE__ */ uuid2(6); + uuid7 = /* @__PURE__ */ uuid2(7); + email2 = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; @@ -24938,26 +32037,26 @@ var init_regexes = __esm({ }; cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; - base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; + base642 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; base64url = /^[A-Za-z0-9_-]*$/; hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; e164 = /^\+[1-9]\d{6,14}$/; dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`; date = /* @__PURE__ */ new RegExp(`^${dateSource}$`); - string = (params) => { + string2 = (params) => { const regex4 = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; return new RegExp(`^${regex4}$`); }; bigint = /^-?\d+n?$/; - integer = /^-?\d+$/; - number = /^-?\d+(?:\.\d+)?$/; + integer2 = /^-?\d+$/; + number2 = /^-?\d+(?:\.\d+)?$/; boolean = /^(?:true|false)$/i; _null = /^null$/i; _undefined = /^undefined$/i; lowercase = /^[^A-Z]*$/; uppercase = /^[^a-z]*$/; - hex = /^[0-9a-fA-F]*$/; + hex2 = /^[0-9a-fA-F]*$/; md5_hex = /^[0-9a-fA-F]{32}$/; md5_base64 = /* @__PURE__ */ fixedBase64(22, "=="); md5_base64url = /* @__PURE__ */ fixedBase64url(22); @@ -25089,7 +32188,7 @@ var init_checks = __esm({ bag.minimum = minimum; bag.maximum = maximum; if (isInt) - bag.pattern = integer; + bag.pattern = integer2; }); inst._zod.check = (payload) => { const input = payload.value; @@ -25747,7 +32846,7 @@ function mergeValues2(a, b) { if (a instanceof Date && b instanceof Date && +a === +b) { return { valid: true, data: a }; } - if (isPlainObject(a) && isPlainObject(b)) { + if (isPlainObject4(a) && isPlainObject4(b)) { const bKeys = Object.keys(b); const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a, ...b }; @@ -26053,7 +33152,7 @@ var init_schemas = __esm({ defineLazy(inst, "~standard", () => ({ validate: (value2) => { try { - const r = safeParse(inst, value2); + const r = safeParse2(inst, value2); return r.success ? { value: r.data } : { issues: r.error?.issues }; } catch (_) { return safeParseAsync(inst, value2).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues }); @@ -26065,7 +33164,7 @@ var init_schemas = __esm({ }); $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => { $ZodType.init(inst, def); - inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag); + inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string2(inst._zod.bag); inst._zod.parse = (payload, _) => { if (def.coerce) try { @@ -26106,13 +33205,13 @@ var init_schemas = __esm({ const v = versionMap[def.version]; if (v === void 0) throw new Error(`Invalid UUID version: "${def.version}"`); - def.pattern ?? (def.pattern = uuid(v)); + def.pattern ?? (def.pattern = uuid2(v)); } else - def.pattern ?? (def.pattern = uuid()); + def.pattern ?? (def.pattern = uuid2()); $ZodStringFormat.init(inst, def); }); $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => { - def.pattern ?? (def.pattern = email); + def.pattern ?? (def.pattern = email2); $ZodStringFormat.init(inst, def); }); $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => { @@ -26271,7 +33370,7 @@ var init_schemas = __esm({ }; }); $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { - def.pattern ?? (def.pattern = base64); + def.pattern ?? (def.pattern = base642); $ZodStringFormat.init(inst, def); inst._zod.bag.contentEncoding = "base64"; inst._zod.check = (payload) => { @@ -26336,7 +33435,7 @@ var init_schemas = __esm({ }); $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { $ZodType.init(inst, def); - inst._zod.pattern = inst._zod.bag.pattern ?? number; + inst._zod.pattern = inst._zod.bag.pattern ?? number2; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { @@ -26579,7 +33678,7 @@ var init_schemas = __esm({ } return propValues; }); - const isObject5 = isObject; + const isObject5 = isObject2; const catchall = def.catchall; let value2; inst._zod.parse = (payload, ctx) => { @@ -26683,7 +33782,7 @@ var init_schemas = __esm({ return (payload, ctx) => fn2(shape, payload, ctx); }; let fastpass; - const isObject5 = isObject; + const isObject5 = isObject2; const jit = !globalConfig.jitless; const allowsEval3 = allowsEval; const fastEnabled = jit && allowsEval3.value; @@ -26826,7 +33925,7 @@ var init_schemas = __esm({ }); inst._zod.parse = (payload, ctx) => { const input = payload.value; - if (!isObject(input)) { + if (!isObject2(input)) { payload.issues.push({ code: "invalid_type", expected: "object", @@ -26941,7 +34040,7 @@ var init_schemas = __esm({ $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { const input = payload.value; - if (!isPlainObject(input)) { + if (!isPlainObject4(input)) { payload.issues.push({ expected: "record", code: "invalid_type", @@ -26998,7 +34097,7 @@ var init_schemas = __esm({ if (keyResult instanceof Promise) { throw new Error("Async schemas not supported in object keys currently"); } - const checkNumericKey = typeof key === "string" && number.test(key) && keyResult.issues.length; + const checkNumericKey = typeof key === "string" && number2.test(key) && keyResult.issues.length; if (checkNumericKey) { const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx); if (retryResult instanceof Promise) { @@ -27464,10 +34563,10 @@ var init_schemas = __esm({ throw new Error("implement() must be called with a function"); } return function(...args2) { - const parsedArgs = inst._def.input ? parse(inst._def.input, args2) : args2; + const parsedArgs = inst._def.input ? parse2(inst._def.input, args2) : args2; const result = Reflect.apply(func, this, parsedArgs); if (inst._def.output) { - return parse(inst._def.output, result); + return parse2(inst._def.output, result); } return result; }; @@ -27572,14 +34671,14 @@ var init_schemas = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ar.js function ar_default() { return { - localeError: error() + localeError: error2() }; } -var error; +var error2; var init_ar = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ar.js"() { init_util2(); - error = () => { + error2 = () => { const Sizable = { string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, @@ -27685,14 +34784,14 @@ var init_ar = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/az.js function az_default() { return { - localeError: error2() + localeError: error3() }; } -var error2; +var error3; var init_az = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/az.js"() { init_util2(); - error2 = () => { + error3 = () => { const Sizable = { string: { unit: "simvol", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, @@ -27812,14 +34911,14 @@ function getBelarusianPlural(count, one, few, many) { } function be_default() { return { - localeError: error3() + localeError: error4() }; } -var error3; +var error4; var init_be = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/be.js"() { init_util2(); - error3 = () => { + error4 = () => { const Sizable = { string: { unit: { @@ -27960,14 +35059,14 @@ var init_be = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/bg.js function bg_default() { return { - localeError: error4() + localeError: error5() }; } -var error4; +var error5; var init_bg = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/bg.js"() { init_util2(); - error4 = () => { + error5 = () => { const Sizable = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, file: { unit: "\u0431\u0430\u0439\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, @@ -28087,14 +35186,14 @@ var init_bg = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ca.js function ca_default() { return { - localeError: error5() + localeError: error6() }; } -var error5; +var error6; var init_ca = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ca.js"() { init_util2(); - error5 = () => { + error6 = () => { const Sizable = { string: { unit: "car\xE0cters", verb: "contenir" }, file: { unit: "bytes", verb: "contenir" }, @@ -28202,14 +35301,14 @@ var init_ca = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/cs.js function cs_default() { return { - localeError: error6() + localeError: error7() }; } -var error6; +var error7; var init_cs = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/cs.js"() { init_util2(); - error6 = () => { + error7 = () => { const Sizable = { string: { unit: "znak\u016F", verb: "m\xEDt" }, file: { unit: "bajt\u016F", verb: "m\xEDt" }, @@ -28320,14 +35419,14 @@ var init_cs = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/da.js function da_default() { return { - localeError: error7() + localeError: error8() }; } -var error7; +var error8; var init_da = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/da.js"() { init_util2(); - error7 = () => { + error8 = () => { const Sizable = { string: { unit: "tegn", verb: "havde" }, file: { unit: "bytes", verb: "havde" }, @@ -28442,14 +35541,14 @@ var init_da = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/de.js function de_default() { return { - localeError: error8() + localeError: error9() }; } -var error8; +var error9; var init_de = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/de.js"() { init_util2(); - error8 = () => { + error9 = () => { const Sizable = { string: { unit: "Zeichen", verb: "zu haben" }, file: { unit: "Bytes", verb: "zu haben" }, @@ -28557,14 +35656,14 @@ var init_de = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/en.js function en_default2() { return { - localeError: error9() + localeError: error10() }; } -var error9; +var error10; var init_en2 = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/en.js"() { init_util2(); - error9 = () => { + error10 = () => { const Sizable = { string: { unit: "characters", verb: "to have" }, file: { unit: "bytes", verb: "to have" }, @@ -28672,14 +35771,14 @@ var init_en2 = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/eo.js function eo_default() { return { - localeError: error10() + localeError: error11() }; } -var error10; +var error11; var init_eo = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/eo.js"() { init_util2(); - error10 = () => { + error11 = () => { const Sizable = { string: { unit: "karaktrojn", verb: "havi" }, file: { unit: "bajtojn", verb: "havi" }, @@ -28788,14 +35887,14 @@ var init_eo = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/es.js function es_default() { return { - localeError: error11() + localeError: error12() }; } -var error11; +var error12; var init_es = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/es.js"() { init_util2(); - error11 = () => { + error12 = () => { const Sizable = { string: { unit: "caracteres", verb: "tener" }, file: { unit: "bytes", verb: "tener" }, @@ -28927,14 +36026,14 @@ var init_es = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fa.js function fa_default() { return { - localeError: error12() + localeError: error13() }; } -var error12; +var error13; var init_fa = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fa.js"() { init_util2(); - error12 = () => { + error13 = () => { const Sizable = { string: { unit: "\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, @@ -29048,14 +36147,14 @@ var init_fa = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fi.js function fi_default() { return { - localeError: error13() + localeError: error14() }; } -var error13; +var error14; var init_fi = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fi.js"() { init_util2(); - error13 = () => { + error14 = () => { const Sizable = { string: { unit: "merkki\xE4", subject: "merkkijonon" }, file: { unit: "tavua", subject: "tiedoston" }, @@ -29167,14 +36266,14 @@ var init_fi = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr.js function fr_default() { return { - localeError: error14() + localeError: error15() }; } -var error14; +var error15; var init_fr = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr.js"() { init_util2(); - error14 = () => { + error15 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, @@ -29282,14 +36381,14 @@ var init_fr = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr-CA.js function fr_CA_default() { return { - localeError: error15() + localeError: error16() }; } -var error15; +var error16; var init_fr_CA = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/fr-CA.js"() { init_util2(); - error15 = () => { + error16 = () => { const Sizable = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, @@ -29396,14 +36495,14 @@ var init_fr_CA = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/he.js function he_default() { return { - localeError: error16() + localeError: error17() }; } -var error16; +var error17; var init_he = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/he.js"() { init_util2(); - error16 = () => { + error17 = () => { const TypeNames = { string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA", gender: "f" }, number: { label: "\u05DE\u05E1\u05E4\u05E8", gender: "m" }, @@ -29597,14 +36696,14 @@ var init_he = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hu.js function hu_default() { return { - localeError: error17() + localeError: error18() }; } -var error17; +var error18; var init_hu = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hu.js"() { init_util2(); - error17 = () => { + error18 = () => { const Sizable = { string: { unit: "karakter", verb: "legyen" }, file: { unit: "byte", verb: "legyen" }, @@ -29722,14 +36821,14 @@ function withDefiniteArticle(word) { } function hy_default() { return { - localeError: error18() + localeError: error19() }; } -var error18; +var error19; var init_hy = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/hy.js"() { init_util2(); - error18 = () => { + error19 = () => { const Sizable = { string: { unit: { @@ -29866,14 +36965,14 @@ var init_hy = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/id.js function id_default() { return { - localeError: error19() + localeError: error20() }; } -var error19; +var error20; var init_id = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/id.js"() { init_util2(); - error19 = () => { + error20 = () => { const Sizable = { string: { unit: "karakter", verb: "memiliki" }, file: { unit: "byte", verb: "memiliki" }, @@ -29979,14 +37078,14 @@ var init_id = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/is.js function is_default() { return { - localeError: error20() + localeError: error21() }; } -var error20; +var error21; var init_is = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/is.js"() { init_util2(); - error20 = () => { + error21 = () => { const Sizable = { string: { unit: "stafi", verb: "a\xF0 hafa" }, file: { unit: "b\xE6ti", verb: "a\xF0 hafa" }, @@ -30095,14 +37194,14 @@ var init_is = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/it.js function it_default() { return { - localeError: error21() + localeError: error22() }; } -var error21; +var error22; var init_it = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/it.js"() { init_util2(); - error21 = () => { + error22 = () => { const Sizable = { string: { unit: "caratteri", verb: "avere" }, file: { unit: "byte", verb: "avere" }, @@ -30210,14 +37309,14 @@ var init_it = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ja.js function ja_default() { return { - localeError: error22() + localeError: error23() }; } -var error22; +var error23; var init_ja = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ja.js"() { init_util2(); - error22 = () => { + error23 = () => { const Sizable = { string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" }, file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" }, @@ -30324,14 +37423,14 @@ var init_ja = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ka.js function ka_default() { return { - localeError: error23() + localeError: error24() }; } -var error23; +var error24; var init_ka = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ka.js"() { init_util2(); - error23 = () => { + error24 = () => { const Sizable = { string: { unit: "\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, file: { unit: "\u10D1\u10D0\u10D8\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, @@ -30443,14 +37542,14 @@ var init_ka = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/km.js function km_default() { return { - localeError: error24() + localeError: error25() }; } -var error24; +var error25; var init_km = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/km.js"() { init_util2(); - error24 = () => { + error25 = () => { const Sizable = { string: { unit: "\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, file: { unit: "\u1794\u17C3", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, @@ -30570,14 +37669,14 @@ var init_kh = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ko.js function ko_default() { return { - localeError: error25() + localeError: error26() }; } -var error25; +var error26; var init_ko = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ko.js"() { init_util2(); - error25 = () => { + error26 = () => { const Sizable = { string: { unit: "\uBB38\uC790", verb: "to have" }, file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" }, @@ -30698,17 +37797,17 @@ function getUnitTypeFromNumber(number7) { } function lt_default() { return { - localeError: error26() + localeError: error27() }; } -var capitalizeFirstCharacter, error26; +var capitalizeFirstCharacter, error27; var init_lt = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/lt.js"() { init_util2(); capitalizeFirstCharacter = (text) => { return text.charAt(0).toUpperCase() + text.slice(1); }; - error26 = () => { + error27 = () => { const Sizable = { string: { unit: { @@ -30898,14 +37997,14 @@ var init_lt = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/mk.js function mk_default() { return { - localeError: error27() + localeError: error28() }; } -var error27; +var error28; var init_mk = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/mk.js"() { init_util2(); - error27 = () => { + error28 = () => { const Sizable = { string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, @@ -31014,14 +38113,14 @@ var init_mk = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ms.js function ms_default() { return { - localeError: error28() + localeError: error29() }; } -var error28; +var error29; var init_ms = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ms.js"() { init_util2(); - error28 = () => { + error29 = () => { const Sizable = { string: { unit: "aksara", verb: "mempunyai" }, file: { unit: "bait", verb: "mempunyai" }, @@ -31128,14 +38227,14 @@ var init_ms = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/nl.js function nl_default() { return { - localeError: error29() + localeError: error30() }; } -var error29; +var error30; var init_nl = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/nl.js"() { init_util2(); - error29 = () => { + error30 = () => { const Sizable = { string: { unit: "tekens", verb: "heeft" }, file: { unit: "bytes", verb: "heeft" }, @@ -31245,14 +38344,14 @@ var init_nl = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/no.js function no_default() { return { - localeError: error30() + localeError: error31() }; } -var error30; +var error31; var init_no = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/no.js"() { init_util2(); - error30 = () => { + error31 = () => { const Sizable = { string: { unit: "tegn", verb: "\xE5 ha" }, file: { unit: "bytes", verb: "\xE5 ha" }, @@ -31360,14 +38459,14 @@ var init_no = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ota.js function ota_default() { return { - localeError: error31() + localeError: error32() }; } -var error31; +var error32; var init_ota = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ota.js"() { init_util2(); - error31 = () => { + error32 = () => { const Sizable = { string: { unit: "harf", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, @@ -31476,14 +38575,14 @@ var init_ota = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ps.js function ps_default() { return { - localeError: error32() + localeError: error33() }; } -var error32; +var error33; var init_ps = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ps.js"() { init_util2(); - error32 = () => { + error33 = () => { const Sizable = { string: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, file: { unit: "\u0628\u0627\u06CC\u067C\u0633", verb: "\u0648\u0644\u0631\u064A" }, @@ -31597,14 +38696,14 @@ var init_ps = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pl.js function pl_default() { return { - localeError: error33() + localeError: error34() }; } -var error33; +var error34; var init_pl = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pl.js"() { init_util2(); - error33 = () => { + error34 = () => { const Sizable = { string: { unit: "znak\xF3w", verb: "mie\u0107" }, file: { unit: "bajt\xF3w", verb: "mie\u0107" }, @@ -31713,14 +38812,14 @@ var init_pl = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pt.js function pt_default() { return { - localeError: error34() + localeError: error35() }; } -var error34; +var error35; var init_pt = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/pt.js"() { init_util2(); - error34 = () => { + error35 = () => { const Sizable = { string: { unit: "caracteres", verb: "ter" }, file: { unit: "bytes", verb: "ter" }, @@ -31843,14 +38942,14 @@ function getRussianPlural(count, one, few, many) { } function ru_default() { return { - localeError: error35() + localeError: error36() }; } -var error35; +var error36; var init_ru = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ru.js"() { init_util2(); - error35 = () => { + error36 = () => { const Sizable = { string: { unit: { @@ -31991,14 +39090,14 @@ var init_ru = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sl.js function sl_default() { return { - localeError: error36() + localeError: error37() }; } -var error36; +var error37; var init_sl = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sl.js"() { init_util2(); - error36 = () => { + error37 = () => { const Sizable = { string: { unit: "znakov", verb: "imeti" }, file: { unit: "bajtov", verb: "imeti" }, @@ -32107,14 +39206,14 @@ var init_sl = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sv.js function sv_default() { return { - localeError: error37() + localeError: error38() }; } -var error37; +var error38; var init_sv = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/sv.js"() { init_util2(); - error37 = () => { + error38 = () => { const Sizable = { string: { unit: "tecken", verb: "att ha" }, file: { unit: "bytes", verb: "att ha" }, @@ -32224,14 +39323,14 @@ var init_sv = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ta.js function ta_default() { return { - localeError: error38() + localeError: error39() }; } -var error38; +var error39; var init_ta = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ta.js"() { init_util2(); - error38 = () => { + error39 = () => { const Sizable = { string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, @@ -32341,14 +39440,14 @@ var init_ta = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/th.js function th_default() { return { - localeError: error39() + localeError: error40() }; } -var error39; +var error40; var init_th = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/th.js"() { init_util2(); - error39 = () => { + error40 = () => { const Sizable = { string: { unit: "\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, file: { unit: "\u0E44\u0E1A\u0E15\u0E4C", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, @@ -32458,14 +39557,14 @@ var init_th = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/tr.js function tr_default() { return { - localeError: error40() + localeError: error41() }; } -var error40; +var error41; var init_tr = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/tr.js"() { init_util2(); - error40 = () => { + error41 = () => { const Sizable = { string: { unit: "karakter", verb: "olmal\u0131" }, file: { unit: "bayt", verb: "olmal\u0131" }, @@ -32570,14 +39669,14 @@ var init_tr = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uk.js function uk_default() { return { - localeError: error41() + localeError: error42() }; } -var error41; +var error42; var init_uk = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uk.js"() { init_util2(); - error41 = () => { + error42 = () => { const Sizable = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, @@ -32695,14 +39794,14 @@ var init_ua = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ur.js function ur_default() { return { - localeError: error42() + localeError: error43() }; } -var error42; +var error43; var init_ur = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/ur.js"() { init_util2(); - error42 = () => { + error43 = () => { const Sizable = { string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" }, file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" }, @@ -32812,14 +39911,14 @@ var init_ur = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uz.js function uz_default() { return { - localeError: error43() + localeError: error44() }; } -var error43; +var error44; var init_uz = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/uz.js"() { init_util2(); - error43 = () => { + error44 = () => { const Sizable = { string: { unit: "belgi", verb: "bo\u2018lishi kerak" }, file: { unit: "bayt", verb: "bo\u2018lishi kerak" }, @@ -32928,14 +40027,14 @@ var init_uz = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/vi.js function vi_default() { return { - localeError: error44() + localeError: error45() }; } -var error44; +var error45; var init_vi = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/vi.js"() { init_util2(); - error44 = () => { + error45 = () => { const Sizable = { string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" }, file: { unit: "byte", verb: "c\xF3" }, @@ -33043,14 +40142,14 @@ var init_vi = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-CN.js function zh_CN_default() { return { - localeError: error45() + localeError: error46() }; } -var error45; +var error46; var init_zh_CN = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-CN.js"() { init_util2(); - error45 = () => { + error46 = () => { const Sizable = { string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" }, file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" }, @@ -33159,14 +40258,14 @@ var init_zh_CN = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-TW.js function zh_TW_default() { return { - localeError: error46() + localeError: error47() }; } -var error46; +var error47; var init_zh_TW = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/zh-TW.js"() { init_util2(); - error46 = () => { + error47 = () => { const Sizable = { string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" }, file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" }, @@ -33273,14 +40372,14 @@ var init_zh_TW = __esm({ // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/yo.js function yo_default() { return { - localeError: error47() + localeError: error48() }; } -var error47; +var error48; var init_yo = __esm({ "node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/locales/yo.js"() { init_util2(); - error47 = () => { + error48 = () => { const Sizable = { string: { unit: "\xE0mi", verb: "n\xED" }, file: { unit: "bytes", verb: "n\xED" }, @@ -35843,7 +42942,7 @@ __export(core_exports2, { decode: () => decode, decodeAsync: () => decodeAsync, describe: () => describe, - encode: () => encode, + encode: () => encode2, encodeAsync: () => encodeAsync, extractDefs: () => extractDefs, finalize: () => finalize, @@ -35857,7 +42956,7 @@ __export(core_exports2, { isValidJWT: () => isValidJWT2, locales: () => locales_exports, meta: () => meta, - parse: () => parse, + parse: () => parse2, parseAsync: () => parseAsync, prettifyError: () => prettifyError, process: () => process2, @@ -35867,7 +42966,7 @@ __export(core_exports2, { safeDecodeAsync: () => safeDecodeAsync, safeEncode: () => safeEncode, safeEncodeAsync: () => safeEncodeAsync, - safeParse: () => safeParse, + safeParse: () => safeParse2, safeParseAsync: () => safeParseAsync, toDotPath: () => toDotPath, toJSONSchema: () => toJSONSchema, @@ -39537,41 +46636,6 @@ var require_subschema = __commonJS({ } }); -// node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js -var require_fast_deep_equal = __commonJS({ - "node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js"(exports, module) { - "use strict"; - module.exports = function equal(a, b) { - if (a === b) return true; - if (a && b && typeof a == "object" && typeof b == "object") { - if (a.constructor !== b.constructor) return false; - var length, i, keys; - if (Array.isArray(a)) { - length = a.length; - if (length != b.length) return false; - for (i = length; i-- !== 0; ) - if (!equal(a[i], b[i])) return false; - return true; - } - if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; - if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); - if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); - keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) return false; - for (i = length; i-- !== 0; ) - if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; - for (i = length; i-- !== 0; ) { - var key = keys[i]; - if (!equal(a[key], b[key])) return false; - } - return true; - } - return a !== a && b !== b; - }; - } -}); - // node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js var require_json_schema_traverse = __commonJS({ "node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js"(exports, module) { @@ -40601,7 +47665,7 @@ var require_data = __commonJS({ }); // node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/utils.js -var require_utils3 = __commonJS({ +var require_utils4 = __commonJS({ "node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/utils.js"(exports, module) { "use strict"; var isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); @@ -40861,7 +47925,7 @@ var require_utils3 = __commonJS({ var require_schemes = __commonJS({ "node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/schemes.js"(exports, module) { "use strict"; - var { isUUID } = require_utils3(); + var { isUUID } = require_utils4(); var URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu; var supportedSchemeNames = ( /** @type {const} */ @@ -41071,7 +48135,7 @@ var require_schemes = __commonJS({ var require_fast_uri = __commonJS({ "node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/index.js"(exports, module) { "use strict"; - var { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils3(); + var { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils4(); var { SCHEMES, getSchemeHandler } = require_schemes(); function normalize2(uri, options) { if (typeof uri === "string") { @@ -42398,7 +49462,7 @@ var require_limitItems = __commonJS({ }); // node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/equal.js -var require_equal = __commonJS({ +var require_equal2 = __commonJS({ "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/equal.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); @@ -42416,7 +49480,7 @@ var require_uniqueItems = __commonJS({ var dataType_1 = require_dataType(); var codegen_1 = require_codegen(); var util_1 = require_util8(); - var equal_1 = require_equal(); + var equal_1 = require_equal2(); var error49 = { message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` @@ -42482,7 +49546,7 @@ var require_const = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util8(); - var equal_1 = require_equal(); + var equal_1 = require_equal2(); var error49 = { message: "must be equal to constant", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` @@ -42511,7 +49575,7 @@ var require_enum = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); var codegen_1 = require_codegen(); var util_1 = require_util8(); - var equal_1 = require_equal(); + var equal_1 = require_equal2(); var error49 = { message: "must be equal to one of the allowed values", params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` @@ -47100,7 +54164,7 @@ var require_connect2 = __commonJS({ }); // node_modules/.pnpm/undici@7.22.0/node_modules/undici/lib/llhttp/utils.js -var require_utils5 = __commonJS({ +var require_utils6 = __commonJS({ "node_modules/.pnpm/undici@7.22.0/node_modules/undici/lib/llhttp/utils.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); @@ -47121,7 +54185,7 @@ var require_constants7 = __commonJS({ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SPECIAL_HEADERS = exports.MINOR = exports.MAJOR = exports.HTAB_SP_VCHAR_OBS_TEXT = exports.QUOTED_STRING = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.HEX = exports.URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.STATUSES_HTTP = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.HEADER_STATE = exports.FINISH = exports.STATUSES = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0; - var utils_1 = require_utils5(); + var utils_1 = require_utils6(); exports.ERROR = { OK: 0, INTERNAL: 1, @@ -55767,7 +62831,7 @@ var require_api_connect2 = __commonJS({ }); // node_modules/.pnpm/undici@7.22.0/node_modules/undici/lib/api/index.js -var require_api2 = __commonJS({ +var require_api3 = __commonJS({ "node_modules/.pnpm/undici@7.22.0/node_modules/undici/lib/api/index.js"(exports, module) { "use strict"; module.exports.request = require_api_request2(); @@ -67804,7 +74868,7 @@ var require_undici2 = __commonJS({ var errors = require_errors4(); var util2 = require_util10(); var { InvalidArgumentError } = errors; - var api = require_api2(); + var api = require_api3(); var buildConnector = require_connect2(); var MockClient = require_mock_client2(); var { MockCallHistory, MockCallHistoryLog } = require_mock_call_history(); @@ -68562,7070 +75626,6 @@ var init_index_DoHiaFQM = __esm({ } }); -// node_modules/.pnpm/ansi-regex@5.0.1/node_modules/ansi-regex/index.js -var require_ansi_regex = __commonJS({ - "node_modules/.pnpm/ansi-regex@5.0.1/node_modules/ansi-regex/index.js"(exports, module) { - "use strict"; - module.exports = ({ onlyFirst = false } = {}) => { - const pattern = [ - "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)", - "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))" - ].join("|"); - return new RegExp(pattern, onlyFirst ? void 0 : "g"); - }; - } -}); - -// node_modules/.pnpm/strip-ansi@6.0.1/node_modules/strip-ansi/index.js -var require_strip_ansi = __commonJS({ - "node_modules/.pnpm/strip-ansi@6.0.1/node_modules/strip-ansi/index.js"(exports, module) { - "use strict"; - var ansiRegex = require_ansi_regex(); - module.exports = (string6) => typeof string6 === "string" ? string6.replace(ansiRegex(), "") : string6; - } -}); - -// node_modules/.pnpm/is-fullwidth-code-point@3.0.0/node_modules/is-fullwidth-code-point/index.js -var require_is_fullwidth_code_point = __commonJS({ - "node_modules/.pnpm/is-fullwidth-code-point@3.0.0/node_modules/is-fullwidth-code-point/index.js"(exports, module) { - "use strict"; - var isFullwidthCodePoint = (codePoint) => { - if (Number.isNaN(codePoint)) { - return false; - } - if (codePoint >= 4352 && (codePoint <= 4447 || // Hangul Jamo - codePoint === 9001 || // LEFT-POINTING ANGLE BRACKET - codePoint === 9002 || // RIGHT-POINTING ANGLE BRACKET - // CJK Radicals Supplement .. Enclosed CJK Letters and Months - 11904 <= codePoint && codePoint <= 12871 && codePoint !== 12351 || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A - 12880 <= codePoint && codePoint <= 19903 || // CJK Unified Ideographs .. Yi Radicals - 19968 <= codePoint && codePoint <= 42182 || // Hangul Jamo Extended-A - 43360 <= codePoint && codePoint <= 43388 || // Hangul Syllables - 44032 <= codePoint && codePoint <= 55203 || // CJK Compatibility Ideographs - 63744 <= codePoint && codePoint <= 64255 || // Vertical Forms - 65040 <= codePoint && codePoint <= 65049 || // CJK Compatibility Forms .. Small Form Variants - 65072 <= codePoint && codePoint <= 65131 || // Halfwidth and Fullwidth Forms - 65281 <= codePoint && codePoint <= 65376 || 65504 <= codePoint && codePoint <= 65510 || // Kana Supplement - 110592 <= codePoint && codePoint <= 110593 || // Enclosed Ideographic Supplement - 127488 <= codePoint && codePoint <= 127569 || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane - 131072 <= codePoint && codePoint <= 262141)) { - return true; - } - return false; - }; - module.exports = isFullwidthCodePoint; - module.exports.default = isFullwidthCodePoint; - } -}); - -// node_modules/.pnpm/emoji-regex@8.0.0/node_modules/emoji-regex/index.js -var require_emoji_regex = __commonJS({ - "node_modules/.pnpm/emoji-regex@8.0.0/node_modules/emoji-regex/index.js"(exports, module) { - "use strict"; - module.exports = function() { - return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; - }; - } -}); - -// node_modules/.pnpm/string-width@4.2.3/node_modules/string-width/index.js -var require_string_width = __commonJS({ - "node_modules/.pnpm/string-width@4.2.3/node_modules/string-width/index.js"(exports, module) { - "use strict"; - var stripAnsi = require_strip_ansi(); - var isFullwidthCodePoint = require_is_fullwidth_code_point(); - var emojiRegex3 = require_emoji_regex(); - var stringWidth = (string6) => { - if (typeof string6 !== "string" || string6.length === 0) { - return 0; - } - string6 = stripAnsi(string6); - if (string6.length === 0) { - return 0; - } - string6 = string6.replace(emojiRegex3(), " "); - let width = 0; - for (let i = 0; i < string6.length; i++) { - const code = string6.codePointAt(i); - if (code <= 31 || code >= 127 && code <= 159) { - continue; - } - if (code >= 768 && code <= 879) { - continue; - } - if (code > 65535) { - i++; - } - width += isFullwidthCodePoint(code) ? 2 : 1; - } - return width; - }; - module.exports = stringWidth; - module.exports.default = stringWidth; - } -}); - -// node_modules/.pnpm/astral-regex@2.0.0/node_modules/astral-regex/index.js -var require_astral_regex = __commonJS({ - "node_modules/.pnpm/astral-regex@2.0.0/node_modules/astral-regex/index.js"(exports, module) { - "use strict"; - var regex4 = "[\uD800-\uDBFF][\uDC00-\uDFFF]"; - var astralRegex = (options) => options && options.exact ? new RegExp(`^${regex4}$`) : new RegExp(regex4, "g"); - module.exports = astralRegex; - } -}); - -// node_modules/.pnpm/color-name@1.1.4/node_modules/color-name/index.js -var require_color_name = __commonJS({ - "node_modules/.pnpm/color-name@1.1.4/node_modules/color-name/index.js"(exports, module) { - "use strict"; - module.exports = { - "aliceblue": [240, 248, 255], - "antiquewhite": [250, 235, 215], - "aqua": [0, 255, 255], - "aquamarine": [127, 255, 212], - "azure": [240, 255, 255], - "beige": [245, 245, 220], - "bisque": [255, 228, 196], - "black": [0, 0, 0], - "blanchedalmond": [255, 235, 205], - "blue": [0, 0, 255], - "blueviolet": [138, 43, 226], - "brown": [165, 42, 42], - "burlywood": [222, 184, 135], - "cadetblue": [95, 158, 160], - "chartreuse": [127, 255, 0], - "chocolate": [210, 105, 30], - "coral": [255, 127, 80], - "cornflowerblue": [100, 149, 237], - "cornsilk": [255, 248, 220], - "crimson": [220, 20, 60], - "cyan": [0, 255, 255], - "darkblue": [0, 0, 139], - "darkcyan": [0, 139, 139], - "darkgoldenrod": [184, 134, 11], - "darkgray": [169, 169, 169], - "darkgreen": [0, 100, 0], - "darkgrey": [169, 169, 169], - "darkkhaki": [189, 183, 107], - "darkmagenta": [139, 0, 139], - "darkolivegreen": [85, 107, 47], - "darkorange": [255, 140, 0], - "darkorchid": [153, 50, 204], - "darkred": [139, 0, 0], - "darksalmon": [233, 150, 122], - "darkseagreen": [143, 188, 143], - "darkslateblue": [72, 61, 139], - "darkslategray": [47, 79, 79], - "darkslategrey": [47, 79, 79], - "darkturquoise": [0, 206, 209], - "darkviolet": [148, 0, 211], - "deeppink": [255, 20, 147], - "deepskyblue": [0, 191, 255], - "dimgray": [105, 105, 105], - "dimgrey": [105, 105, 105], - "dodgerblue": [30, 144, 255], - "firebrick": [178, 34, 34], - "floralwhite": [255, 250, 240], - "forestgreen": [34, 139, 34], - "fuchsia": [255, 0, 255], - "gainsboro": [220, 220, 220], - "ghostwhite": [248, 248, 255], - "gold": [255, 215, 0], - "goldenrod": [218, 165, 32], - "gray": [128, 128, 128], - "green": [0, 128, 0], - "greenyellow": [173, 255, 47], - "grey": [128, 128, 128], - "honeydew": [240, 255, 240], - "hotpink": [255, 105, 180], - "indianred": [205, 92, 92], - "indigo": [75, 0, 130], - "ivory": [255, 255, 240], - "khaki": [240, 230, 140], - "lavender": [230, 230, 250], - "lavenderblush": [255, 240, 245], - "lawngreen": [124, 252, 0], - "lemonchiffon": [255, 250, 205], - "lightblue": [173, 216, 230], - "lightcoral": [240, 128, 128], - "lightcyan": [224, 255, 255], - "lightgoldenrodyellow": [250, 250, 210], - "lightgray": [211, 211, 211], - "lightgreen": [144, 238, 144], - "lightgrey": [211, 211, 211], - "lightpink": [255, 182, 193], - "lightsalmon": [255, 160, 122], - "lightseagreen": [32, 178, 170], - "lightskyblue": [135, 206, 250], - "lightslategray": [119, 136, 153], - "lightslategrey": [119, 136, 153], - "lightsteelblue": [176, 196, 222], - "lightyellow": [255, 255, 224], - "lime": [0, 255, 0], - "limegreen": [50, 205, 50], - "linen": [250, 240, 230], - "magenta": [255, 0, 255], - "maroon": [128, 0, 0], - "mediumaquamarine": [102, 205, 170], - "mediumblue": [0, 0, 205], - "mediumorchid": [186, 85, 211], - "mediumpurple": [147, 112, 219], - "mediumseagreen": [60, 179, 113], - "mediumslateblue": [123, 104, 238], - "mediumspringgreen": [0, 250, 154], - "mediumturquoise": [72, 209, 204], - "mediumvioletred": [199, 21, 133], - "midnightblue": [25, 25, 112], - "mintcream": [245, 255, 250], - "mistyrose": [255, 228, 225], - "moccasin": [255, 228, 181], - "navajowhite": [255, 222, 173], - "navy": [0, 0, 128], - "oldlace": [253, 245, 230], - "olive": [128, 128, 0], - "olivedrab": [107, 142, 35], - "orange": [255, 165, 0], - "orangered": [255, 69, 0], - "orchid": [218, 112, 214], - "palegoldenrod": [238, 232, 170], - "palegreen": [152, 251, 152], - "paleturquoise": [175, 238, 238], - "palevioletred": [219, 112, 147], - "papayawhip": [255, 239, 213], - "peachpuff": [255, 218, 185], - "peru": [205, 133, 63], - "pink": [255, 192, 203], - "plum": [221, 160, 221], - "powderblue": [176, 224, 230], - "purple": [128, 0, 128], - "rebeccapurple": [102, 51, 153], - "red": [255, 0, 0], - "rosybrown": [188, 143, 143], - "royalblue": [65, 105, 225], - "saddlebrown": [139, 69, 19], - "salmon": [250, 128, 114], - "sandybrown": [244, 164, 96], - "seagreen": [46, 139, 87], - "seashell": [255, 245, 238], - "sienna": [160, 82, 45], - "silver": [192, 192, 192], - "skyblue": [135, 206, 235], - "slateblue": [106, 90, 205], - "slategray": [112, 128, 144], - "slategrey": [112, 128, 144], - "snow": [255, 250, 250], - "springgreen": [0, 255, 127], - "steelblue": [70, 130, 180], - "tan": [210, 180, 140], - "teal": [0, 128, 128], - "thistle": [216, 191, 216], - "tomato": [255, 99, 71], - "turquoise": [64, 224, 208], - "violet": [238, 130, 238], - "wheat": [245, 222, 179], - "white": [255, 255, 255], - "whitesmoke": [245, 245, 245], - "yellow": [255, 255, 0], - "yellowgreen": [154, 205, 50] - }; - } -}); - -// node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/conversions.js -var require_conversions = __commonJS({ - "node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/conversions.js"(exports, module) { - var cssKeywords = require_color_name(); - var reverseKeywords = {}; - for (const key of Object.keys(cssKeywords)) { - reverseKeywords[cssKeywords[key]] = key; - } - var convert = { - rgb: { channels: 3, labels: "rgb" }, - hsl: { channels: 3, labels: "hsl" }, - hsv: { channels: 3, labels: "hsv" }, - hwb: { channels: 3, labels: "hwb" }, - cmyk: { channels: 4, labels: "cmyk" }, - xyz: { channels: 3, labels: "xyz" }, - lab: { channels: 3, labels: "lab" }, - lch: { channels: 3, labels: "lch" }, - hex: { channels: 1, labels: ["hex"] }, - keyword: { channels: 1, labels: ["keyword"] }, - ansi16: { channels: 1, labels: ["ansi16"] }, - ansi256: { channels: 1, labels: ["ansi256"] }, - hcg: { channels: 3, labels: ["h", "c", "g"] }, - apple: { channels: 3, labels: ["r16", "g16", "b16"] }, - gray: { channels: 1, labels: ["gray"] } - }; - module.exports = convert; - for (const model of Object.keys(convert)) { - if (!("channels" in convert[model])) { - throw new Error("missing channels property: " + model); - } - if (!("labels" in convert[model])) { - throw new Error("missing channel labels property: " + model); - } - if (convert[model].labels.length !== convert[model].channels) { - throw new Error("channel and label counts mismatch: " + model); - } - const { channels, labels } = convert[model]; - delete convert[model].channels; - delete convert[model].labels; - Object.defineProperty(convert[model], "channels", { value: channels }); - Object.defineProperty(convert[model], "labels", { value: labels }); - } - convert.rgb.hsl = function(rgb) { - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - const min = Math.min(r, g, b); - const max = Math.max(r, g, b); - const delta = max - min; - let h; - let s; - if (max === min) { - h = 0; - } else if (r === max) { - h = (g - b) / delta; - } else if (g === max) { - h = 2 + (b - r) / delta; - } else if (b === max) { - h = 4 + (r - g) / delta; - } - h = Math.min(h * 60, 360); - if (h < 0) { - h += 360; - } - const l = (min + max) / 2; - if (max === min) { - s = 0; - } else if (l <= 0.5) { - s = delta / (max + min); - } else { - s = delta / (2 - max - min); - } - return [h, s * 100, l * 100]; - }; - convert.rgb.hsv = function(rgb) { - let rdif; - let gdif; - let bdif; - let h; - let s; - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - const v = Math.max(r, g, b); - const diff = v - Math.min(r, g, b); - const diffc = function(c) { - return (v - c) / 6 / diff + 1 / 2; - }; - if (diff === 0) { - h = 0; - s = 0; - } else { - s = diff / v; - rdif = diffc(r); - gdif = diffc(g); - bdif = diffc(b); - if (r === v) { - h = bdif - gdif; - } else if (g === v) { - h = 1 / 3 + rdif - bdif; - } else if (b === v) { - h = 2 / 3 + gdif - rdif; - } - if (h < 0) { - h += 1; - } else if (h > 1) { - h -= 1; - } - } - return [ - h * 360, - s * 100, - v * 100 - ]; - }; - convert.rgb.hwb = function(rgb) { - const r = rgb[0]; - const g = rgb[1]; - let b = rgb[2]; - const h = convert.rgb.hsl(rgb)[0]; - const w = 1 / 255 * Math.min(r, Math.min(g, b)); - b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); - return [h, w * 100, b * 100]; - }; - convert.rgb.cmyk = function(rgb) { - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - const k = Math.min(1 - r, 1 - g, 1 - b); - const c = (1 - r - k) / (1 - k) || 0; - const m = (1 - g - k) / (1 - k) || 0; - const y = (1 - b - k) / (1 - k) || 0; - return [c * 100, m * 100, y * 100, k * 100]; - }; - function comparativeDistance(x, y) { - return (x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 + (x[2] - y[2]) ** 2; - } - convert.rgb.keyword = function(rgb) { - const reversed = reverseKeywords[rgb]; - if (reversed) { - return reversed; - } - let currentClosestDistance = Infinity; - let currentClosestKeyword; - for (const keyword of Object.keys(cssKeywords)) { - const value2 = cssKeywords[keyword]; - const distance = comparativeDistance(rgb, value2); - if (distance < currentClosestDistance) { - currentClosestDistance = distance; - currentClosestKeyword = keyword; - } - } - return currentClosestKeyword; - }; - convert.keyword.rgb = function(keyword) { - return cssKeywords[keyword]; - }; - convert.rgb.xyz = function(rgb) { - let r = rgb[0] / 255; - let g = rgb[1] / 255; - let b = rgb[2] / 255; - r = r > 0.04045 ? ((r + 0.055) / 1.055) ** 2.4 : r / 12.92; - g = g > 0.04045 ? ((g + 0.055) / 1.055) ** 2.4 : g / 12.92; - b = b > 0.04045 ? ((b + 0.055) / 1.055) ** 2.4 : b / 12.92; - const x = r * 0.4124 + g * 0.3576 + b * 0.1805; - const y = r * 0.2126 + g * 0.7152 + b * 0.0722; - const z2 = r * 0.0193 + g * 0.1192 + b * 0.9505; - return [x * 100, y * 100, z2 * 100]; - }; - convert.rgb.lab = function(rgb) { - const xyz = convert.rgb.xyz(rgb); - let x = xyz[0]; - let y = xyz[1]; - let z2 = xyz[2]; - x /= 95.047; - y /= 100; - z2 /= 108.883; - x = x > 8856e-6 ? x ** (1 / 3) : 7.787 * x + 16 / 116; - y = y > 8856e-6 ? y ** (1 / 3) : 7.787 * y + 16 / 116; - z2 = z2 > 8856e-6 ? z2 ** (1 / 3) : 7.787 * z2 + 16 / 116; - const l = 116 * y - 16; - const a = 500 * (x - y); - const b = 200 * (y - z2); - return [l, a, b]; - }; - convert.hsl.rgb = function(hsl) { - const h = hsl[0] / 360; - const s = hsl[1] / 100; - const l = hsl[2] / 100; - let t2; - let t3; - let val; - if (s === 0) { - val = l * 255; - return [val, val, val]; - } - if (l < 0.5) { - t2 = l * (1 + s); - } else { - t2 = l + s - l * s; - } - const t1 = 2 * l - t2; - const rgb = [0, 0, 0]; - for (let i = 0; i < 3; i++) { - t3 = h + 1 / 3 * -(i - 1); - if (t3 < 0) { - t3++; - } - if (t3 > 1) { - t3--; - } - if (6 * t3 < 1) { - val = t1 + (t2 - t1) * 6 * t3; - } else if (2 * t3 < 1) { - val = t2; - } else if (3 * t3 < 2) { - val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; - } else { - val = t1; - } - rgb[i] = val * 255; - } - return rgb; - }; - convert.hsl.hsv = function(hsl) { - const h = hsl[0]; - let s = hsl[1] / 100; - let l = hsl[2] / 100; - let smin = s; - const lmin = Math.max(l, 0.01); - l *= 2; - s *= l <= 1 ? l : 2 - l; - smin *= lmin <= 1 ? lmin : 2 - lmin; - const v = (l + s) / 2; - const sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s); - return [h, sv * 100, v * 100]; - }; - convert.hsv.rgb = function(hsv) { - const h = hsv[0] / 60; - const s = hsv[1] / 100; - let v = hsv[2] / 100; - const hi = Math.floor(h) % 6; - const f = h - Math.floor(h); - const p = 255 * v * (1 - s); - const q = 255 * v * (1 - s * f); - const t = 255 * v * (1 - s * (1 - f)); - v *= 255; - switch (hi) { - case 0: - return [v, t, p]; - case 1: - return [q, v, p]; - case 2: - return [p, v, t]; - case 3: - return [p, q, v]; - case 4: - return [t, p, v]; - case 5: - return [v, p, q]; - } - }; - convert.hsv.hsl = function(hsv) { - const h = hsv[0]; - const s = hsv[1] / 100; - const v = hsv[2] / 100; - const vmin = Math.max(v, 0.01); - let sl; - let l; - l = (2 - s) * v; - const lmin = (2 - s) * vmin; - sl = s * vmin; - sl /= lmin <= 1 ? lmin : 2 - lmin; - sl = sl || 0; - l /= 2; - return [h, sl * 100, l * 100]; - }; - convert.hwb.rgb = function(hwb) { - const h = hwb[0] / 360; - let wh = hwb[1] / 100; - let bl = hwb[2] / 100; - const ratio = wh + bl; - let f; - if (ratio > 1) { - wh /= ratio; - bl /= ratio; - } - const i = Math.floor(6 * h); - const v = 1 - bl; - f = 6 * h - i; - if ((i & 1) !== 0) { - f = 1 - f; - } - const n = wh + f * (v - wh); - let r; - let g; - let b; - switch (i) { - default: - case 6: - case 0: - r = v; - g = n; - b = wh; - break; - case 1: - r = n; - g = v; - b = wh; - break; - case 2: - r = wh; - g = v; - b = n; - break; - case 3: - r = wh; - g = n; - b = v; - break; - case 4: - r = n; - g = wh; - b = v; - break; - case 5: - r = v; - g = wh; - b = n; - break; - } - return [r * 255, g * 255, b * 255]; - }; - convert.cmyk.rgb = function(cmyk) { - const c = cmyk[0] / 100; - const m = cmyk[1] / 100; - const y = cmyk[2] / 100; - const k = cmyk[3] / 100; - const r = 1 - Math.min(1, c * (1 - k) + k); - const g = 1 - Math.min(1, m * (1 - k) + k); - const b = 1 - Math.min(1, y * (1 - k) + k); - return [r * 255, g * 255, b * 255]; - }; - convert.xyz.rgb = function(xyz) { - const x = xyz[0] / 100; - const y = xyz[1] / 100; - const z2 = xyz[2] / 100; - let r; - let g; - let b; - r = x * 3.2406 + y * -1.5372 + z2 * -0.4986; - g = x * -0.9689 + y * 1.8758 + z2 * 0.0415; - b = x * 0.0557 + y * -0.204 + z2 * 1.057; - r = r > 31308e-7 ? 1.055 * r ** (1 / 2.4) - 0.055 : r * 12.92; - g = g > 31308e-7 ? 1.055 * g ** (1 / 2.4) - 0.055 : g * 12.92; - b = b > 31308e-7 ? 1.055 * b ** (1 / 2.4) - 0.055 : b * 12.92; - r = Math.min(Math.max(0, r), 1); - g = Math.min(Math.max(0, g), 1); - b = Math.min(Math.max(0, b), 1); - return [r * 255, g * 255, b * 255]; - }; - convert.xyz.lab = function(xyz) { - let x = xyz[0]; - let y = xyz[1]; - let z2 = xyz[2]; - x /= 95.047; - y /= 100; - z2 /= 108.883; - x = x > 8856e-6 ? x ** (1 / 3) : 7.787 * x + 16 / 116; - y = y > 8856e-6 ? y ** (1 / 3) : 7.787 * y + 16 / 116; - z2 = z2 > 8856e-6 ? z2 ** (1 / 3) : 7.787 * z2 + 16 / 116; - const l = 116 * y - 16; - const a = 500 * (x - y); - const b = 200 * (y - z2); - return [l, a, b]; - }; - convert.lab.xyz = function(lab) { - const l = lab[0]; - const a = lab[1]; - const b = lab[2]; - let x; - let y; - let z2; - y = (l + 16) / 116; - x = a / 500 + y; - z2 = y - b / 200; - const y2 = y ** 3; - const x2 = x ** 3; - const z22 = z2 ** 3; - y = y2 > 8856e-6 ? y2 : (y - 16 / 116) / 7.787; - x = x2 > 8856e-6 ? x2 : (x - 16 / 116) / 7.787; - z2 = z22 > 8856e-6 ? z22 : (z2 - 16 / 116) / 7.787; - x *= 95.047; - y *= 100; - z2 *= 108.883; - return [x, y, z2]; - }; - convert.lab.lch = function(lab) { - const l = lab[0]; - const a = lab[1]; - const b = lab[2]; - let h; - const hr = Math.atan2(b, a); - h = hr * 360 / 2 / Math.PI; - if (h < 0) { - h += 360; - } - const c = Math.sqrt(a * a + b * b); - return [l, c, h]; - }; - convert.lch.lab = function(lch) { - const l = lch[0]; - const c = lch[1]; - const h = lch[2]; - const hr = h / 360 * 2 * Math.PI; - const a = c * Math.cos(hr); - const b = c * Math.sin(hr); - return [l, a, b]; - }; - convert.rgb.ansi16 = function(args2, saturation = null) { - const [r, g, b] = args2; - let value2 = saturation === null ? convert.rgb.hsv(args2)[2] : saturation; - value2 = Math.round(value2 / 50); - if (value2 === 0) { - return 30; - } - let ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255)); - if (value2 === 2) { - ansi += 60; - } - return ansi; - }; - convert.hsv.ansi16 = function(args2) { - return convert.rgb.ansi16(convert.hsv.rgb(args2), args2[2]); - }; - convert.rgb.ansi256 = function(args2) { - const r = args2[0]; - const g = args2[1]; - const b = args2[2]; - if (r === g && g === b) { - if (r < 8) { - return 16; - } - if (r > 248) { - return 231; - } - return Math.round((r - 8) / 247 * 24) + 232; - } - const ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5); - return ansi; - }; - convert.ansi16.rgb = function(args2) { - let color = args2 % 10; - if (color === 0 || color === 7) { - if (args2 > 50) { - color += 3.5; - } - color = color / 10.5 * 255; - return [color, color, color]; - } - const mult = (~~(args2 > 50) + 1) * 0.5; - const r = (color & 1) * mult * 255; - const g = (color >> 1 & 1) * mult * 255; - const b = (color >> 2 & 1) * mult * 255; - return [r, g, b]; - }; - convert.ansi256.rgb = function(args2) { - if (args2 >= 232) { - const c = (args2 - 232) * 10 + 8; - return [c, c, c]; - } - args2 -= 16; - let rem; - const r = Math.floor(args2 / 36) / 5 * 255; - const g = Math.floor((rem = args2 % 36) / 6) / 5 * 255; - const b = rem % 6 / 5 * 255; - return [r, g, b]; - }; - convert.rgb.hex = function(args2) { - const integer4 = ((Math.round(args2[0]) & 255) << 16) + ((Math.round(args2[1]) & 255) << 8) + (Math.round(args2[2]) & 255); - const string6 = integer4.toString(16).toUpperCase(); - return "000000".substring(string6.length) + string6; - }; - convert.hex.rgb = function(args2) { - const match3 = args2.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); - if (!match3) { - return [0, 0, 0]; - } - let colorString = match3[0]; - if (match3[0].length === 3) { - colorString = colorString.split("").map((char) => { - return char + char; - }).join(""); - } - const integer4 = parseInt(colorString, 16); - const r = integer4 >> 16 & 255; - const g = integer4 >> 8 & 255; - const b = integer4 & 255; - return [r, g, b]; - }; - convert.rgb.hcg = function(rgb) { - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - const max = Math.max(Math.max(r, g), b); - const min = Math.min(Math.min(r, g), b); - const chroma = max - min; - let grayscale; - let hue; - if (chroma < 1) { - grayscale = min / (1 - chroma); - } else { - grayscale = 0; - } - if (chroma <= 0) { - hue = 0; - } else if (max === r) { - hue = (g - b) / chroma % 6; - } else if (max === g) { - hue = 2 + (b - r) / chroma; - } else { - hue = 4 + (r - g) / chroma; - } - hue /= 6; - hue %= 1; - return [hue * 360, chroma * 100, grayscale * 100]; - }; - convert.hsl.hcg = function(hsl) { - const s = hsl[1] / 100; - const l = hsl[2] / 100; - const c = l < 0.5 ? 2 * s * l : 2 * s * (1 - l); - let f = 0; - if (c < 1) { - f = (l - 0.5 * c) / (1 - c); - } - return [hsl[0], c * 100, f * 100]; - }; - convert.hsv.hcg = function(hsv) { - const s = hsv[1] / 100; - const v = hsv[2] / 100; - const c = s * v; - let f = 0; - if (c < 1) { - f = (v - c) / (1 - c); - } - return [hsv[0], c * 100, f * 100]; - }; - convert.hcg.rgb = function(hcg) { - const h = hcg[0] / 360; - const c = hcg[1] / 100; - const g = hcg[2] / 100; - if (c === 0) { - return [g * 255, g * 255, g * 255]; - } - const pure = [0, 0, 0]; - const hi = h % 1 * 6; - const v = hi % 1; - const w = 1 - v; - let mg = 0; - switch (Math.floor(hi)) { - case 0: - pure[0] = 1; - pure[1] = v; - pure[2] = 0; - break; - case 1: - pure[0] = w; - pure[1] = 1; - pure[2] = 0; - break; - case 2: - pure[0] = 0; - pure[1] = 1; - pure[2] = v; - break; - case 3: - pure[0] = 0; - pure[1] = w; - pure[2] = 1; - break; - case 4: - pure[0] = v; - pure[1] = 0; - pure[2] = 1; - break; - default: - pure[0] = 1; - pure[1] = 0; - pure[2] = w; - } - mg = (1 - c) * g; - return [ - (c * pure[0] + mg) * 255, - (c * pure[1] + mg) * 255, - (c * pure[2] + mg) * 255 - ]; - }; - convert.hcg.hsv = function(hcg) { - const c = hcg[1] / 100; - const g = hcg[2] / 100; - const v = c + g * (1 - c); - let f = 0; - if (v > 0) { - f = c / v; - } - return [hcg[0], f * 100, v * 100]; - }; - convert.hcg.hsl = function(hcg) { - const c = hcg[1] / 100; - const g = hcg[2] / 100; - const l = g * (1 - c) + 0.5 * c; - let s = 0; - if (l > 0 && l < 0.5) { - s = c / (2 * l); - } else if (l >= 0.5 && l < 1) { - s = c / (2 * (1 - l)); - } - return [hcg[0], s * 100, l * 100]; - }; - convert.hcg.hwb = function(hcg) { - const c = hcg[1] / 100; - const g = hcg[2] / 100; - const v = c + g * (1 - c); - return [hcg[0], (v - c) * 100, (1 - v) * 100]; - }; - convert.hwb.hcg = function(hwb) { - const w = hwb[1] / 100; - const b = hwb[2] / 100; - const v = 1 - b; - const c = v - w; - let g = 0; - if (c < 1) { - g = (v - c) / (1 - c); - } - return [hwb[0], c * 100, g * 100]; - }; - convert.apple.rgb = function(apple) { - return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255]; - }; - convert.rgb.apple = function(rgb) { - return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535]; - }; - convert.gray.rgb = function(args2) { - return [args2[0] / 100 * 255, args2[0] / 100 * 255, args2[0] / 100 * 255]; - }; - convert.gray.hsl = function(args2) { - return [0, 0, args2[0]]; - }; - convert.gray.hsv = convert.gray.hsl; - convert.gray.hwb = function(gray) { - return [0, 100, gray[0]]; - }; - convert.gray.cmyk = function(gray) { - return [0, 0, 0, gray[0]]; - }; - convert.gray.lab = function(gray) { - return [gray[0], 0, 0]; - }; - convert.gray.hex = function(gray) { - const val = Math.round(gray[0] / 100 * 255) & 255; - const integer4 = (val << 16) + (val << 8) + val; - const string6 = integer4.toString(16).toUpperCase(); - return "000000".substring(string6.length) + string6; - }; - convert.rgb.gray = function(rgb) { - const val = (rgb[0] + rgb[1] + rgb[2]) / 3; - return [val / 255 * 100]; - }; - } -}); - -// node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/route.js -var require_route = __commonJS({ - "node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/route.js"(exports, module) { - var conversions = require_conversions(); - function buildGraph() { - const graph = {}; - const models = Object.keys(conversions); - for (let len = models.length, i = 0; i < len; i++) { - graph[models[i]] = { - // http://jsperf.com/1-vs-infinity - // micro-opt, but this is simple. - distance: -1, - parent: null - }; - } - return graph; - } - function deriveBFS(fromModel) { - const graph = buildGraph(); - const queue = [fromModel]; - graph[fromModel].distance = 0; - while (queue.length) { - const current = queue.pop(); - const adjacents = Object.keys(conversions[current]); - for (let len = adjacents.length, i = 0; i < len; i++) { - const adjacent = adjacents[i]; - const node2 = graph[adjacent]; - if (node2.distance === -1) { - node2.distance = graph[current].distance + 1; - node2.parent = current; - queue.unshift(adjacent); - } - } - } - return graph; - } - function link(from, to) { - return function(args2) { - return to(from(args2)); - }; - } - function wrapConversion(toModel, graph) { - const path3 = [graph[toModel].parent, toModel]; - let fn2 = conversions[graph[toModel].parent][toModel]; - let cur = graph[toModel].parent; - while (graph[cur].parent) { - path3.unshift(graph[cur].parent); - fn2 = link(conversions[graph[cur].parent][cur], fn2); - cur = graph[cur].parent; - } - fn2.conversion = path3; - return fn2; - } - module.exports = function(fromModel) { - const graph = deriveBFS(fromModel); - const conversion = {}; - const models = Object.keys(graph); - for (let len = models.length, i = 0; i < len; i++) { - const toModel = models[i]; - const node2 = graph[toModel]; - if (node2.parent === null) { - continue; - } - conversion[toModel] = wrapConversion(toModel, graph); - } - return conversion; - }; - } -}); - -// node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/index.js -var require_color_convert = __commonJS({ - "node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/index.js"(exports, module) { - var conversions = require_conversions(); - var route = require_route(); - var convert = {}; - var models = Object.keys(conversions); - function wrapRaw(fn2) { - const wrappedFn = function(...args2) { - const arg0 = args2[0]; - if (arg0 === void 0 || arg0 === null) { - return arg0; - } - if (arg0.length > 1) { - args2 = arg0; - } - return fn2(args2); - }; - if ("conversion" in fn2) { - wrappedFn.conversion = fn2.conversion; - } - return wrappedFn; - } - function wrapRounded(fn2) { - const wrappedFn = function(...args2) { - const arg0 = args2[0]; - if (arg0 === void 0 || arg0 === null) { - return arg0; - } - if (arg0.length > 1) { - args2 = arg0; - } - const result = fn2(args2); - if (typeof result === "object") { - for (let len = result.length, i = 0; i < len; i++) { - result[i] = Math.round(result[i]); - } - } - return result; - }; - if ("conversion" in fn2) { - wrappedFn.conversion = fn2.conversion; - } - return wrappedFn; - } - models.forEach((fromModel) => { - convert[fromModel] = {}; - Object.defineProperty(convert[fromModel], "channels", { value: conversions[fromModel].channels }); - Object.defineProperty(convert[fromModel], "labels", { value: conversions[fromModel].labels }); - const routes = route(fromModel); - const routeModels = Object.keys(routes); - routeModels.forEach((toModel) => { - const fn2 = routes[toModel]; - convert[fromModel][toModel] = wrapRounded(fn2); - convert[fromModel][toModel].raw = wrapRaw(fn2); - }); - }); - module.exports = convert; - } -}); - -// node_modules/.pnpm/ansi-styles@4.3.0/node_modules/ansi-styles/index.js -var require_ansi_styles = __commonJS({ - "node_modules/.pnpm/ansi-styles@4.3.0/node_modules/ansi-styles/index.js"(exports, module) { - "use strict"; - var wrapAnsi16 = (fn2, offset) => (...args2) => { - const code = fn2(...args2); - return `\x1B[${code + offset}m`; - }; - var wrapAnsi256 = (fn2, offset) => (...args2) => { - const code = fn2(...args2); - return `\x1B[${38 + offset};5;${code}m`; - }; - var wrapAnsi16m = (fn2, offset) => (...args2) => { - const rgb = fn2(...args2); - return `\x1B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; - }; - var ansi2ansi = (n) => n; - var rgb2rgb = (r, g, b) => [r, g, b]; - var setLazyProperty = (object5, property, get2) => { - Object.defineProperty(object5, property, { - get: () => { - const value2 = get2(); - Object.defineProperty(object5, property, { - value: value2, - enumerable: true, - configurable: true - }); - return value2; - }, - enumerable: true, - configurable: true - }); - }; - var colorConvert; - var makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { - if (colorConvert === void 0) { - colorConvert = require_color_convert(); - } - const offset = isBackground ? 10 : 0; - const styles = {}; - for (const [sourceSpace, suite] of Object.entries(colorConvert)) { - const name = sourceSpace === "ansi16" ? "ansi" : sourceSpace; - if (sourceSpace === targetSpace) { - styles[name] = wrap(identity, offset); - } else if (typeof suite === "object") { - styles[name] = wrap(suite[targetSpace], offset); - } - } - return styles; - }; - function assembleStyles() { - const codes = /* @__PURE__ */ new Map(); - const styles = { - modifier: { - reset: [0, 0], - // 21 isn't widely supported and 22 does the same thing - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - color: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - // Bright color - blackBright: [90, 39], - redBright: [91, 39], - greenBright: [92, 39], - yellowBright: [93, 39], - blueBright: [94, 39], - magentaBright: [95, 39], - cyanBright: [96, 39], - whiteBright: [97, 39] - }, - bgColor: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - // Bright color - bgBlackBright: [100, 49], - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49] - } - }; - styles.color.gray = styles.color.blackBright; - styles.bgColor.bgGray = styles.bgColor.bgBlackBright; - styles.color.grey = styles.color.blackBright; - styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; - for (const [groupName, group2] of Object.entries(styles)) { - for (const [styleName, style] of Object.entries(group2)) { - styles[styleName] = { - open: `\x1B[${style[0]}m`, - close: `\x1B[${style[1]}m` - }; - group2[styleName] = styles[styleName]; - codes.set(style[0], style[1]); - } - Object.defineProperty(styles, groupName, { - value: group2, - enumerable: false - }); - } - Object.defineProperty(styles, "codes", { - value: codes, - enumerable: false - }); - styles.color.close = "\x1B[39m"; - styles.bgColor.close = "\x1B[49m"; - setLazyProperty(styles.color, "ansi", () => makeDynamicStyles(wrapAnsi16, "ansi16", ansi2ansi, false)); - setLazyProperty(styles.color, "ansi256", () => makeDynamicStyles(wrapAnsi256, "ansi256", ansi2ansi, false)); - setLazyProperty(styles.color, "ansi16m", () => makeDynamicStyles(wrapAnsi16m, "rgb", rgb2rgb, false)); - setLazyProperty(styles.bgColor, "ansi", () => makeDynamicStyles(wrapAnsi16, "ansi16", ansi2ansi, true)); - setLazyProperty(styles.bgColor, "ansi256", () => makeDynamicStyles(wrapAnsi256, "ansi256", ansi2ansi, true)); - setLazyProperty(styles.bgColor, "ansi16m", () => makeDynamicStyles(wrapAnsi16m, "rgb", rgb2rgb, true)); - return styles; - } - Object.defineProperty(module, "exports", { - enumerable: true, - get: assembleStyles - }); - } -}); - -// node_modules/.pnpm/slice-ansi@4.0.0/node_modules/slice-ansi/index.js -var require_slice_ansi = __commonJS({ - "node_modules/.pnpm/slice-ansi@4.0.0/node_modules/slice-ansi/index.js"(exports, module) { - "use strict"; - var isFullwidthCodePoint = require_is_fullwidth_code_point(); - var astralRegex = require_astral_regex(); - var ansiStyles = require_ansi_styles(); - var ESCAPES = [ - "\x1B", - "\x9B" - ]; - var wrapAnsi = (code) => `${ESCAPES[0]}[${code}m`; - var checkAnsi = (ansiCodes, isEscapes, endAnsiCode) => { - let output = []; - ansiCodes = [...ansiCodes]; - for (let ansiCode of ansiCodes) { - const ansiCodeOrigin = ansiCode; - if (ansiCode.includes(";")) { - ansiCode = ansiCode.split(";")[0][0] + "0"; - } - const item = ansiStyles.codes.get(Number.parseInt(ansiCode, 10)); - if (item) { - const indexEscape = ansiCodes.indexOf(item.toString()); - if (indexEscape === -1) { - output.push(wrapAnsi(isEscapes ? item : ansiCodeOrigin)); - } else { - ansiCodes.splice(indexEscape, 1); - } - } else if (isEscapes) { - output.push(wrapAnsi(0)); - break; - } else { - output.push(wrapAnsi(ansiCodeOrigin)); - } - } - if (isEscapes) { - output = output.filter((element, index) => output.indexOf(element) === index); - if (endAnsiCode !== void 0) { - const fistEscapeCode = wrapAnsi(ansiStyles.codes.get(Number.parseInt(endAnsiCode, 10))); - output = output.reduce((current, next2) => next2 === fistEscapeCode ? [next2, ...current] : [...current, next2], []); - } - } - return output.join(""); - }; - module.exports = (string6, begin, end) => { - const characters = [...string6]; - const ansiCodes = []; - let stringEnd = typeof end === "number" ? end : characters.length; - let isInsideEscape = false; - let ansiCode; - let visible = 0; - let output = ""; - for (const [index, character] of characters.entries()) { - let leftEscape = false; - if (ESCAPES.includes(character)) { - const code = /\d[^m]*/.exec(string6.slice(index, index + 18)); - ansiCode = code && code.length > 0 ? code[0] : void 0; - if (visible < stringEnd) { - isInsideEscape = true; - if (ansiCode !== void 0) { - ansiCodes.push(ansiCode); - } - } - } else if (isInsideEscape && character === "m") { - isInsideEscape = false; - leftEscape = true; - } - if (!isInsideEscape && !leftEscape) { - visible++; - } - if (!astralRegex({ exact: true }).test(character) && isFullwidthCodePoint(character.codePointAt())) { - visible++; - if (typeof end !== "number") { - stringEnd++; - } - } - if (visible > begin && visible <= stringEnd) { - output += character; - } else if (visible === begin && !isInsideEscape && ansiCode !== void 0) { - output = checkAnsi(ansiCodes); - } else if (visible >= stringEnd) { - output += checkAnsi(ansiCodes, true, ansiCode); - break; - } - } - return output; - }; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/getBorderCharacters.js -var require_getBorderCharacters = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/getBorderCharacters.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getBorderCharacters = void 0; - var getBorderCharacters = (name) => { - if (name === "honeywell") { - return { - topBody: "\u2550", - topJoin: "\u2564", - topLeft: "\u2554", - topRight: "\u2557", - bottomBody: "\u2550", - bottomJoin: "\u2567", - bottomLeft: "\u255A", - bottomRight: "\u255D", - bodyLeft: "\u2551", - bodyRight: "\u2551", - bodyJoin: "\u2502", - headerJoin: "\u252C", - joinBody: "\u2500", - joinLeft: "\u255F", - joinRight: "\u2562", - joinJoin: "\u253C", - joinMiddleDown: "\u252C", - joinMiddleUp: "\u2534", - joinMiddleLeft: "\u2524", - joinMiddleRight: "\u251C" - }; - } - if (name === "norc") { - return { - topBody: "\u2500", - topJoin: "\u252C", - topLeft: "\u250C", - topRight: "\u2510", - bottomBody: "\u2500", - bottomJoin: "\u2534", - bottomLeft: "\u2514", - bottomRight: "\u2518", - bodyLeft: "\u2502", - bodyRight: "\u2502", - bodyJoin: "\u2502", - headerJoin: "\u252C", - joinBody: "\u2500", - joinLeft: "\u251C", - joinRight: "\u2524", - joinJoin: "\u253C", - joinMiddleDown: "\u252C", - joinMiddleUp: "\u2534", - joinMiddleLeft: "\u2524", - joinMiddleRight: "\u251C" - }; - } - if (name === "ramac") { - return { - topBody: "-", - topJoin: "+", - topLeft: "+", - topRight: "+", - bottomBody: "-", - bottomJoin: "+", - bottomLeft: "+", - bottomRight: "+", - bodyLeft: "|", - bodyRight: "|", - bodyJoin: "|", - headerJoin: "+", - joinBody: "-", - joinLeft: "|", - joinRight: "|", - joinJoin: "|", - joinMiddleDown: "+", - joinMiddleUp: "+", - joinMiddleLeft: "+", - joinMiddleRight: "+" - }; - } - if (name === "void") { - return { - topBody: "", - topJoin: "", - topLeft: "", - topRight: "", - bottomBody: "", - bottomJoin: "", - bottomLeft: "", - bottomRight: "", - bodyLeft: "", - bodyRight: "", - bodyJoin: "", - headerJoin: "", - joinBody: "", - joinLeft: "", - joinRight: "", - joinJoin: "", - joinMiddleDown: "", - joinMiddleUp: "", - joinMiddleLeft: "", - joinMiddleRight: "" - }; - } - throw new Error('Unknown border template "' + name + '".'); - }; - exports.getBorderCharacters = getBorderCharacters; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/utils.js -var require_utils6 = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/utils.js"(exports) { - "use strict"; - var __importDefault = exports && exports.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.isCellInRange = exports.areCellEqual = exports.calculateRangeCoordinate = exports.flatten = exports.extractTruncates = exports.sumArray = exports.sequence = exports.distributeUnevenly = exports.countSpaceSequence = exports.groupBySizes = exports.makeBorderConfig = exports.splitAnsi = exports.normalizeString = void 0; - var slice_ansi_1 = __importDefault(require_slice_ansi()); - var string_width_1 = __importDefault(require_string_width()); - var strip_ansi_1 = __importDefault(require_strip_ansi()); - var getBorderCharacters_1 = require_getBorderCharacters(); - var normalizeString = (input) => { - return input.replace(/\r\n/g, "\n"); - }; - exports.normalizeString = normalizeString; - var splitAnsi = (input) => { - const lengths = (0, strip_ansi_1.default)(input).split("\n").map(string_width_1.default); - const result = []; - let startIndex = 0; - lengths.forEach((length) => { - result.push(length === 0 ? "" : (0, slice_ansi_1.default)(input, startIndex, startIndex + length)); - startIndex += length + 1; - }); - return result; - }; - exports.splitAnsi = splitAnsi; - var makeBorderConfig = (border) => { - return { - ...(0, getBorderCharacters_1.getBorderCharacters)("honeywell"), - ...border - }; - }; - exports.makeBorderConfig = makeBorderConfig; - var groupBySizes = (array3, sizes) => { - let startIndex = 0; - return sizes.map((size) => { - const group2 = array3.slice(startIndex, startIndex + size); - startIndex += size; - return group2; - }); - }; - exports.groupBySizes = groupBySizes; - var countSpaceSequence = (input) => { - var _a2, _b; - return (_b = (_a2 = input.match(/\s+/g)) === null || _a2 === void 0 ? void 0 : _a2.length) !== null && _b !== void 0 ? _b : 0; - }; - exports.countSpaceSequence = countSpaceSequence; - var distributeUnevenly = (sum, length) => { - const result = Array.from({ length }).fill(Math.floor(sum / length)); - return result.map((element, index) => { - return element + (index < sum % length ? 1 : 0); - }); - }; - exports.distributeUnevenly = distributeUnevenly; - var sequence = (start, end) => { - return Array.from({ length: end - start + 1 }, (_, index) => { - return index + start; - }); - }; - exports.sequence = sequence; - var sumArray = (array3) => { - return array3.reduce((accumulator, element) => { - return accumulator + element; - }, 0); - }; - exports.sumArray = sumArray; - var extractTruncates = (config3) => { - return config3.columns.map(({ truncate }) => { - return truncate; - }); - }; - exports.extractTruncates = extractTruncates; - var flatten = (array3) => { - return [].concat(...array3); - }; - exports.flatten = flatten; - var calculateRangeCoordinate = (spanningCellConfig) => { - const { row, col, colSpan = 1, rowSpan = 1 } = spanningCellConfig; - return { - bottomRight: { - col: col + colSpan - 1, - row: row + rowSpan - 1 - }, - topLeft: { - col, - row - } - }; - }; - exports.calculateRangeCoordinate = calculateRangeCoordinate; - var areCellEqual = (cell1, cell2) => { - return cell1.row === cell2.row && cell1.col === cell2.col; - }; - exports.areCellEqual = areCellEqual; - var isCellInRange = (cell, { topLeft, bottomRight }) => { - return topLeft.row <= cell.row && cell.row <= bottomRight.row && topLeft.col <= cell.col && cell.col <= bottomRight.col; - }; - exports.isCellInRange = isCellInRange; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/alignString.js -var require_alignString = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/alignString.js"(exports) { - "use strict"; - var __importDefault = exports && exports.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.alignString = void 0; - var string_width_1 = __importDefault(require_string_width()); - var utils_1 = require_utils6(); - var alignLeft = (subject, width) => { - return subject + " ".repeat(width); - }; - var alignRight = (subject, width) => { - return " ".repeat(width) + subject; - }; - var alignCenter = (subject, width) => { - return " ".repeat(Math.floor(width / 2)) + subject + " ".repeat(Math.ceil(width / 2)); - }; - var alignJustify = (subject, width) => { - const spaceSequenceCount = (0, utils_1.countSpaceSequence)(subject); - if (spaceSequenceCount === 0) { - return alignLeft(subject, width); - } - const addingSpaces = (0, utils_1.distributeUnevenly)(width, spaceSequenceCount); - if (Math.max(...addingSpaces) > 3) { - return alignLeft(subject, width); - } - let spaceSequenceIndex = 0; - return subject.replace(/\s+/g, (groupSpace) => { - return groupSpace + " ".repeat(addingSpaces[spaceSequenceIndex++]); - }); - }; - var alignString = (subject, containerWidth, alignment) => { - const subjectWidth = (0, string_width_1.default)(subject); - if (subjectWidth === containerWidth) { - return subject; - } - if (subjectWidth > containerWidth) { - throw new Error("Subject parameter value width cannot be greater than the container width."); - } - if (subjectWidth === 0) { - return " ".repeat(containerWidth); - } - const availableWidth = containerWidth - subjectWidth; - if (alignment === "left") { - return alignLeft(subject, availableWidth); - } - if (alignment === "right") { - return alignRight(subject, availableWidth); - } - if (alignment === "justify") { - return alignJustify(subject, availableWidth); - } - return alignCenter(subject, availableWidth); - }; - exports.alignString = alignString; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/alignTableData.js -var require_alignTableData = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/alignTableData.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.alignTableData = void 0; - var alignString_1 = require_alignString(); - var alignTableData = (rows, config3) => { - return rows.map((row, rowIndex) => { - return row.map((cell, cellIndex) => { - var _a2; - const { width, alignment } = config3.columns[cellIndex]; - const containingRange = (_a2 = config3.spanningCellManager) === null || _a2 === void 0 ? void 0 : _a2.getContainingRange({ - col: cellIndex, - row: rowIndex - }, { mapped: true }); - if (containingRange) { - return cell; - } - return (0, alignString_1.alignString)(cell, width, alignment); - }); - }); - }; - exports.alignTableData = alignTableData; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/wrapString.js -var require_wrapString = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/wrapString.js"(exports) { - "use strict"; - var __importDefault = exports && exports.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.wrapString = void 0; - var slice_ansi_1 = __importDefault(require_slice_ansi()); - var string_width_1 = __importDefault(require_string_width()); - var wrapString = (subject, size) => { - let subjectSlice = subject; - const chunks = []; - do { - chunks.push((0, slice_ansi_1.default)(subjectSlice, 0, size)); - subjectSlice = (0, slice_ansi_1.default)(subjectSlice, size).trim(); - } while ((0, string_width_1.default)(subjectSlice)); - return chunks; - }; - exports.wrapString = wrapString; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/wrapWord.js -var require_wrapWord = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/wrapWord.js"(exports) { - "use strict"; - var __importDefault = exports && exports.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.wrapWord = void 0; - var slice_ansi_1 = __importDefault(require_slice_ansi()); - var strip_ansi_1 = __importDefault(require_strip_ansi()); - var calculateStringLengths = (input, size) => { - let subject = (0, strip_ansi_1.default)(input); - const chunks = []; - const re = new RegExp("(^.{1," + String(Math.max(size, 1)) + "}(\\s+|$))|(^.{1," + String(Math.max(size - 1, 1)) + "}(\\\\|/|_|\\.|,|;|-))"); - do { - let chunk; - const match3 = re.exec(subject); - if (match3) { - chunk = match3[0]; - subject = subject.slice(chunk.length); - const trimmedLength = chunk.trim().length; - const offset = chunk.length - trimmedLength; - chunks.push([trimmedLength, offset]); - } else { - chunk = subject.slice(0, size); - subject = subject.slice(size); - chunks.push([chunk.length, 0]); - } - } while (subject.length); - return chunks; - }; - var wrapWord = (input, size) => { - const result = []; - let startIndex = 0; - calculateStringLengths(input, size).forEach(([length, offset]) => { - result.push((0, slice_ansi_1.default)(input, startIndex, startIndex + length)); - startIndex += length + offset; - }); - return result; - }; - exports.wrapWord = wrapWord; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/wrapCell.js -var require_wrapCell = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/wrapCell.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.wrapCell = void 0; - var utils_1 = require_utils6(); - var wrapString_1 = require_wrapString(); - var wrapWord_1 = require_wrapWord(); - var wrapCell = (cellValue, cellWidth, useWrapWord) => { - const cellLines = (0, utils_1.splitAnsi)(cellValue); - for (let lineNr = 0; lineNr < cellLines.length; ) { - let lineChunks; - if (useWrapWord) { - lineChunks = (0, wrapWord_1.wrapWord)(cellLines[lineNr], cellWidth); - } else { - lineChunks = (0, wrapString_1.wrapString)(cellLines[lineNr], cellWidth); - } - cellLines.splice(lineNr, 1, ...lineChunks); - lineNr += lineChunks.length; - } - return cellLines; - }; - exports.wrapCell = wrapCell; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/calculateCellHeight.js -var require_calculateCellHeight = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/calculateCellHeight.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.calculateCellHeight = void 0; - var wrapCell_1 = require_wrapCell(); - var calculateCellHeight = (value2, columnWidth, useWrapWord = false) => { - return (0, wrapCell_1.wrapCell)(value2, columnWidth, useWrapWord).length; - }; - exports.calculateCellHeight = calculateCellHeight; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/calculateRowHeights.js -var require_calculateRowHeights = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/calculateRowHeights.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.calculateRowHeights = void 0; - var calculateCellHeight_1 = require_calculateCellHeight(); - var utils_1 = require_utils6(); - var calculateRowHeights = (rows, config3) => { - const rowHeights = []; - for (const [rowIndex, row] of rows.entries()) { - let rowHeight = 1; - row.forEach((cell, cellIndex) => { - var _a2; - const containingRange = (_a2 = config3.spanningCellManager) === null || _a2 === void 0 ? void 0 : _a2.getContainingRange({ - col: cellIndex, - row: rowIndex - }); - if (!containingRange) { - const cellHeight = (0, calculateCellHeight_1.calculateCellHeight)(cell, config3.columns[cellIndex].width, config3.columns[cellIndex].wrapWord); - rowHeight = Math.max(rowHeight, cellHeight); - return; - } - const { topLeft, bottomRight, height } = containingRange; - if (rowIndex === bottomRight.row) { - const totalOccupiedSpanningCellHeight = (0, utils_1.sumArray)(rowHeights.slice(topLeft.row)); - const totalHorizontalBorderHeight = bottomRight.row - topLeft.row; - const totalHiddenHorizontalBorderHeight = (0, utils_1.sequence)(topLeft.row + 1, bottomRight.row).filter((horizontalBorderIndex) => { - var _a3; - return !((_a3 = config3.drawHorizontalLine) === null || _a3 === void 0 ? void 0 : _a3.call(config3, horizontalBorderIndex, rows.length)); - }).length; - const cellHeight = height - totalOccupiedSpanningCellHeight - totalHorizontalBorderHeight + totalHiddenHorizontalBorderHeight; - rowHeight = Math.max(rowHeight, cellHeight); - } - }); - rowHeights.push(rowHeight); - } - return rowHeights; - }; - exports.calculateRowHeights = calculateRowHeights; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/drawContent.js -var require_drawContent = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/drawContent.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.drawContent = void 0; - var drawContent = (parameters) => { - const { contents, separatorGetter, drawSeparator, spanningCellManager, rowIndex, elementType } = parameters; - const contentSize = contents.length; - const result = []; - if (drawSeparator(0, contentSize)) { - result.push(separatorGetter(0, contentSize)); - } - contents.forEach((content, contentIndex) => { - if (!elementType || elementType === "border" || elementType === "row") { - result.push(content); - } - if (elementType === "cell" && rowIndex === void 0) { - result.push(content); - } - if (elementType === "cell" && rowIndex !== void 0) { - const containingRange = spanningCellManager === null || spanningCellManager === void 0 ? void 0 : spanningCellManager.getContainingRange({ - col: contentIndex, - row: rowIndex - }); - if (!containingRange || contentIndex === containingRange.topLeft.col) { - result.push(content); - } - } - if (contentIndex + 1 < contentSize && drawSeparator(contentIndex + 1, contentSize)) { - const separator2 = separatorGetter(contentIndex + 1, contentSize); - if (elementType === "cell" && rowIndex !== void 0) { - const currentCell = { - col: contentIndex + 1, - row: rowIndex - }; - const containingRange = spanningCellManager === null || spanningCellManager === void 0 ? void 0 : spanningCellManager.getContainingRange(currentCell); - if (!containingRange || containingRange.topLeft.col === currentCell.col) { - result.push(separator2); - } - } else { - result.push(separator2); - } - } - }); - if (drawSeparator(contentSize, contentSize)) { - result.push(separatorGetter(contentSize, contentSize)); - } - return result.join(""); - }; - exports.drawContent = drawContent; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/drawBorder.js -var require_drawBorder = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/drawBorder.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.createTableBorderGetter = exports.drawBorderBottom = exports.drawBorderJoin = exports.drawBorderTop = exports.drawBorder = exports.createSeparatorGetter = exports.drawBorderSegments = void 0; - var drawContent_1 = require_drawContent(); - var drawBorderSegments = (columnWidths, parameters) => { - const { separator: separator2, horizontalBorderIndex, spanningCellManager } = parameters; - return columnWidths.map((columnWidth, columnIndex) => { - const normalSegment = separator2.body.repeat(columnWidth); - if (horizontalBorderIndex === void 0) { - return normalSegment; - } - const range2 = spanningCellManager === null || spanningCellManager === void 0 ? void 0 : spanningCellManager.getContainingRange({ - col: columnIndex, - row: horizontalBorderIndex - }); - if (!range2) { - return normalSegment; - } - const { topLeft } = range2; - if (horizontalBorderIndex === topLeft.row) { - return normalSegment; - } - if (columnIndex !== topLeft.col) { - return ""; - } - return range2.extractBorderContent(horizontalBorderIndex); - }); - }; - exports.drawBorderSegments = drawBorderSegments; - var createSeparatorGetter = (dependencies) => { - const { separator: separator2, spanningCellManager, horizontalBorderIndex, rowCount } = dependencies; - return (verticalBorderIndex, columnCount) => { - const inSameRange = spanningCellManager === null || spanningCellManager === void 0 ? void 0 : spanningCellManager.inSameRange; - if (horizontalBorderIndex !== void 0 && inSameRange) { - const topCell = { - col: verticalBorderIndex, - row: horizontalBorderIndex - 1 - }; - const leftCell = { - col: verticalBorderIndex - 1, - row: horizontalBorderIndex - }; - const oppositeCell = { - col: verticalBorderIndex - 1, - row: horizontalBorderIndex - 1 - }; - const currentCell = { - col: verticalBorderIndex, - row: horizontalBorderIndex - }; - const pairs = [ - [oppositeCell, topCell], - [topCell, currentCell], - [currentCell, leftCell], - [leftCell, oppositeCell] - ]; - if (verticalBorderIndex === 0) { - if (inSameRange(currentCell, topCell) && separator2.bodyJoinOuter) { - return separator2.bodyJoinOuter; - } - return separator2.left; - } - if (verticalBorderIndex === columnCount) { - if (inSameRange(oppositeCell, leftCell) && separator2.bodyJoinOuter) { - return separator2.bodyJoinOuter; - } - return separator2.right; - } - if (horizontalBorderIndex === 0) { - if (inSameRange(currentCell, leftCell)) { - return separator2.body; - } - return separator2.join; - } - if (horizontalBorderIndex === rowCount) { - if (inSameRange(topCell, oppositeCell)) { - return separator2.body; - } - return separator2.join; - } - const sameRangeCount = pairs.map((pair) => { - return inSameRange(...pair); - }).filter(Boolean).length; - if (sameRangeCount === 0) { - return separator2.join; - } - if (sameRangeCount === 4) { - return ""; - } - if (sameRangeCount === 2) { - if (inSameRange(...pairs[1]) && inSameRange(...pairs[3]) && separator2.bodyJoinInner) { - return separator2.bodyJoinInner; - } - return separator2.body; - } - if (sameRangeCount === 1) { - if (!separator2.joinRight || !separator2.joinLeft || !separator2.joinUp || !separator2.joinDown) { - throw new Error(`Can not get border separator for position [${horizontalBorderIndex}, ${verticalBorderIndex}]`); - } - if (inSameRange(...pairs[0])) { - return separator2.joinDown; - } - if (inSameRange(...pairs[1])) { - return separator2.joinLeft; - } - if (inSameRange(...pairs[2])) { - return separator2.joinUp; - } - return separator2.joinRight; - } - throw new Error("Invalid case"); - } - if (verticalBorderIndex === 0) { - return separator2.left; - } - if (verticalBorderIndex === columnCount) { - return separator2.right; - } - return separator2.join; - }; - }; - exports.createSeparatorGetter = createSeparatorGetter; - var drawBorder = (columnWidths, parameters) => { - const borderSegments = (0, exports.drawBorderSegments)(columnWidths, parameters); - const { drawVerticalLine, horizontalBorderIndex, spanningCellManager } = parameters; - return (0, drawContent_1.drawContent)({ - contents: borderSegments, - drawSeparator: drawVerticalLine, - elementType: "border", - rowIndex: horizontalBorderIndex, - separatorGetter: (0, exports.createSeparatorGetter)(parameters), - spanningCellManager - }) + "\n"; - }; - exports.drawBorder = drawBorder; - var drawBorderTop = (columnWidths, parameters) => { - const { border } = parameters; - const result = (0, exports.drawBorder)(columnWidths, { - ...parameters, - separator: { - body: border.topBody, - join: border.topJoin, - left: border.topLeft, - right: border.topRight - } - }); - if (result === "\n") { - return ""; - } - return result; - }; - exports.drawBorderTop = drawBorderTop; - var drawBorderJoin = (columnWidths, parameters) => { - const { border } = parameters; - return (0, exports.drawBorder)(columnWidths, { - ...parameters, - separator: { - body: border.joinBody, - bodyJoinInner: border.bodyJoin, - bodyJoinOuter: border.bodyLeft, - join: border.joinJoin, - joinDown: border.joinMiddleDown, - joinLeft: border.joinMiddleLeft, - joinRight: border.joinMiddleRight, - joinUp: border.joinMiddleUp, - left: border.joinLeft, - right: border.joinRight - } - }); - }; - exports.drawBorderJoin = drawBorderJoin; - var drawBorderBottom = (columnWidths, parameters) => { - const { border } = parameters; - return (0, exports.drawBorder)(columnWidths, { - ...parameters, - separator: { - body: border.bottomBody, - join: border.bottomJoin, - left: border.bottomLeft, - right: border.bottomRight - } - }); - }; - exports.drawBorderBottom = drawBorderBottom; - var createTableBorderGetter = (columnWidths, parameters) => { - return (index, size) => { - const drawBorderParameters = { - ...parameters, - horizontalBorderIndex: index - }; - if (index === 0) { - return (0, exports.drawBorderTop)(columnWidths, drawBorderParameters); - } else if (index === size) { - return (0, exports.drawBorderBottom)(columnWidths, drawBorderParameters); - } - return (0, exports.drawBorderJoin)(columnWidths, drawBorderParameters); - }; - }; - exports.createTableBorderGetter = createTableBorderGetter; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/drawRow.js -var require_drawRow = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/drawRow.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.drawRow = void 0; - var drawContent_1 = require_drawContent(); - var drawRow = (row, config3) => { - const { border, drawVerticalLine, rowIndex, spanningCellManager } = config3; - return (0, drawContent_1.drawContent)({ - contents: row, - drawSeparator: drawVerticalLine, - elementType: "cell", - rowIndex, - separatorGetter: (index, columnCount) => { - if (index === 0) { - return border.bodyLeft; - } - if (index === columnCount) { - return border.bodyRight; - } - return border.bodyJoin; - }, - spanningCellManager - }) + "\n"; - }; - exports.drawRow = drawRow; - } -}); - -// node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/runtime/equal.js -var require_equal3 = __commonJS({ - "node_modules/.pnpm/ajv@8.17.1/node_modules/ajv/dist/runtime/equal.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var equal = require_fast_deep_equal(); - equal.code = 'require("ajv/dist/runtime/equal").default'; - exports.default = equal; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/generated/validators.js -var require_validators = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/generated/validators.js"(exports) { - "use strict"; - exports["config.json"] = validate43; - var schema13 = { - "$id": "config.json", - "$schema": "http://json-schema.org/draft-07/schema#", - "type": "object", - "properties": { - "border": { - "$ref": "shared.json#/definitions/borders" - }, - "header": { - "type": "object", - "properties": { - "content": { - "type": "string" - }, - "alignment": { - "$ref": "shared.json#/definitions/alignment" - }, - "wrapWord": { - "type": "boolean" - }, - "truncate": { - "type": "integer" - }, - "paddingLeft": { - "type": "integer" - }, - "paddingRight": { - "type": "integer" - } - }, - "required": ["content"], - "additionalProperties": false - }, - "columns": { - "$ref": "shared.json#/definitions/columns" - }, - "columnDefault": { - "$ref": "shared.json#/definitions/column" - }, - "drawVerticalLine": { - "typeof": "function" - }, - "drawHorizontalLine": { - "typeof": "function" - }, - "singleLine": { - "typeof": "boolean" - }, - "spanningCells": { - "type": "array", - "items": { - "type": "object", - "properties": { - "col": { - "type": "integer", - "minimum": 0 - }, - "row": { - "type": "integer", - "minimum": 0 - }, - "colSpan": { - "type": "integer", - "minimum": 1 - }, - "rowSpan": { - "type": "integer", - "minimum": 1 - }, - "alignment": { - "$ref": "shared.json#/definitions/alignment" - }, - "verticalAlignment": { - "$ref": "shared.json#/definitions/verticalAlignment" - }, - "wrapWord": { - "type": "boolean" - }, - "truncate": { - "type": "integer" - }, - "paddingLeft": { - "type": "integer" - }, - "paddingRight": { - "type": "integer" - } - }, - "required": ["row", "col"], - "additionalProperties": false - } - } - }, - "additionalProperties": false - }; - var schema15 = { - "type": "object", - "properties": { - "topBody": { - "$ref": "#/definitions/border" - }, - "topJoin": { - "$ref": "#/definitions/border" - }, - "topLeft": { - "$ref": "#/definitions/border" - }, - "topRight": { - "$ref": "#/definitions/border" - }, - "bottomBody": { - "$ref": "#/definitions/border" - }, - "bottomJoin": { - "$ref": "#/definitions/border" - }, - "bottomLeft": { - "$ref": "#/definitions/border" - }, - "bottomRight": { - "$ref": "#/definitions/border" - }, - "bodyLeft": { - "$ref": "#/definitions/border" - }, - "bodyRight": { - "$ref": "#/definitions/border" - }, - "bodyJoin": { - "$ref": "#/definitions/border" - }, - "headerJoin": { - "$ref": "#/definitions/border" - }, - "joinBody": { - "$ref": "#/definitions/border" - }, - "joinLeft": { - "$ref": "#/definitions/border" - }, - "joinRight": { - "$ref": "#/definitions/border" - }, - "joinJoin": { - "$ref": "#/definitions/border" - }, - "joinMiddleUp": { - "$ref": "#/definitions/border" - }, - "joinMiddleDown": { - "$ref": "#/definitions/border" - }, - "joinMiddleLeft": { - "$ref": "#/definitions/border" - }, - "joinMiddleRight": { - "$ref": "#/definitions/border" - } - }, - "additionalProperties": false - }; - var func8 = Object.prototype.hasOwnProperty; - function validate46(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { - let vErrors = null; - let errors = 0; - if (typeof data !== "string") { - const err0 = { - instancePath, - schemaPath: "#/type", - keyword: "type", - params: { - type: "string" - }, - message: "must be string" - }; - if (vErrors === null) { - vErrors = [err0]; - } else { - vErrors.push(err0); - } - errors++; - } - validate46.errors = vErrors; - return errors === 0; - } - function validate45(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { - let vErrors = null; - let errors = 0; - if (data && typeof data == "object" && !Array.isArray(data)) { - for (const key0 in data) { - if (!func8.call(schema15.properties, key0)) { - const err0 = { - instancePath, - schemaPath: "#/additionalProperties", - keyword: "additionalProperties", - params: { - additionalProperty: key0 - }, - message: "must NOT have additional properties" - }; - if (vErrors === null) { - vErrors = [err0]; - } else { - vErrors.push(err0); - } - errors++; - } - } - if (data.topBody !== void 0) { - if (!validate46(data.topBody, { - instancePath: instancePath + "/topBody", - parentData: data, - parentDataProperty: "topBody", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.topJoin !== void 0) { - if (!validate46(data.topJoin, { - instancePath: instancePath + "/topJoin", - parentData: data, - parentDataProperty: "topJoin", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.topLeft !== void 0) { - if (!validate46(data.topLeft, { - instancePath: instancePath + "/topLeft", - parentData: data, - parentDataProperty: "topLeft", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.topRight !== void 0) { - if (!validate46(data.topRight, { - instancePath: instancePath + "/topRight", - parentData: data, - parentDataProperty: "topRight", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.bottomBody !== void 0) { - if (!validate46(data.bottomBody, { - instancePath: instancePath + "/bottomBody", - parentData: data, - parentDataProperty: "bottomBody", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.bottomJoin !== void 0) { - if (!validate46(data.bottomJoin, { - instancePath: instancePath + "/bottomJoin", - parentData: data, - parentDataProperty: "bottomJoin", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.bottomLeft !== void 0) { - if (!validate46(data.bottomLeft, { - instancePath: instancePath + "/bottomLeft", - parentData: data, - parentDataProperty: "bottomLeft", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.bottomRight !== void 0) { - if (!validate46(data.bottomRight, { - instancePath: instancePath + "/bottomRight", - parentData: data, - parentDataProperty: "bottomRight", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.bodyLeft !== void 0) { - if (!validate46(data.bodyLeft, { - instancePath: instancePath + "/bodyLeft", - parentData: data, - parentDataProperty: "bodyLeft", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.bodyRight !== void 0) { - if (!validate46(data.bodyRight, { - instancePath: instancePath + "/bodyRight", - parentData: data, - parentDataProperty: "bodyRight", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.bodyJoin !== void 0) { - if (!validate46(data.bodyJoin, { - instancePath: instancePath + "/bodyJoin", - parentData: data, - parentDataProperty: "bodyJoin", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.headerJoin !== void 0) { - if (!validate46(data.headerJoin, { - instancePath: instancePath + "/headerJoin", - parentData: data, - parentDataProperty: "headerJoin", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.joinBody !== void 0) { - if (!validate46(data.joinBody, { - instancePath: instancePath + "/joinBody", - parentData: data, - parentDataProperty: "joinBody", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.joinLeft !== void 0) { - if (!validate46(data.joinLeft, { - instancePath: instancePath + "/joinLeft", - parentData: data, - parentDataProperty: "joinLeft", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.joinRight !== void 0) { - if (!validate46(data.joinRight, { - instancePath: instancePath + "/joinRight", - parentData: data, - parentDataProperty: "joinRight", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.joinJoin !== void 0) { - if (!validate46(data.joinJoin, { - instancePath: instancePath + "/joinJoin", - parentData: data, - parentDataProperty: "joinJoin", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.joinMiddleUp !== void 0) { - if (!validate46(data.joinMiddleUp, { - instancePath: instancePath + "/joinMiddleUp", - parentData: data, - parentDataProperty: "joinMiddleUp", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.joinMiddleDown !== void 0) { - if (!validate46(data.joinMiddleDown, { - instancePath: instancePath + "/joinMiddleDown", - parentData: data, - parentDataProperty: "joinMiddleDown", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.joinMiddleLeft !== void 0) { - if (!validate46(data.joinMiddleLeft, { - instancePath: instancePath + "/joinMiddleLeft", - parentData: data, - parentDataProperty: "joinMiddleLeft", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.joinMiddleRight !== void 0) { - if (!validate46(data.joinMiddleRight, { - instancePath: instancePath + "/joinMiddleRight", - parentData: data, - parentDataProperty: "joinMiddleRight", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - } else { - const err1 = { - instancePath, - schemaPath: "#/type", - keyword: "type", - params: { - type: "object" - }, - message: "must be object" - }; - if (vErrors === null) { - vErrors = [err1]; - } else { - vErrors.push(err1); - } - errors++; - } - validate45.errors = vErrors; - return errors === 0; - } - var schema17 = { - "type": "string", - "enum": ["left", "right", "center", "justify"] - }; - var func0 = require_equal3().default; - function validate68(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { - let vErrors = null; - let errors = 0; - if (typeof data !== "string") { - const err0 = { - instancePath, - schemaPath: "#/type", - keyword: "type", - params: { - type: "string" - }, - message: "must be string" - }; - if (vErrors === null) { - vErrors = [err0]; - } else { - vErrors.push(err0); - } - errors++; - } - if (!(data === "left" || data === "right" || data === "center" || data === "justify")) { - const err1 = { - instancePath, - schemaPath: "#/enum", - keyword: "enum", - params: { - allowedValues: schema17.enum - }, - message: "must be equal to one of the allowed values" - }; - if (vErrors === null) { - vErrors = [err1]; - } else { - vErrors.push(err1); - } - errors++; - } - validate68.errors = vErrors; - return errors === 0; - } - var pattern0 = new RegExp("^[0-9]+$", "u"); - function validate72(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { - let vErrors = null; - let errors = 0; - if (typeof data !== "string") { - const err0 = { - instancePath, - schemaPath: "#/type", - keyword: "type", - params: { - type: "string" - }, - message: "must be string" - }; - if (vErrors === null) { - vErrors = [err0]; - } else { - vErrors.push(err0); - } - errors++; - } - if (!(data === "left" || data === "right" || data === "center" || data === "justify")) { - const err1 = { - instancePath, - schemaPath: "#/enum", - keyword: "enum", - params: { - allowedValues: schema17.enum - }, - message: "must be equal to one of the allowed values" - }; - if (vErrors === null) { - vErrors = [err1]; - } else { - vErrors.push(err1); - } - errors++; - } - validate72.errors = vErrors; - return errors === 0; - } - var schema21 = { - "type": "string", - "enum": ["top", "middle", "bottom"] - }; - function validate74(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { - let vErrors = null; - let errors = 0; - if (typeof data !== "string") { - const err0 = { - instancePath, - schemaPath: "#/type", - keyword: "type", - params: { - type: "string" - }, - message: "must be string" - }; - if (vErrors === null) { - vErrors = [err0]; - } else { - vErrors.push(err0); - } - errors++; - } - if (!(data === "top" || data === "middle" || data === "bottom")) { - const err1 = { - instancePath, - schemaPath: "#/enum", - keyword: "enum", - params: { - allowedValues: schema21.enum - }, - message: "must be equal to one of the allowed values" - }; - if (vErrors === null) { - vErrors = [err1]; - } else { - vErrors.push(err1); - } - errors++; - } - validate74.errors = vErrors; - return errors === 0; - } - function validate71(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { - let vErrors = null; - let errors = 0; - if (data && typeof data == "object" && !Array.isArray(data)) { - for (const key0 in data) { - if (!(key0 === "alignment" || key0 === "verticalAlignment" || key0 === "width" || key0 === "wrapWord" || key0 === "truncate" || key0 === "paddingLeft" || key0 === "paddingRight")) { - const err0 = { - instancePath, - schemaPath: "#/additionalProperties", - keyword: "additionalProperties", - params: { - additionalProperty: key0 - }, - message: "must NOT have additional properties" - }; - if (vErrors === null) { - vErrors = [err0]; - } else { - vErrors.push(err0); - } - errors++; - } - } - if (data.alignment !== void 0) { - if (!validate72(data.alignment, { - instancePath: instancePath + "/alignment", - parentData: data, - parentDataProperty: "alignment", - rootData - })) { - vErrors = vErrors === null ? validate72.errors : vErrors.concat(validate72.errors); - errors = vErrors.length; - } - } - if (data.verticalAlignment !== void 0) { - if (!validate74(data.verticalAlignment, { - instancePath: instancePath + "/verticalAlignment", - parentData: data, - parentDataProperty: "verticalAlignment", - rootData - })) { - vErrors = vErrors === null ? validate74.errors : vErrors.concat(validate74.errors); - errors = vErrors.length; - } - } - if (data.width !== void 0) { - let data2 = data.width; - if (!(typeof data2 == "number" && (!(data2 % 1) && !isNaN(data2)) && isFinite(data2))) { - const err1 = { - instancePath: instancePath + "/width", - schemaPath: "#/properties/width/type", - keyword: "type", - params: { - type: "integer" - }, - message: "must be integer" - }; - if (vErrors === null) { - vErrors = [err1]; - } else { - vErrors.push(err1); - } - errors++; - } - if (typeof data2 == "number" && isFinite(data2)) { - if (data2 < 1 || isNaN(data2)) { - const err2 = { - instancePath: instancePath + "/width", - schemaPath: "#/properties/width/minimum", - keyword: "minimum", - params: { - comparison: ">=", - limit: 1 - }, - message: "must be >= 1" - }; - if (vErrors === null) { - vErrors = [err2]; - } else { - vErrors.push(err2); - } - errors++; - } - } - } - if (data.wrapWord !== void 0) { - if (typeof data.wrapWord !== "boolean") { - const err3 = { - instancePath: instancePath + "/wrapWord", - schemaPath: "#/properties/wrapWord/type", - keyword: "type", - params: { - type: "boolean" - }, - message: "must be boolean" - }; - if (vErrors === null) { - vErrors = [err3]; - } else { - vErrors.push(err3); - } - errors++; - } - } - if (data.truncate !== void 0) { - let data4 = data.truncate; - if (!(typeof data4 == "number" && (!(data4 % 1) && !isNaN(data4)) && isFinite(data4))) { - const err4 = { - instancePath: instancePath + "/truncate", - schemaPath: "#/properties/truncate/type", - keyword: "type", - params: { - type: "integer" - }, - message: "must be integer" - }; - if (vErrors === null) { - vErrors = [err4]; - } else { - vErrors.push(err4); - } - errors++; - } - } - if (data.paddingLeft !== void 0) { - let data5 = data.paddingLeft; - if (!(typeof data5 == "number" && (!(data5 % 1) && !isNaN(data5)) && isFinite(data5))) { - const err5 = { - instancePath: instancePath + "/paddingLeft", - schemaPath: "#/properties/paddingLeft/type", - keyword: "type", - params: { - type: "integer" - }, - message: "must be integer" - }; - if (vErrors === null) { - vErrors = [err5]; - } else { - vErrors.push(err5); - } - errors++; - } - } - if (data.paddingRight !== void 0) { - let data6 = data.paddingRight; - if (!(typeof data6 == "number" && (!(data6 % 1) && !isNaN(data6)) && isFinite(data6))) { - const err6 = { - instancePath: instancePath + "/paddingRight", - schemaPath: "#/properties/paddingRight/type", - keyword: "type", - params: { - type: "integer" - }, - message: "must be integer" - }; - if (vErrors === null) { - vErrors = [err6]; - } else { - vErrors.push(err6); - } - errors++; - } - } - } else { - const err7 = { - instancePath, - schemaPath: "#/type", - keyword: "type", - params: { - type: "object" - }, - message: "must be object" - }; - if (vErrors === null) { - vErrors = [err7]; - } else { - vErrors.push(err7); - } - errors++; - } - validate71.errors = vErrors; - return errors === 0; - } - function validate70(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { - let vErrors = null; - let errors = 0; - const _errs0 = errors; - let valid0 = false; - let passing0 = null; - const _errs1 = errors; - if (data && typeof data == "object" && !Array.isArray(data)) { - for (const key0 in data) { - if (!pattern0.test(key0)) { - const err0 = { - instancePath, - schemaPath: "#/oneOf/0/additionalProperties", - keyword: "additionalProperties", - params: { - additionalProperty: key0 - }, - message: "must NOT have additional properties" - }; - if (vErrors === null) { - vErrors = [err0]; - } else { - vErrors.push(err0); - } - errors++; - } - } - for (const key1 in data) { - if (pattern0.test(key1)) { - if (!validate71(data[key1], { - instancePath: instancePath + "/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), - parentData: data, - parentDataProperty: key1, - rootData - })) { - vErrors = vErrors === null ? validate71.errors : vErrors.concat(validate71.errors); - errors = vErrors.length; - } - } - } - } else { - const err1 = { - instancePath, - schemaPath: "#/oneOf/0/type", - keyword: "type", - params: { - type: "object" - }, - message: "must be object" - }; - if (vErrors === null) { - vErrors = [err1]; - } else { - vErrors.push(err1); - } - errors++; - } - var _valid0 = _errs1 === errors; - if (_valid0) { - valid0 = true; - passing0 = 0; - } - const _errs5 = errors; - if (Array.isArray(data)) { - const len0 = data.length; - for (let i0 = 0; i0 < len0; i0++) { - if (!validate71(data[i0], { - instancePath: instancePath + "/" + i0, - parentData: data, - parentDataProperty: i0, - rootData - })) { - vErrors = vErrors === null ? validate71.errors : vErrors.concat(validate71.errors); - errors = vErrors.length; - } - } - } else { - const err2 = { - instancePath, - schemaPath: "#/oneOf/1/type", - keyword: "type", - params: { - type: "array" - }, - message: "must be array" - }; - if (vErrors === null) { - vErrors = [err2]; - } else { - vErrors.push(err2); - } - errors++; - } - var _valid0 = _errs5 === errors; - if (_valid0 && valid0) { - valid0 = false; - passing0 = [passing0, 1]; - } else { - if (_valid0) { - valid0 = true; - passing0 = 1; - } - } - if (!valid0) { - const err3 = { - instancePath, - schemaPath: "#/oneOf", - keyword: "oneOf", - params: { - passingSchemas: passing0 - }, - message: "must match exactly one schema in oneOf" - }; - if (vErrors === null) { - vErrors = [err3]; - } else { - vErrors.push(err3); - } - errors++; - } else { - errors = _errs0; - if (vErrors !== null) { - if (_errs0) { - vErrors.length = _errs0; - } else { - vErrors = null; - } - } - } - validate70.errors = vErrors; - return errors === 0; - } - function validate79(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { - let vErrors = null; - let errors = 0; - if (data && typeof data == "object" && !Array.isArray(data)) { - for (const key0 in data) { - if (!(key0 === "alignment" || key0 === "verticalAlignment" || key0 === "width" || key0 === "wrapWord" || key0 === "truncate" || key0 === "paddingLeft" || key0 === "paddingRight")) { - const err0 = { - instancePath, - schemaPath: "#/additionalProperties", - keyword: "additionalProperties", - params: { - additionalProperty: key0 - }, - message: "must NOT have additional properties" - }; - if (vErrors === null) { - vErrors = [err0]; - } else { - vErrors.push(err0); - } - errors++; - } - } - if (data.alignment !== void 0) { - if (!validate72(data.alignment, { - instancePath: instancePath + "/alignment", - parentData: data, - parentDataProperty: "alignment", - rootData - })) { - vErrors = vErrors === null ? validate72.errors : vErrors.concat(validate72.errors); - errors = vErrors.length; - } - } - if (data.verticalAlignment !== void 0) { - if (!validate74(data.verticalAlignment, { - instancePath: instancePath + "/verticalAlignment", - parentData: data, - parentDataProperty: "verticalAlignment", - rootData - })) { - vErrors = vErrors === null ? validate74.errors : vErrors.concat(validate74.errors); - errors = vErrors.length; - } - } - if (data.width !== void 0) { - let data2 = data.width; - if (!(typeof data2 == "number" && (!(data2 % 1) && !isNaN(data2)) && isFinite(data2))) { - const err1 = { - instancePath: instancePath + "/width", - schemaPath: "#/properties/width/type", - keyword: "type", - params: { - type: "integer" - }, - message: "must be integer" - }; - if (vErrors === null) { - vErrors = [err1]; - } else { - vErrors.push(err1); - } - errors++; - } - if (typeof data2 == "number" && isFinite(data2)) { - if (data2 < 1 || isNaN(data2)) { - const err2 = { - instancePath: instancePath + "/width", - schemaPath: "#/properties/width/minimum", - keyword: "minimum", - params: { - comparison: ">=", - limit: 1 - }, - message: "must be >= 1" - }; - if (vErrors === null) { - vErrors = [err2]; - } else { - vErrors.push(err2); - } - errors++; - } - } - } - if (data.wrapWord !== void 0) { - if (typeof data.wrapWord !== "boolean") { - const err3 = { - instancePath: instancePath + "/wrapWord", - schemaPath: "#/properties/wrapWord/type", - keyword: "type", - params: { - type: "boolean" - }, - message: "must be boolean" - }; - if (vErrors === null) { - vErrors = [err3]; - } else { - vErrors.push(err3); - } - errors++; - } - } - if (data.truncate !== void 0) { - let data4 = data.truncate; - if (!(typeof data4 == "number" && (!(data4 % 1) && !isNaN(data4)) && isFinite(data4))) { - const err4 = { - instancePath: instancePath + "/truncate", - schemaPath: "#/properties/truncate/type", - keyword: "type", - params: { - type: "integer" - }, - message: "must be integer" - }; - if (vErrors === null) { - vErrors = [err4]; - } else { - vErrors.push(err4); - } - errors++; - } - } - if (data.paddingLeft !== void 0) { - let data5 = data.paddingLeft; - if (!(typeof data5 == "number" && (!(data5 % 1) && !isNaN(data5)) && isFinite(data5))) { - const err5 = { - instancePath: instancePath + "/paddingLeft", - schemaPath: "#/properties/paddingLeft/type", - keyword: "type", - params: { - type: "integer" - }, - message: "must be integer" - }; - if (vErrors === null) { - vErrors = [err5]; - } else { - vErrors.push(err5); - } - errors++; - } - } - if (data.paddingRight !== void 0) { - let data6 = data.paddingRight; - if (!(typeof data6 == "number" && (!(data6 % 1) && !isNaN(data6)) && isFinite(data6))) { - const err6 = { - instancePath: instancePath + "/paddingRight", - schemaPath: "#/properties/paddingRight/type", - keyword: "type", - params: { - type: "integer" - }, - message: "must be integer" - }; - if (vErrors === null) { - vErrors = [err6]; - } else { - vErrors.push(err6); - } - errors++; - } - } - } else { - const err7 = { - instancePath, - schemaPath: "#/type", - keyword: "type", - params: { - type: "object" - }, - message: "must be object" - }; - if (vErrors === null) { - vErrors = [err7]; - } else { - vErrors.push(err7); - } - errors++; - } - validate79.errors = vErrors; - return errors === 0; - } - function validate84(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { - let vErrors = null; - let errors = 0; - if (typeof data !== "string") { - const err0 = { - instancePath, - schemaPath: "#/type", - keyword: "type", - params: { - type: "string" - }, - message: "must be string" - }; - if (vErrors === null) { - vErrors = [err0]; - } else { - vErrors.push(err0); - } - errors++; - } - if (!(data === "top" || data === "middle" || data === "bottom")) { - const err1 = { - instancePath, - schemaPath: "#/enum", - keyword: "enum", - params: { - allowedValues: schema21.enum - }, - message: "must be equal to one of the allowed values" - }; - if (vErrors === null) { - vErrors = [err1]; - } else { - vErrors.push(err1); - } - errors++; - } - validate84.errors = vErrors; - return errors === 0; - } - function validate43(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { - ; - let vErrors = null; - let errors = 0; - if (data && typeof data == "object" && !Array.isArray(data)) { - for (const key0 in data) { - if (!(key0 === "border" || key0 === "header" || key0 === "columns" || key0 === "columnDefault" || key0 === "drawVerticalLine" || key0 === "drawHorizontalLine" || key0 === "singleLine" || key0 === "spanningCells")) { - const err0 = { - instancePath, - schemaPath: "#/additionalProperties", - keyword: "additionalProperties", - params: { - additionalProperty: key0 - }, - message: "must NOT have additional properties" - }; - if (vErrors === null) { - vErrors = [err0]; - } else { - vErrors.push(err0); - } - errors++; - } - } - if (data.border !== void 0) { - if (!validate45(data.border, { - instancePath: instancePath + "/border", - parentData: data, - parentDataProperty: "border", - rootData - })) { - vErrors = vErrors === null ? validate45.errors : vErrors.concat(validate45.errors); - errors = vErrors.length; - } - } - if (data.header !== void 0) { - let data1 = data.header; - if (data1 && typeof data1 == "object" && !Array.isArray(data1)) { - if (data1.content === void 0) { - const err1 = { - instancePath: instancePath + "/header", - schemaPath: "#/properties/header/required", - keyword: "required", - params: { - missingProperty: "content" - }, - message: "must have required property 'content'" - }; - if (vErrors === null) { - vErrors = [err1]; - } else { - vErrors.push(err1); - } - errors++; - } - for (const key1 in data1) { - if (!(key1 === "content" || key1 === "alignment" || key1 === "wrapWord" || key1 === "truncate" || key1 === "paddingLeft" || key1 === "paddingRight")) { - const err2 = { - instancePath: instancePath + "/header", - schemaPath: "#/properties/header/additionalProperties", - keyword: "additionalProperties", - params: { - additionalProperty: key1 - }, - message: "must NOT have additional properties" - }; - if (vErrors === null) { - vErrors = [err2]; - } else { - vErrors.push(err2); - } - errors++; - } - } - if (data1.content !== void 0) { - if (typeof data1.content !== "string") { - const err3 = { - instancePath: instancePath + "/header/content", - schemaPath: "#/properties/header/properties/content/type", - keyword: "type", - params: { - type: "string" - }, - message: "must be string" - }; - if (vErrors === null) { - vErrors = [err3]; - } else { - vErrors.push(err3); - } - errors++; - } - } - if (data1.alignment !== void 0) { - if (!validate68(data1.alignment, { - instancePath: instancePath + "/header/alignment", - parentData: data1, - parentDataProperty: "alignment", - rootData - })) { - vErrors = vErrors === null ? validate68.errors : vErrors.concat(validate68.errors); - errors = vErrors.length; - } - } - if (data1.wrapWord !== void 0) { - if (typeof data1.wrapWord !== "boolean") { - const err4 = { - instancePath: instancePath + "/header/wrapWord", - schemaPath: "#/properties/header/properties/wrapWord/type", - keyword: "type", - params: { - type: "boolean" - }, - message: "must be boolean" - }; - if (vErrors === null) { - vErrors = [err4]; - } else { - vErrors.push(err4); - } - errors++; - } - } - if (data1.truncate !== void 0) { - let data5 = data1.truncate; - if (!(typeof data5 == "number" && (!(data5 % 1) && !isNaN(data5)) && isFinite(data5))) { - const err5 = { - instancePath: instancePath + "/header/truncate", - schemaPath: "#/properties/header/properties/truncate/type", - keyword: "type", - params: { - type: "integer" - }, - message: "must be integer" - }; - if (vErrors === null) { - vErrors = [err5]; - } else { - vErrors.push(err5); - } - errors++; - } - } - if (data1.paddingLeft !== void 0) { - let data6 = data1.paddingLeft; - if (!(typeof data6 == "number" && (!(data6 % 1) && !isNaN(data6)) && isFinite(data6))) { - const err6 = { - instancePath: instancePath + "/header/paddingLeft", - schemaPath: "#/properties/header/properties/paddingLeft/type", - keyword: "type", - params: { - type: "integer" - }, - message: "must be integer" - }; - if (vErrors === null) { - vErrors = [err6]; - } else { - vErrors.push(err6); - } - errors++; - } - } - if (data1.paddingRight !== void 0) { - let data7 = data1.paddingRight; - if (!(typeof data7 == "number" && (!(data7 % 1) && !isNaN(data7)) && isFinite(data7))) { - const err7 = { - instancePath: instancePath + "/header/paddingRight", - schemaPath: "#/properties/header/properties/paddingRight/type", - keyword: "type", - params: { - type: "integer" - }, - message: "must be integer" - }; - if (vErrors === null) { - vErrors = [err7]; - } else { - vErrors.push(err7); - } - errors++; - } - } - } else { - const err8 = { - instancePath: instancePath + "/header", - schemaPath: "#/properties/header/type", - keyword: "type", - params: { - type: "object" - }, - message: "must be object" - }; - if (vErrors === null) { - vErrors = [err8]; - } else { - vErrors.push(err8); - } - errors++; - } - } - if (data.columns !== void 0) { - if (!validate70(data.columns, { - instancePath: instancePath + "/columns", - parentData: data, - parentDataProperty: "columns", - rootData - })) { - vErrors = vErrors === null ? validate70.errors : vErrors.concat(validate70.errors); - errors = vErrors.length; - } - } - if (data.columnDefault !== void 0) { - if (!validate79(data.columnDefault, { - instancePath: instancePath + "/columnDefault", - parentData: data, - parentDataProperty: "columnDefault", - rootData - })) { - vErrors = vErrors === null ? validate79.errors : vErrors.concat(validate79.errors); - errors = vErrors.length; - } - } - if (data.drawVerticalLine !== void 0) { - if (typeof data.drawVerticalLine != "function") { - const err9 = { - instancePath: instancePath + "/drawVerticalLine", - schemaPath: "#/properties/drawVerticalLine/typeof", - keyword: "typeof", - params: {}, - message: 'must pass "typeof" keyword validation' - }; - if (vErrors === null) { - vErrors = [err9]; - } else { - vErrors.push(err9); - } - errors++; - } - } - if (data.drawHorizontalLine !== void 0) { - if (typeof data.drawHorizontalLine != "function") { - const err10 = { - instancePath: instancePath + "/drawHorizontalLine", - schemaPath: "#/properties/drawHorizontalLine/typeof", - keyword: "typeof", - params: {}, - message: 'must pass "typeof" keyword validation' - }; - if (vErrors === null) { - vErrors = [err10]; - } else { - vErrors.push(err10); - } - errors++; - } - } - if (data.singleLine !== void 0) { - if (typeof data.singleLine != "boolean") { - const err11 = { - instancePath: instancePath + "/singleLine", - schemaPath: "#/properties/singleLine/typeof", - keyword: "typeof", - params: {}, - message: 'must pass "typeof" keyword validation' - }; - if (vErrors === null) { - vErrors = [err11]; - } else { - vErrors.push(err11); - } - errors++; - } - } - if (data.spanningCells !== void 0) { - let data13 = data.spanningCells; - if (Array.isArray(data13)) { - const len0 = data13.length; - for (let i0 = 0; i0 < len0; i0++) { - let data14 = data13[i0]; - if (data14 && typeof data14 == "object" && !Array.isArray(data14)) { - if (data14.row === void 0) { - const err12 = { - instancePath: instancePath + "/spanningCells/" + i0, - schemaPath: "#/properties/spanningCells/items/required", - keyword: "required", - params: { - missingProperty: "row" - }, - message: "must have required property 'row'" - }; - if (vErrors === null) { - vErrors = [err12]; - } else { - vErrors.push(err12); - } - errors++; - } - if (data14.col === void 0) { - const err13 = { - instancePath: instancePath + "/spanningCells/" + i0, - schemaPath: "#/properties/spanningCells/items/required", - keyword: "required", - params: { - missingProperty: "col" - }, - message: "must have required property 'col'" - }; - if (vErrors === null) { - vErrors = [err13]; - } else { - vErrors.push(err13); - } - errors++; - } - for (const key2 in data14) { - if (!func8.call(schema13.properties.spanningCells.items.properties, key2)) { - const err14 = { - instancePath: instancePath + "/spanningCells/" + i0, - schemaPath: "#/properties/spanningCells/items/additionalProperties", - keyword: "additionalProperties", - params: { - additionalProperty: key2 - }, - message: "must NOT have additional properties" - }; - if (vErrors === null) { - vErrors = [err14]; - } else { - vErrors.push(err14); - } - errors++; - } - } - if (data14.col !== void 0) { - let data15 = data14.col; - if (!(typeof data15 == "number" && (!(data15 % 1) && !isNaN(data15)) && isFinite(data15))) { - const err15 = { - instancePath: instancePath + "/spanningCells/" + i0 + "/col", - schemaPath: "#/properties/spanningCells/items/properties/col/type", - keyword: "type", - params: { - type: "integer" - }, - message: "must be integer" - }; - if (vErrors === null) { - vErrors = [err15]; - } else { - vErrors.push(err15); - } - errors++; - } - if (typeof data15 == "number" && isFinite(data15)) { - if (data15 < 0 || isNaN(data15)) { - const err16 = { - instancePath: instancePath + "/spanningCells/" + i0 + "/col", - schemaPath: "#/properties/spanningCells/items/properties/col/minimum", - keyword: "minimum", - params: { - comparison: ">=", - limit: 0 - }, - message: "must be >= 0" - }; - if (vErrors === null) { - vErrors = [err16]; - } else { - vErrors.push(err16); - } - errors++; - } - } - } - if (data14.row !== void 0) { - let data16 = data14.row; - if (!(typeof data16 == "number" && (!(data16 % 1) && !isNaN(data16)) && isFinite(data16))) { - const err17 = { - instancePath: instancePath + "/spanningCells/" + i0 + "/row", - schemaPath: "#/properties/spanningCells/items/properties/row/type", - keyword: "type", - params: { - type: "integer" - }, - message: "must be integer" - }; - if (vErrors === null) { - vErrors = [err17]; - } else { - vErrors.push(err17); - } - errors++; - } - if (typeof data16 == "number" && isFinite(data16)) { - if (data16 < 0 || isNaN(data16)) { - const err18 = { - instancePath: instancePath + "/spanningCells/" + i0 + "/row", - schemaPath: "#/properties/spanningCells/items/properties/row/minimum", - keyword: "minimum", - params: { - comparison: ">=", - limit: 0 - }, - message: "must be >= 0" - }; - if (vErrors === null) { - vErrors = [err18]; - } else { - vErrors.push(err18); - } - errors++; - } - } - } - if (data14.colSpan !== void 0) { - let data17 = data14.colSpan; - if (!(typeof data17 == "number" && (!(data17 % 1) && !isNaN(data17)) && isFinite(data17))) { - const err19 = { - instancePath: instancePath + "/spanningCells/" + i0 + "/colSpan", - schemaPath: "#/properties/spanningCells/items/properties/colSpan/type", - keyword: "type", - params: { - type: "integer" - }, - message: "must be integer" - }; - if (vErrors === null) { - vErrors = [err19]; - } else { - vErrors.push(err19); - } - errors++; - } - if (typeof data17 == "number" && isFinite(data17)) { - if (data17 < 1 || isNaN(data17)) { - const err20 = { - instancePath: instancePath + "/spanningCells/" + i0 + "/colSpan", - schemaPath: "#/properties/spanningCells/items/properties/colSpan/minimum", - keyword: "minimum", - params: { - comparison: ">=", - limit: 1 - }, - message: "must be >= 1" - }; - if (vErrors === null) { - vErrors = [err20]; - } else { - vErrors.push(err20); - } - errors++; - } - } - } - if (data14.rowSpan !== void 0) { - let data18 = data14.rowSpan; - if (!(typeof data18 == "number" && (!(data18 % 1) && !isNaN(data18)) && isFinite(data18))) { - const err21 = { - instancePath: instancePath + "/spanningCells/" + i0 + "/rowSpan", - schemaPath: "#/properties/spanningCells/items/properties/rowSpan/type", - keyword: "type", - params: { - type: "integer" - }, - message: "must be integer" - }; - if (vErrors === null) { - vErrors = [err21]; - } else { - vErrors.push(err21); - } - errors++; - } - if (typeof data18 == "number" && isFinite(data18)) { - if (data18 < 1 || isNaN(data18)) { - const err22 = { - instancePath: instancePath + "/spanningCells/" + i0 + "/rowSpan", - schemaPath: "#/properties/spanningCells/items/properties/rowSpan/minimum", - keyword: "minimum", - params: { - comparison: ">=", - limit: 1 - }, - message: "must be >= 1" - }; - if (vErrors === null) { - vErrors = [err22]; - } else { - vErrors.push(err22); - } - errors++; - } - } - } - if (data14.alignment !== void 0) { - if (!validate68(data14.alignment, { - instancePath: instancePath + "/spanningCells/" + i0 + "/alignment", - parentData: data14, - parentDataProperty: "alignment", - rootData - })) { - vErrors = vErrors === null ? validate68.errors : vErrors.concat(validate68.errors); - errors = vErrors.length; - } - } - if (data14.verticalAlignment !== void 0) { - if (!validate84(data14.verticalAlignment, { - instancePath: instancePath + "/spanningCells/" + i0 + "/verticalAlignment", - parentData: data14, - parentDataProperty: "verticalAlignment", - rootData - })) { - vErrors = vErrors === null ? validate84.errors : vErrors.concat(validate84.errors); - errors = vErrors.length; - } - } - if (data14.wrapWord !== void 0) { - if (typeof data14.wrapWord !== "boolean") { - const err23 = { - instancePath: instancePath + "/spanningCells/" + i0 + "/wrapWord", - schemaPath: "#/properties/spanningCells/items/properties/wrapWord/type", - keyword: "type", - params: { - type: "boolean" - }, - message: "must be boolean" - }; - if (vErrors === null) { - vErrors = [err23]; - } else { - vErrors.push(err23); - } - errors++; - } - } - if (data14.truncate !== void 0) { - let data22 = data14.truncate; - if (!(typeof data22 == "number" && (!(data22 % 1) && !isNaN(data22)) && isFinite(data22))) { - const err24 = { - instancePath: instancePath + "/spanningCells/" + i0 + "/truncate", - schemaPath: "#/properties/spanningCells/items/properties/truncate/type", - keyword: "type", - params: { - type: "integer" - }, - message: "must be integer" - }; - if (vErrors === null) { - vErrors = [err24]; - } else { - vErrors.push(err24); - } - errors++; - } - } - if (data14.paddingLeft !== void 0) { - let data23 = data14.paddingLeft; - if (!(typeof data23 == "number" && (!(data23 % 1) && !isNaN(data23)) && isFinite(data23))) { - const err25 = { - instancePath: instancePath + "/spanningCells/" + i0 + "/paddingLeft", - schemaPath: "#/properties/spanningCells/items/properties/paddingLeft/type", - keyword: "type", - params: { - type: "integer" - }, - message: "must be integer" - }; - if (vErrors === null) { - vErrors = [err25]; - } else { - vErrors.push(err25); - } - errors++; - } - } - if (data14.paddingRight !== void 0) { - let data24 = data14.paddingRight; - if (!(typeof data24 == "number" && (!(data24 % 1) && !isNaN(data24)) && isFinite(data24))) { - const err26 = { - instancePath: instancePath + "/spanningCells/" + i0 + "/paddingRight", - schemaPath: "#/properties/spanningCells/items/properties/paddingRight/type", - keyword: "type", - params: { - type: "integer" - }, - message: "must be integer" - }; - if (vErrors === null) { - vErrors = [err26]; - } else { - vErrors.push(err26); - } - errors++; - } - } - } else { - const err27 = { - instancePath: instancePath + "/spanningCells/" + i0, - schemaPath: "#/properties/spanningCells/items/type", - keyword: "type", - params: { - type: "object" - }, - message: "must be object" - }; - if (vErrors === null) { - vErrors = [err27]; - } else { - vErrors.push(err27); - } - errors++; - } - } - } else { - const err28 = { - instancePath: instancePath + "/spanningCells", - schemaPath: "#/properties/spanningCells/type", - keyword: "type", - params: { - type: "array" - }, - message: "must be array" - }; - if (vErrors === null) { - vErrors = [err28]; - } else { - vErrors.push(err28); - } - errors++; - } - } - } else { - const err29 = { - instancePath, - schemaPath: "#/type", - keyword: "type", - params: { - type: "object" - }, - message: "must be object" - }; - if (vErrors === null) { - vErrors = [err29]; - } else { - vErrors.push(err29); - } - errors++; - } - validate43.errors = vErrors; - return errors === 0; - } - exports["streamConfig.json"] = validate86; - function validate87(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { - let vErrors = null; - let errors = 0; - if (data && typeof data == "object" && !Array.isArray(data)) { - for (const key0 in data) { - if (!func8.call(schema15.properties, key0)) { - const err0 = { - instancePath, - schemaPath: "#/additionalProperties", - keyword: "additionalProperties", - params: { - additionalProperty: key0 - }, - message: "must NOT have additional properties" - }; - if (vErrors === null) { - vErrors = [err0]; - } else { - vErrors.push(err0); - } - errors++; - } - } - if (data.topBody !== void 0) { - if (!validate46(data.topBody, { - instancePath: instancePath + "/topBody", - parentData: data, - parentDataProperty: "topBody", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.topJoin !== void 0) { - if (!validate46(data.topJoin, { - instancePath: instancePath + "/topJoin", - parentData: data, - parentDataProperty: "topJoin", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.topLeft !== void 0) { - if (!validate46(data.topLeft, { - instancePath: instancePath + "/topLeft", - parentData: data, - parentDataProperty: "topLeft", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.topRight !== void 0) { - if (!validate46(data.topRight, { - instancePath: instancePath + "/topRight", - parentData: data, - parentDataProperty: "topRight", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.bottomBody !== void 0) { - if (!validate46(data.bottomBody, { - instancePath: instancePath + "/bottomBody", - parentData: data, - parentDataProperty: "bottomBody", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.bottomJoin !== void 0) { - if (!validate46(data.bottomJoin, { - instancePath: instancePath + "/bottomJoin", - parentData: data, - parentDataProperty: "bottomJoin", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.bottomLeft !== void 0) { - if (!validate46(data.bottomLeft, { - instancePath: instancePath + "/bottomLeft", - parentData: data, - parentDataProperty: "bottomLeft", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.bottomRight !== void 0) { - if (!validate46(data.bottomRight, { - instancePath: instancePath + "/bottomRight", - parentData: data, - parentDataProperty: "bottomRight", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.bodyLeft !== void 0) { - if (!validate46(data.bodyLeft, { - instancePath: instancePath + "/bodyLeft", - parentData: data, - parentDataProperty: "bodyLeft", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.bodyRight !== void 0) { - if (!validate46(data.bodyRight, { - instancePath: instancePath + "/bodyRight", - parentData: data, - parentDataProperty: "bodyRight", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.bodyJoin !== void 0) { - if (!validate46(data.bodyJoin, { - instancePath: instancePath + "/bodyJoin", - parentData: data, - parentDataProperty: "bodyJoin", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.headerJoin !== void 0) { - if (!validate46(data.headerJoin, { - instancePath: instancePath + "/headerJoin", - parentData: data, - parentDataProperty: "headerJoin", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.joinBody !== void 0) { - if (!validate46(data.joinBody, { - instancePath: instancePath + "/joinBody", - parentData: data, - parentDataProperty: "joinBody", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.joinLeft !== void 0) { - if (!validate46(data.joinLeft, { - instancePath: instancePath + "/joinLeft", - parentData: data, - parentDataProperty: "joinLeft", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.joinRight !== void 0) { - if (!validate46(data.joinRight, { - instancePath: instancePath + "/joinRight", - parentData: data, - parentDataProperty: "joinRight", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.joinJoin !== void 0) { - if (!validate46(data.joinJoin, { - instancePath: instancePath + "/joinJoin", - parentData: data, - parentDataProperty: "joinJoin", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.joinMiddleUp !== void 0) { - if (!validate46(data.joinMiddleUp, { - instancePath: instancePath + "/joinMiddleUp", - parentData: data, - parentDataProperty: "joinMiddleUp", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.joinMiddleDown !== void 0) { - if (!validate46(data.joinMiddleDown, { - instancePath: instancePath + "/joinMiddleDown", - parentData: data, - parentDataProperty: "joinMiddleDown", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.joinMiddleLeft !== void 0) { - if (!validate46(data.joinMiddleLeft, { - instancePath: instancePath + "/joinMiddleLeft", - parentData: data, - parentDataProperty: "joinMiddleLeft", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - if (data.joinMiddleRight !== void 0) { - if (!validate46(data.joinMiddleRight, { - instancePath: instancePath + "/joinMiddleRight", - parentData: data, - parentDataProperty: "joinMiddleRight", - rootData - })) { - vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); - errors = vErrors.length; - } - } - } else { - const err1 = { - instancePath, - schemaPath: "#/type", - keyword: "type", - params: { - type: "object" - }, - message: "must be object" - }; - if (vErrors === null) { - vErrors = [err1]; - } else { - vErrors.push(err1); - } - errors++; - } - validate87.errors = vErrors; - return errors === 0; - } - function validate109(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { - let vErrors = null; - let errors = 0; - const _errs0 = errors; - let valid0 = false; - let passing0 = null; - const _errs1 = errors; - if (data && typeof data == "object" && !Array.isArray(data)) { - for (const key0 in data) { - if (!pattern0.test(key0)) { - const err0 = { - instancePath, - schemaPath: "#/oneOf/0/additionalProperties", - keyword: "additionalProperties", - params: { - additionalProperty: key0 - }, - message: "must NOT have additional properties" - }; - if (vErrors === null) { - vErrors = [err0]; - } else { - vErrors.push(err0); - } - errors++; - } - } - for (const key1 in data) { - if (pattern0.test(key1)) { - if (!validate71(data[key1], { - instancePath: instancePath + "/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), - parentData: data, - parentDataProperty: key1, - rootData - })) { - vErrors = vErrors === null ? validate71.errors : vErrors.concat(validate71.errors); - errors = vErrors.length; - } - } - } - } else { - const err1 = { - instancePath, - schemaPath: "#/oneOf/0/type", - keyword: "type", - params: { - type: "object" - }, - message: "must be object" - }; - if (vErrors === null) { - vErrors = [err1]; - } else { - vErrors.push(err1); - } - errors++; - } - var _valid0 = _errs1 === errors; - if (_valid0) { - valid0 = true; - passing0 = 0; - } - const _errs5 = errors; - if (Array.isArray(data)) { - const len0 = data.length; - for (let i0 = 0; i0 < len0; i0++) { - if (!validate71(data[i0], { - instancePath: instancePath + "/" + i0, - parentData: data, - parentDataProperty: i0, - rootData - })) { - vErrors = vErrors === null ? validate71.errors : vErrors.concat(validate71.errors); - errors = vErrors.length; - } - } - } else { - const err2 = { - instancePath, - schemaPath: "#/oneOf/1/type", - keyword: "type", - params: { - type: "array" - }, - message: "must be array" - }; - if (vErrors === null) { - vErrors = [err2]; - } else { - vErrors.push(err2); - } - errors++; - } - var _valid0 = _errs5 === errors; - if (_valid0 && valid0) { - valid0 = false; - passing0 = [passing0, 1]; - } else { - if (_valid0) { - valid0 = true; - passing0 = 1; - } - } - if (!valid0) { - const err3 = { - instancePath, - schemaPath: "#/oneOf", - keyword: "oneOf", - params: { - passingSchemas: passing0 - }, - message: "must match exactly one schema in oneOf" - }; - if (vErrors === null) { - vErrors = [err3]; - } else { - vErrors.push(err3); - } - errors++; - } else { - errors = _errs0; - if (vErrors !== null) { - if (_errs0) { - vErrors.length = _errs0; - } else { - vErrors = null; - } - } - } - validate109.errors = vErrors; - return errors === 0; - } - function validate113(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { - let vErrors = null; - let errors = 0; - if (data && typeof data == "object" && !Array.isArray(data)) { - for (const key0 in data) { - if (!(key0 === "alignment" || key0 === "verticalAlignment" || key0 === "width" || key0 === "wrapWord" || key0 === "truncate" || key0 === "paddingLeft" || key0 === "paddingRight")) { - const err0 = { - instancePath, - schemaPath: "#/additionalProperties", - keyword: "additionalProperties", - params: { - additionalProperty: key0 - }, - message: "must NOT have additional properties" - }; - if (vErrors === null) { - vErrors = [err0]; - } else { - vErrors.push(err0); - } - errors++; - } - } - if (data.alignment !== void 0) { - if (!validate72(data.alignment, { - instancePath: instancePath + "/alignment", - parentData: data, - parentDataProperty: "alignment", - rootData - })) { - vErrors = vErrors === null ? validate72.errors : vErrors.concat(validate72.errors); - errors = vErrors.length; - } - } - if (data.verticalAlignment !== void 0) { - if (!validate74(data.verticalAlignment, { - instancePath: instancePath + "/verticalAlignment", - parentData: data, - parentDataProperty: "verticalAlignment", - rootData - })) { - vErrors = vErrors === null ? validate74.errors : vErrors.concat(validate74.errors); - errors = vErrors.length; - } - } - if (data.width !== void 0) { - let data2 = data.width; - if (!(typeof data2 == "number" && (!(data2 % 1) && !isNaN(data2)) && isFinite(data2))) { - const err1 = { - instancePath: instancePath + "/width", - schemaPath: "#/properties/width/type", - keyword: "type", - params: { - type: "integer" - }, - message: "must be integer" - }; - if (vErrors === null) { - vErrors = [err1]; - } else { - vErrors.push(err1); - } - errors++; - } - if (typeof data2 == "number" && isFinite(data2)) { - if (data2 < 1 || isNaN(data2)) { - const err2 = { - instancePath: instancePath + "/width", - schemaPath: "#/properties/width/minimum", - keyword: "minimum", - params: { - comparison: ">=", - limit: 1 - }, - message: "must be >= 1" - }; - if (vErrors === null) { - vErrors = [err2]; - } else { - vErrors.push(err2); - } - errors++; - } - } - } - if (data.wrapWord !== void 0) { - if (typeof data.wrapWord !== "boolean") { - const err3 = { - instancePath: instancePath + "/wrapWord", - schemaPath: "#/properties/wrapWord/type", - keyword: "type", - params: { - type: "boolean" - }, - message: "must be boolean" - }; - if (vErrors === null) { - vErrors = [err3]; - } else { - vErrors.push(err3); - } - errors++; - } - } - if (data.truncate !== void 0) { - let data4 = data.truncate; - if (!(typeof data4 == "number" && (!(data4 % 1) && !isNaN(data4)) && isFinite(data4))) { - const err4 = { - instancePath: instancePath + "/truncate", - schemaPath: "#/properties/truncate/type", - keyword: "type", - params: { - type: "integer" - }, - message: "must be integer" - }; - if (vErrors === null) { - vErrors = [err4]; - } else { - vErrors.push(err4); - } - errors++; - } - } - if (data.paddingLeft !== void 0) { - let data5 = data.paddingLeft; - if (!(typeof data5 == "number" && (!(data5 % 1) && !isNaN(data5)) && isFinite(data5))) { - const err5 = { - instancePath: instancePath + "/paddingLeft", - schemaPath: "#/properties/paddingLeft/type", - keyword: "type", - params: { - type: "integer" - }, - message: "must be integer" - }; - if (vErrors === null) { - vErrors = [err5]; - } else { - vErrors.push(err5); - } - errors++; - } - } - if (data.paddingRight !== void 0) { - let data6 = data.paddingRight; - if (!(typeof data6 == "number" && (!(data6 % 1) && !isNaN(data6)) && isFinite(data6))) { - const err6 = { - instancePath: instancePath + "/paddingRight", - schemaPath: "#/properties/paddingRight/type", - keyword: "type", - params: { - type: "integer" - }, - message: "must be integer" - }; - if (vErrors === null) { - vErrors = [err6]; - } else { - vErrors.push(err6); - } - errors++; - } - } - } else { - const err7 = { - instancePath, - schemaPath: "#/type", - keyword: "type", - params: { - type: "object" - }, - message: "must be object" - }; - if (vErrors === null) { - vErrors = [err7]; - } else { - vErrors.push(err7); - } - errors++; - } - validate113.errors = vErrors; - return errors === 0; - } - function validate86(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) { - ; - let vErrors = null; - let errors = 0; - if (data && typeof data == "object" && !Array.isArray(data)) { - if (data.columnDefault === void 0) { - const err0 = { - instancePath, - schemaPath: "#/required", - keyword: "required", - params: { - missingProperty: "columnDefault" - }, - message: "must have required property 'columnDefault'" - }; - if (vErrors === null) { - vErrors = [err0]; - } else { - vErrors.push(err0); - } - errors++; - } - if (data.columnCount === void 0) { - const err1 = { - instancePath, - schemaPath: "#/required", - keyword: "required", - params: { - missingProperty: "columnCount" - }, - message: "must have required property 'columnCount'" - }; - if (vErrors === null) { - vErrors = [err1]; - } else { - vErrors.push(err1); - } - errors++; - } - for (const key0 in data) { - if (!(key0 === "border" || key0 === "columns" || key0 === "columnDefault" || key0 === "columnCount" || key0 === "drawVerticalLine")) { - const err2 = { - instancePath, - schemaPath: "#/additionalProperties", - keyword: "additionalProperties", - params: { - additionalProperty: key0 - }, - message: "must NOT have additional properties" - }; - if (vErrors === null) { - vErrors = [err2]; - } else { - vErrors.push(err2); - } - errors++; - } - } - if (data.border !== void 0) { - if (!validate87(data.border, { - instancePath: instancePath + "/border", - parentData: data, - parentDataProperty: "border", - rootData - })) { - vErrors = vErrors === null ? validate87.errors : vErrors.concat(validate87.errors); - errors = vErrors.length; - } - } - if (data.columns !== void 0) { - if (!validate109(data.columns, { - instancePath: instancePath + "/columns", - parentData: data, - parentDataProperty: "columns", - rootData - })) { - vErrors = vErrors === null ? validate109.errors : vErrors.concat(validate109.errors); - errors = vErrors.length; - } - } - if (data.columnDefault !== void 0) { - if (!validate113(data.columnDefault, { - instancePath: instancePath + "/columnDefault", - parentData: data, - parentDataProperty: "columnDefault", - rootData - })) { - vErrors = vErrors === null ? validate113.errors : vErrors.concat(validate113.errors); - errors = vErrors.length; - } - } - if (data.columnCount !== void 0) { - let data3 = data.columnCount; - if (!(typeof data3 == "number" && (!(data3 % 1) && !isNaN(data3)) && isFinite(data3))) { - const err3 = { - instancePath: instancePath + "/columnCount", - schemaPath: "#/properties/columnCount/type", - keyword: "type", - params: { - type: "integer" - }, - message: "must be integer" - }; - if (vErrors === null) { - vErrors = [err3]; - } else { - vErrors.push(err3); - } - errors++; - } - if (typeof data3 == "number" && isFinite(data3)) { - if (data3 < 1 || isNaN(data3)) { - const err4 = { - instancePath: instancePath + "/columnCount", - schemaPath: "#/properties/columnCount/minimum", - keyword: "minimum", - params: { - comparison: ">=", - limit: 1 - }, - message: "must be >= 1" - }; - if (vErrors === null) { - vErrors = [err4]; - } else { - vErrors.push(err4); - } - errors++; - } - } - } - if (data.drawVerticalLine !== void 0) { - if (typeof data.drawVerticalLine != "function") { - const err5 = { - instancePath: instancePath + "/drawVerticalLine", - schemaPath: "#/properties/drawVerticalLine/typeof", - keyword: "typeof", - params: {}, - message: 'must pass "typeof" keyword validation' - }; - if (vErrors === null) { - vErrors = [err5]; - } else { - vErrors.push(err5); - } - errors++; - } - } - } else { - const err6 = { - instancePath, - schemaPath: "#/type", - keyword: "type", - params: { - type: "object" - }, - message: "must be object" - }; - if (vErrors === null) { - vErrors = [err6]; - } else { - vErrors.push(err6); - } - errors++; - } - validate86.errors = vErrors; - return errors === 0; - } - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/validateConfig.js -var require_validateConfig = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/validateConfig.js"(exports) { - "use strict"; - var __importDefault = exports && exports.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateConfig = void 0; - var validators_1 = __importDefault(require_validators()); - var validateConfig = (schemaId, config3) => { - const validate2 = validators_1.default[schemaId]; - if (!validate2(config3) && validate2.errors) { - const errors = validate2.errors.map((error49) => { - return { - message: error49.message, - params: error49.params, - schemaPath: error49.schemaPath - }; - }); - console.log("config", config3); - console.log("errors", errors); - throw new Error("Invalid config."); - } - }; - exports.validateConfig = validateConfig; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/makeStreamConfig.js -var require_makeStreamConfig = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/makeStreamConfig.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.makeStreamConfig = void 0; - var utils_1 = require_utils6(); - var validateConfig_1 = require_validateConfig(); - var makeColumnsConfig = (columnCount, columns = {}, columnDefault) => { - return Array.from({ length: columnCount }).map((_, index) => { - return { - alignment: "left", - paddingLeft: 1, - paddingRight: 1, - truncate: Number.POSITIVE_INFINITY, - verticalAlignment: "top", - wrapWord: false, - ...columnDefault, - ...columns[index] - }; - }); - }; - var makeStreamConfig = (config3) => { - (0, validateConfig_1.validateConfig)("streamConfig.json", config3); - if (config3.columnDefault.width === void 0) { - throw new Error("Must provide config.columnDefault.width when creating a stream."); - } - return { - drawVerticalLine: () => { - return true; - }, - ...config3, - border: (0, utils_1.makeBorderConfig)(config3.border), - columns: makeColumnsConfig(config3.columnCount, config3.columns, config3.columnDefault) - }; - }; - exports.makeStreamConfig = makeStreamConfig; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/mapDataUsingRowHeights.js -var require_mapDataUsingRowHeights = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/mapDataUsingRowHeights.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.mapDataUsingRowHeights = exports.padCellVertically = void 0; - var utils_1 = require_utils6(); - var wrapCell_1 = require_wrapCell(); - var createEmptyStrings = (length) => { - return new Array(length).fill(""); - }; - var padCellVertically = (lines, rowHeight, verticalAlignment) => { - const availableLines = rowHeight - lines.length; - if (verticalAlignment === "top") { - return [...lines, ...createEmptyStrings(availableLines)]; - } - if (verticalAlignment === "bottom") { - return [...createEmptyStrings(availableLines), ...lines]; - } - return [ - ...createEmptyStrings(Math.floor(availableLines / 2)), - ...lines, - ...createEmptyStrings(Math.ceil(availableLines / 2)) - ]; - }; - exports.padCellVertically = padCellVertically; - var mapDataUsingRowHeights = (unmappedRows, rowHeights, config3) => { - const nColumns = unmappedRows[0].length; - const mappedRows = unmappedRows.map((unmappedRow, unmappedRowIndex) => { - const outputRowHeight = rowHeights[unmappedRowIndex]; - const outputRow = Array.from({ length: outputRowHeight }, () => { - return new Array(nColumns).fill(""); - }); - unmappedRow.forEach((cell, cellIndex) => { - var _a2; - const containingRange = (_a2 = config3.spanningCellManager) === null || _a2 === void 0 ? void 0 : _a2.getContainingRange({ - col: cellIndex, - row: unmappedRowIndex - }); - if (containingRange) { - containingRange.extractCellContent(unmappedRowIndex).forEach((cellLine, cellLineIndex) => { - outputRow[cellLineIndex][cellIndex] = cellLine; - }); - return; - } - const cellLines = (0, wrapCell_1.wrapCell)(cell, config3.columns[cellIndex].width, config3.columns[cellIndex].wrapWord); - const paddedCellLines = (0, exports.padCellVertically)(cellLines, outputRowHeight, config3.columns[cellIndex].verticalAlignment); - paddedCellLines.forEach((cellLine, cellLineIndex) => { - outputRow[cellLineIndex][cellIndex] = cellLine; - }); - }); - return outputRow; - }); - return (0, utils_1.flatten)(mappedRows); - }; - exports.mapDataUsingRowHeights = mapDataUsingRowHeights; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/padTableData.js -var require_padTableData = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/padTableData.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.padTableData = exports.padString = void 0; - var padString = (input, paddingLeft, paddingRight) => { - return " ".repeat(paddingLeft) + input + " ".repeat(paddingRight); - }; - exports.padString = padString; - var padTableData = (rows, config3) => { - return rows.map((cells, rowIndex) => { - return cells.map((cell, cellIndex) => { - var _a2; - const containingRange = (_a2 = config3.spanningCellManager) === null || _a2 === void 0 ? void 0 : _a2.getContainingRange({ - col: cellIndex, - row: rowIndex - }, { mapped: true }); - if (containingRange) { - return cell; - } - const { paddingLeft, paddingRight } = config3.columns[cellIndex]; - return (0, exports.padString)(cell, paddingLeft, paddingRight); - }); - }); - }; - exports.padTableData = padTableData; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/stringifyTableData.js -var require_stringifyTableData = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/stringifyTableData.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.stringifyTableData = void 0; - var utils_1 = require_utils6(); - var stringifyTableData = (rows) => { - return rows.map((cells) => { - return cells.map((cell) => { - return (0, utils_1.normalizeString)(String(cell)); - }); - }); - }; - exports.stringifyTableData = stringifyTableData; - } -}); - -// node_modules/.pnpm/lodash.truncate@4.4.2/node_modules/lodash.truncate/index.js -var require_lodash = __commonJS({ - "node_modules/.pnpm/lodash.truncate@4.4.2/node_modules/lodash.truncate/index.js"(exports, module) { - var DEFAULT_TRUNC_LENGTH = 30; - var DEFAULT_TRUNC_OMISSION = "..."; - var INFINITY2 = 1 / 0; - var MAX_INTEGER = 17976931348623157e292; - var NAN = 0 / 0; - var regexpTag = "[object RegExp]"; - var symbolTag = "[object Symbol]"; - var reTrim = /^\s+|\s+$/g; - var reFlags = /\w*$/; - var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - var reIsBinary = /^0b[01]+$/i; - var reIsOctal = /^0o[0-7]+$/i; - var rsAstralRange = "\\ud800-\\udfff"; - var rsComboMarksRange = "\\u0300-\\u036f\\ufe20-\\ufe23"; - var rsComboSymbolsRange = "\\u20d0-\\u20f0"; - var rsVarRange = "\\ufe0e\\ufe0f"; - var rsAstral = "[" + rsAstralRange + "]"; - var rsCombo = "[" + rsComboMarksRange + rsComboSymbolsRange + "]"; - var rsFitz = "\\ud83c[\\udffb-\\udfff]"; - var rsModifier = "(?:" + rsCombo + "|" + rsFitz + ")"; - var rsNonAstral = "[^" + rsAstralRange + "]"; - var rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}"; - var rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]"; - var rsZWJ = "\\u200d"; - var reOptMod = rsModifier + "?"; - var rsOptVar = "[" + rsVarRange + "]?"; - var rsOptJoin = "(?:" + rsZWJ + "(?:" + [rsNonAstral, rsRegional, rsSurrPair].join("|") + ")" + rsOptVar + reOptMod + ")*"; - var rsSeq = rsOptVar + reOptMod + rsOptJoin; - var rsSymbol = "(?:" + [rsNonAstral + rsCombo + "?", rsCombo, rsRegional, rsSurrPair, rsAstral].join("|") + ")"; - var reUnicode = RegExp(rsFitz + "(?=" + rsFitz + ")|" + rsSymbol + rsSeq, "g"); - var reHasUnicode = RegExp("[" + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + "]"); - var freeParseInt = parseInt; - var freeGlobal = typeof global == "object" && global && global.Object === Object && global; - var freeSelf = typeof self == "object" && self && self.Object === Object && self; - var root = freeGlobal || freeSelf || Function("return this")(); - var freeExports = typeof exports == "object" && exports && !exports.nodeType && exports; - var freeModule = freeExports && typeof module == "object" && module && !module.nodeType && module; - var moduleExports = freeModule && freeModule.exports === freeExports; - var freeProcess = moduleExports && freeGlobal.process; - var nodeUtil = (function() { - try { - return freeProcess && freeProcess.binding("util"); - } catch (e) { - } - })(); - var nodeIsRegExp = nodeUtil && nodeUtil.isRegExp; - var asciiSize = baseProperty("length"); - function asciiToArray(string6) { - return string6.split(""); - } - function baseProperty(key) { - return function(object5) { - return object5 == null ? void 0 : object5[key]; - }; - } - function baseUnary(func) { - return function(value2) { - return func(value2); - }; - } - function hasUnicode(string6) { - return reHasUnicode.test(string6); - } - function stringSize(string6) { - return hasUnicode(string6) ? unicodeSize(string6) : asciiSize(string6); - } - function stringToArray(string6) { - return hasUnicode(string6) ? unicodeToArray(string6) : asciiToArray(string6); - } - function unicodeSize(string6) { - var result = reUnicode.lastIndex = 0; - while (reUnicode.test(string6)) { - result++; - } - return result; - } - function unicodeToArray(string6) { - return string6.match(reUnicode) || []; - } - var objectProto = Object.prototype; - var objectToString = objectProto.toString; - var Symbol2 = root.Symbol; - var symbolProto = Symbol2 ? Symbol2.prototype : void 0; - var symbolToString = symbolProto ? symbolProto.toString : void 0; - function baseIsRegExp(value2) { - return isObject5(value2) && objectToString.call(value2) == regexpTag; - } - function baseSlice(array3, start, end) { - var index = -1, length = array3.length; - if (start < 0) { - start = -start > length ? 0 : length + start; - } - end = end > length ? length : end; - if (end < 0) { - end += length; - } - length = start > end ? 0 : end - start >>> 0; - start >>>= 0; - var result = Array(length); - while (++index < length) { - result[index] = array3[index + start]; - } - return result; - } - function baseToString2(value2) { - if (typeof value2 == "string") { - return value2; - } - if (isSymbol(value2)) { - return symbolToString ? symbolToString.call(value2) : ""; - } - var result = value2 + ""; - return result == "0" && 1 / value2 == -INFINITY2 ? "-0" : result; - } - function castSlice(array3, start, end) { - var length = array3.length; - end = end === void 0 ? length : end; - return !start && end >= length ? array3 : baseSlice(array3, start, end); - } - function isObject5(value2) { - var type2 = typeof value2; - return !!value2 && (type2 == "object" || type2 == "function"); - } - function isObjectLike2(value2) { - return !!value2 && typeof value2 == "object"; - } - var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; - function isSymbol(value2) { - return typeof value2 == "symbol" || isObjectLike2(value2) && objectToString.call(value2) == symbolTag; - } - function toFinite(value2) { - if (!value2) { - return value2 === 0 ? value2 : 0; - } - value2 = toNumber(value2); - if (value2 === INFINITY2 || value2 === -INFINITY2) { - var sign = value2 < 0 ? -1 : 1; - return sign * MAX_INTEGER; - } - return value2 === value2 ? value2 : 0; - } - function toInteger(value2) { - var result = toFinite(value2), remainder = result % 1; - return result === result ? remainder ? result - remainder : result : 0; - } - function toNumber(value2) { - if (typeof value2 == "number") { - return value2; - } - if (isSymbol(value2)) { - return NAN; - } - if (isObject5(value2)) { - var other = typeof value2.valueOf == "function" ? value2.valueOf() : value2; - value2 = isObject5(other) ? other + "" : other; - } - if (typeof value2 != "string") { - return value2 === 0 ? value2 : +value2; - } - value2 = value2.replace(reTrim, ""); - var isBinary = reIsBinary.test(value2); - return isBinary || reIsOctal.test(value2) ? freeParseInt(value2.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value2) ? NAN : +value2; - } - function toString2(value2) { - return value2 == null ? "" : baseToString2(value2); - } - function truncate(string6, options) { - var length = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION; - if (isObject5(options)) { - var separator2 = "separator" in options ? options.separator : separator2; - length = "length" in options ? toInteger(options.length) : length; - omission = "omission" in options ? baseToString2(options.omission) : omission; - } - string6 = toString2(string6); - var strLength = string6.length; - if (hasUnicode(string6)) { - var strSymbols = stringToArray(string6); - strLength = strSymbols.length; - } - if (length >= strLength) { - return string6; - } - var end = length - stringSize(omission); - if (end < 1) { - return omission; - } - var result = strSymbols ? castSlice(strSymbols, 0, end).join("") : string6.slice(0, end); - if (separator2 === void 0) { - return result + omission; - } - if (strSymbols) { - end += result.length - end; - } - if (isRegExp(separator2)) { - if (string6.slice(end).search(separator2)) { - var match3, substring = result; - if (!separator2.global) { - separator2 = RegExp(separator2.source, toString2(reFlags.exec(separator2)) + "g"); - } - separator2.lastIndex = 0; - while (match3 = separator2.exec(substring)) { - var newEnd = match3.index; - } - result = result.slice(0, newEnd === void 0 ? end : newEnd); - } - } else if (string6.indexOf(baseToString2(separator2), end) != end) { - var index = result.lastIndexOf(separator2); - if (index > -1) { - result = result.slice(0, index); - } - } - return result + omission; - } - module.exports = truncate; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/truncateTableData.js -var require_truncateTableData = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/truncateTableData.js"(exports) { - "use strict"; - var __importDefault = exports && exports.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.truncateTableData = exports.truncateString = void 0; - var lodash_truncate_1 = __importDefault(require_lodash()); - var truncateString = (input, length) => { - return (0, lodash_truncate_1.default)(input, { - length, - omission: "\u2026" - }); - }; - exports.truncateString = truncateString; - var truncateTableData = (rows, truncates) => { - return rows.map((cells) => { - return cells.map((cell, cellIndex) => { - return (0, exports.truncateString)(cell, truncates[cellIndex]); - }); - }); - }; - exports.truncateTableData = truncateTableData; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/createStream.js -var require_createStream = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/createStream.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.createStream = void 0; - var alignTableData_1 = require_alignTableData(); - var calculateRowHeights_1 = require_calculateRowHeights(); - var drawBorder_1 = require_drawBorder(); - var drawRow_1 = require_drawRow(); - var makeStreamConfig_1 = require_makeStreamConfig(); - var mapDataUsingRowHeights_1 = require_mapDataUsingRowHeights(); - var padTableData_1 = require_padTableData(); - var stringifyTableData_1 = require_stringifyTableData(); - var truncateTableData_1 = require_truncateTableData(); - var utils_1 = require_utils6(); - var prepareData = (data, config3) => { - let rows = (0, stringifyTableData_1.stringifyTableData)(data); - rows = (0, truncateTableData_1.truncateTableData)(rows, (0, utils_1.extractTruncates)(config3)); - const rowHeights = (0, calculateRowHeights_1.calculateRowHeights)(rows, config3); - rows = (0, mapDataUsingRowHeights_1.mapDataUsingRowHeights)(rows, rowHeights, config3); - rows = (0, alignTableData_1.alignTableData)(rows, config3); - rows = (0, padTableData_1.padTableData)(rows, config3); - return rows; - }; - var create = (row, columnWidths, config3) => { - const rows = prepareData([row], config3); - const body = rows.map((literalRow) => { - return (0, drawRow_1.drawRow)(literalRow, config3); - }).join(""); - let output; - output = ""; - output += (0, drawBorder_1.drawBorderTop)(columnWidths, config3); - output += body; - output += (0, drawBorder_1.drawBorderBottom)(columnWidths, config3); - output = output.trimEnd(); - process.stdout.write(output); - }; - var append2 = (row, columnWidths, config3) => { - const rows = prepareData([row], config3); - const body = rows.map((literalRow) => { - return (0, drawRow_1.drawRow)(literalRow, config3); - }).join(""); - let output = ""; - const bottom = (0, drawBorder_1.drawBorderBottom)(columnWidths, config3); - if (bottom !== "\n") { - output = "\r\x1B[K"; - } - output += (0, drawBorder_1.drawBorderJoin)(columnWidths, config3); - output += body; - output += bottom; - output = output.trimEnd(); - process.stdout.write(output); - }; - var createStream = (userConfig) => { - const config3 = (0, makeStreamConfig_1.makeStreamConfig)(userConfig); - const columnWidths = Object.values(config3.columns).map((column) => { - return column.width + column.paddingLeft + column.paddingRight; - }); - let empty = true; - return { - write: (row) => { - if (row.length !== config3.columnCount) { - throw new Error("Row cell count does not match the config.columnCount."); - } - if (empty) { - empty = false; - create(row, columnWidths, config3); - } else { - append2(row, columnWidths, config3); - } - } - }; - }; - exports.createStream = createStream; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/calculateOutputColumnWidths.js -var require_calculateOutputColumnWidths = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/calculateOutputColumnWidths.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.calculateOutputColumnWidths = void 0; - var calculateOutputColumnWidths = (config3) => { - return config3.columns.map((col) => { - return col.paddingLeft + col.width + col.paddingRight; - }); - }; - exports.calculateOutputColumnWidths = calculateOutputColumnWidths; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/drawTable.js -var require_drawTable = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/drawTable.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.drawTable = void 0; - var drawBorder_1 = require_drawBorder(); - var drawContent_1 = require_drawContent(); - var drawRow_1 = require_drawRow(); - var utils_1 = require_utils6(); - var drawTable = (rows, outputColumnWidths, rowHeights, config3) => { - const { drawHorizontalLine, singleLine } = config3; - const contents = (0, utils_1.groupBySizes)(rows, rowHeights).map((group2, groupIndex) => { - return group2.map((row) => { - return (0, drawRow_1.drawRow)(row, { - ...config3, - rowIndex: groupIndex - }); - }).join(""); - }); - return (0, drawContent_1.drawContent)({ - contents, - drawSeparator: (index, size) => { - if (index === 0 || index === size) { - return drawHorizontalLine(index, size); - } - return !singleLine && drawHorizontalLine(index, size); - }, - elementType: "row", - rowIndex: -1, - separatorGetter: (0, drawBorder_1.createTableBorderGetter)(outputColumnWidths, { - ...config3, - rowCount: contents.length - }), - spanningCellManager: config3.spanningCellManager - }); - }; - exports.drawTable = drawTable; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/injectHeaderConfig.js -var require_injectHeaderConfig = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/injectHeaderConfig.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.injectHeaderConfig = void 0; - var injectHeaderConfig = (rows, config3) => { - var _a2; - let spanningCellConfig = (_a2 = config3.spanningCells) !== null && _a2 !== void 0 ? _a2 : []; - const headerConfig = config3.header; - const adjustedRows = [...rows]; - if (headerConfig) { - spanningCellConfig = spanningCellConfig.map(({ row, ...rest }) => { - return { - ...rest, - row: row + 1 - }; - }); - const { content, ...headerStyles } = headerConfig; - spanningCellConfig.unshift({ - alignment: "center", - col: 0, - colSpan: rows[0].length, - paddingLeft: 1, - paddingRight: 1, - row: 0, - wrapWord: false, - ...headerStyles - }); - adjustedRows.unshift([content, ...Array.from({ length: rows[0].length - 1 }).fill("")]); - } - return [ - adjustedRows, - spanningCellConfig - ]; - }; - exports.injectHeaderConfig = injectHeaderConfig; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/calculateMaximumColumnWidths.js -var require_calculateMaximumColumnWidths = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/calculateMaximumColumnWidths.js"(exports) { - "use strict"; - var __importDefault = exports && exports.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.calculateMaximumColumnWidths = exports.calculateMaximumCellWidth = void 0; - var string_width_1 = __importDefault(require_string_width()); - var utils_1 = require_utils6(); - var calculateMaximumCellWidth = (cell) => { - return Math.max(...cell.split("\n").map(string_width_1.default)); - }; - exports.calculateMaximumCellWidth = calculateMaximumCellWidth; - var calculateMaximumColumnWidths = (rows, spanningCellConfigs = []) => { - const columnWidths = new Array(rows[0].length).fill(0); - const rangeCoordinates = spanningCellConfigs.map(utils_1.calculateRangeCoordinate); - const isSpanningCell = (rowIndex, columnIndex) => { - return rangeCoordinates.some((rangeCoordinate) => { - return (0, utils_1.isCellInRange)({ - col: columnIndex, - row: rowIndex - }, rangeCoordinate); - }); - }; - rows.forEach((row, rowIndex) => { - row.forEach((cell, cellIndex) => { - if (isSpanningCell(rowIndex, cellIndex)) { - return; - } - columnWidths[cellIndex] = Math.max(columnWidths[cellIndex], (0, exports.calculateMaximumCellWidth)(cell)); - }); - }); - return columnWidths; - }; - exports.calculateMaximumColumnWidths = calculateMaximumColumnWidths; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/alignSpanningCell.js -var require_alignSpanningCell = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/alignSpanningCell.js"(exports) { - "use strict"; - var __importDefault = exports && exports.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { "default": mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.alignVerticalRangeContent = exports.wrapRangeContent = void 0; - var string_width_1 = __importDefault(require_string_width()); - var alignString_1 = require_alignString(); - var mapDataUsingRowHeights_1 = require_mapDataUsingRowHeights(); - var padTableData_1 = require_padTableData(); - var truncateTableData_1 = require_truncateTableData(); - var utils_1 = require_utils6(); - var wrapCell_1 = require_wrapCell(); - var wrapRangeContent = (rangeConfig, rangeWidth, context) => { - const { topLeft, paddingRight, paddingLeft, truncate, wrapWord, alignment } = rangeConfig; - const originalContent = context.rows[topLeft.row][topLeft.col]; - const contentWidth = rangeWidth - paddingLeft - paddingRight; - return (0, wrapCell_1.wrapCell)((0, truncateTableData_1.truncateString)(originalContent, truncate), contentWidth, wrapWord).map((line) => { - const alignedLine = (0, alignString_1.alignString)(line, contentWidth, alignment); - return (0, padTableData_1.padString)(alignedLine, paddingLeft, paddingRight); - }); - }; - exports.wrapRangeContent = wrapRangeContent; - var alignVerticalRangeContent = (range2, content, context) => { - const { rows, drawHorizontalLine, rowHeights } = context; - const { topLeft, bottomRight, verticalAlignment } = range2; - if (rowHeights.length === 0) { - return []; - } - const totalCellHeight = (0, utils_1.sumArray)(rowHeights.slice(topLeft.row, bottomRight.row + 1)); - const totalBorderHeight = bottomRight.row - topLeft.row; - const hiddenHorizontalBorderCount = (0, utils_1.sequence)(topLeft.row + 1, bottomRight.row).filter((horizontalBorderIndex) => { - return !drawHorizontalLine(horizontalBorderIndex, rows.length); - }).length; - const availableRangeHeight = totalCellHeight + totalBorderHeight - hiddenHorizontalBorderCount; - return (0, mapDataUsingRowHeights_1.padCellVertically)(content, availableRangeHeight, verticalAlignment).map((line) => { - if (line.length === 0) { - return " ".repeat((0, string_width_1.default)(content[0])); - } - return line; - }); - }; - exports.alignVerticalRangeContent = alignVerticalRangeContent; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/calculateSpanningCellWidth.js -var require_calculateSpanningCellWidth = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/calculateSpanningCellWidth.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.calculateSpanningCellWidth = void 0; - var utils_1 = require_utils6(); - var calculateSpanningCellWidth = (rangeConfig, dependencies) => { - const { columnsConfig, drawVerticalLine } = dependencies; - const { topLeft, bottomRight } = rangeConfig; - const totalWidth = (0, utils_1.sumArray)(columnsConfig.slice(topLeft.col, bottomRight.col + 1).map(({ width }) => { - return width; - })); - const totalPadding = topLeft.col === bottomRight.col ? columnsConfig[topLeft.col].paddingRight + columnsConfig[bottomRight.col].paddingLeft : (0, utils_1.sumArray)(columnsConfig.slice(topLeft.col, bottomRight.col + 1).map(({ paddingLeft, paddingRight }) => { - return paddingLeft + paddingRight; - })); - const totalBorderWidths = bottomRight.col - topLeft.col; - const totalHiddenVerticalBorders = (0, utils_1.sequence)(topLeft.col + 1, bottomRight.col).filter((verticalBorderIndex) => { - return !drawVerticalLine(verticalBorderIndex, columnsConfig.length); - }).length; - return totalWidth + totalPadding + totalBorderWidths - totalHiddenVerticalBorders; - }; - exports.calculateSpanningCellWidth = calculateSpanningCellWidth; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/makeRangeConfig.js -var require_makeRangeConfig = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/makeRangeConfig.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.makeRangeConfig = void 0; - var utils_1 = require_utils6(); - var makeRangeConfig = (spanningCellConfig, columnsConfig) => { - var _a2; - const { topLeft, bottomRight } = (0, utils_1.calculateRangeCoordinate)(spanningCellConfig); - const cellConfig = { - ...columnsConfig[topLeft.col], - ...spanningCellConfig, - paddingRight: (_a2 = spanningCellConfig.paddingRight) !== null && _a2 !== void 0 ? _a2 : columnsConfig[bottomRight.col].paddingRight - }; - return { - ...cellConfig, - bottomRight, - topLeft - }; - }; - exports.makeRangeConfig = makeRangeConfig; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/spanningCellManager.js -var require_spanningCellManager = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/spanningCellManager.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.createSpanningCellManager = void 0; - var alignSpanningCell_1 = require_alignSpanningCell(); - var calculateSpanningCellWidth_1 = require_calculateSpanningCellWidth(); - var makeRangeConfig_1 = require_makeRangeConfig(); - var utils_1 = require_utils6(); - var findRangeConfig = (cell, rangeConfigs) => { - return rangeConfigs.find((rangeCoordinate) => { - return (0, utils_1.isCellInRange)(cell, rangeCoordinate); - }); - }; - var getContainingRange = (rangeConfig, context) => { - const width = (0, calculateSpanningCellWidth_1.calculateSpanningCellWidth)(rangeConfig, context); - const wrappedContent = (0, alignSpanningCell_1.wrapRangeContent)(rangeConfig, width, context); - const alignedContent = (0, alignSpanningCell_1.alignVerticalRangeContent)(rangeConfig, wrappedContent, context); - const getCellContent = (rowIndex) => { - const { topLeft } = rangeConfig; - const { drawHorizontalLine, rowHeights } = context; - const totalWithinHorizontalBorderHeight = rowIndex - topLeft.row; - const totalHiddenHorizontalBorderHeight = (0, utils_1.sequence)(topLeft.row + 1, rowIndex).filter((index) => { - return !(drawHorizontalLine === null || drawHorizontalLine === void 0 ? void 0 : drawHorizontalLine(index, rowHeights.length)); - }).length; - const offset = (0, utils_1.sumArray)(rowHeights.slice(topLeft.row, rowIndex)) + totalWithinHorizontalBorderHeight - totalHiddenHorizontalBorderHeight; - return alignedContent.slice(offset, offset + rowHeights[rowIndex]); - }; - const getBorderContent = (borderIndex) => { - const { topLeft } = rangeConfig; - const offset = (0, utils_1.sumArray)(context.rowHeights.slice(topLeft.row, borderIndex)) + (borderIndex - topLeft.row - 1); - return alignedContent[offset]; - }; - return { - ...rangeConfig, - extractBorderContent: getBorderContent, - extractCellContent: getCellContent, - height: wrappedContent.length, - width - }; - }; - var inSameRange = (cell1, cell2, ranges) => { - const range1 = findRangeConfig(cell1, ranges); - const range2 = findRangeConfig(cell2, ranges); - if (range1 && range2) { - return (0, utils_1.areCellEqual)(range1.topLeft, range2.topLeft); - } - return false; - }; - var hashRange = (range2) => { - const { row, col } = range2.topLeft; - return `${row}/${col}`; - }; - var createSpanningCellManager = (parameters) => { - const { spanningCellConfigs, columnsConfig } = parameters; - const ranges = spanningCellConfigs.map((config3) => { - return (0, makeRangeConfig_1.makeRangeConfig)(config3, columnsConfig); - }); - const rangeCache = {}; - let rowHeights = []; - let rowIndexMapping = []; - return { - getContainingRange: (cell, options) => { - var _a2; - const originalRow = (options === null || options === void 0 ? void 0 : options.mapped) ? rowIndexMapping[cell.row] : cell.row; - const range2 = findRangeConfig({ - ...cell, - row: originalRow - }, ranges); - if (!range2) { - return void 0; - } - if (rowHeights.length === 0) { - return getContainingRange(range2, { - ...parameters, - rowHeights - }); - } - const hash2 = hashRange(range2); - (_a2 = rangeCache[hash2]) !== null && _a2 !== void 0 ? _a2 : rangeCache[hash2] = getContainingRange(range2, { - ...parameters, - rowHeights - }); - return rangeCache[hash2]; - }, - inSameRange: (cell1, cell2) => { - return inSameRange(cell1, cell2, ranges); - }, - rowHeights, - rowIndexMapping, - setRowHeights: (_rowHeights) => { - rowHeights = _rowHeights; - }, - setRowIndexMapping: (mappedRowHeights) => { - rowIndexMapping = (0, utils_1.flatten)(mappedRowHeights.map((height, index) => { - return Array.from({ length: height }, () => { - return index; - }); - })); - } - }; - }; - exports.createSpanningCellManager = createSpanningCellManager; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/validateSpanningCellConfig.js -var require_validateSpanningCellConfig = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/validateSpanningCellConfig.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateSpanningCellConfig = void 0; - var utils_1 = require_utils6(); - var inRange = (start, end, value2) => { - return start <= value2 && value2 <= end; - }; - var validateSpanningCellConfig = (rows, configs) => { - const [nRow, nCol] = [rows.length, rows[0].length]; - configs.forEach((config3, configIndex) => { - const { colSpan, rowSpan } = config3; - if (colSpan === void 0 && rowSpan === void 0) { - throw new Error(`Expect at least colSpan or rowSpan is provided in config.spanningCells[${configIndex}]`); - } - if (colSpan !== void 0 && colSpan < 1) { - throw new Error(`Expect colSpan is not equal zero, instead got: ${colSpan} in config.spanningCells[${configIndex}]`); - } - if (rowSpan !== void 0 && rowSpan < 1) { - throw new Error(`Expect rowSpan is not equal zero, instead got: ${rowSpan} in config.spanningCells[${configIndex}]`); - } - }); - const rangeCoordinates = configs.map(utils_1.calculateRangeCoordinate); - rangeCoordinates.forEach(({ topLeft, bottomRight }, rangeIndex) => { - if (!inRange(0, nCol - 1, topLeft.col) || !inRange(0, nRow - 1, topLeft.row) || !inRange(0, nCol - 1, bottomRight.col) || !inRange(0, nRow - 1, bottomRight.row)) { - throw new Error(`Some cells in config.spanningCells[${rangeIndex}] are out of the table`); - } - }); - const configOccupy = Array.from({ length: nRow }, () => { - return Array.from({ length: nCol }); - }); - rangeCoordinates.forEach(({ topLeft, bottomRight }, rangeIndex) => { - (0, utils_1.sequence)(topLeft.row, bottomRight.row).forEach((row) => { - (0, utils_1.sequence)(topLeft.col, bottomRight.col).forEach((col) => { - if (configOccupy[row][col] !== void 0) { - throw new Error(`Spanning cells in config.spanningCells[${configOccupy[row][col]}] and config.spanningCells[${rangeIndex}] are overlap each other`); - } - configOccupy[row][col] = rangeIndex; - }); - }); - }); - }; - exports.validateSpanningCellConfig = validateSpanningCellConfig; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/makeTableConfig.js -var require_makeTableConfig = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/makeTableConfig.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.makeTableConfig = void 0; - var calculateMaximumColumnWidths_1 = require_calculateMaximumColumnWidths(); - var spanningCellManager_1 = require_spanningCellManager(); - var utils_1 = require_utils6(); - var validateConfig_1 = require_validateConfig(); - var validateSpanningCellConfig_1 = require_validateSpanningCellConfig(); - var makeColumnsConfig = (rows, columns, columnDefault, spanningCellConfigs) => { - const columnWidths = (0, calculateMaximumColumnWidths_1.calculateMaximumColumnWidths)(rows, spanningCellConfigs); - return rows[0].map((_, columnIndex) => { - return { - alignment: "left", - paddingLeft: 1, - paddingRight: 1, - truncate: Number.POSITIVE_INFINITY, - verticalAlignment: "top", - width: columnWidths[columnIndex], - wrapWord: false, - ...columnDefault, - ...columns === null || columns === void 0 ? void 0 : columns[columnIndex] - }; - }); - }; - var makeTableConfig = (rows, config3 = {}, injectedSpanningCellConfig) => { - var _a2, _b, _c, _d, _e; - (0, validateConfig_1.validateConfig)("config.json", config3); - (0, validateSpanningCellConfig_1.validateSpanningCellConfig)(rows, (_a2 = config3.spanningCells) !== null && _a2 !== void 0 ? _a2 : []); - const spanningCellConfigs = (_b = injectedSpanningCellConfig !== null && injectedSpanningCellConfig !== void 0 ? injectedSpanningCellConfig : config3.spanningCells) !== null && _b !== void 0 ? _b : []; - const columnsConfig = makeColumnsConfig(rows, config3.columns, config3.columnDefault, spanningCellConfigs); - const drawVerticalLine = (_c = config3.drawVerticalLine) !== null && _c !== void 0 ? _c : (() => { - return true; - }); - const drawHorizontalLine = (_d = config3.drawHorizontalLine) !== null && _d !== void 0 ? _d : (() => { - return true; - }); - return { - ...config3, - border: (0, utils_1.makeBorderConfig)(config3.border), - columns: columnsConfig, - drawHorizontalLine, - drawVerticalLine, - singleLine: (_e = config3.singleLine) !== null && _e !== void 0 ? _e : false, - spanningCellManager: (0, spanningCellManager_1.createSpanningCellManager)({ - columnsConfig, - drawHorizontalLine, - drawVerticalLine, - rows, - spanningCellConfigs - }) - }; - }; - exports.makeTableConfig = makeTableConfig; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/validateTableData.js -var require_validateTableData = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/validateTableData.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateTableData = void 0; - var utils_1 = require_utils6(); - var validateTableData = (rows) => { - if (!Array.isArray(rows)) { - throw new TypeError("Table data must be an array."); - } - if (rows.length === 0) { - throw new Error("Table must define at least one row."); - } - if (rows[0].length === 0) { - throw new Error("Table must define at least one column."); - } - const columnNumber = rows[0].length; - for (const row of rows) { - if (!Array.isArray(row)) { - throw new TypeError("Table row data must be an array."); - } - if (row.length !== columnNumber) { - throw new Error("Table must have a consistent number of cells."); - } - for (const cell of row) { - if (/[\u0001-\u0006\u0008\u0009\u000B-\u001A]/.test((0, utils_1.normalizeString)(String(cell)))) { - throw new Error("Table data must not contain control characters."); - } - } - } - }; - exports.validateTableData = validateTableData; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/table.js -var require_table = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/table.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.table = void 0; - var alignTableData_1 = require_alignTableData(); - var calculateOutputColumnWidths_1 = require_calculateOutputColumnWidths(); - var calculateRowHeights_1 = require_calculateRowHeights(); - var drawTable_1 = require_drawTable(); - var injectHeaderConfig_1 = require_injectHeaderConfig(); - var makeTableConfig_1 = require_makeTableConfig(); - var mapDataUsingRowHeights_1 = require_mapDataUsingRowHeights(); - var padTableData_1 = require_padTableData(); - var stringifyTableData_1 = require_stringifyTableData(); - var truncateTableData_1 = require_truncateTableData(); - var utils_1 = require_utils6(); - var validateTableData_1 = require_validateTableData(); - var table2 = (data, userConfig = {}) => { - (0, validateTableData_1.validateTableData)(data); - let rows = (0, stringifyTableData_1.stringifyTableData)(data); - const [injectedRows, injectedSpanningCellConfig] = (0, injectHeaderConfig_1.injectHeaderConfig)(rows, userConfig); - const config3 = (0, makeTableConfig_1.makeTableConfig)(injectedRows, userConfig, injectedSpanningCellConfig); - rows = (0, truncateTableData_1.truncateTableData)(injectedRows, (0, utils_1.extractTruncates)(config3)); - const rowHeights = (0, calculateRowHeights_1.calculateRowHeights)(rows, config3); - config3.spanningCellManager.setRowHeights(rowHeights); - config3.spanningCellManager.setRowIndexMapping(rowHeights); - rows = (0, mapDataUsingRowHeights_1.mapDataUsingRowHeights)(rows, rowHeights, config3); - rows = (0, alignTableData_1.alignTableData)(rows, config3); - rows = (0, padTableData_1.padTableData)(rows, config3); - const outputColumnWidths = (0, calculateOutputColumnWidths_1.calculateOutputColumnWidths)(config3); - return (0, drawTable_1.drawTable)(rows, outputColumnWidths, rowHeights, config3); - }; - exports.table = table2; - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/types/api.js -var require_api3 = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/types/api.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - } -}); - -// node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/index.js -var require_src = __commonJS({ - "node_modules/.pnpm/table@6.9.0/node_modules/table/dist/src/index.js"(exports) { - "use strict"; - var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { - return m[k]; - } }); - }) : (function(o, m, k, k2) { - if (k2 === void 0) k2 = k; - o[k2] = m[k]; - })); - var __exportStar = exports && exports.__exportStar || function(m, exports2) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p); - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getBorderCharacters = exports.createStream = exports.table = void 0; - var createStream_1 = require_createStream(); - Object.defineProperty(exports, "createStream", { enumerable: true, get: function() { - return createStream_1.createStream; - } }); - var getBorderCharacters_1 = require_getBorderCharacters(); - Object.defineProperty(exports, "getBorderCharacters", { enumerable: true, get: function() { - return getBorderCharacters_1.getBorderCharacters; - } }); - var table_1 = require_table(); - Object.defineProperty(exports, "table", { enumerable: true, get: function() { - return table_1.table; - } }); - __exportStar(require_api3(), exports); - } -}); - -// node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/light.js -var require_light = __commonJS({ - "node_modules/.pnpm/bottleneck@2.19.5/node_modules/bottleneck/light.js"(exports, module) { - (function(global2, factory) { - typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && define.amd ? define(factory) : global2.Bottleneck = factory(); - })(exports, (function() { - "use strict"; - var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {}; - function getCjsExportFromNamespace(n) { - return n && n["default"] || n; - } - var load = function(received, defaults, onto = {}) { - var k, ref, v; - for (k in defaults) { - v = defaults[k]; - onto[k] = (ref = received[k]) != null ? ref : v; - } - return onto; - }; - var overwrite = function(received, defaults, onto = {}) { - var k, v; - for (k in received) { - v = received[k]; - if (defaults[k] !== void 0) { - onto[k] = v; - } - } - return onto; - }; - var parser = { - load, - overwrite - }; - var DLList; - DLList = class DLList { - constructor(incr, decr) { - this.incr = incr; - this.decr = decr; - this._first = null; - this._last = null; - this.length = 0; - } - push(value2) { - var node2; - this.length++; - if (typeof this.incr === "function") { - this.incr(); - } - node2 = { - value: value2, - prev: this._last, - next: null - }; - if (this._last != null) { - this._last.next = node2; - this._last = node2; - } else { - this._first = this._last = node2; - } - return void 0; - } - shift() { - var value2; - if (this._first == null) { - return; - } else { - this.length--; - if (typeof this.decr === "function") { - this.decr(); - } - } - value2 = this._first.value; - if ((this._first = this._first.next) != null) { - this._first.prev = null; - } else { - this._last = null; - } - return value2; - } - first() { - if (this._first != null) { - return this._first.value; - } - } - getArray() { - var node2, ref, results; - node2 = this._first; - results = []; - while (node2 != null) { - results.push((ref = node2, node2 = node2.next, ref.value)); - } - return results; - } - forEachShift(cb) { - var node2; - node2 = this.shift(); - while (node2 != null) { - cb(node2), node2 = this.shift(); - } - return void 0; - } - debug() { - var node2, ref, ref1, ref2, results; - node2 = this._first; - results = []; - while (node2 != null) { - results.push((ref = node2, node2 = node2.next, { - value: ref.value, - prev: (ref1 = ref.prev) != null ? ref1.value : void 0, - next: (ref2 = ref.next) != null ? ref2.value : void 0 - })); - } - return results; - } - }; - var DLList_1 = DLList; - var Events; - Events = class Events { - constructor(instance) { - this.instance = instance; - this._events = {}; - if (this.instance.on != null || this.instance.once != null || this.instance.removeAllListeners != null) { - throw new Error("An Emitter already exists for this object"); - } - this.instance.on = (name, cb) => { - return this._addListener(name, "many", cb); - }; - this.instance.once = (name, cb) => { - return this._addListener(name, "once", cb); - }; - this.instance.removeAllListeners = (name = null) => { - if (name != null) { - return delete this._events[name]; - } else { - return this._events = {}; - } - }; - } - _addListener(name, status, cb) { - var base; - if ((base = this._events)[name] == null) { - base[name] = []; - } - this._events[name].push({ cb, status }); - return this.instance; - } - listenerCount(name) { - if (this._events[name] != null) { - return this._events[name].length; - } else { - return 0; - } - } - async trigger(name, ...args2) { - var e, promises; - try { - if (name !== "debug") { - this.trigger("debug", `Event triggered: ${name}`, args2); - } - if (this._events[name] == null) { - return; - } - this._events[name] = this._events[name].filter(function(listener) { - return listener.status !== "none"; - }); - promises = this._events[name].map(async (listener) => { - var e2, returned; - if (listener.status === "none") { - return; - } - if (listener.status === "once") { - listener.status = "none"; - } - try { - returned = typeof listener.cb === "function" ? listener.cb(...args2) : void 0; - if (typeof (returned != null ? returned.then : void 0) === "function") { - return await returned; - } else { - return returned; - } - } catch (error49) { - e2 = error49; - { - this.trigger("error", e2); - } - return null; - } - }); - return (await Promise.all(promises)).find(function(x) { - return x != null; - }); - } catch (error49) { - e = error49; - { - this.trigger("error", e); - } - return null; - } - } - }; - var Events_1 = Events; - var DLList$1, Events$1, Queues; - DLList$1 = DLList_1; - Events$1 = Events_1; - Queues = class Queues { - constructor(num_priorities) { - var i; - this.Events = new Events$1(this); - this._length = 0; - this._lists = (function() { - var j, ref, results; - results = []; - for (i = j = 1, ref = num_priorities; 1 <= ref ? j <= ref : j >= ref; i = 1 <= ref ? ++j : --j) { - results.push(new DLList$1((() => { - return this.incr(); - }), (() => { - return this.decr(); - }))); - } - return results; - }).call(this); - } - incr() { - if (this._length++ === 0) { - return this.Events.trigger("leftzero"); - } - } - decr() { - if (--this._length === 0) { - return this.Events.trigger("zero"); - } - } - push(job) { - return this._lists[job.options.priority].push(job); - } - queued(priority) { - if (priority != null) { - return this._lists[priority].length; - } else { - return this._length; - } - } - shiftAll(fn2) { - return this._lists.forEach(function(list) { - return list.forEachShift(fn2); - }); - } - getFirst(arr = this._lists) { - var j, len, list; - for (j = 0, len = arr.length; j < len; j++) { - list = arr[j]; - if (list.length > 0) { - return list; - } - } - return []; - } - shiftLastFrom(priority) { - return this.getFirst(this._lists.slice(priority).reverse()).shift(); - } - }; - var Queues_1 = Queues; - var BottleneckError; - BottleneckError = class BottleneckError extends Error { - }; - var BottleneckError_1 = BottleneckError; - var BottleneckError$1, DEFAULT_PRIORITY, Job, NUM_PRIORITIES, parser$1; - NUM_PRIORITIES = 10; - DEFAULT_PRIORITY = 5; - parser$1 = parser; - BottleneckError$1 = BottleneckError_1; - Job = class Job { - constructor(task, args2, options, jobDefaults, rejectOnDrop, Events2, _states, Promise2) { - this.task = task; - this.args = args2; - this.rejectOnDrop = rejectOnDrop; - this.Events = Events2; - this._states = _states; - this.Promise = Promise2; - this.options = parser$1.load(options, jobDefaults); - this.options.priority = this._sanitizePriority(this.options.priority); - if (this.options.id === jobDefaults.id) { - this.options.id = `${this.options.id}-${this._randomIndex()}`; - } - this.promise = new this.Promise((_resolve, _reject) => { - this._resolve = _resolve; - this._reject = _reject; - }); - this.retryCount = 0; - } - _sanitizePriority(priority) { - var sProperty; - sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority; - if (sProperty < 0) { - return 0; - } else if (sProperty > NUM_PRIORITIES - 1) { - return NUM_PRIORITIES - 1; - } else { - return sProperty; - } - } - _randomIndex() { - return Math.random().toString(36).slice(2); - } - doDrop({ error: error49, message = "This job has been dropped by Bottleneck" } = {}) { - if (this._states.remove(this.options.id)) { - if (this.rejectOnDrop) { - this._reject(error49 != null ? error49 : new BottleneckError$1(message)); - } - this.Events.trigger("dropped", { args: this.args, options: this.options, task: this.task, promise: this.promise }); - return true; - } else { - return false; - } - } - _assertStatus(expected) { - var status; - status = this._states.jobStatus(this.options.id); - if (!(status === expected || expected === "DONE" && status === null)) { - throw new BottleneckError$1(`Invalid job status ${status}, expected ${expected}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`); - } - } - doReceive() { - this._states.start(this.options.id); - return this.Events.trigger("received", { args: this.args, options: this.options }); - } - doQueue(reachedHWM, blocked) { - this._assertStatus("RECEIVED"); - this._states.next(this.options.id); - return this.Events.trigger("queued", { args: this.args, options: this.options, reachedHWM, blocked }); - } - doRun() { - if (this.retryCount === 0) { - this._assertStatus("QUEUED"); - this._states.next(this.options.id); - } else { - this._assertStatus("EXECUTING"); - } - return this.Events.trigger("scheduled", { args: this.args, options: this.options }); - } - async doExecute(chained, clearGlobalState, run2, free) { - var error49, eventInfo, passed; - if (this.retryCount === 0) { - this._assertStatus("RUNNING"); - this._states.next(this.options.id); - } else { - this._assertStatus("EXECUTING"); - } - eventInfo = { args: this.args, options: this.options, retryCount: this.retryCount }; - this.Events.trigger("executing", eventInfo); - try { - passed = await (chained != null ? chained.schedule(this.options, this.task, ...this.args) : this.task(...this.args)); - if (clearGlobalState()) { - this.doDone(eventInfo); - await free(this.options, eventInfo); - this._assertStatus("DONE"); - return this._resolve(passed); - } - } catch (error1) { - error49 = error1; - return this._onFailure(error49, eventInfo, clearGlobalState, run2, free); - } - } - doExpire(clearGlobalState, run2, free) { - var error49, eventInfo; - if (this._states.jobStatus(this.options.id === "RUNNING")) { - this._states.next(this.options.id); - } - this._assertStatus("EXECUTING"); - eventInfo = { args: this.args, options: this.options, retryCount: this.retryCount }; - error49 = new BottleneckError$1(`This job timed out after ${this.options.expiration} ms.`); - return this._onFailure(error49, eventInfo, clearGlobalState, run2, free); - } - async _onFailure(error49, eventInfo, clearGlobalState, run2, free) { - var retry2, retryAfter; - if (clearGlobalState()) { - retry2 = await this.Events.trigger("failed", error49, eventInfo); - if (retry2 != null) { - retryAfter = ~~retry2; - this.Events.trigger("retry", `Retrying ${this.options.id} after ${retryAfter} ms`, eventInfo); - this.retryCount++; - return run2(retryAfter); - } else { - this.doDone(eventInfo); - await free(this.options, eventInfo); - this._assertStatus("DONE"); - return this._reject(error49); - } - } - } - doDone(eventInfo) { - this._assertStatus("EXECUTING"); - this._states.next(this.options.id); - return this.Events.trigger("done", eventInfo); - } - }; - var Job_1 = Job; - var BottleneckError$2, LocalDatastore, parser$2; - parser$2 = parser; - BottleneckError$2 = BottleneckError_1; - LocalDatastore = class LocalDatastore { - constructor(instance, storeOptions, storeInstanceOptions) { - this.instance = instance; - this.storeOptions = storeOptions; - this.clientId = this.instance._randomIndex(); - parser$2.load(storeInstanceOptions, storeInstanceOptions, this); - this._nextRequest = this._lastReservoirRefresh = this._lastReservoirIncrease = Date.now(); - this._running = 0; - this._done = 0; - this._unblockTime = 0; - this.ready = this.Promise.resolve(); - this.clients = {}; - this._startHeartbeat(); - } - _startHeartbeat() { - var base; - if (this.heartbeat == null && (this.storeOptions.reservoirRefreshInterval != null && this.storeOptions.reservoirRefreshAmount != null || this.storeOptions.reservoirIncreaseInterval != null && this.storeOptions.reservoirIncreaseAmount != null)) { - return typeof (base = this.heartbeat = setInterval(() => { - var amount, incr, maximum, now, reservoir; - now = Date.now(); - if (this.storeOptions.reservoirRefreshInterval != null && now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) { - this._lastReservoirRefresh = now; - this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount; - this.instance._drainAll(this.computeCapacity()); - } - if (this.storeOptions.reservoirIncreaseInterval != null && now >= this._lastReservoirIncrease + this.storeOptions.reservoirIncreaseInterval) { - ({ - reservoirIncreaseAmount: amount, - reservoirIncreaseMaximum: maximum, - reservoir - } = this.storeOptions); - this._lastReservoirIncrease = now; - incr = maximum != null ? Math.min(amount, maximum - reservoir) : amount; - if (incr > 0) { - this.storeOptions.reservoir += incr; - return this.instance._drainAll(this.computeCapacity()); - } - } - }, this.heartbeatInterval)).unref === "function" ? base.unref() : void 0; - } else { - return clearInterval(this.heartbeat); - } - } - async __publish__(message) { - await this.yieldLoop(); - return this.instance.Events.trigger("message", message.toString()); - } - async __disconnect__(flush) { - await this.yieldLoop(); - clearInterval(this.heartbeat); - return this.Promise.resolve(); - } - yieldLoop(t = 0) { - return new this.Promise(function(resolve2, reject) { - return setTimeout(resolve2, t); - }); - } - computePenalty() { - var ref; - return (ref = this.storeOptions.penalty) != null ? ref : 15 * this.storeOptions.minTime || 5e3; - } - async __updateSettings__(options) { - await this.yieldLoop(); - parser$2.overwrite(options, options, this.storeOptions); - this._startHeartbeat(); - this.instance._drainAll(this.computeCapacity()); - return true; - } - async __running__() { - await this.yieldLoop(); - return this._running; - } - async __queued__() { - await this.yieldLoop(); - return this.instance.queued(); - } - async __done__() { - await this.yieldLoop(); - return this._done; - } - async __groupCheck__(time4) { - await this.yieldLoop(); - return this._nextRequest + this.timeout < time4; - } - computeCapacity() { - var maxConcurrent, reservoir; - ({ maxConcurrent, reservoir } = this.storeOptions); - if (maxConcurrent != null && reservoir != null) { - return Math.min(maxConcurrent - this._running, reservoir); - } else if (maxConcurrent != null) { - return maxConcurrent - this._running; - } else if (reservoir != null) { - return reservoir; - } else { - return null; - } - } - conditionsCheck(weight) { - var capacity; - capacity = this.computeCapacity(); - return capacity == null || weight <= capacity; - } - async __incrementReservoir__(incr) { - var reservoir; - await this.yieldLoop(); - reservoir = this.storeOptions.reservoir += incr; - this.instance._drainAll(this.computeCapacity()); - return reservoir; - } - async __currentReservoir__() { - await this.yieldLoop(); - return this.storeOptions.reservoir; - } - isBlocked(now) { - return this._unblockTime >= now; - } - check(weight, now) { - return this.conditionsCheck(weight) && this._nextRequest - now <= 0; - } - async __check__(weight) { - var now; - await this.yieldLoop(); - now = Date.now(); - return this.check(weight, now); - } - async __register__(index, weight, expiration) { - var now, wait; - await this.yieldLoop(); - now = Date.now(); - if (this.conditionsCheck(weight)) { - this._running += weight; - if (this.storeOptions.reservoir != null) { - this.storeOptions.reservoir -= weight; - } - wait = Math.max(this._nextRequest - now, 0); - this._nextRequest = now + wait + this.storeOptions.minTime; - return { - success: true, - wait, - reservoir: this.storeOptions.reservoir - }; - } else { - return { - success: false - }; - } - } - strategyIsBlock() { - return this.storeOptions.strategy === 3; - } - async __submit__(queueLength, weight) { - var blocked, now, reachedHWM; - await this.yieldLoop(); - if (this.storeOptions.maxConcurrent != null && weight > this.storeOptions.maxConcurrent) { - throw new BottleneckError$2(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${this.storeOptions.maxConcurrent}`); - } - now = Date.now(); - reachedHWM = this.storeOptions.highWater != null && queueLength === this.storeOptions.highWater && !this.check(weight, now); - blocked = this.strategyIsBlock() && (reachedHWM || this.isBlocked(now)); - if (blocked) { - this._unblockTime = now + this.computePenalty(); - this._nextRequest = this._unblockTime + this.storeOptions.minTime; - this.instance._dropAllQueued(); - } - return { - reachedHWM, - blocked, - strategy: this.storeOptions.strategy - }; - } - async __free__(index, weight) { - await this.yieldLoop(); - this._running -= weight; - this._done += weight; - this.instance._drainAll(this.computeCapacity()); - return { - running: this._running - }; - } - }; - var LocalDatastore_1 = LocalDatastore; - var BottleneckError$3, States; - BottleneckError$3 = BottleneckError_1; - States = class States { - constructor(status1) { - this.status = status1; - this._jobs = {}; - this.counts = this.status.map(function() { - return 0; - }); - } - next(id) { - var current, next2; - current = this._jobs[id]; - next2 = current + 1; - if (current != null && next2 < this.status.length) { - this.counts[current]--; - this.counts[next2]++; - return this._jobs[id]++; - } else if (current != null) { - this.counts[current]--; - return delete this._jobs[id]; - } - } - start(id) { - var initial; - initial = 0; - this._jobs[id] = initial; - return this.counts[initial]++; - } - remove(id) { - var current; - current = this._jobs[id]; - if (current != null) { - this.counts[current]--; - delete this._jobs[id]; - } - return current != null; - } - jobStatus(id) { - var ref; - return (ref = this.status[this._jobs[id]]) != null ? ref : null; - } - statusJobs(status) { - var k, pos, ref, results, v; - if (status != null) { - pos = this.status.indexOf(status); - if (pos < 0) { - throw new BottleneckError$3(`status must be one of ${this.status.join(", ")}`); - } - ref = this._jobs; - results = []; - for (k in ref) { - v = ref[k]; - if (v === pos) { - results.push(k); - } - } - return results; - } else { - return Object.keys(this._jobs); - } - } - statusCounts() { - return this.counts.reduce(((acc, v, i) => { - acc[this.status[i]] = v; - return acc; - }), {}); - } - }; - var States_1 = States; - var DLList$2, Sync; - DLList$2 = DLList_1; - Sync = class Sync { - constructor(name, Promise2) { - this.schedule = this.schedule.bind(this); - this.name = name; - this.Promise = Promise2; - this._running = 0; - this._queue = new DLList$2(); - } - isEmpty() { - return this._queue.length === 0; - } - async _tryToRun() { - var args2, cb, error49, reject, resolve2, returned, task; - if (this._running < 1 && this._queue.length > 0) { - this._running++; - ({ task, args: args2, resolve: resolve2, reject } = this._queue.shift()); - cb = await (async function() { - try { - returned = await task(...args2); - return function() { - return resolve2(returned); - }; - } catch (error1) { - error49 = error1; - return function() { - return reject(error49); - }; - } - })(); - this._running--; - this._tryToRun(); - return cb(); - } - } - schedule(task, ...args2) { - var promise2, reject, resolve2; - resolve2 = reject = null; - promise2 = new this.Promise(function(_resolve, _reject) { - resolve2 = _resolve; - return reject = _reject; - }); - this._queue.push({ task, args: args2, resolve: resolve2, reject }); - this._tryToRun(); - return promise2; - } - }; - var Sync_1 = Sync; - var version3 = "2.19.5"; - var version$1 = { - version: version3 - }; - var version$2 = /* @__PURE__ */ Object.freeze({ - version: version3, - default: version$1 - }); - var require$$2 = () => console.log("You must import the full version of Bottleneck in order to use this feature."); - var require$$3 = () => console.log("You must import the full version of Bottleneck in order to use this feature."); - var require$$4 = () => console.log("You must import the full version of Bottleneck in order to use this feature."); - var Events$2, Group, IORedisConnection$1, RedisConnection$1, Scripts$1, parser$3; - parser$3 = parser; - Events$2 = Events_1; - RedisConnection$1 = require$$2; - IORedisConnection$1 = require$$3; - Scripts$1 = require$$4; - Group = (function() { - class Group2 { - constructor(limiterOptions = {}) { - this.deleteKey = this.deleteKey.bind(this); - this.limiterOptions = limiterOptions; - parser$3.load(this.limiterOptions, this.defaults, this); - this.Events = new Events$2(this); - this.instances = {}; - this.Bottleneck = Bottleneck_1; - this._startAutoCleanup(); - this.sharedConnection = this.connection != null; - if (this.connection == null) { - if (this.limiterOptions.datastore === "redis") { - this.connection = new RedisConnection$1(Object.assign({}, this.limiterOptions, { Events: this.Events })); - } else if (this.limiterOptions.datastore === "ioredis") { - this.connection = new IORedisConnection$1(Object.assign({}, this.limiterOptions, { Events: this.Events })); - } - } - } - key(key = "") { - var ref; - return (ref = this.instances[key]) != null ? ref : (() => { - var limiter; - limiter = this.instances[key] = new this.Bottleneck(Object.assign(this.limiterOptions, { - id: `${this.id}-${key}`, - timeout: this.timeout, - connection: this.connection - })); - this.Events.trigger("created", limiter, key); - return limiter; - })(); - } - async deleteKey(key = "") { - var deleted, instance; - instance = this.instances[key]; - if (this.connection) { - deleted = await this.connection.__runCommand__(["del", ...Scripts$1.allKeys(`${this.id}-${key}`)]); - } - if (instance != null) { - delete this.instances[key]; - await instance.disconnect(); - } - return instance != null || deleted > 0; - } - limiters() { - var k, ref, results, v; - ref = this.instances; - results = []; - for (k in ref) { - v = ref[k]; - results.push({ - key: k, - limiter: v - }); - } - return results; - } - keys() { - return Object.keys(this.instances); - } - async clusterKeys() { - var cursor, end, found, i, k, keys, len, next2, start; - if (this.connection == null) { - return this.Promise.resolve(this.keys()); - } - keys = []; - cursor = null; - start = `b_${this.id}-`.length; - end = "_settings".length; - while (cursor !== 0) { - [next2, found] = await this.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", `b_${this.id}-*_settings`, "count", 1e4]); - cursor = ~~next2; - for (i = 0, len = found.length; i < len; i++) { - k = found[i]; - keys.push(k.slice(start, -end)); - } - } - return keys; - } - _startAutoCleanup() { - var base; - clearInterval(this.interval); - return typeof (base = this.interval = setInterval(async () => { - var e, k, ref, results, time4, v; - time4 = Date.now(); - ref = this.instances; - results = []; - for (k in ref) { - v = ref[k]; - try { - if (await v._store.__groupCheck__(time4)) { - results.push(this.deleteKey(k)); - } else { - results.push(void 0); - } - } catch (error49) { - e = error49; - results.push(v.Events.trigger("error", e)); - } - } - return results; - }, this.timeout / 2)).unref === "function" ? base.unref() : void 0; - } - updateSettings(options = {}) { - parser$3.overwrite(options, this.defaults, this); - parser$3.overwrite(options, options, this.limiterOptions); - if (options.timeout != null) { - return this._startAutoCleanup(); - } - } - disconnect(flush = true) { - var ref; - if (!this.sharedConnection) { - return (ref = this.connection) != null ? ref.disconnect(flush) : void 0; - } - } - } - Group2.prototype.defaults = { - timeout: 1e3 * 60 * 5, - connection: null, - Promise, - id: "group-key" - }; - return Group2; - }).call(commonjsGlobal); - var Group_1 = Group; - var Batcher, Events$3, parser$4; - parser$4 = parser; - Events$3 = Events_1; - Batcher = (function() { - class Batcher2 { - constructor(options = {}) { - this.options = options; - parser$4.load(this.options, this.defaults, this); - this.Events = new Events$3(this); - this._arr = []; - this._resetPromise(); - this._lastFlush = Date.now(); - } - _resetPromise() { - return this._promise = new this.Promise((res, rej) => { - return this._resolve = res; - }); - } - _flush() { - clearTimeout(this._timeout); - this._lastFlush = Date.now(); - this._resolve(); - this.Events.trigger("batch", this._arr); - this._arr = []; - return this._resetPromise(); - } - add(data) { - var ret; - this._arr.push(data); - ret = this._promise; - if (this._arr.length === this.maxSize) { - this._flush(); - } else if (this.maxTime != null && this._arr.length === 1) { - this._timeout = setTimeout(() => { - return this._flush(); - }, this.maxTime); - } - return ret; - } - } - Batcher2.prototype.defaults = { - maxTime: null, - maxSize: null, - Promise - }; - return Batcher2; - }).call(commonjsGlobal); - var Batcher_1 = Batcher; - var require$$4$1 = () => console.log("You must import the full version of Bottleneck in order to use this feature."); - var require$$8 = getCjsExportFromNamespace(version$2); - var Bottleneck, DEFAULT_PRIORITY$1, Events$4, Job$1, LocalDatastore$1, NUM_PRIORITIES$1, Queues$1, RedisDatastore$1, States$1, Sync$1, parser$5, splice = [].splice; - NUM_PRIORITIES$1 = 10; - DEFAULT_PRIORITY$1 = 5; - parser$5 = parser; - Queues$1 = Queues_1; - Job$1 = Job_1; - LocalDatastore$1 = LocalDatastore_1; - RedisDatastore$1 = require$$4$1; - Events$4 = Events_1; - States$1 = States_1; - Sync$1 = Sync_1; - Bottleneck = (function() { - class Bottleneck2 { - constructor(options = {}, ...invalid) { - var storeInstanceOptions, storeOptions; - this._addToQueue = this._addToQueue.bind(this); - this._validateOptions(options, invalid); - parser$5.load(options, this.instanceDefaults, this); - this._queues = new Queues$1(NUM_PRIORITIES$1); - this._scheduled = {}; - this._states = new States$1(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : [])); - this._limiter = null; - this.Events = new Events$4(this); - this._submitLock = new Sync$1("submit", this.Promise); - this._registerLock = new Sync$1("register", this.Promise); - storeOptions = parser$5.load(options, this.storeDefaults, {}); - this._store = (function() { - if (this.datastore === "redis" || this.datastore === "ioredis" || this.connection != null) { - storeInstanceOptions = parser$5.load(options, this.redisStoreDefaults, {}); - return new RedisDatastore$1(this, storeOptions, storeInstanceOptions); - } else if (this.datastore === "local") { - storeInstanceOptions = parser$5.load(options, this.localStoreDefaults, {}); - return new LocalDatastore$1(this, storeOptions, storeInstanceOptions); - } else { - throw new Bottleneck2.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`); - } - }).call(this); - this._queues.on("leftzero", () => { - var ref; - return (ref = this._store.heartbeat) != null ? typeof ref.ref === "function" ? ref.ref() : void 0 : void 0; - }); - this._queues.on("zero", () => { - var ref; - return (ref = this._store.heartbeat) != null ? typeof ref.unref === "function" ? ref.unref() : void 0 : void 0; - }); - } - _validateOptions(options, invalid) { - if (!(options != null && typeof options === "object" && invalid.length === 0)) { - throw new Bottleneck2.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1."); - } - } - ready() { - return this._store.ready; - } - clients() { - return this._store.clients; - } - channel() { - return `b_${this.id}`; - } - channel_client() { - return `b_${this.id}_${this._store.clientId}`; - } - publish(message) { - return this._store.__publish__(message); - } - disconnect(flush = true) { - return this._store.__disconnect__(flush); - } - chain(_limiter) { - this._limiter = _limiter; - return this; - } - queued(priority) { - return this._queues.queued(priority); - } - clusterQueued() { - return this._store.__queued__(); - } - empty() { - return this.queued() === 0 && this._submitLock.isEmpty(); - } - running() { - return this._store.__running__(); - } - done() { - return this._store.__done__(); - } - jobStatus(id) { - return this._states.jobStatus(id); - } - jobs(status) { - return this._states.statusJobs(status); - } - counts() { - return this._states.statusCounts(); - } - _randomIndex() { - return Math.random().toString(36).slice(2); - } - check(weight = 1) { - return this._store.__check__(weight); - } - _clearGlobalState(index) { - if (this._scheduled[index] != null) { - clearTimeout(this._scheduled[index].expiration); - delete this._scheduled[index]; - return true; - } else { - return false; - } - } - async _free(index, job, options, eventInfo) { - var e, running; - try { - ({ running } = await this._store.__free__(index, options.weight)); - this.Events.trigger("debug", `Freed ${options.id}`, eventInfo); - if (running === 0 && this.empty()) { - return this.Events.trigger("idle"); - } - } catch (error1) { - e = error1; - return this.Events.trigger("error", e); - } - } - _run(index, job, wait) { - var clearGlobalState, free, run2; - job.doRun(); - clearGlobalState = this._clearGlobalState.bind(this, index); - run2 = this._run.bind(this, index, job); - free = this._free.bind(this, index, job); - return this._scheduled[index] = { - timeout: setTimeout(() => { - return job.doExecute(this._limiter, clearGlobalState, run2, free); - }, wait), - expiration: job.options.expiration != null ? setTimeout(function() { - return job.doExpire(clearGlobalState, run2, free); - }, wait + job.options.expiration) : void 0, - job - }; - } - _drainOne(capacity) { - return this._registerLock.schedule(() => { - var args2, index, next2, options, queue; - if (this.queued() === 0) { - return this.Promise.resolve(null); - } - queue = this._queues.getFirst(); - ({ options, args: args2 } = next2 = queue.first()); - if (capacity != null && options.weight > capacity) { - return this.Promise.resolve(null); - } - this.Events.trigger("debug", `Draining ${options.id}`, { args: args2, options }); - index = this._randomIndex(); - return this._store.__register__(index, options.weight, options.expiration).then(({ success: success2, wait, reservoir }) => { - var empty; - this.Events.trigger("debug", `Drained ${options.id}`, { success: success2, args: args2, options }); - if (success2) { - queue.shift(); - empty = this.empty(); - if (empty) { - this.Events.trigger("empty"); - } - if (reservoir === 0) { - this.Events.trigger("depleted", empty); - } - this._run(index, next2, wait); - return this.Promise.resolve(options.weight); - } else { - return this.Promise.resolve(null); - } - }); - }); - } - _drainAll(capacity, total = 0) { - return this._drainOne(capacity).then((drained) => { - var newCapacity; - if (drained != null) { - newCapacity = capacity != null ? capacity - drained : capacity; - return this._drainAll(newCapacity, total + drained); - } else { - return this.Promise.resolve(total); - } - }).catch((e) => { - return this.Events.trigger("error", e); - }); - } - _dropAllQueued(message) { - return this._queues.shiftAll(function(job) { - return job.doDrop({ message }); - }); - } - stop(options = {}) { - var done, waitForExecuting; - options = parser$5.load(options, this.stopDefaults); - waitForExecuting = (at) => { - var finished; - finished = () => { - var counts; - counts = this._states.counts; - return counts[0] + counts[1] + counts[2] + counts[3] === at; - }; - return new this.Promise((resolve2, reject) => { - if (finished()) { - return resolve2(); - } else { - return this.on("done", () => { - if (finished()) { - this.removeAllListeners("done"); - return resolve2(); - } - }); - } - }); - }; - done = options.dropWaitingJobs ? (this._run = function(index, next2) { - return next2.doDrop({ - message: options.dropErrorMessage - }); - }, this._drainOne = () => { - return this.Promise.resolve(null); - }, this._registerLock.schedule(() => { - return this._submitLock.schedule(() => { - var k, ref, v; - ref = this._scheduled; - for (k in ref) { - v = ref[k]; - if (this.jobStatus(v.job.options.id) === "RUNNING") { - clearTimeout(v.timeout); - clearTimeout(v.expiration); - v.job.doDrop({ - message: options.dropErrorMessage - }); - } - } - this._dropAllQueued(options.dropErrorMessage); - return waitForExecuting(0); - }); - })) : this.schedule({ - priority: NUM_PRIORITIES$1 - 1, - weight: 0 - }, () => { - return waitForExecuting(1); - }); - this._receive = function(job) { - return job._reject(new Bottleneck2.prototype.BottleneckError(options.enqueueErrorMessage)); - }; - this.stop = () => { - return this.Promise.reject(new Bottleneck2.prototype.BottleneckError("stop() has already been called")); - }; - return done; - } - async _addToQueue(job) { - var args2, blocked, error49, options, reachedHWM, shifted, strategy; - ({ args: args2, options } = job); - try { - ({ reachedHWM, blocked, strategy } = await this._store.__submit__(this.queued(), options.weight)); - } catch (error1) { - error49 = error1; - this.Events.trigger("debug", `Could not queue ${options.id}`, { args: args2, options, error: error49 }); - job.doDrop({ error: error49 }); - return false; - } - if (blocked) { - job.doDrop(); - return true; - } else if (reachedHWM) { - shifted = strategy === Bottleneck2.prototype.strategy.LEAK ? this._queues.shiftLastFrom(options.priority) : strategy === Bottleneck2.prototype.strategy.OVERFLOW_PRIORITY ? this._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck2.prototype.strategy.OVERFLOW ? job : void 0; - if (shifted != null) { - shifted.doDrop(); - } - if (shifted == null || strategy === Bottleneck2.prototype.strategy.OVERFLOW) { - if (shifted == null) { - job.doDrop(); - } - return reachedHWM; - } - } - job.doQueue(reachedHWM, blocked); - this._queues.push(job); - await this._drainAll(); - return reachedHWM; - } - _receive(job) { - if (this._states.jobStatus(job.options.id) != null) { - job._reject(new Bottleneck2.prototype.BottleneckError(`A job with the same id already exists (id=${job.options.id})`)); - return false; - } else { - job.doReceive(); - return this._submitLock.schedule(this._addToQueue, job); - } - } - submit(...args2) { - var cb, fn2, job, options, ref, ref1, task; - if (typeof args2[0] === "function") { - ref = args2, [fn2, ...args2] = ref, [cb] = splice.call(args2, -1); - options = parser$5.load({}, this.jobDefaults); - } else { - ref1 = args2, [options, fn2, ...args2] = ref1, [cb] = splice.call(args2, -1); - options = parser$5.load(options, this.jobDefaults); - } - task = (...args3) => { - return new this.Promise(function(resolve2, reject) { - return fn2(...args3, function(...args4) { - return (args4[0] != null ? reject : resolve2)(args4); - }); - }); - }; - job = new Job$1(task, args2, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); - job.promise.then(function(args3) { - return typeof cb === "function" ? cb(...args3) : void 0; - }).catch(function(args3) { - if (Array.isArray(args3)) { - return typeof cb === "function" ? cb(...args3) : void 0; - } else { - return typeof cb === "function" ? cb(args3) : void 0; - } - }); - return this._receive(job); - } - schedule(...args2) { - var job, options, task; - if (typeof args2[0] === "function") { - [task, ...args2] = args2; - options = {}; - } else { - [options, task, ...args2] = args2; - } - job = new Job$1(task, args2, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); - this._receive(job); - return job.promise; - } - wrap(fn2) { - var schedule, wrapped; - schedule = this.schedule.bind(this); - wrapped = function(...args2) { - return schedule(fn2.bind(this), ...args2); - }; - wrapped.withOptions = function(options, ...args2) { - return schedule(options, fn2, ...args2); - }; - return wrapped; - } - async updateSettings(options = {}) { - await this._store.__updateSettings__(parser$5.overwrite(options, this.storeDefaults)); - parser$5.overwrite(options, this.instanceDefaults, this); - return this; - } - currentReservoir() { - return this._store.__currentReservoir__(); - } - incrementReservoir(incr = 0) { - return this._store.__incrementReservoir__(incr); - } - } - Bottleneck2.default = Bottleneck2; - Bottleneck2.Events = Events$4; - Bottleneck2.version = Bottleneck2.prototype.version = require$$8.version; - Bottleneck2.strategy = Bottleneck2.prototype.strategy = { - LEAK: 1, - OVERFLOW: 2, - OVERFLOW_PRIORITY: 4, - BLOCK: 3 - }; - Bottleneck2.BottleneckError = Bottleneck2.prototype.BottleneckError = BottleneckError_1; - Bottleneck2.Group = Bottleneck2.prototype.Group = Group_1; - Bottleneck2.RedisConnection = Bottleneck2.prototype.RedisConnection = require$$2; - Bottleneck2.IORedisConnection = Bottleneck2.prototype.IORedisConnection = require$$3; - Bottleneck2.Batcher = Bottleneck2.prototype.Batcher = Batcher_1; - Bottleneck2.prototype.jobDefaults = { - priority: DEFAULT_PRIORITY$1, - weight: 1, - expiration: null, - id: "" - }; - Bottleneck2.prototype.storeDefaults = { - maxConcurrent: null, - minTime: 0, - highWater: null, - strategy: Bottleneck2.prototype.strategy.LEAK, - penalty: null, - reservoir: null, - reservoirRefreshInterval: null, - reservoirRefreshAmount: null, - reservoirIncreaseInterval: null, - reservoirIncreaseAmount: null, - reservoirIncreaseMaximum: null - }; - Bottleneck2.prototype.localStoreDefaults = { - Promise, - timeout: null, - heartbeatInterval: 250 - }; - Bottleneck2.prototype.redisStoreDefaults = { - Promise, - timeout: null, - heartbeatInterval: 5e3, - clientTimeout: 1e4, - Redis: null, - clientOptions: {}, - clusterNodes: null, - clearDatastore: false, - connection: null - }; - Bottleneck2.prototype.instanceDefaults = { - datastore: "local", - connection: null, - id: "", - rejectOnDrop: true, - trackDoneStatus: false, - Promise - }; - Bottleneck2.prototype.stopDefaults = { - enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.", - dropWaitingJobs: true, - dropErrorMessage: "This limiter has been stopped." - }; - return Bottleneck2; - }).call(commonjsGlobal); - var Bottleneck_1 = Bottleneck; - var lib = Bottleneck_1; - return lib; - })); - } -}); - -// node_modules/.pnpm/fast-content-type-parse@3.0.0/node_modules/fast-content-type-parse/index.js -var require_fast_content_type_parse = __commonJS({ - "node_modules/.pnpm/fast-content-type-parse@3.0.0/node_modules/fast-content-type-parse/index.js"(exports, module) { - "use strict"; - var NullObject = function NullObject2() { - }; - NullObject.prototype = /* @__PURE__ */ Object.create(null); - var paramRE = /; *([!#$%&'*+.^\w`|~-]+)=("(?:[\v\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\v\u0020-\u00ff])*"|[!#$%&'*+.^\w`|~-]+) */gu; - var quotedPairRE = /\\([\v\u0020-\u00ff])/gu; - var mediaTypeRE = /^[!#$%&'*+.^\w|~-]+\/[!#$%&'*+.^\w|~-]+$/u; - var defaultContentType = { type: "", parameters: new NullObject() }; - Object.freeze(defaultContentType.parameters); - Object.freeze(defaultContentType); - function parse5(header) { - if (typeof header !== "string") { - throw new TypeError("argument header is required and must be a string"); - } - let index = header.indexOf(";"); - const type2 = index !== -1 ? header.slice(0, index).trim() : header.trim(); - if (mediaTypeRE.test(type2) === false) { - throw new TypeError("invalid media type"); - } - const result = { - type: type2.toLowerCase(), - parameters: new NullObject() - }; - if (index === -1) { - return result; - } - let key; - let match3; - let value2; - paramRE.lastIndex = index; - while (match3 = paramRE.exec(header)) { - if (match3.index !== index) { - throw new TypeError("invalid parameter format"); - } - index += match3[0].length; - key = match3[1].toLowerCase(); - value2 = match3[2]; - if (value2[0] === '"') { - value2 = value2.slice(1, value2.length - 1); - quotedPairRE.test(value2) && (value2 = value2.replace(quotedPairRE, "$1")); - } - result.parameters[key] = value2; - } - if (index !== header.length) { - throw new TypeError("invalid parameter format"); - } - return result; - } - function safeParse5(header) { - if (typeof header !== "string") { - return defaultContentType; - } - let index = header.indexOf(";"); - const type2 = index !== -1 ? header.slice(0, index).trim() : header.trim(); - if (mediaTypeRE.test(type2) === false) { - return defaultContentType; - } - const result = { - type: type2.toLowerCase(), - parameters: new NullObject() - }; - if (index === -1) { - return result; - } - let key; - let match3; - let value2; - paramRE.lastIndex = index; - while (match3 = paramRE.exec(header)) { - if (match3.index !== index) { - return defaultContentType; - } - index += match3[0].length; - key = match3[1].toLowerCase(); - value2 = match3[2]; - if (value2[0] === '"') { - value2 = value2.slice(1, value2.length - 1); - quotedPairRE.test(value2) && (value2 = value2.replace(quotedPairRE, "$1")); - } - result.parameters[key] = value2; - } - if (index !== header.length) { - return defaultContentType; - } - return result; - } - module.exports.default = { parse: parse5, safeParse: safeParse5 }; - module.exports.parse = parse5; - module.exports.safeParse = safeParse5; - module.exports.defaultContentType = defaultContentType; - } -}); - // node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/stream/Errors.js var defaultMessages, EndOfStreamError, AbortError; var init_Errors = __esm({ @@ -100066,9 +100066,12618 @@ var mergeFallbacks = (base, merged) => { }; var normalizeFallback = (fallback) => typeof fallback === "function" ? { default: fallback } : fallback ?? {}; +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/errors.js +var ArkError = class _ArkError extends CastableBase { + [arkKind] = "error"; + path; + data; + nodeConfig; + input; + ctx; + // TS gets confused by , so internally we just use the base type for input + constructor({ prefixPath, relativePath, ...input }, ctx) { + super(); + this.input = input; + this.ctx = ctx; + defineProperties(this, input); + const data = ctx.data; + if (input.code === "union") { + input.errors = input.errors.flatMap((innerError) => { + const flat = innerError.hasCode("union") ? innerError.errors : [innerError]; + if (!prefixPath && !relativePath) + return flat; + return flat.map((e) => e.transform((e2) => ({ + ...e2, + path: conflatenateAll(prefixPath, e2.path, relativePath) + }))); + }); + } + this.nodeConfig = ctx.config[this.code]; + const basePath = [...input.path ?? ctx.path]; + if (relativePath) + basePath.push(...relativePath); + if (prefixPath) + basePath.unshift(...prefixPath); + this.path = new ReadonlyPath(...basePath); + this.data = "data" in input ? input.data : data; + } + transform(f) { + return new _ArkError(f({ + data: this.data, + path: this.path, + ...this.input + }), this.ctx); + } + hasCode(code) { + return this.code === code; + } + get propString() { + return stringifyPath(this.path); + } + get expected() { + if (this.input.expected) + return this.input.expected; + const config3 = this.meta?.expected ?? this.nodeConfig.expected; + return typeof config3 === "function" ? config3(this.input) : config3; + } + get actual() { + if (this.input.actual) + return this.input.actual; + const config3 = this.meta?.actual ?? this.nodeConfig.actual; + return typeof config3 === "function" ? config3(this.data) : config3; + } + get problem() { + if (this.input.problem) + return this.input.problem; + const config3 = this.meta?.problem ?? this.nodeConfig.problem; + return typeof config3 === "function" ? config3(this) : config3; + } + get message() { + if (this.input.message) + return this.input.message; + const config3 = this.meta?.message ?? this.nodeConfig.message; + return typeof config3 === "function" ? config3(this) : config3; + } + get flat() { + return this.hasCode("intersection") ? [...this.errors] : [this]; + } + toJSON() { + return { + data: this.data, + path: this.path, + ...this.input, + expected: this.expected, + actual: this.actual, + problem: this.problem, + message: this.message + }; + } + toString() { + return this.message; + } + throw() { + throw this; + } +}; +var ArkErrors = class _ArkErrors extends ReadonlyArray { + [arkKind] = "errors"; + ctx; + constructor(ctx) { + super(); + this.ctx = ctx; + } + /** + * Errors by a pathString representing their location. + */ + byPath = /* @__PURE__ */ Object.create(null); + /** + * {@link byPath} flattened so that each value is an array of ArkError instances at that path. + * + * ✅ Since "intersection" errors will be flattened to their constituent `.errors`, + * they will never be directly present in this representation. + */ + get flatByPath() { + return flatMorph(this.byPath, (k, v) => [k, v.flat]); + } + /** + * {@link byPath} flattened so that each value is an array of problem strings at that path. + */ + get flatProblemsByPath() { + return flatMorph(this.byPath, (k, v) => [k, v.flat.map((e) => e.problem)]); + } + /** + * All pathStrings at which errors are present mapped to the errors occuring + * at that path or any nested path within it. + */ + byAncestorPath = /* @__PURE__ */ Object.create(null); + count = 0; + mutable = this; + /** + * Throw a TraversalError based on these errors. + */ + throw() { + throw this.toTraversalError(); + } + /** + * Converts ArkErrors to TraversalError, a subclass of `Error` suitable for throwing with nice + * formatting. + */ + toTraversalError() { + return new TraversalError(this); + } + /** + * Append an ArkError to this array, ignoring duplicates. + */ + add(error49) { + const existing = this.byPath[error49.propString]; + if (existing) { + if (error49 === existing) + return; + if (existing.hasCode("union") && existing.errors.length === 0) + return; + const errorIntersection = error49.hasCode("union") && error49.errors.length === 0 ? error49 : new ArkError({ + code: "intersection", + errors: existing.hasCode("intersection") ? [...existing.errors, error49] : [existing, error49] + }, this.ctx); + const existingIndex = this.indexOf(existing); + this.mutable[existingIndex === -1 ? this.length : existingIndex] = errorIntersection; + this.byPath[error49.propString] = errorIntersection; + this.addAncestorPaths(error49); + } else { + this.byPath[error49.propString] = error49; + this.addAncestorPaths(error49); + this.mutable.push(error49); + } + this.count++; + } + transform(f) { + const result = new _ArkErrors(this.ctx); + for (const e of this) + result.add(f(e)); + return result; + } + /** + * Add all errors from an ArkErrors instance, ignoring duplicates and + * prefixing their paths with that of the current Traversal. + */ + merge(errors) { + for (const e of errors) { + this.add(new ArkError({ ...e, path: [...this.ctx.path, ...e.path] }, this.ctx)); + } + } + /** + * @internal + */ + affectsPath(path3) { + if (this.length === 0) + return false; + return ( + // this would occur if there is an existing error at a prefix of path + // e.g. the path is ["foo", "bar"] and there is an error at ["foo"] + path3.stringifyAncestors().some((s) => s in this.byPath) || // this would occur if there is an existing error at a suffix of path + // e.g. the path is ["foo"] and there is an error at ["foo", "bar"] + path3.stringify() in this.byAncestorPath + ); + } + /** + * A human-readable summary of all errors. + */ + get summary() { + return this.toString(); + } + /** + * Alias of this ArkErrors instance for StandardSchema compatibility. + */ + get issues() { + return this; + } + toJSON() { + return [...this.map((e) => e.toJSON())]; + } + toString() { + return this.join("\n"); + } + addAncestorPaths(error49) { + for (const propString of error49.path.stringifyAncestors()) { + this.byAncestorPath[propString] = append(this.byAncestorPath[propString], error49); + } + } +}; +var TraversalError = class extends Error { + name = "TraversalError"; + constructor(errors) { + if (errors.length === 1) + super(errors.summary); + else + super("\n" + errors.map((error49) => ` \u2022 ${indent(error49)}`).join("\n")); + Object.defineProperty(this, "arkErrors", { + value: errors, + enumerable: false + }); + } +}; +var indent = (error49) => error49.toString().split("\n").join("\n "); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/traversal.js +var Traversal = class { + /** + * #### the path being validated or morphed + * + * ✅ array indices represented as numbers + * ⚠️ mutated during traversal - use `path.slice(0)` to snapshot + * 🔗 use {@link propString} for a stringified version + */ + path = []; + /** + * #### {@link ArkErrors} that will be part of this traversal's finalized result + * + * ✅ will always be an empty array for a valid traversal + */ + errors = new ArkErrors(this); + /** + * #### the original value being traversed + */ + root; + /** + * #### configuration for this traversal + * + * ✅ options can affect traversal results and error messages + * ✅ defaults < global config < scope config + * ✅ does not include options configured on individual types + */ + config; + queuedMorphs = []; + branches = []; + seen = {}; + constructor(root, config3) { + this.root = root; + this.config = config3; + } + /** + * #### the data being validated or morphed + * + * ✅ extracted from {@link root} at {@link path} + */ + get data() { + let result = this.root; + for (const segment of this.path) + result = result?.[segment]; + return result; + } + /** + * #### a string representing {@link path} + * + * @propString + */ + get propString() { + return stringifyPath(this.path); + } + /** + * #### add an {@link ArkError} and return `false` + * + * ✅ useful for predicates like `.narrow` + */ + reject(input) { + this.error(input); + return false; + } + /** + * #### add an {@link ArkError} from a description and return `false` + * + * ✅ useful for predicates like `.narrow` + * 🔗 equivalent to {@link reject}({ expected }) + */ + mustBe(expected) { + this.error(expected); + return false; + } + error(input) { + const errCtx = typeof input === "object" ? input.code ? input : { ...input, code: "predicate" } : { code: "predicate", expected: input }; + return this.errorFromContext(errCtx); + } + /** + * #### whether {@link currentBranch} (or the traversal root, outside a union) has one or more errors + */ + hasError() { + return this.currentErrorCount !== 0; + } + get currentBranch() { + return this.branches[this.branches.length - 1]; + } + queueMorphs(morphs) { + const input = { + path: new ReadonlyPath(...this.path), + morphs + }; + if (this.currentBranch) + this.currentBranch.queuedMorphs.push(input); + else + this.queuedMorphs.push(input); + } + finalize(onFail) { + if (this.queuedMorphs.length) { + if (typeof this.root === "object" && this.root !== null && this.config.clone) + this.root = this.config.clone(this.root); + this.applyQueuedMorphs(); + } + if (this.hasError()) + return onFail ? onFail(this.errors) : this.errors; + return this.root; + } + get currentErrorCount() { + return this.currentBranch ? this.currentBranch.error ? 1 : 0 : this.errors.count; + } + get failFast() { + return this.branches.length !== 0; + } + pushBranch() { + this.branches.push({ + error: void 0, + queuedMorphs: [] + }); + } + popBranch() { + return this.branches.pop(); + } + /** + * @internal + * Convenience for casting from InternalTraversal to Traversal + * for cases where the extra methods on the external type are expected, e.g. + * a morph or predicate. + */ + get external() { + return this; + } + errorFromNodeContext(input) { + return this.errorFromContext(input); + } + errorFromContext(errCtx) { + const error49 = new ArkError(errCtx, this); + if (this.currentBranch) + this.currentBranch.error = error49; + else + this.errors.add(error49); + return error49; + } + applyQueuedMorphs() { + while (this.queuedMorphs.length) { + const queuedMorphs = this.queuedMorphs; + this.queuedMorphs = []; + for (const { path: path3, morphs } of queuedMorphs) { + if (this.errors.affectsPath(path3)) + continue; + this.applyMorphsAtPath(path3, morphs); + } + } + } + applyMorphsAtPath(path3, morphs) { + const key = path3[path3.length - 1]; + let parent; + if (key !== void 0) { + parent = this.root; + for (let pathIndex = 0; pathIndex < path3.length - 1; pathIndex++) + parent = parent[path3[pathIndex]]; + } + for (const morph of morphs) { + this.path = [...path3]; + const morphIsNode = isNode(morph); + const result = morph(parent === void 0 ? this.root : parent[key], this); + if (result instanceof ArkError) { + if (!this.errors.includes(result)) + this.errors.add(result); + break; + } + if (result instanceof ArkErrors) { + if (!morphIsNode) { + this.errors.merge(result); + } + this.queuedMorphs = []; + break; + } + if (parent === void 0) + this.root = result; + else + parent[key] = result; + this.applyQueuedMorphs(); + } + } +}; +var traverseKey = (key, fn2, ctx) => { + if (!ctx) + return fn2(); + ctx.path.push(key); + const result = fn2(); + ctx.path.pop(); + return result; +}; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/node.js +var BaseNode = class extends Callable { + attachments; + $; + onFail; + includesTransform; + includesContextualPredicate; + isCyclic; + allowsRequiresContext; + rootApplyStrategy; + contextFreeMorph; + rootApply; + referencesById; + shallowReferences; + flatRefs; + flatMorphs; + allows; + get shallowMorphs() { + return []; + } + constructor(attachments, $2) { + super((data, pipedFromCtx, onFail = this.onFail) => { + if (pipedFromCtx) { + this.traverseApply(data, pipedFromCtx); + return pipedFromCtx.hasError() ? pipedFromCtx.errors : pipedFromCtx.data; + } + return this.rootApply(data, onFail); + }, { attach: attachments }); + this.attachments = attachments; + this.$ = $2; + this.onFail = this.meta.onFail ?? this.$.resolvedConfig.onFail; + this.includesTransform = this.hasKind("morph") || this.hasKind("structure") && this.structuralMorph !== void 0 || this.hasKind("sequence") && this.inner.defaultables !== void 0; + this.includesContextualPredicate = this.hasKind("predicate") && this.inner.predicate.length !== 1; + this.isCyclic = this.kind === "alias"; + this.referencesById = { [this.id]: this }; + this.shallowReferences = this.hasKind("structure") ? [this, ...this.children] : this.children.reduce((acc, child) => appendUniqueNodes(acc, child.shallowReferences), [this]); + const isStructural = this.isStructural(); + this.flatRefs = []; + this.flatMorphs = []; + for (let i = 0; i < this.children.length; i++) { + this.includesTransform ||= this.children[i].includesTransform; + this.includesContextualPredicate ||= this.children[i].includesContextualPredicate; + this.isCyclic ||= this.children[i].isCyclic; + if (!isStructural) { + const childFlatRefs = this.children[i].flatRefs; + for (let j = 0; j < childFlatRefs.length; j++) { + const childRef = childFlatRefs[j]; + if (!this.flatRefs.some((existing) => flatRefsAreEqual(existing, childRef))) { + this.flatRefs.push(childRef); + for (const branch of childRef.node.branches) { + if (branch.hasKind("morph") || branch.hasKind("intersection") && branch.structure?.structuralMorph !== void 0) { + this.flatMorphs.push({ + path: childRef.path, + propString: childRef.propString, + node: branch + }); + } + } + } + } + } + Object.assign(this.referencesById, this.children[i].referencesById); + } + this.flatRefs.sort((l, r) => l.path.length > r.path.length ? 1 : l.path.length < r.path.length ? -1 : l.propString > r.propString ? 1 : l.propString < r.propString ? -1 : l.node.expression < r.node.expression ? -1 : 1); + this.allowsRequiresContext = this.includesContextualPredicate || this.isCyclic; + this.rootApplyStrategy = !this.allowsRequiresContext && this.flatMorphs.length === 0 ? this.shallowMorphs.length === 0 ? "allows" : this.shallowMorphs.every((morph) => morph.length === 1 || morph.name === "$arkStructuralMorph") ? this.hasKind("union") ? ( + // multiple morphs not yet supported for optimistic compilation + this.branches.some((branch) => branch.shallowMorphs.length > 1) ? "contextual" : "branchedOptimistic" + ) : this.shallowMorphs.length > 1 ? "contextual" : "optimistic" : "contextual" : "contextual"; + this.rootApply = this.createRootApply(); + this.allows = this.allowsRequiresContext ? (data) => this.traverseAllows(data, new Traversal(data, this.$.resolvedConfig)) : (data) => this.traverseAllows(data); + } + createRootApply() { + switch (this.rootApplyStrategy) { + case "allows": + return (data, onFail) => { + if (this.allows(data)) + return data; + const ctx = new Traversal(data, this.$.resolvedConfig); + this.traverseApply(data, ctx); + return ctx.finalize(onFail); + }; + case "contextual": + return (data, onFail) => { + const ctx = new Traversal(data, this.$.resolvedConfig); + this.traverseApply(data, ctx); + return ctx.finalize(onFail); + }; + case "optimistic": + this.contextFreeMorph = this.shallowMorphs[0]; + const clone3 = this.$.resolvedConfig.clone; + return (data, onFail) => { + if (this.allows(data)) { + return this.contextFreeMorph(clone3 && (typeof data === "object" && data !== null || typeof data === "function") ? clone3(data) : data); + } + const ctx = new Traversal(data, this.$.resolvedConfig); + this.traverseApply(data, ctx); + return ctx.finalize(onFail); + }; + case "branchedOptimistic": + return this.createBranchedOptimisticRootApply(); + default: + this.rootApplyStrategy; + return throwInternalError(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`); + } + } + compiledMeta = compileMeta(this.metaJson); + cacheGetter(name, value2) { + Object.defineProperty(this, name, { value: value2 }); + return value2; + } + get description() { + return this.cacheGetter("description", this.meta?.description ?? this.$.resolvedConfig[this.kind].description(this)); + } + // we don't cache this currently since it can be updated once a scope finishes + // resolving cyclic references, although it may be possible to ensure it is cached safely + get references() { + return Object.values(this.referencesById); + } + precedence = precedenceOfKind(this.kind); + precompilation; + // defined as an arrow function since it is often detached, e.g. when passing to tRPC + // otherwise, would run into issues with this binding + assert = (data, pipedFromCtx) => this(data, pipedFromCtx, (errors) => errors.throw()); + traverse(data, pipedFromCtx) { + return this(data, pipedFromCtx, null); + } + /** rawIn should be used internally instead */ + get in() { + return this.cacheGetter("in", this.rawIn.isRoot() ? this.$.finalize(this.rawIn) : this.rawIn); + } + get rawIn() { + return this.cacheGetter("rawIn", this.getIo("in")); + } + /** rawOut should be used internally instead */ + get out() { + return this.cacheGetter("out", this.rawOut.isRoot() ? this.$.finalize(this.rawOut) : this.rawOut); + } + get rawOut() { + return this.cacheGetter("rawOut", this.getIo("out")); + } + // Should be refactored to use transform + // https://github.com/arktypeio/arktype/issues/1020 + getIo(ioKind) { + if (!this.includesTransform) + return this; + const ioInner = {}; + for (const [k, v] of this.innerEntries) { + const keySchemaImplementation = this.impl.keys[k]; + if (keySchemaImplementation.reduceIo) + keySchemaImplementation.reduceIo(ioKind, ioInner, v); + else if (keySchemaImplementation.child) { + const childValue = v; + ioInner[k] = isArray(childValue) ? childValue.map((child) => ioKind === "in" ? child.rawIn : child.rawOut) : ioKind === "in" ? childValue.rawIn : childValue.rawOut; + } else + ioInner[k] = v; + } + return this.$.node(this.kind, ioInner); + } + toJSON() { + return this.json; + } + toString() { + return `Type<${this.expression}>`; + } + equals(r) { + const rNode = isNode(r) ? r : this.$.parseDefinition(r); + return this.innerHash === rNode.innerHash; + } + ifEquals(r) { + return this.equals(r) ? this : void 0; + } + hasKind(kind) { + return this.kind === kind; + } + assertHasKind(kind) { + if (this.kind !== kind) + throwError(`${this.kind} node was not of asserted kind ${kind}`); + return this; + } + hasKindIn(...kinds) { + return kinds.includes(this.kind); + } + assertHasKindIn(...kinds) { + if (!includes(kinds, this.kind)) + throwError(`${this.kind} node was not one of asserted kinds ${kinds}`); + return this; + } + isBasis() { + return includes(basisKinds, this.kind); + } + isConstraint() { + return includes(constraintKinds, this.kind); + } + isStructural() { + return includes(structuralKinds, this.kind); + } + isRefinement() { + return includes(refinementKinds, this.kind); + } + isRoot() { + return includes(rootKinds, this.kind); + } + isUnknown() { + return this.hasKind("intersection") && this.children.length === 0; + } + isNever() { + return this.hasKind("union") && this.children.length === 0; + } + hasUnit(value2) { + return this.hasKind("unit") && this.allows(value2); + } + hasOpenIntersection() { + return this.impl.intersectionIsOpen; + } + get nestableExpression() { + return this.expression; + } + select(selector) { + const normalized = NodeSelector.normalize(selector); + return this._select(normalized); + } + _select(selector) { + let nodes = NodeSelector.applyBoundary[selector.boundary ?? "references"](this); + if (selector.kind) + nodes = nodes.filter((n) => n.kind === selector.kind); + if (selector.where) + nodes = nodes.filter(selector.where); + return NodeSelector.applyMethod[selector.method ?? "filter"](nodes, this, selector); + } + transform(mapper, opts) { + return this._transform(mapper, this._createTransformContext(opts)); + } + _createTransformContext(opts) { + return { + root: this, + selected: void 0, + seen: {}, + path: [], + parseOptions: { + prereduced: opts?.prereduced ?? false + }, + undeclaredKeyHandling: void 0, + ...opts + }; + } + _transform(mapper, ctx) { + const $2 = ctx.bindScope ?? this.$; + if (ctx.seen[this.id]) + return this.$.lazilyResolve(ctx.seen[this.id]); + if (ctx.shouldTransform?.(this, ctx) === false) + return this; + let transformedNode; + ctx.seen[this.id] = () => transformedNode; + if (this.hasKind("structure") && this.undeclared !== ctx.undeclaredKeyHandling) { + ctx = { + ...ctx, + undeclaredKeyHandling: this.undeclared + }; + } + const innerWithTransformedChildren = flatMorph(this.inner, (k, v) => { + if (!this.impl.keys[k].child) + return [k, v]; + const children = v; + if (!isArray(children)) { + const transformed2 = children._transform(mapper, ctx); + return transformed2 ? [k, transformed2] : []; + } + if (children.length === 0) + return [k, v]; + const transformed = children.flatMap((n) => { + const transformedChild = n._transform(mapper, ctx); + return transformedChild ?? []; + }); + return transformed.length ? [k, transformed] : []; + }); + delete ctx.seen[this.id]; + const innerWithMeta = Object.assign(innerWithTransformedChildren, { + meta: this.meta + }); + const transformedInner = ctx.selected && !ctx.selected.includes(this) ? innerWithMeta : mapper(this.kind, innerWithMeta, ctx); + if (transformedInner === null) + return null; + if (isNode(transformedInner)) + return transformedNode = transformedInner; + const transformedKeys = Object.keys(transformedInner); + const hasNoTypedKeys = transformedKeys.length === 0 || transformedKeys.length === 1 && transformedKeys[0] === "meta"; + if (hasNoTypedKeys && // if inner was previously an empty object (e.g. unknown) ensure it is not pruned + !isEmptyObject(this.inner)) + return null; + if ((this.kind === "required" || this.kind === "optional" || this.kind === "index") && !("value" in transformedInner)) { + return ctx.undeclaredKeyHandling ? { ...transformedInner, value: $ark.intrinsic.unknown } : null; + } + if (this.kind === "morph") { + ; + transformedInner.in ??= $ark.intrinsic.unknown; + } + return transformedNode = $2.node(this.kind, transformedInner, ctx.parseOptions); + } + configureReferences(meta3, selector = "references") { + const normalized = NodeSelector.normalize(selector); + const mapper = typeof meta3 === "string" ? (kind, inner) => ({ + ...inner, + meta: { ...inner.meta, description: meta3 } + }) : typeof meta3 === "function" ? (kind, inner) => ({ ...inner, meta: meta3(inner.meta) }) : (kind, inner) => ({ + ...inner, + meta: { ...inner.meta, ...meta3 } + }); + if (normalized.boundary === "self") { + return this.$.node(this.kind, mapper(this.kind, { ...this.inner, meta: this.meta })); + } + const rawSelected = this._select(normalized); + const selected = rawSelected && liftArray(rawSelected); + const shouldTransform = normalized.boundary === "child" ? (node2, ctx) => ctx.root.children.includes(node2) : normalized.boundary === "shallow" ? (node2) => node2.kind !== "structure" : () => true; + return this.$.finalize(this.transform(mapper, { + shouldTransform, + selected + })); + } +}; +var NodeSelector = { + applyBoundary: { + self: (node2) => [node2], + child: (node2) => [...node2.children], + shallow: (node2) => [...node2.shallowReferences], + references: (node2) => [...node2.references] + }, + applyMethod: { + filter: (nodes) => nodes, + assertFilter: (nodes, from, selector) => { + if (nodes.length === 0) + throwError(writeSelectAssertionMessage(from, selector)); + return nodes; + }, + find: (nodes) => nodes[0], + assertFind: (nodes, from, selector) => { + if (nodes.length === 0) + throwError(writeSelectAssertionMessage(from, selector)); + return nodes[0]; + } + }, + normalize: (selector) => typeof selector === "function" ? { boundary: "references", method: "filter", where: selector } : typeof selector === "string" ? isKeyOf(selector, NodeSelector.applyBoundary) ? { method: "filter", boundary: selector } : { boundary: "references", method: "filter", kind: selector } : { boundary: "references", method: "filter", ...selector } +}; +var writeSelectAssertionMessage = (from, selector) => `${from} had no references matching ${printable(selector)}.`; +var typePathToPropString = (path3) => stringifyPath(path3, { + stringifyNonKey: (node2) => node2.expression +}); +var referenceMatcher = /"(\$ark\.[^"]+)"/g; +var compileMeta = (metaJson) => JSON.stringify(metaJson).replace(referenceMatcher, "$1"); +var flatRef = (path3, node2) => ({ + path: path3, + node: node2, + propString: typePathToPropString(path3) +}); +var flatRefsAreEqual = (l, r) => l.propString === r.propString && l.node.equals(r.node); +var appendUniqueFlatRefs = (existing, refs) => appendUnique(existing, refs, { + isEqual: flatRefsAreEqual +}); +var appendUniqueNodes = (existing, refs) => appendUnique(existing, refs, { + isEqual: (l, r) => l.equals(r) +}); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/disjoint.js +var Disjoint = class _Disjoint extends Array { + static init(kind, l, r, ctx) { + return new _Disjoint({ + kind, + l, + r, + path: ctx?.path ?? [], + optional: ctx?.optional ?? false + }); + } + add(kind, l, r, ctx) { + this.push({ + kind, + l, + r, + path: ctx?.path ?? [], + optional: ctx?.optional ?? false + }); + return this; + } + get summary() { + return this.describeReasons(); + } + describeReasons() { + if (this.length === 1) { + const { path: path3, l, r } = this[0]; + const pathString = stringifyPath(path3); + return writeUnsatisfiableExpressionError(`Intersection${pathString && ` at ${pathString}`} of ${describeReasons(l, r)}`); + } + return `The following intersections result in unsatisfiable types: +\u2022 ${this.map(({ path: path3, l, r }) => `${path3}: ${describeReasons(l, r)}`).join("\n\u2022 ")}`; + } + throw() { + return throwParseError(this.describeReasons()); + } + invert() { + const result = this.map((entry) => ({ + ...entry, + l: entry.r, + r: entry.l + })); + if (!(result instanceof _Disjoint)) + return new _Disjoint(...result); + return result; + } + withPrefixKey(key, kind) { + return this.map((entry) => ({ + ...entry, + path: [key, ...entry.path], + optional: entry.optional || kind === "optional" + })); + } + toNeverIfDisjoint() { + return $ark.intrinsic.never; + } +}; +var describeReasons = (l, r) => `${describeReason(l)} and ${describeReason(r)}`; +var describeReason = (value2) => isNode(value2) ? value2.expression : isArray(value2) ? value2.map(describeReason).join(" | ") || "never" : String(value2); +var writeUnsatisfiableExpressionError = (expression) => `${expression} results in an unsatisfiable type`; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/intersections.js +var intersectionCache = {}; +var intersectNodesRoot = (l, r, $2) => intersectOrPipeNodes(l, r, { + $: $2, + invert: false, + pipe: false +}); +var pipeNodesRoot = (l, r, $2) => intersectOrPipeNodes(l, r, { + $: $2, + invert: false, + pipe: true +}); +var intersectOrPipeNodes = ((l, r, ctx) => { + const operator = ctx.pipe ? "|>" : "&"; + const lrCacheKey = `${l.hash}${operator}${r.hash}`; + if (intersectionCache[lrCacheKey] !== void 0) + return intersectionCache[lrCacheKey]; + if (!ctx.pipe) { + const rlCacheKey = `${r.hash}${operator}${l.hash}`; + if (intersectionCache[rlCacheKey] !== void 0) { + const rlResult = intersectionCache[rlCacheKey]; + const lrResult = rlResult instanceof Disjoint ? rlResult.invert() : rlResult; + intersectionCache[lrCacheKey] = lrResult; + return lrResult; + } + } + const isPureIntersection = !ctx.pipe || !l.includesTransform && !r.includesTransform; + if (isPureIntersection && l.equals(r)) + return l; + let result = isPureIntersection ? _intersectNodes(l, r, ctx) : l.hasKindIn(...rootKinds) ? ( + // if l is a RootNode, r will be as well + _pipeNodes(l, r, ctx) + ) : _intersectNodes(l, r, ctx); + if (isNode(result)) { + if (l.equals(result)) + result = l; + else if (r.equals(result)) + result = r; + } + intersectionCache[lrCacheKey] = result; + return result; +}); +var _intersectNodes = (l, r, ctx) => { + const leftmostKind = l.precedence < r.precedence ? l.kind : r.kind; + const implementation23 = l.impl.intersections[r.kind] ?? r.impl.intersections[l.kind]; + if (implementation23 === void 0) { + return null; + } else if (leftmostKind === l.kind) + return implementation23(l, r, ctx); + else { + let result = implementation23(r, l, { ...ctx, invert: !ctx.invert }); + if (result instanceof Disjoint) + result = result.invert(); + return result; + } +}; +var _pipeNodes = (l, r, ctx) => l.includesTransform || r.includesTransform ? ctx.invert ? pipeMorphed(r, l, ctx) : pipeMorphed(l, r, ctx) : _intersectNodes(l, r, ctx); +var pipeMorphed = (from, to, ctx) => from.distribute((fromBranch) => _pipeMorphed(fromBranch, to, ctx), (results) => { + const viableBranches = results.filter(isNode); + if (viableBranches.length === 0) + return Disjoint.init("union", from.branches, to.branches); + if (viableBranches.length < from.branches.length || !from.branches.every((branch, i) => branch.rawIn.equals(viableBranches[i].rawIn))) + return ctx.$.parseSchema(viableBranches); + let meta3; + if (viableBranches.length === 1) { + const onlyBranch = viableBranches[0]; + if (!meta3) + return onlyBranch; + return ctx.$.node("morph", { + ...onlyBranch.inner, + in: onlyBranch.rawIn.configure(meta3, "self") + }); + } + const schema2 = { + branches: viableBranches + }; + if (meta3) + schema2.meta = meta3; + return ctx.$.parseSchema(schema2); +}); +var _pipeMorphed = (from, to, ctx) => { + const fromIsMorph = from.hasKind("morph"); + if (fromIsMorph) { + const morphs = [...from.morphs]; + if (from.lastMorphIfNode) { + const outIntersection = intersectOrPipeNodes(from.lastMorphIfNode, to, ctx); + if (outIntersection instanceof Disjoint) + return outIntersection; + morphs[morphs.length - 1] = outIntersection; + } else + morphs.push(to); + return ctx.$.node("morph", { + morphs, + in: from.inner.in + }); + } + if (to.hasKind("morph")) { + const inTersection = intersectOrPipeNodes(from, to.rawIn, ctx); + if (inTersection instanceof Disjoint) + return inTersection; + return ctx.$.node("morph", { + morphs: [to], + in: inTersection + }); + } + return ctx.$.node("morph", { + morphs: [to], + in: from + }); +}; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/constraint.js +var BaseConstraint = class extends BaseNode { + constructor(attachments, $2) { + super(attachments, $2); + Object.defineProperty(this, arkKind, { + value: "constraint", + enumerable: false + }); + } + impliedSiblings; + intersect(r) { + return intersectNodesRoot(this, r, this.$); + } +}; +var InternalPrimitiveConstraint = class extends BaseConstraint { + traverseApply = (data, ctx) => { + if (!this.traverseAllows(data, ctx)) + ctx.errorFromNodeContext(this.errorContext); + }; + compile(js) { + if (js.traversalKind === "Allows") + js.return(this.compiledCondition); + else { + js.if(this.compiledNegation, () => js.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`)); + } + } + get errorContext() { + return { + code: this.kind, + description: this.description, + meta: this.meta, + ...this.inner + }; + } + get compiledErrorContext() { + return compileObjectLiteral(this.errorContext); + } +}; +var constraintKeyParser = (kind) => (schema2, ctx) => { + if (isArray(schema2)) { + if (schema2.length === 0) { + return; + } + const nodes = schema2.map((schema3) => ctx.$.node(kind, schema3)); + if (kind === "predicate") + return nodes; + return nodes.sort((l, r) => l.hash < r.hash ? -1 : 1); + } + const child = ctx.$.node(kind, schema2); + return child.hasOpenIntersection() ? [child] : child; +}; +var intersectConstraints = (s) => { + const head = s.r.shift(); + if (!head) { + let result = s.l.length === 0 && s.kind === "structure" ? $ark.intrinsic.unknown.internal : s.ctx.$.node(s.kind, Object.assign(s.baseInner, unflattenConstraints(s.l)), { prereduced: true }); + for (const root of s.roots) { + if (result instanceof Disjoint) + return result; + result = intersectOrPipeNodes(root, result, s.ctx); + } + return result; + } + let matched = false; + for (let i = 0; i < s.l.length; i++) { + const result = intersectOrPipeNodes(s.l[i], head, s.ctx); + if (result === null) + continue; + if (result instanceof Disjoint) + return result; + if (result.isRoot()) { + s.roots.push(result); + s.l.splice(i); + return intersectConstraints(s); + } + if (!matched) { + s.l[i] = result; + matched = true; + } else if (!s.l.includes(result)) { + return throwInternalError(`Unexpectedly encountered multiple distinct intersection results for refinement ${head}`); + } + } + if (!matched) + s.l.push(head); + if (s.kind === "intersection") { + if (head.impliedSiblings) + for (const node2 of head.impliedSiblings) + appendUnique(s.r, node2); + } + return intersectConstraints(s); +}; +var flattenConstraints = (inner) => { + const result = Object.entries(inner).flatMap(([k, v]) => k in constraintKeys ? v : []).sort((l, r) => l.precedence < r.precedence ? -1 : l.precedence > r.precedence ? 1 : l.kind === "predicate" && r.kind === "predicate" ? 0 : l.hash < r.hash ? -1 : 1); + return result; +}; +var unflattenConstraints = (constraints) => { + const inner = {}; + for (const constraint of constraints) { + if (constraint.hasOpenIntersection()) { + inner[constraint.kind] = append(inner[constraint.kind], constraint); + } else { + if (inner[constraint.kind]) { + return throwInternalError(`Unexpected intersection of closed refinements of kind ${constraint.kind}`); + } + inner[constraint.kind] = constraint; + } + } + return inner; +}; +var throwInvalidOperandError = (...args2) => throwParseError(writeInvalidOperandMessage(...args2)); +var writeInvalidOperandMessage = (kind, expected, actual) => { + const actualDescription = actual.hasKind("morph") ? "a morph" : actual.isUnknown() ? "unknown" : actual.exclude(expected).defaultShortDescription; + return `${capitalize(kind)} operand must be ${expected.description} (was ${actualDescription})`; +}; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/generic.js +var parseGeneric = (paramDefs, bodyDef, $2) => new GenericRoot(paramDefs, bodyDef, $2, $2, null); +var LazyGenericBody = class extends Callable { +}; +var GenericRoot = class extends Callable { + [arkKind] = "generic"; + paramDefs; + bodyDef; + $; + arg$; + baseInstantiation; + hkt; + description; + constructor(paramDefs, bodyDef, $2, arg$, hkt) { + super((...args2) => { + const argNodes = flatMorph(this.names, (i, name) => { + const arg = this.arg$.parse(args2[i]); + if (!arg.extends(this.constraints[i])) { + throwParseError(writeUnsatisfiedParameterConstraintMessage(name, this.constraints[i].expression, arg.expression)); + } + return [name, arg]; + }); + if (this.defIsLazy()) { + const def = this.bodyDef(argNodes); + return this.$.parse(def); + } + return this.$.parse(bodyDef, { args: argNodes }); + }); + this.paramDefs = paramDefs; + this.bodyDef = bodyDef; + this.$ = $2; + this.arg$ = arg$; + this.hkt = hkt; + this.description = hkt ? new hkt().description ?? `a generic type for ${hkt.constructor.name}` : "a generic type"; + this.baseInstantiation = this(...this.constraints); + } + defIsLazy() { + return this.bodyDef instanceof LazyGenericBody; + } + cacheGetter(name, value2) { + Object.defineProperty(this, name, { value: value2 }); + return value2; + } + get json() { + return this.cacheGetter("json", { + params: this.params.map((param) => param[1].isUnknown() ? param[0] : [param[0], param[1].json]), + body: snapshot(this.bodyDef) + }); + } + get params() { + return this.cacheGetter("params", this.paramDefs.map((param) => typeof param === "string" ? [param, $ark.intrinsic.unknown] : [param[0], this.$.parse(param[1])])); + } + get names() { + return this.cacheGetter("names", this.params.map((e) => e[0])); + } + get constraints() { + return this.cacheGetter("constraints", this.params.map((e) => e[1])); + } + get internal() { + return this; + } + get referencesById() { + return this.baseInstantiation.internal.referencesById; + } + get references() { + return this.baseInstantiation.internal.references; + } +}; +var writeUnsatisfiedParameterConstraintMessage = (name, constraint, arg) => `${name} must be assignable to ${constraint} (was ${arg})`; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/predicate.js +var implementation = implementNode({ + kind: "predicate", + hasAssociatedError: true, + collapsibleKey: "predicate", + keys: { + predicate: {} + }, + normalize: (schema2) => typeof schema2 === "function" ? { predicate: schema2 } : schema2, + defaults: { + description: (node2) => `valid according to ${node2.predicate.name || "an anonymous predicate"}` + }, + intersectionIsOpen: true, + intersections: { + // as long as the narrows in l and r are individually safe to check + // in the order they're specified, checking them in the order + // resulting from this intersection should also be safe. + predicate: () => null + } +}); +var PredicateNode = class extends BaseConstraint { + serializedPredicate = registeredReference(this.predicate); + compiledCondition = `${this.serializedPredicate}(data, ctx)`; + compiledNegation = `!${this.compiledCondition}`; + impliedBasis = null; + expression = this.serializedPredicate; + traverseAllows = this.predicate; + errorContext = { + code: "predicate", + description: this.description, + meta: this.meta + }; + compiledErrorContext = compileObjectLiteral(this.errorContext); + traverseApply = (data, ctx) => { + const errorCount = ctx.currentErrorCount; + if (!this.predicate(data, ctx.external) && ctx.currentErrorCount === errorCount) + ctx.errorFromNodeContext(this.errorContext); + }; + compile(js) { + if (js.traversalKind === "Allows") { + js.return(this.compiledCondition); + return; + } + js.initializeErrorCount(); + js.if( + // only add the default error if the predicate didn't add one itself + `${this.compiledNegation} && ctx.currentErrorCount === errorCount`, + () => js.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`) + ); + } + reduceJsonSchema(base, ctx) { + return ctx.fallback.predicate({ + code: "predicate", + base, + predicate: this.predicate + }); + } +}; +var Predicate = { + implementation, + Node: PredicateNode +}; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/divisor.js +var implementation2 = implementNode({ + kind: "divisor", + collapsibleKey: "rule", + keys: { + rule: { + parse: (divisor) => Number.isInteger(divisor) ? divisor : throwParseError(writeNonIntegerDivisorMessage(divisor)) + } + }, + normalize: (schema2) => typeof schema2 === "number" ? { rule: schema2 } : schema2, + hasAssociatedError: true, + defaults: { + description: (node2) => node2.rule === 1 ? "an integer" : node2.rule === 2 ? "even" : `a multiple of ${node2.rule}` + }, + intersections: { + divisor: (l, r, ctx) => ctx.$.node("divisor", { + rule: Math.abs(l.rule * r.rule / greatestCommonDivisor(l.rule, r.rule)) + }) + }, + obviatesBasisDescription: true +}); +var DivisorNode = class extends InternalPrimitiveConstraint { + traverseAllows = (data) => data % this.rule === 0; + compiledCondition = `data % ${this.rule} === 0`; + compiledNegation = `data % ${this.rule} !== 0`; + impliedBasis = $ark.intrinsic.number.internal; + expression = `% ${this.rule}`; + reduceJsonSchema(schema2) { + schema2.type = "integer"; + if (this.rule === 1) + return schema2; + schema2.multipleOf = this.rule; + return schema2; + } +}; +var Divisor = { + implementation: implementation2, + Node: DivisorNode +}; +var writeNonIntegerDivisorMessage = (divisor) => `divisor must be an integer (was ${divisor})`; +var greatestCommonDivisor = (l, r) => { + let previous; + let greatestCommonDivisor2 = l; + let current = r; + while (current !== 0) { + previous = current; + current = greatestCommonDivisor2 % current; + greatestCommonDivisor2 = previous; + } + return greatestCommonDivisor2; +}; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/range.js +var BaseRange = class extends InternalPrimitiveConstraint { + boundOperandKind = operandKindsByBoundKind[this.kind]; + compiledActual = this.boundOperandKind === "value" ? `data` : this.boundOperandKind === "length" ? `data.length` : `data.valueOf()`; + comparator = compileComparator(this.kind, this.exclusive); + numericLimit = this.rule.valueOf(); + expression = `${this.comparator} ${this.rule}`; + compiledCondition = `${this.compiledActual} ${this.comparator} ${this.numericLimit}`; + compiledNegation = `${this.compiledActual} ${negatedComparators[this.comparator]} ${this.numericLimit}`; + // we need to compute stringLimit before errorContext, which references it + // transitively through description for date bounds + stringLimit = this.boundOperandKind === "date" ? dateLimitToString(this.numericLimit) : `${this.numericLimit}`; + limitKind = this.comparator["0"] === "<" ? "upper" : "lower"; + isStricterThan(r) { + const thisLimitIsStricter = this.limitKind === "upper" ? this.numericLimit < r.numericLimit : this.numericLimit > r.numericLimit; + return thisLimitIsStricter || this.numericLimit === r.numericLimit && this.exclusive === true && !r.exclusive; + } + overlapsRange(r) { + if (this.isStricterThan(r)) + return false; + if (this.numericLimit === r.numericLimit && (this.exclusive || r.exclusive)) + return false; + return true; + } + overlapIsUnit(r) { + return this.numericLimit === r.numericLimit && !this.exclusive && !r.exclusive; + } +}; +var negatedComparators = { + "<": ">=", + "<=": ">", + ">": "<=", + ">=": "<" +}; +var boundKindPairsByLower = { + min: "max", + minLength: "maxLength", + after: "before" +}; +var parseExclusiveKey = { + // omit key with value false since it is the default + parse: (flag) => flag || void 0 +}; +var createLengthSchemaNormalizer = (kind) => (schema2) => { + if (typeof schema2 === "number") + return { rule: schema2 }; + const { exclusive, ...normalized } = schema2; + return exclusive ? { + ...normalized, + rule: kind === "minLength" ? normalized.rule + 1 : normalized.rule - 1 + } : normalized; +}; +var createDateSchemaNormalizer = (kind) => (schema2) => { + if (typeof schema2 === "number" || typeof schema2 === "string" || schema2 instanceof Date) + return { rule: schema2 }; + const { exclusive, ...normalized } = schema2; + if (!exclusive) + return normalized; + const numericLimit = typeof normalized.rule === "number" ? normalized.rule : typeof normalized.rule === "string" ? new Date(normalized.rule).valueOf() : normalized.rule.valueOf(); + return exclusive ? { + ...normalized, + rule: kind === "after" ? numericLimit + 1 : numericLimit - 1 + } : normalized; +}; +var parseDateLimit = (limit) => typeof limit === "string" || typeof limit === "number" ? new Date(limit) : limit; +var writeInvalidLengthBoundMessage = (kind, limit) => `${kind} bound must be a positive integer (was ${limit})`; +var createLengthRuleParser = (kind) => (limit) => { + if (!Number.isInteger(limit) || limit < 0) + throwParseError(writeInvalidLengthBoundMessage(kind, limit)); + return limit; +}; +var operandKindsByBoundKind = { + min: "value", + max: "value", + minLength: "length", + maxLength: "length", + after: "date", + before: "date" +}; +var compileComparator = (kind, exclusive) => `${isKeyOf(kind, boundKindPairsByLower) ? ">" : "<"}${exclusive ? "" : "="}`; +var dateLimitToString = (limit) => typeof limit === "string" ? limit : new Date(limit).toLocaleString(); +var writeUnboundableMessage = (root) => `Bounded expression ${root} must be exactly one of number, string, Array, or Date`; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/after.js +var implementation3 = implementNode({ + kind: "after", + collapsibleKey: "rule", + hasAssociatedError: true, + keys: { + rule: { + parse: parseDateLimit, + serialize: (schema2) => schema2.toISOString() + } + }, + normalize: createDateSchemaNormalizer("after"), + defaults: { + description: (node2) => `${node2.collapsibleLimitString} or later`, + actual: describeCollapsibleDate + }, + intersections: { + after: (l, r) => l.isStricterThan(r) ? l : r + } +}); +var AfterNode = class extends BaseRange { + impliedBasis = $ark.intrinsic.Date.internal; + collapsibleLimitString = describeCollapsibleDate(this.rule); + traverseAllows = (data) => data >= this.rule; + reduceJsonSchema(base, ctx) { + return ctx.fallback.date({ code: "date", base, after: this.rule }); + } +}; +var After = { + implementation: implementation3, + Node: AfterNode +}; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/before.js +var implementation4 = implementNode({ + kind: "before", + collapsibleKey: "rule", + hasAssociatedError: true, + keys: { + rule: { + parse: parseDateLimit, + serialize: (schema2) => schema2.toISOString() + } + }, + normalize: createDateSchemaNormalizer("before"), + defaults: { + description: (node2) => `${node2.collapsibleLimitString} or earlier`, + actual: describeCollapsibleDate + }, + intersections: { + before: (l, r) => l.isStricterThan(r) ? l : r, + after: (before, after, ctx) => before.overlapsRange(after) ? before.overlapIsUnit(after) ? ctx.$.node("unit", { unit: before.rule }) : null : Disjoint.init("range", before, after) + } +}); +var BeforeNode = class extends BaseRange { + collapsibleLimitString = describeCollapsibleDate(this.rule); + traverseAllows = (data) => data <= this.rule; + impliedBasis = $ark.intrinsic.Date.internal; + reduceJsonSchema(base, ctx) { + return ctx.fallback.date({ code: "date", base, before: this.rule }); + } +}; +var Before = { + implementation: implementation4, + Node: BeforeNode +}; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/exactLength.js +var implementation5 = implementNode({ + kind: "exactLength", + collapsibleKey: "rule", + keys: { + rule: { + parse: createLengthRuleParser("exactLength") + } + }, + normalize: (schema2) => typeof schema2 === "number" ? { rule: schema2 } : schema2, + hasAssociatedError: true, + defaults: { + description: (node2) => `exactly length ${node2.rule}`, + actual: (data) => `${data.length}` + }, + intersections: { + exactLength: (l, r, ctx) => Disjoint.init("unit", ctx.$.node("unit", { unit: l.rule }), ctx.$.node("unit", { unit: r.rule }), { path: ["length"] }), + minLength: (exactLength, minLength) => exactLength.rule >= minLength.rule ? exactLength : Disjoint.init("range", exactLength, minLength), + maxLength: (exactLength, maxLength) => exactLength.rule <= maxLength.rule ? exactLength : Disjoint.init("range", exactLength, maxLength) + } +}); +var ExactLengthNode = class extends InternalPrimitiveConstraint { + traverseAllows = (data) => data.length === this.rule; + compiledCondition = `data.length === ${this.rule}`; + compiledNegation = `data.length !== ${this.rule}`; + impliedBasis = $ark.intrinsic.lengthBoundable.internal; + expression = `== ${this.rule}`; + reduceJsonSchema(schema2) { + switch (schema2.type) { + case "string": + schema2.minLength = this.rule; + schema2.maxLength = this.rule; + return schema2; + case "array": + schema2.minItems = this.rule; + schema2.maxItems = this.rule; + return schema2; + default: + return ToJsonSchema.throwInternalOperandError("exactLength", schema2); + } + } +}; +var ExactLength = { + implementation: implementation5, + Node: ExactLengthNode +}; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/max.js +var implementation6 = implementNode({ + kind: "max", + collapsibleKey: "rule", + hasAssociatedError: true, + keys: { + rule: {}, + exclusive: parseExclusiveKey + }, + normalize: (schema2) => typeof schema2 === "number" ? { rule: schema2 } : schema2, + defaults: { + description: (node2) => { + if (node2.rule === 0) + return node2.exclusive ? "negative" : "non-positive"; + return `${node2.exclusive ? "less than" : "at most"} ${node2.rule}`; + } + }, + intersections: { + max: (l, r) => l.isStricterThan(r) ? l : r, + min: (max, min, ctx) => max.overlapsRange(min) ? max.overlapIsUnit(min) ? ctx.$.node("unit", { unit: max.rule }) : null : Disjoint.init("range", max, min) + }, + obviatesBasisDescription: true +}); +var MaxNode = class extends BaseRange { + impliedBasis = $ark.intrinsic.number.internal; + traverseAllows = this.exclusive ? (data) => data < this.rule : (data) => data <= this.rule; + reduceJsonSchema(schema2) { + if (this.exclusive) + schema2.exclusiveMaximum = this.rule; + else + schema2.maximum = this.rule; + return schema2; + } +}; +var Max = { + implementation: implementation6, + Node: MaxNode +}; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/maxLength.js +var implementation7 = implementNode({ + kind: "maxLength", + collapsibleKey: "rule", + hasAssociatedError: true, + keys: { + rule: { + parse: createLengthRuleParser("maxLength") + } + }, + reduce: (inner, $2) => inner.rule === 0 ? $2.node("exactLength", inner) : void 0, + normalize: createLengthSchemaNormalizer("maxLength"), + defaults: { + description: (node2) => `at most length ${node2.rule}`, + actual: (data) => `${data.length}` + }, + intersections: { + maxLength: (l, r) => l.isStricterThan(r) ? l : r, + minLength: (max, min, ctx) => max.overlapsRange(min) ? max.overlapIsUnit(min) ? ctx.$.node("exactLength", { rule: max.rule }) : null : Disjoint.init("range", max, min) + } +}); +var MaxLengthNode = class extends BaseRange { + impliedBasis = $ark.intrinsic.lengthBoundable.internal; + traverseAllows = (data) => data.length <= this.rule; + reduceJsonSchema(schema2) { + switch (schema2.type) { + case "string": + schema2.maxLength = this.rule; + return schema2; + case "array": + schema2.maxItems = this.rule; + return schema2; + default: + return ToJsonSchema.throwInternalOperandError("maxLength", schema2); + } + } +}; +var MaxLength = { + implementation: implementation7, + Node: MaxLengthNode +}; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/min.js +var implementation8 = implementNode({ + kind: "min", + collapsibleKey: "rule", + hasAssociatedError: true, + keys: { + rule: {}, + exclusive: parseExclusiveKey + }, + normalize: (schema2) => typeof schema2 === "number" ? { rule: schema2 } : schema2, + defaults: { + description: (node2) => { + if (node2.rule === 0) + return node2.exclusive ? "positive" : "non-negative"; + return `${node2.exclusive ? "more than" : "at least"} ${node2.rule}`; + } + }, + intersections: { + min: (l, r) => l.isStricterThan(r) ? l : r + }, + obviatesBasisDescription: true +}); +var MinNode = class extends BaseRange { + impliedBasis = $ark.intrinsic.number.internal; + traverseAllows = this.exclusive ? (data) => data > this.rule : (data) => data >= this.rule; + reduceJsonSchema(schema2) { + if (this.exclusive) + schema2.exclusiveMinimum = this.rule; + else + schema2.minimum = this.rule; + return schema2; + } +}; +var Min = { + implementation: implementation8, + Node: MinNode +}; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/minLength.js +var implementation9 = implementNode({ + kind: "minLength", + collapsibleKey: "rule", + hasAssociatedError: true, + keys: { + rule: { + parse: createLengthRuleParser("minLength") + } + }, + reduce: (inner) => inner.rule === 0 ? ( + // a minimum length of zero is trivially satisfied + $ark.intrinsic.unknown + ) : void 0, + normalize: createLengthSchemaNormalizer("minLength"), + defaults: { + description: (node2) => node2.rule === 1 ? "non-empty" : `at least length ${node2.rule}`, + // avoid default message like "must be non-empty (was 0)" + actual: (data) => data.length === 0 ? "" : `${data.length}` + }, + intersections: { + minLength: (l, r) => l.isStricterThan(r) ? l : r + } +}); +var MinLengthNode = class extends BaseRange { + impliedBasis = $ark.intrinsic.lengthBoundable.internal; + traverseAllows = (data) => data.length >= this.rule; + reduceJsonSchema(schema2) { + switch (schema2.type) { + case "string": + schema2.minLength = this.rule; + return schema2; + case "array": + schema2.minItems = this.rule; + return schema2; + default: + return ToJsonSchema.throwInternalOperandError("minLength", schema2); + } + } +}; +var MinLength = { + implementation: implementation9, + Node: MinLengthNode +}; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/kinds.js +var boundImplementationsByKind = { + min: Min.implementation, + max: Max.implementation, + minLength: MinLength.implementation, + maxLength: MaxLength.implementation, + exactLength: ExactLength.implementation, + after: After.implementation, + before: Before.implementation +}; +var boundClassesByKind = { + min: Min.Node, + max: Max.Node, + minLength: MinLength.Node, + maxLength: MaxLength.Node, + exactLength: ExactLength.Node, + after: After.Node, + before: Before.Node +}; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/pattern.js +var implementation10 = implementNode({ + kind: "pattern", + collapsibleKey: "rule", + keys: { + rule: {}, + flags: {} + }, + normalize: (schema2) => typeof schema2 === "string" ? { rule: schema2 } : schema2 instanceof RegExp ? schema2.flags ? { rule: schema2.source, flags: schema2.flags } : { rule: schema2.source } : schema2, + obviatesBasisDescription: true, + obviatesBasisExpression: true, + hasAssociatedError: true, + intersectionIsOpen: true, + defaults: { + description: (node2) => `matched by ${node2.rule}` + }, + intersections: { + // for now, non-equal regex are naively intersected: + // https://github.com/arktypeio/arktype/issues/853 + pattern: () => null + } +}); +var PatternNode = class extends InternalPrimitiveConstraint { + instance = new RegExp(this.rule, this.flags); + expression = `${this.instance}`; + traverseAllows = this.instance.test.bind(this.instance); + compiledCondition = `${this.expression}.test(data)`; + compiledNegation = `!${this.compiledCondition}`; + impliedBasis = $ark.intrinsic.string.internal; + reduceJsonSchema(base, ctx) { + if (base.pattern) { + return ctx.fallback.patternIntersection({ + code: "patternIntersection", + base, + pattern: this.rule + }); + } + base.pattern = this.rule; + return base; + } +}; +var Pattern = { + implementation: implementation10, + Node: PatternNode +}; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/parse.js +var schemaKindOf = (schema2, allowedKinds) => { + const kind = discriminateRootKind(schema2); + if (allowedKinds && !allowedKinds.includes(kind)) { + return throwParseError(`Root of kind ${kind} should be one of ${allowedKinds}`); + } + return kind; +}; +var discriminateRootKind = (schema2) => { + if (hasArkKind(schema2, "root")) + return schema2.kind; + if (typeof schema2 === "string") { + return schema2[0] === "$" ? "alias" : schema2 in domainDescriptions ? "domain" : "proto"; + } + if (typeof schema2 === "function") + return "proto"; + if (typeof schema2 !== "object" || schema2 === null) + return throwParseError(writeInvalidSchemaMessage(schema2)); + if ("morphs" in schema2) + return "morph"; + if ("branches" in schema2 || isArray(schema2)) + return "union"; + if ("unit" in schema2) + return "unit"; + if ("reference" in schema2) + return "alias"; + const schemaKeys = Object.keys(schema2); + if (schemaKeys.length === 0 || schemaKeys.some((k) => k in constraintKeys)) + return "intersection"; + if ("proto" in schema2) + return "proto"; + if ("domain" in schema2) + return "domain"; + return throwParseError(writeInvalidSchemaMessage(schema2)); +}; +var writeInvalidSchemaMessage = (schema2) => `${printable(schema2)} is not a valid type schema`; +var nodeCountsByPrefix = {}; +var serializeListableChild = (listableNode) => isArray(listableNode) ? listableNode.map((node2) => node2.collapsibleJson) : listableNode.collapsibleJson; +var nodesByRegisteredId = {}; +$ark.nodesByRegisteredId = nodesByRegisteredId; +var registerNodeId = (prefix) => { + nodeCountsByPrefix[prefix] ??= 0; + return `${prefix}${++nodeCountsByPrefix[prefix]}`; +}; +var parseNode = (ctx) => { + const impl = nodeImplementationsByKind[ctx.kind]; + const configuredSchema = impl.applyConfig?.(ctx.def, ctx.$.resolvedConfig) ?? ctx.def; + const inner = {}; + const { meta: metaSchema, ...innerSchema } = configuredSchema; + const meta3 = metaSchema === void 0 ? {} : typeof metaSchema === "string" ? { description: metaSchema } : metaSchema; + const innerSchemaEntries = entriesOf(innerSchema).sort(([lKey], [rKey]) => isNodeKind(lKey) ? isNodeKind(rKey) ? precedenceOfKind(lKey) - precedenceOfKind(rKey) : 1 : isNodeKind(rKey) ? -1 : lKey < rKey ? -1 : 1).filter(([k, v]) => { + if (k.startsWith("meta.")) { + const metaKey = k.slice(5); + meta3[metaKey] = v; + return false; + } + return true; + }); + for (const entry of innerSchemaEntries) { + const k = entry[0]; + const keyImpl = impl.keys[k]; + if (!keyImpl) + return throwParseError(`Key ${k} is not valid on ${ctx.kind} schema`); + const v = keyImpl.parse ? keyImpl.parse(entry[1], ctx) : entry[1]; + if (v !== unset && (v !== void 0 || keyImpl.preserveUndefined)) + inner[k] = v; + } + if (impl.reduce && !ctx.prereduced) { + const reduced = impl.reduce(inner, ctx.$); + if (reduced) { + if (reduced instanceof Disjoint) + return reduced.throw(); + return withMeta(reduced, meta3); + } + } + const node2 = createNode({ + id: ctx.id, + kind: ctx.kind, + inner, + meta: meta3, + $: ctx.$ + }); + return node2; +}; +var createNode = ({ id, kind, inner, meta: meta3, $: $2, ignoreCache }) => { + const impl = nodeImplementationsByKind[kind]; + const innerEntries = entriesOf(inner); + const children = []; + let innerJson = {}; + for (const [k, v] of innerEntries) { + const keyImpl = impl.keys[k]; + const serialize = keyImpl.serialize ?? (keyImpl.child ? serializeListableChild : defaultValueSerializer); + innerJson[k] = serialize(v); + if (keyImpl.child === true) { + const listableNode = v; + if (isArray(listableNode)) + children.push(...listableNode); + else + children.push(listableNode); + } else if (typeof keyImpl.child === "function") + children.push(...keyImpl.child(v)); + } + if (impl.finalizeInnerJson) + innerJson = impl.finalizeInnerJson(innerJson); + let json4 = { ...innerJson }; + let metaJson = {}; + if (!isEmptyObject(meta3)) { + metaJson = flatMorph(meta3, (k, v) => [ + k, + k === "examples" ? v : defaultValueSerializer(v) + ]); + json4.meta = possiblyCollapse(metaJson, "description", true); + } + innerJson = possiblyCollapse(innerJson, impl.collapsibleKey, false); + const innerHash = JSON.stringify({ kind, ...innerJson }); + json4 = possiblyCollapse(json4, impl.collapsibleKey, false); + const collapsibleJson = possiblyCollapse(json4, impl.collapsibleKey, true); + const hash2 = JSON.stringify({ kind, ...json4 }); + if ($2.nodesByHash[hash2] && !ignoreCache) + return $2.nodesByHash[hash2]; + const attachments = { + id, + kind, + impl, + inner, + innerEntries, + innerJson, + innerHash, + meta: meta3, + metaJson, + json: json4, + hash: hash2, + collapsibleJson, + children + }; + if (kind !== "intersection") { + for (const k in inner) + if (k !== "in" && k !== "out") + attachments[k] = inner[k]; + } + const node2 = new nodeClassesByKind[kind](attachments, $2); + return $2.nodesByHash[hash2] = node2; +}; +var withId = (node2, id) => { + if (node2.id === id) + return node2; + if (isNode(nodesByRegisteredId[id])) + throwInternalError(`Unexpected attempt to overwrite node id ${id}`); + return createNode({ + id, + kind: node2.kind, + inner: node2.inner, + meta: node2.meta, + $: node2.$, + ignoreCache: true + }); +}; +var withMeta = (node2, meta3, id) => { + if (id && isNode(nodesByRegisteredId[id])) + throwInternalError(`Unexpected attempt to overwrite node id ${id}`); + return createNode({ + id: id ?? registerNodeId(meta3.alias ?? node2.kind), + kind: node2.kind, + inner: node2.inner, + meta: meta3, + $: node2.$ + }); +}; +var possiblyCollapse = (json4, toKey, allowPrimitive) => { + const collapsibleKeys = Object.keys(json4); + if (collapsibleKeys.length === 1 && collapsibleKeys[0] === toKey) { + const collapsed = json4[toKey]; + if (allowPrimitive) + return collapsed; + if ( + // if the collapsed value is still an object + hasDomain(collapsed, "object") && // and the JSON did not include any implied keys + (Object.keys(collapsed).length === 1 || Array.isArray(collapsed)) + ) { + return collapsed; + } + } + return json4; +}; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/prop.js +var intersectProps = (l, r, ctx) => { + if (l.key !== r.key) + return null; + const key = l.key; + let value2 = intersectOrPipeNodes(l.value, r.value, ctx); + const kind = l.required || r.required ? "required" : "optional"; + if (value2 instanceof Disjoint) { + if (kind === "optional") + value2 = $ark.intrinsic.never.internal; + else { + return value2.withPrefixKey(l.key, l.required && r.required ? "required" : "optional"); + } + } + if (kind === "required") { + return ctx.$.node("required", { + key, + value: value2 + }); + } + const defaultIntersection = l.hasDefault() ? r.hasDefault() ? l.default === r.default ? l.default : throwParseError(writeDefaultIntersectionMessage(l.default, r.default)) : l.default : r.hasDefault() ? r.default : unset; + return ctx.$.node("optional", { + key, + value: value2, + // unset is stripped during parsing + default: defaultIntersection + }); +}; +var BaseProp = class extends BaseConstraint { + required = this.kind === "required"; + optional = this.kind === "optional"; + impliedBasis = $ark.intrinsic.object.internal; + serializedKey = compileSerializedValue(this.key); + compiledKey = typeof this.key === "string" ? this.key : this.serializedKey; + flatRefs = append(this.value.flatRefs.map((ref) => flatRef([this.key, ...ref.path], ref.node)), flatRef([this.key], this.value)); + _transform(mapper, ctx) { + ctx.path.push(this.key); + const result = super._transform(mapper, ctx); + ctx.path.pop(); + return result; + } + hasDefault() { + return "default" in this.inner; + } + traverseAllows = (data, ctx) => { + if (this.key in data) { + return traverseKey(this.key, () => this.value.traverseAllows(data[this.key], ctx), ctx); + } + return this.optional; + }; + traverseApply = (data, ctx) => { + if (this.key in data) { + traverseKey(this.key, () => this.value.traverseApply(data[this.key], ctx), ctx); + } else if (this.hasKind("required")) + ctx.errorFromNodeContext(this.errorContext); + }; + compile(js) { + js.if(`${this.serializedKey} in data`, () => js.traverseKey(this.serializedKey, `data${js.prop(this.key)}`, this.value)); + if (this.hasKind("required")) { + js.else(() => js.traversalKind === "Apply" ? js.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`) : js.return(false)); + } + if (js.traversalKind === "Allows") + js.return(true); + } +}; +var writeDefaultIntersectionMessage = (lValue, rValue) => `Invalid intersection of default values ${printable(lValue)} & ${printable(rValue)}`; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/optional.js +var implementation11 = implementNode({ + kind: "optional", + hasAssociatedError: false, + intersectionIsOpen: true, + keys: { + key: {}, + value: { + child: true, + parse: (schema2, ctx) => ctx.$.parseSchema(schema2) + }, + default: { + preserveUndefined: true + } + }, + normalize: (schema2) => schema2, + reduce: (inner, $2) => { + if ($2.resolvedConfig.exactOptionalPropertyTypes === false) { + if (!inner.value.allows(void 0)) { + return $2.node("optional", { ...inner, value: inner.value.or(intrinsic.undefined) }, { prereduced: true }); + } + } + }, + defaults: { + description: (node2) => `${node2.compiledKey}?: ${node2.value.description}` + }, + intersections: { + optional: intersectProps + } +}); +var OptionalNode = class extends BaseProp { + constructor(...args2) { + super(...args2); + if ("default" in this.inner) + assertDefaultValueAssignability(this.value, this.inner.default, this.key); + } + get rawIn() { + const baseIn = super.rawIn; + if (!this.hasDefault()) + return baseIn; + return this.$.node("optional", omit(baseIn.inner, { default: true }), { + prereduced: true + }); + } + get outProp() { + if (!this.hasDefault()) + return this; + const { default: defaultValue, ...requiredInner } = this.inner; + return this.cacheGetter("outProp", this.$.node("required", requiredInner, { prereduced: true })); + } + expression = this.hasDefault() ? `${this.compiledKey}: ${this.value.expression} = ${printable(this.inner.default)}` : `${this.compiledKey}?: ${this.value.expression}`; + defaultValueMorph = getDefaultableMorph(this); + defaultValueMorphRef = this.defaultValueMorph && registeredReference(this.defaultValueMorph); +}; +var Optional = { + implementation: implementation11, + Node: OptionalNode +}; +var defaultableMorphCache = {}; +var getDefaultableMorph = (node2) => { + if (!node2.hasDefault()) + return; + const cacheKey = `{${node2.compiledKey}: ${node2.value.id} = ${defaultValueSerializer(node2.default)}}`; + return defaultableMorphCache[cacheKey] ??= computeDefaultValueMorph(node2.key, node2.value, node2.default); +}; +var computeDefaultValueMorph = (key, value2, defaultInput) => { + if (typeof defaultInput === "function") { + return value2.includesTransform ? (data, ctx) => { + traverseKey(key, () => value2(data[key] = defaultInput(), ctx), ctx); + return data; + } : (data) => { + data[key] = defaultInput(); + return data; + }; + } + const precomputedMorphedDefault = value2.includesTransform ? value2.assert(defaultInput) : defaultInput; + return hasDomain(precomputedMorphedDefault, "object") ? ( + // the type signature only allows this if the value was morphed + (data, ctx) => { + traverseKey(key, () => value2(data[key] = defaultInput, ctx), ctx); + return data; + } + ) : (data) => { + data[key] = precomputedMorphedDefault; + return data; + }; +}; +var assertDefaultValueAssignability = (node2, value2, key) => { + const wrapped = isThunk(value2); + if (hasDomain(value2, "object") && !wrapped) + throwParseError(writeNonPrimitiveNonFunctionDefaultValueMessage(key)); + const out = node2.in(wrapped ? value2() : value2); + if (out instanceof ArkErrors) { + if (key === null) { + throwParseError(`Default ${out.summary}`); + } + const atPath = out.transform((e) => e.transform((input) => ({ ...input, prefixPath: [key] }))); + throwParseError(`Default for ${atPath.summary}`); + } + return value2; +}; +var writeNonPrimitiveNonFunctionDefaultValueMessage = (key) => { + const keyDescription = key === null ? "" : typeof key === "number" ? `for value at [${key}] ` : `for ${compileSerializedValue(key)} `; + return `Non-primitive default ${keyDescription}must be specified as a function like () => ({my: 'object'})`; +}; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/root.js +var BaseRoot = class extends BaseNode { + constructor(attachments, $2) { + super(attachments, $2); + Object.defineProperty(this, arkKind, { value: "root", enumerable: false }); + } + // doesn't seem possible to override this at a type-level (e.g. via declare) + // without TS complaining about getters + get rawIn() { + return super.rawIn; + } + get rawOut() { + return super.rawOut; + } + get internal() { + return this; + } + get "~standard"() { + return { + vendor: "arktype", + version: 1, + validate: (input) => { + const out = this(input); + if (out instanceof ArkErrors) + return out; + return { value: out }; + }, + jsonSchema: { + input: (opts) => this.rawIn.toJsonSchema({ + target: validateStandardJsonSchemaTarget(opts.target), + ...opts.libraryOptions + }), + output: (opts) => this.rawOut.toJsonSchema({ + target: validateStandardJsonSchemaTarget(opts.target), + ...opts.libraryOptions + }) + } + }; + } + as() { + return this; + } + brand(name) { + if (name === "") + return throwParseError(emptyBrandNameMessage); + return this; + } + readonly() { + return this; + } + branches = this.hasKind("union") ? this.inner.branches : [this]; + distribute(mapBranch, reduceMapped) { + const mappedBranches = this.branches.map(mapBranch); + return reduceMapped?.(mappedBranches) ?? mappedBranches; + } + get shortDescription() { + return this.meta.description ?? this.defaultShortDescription; + } + toJsonSchema(opts = {}) { + const ctx = mergeToJsonSchemaConfigs(this.$.resolvedConfig.toJsonSchema, opts); + ctx.useRefs ||= this.isCyclic; + const schema2 = typeof ctx.dialect === "string" ? { $schema: ctx.dialect } : {}; + Object.assign(schema2, this.toJsonSchemaRecurse(ctx)); + if (ctx.useRefs) { + const defs = flatMorph(this.references, (i, ref) => ref.isRoot() && !ref.alwaysExpandJsonSchema ? [ref.id, ref.toResolvedJsonSchema(ctx)] : []); + if (ctx.target === "draft-07") + Object.assign(schema2, { definitions: defs }); + else + schema2.$defs = defs; + } + return schema2; + } + toJsonSchemaRecurse(ctx) { + if (ctx.useRefs && !this.alwaysExpandJsonSchema) { + const defsKey = ctx.target === "draft-07" ? "definitions" : "$defs"; + return { $ref: `#/${defsKey}/${this.id}` }; + } + return this.toResolvedJsonSchema(ctx); + } + get alwaysExpandJsonSchema() { + return this.isBasis() || this.kind === "alias" || this.hasKind("union") && this.isBoolean; + } + toResolvedJsonSchema(ctx) { + const result = this.innerToJsonSchema(ctx); + return Object.assign(result, this.metaJson); + } + intersect(r) { + const rNode = this.$.parseDefinition(r); + const result = this.rawIntersect(rNode); + if (result instanceof Disjoint) + return result; + return this.$.finalize(result); + } + rawIntersect(r) { + return intersectNodesRoot(this, r, this.$); + } + toNeverIfDisjoint() { + return this; + } + and(r) { + const result = this.intersect(r); + return result instanceof Disjoint ? result.throw() : result; + } + rawAnd(r) { + const result = this.rawIntersect(r); + return result instanceof Disjoint ? result.throw() : result; + } + or(r) { + const rNode = this.$.parseDefinition(r); + return this.$.finalize(this.rawOr(rNode)); + } + rawOr(r) { + const branches = [...this.branches, ...r.branches]; + return this.$.node("union", branches); + } + map(flatMapEntry) { + return this.$.schema(this.applyStructuralOperation("map", [flatMapEntry])); + } + pick(...keys) { + return this.$.schema(this.applyStructuralOperation("pick", keys)); + } + omit(...keys) { + return this.$.schema(this.applyStructuralOperation("omit", keys)); + } + required() { + return this.$.schema(this.applyStructuralOperation("required", [])); + } + partial() { + return this.$.schema(this.applyStructuralOperation("partial", [])); + } + _keyof; + keyof() { + if (this._keyof) + return this._keyof; + const result = this.applyStructuralOperation("keyof", []).reduce((result2, branch) => result2.intersect(branch).toNeverIfDisjoint(), $ark.intrinsic.unknown.internal); + if (result.branches.length === 0) { + throwParseError(writeUnsatisfiableExpressionError(`keyof ${this.expression}`)); + } + return this._keyof = this.$.finalize(result); + } + get props() { + if (this.branches.length !== 1) + return throwParseError(writeLiteralUnionEntriesMessage(this.expression)); + return [...this.applyStructuralOperation("props", [])[0]]; + } + merge(r) { + const rNode = this.$.parseDefinition(r); + return this.$.schema(rNode.distribute((branch) => this.applyStructuralOperation("merge", [ + structureOf(branch) ?? throwParseError(writeNonStructuralOperandMessage("merge", branch.expression)) + ]))); + } + applyStructuralOperation(operation, args2) { + return this.distribute((branch) => { + if (branch.equals($ark.intrinsic.object) && operation !== "merge") + return branch; + const structure = structureOf(branch); + if (!structure) { + throwParseError(writeNonStructuralOperandMessage(operation, branch.expression)); + } + if (operation === "keyof") + return structure.keyof(); + if (operation === "get") + return structure.get(...args2); + if (operation === "props") + return structure.props; + const structuralMethodName = operation === "required" ? "require" : operation === "partial" ? "optionalize" : operation; + return this.$.node("intersection", { + domain: "object", + structure: structure[structuralMethodName](...args2) + }); + }); + } + get(...path3) { + if (path3[0] === void 0) + return this; + return this.$.schema(this.applyStructuralOperation("get", path3)); + } + extract(r) { + const rNode = this.$.parseDefinition(r); + return this.$.schema(this.branches.filter((branch) => branch.extends(rNode))); + } + exclude(r) { + const rNode = this.$.parseDefinition(r); + return this.$.schema(this.branches.filter((branch) => !branch.extends(rNode))); + } + array() { + return this.$.schema(this.isUnknown() ? { proto: Array } : { + proto: Array, + sequence: this + }, { prereduced: true }); + } + overlaps(r) { + const intersection3 = this.intersect(r); + return !(intersection3 instanceof Disjoint); + } + extends(r) { + if (this.isNever()) + return true; + const intersection3 = this.intersect(r); + return !(intersection3 instanceof Disjoint) && this.equals(intersection3); + } + ifExtends(r) { + return this.extends(r) ? this : void 0; + } + subsumes(r) { + const rNode = this.$.parseDefinition(r); + return rNode.extends(this); + } + configure(meta3, selector = "shallow") { + return this.configureReferences(meta3, selector); + } + describe(description, selector = "shallow") { + return this.configure({ description }, selector); + } + // these should ideally be implemented in arktype since they use its syntax + // https://github.com/arktypeio/arktype/issues/1223 + optional() { + return [this, "?"]; + } + // these should ideally be implemented in arktype since they use its syntax + // https://github.com/arktypeio/arktype/issues/1223 + default(thunkableValue) { + assertDefaultValueAssignability(this, thunkableValue, null); + return [this, "=", thunkableValue]; + } + from(input) { + return this.assert(input); + } + _pipe(...morphs) { + const result = morphs.reduce((acc, morph) => acc.rawPipeOnce(morph), this); + return this.$.finalize(result); + } + tryPipe(...morphs) { + const result = morphs.reduce((acc, morph) => acc.rawPipeOnce(hasArkKind(morph, "root") ? morph : ((In, ctx) => { + try { + return morph(In, ctx); + } catch (e) { + return ctx.error({ + code: "predicate", + predicate: morph, + actual: `aborted due to error: + ${e} +` + }); + } + })), this); + return this.$.finalize(result); + } + pipe = Object.assign(this._pipe.bind(this), { + try: this.tryPipe.bind(this) + }); + to(def) { + return this.$.finalize(this.toNode(this.$.parseDefinition(def))); + } + toNode(root) { + const result = pipeNodesRoot(this, root, this.$); + if (result instanceof Disjoint) + return result.throw(); + return result; + } + rawPipeOnce(morph) { + if (hasArkKind(morph, "root")) + return this.toNode(morph); + return this.distribute((branch) => branch.hasKind("morph") ? this.$.node("morph", { + in: branch.inner.in, + morphs: [...branch.morphs, morph] + }) : this.$.node("morph", { + in: branch, + morphs: [morph] + }), this.$.parseSchema); + } + narrow(predicate) { + return this.constrainOut("predicate", predicate); + } + constrain(kind, schema2) { + return this._constrain("root", kind, schema2); + } + constrainIn(kind, schema2) { + return this._constrain("in", kind, schema2); + } + constrainOut(kind, schema2) { + return this._constrain("out", kind, schema2); + } + _constrain(io, kind, schema2) { + const constraint = this.$.node(kind, schema2); + if (constraint.isRoot()) { + return constraint.isUnknown() ? this : throwInternalError(`Unexpected constraint node ${constraint}`); + } + const operand = io === "root" ? this : io === "in" ? this.rawIn : this.rawOut; + if (operand.hasKind("morph") || constraint.impliedBasis && !operand.extends(constraint.impliedBasis)) { + return throwInvalidOperandError(kind, constraint.impliedBasis, this); + } + const partialIntersection = this.$.node("intersection", { + // important this is constraint.kind instead of kind in case + // the node was reduced during parsing + [constraint.kind]: constraint + }); + const result = io === "out" ? pipeNodesRoot(this, partialIntersection, this.$) : intersectNodesRoot(this, partialIntersection, this.$); + if (result instanceof Disjoint) + result.throw(); + return this.$.finalize(result); + } + onUndeclaredKey(cfg) { + const rule = typeof cfg === "string" ? cfg : cfg.rule; + const deep = typeof cfg === "string" ? false : cfg.deep; + return this.$.finalize(this.transform((kind, inner) => kind === "structure" ? rule === "ignore" ? omit(inner, { undeclared: 1 }) : { ...inner, undeclared: rule } : inner, deep ? void 0 : { shouldTransform: (node2) => !includes(structuralKinds, node2.kind) })); + } + hasEqualMorphs(r) { + if (!this.includesTransform && !r.includesTransform) + return true; + if (!arrayEquals(this.shallowMorphs, r.shallowMorphs)) + return false; + if (!arrayEquals(this.flatMorphs, r.flatMorphs, { + isEqual: (l, r2) => l.propString === r2.propString && (l.node.hasKind("morph") && r2.node.hasKind("morph") ? l.node.hasEqualMorphs(r2.node) : l.node.hasKind("intersection") && r2.node.hasKind("intersection") ? l.node.structure?.structuralMorphRef === r2.node.structure?.structuralMorphRef : false) + })) + return false; + return true; + } + onDeepUndeclaredKey(behavior) { + return this.onUndeclaredKey({ rule: behavior, deep: true }); + } + filter(predicate) { + return this.constrainIn("predicate", predicate); + } + divisibleBy(schema2) { + return this.constrain("divisor", schema2); + } + matching(schema2) { + return this.constrain("pattern", schema2); + } + atLeast(schema2) { + return this.constrain("min", schema2); + } + atMost(schema2) { + return this.constrain("max", schema2); + } + moreThan(schema2) { + return this.constrain("min", exclusivizeRangeSchema(schema2)); + } + lessThan(schema2) { + return this.constrain("max", exclusivizeRangeSchema(schema2)); + } + atLeastLength(schema2) { + return this.constrain("minLength", schema2); + } + atMostLength(schema2) { + return this.constrain("maxLength", schema2); + } + moreThanLength(schema2) { + return this.constrain("minLength", exclusivizeRangeSchema(schema2)); + } + lessThanLength(schema2) { + return this.constrain("maxLength", exclusivizeRangeSchema(schema2)); + } + exactlyLength(schema2) { + return this.constrain("exactLength", schema2); + } + atOrAfter(schema2) { + return this.constrain("after", schema2); + } + atOrBefore(schema2) { + return this.constrain("before", schema2); + } + laterThan(schema2) { + return this.constrain("after", exclusivizeRangeSchema(schema2)); + } + earlierThan(schema2) { + return this.constrain("before", exclusivizeRangeSchema(schema2)); + } +}; +var emptyBrandNameMessage = `Expected a non-empty brand name after #`; +var supportedJsonSchemaTargets = [ + "draft-2020-12", + "draft-07" +]; +var writeInvalidJsonSchemaTargetMessage = (target) => `JSONSchema target '${target}' is not supported (must be ${supportedJsonSchemaTargets.map((t) => `"${t}"`).join(" or ")})`; +var validateStandardJsonSchemaTarget = (target) => { + if (!includes(supportedJsonSchemaTargets, target)) + throwParseError(writeInvalidJsonSchemaTargetMessage(target)); + return target; +}; +var exclusivizeRangeSchema = (schema2) => typeof schema2 === "object" && !(schema2 instanceof Date) ? { ...schema2, exclusive: true } : { + rule: schema2, + exclusive: true +}; +var typeOrTermExtends = (t, base) => hasArkKind(base, "root") ? hasArkKind(t, "root") ? t.extends(base) : base.allows(t) : hasArkKind(t, "root") ? t.hasUnit(base) : base === t; +var structureOf = (branch) => { + if (branch.hasKind("morph")) + return null; + if (branch.hasKind("intersection")) { + return branch.inner.structure ?? (branch.basis?.domain === "object" ? branch.$.bindReference($ark.intrinsic.emptyStructure) : null); + } + if (branch.isBasis() && branch.domain === "object") + return branch.$.bindReference($ark.intrinsic.emptyStructure); + return null; +}; +var writeLiteralUnionEntriesMessage = (expression) => `Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received: +${expression}`; +var writeNonStructuralOperandMessage = (operation, operand) => `${operation} operand must be an object (was ${operand})`; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/utils.js +var defineRightwardIntersections = (kind, implementation23) => flatMorph(schemaKindsRightOf(kind), (i, kind2) => [ + kind2, + implementation23 +]); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/alias.js +var normalizeAliasSchema = (schema2) => typeof schema2 === "string" ? { reference: schema2 } : schema2; +var neverIfDisjoint = (result) => result instanceof Disjoint ? $ark.intrinsic.never.internal : result; +var implementation12 = implementNode({ + kind: "alias", + hasAssociatedError: false, + collapsibleKey: "reference", + keys: { + reference: { + serialize: (s) => s.startsWith("$") ? s : `$ark.${s}` + }, + resolve: {} + }, + normalize: normalizeAliasSchema, + defaults: { + description: (node2) => node2.reference + }, + intersections: { + alias: (l, r, ctx) => ctx.$.lazilyResolve(() => neverIfDisjoint(intersectOrPipeNodes(l.resolution, r.resolution, ctx)), `${l.reference}${ctx.pipe ? "=>" : "&"}${r.reference}`), + ...defineRightwardIntersections("alias", (l, r, ctx) => { + if (r.isUnknown()) + return l; + if (r.isNever()) + return r; + if (r.isBasis() && !r.overlaps($ark.intrinsic.object)) { + return Disjoint.init("assignability", $ark.intrinsic.object, r); + } + return ctx.$.lazilyResolve(() => neverIfDisjoint(intersectOrPipeNodes(l.resolution, r, ctx)), `${l.reference}${ctx.pipe ? "=>" : "&"}${r.id}`); + }) + } +}); +var AliasNode = class extends BaseRoot { + expression = this.reference; + structure = void 0; + get resolution() { + const result = this._resolve(); + return nodesByRegisteredId[this.id] = result; + } + _resolve() { + if (this.resolve) + return this.resolve(); + if (this.reference[0] === "$") + return this.$.resolveRoot(this.reference.slice(1)); + const id = this.reference; + let resolution = nodesByRegisteredId[id]; + const seen = []; + while (hasArkKind(resolution, "context")) { + if (seen.includes(resolution.id)) { + return throwParseError(writeShallowCycleErrorMessage(resolution.id, seen)); + } + seen.push(resolution.id); + resolution = nodesByRegisteredId[resolution.id]; + } + if (!hasArkKind(resolution, "root")) { + return throwInternalError(`Unexpected resolution for reference ${this.reference} +Seen: [${seen.join("->")}] +Resolution: ${printable(resolution)}`); + } + return resolution; + } + get resolutionId() { + if (this.reference.includes("&") || this.reference.includes("=>")) + return this.resolution.id; + if (this.reference[0] !== "$") + return this.reference; + const alias = this.reference.slice(1); + const resolution = this.$.resolutions[alias]; + if (typeof resolution === "string") + return resolution; + if (hasArkKind(resolution, "root")) + return resolution.id; + return throwInternalError(`Unexpected resolution for reference ${this.reference}: ${printable(resolution)}`); + } + get defaultShortDescription() { + return domainDescriptions.object; + } + innerToJsonSchema(ctx) { + return this.resolution.toJsonSchemaRecurse(ctx); + } + traverseAllows = (data, ctx) => { + const seen = ctx.seen[this.reference]; + if (seen?.includes(data)) + return true; + ctx.seen[this.reference] = append(seen, data); + return this.resolution.traverseAllows(data, ctx); + }; + traverseApply = (data, ctx) => { + const seen = ctx.seen[this.reference]; + if (seen?.includes(data)) + return; + ctx.seen[this.reference] = append(seen, data); + this.resolution.traverseApply(data, ctx); + }; + compile(js) { + const id = this.resolutionId; + js.if(`ctx.seen.${id} && ctx.seen.${id}.includes(data)`, () => js.return(true)); + js.if(`!ctx.seen.${id}`, () => js.line(`ctx.seen.${id} = []`)); + js.line(`ctx.seen.${id}.push(data)`); + js.return(js.invoke(id)); + } +}; +var writeShallowCycleErrorMessage = (name, seen) => `Alias '${name}' has a shallow resolution cycle: ${[...seen, name].join("->")}`; +var Alias = { + implementation: implementation12, + Node: AliasNode +}; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/basis.js +var InternalBasis = class extends BaseRoot { + traverseApply = (data, ctx) => { + if (!this.traverseAllows(data, ctx)) + ctx.errorFromNodeContext(this.errorContext); + }; + get errorContext() { + return { + code: this.kind, + description: this.description, + meta: this.meta, + ...this.inner + }; + } + get compiledErrorContext() { + return compileObjectLiteral(this.errorContext); + } + compile(js) { + if (js.traversalKind === "Allows") + js.return(this.compiledCondition); + else { + js.if(this.compiledNegation, () => js.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`)); + } + } +}; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/domain.js +var implementation13 = implementNode({ + kind: "domain", + hasAssociatedError: true, + collapsibleKey: "domain", + keys: { + domain: {}, + numberAllowsNaN: {} + }, + normalize: (schema2) => typeof schema2 === "string" ? { domain: schema2 } : hasKey(schema2, "numberAllowsNaN") && schema2.domain !== "number" ? throwParseError(Domain.writeBadAllowNanMessage(schema2.domain)) : schema2, + applyConfig: (schema2, config3) => schema2.numberAllowsNaN === void 0 && schema2.domain === "number" && config3.numberAllowsNaN ? { ...schema2, numberAllowsNaN: true } : schema2, + defaults: { + description: (node2) => domainDescriptions[node2.domain], + actual: (data) => Number.isNaN(data) ? "NaN" : domainDescriptions[domainOf(data)] + }, + intersections: { + domain: (l, r) => ( + // since l === r is handled by default, remaining cases are disjoint + // outside those including options like numberAllowsNaN + l.domain === "number" && r.domain === "number" ? l.numberAllowsNaN ? r : l : Disjoint.init("domain", l, r) + ) + } +}); +var DomainNode = class extends InternalBasis { + requiresNaNCheck = this.domain === "number" && !this.numberAllowsNaN; + traverseAllows = this.requiresNaNCheck ? (data) => typeof data === "number" && !Number.isNaN(data) : (data) => domainOf(data) === this.domain; + compiledCondition = this.domain === "object" ? `((typeof data === "object" && data !== null) || typeof data === "function")` : `typeof data === "${this.domain}"${this.requiresNaNCheck ? " && !Number.isNaN(data)" : ""}`; + compiledNegation = this.domain === "object" ? `((typeof data !== "object" || data === null) && typeof data !== "function")` : `typeof data !== "${this.domain}"${this.requiresNaNCheck ? " || Number.isNaN(data)" : ""}`; + expression = this.numberAllowsNaN ? "number | NaN" : this.domain; + get nestableExpression() { + return this.numberAllowsNaN ? `(${this.expression})` : this.expression; + } + get defaultShortDescription() { + return domainDescriptions[this.domain]; + } + innerToJsonSchema(ctx) { + if (this.domain === "bigint" || this.domain === "symbol") { + return ctx.fallback.domain({ + code: "domain", + base: {}, + domain: this.domain + }); + } + return { + type: this.domain + }; + } +}; +var Domain = { + implementation: implementation13, + Node: DomainNode, + writeBadAllowNanMessage: (actual) => `numberAllowsNaN may only be specified with domain "number" (was ${actual})` +}; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/intersection.js +var implementation14 = implementNode({ + kind: "intersection", + hasAssociatedError: true, + normalize: (rawSchema) => { + if (isNode(rawSchema)) + return rawSchema; + const { structure, ...schema2 } = rawSchema; + const hasRootStructureKey = !!structure; + const normalizedStructure = structure ?? {}; + const normalized = flatMorph(schema2, (k, v) => { + if (isKeyOf(k, structureKeys)) { + if (hasRootStructureKey) { + throwParseError(`Flattened structure key ${k} cannot be specified alongside a root 'structure' key.`); + } + normalizedStructure[k] = v; + return []; + } + return [k, v]; + }); + if (hasArkKind(normalizedStructure, "constraint") || !isEmptyObject(normalizedStructure)) + normalized.structure = normalizedStructure; + return normalized; + }, + finalizeInnerJson: ({ structure, ...rest }) => hasDomain(structure, "object") ? { ...structure, ...rest } : rest, + keys: { + domain: { + child: true, + parse: (schema2, ctx) => ctx.$.node("domain", schema2) + }, + proto: { + child: true, + parse: (schema2, ctx) => ctx.$.node("proto", schema2) + }, + structure: { + child: true, + parse: (schema2, ctx) => ctx.$.node("structure", schema2), + serialize: (node2) => { + if (!node2.sequence?.minLength) + return node2.collapsibleJson; + const { sequence, ...structureJson } = node2.collapsibleJson; + const { minVariadicLength, ...sequenceJson } = sequence; + const collapsibleSequenceJson = sequenceJson.variadic && Object.keys(sequenceJson).length === 1 ? sequenceJson.variadic : sequenceJson; + return { ...structureJson, sequence: collapsibleSequenceJson }; + } + }, + divisor: { + child: true, + parse: constraintKeyParser("divisor") + }, + max: { + child: true, + parse: constraintKeyParser("max") + }, + min: { + child: true, + parse: constraintKeyParser("min") + }, + maxLength: { + child: true, + parse: constraintKeyParser("maxLength") + }, + minLength: { + child: true, + parse: constraintKeyParser("minLength") + }, + exactLength: { + child: true, + parse: constraintKeyParser("exactLength") + }, + before: { + child: true, + parse: constraintKeyParser("before") + }, + after: { + child: true, + parse: constraintKeyParser("after") + }, + pattern: { + child: true, + parse: constraintKeyParser("pattern") + }, + predicate: { + child: true, + parse: constraintKeyParser("predicate") + } + }, + // leverage reduction logic from intersection and identity to ensure initial + // parse result is reduced + reduce: (inner, $2) => ( + // we cast union out of the result here since that only occurs when intersecting two sequences + // that cannot occur when reducing a single intersection schema using unknown + intersectIntersections({}, inner, { + $: $2, + invert: false, + pipe: false + }) + ), + defaults: { + description: (node2) => { + if (node2.children.length === 0) + return "unknown"; + if (node2.structure) + return node2.structure.description; + const childDescriptions = []; + if (node2.basis && !node2.prestructurals.some((r) => r.impl.obviatesBasisDescription)) + childDescriptions.push(node2.basis.description); + if (node2.prestructurals.length) { + const sortedRefinementDescriptions = node2.prestructurals.slice().sort((l, r) => l.kind === "min" && r.kind === "max" ? -1 : 0).map((r) => r.description); + childDescriptions.push(...sortedRefinementDescriptions); + } + if (node2.inner.predicate) { + childDescriptions.push(...node2.inner.predicate.map((p) => p.description)); + } + return childDescriptions.join(" and "); + }, + expected: (source) => ` \u25E6 ${source.errors.map((e) => e.expected).join("\n \u25E6 ")}`, + problem: (ctx) => `(${ctx.actual}) must be... +${ctx.expected}` + }, + intersections: { + intersection: (l, r, ctx) => intersectIntersections(l.inner, r.inner, ctx), + ...defineRightwardIntersections("intersection", (l, r, ctx) => { + if (l.children.length === 0) + return r; + const { domain: domain2, proto, ...lInnerConstraints } = l.inner; + const lBasis = proto ?? domain2; + const basis = lBasis ? intersectOrPipeNodes(lBasis, r, ctx) : r; + return basis instanceof Disjoint ? basis : l?.basis?.equals(basis) ? ( + // if the basis doesn't change, return the original intesection + l + ) : l.$.node("intersection", { ...lInnerConstraints, [basis.kind]: basis }, { prereduced: true }); + }) + } +}); +var IntersectionNode = class extends BaseRoot { + basis = this.inner.domain ?? this.inner.proto ?? null; + prestructurals = []; + refinements = this.children.filter((node2) => { + if (!node2.isRefinement()) + return false; + if (includes(prestructuralKinds, node2.kind)) + this.prestructurals.push(node2); + return true; + }); + structure = this.inner.structure; + expression = writeIntersectionExpression(this); + get shallowMorphs() { + return this.inner.structure?.structuralMorph ? [this.inner.structure.structuralMorph] : []; + } + get defaultShortDescription() { + return this.basis?.defaultShortDescription ?? "present"; + } + innerToJsonSchema(ctx) { + return this.children.reduce( + // cast is required since TS doesn't know children have compatible schema prerequisites + (schema2, child) => child.isBasis() ? child.toJsonSchemaRecurse(ctx) : child.reduceJsonSchema(schema2, ctx), + {} + ); + } + traverseAllows = (data, ctx) => this.children.every((child) => child.traverseAllows(data, ctx)); + traverseApply = (data, ctx) => { + const errorCount = ctx.currentErrorCount; + if (this.basis) { + this.basis.traverseApply(data, ctx); + if (ctx.currentErrorCount > errorCount) + return; + } + if (this.prestructurals.length) { + for (let i = 0; i < this.prestructurals.length - 1; i++) { + this.prestructurals[i].traverseApply(data, ctx); + if (ctx.failFast && ctx.currentErrorCount > errorCount) + return; + } + this.prestructurals[this.prestructurals.length - 1].traverseApply(data, ctx); + if (ctx.currentErrorCount > errorCount) + return; + } + if (this.structure) { + this.structure.traverseApply(data, ctx); + if (ctx.currentErrorCount > errorCount) + return; + } + if (this.inner.predicate) { + for (let i = 0; i < this.inner.predicate.length - 1; i++) { + this.inner.predicate[i].traverseApply(data, ctx); + if (ctx.failFast && ctx.currentErrorCount > errorCount) + return; + } + this.inner.predicate[this.inner.predicate.length - 1].traverseApply(data, ctx); + } + }; + compile(js) { + if (js.traversalKind === "Allows") { + for (const child of this.children) + js.check(child); + js.return(true); + return; + } + js.initializeErrorCount(); + if (this.basis) { + js.check(this.basis); + if (this.children.length > 1) + js.returnIfFail(); + } + if (this.prestructurals.length) { + for (let i = 0; i < this.prestructurals.length - 1; i++) { + js.check(this.prestructurals[i]); + js.returnIfFailFast(); + } + js.check(this.prestructurals[this.prestructurals.length - 1]); + if (this.structure || this.inner.predicate) + js.returnIfFail(); + } + if (this.structure) { + js.check(this.structure); + if (this.inner.predicate) + js.returnIfFail(); + } + if (this.inner.predicate) { + for (let i = 0; i < this.inner.predicate.length - 1; i++) { + js.check(this.inner.predicate[i]); + js.returnIfFail(); + } + js.check(this.inner.predicate[this.inner.predicate.length - 1]); + } + } +}; +var Intersection = { + implementation: implementation14, + Node: IntersectionNode +}; +var writeIntersectionExpression = (node2) => { + if (node2.structure?.expression) + return node2.structure.expression; + const basisExpression = node2.basis && !node2.prestructurals.some((n) => n.impl.obviatesBasisExpression) ? node2.basis.nestableExpression : ""; + const refinementsExpression = node2.prestructurals.map((n) => n.expression).join(" & "); + const fullExpression = `${basisExpression}${basisExpression ? " " : ""}${refinementsExpression}`; + if (fullExpression === "Array == 0") + return "[]"; + return fullExpression || "unknown"; +}; +var intersectIntersections = (l, r, ctx) => { + const baseInner = {}; + const lBasis = l.proto ?? l.domain; + const rBasis = r.proto ?? r.domain; + const basisResult = lBasis ? rBasis ? intersectOrPipeNodes(lBasis, rBasis, ctx) : lBasis : rBasis; + if (basisResult instanceof Disjoint) + return basisResult; + if (basisResult) + baseInner[basisResult.kind] = basisResult; + return intersectConstraints({ + kind: "intersection", + baseInner, + l: flattenConstraints(l), + r: flattenConstraints(r), + roots: [], + ctx + }); +}; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/morph.js +var implementation15 = implementNode({ + kind: "morph", + hasAssociatedError: false, + keys: { + in: { + child: true, + parse: (schema2, ctx) => ctx.$.parseSchema(schema2) + }, + morphs: { + parse: liftArray, + serialize: (morphs) => morphs.map((m) => hasArkKind(m, "root") ? m.json : registeredReference(m)) + }, + declaredIn: { + child: false, + serialize: (node2) => node2.json + }, + declaredOut: { + child: false, + serialize: (node2) => node2.json + } + }, + normalize: (schema2) => schema2, + defaults: { + description: (node2) => `a morph from ${node2.rawIn.description} to ${node2.rawOut?.description ?? "unknown"}` + }, + intersections: { + morph: (l, r, ctx) => { + if (!l.hasEqualMorphs(r)) { + return throwParseError(writeMorphIntersectionMessage(l.expression, r.expression)); + } + const inTersection = intersectOrPipeNodes(l.rawIn, r.rawIn, ctx); + if (inTersection instanceof Disjoint) + return inTersection; + const baseInner = { + morphs: l.morphs + }; + if (l.declaredIn || r.declaredIn) { + const declaredIn = intersectOrPipeNodes(l.rawIn, r.rawIn, ctx); + if (declaredIn instanceof Disjoint) + return declaredIn.throw(); + else + baseInner.declaredIn = declaredIn; + } + if (l.declaredOut || r.declaredOut) { + const declaredOut = intersectOrPipeNodes(l.rawOut, r.rawOut, ctx); + if (declaredOut instanceof Disjoint) + return declaredOut.throw(); + else + baseInner.declaredOut = declaredOut; + } + return inTersection.distribute((inBranch) => ctx.$.node("morph", { + ...baseInner, + in: inBranch + }), ctx.$.parseSchema); + }, + ...defineRightwardIntersections("morph", (l, r, ctx) => { + const inTersection = l.inner.in ? intersectOrPipeNodes(l.inner.in, r, ctx) : r; + return inTersection instanceof Disjoint ? inTersection : inTersection.equals(l.inner.in) ? l : ctx.$.node("morph", { + ...l.inner, + in: inTersection + }); + }) + } +}); +var MorphNode = class extends BaseRoot { + serializedMorphs = this.morphs.map(registeredReference); + compiledMorphs = `[${this.serializedMorphs}]`; + lastMorph = this.inner.morphs[this.inner.morphs.length - 1]; + lastMorphIfNode = hasArkKind(this.lastMorph, "root") ? this.lastMorph : void 0; + introspectableIn = this.inner.in; + introspectableOut = this.lastMorphIfNode ? Object.assign(this.referencesById, this.lastMorphIfNode.referencesById) && this.lastMorphIfNode.rawOut : void 0; + get shallowMorphs() { + return Array.isArray(this.inner.in?.shallowMorphs) ? [...this.inner.in.shallowMorphs, ...this.morphs] : this.morphs; + } + get rawIn() { + return this.declaredIn ?? this.inner.in?.rawIn ?? $ark.intrinsic.unknown.internal; + } + get rawOut() { + return this.declaredOut ?? this.introspectableOut ?? $ark.intrinsic.unknown.internal; + } + declareIn(declaredIn) { + return this.$.node("morph", { + ...this.inner, + declaredIn + }); + } + declareOut(declaredOut) { + return this.$.node("morph", { + ...this.inner, + declaredOut + }); + } + expression = `(In: ${this.rawIn.expression}) => ${this.lastMorphIfNode ? "To" : "Out"}<${this.rawOut.expression}>`; + get defaultShortDescription() { + return this.rawIn.meta.description ?? this.rawIn.defaultShortDescription; + } + innerToJsonSchema(ctx) { + return ctx.fallback.morph({ + code: "morph", + base: this.rawIn.toJsonSchemaRecurse(ctx), + out: this.introspectableOut?.toJsonSchemaRecurse(ctx) ?? null + }); + } + compile(js) { + if (js.traversalKind === "Allows") { + if (!this.introspectableIn) + return; + js.return(js.invoke(this.introspectableIn)); + return; + } + if (this.introspectableIn) + js.line(js.invoke(this.introspectableIn)); + js.line(`ctx.queueMorphs(${this.compiledMorphs})`); + } + traverseAllows = (data, ctx) => !this.introspectableIn || this.introspectableIn.traverseAllows(data, ctx); + traverseApply = (data, ctx) => { + if (this.introspectableIn) + this.introspectableIn.traverseApply(data, ctx); + ctx.queueMorphs(this.morphs); + }; + /** Check if the morphs of r are equal to those of this node */ + hasEqualMorphs(r) { + return arrayEquals(this.morphs, r.morphs, { + isEqual: (lMorph, rMorph) => lMorph === rMorph || hasArkKind(lMorph, "root") && hasArkKind(rMorph, "root") && lMorph.equals(rMorph) + }); + } +}; +var Morph = { + implementation: implementation15, + Node: MorphNode +}; +var writeMorphIntersectionMessage = (lDescription, rDescription) => `The intersection of distinct morphs at a single path is indeterminate: +Left: ${lDescription} +Right: ${rDescription}`; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/proto.js +var implementation16 = implementNode({ + kind: "proto", + hasAssociatedError: true, + collapsibleKey: "proto", + keys: { + proto: { + serialize: (ctor) => getBuiltinNameOfConstructor(ctor) ?? defaultValueSerializer(ctor) + }, + dateAllowsInvalid: {} + }, + normalize: (schema2) => { + const normalized = typeof schema2 === "string" ? { proto: builtinConstructors[schema2] } : typeof schema2 === "function" ? isNode(schema2) ? schema2 : { proto: schema2 } : typeof schema2.proto === "string" ? { ...schema2, proto: builtinConstructors[schema2.proto] } : schema2; + if (typeof normalized.proto !== "function") + throwParseError(Proto.writeInvalidSchemaMessage(normalized.proto)); + if (hasKey(normalized, "dateAllowsInvalid") && normalized.proto !== Date) + throwParseError(Proto.writeBadInvalidDateMessage(normalized.proto)); + return normalized; + }, + applyConfig: (schema2, config3) => { + if (schema2.dateAllowsInvalid === void 0 && schema2.proto === Date && config3.dateAllowsInvalid) + return { ...schema2, dateAllowsInvalid: true }; + return schema2; + }, + defaults: { + description: (node2) => node2.builtinName ? objectKindDescriptions[node2.builtinName] : `an instance of ${node2.proto.name}`, + actual: (data) => data instanceof Date && data.toString() === "Invalid Date" ? "an invalid Date" : objectKindOrDomainOf(data) + }, + intersections: { + proto: (l, r) => l.proto === Date && r.proto === Date ? ( + // since l === r is handled by default, + // exactly one of l or r must have allow invalid dates + l.dateAllowsInvalid ? r : l + ) : constructorExtends(l.proto, r.proto) ? l : constructorExtends(r.proto, l.proto) ? r : Disjoint.init("proto", l, r), + domain: (proto, domain2) => domain2.domain === "object" ? proto : Disjoint.init("domain", $ark.intrinsic.object.internal, domain2) + } +}); +var ProtoNode = class extends InternalBasis { + builtinName = getBuiltinNameOfConstructor(this.proto); + serializedConstructor = this.json.proto; + requiresInvalidDateCheck = this.proto === Date && !this.dateAllowsInvalid; + traverseAllows = this.requiresInvalidDateCheck ? (data) => data instanceof Date && data.toString() !== "Invalid Date" : (data) => data instanceof this.proto; + compiledCondition = `data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck ? ` && data.toString() !== "Invalid Date"` : ""}`; + compiledNegation = `!(${this.compiledCondition})`; + innerToJsonSchema(ctx) { + switch (this.builtinName) { + case "Array": + return { + type: "array" + }; + case "Date": + return ctx.fallback.date?.({ code: "date", base: {} }) ?? ctx.fallback.proto({ code: "proto", base: {}, proto: this.proto }); + default: + return ctx.fallback.proto({ + code: "proto", + base: {}, + proto: this.proto + }); + } + } + expression = this.dateAllowsInvalid ? "Date | InvalidDate" : this.proto.name; + get nestableExpression() { + return this.dateAllowsInvalid ? `(${this.expression})` : this.expression; + } + domain = "object"; + get defaultShortDescription() { + return this.description; + } +}; +var Proto = { + implementation: implementation16, + Node: ProtoNode, + writeBadInvalidDateMessage: (actual) => `dateAllowsInvalid may only be specified with constructor Date (was ${actual.name})`, + writeInvalidSchemaMessage: (actual) => `instanceOf operand must be a function (was ${domainOf(actual)})` +}; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/union.js +var implementation17 = implementNode({ + kind: "union", + hasAssociatedError: true, + collapsibleKey: "branches", + keys: { + ordered: {}, + branches: { + child: true, + parse: (schema2, ctx) => { + const branches = []; + for (const branchSchema of schema2) { + const branchNodes = hasArkKind(branchSchema, "root") ? branchSchema.branches : ctx.$.parseSchema(branchSchema).branches; + for (const node2 of branchNodes) { + if (node2.hasKind("morph")) { + const matchingMorphIndex = branches.findIndex((matching) => matching.hasKind("morph") && matching.hasEqualMorphs(node2)); + if (matchingMorphIndex === -1) + branches.push(node2); + else { + const matchingMorph = branches[matchingMorphIndex]; + branches[matchingMorphIndex] = ctx.$.node("morph", { + ...matchingMorph.inner, + in: matchingMorph.rawIn.rawOr(node2.rawIn) + }); + } + } else + branches.push(node2); + } + } + if (!ctx.def.ordered) + branches.sort((l, r) => l.hash < r.hash ? -1 : 1); + return branches; + } + } + }, + normalize: (schema2) => isArray(schema2) ? { branches: schema2 } : schema2, + reduce: (inner, $2) => { + const reducedBranches = reduceBranches(inner); + if (reducedBranches.length === 1) + return reducedBranches[0]; + if (reducedBranches.length === inner.branches.length) + return; + return $2.node("union", { + ...inner, + branches: reducedBranches + }, { prereduced: true }); + }, + defaults: { + description: (node2) => node2.distribute((branch) => branch.description, describeBranches), + expected: (ctx) => { + const byPath = groupBy(ctx.errors, "propString"); + const pathDescriptions = Object.entries(byPath).map(([path3, errors]) => { + const branchesAtPath = []; + for (const errorAtPath of errors) + appendUnique(branchesAtPath, errorAtPath.expected); + const expected = describeBranches(branchesAtPath); + const actual = errors.every((e) => e.actual === errors[0].actual) ? errors[0].actual : printable(errors[0].data); + return `${path3 && `${path3} `}must be ${expected}${actual && ` (was ${actual})`}`; + }); + return describeBranches(pathDescriptions); + }, + problem: (ctx) => ctx.expected, + message: (ctx) => { + if (ctx.problem[0] === "[") { + return `value at ${ctx.problem}`; + } + return ctx.problem; + } + }, + intersections: { + union: (l, r, ctx) => { + if (l.isNever !== r.isNever) { + return Disjoint.init("presence", l, r); + } + let resultBranches; + if (l.ordered) { + if (r.ordered) { + throwParseError(writeOrderedIntersectionMessage(l.expression, r.expression)); + } + resultBranches = intersectBranches(r.branches, l.branches, ctx); + if (resultBranches instanceof Disjoint) + resultBranches.invert(); + } else + resultBranches = intersectBranches(l.branches, r.branches, ctx); + if (resultBranches instanceof Disjoint) + return resultBranches; + return ctx.$.parseSchema(l.ordered || r.ordered ? { + branches: resultBranches, + ordered: true + } : { branches: resultBranches }); + }, + ...defineRightwardIntersections("union", (l, r, ctx) => { + const branches = intersectBranches(l.branches, [r], ctx); + if (branches instanceof Disjoint) + return branches; + if (branches.length === 1) + return branches[0]; + return ctx.$.parseSchema(l.ordered ? { branches, ordered: true } : { branches }); + }) + } +}); +var UnionNode = class extends BaseRoot { + isBoolean = this.branches.length === 2 && this.branches[0].hasUnit(false) && this.branches[1].hasUnit(true); + get branchGroups() { + const branchGroups = []; + let firstBooleanIndex = -1; + for (const branch of this.branches) { + if (branch.hasKind("unit") && branch.domain === "boolean") { + if (firstBooleanIndex === -1) { + firstBooleanIndex = branchGroups.length; + branchGroups.push(branch); + } else + branchGroups[firstBooleanIndex] = $ark.intrinsic.boolean; + continue; + } + branchGroups.push(branch); + } + return branchGroups; + } + unitBranches = this.branches.filter((n) => n.rawIn.hasKind("unit")); + discriminant = this.discriminate(); + discriminantJson = this.discriminant ? discriminantToJson(this.discriminant) : null; + expression = this.distribute((n) => n.nestableExpression, expressBranches); + createBranchedOptimisticRootApply() { + return (data, onFail) => { + const optimisticResult = this.traverseOptimistic(data); + if (optimisticResult !== unset) + return optimisticResult; + const ctx = new Traversal(data, this.$.resolvedConfig); + this.traverseApply(data, ctx); + return ctx.finalize(onFail); + }; + } + get shallowMorphs() { + return this.branches.reduce((morphs, branch) => appendUnique(morphs, branch.shallowMorphs), []); + } + get defaultShortDescription() { + return this.distribute((branch) => branch.defaultShortDescription, describeBranches); + } + innerToJsonSchema(ctx) { + if (this.branchGroups.length === 1 && this.branchGroups[0].equals($ark.intrinsic.boolean)) + return { type: "boolean" }; + const jsonSchemaBranches = this.branchGroups.map((group2) => group2.toJsonSchemaRecurse(ctx)); + if (jsonSchemaBranches.every((branch) => ( + // iff all branches are pure unit values with no metadata, + // we can simplify the representation to an enum + Object.keys(branch).length === 1 && hasKey(branch, "const") + ))) { + return { + enum: jsonSchemaBranches.map((branch) => branch.const) + }; + } + return { + anyOf: jsonSchemaBranches + }; + } + traverseAllows = (data, ctx) => this.branches.some((b) => b.traverseAllows(data, ctx)); + traverseApply = (data, ctx) => { + const errors = []; + for (let i = 0; i < this.branches.length; i++) { + ctx.pushBranch(); + this.branches[i].traverseApply(data, ctx); + if (!ctx.hasError()) { + if (this.branches[i].includesTransform) + return ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs); + return ctx.popBranch(); + } + errors.push(ctx.popBranch().error); + } + ctx.errorFromNodeContext({ code: "union", errors, meta: this.meta }); + }; + traverseOptimistic = (data) => { + for (let i = 0; i < this.branches.length; i++) { + const branch = this.branches[i]; + if (branch.traverseAllows(data)) { + if (branch.contextFreeMorph) + return branch.contextFreeMorph(data); + return data; + } + } + return unset; + }; + compile(js) { + if (!this.discriminant || // if we have a union of two units like `boolean`, the + // undiscriminated compilation will be just as fast + this.unitBranches.length === this.branches.length && this.branches.length === 2) + return this.compileIndiscriminable(js); + let condition = this.discriminant.optionallyChainedPropString; + if (this.discriminant.kind === "domain") + condition = `typeof ${condition} === "object" ? ${condition} === null ? "null" : "object" : typeof ${condition} === "function" ? "object" : typeof ${condition}`; + const cases = this.discriminant.cases; + const caseKeys = Object.keys(cases); + const { optimistic } = js; + js.optimistic = false; + js.block(`switch(${condition})`, () => { + for (const k in cases) { + const v = cases[k]; + const caseCondition = k === "default" ? k : `case ${k}`; + let caseResult; + if (v === true) + caseResult = optimistic ? "data" : "true"; + else if (optimistic) { + if (v.rootApplyStrategy === "branchedOptimistic") + caseResult = js.invoke(v, { kind: "Optimistic" }); + else if (v.contextFreeMorph) + caseResult = `${js.invoke(v)} ? ${registeredReference(v.contextFreeMorph)}(data) : "${unset}"`; + else + caseResult = `${js.invoke(v)} ? data : "${unset}"`; + } else + caseResult = js.invoke(v); + js.line(`${caseCondition}: return ${caseResult}`); + } + return js; + }); + if (js.traversalKind === "Allows") { + js.return(optimistic ? `"${unset}"` : false); + return; + } + const expected = describeBranches(this.discriminant.kind === "domain" ? caseKeys.map((k) => { + const jsTypeOf = k.slice(1, -1); + return jsTypeOf === "function" ? domainDescriptions.object : domainDescriptions[jsTypeOf]; + }) : caseKeys); + const serializedPathSegments = this.discriminant.path.map((k) => typeof k === "symbol" ? registeredReference(k) : JSON.stringify(k)); + const serializedExpected = JSON.stringify(expected); + const serializedActual = this.discriminant.kind === "domain" ? `${serializedTypeOfDescriptions}[${condition}]` : `${serializedPrintable}(${condition})`; + js.line(`ctx.errorFromNodeContext({ + code: "predicate", + expected: ${serializedExpected}, + actual: ${serializedActual}, + relativePath: [${serializedPathSegments}], + meta: ${this.compiledMeta} +})`); + } + compileIndiscriminable(js) { + if (js.traversalKind === "Apply") { + js.const("errors", "[]"); + for (const branch of this.branches) { + js.line("ctx.pushBranch()").line(js.invoke(branch)).if("!ctx.hasError()", () => js.return(branch.includesTransform ? "ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)" : "ctx.popBranch()")).line("errors.push(ctx.popBranch().error)"); + } + js.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`); + } else { + const { optimistic } = js; + js.optimistic = false; + for (const branch of this.branches) { + js.if(`${js.invoke(branch)}`, () => js.return(optimistic ? branch.contextFreeMorph ? `${registeredReference(branch.contextFreeMorph)}(data)` : "data" : true)); + } + js.return(optimistic ? `"${unset}"` : false); + } + } + get nestableExpression() { + return this.isBoolean ? "boolean" : `(${this.expression})`; + } + discriminate() { + if (this.branches.length < 2 || this.isCyclic) + return null; + if (this.unitBranches.length === this.branches.length) { + const cases2 = flatMorph(this.unitBranches, (i, n) => [ + `${n.rawIn.serializedValue}`, + n.hasKind("morph") ? n : true + ]); + return { + kind: "unit", + path: [], + optionallyChainedPropString: "data", + cases: cases2 + }; + } + const candidates = []; + for (let lIndex = 0; lIndex < this.branches.length - 1; lIndex++) { + const l = this.branches[lIndex]; + for (let rIndex = lIndex + 1; rIndex < this.branches.length; rIndex++) { + const r = this.branches[rIndex]; + const result = intersectNodesRoot(l.rawIn, r.rawIn, l.$); + if (!(result instanceof Disjoint)) + continue; + for (const entry of result) { + if (!entry.kind || entry.optional) + continue; + let lSerialized; + let rSerialized; + if (entry.kind === "domain") { + const lValue = entry.l; + const rValue = entry.r; + lSerialized = `"${typeof lValue === "string" ? lValue : lValue.domain}"`; + rSerialized = `"${typeof rValue === "string" ? rValue : rValue.domain}"`; + } else if (entry.kind === "unit") { + lSerialized = entry.l.serializedValue; + rSerialized = entry.r.serializedValue; + } else + continue; + const matching = candidates.find((d) => arrayEquals(d.path, entry.path) && d.kind === entry.kind); + if (!matching) { + candidates.push({ + kind: entry.kind, + cases: { + [lSerialized]: { + branchIndices: [lIndex], + condition: entry.l + }, + [rSerialized]: { + branchIndices: [rIndex], + condition: entry.r + } + }, + path: entry.path + }); + } else { + if (matching.cases[lSerialized]) { + matching.cases[lSerialized].branchIndices = appendUnique(matching.cases[lSerialized].branchIndices, lIndex); + } else { + matching.cases[lSerialized] ??= { + branchIndices: [lIndex], + condition: entry.l + }; + } + if (matching.cases[rSerialized]) { + matching.cases[rSerialized].branchIndices = appendUnique(matching.cases[rSerialized].branchIndices, rIndex); + } else { + matching.cases[rSerialized] ??= { + branchIndices: [rIndex], + condition: entry.r + }; + } + } + } + } + } + const viableCandidates = this.ordered ? viableOrderedCandidates(candidates, this.branches) : candidates; + if (!viableCandidates.length) + return null; + const ctx = createCaseResolutionContext(viableCandidates, this); + const cases = {}; + for (const k in ctx.best.cases) { + const resolution = resolveCase(ctx, k); + if (resolution === null) { + cases[k] = true; + continue; + } + if (resolution.length === this.branches.length) + return null; + if (this.ordered) { + resolution.sort((l, r) => l.originalIndex - r.originalIndex); + } + const branches = resolution.map((entry) => entry.branch); + const caseNode = branches.length === 1 ? branches[0] : this.$.node("union", this.ordered ? { branches, ordered: true } : branches); + Object.assign(this.referencesById, caseNode.referencesById); + cases[k] = caseNode; + } + if (ctx.defaultEntries.length) { + const branches = ctx.defaultEntries.map((entry) => entry.branch); + cases.default = this.$.node("union", this.ordered ? { branches, ordered: true } : branches, { + prereduced: true + }); + Object.assign(this.referencesById, cases.default.referencesById); + } + return Object.assign(ctx.location, { + cases + }); + } +}; +var createCaseResolutionContext = (viableCandidates, node2) => { + const ordered = viableCandidates.sort((l, r) => l.path.length === r.path.length ? Object.keys(r.cases).length - Object.keys(l.cases).length : l.path.length - r.path.length); + const best = ordered[0]; + const location = { + kind: best.kind, + path: best.path, + optionallyChainedPropString: optionallyChainPropString(best.path) + }; + const defaultEntries = node2.branches.map((branch, originalIndex) => ({ + originalIndex, + branch + })); + return { + best, + location, + defaultEntries, + node: node2 + }; +}; +var resolveCase = (ctx, key) => { + const caseCtx = ctx.best.cases[key]; + const discriminantNode = discriminantCaseToNode(caseCtx.condition, ctx.location.path, ctx.node.$); + let resolvedEntries = []; + const nextDefaults = []; + for (let i = 0; i < ctx.defaultEntries.length; i++) { + const entry = ctx.defaultEntries[i]; + if (caseCtx.branchIndices.includes(entry.originalIndex)) { + const pruned = pruneDiscriminant(ctx.node.branches[entry.originalIndex], ctx.location); + if (pruned === null) { + resolvedEntries = null; + } else { + resolvedEntries?.push({ + originalIndex: entry.originalIndex, + branch: pruned + }); + } + } else if ( + // we shouldn't need a special case for alias to avoid the below + // once alias resolution issues are improved: + // https://github.com/arktypeio/arktype/issues/1026 + entry.branch.hasKind("alias") && discriminantNode.hasKind("domain") && discriminantNode.domain === "object" + ) + resolvedEntries?.push(entry); + else { + if (entry.branch.rawIn.overlaps(discriminantNode)) { + const overlapping = pruneDiscriminant(entry.branch, ctx.location); + resolvedEntries?.push({ + originalIndex: entry.originalIndex, + branch: overlapping + }); + } + nextDefaults.push(entry); + } + } + ctx.defaultEntries = nextDefaults; + return resolvedEntries; +}; +var viableOrderedCandidates = (candidates, originalBranches) => { + const viableCandidates = candidates.filter((candidate) => { + const caseGroups = Object.values(candidate.cases).map((caseCtx) => caseCtx.branchIndices); + for (let i = 0; i < caseGroups.length - 1; i++) { + const currentGroup = caseGroups[i]; + for (let j = i + 1; j < caseGroups.length; j++) { + const nextGroup = caseGroups[j]; + for (const currentIndex of currentGroup) { + for (const nextIndex of nextGroup) { + if (currentIndex > nextIndex) { + if (originalBranches[currentIndex].overlaps(originalBranches[nextIndex])) { + return false; + } + } + } + } + } + } + return true; + }); + return viableCandidates; +}; +var discriminantCaseToNode = (caseDiscriminant, path3, $2) => { + let node2 = caseDiscriminant === "undefined" ? $2.node("unit", { unit: void 0 }) : caseDiscriminant === "null" ? $2.node("unit", { unit: null }) : caseDiscriminant === "boolean" ? $2.units([true, false]) : caseDiscriminant; + for (let i = path3.length - 1; i >= 0; i--) { + const key = path3[i]; + node2 = $2.node("intersection", typeof key === "number" ? { + proto: "Array", + // create unknown for preceding elements (could be optimized with safe imports) + sequence: [...range(key).map((_) => ({})), node2] + } : { + domain: "object", + required: [{ key, value: node2 }] + }); + } + return node2; +}; +var optionallyChainPropString = (path3) => path3.reduce((acc, k) => acc + compileLiteralPropAccess(k, true), "data"); +var serializedTypeOfDescriptions = registeredReference(jsTypeOfDescriptions); +var serializedPrintable = registeredReference(printable); +var Union = { + implementation: implementation17, + Node: UnionNode +}; +var discriminantToJson = (discriminant) => ({ + kind: discriminant.kind, + path: discriminant.path.map((k) => typeof k === "string" ? k : compileSerializedValue(k)), + cases: flatMorph(discriminant.cases, (k, node2) => [ + k, + node2 === true ? node2 : node2.hasKind("union") && node2.discriminantJson ? node2.discriminantJson : node2.json + ]) +}); +var describeExpressionOptions = { + delimiter: " | ", + finalDelimiter: " | " +}; +var expressBranches = (expressions) => describeBranches(expressions, describeExpressionOptions); +var describeBranches = (descriptions, opts) => { + const delimiter = opts?.delimiter ?? ", "; + const finalDelimiter = opts?.finalDelimiter ?? " or "; + if (descriptions.length === 0) + return "never"; + if (descriptions.length === 1) + return descriptions[0]; + if (descriptions.length === 2 && descriptions[0] === "false" && descriptions[1] === "true" || descriptions[0] === "true" && descriptions[1] === "false") + return "boolean"; + const seen = {}; + const unique = descriptions.filter((s) => seen[s] ? false : seen[s] = true); + const last = unique.pop(); + return `${unique.join(delimiter)}${unique.length ? finalDelimiter : ""}${last}`; +}; +var intersectBranches = (l, r, ctx) => { + const batchesByR = r.map(() => []); + for (let lIndex = 0; lIndex < l.length; lIndex++) { + let candidatesByR = {}; + for (let rIndex = 0; rIndex < r.length; rIndex++) { + if (batchesByR[rIndex] === null) { + continue; + } + if (l[lIndex].equals(r[rIndex])) { + batchesByR[rIndex] = null; + candidatesByR = {}; + break; + } + const branchIntersection = intersectOrPipeNodes(l[lIndex], r[rIndex], ctx); + if (branchIntersection instanceof Disjoint) { + continue; + } + if (branchIntersection.equals(l[lIndex])) { + batchesByR[rIndex].push(l[lIndex]); + candidatesByR = {}; + break; + } + if (branchIntersection.equals(r[rIndex])) { + batchesByR[rIndex] = null; + } else { + candidatesByR[rIndex] = branchIntersection; + } + } + for (const rIndex in candidatesByR) { + batchesByR[rIndex][lIndex] = candidatesByR[rIndex]; + } + } + const resultBranches = batchesByR.flatMap( + // ensure unions returned from branchable intersections like sequence are flattened + (batch, i) => batch?.flatMap((branch) => branch.branches) ?? r[i] + ); + return resultBranches.length === 0 ? Disjoint.init("union", l, r) : resultBranches; +}; +var reduceBranches = ({ branches, ordered }) => { + if (branches.length < 2) + return branches; + const uniquenessByIndex = branches.map(() => true); + for (let i = 0; i < branches.length; i++) { + for (let j = i + 1; j < branches.length && uniquenessByIndex[i] && uniquenessByIndex[j]; j++) { + if (branches[i].equals(branches[j])) { + uniquenessByIndex[j] = false; + continue; + } + const intersection3 = intersectNodesRoot(branches[i].rawIn, branches[j].rawIn, branches[0].$); + if (intersection3 instanceof Disjoint) + continue; + if (!ordered) + assertDeterminateOverlap(branches[i], branches[j]); + if (intersection3.equals(branches[i].rawIn)) { + uniquenessByIndex[i] = !!ordered; + } else if (intersection3.equals(branches[j].rawIn)) + uniquenessByIndex[j] = false; + } + } + return branches.filter((_, i) => uniquenessByIndex[i]); +}; +var assertDeterminateOverlap = (l, r) => { + if (!l.includesTransform && !r.includesTransform) + return; + if (!arrayEquals(l.shallowMorphs, r.shallowMorphs)) { + throwParseError(writeIndiscriminableMorphMessage(l.expression, r.expression)); + } + if (!arrayEquals(l.flatMorphs, r.flatMorphs, { + isEqual: (l2, r2) => l2.propString === r2.propString && (l2.node.hasKind("morph") && r2.node.hasKind("morph") ? l2.node.hasEqualMorphs(r2.node) : l2.node.hasKind("intersection") && r2.node.hasKind("intersection") ? l2.node.structure?.structuralMorphRef === r2.node.structure?.structuralMorphRef : false) + })) { + throwParseError(writeIndiscriminableMorphMessage(l.expression, r.expression)); + } +}; +var pruneDiscriminant = (discriminantBranch, discriminantCtx) => discriminantBranch.transform((nodeKind, inner) => { + if (nodeKind === "domain" || nodeKind === "unit") + return null; + return inner; +}, { + shouldTransform: (node2, ctx) => { + const propString = optionallyChainPropString(ctx.path); + if (!discriminantCtx.optionallyChainedPropString.startsWith(propString)) + return false; + if (node2.hasKind("domain") && node2.domain === "object") + return true; + if ((node2.hasKind("domain") || discriminantCtx.kind === "unit") && propString === discriminantCtx.optionallyChainedPropString) + return true; + return node2.children.length !== 0 && node2.kind !== "index"; + } +}); +var writeIndiscriminableMorphMessage = (lDescription, rDescription) => `An unordered union of a type including a morph and a type with overlapping input is indeterminate: +Left: ${lDescription} +Right: ${rDescription}`; +var writeOrderedIntersectionMessage = (lDescription, rDescription) => `The intersection of two ordered unions is indeterminate: +Left: ${lDescription} +Right: ${rDescription}`; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/unit.js +var implementation18 = implementNode({ + kind: "unit", + hasAssociatedError: true, + keys: { + unit: { + preserveUndefined: true, + serialize: (schema2) => schema2 instanceof Date ? schema2.toISOString() : defaultValueSerializer(schema2) + } + }, + normalize: (schema2) => schema2, + defaults: { + description: (node2) => printable(node2.unit), + problem: ({ expected, actual }) => `${expected === actual ? `must be reference equal to ${expected} (serialized to the same value)` : `must be ${expected} (was ${actual})`}` + }, + intersections: { + unit: (l, r) => Disjoint.init("unit", l, r), + ...defineRightwardIntersections("unit", (l, r) => { + if (r.allows(l.unit)) + return l; + const rBasis = r.hasKind("intersection") ? r.basis : r; + if (rBasis) { + const rDomain = rBasis.hasKind("domain") ? rBasis : $ark.intrinsic.object; + if (l.domain !== rDomain.domain) { + const lDomainDisjointValue = l.domain === "undefined" || l.domain === "null" || l.domain === "boolean" ? l.domain : $ark.intrinsic[l.domain]; + return Disjoint.init("domain", lDomainDisjointValue, rDomain); + } + } + return Disjoint.init("assignability", l, r.hasKind("intersection") ? r.children.find((rConstraint) => !rConstraint.allows(l.unit)) : r); + }) + } +}); +var UnitNode = class extends InternalBasis { + compiledValue = this.json.unit; + serializedValue = typeof this.unit === "string" || this.unit instanceof Date ? JSON.stringify(this.compiledValue) : `${this.compiledValue}`; + compiledCondition = compileEqualityCheck(this.unit, this.serializedValue); + compiledNegation = compileEqualityCheck(this.unit, this.serializedValue, "negated"); + expression = printable(this.unit); + domain = domainOf(this.unit); + get defaultShortDescription() { + return this.domain === "object" ? domainDescriptions.object : this.description; + } + innerToJsonSchema(ctx) { + return ( + // this is the more standard JSON schema representation, especially for Open API + this.unit === null ? { type: "null" } : $ark.intrinsic.jsonPrimitive.allows(this.unit) ? { const: this.unit } : ctx.fallback.unit({ code: "unit", base: {}, unit: this.unit }) + ); + } + traverseAllows = this.unit instanceof Date ? (data) => data instanceof Date && data.toISOString() === this.compiledValue : Number.isNaN(this.unit) ? (data) => Number.isNaN(data) : (data) => data === this.unit; +}; +var Unit = { + implementation: implementation18, + Node: UnitNode +}; +var compileEqualityCheck = (unit, serializedValue, negated) => { + if (unit instanceof Date) { + const condition = `data instanceof Date && data.toISOString() === ${serializedValue}`; + return negated ? `!(${condition})` : condition; + } + if (Number.isNaN(unit)) + return `${negated ? "!" : ""}Number.isNaN(data)`; + return `data ${negated ? "!" : "="}== ${serializedValue}`; +}; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/index.js +var implementation19 = implementNode({ + kind: "index", + hasAssociatedError: false, + intersectionIsOpen: true, + keys: { + signature: { + child: true, + parse: (schema2, ctx) => { + const key = ctx.$.parseSchema(schema2); + if (!key.extends($ark.intrinsic.key)) { + return throwParseError(writeInvalidPropertyKeyMessage(key.expression)); + } + const enumerableBranches = key.branches.filter((b) => b.hasKind("unit")); + if (enumerableBranches.length) { + return throwParseError(writeEnumerableIndexBranches(enumerableBranches.map((b) => printable(b.unit)))); + } + return key; + } + }, + value: { + child: true, + parse: (schema2, ctx) => ctx.$.parseSchema(schema2) + } + }, + normalize: (schema2) => schema2, + defaults: { + description: (node2) => `[${node2.signature.expression}]: ${node2.value.description}` + }, + intersections: { + index: (l, r, ctx) => { + if (l.signature.equals(r.signature)) { + const valueIntersection = intersectOrPipeNodes(l.value, r.value, ctx); + const value2 = valueIntersection instanceof Disjoint ? $ark.intrinsic.never.internal : valueIntersection; + return ctx.$.node("index", { signature: l.signature, value: value2 }); + } + if (l.signature.extends(r.signature) && l.value.subsumes(r.value)) + return r; + if (r.signature.extends(l.signature) && r.value.subsumes(l.value)) + return l; + return null; + } + } +}); +var IndexNode = class extends BaseConstraint { + impliedBasis = $ark.intrinsic.object.internal; + expression = `[${this.signature.expression}]: ${this.value.expression}`; + flatRefs = append(this.value.flatRefs.map((ref) => flatRef([this.signature, ...ref.path], ref.node)), flatRef([this.signature], this.value)); + traverseAllows = (data, ctx) => stringAndSymbolicEntriesOf(data).every((entry) => { + if (this.signature.traverseAllows(entry[0], ctx)) { + return traverseKey(entry[0], () => this.value.traverseAllows(entry[1], ctx), ctx); + } + return true; + }); + traverseApply = (data, ctx) => { + for (const entry of stringAndSymbolicEntriesOf(data)) { + if (this.signature.traverseAllows(entry[0], ctx)) { + traverseKey(entry[0], () => this.value.traverseApply(entry[1], ctx), ctx); + } + } + }; + _transform(mapper, ctx) { + ctx.path.push(this.signature); + const result = super._transform(mapper, ctx); + ctx.path.pop(); + return result; + } + compile() { + } +}; +var Index = { + implementation: implementation19, + Node: IndexNode +}; +var writeEnumerableIndexBranches = (keys) => `Index keys ${keys.join(", ")} should be specified as named props.`; +var writeInvalidPropertyKeyMessage = (indexSchema) => `Indexed key definition '${indexSchema}' must be a string or symbol`; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/required.js +var implementation20 = implementNode({ + kind: "required", + hasAssociatedError: true, + intersectionIsOpen: true, + keys: { + key: {}, + value: { + child: true, + parse: (schema2, ctx) => ctx.$.parseSchema(schema2) + } + }, + normalize: (schema2) => schema2, + defaults: { + description: (node2) => `${node2.compiledKey}: ${node2.value.description}`, + expected: (ctx) => ctx.missingValueDescription, + actual: () => "missing" + }, + intersections: { + required: intersectProps, + optional: intersectProps + } +}); +var RequiredNode = class extends BaseProp { + expression = `${this.compiledKey}: ${this.value.expression}`; + errorContext = Object.freeze({ + code: "required", + missingValueDescription: this.value.defaultShortDescription, + relativePath: [this.key], + meta: this.meta + }); + compiledErrorContext = compileObjectLiteral(this.errorContext); +}; +var Required = { + implementation: implementation20, + Node: RequiredNode +}; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/sequence.js +var implementation21 = implementNode({ + kind: "sequence", + hasAssociatedError: false, + collapsibleKey: "variadic", + keys: { + prefix: { + child: true, + parse: (schema2, ctx) => { + if (schema2.length === 0) + return void 0; + return schema2.map((element) => ctx.$.parseSchema(element)); + } + }, + optionals: { + child: true, + parse: (schema2, ctx) => { + if (schema2.length === 0) + return void 0; + return schema2.map((element) => ctx.$.parseSchema(element)); + } + }, + defaultables: { + child: (defaultables) => defaultables.map((element) => element[0]), + parse: (defaultables, ctx) => { + if (defaultables.length === 0) + return void 0; + return defaultables.map((element) => { + const node2 = ctx.$.parseSchema(element[0]); + assertDefaultValueAssignability(node2, element[1], null); + return [node2, element[1]]; + }); + }, + serialize: (defaults) => defaults.map((element) => [ + element[0].collapsibleJson, + defaultValueSerializer(element[1]) + ]), + reduceIo: (ioKind, inner, defaultables) => { + if (ioKind === "in") { + inner.optionals = defaultables.map((d) => d[0].rawIn); + return; + } + inner.prefix = defaultables.map((d) => d[0].rawOut); + return; + } + }, + variadic: { + child: true, + parse: (schema2, ctx) => ctx.$.parseSchema(schema2, ctx) + }, + minVariadicLength: { + // minVariadicLength is reflected in the id of this node, + // but not its IntersectionNode parent since it is superceded by the minLength + // node it implies + parse: (min) => min === 0 ? void 0 : min + }, + postfix: { + child: true, + parse: (schema2, ctx) => { + if (schema2.length === 0) + return void 0; + return schema2.map((element) => ctx.$.parseSchema(element)); + } + } + }, + normalize: (schema2) => { + if (typeof schema2 === "string") + return { variadic: schema2 }; + if ("variadic" in schema2 || "prefix" in schema2 || "defaultables" in schema2 || "optionals" in schema2 || "postfix" in schema2 || "minVariadicLength" in schema2) { + if (schema2.postfix?.length) { + if (!schema2.variadic) + return throwParseError(postfixWithoutVariadicMessage); + if (schema2.optionals?.length || schema2.defaultables?.length) + return throwParseError(postfixAfterOptionalOrDefaultableMessage); + } + if (schema2.minVariadicLength && !schema2.variadic) { + return throwParseError("minVariadicLength may not be specified without a variadic element"); + } + return schema2; + } + return { variadic: schema2 }; + }, + reduce: (raw2, $2) => { + let minVariadicLength = raw2.minVariadicLength ?? 0; + const prefix = raw2.prefix?.slice() ?? []; + const defaultables = raw2.defaultables?.slice() ?? []; + const optionals = raw2.optionals?.slice() ?? []; + const postfix = raw2.postfix?.slice() ?? []; + if (raw2.variadic) { + while (optionals[optionals.length - 1]?.equals(raw2.variadic)) + optionals.pop(); + if (optionals.length === 0 && defaultables.length === 0) { + while (prefix[prefix.length - 1]?.equals(raw2.variadic)) { + prefix.pop(); + minVariadicLength++; + } + } + while (postfix[0]?.equals(raw2.variadic)) { + postfix.shift(); + minVariadicLength++; + } + } else if (optionals.length === 0 && defaultables.length === 0) { + prefix.push(...postfix.splice(0)); + } + if ( + // if any variadic adjacent elements were moved to minVariadicLength + minVariadicLength !== raw2.minVariadicLength || // or any postfix elements were moved to prefix + raw2.prefix && raw2.prefix.length !== prefix.length + ) { + return $2.node("sequence", { + ...raw2, + // empty lists will be omitted during parsing + prefix, + defaultables, + optionals, + postfix, + minVariadicLength + }, { prereduced: true }); + } + }, + defaults: { + description: (node2) => { + if (node2.isVariadicOnly) + return `${node2.variadic.nestableExpression}[]`; + const innerDescription = node2.tuple.map((element) => element.kind === "defaultables" ? `${element.node.nestableExpression} = ${printable(element.default)}` : element.kind === "optionals" ? `${element.node.nestableExpression}?` : element.kind === "variadic" ? `...${element.node.nestableExpression}[]` : element.node.expression).join(", "); + return `[${innerDescription}]`; + } + }, + intersections: { + sequence: (l, r, ctx) => { + const rootState = _intersectSequences({ + l: l.tuple, + r: r.tuple, + disjoint: new Disjoint(), + result: [], + fixedVariants: [], + ctx + }); + const viableBranches = rootState.disjoint.length === 0 ? [rootState, ...rootState.fixedVariants] : rootState.fixedVariants; + return viableBranches.length === 0 ? rootState.disjoint : viableBranches.length === 1 ? ctx.$.node("sequence", sequenceTupleToInner(viableBranches[0].result)) : ctx.$.node("union", viableBranches.map((state) => ({ + proto: Array, + sequence: sequenceTupleToInner(state.result) + }))); + } + // exactLength, minLength, and maxLength don't need to be defined + // here since impliedSiblings guarantees they will be added + // directly to the IntersectionNode parent of the SequenceNode + // they exist on + } +}); +var SequenceNode = class extends BaseConstraint { + impliedBasis = $ark.intrinsic.Array.internal; + tuple = sequenceInnerToTuple(this.inner); + prefixLength = this.prefix?.length ?? 0; + defaultablesLength = this.defaultables?.length ?? 0; + optionalsLength = this.optionals?.length ?? 0; + postfixLength = this.postfix?.length ?? 0; + defaultablesAndOptionals = []; + prevariadic = this.tuple.filter((el) => { + if (el.kind === "defaultables" || el.kind === "optionals") { + this.defaultablesAndOptionals.push(el.node); + return true; + } + return el.kind === "prefix"; + }); + variadicOrPostfix = conflatenate(this.variadic && [this.variadic], this.postfix); + // have to wait until prevariadic and variadicOrPostfix are set to calculate + flatRefs = this.addFlatRefs(); + addFlatRefs() { + appendUniqueFlatRefs(this.flatRefs, this.prevariadic.flatMap((element, i) => append(element.node.flatRefs.map((ref) => flatRef([`${i}`, ...ref.path], ref.node)), flatRef([`${i}`], element.node)))); + appendUniqueFlatRefs(this.flatRefs, this.variadicOrPostfix.flatMap((element) => ( + // a postfix index can't be directly represented as a type + // key, so we just use the same matcher for variadic + append(element.flatRefs.map((ref) => flatRef([$ark.intrinsic.nonNegativeIntegerString.internal, ...ref.path], ref.node)), flatRef([$ark.intrinsic.nonNegativeIntegerString.internal], element)) + ))); + return this.flatRefs; + } + isVariadicOnly = this.prevariadic.length + this.postfixLength === 0; + minVariadicLength = this.inner.minVariadicLength ?? 0; + minLength = this.prefixLength + this.minVariadicLength + this.postfixLength; + minLengthNode = this.minLength === 0 ? null : this.$.node("minLength", this.minLength); + maxLength = this.variadic ? null : this.tuple.length; + maxLengthNode = this.maxLength === null ? null : this.$.node("maxLength", this.maxLength); + impliedSiblings = this.minLengthNode ? this.maxLengthNode ? [this.minLengthNode, this.maxLengthNode] : [this.minLengthNode] : this.maxLengthNode ? [this.maxLengthNode] : []; + defaultValueMorphs = getDefaultableMorphs(this); + defaultValueMorphsReference = this.defaultValueMorphs.length ? registeredReference(this.defaultValueMorphs) : void 0; + elementAtIndex(data, index) { + if (index < this.prevariadic.length) + return this.tuple[index]; + const firstPostfixIndex = data.length - this.postfixLength; + if (index >= firstPostfixIndex) + return { kind: "postfix", node: this.postfix[index - firstPostfixIndex] }; + return { + kind: "variadic", + node: this.variadic ?? throwInternalError(`Unexpected attempt to access index ${index} on ${this}`) + }; + } + // minLength/maxLength should be checked by Intersection before either traversal + traverseAllows = (data, ctx) => { + for (let i = 0; i < data.length; i++) { + if (!this.elementAtIndex(data, i).node.traverseAllows(data[i], ctx)) + return false; + } + return true; + }; + traverseApply = (data, ctx) => { + let i = 0; + for (; i < data.length; i++) { + traverseKey(i, () => this.elementAtIndex(data, i).node.traverseApply(data[i], ctx), ctx); + } + }; + get element() { + return this.cacheGetter("element", this.$.node("union", this.children)); + } + // minLength/maxLength compilation should be handled by Intersection + compile(js) { + if (this.prefix) { + for (const [i, node2] of this.prefix.entries()) + js.traverseKey(`${i}`, `data[${i}]`, node2); + } + for (const [i, node2] of this.defaultablesAndOptionals.entries()) { + const dataIndex = `${i + this.prefixLength}`; + js.if(`${dataIndex} >= data.length`, () => js.traversalKind === "Allows" ? js.return(true) : js.return()); + js.traverseKey(dataIndex, `data[${dataIndex}]`, node2); + } + if (this.variadic) { + if (this.postfix) { + js.const("firstPostfixIndex", `data.length${this.postfix ? `- ${this.postfix.length}` : ""}`); + } + js.for(`i < ${this.postfix ? "firstPostfixIndex" : "data.length"}`, () => js.traverseKey("i", "data[i]", this.variadic), this.prevariadic.length); + if (this.postfix) { + for (const [i, node2] of this.postfix.entries()) { + const keyExpression = `firstPostfixIndex + ${i}`; + js.traverseKey(keyExpression, `data[${keyExpression}]`, node2); + } + } + } + if (js.traversalKind === "Allows") + js.return(true); + } + _transform(mapper, ctx) { + ctx.path.push($ark.intrinsic.nonNegativeIntegerString.internal); + const result = super._transform(mapper, ctx); + ctx.path.pop(); + return result; + } + // this depends on tuple so needs to come after it + expression = this.description; + reduceJsonSchema(schema2, ctx) { + const isDraft07 = ctx.target === "draft-07"; + if (this.prevariadic.length) { + const prefixSchemas = this.prevariadic.map((el) => { + const valueSchema = el.node.toJsonSchemaRecurse(ctx); + if (el.kind === "defaultables") { + const value2 = typeof el.default === "function" ? el.default() : el.default; + valueSchema.default = $ark.intrinsic.jsonData.allows(value2) ? value2 : ctx.fallback.defaultValue({ + code: "defaultValue", + base: valueSchema, + value: value2 + }); + } + return valueSchema; + }); + if (isDraft07) + schema2.items = prefixSchemas; + else + schema2.prefixItems = prefixSchemas; + } + if (this.minLength) + schema2.minItems = this.minLength; + if (this.variadic) { + const variadicItemSchema = this.variadic.toJsonSchemaRecurse(ctx); + if (isDraft07 && this.prevariadic.length) + schema2.additionalItems = variadicItemSchema; + else + schema2.items = variadicItemSchema; + if (this.maxLength) + schema2.maxItems = this.maxLength; + if (this.postfix) { + const elements = this.postfix.map((el) => el.toJsonSchemaRecurse(ctx)); + schema2 = ctx.fallback.arrayPostfix({ + code: "arrayPostfix", + base: schema2, + elements + }); + } + } else { + if (isDraft07) + schema2.additionalItems = false; + else + schema2.items = false; + delete schema2.maxItems; + } + return schema2; + } +}; +var defaultableMorphsCache = {}; +var getDefaultableMorphs = (node2) => { + if (!node2.defaultables) + return []; + const morphs = []; + let cacheKey = "["; + const lastDefaultableIndex = node2.prefixLength + node2.defaultablesLength - 1; + for (let i = node2.prefixLength; i <= lastDefaultableIndex; i++) { + const [elementNode, defaultValue] = node2.defaultables[i - node2.prefixLength]; + morphs.push(computeDefaultValueMorph(i, elementNode, defaultValue)); + cacheKey += `${i}: ${elementNode.id} = ${defaultValueSerializer(defaultValue)}, `; + } + cacheKey += "]"; + return defaultableMorphsCache[cacheKey] ??= morphs; +}; +var Sequence = { + implementation: implementation21, + Node: SequenceNode +}; +var sequenceInnerToTuple = (inner) => { + const tuple2 = []; + if (inner.prefix) + for (const node2 of inner.prefix) + tuple2.push({ kind: "prefix", node: node2 }); + if (inner.defaultables) { + for (const [node2, defaultValue] of inner.defaultables) + tuple2.push({ kind: "defaultables", node: node2, default: defaultValue }); + } + if (inner.optionals) + for (const node2 of inner.optionals) + tuple2.push({ kind: "optionals", node: node2 }); + if (inner.variadic) + tuple2.push({ kind: "variadic", node: inner.variadic }); + if (inner.postfix) + for (const node2 of inner.postfix) + tuple2.push({ kind: "postfix", node: node2 }); + return tuple2; +}; +var sequenceTupleToInner = (tuple2) => tuple2.reduce((result, element) => { + if (element.kind === "variadic") + result.variadic = element.node; + else if (element.kind === "defaultables") { + result.defaultables = append(result.defaultables, [ + [element.node, element.default] + ]); + } else + result[element.kind] = append(result[element.kind], element.node); + return result; +}, {}); +var postfixAfterOptionalOrDefaultableMessage = "A postfix required element cannot follow an optional or defaultable element"; +var postfixWithoutVariadicMessage = "A postfix element requires a variadic element"; +var _intersectSequences = (s) => { + const [lHead, ...lTail] = s.l; + const [rHead, ...rTail] = s.r; + if (!lHead || !rHead) + return s; + const lHasPostfix = lTail[lTail.length - 1]?.kind === "postfix"; + const rHasPostfix = rTail[rTail.length - 1]?.kind === "postfix"; + const kind = lHead.kind === "prefix" || rHead.kind === "prefix" ? "prefix" : lHead.kind === "postfix" || rHead.kind === "postfix" ? "postfix" : lHead.kind === "variadic" && rHead.kind === "variadic" ? "variadic" : lHasPostfix || rHasPostfix ? "prefix" : lHead.kind === "defaultables" || rHead.kind === "defaultables" ? "defaultables" : "optionals"; + if (lHead.kind === "prefix" && rHead.kind === "variadic" && rHasPostfix) { + const postfixBranchResult = _intersectSequences({ + ...s, + fixedVariants: [], + r: rTail.map((element) => ({ ...element, kind: "prefix" })) + }); + if (postfixBranchResult.disjoint.length === 0) + s.fixedVariants.push(postfixBranchResult); + } else if (rHead.kind === "prefix" && lHead.kind === "variadic" && lHasPostfix) { + const postfixBranchResult = _intersectSequences({ + ...s, + fixedVariants: [], + l: lTail.map((element) => ({ ...element, kind: "prefix" })) + }); + if (postfixBranchResult.disjoint.length === 0) + s.fixedVariants.push(postfixBranchResult); + } + const result = intersectOrPipeNodes(lHead.node, rHead.node, s.ctx); + if (result instanceof Disjoint) { + if (kind === "prefix" || kind === "postfix") { + s.disjoint.push(...result.withPrefixKey( + // ideally we could handle disjoint paths more precisely here, + // but not trivial to serialize postfix elements as keys + kind === "prefix" ? s.result.length : `-${lTail.length + 1}`, + // both operands must be required for the disjoint to be considered required + elementIsRequired(lHead) && elementIsRequired(rHead) ? "required" : "optional" + )); + s.result = [...s.result, { kind, node: $ark.intrinsic.never.internal }]; + } else if (kind === "optionals" || kind === "defaultables") { + return s; + } else { + return _intersectSequences({ + ...s, + fixedVariants: [], + // if there were any optional elements, there will be no postfix elements + // so this mapping will never occur (which would be illegal otherwise) + l: lTail.map((element) => ({ ...element, kind: "prefix" })), + r: lTail.map((element) => ({ ...element, kind: "prefix" })) + }); + } + } else if (kind === "defaultables") { + if (lHead.kind === "defaultables" && rHead.kind === "defaultables" && lHead.default !== rHead.default) { + throwParseError(writeDefaultIntersectionMessage(lHead.default, rHead.default)); + } + s.result = [ + ...s.result, + { + kind, + node: result, + default: lHead.kind === "defaultables" ? lHead.default : rHead.kind === "defaultables" ? rHead.default : throwInternalError(`Unexpected defaultable intersection from ${lHead.kind} and ${rHead.kind} elements.`) + } + ]; + } else + s.result = [...s.result, { kind, node: result }]; + const lRemaining = s.l.length; + const rRemaining = s.r.length; + if (lHead.kind !== "variadic" || lRemaining >= rRemaining && (rHead.kind === "variadic" || rRemaining === 1)) + s.l = lTail; + if (rHead.kind !== "variadic" || rRemaining >= lRemaining && (lHead.kind === "variadic" || lRemaining === 1)) + s.r = rTail; + return _intersectSequences(s); +}; +var elementIsRequired = (el) => el.kind === "prefix" || el.kind === "postfix"; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/structure.js +var createStructuralWriter = (childStringProp) => (node2) => { + if (node2.props.length || node2.index) { + const parts = node2.index?.map((index) => index[childStringProp]) ?? []; + for (const prop of node2.props) + parts.push(prop[childStringProp]); + if (node2.undeclared) + parts.push(`+ (undeclared): ${node2.undeclared}`); + const objectLiteralDescription = `{ ${parts.join(", ")} }`; + return node2.sequence ? `${objectLiteralDescription} & ${node2.sequence.description}` : objectLiteralDescription; + } + return node2.sequence?.description ?? "{}"; +}; +var structuralDescription = createStructuralWriter("description"); +var structuralExpression = createStructuralWriter("expression"); +var intersectPropsAndIndex = (l, r, $2) => { + const kind = l.required ? "required" : "optional"; + if (!r.signature.allows(l.key)) + return null; + const value2 = intersectNodesRoot(l.value, r.value, $2); + if (value2 instanceof Disjoint) { + return kind === "optional" ? $2.node("optional", { + key: l.key, + value: $ark.intrinsic.never.internal + }) : value2.withPrefixKey(l.key, l.kind); + } + return null; +}; +var implementation22 = implementNode({ + kind: "structure", + hasAssociatedError: false, + normalize: (schema2) => schema2, + applyConfig: (schema2, config3) => { + if (!schema2.undeclared && config3.onUndeclaredKey !== "ignore") { + return { + ...schema2, + undeclared: config3.onUndeclaredKey + }; + } + return schema2; + }, + keys: { + required: { + child: true, + parse: constraintKeyParser("required"), + reduceIo: (ioKind, inner, nodes) => { + inner.required = append(inner.required, nodes.map((node2) => ioKind === "in" ? node2.rawIn : node2.rawOut)); + return; + } + }, + optional: { + child: true, + parse: constraintKeyParser("optional"), + reduceIo: (ioKind, inner, nodes) => { + if (ioKind === "in") { + inner.optional = nodes.map((node2) => node2.rawIn); + return; + } + for (const node2 of nodes) { + inner[node2.outProp.kind] = append(inner[node2.outProp.kind], node2.outProp.rawOut); + } + } + }, + index: { + child: true, + parse: constraintKeyParser("index") + }, + sequence: { + child: true, + parse: constraintKeyParser("sequence") + }, + undeclared: { + parse: (behavior) => behavior === "ignore" ? void 0 : behavior, + reduceIo: (ioKind, inner, value2) => { + if (value2 === "reject") { + inner.undeclared = "reject"; + return; + } + if (ioKind === "in") + delete inner.undeclared; + else + inner.undeclared = "reject"; + } + } + }, + defaults: { + description: structuralDescription + }, + intersections: { + structure: (l, r, ctx) => { + const lInner = { ...l.inner }; + const rInner = { ...r.inner }; + const disjointResult = new Disjoint(); + if (l.undeclared) { + const lKey = l.keyof(); + for (const k of r.requiredKeys) { + if (!lKey.allows(k)) { + disjointResult.add("presence", $ark.intrinsic.never.internal, r.propsByKey[k].value, { + path: [k] + }); + } + } + if (rInner.optional) + rInner.optional = rInner.optional.filter((n) => lKey.allows(n.key)); + if (rInner.index) { + rInner.index = rInner.index.flatMap((n) => { + if (n.signature.extends(lKey)) + return n; + const indexOverlap = intersectNodesRoot(lKey, n.signature, ctx.$); + if (indexOverlap instanceof Disjoint) + return []; + const normalized = normalizeIndex(indexOverlap, n.value, ctx.$); + if (normalized.required) { + rInner.required = conflatenate(rInner.required, normalized.required); + } + if (normalized.optional) { + rInner.optional = conflatenate(rInner.optional, normalized.optional); + } + return normalized.index ?? []; + }); + } + } + if (r.undeclared) { + const rKey = r.keyof(); + for (const k of l.requiredKeys) { + if (!rKey.allows(k)) { + disjointResult.add("presence", l.propsByKey[k].value, $ark.intrinsic.never.internal, { + path: [k] + }); + } + } + if (lInner.optional) + lInner.optional = lInner.optional.filter((n) => rKey.allows(n.key)); + if (lInner.index) { + lInner.index = lInner.index.flatMap((n) => { + if (n.signature.extends(rKey)) + return n; + const indexOverlap = intersectNodesRoot(rKey, n.signature, ctx.$); + if (indexOverlap instanceof Disjoint) + return []; + const normalized = normalizeIndex(indexOverlap, n.value, ctx.$); + if (normalized.required) { + lInner.required = conflatenate(lInner.required, normalized.required); + } + if (normalized.optional) { + lInner.optional = conflatenate(lInner.optional, normalized.optional); + } + return normalized.index ?? []; + }); + } + } + const baseInner = {}; + if (l.undeclared || r.undeclared) { + baseInner.undeclared = l.undeclared === "reject" || r.undeclared === "reject" ? "reject" : "delete"; + } + const childIntersectionResult = intersectConstraints({ + kind: "structure", + baseInner, + l: flattenConstraints(lInner), + r: flattenConstraints(rInner), + roots: [], + ctx + }); + if (childIntersectionResult instanceof Disjoint) + disjointResult.push(...childIntersectionResult); + if (disjointResult.length) + return disjointResult; + return childIntersectionResult; + } + }, + reduce: (inner, $2) => { + if (!inner.required && !inner.optional) + return; + const seen = {}; + let updated = false; + const newOptionalProps = inner.optional ? [...inner.optional] : []; + if (inner.required) { + for (let i = 0; i < inner.required.length; i++) { + const requiredProp = inner.required[i]; + if (requiredProp.key in seen) + throwParseError(writeDuplicateKeyMessage(requiredProp.key)); + seen[requiredProp.key] = true; + if (inner.index) { + for (const index of inner.index) { + const intersection3 = intersectPropsAndIndex(requiredProp, index, $2); + if (intersection3 instanceof Disjoint) + return intersection3; + } + } + } + } + if (inner.optional) { + for (let i = 0; i < inner.optional.length; i++) { + const optionalProp = inner.optional[i]; + if (optionalProp.key in seen) + throwParseError(writeDuplicateKeyMessage(optionalProp.key)); + seen[optionalProp.key] = true; + if (inner.index) { + for (const index of inner.index) { + const intersection3 = intersectPropsAndIndex(optionalProp, index, $2); + if (intersection3 instanceof Disjoint) + return intersection3; + if (intersection3 !== null) { + newOptionalProps[i] = intersection3; + updated = true; + } + } + } + } + } + if (updated) { + return $2.node("structure", { ...inner, optional: newOptionalProps }, { prereduced: true }); + } + } +}); +var StructureNode = class extends BaseConstraint { + impliedBasis = $ark.intrinsic.object.internal; + impliedSiblings = this.children.flatMap((n) => n.impliedSiblings ?? []); + props = conflatenate(this.required, this.optional); + propsByKey = flatMorph(this.props, (i, node2) => [node2.key, node2]); + propsByKeyReference = registeredReference(this.propsByKey); + expression = structuralExpression(this); + requiredKeys = this.required?.map((node2) => node2.key) ?? []; + optionalKeys = this.optional?.map((node2) => node2.key) ?? []; + literalKeys = [...this.requiredKeys, ...this.optionalKeys]; + _keyof; + keyof() { + if (this._keyof) + return this._keyof; + let branches = this.$.units(this.literalKeys).branches; + if (this.index) { + for (const { signature } of this.index) + branches = branches.concat(signature.branches); + } + return this._keyof = this.$.node("union", branches); + } + map(flatMapProp) { + return this.$.node("structure", this.props.flatMap(flatMapProp).reduce((structureInner, mapped) => { + const originalProp = this.propsByKey[mapped.key]; + if (isNode(mapped)) { + if (mapped.kind !== "required" && mapped.kind !== "optional") { + return throwParseError(`Map result must have kind "required" or "optional" (was ${mapped.kind})`); + } + structureInner[mapped.kind] = append(structureInner[mapped.kind], mapped); + return structureInner; + } + const mappedKind = mapped.kind ?? originalProp?.kind ?? "required"; + const mappedPropInner = flatMorph(mapped, (k, v) => k in Optional.implementation.keys ? [k, v] : []); + structureInner[mappedKind] = append(structureInner[mappedKind], this.$.node(mappedKind, mappedPropInner)); + return structureInner; + }, {})); + } + assertHasKeys(keys) { + const invalidKeys = keys.filter((k) => !typeOrTermExtends(k, this.keyof())); + if (invalidKeys.length) { + return throwParseError(writeInvalidKeysMessage(this.expression, invalidKeys)); + } + } + get(indexer, ...path3) { + let value2; + let required3 = false; + const key = indexerToKey(indexer); + if ((typeof key === "string" || typeof key === "symbol") && this.propsByKey[key]) { + value2 = this.propsByKey[key].value; + required3 = this.propsByKey[key].required; + } + if (this.index) { + for (const n of this.index) { + if (typeOrTermExtends(key, n.signature)) + value2 = value2?.and(n.value) ?? n.value; + } + } + if (this.sequence && typeOrTermExtends(key, $ark.intrinsic.nonNegativeIntegerString)) { + if (hasArkKind(key, "root")) { + if (this.sequence.variadic) + value2 = value2?.and(this.sequence.element) ?? this.sequence.element; + } else { + const index = Number.parseInt(key); + if (index < this.sequence.prevariadic.length) { + const fixedElement = this.sequence.prevariadic[index].node; + value2 = value2?.and(fixedElement) ?? fixedElement; + required3 ||= index < this.sequence.prefixLength; + } else if (this.sequence.variadic) { + const nonFixedElement = this.$.node("union", this.sequence.variadicOrPostfix); + value2 = value2?.and(nonFixedElement) ?? nonFixedElement; + } + } + } + if (!value2) { + if (this.sequence?.variadic && hasArkKind(key, "root") && key.extends($ark.intrinsic.number)) { + return throwParseError(writeNumberIndexMessage(key.expression, this.sequence.expression)); + } + return throwParseError(writeInvalidKeysMessage(this.expression, [key])); + } + const result = value2.get(...path3); + return required3 ? result : result.or($ark.intrinsic.undefined); + } + pick(...keys) { + this.assertHasKeys(keys); + return this.$.node("structure", this.filterKeys("pick", keys)); + } + omit(...keys) { + this.assertHasKeys(keys); + return this.$.node("structure", this.filterKeys("omit", keys)); + } + optionalize() { + const { required: required3, ...inner } = this.inner; + return this.$.node("structure", { + ...inner, + optional: this.props.map((prop) => prop.hasKind("required") ? this.$.node("optional", prop.inner) : prop) + }); + } + require() { + const { optional: optional3, ...inner } = this.inner; + return this.$.node("structure", { + ...inner, + required: this.props.map((prop) => prop.hasKind("optional") ? { + key: prop.key, + value: prop.value + } : prop) + }); + } + merge(r) { + const inner = this.filterKeys("omit", [r.keyof()]); + if (r.required) + inner.required = append(inner.required, r.required); + if (r.optional) + inner.optional = append(inner.optional, r.optional); + if (r.index) + inner.index = append(inner.index, r.index); + if (r.sequence) + inner.sequence = r.sequence; + if (r.undeclared) + inner.undeclared = r.undeclared; + else + delete inner.undeclared; + return this.$.node("structure", inner); + } + filterKeys(operation, keys) { + const result = makeRootAndArrayPropertiesMutable(this.inner); + const shouldKeep = (key) => { + const matchesKey = keys.some((k) => typeOrTermExtends(key, k)); + return operation === "pick" ? matchesKey : !matchesKey; + }; + if (result.required) + result.required = result.required.filter((prop) => shouldKeep(prop.key)); + if (result.optional) + result.optional = result.optional.filter((prop) => shouldKeep(prop.key)); + if (result.index) + result.index = result.index.filter((index) => shouldKeep(index.signature)); + return result; + } + traverseAllows = (data, ctx) => this._traverse("Allows", data, ctx); + traverseApply = (data, ctx) => this._traverse("Apply", data, ctx); + _traverse = (traversalKind, data, ctx) => { + const errorCount = ctx?.currentErrorCount ?? 0; + for (let i = 0; i < this.props.length; i++) { + if (traversalKind === "Allows") { + if (!this.props[i].traverseAllows(data, ctx)) + return false; + } else { + this.props[i].traverseApply(data, ctx); + if (ctx.failFast && ctx.currentErrorCount > errorCount) + return false; + } + } + if (this.sequence) { + if (traversalKind === "Allows") { + if (!this.sequence.traverseAllows(data, ctx)) + return false; + } else { + this.sequence.traverseApply(data, ctx); + if (ctx.failFast && ctx.currentErrorCount > errorCount) + return false; + } + } + if (this.index || this.undeclared === "reject") { + const keys = Object.keys(data); + keys.push(...Object.getOwnPropertySymbols(data)); + for (let i = 0; i < keys.length; i++) { + const k = keys[i]; + if (this.index) { + for (const node2 of this.index) { + if (node2.signature.traverseAllows(k, ctx)) { + if (traversalKind === "Allows") { + const result = traverseKey(k, () => node2.value.traverseAllows(data[k], ctx), ctx); + if (!result) + return false; + } else { + traverseKey(k, () => node2.value.traverseApply(data[k], ctx), ctx); + if (ctx.failFast && ctx.currentErrorCount > errorCount) + return false; + } + } + } + } + if (this.undeclared === "reject" && !this.declaresKey(k)) { + if (traversalKind === "Allows") + return false; + ctx.errorFromNodeContext({ + code: "predicate", + expected: "removed", + actual: "", + relativePath: [k], + meta: this.meta + }); + if (ctx.failFast) + return false; + } + } + } + if (this.structuralMorph && ctx && !ctx.hasError()) + ctx.queueMorphs([this.structuralMorph]); + return true; + }; + get defaultable() { + return this.cacheGetter("defaultable", this.optional?.filter((o) => o.hasDefault()) ?? []); + } + declaresKey = (k) => k in this.propsByKey || this.index?.some((n) => n.signature.allows(k)) || this.sequence !== void 0 && $ark.intrinsic.nonNegativeIntegerString.allows(k); + _compileDeclaresKey(js) { + const parts = []; + if (this.props.length) + parts.push(`k in ${this.propsByKeyReference}`); + if (this.index) { + for (const index of this.index) + parts.push(js.invoke(index.signature, { kind: "Allows", arg: "k" })); + } + if (this.sequence) + parts.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)"); + return parts.join(" || ") || "false"; + } + get structuralMorph() { + return this.cacheGetter("structuralMorph", getPossibleMorph(this)); + } + structuralMorphRef = this.structuralMorph && registeredReference(this.structuralMorph); + compile(js) { + if (js.traversalKind === "Apply") + js.initializeErrorCount(); + for (const prop of this.props) { + js.check(prop); + if (js.traversalKind === "Apply") + js.returnIfFailFast(); + } + if (this.sequence) { + js.check(this.sequence); + if (js.traversalKind === "Apply") + js.returnIfFailFast(); + } + if (this.index || this.undeclared === "reject") { + js.const("keys", "Object.keys(data)"); + js.line("keys.push(...Object.getOwnPropertySymbols(data))"); + js.for("i < keys.length", () => this.compileExhaustiveEntry(js)); + } + if (js.traversalKind === "Allows") + return js.return(true); + if (this.structuralMorphRef) { + js.if("ctx && !ctx.hasError()", () => { + js.line(`ctx.queueMorphs([`); + precompileMorphs(js, this); + return js.line("])"); + }); + } + } + compileExhaustiveEntry(js) { + js.const("k", "keys[i]"); + if (this.index) { + for (const node2 of this.index) { + js.if(`${js.invoke(node2.signature, { arg: "k", kind: "Allows" })}`, () => js.traverseKey("k", "data[k]", node2.value)); + } + } + if (this.undeclared === "reject") { + js.if(`!(${this._compileDeclaresKey(js)})`, () => { + if (js.traversalKind === "Allows") + return js.return(false); + return js.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast", () => js.return()); + }); + } + return js; + } + reduceJsonSchema(schema2, ctx) { + switch (schema2.type) { + case "object": + return this.reduceObjectJsonSchema(schema2, ctx); + case "array": + const arraySchema = this.sequence?.reduceJsonSchema(schema2, ctx) ?? schema2; + if (this.props.length || this.index) { + return ctx.fallback.arrayObject({ + code: "arrayObject", + base: arraySchema, + object: this.reduceObjectJsonSchema({ type: "object" }, ctx) + }); + } + return arraySchema; + default: + return ToJsonSchema.throwInternalOperandError("structure", schema2); + } + } + reduceObjectJsonSchema(schema2, ctx) { + if (this.props.length) { + schema2.properties = {}; + for (const prop of this.props) { + const valueSchema = prop.value.toJsonSchemaRecurse(ctx); + if (typeof prop.key === "symbol") { + ctx.fallback.symbolKey({ + code: "symbolKey", + base: schema2, + key: prop.key, + value: valueSchema, + optional: prop.optional + }); + continue; + } + if (prop.hasDefault()) { + const value2 = typeof prop.default === "function" ? prop.default() : prop.default; + valueSchema.default = $ark.intrinsic.jsonData.allows(value2) ? value2 : ctx.fallback.defaultValue({ + code: "defaultValue", + base: valueSchema, + value: value2 + }); + } + schema2.properties[prop.key] = valueSchema; + } + if (this.requiredKeys.length && schema2.properties) { + schema2.required = this.requiredKeys.filter((k) => typeof k === "string" && k in schema2.properties); + } + } + if (this.index) { + for (const index of this.index) { + const valueJsonSchema = index.value.toJsonSchemaRecurse(ctx); + if (index.signature.equals($ark.intrinsic.string)) { + schema2.additionalProperties = valueJsonSchema; + continue; + } + for (const keyBranch of index.signature.branches) { + if (!keyBranch.extends($ark.intrinsic.string)) { + schema2 = ctx.fallback.symbolKey({ + code: "symbolKey", + base: schema2, + key: null, + value: valueJsonSchema, + optional: false + }); + continue; + } + let keySchema = { type: "string" }; + if (keyBranch.hasKind("morph")) { + keySchema = ctx.fallback.morph({ + code: "morph", + base: keyBranch.rawIn.toJsonSchemaRecurse(ctx), + out: keyBranch.rawOut.toJsonSchemaRecurse(ctx) + }); + } + if (!keyBranch.hasKind("intersection")) { + return throwInternalError(`Unexpected index branch kind ${keyBranch.kind}.`); + } + const { pattern } = keyBranch.inner; + if (pattern) { + const keySchemaWithPattern = Object.assign(keySchema, { + pattern: pattern[0].rule + }); + for (let i = 1; i < pattern.length; i++) { + keySchema = ctx.fallback.patternIntersection({ + code: "patternIntersection", + base: keySchemaWithPattern, + pattern: pattern[i].rule + }); + } + schema2.patternProperties ??= {}; + schema2.patternProperties[keySchemaWithPattern.pattern] = valueJsonSchema; + } + } + } + } + if (this.undeclared && !schema2.additionalProperties) + schema2.additionalProperties = false; + return schema2; + } +}; +var defaultableMorphsCache2 = {}; +var constructStructuralMorphCacheKey = (node2) => { + let cacheKey = ""; + for (let i = 0; i < node2.defaultable.length; i++) + cacheKey += node2.defaultable[i].defaultValueMorphRef; + if (node2.sequence?.defaultValueMorphsReference) + cacheKey += node2.sequence?.defaultValueMorphsReference; + if (node2.undeclared === "delete") { + cacheKey += "delete !("; + if (node2.required) + for (const n of node2.required) + cacheKey += n.compiledKey + " | "; + if (node2.optional) + for (const n of node2.optional) + cacheKey += n.compiledKey + " | "; + if (node2.index) + for (const index of node2.index) + cacheKey += index.signature.id + " | "; + if (node2.sequence) { + if (node2.sequence.maxLength === null) + cacheKey += intrinsic.nonNegativeIntegerString.id; + else { + for (let i = 0; i < node2.sequence.tuple.length; i++) + cacheKey += i + " | "; + } + } + cacheKey += ")"; + } + return cacheKey; +}; +var getPossibleMorph = (node2) => { + const cacheKey = constructStructuralMorphCacheKey(node2); + if (!cacheKey) + return void 0; + if (defaultableMorphsCache2[cacheKey]) + return defaultableMorphsCache2[cacheKey]; + const $arkStructuralMorph = (data, ctx) => { + for (let i = 0; i < node2.defaultable.length; i++) { + if (!(node2.defaultable[i].key in data)) + node2.defaultable[i].defaultValueMorph(data, ctx); + } + if (node2.sequence?.defaultables) { + for (let i = data.length - node2.sequence.prefixLength; i < node2.sequence.defaultables.length; i++) + node2.sequence.defaultValueMorphs[i](data, ctx); + } + if (node2.undeclared === "delete") { + for (const k in data) + if (!node2.declaresKey(k)) + delete data[k]; + } + return data; + }; + return defaultableMorphsCache2[cacheKey] = $arkStructuralMorph; +}; +var precompileMorphs = (js, node2) => { + const requiresContext = node2.defaultable.some((node3) => node3.defaultValueMorph.length === 2) || node2.sequence?.defaultValueMorphs.some((morph) => morph.length === 2); + const args2 = `(data${requiresContext ? ", ctx" : ""})`; + return js.block(`${args2} => `, (js2) => { + for (let i = 0; i < node2.defaultable.length; i++) { + const { serializedKey, defaultValueMorphRef } = node2.defaultable[i]; + js2.if(`!(${serializedKey} in data)`, (js3) => js3.line(`${defaultValueMorphRef}${args2}`)); + } + if (node2.sequence?.defaultables) { + js2.for(`i < ${node2.sequence.defaultables.length}`, (js3) => js3.set(`data[i]`, 5), `data.length - ${node2.sequence.prefixLength}`); + } + if (node2.undeclared === "delete") { + js2.forIn("data", (js3) => js3.if(`!(${node2._compileDeclaresKey(js3)})`, (js4) => js4.line(`delete data[k]`))); + } + return js2.return("data"); + }); +}; +var Structure = { + implementation: implementation22, + Node: StructureNode +}; +var indexerToKey = (indexable) => { + if (hasArkKind(indexable, "root") && indexable.hasKind("unit")) + indexable = indexable.unit; + if (typeof indexable === "number") + indexable = `${indexable}`; + return indexable; +}; +var writeNumberIndexMessage = (indexExpression, sequenceExpression) => `${indexExpression} is not allowed as an array index on ${sequenceExpression}. Use the 'nonNegativeIntegerString' keyword instead.`; +var normalizeIndex = (signature, value2, $2) => { + const [enumerableBranches, nonEnumerableBranches] = spliterate(signature.branches, (k) => k.hasKind("unit")); + if (!enumerableBranches.length) + return { index: $2.node("index", { signature, value: value2 }) }; + const normalized = {}; + for (const n of enumerableBranches) { + const prop = $2.node("required", { key: n.unit, value: value2 }); + normalized[prop.kind] = append(normalized[prop.kind], prop); + } + if (nonEnumerableBranches.length) { + normalized.index = $2.node("index", { + signature: nonEnumerableBranches, + value: value2 + }); + } + return normalized; +}; +var typeKeyToString = (k) => hasArkKind(k, "root") ? k.expression : printable(k); +var writeInvalidKeysMessage = (o, keys) => `Key${keys.length === 1 ? "" : "s"} ${keys.map(typeKeyToString).join(", ")} ${keys.length === 1 ? "does" : "do"} not exist on ${o}`; +var writeDuplicateKeyMessage = (key) => `Duplicate key ${compileSerializedValue(key)}`; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/kinds.js +var nodeImplementationsByKind = { + ...boundImplementationsByKind, + alias: Alias.implementation, + domain: Domain.implementation, + unit: Unit.implementation, + proto: Proto.implementation, + union: Union.implementation, + morph: Morph.implementation, + intersection: Intersection.implementation, + divisor: Divisor.implementation, + pattern: Pattern.implementation, + predicate: Predicate.implementation, + required: Required.implementation, + optional: Optional.implementation, + index: Index.implementation, + sequence: Sequence.implementation, + structure: Structure.implementation +}; +$ark.defaultConfig = withAlphabetizedKeys(Object.assign(flatMorph(nodeImplementationsByKind, (kind, implementation23) => [ + kind, + implementation23.defaults +]), { + jitless: envHasCsp(), + clone: deepClone, + onUndeclaredKey: "ignore", + exactOptionalPropertyTypes: true, + numberAllowsNaN: false, + dateAllowsInvalid: false, + onFail: null, + keywords: {}, + toJsonSchema: ToJsonSchema.defaultConfig +})); +$ark.resolvedConfig = mergeConfigs($ark.defaultConfig, $ark.config); +var nodeClassesByKind = { + ...boundClassesByKind, + alias: Alias.Node, + domain: Domain.Node, + unit: Unit.Node, + proto: Proto.Node, + union: Union.Node, + morph: Morph.Node, + intersection: Intersection.Node, + divisor: Divisor.Node, + pattern: Pattern.Node, + predicate: Predicate.Node, + required: Required.Node, + optional: Optional.Node, + index: Index.Node, + sequence: Sequence.Node, + structure: Structure.Node +}; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/module.js +var RootModule = class extends DynamicBase { + // ensure `[arkKind]` is non-enumerable so it doesn't get spread on import/export + get [arkKind]() { + return "module"; + } +}; +var bindModule = (module, $2) => new RootModule(flatMorph(module, (alias, value2) => [ + alias, + hasArkKind(value2, "module") ? bindModule(value2, $2) : $2.bindReference(value2) +])); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/scope.js +var schemaBranchesOf = (schema2) => isArray(schema2) ? schema2 : "branches" in schema2 && isArray(schema2.branches) ? schema2.branches : void 0; +var throwMismatchedNodeRootError = (expected, actual) => throwParseError(`Node of kind ${actual} is not valid as a ${expected} definition`); +var writeDuplicateAliasError = (alias) => `#${alias} duplicates public alias ${alias}`; +var scopesByName = {}; +$ark.ambient ??= {}; +var rawUnknownUnion; +var rootScopeFnName = "function $"; +var precompile = (references) => bindPrecompilation(references, precompileReferences(references)); +var bindPrecompilation = (references, precompiler) => { + const precompilation = precompiler.write(rootScopeFnName, 4); + const compiledTraversals = precompiler.compile()(); + for (const node2 of references) { + if (node2.precompilation) { + continue; + } + node2.traverseAllows = compiledTraversals[`${node2.id}Allows`].bind(compiledTraversals); + if (node2.isRoot() && !node2.allowsRequiresContext) { + node2.allows = node2.traverseAllows; + } + node2.traverseApply = compiledTraversals[`${node2.id}Apply`].bind(compiledTraversals); + if (compiledTraversals[`${node2.id}Optimistic`]) { + ; + node2.traverseOptimistic = compiledTraversals[`${node2.id}Optimistic`].bind(compiledTraversals); + } + node2.precompilation = precompilation; + } +}; +var precompileReferences = (references) => new CompiledFunction().return(references.reduce((js, node2) => { + const allowsCompiler = new NodeCompiler({ kind: "Allows" }).indent(); + node2.compile(allowsCompiler); + const allowsJs = allowsCompiler.write(`${node2.id}Allows`); + const applyCompiler = new NodeCompiler({ kind: "Apply" }).indent(); + node2.compile(applyCompiler); + const applyJs = applyCompiler.write(`${node2.id}Apply`); + const result = `${js}${allowsJs}, +${applyJs}, +`; + if (!node2.hasKind("union")) + return result; + const optimisticCompiler = new NodeCompiler({ + kind: "Allows", + optimistic: true + }).indent(); + node2.compile(optimisticCompiler); + const optimisticJs = optimisticCompiler.write(`${node2.id}Optimistic`); + return `${result}${optimisticJs}, +`; +}, "{\n") + "}"); +var BaseScope = class { + config; + resolvedConfig; + name; + get [arkKind]() { + return "scope"; + } + referencesById = {}; + references = []; + resolutions = {}; + exportedNames = []; + aliases = {}; + resolved = false; + nodesByHash = {}; + intrinsic; + constructor(def, config3) { + this.config = mergeConfigs($ark.config, config3); + this.resolvedConfig = mergeConfigs($ark.resolvedConfig, config3); + this.name = this.resolvedConfig.name ?? `anonymousScope${Object.keys(scopesByName).length}`; + if (this.name in scopesByName) + throwParseError(`A Scope already named ${this.name} already exists`); + scopesByName[this.name] = this; + const aliasEntries = Object.entries(def).map((entry) => this.preparseOwnAliasEntry(...entry)); + for (const [k, v] of aliasEntries) { + let name = k; + if (k[0] === "#") { + name = k.slice(1); + if (name in this.aliases) + throwParseError(writeDuplicateAliasError(name)); + this.aliases[name] = v; + } else { + if (name in this.aliases) + throwParseError(writeDuplicateAliasError(k)); + this.aliases[name] = v; + this.exportedNames.push(name); + } + if (!hasArkKind(v, "module") && !hasArkKind(v, "generic") && !isThunk(v)) { + const preparsed = this.preparseOwnDefinitionFormat(v, { alias: name }); + this.resolutions[name] = hasArkKind(preparsed, "root") ? this.bindReference(preparsed) : this.createParseContext(preparsed).id; + } + } + rawUnknownUnion ??= this.node("union", { + branches: [ + "string", + "number", + "object", + "bigint", + "symbol", + { unit: true }, + { unit: false }, + { unit: void 0 }, + { unit: null } + ] + }, { prereduced: true }); + this.nodesByHash[rawUnknownUnion.hash] = this.node("intersection", {}, { prereduced: true }); + this.intrinsic = $ark.intrinsic ? flatMorph($ark.intrinsic, (k, v) => ( + // don't include cyclic aliases from JSON scope + k.startsWith("json") ? [] : [k, this.bindReference(v)] + )) : {}; + } + cacheGetter(name, value2) { + Object.defineProperty(this, name, { value: value2 }); + return value2; + } + get internal() { + return this; + } + // json is populated when the scope is exported, so ensure it is populated + // before allowing external access + _json; + get json() { + if (!this._json) + this.export(); + return this._json; + } + defineSchema(def) { + return def; + } + generic = (...params) => { + const $2 = this; + return (def, possibleHkt) => new GenericRoot(params, possibleHkt ? new LazyGenericBody(def) : def, $2, $2, possibleHkt ?? null); + }; + units = (values, opts) => { + const uniqueValues = []; + for (const value2 of values) + if (!uniqueValues.includes(value2)) + uniqueValues.push(value2); + const branches = uniqueValues.map((unit) => this.node("unit", { unit }, opts)); + return this.node("union", branches, { + ...opts, + prereduced: true + }); + }; + lazyResolutions = []; + lazilyResolve(resolve2, syntheticAlias) { + const node2 = this.node("alias", { + reference: syntheticAlias ?? "synthetic", + resolve: resolve2 + }, { prereduced: true }); + if (!this.resolved) + this.lazyResolutions.push(node2); + return node2; + } + schema = (schema2, opts) => this.finalize(this.parseSchema(schema2, opts)); + parseSchema = (schema2, opts) => this.node(schemaKindOf(schema2), schema2, opts); + preparseNode(kinds, schema2, opts) { + let kind = typeof kinds === "string" ? kinds : schemaKindOf(schema2, kinds); + if (isNode(schema2) && schema2.kind === kind) + return schema2; + if (kind === "alias" && !opts?.prereduced) { + const { reference: reference2 } = Alias.implementation.normalize(schema2, this); + if (reference2.startsWith("$")) { + const resolution = this.resolveRoot(reference2.slice(1)); + schema2 = resolution; + kind = resolution.kind; + } + } else if (kind === "union" && hasDomain(schema2, "object")) { + const branches = schemaBranchesOf(schema2); + if (branches?.length === 1) { + schema2 = branches[0]; + kind = schemaKindOf(schema2); + } + } + if (isNode(schema2) && schema2.kind === kind) + return schema2; + const impl = nodeImplementationsByKind[kind]; + const normalizedSchema = impl.normalize?.(schema2, this) ?? schema2; + if (isNode(normalizedSchema)) { + return normalizedSchema.kind === kind ? normalizedSchema : throwMismatchedNodeRootError(kind, normalizedSchema.kind); + } + return { + ...opts, + $: this, + kind, + def: normalizedSchema, + prefix: opts.alias ?? kind + }; + } + bindReference(reference2) { + let bound; + if (isNode(reference2)) { + bound = reference2.$ === this ? reference2 : new reference2.constructor(reference2.attachments, this); + } else { + bound = reference2.$ === this ? reference2 : new GenericRoot(reference2.params, reference2.bodyDef, reference2.$, this, reference2.hkt); + } + if (!this.resolved) { + Object.assign(this.referencesById, bound.referencesById); + } + return bound; + } + resolveRoot(name) { + return this.maybeResolveRoot(name) ?? throwParseError(writeUnresolvableMessage(name)); + } + maybeResolveRoot(name) { + const result = this.maybeResolve(name); + if (hasArkKind(result, "generic")) + return; + return result; + } + /** If name is a valid reference to a submodule alias, return its resolution */ + maybeResolveSubalias(name) { + return maybeResolveSubalias(this.aliases, name) ?? maybeResolveSubalias(this.ambient, name); + } + get ambient() { + return $ark.ambient; + } + maybeResolve(name) { + const cached4 = this.resolutions[name]; + if (cached4) { + if (typeof cached4 !== "string") + return this.bindReference(cached4); + const v = nodesByRegisteredId[cached4]; + if (hasArkKind(v, "root")) + return this.resolutions[name] = v; + if (hasArkKind(v, "context")) { + if (v.phase === "resolving") { + return this.node("alias", { reference: `$${name}` }, { prereduced: true }); + } + if (v.phase === "resolved") { + return throwInternalError(`Unexpected resolved context for was uncached by its scope: ${printable(v)}`); + } + v.phase = "resolving"; + const node2 = this.bindReference(this.parseOwnDefinitionFormat(v.def, v)); + v.phase = "resolved"; + nodesByRegisteredId[node2.id] = node2; + nodesByRegisteredId[v.id] = node2; + return this.resolutions[name] = node2; + } + return throwInternalError(`Unexpected nodesById entry for ${cached4}: ${printable(v)}`); + } + let def = this.aliases[name] ?? this.ambient?.[name]; + if (!def) + return this.maybeResolveSubalias(name); + def = this.normalizeRootScopeValue(def); + if (hasArkKind(def, "generic")) + return this.resolutions[name] = this.bindReference(def); + if (hasArkKind(def, "module")) { + if (!def.root) + throwParseError(writeMissingSubmoduleAccessMessage(name)); + return this.resolutions[name] = this.bindReference(def.root); + } + return this.resolutions[name] = this.parse(def, { + alias: name + }); + } + createParseContext(input) { + const id = input.id ?? registerNodeId(input.prefix); + return nodesByRegisteredId[id] = Object.assign(input, { + [arkKind]: "context", + $: this, + id, + phase: "unresolved" + }); + } + traversal(root) { + return new Traversal(root, this.resolvedConfig); + } + import(...names) { + return new RootModule(flatMorph(this.export(...names), (alias, value2) => [ + `#${alias}`, + value2 + ])); + } + precompilation; + _exportedResolutions; + _exports; + export(...names) { + if (!this._exports) { + this._exports = {}; + for (const name of this.exportedNames) { + const def = this.aliases[name]; + this._exports[name] = hasArkKind(def, "module") ? bindModule(def, this) : bootstrapAliasReferences(this.maybeResolve(name)); + } + for (const node2 of this.lazyResolutions) + node2.resolution; + this._exportedResolutions = resolutionsOfModule(this, this._exports); + this._json = resolutionsToJson(this._exportedResolutions); + Object.assign(this.resolutions, this._exportedResolutions); + this.references = Object.values(this.referencesById); + if (!this.resolvedConfig.jitless) { + const precompiler = precompileReferences(this.references); + this.precompilation = precompiler.write(rootScopeFnName, 4); + bindPrecompilation(this.references, precompiler); + } + this.resolved = true; + } + const namesToExport = names.length ? names : this.exportedNames; + return new RootModule(flatMorph(namesToExport, (_, name) => [ + name, + this._exports[name] + ])); + } + resolve(name) { + return this.export()[name]; + } + node = (kinds, nodeSchema, opts = {}) => { + const ctxOrNode = this.preparseNode(kinds, nodeSchema, opts); + if (isNode(ctxOrNode)) + return this.bindReference(ctxOrNode); + const ctx = this.createParseContext(ctxOrNode); + const node2 = parseNode(ctx); + const bound = this.bindReference(node2); + return nodesByRegisteredId[ctx.id] = bound; + }; + parse = (def, opts = {}) => this.finalize(this.parseDefinition(def, opts)); + parseDefinition(def, opts = {}) { + if (hasArkKind(def, "root")) + return this.bindReference(def); + const ctxInputOrNode = this.preparseOwnDefinitionFormat(def, opts); + if (hasArkKind(ctxInputOrNode, "root")) + return this.bindReference(ctxInputOrNode); + const ctx = this.createParseContext(ctxInputOrNode); + nodesByRegisteredId[ctx.id] = ctx; + let node2 = this.bindReference(this.parseOwnDefinitionFormat(def, ctx)); + if (node2.isCyclic) + node2 = withId(node2, ctx.id); + nodesByRegisteredId[ctx.id] = node2; + return node2; + } + finalize(node2) { + bootstrapAliasReferences(node2); + if (!node2.precompilation && !this.resolvedConfig.jitless) + precompile(node2.references); + return node2; + } +}; +var SchemaScope = class extends BaseScope { + parseOwnDefinitionFormat(def, ctx) { + return parseNode(ctx); + } + preparseOwnDefinitionFormat(schema2, opts) { + return this.preparseNode(schemaKindOf(schema2), schema2, opts); + } + preparseOwnAliasEntry(k, v) { + return [k, v]; + } + normalizeRootScopeValue(v) { + return v; + } +}; +var bootstrapAliasReferences = (resolution) => { + const aliases = resolution.references.filter((node2) => node2.hasKind("alias")); + for (const aliasNode of aliases) { + Object.assign(aliasNode.referencesById, aliasNode.resolution.referencesById); + for (const ref of resolution.references) { + if (aliasNode.id in ref.referencesById) + Object.assign(ref.referencesById, aliasNode.referencesById); + } + } + return resolution; +}; +var resolutionsToJson = (resolutions) => flatMorph(resolutions, (k, v) => [ + k, + hasArkKind(v, "root") || hasArkKind(v, "generic") ? v.json : hasArkKind(v, "module") ? resolutionsToJson(v) : throwInternalError(`Unexpected resolution ${printable(v)}`) +]); +var maybeResolveSubalias = (base, name) => { + const dotIndex = name.indexOf("."); + if (dotIndex === -1) + return; + const dotPrefix = name.slice(0, dotIndex); + const prefixSchema = base[dotPrefix]; + if (prefixSchema === void 0) + return; + if (!hasArkKind(prefixSchema, "module")) + return throwParseError(writeNonSubmoduleDotMessage(dotPrefix)); + const subalias = name.slice(dotIndex + 1); + const resolution = prefixSchema[subalias]; + if (resolution === void 0) + return maybeResolveSubalias(prefixSchema, subalias); + if (hasArkKind(resolution, "root") || hasArkKind(resolution, "generic")) + return resolution; + if (hasArkKind(resolution, "module")) { + return resolution.root ?? throwParseError(writeMissingSubmoduleAccessMessage(name)); + } + throwInternalError(`Unexpected resolution for alias '${name}': ${printable(resolution)}`); +}; +var schemaScope = (aliases, config3) => new SchemaScope(aliases, config3); +var rootSchemaScope = new SchemaScope({}); +var resolutionsOfModule = ($2, typeSet) => { + const result = {}; + for (const k in typeSet) { + const v = typeSet[k]; + if (hasArkKind(v, "module")) { + const innerResolutions = resolutionsOfModule($2, v); + const prefixedResolutions = flatMorph(innerResolutions, (innerK, innerV) => [`${k}.${innerK}`, innerV]); + Object.assign(result, prefixedResolutions); + } else if (hasArkKind(v, "root") || hasArkKind(v, "generic")) + result[k] = v; + else + throwInternalError(`Unexpected scope resolution ${printable(v)}`); + } + return result; +}; +var writeUnresolvableMessage = (token) => `'${token}' is unresolvable`; +var writeNonSubmoduleDotMessage = (name) => `'${name}' must reference a module to be accessed using dot syntax`; +var writeMissingSubmoduleAccessMessage = (name) => `Reference to submodule '${name}' must specify an alias`; +rootSchemaScope.export(); +var rootSchema = rootSchemaScope.schema; +var node = rootSchemaScope.node; +var defineSchema = rootSchemaScope.defineSchema; +var genericNode = rootSchemaScope.generic; + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/shared.js +var arrayIndexSource = `^(?:0|[1-9]\\d*)$`; +var arrayIndexMatcher = new RegExp(arrayIndexSource); +var arrayIndexMatcherReference = registeredReference(arrayIndexMatcher); + +// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/intrinsic.js +var intrinsicBases = schemaScope({ + bigint: "bigint", + // since we know this won't be reduced, it can be safely cast to a union + boolean: [{ unit: false }, { unit: true }], + false: { unit: false }, + never: [], + null: { unit: null }, + number: "number", + object: "object", + string: "string", + symbol: "symbol", + true: { unit: true }, + unknown: {}, + undefined: { unit: void 0 }, + Array, + Date +}, { prereducedAliases: true }).export(); +$ark.intrinsic = { ...intrinsicBases }; +var intrinsicRoots = schemaScope({ + integer: { + domain: "number", + divisor: 1 + }, + lengthBoundable: ["string", Array], + key: ["string", "symbol"], + nonNegativeIntegerString: { domain: "string", pattern: arrayIndexSource } +}, { prereducedAliases: true }).export(); +Object.assign($ark.intrinsic, intrinsicRoots); +var intrinsicJson = schemaScope({ + jsonPrimitive: [ + "string", + "number", + { unit: true }, + { unit: false }, + { unit: null } + ], + jsonObject: { + domain: "object", + index: { + signature: "string", + value: "$jsonData" + } + }, + jsonData: ["$jsonPrimitive", "$jsonObject"] +}, { prereducedAliases: true }).export(); +var intrinsic = { + ...intrinsicBases, + ...intrinsicRoots, + ...intrinsicJson, + emptyStructure: node("structure", {}, { prereduced: true }) +}; +$ark.intrinsic = { ...intrinsic }; + +// node_modules/.pnpm/arkregex@0.0.5/node_modules/arkregex/out/regex.js +var regex = ((src, flags) => new RegExp(src, flags)); +Object.assign(regex, { as: regex }); + // node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/config.js var configure = configureSchema; +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/shift/operand/date.js +var isDateLiteral = (value2) => typeof value2 === "string" && value2[0] === "d" && (value2[1] === "'" || value2[1] === '"') && value2[value2.length - 1] === value2[1]; +var isValidDate = (d) => d.toString() !== "Invalid Date"; +var extractDateLiteralSource = (literal3) => literal3.slice(2, -1); +var writeInvalidDateMessage = (source) => `'${source}' could not be parsed by the Date constructor`; +var tryParseDate = (source, errorOnFail) => maybeParseDate(source, errorOnFail); +var maybeParseDate = (source, errorOnFail) => { + const stringParsedDate = new Date(source); + if (isValidDate(stringParsedDate)) + return stringParsedDate; + const epochMillis = tryParseNumber(source); + if (epochMillis !== void 0) { + const numberParsedDate = new Date(epochMillis); + if (isValidDate(numberParsedDate)) + return numberParsedDate; + } + return errorOnFail ? throwParseError(errorOnFail === true ? writeInvalidDateMessage(source) : errorOnFail) : void 0; +}; + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/shift/operand/enclosed.js +var regexExecArray = rootSchema({ + proto: "Array", + sequence: "string", + required: { + key: "groups", + value: ["object", { unit: void 0 }] + } +}); +var parseEnclosed = (s, enclosing) => { + const enclosed = s.scanner.shiftUntilEscapable(untilLookaheadIsClosing[enclosingTokens[enclosing]]); + if (s.scanner.lookahead === "") + return s.error(writeUnterminatedEnclosedMessage(enclosed, enclosing)); + s.scanner.shift(); + if (enclosing in enclosingRegexTokens) { + let regex4; + try { + regex4 = new RegExp(enclosed); + } catch (e) { + throwParseError(String(e)); + } + s.root = s.ctx.$.node("intersection", { + domain: "string", + pattern: enclosed + }, { prereduced: true }); + if (enclosing === "x/") { + s.root = s.ctx.$.node("morph", { + in: s.root, + morphs: (s2) => regex4.exec(s2), + declaredOut: regexExecArray + }); + } + } else if (isKeyOf(enclosing, enclosingQuote)) + s.root = s.ctx.$.node("unit", { unit: enclosed }); + else { + const date5 = tryParseDate(enclosed, writeInvalidDateMessage(enclosed)); + s.root = s.ctx.$.node("unit", { meta: enclosed, unit: date5 }); + } +}; +var enclosingQuote = { + "'": 1, + '"': 1 +}; +var enclosingChar = { + "/": 1, + "'": 1, + '"': 1 +}; +var enclosingLiteralTokens = { + "d'": "'", + 'd"': '"', + "'": "'", + '"': '"' +}; +var enclosingRegexTokens = { + "/": "/", + "x/": "/" +}; +var enclosingTokens = { + ...enclosingLiteralTokens, + ...enclosingRegexTokens +}; +var untilLookaheadIsClosing = { + "'": (scanner) => scanner.lookahead === `'`, + '"': (scanner) => scanner.lookahead === `"`, + "/": (scanner) => scanner.lookahead === `/` +}; +var enclosingCharDescriptions = { + '"': "double-quote", + "'": "single-quote", + "/": "forward slash" +}; +var writeUnterminatedEnclosedMessage = (fragment, enclosingStart) => `${enclosingStart}${fragment} requires a closing ${enclosingCharDescriptions[enclosingTokens[enclosingStart]]}`; + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/ast/validate.js +var writePrefixedPrivateReferenceMessage = (name) => `Private type references should not include '#'. Use '${name}' instead.`; +var shallowOptionalMessage = "Optional definitions like 'string?' are only valid as properties in an object or tuple"; +var shallowDefaultableMessage = "Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple"; + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/shift/tokens.js +var terminatingChars = { + "<": 1, + ">": 1, + "=": 1, + "|": 1, + "&": 1, + ")": 1, + "[": 1, + "%": 1, + ",": 1, + ":": 1, + "?": 1, + "#": 1, + ...whitespaceChars +}; +var lookaheadIsFinalizing = (lookahead, unscanned) => lookahead === ">" ? unscanned[0] === "=" ? ( + // >== would only occur in an expression like Array==5 + // otherwise, >= would only occur as part of a bound like number>=5 + unscanned[1] === "=" +) : unscanned.trimStart() === "" || isKeyOf(unscanned.trimStart()[0], terminatingChars) : lookahead === "=" ? unscanned[0] !== "=" : lookahead === "," || lookahead === "?"; + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/shift/operand/genericArgs.js +var parseGenericArgs = (name, g, s) => _parseGenericArgs(name, g, s, []); +var _parseGenericArgs = (name, g, s, argNodes) => { + const argState = s.parseUntilFinalizer(); + argNodes.push(argState.root); + if (argState.finalizer === ">") { + if (argNodes.length !== g.params.length) { + return s.error(writeInvalidGenericArgCountMessage(name, g.names, argNodes.map((arg) => arg.expression))); + } + return argNodes; + } + if (argState.finalizer === ",") + return _parseGenericArgs(name, g, s, argNodes); + return argState.error(writeUnclosedGroupMessage(">")); +}; +var writeInvalidGenericArgCountMessage = (name, params, argDefs) => `${name}<${params.join(", ")}> requires exactly ${params.length} args (got ${argDefs.length}${argDefs.length === 0 ? "" : `: ${argDefs.join(", ")}`})`; + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/shift/operand/unenclosed.js +var parseUnenclosed = (s) => { + const token = s.scanner.shiftUntilLookahead(terminatingChars); + if (token === "keyof") + s.addPrefix("keyof"); + else + s.root = unenclosedToNode(s, token); +}; +var parseGenericInstantiation = (name, g, s) => { + s.scanner.shiftUntilNonWhitespace(); + const lookahead = s.scanner.shift(); + if (lookahead !== "<") + return s.error(writeInvalidGenericArgCountMessage(name, g.names, [])); + const parsedArgs = parseGenericArgs(name, g, s); + return g(...parsedArgs); +}; +var unenclosedToNode = (s, token) => maybeParseReference(s, token) ?? maybeParseUnenclosedLiteral(s, token) ?? s.error(token === "" ? s.scanner.lookahead === "#" ? writePrefixedPrivateReferenceMessage(s.shiftedBy(1).scanner.shiftUntilLookahead(terminatingChars)) : writeMissingOperandMessage(s) : writeUnresolvableMessage(token)); +var maybeParseReference = (s, token) => { + if (s.ctx.args?.[token]) { + const arg = s.ctx.args[token]; + if (typeof arg !== "string") + return arg; + return s.ctx.$.node("alias", { reference: arg }, { prereduced: true }); + } + const resolution = s.ctx.$.maybeResolve(token); + if (hasArkKind(resolution, "root")) + return resolution; + if (resolution === void 0) + return; + if (hasArkKind(resolution, "generic")) + return parseGenericInstantiation(token, resolution, s); + return throwParseError(`Unexpected resolution ${printable(resolution)}`); +}; +var maybeParseUnenclosedLiteral = (s, token) => { + const maybeNumber = tryParseWellFormedNumber(token); + if (maybeNumber !== void 0) + return s.ctx.$.node("unit", { unit: maybeNumber }); + const maybeBigint = tryParseWellFormedBigint(token); + if (maybeBigint !== void 0) + return s.ctx.$.node("unit", { unit: maybeBigint }); +}; +var writeMissingOperandMessage = (s) => { + const operator = s.previousOperator(); + return operator ? writeMissingRightOperandMessage(operator, s.scanner.unscanned) : writeExpressionExpectedMessage(s.scanner.unscanned); +}; +var writeMissingRightOperandMessage = (token, unscanned = "") => `Token '${token}' requires a right operand${unscanned ? ` before '${unscanned}'` : ""}`; +var writeExpressionExpectedMessage = (unscanned) => `Expected an expression${unscanned ? ` before '${unscanned}'` : ""}`; + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/shift/operand/operand.js +var parseOperand = (s) => s.scanner.lookahead === "" ? s.error(writeMissingOperandMessage(s)) : s.scanner.lookahead === "(" ? s.shiftedBy(1).reduceGroupOpen() : s.scanner.lookaheadIsIn(enclosingChar) ? parseEnclosed(s, s.scanner.shift()) : s.scanner.lookaheadIsIn(whitespaceChars) ? parseOperand(s.shiftedBy(1)) : s.scanner.lookahead === "d" ? s.scanner.nextLookahead in enclosingQuote ? parseEnclosed(s, `${s.scanner.shift()}${s.scanner.shift()}`) : parseUnenclosed(s) : s.scanner.lookahead === "x" ? s.scanner.nextLookahead === "/" ? s.shiftedBy(2) && parseEnclosed(s, "x/") : parseUnenclosed(s) : parseUnenclosed(s); + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/reduce/shared.js +var minComparators = { + ">": true, + ">=": true +}; +var maxComparators = { + "<": true, + "<=": true +}; +var invertedComparators = { + "<": ">", + ">": "<", + "<=": ">=", + ">=": "<=", + "==": "==" +}; +var writeOpenRangeMessage = (min, comparator) => `Left bounds are only valid when paired with right bounds (try ...${comparator}${min})`; +var writeUnpairableComparatorMessage = (comparator) => `Left-bounded expressions must specify their limits using < or <= (was ${comparator})`; +var writeMultipleLeftBoundsMessage = (openLimit, openComparator, limit, comparator) => `An expression may have at most one left bound (parsed ${openLimit}${invertedComparators[openComparator]}, ${limit}${invertedComparators[comparator]})`; + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/shift/operator/bounds.js +var parseBound = (s, start) => { + const comparator = shiftComparator(s, start); + if (s.root.hasKind("unit")) { + if (typeof s.root.unit === "number") { + s.reduceLeftBound(s.root.unit, comparator); + s.unsetRoot(); + return; + } + if (s.root.unit instanceof Date) { + const literal3 = `d'${s.root.description ?? s.root.unit.toISOString()}'`; + s.unsetRoot(); + s.reduceLeftBound(literal3, comparator); + return; + } + } + return parseRightBound(s, comparator); +}; +var comparatorStartChars = { + "<": 1, + ">": 1, + "=": 1 +}; +var shiftComparator = (s, start) => s.scanner.lookaheadIs("=") ? `${start}${s.scanner.shift()}` : start; +var getBoundKinds = (comparator, limit, root, boundKind) => { + if (root.extends($ark.intrinsic.number)) { + if (typeof limit !== "number") { + return throwParseError(writeInvalidLimitMessage(comparator, limit, boundKind)); + } + return comparator === "==" ? ["min", "max"] : comparator[0] === ">" ? ["min"] : ["max"]; + } + if (root.extends($ark.intrinsic.lengthBoundable)) { + if (typeof limit !== "number") { + return throwParseError(writeInvalidLimitMessage(comparator, limit, boundKind)); + } + return comparator === "==" ? ["exactLength"] : comparator[0] === ">" ? ["minLength"] : ["maxLength"]; + } + if (root.extends($ark.intrinsic.Date)) { + return comparator === "==" ? ["after", "before"] : comparator[0] === ">" ? ["after"] : ["before"]; + } + return throwParseError(writeUnboundableMessage(root.expression)); +}; +var openLeftBoundToRoot = (leftBound) => ({ + rule: isDateLiteral(leftBound.limit) ? extractDateLiteralSource(leftBound.limit) : leftBound.limit, + exclusive: leftBound.comparator.length === 1 +}); +var parseRightBound = (s, comparator) => { + const previousRoot = s.unsetRoot(); + const previousScannerIndex = s.scanner.location; + s.parseOperand(); + const limitNode = s.unsetRoot(); + const limitToken = s.scanner.sliceChars(previousScannerIndex, s.scanner.location); + s.root = previousRoot; + if (!limitNode.hasKind("unit") || typeof limitNode.unit !== "number" && !(limitNode.unit instanceof Date)) + return s.error(writeInvalidLimitMessage(comparator, limitToken, "right")); + const limit = limitNode.unit; + const exclusive = comparator.length === 1; + const boundKinds = getBoundKinds(comparator, typeof limit === "number" ? limit : limitToken, previousRoot, "right"); + for (const kind of boundKinds) { + s.constrainRoot(kind, comparator === "==" ? { rule: limit } : { rule: limit, exclusive }); + } + if (!s.branches.leftBound) + return; + if (!isKeyOf(comparator, maxComparators)) + return s.error(writeUnpairableComparatorMessage(comparator)); + const lowerBoundKind = getBoundKinds(s.branches.leftBound.comparator, s.branches.leftBound.limit, previousRoot, "left"); + s.constrainRoot(lowerBoundKind[0], openLeftBoundToRoot(s.branches.leftBound)); + s.branches.leftBound = null; +}; +var writeInvalidLimitMessage = (comparator, limit, boundKind) => `Comparator ${boundKind === "left" ? invertedComparators[comparator] : comparator} must be ${boundKind === "left" ? "preceded" : "followed"} by a corresponding literal (was ${limit})`; + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/shift/operator/brand.js +var parseBrand = (s) => { + s.scanner.shiftUntilNonWhitespace(); + const brandName = s.scanner.shiftUntilLookahead(terminatingChars); + s.root = s.root.brand(brandName); +}; + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/shift/operator/divisor.js +var parseDivisor = (s) => { + s.scanner.shiftUntilNonWhitespace(); + const divisorToken = s.scanner.shiftUntilLookahead(terminatingChars); + const divisor = tryParseInteger(divisorToken, { + errorOnFail: writeInvalidDivisorMessage(divisorToken) + }); + if (divisor === 0) + s.error(writeInvalidDivisorMessage(0)); + s.root = s.root.constrain("divisor", divisor); +}; +var writeInvalidDivisorMessage = (divisor) => `% operator must be followed by a non-zero integer literal (was ${divisor})`; + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/shift/operator/operator.js +var parseOperator = (s) => { + const lookahead = s.scanner.shift(); + return lookahead === "" ? s.finalize("") : lookahead === "[" ? s.scanner.shift() === "]" ? s.setRoot(s.root.array()) : s.error(incompleteArrayTokenMessage) : lookahead === "|" ? s.scanner.lookahead === ">" ? s.shiftedBy(1).pushRootToBranch("|>") : s.pushRootToBranch(lookahead) : lookahead === "&" ? s.pushRootToBranch(lookahead) : lookahead === ")" ? s.finalizeGroup() : lookaheadIsFinalizing(lookahead, s.scanner.unscanned) ? s.finalize(lookahead) : isKeyOf(lookahead, comparatorStartChars) ? parseBound(s, lookahead) : lookahead === "%" ? parseDivisor(s) : lookahead === "#" ? parseBrand(s) : lookahead in whitespaceChars ? parseOperator(s) : s.error(writeUnexpectedCharacterMessage(lookahead)); +}; +var writeUnexpectedCharacterMessage = (char, shouldBe = "") => `'${char}' is not allowed here${shouldBe && ` (should be ${shouldBe})`}`; +var incompleteArrayTokenMessage = `Missing expected ']'`; + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/shift/operator/default.js +var parseDefault = (s) => { + const baseNode = s.unsetRoot(); + s.parseOperand(); + const defaultNode = s.unsetRoot(); + if (!defaultNode.hasKind("unit")) + return s.error(writeNonLiteralDefaultMessage(defaultNode.expression)); + const defaultValue = defaultNode.unit instanceof Date ? () => new Date(defaultNode.unit) : defaultNode.unit; + return [baseNode, "=", defaultValue]; +}; +var writeNonLiteralDefaultMessage = (defaultDef) => `Default value '${defaultDef}' must be a literal value`; + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/string.js +var parseString = (def, ctx) => { + const aliasResolution = ctx.$.maybeResolveRoot(def); + if (aliasResolution) + return aliasResolution; + if (def.endsWith("[]")) { + const possibleElementResolution = ctx.$.maybeResolveRoot(def.slice(0, -2)); + if (possibleElementResolution) + return possibleElementResolution.array(); + } + const s = new RuntimeState(new Scanner(def), ctx); + const node2 = fullStringParse(s); + if (s.finalizer === ">") + throwParseError(writeUnexpectedCharacterMessage(">")); + return node2; +}; +var fullStringParse = (s) => { + s.parseOperand(); + let result = parseUntilFinalizer(s).root; + if (!result) { + return throwInternalError(`Root was unexpectedly unset after parsing string '${s.scanner.scanned}'`); + } + if (s.finalizer === "=") + result = parseDefault(s); + else if (s.finalizer === "?") + result = [result, "?"]; + s.scanner.shiftUntilNonWhitespace(); + if (s.scanner.lookahead) { + throwParseError(writeUnexpectedCharacterMessage(s.scanner.lookahead)); + } + return result; +}; +var parseUntilFinalizer = (s) => { + while (s.finalizer === void 0) + next(s); + return s; +}; +var next = (s) => s.hasRoot() ? s.parseOperator() : s.parseOperand(); + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/reduce/dynamic.js +var RuntimeState = class _RuntimeState { + root; + branches = { + prefixes: [], + leftBound: null, + intersection: null, + union: null, + pipe: null + }; + finalizer; + groups = []; + scanner; + ctx; + constructor(scanner, ctx) { + this.scanner = scanner; + this.ctx = ctx; + } + error(message) { + return throwParseError(message); + } + hasRoot() { + return this.root !== void 0; + } + setRoot(root) { + this.root = root; + } + unsetRoot() { + const value2 = this.root; + this.root = void 0; + return value2; + } + constrainRoot(...args2) { + this.root = this.root.constrain(args2[0], args2[1]); + } + finalize(finalizer) { + if (this.groups.length) + return this.error(writeUnclosedGroupMessage(")")); + this.finalizeBranches(); + this.finalizer = finalizer; + } + reduceLeftBound(limit, comparator) { + const invertedComparator = invertedComparators[comparator]; + if (!isKeyOf(invertedComparator, minComparators)) + return this.error(writeUnpairableComparatorMessage(comparator)); + if (this.branches.leftBound) { + return this.error(writeMultipleLeftBoundsMessage(this.branches.leftBound.limit, this.branches.leftBound.comparator, limit, invertedComparator)); + } + this.branches.leftBound = { + comparator: invertedComparator, + limit + }; + } + finalizeBranches() { + this.assertRangeUnset(); + if (this.branches.pipe) { + this.pushRootToBranch("|>"); + this.root = this.branches.pipe; + return; + } + if (this.branches.union) { + this.pushRootToBranch("|"); + this.root = this.branches.union; + return; + } + if (this.branches.intersection) { + this.pushRootToBranch("&"); + this.root = this.branches.intersection; + return; + } + this.applyPrefixes(); + } + finalizeGroup() { + this.finalizeBranches(); + const topBranchState = this.groups.pop(); + if (!topBranchState) { + return this.error(writeUnmatchedGroupCloseMessage(")", this.scanner.unscanned)); + } + this.branches = topBranchState; + } + addPrefix(prefix) { + this.branches.prefixes.push(prefix); + } + applyPrefixes() { + while (this.branches.prefixes.length) { + const lastPrefix = this.branches.prefixes.pop(); + this.root = lastPrefix === "keyof" ? this.root.keyof() : throwInternalError(`Unexpected prefix '${lastPrefix}'`); + } + } + pushRootToBranch(token) { + this.assertRangeUnset(); + this.applyPrefixes(); + const root = this.root; + this.root = void 0; + this.branches.intersection = this.branches.intersection?.rawAnd(root) ?? root; + if (token === "&") + return; + this.branches.union = this.branches.union?.rawOr(this.branches.intersection) ?? this.branches.intersection; + this.branches.intersection = null; + if (token === "|") + return; + this.branches.pipe = this.branches.pipe?.rawPipeOnce(this.branches.union) ?? this.branches.union; + this.branches.union = null; + } + parseUntilFinalizer() { + return parseUntilFinalizer(new _RuntimeState(this.scanner, this.ctx)); + } + parseOperator() { + return parseOperator(this); + } + parseOperand() { + return parseOperand(this); + } + assertRangeUnset() { + if (this.branches.leftBound) { + return this.error(writeOpenRangeMessage(this.branches.leftBound.limit, this.branches.leftBound.comparator)); + } + } + reduceGroupOpen() { + this.groups.push(this.branches); + this.branches = { + prefixes: [], + leftBound: null, + union: null, + intersection: null, + pipe: null + }; + } + previousOperator() { + return this.branches.leftBound?.comparator ?? this.branches.prefixes[this.branches.prefixes.length - 1] ?? (this.branches.intersection ? "&" : this.branches.union ? "|" : this.branches.pipe ? "|>" : void 0); + } + shiftedBy(count) { + this.scanner.jumpForward(count); + return this; + } +}; + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/generic.js +var emptyGenericParameterMessage = "An empty string is not a valid generic parameter name"; +var parseGenericParamName = (scanner, result, ctx) => { + scanner.shiftUntilNonWhitespace(); + const name = scanner.shiftUntilLookahead(terminatingChars); + if (name === "") { + if (scanner.lookahead === "" && result.length) + return result; + return throwParseError(emptyGenericParameterMessage); + } + scanner.shiftUntilNonWhitespace(); + return _parseOptionalConstraint(scanner, name, result, ctx); +}; +var extendsToken = "extends "; +var _parseOptionalConstraint = (scanner, name, result, ctx) => { + scanner.shiftUntilNonWhitespace(); + if (scanner.unscanned.startsWith(extendsToken)) + scanner.jumpForward(extendsToken.length); + else { + if (scanner.lookahead === ",") + scanner.shift(); + result.push(name); + return parseGenericParamName(scanner, result, ctx); + } + const s = parseUntilFinalizer(new RuntimeState(scanner, ctx)); + result.push([name, s.root]); + return parseGenericParamName(scanner, result, ctx); +}; + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/fn.js +var InternalFnParser = class extends Callable { + constructor($2) { + const attach = { + $: $2, + raw: $2.fn + }; + super((...signature) => { + const returnOperatorIndex = signature.indexOf(":"); + const lastParamIndex = returnOperatorIndex === -1 ? signature.length - 1 : returnOperatorIndex - 1; + const paramDefs = signature.slice(0, lastParamIndex + 1); + const paramTuple = $2.parse(paramDefs).assertHasKind("intersection"); + let returnType = $2.intrinsic.unknown; + if (returnOperatorIndex !== -1) { + if (returnOperatorIndex !== signature.length - 2) + return throwParseError(badFnReturnTypeMessage); + returnType = $2.parse(signature[returnOperatorIndex + 1]); + } + return (impl) => new InternalTypedFn(impl, paramTuple, returnType); + }, { attach }); + } +}; +var InternalTypedFn = class extends Callable { + raw; + params; + returns; + expression; + constructor(raw2, params, returns) { + const typedName = `typed ${raw2.name}`; + const typed = { + // assign to a key with the expected name to force it to be created that way + [typedName]: (...args2) => { + const validatedArgs = params.assert(args2); + const returned = raw2(...validatedArgs); + return returns.assert(returned); + } + }[typedName]; + super(typed); + this.raw = raw2; + this.params = params; + this.returns = returns; + let argsExpression = params.expression; + if (argsExpression[0] === "[" && argsExpression[argsExpression.length - 1] === "]") + argsExpression = argsExpression.slice(1, -1); + else if (argsExpression.endsWith("[]")) + argsExpression = `...${argsExpression}`; + this.expression = `(${argsExpression}) => ${returns?.expression ?? "unknown"}`; + } +}; +var badFnReturnTypeMessage = `":" must be followed by exactly one return type e.g: +fn("string", ":", "number")(s => s.length)`; + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/match.js +var InternalMatchParser = class extends Callable { + $; + constructor($2) { + super((...args2) => new InternalChainedMatchParser($2)(...args2), { + bind: $2 + }); + this.$ = $2; + } + in(def) { + return new InternalChainedMatchParser(this.$, def === void 0 ? void 0 : this.$.parse(def)); + } + at(key, cases) { + return new InternalChainedMatchParser(this.$).at(key, cases); + } + case(when, then) { + return new InternalChainedMatchParser(this.$).case(when, then); + } +}; +var InternalChainedMatchParser = class extends Callable { + $; + in; + key; + branches = []; + constructor($2, In) { + super((cases) => this.caseEntries(Object.entries(cases).map(([k, v]) => k === "default" ? [k, v] : [this.$.parse(k), v]))); + this.$ = $2; + this.in = In; + } + at(key, cases) { + if (this.key) + throwParseError(doubleAtMessage); + if (this.branches.length) + throwParseError(chainedAtMessage); + this.key = key; + return cases ? this.match(cases) : this; + } + case(def, resolver) { + return this.caseEntry(this.$.parse(def), resolver); + } + caseEntry(node2, resolver) { + const wrappableNode = this.key ? this.$.parse({ [this.key]: node2 }) : node2; + const branch = wrappableNode.pipe(resolver); + this.branches.push(branch); + return this; + } + match(cases) { + return this(cases); + } + strings(cases) { + return this.caseEntries(Object.entries(cases).map(([k, v]) => k === "default" ? [k, v] : [this.$.node("unit", { unit: k }), v])); + } + caseEntries(entries) { + for (let i = 0; i < entries.length; i++) { + const [k, v] = entries[i]; + if (k === "default") { + if (i !== entries.length - 1) { + throwParseError(`default may only be specified as the last key of a switch definition`); + } + return this.default(v); + } + if (typeof v !== "function") { + return throwParseError(`Value for case "${k}" must be a function (was ${domainOf(v)})`); + } + this.caseEntry(k, v); + } + return this; + } + default(defaultCase) { + if (typeof defaultCase === "function") + this.case(intrinsic.unknown, defaultCase); + const schema2 = { + branches: this.branches, + ordered: true + }; + if (defaultCase === "never" || defaultCase === "assert") + schema2.meta = { onFail: throwOnDefault }; + const cases = this.$.node("union", schema2); + if (!this.in) + return this.$.finalize(cases); + let inputValidatedCases = this.in.pipe(cases); + if (defaultCase === "never" || defaultCase === "assert") { + inputValidatedCases = inputValidatedCases.configureReferences({ + onFail: throwOnDefault + }, "self"); + } + return this.$.finalize(inputValidatedCases); + } +}; +var throwOnDefault = (errors) => errors.throw(); +var chainedAtMessage = `A key matcher must be specified before the first case i.e. match.at('foo') or match.in().at('bar')`; +var doubleAtMessage = `At most one key matcher may be specified per expression`; + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/property.js +var parseProperty = (def, ctx) => { + if (isArray(def)) { + if (def[1] === "=") + return [ctx.$.parseOwnDefinitionFormat(def[0], ctx), "=", def[2]]; + if (def[1] === "?") + return [ctx.$.parseOwnDefinitionFormat(def[0], ctx), "?"]; + } + return parseInnerDefinition(def, ctx); +}; +var invalidOptionalKeyKindMessage = `Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }`; +var invalidDefaultableKeyKindMessage = `Only required keys may specify default values, e.g. { value: 'number = 0' }`; + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/objectLiteral.js +var parseObjectLiteral = (def, ctx) => { + let spread; + const structure = {}; + const defEntries = stringAndSymbolicEntriesOf(def); + for (const [k, v] of defEntries) { + const parsedKey = preparseKey(k); + if (parsedKey.kind === "spread") { + if (!isEmptyObject(structure)) + return throwParseError(nonLeadingSpreadError); + const operand = ctx.$.parseOwnDefinitionFormat(v, ctx); + if (operand.equals(intrinsic.object)) + continue; + if (!operand.hasKind("intersection") || // still error on attempts to spread proto nodes like ...Date + !operand.basis?.equals(intrinsic.object)) { + return throwParseError(writeInvalidSpreadTypeMessage(operand.expression)); + } + spread = operand.structure; + continue; + } + if (parsedKey.kind === "undeclared") { + if (v !== "reject" && v !== "delete" && v !== "ignore") + throwParseError(writeInvalidUndeclaredBehaviorMessage(v)); + structure.undeclared = v; + continue; + } + const parsedValue = parseProperty(v, ctx); + const parsedEntryKey = parsedKey; + if (parsedKey.kind === "required") { + if (!isArray(parsedValue)) { + appendNamedProp(structure, "required", { + key: parsedKey.normalized, + value: parsedValue + }, ctx); + } else { + appendNamedProp(structure, "optional", parsedValue[1] === "=" ? { + key: parsedKey.normalized, + value: parsedValue[0], + default: parsedValue[2] + } : { + key: parsedKey.normalized, + value: parsedValue[0] + }, ctx); + } + continue; + } + if (isArray(parsedValue)) { + if (parsedValue[1] === "?") + throwParseError(invalidOptionalKeyKindMessage); + if (parsedValue[1] === "=") + throwParseError(invalidDefaultableKeyKindMessage); + } + if (parsedKey.kind === "optional") { + appendNamedProp(structure, "optional", { + key: parsedKey.normalized, + value: parsedValue + }, ctx); + continue; + } + const signature = ctx.$.parseOwnDefinitionFormat(parsedEntryKey.normalized, ctx); + const normalized = normalizeIndex(signature, parsedValue, ctx.$); + if (normalized.index) + structure.index = append(structure.index, normalized.index); + if (normalized.required) + structure.required = append(structure.required, normalized.required); + } + const structureNode = ctx.$.node("structure", structure); + return ctx.$.parseSchema({ + domain: "object", + structure: spread?.merge(structureNode) ?? structureNode + }); +}; +var appendNamedProp = (structure, kind, inner, ctx) => { + structure[kind] = append( + // doesn't seem like this cast should be necessary + structure[kind], + ctx.$.node(kind, inner) + ); +}; +var writeInvalidUndeclaredBehaviorMessage = (actual) => `Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${printable(actual)})`; +var nonLeadingSpreadError = "Spread operator may only be used as the first key in an object"; +var preparseKey = (key) => typeof key === "symbol" ? { kind: "required", normalized: key } : key[key.length - 1] === "?" ? key[key.length - 2] === Backslash ? { kind: "required", normalized: `${key.slice(0, -2)}?` } : { + kind: "optional", + normalized: key.slice(0, -1) +} : key[0] === "[" && key[key.length - 1] === "]" ? { kind: "index", normalized: key.slice(1, -1) } : key[0] === Backslash && key[1] === "[" && key[key.length - 1] === "]" ? { kind: "required", normalized: key.slice(1) } : key === "..." ? { kind: "spread" } : key === "+" ? { kind: "undeclared" } : { + kind: "required", + normalized: key === "\\..." ? "..." : key === "\\+" ? "+" : key +}; +var writeInvalidSpreadTypeMessage = (def) => `Spread operand must resolve to an object literal type (was ${def})`; + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/tupleExpressions.js +var maybeParseTupleExpression = (def, ctx) => isIndexZeroExpression(def) ? indexZeroParsers[def[0]](def, ctx) : isIndexOneExpression(def) ? indexOneParsers[def[1]](def, ctx) : null; +var parseKeyOfTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[1], ctx).keyof(); +var parseBranchTuple = (def, ctx) => { + if (def[2] === void 0) + return throwParseError(writeMissingRightOperandMessage(def[1], "")); + const l = ctx.$.parseOwnDefinitionFormat(def[0], ctx); + const r = ctx.$.parseOwnDefinitionFormat(def[2], ctx); + if (def[1] === "|") + return ctx.$.node("union", { branches: [l, r] }); + const result = def[1] === "&" ? intersectNodesRoot(l, r, ctx.$) : pipeNodesRoot(l, r, ctx.$); + if (result instanceof Disjoint) + return result.throw(); + return result; +}; +var parseArrayTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[0], ctx).array(); +var parseMorphTuple = (def, ctx) => { + if (typeof def[2] !== "function") { + return throwParseError(writeMalformedFunctionalExpressionMessage("=>", def[2])); + } + return ctx.$.parseOwnDefinitionFormat(def[0], ctx).pipe(def[2]); +}; +var writeMalformedFunctionalExpressionMessage = (operator, value2) => `${operator === ":" ? "Narrow" : "Morph"} expression requires a function following '${operator}' (was ${typeof value2})`; +var parseNarrowTuple = (def, ctx) => { + if (typeof def[2] !== "function") { + return throwParseError(writeMalformedFunctionalExpressionMessage(":", def[2])); + } + return ctx.$.parseOwnDefinitionFormat(def[0], ctx).constrain("predicate", def[2]); +}; +var parseMetaTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[0], ctx).configure(def[2], def[3]); +var defineIndexOneParsers = (parsers) => parsers; +var postfixParsers = defineIndexOneParsers({ + "[]": parseArrayTuple, + "?": () => throwParseError(shallowOptionalMessage) +}); +var infixParsers = defineIndexOneParsers({ + "|": parseBranchTuple, + "&": parseBranchTuple, + ":": parseNarrowTuple, + "=>": parseMorphTuple, + "|>": parseBranchTuple, + "@": parseMetaTuple, + // since object and tuple literals parse there via `parseProperty`, + // they must be shallow if parsed directly as a tuple expression + "=": () => throwParseError(shallowDefaultableMessage) +}); +var indexOneParsers = { ...postfixParsers, ...infixParsers }; +var isIndexOneExpression = (def) => indexOneParsers[def[1]] !== void 0; +var defineIndexZeroParsers = (parsers) => parsers; +var indexZeroParsers = defineIndexZeroParsers({ + keyof: parseKeyOfTuple, + instanceof: (def, ctx) => { + if (typeof def[1] !== "function") { + return throwParseError(writeInvalidConstructorMessage(objectKindOrDomainOf(def[1]))); + } + const branches = def.slice(1).map((ctor) => typeof ctor === "function" ? ctx.$.node("proto", { proto: ctor }) : throwParseError(writeInvalidConstructorMessage(objectKindOrDomainOf(ctor)))); + return branches.length === 1 ? branches[0] : ctx.$.node("union", { branches }); + }, + "===": (def, ctx) => ctx.$.units(def.slice(1)) +}); +var isIndexZeroExpression = (def) => indexZeroParsers[def[0]] !== void 0; +var writeInvalidConstructorMessage = (actual) => `Expected a constructor following 'instanceof' operator (was ${actual})`; + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/tupleLiteral.js +var parseTupleLiteral = (def, ctx) => { + let sequences = [{}]; + let i = 0; + while (i < def.length) { + let spread = false; + if (def[i] === "..." && i < def.length - 1) { + spread = true; + i++; + } + const parsedProperty = parseProperty(def[i], ctx); + const [valueNode, operator, possibleDefaultValue] = !isArray(parsedProperty) ? [parsedProperty] : parsedProperty; + i++; + if (spread) { + if (!valueNode.extends($ark.intrinsic.Array)) + return throwParseError(writeNonArraySpreadMessage(valueNode.expression)); + sequences = sequences.flatMap((base) => ( + // since appendElement mutates base, we have to shallow-ish clone it for each branch + valueNode.distribute((branch) => appendSpreadBranch(makeRootAndArrayPropertiesMutable(base), branch)) + )); + } else { + sequences = sequences.map((base) => { + if (operator === "?") + return appendOptionalElement(base, valueNode); + if (operator === "=") + return appendDefaultableElement(base, valueNode, possibleDefaultValue); + return appendRequiredElement(base, valueNode); + }); + } + } + return ctx.$.parseSchema(sequences.map((sequence) => isEmptyObject(sequence) ? { + proto: Array, + exactLength: 0 + } : { + proto: Array, + sequence + })); +}; +var appendRequiredElement = (base, element) => { + if (base.defaultables || base.optionals) { + return throwParseError(base.variadic ? ( + // e.g. [boolean = true, ...string[], number] + postfixAfterOptionalOrDefaultableMessage + ) : requiredPostOptionalMessage); + } + if (base.variadic) { + base.postfix = append(base.postfix, element); + } else { + base.prefix = append(base.prefix, element); + } + return base; +}; +var appendOptionalElement = (base, element) => { + if (base.variadic) + return throwParseError(optionalOrDefaultableAfterVariadicMessage); + base.optionals = append(base.optionals, element); + return base; +}; +var appendDefaultableElement = (base, element, value2) => { + if (base.variadic) + return throwParseError(optionalOrDefaultableAfterVariadicMessage); + if (base.optionals) + return throwParseError(defaultablePostOptionalMessage); + base.defaultables = append(base.defaultables, [[element, value2]]); + return base; +}; +var appendVariadicElement = (base, element) => { + if (base.postfix) + throwParseError(multipleVariadicMesage); + if (base.variadic) { + if (!base.variadic.equals(element)) { + throwParseError(multipleVariadicMesage); + } + } else { + base.variadic = element.internal; + } + return base; +}; +var appendSpreadBranch = (base, branch) => { + const spread = branch.select({ method: "find", kind: "sequence" }); + if (!spread) { + return appendVariadicElement(base, $ark.intrinsic.unknown); + } + if (spread.prefix) + for (const node2 of spread.prefix) + appendRequiredElement(base, node2); + if (spread.optionals) + for (const node2 of spread.optionals) + appendOptionalElement(base, node2); + if (spread.variadic) + appendVariadicElement(base, spread.variadic); + if (spread.postfix) + for (const node2 of spread.postfix) + appendRequiredElement(base, node2); + return base; +}; +var writeNonArraySpreadMessage = (operand) => `Spread element must be an array (was ${operand})`; +var multipleVariadicMesage = "A tuple may have at most one variadic element"; +var requiredPostOptionalMessage = "A required element may not follow an optional element"; +var optionalOrDefaultableAfterVariadicMessage = "An optional element may not follow a variadic element"; +var defaultablePostOptionalMessage = "A defaultable element may not follow an optional element without a default"; + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/definition.js +var parseCache = {}; +var parseInnerDefinition = (def, ctx) => { + if (typeof def === "string") { + if (ctx.args && Object.keys(ctx.args).some((k) => def.includes(k))) { + return parseString(def, ctx); + } + const scopeCache = parseCache[ctx.$.name] ??= {}; + return scopeCache[def] ??= parseString(def, ctx); + } + return hasDomain(def, "object") ? parseObject(def, ctx) : throwParseError(writeBadDefinitionTypeMessage(domainOf(def))); +}; +var parseObject = (def, ctx) => { + const objectKind = objectKindOf(def); + switch (objectKind) { + case void 0: + if (hasArkKind(def, "root")) + return def; + if ("~standard" in def) + return parseStandardSchema(def, ctx); + return parseObjectLiteral(def, ctx); + case "Array": + return parseTuple(def, ctx); + case "RegExp": + return ctx.$.node("intersection", { + domain: "string", + pattern: def + }, { prereduced: true }); + case "Function": { + const resolvedDef = isThunk(def) ? def() : def; + if (hasArkKind(resolvedDef, "root")) + return resolvedDef; + return throwParseError(writeBadDefinitionTypeMessage("Function")); + } + default: + return throwParseError(writeBadDefinitionTypeMessage(objectKind ?? printable(def))); + } +}; +var parseStandardSchema = (def, ctx) => ctx.$.intrinsic.unknown.pipe((v, ctx2) => { + const result = def["~standard"].validate(v); + if (!result.issues) + return result.value; + for (const { message, path: path3 } of result.issues) { + if (path3) { + if (path3.length) { + ctx2.error({ + problem: uncapitalize(message), + relativePath: path3.map((k) => typeof k === "object" ? k.key : k) + }); + } else { + ctx2.error({ + message + }); + } + } else { + ctx2.error({ + message + }); + } + } +}); +var parseTuple = (def, ctx) => maybeParseTupleExpression(def, ctx) ?? parseTupleLiteral(def, ctx); +var writeBadDefinitionTypeMessage = (actual) => `Type definitions must be strings or objects (was ${actual})`; + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/type.js +var InternalTypeParser = class extends Callable { + constructor($2) { + const attach = Object.assign( + { + errors: ArkErrors, + hkt: Hkt, + $: $2, + raw: $2.parse, + module: $2.constructor.module, + scope: $2.constructor.scope, + declare: $2.declare, + define: $2.define, + match: $2.match, + generic: $2.generic, + schema: $2.schema, + // this won't be defined during bootstrapping, but externally always will be + keywords: $2.ambient, + unit: $2.unit, + enumerated: $2.enumerated, + instanceOf: $2.instanceOf, + valueOf: $2.valueOf, + or: $2.or, + and: $2.and, + merge: $2.merge, + pipe: $2.pipe, + fn: $2.fn + }, + // also won't be defined during bootstrapping + $2.ambientAttachments + ); + super((...args2) => { + if (args2.length === 1) { + return $2.parse(args2[0]); + } + if (args2.length === 2 && typeof args2[0] === "string" && args2[0][0] === "<" && args2[0][args2[0].length - 1] === ">") { + const paramString = args2[0].slice(1, -1); + const params = $2.parseGenericParams(paramString, {}); + return new GenericRoot(params, args2[1], $2, $2, null); + } + return $2.parse(args2); + }, { + attach + }); + } +}; + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/scope.js +var $arkTypeRegistry = $ark; +var InternalScope = class _InternalScope extends BaseScope { + get ambientAttachments() { + if (!$arkTypeRegistry.typeAttachments) + return; + return this.cacheGetter("ambientAttachments", flatMorph($arkTypeRegistry.typeAttachments, (k, v) => [ + k, + this.bindReference(v) + ])); + } + preparseOwnAliasEntry(alias, def) { + const firstParamIndex = alias.indexOf("<"); + if (firstParamIndex === -1) { + if (hasArkKind(def, "module") || hasArkKind(def, "generic")) + return [alias, def]; + const qualifiedName = this.name === "ark" ? alias : alias === "root" ? this.name : `${this.name}.${alias}`; + const config3 = this.resolvedConfig.keywords?.[qualifiedName]; + if (config3) + def = [def, "@", config3]; + return [alias, def]; + } + if (alias[alias.length - 1] !== ">") { + throwParseError(`'>' must be the last character of a generic declaration in a scope`); + } + const name = alias.slice(0, firstParamIndex); + const paramString = alias.slice(firstParamIndex + 1, -1); + return [ + name, + // use a thunk definition for the generic so that we can parse + // constraints within the current scope + () => { + const params = this.parseGenericParams(paramString, { alias: name }); + const generic2 = parseGeneric(params, def, this); + return generic2; + } + ]; + } + parseGenericParams(def, opts) { + return parseGenericParamName(new Scanner(def), [], this.createParseContext({ + ...opts, + def, + prefix: "generic" + })); + } + normalizeRootScopeValue(resolution) { + if (isThunk(resolution) && !hasArkKind(resolution, "generic")) + return resolution(); + return resolution; + } + preparseOwnDefinitionFormat(def, opts) { + return { + ...opts, + def, + prefix: opts.alias ?? "type" + }; + } + parseOwnDefinitionFormat(def, ctx) { + const isScopeAlias = ctx.alias && ctx.alias in this.aliases; + if (!isScopeAlias && !ctx.args) + ctx.args = { this: ctx.id }; + const result = parseInnerDefinition(def, ctx); + if (isArray(result)) { + if (result[1] === "=") + return throwParseError(shallowDefaultableMessage); + if (result[1] === "?") + return throwParseError(shallowOptionalMessage); + } + return result; + } + unit = (value2) => this.units([value2]); + valueOf = (tsEnum) => this.units(enumValues(tsEnum)); + enumerated = (...values) => this.units(values); + instanceOf = (ctor) => this.node("proto", { proto: ctor }, { prereduced: true }); + or = (...defs) => this.schema(defs.map((def) => this.parse(def))); + and = (...defs) => defs.reduce((node2, def) => node2.and(this.parse(def)), this.intrinsic.unknown); + merge = (...defs) => defs.reduce((node2, def) => node2.merge(this.parse(def)), this.intrinsic.object); + pipe = (...morphs) => this.intrinsic.unknown.pipe(...morphs); + fn = new InternalFnParser(this); + match = new InternalMatchParser(this); + declare = () => ({ + type: this.type + }); + define(def) { + return def; + } + type = new InternalTypeParser(this); + static scope = ((def, config3 = {}) => new _InternalScope(def, config3)); + static module = ((def, config3 = {}) => this.scope(def, config3).export()); +}; +var scope = Object.assign(InternalScope.scope, { + define: (def) => def +}); +var Scope = InternalScope; + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/keywords/builtins.js +var MergeHkt = class extends Hkt { + description = 'merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'; +}; +var Merge = genericNode(["base", intrinsic.object], ["props", intrinsic.object])((args2) => args2.base.merge(args2.props), MergeHkt); +var arkBuiltins = Scope.module({ + Key: intrinsic.key, + Merge +}); + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/keywords/Array.js +var liftFromHkt = class extends Hkt { +}; +var liftFrom = genericNode("element")((args2) => { + const nonArrayElement = args2.element.exclude(intrinsic.Array); + const lifted = nonArrayElement.array(); + return nonArrayElement.rawOr(lifted).pipe(liftArray).distribute((branch) => branch.assertHasKind("morph").declareOut(lifted), rootSchema); +}, liftFromHkt); +var arkArray = Scope.module({ + root: intrinsic.Array, + readonly: "root", + index: intrinsic.nonNegativeIntegerString, + liftFrom +}, { + name: "Array" +}); + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/keywords/FormData.js +var value = rootSchema(["string", registry.FileConstructor]); +var parsedFormDataValue = value.rawOr(value.array()); +var parsed = rootSchema({ + meta: "an object representing parsed form data", + domain: "object", + index: { + signature: "string", + value: parsedFormDataValue + } +}); +var arkFormData = Scope.module({ + root: ["instanceof", FormData], + value, + parsed, + parse: rootSchema({ + in: FormData, + morphs: (data) => { + const result = {}; + for (const [k, v] of data) { + if (k in result) { + const existing = result[k]; + if (typeof existing === "string" || existing instanceof registry.FileConstructor) + result[k] = [existing, v]; + else + existing.push(v); + } else + result[k] = v; + } + return result; + }, + declaredOut: parsed + }) +}, { + name: "FormData" +}); + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/keywords/TypedArray.js +var TypedArray = Scope.module({ + Int8: ["instanceof", Int8Array], + Uint8: ["instanceof", Uint8Array], + Uint8Clamped: ["instanceof", Uint8ClampedArray], + Int16: ["instanceof", Int16Array], + Uint16: ["instanceof", Uint16Array], + Int32: ["instanceof", Int32Array], + Uint32: ["instanceof", Uint32Array], + Float32: ["instanceof", Float32Array], + Float64: ["instanceof", Float64Array], + BigInt64: ["instanceof", BigInt64Array], + BigUint64: ["instanceof", BigUint64Array] +}, { + name: "TypedArray" +}); + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/keywords/constructors.js +var omittedPrototypes = { + Boolean: 1, + Number: 1, + String: 1 +}; +var arkPrototypes = Scope.module({ + ...flatMorph({ ...ecmascriptConstructors, ...platformConstructors }, (k, v) => k in omittedPrototypes ? [] : [k, ["instanceof", v]]), + Array: arkArray, + TypedArray, + FormData: arkFormData +}); + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/keywords/number.js +var epoch = rootSchema({ + domain: { + domain: "number", + meta: "a number representing a Unix timestamp" + }, + divisor: { + rule: 1, + meta: `an integer representing a Unix timestamp` + }, + min: { + rule: -864e13, + meta: `a Unix timestamp after -8640000000000000` + }, + max: { + rule: 864e13, + meta: "a Unix timestamp before 8640000000000000" + }, + meta: "an integer representing a safe Unix timestamp" +}); +var integer = rootSchema({ + domain: "number", + divisor: 1 +}); +var number = Scope.module({ + root: intrinsic.number, + integer, + epoch, + safe: rootSchema({ + domain: { + domain: "number", + numberAllowsNaN: false + }, + min: Number.MIN_SAFE_INTEGER, + max: Number.MAX_SAFE_INTEGER + }), + NaN: ["===", Number.NaN], + Infinity: ["===", Number.POSITIVE_INFINITY], + NegativeInfinity: ["===", Number.NEGATIVE_INFINITY] +}, { + name: "number" +}); + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/keywords/string.js +var regexStringNode = (regex4, description, jsonSchemaFormat) => { + const schema2 = { + domain: "string", + pattern: { + rule: regex4.source, + flags: regex4.flags, + meta: description + } + }; + if (jsonSchemaFormat) + schema2.meta = { format: jsonSchemaFormat }; + return node("intersection", schema2); +}; +var stringIntegerRoot = regexStringNode(wellFormedIntegerMatcher, "a well-formed integer string"); +var stringInteger = Scope.module({ + root: stringIntegerRoot, + parse: rootSchema({ + in: stringIntegerRoot, + morphs: (s, ctx) => { + const parsed2 = Number.parseInt(s); + return Number.isSafeInteger(parsed2) ? parsed2 : ctx.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER"); + }, + declaredOut: intrinsic.integer + }) +}, { + name: "string.integer" +}); +var hex = regexStringNode(/^[\dA-Fa-f]+$/, "hex characters only"); +var base64 = Scope.module({ + root: regexStringNode(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/, "base64-encoded"), + url: regexStringNode(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/, "base64url-encoded") +}, { + name: "string.base64" +}); +var preformattedCapitalize = regexStringNode(/^[A-Z].*$/, "capitalized"); +var capitalize2 = Scope.module({ + root: rootSchema({ + in: "string", + morphs: (s) => s.charAt(0).toUpperCase() + s.slice(1), + declaredOut: preformattedCapitalize + }), + preformatted: preformattedCapitalize +}, { + name: "string.capitalize" +}); +var isLuhnValid = (creditCardInput) => { + const sanitized = creditCardInput.replace(/[ -]+/g, ""); + let sum = 0; + let digit; + let tmpNum; + let shouldDouble = false; + for (let i = sanitized.length - 1; i >= 0; i--) { + digit = sanitized.substring(i, i + 1); + tmpNum = Number.parseInt(digit, 10); + if (shouldDouble) { + tmpNum *= 2; + sum += tmpNum >= 10 ? tmpNum % 10 + 1 : tmpNum; + } else + sum += tmpNum; + shouldDouble = !shouldDouble; + } + return !!(sum % 10 === 0 ? sanitized : false); +}; +var creditCardMatcher = /^(?:4\d{12}(?:\d{3,6})?|5[1-5]\d{14}|(222[1-9]|22[3-9]\d|2[3-6]\d{2}|27[01]\d|2720)\d{12}|6(?:011|5\d\d)\d{12,15}|3[47]\d{13}|3(?:0[0-5]|[68]\d)\d{11}|(?:2131|1800|35\d{3})\d{11}|6[27]\d{14}|^(81\d{14,17}))$/; +var creditCard = rootSchema({ + domain: "string", + pattern: { + meta: "a credit card number", + rule: creditCardMatcher.source + }, + predicate: { + meta: "a credit card number", + predicate: isLuhnValid + } +}); +var iso8601Matcher = /^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))(T((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([,.]\d+(?!:))?)?(\17[0-5]\d([,.]\d+)?)?([Zz]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/; +var isParsableDate = (s) => !Number.isNaN(new Date(s).valueOf()); +var parsableDate = rootSchema({ + domain: "string", + predicate: { + meta: "a parsable date", + predicate: isParsableDate + } +}).assertHasKind("intersection"); +var epochRoot = stringInteger.root.internal.narrow((s, ctx) => { + const n = Number.parseInt(s); + const out = number.epoch(n); + if (out instanceof ArkErrors) { + ctx.errors.merge(out); + return false; + } + return true; +}).configure({ + description: "an integer string representing a safe Unix timestamp" +}, "self").assertHasKind("intersection"); +var epoch2 = Scope.module({ + root: epochRoot, + parse: rootSchema({ + in: epochRoot, + morphs: (s) => new Date(s), + declaredOut: intrinsic.Date + }) +}, { + name: "string.date.epoch" +}); +var isoRoot = regexStringNode(iso8601Matcher, "an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"); +var iso = Scope.module({ + root: isoRoot, + parse: rootSchema({ + in: isoRoot, + morphs: (s) => new Date(s), + declaredOut: intrinsic.Date + }) +}, { + name: "string.date.iso" +}); +var stringDate = Scope.module({ + root: parsableDate, + parse: rootSchema({ + declaredIn: parsableDate, + in: "string", + morphs: (s, ctx) => { + const date5 = new Date(s); + if (Number.isNaN(date5.valueOf())) + return ctx.error("a parsable date"); + return date5; + }, + declaredOut: intrinsic.Date + }), + iso, + epoch: epoch2 +}, { + name: "string.date" +}); +var email = regexStringNode( + // considered https://colinhacks.com/essays/reasonable-email-regex but it includes a lookahead + // which breaks some integrations e.g. fast-check + // regex based on: + // https://www.regular-expressions.info/email.html + /^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/, + "an email address", + "email" +); +var ipv4Segment = "(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"; +var ipv4Address = `(${ipv4Segment}[.]){3}${ipv4Segment}`; +var ipv4Matcher = new RegExp(`^${ipv4Address}$`); +var ipv6Segment = "(?:[0-9a-fA-F]{1,4})"; +var ipv6Matcher = new RegExp(`^((?:${ipv6Segment}:){7}(?:${ipv6Segment}|:)|(?:${ipv6Segment}:){6}(?:${ipv4Address}|:${ipv6Segment}|:)|(?:${ipv6Segment}:){5}(?::${ipv4Address}|(:${ipv6Segment}){1,2}|:)|(?:${ipv6Segment}:){4}(?:(:${ipv6Segment}){0,1}:${ipv4Address}|(:${ipv6Segment}){1,3}|:)|(?:${ipv6Segment}:){3}(?:(:${ipv6Segment}){0,2}:${ipv4Address}|(:${ipv6Segment}){1,4}|:)|(?:${ipv6Segment}:){2}(?:(:${ipv6Segment}){0,3}:${ipv4Address}|(:${ipv6Segment}){1,5}|:)|(?:${ipv6Segment}:){1}(?:(:${ipv6Segment}){0,4}:${ipv4Address}|(:${ipv6Segment}){1,6}|:)|(?::((?::${ipv6Segment}){0,5}:${ipv4Address}|(?::${ipv6Segment}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`); +var ip = Scope.module({ + root: ["v4 | v6", "@", "an IP address"], + v4: regexStringNode(ipv4Matcher, "an IPv4 address", "ipv4"), + v6: regexStringNode(ipv6Matcher, "an IPv6 address", "ipv6") +}, { + name: "string.ip" +}); +var jsonStringDescription = "a JSON string"; +var writeJsonSyntaxErrorProblem = (error49) => { + if (!(error49 instanceof SyntaxError)) + throw error49; + return `must be ${jsonStringDescription} (${error49})`; +}; +var jsonRoot = rootSchema({ + meta: jsonStringDescription, + domain: "string", + predicate: { + meta: jsonStringDescription, + predicate: (s, ctx) => { + try { + JSON.parse(s); + return true; + } catch (e) { + return ctx.reject({ + code: "predicate", + expected: jsonStringDescription, + problem: writeJsonSyntaxErrorProblem(e) + }); + } + } + } +}); +var parseJson = (s, ctx) => { + if (s.length === 0) { + return ctx.error({ + code: "predicate", + expected: jsonStringDescription, + actual: "empty" + }); + } + try { + return JSON.parse(s); + } catch (e) { + return ctx.error({ + code: "predicate", + expected: jsonStringDescription, + problem: writeJsonSyntaxErrorProblem(e) + }); + } +}; +var json = Scope.module({ + root: jsonRoot, + parse: rootSchema({ + meta: "safe JSON string parser", + in: "string", + morphs: parseJson, + declaredOut: intrinsic.jsonObject + }) +}, { + name: "string.json" +}); +var preformattedLower = regexStringNode(/^[a-z]*$/, "only lowercase letters"); +var lower = Scope.module({ + root: rootSchema({ + in: "string", + morphs: (s) => s.toLowerCase(), + declaredOut: preformattedLower + }), + preformatted: preformattedLower +}, { + name: "string.lower" +}); +var normalizedForms = ["NFC", "NFD", "NFKC", "NFKD"]; +var preformattedNodes = flatMorph(normalizedForms, (i, form) => [ + form, + rootSchema({ + domain: "string", + predicate: (s) => s.normalize(form) === s, + meta: `${form}-normalized unicode` + }) +]); +var normalizeNodes = flatMorph(normalizedForms, (i, form) => [ + form, + rootSchema({ + in: "string", + morphs: (s) => s.normalize(form), + declaredOut: preformattedNodes[form] + }) +]); +var NFC = Scope.module({ + root: normalizeNodes.NFC, + preformatted: preformattedNodes.NFC +}, { + name: "string.normalize.NFC" +}); +var NFD = Scope.module({ + root: normalizeNodes.NFD, + preformatted: preformattedNodes.NFD +}, { + name: "string.normalize.NFD" +}); +var NFKC = Scope.module({ + root: normalizeNodes.NFKC, + preformatted: preformattedNodes.NFKC +}, { + name: "string.normalize.NFKC" +}); +var NFKD = Scope.module({ + root: normalizeNodes.NFKD, + preformatted: preformattedNodes.NFKD +}, { + name: "string.normalize.NFKD" +}); +var normalize = Scope.module({ + root: "NFC", + NFC, + NFD, + NFKC, + NFKD +}, { + name: "string.normalize" +}); +var numericRoot = regexStringNode(numericStringMatcher, "a well-formed numeric string"); +var stringNumeric = Scope.module({ + root: numericRoot, + parse: rootSchema({ + in: numericRoot, + morphs: (s) => Number.parseFloat(s), + declaredOut: intrinsic.number + }) +}, { + name: "string.numeric" +}); +var regexPatternDescription = "a regex pattern"; +var regex2 = rootSchema({ + domain: "string", + predicate: { + meta: regexPatternDescription, + predicate: (s, ctx) => { + try { + new RegExp(s); + return true; + } catch (e) { + return ctx.reject({ + code: "predicate", + expected: regexPatternDescription, + problem: String(e) + }); + } + } + }, + meta: { format: "regex" } +}); +var semverMatcher = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*))*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?$/; +var semver = regexStringNode(semverMatcher, "a semantic version (see https://semver.org/)"); +var preformattedTrim = regexStringNode( + // no leading or trailing whitespace + /^\S.*\S$|^\S?$/, + "trimmed" +); +var trim = Scope.module({ + root: rootSchema({ + in: "string", + morphs: (s) => s.trim(), + declaredOut: preformattedTrim + }), + preformatted: preformattedTrim +}, { + name: "string.trim" +}); +var preformattedUpper = regexStringNode(/^[A-Z]*$/, "only uppercase letters"); +var upper = Scope.module({ + root: rootSchema({ + in: "string", + morphs: (s) => s.toUpperCase(), + declaredOut: preformattedUpper + }), + preformatted: preformattedUpper +}, { + name: "string.upper" +}); +var isParsableUrl = (s) => URL.canParse(s); +var urlRoot = rootSchema({ + domain: "string", + predicate: { + meta: "a URL string", + predicate: isParsableUrl + }, + // URL.canParse allows a subset of the RFC-3986 URI spec + // since there is no other serializable validation, best include a format + meta: { format: "uri" } +}); +var url = Scope.module({ + root: urlRoot, + parse: rootSchema({ + declaredIn: urlRoot, + in: "string", + morphs: (s, ctx) => { + try { + return new URL(s); + } catch { + return ctx.error("a URL string"); + } + }, + declaredOut: rootSchema(URL) + }) +}, { + name: "string.url" +}); +var uuid = Scope.module({ + // the meta tuple expression ensures the error message does not delegate + // to the individual branches, which are too detailed + root: [ + "versioned | nil | max", + "@", + { description: "a UUID", format: "uuid" } + ], + "#nil": "'00000000-0000-0000-0000-000000000000'", + "#max": "'ffffffff-ffff-ffff-ffff-ffffffffffff'", + "#versioned": /[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}/i, + v1: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv1"), + v2: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv2"), + v3: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv3"), + v4: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv4"), + v5: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv5"), + v6: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv6"), + v7: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv7"), + v8: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv8") +}, { + name: "string.uuid" +}); +var string = Scope.module({ + root: intrinsic.string, + alpha: regexStringNode(/^[A-Za-z]*$/, "only letters"), + alphanumeric: regexStringNode(/^[\dA-Za-z]*$/, "only letters and digits 0-9"), + hex, + base64, + capitalize: capitalize2, + creditCard, + date: stringDate, + digits: regexStringNode(/^\d*$/, "only digits 0-9"), + email, + integer: stringInteger, + ip, + json, + lower, + normalize, + numeric: stringNumeric, + regex: regex2, + semver, + trim, + upper, + url, + uuid +}, { + name: "string" +}); + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/keywords/ts.js +var arkTsKeywords = Scope.module({ + bigint: intrinsic.bigint, + boolean: intrinsic.boolean, + false: intrinsic.false, + never: intrinsic.never, + null: intrinsic.null, + number: intrinsic.number, + object: intrinsic.object, + string: intrinsic.string, + symbol: intrinsic.symbol, + true: intrinsic.true, + unknown: intrinsic.unknown, + undefined: intrinsic.undefined +}); +var unknown = Scope.module({ + root: intrinsic.unknown, + any: intrinsic.unknown +}, { + name: "unknown" +}); +var json2 = Scope.module({ + root: intrinsic.jsonObject, + stringify: node("morph", { + in: intrinsic.jsonObject, + morphs: (data) => JSON.stringify(data), + declaredOut: intrinsic.string + }) +}, { + name: "object.json" +}); +var object = Scope.module({ + root: intrinsic.object, + json: json2 +}, { + name: "object" +}); +var RecordHkt = class extends Hkt { + description = 'instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'; +}; +var Record = genericNode(["K", intrinsic.key], "V")((args2) => ({ + domain: "object", + index: { + signature: args2.K, + value: args2.V + } +}), RecordHkt); +var PickHkt = class extends Hkt { + description = 'pick a set of properties from an object like `Pick(User, "name | age")`'; +}; +var Pick = genericNode(["T", intrinsic.object], ["K", intrinsic.key])((args2) => args2.T.pick(args2.K), PickHkt); +var OmitHkt = class extends Hkt { + description = 'omit a set of properties from an object like `Omit(User, "age")`'; +}; +var Omit = genericNode(["T", intrinsic.object], ["K", intrinsic.key])((args2) => args2.T.omit(args2.K), OmitHkt); +var PartialHkt = class extends Hkt { + description = "make all named properties of an object optional like `Partial(User)`"; +}; +var Partial = genericNode(["T", intrinsic.object])((args2) => args2.T.partial(), PartialHkt); +var RequiredHkt = class extends Hkt { + description = "make all named properties of an object required like `Required(User)`"; +}; +var Required2 = genericNode(["T", intrinsic.object])((args2) => args2.T.required(), RequiredHkt); +var ExcludeHkt = class extends Hkt { + description = 'exclude branches of a union like `Exclude("boolean", "true")`'; +}; +var Exclude = genericNode("T", "U")((args2) => args2.T.exclude(args2.U), ExcludeHkt); +var ExtractHkt = class extends Hkt { + description = 'extract branches of a union like `Extract("0 | false | 1", "number")`'; +}; +var Extract = genericNode("T", "U")((args2) => args2.T.extract(args2.U), ExtractHkt); +var arkTsGenerics = Scope.module({ + Exclude, + Extract, + Omit, + Partial, + Pick, + Record, + Required: Required2 +}); + +// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/keywords/keywords.js +var ark = scope({ + ...arkTsKeywords, + ...arkTsGenerics, + ...arkPrototypes, + ...arkBuiltins, + string, + number, + object, + unknown +}, { prereducedAliases: true, name: "ark" }); +var keywords = ark.export(); +Object.assign($arkTypeRegistry.ambient, keywords); +$arkTypeRegistry.typeAttachments = { + string: keywords.string.root, + number: keywords.number.root, + bigint: keywords.bigint, + boolean: keywords.boolean, + symbol: keywords.symbol, + undefined: keywords.undefined, + null: keywords.null, + object: keywords.object.root, + unknown: keywords.unknown.root, + false: keywords.false, + true: keywords.true, + never: keywords.never, + arrayIndex: keywords.Array.index, + Key: keywords.Key, + Record: keywords.Record, + Array: keywords.Array.root, + Date: keywords.Date +}; +var type = Object.assign( + ark.type, + // assign attachments newly parsed in keywords + // future scopes add these directly from the + // registry when their TypeParsers are instantiated + $arkTypeRegistry.typeAttachments +); +var match = ark.match; +var fn = ark.fn; +var generic = ark.generic; +var schema = ark.schema; +var define2 = ark.define; +var declare = ark.declare; + +// utils/log.ts +var core = __toESM(require_core(), 1); +var import_table = __toESM(require_src(), 1); +import { AsyncLocalStorage } from "node:async_hooks"; + +// utils/globals.ts +import { existsSync } from "node:fs"; +var isCloudflareSandbox = !!process.env.CLOUDFLARE_APPLICATION_ID && !!process.env.SANDBOX_VERSION; +var isGitHubActions = !!process.env.GITHUB_ACTIONS; +var isInsideDocker = existsSync("/.dockerenv"); + +// utils/log.ts +var logContext = new AsyncLocalStorage(); +var MAGENTA = "\x1B[35m"; +var RESET = "\x1B[0m"; +function prefixLines(message) { + const ctx = logContext.getStore(); + if (!ctx) return message; + const colored = `${MAGENTA}${ctx.prefix}${RESET} `; + return message.split("\n").map((line) => `${colored}${line}`).join("\n"); +} +function prefixPlain(name) { + const ctx = logContext.getStore(); + if (!ctx) return name; + return `${ctx.prefix} ${name}`; +} +var isRunnerDebugEnabled = () => core.isDebug(); +var isLocalDebugEnabled = () => process.env.LOG_LEVEL === "debug" || process.env.ACTIONS_STEP_DEBUG === "true"; +var isDebugEnabled = () => isLocalDebugEnabled() || isRunnerDebugEnabled(); +function ts() { + return isDebugEnabled() ? `[${(/* @__PURE__ */ new Date()).toISOString()}] ` : ""; +} +function formatArgs(args2) { + return args2.map((arg) => { + if (typeof arg === "string") return arg; + if (arg instanceof Error) return `${arg.message} +${arg.stack}`; + return JSON.stringify(arg); + }).join(" "); +} +function startGroup2(name) { + const prefixed = prefixPlain(name); + if (isGitHubActions) { + core.startGroup(prefixed); + } else { + console.group(prefixed); + } +} +function endGroup2() { + if (isGitHubActions) { + core.endGroup(); + } else { + console.groupEnd(); + } +} +function group(name, fn2) { + startGroup2(name); + fn2(); + endGroup2(); +} +function boxString(text, options) { + const { title, maxWidth = 80, indent: indent2 = "", padding = 1 } = options || {}; + const lines = text.trim().split("\n"); + const wrappedLines = []; + for (const line of lines) { + if (line.length <= maxWidth - padding * 2) { + wrappedLines.push(line); + } else { + const words = line.split(" "); + let currentLine = ""; + for (const word of words) { + const testLine = currentLine ? `${currentLine} ${word}` : word; + if (testLine.length <= maxWidth - padding * 2) { + currentLine = testLine; + } else { + if (currentLine) { + wrappedLines.push(currentLine); + currentLine = ""; + } + const maxLineLength2 = maxWidth - padding * 2; + let remainingWord = word; + while (remainingWord.length > maxLineLength2) { + wrappedLines.push(remainingWord.substring(0, maxLineLength2)); + remainingWord = remainingWord.substring(maxLineLength2); + } + currentLine = remainingWord; + } + } + if (currentLine) { + wrappedLines.push(currentLine); + } + } + } + const maxLineLength = Math.max(...wrappedLines.map((line) => line.length)); + const contentBoxWidth = maxLineLength + padding * 2; + const titleLineLength = title ? ` ${title} `.length : 0; + const boxWidth = Math.max(contentBoxWidth, titleLineLength); + let result = ""; + if (title) { + const titleLine = ` ${title} `; + const titlePadding = Math.max(0, boxWidth - titleLine.length); + result += `${indent2}\u250C${titleLine}${"\u2500".repeat(titlePadding)}\u2510 +`; + } + if (!title) { + result += `${indent2}\u250C${"\u2500".repeat(boxWidth)}\u2510 +`; + } + for (const line of wrappedLines) { + const paddedLine = line.padEnd(maxLineLength); + result += `${indent2}\u2502${" ".repeat(padding)}${paddedLine}${" ".repeat(padding)}\u2502 +`; + } + result += `${indent2}\u2514${"\u2500".repeat(boxWidth)}\u2518`; + return result; +} +function box(text, options) { + const boxContent = boxString(text, options); + core.info(prefixLines(boxContent)); +} +async function writeSummary(text) { + if (!isGitHubActions) return; + if (isInsideDocker) return; + if (!process.env.GITHUB_STEP_SUMMARY) return; + await core.summary.addRaw(text).write({ overwrite: true }); +} +function printTable(rows, options) { + const { title } = options || {}; + const tableData = rows.map( + (row) => row.map((cell) => { + if (typeof cell === "string") { + return cell; + } + return cell.data; + }) + ); + const formatted = (0, import_table.table)(tableData); + if (title) { + core.info(prefixLines(` +${title}`)); + } + core.info(prefixLines(` +${formatted} +`)); +} +function separator(length = 50) { + const separatorText = "\u2500".repeat(length); + core.info(prefixLines(separatorText)); +} +var log = { + /** Print info message */ + info: (...args2) => { + core.info(prefixLines(`${ts()}${formatArgs(args2)}`)); + }, + /** Print a warning message. Use only for warnings that should be displayed in the job summary. */ + warning: (...args2) => { + core.warning(prefixLines(`${ts()}${formatArgs(args2)}`)); + }, + /** Print an error message. Use only for errors that should be displayed in the job summary. */ + error: (...args2) => { + core.error(prefixLines(`${ts()}${formatArgs(args2)}`)); + }, + /** Print success message */ + success: (...args2) => { + core.info(prefixLines(`${ts()}\xBB ${formatArgs(args2)}`)); + }, + /** Print debug message (only when debug mode is enabled) */ + debug: (...args2) => { + if (isRunnerDebugEnabled()) { + core.debug(prefixLines(formatArgs(args2))); + return; + } + if (isLocalDebugEnabled()) { + core.info(prefixLines(`${ts()}[DEBUG] ${formatArgs(args2)}`)); + } + }, + /** Print a formatted box with text */ + box, + /** Print a formatted table using the table package */ + table: printTable, + /** Print a separator line */ + separator, + /** Start a collapsed group (GitHub Actions) or regular group (local) */ + startGroup: startGroup2, + /** End a collapsed group */ + endGroup: endGroup2, + /** Run a callback within a collapsed group */ + group, + /** Log tool call information to console with formatted output */ + toolCall: ({ toolName, input }) => { + const inputFormatted = formatJsonValue(input); + const output = inputFormatted !== "{}" ? `\xBB ${toolName}(${inputFormatted})` : `\xBB ${toolName}()`; + log.info(output.trimEnd()); + } +}; +function formatJsonValue(value2) { + const compact = JSON.stringify(value2); + return compact.length > 80 || compact.includes("\n") ? JSON.stringify(value2, null, 2) : compact; +} +function formatUsageSummary(entries) { + if (entries.length === 0) return ""; + const hasCost = entries.some((e) => e.costUsd !== void 0); + const header = hasCost ? "| Agent | Input | Output | Cache Read | Cache Write | Cost |" : "| Agent | Input | Output | Cache Read | Cache Write |"; + const fmt = (n) => n.toLocaleString("en-US"); + const separatorRow = hasCost ? "| --- | ---: | ---: | ---: | ---: | ---: |" : "| --- | ---: | ---: | ---: | ---: |"; + const rows = entries.map((e) => { + const base = `| ${e.agent} | ${fmt(e.inputTokens)} | ${fmt(e.outputTokens)} | ${fmt(e.cacheReadTokens ?? 0)} | ${fmt(e.cacheWriteTokens ?? 0)} |`; + return hasCost ? `${base} ${e.costUsd !== void 0 ? `$${e.costUsd.toFixed(4)}` : "-"} |` : base; + }); + const totalsRows = []; + if (entries.length > 1) { + const totalInput = entries.reduce((sum, e) => sum + e.inputTokens, 0); + const totalOutput = entries.reduce((sum, e) => sum + e.outputTokens, 0); + const totalCacheRead = entries.reduce((sum, e) => sum + (e.cacheReadTokens ?? 0), 0); + const totalCacheWrite = entries.reduce((sum, e) => sum + (e.cacheWriteTokens ?? 0), 0); + const totalBase = `| **Total** | **${fmt(totalInput)}** | **${fmt(totalOutput)}** | **${fmt(totalCacheRead)}** | **${fmt(totalCacheWrite)}** |`; + if (hasCost) { + const totalCost = entries.reduce((sum, e) => sum + (e.costUsd ?? 0), 0); + totalsRows.push(`${totalBase} **$${totalCost.toFixed(4)}** |`); + } else { + totalsRows.push(totalBase); + } + } + return [ + "
", + "Usage", + "", + header, + separatorRow, + ...rows, + ...totalsRows, + "", + "
" + ].join("\n"); +} + +// utils/apiUrl.ts +function isLocalUrl(url4) { + return url4.hostname === "localhost" || url4.hostname === "127.0.0.1"; +} +function getApiUrl() { + const raw2 = process.env.API_URL || "https://pullfrog.com"; + const parsed2 = new URL(raw2); + if (parsed2.protocol !== "https:" && !isLocalUrl(parsed2)) { + throw new Error( + `API_URL must use https:// (got ${parsed2.protocol}). only localhost is exempt.` + ); + } + log.debug(`resolved API_URL: ${raw2}`); + return raw2; +} + +// utils/apiFetch.ts +async function apiFetch(options) { + const apiUrl = getApiUrl(); + const url4 = new URL(options.path, apiUrl); + const bypassSecret = process.env.VERCEL_AUTOMATION_BYPASS_SECRET; + if (bypassSecret) { + url4.searchParams.set("x-vercel-protection-bypass", bypassSecret); + } + const headers = { + ...options.headers + }; + if (bypassSecret) { + headers["x-vercel-protection-bypass"] = bypassSecret; + } + log.debug(`api fetch: ${options.method ?? "GET"} ${url4.pathname}`); + const init = { + method: options.method ?? "GET", + headers + }; + if (options.body) init.body = options.body; + if (options.signal) init.signal = options.signal; + return fetch(url4.toString(), init); +} + +// models.ts +function provider(config3) { + return config3; +} +var providers = { + anthropic: provider({ + displayName: "Anthropic", + envVars: ["ANTHROPIC_API_KEY"], + models: { + "claude-opus": { + displayName: "Claude Opus", + resolve: "anthropic/claude-opus-4-6", + openRouterResolve: "openrouter/anthropic/claude-opus-4.6", + preferred: true + }, + "claude-sonnet": { + displayName: "Claude Sonnet", + resolve: "anthropic/claude-sonnet-4-6", + openRouterResolve: "openrouter/anthropic/claude-sonnet-4.6" + }, + "claude-haiku": { + displayName: "Claude Haiku", + resolve: "anthropic/claude-haiku-4-5", + openRouterResolve: "openrouter/anthropic/claude-haiku-4.5" + } + } + }), + openai: provider({ + displayName: "OpenAI", + envVars: ["OPENAI_API_KEY"], + models: { + "gpt-codex": { + displayName: "GPT Codex", + resolve: "openai/gpt-5.3-codex", + openRouterResolve: "openrouter/openai/gpt-5.3-codex", + preferred: true + }, + "gpt-codex-mini": { + displayName: "GPT Codex Mini", + resolve: "openai/codex-mini-latest", + openRouterResolve: "openrouter/openai/gpt-5.1-codex-mini" + }, + o3: { + displayName: "O3", + resolve: "openai/o3" + } + } + }), + google: provider({ + displayName: "Google", + envVars: ["GOOGLE_GENERATIVE_AI_API_KEY", "GEMINI_API_KEY"], + models: { + "gemini-pro": { + displayName: "Gemini Pro", + resolve: "google/gemini-3.1-pro-preview", + openRouterResolve: "openrouter/google/gemini-3.1-pro-preview", + preferred: true + }, + "gemini-flash": { + displayName: "Gemini Flash", + resolve: "google/gemini-3-flash-preview", + openRouterResolve: "openrouter/google/gemini-3-flash-preview" + } + } + }), + xai: provider({ + displayName: "xAI", + envVars: ["XAI_API_KEY"], + models: { + grok: { + displayName: "Grok", + resolve: "xai/grok-4", + openRouterResolve: "openrouter/x-ai/grok-4", + preferred: true + }, + "grok-fast": { + displayName: "Grok Fast", + resolve: "xai/grok-4-fast", + openRouterResolve: "openrouter/x-ai/grok-4-fast" + }, + "grok-code-fast": { + displayName: "Grok Code Fast", + resolve: "xai/grok-code-fast-1", + openRouterResolve: "openrouter/x-ai/grok-code-fast-1" + } + } + }), + deepseek: provider({ + displayName: "DeepSeek", + envVars: ["DEEPSEEK_API_KEY"], + models: { + "deepseek-reasoner": { + displayName: "DeepSeek Reasoner", + resolve: "deepseek/deepseek-reasoner", + openRouterResolve: "openrouter/deepseek/deepseek-v3.2", + preferred: true + }, + "deepseek-chat": { + displayName: "DeepSeek Chat", + resolve: "deepseek/deepseek-chat", + openRouterResolve: "openrouter/deepseek/deepseek-v3.2" + } + } + }), + moonshotai: provider({ + displayName: "Moonshot AI", + envVars: ["MOONSHOT_API_KEY"], + models: { + "kimi-k2": { + displayName: "Kimi K2", + resolve: "moonshotai/kimi-k2.5", + openRouterResolve: "openrouter/moonshotai/kimi-k2.5", + preferred: true + } + } + }), + opencode: provider({ + displayName: "OpenCode", + envVars: ["OPENCODE_API_KEY"], + models: { + "big-pickle": { + displayName: "Big Pickle", + resolve: "opencode/big-pickle", + preferred: true, + envVars: [], + isFree: true + }, + "claude-opus": { + displayName: "Claude Opus", + resolve: "opencode/claude-opus-4-6", + openRouterResolve: "openrouter/anthropic/claude-opus-4.6" + }, + "claude-sonnet": { + displayName: "Claude Sonnet", + resolve: "opencode/claude-sonnet-4-6", + openRouterResolve: "openrouter/anthropic/claude-sonnet-4.6" + }, + "claude-haiku": { + displayName: "Claude Haiku", + resolve: "opencode/claude-haiku-4-5", + openRouterResolve: "openrouter/anthropic/claude-haiku-4.5" + }, + "gpt-codex": { + displayName: "GPT Codex", + resolve: "opencode/gpt-5.3-codex", + openRouterResolve: "openrouter/openai/gpt-5.3-codex" + }, + "gpt-codex-mini": { + displayName: "GPT Codex Mini", + resolve: "opencode/gpt-5.1-codex-mini", + openRouterResolve: "openrouter/openai/gpt-5.1-codex-mini" + }, + "gemini-pro": { + displayName: "Gemini Pro", + resolve: "opencode/gemini-3.1-pro", + openRouterResolve: "openrouter/google/gemini-3.1-pro-preview" + }, + "gemini-flash": { + displayName: "Gemini Flash", + resolve: "opencode/gemini-3-flash", + openRouterResolve: "openrouter/google/gemini-3-flash-preview" + }, + "kimi-k2": { + displayName: "Kimi K2", + resolve: "opencode/kimi-k2.5", + openRouterResolve: "openrouter/moonshotai/kimi-k2.5" + }, + "gpt-5-nano": { + displayName: "GPT Nano", + resolve: "opencode/gpt-5-nano", + envVars: [], + isFree: true + }, + "mimo-v2-pro-free": { + displayName: "MiMo V2 Pro", + resolve: "opencode/mimo-v2-pro-free", + envVars: [], + isFree: true + }, + "minimax-m2.5-free": { + displayName: "MiniMax M2.5", + resolve: "opencode/minimax-m2.5-free", + envVars: [], + isFree: true + }, + "nemotron-3-super-free": { + displayName: "Nemotron 3 Super", + resolve: "opencode/nemotron-3-super-free", + envVars: [], + isFree: true + } + } + }), + openrouter: provider({ + displayName: "OpenRouter", + envVars: ["OPENROUTER_API_KEY"], + models: { + "claude-opus": { + displayName: "Claude Opus", + resolve: "openrouter/anthropic/claude-opus-4.6", + openRouterResolve: "openrouter/anthropic/claude-opus-4.6", + preferred: true + }, + "claude-sonnet": { + displayName: "Claude Sonnet", + resolve: "openrouter/anthropic/claude-sonnet-4.6", + openRouterResolve: "openrouter/anthropic/claude-sonnet-4.6" + }, + "claude-haiku": { + displayName: "Claude Haiku", + resolve: "openrouter/anthropic/claude-haiku-4.5", + openRouterResolve: "openrouter/anthropic/claude-haiku-4.5" + }, + "gpt-codex": { + displayName: "GPT Codex", + resolve: "openrouter/openai/gpt-5.3-codex", + openRouterResolve: "openrouter/openai/gpt-5.3-codex" + }, + "gpt-codex-mini": { + displayName: "GPT Codex Mini", + resolve: "openrouter/openai/gpt-5.1-codex-mini", + openRouterResolve: "openrouter/openai/gpt-5.1-codex-mini" + }, + "o4-mini": { + displayName: "O4 Mini", + resolve: "openrouter/openai/o4-mini", + openRouterResolve: "openrouter/openai/o4-mini" + }, + "gemini-pro": { + displayName: "Gemini Pro", + resolve: "openrouter/google/gemini-3.1-pro-preview", + openRouterResolve: "openrouter/google/gemini-3.1-pro-preview" + }, + "gemini-flash": { + displayName: "Gemini Flash", + resolve: "openrouter/google/gemini-3-flash-preview", + openRouterResolve: "openrouter/google/gemini-3-flash-preview" + }, + grok: { + displayName: "Grok", + resolve: "openrouter/x-ai/grok-4", + openRouterResolve: "openrouter/x-ai/grok-4" + }, + "deepseek-chat": { + displayName: "DeepSeek Chat", + resolve: "openrouter/deepseek/deepseek-v3.2", + openRouterResolve: "openrouter/deepseek/deepseek-v3.2" + }, + "kimi-k2": { + displayName: "Kimi K2", + resolve: "openrouter/moonshotai/kimi-k2.5", + openRouterResolve: "openrouter/moonshotai/kimi-k2.5" + } + } + }) +}; +function parseModel(slug) { + const slashIdx = slug.indexOf("/"); + if (slashIdx === -1) { + throw new Error(`invalid model slug "${slug}" \u2014 expected "provider/model"`); + } + return { provider: slug.slice(0, slashIdx), model: slug.slice(slashIdx + 1) }; +} +function getModelEnvVars(slug) { + const parsed2 = parseModel(slug); + const providerConfig = providers[parsed2.provider]; + if (!providerConfig) { + return []; + } + const modelConfig = providerConfig.models[parsed2.model]; + if (modelConfig?.envVars) { + return modelConfig.envVars.slice(); + } + return providerConfig.envVars.slice(); +} +var modelAliases = Object.entries(providers).flatMap( + ([providerKey, config3]) => Object.entries(config3.models).map(([modelId, def]) => ({ + slug: `${providerKey}/${modelId}`, + provider: providerKey, + displayName: def.displayName, + resolve: def.resolve, + openRouterResolve: def.openRouterResolve, + preferred: def.preferred ?? false, + isFree: def.isFree ?? false + })) +); +function resolveModelSlug(slug) { + return modelAliases.find((a) => a.slug === slug)?.resolve; +} +function resolveCliModel(slug) { + return resolveModelSlug(slug); +} + +// utils/buildPullfrogFooter.ts +var PULLFROG_DIVIDER = ""; +var FROG_LOGO = `Pullfrog`; +function formatModelLabel(slug) { + const alias = modelAliases.find((a) => a.slug === slug); + if (!alias) return `\`${slug}\``; + return alias.isFree ? `\`${alias.displayName}\` (free)` : `\`${alias.displayName}\``; +} +function buildPullfrogFooter(params) { + const parts = []; + if (params.customParts) { + parts.push(...params.customParts); + } + if (params.workflowRunUrl) { + parts.push(`[View workflow run](${params.workflowRunUrl})`); + } else if (params.workflowRun) { + const baseUrl = `https://github.com/${params.workflowRun.owner}/${params.workflowRun.repo}/actions/runs/${params.workflowRun.runId}`; + const url4 = params.workflowRun.jobId ? `${baseUrl}/job/${params.workflowRun.jobId}` : baseUrl; + parts.push(`[View workflow run](${url4})`); + } + if (params.triggeredBy) { + parts.push("Triggered by [Pullfrog](https://pullfrog.com)"); + } + if (params.model) { + parts.push(`Using ${formatModelLabel(params.model)}`); + } + const allParts = [...parts, "[\u{1D54F}](https://x.com/pullfrogai)"]; + return ` +${PULLFROG_DIVIDER} +${FROG_LOGO}  \uFF5C ${allParts.join(" \uFF5C ")}`; +} +function stripExistingFooter(body) { + const dividerIndex = body.indexOf(PULLFROG_DIVIDER); + if (dividerIndex === -1) { + return body; + } + return body.substring(0, dividerIndex).trimEnd(); +} + +// utils/fixDoubleEscapedString.ts +function fixDoubleEscapedString(str) { + if (!str.includes("\n") && str.includes("\\n")) { + return str.replace(/\\n/g, "\n").replace(/\\t/g, " ").replace(/\\"/g, '"'); + } + return str; +} + +// utils/github.ts +var core2 = __toESM(require_core(), 1); +import { createSign } from "node:crypto"; +import { rename, writeFile } from "node:fs/promises"; +import { dirname, join } from "node:path"; + +// node_modules/.pnpm/@octokit+plugin-throttling@11.0.3_@octokit+core@7.0.5/node_modules/@octokit/plugin-throttling/dist-bundle/index.js +var import_light = __toESM(require_light(), 1); +var VERSION = "0.0.0-development"; +var noop = () => Promise.resolve(); +function wrapRequest(state, request2, options) { + return state.retryLimiter.schedule(doRequest, state, request2, options); +} +async function doRequest(state, request2, options) { + const { pathname } = new URL(options.url, "http://github.test"); + const isAuth = isAuthRequest(options.method, pathname); + const isWrite = !isAuth && options.method !== "GET" && options.method !== "HEAD"; + const isSearch = options.method === "GET" && pathname.startsWith("/search/"); + const isGraphQL = pathname.startsWith("/graphql"); + const retryCount = ~~request2.retryCount; + const jobOptions = retryCount > 0 ? { priority: 0, weight: 0 } : {}; + if (state.clustering) { + jobOptions.expiration = 1e3 * 60; + } + if (isWrite || isGraphQL) { + await state.write.key(state.id).schedule(jobOptions, noop); + } + if (isWrite && state.triggersNotification(pathname)) { + await state.notifications.key(state.id).schedule(jobOptions, noop); + } + if (isSearch) { + await state.search.key(state.id).schedule(jobOptions, noop); + } + const req = (isAuth ? state.auth : state.global).key(state.id).schedule(jobOptions, request2, options); + if (isGraphQL) { + const res = await req; + if (res.data.errors != null && res.data.errors.some((error49) => error49.type === "RATE_LIMITED")) { + const error49 = Object.assign(new Error("GraphQL Rate Limit Exceeded"), { + response: res, + data: res.data + }); + throw error49; + } + } + return req; +} +function isAuthRequest(method, pathname) { + return method === "PATCH" && // https://docs.github.com/en/rest/apps/apps?apiVersion=2022-11-28#create-a-scoped-access-token + /^\/applications\/[^/]+\/token\/scoped$/.test(pathname) || method === "POST" && // https://docs.github.com/en/rest/apps/oauth-applications?apiVersion=2022-11-28#reset-a-token + (/^\/applications\/[^/]+\/token$/.test(pathname) || // https://docs.github.com/en/rest/apps/apps?apiVersion=2022-11-28#create-an-installation-access-token-for-an-app + /^\/app\/installations\/[^/]+\/access_tokens$/.test(pathname) || // https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/authorizing-oauth-apps + pathname === "/login/oauth/access_token"); +} +var triggers_notification_paths_default = [ + "/orgs/{org}/invitations", + "/orgs/{org}/invitations/{invitation_id}", + "/orgs/{org}/teams/{team_slug}/discussions", + "/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", + "/repos/{owner}/{repo}/collaborators/{username}", + "/repos/{owner}/{repo}/commits/{commit_sha}/comments", + "/repos/{owner}/{repo}/issues", + "/repos/{owner}/{repo}/issues/{issue_number}/comments", + "/repos/{owner}/{repo}/issues/{issue_number}/sub_issue", + "/repos/{owner}/{repo}/issues/{issue_number}/sub_issues/priority", + "/repos/{owner}/{repo}/pulls", + "/repos/{owner}/{repo}/pulls/{pull_number}/comments", + "/repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies", + "/repos/{owner}/{repo}/pulls/{pull_number}/merge", + "/repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers", + "/repos/{owner}/{repo}/pulls/{pull_number}/reviews", + "/repos/{owner}/{repo}/releases", + "/teams/{team_id}/discussions", + "/teams/{team_id}/discussions/{discussion_number}/comments" +]; +function routeMatcher(paths) { + const regexes = paths.map( + (path3) => path3.split("/").map((c) => c.startsWith("{") ? "(?:.+?)" : c).join("/") + ); + const regex22 = `^(?:${regexes.map((r) => `(?:${r})`).join("|")})[^/]*$`; + return new RegExp(regex22, "i"); +} +var regex3 = routeMatcher(triggers_notification_paths_default); +var triggersNotification = regex3.test.bind(regex3); +var groups = {}; +var createGroups = function(Bottleneck, common) { + groups.global = new Bottleneck.Group({ + id: "octokit-global", + maxConcurrent: 10, + ...common + }); + groups.auth = new Bottleneck.Group({ + id: "octokit-auth", + maxConcurrent: 1, + ...common + }); + groups.search = new Bottleneck.Group({ + id: "octokit-search", + maxConcurrent: 1, + minTime: 2e3, + ...common + }); + groups.write = new Bottleneck.Group({ + id: "octokit-write", + maxConcurrent: 1, + minTime: 1e3, + ...common + }); + groups.notifications = new Bottleneck.Group({ + id: "octokit-notifications", + maxConcurrent: 1, + minTime: 3e3, + ...common + }); +}; +function throttling(octokit, octokitOptions) { + const { + enabled = true, + Bottleneck = import_light.default, + id = "no-id", + timeout = 1e3 * 60 * 2, + // Redis TTL: 2 minutes + connection + } = octokitOptions.throttle || {}; + if (!enabled) { + return {}; + } + const common = { timeout }; + if (typeof connection !== "undefined") { + common.connection = connection; + } + if (groups.global == null) { + createGroups(Bottleneck, common); + } + const state = Object.assign( + { + clustering: connection != null, + triggersNotification, + fallbackSecondaryRateRetryAfter: 60, + retryAfterBaseValue: 1e3, + retryLimiter: new Bottleneck(), + id, + ...groups + }, + octokitOptions.throttle + ); + if (typeof state.onSecondaryRateLimit !== "function" || typeof state.onRateLimit !== "function") { + throw new Error(`octokit/plugin-throttling error: + You must pass the onSecondaryRateLimit and onRateLimit error handlers. + See https://octokit.github.io/rest.js/#throttling + + const octokit = new Octokit({ + throttle: { + onSecondaryRateLimit: (retryAfter, options) => {/* ... */}, + onRateLimit: (retryAfter, options) => {/* ... */} + } + }) + `); + } + const events = {}; + const emitter = new Bottleneck.Events(events); + events.on("secondary-limit", state.onSecondaryRateLimit); + events.on("rate-limit", state.onRateLimit); + events.on( + "error", + (e) => octokit.log.warn("Error in throttling-plugin limit handler", e) + ); + state.retryLimiter.on("failed", async function(error49, info2) { + const [state2, request2, options] = info2.args; + const { pathname } = new URL(options.url, "http://github.test"); + const shouldRetryGraphQL = pathname.startsWith("/graphql") && error49.status !== 401; + if (!(shouldRetryGraphQL || error49.status === 403 || error49.status === 429)) { + return; + } + const retryCount = ~~request2.retryCount; + request2.retryCount = retryCount; + options.request.retryCount = retryCount; + const { wantRetry, retryAfter = 0 } = await (async function() { + if (/\bsecondary rate\b/i.test(error49.message)) { + const retryAfter2 = Number(error49.response.headers["retry-after"]) || state2.fallbackSecondaryRateRetryAfter; + const wantRetry2 = await emitter.trigger( + "secondary-limit", + retryAfter2, + options, + octokit, + retryCount + ); + return { wantRetry: wantRetry2, retryAfter: retryAfter2 }; + } + if (error49.response.headers != null && error49.response.headers["x-ratelimit-remaining"] === "0" || (error49.response.data?.errors ?? []).some( + (error210) => error210.type === "RATE_LIMITED" + )) { + const rateLimitReset = new Date( + ~~error49.response.headers["x-ratelimit-reset"] * 1e3 + ).getTime(); + const retryAfter2 = Math.max( + // Add one second so we retry _after_ the reset time + // https://docs.github.com/en/rest/overview/resources-in-the-rest-api?apiVersion=2022-11-28#exceeding-the-rate-limit + Math.ceil((rateLimitReset - Date.now()) / 1e3) + 1, + 0 + ); + const wantRetry2 = await emitter.trigger( + "rate-limit", + retryAfter2, + options, + octokit, + retryCount + ); + return { wantRetry: wantRetry2, retryAfter: retryAfter2 }; + } + return {}; + })(); + if (wantRetry) { + request2.retryCount++; + return retryAfter * state2.retryAfterBaseValue; + } + }); + octokit.hook.wrap("request", wrapRequest.bind(null, state)); + return {}; +} +throttling.VERSION = VERSION; +throttling.triggersNotification = triggersNotification; + +// node_modules/.pnpm/universal-user-agent@7.0.3/node_modules/universal-user-agent/index.js +function getUserAgent() { + if (typeof navigator === "object" && "userAgent" in navigator) { + return navigator.userAgent; + } + if (typeof process === "object" && process.version !== void 0) { + return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; + } + return ""; +} + +// node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/lib/register.js +function register2(state, name, method, options) { + if (typeof method !== "function") { + throw new Error("method for before hook must be a function"); + } + if (!options) { + options = {}; + } + if (Array.isArray(name)) { + return name.reverse().reduce((callback, name2) => { + return register2.bind(null, state, name2, callback, options); + }, method)(); + } + return Promise.resolve().then(() => { + if (!state.registry[name]) { + return method(options); + } + return state.registry[name].reduce((method2, registered) => { + return registered.hook.bind(null, method2, options); + }, method)(); + }); +} + +// node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/lib/add.js +function addHook(state, kind, name, hook2) { + const orig = hook2; + if (!state.registry[name]) { + state.registry[name] = []; + } + if (kind === "before") { + hook2 = (method, options) => { + return Promise.resolve().then(orig.bind(null, options)).then(method.bind(null, options)); + }; + } + if (kind === "after") { + hook2 = (method, options) => { + let result; + return Promise.resolve().then(method.bind(null, options)).then((result_) => { + result = result_; + return orig(result, options); + }).then(() => { + return result; + }); + }; + } + if (kind === "error") { + hook2 = (method, options) => { + return Promise.resolve().then(method.bind(null, options)).catch((error49) => { + return orig(error49, options); + }); + }; + } + state.registry[name].push({ + hook: hook2, + orig + }); +} + +// node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/lib/remove.js +function removeHook(state, name, method) { + if (!state.registry[name]) { + return; + } + const index = state.registry[name].map((registered) => { + return registered.orig; + }).indexOf(method); + if (index === -1) { + return; + } + state.registry[name].splice(index, 1); +} + +// node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/index.js +var bind = Function.bind; +var bindable = bind.bind(bind); +function bindApi(hook2, state, name) { + const removeHookRef = bindable(removeHook, null).apply( + null, + name ? [state, name] : [state] + ); + hook2.api = { remove: removeHookRef }; + hook2.remove = removeHookRef; + ["before", "error", "after", "wrap"].forEach((kind) => { + const args2 = name ? [state, kind, name] : [state, kind]; + hook2[kind] = hook2.api[kind] = bindable(addHook, null).apply(null, args2); + }); +} +function Singular() { + const singularHookName = Symbol("Singular"); + const singularHookState = { + registry: {} + }; + const singularHook = register2.bind(null, singularHookState, singularHookName); + bindApi(singularHook, singularHookState, singularHookName); + return singularHook; +} +function Collection() { + const state = { + registry: {} + }; + const hook2 = register2.bind(null, state); + bindApi(hook2, state); + return hook2; +} +var before_after_hook_default = { Singular, Collection }; + +// node_modules/.pnpm/@octokit+endpoint@11.0.1/node_modules/@octokit/endpoint/dist-bundle/index.js +var VERSION2 = "0.0.0-development"; +var userAgent = `octokit-endpoint.js/${VERSION2} ${getUserAgent()}`; +var DEFAULTS = { + method: "GET", + baseUrl: "https://api.github.com", + headers: { + accept: "application/vnd.github.v3+json", + "user-agent": userAgent + }, + mediaType: { + format: "" + } +}; +function lowercaseKeys(object5) { + if (!object5) { + return {}; + } + return Object.keys(object5).reduce((newObj, key) => { + newObj[key.toLowerCase()] = object5[key]; + return newObj; + }, {}); +} +function isPlainObject(value2) { + if (typeof value2 !== "object" || value2 === null) return false; + if (Object.prototype.toString.call(value2) !== "[object Object]") return false; + const proto = Object.getPrototypeOf(value2); + if (proto === null) return true; + const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor; + return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value2); +} +function mergeDeep(defaults, options) { + const result = Object.assign({}, defaults); + Object.keys(options).forEach((key) => { + if (isPlainObject(options[key])) { + if (!(key in defaults)) Object.assign(result, { [key]: options[key] }); + else result[key] = mergeDeep(defaults[key], options[key]); + } else { + Object.assign(result, { [key]: options[key] }); + } + }); + return result; +} +function removeUndefinedProperties(obj) { + for (const key in obj) { + if (obj[key] === void 0) { + delete obj[key]; + } + } + return obj; +} +function merge(defaults, route, options) { + if (typeof route === "string") { + let [method, url4] = route.split(" "); + options = Object.assign(url4 ? { method, url: url4 } : { url: method }, options); + } else { + options = Object.assign({}, route); + } + options.headers = lowercaseKeys(options.headers); + removeUndefinedProperties(options); + removeUndefinedProperties(options.headers); + const mergedOptions = mergeDeep(defaults || {}, options); + if (options.url === "/graphql") { + if (defaults && defaults.mediaType.previews?.length) { + mergedOptions.mediaType.previews = defaults.mediaType.previews.filter( + (preview) => !mergedOptions.mediaType.previews.includes(preview) + ).concat(mergedOptions.mediaType.previews); + } + mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, "")); + } + return mergedOptions; +} +function addQueryParameters(url4, parameters) { + const separator2 = /\?/.test(url4) ? "&" : "?"; + const names = Object.keys(parameters); + if (names.length === 0) { + return url4; + } + return url4 + separator2 + names.map((name) => { + if (name === "q") { + return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); + } + return `${name}=${encodeURIComponent(parameters[name])}`; + }).join("&"); +} +var urlVariableRegex = /\{[^{}}]+\}/g; +function removeNonChars(variableName) { + return variableName.replace(/(?:^\W+)|(?:(? a.concat(b), []); +} +function omit2(object5, keysToOmit) { + const result = { __proto__: null }; + for (const key of Object.keys(object5)) { + if (keysToOmit.indexOf(key) === -1) { + result[key] = object5[key]; + } + } + return result; +} +function encodeReserved(str) { + return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) { + if (!/%[0-9A-Fa-f]/.test(part)) { + part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); + } + return part; + }).join(""); +} +function encodeUnreserved(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); + }); +} +function encodeValue(operator, value2, key) { + value2 = operator === "+" || operator === "#" ? encodeReserved(value2) : encodeUnreserved(value2); + if (key) { + return encodeUnreserved(key) + "=" + value2; + } else { + return value2; + } +} +function isDefined(value2) { + return value2 !== void 0 && value2 !== null; +} +function isKeyOperator(operator) { + return operator === ";" || operator === "&" || operator === "?"; +} +function getValues(context, operator, key, modifier) { + var value2 = context[key], result = []; + if (isDefined(value2) && value2 !== "") { + if (typeof value2 === "string" || typeof value2 === "number" || typeof value2 === "boolean") { + value2 = value2.toString(); + if (modifier && modifier !== "*") { + value2 = value2.substring(0, parseInt(modifier, 10)); + } + result.push( + encodeValue(operator, value2, isKeyOperator(operator) ? key : "") + ); + } else { + if (modifier === "*") { + if (Array.isArray(value2)) { + value2.filter(isDefined).forEach(function(value22) { + result.push( + encodeValue(operator, value22, isKeyOperator(operator) ? key : "") + ); + }); + } else { + Object.keys(value2).forEach(function(k) { + if (isDefined(value2[k])) { + result.push(encodeValue(operator, value2[k], k)); + } + }); + } + } else { + const tmp = []; + if (Array.isArray(value2)) { + value2.filter(isDefined).forEach(function(value22) { + tmp.push(encodeValue(operator, value22)); + }); + } else { + Object.keys(value2).forEach(function(k) { + if (isDefined(value2[k])) { + tmp.push(encodeUnreserved(k)); + tmp.push(encodeValue(operator, value2[k].toString())); + } + }); + } + if (isKeyOperator(operator)) { + result.push(encodeUnreserved(key) + "=" + tmp.join(",")); + } else if (tmp.length !== 0) { + result.push(tmp.join(",")); + } + } + } + } else { + if (operator === ";") { + if (isDefined(value2)) { + result.push(encodeUnreserved(key)); + } + } else if (value2 === "" && (operator === "&" || operator === "?")) { + result.push(encodeUnreserved(key) + "="); + } else if (value2 === "") { + result.push(""); + } + } + return result; +} +function parseUrl(template) { + return { + expand: expand.bind(null, template) + }; +} +function expand(template, context) { + var operators = ["+", "#", ".", "/", ";", "?", "&"]; + template = template.replace( + /\{([^\{\}]+)\}|([^\{\}]+)/g, + function(_, expression, literal3) { + if (expression) { + let operator = ""; + const values = []; + if (operators.indexOf(expression.charAt(0)) !== -1) { + operator = expression.charAt(0); + expression = expression.substr(1); + } + expression.split(/,/g).forEach(function(variable) { + var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); + values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); + }); + if (operator && operator !== "+") { + var separator2 = ","; + if (operator === "?") { + separator2 = "&"; + } else if (operator !== "#") { + separator2 = operator; + } + return (values.length !== 0 ? operator : "") + values.join(separator2); + } else { + return values.join(","); + } + } else { + return encodeReserved(literal3); + } + } + ); + if (template === "/") { + return template; + } else { + return template.replace(/\/$/, ""); + } +} +function parse(options) { + let method = options.method.toUpperCase(); + let url4 = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); + let headers = Object.assign({}, options.headers); + let body; + let parameters = omit2(options, [ + "method", + "baseUrl", + "url", + "headers", + "request", + "mediaType" + ]); + const urlVariableNames = extractUrlVariableNames(url4); + url4 = parseUrl(url4).expand(parameters); + if (!/^http/.test(url4)) { + url4 = options.baseUrl + url4; + } + const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl"); + const remainingParameters = omit2(parameters, omittedParameters); + const isBinaryRequest = /application\/octet-stream/i.test(headers.accept); + if (!isBinaryRequest) { + if (options.mediaType.format) { + headers.accept = headers.accept.split(/,/).map( + (format2) => format2.replace( + /application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, + `application/vnd$1$2.${options.mediaType.format}` + ) + ).join(","); + } + if (url4.endsWith("/graphql")) { + if (options.mediaType.previews?.length) { + const previewsFromAcceptHeader = headers.accept.match(/(? { + const format2 = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; + return `application/vnd.github.${preview}-preview${format2}`; + }).join(","); + } + } + } + if (["GET", "HEAD"].includes(method)) { + url4 = addQueryParameters(url4, remainingParameters); + } else { + if ("data" in remainingParameters) { + body = remainingParameters.data; + } else { + if (Object.keys(remainingParameters).length) { + body = remainingParameters; + } + } + } + if (!headers["content-type"] && typeof body !== "undefined") { + headers["content-type"] = "application/json; charset=utf-8"; + } + if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { + body = ""; + } + return Object.assign( + { method, url: url4, headers }, + typeof body !== "undefined" ? { body } : null, + options.request ? { request: options.request } : null + ); +} +function endpointWithDefaults(defaults, route, options) { + return parse(merge(defaults, route, options)); +} +function withDefaults(oldDefaults, newDefaults) { + const DEFAULTS2 = merge(oldDefaults, newDefaults); + const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2); + return Object.assign(endpoint2, { + DEFAULTS: DEFAULTS2, + defaults: withDefaults.bind(null, DEFAULTS2), + merge: merge.bind(null, DEFAULTS2), + parse + }); +} +var endpoint = withDefaults(null, DEFAULTS); + +// node_modules/.pnpm/@octokit+request@10.0.5/node_modules/@octokit/request/dist-bundle/index.js +var import_fast_content_type_parse = __toESM(require_fast_content_type_parse(), 1); + +// node_modules/.pnpm/@octokit+request-error@7.0.1/node_modules/@octokit/request-error/dist-src/index.js +var RequestError = class extends Error { + name; + /** + * http status code + */ + status; + /** + * Request options that lead to the error. + */ + request; + /** + * Response object if a response was received + */ + response; + constructor(message, statusCode, options) { + super(message); + this.name = "HttpError"; + this.status = Number.parseInt(statusCode); + if (Number.isNaN(this.status)) { + this.status = 0; + } + if ("response" in options) { + this.response = options.response; + } + const requestCopy = Object.assign({}, options.request); + if (options.request.headers.authorization) { + requestCopy.headers = Object.assign({}, options.request.headers, { + authorization: options.request.headers.authorization.replace( + /(? [ + name, + String(value2) + ]) + ); + let fetchResponse; + try { + fetchResponse = await fetch3(requestOptions.url, { + method: requestOptions.method, + body, + redirect: requestOptions.request?.redirect, + headers: requestHeaders, + signal: requestOptions.request?.signal, + // duplex must be set if request.body is ReadableStream or Async Iterables. + // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex. + ...requestOptions.body && { duplex: "half" } + }); + } catch (error49) { + let message = "Unknown Error"; + if (error49 instanceof Error) { + if (error49.name === "AbortError") { + error49.status = 500; + throw error49; + } + message = error49.message; + if (error49.name === "TypeError" && "cause" in error49) { + if (error49.cause instanceof Error) { + message = error49.cause.message; + } else if (typeof error49.cause === "string") { + message = error49.cause; + } + } + } + const requestError = new RequestError(message, 500, { + request: requestOptions + }); + requestError.cause = error49; + throw requestError; + } + const status = fetchResponse.status; + const url4 = fetchResponse.url; + const responseHeaders = {}; + for (const [key, value2] of fetchResponse.headers) { + responseHeaders[key] = value2; + } + const octokitResponse = { + url: url4, + status, + headers: responseHeaders, + data: "" + }; + if ("deprecation" in responseHeaders) { + const matches = responseHeaders.link && responseHeaders.link.match(/<([^<>]+)>; rel="deprecation"/); + const deprecationLink = matches && matches.pop(); + log2.warn( + `[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${responseHeaders.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` + ); + } + if (status === 204 || status === 205) { + return octokitResponse; + } + if (requestOptions.method === "HEAD") { + if (status < 400) { + return octokitResponse; + } + throw new RequestError(fetchResponse.statusText, status, { + response: octokitResponse, + request: requestOptions + }); + } + if (status === 304) { + octokitResponse.data = await getResponseData(fetchResponse); + throw new RequestError("Not modified", status, { + response: octokitResponse, + request: requestOptions + }); + } + if (status >= 400) { + octokitResponse.data = await getResponseData(fetchResponse); + throw new RequestError(toErrorMessage(octokitResponse.data), status, { + response: octokitResponse, + request: requestOptions + }); + } + octokitResponse.data = parseSuccessResponseBody ? await getResponseData(fetchResponse) : fetchResponse.body; + return octokitResponse; +} +async function getResponseData(response) { + const contentType = response.headers.get("content-type"); + if (!contentType) { + return response.text().catch(() => ""); + } + const mimetype = (0, import_fast_content_type_parse.safeParse)(contentType); + if (isJSONResponse(mimetype)) { + let text = ""; + try { + text = await response.text(); + return JSON.parse(text); + } catch (err) { + return text; + } + } else if (mimetype.type.startsWith("text/") || mimetype.parameters.charset?.toLowerCase() === "utf-8") { + return response.text().catch(() => ""); + } else { + return response.arrayBuffer().catch(() => new ArrayBuffer(0)); + } +} +function isJSONResponse(mimetype) { + return mimetype.type === "application/json" || mimetype.type === "application/scim+json"; +} +function toErrorMessage(data) { + if (typeof data === "string") { + return data; + } + if (data instanceof ArrayBuffer) { + return "Unknown error"; + } + if ("message" in data) { + const suffix2 = "documentation_url" in data ? ` - ${data.documentation_url}` : ""; + return Array.isArray(data.errors) ? `${data.message}: ${data.errors.map((v) => JSON.stringify(v)).join(", ")}${suffix2}` : `${data.message}${suffix2}`; + } + return `Unknown error: ${JSON.stringify(data)}`; +} +function withDefaults2(oldEndpoint, newDefaults) { + const endpoint2 = oldEndpoint.defaults(newDefaults); + const newApi = function(route, parameters) { + const endpointOptions = endpoint2.merge(route, parameters); + if (!endpointOptions.request || !endpointOptions.request.hook) { + return fetchWrapper(endpoint2.parse(endpointOptions)); + } + const request2 = (route2, parameters2) => { + return fetchWrapper( + endpoint2.parse(endpoint2.merge(route2, parameters2)) + ); + }; + Object.assign(request2, { + endpoint: endpoint2, + defaults: withDefaults2.bind(null, endpoint2) + }); + return endpointOptions.request.hook(request2, endpointOptions); + }; + return Object.assign(newApi, { + endpoint: endpoint2, + defaults: withDefaults2.bind(null, endpoint2) + }); +} +var request = withDefaults2(endpoint, defaults_default); + +// node_modules/.pnpm/@octokit+graphql@9.0.2/node_modules/@octokit/graphql/dist-bundle/index.js +var VERSION4 = "0.0.0-development"; +function _buildMessageForResponseErrors(data) { + return `Request failed due to following response errors: +` + data.errors.map((e) => ` - ${e.message}`).join("\n"); +} +var GraphqlResponseError = class extends Error { + constructor(request2, headers, response) { + super(_buildMessageForResponseErrors(response)); + this.request = request2; + this.headers = headers; + this.response = response; + this.errors = response.errors; + this.data = response.data; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + } + name = "GraphqlResponseError"; + errors; + data; +}; +var NON_VARIABLE_OPTIONS = [ + "method", + "baseUrl", + "url", + "headers", + "request", + "query", + "mediaType", + "operationName" +]; +var FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"]; +var GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; +function graphql(request2, query, options) { + if (options) { + if (typeof query === "string" && "query" in options) { + return Promise.reject( + new Error(`[@octokit/graphql] "query" cannot be used as variable name`) + ); + } + for (const key in options) { + if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue; + return Promise.reject( + new Error( + `[@octokit/graphql] "${key}" cannot be used as variable name` + ) + ); + } + } + const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query; + const requestOptions = Object.keys( + parsedOptions + ).reduce((result, key) => { + if (NON_VARIABLE_OPTIONS.includes(key)) { + result[key] = parsedOptions[key]; + return result; + } + if (!result.variables) { + result.variables = {}; + } + result.variables[key] = parsedOptions[key]; + return result; + }, {}); + const baseUrl = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl; + if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) { + requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql"); + } + return request2(requestOptions).then((response) => { + if (response.data.errors) { + const headers = {}; + for (const key of Object.keys(response.headers)) { + headers[key] = response.headers[key]; + } + throw new GraphqlResponseError( + requestOptions, + headers, + response.data + ); + } + return response.data.data; + }); +} +function withDefaults3(request2, newDefaults) { + const newRequest = request2.defaults(newDefaults); + const newApi = (query, options) => { + return graphql(newRequest, query, options); + }; + return Object.assign(newApi, { + defaults: withDefaults3.bind(null, newRequest), + endpoint: newRequest.endpoint + }); +} +var graphql2 = withDefaults3(request, { + headers: { + "user-agent": `octokit-graphql.js/${VERSION4} ${getUserAgent()}` + }, + method: "POST", + url: "/graphql" +}); +function withCustomRequest(customRequest) { + return withDefaults3(customRequest, { + method: "POST", + url: "/graphql" + }); +} + +// node_modules/.pnpm/@octokit+auth-token@6.0.0/node_modules/@octokit/auth-token/dist-bundle/index.js +var b64url = "(?:[a-zA-Z0-9_-]+)"; +var sep = "\\."; +var jwtRE = new RegExp(`^${b64url}${sep}${b64url}${sep}${b64url}$`); +var isJWT = jwtRE.test.bind(jwtRE); +async function auth(token) { + const isApp = isJWT(token); + const isInstallation = token.startsWith("v1.") || token.startsWith("ghs_"); + const isUserToServer = token.startsWith("ghu_"); + const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth"; + return { + type: "token", + token, + tokenType + }; +} +function withAuthorizationPrefix(token) { + if (token.split(/\./).length === 3) { + return `bearer ${token}`; + } + return `token ${token}`; +} +async function hook(token, request2, route, parameters) { + const endpoint2 = request2.endpoint.merge( + route, + parameters + ); + endpoint2.headers.authorization = withAuthorizationPrefix(token); + return request2(endpoint2); +} +var createTokenAuth = function createTokenAuth2(token) { + if (!token) { + throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); + } + if (typeof token !== "string") { + throw new Error( + "[@octokit/auth-token] Token passed to createTokenAuth is not a string" + ); + } + token = token.replace(/^(token|bearer) +/i, ""); + return Object.assign(auth.bind(null, token), { + hook: hook.bind(null, token) + }); +}; + +// node_modules/.pnpm/@octokit+core@7.0.5/node_modules/@octokit/core/dist-src/version.js +var VERSION5 = "7.0.5"; + +// node_modules/.pnpm/@octokit+core@7.0.5/node_modules/@octokit/core/dist-src/index.js +var noop2 = () => { +}; +var consoleWarn = console.warn.bind(console); +var consoleError = console.error.bind(console); +function createLogger(logger = {}) { + if (typeof logger.debug !== "function") { + logger.debug = noop2; + } + if (typeof logger.info !== "function") { + logger.info = noop2; + } + if (typeof logger.warn !== "function") { + logger.warn = consoleWarn; + } + if (typeof logger.error !== "function") { + logger.error = consoleError; + } + return logger; +} +var userAgentTrail = `octokit-core.js/${VERSION5} ${getUserAgent()}`; +var Octokit = class { + static VERSION = VERSION5; + static defaults(defaults) { + const OctokitWithDefaults = class extends this { + constructor(...args2) { + const options = args2[0] || {}; + if (typeof defaults === "function") { + super(defaults(options)); + return; + } + super( + Object.assign( + {}, + defaults, + options, + options.userAgent && defaults.userAgent ? { + userAgent: `${options.userAgent} ${defaults.userAgent}` + } : null + ) + ); + } + }; + return OctokitWithDefaults; + } + static plugins = []; + /** + * Attach a plugin (or many) to your Octokit instance. + * + * @example + * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) + */ + static plugin(...newPlugins) { + const currentPlugins = this.plugins; + const NewOctokit = class extends this { + static plugins = currentPlugins.concat( + newPlugins.filter((plugin) => !currentPlugins.includes(plugin)) + ); + }; + return NewOctokit; + } + constructor(options = {}) { + const hook2 = new before_after_hook_default.Collection(); + const requestDefaults = { + baseUrl: request.endpoint.DEFAULTS.baseUrl, + headers: {}, + request: Object.assign({}, options.request, { + // @ts-ignore internal usage only, no need to type + hook: hook2.bind(null, "request") + }), + mediaType: { + previews: [], + format: "" + } + }; + requestDefaults.headers["user-agent"] = options.userAgent ? `${options.userAgent} ${userAgentTrail}` : userAgentTrail; + if (options.baseUrl) { + requestDefaults.baseUrl = options.baseUrl; + } + if (options.previews) { + requestDefaults.mediaType.previews = options.previews; + } + if (options.timeZone) { + requestDefaults.headers["time-zone"] = options.timeZone; + } + this.request = request.defaults(requestDefaults); + this.graphql = withCustomRequest(this.request).defaults(requestDefaults); + this.log = createLogger(options.log); + this.hook = hook2; + if (!options.authStrategy) { + if (!options.auth) { + this.auth = async () => ({ + type: "unauthenticated" + }); + } else { + const auth2 = createTokenAuth(options.auth); + hook2.wrap("request", auth2.hook); + this.auth = auth2; + } + } else { + const { authStrategy, ...otherOptions } = options; + const auth2 = authStrategy( + Object.assign( + { + request: this.request, + log: this.log, + // we pass the current octokit instance as well as its constructor options + // to allow for authentication strategies that return a new octokit instance + // that shares the same internal state as the current one. The original + // requirement for this was the "event-octokit" authentication strategy + // of https://github.com/probot/octokit-auth-probot. + octokit: this, + octokitOptions: otherOptions + }, + options.auth + ) + ); + hook2.wrap("request", auth2.hook); + this.auth = auth2; + } + const classConstructor = this.constructor; + for (let i = 0; i < classConstructor.plugins.length; ++i) { + Object.assign(this, classConstructor.plugins[i](this, options)); + } + } + // assigned during constructor + request; + graphql; + log; + hook; + // TODO: type `octokit.auth` based on passed options.authStrategy + auth; +}; + +// node_modules/.pnpm/@octokit+plugin-request-log@6.0.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-request-log/dist-src/version.js +var VERSION6 = "6.0.0"; + +// node_modules/.pnpm/@octokit+plugin-request-log@6.0.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-request-log/dist-src/index.js +function requestLog(octokit) { + octokit.hook.wrap("request", (request2, options) => { + octokit.log.debug("request", options); + const start = Date.now(); + const requestOptions = octokit.request.endpoint.parse(options); + const path3 = requestOptions.url.replace(options.baseUrl, ""); + return request2(options).then((response) => { + const requestId = response.headers["x-github-request-id"]; + octokit.log.info( + `${requestOptions.method} ${path3} - ${response.status} with id ${requestId} in ${Date.now() - start}ms` + ); + return response; + }).catch((error49) => { + const requestId = error49.response?.headers["x-github-request-id"] || "UNKNOWN"; + octokit.log.error( + `${requestOptions.method} ${path3} - ${error49.status} with id ${requestId} in ${Date.now() - start}ms` + ); + throw error49; + }); + }); +} +requestLog.VERSION = VERSION6; + +// node_modules/.pnpm/@octokit+plugin-paginate-rest@13.2.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-paginate-rest/dist-bundle/index.js +var VERSION7 = "0.0.0-development"; +function normalizePaginatedListResponse(response) { + if (!response.data) { + return { + ...response, + data: [] + }; + } + const responseNeedsNormalization = ("total_count" in response.data || "total_commits" in response.data) && !("url" in response.data); + if (!responseNeedsNormalization) return response; + const incompleteResults = response.data.incomplete_results; + const repositorySelection = response.data.repository_selection; + const totalCount = response.data.total_count; + const totalCommits = response.data.total_commits; + delete response.data.incomplete_results; + delete response.data.repository_selection; + delete response.data.total_count; + delete response.data.total_commits; + const namespaceKey = Object.keys(response.data)[0]; + const data = response.data[namespaceKey]; + response.data = data; + if (typeof incompleteResults !== "undefined") { + response.data.incomplete_results = incompleteResults; + } + if (typeof repositorySelection !== "undefined") { + response.data.repository_selection = repositorySelection; + } + response.data.total_count = totalCount; + response.data.total_commits = totalCommits; + return response; +} +function iterator(octokit, route, parameters) { + const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters); + const requestMethod = typeof route === "function" ? route : octokit.request; + const method = options.method; + const headers = options.headers; + let url4 = options.url; + return { + [Symbol.asyncIterator]: () => ({ + async next() { + if (!url4) return { done: true }; + try { + const response = await requestMethod({ method, url: url4, headers }); + const normalizedResponse = normalizePaginatedListResponse(response); + url4 = ((normalizedResponse.headers.link || "").match( + /<([^<>]+)>;\s*rel="next"/ + ) || [])[1]; + if (!url4 && "total_commits" in normalizedResponse.data) { + const parsedUrl = new URL(normalizedResponse.url); + const params = parsedUrl.searchParams; + const page = parseInt(params.get("page") || "1", 10); + const per_page = parseInt(params.get("per_page") || "250", 10); + if (page * per_page < normalizedResponse.data.total_commits) { + params.set("page", String(page + 1)); + url4 = parsedUrl.toString(); + } + } + return { value: normalizedResponse }; + } catch (error49) { + if (error49.status !== 409) throw error49; + url4 = ""; + return { + value: { + status: 200, + headers: {}, + data: [] + } + }; + } + } + }) + }; +} +function paginate(octokit, route, parameters, mapFn) { + if (typeof parameters === "function") { + mapFn = parameters; + parameters = void 0; + } + return gather( + octokit, + [], + iterator(octokit, route, parameters)[Symbol.asyncIterator](), + mapFn + ); +} +function gather(octokit, results, iterator2, mapFn) { + return iterator2.next().then((result) => { + if (result.done) { + return results; + } + let earlyExit = false; + function done() { + earlyExit = true; + } + results = results.concat( + mapFn ? mapFn(result.value, done) : result.value.data + ); + if (earlyExit) { + return results; + } + return gather(octokit, results, iterator2, mapFn); + }); +} +var composePaginateRest = Object.assign(paginate, { + iterator +}); +function paginateRest(octokit) { + return { + paginate: Object.assign(paginate.bind(null, octokit), { + iterator: iterator.bind(null, octokit) + }) + }; +} +paginateRest.VERSION = VERSION7; + +// node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@16.1.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/version.js +var VERSION8 = "16.1.0"; + +// node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@16.1.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/generated/endpoints.js +var Endpoints = { + actions: { + addCustomLabelsToSelfHostedRunnerForOrg: [ + "POST /orgs/{org}/actions/runners/{runner_id}/labels" + ], + addCustomLabelsToSelfHostedRunnerForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + addRepoAccessToSelfHostedRunnerGroupInOrg: [ + "PUT /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories/{repository_id}" + ], + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" + ], + addSelectedRepoToOrgVariable: [ + "PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" + ], + approveWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve" + ], + cancelWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel" + ], + createEnvironmentVariable: [ + "POST /repos/{owner}/{repo}/environments/{environment_name}/variables" + ], + createHostedRunnerForOrg: ["POST /orgs/{org}/actions/hosted-runners"], + createOrUpdateEnvironmentSecret: [ + "PUT /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}" + ], + createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}" + ], + createOrgVariable: ["POST /orgs/{org}/actions/variables"], + createRegistrationTokenForOrg: [ + "POST /orgs/{org}/actions/runners/registration-token" + ], + createRegistrationTokenForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/registration-token" + ], + createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], + createRemoveTokenForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/remove-token" + ], + createRepoVariable: ["POST /repos/{owner}/{repo}/actions/variables"], + createWorkflowDispatch: [ + "POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches" + ], + deleteActionsCacheById: [ + "DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}" + ], + deleteActionsCacheByKey: [ + "DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}" + ], + deleteArtifact: [ + "DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}" + ], + deleteEnvironmentSecret: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}" + ], + deleteEnvironmentVariable: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}" + ], + deleteHostedRunnerForOrg: [ + "DELETE /orgs/{org}/actions/hosted-runners/{hosted_runner_id}" + ], + deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"], + deleteOrgVariable: ["DELETE /orgs/{org}/actions/variables/{name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}" + ], + deleteRepoVariable: [ + "DELETE /repos/{owner}/{repo}/actions/variables/{name}" + ], + deleteSelfHostedRunnerFromOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}" + ], + deleteSelfHostedRunnerFromRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}" + ], + deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"], + deleteWorkflowRunLogs: [ + "DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs" + ], + disableSelectedRepositoryGithubActionsOrganization: [ + "DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}" + ], + disableWorkflow: [ + "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable" + ], + downloadArtifact: [ + "GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}" + ], + downloadJobLogsForWorkflowRun: [ + "GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs" + ], + downloadWorkflowRunAttemptLogs: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs" + ], + downloadWorkflowRunLogs: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs" + ], + enableSelectedRepositoryGithubActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/repositories/{repository_id}" + ], + enableWorkflow: [ + "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable" + ], + forceCancelWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel" + ], + generateRunnerJitconfigForOrg: [ + "POST /orgs/{org}/actions/runners/generate-jitconfig" + ], + generateRunnerJitconfigForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig" + ], + getActionsCacheList: ["GET /repos/{owner}/{repo}/actions/caches"], + getActionsCacheUsage: ["GET /repos/{owner}/{repo}/actions/cache/usage"], + getActionsCacheUsageByRepoForOrg: [ + "GET /orgs/{org}/actions/cache/usage-by-repository" + ], + getActionsCacheUsageForOrg: ["GET /orgs/{org}/actions/cache/usage"], + getAllowedActionsOrganization: [ + "GET /orgs/{org}/actions/permissions/selected-actions" + ], + getAllowedActionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/selected-actions" + ], + getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], + getCustomOidcSubClaimForRepo: [ + "GET /repos/{owner}/{repo}/actions/oidc/customization/sub" + ], + getEnvironmentPublicKey: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/public-key" + ], + getEnvironmentSecret: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}" + ], + getEnvironmentVariable: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}" + ], + getGithubActionsDefaultWorkflowPermissionsOrganization: [ + "GET /orgs/{org}/actions/permissions/workflow" + ], + getGithubActionsDefaultWorkflowPermissionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/workflow" + ], + getGithubActionsPermissionsOrganization: [ + "GET /orgs/{org}/actions/permissions" + ], + getGithubActionsPermissionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions" + ], + getHostedRunnerForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/{hosted_runner_id}" + ], + getHostedRunnersGithubOwnedImagesForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/images/github-owned" + ], + getHostedRunnersLimitsForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/limits" + ], + getHostedRunnersMachineSpecsForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/machine-sizes" + ], + getHostedRunnersPartnerImagesForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/images/partner" + ], + getHostedRunnersPlatformsForOrg: [ + "GET /orgs/{org}/actions/hosted-runners/platforms" + ], + getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"], + getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"], + getOrgVariable: ["GET /orgs/{org}/actions/variables/{name}"], + getPendingDeploymentsForRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" + ], + getRepoPermissions: [ + "GET /repos/{owner}/{repo}/actions/permissions", + {}, + { renamed: ["actions", "getGithubActionsPermissionsRepository"] } + ], + getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"], + getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"], + getRepoVariable: ["GET /repos/{owner}/{repo}/actions/variables/{name}"], + getReviewsForRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals" + ], + getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"], + getSelfHostedRunnerForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/{runner_id}" + ], + getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"], + getWorkflowAccessToRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/access" + ], + getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"], + getWorkflowRunAttempt: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}" + ], + getWorkflowRunUsage: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing" + ], + getWorkflowUsage: [ + "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing" + ], + listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"], + listEnvironmentSecrets: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/secrets" + ], + listEnvironmentVariables: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/variables" + ], + listGithubHostedRunnersInGroupForOrg: [ + "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/hosted-runners" + ], + listHostedRunnersForOrg: ["GET /orgs/{org}/actions/hosted-runners"], + listJobsForWorkflowRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs" + ], + listJobsForWorkflowRunAttempt: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs" + ], + listLabelsForSelfHostedRunnerForOrg: [ + "GET /orgs/{org}/actions/runners/{runner_id}/labels" + ], + listLabelsForSelfHostedRunnerForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + listOrgSecrets: ["GET /orgs/{org}/actions/secrets"], + listOrgVariables: ["GET /orgs/{org}/actions/variables"], + listRepoOrganizationSecrets: [ + "GET /repos/{owner}/{repo}/actions/organization-secrets" + ], + listRepoOrganizationVariables: [ + "GET /repos/{owner}/{repo}/actions/organization-variables" + ], + listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"], + listRepoVariables: ["GET /repos/{owner}/{repo}/actions/variables"], + listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"], + listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"], + listRunnerApplicationsForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/downloads" + ], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/actions/secrets/{secret_name}/repositories" + ], + listSelectedReposForOrgVariable: [ + "GET /orgs/{org}/actions/variables/{name}/repositories" + ], + listSelectedRepositoriesEnabledGithubActionsOrganization: [ + "GET /orgs/{org}/actions/permissions/repositories" + ], + listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"], + listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"], + listWorkflowRunArtifacts: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts" + ], + listWorkflowRuns: [ + "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs" + ], + listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"], + reRunJobForWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun" + ], + reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"], + reRunWorkflowFailedJobs: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs" + ], + removeAllCustomLabelsFromSelfHostedRunnerForOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}/labels" + ], + removeAllCustomLabelsFromSelfHostedRunnerForRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + removeCustomLabelFromSelfHostedRunnerForOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}" + ], + removeCustomLabelFromSelfHostedRunnerForRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}" + ], + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" + ], + removeSelectedRepoFromOrgVariable: [ + "DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" + ], + reviewCustomGatesForRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule" + ], + reviewPendingDeploymentsForRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" + ], + setAllowedActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/selected-actions" + ], + setAllowedActionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/selected-actions" + ], + setCustomLabelsForSelfHostedRunnerForOrg: [ + "PUT /orgs/{org}/actions/runners/{runner_id}/labels" + ], + setCustomLabelsForSelfHostedRunnerForRepo: [ + "PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + setCustomOidcSubClaimForRepo: [ + "PUT /repos/{owner}/{repo}/actions/oidc/customization/sub" + ], + setGithubActionsDefaultWorkflowPermissionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/workflow" + ], + setGithubActionsDefaultWorkflowPermissionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/workflow" + ], + setGithubActionsPermissionsOrganization: [ + "PUT /orgs/{org}/actions/permissions" + ], + setGithubActionsPermissionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions" + ], + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories" + ], + setSelectedReposForOrgVariable: [ + "PUT /orgs/{org}/actions/variables/{name}/repositories" + ], + setSelectedRepositoriesEnabledGithubActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/repositories" + ], + setWorkflowAccessToRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/access" + ], + updateEnvironmentVariable: [ + "PATCH /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}" + ], + updateHostedRunnerForOrg: [ + "PATCH /orgs/{org}/actions/hosted-runners/{hosted_runner_id}" + ], + updateOrgVariable: ["PATCH /orgs/{org}/actions/variables/{name}"], + updateRepoVariable: [ + "PATCH /repos/{owner}/{repo}/actions/variables/{name}" + ] + }, + activity: { + checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"], + deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"], + deleteThreadSubscription: [ + "DELETE /notifications/threads/{thread_id}/subscription" + ], + getFeeds: ["GET /feeds"], + getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"], + getThread: ["GET /notifications/threads/{thread_id}"], + getThreadSubscriptionForAuthenticatedUser: [ + "GET /notifications/threads/{thread_id}/subscription" + ], + listEventsForAuthenticatedUser: ["GET /users/{username}/events"], + listNotificationsForAuthenticatedUser: ["GET /notifications"], + listOrgEventsForAuthenticatedUser: [ + "GET /users/{username}/events/orgs/{org}" + ], + listPublicEvents: ["GET /events"], + listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"], + listPublicEventsForUser: ["GET /users/{username}/events/public"], + listPublicOrgEvents: ["GET /orgs/{org}/events"], + listReceivedEventsForUser: ["GET /users/{username}/received_events"], + listReceivedPublicEventsForUser: [ + "GET /users/{username}/received_events/public" + ], + listRepoEvents: ["GET /repos/{owner}/{repo}/events"], + listRepoNotificationsForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/notifications" + ], + listReposStarredByAuthenticatedUser: ["GET /user/starred"], + listReposStarredByUser: ["GET /users/{username}/starred"], + listReposWatchedByUser: ["GET /users/{username}/subscriptions"], + listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"], + listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"], + listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"], + markNotificationsAsRead: ["PUT /notifications"], + markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"], + markThreadAsDone: ["DELETE /notifications/threads/{thread_id}"], + markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"], + setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"], + setThreadSubscription: [ + "PUT /notifications/threads/{thread_id}/subscription" + ], + starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"], + unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"] + }, + apps: { + addRepoToInstallation: [ + "PUT /user/installations/{installation_id}/repositories/{repository_id}", + {}, + { renamed: ["apps", "addRepoToInstallationForAuthenticatedUser"] } + ], + addRepoToInstallationForAuthenticatedUser: [ + "PUT /user/installations/{installation_id}/repositories/{repository_id}" + ], + checkToken: ["POST /applications/{client_id}/token"], + createFromManifest: ["POST /app-manifests/{code}/conversions"], + createInstallationAccessToken: [ + "POST /app/installations/{installation_id}/access_tokens" + ], + deleteAuthorization: ["DELETE /applications/{client_id}/grant"], + deleteInstallation: ["DELETE /app/installations/{installation_id}"], + deleteToken: ["DELETE /applications/{client_id}/token"], + getAuthenticated: ["GET /app"], + getBySlug: ["GET /apps/{app_slug}"], + getInstallation: ["GET /app/installations/{installation_id}"], + getOrgInstallation: ["GET /orgs/{org}/installation"], + getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"], + getSubscriptionPlanForAccount: [ + "GET /marketplace_listing/accounts/{account_id}" + ], + getSubscriptionPlanForAccountStubbed: [ + "GET /marketplace_listing/stubbed/accounts/{account_id}" + ], + getUserInstallation: ["GET /users/{username}/installation"], + getWebhookConfigForApp: ["GET /app/hook/config"], + getWebhookDelivery: ["GET /app/hook/deliveries/{delivery_id}"], + listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"], + listAccountsForPlanStubbed: [ + "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts" + ], + listInstallationReposForAuthenticatedUser: [ + "GET /user/installations/{installation_id}/repositories" + ], + listInstallationRequestsForAuthenticatedApp: [ + "GET /app/installation-requests" + ], + listInstallations: ["GET /app/installations"], + listInstallationsForAuthenticatedUser: ["GET /user/installations"], + listPlans: ["GET /marketplace_listing/plans"], + listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"], + listReposAccessibleToInstallation: ["GET /installation/repositories"], + listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"], + listSubscriptionsForAuthenticatedUserStubbed: [ + "GET /user/marketplace_purchases/stubbed" + ], + listWebhookDeliveries: ["GET /app/hook/deliveries"], + redeliverWebhookDelivery: [ + "POST /app/hook/deliveries/{delivery_id}/attempts" + ], + removeRepoFromInstallation: [ + "DELETE /user/installations/{installation_id}/repositories/{repository_id}", + {}, + { renamed: ["apps", "removeRepoFromInstallationForAuthenticatedUser"] } + ], + removeRepoFromInstallationForAuthenticatedUser: [ + "DELETE /user/installations/{installation_id}/repositories/{repository_id}" + ], + resetToken: ["PATCH /applications/{client_id}/token"], + revokeInstallationAccessToken: ["DELETE /installation/token"], + scopeToken: ["POST /applications/{client_id}/token/scoped"], + suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"], + unsuspendInstallation: [ + "DELETE /app/installations/{installation_id}/suspended" + ], + updateWebhookConfigForApp: ["PATCH /app/hook/config"] + }, + billing: { + getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"], + getGithubActionsBillingUser: [ + "GET /users/{username}/settings/billing/actions" + ], + getGithubBillingUsageReportOrg: [ + "GET /organizations/{org}/settings/billing/usage" + ], + getGithubBillingUsageReportUser: [ + "GET /users/{username}/settings/billing/usage" + ], + getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"], + getGithubPackagesBillingUser: [ + "GET /users/{username}/settings/billing/packages" + ], + getSharedStorageBillingOrg: [ + "GET /orgs/{org}/settings/billing/shared-storage" + ], + getSharedStorageBillingUser: [ + "GET /users/{username}/settings/billing/shared-storage" + ] + }, + campaigns: { + createCampaign: ["POST /orgs/{org}/campaigns"], + deleteCampaign: ["DELETE /orgs/{org}/campaigns/{campaign_number}"], + getCampaignSummary: ["GET /orgs/{org}/campaigns/{campaign_number}"], + listOrgCampaigns: ["GET /orgs/{org}/campaigns"], + updateCampaign: ["PATCH /orgs/{org}/campaigns/{campaign_number}"] + }, + checks: { + create: ["POST /repos/{owner}/{repo}/check-runs"], + createSuite: ["POST /repos/{owner}/{repo}/check-suites"], + get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"], + getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"], + listAnnotations: [ + "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations" + ], + listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"], + listForSuite: [ + "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs" + ], + listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"], + rerequestRun: [ + "POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest" + ], + rerequestSuite: [ + "POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest" + ], + setSuitesPreferences: [ + "PATCH /repos/{owner}/{repo}/check-suites/preferences" + ], + update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"] + }, + codeScanning: { + commitAutofix: [ + "POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix/commits" + ], + createAutofix: [ + "POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix" + ], + createVariantAnalysis: [ + "POST /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses" + ], + deleteAnalysis: [ + "DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}" + ], + deleteCodeqlDatabase: [ + "DELETE /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}" + ], + getAlert: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", + {}, + { renamedParameters: { alert_id: "alert_number" } } + ], + getAnalysis: [ + "GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}" + ], + getAutofix: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix" + ], + getCodeqlDatabase: [ + "GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}" + ], + getDefaultSetup: ["GET /repos/{owner}/{repo}/code-scanning/default-setup"], + getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"], + getVariantAnalysis: [ + "GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}" + ], + getVariantAnalysisRepoTask: [ + "GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}/repos/{repo_owner}/{repo_name}" + ], + listAlertInstances: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances" + ], + listAlertsForOrg: ["GET /orgs/{org}/code-scanning/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"], + listAlertsInstances: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", + {}, + { renamed: ["codeScanning", "listAlertInstances"] } + ], + listCodeqlDatabases: [ + "GET /repos/{owner}/{repo}/code-scanning/codeql/databases" + ], + listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}" + ], + updateDefaultSetup: [ + "PATCH /repos/{owner}/{repo}/code-scanning/default-setup" + ], + uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"] + }, + codeSecurity: { + attachConfiguration: [ + "POST /orgs/{org}/code-security/configurations/{configuration_id}/attach" + ], + attachEnterpriseConfiguration: [ + "POST /enterprises/{enterprise}/code-security/configurations/{configuration_id}/attach" + ], + createConfiguration: ["POST /orgs/{org}/code-security/configurations"], + createConfigurationForEnterprise: [ + "POST /enterprises/{enterprise}/code-security/configurations" + ], + deleteConfiguration: [ + "DELETE /orgs/{org}/code-security/configurations/{configuration_id}" + ], + deleteConfigurationForEnterprise: [ + "DELETE /enterprises/{enterprise}/code-security/configurations/{configuration_id}" + ], + detachConfiguration: [ + "DELETE /orgs/{org}/code-security/configurations/detach" + ], + getConfiguration: [ + "GET /orgs/{org}/code-security/configurations/{configuration_id}" + ], + getConfigurationForRepository: [ + "GET /repos/{owner}/{repo}/code-security-configuration" + ], + getConfigurationsForEnterprise: [ + "GET /enterprises/{enterprise}/code-security/configurations" + ], + getConfigurationsForOrg: ["GET /orgs/{org}/code-security/configurations"], + getDefaultConfigurations: [ + "GET /orgs/{org}/code-security/configurations/defaults" + ], + getDefaultConfigurationsForEnterprise: [ + "GET /enterprises/{enterprise}/code-security/configurations/defaults" + ], + getRepositoriesForConfiguration: [ + "GET /orgs/{org}/code-security/configurations/{configuration_id}/repositories" + ], + getRepositoriesForEnterpriseConfiguration: [ + "GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}/repositories" + ], + getSingleConfigurationForEnterprise: [ + "GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}" + ], + setConfigurationAsDefault: [ + "PUT /orgs/{org}/code-security/configurations/{configuration_id}/defaults" + ], + setConfigurationAsDefaultForEnterprise: [ + "PUT /enterprises/{enterprise}/code-security/configurations/{configuration_id}/defaults" + ], + updateConfiguration: [ + "PATCH /orgs/{org}/code-security/configurations/{configuration_id}" + ], + updateEnterpriseConfiguration: [ + "PATCH /enterprises/{enterprise}/code-security/configurations/{configuration_id}" + ] + }, + codesOfConduct: { + getAllCodesOfConduct: ["GET /codes_of_conduct"], + getConductCode: ["GET /codes_of_conduct/{key}"] + }, + codespaces: { + addRepositoryForSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + checkPermissionsForDevcontainer: [ + "GET /repos/{owner}/{repo}/codespaces/permissions_check" + ], + codespaceMachinesForAuthenticatedUser: [ + "GET /user/codespaces/{codespace_name}/machines" + ], + createForAuthenticatedUser: ["POST /user/codespaces"], + createOrUpdateOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}" + ], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" + ], + createOrUpdateSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}" + ], + createWithPrForAuthenticatedUser: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces" + ], + createWithRepoForAuthenticatedUser: [ + "POST /repos/{owner}/{repo}/codespaces" + ], + deleteForAuthenticatedUser: ["DELETE /user/codespaces/{codespace_name}"], + deleteFromOrganization: [ + "DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}" + ], + deleteOrgSecret: ["DELETE /orgs/{org}/codespaces/secrets/{secret_name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" + ], + deleteSecretForAuthenticatedUser: [ + "DELETE /user/codespaces/secrets/{secret_name}" + ], + exportForAuthenticatedUser: [ + "POST /user/codespaces/{codespace_name}/exports" + ], + getCodespacesForUserInOrg: [ + "GET /orgs/{org}/members/{username}/codespaces" + ], + getExportDetailsForAuthenticatedUser: [ + "GET /user/codespaces/{codespace_name}/exports/{export_id}" + ], + getForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}"], + getOrgPublicKey: ["GET /orgs/{org}/codespaces/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/codespaces/secrets/{secret_name}"], + getPublicKeyForAuthenticatedUser: [ + "GET /user/codespaces/secrets/public-key" + ], + getRepoPublicKey: [ + "GET /repos/{owner}/{repo}/codespaces/secrets/public-key" + ], + getRepoSecret: [ + "GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" + ], + getSecretForAuthenticatedUser: [ + "GET /user/codespaces/secrets/{secret_name}" + ], + listDevcontainersInRepositoryForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/devcontainers" + ], + listForAuthenticatedUser: ["GET /user/codespaces"], + listInOrganization: [ + "GET /orgs/{org}/codespaces", + {}, + { renamedParameters: { org_id: "org" } } + ], + listInRepositoryForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces" + ], + listOrgSecrets: ["GET /orgs/{org}/codespaces/secrets"], + listRepoSecrets: ["GET /repos/{owner}/{repo}/codespaces/secrets"], + listRepositoriesForSecretForAuthenticatedUser: [ + "GET /user/codespaces/secrets/{secret_name}/repositories" + ], + listSecretsForAuthenticatedUser: ["GET /user/codespaces/secrets"], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories" + ], + preFlightWithRepoForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/new" + ], + publishForAuthenticatedUser: [ + "POST /user/codespaces/{codespace_name}/publish" + ], + removeRepositoryForSecretForAuthenticatedUser: [ + "DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + repoMachinesForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/machines" + ], + setRepositoriesForSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}/repositories" + ], + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories" + ], + startForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/start"], + stopForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/stop"], + stopInOrganization: [ + "POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop" + ], + updateForAuthenticatedUser: ["PATCH /user/codespaces/{codespace_name}"] + }, + copilot: { + addCopilotSeatsForTeams: [ + "POST /orgs/{org}/copilot/billing/selected_teams" + ], + addCopilotSeatsForUsers: [ + "POST /orgs/{org}/copilot/billing/selected_users" + ], + cancelCopilotSeatAssignmentForTeams: [ + "DELETE /orgs/{org}/copilot/billing/selected_teams" + ], + cancelCopilotSeatAssignmentForUsers: [ + "DELETE /orgs/{org}/copilot/billing/selected_users" + ], + copilotMetricsForOrganization: ["GET /orgs/{org}/copilot/metrics"], + copilotMetricsForTeam: ["GET /orgs/{org}/team/{team_slug}/copilot/metrics"], + getCopilotOrganizationDetails: ["GET /orgs/{org}/copilot/billing"], + getCopilotSeatDetailsForUser: [ + "GET /orgs/{org}/members/{username}/copilot" + ], + listCopilotSeats: ["GET /orgs/{org}/copilot/billing/seats"] + }, + credentials: { revoke: ["POST /credentials/revoke"] }, + dependabot: { + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" + ], + createOrUpdateOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}" + ], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" + ], + deleteOrgSecret: ["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" + ], + getAlert: ["GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"], + getOrgPublicKey: ["GET /orgs/{org}/dependabot/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/dependabot/secrets/{secret_name}"], + getRepoPublicKey: [ + "GET /repos/{owner}/{repo}/dependabot/secrets/public-key" + ], + getRepoSecret: [ + "GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" + ], + listAlertsForEnterprise: [ + "GET /enterprises/{enterprise}/dependabot/alerts" + ], + listAlertsForOrg: ["GET /orgs/{org}/dependabot/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/dependabot/alerts"], + listOrgSecrets: ["GET /orgs/{org}/dependabot/secrets"], + listRepoSecrets: ["GET /repos/{owner}/{repo}/dependabot/secrets"], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories" + ], + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" + ], + repositoryAccessForOrg: [ + "GET /organizations/{org}/dependabot/repository-access" + ], + setRepositoryAccessDefaultLevel: [ + "PUT /organizations/{org}/dependabot/repository-access/default-level" + ], + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories" + ], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}" + ], + updateRepositoryAccessForOrg: [ + "PATCH /organizations/{org}/dependabot/repository-access" + ] + }, + dependencyGraph: { + createRepositorySnapshot: [ + "POST /repos/{owner}/{repo}/dependency-graph/snapshots" + ], + diffRange: [ + "GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}" + ], + exportSbom: ["GET /repos/{owner}/{repo}/dependency-graph/sbom"] + }, + emojis: { get: ["GET /emojis"] }, + gists: { + checkIsStarred: ["GET /gists/{gist_id}/star"], + create: ["POST /gists"], + createComment: ["POST /gists/{gist_id}/comments"], + delete: ["DELETE /gists/{gist_id}"], + deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"], + fork: ["POST /gists/{gist_id}/forks"], + get: ["GET /gists/{gist_id}"], + getComment: ["GET /gists/{gist_id}/comments/{comment_id}"], + getRevision: ["GET /gists/{gist_id}/{sha}"], + list: ["GET /gists"], + listComments: ["GET /gists/{gist_id}/comments"], + listCommits: ["GET /gists/{gist_id}/commits"], + listForUser: ["GET /users/{username}/gists"], + listForks: ["GET /gists/{gist_id}/forks"], + listPublic: ["GET /gists/public"], + listStarred: ["GET /gists/starred"], + star: ["PUT /gists/{gist_id}/star"], + unstar: ["DELETE /gists/{gist_id}/star"], + update: ["PATCH /gists/{gist_id}"], + updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"] + }, + git: { + createBlob: ["POST /repos/{owner}/{repo}/git/blobs"], + createCommit: ["POST /repos/{owner}/{repo}/git/commits"], + createRef: ["POST /repos/{owner}/{repo}/git/refs"], + createTag: ["POST /repos/{owner}/{repo}/git/tags"], + createTree: ["POST /repos/{owner}/{repo}/git/trees"], + deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"], + getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"], + getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"], + getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"], + getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"], + getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"], + listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"], + updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"] + }, + gitignore: { + getAllTemplates: ["GET /gitignore/templates"], + getTemplate: ["GET /gitignore/templates/{name}"] + }, + hostedCompute: { + createNetworkConfigurationForOrg: [ + "POST /orgs/{org}/settings/network-configurations" + ], + deleteNetworkConfigurationFromOrg: [ + "DELETE /orgs/{org}/settings/network-configurations/{network_configuration_id}" + ], + getNetworkConfigurationForOrg: [ + "GET /orgs/{org}/settings/network-configurations/{network_configuration_id}" + ], + getNetworkSettingsForOrg: [ + "GET /orgs/{org}/settings/network-settings/{network_settings_id}" + ], + listNetworkConfigurationsForOrg: [ + "GET /orgs/{org}/settings/network-configurations" + ], + updateNetworkConfigurationForOrg: [ + "PATCH /orgs/{org}/settings/network-configurations/{network_configuration_id}" + ] + }, + interactions: { + getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"], + getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"], + getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"], + getRestrictionsForYourPublicRepos: [ + "GET /user/interaction-limits", + {}, + { renamed: ["interactions", "getRestrictionsForAuthenticatedUser"] } + ], + removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"], + removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"], + removeRestrictionsForRepo: [ + "DELETE /repos/{owner}/{repo}/interaction-limits" + ], + removeRestrictionsForYourPublicRepos: [ + "DELETE /user/interaction-limits", + {}, + { renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"] } + ], + setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"], + setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"], + setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"], + setRestrictionsForYourPublicRepos: [ + "PUT /user/interaction-limits", + {}, + { renamed: ["interactions", "setRestrictionsForAuthenticatedUser"] } + ] + }, + issues: { + addAssignees: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/assignees" + ], + addBlockedByDependency: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by" + ], + addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"], + addSubIssue: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/sub_issues" + ], + checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"], + checkUserCanBeAssignedToIssue: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}" + ], + create: ["POST /repos/{owner}/{repo}/issues"], + createComment: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/comments" + ], + createLabel: ["POST /repos/{owner}/{repo}/labels"], + createMilestone: ["POST /repos/{owner}/{repo}/milestones"], + deleteComment: [ + "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}" + ], + deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"], + deleteMilestone: [ + "DELETE /repos/{owner}/{repo}/milestones/{milestone_number}" + ], + get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"], + getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"], + getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"], + getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"], + getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"], + getParent: ["GET /repos/{owner}/{repo}/issues/{issue_number}/parent"], + list: ["GET /issues"], + listAssignees: ["GET /repos/{owner}/{repo}/assignees"], + listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"], + listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"], + listDependenciesBlockedBy: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by" + ], + listDependenciesBlocking: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocking" + ], + listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"], + listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"], + listEventsForTimeline: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline" + ], + listForAuthenticatedUser: ["GET /user/issues"], + listForOrg: ["GET /orgs/{org}/issues"], + listForRepo: ["GET /repos/{owner}/{repo}/issues"], + listLabelsForMilestone: [ + "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels" + ], + listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"], + listLabelsOnIssue: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/labels" + ], + listMilestones: ["GET /repos/{owner}/{repo}/milestones"], + listSubIssues: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/sub_issues" + ], + lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"], + removeAllLabels: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels" + ], + removeAssignees: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees" + ], + removeDependencyBlockedBy: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by/{issue_id}" + ], + removeLabel: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}" + ], + removeSubIssue: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/sub_issue" + ], + reprioritizeSubIssue: [ + "PATCH /repos/{owner}/{repo}/issues/{issue_number}/sub_issues/priority" + ], + setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"], + unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"], + update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"], + updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"], + updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"], + updateMilestone: [ + "PATCH /repos/{owner}/{repo}/milestones/{milestone_number}" + ] + }, + licenses: { + get: ["GET /licenses/{license}"], + getAllCommonlyUsed: ["GET /licenses"], + getForRepo: ["GET /repos/{owner}/{repo}/license"] + }, + markdown: { + render: ["POST /markdown"], + renderRaw: [ + "POST /markdown/raw", + { headers: { "content-type": "text/plain; charset=utf-8" } } + ] + }, + meta: { + get: ["GET /meta"], + getAllVersions: ["GET /versions"], + getOctocat: ["GET /octocat"], + getZen: ["GET /zen"], + root: ["GET /"] + }, + migrations: { + deleteArchiveForAuthenticatedUser: [ + "DELETE /user/migrations/{migration_id}/archive" + ], + deleteArchiveForOrg: [ + "DELETE /orgs/{org}/migrations/{migration_id}/archive" + ], + downloadArchiveForOrg: [ + "GET /orgs/{org}/migrations/{migration_id}/archive" + ], + getArchiveForAuthenticatedUser: [ + "GET /user/migrations/{migration_id}/archive" + ], + getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"], + getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"], + listForAuthenticatedUser: ["GET /user/migrations"], + listForOrg: ["GET /orgs/{org}/migrations"], + listReposForAuthenticatedUser: [ + "GET /user/migrations/{migration_id}/repositories" + ], + listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories"], + listReposForUser: [ + "GET /user/migrations/{migration_id}/repositories", + {}, + { renamed: ["migrations", "listReposForAuthenticatedUser"] } + ], + startForAuthenticatedUser: ["POST /user/migrations"], + startForOrg: ["POST /orgs/{org}/migrations"], + unlockRepoForAuthenticatedUser: [ + "DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock" + ], + unlockRepoForOrg: [ + "DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock" + ] + }, + oidc: { + getOidcCustomSubTemplateForOrg: [ + "GET /orgs/{org}/actions/oidc/customization/sub" + ], + updateOidcCustomSubTemplateForOrg: [ + "PUT /orgs/{org}/actions/oidc/customization/sub" + ] + }, + orgs: { + addSecurityManagerTeam: [ + "PUT /orgs/{org}/security-managers/teams/{team_slug}", + {}, + { + deprecated: "octokit.rest.orgs.addSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#add-a-security-manager-team" + } + ], + assignTeamToOrgRole: [ + "PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" + ], + assignUserToOrgRole: [ + "PUT /orgs/{org}/organization-roles/users/{username}/{role_id}" + ], + blockUser: ["PUT /orgs/{org}/blocks/{username}"], + cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"], + checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"], + checkMembershipForUser: ["GET /orgs/{org}/members/{username}"], + checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"], + convertMemberToOutsideCollaborator: [ + "PUT /orgs/{org}/outside_collaborators/{username}" + ], + createArtifactStorageRecord: [ + "POST /orgs/{org}/artifacts/metadata/storage-record" + ], + createInvitation: ["POST /orgs/{org}/invitations"], + createIssueType: ["POST /orgs/{org}/issue-types"], + createOrUpdateCustomProperties: ["PATCH /orgs/{org}/properties/schema"], + createOrUpdateCustomPropertiesValuesForRepos: [ + "PATCH /orgs/{org}/properties/values" + ], + createOrUpdateCustomProperty: [ + "PUT /orgs/{org}/properties/schema/{custom_property_name}" + ], + createWebhook: ["POST /orgs/{org}/hooks"], + delete: ["DELETE /orgs/{org}"], + deleteAttestationsBulk: ["POST /orgs/{org}/attestations/delete-request"], + deleteAttestationsById: [ + "DELETE /orgs/{org}/attestations/{attestation_id}" + ], + deleteAttestationsBySubjectDigest: [ + "DELETE /orgs/{org}/attestations/digest/{subject_digest}" + ], + deleteIssueType: ["DELETE /orgs/{org}/issue-types/{issue_type_id}"], + deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], + get: ["GET /orgs/{org}"], + getAllCustomProperties: ["GET /orgs/{org}/properties/schema"], + getCustomProperty: [ + "GET /orgs/{org}/properties/schema/{custom_property_name}" + ], + getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], + getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], + getOrgRole: ["GET /orgs/{org}/organization-roles/{role_id}"], + getOrgRulesetHistory: ["GET /orgs/{org}/rulesets/{ruleset_id}/history"], + getOrgRulesetVersion: [ + "GET /orgs/{org}/rulesets/{ruleset_id}/history/{version_id}" + ], + getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], + getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"], + getWebhookDelivery: [ + "GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}" + ], + list: ["GET /organizations"], + listAppInstallations: ["GET /orgs/{org}/installations"], + listArtifactStorageRecords: [ + "GET /orgs/{org}/artifacts/{subject_digest}/metadata/storage-records" + ], + listAttestations: ["GET /orgs/{org}/attestations/{subject_digest}"], + listAttestationsBulk: [ + "POST /orgs/{org}/attestations/bulk-list{?per_page,before,after}" + ], + listBlockedUsers: ["GET /orgs/{org}/blocks"], + listCustomPropertiesValuesForRepos: ["GET /orgs/{org}/properties/values"], + listFailedInvitations: ["GET /orgs/{org}/failed_invitations"], + listForAuthenticatedUser: ["GET /user/orgs"], + listForUser: ["GET /users/{username}/orgs"], + listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"], + listIssueTypes: ["GET /orgs/{org}/issue-types"], + listMembers: ["GET /orgs/{org}/members"], + listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"], + listOrgRoleTeams: ["GET /orgs/{org}/organization-roles/{role_id}/teams"], + listOrgRoleUsers: ["GET /orgs/{org}/organization-roles/{role_id}/users"], + listOrgRoles: ["GET /orgs/{org}/organization-roles"], + listOrganizationFineGrainedPermissions: [ + "GET /orgs/{org}/organization-fine-grained-permissions" + ], + listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"], + listPatGrantRepositories: [ + "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories" + ], + listPatGrantRequestRepositories: [ + "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories" + ], + listPatGrantRequests: ["GET /orgs/{org}/personal-access-token-requests"], + listPatGrants: ["GET /orgs/{org}/personal-access-tokens"], + listPendingInvitations: ["GET /orgs/{org}/invitations"], + listPublicMembers: ["GET /orgs/{org}/public_members"], + listSecurityManagerTeams: [ + "GET /orgs/{org}/security-managers", + {}, + { + deprecated: "octokit.rest.orgs.listSecurityManagerTeams() is deprecated, see https://docs.github.com/rest/orgs/security-managers#list-security-manager-teams" + } + ], + listWebhookDeliveries: ["GET /orgs/{org}/hooks/{hook_id}/deliveries"], + listWebhooks: ["GET /orgs/{org}/hooks"], + pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"], + redeliverWebhookDelivery: [ + "POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" + ], + removeCustomProperty: [ + "DELETE /orgs/{org}/properties/schema/{custom_property_name}" + ], + removeMember: ["DELETE /orgs/{org}/members/{username}"], + removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], + removeOutsideCollaborator: [ + "DELETE /orgs/{org}/outside_collaborators/{username}" + ], + removePublicMembershipForAuthenticatedUser: [ + "DELETE /orgs/{org}/public_members/{username}" + ], + removeSecurityManagerTeam: [ + "DELETE /orgs/{org}/security-managers/teams/{team_slug}", + {}, + { + deprecated: "octokit.rest.orgs.removeSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#remove-a-security-manager-team" + } + ], + reviewPatGrantRequest: [ + "POST /orgs/{org}/personal-access-token-requests/{pat_request_id}" + ], + reviewPatGrantRequestsInBulk: [ + "POST /orgs/{org}/personal-access-token-requests" + ], + revokeAllOrgRolesTeam: [ + "DELETE /orgs/{org}/organization-roles/teams/{team_slug}" + ], + revokeAllOrgRolesUser: [ + "DELETE /orgs/{org}/organization-roles/users/{username}" + ], + revokeOrgRoleTeam: [ + "DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" + ], + revokeOrgRoleUser: [ + "DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}" + ], + setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"], + setPublicMembershipForAuthenticatedUser: [ + "PUT /orgs/{org}/public_members/{username}" + ], + unblockUser: ["DELETE /orgs/{org}/blocks/{username}"], + update: ["PATCH /orgs/{org}"], + updateIssueType: ["PUT /orgs/{org}/issue-types/{issue_type_id}"], + updateMembershipForAuthenticatedUser: [ + "PATCH /user/memberships/orgs/{org}" + ], + updatePatAccess: ["POST /orgs/{org}/personal-access-tokens/{pat_id}"], + updatePatAccesses: ["POST /orgs/{org}/personal-access-tokens"], + updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"], + updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"] + }, + packages: { + deletePackageForAuthenticatedUser: [ + "DELETE /user/packages/{package_type}/{package_name}" + ], + deletePackageForOrg: [ + "DELETE /orgs/{org}/packages/{package_type}/{package_name}" + ], + deletePackageForUser: [ + "DELETE /users/{username}/packages/{package_type}/{package_name}" + ], + deletePackageVersionForAuthenticatedUser: [ + "DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + deletePackageVersionForOrg: [ + "DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + deletePackageVersionForUser: [ + "DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getAllPackageVersionsForAPackageOwnedByAnOrg: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", + {}, + { renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"] } + ], + getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions", + {}, + { + renamed: [ + "packages", + "getAllPackageVersionsForPackageOwnedByAuthenticatedUser" + ] + } + ], + getAllPackageVersionsForPackageOwnedByAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions" + ], + getAllPackageVersionsForPackageOwnedByOrg: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions" + ], + getAllPackageVersionsForPackageOwnedByUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}/versions" + ], + getPackageForAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}" + ], + getPackageForOrganization: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}" + ], + getPackageForUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}" + ], + getPackageVersionForAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getPackageVersionForOrganization: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getPackageVersionForUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + listDockerMigrationConflictingPackagesForAuthenticatedUser: [ + "GET /user/docker/conflicts" + ], + listDockerMigrationConflictingPackagesForOrganization: [ + "GET /orgs/{org}/docker/conflicts" + ], + listDockerMigrationConflictingPackagesForUser: [ + "GET /users/{username}/docker/conflicts" + ], + listPackagesForAuthenticatedUser: ["GET /user/packages"], + listPackagesForOrganization: ["GET /orgs/{org}/packages"], + listPackagesForUser: ["GET /users/{username}/packages"], + restorePackageForAuthenticatedUser: [ + "POST /user/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageForOrg: [ + "POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageForUser: [ + "POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageVersionForAuthenticatedUser: [ + "POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ], + restorePackageVersionForOrg: [ + "POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ], + restorePackageVersionForUser: [ + "POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ] + }, + privateRegistries: { + createOrgPrivateRegistry: ["POST /orgs/{org}/private-registries"], + deleteOrgPrivateRegistry: [ + "DELETE /orgs/{org}/private-registries/{secret_name}" + ], + getOrgPrivateRegistry: ["GET /orgs/{org}/private-registries/{secret_name}"], + getOrgPublicKey: ["GET /orgs/{org}/private-registries/public-key"], + listOrgPrivateRegistries: ["GET /orgs/{org}/private-registries"], + updateOrgPrivateRegistry: [ + "PATCH /orgs/{org}/private-registries/{secret_name}" + ] + }, + projects: { + addItemForOrg: ["POST /orgs/{org}/projectsV2/{project_number}/items"], + addItemForUser: ["POST /users/{user_id}/projectsV2/{project_number}/items"], + deleteItemForOrg: [ + "DELETE /orgs/{org}/projectsV2/{project_number}/items/{item_id}" + ], + deleteItemForUser: [ + "DELETE /users/{user_id}/projectsV2/{project_number}/items/{item_id}" + ], + getFieldForOrg: [ + "GET /orgs/{org}/projectsV2/{project_number}/fields/{field_id}" + ], + getFieldForUser: [ + "GET /users/{user_id}/projectsV2/{project_number}/fields/{field_id}" + ], + getForOrg: ["GET /orgs/{org}/projectsV2/{project_number}"], + getForUser: ["GET /users/{user_id}/projectsV2/{project_number}"], + getOrgItem: ["GET /orgs/{org}/projectsV2/{project_number}/items/{item_id}"], + getUserItem: [ + "GET /users/{user_id}/projectsV2/{project_number}/items/{item_id}" + ], + listFieldsForOrg: ["GET /orgs/{org}/projectsV2/{project_number}/fields"], + listFieldsForUser: [ + "GET /users/{user_id}/projectsV2/{project_number}/fields" + ], + listForOrg: ["GET /orgs/{org}/projectsV2"], + listForUser: ["GET /users/{username}/projectsV2"], + listItemsForOrg: ["GET /orgs/{org}/projectsV2/{project_number}/items"], + listItemsForUser: [ + "GET /users/{user_id}/projectsV2/{project_number}/items" + ], + updateItemForOrg: [ + "PATCH /orgs/{org}/projectsV2/{project_number}/items/{item_id}" + ], + updateItemForUser: [ + "PATCH /users/{user_id}/projectsV2/{project_number}/items/{item_id}" + ] + }, + pulls: { + checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"], + create: ["POST /repos/{owner}/{repo}/pulls"], + createReplyForReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies" + ], + createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], + createReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments" + ], + deletePendingReview: [ + "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], + deleteReviewComment: [ + "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}" + ], + dismissReview: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals" + ], + get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"], + getReview: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], + getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"], + list: ["GET /repos/{owner}/{repo}/pulls"], + listCommentsForReview: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments" + ], + listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"], + listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"], + listRequestedReviewers: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + listReviewComments: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments" + ], + listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"], + listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], + merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"], + removeRequestedReviewers: [ + "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + requestReviewers: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + submitReview: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events" + ], + update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"], + updateBranch: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch" + ], + updateReview: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], + updateReviewComment: [ + "PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}" + ] + }, + rateLimit: { get: ["GET /rate_limit"] }, + reactions: { + createForCommitComment: [ + "POST /repos/{owner}/{repo}/comments/{comment_id}/reactions" + ], + createForIssue: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/reactions" + ], + createForIssueComment: [ + "POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" + ], + createForPullRequestReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" + ], + createForRelease: [ + "POST /repos/{owner}/{repo}/releases/{release_id}/reactions" + ], + createForTeamDiscussionCommentInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" + ], + createForTeamDiscussionInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" + ], + deleteForCommitComment: [ + "DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForIssue: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}" + ], + deleteForIssueComment: [ + "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForPullRequestComment: [ + "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForRelease: [ + "DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}" + ], + deleteForTeamDiscussion: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}" + ], + deleteForTeamDiscussionComment: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}" + ], + listForCommitComment: [ + "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions" + ], + listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"], + listForIssueComment: [ + "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" + ], + listForPullRequestReviewComment: [ + "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" + ], + listForRelease: [ + "GET /repos/{owner}/{repo}/releases/{release_id}/reactions" + ], + listForTeamDiscussionCommentInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" + ], + listForTeamDiscussionInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" + ] + }, + repos: { + acceptInvitation: [ + "PATCH /user/repository_invitations/{invitation_id}", + {}, + { renamed: ["repos", "acceptInvitationForAuthenticatedUser"] } + ], + acceptInvitationForAuthenticatedUser: [ + "PATCH /user/repository_invitations/{invitation_id}" + ], + addAppAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], + addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"], + addStatusCheckContexts: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + addTeamAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + addUserAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], + cancelPagesDeployment: [ + "POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel" + ], + checkAutomatedSecurityFixes: [ + "GET /repos/{owner}/{repo}/automated-security-fixes" + ], + checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"], + checkPrivateVulnerabilityReporting: [ + "GET /repos/{owner}/{repo}/private-vulnerability-reporting" + ], + checkVulnerabilityAlerts: [ + "GET /repos/{owner}/{repo}/vulnerability-alerts" + ], + codeownersErrors: ["GET /repos/{owner}/{repo}/codeowners/errors"], + compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"], + compareCommitsWithBasehead: [ + "GET /repos/{owner}/{repo}/compare/{basehead}" + ], + createAttestation: ["POST /repos/{owner}/{repo}/attestations"], + createAutolink: ["POST /repos/{owner}/{repo}/autolinks"], + createCommitComment: [ + "POST /repos/{owner}/{repo}/commits/{commit_sha}/comments" + ], + createCommitSignatureProtection: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], + createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"], + createDeployKey: ["POST /repos/{owner}/{repo}/keys"], + createDeployment: ["POST /repos/{owner}/{repo}/deployments"], + createDeploymentBranchPolicy: [ + "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" + ], + createDeploymentProtectionRule: [ + "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" + ], + createDeploymentStatus: [ + "POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" + ], + createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"], + createForAuthenticatedUser: ["POST /user/repos"], + createFork: ["POST /repos/{owner}/{repo}/forks"], + createInOrg: ["POST /orgs/{org}/repos"], + createOrUpdateCustomPropertiesValues: [ + "PATCH /repos/{owner}/{repo}/properties/values" + ], + createOrUpdateEnvironment: [ + "PUT /repos/{owner}/{repo}/environments/{environment_name}" + ], + createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"], + createOrgRuleset: ["POST /orgs/{org}/rulesets"], + createPagesDeployment: ["POST /repos/{owner}/{repo}/pages/deployments"], + createPagesSite: ["POST /repos/{owner}/{repo}/pages"], + createRelease: ["POST /repos/{owner}/{repo}/releases"], + createRepoRuleset: ["POST /repos/{owner}/{repo}/rulesets"], + createUsingTemplate: [ + "POST /repos/{template_owner}/{template_repo}/generate" + ], + createWebhook: ["POST /repos/{owner}/{repo}/hooks"], + declineInvitation: [ + "DELETE /user/repository_invitations/{invitation_id}", + {}, + { renamed: ["repos", "declineInvitationForAuthenticatedUser"] } + ], + declineInvitationForAuthenticatedUser: [ + "DELETE /user/repository_invitations/{invitation_id}" + ], + delete: ["DELETE /repos/{owner}/{repo}"], + deleteAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" + ], + deleteAdminBranchProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + deleteAnEnvironment: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}" + ], + deleteAutolink: ["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"], + deleteBranchProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection" + ], + deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"], + deleteCommitSignatureProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], + deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"], + deleteDeployment: [ + "DELETE /repos/{owner}/{repo}/deployments/{deployment_id}" + ], + deleteDeploymentBranchPolicy: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], + deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"], + deleteInvitation: [ + "DELETE /repos/{owner}/{repo}/invitations/{invitation_id}" + ], + deleteOrgRuleset: ["DELETE /orgs/{org}/rulesets/{ruleset_id}"], + deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages"], + deletePullRequestReviewProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], + deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"], + deleteReleaseAsset: [ + "DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}" + ], + deleteRepoRuleset: ["DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"], + disableAutomatedSecurityFixes: [ + "DELETE /repos/{owner}/{repo}/automated-security-fixes" + ], + disableDeploymentProtectionRule: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" + ], + disablePrivateVulnerabilityReporting: [ + "DELETE /repos/{owner}/{repo}/private-vulnerability-reporting" + ], + disableVulnerabilityAlerts: [ + "DELETE /repos/{owner}/{repo}/vulnerability-alerts" + ], + downloadArchive: [ + "GET /repos/{owner}/{repo}/zipball/{ref}", + {}, + { renamed: ["repos", "downloadZipballArchive"] } + ], + downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"], + downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"], + enableAutomatedSecurityFixes: [ + "PUT /repos/{owner}/{repo}/automated-security-fixes" + ], + enablePrivateVulnerabilityReporting: [ + "PUT /repos/{owner}/{repo}/private-vulnerability-reporting" + ], + enableVulnerabilityAlerts: [ + "PUT /repos/{owner}/{repo}/vulnerability-alerts" + ], + generateReleaseNotes: [ + "POST /repos/{owner}/{repo}/releases/generate-notes" + ], + get: ["GET /repos/{owner}/{repo}"], + getAccessRestrictions: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" + ], + getAdminBranchProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + getAllDeploymentProtectionRules: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" + ], + getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"], + getAllStatusCheckContexts: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts" + ], + getAllTopics: ["GET /repos/{owner}/{repo}/topics"], + getAppsWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps" + ], + getAutolink: ["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"], + getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"], + getBranchProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection" + ], + getBranchRules: ["GET /repos/{owner}/{repo}/rules/branches/{branch}"], + getClones: ["GET /repos/{owner}/{repo}/traffic/clones"], + getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"], + getCollaboratorPermissionLevel: [ + "GET /repos/{owner}/{repo}/collaborators/{username}/permission" + ], + getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"], + getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"], + getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"], + getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"], + getCommitSignatureProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], + getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"], + getContent: ["GET /repos/{owner}/{repo}/contents/{path}"], + getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"], + getCustomDeploymentProtectionRule: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" + ], + getCustomPropertiesValues: ["GET /repos/{owner}/{repo}/properties/values"], + getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"], + getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"], + getDeploymentBranchPolicy: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], + getDeploymentStatus: [ + "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}" + ], + getEnvironment: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}" + ], + getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], + getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], + getOrgRuleSuite: ["GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}"], + getOrgRuleSuites: ["GET /orgs/{org}/rulesets/rule-suites"], + getOrgRuleset: ["GET /orgs/{org}/rulesets/{ruleset_id}"], + getOrgRulesets: ["GET /orgs/{org}/rulesets"], + getPages: ["GET /repos/{owner}/{repo}/pages"], + getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"], + getPagesDeployment: [ + "GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}" + ], + getPagesHealthCheck: ["GET /repos/{owner}/{repo}/pages/health"], + getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"], + getPullRequestReviewProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], + getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"], + getReadme: ["GET /repos/{owner}/{repo}/readme"], + getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"], + getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"], + getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"], + getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"], + getRepoRuleSuite: [ + "GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}" + ], + getRepoRuleSuites: ["GET /repos/{owner}/{repo}/rulesets/rule-suites"], + getRepoRuleset: ["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + getRepoRulesetHistory: [ + "GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history" + ], + getRepoRulesetVersion: [ + "GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history/{version_id}" + ], + getRepoRulesets: ["GET /repos/{owner}/{repo}/rulesets"], + getStatusChecksProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], + getTeamsWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams" + ], + getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"], + getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"], + getUsersWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users" + ], + getViews: ["GET /repos/{owner}/{repo}/traffic/views"], + getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"], + getWebhookConfigForRepo: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/config" + ], + getWebhookDelivery: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}" + ], + listActivities: ["GET /repos/{owner}/{repo}/activity"], + listAttestations: [ + "GET /repos/{owner}/{repo}/attestations/{subject_digest}" + ], + listAutolinks: ["GET /repos/{owner}/{repo}/autolinks"], + listBranches: ["GET /repos/{owner}/{repo}/branches"], + listBranchesForHeadCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head" + ], + listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"], + listCommentsForCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments" + ], + listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"], + listCommitStatusesForRef: [ + "GET /repos/{owner}/{repo}/commits/{ref}/statuses" + ], + listCommits: ["GET /repos/{owner}/{repo}/commits"], + listContributors: ["GET /repos/{owner}/{repo}/contributors"], + listCustomDeploymentRuleIntegrations: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps" + ], + listDeployKeys: ["GET /repos/{owner}/{repo}/keys"], + listDeploymentBranchPolicies: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" + ], + listDeploymentStatuses: [ + "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" + ], + listDeployments: ["GET /repos/{owner}/{repo}/deployments"], + listForAuthenticatedUser: ["GET /user/repos"], + listForOrg: ["GET /orgs/{org}/repos"], + listForUser: ["GET /users/{username}/repos"], + listForks: ["GET /repos/{owner}/{repo}/forks"], + listInvitations: ["GET /repos/{owner}/{repo}/invitations"], + listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"], + listLanguages: ["GET /repos/{owner}/{repo}/languages"], + listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"], + listPublic: ["GET /repositories"], + listPullRequestsAssociatedWithCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls" + ], + listReleaseAssets: [ + "GET /repos/{owner}/{repo}/releases/{release_id}/assets" + ], + listReleases: ["GET /repos/{owner}/{repo}/releases"], + listTags: ["GET /repos/{owner}/{repo}/tags"], + listTeams: ["GET /repos/{owner}/{repo}/teams"], + listWebhookDeliveries: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries" + ], + listWebhooks: ["GET /repos/{owner}/{repo}/hooks"], + merge: ["POST /repos/{owner}/{repo}/merges"], + mergeUpstream: ["POST /repos/{owner}/{repo}/merge-upstream"], + pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"], + redeliverWebhookDelivery: [ + "POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" + ], + removeAppAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], + removeCollaborator: [ + "DELETE /repos/{owner}/{repo}/collaborators/{username}" + ], + removeStatusCheckContexts: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + removeStatusCheckProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], + removeTeamAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + removeUserAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], + renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"], + replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics"], + requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"], + setAdminBranchProtection: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + setAppAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], + setStatusCheckContexts: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + setTeamAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + setUserAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], + testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"], + transfer: ["POST /repos/{owner}/{repo}/transfer"], + update: ["PATCH /repos/{owner}/{repo}"], + updateBranchProtection: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection" + ], + updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"], + updateDeploymentBranchPolicy: [ + "PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], + updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"], + updateInvitation: [ + "PATCH /repos/{owner}/{repo}/invitations/{invitation_id}" + ], + updateOrgRuleset: ["PUT /orgs/{org}/rulesets/{ruleset_id}"], + updatePullRequestReviewProtection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], + updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"], + updateReleaseAsset: [ + "PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}" + ], + updateRepoRuleset: ["PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + updateStatusCheckPotection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", + {}, + { renamed: ["repos", "updateStatusCheckProtection"] } + ], + updateStatusCheckProtection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], + updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"], + updateWebhookConfigForRepo: [ + "PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config" + ], + uploadReleaseAsset: [ + "POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", + { baseUrl: "https://uploads.github.com" } + ] + }, + search: { + code: ["GET /search/code"], + commits: ["GET /search/commits"], + issuesAndPullRequests: [ + "GET /search/issues", + {}, + { + deprecated: "octokit.rest.search.issuesAndPullRequests() is deprecated, see https://docs.github.com/rest/search/search#search-issues-and-pull-requests" + } + ], + labels: ["GET /search/labels"], + repos: ["GET /search/repositories"], + topics: ["GET /search/topics"], + users: ["GET /search/users"] + }, + secretScanning: { + createPushProtectionBypass: [ + "POST /repos/{owner}/{repo}/secret-scanning/push-protection-bypasses" + ], + getAlert: [ + "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" + ], + getScanHistory: ["GET /repos/{owner}/{repo}/secret-scanning/scan-history"], + listAlertsForEnterprise: [ + "GET /enterprises/{enterprise}/secret-scanning/alerts" + ], + listAlertsForOrg: ["GET /orgs/{org}/secret-scanning/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"], + listLocationsForAlert: [ + "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations" + ], + listOrgPatternConfigs: [ + "GET /orgs/{org}/secret-scanning/pattern-configurations" + ], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" + ], + updateOrgPatternConfigs: [ + "PATCH /orgs/{org}/secret-scanning/pattern-configurations" + ] + }, + securityAdvisories: { + createFork: [ + "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks" + ], + createPrivateVulnerabilityReport: [ + "POST /repos/{owner}/{repo}/security-advisories/reports" + ], + createRepositoryAdvisory: [ + "POST /repos/{owner}/{repo}/security-advisories" + ], + createRepositoryAdvisoryCveRequest: [ + "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve" + ], + getGlobalAdvisory: ["GET /advisories/{ghsa_id}"], + getRepositoryAdvisory: [ + "GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}" + ], + listGlobalAdvisories: ["GET /advisories"], + listOrgRepositoryAdvisories: ["GET /orgs/{org}/security-advisories"], + listRepositoryAdvisories: ["GET /repos/{owner}/{repo}/security-advisories"], + updateRepositoryAdvisory: [ + "PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}" + ] + }, + teams: { + addOrUpdateMembershipForUserInOrg: [ + "PUT /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], + addOrUpdateRepoPermissionsInOrg: [ + "PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], + checkPermissionsForRepoInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], + create: ["POST /orgs/{org}/teams"], + createDiscussionCommentInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" + ], + createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"], + deleteDiscussionCommentInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + deleteDiscussionInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], + deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"], + getByName: ["GET /orgs/{org}/teams/{team_slug}"], + getDiscussionCommentInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + getDiscussionInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], + getMembershipForUserInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], + list: ["GET /orgs/{org}/teams"], + listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"], + listDiscussionCommentsInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" + ], + listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"], + listForAuthenticatedUser: ["GET /user/teams"], + listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"], + listPendingInvitationsInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/invitations" + ], + listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"], + removeMembershipForUserInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], + removeRepoInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], + updateDiscussionCommentInOrg: [ + "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + updateDiscussionInOrg: [ + "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], + updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"] + }, + users: { + addEmailForAuthenticated: [ + "POST /user/emails", + {}, + { renamed: ["users", "addEmailForAuthenticatedUser"] } + ], + addEmailForAuthenticatedUser: ["POST /user/emails"], + addSocialAccountForAuthenticatedUser: ["POST /user/social_accounts"], + block: ["PUT /user/blocks/{username}"], + checkBlocked: ["GET /user/blocks/{username}"], + checkFollowingForUser: ["GET /users/{username}/following/{target_user}"], + checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"], + createGpgKeyForAuthenticated: [ + "POST /user/gpg_keys", + {}, + { renamed: ["users", "createGpgKeyForAuthenticatedUser"] } + ], + createGpgKeyForAuthenticatedUser: ["POST /user/gpg_keys"], + createPublicSshKeyForAuthenticated: [ + "POST /user/keys", + {}, + { renamed: ["users", "createPublicSshKeyForAuthenticatedUser"] } + ], + createPublicSshKeyForAuthenticatedUser: ["POST /user/keys"], + createSshSigningKeyForAuthenticatedUser: ["POST /user/ssh_signing_keys"], + deleteAttestationsBulk: [ + "POST /users/{username}/attestations/delete-request" + ], + deleteAttestationsById: [ + "DELETE /users/{username}/attestations/{attestation_id}" + ], + deleteAttestationsBySubjectDigest: [ + "DELETE /users/{username}/attestations/digest/{subject_digest}" + ], + deleteEmailForAuthenticated: [ + "DELETE /user/emails", + {}, + { renamed: ["users", "deleteEmailForAuthenticatedUser"] } + ], + deleteEmailForAuthenticatedUser: ["DELETE /user/emails"], + deleteGpgKeyForAuthenticated: [ + "DELETE /user/gpg_keys/{gpg_key_id}", + {}, + { renamed: ["users", "deleteGpgKeyForAuthenticatedUser"] } + ], + deleteGpgKeyForAuthenticatedUser: ["DELETE /user/gpg_keys/{gpg_key_id}"], + deletePublicSshKeyForAuthenticated: [ + "DELETE /user/keys/{key_id}", + {}, + { renamed: ["users", "deletePublicSshKeyForAuthenticatedUser"] } + ], + deletePublicSshKeyForAuthenticatedUser: ["DELETE /user/keys/{key_id}"], + deleteSocialAccountForAuthenticatedUser: ["DELETE /user/social_accounts"], + deleteSshSigningKeyForAuthenticatedUser: [ + "DELETE /user/ssh_signing_keys/{ssh_signing_key_id}" + ], + follow: ["PUT /user/following/{username}"], + getAuthenticated: ["GET /user"], + getById: ["GET /user/{account_id}"], + getByUsername: ["GET /users/{username}"], + getContextForUser: ["GET /users/{username}/hovercard"], + getGpgKeyForAuthenticated: [ + "GET /user/gpg_keys/{gpg_key_id}", + {}, + { renamed: ["users", "getGpgKeyForAuthenticatedUser"] } + ], + getGpgKeyForAuthenticatedUser: ["GET /user/gpg_keys/{gpg_key_id}"], + getPublicSshKeyForAuthenticated: [ + "GET /user/keys/{key_id}", + {}, + { renamed: ["users", "getPublicSshKeyForAuthenticatedUser"] } + ], + getPublicSshKeyForAuthenticatedUser: ["GET /user/keys/{key_id}"], + getSshSigningKeyForAuthenticatedUser: [ + "GET /user/ssh_signing_keys/{ssh_signing_key_id}" + ], + list: ["GET /users"], + listAttestations: ["GET /users/{username}/attestations/{subject_digest}"], + listAttestationsBulk: [ + "POST /users/{username}/attestations/bulk-list{?per_page,before,after}" + ], + listBlockedByAuthenticated: [ + "GET /user/blocks", + {}, + { renamed: ["users", "listBlockedByAuthenticatedUser"] } + ], + listBlockedByAuthenticatedUser: ["GET /user/blocks"], + listEmailsForAuthenticated: [ + "GET /user/emails", + {}, + { renamed: ["users", "listEmailsForAuthenticatedUser"] } + ], + listEmailsForAuthenticatedUser: ["GET /user/emails"], + listFollowedByAuthenticated: [ + "GET /user/following", + {}, + { renamed: ["users", "listFollowedByAuthenticatedUser"] } + ], + listFollowedByAuthenticatedUser: ["GET /user/following"], + listFollowersForAuthenticatedUser: ["GET /user/followers"], + listFollowersForUser: ["GET /users/{username}/followers"], + listFollowingForUser: ["GET /users/{username}/following"], + listGpgKeysForAuthenticated: [ + "GET /user/gpg_keys", + {}, + { renamed: ["users", "listGpgKeysForAuthenticatedUser"] } + ], + listGpgKeysForAuthenticatedUser: ["GET /user/gpg_keys"], + listGpgKeysForUser: ["GET /users/{username}/gpg_keys"], + listPublicEmailsForAuthenticated: [ + "GET /user/public_emails", + {}, + { renamed: ["users", "listPublicEmailsForAuthenticatedUser"] } + ], + listPublicEmailsForAuthenticatedUser: ["GET /user/public_emails"], + listPublicKeysForUser: ["GET /users/{username}/keys"], + listPublicSshKeysForAuthenticated: [ + "GET /user/keys", + {}, + { renamed: ["users", "listPublicSshKeysForAuthenticatedUser"] } + ], + listPublicSshKeysForAuthenticatedUser: ["GET /user/keys"], + listSocialAccountsForAuthenticatedUser: ["GET /user/social_accounts"], + listSocialAccountsForUser: ["GET /users/{username}/social_accounts"], + listSshSigningKeysForAuthenticatedUser: ["GET /user/ssh_signing_keys"], + listSshSigningKeysForUser: ["GET /users/{username}/ssh_signing_keys"], + setPrimaryEmailVisibilityForAuthenticated: [ + "PATCH /user/email/visibility", + {}, + { renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"] } + ], + setPrimaryEmailVisibilityForAuthenticatedUser: [ + "PATCH /user/email/visibility" + ], + unblock: ["DELETE /user/blocks/{username}"], + unfollow: ["DELETE /user/following/{username}"], + updateAuthenticated: ["PATCH /user"] + } +}; +var endpoints_default = Endpoints; + +// node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@16.1.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/endpoints-to-methods.js +var endpointMethodsMap = /* @__PURE__ */ new Map(); +for (const [scope2, endpoints] of Object.entries(endpoints_default)) { + for (const [methodName, endpoint2] of Object.entries(endpoints)) { + const [route, defaults, decorations] = endpoint2; + const [method, url4] = route.split(/ /); + const endpointDefaults = Object.assign( + { + method, + url: url4 + }, + defaults + ); + if (!endpointMethodsMap.has(scope2)) { + endpointMethodsMap.set(scope2, /* @__PURE__ */ new Map()); + } + endpointMethodsMap.get(scope2).set(methodName, { + scope: scope2, + methodName, + endpointDefaults, + decorations + }); + } +} +var handler = { + has({ scope: scope2 }, methodName) { + return endpointMethodsMap.get(scope2).has(methodName); + }, + getOwnPropertyDescriptor(target, methodName) { + return { + value: this.get(target, methodName), + // ensures method is in the cache + configurable: true, + writable: true, + enumerable: true + }; + }, + defineProperty(target, methodName, descriptor) { + Object.defineProperty(target.cache, methodName, descriptor); + return true; + }, + deleteProperty(target, methodName) { + delete target.cache[methodName]; + return true; + }, + ownKeys({ scope: scope2 }) { + return [...endpointMethodsMap.get(scope2).keys()]; + }, + set(target, methodName, value2) { + return target.cache[methodName] = value2; + }, + get({ octokit, scope: scope2, cache }, methodName) { + if (cache[methodName]) { + return cache[methodName]; + } + const method = endpointMethodsMap.get(scope2).get(methodName); + if (!method) { + return void 0; + } + const { endpointDefaults, decorations } = method; + if (decorations) { + cache[methodName] = decorate( + octokit, + scope2, + methodName, + endpointDefaults, + decorations + ); + } else { + cache[methodName] = octokit.request.defaults(endpointDefaults); + } + return cache[methodName]; + } +}; +function endpointsToMethods(octokit) { + const newMethods = {}; + for (const scope2 of endpointMethodsMap.keys()) { + newMethods[scope2] = new Proxy({ octokit, scope: scope2, cache: {} }, handler); + } + return newMethods; +} +function decorate(octokit, scope2, methodName, defaults, decorations) { + const requestWithDefaults = octokit.request.defaults(defaults); + function withDecorations(...args2) { + let options = requestWithDefaults.endpoint.merge(...args2); + if (decorations.mapToData) { + options = Object.assign({}, options, { + data: options[decorations.mapToData], + [decorations.mapToData]: void 0 + }); + return requestWithDefaults(options); + } + if (decorations.renamed) { + const [newScope, newMethodName] = decorations.renamed; + octokit.log.warn( + `octokit.${scope2}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()` + ); + } + if (decorations.deprecated) { + octokit.log.warn(decorations.deprecated); + } + if (decorations.renamedParameters) { + const options2 = requestWithDefaults.endpoint.merge(...args2); + for (const [name, alias] of Object.entries( + decorations.renamedParameters + )) { + if (name in options2) { + octokit.log.warn( + `"${name}" parameter is deprecated for "octokit.${scope2}.${methodName}()". Use "${alias}" instead` + ); + if (!(alias in options2)) { + options2[alias] = options2[name]; + } + delete options2[name]; + } + } + return requestWithDefaults(options2); + } + return requestWithDefaults(...args2); + } + return Object.assign(withDecorations, requestWithDefaults); +} + +// node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@16.1.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/index.js +function restEndpointMethods(octokit) { + const api = endpointsToMethods(octokit); + return { + rest: api + }; +} +restEndpointMethods.VERSION = VERSION8; +function legacyRestEndpointMethods(octokit) { + const api = endpointsToMethods(octokit); + return { + ...api, + rest: api + }; +} +legacyRestEndpointMethods.VERSION = VERSION8; + +// node_modules/.pnpm/@octokit+rest@22.0.0/node_modules/@octokit/rest/dist-src/version.js +var VERSION9 = "22.0.0"; + +// node_modules/.pnpm/@octokit+rest@22.0.0/node_modules/@octokit/rest/dist-src/index.js +var Octokit2 = Octokit.plugin(requestLog, legacyRestEndpointMethods, paginateRest).defaults( + { + userAgent: `octokit-rest.js/${VERSION9}` + } +); + +// utils/retry.ts +var defaultShouldRetry = (error49) => { + if (!(error49 instanceof Error)) return false; + return error49.name === "AbortError" || error49.message.includes("fetch failed") || error49.message.includes("ECONNRESET") || error49.message.includes("ETIMEDOUT"); +}; +async function retry(fn2, options = {}) { + const maxAttempts = options.maxAttempts ?? 3; + const delayMs = options.delayMs ?? 1e3; + const shouldRetry = options.shouldRetry ?? defaultShouldRetry; + const label = options.label ?? "operation"; + let lastError; + for (let attempt = 1; attempt <= maxAttempts; attempt++) { + try { + return await fn2(); + } catch (error49) { + lastError = error49; + if (attempt === maxAttempts || !shouldRetry(error49)) { + throw error49; + } + const delay2 = delayMs * attempt; + log.info(`\xBB ${label} failed (attempt ${attempt}/${maxAttempts}), retrying in ${delay2}ms...`); + await new Promise((resolve2) => setTimeout(resolve2, delay2)); + } + } + throw lastError; +} + +// utils/github.ts +function isObject(value2) { + return typeof value2 === "object" && value2 !== null; +} +function isOIDCAvailable() { + return Boolean( + process.env.ACTIONS_ID_TOKEN_REQUEST_URL && process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN + ); +} +async function acquireTokenViaOIDC(opts) { + const oidcToken = await core2.getIDToken("pullfrog-api"); + const repos = [...opts?.repos ?? []]; + const targetRepo = process.env.GITHUB_REPOSITORY?.split("/")[1]; + if (targetRepo) { + repos.push(targetRepo); + } + const reposParam = repos.length ? `?repos=${repos.join(",")}` : ""; + const timeoutMs = 3e4; + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), timeoutMs); + try { + const tokenResponse = await apiFetch({ + path: `/api/github/installation-token${reposParam}`, + method: "POST", + headers: { + Authorization: `Bearer ${oidcToken}`, + "Content-Type": "application/json" + }, + body: opts?.permissions ? JSON.stringify({ permissions: opts.permissions }) : void 0, + signal: controller.signal + }); + clearTimeout(timeoutId); + if (!tokenResponse.ok) { + throw new Error(`Token exchange failed: ${tokenResponse.status} ${tokenResponse.statusText}`); + } + const tokenData = await tokenResponse.json(); + return tokenData.token; + } catch (error49) { + clearTimeout(timeoutId); + if (error49 instanceof Error && error49.name === "AbortError") { + throw new Error(`Token exchange timed out after ${timeoutMs}ms`); + } + throw error49; + } +} +var base64UrlEncode = (str) => { + return Buffer.from(str).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); +}; +var generateJWT = (appId, privateKey) => { + const now = Math.floor(Date.now() / 1e3); + const payload = { + iat: now - 60, + exp: now + 5 * 60, + iss: appId + }; + const header = { + alg: "RS256", + typ: "JWT" + }; + const encodedHeader = base64UrlEncode(JSON.stringify(header)); + const encodedPayload = base64UrlEncode(JSON.stringify(payload)); + const signaturePart = `${encodedHeader}.${encodedPayload}`; + const signature = createSign("RSA-SHA256").update(signaturePart).sign(privateKey, "base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); + return `${signaturePart}.${signature}`; +}; +var githubRequest = async (path3, options = {}) => { + const { method = "GET", headers = {}, body } = options; + const url4 = `https://api.github.com${path3}`; + const requestHeaders = { + Accept: "application/vnd.github.v3+json", + "User-Agent": "Pullfrog-Installation-Token-Generator/1.0", + ...headers + }; + const response = await fetch(url4, { + method, + headers: requestHeaders, + ...body && { body } + }); + if (!response.ok) { + const errorText = await response.text(); + throw new Error( + `GitHub API request failed: ${response.status} ${response.statusText} +${errorText}` + ); + } + return response.json(); +}; +var checkRepositoryAccess = async (token, repoOwner, repoName) => { + try { + const response = await githubRequest("/installation/repositories", { + headers: { Authorization: `token ${token}` } + }); + return response.repositories.some( + (repo) => repo.owner.login === repoOwner && repo.name === repoName + ); + } catch { + return false; + } +}; +var createInstallationToken = async (jwt2, installationId, permissions) => { + const requestOpts = { + method: "POST", + headers: { Authorization: `Bearer ${jwt2}` } + }; + if (permissions) { + requestOpts.body = JSON.stringify({ permissions }); + } + const response = await githubRequest( + `/app/installations/${installationId}/access_tokens`, + requestOpts + ); + return response.token; +}; +var findInstallationId = async (jwt2, repoOwner, repoName) => { + const installations = await githubRequest("/app/installations", { + headers: { Authorization: `Bearer ${jwt2}` } + }); + for (const installation of installations) { + try { + const tempToken = await createInstallationToken(jwt2, installation.id); + const hasAccess = await checkRepositoryAccess(tempToken, repoOwner, repoName); + if (hasAccess) { + return installation.id; + } + } catch { + } + } + throw new Error( + `No installation found with access to ${repoOwner}/${repoName}. Ensure the GitHub App is installed on the target repository.` + ); +}; +async function acquireTokenViaGitHubApp(opts) { + if (!process.env.GITHUB_APP_ID || !process.env.GITHUB_PRIVATE_KEY) { + throw new Error( + "cannot acquire token via GitHub App: GITHUB_APP_ID and GITHUB_PRIVATE_KEY must be set" + ); + } + const repoContext = parseRepoContext(); + const config3 = { + appId: process.env.GITHUB_APP_ID, + privateKey: process.env.GITHUB_PRIVATE_KEY.replace(/\\n/g, "\n"), + repoOwner: repoContext.owner, + repoName: repoContext.name + }; + const jwt2 = generateJWT(config3.appId, config3.privateKey); + const installationId = await findInstallationId(jwt2, config3.repoOwner, config3.repoName); + return await createInstallationToken(jwt2, installationId, opts?.permissions); +} +async function acquireNewToken(opts) { + if (isOIDCAvailable()) { + return await retry(() => acquireTokenViaOIDC(opts), { + label: "token exchange", + shouldRetry: (error49) => error49 instanceof Error && (error49.name === "AbortError" || error49.message.includes("fetch failed") || error49.message.includes("ECONNRESET") || error49.message.includes("ETIMEDOUT") || error49.message.includes("Token exchange failed")) + }); + } else { + return await acquireTokenViaGitHubApp(opts); + } +} +function parseRepoContext() { + const githubRepo = process.env.GITHUB_REPOSITORY; + if (!githubRepo) { + throw new Error("GITHUB_REPOSITORY environment variable is required"); + } + const [owner, name] = githubRepo.split("/"); + if (!owner || !name) { + throw new Error(`Invalid GITHUB_REPOSITORY format: ${githubRepo}. Expected 'owner/repo'`); + } + return { owner, name }; +} +function emptyResourceUsage() { + return { + requestCount: 0, + rateLimitRemaining: null, + rateLimitResetMs: null + }; +} +var usageByResource = { + core: emptyResourceUsage(), + graphql: emptyResourceUsage() +}; +function getGitHubUsageSummary() { + return { + version: 1, + github: { + core: usageByResource.core, + graphql: usageByResource.graphql + } + }; +} +async function writeGitHubUsageSummaryToFile(path3) { + const summary2 = getGitHubUsageSummary(); + const tmpPath = join(dirname(path3), `.usage-summary-${process.pid}.tmp`); + await writeFile(tmpPath, JSON.stringify(summary2)); + await rename(tmpPath, path3); +} +function createOctokit(token) { + const OctokitWithPlugins = Octokit2.plugin(throttling); + const octokit = new OctokitWithPlugins({ + auth: token, + throttle: { + onRateLimit: (_retryAfter, _options, _octokit, retryCount) => { + return retryCount <= 2; + }, + onSecondaryRateLimit: (_retryAfter, _options, _octokit, retryCount) => { + return retryCount <= 2; + } + } + }); + const onResponse = (response) => { + const resource = response.headers["x-ratelimit-resource"]; + if (!resource) { + return response; + } + usageByResource[resource] ??= emptyResourceUsage(); + const usage = usageByResource[resource]; + usage.requestCount++; + const remaining = response.headers["x-ratelimit-remaining"]; + const reset = response.headers["x-ratelimit-reset"]; + if (remaining !== void 0) { + usage.rateLimitRemaining = Number(remaining); + } + if (reset !== void 0) { + usage.rateLimitResetMs = Number(reset) * 1e3; + } + return response; + }; + octokit.hook.wrap("request", async (request2, options) => { + try { + const response = await request2(options); + onResponse(response); + return response; + } catch (error49) { + if (isObject(error49) && "response" in error49 && isObject(error49.response) && "headers" in error49.response && isObject(error49.response.headers)) { + onResponse(error49.response); + } + throw error49; + } + }); + return octokit; +} + +// node_modules/.pnpm/@toon-format+toon@1.4.0/node_modules/@toon-format/toon/dist/index.mjs +var LIST_ITEM_MARKER = "-"; +var LIST_ITEM_PREFIX = "- "; +var COMMA = ","; +var PIPE = "|"; +var DOT = "."; +var NULL_LITERAL = "null"; +var TRUE_LITERAL = "true"; +var FALSE_LITERAL = "false"; +var BACKSLASH = "\\"; +var DOUBLE_QUOTE = '"'; +var TAB = " "; +var DELIMITERS = { + comma: COMMA, + tab: TAB, + pipe: PIPE +}; +var DEFAULT_DELIMITER = DELIMITERS.comma; +function escapeString(value2) { + return value2.replace(/\\/g, `${BACKSLASH}${BACKSLASH}`).replace(/"/g, `${BACKSLASH}${DOUBLE_QUOTE}`).replace(/\n/g, `${BACKSLASH}n`).replace(/\r/g, `${BACKSLASH}r`).replace(/\t/g, `${BACKSLASH}t`); +} +function isBooleanOrNullLiteral(token) { + return token === TRUE_LITERAL || token === FALSE_LITERAL || token === NULL_LITERAL; +} +function normalizeValue(value2) { + if (value2 === null) return null; + if (typeof value2 === "string" || typeof value2 === "boolean") return value2; + if (typeof value2 === "number") { + if (Object.is(value2, -0)) return 0; + if (!Number.isFinite(value2)) return null; + return value2; + } + if (typeof value2 === "bigint") { + if (value2 >= Number.MIN_SAFE_INTEGER && value2 <= Number.MAX_SAFE_INTEGER) return Number(value2); + return value2.toString(); + } + if (value2 instanceof Date) return value2.toISOString(); + if (Array.isArray(value2)) return value2.map(normalizeValue); + if (value2 instanceof Set) return Array.from(value2).map(normalizeValue); + if (value2 instanceof Map) return Object.fromEntries(Array.from(value2, ([k, v]) => [String(k), normalizeValue(v)])); + if (isPlainObject3(value2)) { + const normalized = {}; + for (const key in value2) if (Object.prototype.hasOwnProperty.call(value2, key)) normalized[key] = normalizeValue(value2[key]); + return normalized; + } + return null; +} +function isJsonPrimitive(value2) { + return value2 === null || typeof value2 === "string" || typeof value2 === "number" || typeof value2 === "boolean"; +} +function isJsonArray(value2) { + return Array.isArray(value2); +} +function isJsonObject(value2) { + return value2 !== null && typeof value2 === "object" && !Array.isArray(value2); +} +function isEmptyObject2(value2) { + return Object.keys(value2).length === 0; +} +function isPlainObject3(value2) { + if (value2 === null || typeof value2 !== "object") return false; + const prototype = Object.getPrototypeOf(value2); + return prototype === null || prototype === Object.prototype; +} +function isArrayOfPrimitives(value2) { + return value2.length === 0 || value2.every((item) => isJsonPrimitive(item)); +} +function isArrayOfArrays(value2) { + return value2.length === 0 || value2.every((item) => isJsonArray(item)); +} +function isArrayOfObjects(value2) { + return value2.length === 0 || value2.every((item) => isJsonObject(item)); +} +function isValidUnquotedKey(key) { + return /^[A-Z_][\w.]*$/i.test(key); +} +function isIdentifierSegment(key) { + return /^[A-Z_]\w*$/i.test(key); +} +function isSafeUnquoted(value2, delimiter = DEFAULT_DELIMITER) { + if (!value2) return false; + if (value2 !== value2.trim()) return false; + if (isBooleanOrNullLiteral(value2) || isNumericLike(value2)) return false; + if (value2.includes(":")) return false; + if (value2.includes('"') || value2.includes("\\")) return false; + if (/[[\]{}]/.test(value2)) return false; + if (/[\n\r\t]/.test(value2)) return false; + if (value2.includes(delimiter)) return false; + if (value2.startsWith(LIST_ITEM_MARKER)) return false; + return true; +} +function isNumericLike(value2) { + return /^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i.test(value2) || /^0\d+$/.test(value2); +} +var QUOTED_KEY_MARKER = Symbol("quotedKey"); +function tryFoldKeyChain(key, value2, siblings, options, rootLiteralKeys, pathPrefix, flattenDepth) { + if (options.keyFolding !== "safe") return; + if (!isJsonObject(value2)) return; + const { segments, tail, leafValue } = collectSingleKeyChain(key, value2, flattenDepth ?? options.flattenDepth); + if (segments.length < 2) return; + if (!segments.every((seg) => isIdentifierSegment(seg))) return; + const foldedKey = buildFoldedKey(segments); + const absolutePath = pathPrefix ? `${pathPrefix}${DOT}${foldedKey}` : foldedKey; + if (siblings.includes(foldedKey)) return; + if (rootLiteralKeys && rootLiteralKeys.has(absolutePath)) return; + return { + foldedKey, + remainder: tail, + leafValue, + segmentCount: segments.length + }; +} +function collectSingleKeyChain(startKey, startValue, maxDepth) { + const segments = [startKey]; + let currentValue = startValue; + while (segments.length < maxDepth) { + if (!isJsonObject(currentValue)) break; + const keys = Object.keys(currentValue); + if (keys.length !== 1) break; + const nextKey = keys[0]; + const nextValue = currentValue[nextKey]; + segments.push(nextKey); + currentValue = nextValue; + } + if (!isJsonObject(currentValue) || isEmptyObject2(currentValue)) return { + segments, + tail: void 0, + leafValue: currentValue + }; + return { + segments, + tail: currentValue, + leafValue: currentValue + }; +} +function buildFoldedKey(segments) { + return segments.join(DOT); +} +function encodePrimitive(value2, delimiter) { + if (value2 === null) return NULL_LITERAL; + if (typeof value2 === "boolean") return String(value2); + if (typeof value2 === "number") return String(value2); + return encodeStringLiteral(value2, delimiter); +} +function encodeStringLiteral(value2, delimiter = DEFAULT_DELIMITER) { + if (isSafeUnquoted(value2, delimiter)) return value2; + return `${DOUBLE_QUOTE}${escapeString(value2)}${DOUBLE_QUOTE}`; +} +function encodeKey(key) { + if (isValidUnquotedKey(key)) return key; + return `${DOUBLE_QUOTE}${escapeString(key)}${DOUBLE_QUOTE}`; +} +function encodeAndJoinPrimitives(values, delimiter = DEFAULT_DELIMITER) { + return values.map((v) => encodePrimitive(v, delimiter)).join(delimiter); +} +function formatHeader(length, options) { + const key = options?.key; + const fields = options?.fields; + const delimiter = options?.delimiter ?? COMMA; + let header = ""; + if (key) header += encodeKey(key); + header += `[${length}${delimiter !== DEFAULT_DELIMITER ? delimiter : ""}]`; + if (fields) { + const quotedFields = fields.map((f) => encodeKey(f)); + header += `{${quotedFields.join(delimiter)}}`; + } + header += ":"; + return header; +} +function* encodeJsonValue(value2, options, depth) { + if (isJsonPrimitive(value2)) { + const encodedPrimitive = encodePrimitive(value2, options.delimiter); + if (encodedPrimitive !== "") yield encodedPrimitive; + return; + } + if (isJsonArray(value2)) yield* encodeArrayLines(void 0, value2, depth, options); + else if (isJsonObject(value2)) yield* encodeObjectLines(value2, depth, options); +} +function* encodeObjectLines(value2, depth, options, rootLiteralKeys, pathPrefix, remainingDepth) { + const keys = Object.keys(value2); + if (depth === 0 && !rootLiteralKeys) rootLiteralKeys = new Set(keys.filter((k) => k.includes("."))); + const effectiveFlattenDepth = remainingDepth ?? options.flattenDepth; + for (const [key, val] of Object.entries(value2)) yield* encodeKeyValuePairLines(key, val, depth, options, keys, rootLiteralKeys, pathPrefix, effectiveFlattenDepth); +} +function* encodeKeyValuePairLines(key, value2, depth, options, siblings, rootLiteralKeys, pathPrefix, flattenDepth) { + const currentPath = pathPrefix ? `${pathPrefix}${DOT}${key}` : key; + const effectiveFlattenDepth = flattenDepth ?? options.flattenDepth; + if (options.keyFolding === "safe" && siblings) { + const foldResult = tryFoldKeyChain(key, value2, siblings, options, rootLiteralKeys, pathPrefix, effectiveFlattenDepth); + if (foldResult) { + const { foldedKey, remainder, leafValue, segmentCount } = foldResult; + const encodedFoldedKey = encodeKey(foldedKey); + if (remainder === void 0) { + if (isJsonPrimitive(leafValue)) { + yield indentedLine(depth, `${encodedFoldedKey}: ${encodePrimitive(leafValue, options.delimiter)}`, options.indent); + return; + } else if (isJsonArray(leafValue)) { + yield* encodeArrayLines(foldedKey, leafValue, depth, options); + return; + } else if (isJsonObject(leafValue) && isEmptyObject2(leafValue)) { + yield indentedLine(depth, `${encodedFoldedKey}:`, options.indent); + return; + } + } + if (isJsonObject(remainder)) { + yield indentedLine(depth, `${encodedFoldedKey}:`, options.indent); + const remainingDepth = effectiveFlattenDepth - segmentCount; + const foldedPath = pathPrefix ? `${pathPrefix}${DOT}${foldedKey}` : foldedKey; + yield* encodeObjectLines(remainder, depth + 1, options, rootLiteralKeys, foldedPath, remainingDepth); + return; + } + } + } + const encodedKey = encodeKey(key); + if (isJsonPrimitive(value2)) yield indentedLine(depth, `${encodedKey}: ${encodePrimitive(value2, options.delimiter)}`, options.indent); + else if (isJsonArray(value2)) yield* encodeArrayLines(key, value2, depth, options); + else if (isJsonObject(value2)) { + yield indentedLine(depth, `${encodedKey}:`, options.indent); + if (!isEmptyObject2(value2)) yield* encodeObjectLines(value2, depth + 1, options, rootLiteralKeys, currentPath, effectiveFlattenDepth); + } +} +function* encodeArrayLines(key, value2, depth, options) { + if (value2.length === 0) { + yield indentedLine(depth, formatHeader(0, { + key, + delimiter: options.delimiter + }), options.indent); + return; + } + if (isArrayOfPrimitives(value2)) { + yield indentedLine(depth, encodeInlineArrayLine(value2, options.delimiter, key), options.indent); + return; + } + if (isArrayOfArrays(value2)) { + if (value2.every((arr) => isArrayOfPrimitives(arr))) { + yield* encodeArrayOfArraysAsListItemsLines(key, value2, depth, options); + return; + } + } + if (isArrayOfObjects(value2)) { + const header = extractTabularHeader(value2); + if (header) yield* encodeArrayOfObjectsAsTabularLines(key, value2, header, depth, options); + else yield* encodeMixedArrayAsListItemsLines(key, value2, depth, options); + return; + } + yield* encodeMixedArrayAsListItemsLines(key, value2, depth, options); +} +function* encodeArrayOfArraysAsListItemsLines(prefix, values, depth, options) { + yield indentedLine(depth, formatHeader(values.length, { + key: prefix, + delimiter: options.delimiter + }), options.indent); + for (const arr of values) if (isArrayOfPrimitives(arr)) { + const arrayLine = encodeInlineArrayLine(arr, options.delimiter); + yield indentedListItem(depth + 1, arrayLine, options.indent); + } +} +function encodeInlineArrayLine(values, delimiter, prefix) { + const header = formatHeader(values.length, { + key: prefix, + delimiter + }); + const joinedValue = encodeAndJoinPrimitives(values, delimiter); + if (values.length === 0) return header; + return `${header} ${joinedValue}`; +} +function* encodeArrayOfObjectsAsTabularLines(prefix, rows, header, depth, options) { + yield indentedLine(depth, formatHeader(rows.length, { + key: prefix, + fields: header, + delimiter: options.delimiter + }), options.indent); + yield* writeTabularRowsLines(rows, header, depth + 1, options); +} +function extractTabularHeader(rows) { + if (rows.length === 0) return; + const firstRow = rows[0]; + const firstKeys = Object.keys(firstRow); + if (firstKeys.length === 0) return; + if (isTabularArray(rows, firstKeys)) return firstKeys; +} +function isTabularArray(rows, header) { + for (const row of rows) { + if (Object.keys(row).length !== header.length) return false; + for (const key of header) { + if (!(key in row)) return false; + if (!isJsonPrimitive(row[key])) return false; + } + } + return true; +} +function* writeTabularRowsLines(rows, header, depth, options) { + for (const row of rows) yield indentedLine(depth, encodeAndJoinPrimitives(header.map((key) => row[key]), options.delimiter), options.indent); +} +function* encodeMixedArrayAsListItemsLines(prefix, items, depth, options) { + yield indentedLine(depth, formatHeader(items.length, { + key: prefix, + delimiter: options.delimiter + }), options.indent); + for (const item of items) yield* encodeListItemValueLines(item, depth + 1, options); +} +function* encodeObjectAsListItemLines(obj, depth, options) { + if (isEmptyObject2(obj)) { + yield indentedLine(depth, LIST_ITEM_MARKER, options.indent); + return; + } + const entries = Object.entries(obj); + if (entries.length === 1) { + const [key, value2] = entries[0]; + if (isJsonArray(value2) && isArrayOfObjects(value2)) { + const header = extractTabularHeader(value2); + if (header) { + yield indentedListItem(depth, formatHeader(value2.length, { + key, + fields: header, + delimiter: options.delimiter + }), options.indent); + yield* writeTabularRowsLines(value2, header, depth + 1, options); + return; + } + } + } + yield indentedLine(depth, LIST_ITEM_MARKER, options.indent); + yield* encodeObjectLines(obj, depth + 1, options); +} +function* encodeListItemValueLines(value2, depth, options) { + if (isJsonPrimitive(value2)) yield indentedListItem(depth, encodePrimitive(value2, options.delimiter), options.indent); + else if (isJsonArray(value2)) if (isArrayOfPrimitives(value2)) yield indentedListItem(depth, encodeInlineArrayLine(value2, options.delimiter), options.indent); + else { + yield indentedListItem(depth, formatHeader(value2.length, { delimiter: options.delimiter }), options.indent); + for (const item of value2) yield* encodeListItemValueLines(item, depth + 1, options); + } + else if (isJsonObject(value2)) yield* encodeObjectAsListItemLines(value2, depth, options); +} +function indentedLine(depth, content, indentSize) { + return " ".repeat(indentSize * depth) + content; +} +function indentedListItem(depth, content, indentSize) { + return indentedLine(depth, LIST_ITEM_PREFIX + content, indentSize); +} +function encode(input, options) { + return Array.from(encodeLines(input, options)).join("\n"); +} +function encodeLines(input, options) { + return encodeJsonValue(normalizeValue(input), resolveOptions(options), 0); +} +function resolveOptions(options) { + return { + indent: options?.indent ?? 2, + delimiter: options?.delimiter ?? DEFAULT_DELIMITER, + keyFolding: options?.keyFolding ?? "off", + flattenDepth: options?.flattenDepth ?? Number.POSITIVE_INFINITY + }; +} + +// mcp/shared.ts +var tool = (toolDef) => toolDef; +var handleToolSuccess = (data) => { + const text = typeof data === "string" ? data : encode(data); + return { + content: [{ type: "text", text }] + }; +}; +var handleToolError = (error49) => { + const errorMessage = error49 instanceof Error ? error49.message : String(error49); + return { + content: [ + { + type: "text", + text: `Error: ${errorMessage}` + } + ], + isError: true + }; +}; +var execute = (fn2, toolName) => { + const _fn = async (params) => { + try { + const result = await fn2(params); + return handleToolSuccess(result); + } catch (error49) { + const errorMessage = error49 instanceof Error ? error49.message : String(error49); + const prefix = toolName ? `[${toolName}]` : "tool"; + log.info(`${prefix} error: ${errorMessage}`); + log.debug(`${prefix} params: ${formatJsonValue(params)}`); + return handleToolError(error49); + } + }; + return _fn; +}; +var addTools = (_ctx, server, tools) => { + for (const tool2 of tools) { + server.addTool(tool2); + } + return server; +}; + +// mcp/comment.ts +async function updateCommentNodeId(ctx, field, nodeId) { + if (ctx.runId === void 0 || !ctx.apiToken) return; + try { + await retry( + async () => { + const response = await apiFetch({ + path: `/api/workflow-run/${ctx.runId}`, + method: "PATCH", + headers: { + authorization: `Bearer ${ctx.apiToken}`, + "content-type": "application/json" + }, + body: JSON.stringify({ [field]: nodeId }), + signal: AbortSignal.timeout(1e4) + }); + if (!response.ok) throw new Error(`PATCH workflow-run: ${response.status}`); + }, + { + maxAttempts: 3, + delayMs: 2e3, + label: `updateCommentNodeId(${field})` + } + ); + } catch (error49) { + log.warning(`updateCommentNodeId(${field}) exhausted retries: ${error49}`); + } +} +async function buildCommentFooter(params) { + const repoContext = parseRepoContext(); + const runId = process.env.GITHUB_RUN_ID ? Number.parseInt(process.env.GITHUB_RUN_ID, 10) : void 0; + let jobId; + if (runId && params.octokit) { + try { + const { data: jobs } = await params.octokit.rest.actions.listJobsForWorkflowRun({ + owner: repoContext.owner, + repo: repoContext.name, + run_id: runId + }); + jobId = jobs.jobs[0]?.id.toString(); + } catch { + } + } + return buildPullfrogFooter({ + triggeredBy: true, + workflowRun: runId ? { owner: repoContext.owner, repo: repoContext.name, runId, jobId } : void 0, + customParts: params.customParts, + model: params.model + }); +} +function buildImplementPlanLink(owner, repo, issueNumber, commentId) { + const apiUrl = getApiUrl(); + return `[Implement plan \u2794](${apiUrl}/trigger/${owner}/${repo}/${issueNumber}?action=implement&comment_id=${commentId})`; +} +async function addFooter(ctx, body) { + if (/[ \t]*\n(?!\s*\n)/i.test(body)) { + throw new Error( + "body contains
followed by a non-blank line, which breaks GitHub markdown rendering. always add a blank line after
tags." + ); + } + const bodyWithoutFooter = stripExistingFooter(fixDoubleEscapedString(body)); + const footer = await buildCommentFooter({ octokit: ctx.octokit, model: ctx.toolState?.model }); + return `${bodyWithoutFooter}${footer}`; +} +var Comment = type({ + issueNumber: type.number.describe("the issue number to comment on"), + body: type.string.describe("the comment body content"), + type: type.enumerated("Plan", "Summary", "Comment").describe( + "Plan: record as the plan for this run. Summary: record as the PR summary comment (one per PR, updated in place). Comment: regular comment (default)." + ).optional() +}); +function CreateCommentTool(ctx) { + return tool({ + name: "create_issue_comment", + description: "Create a comment on a GitHub issue or PR. For progress/plan updates on the current run use report_progress instead. Use type: 'Plan' for plan comments, type: 'Summary' for PR summary comments.", + parameters: Comment, + execute: execute(async ({ issueNumber, body, type: commentType }) => { + const bodyWithFooter = await addFooter(ctx, body); + if (commentType === "Summary" && ctx.toolState.existingSummaryCommentId) { + log.info( + `\xBB redirecting create_issue_comment(Summary) to update existing comment ${ctx.toolState.existingSummaryCommentId}` + ); + const result2 = await ctx.octokit.rest.issues.updateComment({ + owner: ctx.repo.owner, + repo: ctx.repo.name, + comment_id: ctx.toolState.existingSummaryCommentId, + body: bodyWithFooter + }); + if (result2.data.node_id) { + await updateCommentNodeId(ctx, "summaryCommentNodeId", result2.data.node_id); + } + return { + success: true, + commentId: result2.data.id, + url: result2.data.html_url, + body: result2.data.body + }; + } + const result = await ctx.octokit.rest.issues.createComment({ + owner: ctx.repo.owner, + repo: ctx.repo.name, + issue_number: issueNumber, + body: bodyWithFooter + }); + if (commentType === "Plan" && result.data.node_id) { + await updateCommentNodeId(ctx, "planCommentNodeId", result.data.node_id); + } + if (commentType === "Summary" && result.data.node_id) { + await updateCommentNodeId(ctx, "summaryCommentNodeId", result.data.node_id); + } + return { + success: true, + commentId: result.data.id, + url: result.data.html_url, + body: result.data.body + }; + }) + }); +} +var EditComment = type({ + commentId: type.number.describe("the ID of the comment to edit"), + body: type.string.describe("the new comment body content") +}); +function EditCommentTool(ctx) { + return tool({ + name: "edit_issue_comment", + description: "Edit a GitHub issue comment by its ID", + parameters: EditComment, + execute: execute(async ({ commentId, body }) => { + const bodyWithFooter = await addFooter(ctx, body); + const result = await ctx.octokit.rest.issues.updateComment({ + owner: ctx.repo.owner, + repo: ctx.repo.name, + comment_id: commentId, + body: bodyWithFooter + }); + return { + success: true, + commentId: result.data.id, + url: result.data.html_url, + body: result.data.body, + updatedAt: result.data.updated_at + }; + }) + }); +} +var ReportProgress = type({ + body: type.string.describe("the progress update content to share"), + "target_plan_comment?": type("boolean").describe( + "when true, update the existing plan comment (from select_mode lookup) instead of the progress comment; use when editing an existing plan" + ) +}); +async function reportProgress(ctx, params) { + const { body, target_plan_comment } = params; + ctx.toolState.lastProgressBody = body; + if (ctx.payload.event.silent) { + return { body, action: "skipped" }; + } + const issueNumber = ctx.payload.event.issue_number ?? ctx.toolState.issueNumber; + const isPlanMode = ctx.toolState.selectedMode === "Plan"; + if (target_plan_comment === true && ctx.toolState.existingPlanCommentId === void 0) { + log.warning("target_plan_comment requested but no existingPlanCommentId in tool state"); + } + if (target_plan_comment === true && ctx.toolState.existingPlanCommentId !== void 0) { + const commentId = ctx.toolState.existingPlanCommentId; + const customParts = isPlanMode && issueNumber !== void 0 ? [buildImplementPlanLink(ctx.repo.owner, ctx.repo.name, issueNumber, commentId)] : void 0; + const bodyWithoutFooter = stripExistingFooter(body); + const footer = await buildCommentFooter({ + octokit: ctx.octokit, + customParts, + model: ctx.toolState.model + }); + const bodyWithFooter = `${bodyWithoutFooter}${footer}`; + const result2 = await ctx.octokit.rest.issues.updateComment({ + owner: ctx.repo.owner, + repo: ctx.repo.name, + comment_id: commentId, + body: bodyWithFooter + }); + ctx.toolState.wasUpdated = true; + if (isPlanMode && result2.data.node_id) { + await updateCommentNodeId(ctx, "planCommentNodeId", result2.data.node_id); + } + return { + commentId: result2.data.id, + url: result2.data.html_url, + body: result2.data.body || "", + action: "updated" + }; + } + const existingCommentId = ctx.toolState.progressCommentId; + if (existingCommentId) { + const customParts = isPlanMode && issueNumber !== void 0 ? [buildImplementPlanLink(ctx.repo.owner, ctx.repo.name, issueNumber, existingCommentId)] : void 0; + const bodyWithoutFooter = stripExistingFooter(body); + const footer = await buildCommentFooter({ + octokit: ctx.octokit, + customParts, + model: ctx.toolState.model + }); + const bodyWithFooter = `${bodyWithoutFooter}${footer}`; + const result2 = await ctx.octokit.rest.issues.updateComment({ + owner: ctx.repo.owner, + repo: ctx.repo.name, + comment_id: existingCommentId, + body: bodyWithFooter + }); + ctx.toolState.wasUpdated = true; + if (isPlanMode && result2.data.node_id) { + await updateCommentNodeId(ctx, "planCommentNodeId", result2.data.node_id); + } + return { + commentId: result2.data.id, + url: result2.data.html_url, + body: result2.data.body || "", + action: "updated" + }; + } + if (existingCommentId === null) { + return { body, action: "skipped" }; + } + if (issueNumber === void 0) { + return { body, action: "skipped" }; + } + const initialBody = await addFooter(ctx, body); + const result = await ctx.octokit.rest.issues.createComment({ + owner: ctx.repo.owner, + repo: ctx.repo.name, + issue_number: issueNumber, + body: initialBody + }); + ctx.toolState.progressCommentId = result.data.id; + ctx.toolState.wasUpdated = true; + if (isPlanMode) { + const customParts = [ + buildImplementPlanLink(ctx.repo.owner, ctx.repo.name, issueNumber, result.data.id) + ]; + const bodyWithoutFooter = stripExistingFooter(body); + const footer = await buildCommentFooter({ + octokit: ctx.octokit, + customParts, + model: ctx.toolState.model + }); + const bodyWithPlanLink = `${bodyWithoutFooter}${footer}`; + const updateResult = await ctx.octokit.rest.issues.updateComment({ + owner: ctx.repo.owner, + repo: ctx.repo.name, + comment_id: result.data.id, + body: bodyWithPlanLink + }); + if (updateResult.data.node_id) { + await updateCommentNodeId(ctx, "planCommentNodeId", updateResult.data.node_id); + } + return { + commentId: updateResult.data.id, + url: updateResult.data.html_url, + body: updateResult.data.body || "", + action: "created" + }; + } + return { + commentId: result.data.id, + url: result.data.html_url, + body: result.data.body || "", + action: "created" + }; +} +function ReportProgressTool(ctx) { + return tool({ + name: "report_progress", + description: "Share progress on the associated GitHub issue/PR. The first call creates a comment; subsequent calls update it in place. You MUST call this at the end of every run with a brief final summary (1-3 sentences). The completed task list is automatically appended in a collapsible section \u2014 do not restate individual steps.", + parameters: ReportProgress, + execute: execute(async (params) => { + let body = params.body; + if (!params.target_plan_comment && ctx.toolState.todoTracker) { + ctx.toolState.todoTracker.cancel(); + await ctx.toolState.todoTracker.settled(); + const collapsible = ctx.toolState.todoTracker.renderCollapsible(); + if (collapsible) { + body = `${body} + +${collapsible}`; + } + } + const reportParams = { body }; + if (params.target_plan_comment !== void 0) { + reportParams.target_plan_comment = params.target_plan_comment; + } + const result = await reportProgress(ctx, reportParams); + if (!params.target_plan_comment) { + ctx.toolState.finalSummaryWritten = true; + } + if (result.action === "skipped") { + return { + success: true, + message: "progress recorded (no GitHub comment created - this may occur for workflow_dispatch events or when there is no associated issue/PR)" + }; + } + return { + success: true, + ...result + }; + }) + }); +} +async function deleteProgressComment(ctx) { + const existingCommentId = ctx.toolState.progressCommentId; + if (!existingCommentId) { + return false; + } + try { + await ctx.octokit.rest.issues.deleteComment({ + owner: ctx.repo.owner, + repo: ctx.repo.name, + comment_id: existingCommentId + }); + } catch (error49) { + if (error49 instanceof Error && error49.message.includes("Not Found")) { + } else { + throw error49; + } + } + ctx.toolState.progressCommentId = null; + return true; +} +var ReplyToReviewComment = type({ + pull_number: type.number.describe("the pull request number"), + comment_id: type.number.describe("the ID of the review comment to reply to"), + body: type.string.describe( + "extremely brief reply (1 sentence max) explaining what was fixed, e.g. 'Fixed by renaming to X' or 'Added null check'" + ) +}); +function ReplyToReviewCommentTool(ctx) { + return tool({ + name: "reply_to_review_comment", + description: "Reply to a PR review comment thread (NOT issue comments \u2014 this only works for inline review comments on PR diffs). Call this for EACH comment you address in AddressReviews mode. Keep replies extremely brief (1 sentence max).", + parameters: ReplyToReviewComment, + execute: execute(async ({ pull_number, comment_id, body }) => { + const bodyWithFooter = await addFooter(ctx, body); + const result = await ctx.octokit.rest.pulls.createReplyForReviewComment({ + owner: ctx.repo.owner, + repo: ctx.repo.name, + pull_number, + comment_id, + body: bodyWithFooter + }); + ctx.toolState.wasUpdated = true; + return { + success: true, + commentId: result.data.id, + url: result.data.html_url, + body: result.data.body, + in_reply_to_id: result.data.in_reply_to_id + }; + }, "reply_to_review_comment") + }); +} + // mcp/arkConfig.ts configure({ toJsonSchema: { @@ -100111,9 +112720,9 @@ function isZ4Schema(s) { const schema2 = s; return !!schema2._zod; } -function safeParse2(schema2, data) { +function safeParse3(schema2, data) { if (isZ4Schema(schema2)) { - const result2 = safeParse(schema2, data); + const result2 = safeParse2(schema2, data); return result2; } const v3Schema = schema2; @@ -100258,7 +112867,7 @@ __export(external_exports3, { _function: () => _function, any: () => any, array: () => array, - base64: () => base642, + base64: () => base643, base64url: () => base64url2, bigint: () => bigint2, boolean: () => boolean2, @@ -100280,9 +112889,9 @@ __export(external_exports3, { describe: () => describe2, discriminatedUnion: () => discriminatedUnion, e164: () => e1642, - email: () => email2, + email: () => email3, emoji: () => emoji2, - encode: () => encode2, + encode: () => encode3, encodeAsync: () => encodeAsync2, endsWith: () => _endsWith, enum: () => _enum2, @@ -100300,7 +112909,7 @@ __export(external_exports3, { gte: () => _gte, guid: () => guid2, hash: () => hash, - hex: () => hex2, + hex: () => hex3, hostname: () => hostname2, httpUrl: () => httpUrl, includes: () => _includes, @@ -100312,7 +112921,7 @@ __export(external_exports3, { ipv4: () => ipv42, ipv6: () => ipv62, iso: () => iso_exports2, - json: () => json, + json: () => json3, jwt: () => jwt, keyof: () => keyof, ksuid: () => ksuid2, @@ -100346,11 +112955,11 @@ __export(external_exports3, { null: () => _null3, nullable: () => nullable, nullish: () => nullish2, - number: () => number2, - object: () => object2, + number: () => number3, + object: () => object3, optional: () => optional, overwrite: () => _overwrite, - parse: () => parse2, + parse: () => parse3, parseAsync: () => parseAsync2, partialRecord: () => partialRecord, pipe: () => pipe, @@ -100370,7 +112979,7 @@ __export(external_exports3, { safeDecodeAsync: () => safeDecodeAsync2, safeEncode: () => safeEncode2, safeEncodeAsync: () => safeEncodeAsync2, - safeParse: () => safeParse3, + safeParse: () => safeParse4, safeParseAsync: () => safeParseAsync2, set: () => set, setErrorMap: () => setErrorMap, @@ -100378,7 +112987,7 @@ __export(external_exports3, { slugify: () => _slugify, startsWith: () => _startsWith, strictObject: () => strictObject, - string: () => string2, + string: () => string3, stringFormat: () => stringFormat, stringbool: () => stringbool, success: () => success, @@ -100397,11 +113006,11 @@ __export(external_exports3, { ulid: () => ulid2, undefined: () => _undefined3, union: () => union, - unknown: () => unknown, + unknown: () => unknown2, uppercase: () => _uppercase, - url: () => url, + url: () => url2, util: () => util_exports, - uuid: () => uuid2, + uuid: () => uuid3, uuidv4: () => uuidv4, uuidv6: () => uuidv6, uuidv7: () => uuidv7, @@ -100487,7 +113096,7 @@ __export(schemas_exports3, { _function: () => _function, any: () => any, array: () => array, - base64: () => base642, + base64: () => base643, base64url: () => base64url2, bigint: () => bigint2, boolean: () => boolean2, @@ -100503,7 +113112,7 @@ __export(schemas_exports3, { describe: () => describe2, discriminatedUnion: () => discriminatedUnion, e164: () => e1642, - email: () => email2, + email: () => email3, emoji: () => emoji2, enum: () => _enum2, exactOptional: () => exactOptional, @@ -100513,7 +113122,7 @@ __export(schemas_exports3, { function: () => _function, guid: () => guid2, hash: () => hash, - hex: () => hex2, + hex: () => hex3, hostname: () => hostname2, httpUrl: () => httpUrl, instanceof: () => _instanceof, @@ -100523,7 +113132,7 @@ __export(schemas_exports3, { intersection: () => intersection, ipv4: () => ipv42, ipv6: () => ipv62, - json: () => json, + json: () => json3, jwt: () => jwt, keyof: () => keyof, ksuid: () => ksuid2, @@ -100542,8 +113151,8 @@ __export(schemas_exports3, { null: () => _null3, nullable: () => nullable, nullish: () => nullish2, - number: () => number2, - object: () => object2, + number: () => number3, + object: () => object3, optional: () => optional, partialRecord: () => partialRecord, pipe: () => pipe, @@ -100555,7 +113164,7 @@ __export(schemas_exports3, { refine: () => refine, set: () => set, strictObject: () => strictObject, - string: () => string2, + string: () => string3, stringFormat: () => stringFormat, stringbool: () => stringbool, success: () => success, @@ -100569,9 +113178,9 @@ __export(schemas_exports3, { ulid: () => ulid2, undefined: () => _undefined3, union: () => union, - unknown: () => unknown, - url: () => url, - uuid: () => uuid2, + unknown: () => unknown2, + url: () => url2, + uuid: () => uuid3, uuidv4: () => uuidv4, uuidv6: () => uuidv6, uuidv7: () => uuidv7, @@ -100708,11 +113317,11 @@ var ZodRealError = $constructor("ZodError", initializer2, { }); // node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/parse.js -var parse2 = /* @__PURE__ */ _parse(ZodRealError); +var parse3 = /* @__PURE__ */ _parse(ZodRealError); var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError); -var safeParse3 = /* @__PURE__ */ _safeParse(ZodRealError); +var safeParse4 = /* @__PURE__ */ _safeParse(ZodRealError); var safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError); -var encode2 = /* @__PURE__ */ _encode(ZodRealError); +var encode3 = /* @__PURE__ */ _encode(ZodRealError); var decode2 = /* @__PURE__ */ _decode(ZodRealError); var encodeAsync2 = /* @__PURE__ */ _encodeAsync(ZodRealError); var decodeAsync2 = /* @__PURE__ */ _decodeAsync(ZodRealError); @@ -100751,12 +113360,12 @@ var ZodType2 = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { reg.add(inst, meta3); return inst; }); - inst.parse = (data, params) => parse2(inst, data, params, { callee: inst.parse }); - inst.safeParse = (data, params) => safeParse3(inst, data, params); + inst.parse = (data, params) => parse3(inst, data, params, { callee: inst.parse }); + inst.safeParse = (data, params) => safeParse4(inst, data, params); inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync }); inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params); inst.spa = inst.safeParseAsync; - inst.encode = (data, params) => encode2(inst, data, params); + inst.encode = (data, params) => encode3(inst, data, params); inst.decode = (data, params) => decode2(inst, data, params); inst.encodeAsync = async (data, params) => encodeAsync2(inst, data, params); inst.decodeAsync = async (data, params) => decodeAsync2(inst, data, params); @@ -100860,7 +113469,7 @@ var ZodString2 = /* @__PURE__ */ $constructor("ZodString", (inst, def) => { inst.time = (params) => inst.check(time2(params)); inst.duration = (params) => inst.check(duration2(params)); }); -function string2(params) { +function string3(params) { return _string(ZodString2, params); } var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => { @@ -100871,7 +113480,7 @@ var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => { $ZodEmail.init(inst, def); ZodStringFormat.init(inst, def); }); -function email2(params) { +function email3(params) { return _email(ZodEmail, params); } var ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => { @@ -100885,7 +113494,7 @@ var ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => { $ZodUUID.init(inst, def); ZodStringFormat.init(inst, def); }); -function uuid2(params) { +function uuid3(params) { return _uuid(ZodUUID, params); } function uuidv4(params) { @@ -100901,7 +113510,7 @@ var ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => { $ZodURL.init(inst, def); ZodStringFormat.init(inst, def); }); -function url(params) { +function url2(params) { return _url(ZodURL, params); } function httpUrl(params) { @@ -100999,7 +113608,7 @@ var ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => { $ZodBase64.init(inst, def); ZodStringFormat.init(inst, def); }); -function base642(params) { +function base643(params) { return _base64(ZodBase64, params); } var ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => { @@ -101033,7 +113642,7 @@ function stringFormat(format2, fnOrRegex, _params = {}) { function hostname2(_params) { return _stringFormat(ZodCustomStringFormat, "hostname", regexes_exports.hostname, _params); } -function hex2(_params) { +function hex3(_params) { return _stringFormat(ZodCustomStringFormat, "hex", regexes_exports.hex, _params); } function hash(alg, params) { @@ -101070,7 +113679,7 @@ var ZodNumber2 = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { inst.isFinite = true; inst.format = bag.format ?? null; }); -function number2(params) { +function number3(params) { return _number(ZodNumber2, params); } var ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => { @@ -101172,7 +113781,7 @@ var ZodUnknown2 = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => { ZodType2.init(inst, def); inst._zod.processJSONSchema = (ctx, json4, params) => unknownProcessor(inst, ctx, json4, params); }); -function unknown() { +function unknown2() { return _unknown(ZodUnknown2); } var ZodNever2 = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => { @@ -101231,8 +113840,8 @@ var ZodObject2 = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => { }); inst.keyof = () => _enum2(Object.keys(inst._zod.def.shape)); inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall }); - inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); - inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); + inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown2() }); + inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown2() }); inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() }); inst.strip = () => inst.clone({ ...inst._zod.def, catchall: void 0 }); inst.extend = (incoming) => { @@ -101247,7 +113856,7 @@ var ZodObject2 = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => { inst.partial = (...args2) => util_exports.partial(ZodOptional2, inst, args2[0]); inst.required = (...args2) => util_exports.required(ZodNonOptional, inst, args2[0]); }); -function object2(shape, params) { +function object3(shape, params) { const def = { type: "object", shape: shape ?? {}, @@ -101267,7 +113876,7 @@ function looseObject(shape, params) { return new ZodObject2({ type: "object", shape, - catchall: unknown(), + catchall: unknown2(), ...util_exports.normalizeParams(params) }); } @@ -101735,8 +114344,8 @@ var ZodFunction2 = /* @__PURE__ */ $constructor("ZodFunction", (inst, def) => { function _function(params) { return new ZodFunction2({ type: "function", - input: Array.isArray(params?.input) ? tuple(params?.input) : params?.input ?? array(unknown()), - output: params?.output ?? unknown() + input: Array.isArray(params?.input) ? tuple(params?.input) : params?.input ?? array(unknown2()), + output: params?.output ?? unknown2() }); } var ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => { @@ -101790,9 +114399,9 @@ var stringbool = (...args2) => _stringbool({ Boolean: ZodBoolean2, String: ZodString2 }, ...args2); -function json(params) { +function json3(params) { const jsonSchema2 = lazy(() => { - return union([string2(params), number2(), boolean2(), _null3(), array(jsonSchema2), record(string2(), jsonSchema2)]); + return union([string3(params), number3(), boolean2(), _null3(), array(jsonSchema2), record(string3(), jsonSchema2)]); }); return jsonSchema2; } @@ -102318,14 +114927,14 @@ __export(coerce_exports2, { bigint: () => bigint3, boolean: () => boolean3, date: () => date4, - number: () => number3, - string: () => string3 + number: () => number4, + string: () => string4 }); init_core2(); -function string3(params) { +function string4(params) { return _coercedString(ZodString2, params); } -function number3(params) { +function number4(params) { return _coercedNumber(ZodNumber2, params); } function boolean3(params) { @@ -102347,24 +114956,24 @@ var SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-06-18", "2025- var RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task"; var JSONRPC_VERSION = "2.0"; var AssertObjectSchema = custom((v) => v !== null && (typeof v === "object" || typeof v === "function")); -var ProgressTokenSchema = union([string2(), number2().int()]); -var CursorSchema = string2(); +var ProgressTokenSchema = union([string3(), number3().int()]); +var CursorSchema = string3(); var TaskCreationParamsSchema = looseObject({ /** * Time in milliseconds to keep task results available after completion. * If null, the task has unlimited lifetime until manually cleaned up. */ - ttl: union([number2(), _null3()]).optional(), + ttl: union([number3(), _null3()]).optional(), /** * Time in milliseconds to wait between task status requests. */ - pollInterval: number2().optional() + pollInterval: number3().optional() }); -var TaskMetadataSchema = object2({ - ttl: number2().optional() +var TaskMetadataSchema = object3({ + ttl: number3().optional() }); -var RelatedTaskMetadataSchema = object2({ - taskId: string2() +var RelatedTaskMetadataSchema = object3({ + taskId: string3() }); var RequestMetaSchema = looseObject({ /** @@ -102376,7 +114985,7 @@ var RequestMetaSchema = looseObject({ */ [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() }); -var BaseRequestParamsSchema = object2({ +var BaseRequestParamsSchema = object3({ /** * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. */ @@ -102394,19 +115003,19 @@ var TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ task: TaskMetadataSchema.optional() }); var isTaskAugmentedRequestParams = (value2) => TaskAugmentedRequestParamsSchema.safeParse(value2).success; -var RequestSchema = object2({ - method: string2(), +var RequestSchema = object3({ + method: string3(), params: BaseRequestParamsSchema.loose().optional() }); -var NotificationsParamsSchema = object2({ +var NotificationsParamsSchema = object3({ /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ _meta: RequestMetaSchema.optional() }); -var NotificationSchema = object2({ - method: string2(), +var NotificationSchema = object3({ + method: string3(), params: NotificationsParamsSchema.loose().optional() }); var ResultSchema = looseObject({ @@ -102416,19 +115025,19 @@ var ResultSchema = looseObject({ */ _meta: RequestMetaSchema.optional() }); -var RequestIdSchema = union([string2(), number2().int()]); -var JSONRPCRequestSchema = object2({ +var RequestIdSchema = union([string3(), number3().int()]); +var JSONRPCRequestSchema = object3({ jsonrpc: literal(JSONRPC_VERSION), id: RequestIdSchema, ...RequestSchema.shape }).strict(); var isJSONRPCRequest = (value2) => JSONRPCRequestSchema.safeParse(value2).success; -var JSONRPCNotificationSchema = object2({ +var JSONRPCNotificationSchema = object3({ jsonrpc: literal(JSONRPC_VERSION), ...NotificationSchema.shape }).strict(); var isJSONRPCNotification = (value2) => JSONRPCNotificationSchema.safeParse(value2).success; -var JSONRPCResultResponseSchema = object2({ +var JSONRPCResultResponseSchema = object3({ jsonrpc: literal(JSONRPC_VERSION), id: RequestIdSchema, result: ResultSchema @@ -102445,22 +115054,22 @@ var ErrorCode; ErrorCode3[ErrorCode3["InternalError"] = -32603] = "InternalError"; ErrorCode3[ErrorCode3["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; })(ErrorCode || (ErrorCode = {})); -var JSONRPCErrorResponseSchema = object2({ +var JSONRPCErrorResponseSchema = object3({ jsonrpc: literal(JSONRPC_VERSION), id: RequestIdSchema.optional(), - error: object2({ + error: object3({ /** * The error type that occurred. */ - code: number2().int(), + code: number3().int(), /** * A short description of the error. The message SHOULD be limited to a concise single sentence. */ - message: string2(), + message: string3(), /** * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). */ - data: unknown().optional() + data: unknown2().optional() }) }).strict(); var isJSONRPCErrorResponse = (value2) => JSONRPCErrorResponseSchema.safeParse(value2).success; @@ -102482,28 +115091,28 @@ var CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ /** * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. */ - reason: string2().optional() + reason: string3().optional() }); var CancelledNotificationSchema = NotificationSchema.extend({ method: literal("notifications/cancelled"), params: CancelledNotificationParamsSchema }); -var IconSchema = object2({ +var IconSchema = object3({ /** * URL or data URI for the icon. */ - src: string2(), + src: string3(), /** * Optional MIME type for the icon. */ - mimeType: string2().optional(), + mimeType: string3().optional(), /** * Optional array of strings that specify sizes at which the icon can be used. * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. * * If not provided, the client should assume that the icon can be used at any size. */ - sizes: array(string2()).optional(), + sizes: array(string3()).optional(), /** * Optional specifier for the theme this icon is designed for. `light` indicates * the icon is designed to be used with a light background, and `dark` indicates @@ -102513,7 +115122,7 @@ var IconSchema = object2({ */ theme: _enum2(["light", "dark"]).optional() }); -var IconsSchema = object2({ +var IconsSchema = object3({ /** * Optional set of sized icons that the client can display in a user interface. * @@ -102527,9 +115136,9 @@ var IconsSchema = object2({ */ icons: array(IconSchema).optional() }); -var BaseMetadataSchema = object2({ +var BaseMetadataSchema = object3({ /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */ - name: string2(), + name: string3(), /** * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, * even by those unfamiliar with domain-specific terminology. @@ -102538,16 +115147,16 @@ var BaseMetadataSchema = object2({ * where `annotations.title` should be given precedence over using `name`, * if present). */ - title: string2().optional() + title: string3().optional() }); var ImplementationSchema = BaseMetadataSchema.extend({ ...BaseMetadataSchema.shape, ...IconsSchema.shape, - version: string2(), + version: string3(), /** * An optional URL of the website for this implementation. */ - websiteUrl: string2().optional(), + websiteUrl: string3().optional(), /** * An optional human-readable description of what this implementation does. * @@ -102555,11 +115164,11 @@ var ImplementationSchema = BaseMetadataSchema.extend({ * and capabilities. For example, a server might describe the types of resources * or tools it provides, while a client might describe its intended use case. */ - description: string2().optional() + description: string3().optional() }); -var FormElicitationCapabilitySchema = intersection(object2({ +var FormElicitationCapabilitySchema = intersection(object3({ applyDefaults: boolean2().optional() -}), record(string2(), unknown())); +}), record(string3(), unknown2())); var ElicitationCapabilitySchema = preprocess((value2) => { if (value2 && typeof value2 === "object" && !Array.isArray(value2)) { if (Object.keys(value2).length === 0) { @@ -102567,10 +115176,10 @@ var ElicitationCapabilitySchema = preprocess((value2) => { } } return value2; -}, intersection(object2({ +}, intersection(object3({ form: FormElicitationCapabilitySchema.optional(), url: AssertObjectSchema.optional() -}), record(string2(), unknown()).optional())); +}), record(string3(), unknown2()).optional())); var ClientTasksCapabilitySchema = looseObject({ /** * Present if the client supports listing tasks. @@ -102619,15 +115228,15 @@ var ServerTasksCapabilitySchema = looseObject({ }).optional() }).optional() }); -var ClientCapabilitiesSchema = object2({ +var ClientCapabilitiesSchema = object3({ /** * Experimental, non-standard capabilities that the client supports. */ - experimental: record(string2(), AssertObjectSchema).optional(), + experimental: record(string3(), AssertObjectSchema).optional(), /** * Present if the client supports sampling from an LLM. */ - sampling: object2({ + sampling: object3({ /** * Present if the client supports context inclusion via includeContext parameter. * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). @@ -102645,7 +115254,7 @@ var ClientCapabilitiesSchema = object2({ /** * Present if the client supports listing roots. */ - roots: object2({ + roots: object3({ /** * Whether the client supports issuing notifications for changes to the roots list. */ @@ -102660,7 +115269,7 @@ var InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ /** * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. */ - protocolVersion: string2(), + protocolVersion: string3(), capabilities: ClientCapabilitiesSchema, clientInfo: ImplementationSchema }); @@ -102668,11 +115277,11 @@ var InitializeRequestSchema = RequestSchema.extend({ method: literal("initialize"), params: InitializeRequestParamsSchema }); -var ServerCapabilitiesSchema = object2({ +var ServerCapabilitiesSchema = object3({ /** * Experimental, non-standard capabilities that the server supports. */ - experimental: record(string2(), AssertObjectSchema).optional(), + experimental: record(string3(), AssertObjectSchema).optional(), /** * Present if the server supports sending log messages to the client. */ @@ -102684,7 +115293,7 @@ var ServerCapabilitiesSchema = object2({ /** * Present if the server offers any prompt templates. */ - prompts: object2({ + prompts: object3({ /** * Whether this server supports issuing notifications for changes to the prompt list. */ @@ -102693,7 +115302,7 @@ var ServerCapabilitiesSchema = object2({ /** * Present if the server offers any resources to read. */ - resources: object2({ + resources: object3({ /** * Whether this server supports clients subscribing to resource updates. */ @@ -102706,7 +115315,7 @@ var ServerCapabilitiesSchema = object2({ /** * Present if the server offers any tools to call. */ - tools: object2({ + tools: object3({ /** * Whether this server supports issuing notifications for changes to the tool list. */ @@ -102721,7 +115330,7 @@ var InitializeResultSchema = ResultSchema.extend({ /** * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. */ - protocolVersion: string2(), + protocolVersion: string3(), capabilities: ServerCapabilitiesSchema, serverInfo: ImplementationSchema, /** @@ -102729,7 +115338,7 @@ var InitializeResultSchema = ResultSchema.extend({ * * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. */ - instructions: string2().optional() + instructions: string3().optional() }); var InitializedNotificationSchema = NotificationSchema.extend({ method: literal("notifications/initialized"), @@ -102739,21 +115348,21 @@ var PingRequestSchema = RequestSchema.extend({ method: literal("ping"), params: BaseRequestParamsSchema.optional() }); -var ProgressSchema = object2({ +var ProgressSchema = object3({ /** * The progress thus far. This should increase every time progress is made, even if the total is unknown. */ - progress: number2(), + progress: number3(), /** * Total number of items to process (or total progress required), if known. */ - total: optional(number2()), + total: optional(number3()), /** * An optional message describing the current progress. */ - message: optional(string2()) + message: optional(string3()) }); -var ProgressNotificationParamsSchema = object2({ +var ProgressNotificationParamsSchema = object3({ ...NotificationsParamsSchema.shape, ...ProgressSchema.shape, /** @@ -102783,27 +115392,27 @@ var PaginatedResultSchema = ResultSchema.extend({ nextCursor: CursorSchema.optional() }); var TaskStatusSchema = _enum2(["working", "input_required", "completed", "failed", "cancelled"]); -var TaskSchema = object2({ - taskId: string2(), +var TaskSchema = object3({ + taskId: string3(), status: TaskStatusSchema, /** * Time in milliseconds to keep task results available after completion. * If null, the task has unlimited lifetime until manually cleaned up. */ - ttl: union([number2(), _null3()]), + ttl: union([number3(), _null3()]), /** * ISO 8601 timestamp when the task was created. */ - createdAt: string2(), + createdAt: string3(), /** * ISO 8601 timestamp when the task was last updated. */ - lastUpdatedAt: string2(), - pollInterval: optional(number2()), + lastUpdatedAt: string3(), + pollInterval: optional(number3()), /** * Optional diagnostic message for failed tasks or other status information. */ - statusMessage: optional(string2()) + statusMessage: optional(string3()) }); var CreateTaskResultSchema = ResultSchema.extend({ task: TaskSchema @@ -102816,14 +115425,14 @@ var TaskStatusNotificationSchema = NotificationSchema.extend({ var GetTaskRequestSchema = RequestSchema.extend({ method: literal("tasks/get"), params: BaseRequestParamsSchema.extend({ - taskId: string2() + taskId: string3() }) }); var GetTaskResultSchema = ResultSchema.merge(TaskSchema); var GetTaskPayloadRequestSchema = RequestSchema.extend({ method: literal("tasks/result"), params: BaseRequestParamsSchema.extend({ - taskId: string2() + taskId: string3() }) }); var GetTaskPayloadResultSchema = ResultSchema.loose(); @@ -102836,32 +115445,32 @@ var ListTasksResultSchema = PaginatedResultSchema.extend({ var CancelTaskRequestSchema = RequestSchema.extend({ method: literal("tasks/cancel"), params: BaseRequestParamsSchema.extend({ - taskId: string2() + taskId: string3() }) }); var CancelTaskResultSchema = ResultSchema.merge(TaskSchema); -var ResourceContentsSchema = object2({ +var ResourceContentsSchema = object3({ /** * The URI of this resource. */ - uri: string2(), + uri: string3(), /** * The MIME type of this resource, if known. */ - mimeType: optional(string2()), + mimeType: optional(string3()), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ - _meta: record(string2(), unknown()).optional() + _meta: record(string3(), unknown2()).optional() }); var TextResourceContentsSchema = ResourceContentsSchema.extend({ /** * The text of the item. This must only be set if the item can actually be represented as text (not binary data). */ - text: string2() + text: string3() }); -var Base64Schema = string2().refine((val) => { +var Base64Schema = string3().refine((val) => { try { atob(val); return true; @@ -102876,7 +115485,7 @@ var BlobResourceContentsSchema = ResourceContentsSchema.extend({ blob: Base64Schema }); var RoleSchema = _enum2(["user", "assistant"]); -var AnnotationsSchema = object2({ +var AnnotationsSchema = object3({ /** * Intended audience(s) for the resource. */ @@ -102884,29 +115493,29 @@ var AnnotationsSchema = object2({ /** * Importance hint for the resource, from 0 (least) to 1 (most). */ - priority: number2().min(0).max(1).optional(), + priority: number3().min(0).max(1).optional(), /** * ISO 8601 timestamp for the most recent modification. */ lastModified: iso_exports2.datetime({ offset: true }).optional() }); -var ResourceSchema = object2({ +var ResourceSchema = object3({ ...BaseMetadataSchema.shape, ...IconsSchema.shape, /** * The URI of this resource. */ - uri: string2(), + uri: string3(), /** * A description of what this resource represents. * * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. */ - description: optional(string2()), + description: optional(string3()), /** * The MIME type of this resource, if known. */ - mimeType: optional(string2()), + mimeType: optional(string3()), /** * Optional annotations for the client. */ @@ -102917,23 +115526,23 @@ var ResourceSchema = object2({ */ _meta: optional(looseObject({})) }); -var ResourceTemplateSchema = object2({ +var ResourceTemplateSchema = object3({ ...BaseMetadataSchema.shape, ...IconsSchema.shape, /** * A URI template (according to RFC 6570) that can be used to construct resource URIs. */ - uriTemplate: string2(), + uriTemplate: string3(), /** * A description of what this template is for. * * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. */ - description: optional(string2()), + description: optional(string3()), /** * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. */ - mimeType: optional(string2()), + mimeType: optional(string3()), /** * Optional annotations for the client. */ @@ -102962,7 +115571,7 @@ var ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ * * @format uri */ - uri: string2() + uri: string3() }); var ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; var ReadResourceRequestSchema = RequestSchema.extend({ @@ -102990,33 +115599,33 @@ var ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ /** * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. */ - uri: string2() + uri: string3() }); var ResourceUpdatedNotificationSchema = NotificationSchema.extend({ method: literal("notifications/resources/updated"), params: ResourceUpdatedNotificationParamsSchema }); -var PromptArgumentSchema = object2({ +var PromptArgumentSchema = object3({ /** * The name of the argument. */ - name: string2(), + name: string3(), /** * A human-readable description of the argument. */ - description: optional(string2()), + description: optional(string3()), /** * Whether this argument must be provided. */ required: optional(boolean2()) }); -var PromptSchema = object2({ +var PromptSchema = object3({ ...BaseMetadataSchema.shape, ...IconsSchema.shape, /** * An optional description of what this prompt provides */ - description: optional(string2()), + description: optional(string3()), /** * A list of arguments to use for templating the prompt. */ @@ -103037,22 +115646,22 @@ var GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ /** * The name of the prompt or prompt template. */ - name: string2(), + name: string3(), /** * Arguments to use for templating the prompt. */ - arguments: record(string2(), string2()).optional() + arguments: record(string3(), string3()).optional() }); var GetPromptRequestSchema = RequestSchema.extend({ method: literal("prompts/get"), params: GetPromptRequestParamsSchema }); -var TextContentSchema = object2({ +var TextContentSchema = object3({ type: literal("text"), /** * The text content of the message. */ - text: string2(), + text: string3(), /** * Optional annotations for the client. */ @@ -103061,9 +115670,9 @@ var TextContentSchema = object2({ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ - _meta: record(string2(), unknown()).optional() + _meta: record(string3(), unknown2()).optional() }); -var ImageContentSchema = object2({ +var ImageContentSchema = object3({ type: literal("image"), /** * The base64-encoded image data. @@ -103072,7 +115681,7 @@ var ImageContentSchema = object2({ /** * The MIME type of the image. Different providers may support different image types. */ - mimeType: string2(), + mimeType: string3(), /** * Optional annotations for the client. */ @@ -103081,9 +115690,9 @@ var ImageContentSchema = object2({ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ - _meta: record(string2(), unknown()).optional() + _meta: record(string3(), unknown2()).optional() }); -var AudioContentSchema = object2({ +var AudioContentSchema = object3({ type: literal("audio"), /** * The base64-encoded audio data. @@ -103092,7 +115701,7 @@ var AudioContentSchema = object2({ /** * The MIME type of the audio. Different providers may support different audio types. */ - mimeType: string2(), + mimeType: string3(), /** * Optional annotations for the client. */ @@ -103101,32 +115710,32 @@ var AudioContentSchema = object2({ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ - _meta: record(string2(), unknown()).optional() + _meta: record(string3(), unknown2()).optional() }); -var ToolUseContentSchema = object2({ +var ToolUseContentSchema = object3({ type: literal("tool_use"), /** * The name of the tool to invoke. * Must match a tool name from the request's tools array. */ - name: string2(), + name: string3(), /** * Unique identifier for this tool call. * Used to correlate with ToolResultContent in subsequent messages. */ - id: string2(), + id: string3(), /** * Arguments to pass to the tool. * Must conform to the tool's inputSchema. */ - input: record(string2(), unknown()), + input: record(string3(), unknown2()), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ - _meta: record(string2(), unknown()).optional() + _meta: record(string3(), unknown2()).optional() }); -var EmbeddedResourceSchema = object2({ +var EmbeddedResourceSchema = object3({ type: literal("resource"), resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]), /** @@ -103137,7 +115746,7 @@ var EmbeddedResourceSchema = object2({ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ - _meta: record(string2(), unknown()).optional() + _meta: record(string3(), unknown2()).optional() }); var ResourceLinkSchema = ResourceSchema.extend({ type: literal("resource_link") @@ -103149,7 +115758,7 @@ var ContentBlockSchema = union([ ResourceLinkSchema, EmbeddedResourceSchema ]); -var PromptMessageSchema = object2({ +var PromptMessageSchema = object3({ role: RoleSchema, content: ContentBlockSchema }); @@ -103157,18 +115766,18 @@ var GetPromptResultSchema = ResultSchema.extend({ /** * An optional description for the prompt. */ - description: string2().optional(), + description: string3().optional(), messages: array(PromptMessageSchema) }); var PromptListChangedNotificationSchema = NotificationSchema.extend({ method: literal("notifications/prompts/list_changed"), params: NotificationsParamsSchema.optional() }); -var ToolAnnotationsSchema = object2({ +var ToolAnnotationsSchema = object3({ /** * A human-readable title for the tool. */ - title: string2().optional(), + title: string3().optional(), /** * If true, the tool does not modify its environment. * @@ -103203,7 +115812,7 @@ var ToolAnnotationsSchema = object2({ */ openWorldHint: boolean2().optional() }); -var ToolExecutionSchema = object2({ +var ToolExecutionSchema = object3({ /** * Indicates the tool's preference for task-augmented execution. * - "required": Clients MUST invoke the tool as a task @@ -103214,32 +115823,32 @@ var ToolExecutionSchema = object2({ */ taskSupport: _enum2(["required", "optional", "forbidden"]).optional() }); -var ToolSchema = object2({ +var ToolSchema = object3({ ...BaseMetadataSchema.shape, ...IconsSchema.shape, /** * A human-readable description of the tool. */ - description: string2().optional(), + description: string3().optional(), /** * A JSON Schema 2020-12 object defining the expected parameters for the tool. * Must have type: 'object' at the root level per MCP spec. */ - inputSchema: object2({ + inputSchema: object3({ type: literal("object"), - properties: record(string2(), AssertObjectSchema).optional(), - required: array(string2()).optional() - }).catchall(unknown()), + properties: record(string3(), AssertObjectSchema).optional(), + required: array(string3()).optional() + }).catchall(unknown2()), /** * An optional JSON Schema 2020-12 object defining the structure of the tool's output * returned in the structuredContent field of a CallToolResult. * Must have type: 'object' at the root level per MCP spec. */ - outputSchema: object2({ + outputSchema: object3({ type: literal("object"), - properties: record(string2(), AssertObjectSchema).optional(), - required: array(string2()).optional() - }).catchall(unknown()).optional(), + properties: record(string3(), AssertObjectSchema).optional(), + required: array(string3()).optional() + }).catchall(unknown2()).optional(), /** * Optional additional tool information. */ @@ -103252,7 +115861,7 @@ var ToolSchema = object2({ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ - _meta: record(string2(), unknown()).optional() + _meta: record(string3(), unknown2()).optional() }); var ListToolsRequestSchema = PaginatedRequestSchema.extend({ method: literal("tools/list") @@ -103273,7 +115882,7 @@ var CallToolResultSchema = ResultSchema.extend({ * * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema. */ - structuredContent: record(string2(), unknown()).optional(), + structuredContent: record(string3(), unknown2()).optional(), /** * Whether the tool call ended in an error. * @@ -103291,17 +115900,17 @@ var CallToolResultSchema = ResultSchema.extend({ isError: boolean2().optional() }); var CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({ - toolResult: unknown() + toolResult: unknown2() })); var CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ /** * The name of the tool to call. */ - name: string2(), + name: string3(), /** * Arguments to pass to the tool. */ - arguments: record(string2(), unknown()).optional() + arguments: record(string3(), unknown2()).optional() }); var CallToolRequestSchema = RequestSchema.extend({ method: literal("tools/call"), @@ -103311,7 +115920,7 @@ var ToolListChangedNotificationSchema = NotificationSchema.extend({ method: literal("notifications/tools/list_changed"), params: NotificationsParamsSchema.optional() }); -var ListChangedOptionsBaseSchema = object2({ +var ListChangedOptionsBaseSchema = object3({ /** * If true, the list will be refreshed automatically when a list changed notification is received. * The callback will be called with the updated list. @@ -103329,7 +115938,7 @@ var ListChangedOptionsBaseSchema = object2({ * * @default 300 */ - debounceMs: number2().int().nonnegative().default(300) + debounceMs: number3().int().nonnegative().default(300) }); var LoggingLevelSchema = _enum2(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]); var SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ @@ -103350,23 +115959,23 @@ var LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ /** * An optional name of the logger issuing this message. */ - logger: string2().optional(), + logger: string3().optional(), /** * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. */ - data: unknown() + data: unknown2() }); var LoggingMessageNotificationSchema = NotificationSchema.extend({ method: literal("notifications/message"), params: LoggingMessageNotificationParamsSchema }); -var ModelHintSchema = object2({ +var ModelHintSchema = object3({ /** * A hint for a model name. */ - name: string2().optional() + name: string3().optional() }); -var ModelPreferencesSchema = object2({ +var ModelPreferencesSchema = object3({ /** * Optional hints to use for model selection. */ @@ -103374,17 +115983,17 @@ var ModelPreferencesSchema = object2({ /** * How much to prioritize cost when selecting a model. */ - costPriority: number2().min(0).max(1).optional(), + costPriority: number3().min(0).max(1).optional(), /** * How much to prioritize sampling speed (latency) when selecting a model. */ - speedPriority: number2().min(0).max(1).optional(), + speedPriority: number3().min(0).max(1).optional(), /** * How much to prioritize intelligence and capabilities when selecting a model. */ - intelligencePriority: number2().min(0).max(1).optional() + intelligencePriority: number3().min(0).max(1).optional() }); -var ToolChoiceSchema = object2({ +var ToolChoiceSchema = object3({ /** * Controls when tools are used: * - "auto": Model decides whether to use tools (default) @@ -103393,17 +116002,17 @@ var ToolChoiceSchema = object2({ */ mode: _enum2(["auto", "required", "none"]).optional() }); -var ToolResultContentSchema = object2({ +var ToolResultContentSchema = object3({ type: literal("tool_result"), - toolUseId: string2().describe("The unique identifier for the corresponding tool call."), + toolUseId: string3().describe("The unique identifier for the corresponding tool call."), content: array(ContentBlockSchema).default([]), - structuredContent: object2({}).loose().optional(), + structuredContent: object3({}).loose().optional(), isError: boolean2().optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ - _meta: record(string2(), unknown()).optional() + _meta: record(string3(), unknown2()).optional() }); var SamplingContentSchema = discriminatedUnion("type", [TextContentSchema, ImageContentSchema, AudioContentSchema]); var SamplingMessageContentBlockSchema = discriminatedUnion("type", [ @@ -103413,14 +116022,14 @@ var SamplingMessageContentBlockSchema = discriminatedUnion("type", [ ToolUseContentSchema, ToolResultContentSchema ]); -var SamplingMessageSchema = object2({ +var SamplingMessageSchema = object3({ role: RoleSchema, content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ - _meta: record(string2(), unknown()).optional() + _meta: record(string3(), unknown2()).optional() }); var CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ messages: array(SamplingMessageSchema), @@ -103431,7 +116040,7 @@ var CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ /** * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. */ - systemPrompt: string2().optional(), + systemPrompt: string3().optional(), /** * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. * The client MAY ignore this request. @@ -103440,14 +116049,14 @@ var CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases. */ includeContext: _enum2(["none", "thisServer", "allServers"]).optional(), - temperature: number2().optional(), + temperature: number3().optional(), /** * The requested maximum number of tokens to sample (to prevent runaway completions). * * The client MAY choose to sample fewer tokens than the requested maximum. */ - maxTokens: number2().int(), - stopSequences: array(string2()).optional(), + maxTokens: number3().int(), + stopSequences: array(string3()).optional(), /** * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. */ @@ -103472,7 +116081,7 @@ var CreateMessageResultSchema = ResultSchema.extend({ /** * The name of the model that generated the message. */ - model: string2(), + model: string3(), /** * The reason why sampling stopped, if known. * @@ -103483,7 +116092,7 @@ var CreateMessageResultSchema = ResultSchema.extend({ * * This field is an open string to allow for provider-specific stop reasons. */ - stopReason: optional(_enum2(["endTurn", "stopSequence", "maxTokens"]).or(string2())), + stopReason: optional(_enum2(["endTurn", "stopSequence", "maxTokens"]).or(string3())), role: RoleSchema, /** * Response content. Single content block (text, image, or audio). @@ -103494,7 +116103,7 @@ var CreateMessageResultWithToolsSchema = ResultSchema.extend({ /** * The name of the model that generated the message. */ - model: string2(), + model: string3(), /** * The reason why sampling stopped, if known. * @@ -103506,87 +116115,87 @@ var CreateMessageResultWithToolsSchema = ResultSchema.extend({ * * This field is an open string to allow for provider-specific stop reasons. */ - stopReason: optional(_enum2(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(string2())), + stopReason: optional(_enum2(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(string3())), role: RoleSchema, /** * Response content. May be a single block or array. May include ToolUseContent if stopReason is "toolUse". */ content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]) }); -var BooleanSchemaSchema = object2({ +var BooleanSchemaSchema = object3({ type: literal("boolean"), - title: string2().optional(), - description: string2().optional(), + title: string3().optional(), + description: string3().optional(), default: boolean2().optional() }); -var StringSchemaSchema = object2({ +var StringSchemaSchema = object3({ type: literal("string"), - title: string2().optional(), - description: string2().optional(), - minLength: number2().optional(), - maxLength: number2().optional(), + title: string3().optional(), + description: string3().optional(), + minLength: number3().optional(), + maxLength: number3().optional(), format: _enum2(["email", "uri", "date", "date-time"]).optional(), - default: string2().optional() + default: string3().optional() }); -var NumberSchemaSchema = object2({ +var NumberSchemaSchema = object3({ type: _enum2(["number", "integer"]), - title: string2().optional(), - description: string2().optional(), - minimum: number2().optional(), - maximum: number2().optional(), - default: number2().optional() + title: string3().optional(), + description: string3().optional(), + minimum: number3().optional(), + maximum: number3().optional(), + default: number3().optional() }); -var UntitledSingleSelectEnumSchemaSchema = object2({ +var UntitledSingleSelectEnumSchemaSchema = object3({ type: literal("string"), - title: string2().optional(), - description: string2().optional(), - enum: array(string2()), - default: string2().optional() + title: string3().optional(), + description: string3().optional(), + enum: array(string3()), + default: string3().optional() }); -var TitledSingleSelectEnumSchemaSchema = object2({ +var TitledSingleSelectEnumSchemaSchema = object3({ type: literal("string"), - title: string2().optional(), - description: string2().optional(), - oneOf: array(object2({ - const: string2(), - title: string2() + title: string3().optional(), + description: string3().optional(), + oneOf: array(object3({ + const: string3(), + title: string3() })), - default: string2().optional() + default: string3().optional() }); -var LegacyTitledEnumSchemaSchema = object2({ +var LegacyTitledEnumSchemaSchema = object3({ type: literal("string"), - title: string2().optional(), - description: string2().optional(), - enum: array(string2()), - enumNames: array(string2()).optional(), - default: string2().optional() + title: string3().optional(), + description: string3().optional(), + enum: array(string3()), + enumNames: array(string3()).optional(), + default: string3().optional() }); var SingleSelectEnumSchemaSchema = union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); -var UntitledMultiSelectEnumSchemaSchema = object2({ +var UntitledMultiSelectEnumSchemaSchema = object3({ type: literal("array"), - title: string2().optional(), - description: string2().optional(), - minItems: number2().optional(), - maxItems: number2().optional(), - items: object2({ + title: string3().optional(), + description: string3().optional(), + minItems: number3().optional(), + maxItems: number3().optional(), + items: object3({ type: literal("string"), - enum: array(string2()) + enum: array(string3()) }), - default: array(string2()).optional() + default: array(string3()).optional() }); -var TitledMultiSelectEnumSchemaSchema = object2({ +var TitledMultiSelectEnumSchemaSchema = object3({ type: literal("array"), - title: string2().optional(), - description: string2().optional(), - minItems: number2().optional(), - maxItems: number2().optional(), - items: object2({ - anyOf: array(object2({ - const: string2(), - title: string2() + title: string3().optional(), + description: string3().optional(), + minItems: number3().optional(), + maxItems: number3().optional(), + items: object3({ + anyOf: array(object3({ + const: string3(), + title: string3() })) }), - default: array(string2()).optional() + default: array(string3()).optional() }); var MultiSelectEnumSchemaSchema = union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); var EnumSchemaSchema = union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]); @@ -103601,15 +116210,15 @@ var ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({ /** * The message to present to the user describing what information is being requested. */ - message: string2(), + message: string3(), /** * A restricted subset of JSON Schema. * Only top-level properties are allowed, without nesting. */ - requestedSchema: object2({ + requestedSchema: object3({ type: literal("object"), - properties: record(string2(), PrimitiveSchemaDefinitionSchema), - required: array(string2()).optional() + properties: record(string3(), PrimitiveSchemaDefinitionSchema), + required: array(string3()).optional() }) }); var ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({ @@ -103620,16 +116229,16 @@ var ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({ /** * The message to present to the user explaining why the interaction is needed. */ - message: string2(), + message: string3(), /** * The ID of the elicitation, which must be unique within the context of the server. * The client MUST treat this ID as an opaque value. */ - elicitationId: string2(), + elicitationId: string3(), /** * The URL that the user should navigate to. */ - url: string2().url() + url: string3().url() }); var ElicitRequestParamsSchema = union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); var ElicitRequestSchema = RequestSchema.extend({ @@ -103640,7 +116249,7 @@ var ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.exte /** * The ID of the elicitation that completed. */ - elicitationId: string2() + elicitationId: string3() }); var ElicitationCompleteNotificationSchema = NotificationSchema.extend({ method: literal("notifications/elicitation/complete"), @@ -103660,42 +116269,42 @@ var ElicitResultSchema = ResultSchema.extend({ * Per MCP spec, content is "typically omitted" for decline/cancel actions. * We normalize null to undefined for leniency while maintaining type compatibility. */ - content: preprocess((val) => val === null ? void 0 : val, record(string2(), union([string2(), number2(), boolean2(), array(string2())])).optional()) + content: preprocess((val) => val === null ? void 0 : val, record(string3(), union([string3(), number3(), boolean2(), array(string3())])).optional()) }); -var ResourceTemplateReferenceSchema = object2({ +var ResourceTemplateReferenceSchema = object3({ type: literal("ref/resource"), /** * The URI or URI template of the resource. */ - uri: string2() + uri: string3() }); -var PromptReferenceSchema = object2({ +var PromptReferenceSchema = object3({ type: literal("ref/prompt"), /** * The name of the prompt or prompt template */ - name: string2() + name: string3() }); var CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ ref: union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), /** * The argument's information */ - argument: object2({ + argument: object3({ /** * The name of the argument */ - name: string2(), + name: string3(), /** * The value of the argument to use for completion matching. */ - value: string2() + value: string3() }), - context: object2({ + context: object3({ /** * Previously-resolved variables in a URI template or prompt. */ - arguments: record(string2(), string2()).optional() + arguments: record(string3(), string3()).optional() }).optional() }); var CompleteRequestSchema = RequestSchema.extend({ @@ -103707,31 +116316,31 @@ var CompleteResultSchema = ResultSchema.extend({ /** * An array of completion values. Must not exceed 100 items. */ - values: array(string2()).max(100), + values: array(string3()).max(100), /** * The total number of completion options available. This can exceed the number of values actually sent in the response. */ - total: optional(number2().int()), + total: optional(number3().int()), /** * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. */ hasMore: optional(boolean2()) }) }); -var RootSchema = object2({ +var RootSchema = object3({ /** * The URI identifying the root. This *must* start with file:// for now. */ - uri: string2().startsWith("file://"), + uri: string3().startsWith("file://"), /** * An optional name for the root. */ - name: string2().optional(), + name: string3().optional(), /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ - _meta: record(string2(), unknown()).optional() + _meta: record(string3(), unknown2()).optional() }); var ListRootsRequestSchema = RequestSchema.extend({ method: literal("roots/list"), @@ -103867,7 +116476,7 @@ function getMethodLiteral(schema2) { return value2; } function parseWithCompat(schema2, data) { - const result = safeParse2(schema2, data); + const result = safeParse3(schema2, data); if (!result.success) { throw result.error; } @@ -104459,7 +117068,7 @@ var Protocol = class { return reject(response); } try { - const parseResult = safeParse2(resultSchema, response.result); + const parseResult = safeParse3(resultSchema, response.result); if (!parseResult.success) { reject(parseResult.error); } else { @@ -104802,7 +117411,7 @@ var Protocol = class { }; } }; -function isPlainObject2(value2) { +function isPlainObject5(value2) { return value2 !== null && typeof value2 === "object" && !Array.isArray(value2); } function mergeCapabilities(base, additional) { @@ -104813,7 +117422,7 @@ function mergeCapabilities(base, additional) { if (addValue === void 0) continue; const baseValue = result[k]; - if (isPlainObject2(baseValue) && isPlainObject2(addValue)) { + if (isPlainObject5(baseValue) && isPlainObject5(addValue)) { result[k] = { ...baseValue, ...addValue }; } else { result[k] = addValue; @@ -105220,7 +117829,7 @@ var Server = class extends Protocol { const method = methodValue; if (method === "tools/call") { const wrappedHandler = async (request2, extra) => { - const validatedRequest = safeParse2(CallToolRequestSchema, request2); + const validatedRequest = safeParse3(CallToolRequestSchema, request2); if (!validatedRequest.success) { const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error); throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call request: ${errorMessage}`); @@ -105228,14 +117837,14 @@ var Server = class extends Protocol { const { params } = validatedRequest.data; const result = await Promise.resolve(handler2(request2, extra)); if (params.task) { - const taskValidationResult = safeParse2(CreateTaskResultSchema, result); + const taskValidationResult = safeParse3(CreateTaskResultSchema, result); if (!taskValidationResult.success) { const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error); throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`); } return taskValidationResult.data; } - const validationResult = safeParse2(CallToolResultSchema, result); + const validationResult = safeParse3(CallToolResultSchema, result); if (!validationResult.success) { const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error); throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call result: ${errorMessage}`); @@ -105637,13 +118246,13 @@ function isNumber(value2) { function isBoolean(value2) { return value2 === true || value2 === false || isObjectLike(value2) && getTag(value2) == "[object Boolean]"; } -function isObject2(value2) { +function isObject3(value2) { return typeof value2 === "object"; } function isObjectLike(value2) { - return isObject2(value2) && value2 !== null; + return isObject3(value2) && value2 !== null; } -function isDefined(value2) { +function isDefined2(value2) { return value2 !== void 0 && value2 !== null; } function isBlank(value2) { @@ -105721,7 +118330,7 @@ function get(obj, path3) { let list = []; let arr = false; const deepGet = (obj2, path4, index) => { - if (!isDefined(obj2)) { + if (!isDefined2(obj2)) { return; } if (!path4[index]) { @@ -105729,7 +118338,7 @@ function get(obj, path3) { } else { let key = path4[index]; const value2 = obj2[key]; - if (!isDefined(value2)) { + if (!isDefined2(value2)) { return; } if (index === path4.length - 1 && (isString(value2) || isNumber(value2) || isBoolean(value2))) { @@ -105891,7 +118500,7 @@ var FuseIndex = class { return this.records.length; } _addString(doc, docIndex) { - if (!isDefined(doc) || isBlank(doc)) { + if (!isDefined2(doc) || isBlank(doc)) { return; } let record3 = { @@ -105905,7 +118514,7 @@ var FuseIndex = class { let record3 = { i: docIndex, $: {} }; this.keys.forEach((key, keyIndex) => { let value2 = key.getFn ? key.getFn(doc) : this.getFn(doc, key.path); - if (!isDefined(value2)) { + if (!isDefined2(value2)) { return; } if (isArray2(value2)) { @@ -105913,7 +118522,7 @@ var FuseIndex = class { const stack = [{ nestedArrIndex: -1, value: value2 }]; while (stack.length) { const { nestedArrIndex, value: value3 } = stack.pop(); - if (!isDefined(value3)) { + if (!isDefined2(value3)) { continue; } if (isString(value3) && !isBlank(value3)) { @@ -106593,7 +119202,7 @@ var ExtendedSearch = class { } }; var registeredSearchers = []; -function register2(...args2) { +function register3(...args2) { registeredSearchers.push(...args2); } function createSearcher(pattern, options) { @@ -106615,13 +119224,13 @@ var KeyType = { }; var isExpression = (query) => !!(query[LogicalOperator.AND] || query[LogicalOperator.OR]); var isPath = (query) => !!query[KeyType.PATH]; -var isLeaf = (query) => !isArray2(query) && isObject2(query) && !isExpression(query); +var isLeaf = (query) => !isArray2(query) && isObject3(query) && !isExpression(query); var convertToExplicit = (query) => ({ [LogicalOperator.AND]: Object.keys(query).map((key) => ({ [key]: query[key] })) }); -function parse3(query, options, { auto = true } = {}) { +function parse4(query, options, { auto = true } = {}) { const next2 = (query2) => { let keys = Object.keys(query2); const isQueryPath = isPath(query2); @@ -106678,11 +119287,11 @@ function computeScore(results, { ignoreFieldNorm = Config.ignoreFieldNorm }) { function transformMatches(result, data) { const matches = result.matches; data.matches = []; - if (!isDefined(matches)) { + if (!isDefined2(matches)) { return; } matches.forEach((match3) => { - if (!isDefined(match3.indices) || !match3.indices.length) { + if (!isDefined2(match3.indices) || !match3.indices.length) { return; } const { indices, value: value2 } = match3; @@ -106743,7 +119352,7 @@ var Fuse = class { }); } add(doc) { - if (!isDefined(doc)) { + if (!isDefined2(doc)) { return; } this._docs.push(doc); @@ -106795,7 +119404,7 @@ var Fuse = class { const { records } = this._myIndex; const results = []; records.forEach(({ v: text, i: idx, n: norm2 }) => { - if (!isDefined(text)) { + if (!isDefined2(text)) { return; } const { isMatch, score, indices } = searcher.searchIn(text); @@ -106810,7 +119419,7 @@ var Fuse = class { return results; } _searchLogical(query) { - const expression = parse3(query, this.options); + const expression = parse4(query, this.options); const evaluate = (node2, item, idx) => { if (!node2.children) { const { keyId, searcher } = node2; @@ -106846,7 +119455,7 @@ var Fuse = class { const resultMap = {}; const results = []; records.forEach(({ $: item, i: idx }) => { - if (isDefined(item)) { + if (isDefined2(item)) { let expResults = evaluate(expression, item, idx); if (expResults.length) { if (!resultMap[idx]) { @@ -106866,7 +119475,7 @@ var Fuse = class { const { keys, records } = this._myIndex; const results = []; records.forEach(({ $: item, i: idx }) => { - if (!isDefined(item)) { + if (!isDefined2(item)) { return; } let matches = []; @@ -106890,13 +119499,13 @@ var Fuse = class { return results; } _findMatches({ key, value: value2, searcher }) { - if (!isDefined(value2)) { + if (!isDefined2(value2)) { return []; } let matches = []; if (isArray2(value2)) { value2.forEach(({ v: text, i: idx, n: norm2 }) => { - if (!isDefined(text)) { + if (!isDefined2(text)) { return; } const { isMatch, score, indices } = searcher.searchIn(text); @@ -106926,10 +119535,10 @@ Fuse.createIndex = createIndex; Fuse.parseIndex = parseIndex; Fuse.config = Config; { - Fuse.parseQuery = parse3; + Fuse.parseQuery = parse4; } { - register2(ExtendedSearch); + register3(ExtendedSearch); } // node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/compose.js @@ -108353,7 +120962,7 @@ var Hono = class _Hono { // node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/reg-exp-router/matcher.js var emptyParam = []; -function match(method, path3) { +function match2(method, path3) { const matchers = this.buildAllMatchers(); const match22 = ((method2, path22) => { const matcher = matchers[method2] || matchers[METHOD_NAME_ALL]; @@ -108683,7 +121292,7 @@ var RegExpRouter = class { }); } } - match = match; + match = match2; buildAllMatchers() { const matchers = /* @__PURE__ */ Object.create(null); Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => { @@ -109249,7 +121858,7 @@ function esc2(str$1) { } var captureStackTrace2 = Error.captureStackTrace ? Error.captureStackTrace : (..._args) => { }; -function isObject3(data) { +function isObject4(data) { return typeof data === "object" && data !== null && !Array.isArray(data); } var allowsEval2 = cached3(() => { @@ -109262,11 +121871,11 @@ var allowsEval2 = cached3(() => { } }); function isPlainObject$1(o) { - if (isObject3(o) === false) return false; + if (isObject4(o) === false) return false; const ctor = o.constructor; if (ctor === void 0) return true; const prot = ctor.prototype; - if (isObject3(prot) === false) return false; + if (isObject4(prot) === false) return false; if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) return false; return true; } @@ -109324,7 +121933,7 @@ function pick2(schema2, mask) { checks: [] }); } -function omit3(schema2, mask) { +function omit4(schema2, mask) { const newShape = { ...schema2._zod.def.shape }; const currDef = schema2._zod.def; for (const key$1 in mask) { @@ -109353,7 +121962,7 @@ function extend2(schema2, shape) { checks: [] }); } -function merge2(a, b) { +function merge3(a, b) { return clone2(a, { ...a._zod.def, get shape() { @@ -109585,11 +122194,11 @@ var ksuid3 = /^[A-Za-z0-9]{27}$/; var nanoid3 = /^[a-zA-Z0-9_-]{21}$/; var duration$1 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; var guid3 = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; -var uuid3 = (version$1) => { +var uuid5 = (version$1) => { if (!version$1) return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/; return /* @__PURE__ */ new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version$1}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); }; -var email3 = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; +var email4 = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; var _emoji$1 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; function emoji3() { return new RegExp(_emoji$1, "u"); @@ -109598,7 +122207,7 @@ var ipv43 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25 var ipv63 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/; var cidrv43 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; var cidrv63 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -var base643 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; +var base644 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; var base64url3 = /^[A-Za-z0-9_-]*$/; var hostname3 = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/; var e1643 = /^\+(?:[0-9]){6,14}[0-9]$/; @@ -109623,7 +122232,7 @@ var string$1 = (params) => { const regex$1 = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; return /* @__PURE__ */ new RegExp(`^${regex$1}$`); }; -var integer2 = /^\d+$/; +var integer3 = /^\d+$/; var number$1 = /^-?\d+(?:\.\d+)?/i; var boolean$1 = /true|false/i; var _null$2 = /null/i; @@ -109714,7 +122323,7 @@ var $ZodCheckNumberFormat2 = /* @__PURE__ */ $constructor2("$ZodCheckNumberForma bag.format = def$30.format; bag.minimum = minimum; bag.maximum = maximum; - if (isInt) bag.pattern = integer2; + if (isInt) bag.pattern = integer3; }); inst._zod.check = (payload) => { const input = payload.value; @@ -110116,12 +122725,12 @@ var $ZodUUID2 = /* @__PURE__ */ $constructor2("$ZodUUID", (inst, def$30) => { v8: 8 }[def$30.version]; if (v === void 0) throw new Error(`Invalid UUID version: "${def$30.version}"`); - def$30.pattern ?? (def$30.pattern = uuid3(v)); - } else def$30.pattern ?? (def$30.pattern = uuid3()); + def$30.pattern ?? (def$30.pattern = uuid5(v)); + } else def$30.pattern ?? (def$30.pattern = uuid5()); $ZodStringFormat2.init(inst, def$30); }); var $ZodEmail2 = /* @__PURE__ */ $constructor2("$ZodEmail", (inst, def$30) => { - def$30.pattern ?? (def$30.pattern = email3); + def$30.pattern ?? (def$30.pattern = email4); $ZodStringFormat2.init(inst, def$30); }); var $ZodURL2 = /* @__PURE__ */ $constructor2("$ZodURL", (inst, def$30) => { @@ -110279,7 +122888,7 @@ function isValidBase642(data) { } } var $ZodBase642 = /* @__PURE__ */ $constructor2("$ZodBase64", (inst, def$30) => { - def$30.pattern ?? (def$30.pattern = base643); + def$30.pattern ?? (def$30.pattern = base644); $ZodStringFormat2.init(inst, def$30); inst._zod.onattach.push((inst$1) => { inst$1._zod.bag.contentEncoding = "base64"; @@ -110555,7 +123164,7 @@ var $ZodObject2 = /* @__PURE__ */ $constructor2("$ZodObject", (inst, def$30) => return (payload, ctx) => fn2(shape, payload, ctx); }; let fastpass; - const isObject$1 = isObject3; + const isObject$1 = isObject4; const jit = !globalConfig2.jitless; const allowsEval$1 = allowsEval2; const fastEnabled = jit && allowsEval$1.value; @@ -110700,7 +123309,7 @@ var $ZodDiscriminatedUnion2 = /* @__PURE__ */ $constructor2("$ZodDiscriminatedUn }); inst._zod.parse = (payload, ctx) => { const input = payload.value; - if (!isObject3(input)) { + if (!isObject4(input)) { payload.issues.push({ code: "invalid_type", expected: "object", @@ -111751,7 +124360,7 @@ var ZodString3 = /* @__PURE__ */ $constructor2("ZodString", (inst, def$30) => { inst.time = (params) => inst.check(time3(params)); inst.duration = (params) => inst.check(duration3(params)); }); -function string4(params) { +function string5(params) { return _string2(ZodString3, params); } var ZodStringFormat2 = /* @__PURE__ */ $constructor2("ZodStringFormat", (inst, def$30) => { @@ -111774,7 +124383,7 @@ var ZodURL2 = /* @__PURE__ */ $constructor2("ZodURL", (inst, def$30) => { $ZodURL2.init(inst, def$30); ZodStringFormat2.init(inst, def$30); }); -function url2(params) { +function url3(params) { return _url2(ZodURL2, params); } var ZodEmoji2 = /* @__PURE__ */ $constructor2("ZodEmoji", (inst, def$30) => { @@ -111862,7 +124471,7 @@ var ZodNumber3 = /* @__PURE__ */ $constructor2("ZodNumber", (inst, def$30) => { inst.isFinite = true; inst.format = bag.format ?? null; }); -function number4(params) { +function number5(params) { return _number2(ZodNumber3, params); } var ZodNumberFormat2 = /* @__PURE__ */ $constructor2("ZodNumberFormat", (inst, def$30) => { @@ -111897,7 +124506,7 @@ var ZodUnknown3 = /* @__PURE__ */ $constructor2("ZodUnknown", (inst, def$30) => $ZodUnknown2.init(inst, def$30); ZodType3.init(inst, def$30); }); -function unknown2() { +function unknown3() { return _unknown2(ZodUnknown3); } var ZodNever3 = /* @__PURE__ */ $constructor2("ZodNever", (inst, def$30) => { @@ -111931,11 +124540,11 @@ var ZodObject3 = /* @__PURE__ */ $constructor2("ZodObject", (inst, def$30) => { }); inst.passthrough = () => inst.clone({ ...inst._zod.def, - catchall: unknown2() + catchall: unknown3() }); inst.loose = () => inst.clone({ ...inst._zod.def, - catchall: unknown2() + catchall: unknown3() }); inst.strict = () => inst.clone({ ...inst._zod.def, @@ -111948,13 +124557,13 @@ var ZodObject3 = /* @__PURE__ */ $constructor2("ZodObject", (inst, def$30) => { inst.extend = (incoming) => { return extend2(inst, incoming); }; - inst.merge = (other) => merge2(inst, other); + inst.merge = (other) => merge3(inst, other); inst.pick = (mask) => pick2(inst, mask); - inst.omit = (mask) => omit3(inst, mask); + inst.omit = (mask) => omit4(inst, mask); inst.partial = (...args2) => partial2(ZodOptional3, inst, args2[0]); inst.required = (...args2) => required2(ZodNonOptional2, inst, args2[0]); }); -function object3(shape, params) { +function object4(shape, params) { return new ZodObject3({ type: "object", get shape() { @@ -111971,7 +124580,7 @@ function looseObject2(shape, params) { assignProp2(this, "shape", { ...shape }); return this.shape; }, - catchall: unknown2(), + catchall: unknown3(), ...normalizeParams2(params) }); } @@ -112254,13 +124863,13 @@ var SUPPORTED_PROTOCOL_VERSIONS2 = [ var RELATED_TASK_META_KEY2 = "io.modelcontextprotocol/related-task"; var JSONRPC_VERSION2 = "2.0"; var AssertObjectSchema2 = custom2((v) => v !== null && (typeof v === "object" || typeof v === "function")); -var ProgressTokenSchema2 = union2([string4(), number4().int()]); -var CursorSchema2 = string4(); +var ProgressTokenSchema2 = union2([string5(), number5().int()]); +var CursorSchema2 = string5(); var TaskCreationParamsSchema2 = looseObject2({ - ttl: union2([number4(), _null4()]).optional(), - pollInterval: number4().optional() + ttl: union2([number5(), _null4()]).optional(), + pollInterval: number5().optional() }); -var RelatedTaskMetadataSchema2 = looseObject2({ taskId: string4() }); +var RelatedTaskMetadataSchema2 = looseObject2({ taskId: string5() }); var RequestMetaSchema2 = looseObject2({ progressToken: ProgressTokenSchema2.optional(), [RELATED_TASK_META_KEY2]: RelatedTaskMetadataSchema2.optional() @@ -112269,28 +124878,28 @@ var BaseRequestParamsSchema2 = looseObject2({ task: TaskCreationParamsSchema2.optional(), _meta: RequestMetaSchema2.optional() }); -var RequestSchema2 = object3({ - method: string4(), +var RequestSchema2 = object4({ + method: string5(), params: BaseRequestParamsSchema2.optional() }); -var NotificationsParamsSchema2 = looseObject2({ _meta: object3({ [RELATED_TASK_META_KEY2]: optional2(RelatedTaskMetadataSchema2) }).passthrough().optional() }); -var NotificationSchema2 = object3({ - method: string4(), +var NotificationsParamsSchema2 = looseObject2({ _meta: object4({ [RELATED_TASK_META_KEY2]: optional2(RelatedTaskMetadataSchema2) }).passthrough().optional() }); +var NotificationSchema2 = object4({ + method: string5(), params: NotificationsParamsSchema2.optional() }); var ResultSchema2 = looseObject2({ _meta: looseObject2({ [RELATED_TASK_META_KEY2]: RelatedTaskMetadataSchema2.optional() }).optional() }); -var RequestIdSchema2 = union2([string4(), number4().int()]); -var JSONRPCRequestSchema2 = object3({ +var RequestIdSchema2 = union2([string5(), number5().int()]); +var JSONRPCRequestSchema2 = object4({ jsonrpc: literal2(JSONRPC_VERSION2), id: RequestIdSchema2, ...RequestSchema2.shape }).strict(); var isJSONRPCRequest2 = (value2) => JSONRPCRequestSchema2.safeParse(value2).success; -var JSONRPCNotificationSchema2 = object3({ +var JSONRPCNotificationSchema2 = object4({ jsonrpc: literal2(JSONRPC_VERSION2), ...NotificationSchema2.shape }).strict(); -var JSONRPCResponseSchema2 = object3({ +var JSONRPCResponseSchema2 = object4({ jsonrpc: literal2(JSONRPC_VERSION2), id: RequestIdSchema2, result: ResultSchema2 @@ -112307,13 +124916,13 @@ var ErrorCode2; ErrorCode$1[ErrorCode$1["InternalError"] = -32603] = "InternalError"; ErrorCode$1[ErrorCode$1["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; })(ErrorCode2 || (ErrorCode2 = {})); -var JSONRPCErrorSchema = object3({ +var JSONRPCErrorSchema = object4({ jsonrpc: literal2(JSONRPC_VERSION2), id: RequestIdSchema2, - error: object3({ - code: number4().int(), - message: string4(), - data: optional2(unknown2()) + error: object4({ + code: number5().int(), + message: string5(), + data: optional2(unknown3()) }) }).strict(); var isJSONRPCError = (value2) => JSONRPCErrorSchema.safeParse(value2).success; @@ -112326,63 +124935,63 @@ var JSONRPCMessageSchema2 = union2([ var EmptyResultSchema2 = ResultSchema2.strict(); var CancelledNotificationParamsSchema2 = NotificationsParamsSchema2.extend({ requestId: RequestIdSchema2, - reason: string4().optional() + reason: string5().optional() }); var CancelledNotificationSchema2 = NotificationSchema2.extend({ method: literal2("notifications/cancelled"), params: CancelledNotificationParamsSchema2 }); -var IconSchema2 = object3({ - src: string4(), - mimeType: string4().optional(), - sizes: array2(string4()).optional() +var IconSchema2 = object4({ + src: string5(), + mimeType: string5().optional(), + sizes: array2(string5()).optional() }); -var IconsSchema2 = object3({ icons: array2(IconSchema2).optional() }); -var BaseMetadataSchema2 = object3({ - name: string4(), - title: string4().optional() +var IconsSchema2 = object4({ icons: array2(IconSchema2).optional() }); +var BaseMetadataSchema2 = object4({ + name: string5(), + title: string5().optional() }); var ImplementationSchema2 = BaseMetadataSchema2.extend({ ...BaseMetadataSchema2.shape, ...IconsSchema2.shape, - version: string4(), - websiteUrl: string4().optional() + version: string5(), + websiteUrl: string5().optional() }); -var FormElicitationCapabilitySchema2 = intersection2(object3({ applyDefaults: boolean4().optional() }), record2(string4(), unknown2())); +var FormElicitationCapabilitySchema2 = intersection2(object4({ applyDefaults: boolean4().optional() }), record2(string5(), unknown3())); var ElicitationCapabilitySchema2 = preprocess2((value2) => { if (value2 && typeof value2 === "object" && !Array.isArray(value2)) { if (Object.keys(value2).length === 0) return { form: {} }; } return value2; -}, intersection2(object3({ +}, intersection2(object4({ form: FormElicitationCapabilitySchema2.optional(), url: AssertObjectSchema2.optional() -}), record2(string4(), unknown2()).optional())); -var ClientTasksCapabilitySchema2 = object3({ - list: optional2(object3({}).passthrough()), - cancel: optional2(object3({}).passthrough()), - requests: optional2(object3({ - sampling: optional2(object3({ createMessage: optional2(object3({}).passthrough()) }).passthrough()), - elicitation: optional2(object3({ create: optional2(object3({}).passthrough()) }).passthrough()) +}), record2(string5(), unknown3()).optional())); +var ClientTasksCapabilitySchema2 = object4({ + list: optional2(object4({}).passthrough()), + cancel: optional2(object4({}).passthrough()), + requests: optional2(object4({ + sampling: optional2(object4({ createMessage: optional2(object4({}).passthrough()) }).passthrough()), + elicitation: optional2(object4({ create: optional2(object4({}).passthrough()) }).passthrough()) }).passthrough()) }).passthrough(); -var ServerTasksCapabilitySchema2 = object3({ - list: optional2(object3({}).passthrough()), - cancel: optional2(object3({}).passthrough()), - requests: optional2(object3({ tools: optional2(object3({ call: optional2(object3({}).passthrough()) }).passthrough()) }).passthrough()) +var ServerTasksCapabilitySchema2 = object4({ + list: optional2(object4({}).passthrough()), + cancel: optional2(object4({}).passthrough()), + requests: optional2(object4({ tools: optional2(object4({ call: optional2(object4({}).passthrough()) }).passthrough()) }).passthrough()) }).passthrough(); -var ClientCapabilitiesSchema2 = object3({ - experimental: record2(string4(), AssertObjectSchema2).optional(), - sampling: object3({ +var ClientCapabilitiesSchema2 = object4({ + experimental: record2(string5(), AssertObjectSchema2).optional(), + sampling: object4({ context: AssertObjectSchema2.optional(), tools: AssertObjectSchema2.optional() }).optional(), elicitation: ElicitationCapabilitySchema2.optional(), - roots: object3({ listChanged: boolean4().optional() }).optional(), + roots: object4({ listChanged: boolean4().optional() }).optional(), tasks: optional2(ClientTasksCapabilitySchema2) }); var InitializeRequestParamsSchema2 = BaseRequestParamsSchema2.extend({ - protocolVersion: string4(), + protocolVersion: string5(), capabilities: ClientCapabilitiesSchema2, clientInfo: ImplementationSchema2 }); @@ -112391,32 +125000,32 @@ var InitializeRequestSchema2 = RequestSchema2.extend({ params: InitializeRequestParamsSchema2 }); var isInitializeRequest = (value2) => InitializeRequestSchema2.safeParse(value2).success; -var ServerCapabilitiesSchema2 = object3({ - experimental: record2(string4(), AssertObjectSchema2).optional(), +var ServerCapabilitiesSchema2 = object4({ + experimental: record2(string5(), AssertObjectSchema2).optional(), logging: AssertObjectSchema2.optional(), completions: AssertObjectSchema2.optional(), - prompts: optional2(object3({ listChanged: optional2(boolean4()) })), - resources: object3({ + prompts: optional2(object4({ listChanged: optional2(boolean4()) })), + resources: object4({ subscribe: boolean4().optional(), listChanged: boolean4().optional() }).optional(), - tools: object3({ listChanged: boolean4().optional() }).optional(), + tools: object4({ listChanged: boolean4().optional() }).optional(), tasks: optional2(ServerTasksCapabilitySchema2) }).passthrough(); var InitializeResultSchema2 = ResultSchema2.extend({ - protocolVersion: string4(), + protocolVersion: string5(), capabilities: ServerCapabilitiesSchema2, serverInfo: ImplementationSchema2, - instructions: string4().optional() + instructions: string5().optional() }); var InitializedNotificationSchema2 = NotificationSchema2.extend({ method: literal2("notifications/initialized") }); var PingRequestSchema2 = RequestSchema2.extend({ method: literal2("ping") }); -var ProgressSchema2 = object3({ - progress: number4(), - total: optional2(number4()), - message: optional2(string4()) +var ProgressSchema2 = object4({ + progress: number5(), + total: optional2(number5()), + message: optional2(string5()) }); -var ProgressNotificationParamsSchema2 = object3({ +var ProgressNotificationParamsSchema2 = object4({ ...NotificationsParamsSchema2.shape, ...ProgressSchema2.shape, progressToken: ProgressTokenSchema2 @@ -112428,8 +125037,8 @@ var ProgressNotificationSchema2 = NotificationSchema2.extend({ var PaginatedRequestParamsSchema2 = BaseRequestParamsSchema2.extend({ cursor: CursorSchema2.optional() }); var PaginatedRequestSchema2 = RequestSchema2.extend({ params: PaginatedRequestParamsSchema2.optional() }); var PaginatedResultSchema2 = ResultSchema2.extend({ nextCursor: optional2(CursorSchema2) }); -var TaskSchema2 = object3({ - taskId: string4(), +var TaskSchema2 = object4({ + taskId: string5(), status: _enum3([ "working", "input_required", @@ -112437,11 +125046,11 @@ var TaskSchema2 = object3({ "failed", "cancelled" ]), - ttl: union2([number4(), _null4()]), - createdAt: string4(), - lastUpdatedAt: string4(), - pollInterval: optional2(number4()), - statusMessage: optional2(string4()) + ttl: union2([number5(), _null4()]), + createdAt: string5(), + lastUpdatedAt: string5(), + pollInterval: optional2(number5()), + statusMessage: optional2(string5()) }); var CreateTaskResultSchema2 = ResultSchema2.extend({ task: TaskSchema2 }); var TaskStatusNotificationParamsSchema2 = NotificationsParamsSchema2.merge(TaskSchema2); @@ -112451,27 +125060,27 @@ var TaskStatusNotificationSchema2 = NotificationSchema2.extend({ }); var GetTaskRequestSchema2 = RequestSchema2.extend({ method: literal2("tasks/get"), - params: BaseRequestParamsSchema2.extend({ taskId: string4() }) + params: BaseRequestParamsSchema2.extend({ taskId: string5() }) }); var GetTaskResultSchema2 = ResultSchema2.merge(TaskSchema2); var GetTaskPayloadRequestSchema2 = RequestSchema2.extend({ method: literal2("tasks/result"), - params: BaseRequestParamsSchema2.extend({ taskId: string4() }) + params: BaseRequestParamsSchema2.extend({ taskId: string5() }) }); var ListTasksRequestSchema2 = PaginatedRequestSchema2.extend({ method: literal2("tasks/list") }); var ListTasksResultSchema2 = PaginatedResultSchema2.extend({ tasks: array2(TaskSchema2) }); var CancelTaskRequestSchema2 = RequestSchema2.extend({ method: literal2("tasks/cancel"), - params: BaseRequestParamsSchema2.extend({ taskId: string4() }) + params: BaseRequestParamsSchema2.extend({ taskId: string5() }) }); var CancelTaskResultSchema2 = ResultSchema2.merge(TaskSchema2); -var ResourceContentsSchema2 = object3({ - uri: string4(), - mimeType: optional2(string4()), - _meta: record2(string4(), unknown2()).optional() +var ResourceContentsSchema2 = object4({ + uri: string5(), + mimeType: optional2(string5()), + _meta: record2(string5(), unknown3()).optional() }); -var TextResourceContentsSchema2 = ResourceContentsSchema2.extend({ text: string4() }); -var Base64Schema2 = string4().refine((val) => { +var TextResourceContentsSchema2 = ResourceContentsSchema2.extend({ text: string5() }); +var Base64Schema2 = string5().refine((val) => { try { atob(val); return true; @@ -112480,26 +125089,26 @@ var Base64Schema2 = string4().refine((val) => { } }, { message: "Invalid Base64 string" }); var BlobResourceContentsSchema2 = ResourceContentsSchema2.extend({ blob: Base64Schema2 }); -var AnnotationsSchema2 = object3({ +var AnnotationsSchema2 = object4({ audience: array2(_enum3(["user", "assistant"])).optional(), - priority: number4().min(0).max(1).optional(), + priority: number5().min(0).max(1).optional(), lastModified: datetime3({ offset: true }).optional() }); -var ResourceSchema2 = object3({ +var ResourceSchema2 = object4({ ...BaseMetadataSchema2.shape, ...IconsSchema2.shape, - uri: string4(), - description: optional2(string4()), - mimeType: optional2(string4()), + uri: string5(), + description: optional2(string5()), + mimeType: optional2(string5()), annotations: AnnotationsSchema2.optional(), _meta: optional2(looseObject2({})) }); -var ResourceTemplateSchema2 = object3({ +var ResourceTemplateSchema2 = object4({ ...BaseMetadataSchema2.shape, ...IconsSchema2.shape, - uriTemplate: string4(), - description: optional2(string4()), - mimeType: optional2(string4()), + uriTemplate: string5(), + description: optional2(string5()), + mimeType: optional2(string5()), annotations: AnnotationsSchema2.optional(), _meta: optional2(looseObject2({})) }); @@ -112507,7 +125116,7 @@ var ListResourcesRequestSchema2 = PaginatedRequestSchema2.extend({ method: liter var ListResourcesResultSchema2 = PaginatedResultSchema2.extend({ resources: array2(ResourceSchema2) }); var ListResourceTemplatesRequestSchema2 = PaginatedRequestSchema2.extend({ method: literal2("resources/templates/list") }); var ListResourceTemplatesResultSchema2 = PaginatedResultSchema2.extend({ resourceTemplates: array2(ResourceTemplateSchema2) }); -var ResourceRequestParamsSchema2 = BaseRequestParamsSchema2.extend({ uri: string4() }); +var ResourceRequestParamsSchema2 = BaseRequestParamsSchema2.extend({ uri: string5() }); var ReadResourceRequestParamsSchema2 = ResourceRequestParamsSchema2; var ReadResourceRequestSchema2 = RequestSchema2.extend({ method: literal2("resources/read"), @@ -112525,65 +125134,65 @@ var UnsubscribeRequestSchema2 = RequestSchema2.extend({ method: literal2("resources/unsubscribe"), params: UnsubscribeRequestParamsSchema2 }); -var ResourceUpdatedNotificationParamsSchema2 = NotificationsParamsSchema2.extend({ uri: string4() }); +var ResourceUpdatedNotificationParamsSchema2 = NotificationsParamsSchema2.extend({ uri: string5() }); var ResourceUpdatedNotificationSchema2 = NotificationSchema2.extend({ method: literal2("notifications/resources/updated"), params: ResourceUpdatedNotificationParamsSchema2 }); -var PromptArgumentSchema2 = object3({ - name: string4(), - description: optional2(string4()), +var PromptArgumentSchema2 = object4({ + name: string5(), + description: optional2(string5()), required: optional2(boolean4()) }); -var PromptSchema2 = object3({ +var PromptSchema2 = object4({ ...BaseMetadataSchema2.shape, ...IconsSchema2.shape, - description: optional2(string4()), + description: optional2(string5()), arguments: optional2(array2(PromptArgumentSchema2)), _meta: optional2(looseObject2({})) }); var ListPromptsRequestSchema2 = PaginatedRequestSchema2.extend({ method: literal2("prompts/list") }); var ListPromptsResultSchema2 = PaginatedResultSchema2.extend({ prompts: array2(PromptSchema2) }); var GetPromptRequestParamsSchema2 = BaseRequestParamsSchema2.extend({ - name: string4(), - arguments: record2(string4(), string4()).optional() + name: string5(), + arguments: record2(string5(), string5()).optional() }); var GetPromptRequestSchema2 = RequestSchema2.extend({ method: literal2("prompts/get"), params: GetPromptRequestParamsSchema2 }); -var TextContentSchema2 = object3({ +var TextContentSchema2 = object4({ type: literal2("text"), - text: string4(), + text: string5(), annotations: AnnotationsSchema2.optional(), - _meta: record2(string4(), unknown2()).optional() + _meta: record2(string5(), unknown3()).optional() }); -var ImageContentSchema2 = object3({ +var ImageContentSchema2 = object4({ type: literal2("image"), data: Base64Schema2, - mimeType: string4(), + mimeType: string5(), annotations: AnnotationsSchema2.optional(), - _meta: record2(string4(), unknown2()).optional() + _meta: record2(string5(), unknown3()).optional() }); -var AudioContentSchema2 = object3({ +var AudioContentSchema2 = object4({ type: literal2("audio"), data: Base64Schema2, - mimeType: string4(), + mimeType: string5(), annotations: AnnotationsSchema2.optional(), - _meta: record2(string4(), unknown2()).optional() + _meta: record2(string5(), unknown3()).optional() }); -var ToolUseContentSchema2 = object3({ +var ToolUseContentSchema2 = object4({ type: literal2("tool_use"), - name: string4(), - id: string4(), - input: object3({}).passthrough(), - _meta: optional2(object3({}).passthrough()) + name: string5(), + id: string5(), + input: object4({}).passthrough(), + _meta: optional2(object4({}).passthrough()) }).passthrough(); -var EmbeddedResourceSchema2 = object3({ +var EmbeddedResourceSchema2 = object4({ type: literal2("resource"), resource: union2([TextResourceContentsSchema2, BlobResourceContentsSchema2]), annotations: AnnotationsSchema2.optional(), - _meta: record2(string4(), unknown2()).optional() + _meta: record2(string5(), unknown3()).optional() }); var ResourceLinkSchema2 = ResourceSchema2.extend({ type: literal2("resource_link") }); var ContentBlockSchema2 = union2([ @@ -112593,56 +125202,56 @@ var ContentBlockSchema2 = union2([ ResourceLinkSchema2, EmbeddedResourceSchema2 ]); -var PromptMessageSchema2 = object3({ +var PromptMessageSchema2 = object4({ role: _enum3(["user", "assistant"]), content: ContentBlockSchema2 }); var GetPromptResultSchema2 = ResultSchema2.extend({ - description: optional2(string4()), + description: optional2(string5()), messages: array2(PromptMessageSchema2) }); var PromptListChangedNotificationSchema2 = NotificationSchema2.extend({ method: literal2("notifications/prompts/list_changed") }); -var ToolAnnotationsSchema2 = object3({ - title: string4().optional(), +var ToolAnnotationsSchema2 = object4({ + title: string5().optional(), readOnlyHint: boolean4().optional(), destructiveHint: boolean4().optional(), idempotentHint: boolean4().optional(), openWorldHint: boolean4().optional() }); -var ToolExecutionSchema2 = object3({ taskSupport: _enum3([ +var ToolExecutionSchema2 = object4({ taskSupport: _enum3([ "required", "optional", "forbidden" ]).optional() }); -var ToolSchema2 = object3({ +var ToolSchema2 = object4({ ...BaseMetadataSchema2.shape, ...IconsSchema2.shape, - description: string4().optional(), - inputSchema: object3({ + description: string5().optional(), + inputSchema: object4({ type: literal2("object"), - properties: record2(string4(), AssertObjectSchema2).optional(), - required: array2(string4()).optional() - }).catchall(unknown2()), - outputSchema: object3({ + properties: record2(string5(), AssertObjectSchema2).optional(), + required: array2(string5()).optional() + }).catchall(unknown3()), + outputSchema: object4({ type: literal2("object"), - properties: record2(string4(), AssertObjectSchema2).optional(), - required: array2(string4()).optional() - }).catchall(unknown2()).optional(), + properties: record2(string5(), AssertObjectSchema2).optional(), + required: array2(string5()).optional() + }).catchall(unknown3()).optional(), annotations: optional2(ToolAnnotationsSchema2), execution: optional2(ToolExecutionSchema2), - _meta: record2(string4(), unknown2()).optional() + _meta: record2(string5(), unknown3()).optional() }); var ListToolsRequestSchema2 = PaginatedRequestSchema2.extend({ method: literal2("tools/list") }); var ListToolsResultSchema2 = PaginatedResultSchema2.extend({ tools: array2(ToolSchema2) }); var CallToolResultSchema2 = ResultSchema2.extend({ content: array2(ContentBlockSchema2).default([]), - structuredContent: record2(string4(), unknown2()).optional(), + structuredContent: record2(string5(), unknown3()).optional(), isError: optional2(boolean4()) }); -var CompatibilityCallToolResultSchema2 = CallToolResultSchema2.or(ResultSchema2.extend({ toolResult: unknown2() })); +var CompatibilityCallToolResultSchema2 = CallToolResultSchema2.or(ResultSchema2.extend({ toolResult: unknown3() })); var CallToolRequestParamsSchema2 = BaseRequestParamsSchema2.extend({ - name: string4(), - arguments: optional2(record2(string4(), unknown2())) + name: string5(), + arguments: optional2(record2(string5(), unknown3())) }); var CallToolRequestSchema2 = RequestSchema2.extend({ method: literal2("tools/call"), @@ -112666,32 +125275,32 @@ var SetLevelRequestSchema2 = RequestSchema2.extend({ }); var LoggingMessageNotificationParamsSchema2 = NotificationsParamsSchema2.extend({ level: LoggingLevelSchema2, - logger: string4().optional(), - data: unknown2() + logger: string5().optional(), + data: unknown3() }); var LoggingMessageNotificationSchema2 = NotificationSchema2.extend({ method: literal2("notifications/message"), params: LoggingMessageNotificationParamsSchema2 }); -var ModelHintSchema2 = object3({ name: string4().optional() }); -var ModelPreferencesSchema2 = object3({ +var ModelHintSchema2 = object4({ name: string5().optional() }); +var ModelPreferencesSchema2 = object4({ hints: optional2(array2(ModelHintSchema2)), - costPriority: optional2(number4().min(0).max(1)), - speedPriority: optional2(number4().min(0).max(1)), - intelligencePriority: optional2(number4().min(0).max(1)) + costPriority: optional2(number5().min(0).max(1)), + speedPriority: optional2(number5().min(0).max(1)), + intelligencePriority: optional2(number5().min(0).max(1)) }); -var ToolChoiceSchema2 = object3({ mode: optional2(_enum3([ +var ToolChoiceSchema2 = object4({ mode: optional2(_enum3([ "auto", "required", "none" ])) }); -var ToolResultContentSchema2 = object3({ +var ToolResultContentSchema2 = object4({ type: literal2("tool_result"), - toolUseId: string4().describe("The unique identifier for the corresponding tool call."), + toolUseId: string5().describe("The unique identifier for the corresponding tool call."), content: array2(ContentBlockSchema2).default([]), - structuredContent: object3({}).passthrough().optional(), + structuredContent: object4({}).passthrough().optional(), isError: optional2(boolean4()), - _meta: optional2(object3({}).passthrough()) + _meta: optional2(object4({}).passthrough()) }).passthrough(); var SamplingContentSchema2 = discriminatedUnion2("type", [ TextContentSchema2, @@ -112705,23 +125314,23 @@ var SamplingMessageContentBlockSchema2 = discriminatedUnion2("type", [ ToolUseContentSchema2, ToolResultContentSchema2 ]); -var SamplingMessageSchema2 = object3({ +var SamplingMessageSchema2 = object4({ role: _enum3(["user", "assistant"]), content: union2([SamplingMessageContentBlockSchema2, array2(SamplingMessageContentBlockSchema2)]), - _meta: optional2(object3({}).passthrough()) + _meta: optional2(object4({}).passthrough()) }).passthrough(); var CreateMessageRequestParamsSchema2 = BaseRequestParamsSchema2.extend({ messages: array2(SamplingMessageSchema2), modelPreferences: ModelPreferencesSchema2.optional(), - systemPrompt: string4().optional(), + systemPrompt: string5().optional(), includeContext: _enum3([ "none", "thisServer", "allServers" ]).optional(), - temperature: number4().optional(), - maxTokens: number4().int(), - stopSequences: array2(string4()).optional(), + temperature: number5().optional(), + maxTokens: number5().int(), + stopSequences: array2(string5()).optional(), metadata: AssertObjectSchema2.optional(), tools: optional2(array2(ToolSchema2)), toolChoice: optional2(ToolChoiceSchema2) @@ -112731,103 +125340,103 @@ var CreateMessageRequestSchema2 = RequestSchema2.extend({ params: CreateMessageRequestParamsSchema2 }); var CreateMessageResultSchema2 = ResultSchema2.extend({ - model: string4(), + model: string5(), stopReason: optional2(_enum3([ "endTurn", "stopSequence", "maxTokens" - ]).or(string4())), + ]).or(string5())), role: _enum3(["user", "assistant"]), content: SamplingContentSchema2 }); var CreateMessageResultWithToolsSchema2 = ResultSchema2.extend({ - model: string4(), + model: string5(), stopReason: optional2(_enum3([ "endTurn", "stopSequence", "maxTokens", "toolUse" - ]).or(string4())), + ]).or(string5())), role: _enum3(["user", "assistant"]), content: union2([SamplingMessageContentBlockSchema2, array2(SamplingMessageContentBlockSchema2)]) }); -var BooleanSchemaSchema2 = object3({ +var BooleanSchemaSchema2 = object4({ type: literal2("boolean"), - title: string4().optional(), - description: string4().optional(), + title: string5().optional(), + description: string5().optional(), default: boolean4().optional() }); -var StringSchemaSchema2 = object3({ +var StringSchemaSchema2 = object4({ type: literal2("string"), - title: string4().optional(), - description: string4().optional(), - minLength: number4().optional(), - maxLength: number4().optional(), + title: string5().optional(), + description: string5().optional(), + minLength: number5().optional(), + maxLength: number5().optional(), format: _enum3([ "email", "uri", "date", "date-time" ]).optional(), - default: string4().optional() + default: string5().optional() }); -var NumberSchemaSchema2 = object3({ +var NumberSchemaSchema2 = object4({ type: _enum3(["number", "integer"]), - title: string4().optional(), - description: string4().optional(), - minimum: number4().optional(), - maximum: number4().optional(), - default: number4().optional() + title: string5().optional(), + description: string5().optional(), + minimum: number5().optional(), + maximum: number5().optional(), + default: number5().optional() }); -var UntitledSingleSelectEnumSchemaSchema2 = object3({ +var UntitledSingleSelectEnumSchemaSchema2 = object4({ type: literal2("string"), - title: string4().optional(), - description: string4().optional(), - enum: array2(string4()), - default: string4().optional() + title: string5().optional(), + description: string5().optional(), + enum: array2(string5()), + default: string5().optional() }); -var TitledSingleSelectEnumSchemaSchema2 = object3({ +var TitledSingleSelectEnumSchemaSchema2 = object4({ type: literal2("string"), - title: string4().optional(), - description: string4().optional(), - oneOf: array2(object3({ - const: string4(), - title: string4() + title: string5().optional(), + description: string5().optional(), + oneOf: array2(object4({ + const: string5(), + title: string5() })), - default: string4().optional() + default: string5().optional() }); -var LegacyTitledEnumSchemaSchema2 = object3({ +var LegacyTitledEnumSchemaSchema2 = object4({ type: literal2("string"), - title: string4().optional(), - description: string4().optional(), - enum: array2(string4()), - enumNames: array2(string4()).optional(), - default: string4().optional() + title: string5().optional(), + description: string5().optional(), + enum: array2(string5()), + enumNames: array2(string5()).optional(), + default: string5().optional() }); var SingleSelectEnumSchemaSchema2 = union2([UntitledSingleSelectEnumSchemaSchema2, TitledSingleSelectEnumSchemaSchema2]); -var UntitledMultiSelectEnumSchemaSchema2 = object3({ +var UntitledMultiSelectEnumSchemaSchema2 = object4({ type: literal2("array"), - title: string4().optional(), - description: string4().optional(), - minItems: number4().optional(), - maxItems: number4().optional(), - items: object3({ + title: string5().optional(), + description: string5().optional(), + minItems: number5().optional(), + maxItems: number5().optional(), + items: object4({ type: literal2("string"), - enum: array2(string4()) + enum: array2(string5()) }), - default: array2(string4()).optional() + default: array2(string5()).optional() }); -var TitledMultiSelectEnumSchemaSchema2 = object3({ +var TitledMultiSelectEnumSchemaSchema2 = object4({ type: literal2("array"), - title: string4().optional(), - description: string4().optional(), - minItems: number4().optional(), - maxItems: number4().optional(), - items: object3({ anyOf: array2(object3({ - const: string4(), - title: string4() + title: string5().optional(), + description: string5().optional(), + minItems: number5().optional(), + maxItems: number5().optional(), + items: object4({ anyOf: array2(object4({ + const: string5(), + title: string5() })) }), - default: array2(string4()).optional() + default: array2(string5()).optional() }); var MultiSelectEnumSchemaSchema2 = union2([UntitledMultiSelectEnumSchemaSchema2, TitledMultiSelectEnumSchemaSchema2]); var EnumSchemaSchema2 = union2([ @@ -112843,25 +125452,25 @@ var PrimitiveSchemaDefinitionSchema2 = union2([ ]); var ElicitRequestFormParamsSchema2 = BaseRequestParamsSchema2.extend({ mode: literal2("form").optional(), - message: string4(), - requestedSchema: object3({ + message: string5(), + requestedSchema: object4({ type: literal2("object"), - properties: record2(string4(), PrimitiveSchemaDefinitionSchema2), - required: array2(string4()).optional() + properties: record2(string5(), PrimitiveSchemaDefinitionSchema2), + required: array2(string5()).optional() }) }); var ElicitRequestURLParamsSchema2 = BaseRequestParamsSchema2.extend({ mode: literal2("url"), - message: string4(), - elicitationId: string4(), - url: string4().url() + message: string5(), + elicitationId: string5(), + url: string5().url() }); var ElicitRequestParamsSchema2 = union2([ElicitRequestFormParamsSchema2, ElicitRequestURLParamsSchema2]); var ElicitRequestSchema2 = RequestSchema2.extend({ method: literal2("elicitation/create"), params: ElicitRequestParamsSchema2 }); -var ElicitationCompleteNotificationParamsSchema2 = NotificationsParamsSchema2.extend({ elicitationId: string4() }); +var ElicitationCompleteNotificationParamsSchema2 = NotificationsParamsSchema2.extend({ elicitationId: string5() }); var ElicitationCompleteNotificationSchema2 = NotificationSchema2.extend({ method: literal2("notifications/elicitation/complete"), params: ElicitationCompleteNotificationParamsSchema2 @@ -112872,42 +125481,42 @@ var ElicitResultSchema2 = ResultSchema2.extend({ "decline", "cancel" ]), - content: preprocess2((val) => val === null ? void 0 : val, record2(string4(), union2([ - string4(), - number4(), + content: preprocess2((val) => val === null ? void 0 : val, record2(string5(), union2([ + string5(), + number5(), boolean4(), - array2(string4()) + array2(string5()) ])).optional()) }); -var ResourceTemplateReferenceSchema2 = object3({ +var ResourceTemplateReferenceSchema2 = object4({ type: literal2("ref/resource"), - uri: string4() + uri: string5() }); -var PromptReferenceSchema2 = object3({ +var PromptReferenceSchema2 = object4({ type: literal2("ref/prompt"), - name: string4() + name: string5() }); var CompleteRequestParamsSchema2 = BaseRequestParamsSchema2.extend({ ref: union2([PromptReferenceSchema2, ResourceTemplateReferenceSchema2]), - argument: object3({ - name: string4(), - value: string4() + argument: object4({ + name: string5(), + value: string5() }), - context: object3({ arguments: record2(string4(), string4()).optional() }).optional() + context: object4({ arguments: record2(string5(), string5()).optional() }).optional() }); var CompleteRequestSchema2 = RequestSchema2.extend({ method: literal2("completion/complete"), params: CompleteRequestParamsSchema2 }); var CompleteResultSchema2 = ResultSchema2.extend({ completion: looseObject2({ - values: array2(string4()).max(100), - total: optional2(number4().int()), + values: array2(string5()).max(100), + total: optional2(number5().int()), hasMore: optional2(boolean4()) }) }); -var RootSchema2 = object3({ - uri: string4().startsWith("file://"), - name: string4().optional(), - _meta: record2(string4(), unknown2()).optional() +var RootSchema2 = object4({ + uri: string5().startsWith("file://"), + name: string5().optional(), + _meta: record2(string5(), unknown3()).optional() }); var ListRootsRequestSchema2 = RequestSchema2.extend({ method: literal2("roots/list") }); var ListRootsResultSchema2 = ResultSchema2.extend({ roots: array2(RootSchema2) }); @@ -126267,7 +138876,7 @@ var require_data2 = /* @__PURE__ */ __commonJSMin(((exports, module) => { "additionalProperties": false }; })); -var require_utils4 = /* @__PURE__ */ __commonJSMin(((exports, module) => { +var require_utils5 = /* @__PURE__ */ __commonJSMin(((exports, module) => { const isUUID$1 = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); const isIPv4$1 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u); function stringArrayToHexStripped(input) { @@ -126483,7 +139092,7 @@ var require_utils4 = /* @__PURE__ */ __commonJSMin(((exports, module) => { }; })); var require_schemes2 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - const { isUUID } = require_utils4(); + const { isUUID } = require_utils5(); const URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu; const supportedSchemeNames = [ "http", @@ -126630,7 +139239,7 @@ var require_schemes2 = /* @__PURE__ */ __commonJSMin(((exports, module) => { }; })); var require_fast_uri2 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils4(); + const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils5(); const { SCHEMES, getSchemeHandler } = require_schemes2(); function normalize2(uri$2, options) { if (typeof uri$2 === "string") uri$2 = serialize(parse5(uri$2, options), options); @@ -127767,7 +140376,7 @@ var require_limitItems2 = /* @__PURE__ */ __commonJSMin(((exports) => { }; exports.default = def$21; })); -var require_equal2 = /* @__PURE__ */ __commonJSMin(((exports) => { +var require_equal3 = /* @__PURE__ */ __commonJSMin(((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); const equal = require_fast_deep_equal2(); equal.code = 'require("ajv/dist/runtime/equal").default'; @@ -127778,7 +140387,7 @@ var require_uniqueItems2 = /* @__PURE__ */ __commonJSMin(((exports) => { const dataType_1 = require_dataType2(); const codegen_1$17 = require_codegen2(); const util_1$17 = require_util9(); - const equal_1$2 = require_equal2(); + const equal_1$2 = require_equal3(); const def$20 = { keyword: "uniqueItems", type: "array", @@ -127839,7 +140448,7 @@ var require_const2 = /* @__PURE__ */ __commonJSMin(((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); const codegen_1$16 = require_codegen2(); const util_1$16 = require_util9(); - const equal_1$1 = require_equal2(); + const equal_1$1 = require_equal3(); const def$19 = { keyword: "const", $data: true, @@ -127859,7 +140468,7 @@ var require_enum2 = /* @__PURE__ */ __commonJSMin(((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); const codegen_1$15 = require_codegen2(); const util_1$15 = require_util9(); - const equal_1 = require_equal2(); + const equal_1 = require_equal3(); const def$18 = { keyword: "enum", schemaType: "array", @@ -129427,7 +142036,7 @@ var ZodIssueCode3 = { invalid_value: "invalid_value", custom: "custom" }; -function number5(params) { +function number6(params) { return _coercedNumber2(ZodNumber3, params); } var ParseError2 = class extends Error { @@ -129435,11 +142044,11 @@ var ParseError2 = class extends Error { super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line; } }; -function noop(_arg) { +function noop3(_arg) { } function createParser(callbacks) { if (typeof callbacks == "function") throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"); - const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks; + const { onEvent = noop3, onError = noop3, onRetry = noop3, onComment } = callbacks; let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = ""; function feed(newChunk) { const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`); @@ -129785,7 +142394,7 @@ function getBaseURL() { } var crypto; crypto = globalThis.crypto?.webcrypto ?? globalThis.crypto ?? import("node:crypto").then((m) => m.webcrypto); -var SafeUrlSchema = url2().superRefine((val, ctx) => { +var SafeUrlSchema = url3().superRefine((val, ctx) => { if (!URL.canParse(val)) { ctx.addIssue({ code: ZodIssueCode3.custom, @@ -129799,72 +142408,72 @@ var SafeUrlSchema = url2().superRefine((val, ctx) => { return u.protocol !== "javascript:" && u.protocol !== "data:" && u.protocol !== "vbscript:"; }, { message: "URL cannot use javascript:, data:, or vbscript: scheme" }); var OAuthProtectedResourceMetadataSchema = looseObject2({ - resource: string4().url(), + resource: string5().url(), authorization_servers: array2(SafeUrlSchema).optional(), - jwks_uri: string4().url().optional(), - scopes_supported: array2(string4()).optional(), - bearer_methods_supported: array2(string4()).optional(), - resource_signing_alg_values_supported: array2(string4()).optional(), - resource_name: string4().optional(), - resource_documentation: string4().optional(), - resource_policy_uri: string4().url().optional(), - resource_tos_uri: string4().url().optional(), + jwks_uri: string5().url().optional(), + scopes_supported: array2(string5()).optional(), + bearer_methods_supported: array2(string5()).optional(), + resource_signing_alg_values_supported: array2(string5()).optional(), + resource_name: string5().optional(), + resource_documentation: string5().optional(), + resource_policy_uri: string5().url().optional(), + resource_tos_uri: string5().url().optional(), tls_client_certificate_bound_access_tokens: boolean4().optional(), - authorization_details_types_supported: array2(string4()).optional(), - dpop_signing_alg_values_supported: array2(string4()).optional(), + authorization_details_types_supported: array2(string5()).optional(), + dpop_signing_alg_values_supported: array2(string5()).optional(), dpop_bound_access_tokens_required: boolean4().optional() }); var OAuthMetadataSchema = looseObject2({ - issuer: string4(), + issuer: string5(), authorization_endpoint: SafeUrlSchema, token_endpoint: SafeUrlSchema, registration_endpoint: SafeUrlSchema.optional(), - scopes_supported: array2(string4()).optional(), - response_types_supported: array2(string4()), - response_modes_supported: array2(string4()).optional(), - grant_types_supported: array2(string4()).optional(), - token_endpoint_auth_methods_supported: array2(string4()).optional(), - token_endpoint_auth_signing_alg_values_supported: array2(string4()).optional(), + scopes_supported: array2(string5()).optional(), + response_types_supported: array2(string5()), + response_modes_supported: array2(string5()).optional(), + grant_types_supported: array2(string5()).optional(), + token_endpoint_auth_methods_supported: array2(string5()).optional(), + token_endpoint_auth_signing_alg_values_supported: array2(string5()).optional(), service_documentation: SafeUrlSchema.optional(), revocation_endpoint: SafeUrlSchema.optional(), - revocation_endpoint_auth_methods_supported: array2(string4()).optional(), - revocation_endpoint_auth_signing_alg_values_supported: array2(string4()).optional(), - introspection_endpoint: string4().optional(), - introspection_endpoint_auth_methods_supported: array2(string4()).optional(), - introspection_endpoint_auth_signing_alg_values_supported: array2(string4()).optional(), - code_challenge_methods_supported: array2(string4()).optional(), + revocation_endpoint_auth_methods_supported: array2(string5()).optional(), + revocation_endpoint_auth_signing_alg_values_supported: array2(string5()).optional(), + introspection_endpoint: string5().optional(), + introspection_endpoint_auth_methods_supported: array2(string5()).optional(), + introspection_endpoint_auth_signing_alg_values_supported: array2(string5()).optional(), + code_challenge_methods_supported: array2(string5()).optional(), client_id_metadata_document_supported: boolean4().optional() }); var OpenIdProviderMetadataSchema = looseObject2({ - issuer: string4(), + issuer: string5(), authorization_endpoint: SafeUrlSchema, token_endpoint: SafeUrlSchema, userinfo_endpoint: SafeUrlSchema.optional(), jwks_uri: SafeUrlSchema, registration_endpoint: SafeUrlSchema.optional(), - scopes_supported: array2(string4()).optional(), - response_types_supported: array2(string4()), - response_modes_supported: array2(string4()).optional(), - grant_types_supported: array2(string4()).optional(), - acr_values_supported: array2(string4()).optional(), - subject_types_supported: array2(string4()), - id_token_signing_alg_values_supported: array2(string4()), - id_token_encryption_alg_values_supported: array2(string4()).optional(), - id_token_encryption_enc_values_supported: array2(string4()).optional(), - userinfo_signing_alg_values_supported: array2(string4()).optional(), - userinfo_encryption_alg_values_supported: array2(string4()).optional(), - userinfo_encryption_enc_values_supported: array2(string4()).optional(), - request_object_signing_alg_values_supported: array2(string4()).optional(), - request_object_encryption_alg_values_supported: array2(string4()).optional(), - request_object_encryption_enc_values_supported: array2(string4()).optional(), - token_endpoint_auth_methods_supported: array2(string4()).optional(), - token_endpoint_auth_signing_alg_values_supported: array2(string4()).optional(), - display_values_supported: array2(string4()).optional(), - claim_types_supported: array2(string4()).optional(), - claims_supported: array2(string4()).optional(), - service_documentation: string4().optional(), - claims_locales_supported: array2(string4()).optional(), - ui_locales_supported: array2(string4()).optional(), + scopes_supported: array2(string5()).optional(), + response_types_supported: array2(string5()), + response_modes_supported: array2(string5()).optional(), + grant_types_supported: array2(string5()).optional(), + acr_values_supported: array2(string5()).optional(), + subject_types_supported: array2(string5()), + id_token_signing_alg_values_supported: array2(string5()), + id_token_encryption_alg_values_supported: array2(string5()).optional(), + id_token_encryption_enc_values_supported: array2(string5()).optional(), + userinfo_signing_alg_values_supported: array2(string5()).optional(), + userinfo_encryption_alg_values_supported: array2(string5()).optional(), + userinfo_encryption_enc_values_supported: array2(string5()).optional(), + request_object_signing_alg_values_supported: array2(string5()).optional(), + request_object_encryption_alg_values_supported: array2(string5()).optional(), + request_object_encryption_enc_values_supported: array2(string5()).optional(), + token_endpoint_auth_methods_supported: array2(string5()).optional(), + token_endpoint_auth_signing_alg_values_supported: array2(string5()).optional(), + display_values_supported: array2(string5()).optional(), + claim_types_supported: array2(string5()).optional(), + claims_supported: array2(string5()).optional(), + service_documentation: string5().optional(), + claims_locales_supported: array2(string5()).optional(), + ui_locales_supported: array2(string5()).optional(), claims_parameter_supported: boolean4().optional(), request_parameter_supported: boolean4().optional(), request_uri_parameter_supported: boolean4().optional(), @@ -129873,56 +142482,56 @@ var OpenIdProviderMetadataSchema = looseObject2({ op_tos_uri: SafeUrlSchema.optional(), client_id_metadata_document_supported: boolean4().optional() }); -var OpenIdProviderDiscoveryMetadataSchema = object3({ +var OpenIdProviderDiscoveryMetadataSchema = object4({ ...OpenIdProviderMetadataSchema.shape, ...OAuthMetadataSchema.pick({ code_challenge_methods_supported: true }).shape }); -var OAuthTokensSchema = object3({ - access_token: string4(), - id_token: string4().optional(), - token_type: string4(), - expires_in: number5().optional(), - scope: string4().optional(), - refresh_token: string4().optional() +var OAuthTokensSchema = object4({ + access_token: string5(), + id_token: string5().optional(), + token_type: string5(), + expires_in: number6().optional(), + scope: string5().optional(), + refresh_token: string5().optional() }).strip(); -var OAuthErrorResponseSchema = object3({ - error: string4(), - error_description: string4().optional(), - error_uri: string4().optional() +var OAuthErrorResponseSchema = object4({ + error: string5(), + error_description: string5().optional(), + error_uri: string5().optional() }); var OptionalSafeUrlSchema = SafeUrlSchema.optional().or(literal2("").transform(() => void 0)); -var OAuthClientMetadataSchema = object3({ +var OAuthClientMetadataSchema = object4({ redirect_uris: array2(SafeUrlSchema), - token_endpoint_auth_method: string4().optional(), - grant_types: array2(string4()).optional(), - response_types: array2(string4()).optional(), - client_name: string4().optional(), + token_endpoint_auth_method: string5().optional(), + grant_types: array2(string5()).optional(), + response_types: array2(string5()).optional(), + client_name: string5().optional(), client_uri: SafeUrlSchema.optional(), logo_uri: OptionalSafeUrlSchema, - scope: string4().optional(), - contacts: array2(string4()).optional(), + scope: string5().optional(), + contacts: array2(string5()).optional(), tos_uri: OptionalSafeUrlSchema, - policy_uri: string4().optional(), + policy_uri: string5().optional(), jwks_uri: SafeUrlSchema.optional(), jwks: any2().optional(), - software_id: string4().optional(), - software_version: string4().optional(), - software_statement: string4().optional() + software_id: string5().optional(), + software_version: string5().optional(), + software_statement: string5().optional() }).strip(); -var OAuthClientInformationSchema = object3({ - client_id: string4(), - client_secret: string4().optional(), - client_id_issued_at: number4().optional(), - client_secret_expires_at: number4().optional() +var OAuthClientInformationSchema = object4({ + client_id: string5(), + client_secret: string5().optional(), + client_id_issued_at: number5().optional(), + client_secret_expires_at: number5().optional() }).strip(); var OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema); -var OAuthClientRegistrationErrorSchema = object3({ - error: string4(), - error_description: string4().optional() +var OAuthClientRegistrationErrorSchema = object4({ + error: string5(), + error_description: string5().optional() }).strip(); -var OAuthTokenRevocationRequestSchema = object3({ - token: string4(), - token_type_hint: string4().optional() +var OAuthTokenRevocationRequestSchema = object4({ + token: string5(), + token_type_hint: string5().optional() }).strip(); var OAuthError = class extends Error { constructor(message, errorUri) { @@ -131913,7868 +144522,13 @@ import { createHmac as createHmac2, pbkdf2, randomBytes } from "crypto"; import { promisify } from "util"; var pbkdf2Async = promisify(pbkdf2); -// models.ts -function provider(config3) { - return config3; -} -var providers = { - anthropic: provider({ - displayName: "Anthropic", - envVars: ["ANTHROPIC_API_KEY"], - models: { - "claude-opus": { - displayName: "Claude Opus", - resolve: "anthropic/claude-opus-4-6", - openRouterResolve: "openrouter/anthropic/claude-opus-4.6", - preferred: true - }, - "claude-sonnet": { - displayName: "Claude Sonnet", - resolve: "anthropic/claude-sonnet-4-6", - openRouterResolve: "openrouter/anthropic/claude-sonnet-4.6" - }, - "claude-haiku": { - displayName: "Claude Haiku", - resolve: "anthropic/claude-haiku-4-5", - openRouterResolve: "openrouter/anthropic/claude-haiku-4.5" - } - } - }), - openai: provider({ - displayName: "OpenAI", - envVars: ["OPENAI_API_KEY"], - models: { - "gpt-codex": { - displayName: "GPT Codex", - resolve: "openai/gpt-5.3-codex", - openRouterResolve: "openrouter/openai/gpt-5.3-codex", - preferred: true - }, - "gpt-codex-mini": { - displayName: "GPT Codex Mini", - resolve: "openai/codex-mini-latest", - openRouterResolve: "openrouter/openai/gpt-5.1-codex-mini" - }, - o3: { - displayName: "O3", - resolve: "openai/o3" - } - } - }), - google: provider({ - displayName: "Google", - envVars: ["GOOGLE_GENERATIVE_AI_API_KEY", "GEMINI_API_KEY"], - models: { - "gemini-pro": { - displayName: "Gemini Pro", - resolve: "google/gemini-3.1-pro-preview", - openRouterResolve: "openrouter/google/gemini-3.1-pro-preview", - preferred: true - }, - "gemini-flash": { - displayName: "Gemini Flash", - resolve: "google/gemini-3-flash-preview", - openRouterResolve: "openrouter/google/gemini-3-flash-preview" - } - } - }), - xai: provider({ - displayName: "xAI", - envVars: ["XAI_API_KEY"], - models: { - grok: { - displayName: "Grok", - resolve: "xai/grok-4", - openRouterResolve: "openrouter/x-ai/grok-4", - preferred: true - }, - "grok-fast": { - displayName: "Grok Fast", - resolve: "xai/grok-4-fast", - openRouterResolve: "openrouter/x-ai/grok-4-fast" - }, - "grok-code-fast": { - displayName: "Grok Code Fast", - resolve: "xai/grok-code-fast-1", - openRouterResolve: "openrouter/x-ai/grok-code-fast-1" - } - } - }), - deepseek: provider({ - displayName: "DeepSeek", - envVars: ["DEEPSEEK_API_KEY"], - models: { - "deepseek-reasoner": { - displayName: "DeepSeek Reasoner", - resolve: "deepseek/deepseek-reasoner", - openRouterResolve: "openrouter/deepseek/deepseek-v3.2", - preferred: true - }, - "deepseek-chat": { - displayName: "DeepSeek Chat", - resolve: "deepseek/deepseek-chat", - openRouterResolve: "openrouter/deepseek/deepseek-v3.2" - } - } - }), - moonshotai: provider({ - displayName: "Moonshot AI", - envVars: ["MOONSHOT_API_KEY"], - models: { - "kimi-k2": { - displayName: "Kimi K2", - resolve: "moonshotai/kimi-k2.5", - openRouterResolve: "openrouter/moonshotai/kimi-k2.5", - preferred: true - } - } - }), - opencode: provider({ - displayName: "OpenCode", - envVars: ["OPENCODE_API_KEY"], - models: { - "big-pickle": { - displayName: "Big Pickle", - resolve: "opencode/big-pickle", - preferred: true, - envVars: [], - isFree: true - }, - "claude-opus": { - displayName: "Claude Opus", - resolve: "opencode/claude-opus-4-6", - openRouterResolve: "openrouter/anthropic/claude-opus-4.6" - }, - "claude-sonnet": { - displayName: "Claude Sonnet", - resolve: "opencode/claude-sonnet-4-6", - openRouterResolve: "openrouter/anthropic/claude-sonnet-4.6" - }, - "claude-haiku": { - displayName: "Claude Haiku", - resolve: "opencode/claude-haiku-4-5", - openRouterResolve: "openrouter/anthropic/claude-haiku-4.5" - }, - "gpt-codex": { - displayName: "GPT Codex", - resolve: "opencode/gpt-5.3-codex", - openRouterResolve: "openrouter/openai/gpt-5.3-codex" - }, - "gpt-codex-mini": { - displayName: "GPT Codex Mini", - resolve: "opencode/gpt-5.1-codex-mini", - openRouterResolve: "openrouter/openai/gpt-5.1-codex-mini" - }, - "gemini-pro": { - displayName: "Gemini Pro", - resolve: "opencode/gemini-3.1-pro", - openRouterResolve: "openrouter/google/gemini-3.1-pro-preview" - }, - "gemini-flash": { - displayName: "Gemini Flash", - resolve: "opencode/gemini-3-flash", - openRouterResolve: "openrouter/google/gemini-3-flash-preview" - }, - "kimi-k2": { - displayName: "Kimi K2", - resolve: "opencode/kimi-k2.5", - openRouterResolve: "openrouter/moonshotai/kimi-k2.5" - }, - "gpt-5-nano": { - displayName: "GPT Nano", - resolve: "opencode/gpt-5-nano", - envVars: [], - isFree: true - }, - "mimo-v2-pro-free": { - displayName: "MiMo V2 Pro", - resolve: "opencode/mimo-v2-pro-free", - envVars: [], - isFree: true - }, - "minimax-m2.5-free": { - displayName: "MiniMax M2.5", - resolve: "opencode/minimax-m2.5-free", - envVars: [], - isFree: true - }, - "nemotron-3-super-free": { - displayName: "Nemotron 3 Super", - resolve: "opencode/nemotron-3-super-free", - envVars: [], - isFree: true - } - } - }), - openrouter: provider({ - displayName: "OpenRouter", - envVars: ["OPENROUTER_API_KEY"], - models: { - "claude-opus": { - displayName: "Claude Opus", - resolve: "openrouter/anthropic/claude-opus-4.6", - openRouterResolve: "openrouter/anthropic/claude-opus-4.6", - preferred: true - }, - "claude-sonnet": { - displayName: "Claude Sonnet", - resolve: "openrouter/anthropic/claude-sonnet-4.6", - openRouterResolve: "openrouter/anthropic/claude-sonnet-4.6" - }, - "claude-haiku": { - displayName: "Claude Haiku", - resolve: "openrouter/anthropic/claude-haiku-4.5", - openRouterResolve: "openrouter/anthropic/claude-haiku-4.5" - }, - "gpt-codex": { - displayName: "GPT Codex", - resolve: "openrouter/openai/gpt-5.3-codex", - openRouterResolve: "openrouter/openai/gpt-5.3-codex" - }, - "gpt-codex-mini": { - displayName: "GPT Codex Mini", - resolve: "openrouter/openai/gpt-5.1-codex-mini", - openRouterResolve: "openrouter/openai/gpt-5.1-codex-mini" - }, - "o4-mini": { - displayName: "O4 Mini", - resolve: "openrouter/openai/o4-mini", - openRouterResolve: "openrouter/openai/o4-mini" - }, - "gemini-pro": { - displayName: "Gemini Pro", - resolve: "openrouter/google/gemini-3.1-pro-preview", - openRouterResolve: "openrouter/google/gemini-3.1-pro-preview" - }, - "gemini-flash": { - displayName: "Gemini Flash", - resolve: "openrouter/google/gemini-3-flash-preview", - openRouterResolve: "openrouter/google/gemini-3-flash-preview" - }, - grok: { - displayName: "Grok", - resolve: "openrouter/x-ai/grok-4", - openRouterResolve: "openrouter/x-ai/grok-4" - }, - "deepseek-chat": { - displayName: "DeepSeek Chat", - resolve: "openrouter/deepseek/deepseek-v3.2", - openRouterResolve: "openrouter/deepseek/deepseek-v3.2" - }, - "kimi-k2": { - displayName: "Kimi K2", - resolve: "openrouter/moonshotai/kimi-k2.5", - openRouterResolve: "openrouter/moonshotai/kimi-k2.5" - } - } - }) -}; -function parseModel(slug) { - const slashIdx = slug.indexOf("/"); - if (slashIdx === -1) { - throw new Error(`invalid model slug "${slug}" \u2014 expected "provider/model"`); - } - return { provider: slug.slice(0, slashIdx), model: slug.slice(slashIdx + 1) }; -} -function getModelEnvVars(slug) { - const parsed2 = parseModel(slug); - const providerConfig = providers[parsed2.provider]; - if (!providerConfig) { - return []; - } - const modelConfig = providerConfig.models[parsed2.model]; - if (modelConfig?.envVars) { - return modelConfig.envVars.slice(); - } - return providerConfig.envVars.slice(); -} -var modelAliases = Object.entries(providers).flatMap( - ([providerKey, config3]) => Object.entries(config3.models).map(([modelId, def]) => ({ - slug: `${providerKey}/${modelId}`, - provider: providerKey, - displayName: def.displayName, - resolve: def.resolve, - openRouterResolve: def.openRouterResolve, - preferred: def.preferred ?? false, - isFree: def.isFree ?? false - })) -); -function resolveModelSlug(slug) { - return modelAliases.find((a) => a.slug === slug)?.resolve; -} -function resolveCliModel(slug) { - return resolveModelSlug(slug); -} - // external.ts var ghPullfrogMcpName = "gh_pullfrog"; -// utils/log.ts -var core = __toESM(require_core(), 1); -var import_table = __toESM(require_src(), 1); -import { AsyncLocalStorage } from "node:async_hooks"; - -// utils/globals.ts -import { existsSync } from "node:fs"; -var isCloudflareSandbox = !!process.env.CLOUDFLARE_APPLICATION_ID && !!process.env.SANDBOX_VERSION; -var isGitHubActions = !!process.env.GITHUB_ACTIONS; -var isInsideDocker = existsSync("/.dockerenv"); - -// utils/log.ts -var logContext = new AsyncLocalStorage(); -var MAGENTA = "\x1B[35m"; -var RESET = "\x1B[0m"; -function prefixLines(message) { - const ctx = logContext.getStore(); - if (!ctx) return message; - const colored = `${MAGENTA}${ctx.prefix}${RESET} `; - return message.split("\n").map((line) => `${colored}${line}`).join("\n"); -} -function prefixPlain(name) { - const ctx = logContext.getStore(); - if (!ctx) return name; - return `${ctx.prefix} ${name}`; -} -var isRunnerDebugEnabled = () => core.isDebug(); -var isLocalDebugEnabled = () => process.env.LOG_LEVEL === "debug" || process.env.ACTIONS_STEP_DEBUG === "true"; -var isDebugEnabled = () => isLocalDebugEnabled() || isRunnerDebugEnabled(); -function ts() { - return isDebugEnabled() ? `[${(/* @__PURE__ */ new Date()).toISOString()}] ` : ""; -} -function formatArgs(args2) { - return args2.map((arg) => { - if (typeof arg === "string") return arg; - if (arg instanceof Error) return `${arg.message} -${arg.stack}`; - return JSON.stringify(arg); - }).join(" "); -} -function startGroup2(name) { - const prefixed = prefixPlain(name); - if (isGitHubActions) { - core.startGroup(prefixed); - } else { - console.group(prefixed); - } -} -function endGroup2() { - if (isGitHubActions) { - core.endGroup(); - } else { - console.groupEnd(); - } -} -function group(name, fn2) { - startGroup2(name); - fn2(); - endGroup2(); -} -function boxString(text, options) { - const { title, maxWidth = 80, indent: indent2 = "", padding = 1 } = options || {}; - const lines = text.trim().split("\n"); - const wrappedLines = []; - for (const line of lines) { - if (line.length <= maxWidth - padding * 2) { - wrappedLines.push(line); - } else { - const words = line.split(" "); - let currentLine = ""; - for (const word of words) { - const testLine = currentLine ? `${currentLine} ${word}` : word; - if (testLine.length <= maxWidth - padding * 2) { - currentLine = testLine; - } else { - if (currentLine) { - wrappedLines.push(currentLine); - currentLine = ""; - } - const maxLineLength2 = maxWidth - padding * 2; - let remainingWord = word; - while (remainingWord.length > maxLineLength2) { - wrappedLines.push(remainingWord.substring(0, maxLineLength2)); - remainingWord = remainingWord.substring(maxLineLength2); - } - currentLine = remainingWord; - } - } - if (currentLine) { - wrappedLines.push(currentLine); - } - } - } - const maxLineLength = Math.max(...wrappedLines.map((line) => line.length)); - const contentBoxWidth = maxLineLength + padding * 2; - const titleLineLength = title ? ` ${title} `.length : 0; - const boxWidth = Math.max(contentBoxWidth, titleLineLength); - let result = ""; - if (title) { - const titleLine = ` ${title} `; - const titlePadding = Math.max(0, boxWidth - titleLine.length); - result += `${indent2}\u250C${titleLine}${"\u2500".repeat(titlePadding)}\u2510 -`; - } - if (!title) { - result += `${indent2}\u250C${"\u2500".repeat(boxWidth)}\u2510 -`; - } - for (const line of wrappedLines) { - const paddedLine = line.padEnd(maxLineLength); - result += `${indent2}\u2502${" ".repeat(padding)}${paddedLine}${" ".repeat(padding)}\u2502 -`; - } - result += `${indent2}\u2514${"\u2500".repeat(boxWidth)}\u2518`; - return result; -} -function box(text, options) { - const boxContent = boxString(text, options); - core.info(prefixLines(boxContent)); -} -async function writeSummary(text) { - if (!isGitHubActions) return; - if (isInsideDocker) return; - if (!process.env.GITHUB_STEP_SUMMARY) return; - await core.summary.addRaw(text).write({ overwrite: true }); -} -function printTable(rows, options) { - const { title } = options || {}; - const tableData = rows.map( - (row) => row.map((cell) => { - if (typeof cell === "string") { - return cell; - } - return cell.data; - }) - ); - const formatted = (0, import_table.table)(tableData); - if (title) { - core.info(prefixLines(` -${title}`)); - } - core.info(prefixLines(` -${formatted} -`)); -} -function separator(length = 50) { - const separatorText = "\u2500".repeat(length); - core.info(prefixLines(separatorText)); -} -var log = { - /** Print info message */ - info: (...args2) => { - core.info(prefixLines(`${ts()}${formatArgs(args2)}`)); - }, - /** Print a warning message. Use only for warnings that should be displayed in the job summary. */ - warning: (...args2) => { - core.warning(prefixLines(`${ts()}${formatArgs(args2)}`)); - }, - /** Print an error message. Use only for errors that should be displayed in the job summary. */ - error: (...args2) => { - core.error(prefixLines(`${ts()}${formatArgs(args2)}`)); - }, - /** Print success message */ - success: (...args2) => { - core.info(prefixLines(`${ts()}\xBB ${formatArgs(args2)}`)); - }, - /** Print debug message (only when debug mode is enabled) */ - debug: (...args2) => { - if (isRunnerDebugEnabled()) { - core.debug(prefixLines(formatArgs(args2))); - return; - } - if (isLocalDebugEnabled()) { - core.info(prefixLines(`${ts()}[DEBUG] ${formatArgs(args2)}`)); - } - }, - /** Print a formatted box with text */ - box, - /** Print a formatted table using the table package */ - table: printTable, - /** Print a separator line */ - separator, - /** Start a collapsed group (GitHub Actions) or regular group (local) */ - startGroup: startGroup2, - /** End a collapsed group */ - endGroup: endGroup2, - /** Run a callback within a collapsed group */ - group, - /** Log tool call information to console with formatted output */ - toolCall: ({ toolName, input }) => { - const inputFormatted = formatJsonValue(input); - const output = inputFormatted !== "{}" ? `\xBB ${toolName}(${inputFormatted})` : `\xBB ${toolName}()`; - log.info(output.trimEnd()); - } -}; -function formatJsonValue(value2) { - const compact = JSON.stringify(value2); - return compact.length > 80 || compact.includes("\n") ? JSON.stringify(value2, null, 2) : compact; -} -function formatUsageSummary(entries) { - if (entries.length === 0) return ""; - const hasCost = entries.some((e) => e.costUsd !== void 0); - const header = hasCost ? "| Agent | Input | Output | Cache Read | Cache Write | Cost |" : "| Agent | Input | Output | Cache Read | Cache Write |"; - const fmt = (n) => n.toLocaleString("en-US"); - const separatorRow = hasCost ? "| --- | ---: | ---: | ---: | ---: | ---: |" : "| --- | ---: | ---: | ---: | ---: |"; - const rows = entries.map((e) => { - const base = `| ${e.agent} | ${fmt(e.inputTokens)} | ${fmt(e.outputTokens)} | ${fmt(e.cacheReadTokens ?? 0)} | ${fmt(e.cacheWriteTokens ?? 0)} |`; - return hasCost ? `${base} ${e.costUsd !== void 0 ? `$${e.costUsd.toFixed(4)}` : "-"} |` : base; - }); - const totalsRows = []; - if (entries.length > 1) { - const totalInput = entries.reduce((sum, e) => sum + e.inputTokens, 0); - const totalOutput = entries.reduce((sum, e) => sum + e.outputTokens, 0); - const totalCacheRead = entries.reduce((sum, e) => sum + (e.cacheReadTokens ?? 0), 0); - const totalCacheWrite = entries.reduce((sum, e) => sum + (e.cacheWriteTokens ?? 0), 0); - const totalBase = `| **Total** | **${fmt(totalInput)}** | **${fmt(totalOutput)}** | **${fmt(totalCacheRead)}** | **${fmt(totalCacheWrite)}** |`; - if (hasCost) { - const totalCost = entries.reduce((sum, e) => sum + (e.costUsd ?? 0), 0); - totalsRows.push(`${totalBase} **$${totalCost.toFixed(4)}** |`); - } else { - totalsRows.push(totalBase); - } - } - return [ - "
", - "Usage", - "", - header, - separatorRow, - ...rows, - ...totalsRows, - "", - "
" - ].join("\n"); -} - // mcp/checkout.ts import { writeFileSync } from "node:fs"; import { join as join2 } from "node:path"; -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/errors.js -var ArkError = class _ArkError extends CastableBase { - [arkKind] = "error"; - path; - data; - nodeConfig; - input; - ctx; - // TS gets confused by , so internally we just use the base type for input - constructor({ prefixPath, relativePath, ...input }, ctx) { - super(); - this.input = input; - this.ctx = ctx; - defineProperties(this, input); - const data = ctx.data; - if (input.code === "union") { - input.errors = input.errors.flatMap((innerError) => { - const flat = innerError.hasCode("union") ? innerError.errors : [innerError]; - if (!prefixPath && !relativePath) - return flat; - return flat.map((e) => e.transform((e2) => ({ - ...e2, - path: conflatenateAll(prefixPath, e2.path, relativePath) - }))); - }); - } - this.nodeConfig = ctx.config[this.code]; - const basePath = [...input.path ?? ctx.path]; - if (relativePath) - basePath.push(...relativePath); - if (prefixPath) - basePath.unshift(...prefixPath); - this.path = new ReadonlyPath(...basePath); - this.data = "data" in input ? input.data : data; - } - transform(f) { - return new _ArkError(f({ - data: this.data, - path: this.path, - ...this.input - }), this.ctx); - } - hasCode(code) { - return this.code === code; - } - get propString() { - return stringifyPath(this.path); - } - get expected() { - if (this.input.expected) - return this.input.expected; - const config3 = this.meta?.expected ?? this.nodeConfig.expected; - return typeof config3 === "function" ? config3(this.input) : config3; - } - get actual() { - if (this.input.actual) - return this.input.actual; - const config3 = this.meta?.actual ?? this.nodeConfig.actual; - return typeof config3 === "function" ? config3(this.data) : config3; - } - get problem() { - if (this.input.problem) - return this.input.problem; - const config3 = this.meta?.problem ?? this.nodeConfig.problem; - return typeof config3 === "function" ? config3(this) : config3; - } - get message() { - if (this.input.message) - return this.input.message; - const config3 = this.meta?.message ?? this.nodeConfig.message; - return typeof config3 === "function" ? config3(this) : config3; - } - get flat() { - return this.hasCode("intersection") ? [...this.errors] : [this]; - } - toJSON() { - return { - data: this.data, - path: this.path, - ...this.input, - expected: this.expected, - actual: this.actual, - problem: this.problem, - message: this.message - }; - } - toString() { - return this.message; - } - throw() { - throw this; - } -}; -var ArkErrors = class _ArkErrors extends ReadonlyArray { - [arkKind] = "errors"; - ctx; - constructor(ctx) { - super(); - this.ctx = ctx; - } - /** - * Errors by a pathString representing their location. - */ - byPath = /* @__PURE__ */ Object.create(null); - /** - * {@link byPath} flattened so that each value is an array of ArkError instances at that path. - * - * ✅ Since "intersection" errors will be flattened to their constituent `.errors`, - * they will never be directly present in this representation. - */ - get flatByPath() { - return flatMorph(this.byPath, (k, v) => [k, v.flat]); - } - /** - * {@link byPath} flattened so that each value is an array of problem strings at that path. - */ - get flatProblemsByPath() { - return flatMorph(this.byPath, (k, v) => [k, v.flat.map((e) => e.problem)]); - } - /** - * All pathStrings at which errors are present mapped to the errors occuring - * at that path or any nested path within it. - */ - byAncestorPath = /* @__PURE__ */ Object.create(null); - count = 0; - mutable = this; - /** - * Throw a TraversalError based on these errors. - */ - throw() { - throw this.toTraversalError(); - } - /** - * Converts ArkErrors to TraversalError, a subclass of `Error` suitable for throwing with nice - * formatting. - */ - toTraversalError() { - return new TraversalError(this); - } - /** - * Append an ArkError to this array, ignoring duplicates. - */ - add(error49) { - const existing = this.byPath[error49.propString]; - if (existing) { - if (error49 === existing) - return; - if (existing.hasCode("union") && existing.errors.length === 0) - return; - const errorIntersection = error49.hasCode("union") && error49.errors.length === 0 ? error49 : new ArkError({ - code: "intersection", - errors: existing.hasCode("intersection") ? [...existing.errors, error49] : [existing, error49] - }, this.ctx); - const existingIndex = this.indexOf(existing); - this.mutable[existingIndex === -1 ? this.length : existingIndex] = errorIntersection; - this.byPath[error49.propString] = errorIntersection; - this.addAncestorPaths(error49); - } else { - this.byPath[error49.propString] = error49; - this.addAncestorPaths(error49); - this.mutable.push(error49); - } - this.count++; - } - transform(f) { - const result = new _ArkErrors(this.ctx); - for (const e of this) - result.add(f(e)); - return result; - } - /** - * Add all errors from an ArkErrors instance, ignoring duplicates and - * prefixing their paths with that of the current Traversal. - */ - merge(errors) { - for (const e of errors) { - this.add(new ArkError({ ...e, path: [...this.ctx.path, ...e.path] }, this.ctx)); - } - } - /** - * @internal - */ - affectsPath(path3) { - if (this.length === 0) - return false; - return ( - // this would occur if there is an existing error at a prefix of path - // e.g. the path is ["foo", "bar"] and there is an error at ["foo"] - path3.stringifyAncestors().some((s) => s in this.byPath) || // this would occur if there is an existing error at a suffix of path - // e.g. the path is ["foo"] and there is an error at ["foo", "bar"] - path3.stringify() in this.byAncestorPath - ); - } - /** - * A human-readable summary of all errors. - */ - get summary() { - return this.toString(); - } - /** - * Alias of this ArkErrors instance for StandardSchema compatibility. - */ - get issues() { - return this; - } - toJSON() { - return [...this.map((e) => e.toJSON())]; - } - toString() { - return this.join("\n"); - } - addAncestorPaths(error49) { - for (const propString of error49.path.stringifyAncestors()) { - this.byAncestorPath[propString] = append(this.byAncestorPath[propString], error49); - } - } -}; -var TraversalError = class extends Error { - name = "TraversalError"; - constructor(errors) { - if (errors.length === 1) - super(errors.summary); - else - super("\n" + errors.map((error49) => ` \u2022 ${indent(error49)}`).join("\n")); - Object.defineProperty(this, "arkErrors", { - value: errors, - enumerable: false - }); - } -}; -var indent = (error49) => error49.toString().split("\n").join("\n "); - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/traversal.js -var Traversal = class { - /** - * #### the path being validated or morphed - * - * ✅ array indices represented as numbers - * ⚠️ mutated during traversal - use `path.slice(0)` to snapshot - * 🔗 use {@link propString} for a stringified version - */ - path = []; - /** - * #### {@link ArkErrors} that will be part of this traversal's finalized result - * - * ✅ will always be an empty array for a valid traversal - */ - errors = new ArkErrors(this); - /** - * #### the original value being traversed - */ - root; - /** - * #### configuration for this traversal - * - * ✅ options can affect traversal results and error messages - * ✅ defaults < global config < scope config - * ✅ does not include options configured on individual types - */ - config; - queuedMorphs = []; - branches = []; - seen = {}; - constructor(root, config3) { - this.root = root; - this.config = config3; - } - /** - * #### the data being validated or morphed - * - * ✅ extracted from {@link root} at {@link path} - */ - get data() { - let result = this.root; - for (const segment of this.path) - result = result?.[segment]; - return result; - } - /** - * #### a string representing {@link path} - * - * @propString - */ - get propString() { - return stringifyPath(this.path); - } - /** - * #### add an {@link ArkError} and return `false` - * - * ✅ useful for predicates like `.narrow` - */ - reject(input) { - this.error(input); - return false; - } - /** - * #### add an {@link ArkError} from a description and return `false` - * - * ✅ useful for predicates like `.narrow` - * 🔗 equivalent to {@link reject}({ expected }) - */ - mustBe(expected) { - this.error(expected); - return false; - } - error(input) { - const errCtx = typeof input === "object" ? input.code ? input : { ...input, code: "predicate" } : { code: "predicate", expected: input }; - return this.errorFromContext(errCtx); - } - /** - * #### whether {@link currentBranch} (or the traversal root, outside a union) has one or more errors - */ - hasError() { - return this.currentErrorCount !== 0; - } - get currentBranch() { - return this.branches[this.branches.length - 1]; - } - queueMorphs(morphs) { - const input = { - path: new ReadonlyPath(...this.path), - morphs - }; - if (this.currentBranch) - this.currentBranch.queuedMorphs.push(input); - else - this.queuedMorphs.push(input); - } - finalize(onFail) { - if (this.queuedMorphs.length) { - if (typeof this.root === "object" && this.root !== null && this.config.clone) - this.root = this.config.clone(this.root); - this.applyQueuedMorphs(); - } - if (this.hasError()) - return onFail ? onFail(this.errors) : this.errors; - return this.root; - } - get currentErrorCount() { - return this.currentBranch ? this.currentBranch.error ? 1 : 0 : this.errors.count; - } - get failFast() { - return this.branches.length !== 0; - } - pushBranch() { - this.branches.push({ - error: void 0, - queuedMorphs: [] - }); - } - popBranch() { - return this.branches.pop(); - } - /** - * @internal - * Convenience for casting from InternalTraversal to Traversal - * for cases where the extra methods on the external type are expected, e.g. - * a morph or predicate. - */ - get external() { - return this; - } - errorFromNodeContext(input) { - return this.errorFromContext(input); - } - errorFromContext(errCtx) { - const error49 = new ArkError(errCtx, this); - if (this.currentBranch) - this.currentBranch.error = error49; - else - this.errors.add(error49); - return error49; - } - applyQueuedMorphs() { - while (this.queuedMorphs.length) { - const queuedMorphs = this.queuedMorphs; - this.queuedMorphs = []; - for (const { path: path3, morphs } of queuedMorphs) { - if (this.errors.affectsPath(path3)) - continue; - this.applyMorphsAtPath(path3, morphs); - } - } - } - applyMorphsAtPath(path3, morphs) { - const key = path3[path3.length - 1]; - let parent; - if (key !== void 0) { - parent = this.root; - for (let pathIndex = 0; pathIndex < path3.length - 1; pathIndex++) - parent = parent[path3[pathIndex]]; - } - for (const morph of morphs) { - this.path = [...path3]; - const morphIsNode = isNode(morph); - const result = morph(parent === void 0 ? this.root : parent[key], this); - if (result instanceof ArkError) { - if (!this.errors.includes(result)) - this.errors.add(result); - break; - } - if (result instanceof ArkErrors) { - if (!morphIsNode) { - this.errors.merge(result); - } - this.queuedMorphs = []; - break; - } - if (parent === void 0) - this.root = result; - else - parent[key] = result; - this.applyQueuedMorphs(); - } - } -}; -var traverseKey = (key, fn2, ctx) => { - if (!ctx) - return fn2(); - ctx.path.push(key); - const result = fn2(); - ctx.path.pop(); - return result; -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/node.js -var BaseNode = class extends Callable { - attachments; - $; - onFail; - includesTransform; - includesContextualPredicate; - isCyclic; - allowsRequiresContext; - rootApplyStrategy; - contextFreeMorph; - rootApply; - referencesById; - shallowReferences; - flatRefs; - flatMorphs; - allows; - get shallowMorphs() { - return []; - } - constructor(attachments, $2) { - super((data, pipedFromCtx, onFail = this.onFail) => { - if (pipedFromCtx) { - this.traverseApply(data, pipedFromCtx); - return pipedFromCtx.hasError() ? pipedFromCtx.errors : pipedFromCtx.data; - } - return this.rootApply(data, onFail); - }, { attach: attachments }); - this.attachments = attachments; - this.$ = $2; - this.onFail = this.meta.onFail ?? this.$.resolvedConfig.onFail; - this.includesTransform = this.hasKind("morph") || this.hasKind("structure") && this.structuralMorph !== void 0 || this.hasKind("sequence") && this.inner.defaultables !== void 0; - this.includesContextualPredicate = this.hasKind("predicate") && this.inner.predicate.length !== 1; - this.isCyclic = this.kind === "alias"; - this.referencesById = { [this.id]: this }; - this.shallowReferences = this.hasKind("structure") ? [this, ...this.children] : this.children.reduce((acc, child) => appendUniqueNodes(acc, child.shallowReferences), [this]); - const isStructural = this.isStructural(); - this.flatRefs = []; - this.flatMorphs = []; - for (let i = 0; i < this.children.length; i++) { - this.includesTransform ||= this.children[i].includesTransform; - this.includesContextualPredicate ||= this.children[i].includesContextualPredicate; - this.isCyclic ||= this.children[i].isCyclic; - if (!isStructural) { - const childFlatRefs = this.children[i].flatRefs; - for (let j = 0; j < childFlatRefs.length; j++) { - const childRef = childFlatRefs[j]; - if (!this.flatRefs.some((existing) => flatRefsAreEqual(existing, childRef))) { - this.flatRefs.push(childRef); - for (const branch of childRef.node.branches) { - if (branch.hasKind("morph") || branch.hasKind("intersection") && branch.structure?.structuralMorph !== void 0) { - this.flatMorphs.push({ - path: childRef.path, - propString: childRef.propString, - node: branch - }); - } - } - } - } - } - Object.assign(this.referencesById, this.children[i].referencesById); - } - this.flatRefs.sort((l, r) => l.path.length > r.path.length ? 1 : l.path.length < r.path.length ? -1 : l.propString > r.propString ? 1 : l.propString < r.propString ? -1 : l.node.expression < r.node.expression ? -1 : 1); - this.allowsRequiresContext = this.includesContextualPredicate || this.isCyclic; - this.rootApplyStrategy = !this.allowsRequiresContext && this.flatMorphs.length === 0 ? this.shallowMorphs.length === 0 ? "allows" : this.shallowMorphs.every((morph) => morph.length === 1 || morph.name === "$arkStructuralMorph") ? this.hasKind("union") ? ( - // multiple morphs not yet supported for optimistic compilation - this.branches.some((branch) => branch.shallowMorphs.length > 1) ? "contextual" : "branchedOptimistic" - ) : this.shallowMorphs.length > 1 ? "contextual" : "optimistic" : "contextual" : "contextual"; - this.rootApply = this.createRootApply(); - this.allows = this.allowsRequiresContext ? (data) => this.traverseAllows(data, new Traversal(data, this.$.resolvedConfig)) : (data) => this.traverseAllows(data); - } - createRootApply() { - switch (this.rootApplyStrategy) { - case "allows": - return (data, onFail) => { - if (this.allows(data)) - return data; - const ctx = new Traversal(data, this.$.resolvedConfig); - this.traverseApply(data, ctx); - return ctx.finalize(onFail); - }; - case "contextual": - return (data, onFail) => { - const ctx = new Traversal(data, this.$.resolvedConfig); - this.traverseApply(data, ctx); - return ctx.finalize(onFail); - }; - case "optimistic": - this.contextFreeMorph = this.shallowMorphs[0]; - const clone3 = this.$.resolvedConfig.clone; - return (data, onFail) => { - if (this.allows(data)) { - return this.contextFreeMorph(clone3 && (typeof data === "object" && data !== null || typeof data === "function") ? clone3(data) : data); - } - const ctx = new Traversal(data, this.$.resolvedConfig); - this.traverseApply(data, ctx); - return ctx.finalize(onFail); - }; - case "branchedOptimistic": - return this.createBranchedOptimisticRootApply(); - default: - this.rootApplyStrategy; - return throwInternalError(`Unexpected rootApplyStrategy ${this.rootApplyStrategy}`); - } - } - compiledMeta = compileMeta(this.metaJson); - cacheGetter(name, value2) { - Object.defineProperty(this, name, { value: value2 }); - return value2; - } - get description() { - return this.cacheGetter("description", this.meta?.description ?? this.$.resolvedConfig[this.kind].description(this)); - } - // we don't cache this currently since it can be updated once a scope finishes - // resolving cyclic references, although it may be possible to ensure it is cached safely - get references() { - return Object.values(this.referencesById); - } - precedence = precedenceOfKind(this.kind); - precompilation; - // defined as an arrow function since it is often detached, e.g. when passing to tRPC - // otherwise, would run into issues with this binding - assert = (data, pipedFromCtx) => this(data, pipedFromCtx, (errors) => errors.throw()); - traverse(data, pipedFromCtx) { - return this(data, pipedFromCtx, null); - } - /** rawIn should be used internally instead */ - get in() { - return this.cacheGetter("in", this.rawIn.isRoot() ? this.$.finalize(this.rawIn) : this.rawIn); - } - get rawIn() { - return this.cacheGetter("rawIn", this.getIo("in")); - } - /** rawOut should be used internally instead */ - get out() { - return this.cacheGetter("out", this.rawOut.isRoot() ? this.$.finalize(this.rawOut) : this.rawOut); - } - get rawOut() { - return this.cacheGetter("rawOut", this.getIo("out")); - } - // Should be refactored to use transform - // https://github.com/arktypeio/arktype/issues/1020 - getIo(ioKind) { - if (!this.includesTransform) - return this; - const ioInner = {}; - for (const [k, v] of this.innerEntries) { - const keySchemaImplementation = this.impl.keys[k]; - if (keySchemaImplementation.reduceIo) - keySchemaImplementation.reduceIo(ioKind, ioInner, v); - else if (keySchemaImplementation.child) { - const childValue = v; - ioInner[k] = isArray(childValue) ? childValue.map((child) => ioKind === "in" ? child.rawIn : child.rawOut) : ioKind === "in" ? childValue.rawIn : childValue.rawOut; - } else - ioInner[k] = v; - } - return this.$.node(this.kind, ioInner); - } - toJSON() { - return this.json; - } - toString() { - return `Type<${this.expression}>`; - } - equals(r) { - const rNode = isNode(r) ? r : this.$.parseDefinition(r); - return this.innerHash === rNode.innerHash; - } - ifEquals(r) { - return this.equals(r) ? this : void 0; - } - hasKind(kind) { - return this.kind === kind; - } - assertHasKind(kind) { - if (this.kind !== kind) - throwError(`${this.kind} node was not of asserted kind ${kind}`); - return this; - } - hasKindIn(...kinds) { - return kinds.includes(this.kind); - } - assertHasKindIn(...kinds) { - if (!includes(kinds, this.kind)) - throwError(`${this.kind} node was not one of asserted kinds ${kinds}`); - return this; - } - isBasis() { - return includes(basisKinds, this.kind); - } - isConstraint() { - return includes(constraintKinds, this.kind); - } - isStructural() { - return includes(structuralKinds, this.kind); - } - isRefinement() { - return includes(refinementKinds, this.kind); - } - isRoot() { - return includes(rootKinds, this.kind); - } - isUnknown() { - return this.hasKind("intersection") && this.children.length === 0; - } - isNever() { - return this.hasKind("union") && this.children.length === 0; - } - hasUnit(value2) { - return this.hasKind("unit") && this.allows(value2); - } - hasOpenIntersection() { - return this.impl.intersectionIsOpen; - } - get nestableExpression() { - return this.expression; - } - select(selector) { - const normalized = NodeSelector.normalize(selector); - return this._select(normalized); - } - _select(selector) { - let nodes = NodeSelector.applyBoundary[selector.boundary ?? "references"](this); - if (selector.kind) - nodes = nodes.filter((n) => n.kind === selector.kind); - if (selector.where) - nodes = nodes.filter(selector.where); - return NodeSelector.applyMethod[selector.method ?? "filter"](nodes, this, selector); - } - transform(mapper, opts) { - return this._transform(mapper, this._createTransformContext(opts)); - } - _createTransformContext(opts) { - return { - root: this, - selected: void 0, - seen: {}, - path: [], - parseOptions: { - prereduced: opts?.prereduced ?? false - }, - undeclaredKeyHandling: void 0, - ...opts - }; - } - _transform(mapper, ctx) { - const $2 = ctx.bindScope ?? this.$; - if (ctx.seen[this.id]) - return this.$.lazilyResolve(ctx.seen[this.id]); - if (ctx.shouldTransform?.(this, ctx) === false) - return this; - let transformedNode; - ctx.seen[this.id] = () => transformedNode; - if (this.hasKind("structure") && this.undeclared !== ctx.undeclaredKeyHandling) { - ctx = { - ...ctx, - undeclaredKeyHandling: this.undeclared - }; - } - const innerWithTransformedChildren = flatMorph(this.inner, (k, v) => { - if (!this.impl.keys[k].child) - return [k, v]; - const children = v; - if (!isArray(children)) { - const transformed2 = children._transform(mapper, ctx); - return transformed2 ? [k, transformed2] : []; - } - if (children.length === 0) - return [k, v]; - const transformed = children.flatMap((n) => { - const transformedChild = n._transform(mapper, ctx); - return transformedChild ?? []; - }); - return transformed.length ? [k, transformed] : []; - }); - delete ctx.seen[this.id]; - const innerWithMeta = Object.assign(innerWithTransformedChildren, { - meta: this.meta - }); - const transformedInner = ctx.selected && !ctx.selected.includes(this) ? innerWithMeta : mapper(this.kind, innerWithMeta, ctx); - if (transformedInner === null) - return null; - if (isNode(transformedInner)) - return transformedNode = transformedInner; - const transformedKeys = Object.keys(transformedInner); - const hasNoTypedKeys = transformedKeys.length === 0 || transformedKeys.length === 1 && transformedKeys[0] === "meta"; - if (hasNoTypedKeys && // if inner was previously an empty object (e.g. unknown) ensure it is not pruned - !isEmptyObject(this.inner)) - return null; - if ((this.kind === "required" || this.kind === "optional" || this.kind === "index") && !("value" in transformedInner)) { - return ctx.undeclaredKeyHandling ? { ...transformedInner, value: $ark.intrinsic.unknown } : null; - } - if (this.kind === "morph") { - ; - transformedInner.in ??= $ark.intrinsic.unknown; - } - return transformedNode = $2.node(this.kind, transformedInner, ctx.parseOptions); - } - configureReferences(meta3, selector = "references") { - const normalized = NodeSelector.normalize(selector); - const mapper = typeof meta3 === "string" ? (kind, inner) => ({ - ...inner, - meta: { ...inner.meta, description: meta3 } - }) : typeof meta3 === "function" ? (kind, inner) => ({ ...inner, meta: meta3(inner.meta) }) : (kind, inner) => ({ - ...inner, - meta: { ...inner.meta, ...meta3 } - }); - if (normalized.boundary === "self") { - return this.$.node(this.kind, mapper(this.kind, { ...this.inner, meta: this.meta })); - } - const rawSelected = this._select(normalized); - const selected = rawSelected && liftArray(rawSelected); - const shouldTransform = normalized.boundary === "child" ? (node2, ctx) => ctx.root.children.includes(node2) : normalized.boundary === "shallow" ? (node2) => node2.kind !== "structure" : () => true; - return this.$.finalize(this.transform(mapper, { - shouldTransform, - selected - })); - } -}; -var NodeSelector = { - applyBoundary: { - self: (node2) => [node2], - child: (node2) => [...node2.children], - shallow: (node2) => [...node2.shallowReferences], - references: (node2) => [...node2.references] - }, - applyMethod: { - filter: (nodes) => nodes, - assertFilter: (nodes, from, selector) => { - if (nodes.length === 0) - throwError(writeSelectAssertionMessage(from, selector)); - return nodes; - }, - find: (nodes) => nodes[0], - assertFind: (nodes, from, selector) => { - if (nodes.length === 0) - throwError(writeSelectAssertionMessage(from, selector)); - return nodes[0]; - } - }, - normalize: (selector) => typeof selector === "function" ? { boundary: "references", method: "filter", where: selector } : typeof selector === "string" ? isKeyOf(selector, NodeSelector.applyBoundary) ? { method: "filter", boundary: selector } : { boundary: "references", method: "filter", kind: selector } : { boundary: "references", method: "filter", ...selector } -}; -var writeSelectAssertionMessage = (from, selector) => `${from} had no references matching ${printable(selector)}.`; -var typePathToPropString = (path3) => stringifyPath(path3, { - stringifyNonKey: (node2) => node2.expression -}); -var referenceMatcher = /"(\$ark\.[^"]+)"/g; -var compileMeta = (metaJson) => JSON.stringify(metaJson).replace(referenceMatcher, "$1"); -var flatRef = (path3, node2) => ({ - path: path3, - node: node2, - propString: typePathToPropString(path3) -}); -var flatRefsAreEqual = (l, r) => l.propString === r.propString && l.node.equals(r.node); -var appendUniqueFlatRefs = (existing, refs) => appendUnique(existing, refs, { - isEqual: flatRefsAreEqual -}); -var appendUniqueNodes = (existing, refs) => appendUnique(existing, refs, { - isEqual: (l, r) => l.equals(r) -}); - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/disjoint.js -var Disjoint = class _Disjoint extends Array { - static init(kind, l, r, ctx) { - return new _Disjoint({ - kind, - l, - r, - path: ctx?.path ?? [], - optional: ctx?.optional ?? false - }); - } - add(kind, l, r, ctx) { - this.push({ - kind, - l, - r, - path: ctx?.path ?? [], - optional: ctx?.optional ?? false - }); - return this; - } - get summary() { - return this.describeReasons(); - } - describeReasons() { - if (this.length === 1) { - const { path: path3, l, r } = this[0]; - const pathString = stringifyPath(path3); - return writeUnsatisfiableExpressionError(`Intersection${pathString && ` at ${pathString}`} of ${describeReasons(l, r)}`); - } - return `The following intersections result in unsatisfiable types: -\u2022 ${this.map(({ path: path3, l, r }) => `${path3}: ${describeReasons(l, r)}`).join("\n\u2022 ")}`; - } - throw() { - return throwParseError(this.describeReasons()); - } - invert() { - const result = this.map((entry) => ({ - ...entry, - l: entry.r, - r: entry.l - })); - if (!(result instanceof _Disjoint)) - return new _Disjoint(...result); - return result; - } - withPrefixKey(key, kind) { - return this.map((entry) => ({ - ...entry, - path: [key, ...entry.path], - optional: entry.optional || kind === "optional" - })); - } - toNeverIfDisjoint() { - return $ark.intrinsic.never; - } -}; -var describeReasons = (l, r) => `${describeReason(l)} and ${describeReason(r)}`; -var describeReason = (value2) => isNode(value2) ? value2.expression : isArray(value2) ? value2.map(describeReason).join(" | ") || "never" : String(value2); -var writeUnsatisfiableExpressionError = (expression) => `${expression} results in an unsatisfiable type`; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/shared/intersections.js -var intersectionCache = {}; -var intersectNodesRoot = (l, r, $2) => intersectOrPipeNodes(l, r, { - $: $2, - invert: false, - pipe: false -}); -var pipeNodesRoot = (l, r, $2) => intersectOrPipeNodes(l, r, { - $: $2, - invert: false, - pipe: true -}); -var intersectOrPipeNodes = ((l, r, ctx) => { - const operator = ctx.pipe ? "|>" : "&"; - const lrCacheKey = `${l.hash}${operator}${r.hash}`; - if (intersectionCache[lrCacheKey] !== void 0) - return intersectionCache[lrCacheKey]; - if (!ctx.pipe) { - const rlCacheKey = `${r.hash}${operator}${l.hash}`; - if (intersectionCache[rlCacheKey] !== void 0) { - const rlResult = intersectionCache[rlCacheKey]; - const lrResult = rlResult instanceof Disjoint ? rlResult.invert() : rlResult; - intersectionCache[lrCacheKey] = lrResult; - return lrResult; - } - } - const isPureIntersection = !ctx.pipe || !l.includesTransform && !r.includesTransform; - if (isPureIntersection && l.equals(r)) - return l; - let result = isPureIntersection ? _intersectNodes(l, r, ctx) : l.hasKindIn(...rootKinds) ? ( - // if l is a RootNode, r will be as well - _pipeNodes(l, r, ctx) - ) : _intersectNodes(l, r, ctx); - if (isNode(result)) { - if (l.equals(result)) - result = l; - else if (r.equals(result)) - result = r; - } - intersectionCache[lrCacheKey] = result; - return result; -}); -var _intersectNodes = (l, r, ctx) => { - const leftmostKind = l.precedence < r.precedence ? l.kind : r.kind; - const implementation23 = l.impl.intersections[r.kind] ?? r.impl.intersections[l.kind]; - if (implementation23 === void 0) { - return null; - } else if (leftmostKind === l.kind) - return implementation23(l, r, ctx); - else { - let result = implementation23(r, l, { ...ctx, invert: !ctx.invert }); - if (result instanceof Disjoint) - result = result.invert(); - return result; - } -}; -var _pipeNodes = (l, r, ctx) => l.includesTransform || r.includesTransform ? ctx.invert ? pipeMorphed(r, l, ctx) : pipeMorphed(l, r, ctx) : _intersectNodes(l, r, ctx); -var pipeMorphed = (from, to, ctx) => from.distribute((fromBranch) => _pipeMorphed(fromBranch, to, ctx), (results) => { - const viableBranches = results.filter(isNode); - if (viableBranches.length === 0) - return Disjoint.init("union", from.branches, to.branches); - if (viableBranches.length < from.branches.length || !from.branches.every((branch, i) => branch.rawIn.equals(viableBranches[i].rawIn))) - return ctx.$.parseSchema(viableBranches); - let meta3; - if (viableBranches.length === 1) { - const onlyBranch = viableBranches[0]; - if (!meta3) - return onlyBranch; - return ctx.$.node("morph", { - ...onlyBranch.inner, - in: onlyBranch.rawIn.configure(meta3, "self") - }); - } - const schema2 = { - branches: viableBranches - }; - if (meta3) - schema2.meta = meta3; - return ctx.$.parseSchema(schema2); -}); -var _pipeMorphed = (from, to, ctx) => { - const fromIsMorph = from.hasKind("morph"); - if (fromIsMorph) { - const morphs = [...from.morphs]; - if (from.lastMorphIfNode) { - const outIntersection = intersectOrPipeNodes(from.lastMorphIfNode, to, ctx); - if (outIntersection instanceof Disjoint) - return outIntersection; - morphs[morphs.length - 1] = outIntersection; - } else - morphs.push(to); - return ctx.$.node("morph", { - morphs, - in: from.inner.in - }); - } - if (to.hasKind("morph")) { - const inTersection = intersectOrPipeNodes(from, to.rawIn, ctx); - if (inTersection instanceof Disjoint) - return inTersection; - return ctx.$.node("morph", { - morphs: [to], - in: inTersection - }); - } - return ctx.$.node("morph", { - morphs: [to], - in: from - }); -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/constraint.js -var BaseConstraint = class extends BaseNode { - constructor(attachments, $2) { - super(attachments, $2); - Object.defineProperty(this, arkKind, { - value: "constraint", - enumerable: false - }); - } - impliedSiblings; - intersect(r) { - return intersectNodesRoot(this, r, this.$); - } -}; -var InternalPrimitiveConstraint = class extends BaseConstraint { - traverseApply = (data, ctx) => { - if (!this.traverseAllows(data, ctx)) - ctx.errorFromNodeContext(this.errorContext); - }; - compile(js) { - if (js.traversalKind === "Allows") - js.return(this.compiledCondition); - else { - js.if(this.compiledNegation, () => js.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`)); - } - } - get errorContext() { - return { - code: this.kind, - description: this.description, - meta: this.meta, - ...this.inner - }; - } - get compiledErrorContext() { - return compileObjectLiteral(this.errorContext); - } -}; -var constraintKeyParser = (kind) => (schema2, ctx) => { - if (isArray(schema2)) { - if (schema2.length === 0) { - return; - } - const nodes = schema2.map((schema3) => ctx.$.node(kind, schema3)); - if (kind === "predicate") - return nodes; - return nodes.sort((l, r) => l.hash < r.hash ? -1 : 1); - } - const child = ctx.$.node(kind, schema2); - return child.hasOpenIntersection() ? [child] : child; -}; -var intersectConstraints = (s) => { - const head = s.r.shift(); - if (!head) { - let result = s.l.length === 0 && s.kind === "structure" ? $ark.intrinsic.unknown.internal : s.ctx.$.node(s.kind, Object.assign(s.baseInner, unflattenConstraints(s.l)), { prereduced: true }); - for (const root of s.roots) { - if (result instanceof Disjoint) - return result; - result = intersectOrPipeNodes(root, result, s.ctx); - } - return result; - } - let matched = false; - for (let i = 0; i < s.l.length; i++) { - const result = intersectOrPipeNodes(s.l[i], head, s.ctx); - if (result === null) - continue; - if (result instanceof Disjoint) - return result; - if (result.isRoot()) { - s.roots.push(result); - s.l.splice(i); - return intersectConstraints(s); - } - if (!matched) { - s.l[i] = result; - matched = true; - } else if (!s.l.includes(result)) { - return throwInternalError(`Unexpectedly encountered multiple distinct intersection results for refinement ${head}`); - } - } - if (!matched) - s.l.push(head); - if (s.kind === "intersection") { - if (head.impliedSiblings) - for (const node2 of head.impliedSiblings) - appendUnique(s.r, node2); - } - return intersectConstraints(s); -}; -var flattenConstraints = (inner) => { - const result = Object.entries(inner).flatMap(([k, v]) => k in constraintKeys ? v : []).sort((l, r) => l.precedence < r.precedence ? -1 : l.precedence > r.precedence ? 1 : l.kind === "predicate" && r.kind === "predicate" ? 0 : l.hash < r.hash ? -1 : 1); - return result; -}; -var unflattenConstraints = (constraints) => { - const inner = {}; - for (const constraint of constraints) { - if (constraint.hasOpenIntersection()) { - inner[constraint.kind] = append(inner[constraint.kind], constraint); - } else { - if (inner[constraint.kind]) { - return throwInternalError(`Unexpected intersection of closed refinements of kind ${constraint.kind}`); - } - inner[constraint.kind] = constraint; - } - } - return inner; -}; -var throwInvalidOperandError = (...args2) => throwParseError(writeInvalidOperandMessage(...args2)); -var writeInvalidOperandMessage = (kind, expected, actual) => { - const actualDescription = actual.hasKind("morph") ? "a morph" : actual.isUnknown() ? "unknown" : actual.exclude(expected).defaultShortDescription; - return `${capitalize(kind)} operand must be ${expected.description} (was ${actualDescription})`; -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/generic.js -var parseGeneric = (paramDefs, bodyDef, $2) => new GenericRoot(paramDefs, bodyDef, $2, $2, null); -var LazyGenericBody = class extends Callable { -}; -var GenericRoot = class extends Callable { - [arkKind] = "generic"; - paramDefs; - bodyDef; - $; - arg$; - baseInstantiation; - hkt; - description; - constructor(paramDefs, bodyDef, $2, arg$, hkt) { - super((...args2) => { - const argNodes = flatMorph(this.names, (i, name) => { - const arg = this.arg$.parse(args2[i]); - if (!arg.extends(this.constraints[i])) { - throwParseError(writeUnsatisfiedParameterConstraintMessage(name, this.constraints[i].expression, arg.expression)); - } - return [name, arg]; - }); - if (this.defIsLazy()) { - const def = this.bodyDef(argNodes); - return this.$.parse(def); - } - return this.$.parse(bodyDef, { args: argNodes }); - }); - this.paramDefs = paramDefs; - this.bodyDef = bodyDef; - this.$ = $2; - this.arg$ = arg$; - this.hkt = hkt; - this.description = hkt ? new hkt().description ?? `a generic type for ${hkt.constructor.name}` : "a generic type"; - this.baseInstantiation = this(...this.constraints); - } - defIsLazy() { - return this.bodyDef instanceof LazyGenericBody; - } - cacheGetter(name, value2) { - Object.defineProperty(this, name, { value: value2 }); - return value2; - } - get json() { - return this.cacheGetter("json", { - params: this.params.map((param) => param[1].isUnknown() ? param[0] : [param[0], param[1].json]), - body: snapshot(this.bodyDef) - }); - } - get params() { - return this.cacheGetter("params", this.paramDefs.map((param) => typeof param === "string" ? [param, $ark.intrinsic.unknown] : [param[0], this.$.parse(param[1])])); - } - get names() { - return this.cacheGetter("names", this.params.map((e) => e[0])); - } - get constraints() { - return this.cacheGetter("constraints", this.params.map((e) => e[1])); - } - get internal() { - return this; - } - get referencesById() { - return this.baseInstantiation.internal.referencesById; - } - get references() { - return this.baseInstantiation.internal.references; - } -}; -var writeUnsatisfiedParameterConstraintMessage = (name, constraint, arg) => `${name} must be assignable to ${constraint} (was ${arg})`; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/predicate.js -var implementation = implementNode({ - kind: "predicate", - hasAssociatedError: true, - collapsibleKey: "predicate", - keys: { - predicate: {} - }, - normalize: (schema2) => typeof schema2 === "function" ? { predicate: schema2 } : schema2, - defaults: { - description: (node2) => `valid according to ${node2.predicate.name || "an anonymous predicate"}` - }, - intersectionIsOpen: true, - intersections: { - // as long as the narrows in l and r are individually safe to check - // in the order they're specified, checking them in the order - // resulting from this intersection should also be safe. - predicate: () => null - } -}); -var PredicateNode = class extends BaseConstraint { - serializedPredicate = registeredReference(this.predicate); - compiledCondition = `${this.serializedPredicate}(data, ctx)`; - compiledNegation = `!${this.compiledCondition}`; - impliedBasis = null; - expression = this.serializedPredicate; - traverseAllows = this.predicate; - errorContext = { - code: "predicate", - description: this.description, - meta: this.meta - }; - compiledErrorContext = compileObjectLiteral(this.errorContext); - traverseApply = (data, ctx) => { - const errorCount = ctx.currentErrorCount; - if (!this.predicate(data, ctx.external) && ctx.currentErrorCount === errorCount) - ctx.errorFromNodeContext(this.errorContext); - }; - compile(js) { - if (js.traversalKind === "Allows") { - js.return(this.compiledCondition); - return; - } - js.initializeErrorCount(); - js.if( - // only add the default error if the predicate didn't add one itself - `${this.compiledNegation} && ctx.currentErrorCount === errorCount`, - () => js.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`) - ); - } - reduceJsonSchema(base, ctx) { - return ctx.fallback.predicate({ - code: "predicate", - base, - predicate: this.predicate - }); - } -}; -var Predicate = { - implementation, - Node: PredicateNode -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/divisor.js -var implementation2 = implementNode({ - kind: "divisor", - collapsibleKey: "rule", - keys: { - rule: { - parse: (divisor) => Number.isInteger(divisor) ? divisor : throwParseError(writeNonIntegerDivisorMessage(divisor)) - } - }, - normalize: (schema2) => typeof schema2 === "number" ? { rule: schema2 } : schema2, - hasAssociatedError: true, - defaults: { - description: (node2) => node2.rule === 1 ? "an integer" : node2.rule === 2 ? "even" : `a multiple of ${node2.rule}` - }, - intersections: { - divisor: (l, r, ctx) => ctx.$.node("divisor", { - rule: Math.abs(l.rule * r.rule / greatestCommonDivisor(l.rule, r.rule)) - }) - }, - obviatesBasisDescription: true -}); -var DivisorNode = class extends InternalPrimitiveConstraint { - traverseAllows = (data) => data % this.rule === 0; - compiledCondition = `data % ${this.rule} === 0`; - compiledNegation = `data % ${this.rule} !== 0`; - impliedBasis = $ark.intrinsic.number.internal; - expression = `% ${this.rule}`; - reduceJsonSchema(schema2) { - schema2.type = "integer"; - if (this.rule === 1) - return schema2; - schema2.multipleOf = this.rule; - return schema2; - } -}; -var Divisor = { - implementation: implementation2, - Node: DivisorNode -}; -var writeNonIntegerDivisorMessage = (divisor) => `divisor must be an integer (was ${divisor})`; -var greatestCommonDivisor = (l, r) => { - let previous; - let greatestCommonDivisor2 = l; - let current = r; - while (current !== 0) { - previous = current; - current = greatestCommonDivisor2 % current; - greatestCommonDivisor2 = previous; - } - return greatestCommonDivisor2; -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/range.js -var BaseRange = class extends InternalPrimitiveConstraint { - boundOperandKind = operandKindsByBoundKind[this.kind]; - compiledActual = this.boundOperandKind === "value" ? `data` : this.boundOperandKind === "length" ? `data.length` : `data.valueOf()`; - comparator = compileComparator(this.kind, this.exclusive); - numericLimit = this.rule.valueOf(); - expression = `${this.comparator} ${this.rule}`; - compiledCondition = `${this.compiledActual} ${this.comparator} ${this.numericLimit}`; - compiledNegation = `${this.compiledActual} ${negatedComparators[this.comparator]} ${this.numericLimit}`; - // we need to compute stringLimit before errorContext, which references it - // transitively through description for date bounds - stringLimit = this.boundOperandKind === "date" ? dateLimitToString(this.numericLimit) : `${this.numericLimit}`; - limitKind = this.comparator["0"] === "<" ? "upper" : "lower"; - isStricterThan(r) { - const thisLimitIsStricter = this.limitKind === "upper" ? this.numericLimit < r.numericLimit : this.numericLimit > r.numericLimit; - return thisLimitIsStricter || this.numericLimit === r.numericLimit && this.exclusive === true && !r.exclusive; - } - overlapsRange(r) { - if (this.isStricterThan(r)) - return false; - if (this.numericLimit === r.numericLimit && (this.exclusive || r.exclusive)) - return false; - return true; - } - overlapIsUnit(r) { - return this.numericLimit === r.numericLimit && !this.exclusive && !r.exclusive; - } -}; -var negatedComparators = { - "<": ">=", - "<=": ">", - ">": "<=", - ">=": "<" -}; -var boundKindPairsByLower = { - min: "max", - minLength: "maxLength", - after: "before" -}; -var parseExclusiveKey = { - // omit key with value false since it is the default - parse: (flag) => flag || void 0 -}; -var createLengthSchemaNormalizer = (kind) => (schema2) => { - if (typeof schema2 === "number") - return { rule: schema2 }; - const { exclusive, ...normalized } = schema2; - return exclusive ? { - ...normalized, - rule: kind === "minLength" ? normalized.rule + 1 : normalized.rule - 1 - } : normalized; -}; -var createDateSchemaNormalizer = (kind) => (schema2) => { - if (typeof schema2 === "number" || typeof schema2 === "string" || schema2 instanceof Date) - return { rule: schema2 }; - const { exclusive, ...normalized } = schema2; - if (!exclusive) - return normalized; - const numericLimit = typeof normalized.rule === "number" ? normalized.rule : typeof normalized.rule === "string" ? new Date(normalized.rule).valueOf() : normalized.rule.valueOf(); - return exclusive ? { - ...normalized, - rule: kind === "after" ? numericLimit + 1 : numericLimit - 1 - } : normalized; -}; -var parseDateLimit = (limit) => typeof limit === "string" || typeof limit === "number" ? new Date(limit) : limit; -var writeInvalidLengthBoundMessage = (kind, limit) => `${kind} bound must be a positive integer (was ${limit})`; -var createLengthRuleParser = (kind) => (limit) => { - if (!Number.isInteger(limit) || limit < 0) - throwParseError(writeInvalidLengthBoundMessage(kind, limit)); - return limit; -}; -var operandKindsByBoundKind = { - min: "value", - max: "value", - minLength: "length", - maxLength: "length", - after: "date", - before: "date" -}; -var compileComparator = (kind, exclusive) => `${isKeyOf(kind, boundKindPairsByLower) ? ">" : "<"}${exclusive ? "" : "="}`; -var dateLimitToString = (limit) => typeof limit === "string" ? limit : new Date(limit).toLocaleString(); -var writeUnboundableMessage = (root) => `Bounded expression ${root} must be exactly one of number, string, Array, or Date`; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/after.js -var implementation3 = implementNode({ - kind: "after", - collapsibleKey: "rule", - hasAssociatedError: true, - keys: { - rule: { - parse: parseDateLimit, - serialize: (schema2) => schema2.toISOString() - } - }, - normalize: createDateSchemaNormalizer("after"), - defaults: { - description: (node2) => `${node2.collapsibleLimitString} or later`, - actual: describeCollapsibleDate - }, - intersections: { - after: (l, r) => l.isStricterThan(r) ? l : r - } -}); -var AfterNode = class extends BaseRange { - impliedBasis = $ark.intrinsic.Date.internal; - collapsibleLimitString = describeCollapsibleDate(this.rule); - traverseAllows = (data) => data >= this.rule; - reduceJsonSchema(base, ctx) { - return ctx.fallback.date({ code: "date", base, after: this.rule }); - } -}; -var After = { - implementation: implementation3, - Node: AfterNode -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/before.js -var implementation4 = implementNode({ - kind: "before", - collapsibleKey: "rule", - hasAssociatedError: true, - keys: { - rule: { - parse: parseDateLimit, - serialize: (schema2) => schema2.toISOString() - } - }, - normalize: createDateSchemaNormalizer("before"), - defaults: { - description: (node2) => `${node2.collapsibleLimitString} or earlier`, - actual: describeCollapsibleDate - }, - intersections: { - before: (l, r) => l.isStricterThan(r) ? l : r, - after: (before, after, ctx) => before.overlapsRange(after) ? before.overlapIsUnit(after) ? ctx.$.node("unit", { unit: before.rule }) : null : Disjoint.init("range", before, after) - } -}); -var BeforeNode = class extends BaseRange { - collapsibleLimitString = describeCollapsibleDate(this.rule); - traverseAllows = (data) => data <= this.rule; - impliedBasis = $ark.intrinsic.Date.internal; - reduceJsonSchema(base, ctx) { - return ctx.fallback.date({ code: "date", base, before: this.rule }); - } -}; -var Before = { - implementation: implementation4, - Node: BeforeNode -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/exactLength.js -var implementation5 = implementNode({ - kind: "exactLength", - collapsibleKey: "rule", - keys: { - rule: { - parse: createLengthRuleParser("exactLength") - } - }, - normalize: (schema2) => typeof schema2 === "number" ? { rule: schema2 } : schema2, - hasAssociatedError: true, - defaults: { - description: (node2) => `exactly length ${node2.rule}`, - actual: (data) => `${data.length}` - }, - intersections: { - exactLength: (l, r, ctx) => Disjoint.init("unit", ctx.$.node("unit", { unit: l.rule }), ctx.$.node("unit", { unit: r.rule }), { path: ["length"] }), - minLength: (exactLength, minLength) => exactLength.rule >= minLength.rule ? exactLength : Disjoint.init("range", exactLength, minLength), - maxLength: (exactLength, maxLength) => exactLength.rule <= maxLength.rule ? exactLength : Disjoint.init("range", exactLength, maxLength) - } -}); -var ExactLengthNode = class extends InternalPrimitiveConstraint { - traverseAllows = (data) => data.length === this.rule; - compiledCondition = `data.length === ${this.rule}`; - compiledNegation = `data.length !== ${this.rule}`; - impliedBasis = $ark.intrinsic.lengthBoundable.internal; - expression = `== ${this.rule}`; - reduceJsonSchema(schema2) { - switch (schema2.type) { - case "string": - schema2.minLength = this.rule; - schema2.maxLength = this.rule; - return schema2; - case "array": - schema2.minItems = this.rule; - schema2.maxItems = this.rule; - return schema2; - default: - return ToJsonSchema.throwInternalOperandError("exactLength", schema2); - } - } -}; -var ExactLength = { - implementation: implementation5, - Node: ExactLengthNode -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/max.js -var implementation6 = implementNode({ - kind: "max", - collapsibleKey: "rule", - hasAssociatedError: true, - keys: { - rule: {}, - exclusive: parseExclusiveKey - }, - normalize: (schema2) => typeof schema2 === "number" ? { rule: schema2 } : schema2, - defaults: { - description: (node2) => { - if (node2.rule === 0) - return node2.exclusive ? "negative" : "non-positive"; - return `${node2.exclusive ? "less than" : "at most"} ${node2.rule}`; - } - }, - intersections: { - max: (l, r) => l.isStricterThan(r) ? l : r, - min: (max, min, ctx) => max.overlapsRange(min) ? max.overlapIsUnit(min) ? ctx.$.node("unit", { unit: max.rule }) : null : Disjoint.init("range", max, min) - }, - obviatesBasisDescription: true -}); -var MaxNode = class extends BaseRange { - impliedBasis = $ark.intrinsic.number.internal; - traverseAllows = this.exclusive ? (data) => data < this.rule : (data) => data <= this.rule; - reduceJsonSchema(schema2) { - if (this.exclusive) - schema2.exclusiveMaximum = this.rule; - else - schema2.maximum = this.rule; - return schema2; - } -}; -var Max = { - implementation: implementation6, - Node: MaxNode -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/maxLength.js -var implementation7 = implementNode({ - kind: "maxLength", - collapsibleKey: "rule", - hasAssociatedError: true, - keys: { - rule: { - parse: createLengthRuleParser("maxLength") - } - }, - reduce: (inner, $2) => inner.rule === 0 ? $2.node("exactLength", inner) : void 0, - normalize: createLengthSchemaNormalizer("maxLength"), - defaults: { - description: (node2) => `at most length ${node2.rule}`, - actual: (data) => `${data.length}` - }, - intersections: { - maxLength: (l, r) => l.isStricterThan(r) ? l : r, - minLength: (max, min, ctx) => max.overlapsRange(min) ? max.overlapIsUnit(min) ? ctx.$.node("exactLength", { rule: max.rule }) : null : Disjoint.init("range", max, min) - } -}); -var MaxLengthNode = class extends BaseRange { - impliedBasis = $ark.intrinsic.lengthBoundable.internal; - traverseAllows = (data) => data.length <= this.rule; - reduceJsonSchema(schema2) { - switch (schema2.type) { - case "string": - schema2.maxLength = this.rule; - return schema2; - case "array": - schema2.maxItems = this.rule; - return schema2; - default: - return ToJsonSchema.throwInternalOperandError("maxLength", schema2); - } - } -}; -var MaxLength = { - implementation: implementation7, - Node: MaxLengthNode -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/min.js -var implementation8 = implementNode({ - kind: "min", - collapsibleKey: "rule", - hasAssociatedError: true, - keys: { - rule: {}, - exclusive: parseExclusiveKey - }, - normalize: (schema2) => typeof schema2 === "number" ? { rule: schema2 } : schema2, - defaults: { - description: (node2) => { - if (node2.rule === 0) - return node2.exclusive ? "positive" : "non-negative"; - return `${node2.exclusive ? "more than" : "at least"} ${node2.rule}`; - } - }, - intersections: { - min: (l, r) => l.isStricterThan(r) ? l : r - }, - obviatesBasisDescription: true -}); -var MinNode = class extends BaseRange { - impliedBasis = $ark.intrinsic.number.internal; - traverseAllows = this.exclusive ? (data) => data > this.rule : (data) => data >= this.rule; - reduceJsonSchema(schema2) { - if (this.exclusive) - schema2.exclusiveMinimum = this.rule; - else - schema2.minimum = this.rule; - return schema2; - } -}; -var Min = { - implementation: implementation8, - Node: MinNode -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/minLength.js -var implementation9 = implementNode({ - kind: "minLength", - collapsibleKey: "rule", - hasAssociatedError: true, - keys: { - rule: { - parse: createLengthRuleParser("minLength") - } - }, - reduce: (inner) => inner.rule === 0 ? ( - // a minimum length of zero is trivially satisfied - $ark.intrinsic.unknown - ) : void 0, - normalize: createLengthSchemaNormalizer("minLength"), - defaults: { - description: (node2) => node2.rule === 1 ? "non-empty" : `at least length ${node2.rule}`, - // avoid default message like "must be non-empty (was 0)" - actual: (data) => data.length === 0 ? "" : `${data.length}` - }, - intersections: { - minLength: (l, r) => l.isStricterThan(r) ? l : r - } -}); -var MinLengthNode = class extends BaseRange { - impliedBasis = $ark.intrinsic.lengthBoundable.internal; - traverseAllows = (data) => data.length >= this.rule; - reduceJsonSchema(schema2) { - switch (schema2.type) { - case "string": - schema2.minLength = this.rule; - return schema2; - case "array": - schema2.minItems = this.rule; - return schema2; - default: - return ToJsonSchema.throwInternalOperandError("minLength", schema2); - } - } -}; -var MinLength = { - implementation: implementation9, - Node: MinLengthNode -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/kinds.js -var boundImplementationsByKind = { - min: Min.implementation, - max: Max.implementation, - minLength: MinLength.implementation, - maxLength: MaxLength.implementation, - exactLength: ExactLength.implementation, - after: After.implementation, - before: Before.implementation -}; -var boundClassesByKind = { - min: Min.Node, - max: Max.Node, - minLength: MinLength.Node, - maxLength: MaxLength.Node, - exactLength: ExactLength.Node, - after: After.Node, - before: Before.Node -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/refinements/pattern.js -var implementation10 = implementNode({ - kind: "pattern", - collapsibleKey: "rule", - keys: { - rule: {}, - flags: {} - }, - normalize: (schema2) => typeof schema2 === "string" ? { rule: schema2 } : schema2 instanceof RegExp ? schema2.flags ? { rule: schema2.source, flags: schema2.flags } : { rule: schema2.source } : schema2, - obviatesBasisDescription: true, - obviatesBasisExpression: true, - hasAssociatedError: true, - intersectionIsOpen: true, - defaults: { - description: (node2) => `matched by ${node2.rule}` - }, - intersections: { - // for now, non-equal regex are naively intersected: - // https://github.com/arktypeio/arktype/issues/853 - pattern: () => null - } -}); -var PatternNode = class extends InternalPrimitiveConstraint { - instance = new RegExp(this.rule, this.flags); - expression = `${this.instance}`; - traverseAllows = this.instance.test.bind(this.instance); - compiledCondition = `${this.expression}.test(data)`; - compiledNegation = `!${this.compiledCondition}`; - impliedBasis = $ark.intrinsic.string.internal; - reduceJsonSchema(base, ctx) { - if (base.pattern) { - return ctx.fallback.patternIntersection({ - code: "patternIntersection", - base, - pattern: this.rule - }); - } - base.pattern = this.rule; - return base; - } -}; -var Pattern = { - implementation: implementation10, - Node: PatternNode -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/parse.js -var schemaKindOf = (schema2, allowedKinds) => { - const kind = discriminateRootKind(schema2); - if (allowedKinds && !allowedKinds.includes(kind)) { - return throwParseError(`Root of kind ${kind} should be one of ${allowedKinds}`); - } - return kind; -}; -var discriminateRootKind = (schema2) => { - if (hasArkKind(schema2, "root")) - return schema2.kind; - if (typeof schema2 === "string") { - return schema2[0] === "$" ? "alias" : schema2 in domainDescriptions ? "domain" : "proto"; - } - if (typeof schema2 === "function") - return "proto"; - if (typeof schema2 !== "object" || schema2 === null) - return throwParseError(writeInvalidSchemaMessage(schema2)); - if ("morphs" in schema2) - return "morph"; - if ("branches" in schema2 || isArray(schema2)) - return "union"; - if ("unit" in schema2) - return "unit"; - if ("reference" in schema2) - return "alias"; - const schemaKeys = Object.keys(schema2); - if (schemaKeys.length === 0 || schemaKeys.some((k) => k in constraintKeys)) - return "intersection"; - if ("proto" in schema2) - return "proto"; - if ("domain" in schema2) - return "domain"; - return throwParseError(writeInvalidSchemaMessage(schema2)); -}; -var writeInvalidSchemaMessage = (schema2) => `${printable(schema2)} is not a valid type schema`; -var nodeCountsByPrefix = {}; -var serializeListableChild = (listableNode) => isArray(listableNode) ? listableNode.map((node2) => node2.collapsibleJson) : listableNode.collapsibleJson; -var nodesByRegisteredId = {}; -$ark.nodesByRegisteredId = nodesByRegisteredId; -var registerNodeId = (prefix) => { - nodeCountsByPrefix[prefix] ??= 0; - return `${prefix}${++nodeCountsByPrefix[prefix]}`; -}; -var parseNode = (ctx) => { - const impl = nodeImplementationsByKind[ctx.kind]; - const configuredSchema = impl.applyConfig?.(ctx.def, ctx.$.resolvedConfig) ?? ctx.def; - const inner = {}; - const { meta: metaSchema, ...innerSchema } = configuredSchema; - const meta3 = metaSchema === void 0 ? {} : typeof metaSchema === "string" ? { description: metaSchema } : metaSchema; - const innerSchemaEntries = entriesOf(innerSchema).sort(([lKey], [rKey]) => isNodeKind(lKey) ? isNodeKind(rKey) ? precedenceOfKind(lKey) - precedenceOfKind(rKey) : 1 : isNodeKind(rKey) ? -1 : lKey < rKey ? -1 : 1).filter(([k, v]) => { - if (k.startsWith("meta.")) { - const metaKey = k.slice(5); - meta3[metaKey] = v; - return false; - } - return true; - }); - for (const entry of innerSchemaEntries) { - const k = entry[0]; - const keyImpl = impl.keys[k]; - if (!keyImpl) - return throwParseError(`Key ${k} is not valid on ${ctx.kind} schema`); - const v = keyImpl.parse ? keyImpl.parse(entry[1], ctx) : entry[1]; - if (v !== unset && (v !== void 0 || keyImpl.preserveUndefined)) - inner[k] = v; - } - if (impl.reduce && !ctx.prereduced) { - const reduced = impl.reduce(inner, ctx.$); - if (reduced) { - if (reduced instanceof Disjoint) - return reduced.throw(); - return withMeta(reduced, meta3); - } - } - const node2 = createNode({ - id: ctx.id, - kind: ctx.kind, - inner, - meta: meta3, - $: ctx.$ - }); - return node2; -}; -var createNode = ({ id, kind, inner, meta: meta3, $: $2, ignoreCache }) => { - const impl = nodeImplementationsByKind[kind]; - const innerEntries = entriesOf(inner); - const children = []; - let innerJson = {}; - for (const [k, v] of innerEntries) { - const keyImpl = impl.keys[k]; - const serialize = keyImpl.serialize ?? (keyImpl.child ? serializeListableChild : defaultValueSerializer); - innerJson[k] = serialize(v); - if (keyImpl.child === true) { - const listableNode = v; - if (isArray(listableNode)) - children.push(...listableNode); - else - children.push(listableNode); - } else if (typeof keyImpl.child === "function") - children.push(...keyImpl.child(v)); - } - if (impl.finalizeInnerJson) - innerJson = impl.finalizeInnerJson(innerJson); - let json4 = { ...innerJson }; - let metaJson = {}; - if (!isEmptyObject(meta3)) { - metaJson = flatMorph(meta3, (k, v) => [ - k, - k === "examples" ? v : defaultValueSerializer(v) - ]); - json4.meta = possiblyCollapse(metaJson, "description", true); - } - innerJson = possiblyCollapse(innerJson, impl.collapsibleKey, false); - const innerHash = JSON.stringify({ kind, ...innerJson }); - json4 = possiblyCollapse(json4, impl.collapsibleKey, false); - const collapsibleJson = possiblyCollapse(json4, impl.collapsibleKey, true); - const hash2 = JSON.stringify({ kind, ...json4 }); - if ($2.nodesByHash[hash2] && !ignoreCache) - return $2.nodesByHash[hash2]; - const attachments = { - id, - kind, - impl, - inner, - innerEntries, - innerJson, - innerHash, - meta: meta3, - metaJson, - json: json4, - hash: hash2, - collapsibleJson, - children - }; - if (kind !== "intersection") { - for (const k in inner) - if (k !== "in" && k !== "out") - attachments[k] = inner[k]; - } - const node2 = new nodeClassesByKind[kind](attachments, $2); - return $2.nodesByHash[hash2] = node2; -}; -var withId = (node2, id) => { - if (node2.id === id) - return node2; - if (isNode(nodesByRegisteredId[id])) - throwInternalError(`Unexpected attempt to overwrite node id ${id}`); - return createNode({ - id, - kind: node2.kind, - inner: node2.inner, - meta: node2.meta, - $: node2.$, - ignoreCache: true - }); -}; -var withMeta = (node2, meta3, id) => { - if (id && isNode(nodesByRegisteredId[id])) - throwInternalError(`Unexpected attempt to overwrite node id ${id}`); - return createNode({ - id: id ?? registerNodeId(meta3.alias ?? node2.kind), - kind: node2.kind, - inner: node2.inner, - meta: meta3, - $: node2.$ - }); -}; -var possiblyCollapse = (json4, toKey, allowPrimitive) => { - const collapsibleKeys = Object.keys(json4); - if (collapsibleKeys.length === 1 && collapsibleKeys[0] === toKey) { - const collapsed = json4[toKey]; - if (allowPrimitive) - return collapsed; - if ( - // if the collapsed value is still an object - hasDomain(collapsed, "object") && // and the JSON did not include any implied keys - (Object.keys(collapsed).length === 1 || Array.isArray(collapsed)) - ) { - return collapsed; - } - } - return json4; -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/prop.js -var intersectProps = (l, r, ctx) => { - if (l.key !== r.key) - return null; - const key = l.key; - let value2 = intersectOrPipeNodes(l.value, r.value, ctx); - const kind = l.required || r.required ? "required" : "optional"; - if (value2 instanceof Disjoint) { - if (kind === "optional") - value2 = $ark.intrinsic.never.internal; - else { - return value2.withPrefixKey(l.key, l.required && r.required ? "required" : "optional"); - } - } - if (kind === "required") { - return ctx.$.node("required", { - key, - value: value2 - }); - } - const defaultIntersection = l.hasDefault() ? r.hasDefault() ? l.default === r.default ? l.default : throwParseError(writeDefaultIntersectionMessage(l.default, r.default)) : l.default : r.hasDefault() ? r.default : unset; - return ctx.$.node("optional", { - key, - value: value2, - // unset is stripped during parsing - default: defaultIntersection - }); -}; -var BaseProp = class extends BaseConstraint { - required = this.kind === "required"; - optional = this.kind === "optional"; - impliedBasis = $ark.intrinsic.object.internal; - serializedKey = compileSerializedValue(this.key); - compiledKey = typeof this.key === "string" ? this.key : this.serializedKey; - flatRefs = append(this.value.flatRefs.map((ref) => flatRef([this.key, ...ref.path], ref.node)), flatRef([this.key], this.value)); - _transform(mapper, ctx) { - ctx.path.push(this.key); - const result = super._transform(mapper, ctx); - ctx.path.pop(); - return result; - } - hasDefault() { - return "default" in this.inner; - } - traverseAllows = (data, ctx) => { - if (this.key in data) { - return traverseKey(this.key, () => this.value.traverseAllows(data[this.key], ctx), ctx); - } - return this.optional; - }; - traverseApply = (data, ctx) => { - if (this.key in data) { - traverseKey(this.key, () => this.value.traverseApply(data[this.key], ctx), ctx); - } else if (this.hasKind("required")) - ctx.errorFromNodeContext(this.errorContext); - }; - compile(js) { - js.if(`${this.serializedKey} in data`, () => js.traverseKey(this.serializedKey, `data${js.prop(this.key)}`, this.value)); - if (this.hasKind("required")) { - js.else(() => js.traversalKind === "Apply" ? js.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`) : js.return(false)); - } - if (js.traversalKind === "Allows") - js.return(true); - } -}; -var writeDefaultIntersectionMessage = (lValue, rValue) => `Invalid intersection of default values ${printable(lValue)} & ${printable(rValue)}`; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/optional.js -var implementation11 = implementNode({ - kind: "optional", - hasAssociatedError: false, - intersectionIsOpen: true, - keys: { - key: {}, - value: { - child: true, - parse: (schema2, ctx) => ctx.$.parseSchema(schema2) - }, - default: { - preserveUndefined: true - } - }, - normalize: (schema2) => schema2, - reduce: (inner, $2) => { - if ($2.resolvedConfig.exactOptionalPropertyTypes === false) { - if (!inner.value.allows(void 0)) { - return $2.node("optional", { ...inner, value: inner.value.or(intrinsic.undefined) }, { prereduced: true }); - } - } - }, - defaults: { - description: (node2) => `${node2.compiledKey}?: ${node2.value.description}` - }, - intersections: { - optional: intersectProps - } -}); -var OptionalNode = class extends BaseProp { - constructor(...args2) { - super(...args2); - if ("default" in this.inner) - assertDefaultValueAssignability(this.value, this.inner.default, this.key); - } - get rawIn() { - const baseIn = super.rawIn; - if (!this.hasDefault()) - return baseIn; - return this.$.node("optional", omit(baseIn.inner, { default: true }), { - prereduced: true - }); - } - get outProp() { - if (!this.hasDefault()) - return this; - const { default: defaultValue, ...requiredInner } = this.inner; - return this.cacheGetter("outProp", this.$.node("required", requiredInner, { prereduced: true })); - } - expression = this.hasDefault() ? `${this.compiledKey}: ${this.value.expression} = ${printable(this.inner.default)}` : `${this.compiledKey}?: ${this.value.expression}`; - defaultValueMorph = getDefaultableMorph(this); - defaultValueMorphRef = this.defaultValueMorph && registeredReference(this.defaultValueMorph); -}; -var Optional = { - implementation: implementation11, - Node: OptionalNode -}; -var defaultableMorphCache = {}; -var getDefaultableMorph = (node2) => { - if (!node2.hasDefault()) - return; - const cacheKey = `{${node2.compiledKey}: ${node2.value.id} = ${defaultValueSerializer(node2.default)}}`; - return defaultableMorphCache[cacheKey] ??= computeDefaultValueMorph(node2.key, node2.value, node2.default); -}; -var computeDefaultValueMorph = (key, value2, defaultInput) => { - if (typeof defaultInput === "function") { - return value2.includesTransform ? (data, ctx) => { - traverseKey(key, () => value2(data[key] = defaultInput(), ctx), ctx); - return data; - } : (data) => { - data[key] = defaultInput(); - return data; - }; - } - const precomputedMorphedDefault = value2.includesTransform ? value2.assert(defaultInput) : defaultInput; - return hasDomain(precomputedMorphedDefault, "object") ? ( - // the type signature only allows this if the value was morphed - (data, ctx) => { - traverseKey(key, () => value2(data[key] = defaultInput, ctx), ctx); - return data; - } - ) : (data) => { - data[key] = precomputedMorphedDefault; - return data; - }; -}; -var assertDefaultValueAssignability = (node2, value2, key) => { - const wrapped = isThunk(value2); - if (hasDomain(value2, "object") && !wrapped) - throwParseError(writeNonPrimitiveNonFunctionDefaultValueMessage(key)); - const out = node2.in(wrapped ? value2() : value2); - if (out instanceof ArkErrors) { - if (key === null) { - throwParseError(`Default ${out.summary}`); - } - const atPath = out.transform((e) => e.transform((input) => ({ ...input, prefixPath: [key] }))); - throwParseError(`Default for ${atPath.summary}`); - } - return value2; -}; -var writeNonPrimitiveNonFunctionDefaultValueMessage = (key) => { - const keyDescription = key === null ? "" : typeof key === "number" ? `for value at [${key}] ` : `for ${compileSerializedValue(key)} `; - return `Non-primitive default ${keyDescription}must be specified as a function like () => ({my: 'object'})`; -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/root.js -var BaseRoot = class extends BaseNode { - constructor(attachments, $2) { - super(attachments, $2); - Object.defineProperty(this, arkKind, { value: "root", enumerable: false }); - } - // doesn't seem possible to override this at a type-level (e.g. via declare) - // without TS complaining about getters - get rawIn() { - return super.rawIn; - } - get rawOut() { - return super.rawOut; - } - get internal() { - return this; - } - get "~standard"() { - return { - vendor: "arktype", - version: 1, - validate: (input) => { - const out = this(input); - if (out instanceof ArkErrors) - return out; - return { value: out }; - }, - jsonSchema: { - input: (opts) => this.rawIn.toJsonSchema({ - target: validateStandardJsonSchemaTarget(opts.target), - ...opts.libraryOptions - }), - output: (opts) => this.rawOut.toJsonSchema({ - target: validateStandardJsonSchemaTarget(opts.target), - ...opts.libraryOptions - }) - } - }; - } - as() { - return this; - } - brand(name) { - if (name === "") - return throwParseError(emptyBrandNameMessage); - return this; - } - readonly() { - return this; - } - branches = this.hasKind("union") ? this.inner.branches : [this]; - distribute(mapBranch, reduceMapped) { - const mappedBranches = this.branches.map(mapBranch); - return reduceMapped?.(mappedBranches) ?? mappedBranches; - } - get shortDescription() { - return this.meta.description ?? this.defaultShortDescription; - } - toJsonSchema(opts = {}) { - const ctx = mergeToJsonSchemaConfigs(this.$.resolvedConfig.toJsonSchema, opts); - ctx.useRefs ||= this.isCyclic; - const schema2 = typeof ctx.dialect === "string" ? { $schema: ctx.dialect } : {}; - Object.assign(schema2, this.toJsonSchemaRecurse(ctx)); - if (ctx.useRefs) { - const defs = flatMorph(this.references, (i, ref) => ref.isRoot() && !ref.alwaysExpandJsonSchema ? [ref.id, ref.toResolvedJsonSchema(ctx)] : []); - if (ctx.target === "draft-07") - Object.assign(schema2, { definitions: defs }); - else - schema2.$defs = defs; - } - return schema2; - } - toJsonSchemaRecurse(ctx) { - if (ctx.useRefs && !this.alwaysExpandJsonSchema) { - const defsKey = ctx.target === "draft-07" ? "definitions" : "$defs"; - return { $ref: `#/${defsKey}/${this.id}` }; - } - return this.toResolvedJsonSchema(ctx); - } - get alwaysExpandJsonSchema() { - return this.isBasis() || this.kind === "alias" || this.hasKind("union") && this.isBoolean; - } - toResolvedJsonSchema(ctx) { - const result = this.innerToJsonSchema(ctx); - return Object.assign(result, this.metaJson); - } - intersect(r) { - const rNode = this.$.parseDefinition(r); - const result = this.rawIntersect(rNode); - if (result instanceof Disjoint) - return result; - return this.$.finalize(result); - } - rawIntersect(r) { - return intersectNodesRoot(this, r, this.$); - } - toNeverIfDisjoint() { - return this; - } - and(r) { - const result = this.intersect(r); - return result instanceof Disjoint ? result.throw() : result; - } - rawAnd(r) { - const result = this.rawIntersect(r); - return result instanceof Disjoint ? result.throw() : result; - } - or(r) { - const rNode = this.$.parseDefinition(r); - return this.$.finalize(this.rawOr(rNode)); - } - rawOr(r) { - const branches = [...this.branches, ...r.branches]; - return this.$.node("union", branches); - } - map(flatMapEntry) { - return this.$.schema(this.applyStructuralOperation("map", [flatMapEntry])); - } - pick(...keys) { - return this.$.schema(this.applyStructuralOperation("pick", keys)); - } - omit(...keys) { - return this.$.schema(this.applyStructuralOperation("omit", keys)); - } - required() { - return this.$.schema(this.applyStructuralOperation("required", [])); - } - partial() { - return this.$.schema(this.applyStructuralOperation("partial", [])); - } - _keyof; - keyof() { - if (this._keyof) - return this._keyof; - const result = this.applyStructuralOperation("keyof", []).reduce((result2, branch) => result2.intersect(branch).toNeverIfDisjoint(), $ark.intrinsic.unknown.internal); - if (result.branches.length === 0) { - throwParseError(writeUnsatisfiableExpressionError(`keyof ${this.expression}`)); - } - return this._keyof = this.$.finalize(result); - } - get props() { - if (this.branches.length !== 1) - return throwParseError(writeLiteralUnionEntriesMessage(this.expression)); - return [...this.applyStructuralOperation("props", [])[0]]; - } - merge(r) { - const rNode = this.$.parseDefinition(r); - return this.$.schema(rNode.distribute((branch) => this.applyStructuralOperation("merge", [ - structureOf(branch) ?? throwParseError(writeNonStructuralOperandMessage("merge", branch.expression)) - ]))); - } - applyStructuralOperation(operation, args2) { - return this.distribute((branch) => { - if (branch.equals($ark.intrinsic.object) && operation !== "merge") - return branch; - const structure = structureOf(branch); - if (!structure) { - throwParseError(writeNonStructuralOperandMessage(operation, branch.expression)); - } - if (operation === "keyof") - return structure.keyof(); - if (operation === "get") - return structure.get(...args2); - if (operation === "props") - return structure.props; - const structuralMethodName = operation === "required" ? "require" : operation === "partial" ? "optionalize" : operation; - return this.$.node("intersection", { - domain: "object", - structure: structure[structuralMethodName](...args2) - }); - }); - } - get(...path3) { - if (path3[0] === void 0) - return this; - return this.$.schema(this.applyStructuralOperation("get", path3)); - } - extract(r) { - const rNode = this.$.parseDefinition(r); - return this.$.schema(this.branches.filter((branch) => branch.extends(rNode))); - } - exclude(r) { - const rNode = this.$.parseDefinition(r); - return this.$.schema(this.branches.filter((branch) => !branch.extends(rNode))); - } - array() { - return this.$.schema(this.isUnknown() ? { proto: Array } : { - proto: Array, - sequence: this - }, { prereduced: true }); - } - overlaps(r) { - const intersection3 = this.intersect(r); - return !(intersection3 instanceof Disjoint); - } - extends(r) { - if (this.isNever()) - return true; - const intersection3 = this.intersect(r); - return !(intersection3 instanceof Disjoint) && this.equals(intersection3); - } - ifExtends(r) { - return this.extends(r) ? this : void 0; - } - subsumes(r) { - const rNode = this.$.parseDefinition(r); - return rNode.extends(this); - } - configure(meta3, selector = "shallow") { - return this.configureReferences(meta3, selector); - } - describe(description, selector = "shallow") { - return this.configure({ description }, selector); - } - // these should ideally be implemented in arktype since they use its syntax - // https://github.com/arktypeio/arktype/issues/1223 - optional() { - return [this, "?"]; - } - // these should ideally be implemented in arktype since they use its syntax - // https://github.com/arktypeio/arktype/issues/1223 - default(thunkableValue) { - assertDefaultValueAssignability(this, thunkableValue, null); - return [this, "=", thunkableValue]; - } - from(input) { - return this.assert(input); - } - _pipe(...morphs) { - const result = morphs.reduce((acc, morph) => acc.rawPipeOnce(morph), this); - return this.$.finalize(result); - } - tryPipe(...morphs) { - const result = morphs.reduce((acc, morph) => acc.rawPipeOnce(hasArkKind(morph, "root") ? morph : ((In, ctx) => { - try { - return morph(In, ctx); - } catch (e) { - return ctx.error({ - code: "predicate", - predicate: morph, - actual: `aborted due to error: - ${e} -` - }); - } - })), this); - return this.$.finalize(result); - } - pipe = Object.assign(this._pipe.bind(this), { - try: this.tryPipe.bind(this) - }); - to(def) { - return this.$.finalize(this.toNode(this.$.parseDefinition(def))); - } - toNode(root) { - const result = pipeNodesRoot(this, root, this.$); - if (result instanceof Disjoint) - return result.throw(); - return result; - } - rawPipeOnce(morph) { - if (hasArkKind(morph, "root")) - return this.toNode(morph); - return this.distribute((branch) => branch.hasKind("morph") ? this.$.node("morph", { - in: branch.inner.in, - morphs: [...branch.morphs, morph] - }) : this.$.node("morph", { - in: branch, - morphs: [morph] - }), this.$.parseSchema); - } - narrow(predicate) { - return this.constrainOut("predicate", predicate); - } - constrain(kind, schema2) { - return this._constrain("root", kind, schema2); - } - constrainIn(kind, schema2) { - return this._constrain("in", kind, schema2); - } - constrainOut(kind, schema2) { - return this._constrain("out", kind, schema2); - } - _constrain(io, kind, schema2) { - const constraint = this.$.node(kind, schema2); - if (constraint.isRoot()) { - return constraint.isUnknown() ? this : throwInternalError(`Unexpected constraint node ${constraint}`); - } - const operand = io === "root" ? this : io === "in" ? this.rawIn : this.rawOut; - if (operand.hasKind("morph") || constraint.impliedBasis && !operand.extends(constraint.impliedBasis)) { - return throwInvalidOperandError(kind, constraint.impliedBasis, this); - } - const partialIntersection = this.$.node("intersection", { - // important this is constraint.kind instead of kind in case - // the node was reduced during parsing - [constraint.kind]: constraint - }); - const result = io === "out" ? pipeNodesRoot(this, partialIntersection, this.$) : intersectNodesRoot(this, partialIntersection, this.$); - if (result instanceof Disjoint) - result.throw(); - return this.$.finalize(result); - } - onUndeclaredKey(cfg) { - const rule = typeof cfg === "string" ? cfg : cfg.rule; - const deep = typeof cfg === "string" ? false : cfg.deep; - return this.$.finalize(this.transform((kind, inner) => kind === "structure" ? rule === "ignore" ? omit(inner, { undeclared: 1 }) : { ...inner, undeclared: rule } : inner, deep ? void 0 : { shouldTransform: (node2) => !includes(structuralKinds, node2.kind) })); - } - hasEqualMorphs(r) { - if (!this.includesTransform && !r.includesTransform) - return true; - if (!arrayEquals(this.shallowMorphs, r.shallowMorphs)) - return false; - if (!arrayEquals(this.flatMorphs, r.flatMorphs, { - isEqual: (l, r2) => l.propString === r2.propString && (l.node.hasKind("morph") && r2.node.hasKind("morph") ? l.node.hasEqualMorphs(r2.node) : l.node.hasKind("intersection") && r2.node.hasKind("intersection") ? l.node.structure?.structuralMorphRef === r2.node.structure?.structuralMorphRef : false) - })) - return false; - return true; - } - onDeepUndeclaredKey(behavior) { - return this.onUndeclaredKey({ rule: behavior, deep: true }); - } - filter(predicate) { - return this.constrainIn("predicate", predicate); - } - divisibleBy(schema2) { - return this.constrain("divisor", schema2); - } - matching(schema2) { - return this.constrain("pattern", schema2); - } - atLeast(schema2) { - return this.constrain("min", schema2); - } - atMost(schema2) { - return this.constrain("max", schema2); - } - moreThan(schema2) { - return this.constrain("min", exclusivizeRangeSchema(schema2)); - } - lessThan(schema2) { - return this.constrain("max", exclusivizeRangeSchema(schema2)); - } - atLeastLength(schema2) { - return this.constrain("minLength", schema2); - } - atMostLength(schema2) { - return this.constrain("maxLength", schema2); - } - moreThanLength(schema2) { - return this.constrain("minLength", exclusivizeRangeSchema(schema2)); - } - lessThanLength(schema2) { - return this.constrain("maxLength", exclusivizeRangeSchema(schema2)); - } - exactlyLength(schema2) { - return this.constrain("exactLength", schema2); - } - atOrAfter(schema2) { - return this.constrain("after", schema2); - } - atOrBefore(schema2) { - return this.constrain("before", schema2); - } - laterThan(schema2) { - return this.constrain("after", exclusivizeRangeSchema(schema2)); - } - earlierThan(schema2) { - return this.constrain("before", exclusivizeRangeSchema(schema2)); - } -}; -var emptyBrandNameMessage = `Expected a non-empty brand name after #`; -var supportedJsonSchemaTargets = [ - "draft-2020-12", - "draft-07" -]; -var writeInvalidJsonSchemaTargetMessage = (target) => `JSONSchema target '${target}' is not supported (must be ${supportedJsonSchemaTargets.map((t) => `"${t}"`).join(" or ")})`; -var validateStandardJsonSchemaTarget = (target) => { - if (!includes(supportedJsonSchemaTargets, target)) - throwParseError(writeInvalidJsonSchemaTargetMessage(target)); - return target; -}; -var exclusivizeRangeSchema = (schema2) => typeof schema2 === "object" && !(schema2 instanceof Date) ? { ...schema2, exclusive: true } : { - rule: schema2, - exclusive: true -}; -var typeOrTermExtends = (t, base) => hasArkKind(base, "root") ? hasArkKind(t, "root") ? t.extends(base) : base.allows(t) : hasArkKind(t, "root") ? t.hasUnit(base) : base === t; -var structureOf = (branch) => { - if (branch.hasKind("morph")) - return null; - if (branch.hasKind("intersection")) { - return branch.inner.structure ?? (branch.basis?.domain === "object" ? branch.$.bindReference($ark.intrinsic.emptyStructure) : null); - } - if (branch.isBasis() && branch.domain === "object") - return branch.$.bindReference($ark.intrinsic.emptyStructure); - return null; -}; -var writeLiteralUnionEntriesMessage = (expression) => `Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received: -${expression}`; -var writeNonStructuralOperandMessage = (operation, operand) => `${operation} operand must be an object (was ${operand})`; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/utils.js -var defineRightwardIntersections = (kind, implementation23) => flatMorph(schemaKindsRightOf(kind), (i, kind2) => [ - kind2, - implementation23 -]); - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/alias.js -var normalizeAliasSchema = (schema2) => typeof schema2 === "string" ? { reference: schema2 } : schema2; -var neverIfDisjoint = (result) => result instanceof Disjoint ? $ark.intrinsic.never.internal : result; -var implementation12 = implementNode({ - kind: "alias", - hasAssociatedError: false, - collapsibleKey: "reference", - keys: { - reference: { - serialize: (s) => s.startsWith("$") ? s : `$ark.${s}` - }, - resolve: {} - }, - normalize: normalizeAliasSchema, - defaults: { - description: (node2) => node2.reference - }, - intersections: { - alias: (l, r, ctx) => ctx.$.lazilyResolve(() => neverIfDisjoint(intersectOrPipeNodes(l.resolution, r.resolution, ctx)), `${l.reference}${ctx.pipe ? "=>" : "&"}${r.reference}`), - ...defineRightwardIntersections("alias", (l, r, ctx) => { - if (r.isUnknown()) - return l; - if (r.isNever()) - return r; - if (r.isBasis() && !r.overlaps($ark.intrinsic.object)) { - return Disjoint.init("assignability", $ark.intrinsic.object, r); - } - return ctx.$.lazilyResolve(() => neverIfDisjoint(intersectOrPipeNodes(l.resolution, r, ctx)), `${l.reference}${ctx.pipe ? "=>" : "&"}${r.id}`); - }) - } -}); -var AliasNode = class extends BaseRoot { - expression = this.reference; - structure = void 0; - get resolution() { - const result = this._resolve(); - return nodesByRegisteredId[this.id] = result; - } - _resolve() { - if (this.resolve) - return this.resolve(); - if (this.reference[0] === "$") - return this.$.resolveRoot(this.reference.slice(1)); - const id = this.reference; - let resolution = nodesByRegisteredId[id]; - const seen = []; - while (hasArkKind(resolution, "context")) { - if (seen.includes(resolution.id)) { - return throwParseError(writeShallowCycleErrorMessage(resolution.id, seen)); - } - seen.push(resolution.id); - resolution = nodesByRegisteredId[resolution.id]; - } - if (!hasArkKind(resolution, "root")) { - return throwInternalError(`Unexpected resolution for reference ${this.reference} -Seen: [${seen.join("->")}] -Resolution: ${printable(resolution)}`); - } - return resolution; - } - get resolutionId() { - if (this.reference.includes("&") || this.reference.includes("=>")) - return this.resolution.id; - if (this.reference[0] !== "$") - return this.reference; - const alias = this.reference.slice(1); - const resolution = this.$.resolutions[alias]; - if (typeof resolution === "string") - return resolution; - if (hasArkKind(resolution, "root")) - return resolution.id; - return throwInternalError(`Unexpected resolution for reference ${this.reference}: ${printable(resolution)}`); - } - get defaultShortDescription() { - return domainDescriptions.object; - } - innerToJsonSchema(ctx) { - return this.resolution.toJsonSchemaRecurse(ctx); - } - traverseAllows = (data, ctx) => { - const seen = ctx.seen[this.reference]; - if (seen?.includes(data)) - return true; - ctx.seen[this.reference] = append(seen, data); - return this.resolution.traverseAllows(data, ctx); - }; - traverseApply = (data, ctx) => { - const seen = ctx.seen[this.reference]; - if (seen?.includes(data)) - return; - ctx.seen[this.reference] = append(seen, data); - this.resolution.traverseApply(data, ctx); - }; - compile(js) { - const id = this.resolutionId; - js.if(`ctx.seen.${id} && ctx.seen.${id}.includes(data)`, () => js.return(true)); - js.if(`!ctx.seen.${id}`, () => js.line(`ctx.seen.${id} = []`)); - js.line(`ctx.seen.${id}.push(data)`); - js.return(js.invoke(id)); - } -}; -var writeShallowCycleErrorMessage = (name, seen) => `Alias '${name}' has a shallow resolution cycle: ${[...seen, name].join("->")}`; -var Alias = { - implementation: implementation12, - Node: AliasNode -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/basis.js -var InternalBasis = class extends BaseRoot { - traverseApply = (data, ctx) => { - if (!this.traverseAllows(data, ctx)) - ctx.errorFromNodeContext(this.errorContext); - }; - get errorContext() { - return { - code: this.kind, - description: this.description, - meta: this.meta, - ...this.inner - }; - } - get compiledErrorContext() { - return compileObjectLiteral(this.errorContext); - } - compile(js) { - if (js.traversalKind === "Allows") - js.return(this.compiledCondition); - else { - js.if(this.compiledNegation, () => js.line(`ctx.errorFromNodeContext(${this.compiledErrorContext})`)); - } - } -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/domain.js -var implementation13 = implementNode({ - kind: "domain", - hasAssociatedError: true, - collapsibleKey: "domain", - keys: { - domain: {}, - numberAllowsNaN: {} - }, - normalize: (schema2) => typeof schema2 === "string" ? { domain: schema2 } : hasKey(schema2, "numberAllowsNaN") && schema2.domain !== "number" ? throwParseError(Domain.writeBadAllowNanMessage(schema2.domain)) : schema2, - applyConfig: (schema2, config3) => schema2.numberAllowsNaN === void 0 && schema2.domain === "number" && config3.numberAllowsNaN ? { ...schema2, numberAllowsNaN: true } : schema2, - defaults: { - description: (node2) => domainDescriptions[node2.domain], - actual: (data) => Number.isNaN(data) ? "NaN" : domainDescriptions[domainOf(data)] - }, - intersections: { - domain: (l, r) => ( - // since l === r is handled by default, remaining cases are disjoint - // outside those including options like numberAllowsNaN - l.domain === "number" && r.domain === "number" ? l.numberAllowsNaN ? r : l : Disjoint.init("domain", l, r) - ) - } -}); -var DomainNode = class extends InternalBasis { - requiresNaNCheck = this.domain === "number" && !this.numberAllowsNaN; - traverseAllows = this.requiresNaNCheck ? (data) => typeof data === "number" && !Number.isNaN(data) : (data) => domainOf(data) === this.domain; - compiledCondition = this.domain === "object" ? `((typeof data === "object" && data !== null) || typeof data === "function")` : `typeof data === "${this.domain}"${this.requiresNaNCheck ? " && !Number.isNaN(data)" : ""}`; - compiledNegation = this.domain === "object" ? `((typeof data !== "object" || data === null) && typeof data !== "function")` : `typeof data !== "${this.domain}"${this.requiresNaNCheck ? " || Number.isNaN(data)" : ""}`; - expression = this.numberAllowsNaN ? "number | NaN" : this.domain; - get nestableExpression() { - return this.numberAllowsNaN ? `(${this.expression})` : this.expression; - } - get defaultShortDescription() { - return domainDescriptions[this.domain]; - } - innerToJsonSchema(ctx) { - if (this.domain === "bigint" || this.domain === "symbol") { - return ctx.fallback.domain({ - code: "domain", - base: {}, - domain: this.domain - }); - } - return { - type: this.domain - }; - } -}; -var Domain = { - implementation: implementation13, - Node: DomainNode, - writeBadAllowNanMessage: (actual) => `numberAllowsNaN may only be specified with domain "number" (was ${actual})` -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/intersection.js -var implementation14 = implementNode({ - kind: "intersection", - hasAssociatedError: true, - normalize: (rawSchema) => { - if (isNode(rawSchema)) - return rawSchema; - const { structure, ...schema2 } = rawSchema; - const hasRootStructureKey = !!structure; - const normalizedStructure = structure ?? {}; - const normalized = flatMorph(schema2, (k, v) => { - if (isKeyOf(k, structureKeys)) { - if (hasRootStructureKey) { - throwParseError(`Flattened structure key ${k} cannot be specified alongside a root 'structure' key.`); - } - normalizedStructure[k] = v; - return []; - } - return [k, v]; - }); - if (hasArkKind(normalizedStructure, "constraint") || !isEmptyObject(normalizedStructure)) - normalized.structure = normalizedStructure; - return normalized; - }, - finalizeInnerJson: ({ structure, ...rest }) => hasDomain(structure, "object") ? { ...structure, ...rest } : rest, - keys: { - domain: { - child: true, - parse: (schema2, ctx) => ctx.$.node("domain", schema2) - }, - proto: { - child: true, - parse: (schema2, ctx) => ctx.$.node("proto", schema2) - }, - structure: { - child: true, - parse: (schema2, ctx) => ctx.$.node("structure", schema2), - serialize: (node2) => { - if (!node2.sequence?.minLength) - return node2.collapsibleJson; - const { sequence, ...structureJson } = node2.collapsibleJson; - const { minVariadicLength, ...sequenceJson } = sequence; - const collapsibleSequenceJson = sequenceJson.variadic && Object.keys(sequenceJson).length === 1 ? sequenceJson.variadic : sequenceJson; - return { ...structureJson, sequence: collapsibleSequenceJson }; - } - }, - divisor: { - child: true, - parse: constraintKeyParser("divisor") - }, - max: { - child: true, - parse: constraintKeyParser("max") - }, - min: { - child: true, - parse: constraintKeyParser("min") - }, - maxLength: { - child: true, - parse: constraintKeyParser("maxLength") - }, - minLength: { - child: true, - parse: constraintKeyParser("minLength") - }, - exactLength: { - child: true, - parse: constraintKeyParser("exactLength") - }, - before: { - child: true, - parse: constraintKeyParser("before") - }, - after: { - child: true, - parse: constraintKeyParser("after") - }, - pattern: { - child: true, - parse: constraintKeyParser("pattern") - }, - predicate: { - child: true, - parse: constraintKeyParser("predicate") - } - }, - // leverage reduction logic from intersection and identity to ensure initial - // parse result is reduced - reduce: (inner, $2) => ( - // we cast union out of the result here since that only occurs when intersecting two sequences - // that cannot occur when reducing a single intersection schema using unknown - intersectIntersections({}, inner, { - $: $2, - invert: false, - pipe: false - }) - ), - defaults: { - description: (node2) => { - if (node2.children.length === 0) - return "unknown"; - if (node2.structure) - return node2.structure.description; - const childDescriptions = []; - if (node2.basis && !node2.prestructurals.some((r) => r.impl.obviatesBasisDescription)) - childDescriptions.push(node2.basis.description); - if (node2.prestructurals.length) { - const sortedRefinementDescriptions = node2.prestructurals.slice().sort((l, r) => l.kind === "min" && r.kind === "max" ? -1 : 0).map((r) => r.description); - childDescriptions.push(...sortedRefinementDescriptions); - } - if (node2.inner.predicate) { - childDescriptions.push(...node2.inner.predicate.map((p) => p.description)); - } - return childDescriptions.join(" and "); - }, - expected: (source) => ` \u25E6 ${source.errors.map((e) => e.expected).join("\n \u25E6 ")}`, - problem: (ctx) => `(${ctx.actual}) must be... -${ctx.expected}` - }, - intersections: { - intersection: (l, r, ctx) => intersectIntersections(l.inner, r.inner, ctx), - ...defineRightwardIntersections("intersection", (l, r, ctx) => { - if (l.children.length === 0) - return r; - const { domain: domain2, proto, ...lInnerConstraints } = l.inner; - const lBasis = proto ?? domain2; - const basis = lBasis ? intersectOrPipeNodes(lBasis, r, ctx) : r; - return basis instanceof Disjoint ? basis : l?.basis?.equals(basis) ? ( - // if the basis doesn't change, return the original intesection - l - ) : l.$.node("intersection", { ...lInnerConstraints, [basis.kind]: basis }, { prereduced: true }); - }) - } -}); -var IntersectionNode = class extends BaseRoot { - basis = this.inner.domain ?? this.inner.proto ?? null; - prestructurals = []; - refinements = this.children.filter((node2) => { - if (!node2.isRefinement()) - return false; - if (includes(prestructuralKinds, node2.kind)) - this.prestructurals.push(node2); - return true; - }); - structure = this.inner.structure; - expression = writeIntersectionExpression(this); - get shallowMorphs() { - return this.inner.structure?.structuralMorph ? [this.inner.structure.structuralMorph] : []; - } - get defaultShortDescription() { - return this.basis?.defaultShortDescription ?? "present"; - } - innerToJsonSchema(ctx) { - return this.children.reduce( - // cast is required since TS doesn't know children have compatible schema prerequisites - (schema2, child) => child.isBasis() ? child.toJsonSchemaRecurse(ctx) : child.reduceJsonSchema(schema2, ctx), - {} - ); - } - traverseAllows = (data, ctx) => this.children.every((child) => child.traverseAllows(data, ctx)); - traverseApply = (data, ctx) => { - const errorCount = ctx.currentErrorCount; - if (this.basis) { - this.basis.traverseApply(data, ctx); - if (ctx.currentErrorCount > errorCount) - return; - } - if (this.prestructurals.length) { - for (let i = 0; i < this.prestructurals.length - 1; i++) { - this.prestructurals[i].traverseApply(data, ctx); - if (ctx.failFast && ctx.currentErrorCount > errorCount) - return; - } - this.prestructurals[this.prestructurals.length - 1].traverseApply(data, ctx); - if (ctx.currentErrorCount > errorCount) - return; - } - if (this.structure) { - this.structure.traverseApply(data, ctx); - if (ctx.currentErrorCount > errorCount) - return; - } - if (this.inner.predicate) { - for (let i = 0; i < this.inner.predicate.length - 1; i++) { - this.inner.predicate[i].traverseApply(data, ctx); - if (ctx.failFast && ctx.currentErrorCount > errorCount) - return; - } - this.inner.predicate[this.inner.predicate.length - 1].traverseApply(data, ctx); - } - }; - compile(js) { - if (js.traversalKind === "Allows") { - for (const child of this.children) - js.check(child); - js.return(true); - return; - } - js.initializeErrorCount(); - if (this.basis) { - js.check(this.basis); - if (this.children.length > 1) - js.returnIfFail(); - } - if (this.prestructurals.length) { - for (let i = 0; i < this.prestructurals.length - 1; i++) { - js.check(this.prestructurals[i]); - js.returnIfFailFast(); - } - js.check(this.prestructurals[this.prestructurals.length - 1]); - if (this.structure || this.inner.predicate) - js.returnIfFail(); - } - if (this.structure) { - js.check(this.structure); - if (this.inner.predicate) - js.returnIfFail(); - } - if (this.inner.predicate) { - for (let i = 0; i < this.inner.predicate.length - 1; i++) { - js.check(this.inner.predicate[i]); - js.returnIfFail(); - } - js.check(this.inner.predicate[this.inner.predicate.length - 1]); - } - } -}; -var Intersection = { - implementation: implementation14, - Node: IntersectionNode -}; -var writeIntersectionExpression = (node2) => { - if (node2.structure?.expression) - return node2.structure.expression; - const basisExpression = node2.basis && !node2.prestructurals.some((n) => n.impl.obviatesBasisExpression) ? node2.basis.nestableExpression : ""; - const refinementsExpression = node2.prestructurals.map((n) => n.expression).join(" & "); - const fullExpression = `${basisExpression}${basisExpression ? " " : ""}${refinementsExpression}`; - if (fullExpression === "Array == 0") - return "[]"; - return fullExpression || "unknown"; -}; -var intersectIntersections = (l, r, ctx) => { - const baseInner = {}; - const lBasis = l.proto ?? l.domain; - const rBasis = r.proto ?? r.domain; - const basisResult = lBasis ? rBasis ? intersectOrPipeNodes(lBasis, rBasis, ctx) : lBasis : rBasis; - if (basisResult instanceof Disjoint) - return basisResult; - if (basisResult) - baseInner[basisResult.kind] = basisResult; - return intersectConstraints({ - kind: "intersection", - baseInner, - l: flattenConstraints(l), - r: flattenConstraints(r), - roots: [], - ctx - }); -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/morph.js -var implementation15 = implementNode({ - kind: "morph", - hasAssociatedError: false, - keys: { - in: { - child: true, - parse: (schema2, ctx) => ctx.$.parseSchema(schema2) - }, - morphs: { - parse: liftArray, - serialize: (morphs) => morphs.map((m) => hasArkKind(m, "root") ? m.json : registeredReference(m)) - }, - declaredIn: { - child: false, - serialize: (node2) => node2.json - }, - declaredOut: { - child: false, - serialize: (node2) => node2.json - } - }, - normalize: (schema2) => schema2, - defaults: { - description: (node2) => `a morph from ${node2.rawIn.description} to ${node2.rawOut?.description ?? "unknown"}` - }, - intersections: { - morph: (l, r, ctx) => { - if (!l.hasEqualMorphs(r)) { - return throwParseError(writeMorphIntersectionMessage(l.expression, r.expression)); - } - const inTersection = intersectOrPipeNodes(l.rawIn, r.rawIn, ctx); - if (inTersection instanceof Disjoint) - return inTersection; - const baseInner = { - morphs: l.morphs - }; - if (l.declaredIn || r.declaredIn) { - const declaredIn = intersectOrPipeNodes(l.rawIn, r.rawIn, ctx); - if (declaredIn instanceof Disjoint) - return declaredIn.throw(); - else - baseInner.declaredIn = declaredIn; - } - if (l.declaredOut || r.declaredOut) { - const declaredOut = intersectOrPipeNodes(l.rawOut, r.rawOut, ctx); - if (declaredOut instanceof Disjoint) - return declaredOut.throw(); - else - baseInner.declaredOut = declaredOut; - } - return inTersection.distribute((inBranch) => ctx.$.node("morph", { - ...baseInner, - in: inBranch - }), ctx.$.parseSchema); - }, - ...defineRightwardIntersections("morph", (l, r, ctx) => { - const inTersection = l.inner.in ? intersectOrPipeNodes(l.inner.in, r, ctx) : r; - return inTersection instanceof Disjoint ? inTersection : inTersection.equals(l.inner.in) ? l : ctx.$.node("morph", { - ...l.inner, - in: inTersection - }); - }) - } -}); -var MorphNode = class extends BaseRoot { - serializedMorphs = this.morphs.map(registeredReference); - compiledMorphs = `[${this.serializedMorphs}]`; - lastMorph = this.inner.morphs[this.inner.morphs.length - 1]; - lastMorphIfNode = hasArkKind(this.lastMorph, "root") ? this.lastMorph : void 0; - introspectableIn = this.inner.in; - introspectableOut = this.lastMorphIfNode ? Object.assign(this.referencesById, this.lastMorphIfNode.referencesById) && this.lastMorphIfNode.rawOut : void 0; - get shallowMorphs() { - return Array.isArray(this.inner.in?.shallowMorphs) ? [...this.inner.in.shallowMorphs, ...this.morphs] : this.morphs; - } - get rawIn() { - return this.declaredIn ?? this.inner.in?.rawIn ?? $ark.intrinsic.unknown.internal; - } - get rawOut() { - return this.declaredOut ?? this.introspectableOut ?? $ark.intrinsic.unknown.internal; - } - declareIn(declaredIn) { - return this.$.node("morph", { - ...this.inner, - declaredIn - }); - } - declareOut(declaredOut) { - return this.$.node("morph", { - ...this.inner, - declaredOut - }); - } - expression = `(In: ${this.rawIn.expression}) => ${this.lastMorphIfNode ? "To" : "Out"}<${this.rawOut.expression}>`; - get defaultShortDescription() { - return this.rawIn.meta.description ?? this.rawIn.defaultShortDescription; - } - innerToJsonSchema(ctx) { - return ctx.fallback.morph({ - code: "morph", - base: this.rawIn.toJsonSchemaRecurse(ctx), - out: this.introspectableOut?.toJsonSchemaRecurse(ctx) ?? null - }); - } - compile(js) { - if (js.traversalKind === "Allows") { - if (!this.introspectableIn) - return; - js.return(js.invoke(this.introspectableIn)); - return; - } - if (this.introspectableIn) - js.line(js.invoke(this.introspectableIn)); - js.line(`ctx.queueMorphs(${this.compiledMorphs})`); - } - traverseAllows = (data, ctx) => !this.introspectableIn || this.introspectableIn.traverseAllows(data, ctx); - traverseApply = (data, ctx) => { - if (this.introspectableIn) - this.introspectableIn.traverseApply(data, ctx); - ctx.queueMorphs(this.morphs); - }; - /** Check if the morphs of r are equal to those of this node */ - hasEqualMorphs(r) { - return arrayEquals(this.morphs, r.morphs, { - isEqual: (lMorph, rMorph) => lMorph === rMorph || hasArkKind(lMorph, "root") && hasArkKind(rMorph, "root") && lMorph.equals(rMorph) - }); - } -}; -var Morph = { - implementation: implementation15, - Node: MorphNode -}; -var writeMorphIntersectionMessage = (lDescription, rDescription) => `The intersection of distinct morphs at a single path is indeterminate: -Left: ${lDescription} -Right: ${rDescription}`; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/proto.js -var implementation16 = implementNode({ - kind: "proto", - hasAssociatedError: true, - collapsibleKey: "proto", - keys: { - proto: { - serialize: (ctor) => getBuiltinNameOfConstructor(ctor) ?? defaultValueSerializer(ctor) - }, - dateAllowsInvalid: {} - }, - normalize: (schema2) => { - const normalized = typeof schema2 === "string" ? { proto: builtinConstructors[schema2] } : typeof schema2 === "function" ? isNode(schema2) ? schema2 : { proto: schema2 } : typeof schema2.proto === "string" ? { ...schema2, proto: builtinConstructors[schema2.proto] } : schema2; - if (typeof normalized.proto !== "function") - throwParseError(Proto.writeInvalidSchemaMessage(normalized.proto)); - if (hasKey(normalized, "dateAllowsInvalid") && normalized.proto !== Date) - throwParseError(Proto.writeBadInvalidDateMessage(normalized.proto)); - return normalized; - }, - applyConfig: (schema2, config3) => { - if (schema2.dateAllowsInvalid === void 0 && schema2.proto === Date && config3.dateAllowsInvalid) - return { ...schema2, dateAllowsInvalid: true }; - return schema2; - }, - defaults: { - description: (node2) => node2.builtinName ? objectKindDescriptions[node2.builtinName] : `an instance of ${node2.proto.name}`, - actual: (data) => data instanceof Date && data.toString() === "Invalid Date" ? "an invalid Date" : objectKindOrDomainOf(data) - }, - intersections: { - proto: (l, r) => l.proto === Date && r.proto === Date ? ( - // since l === r is handled by default, - // exactly one of l or r must have allow invalid dates - l.dateAllowsInvalid ? r : l - ) : constructorExtends(l.proto, r.proto) ? l : constructorExtends(r.proto, l.proto) ? r : Disjoint.init("proto", l, r), - domain: (proto, domain2) => domain2.domain === "object" ? proto : Disjoint.init("domain", $ark.intrinsic.object.internal, domain2) - } -}); -var ProtoNode = class extends InternalBasis { - builtinName = getBuiltinNameOfConstructor(this.proto); - serializedConstructor = this.json.proto; - requiresInvalidDateCheck = this.proto === Date && !this.dateAllowsInvalid; - traverseAllows = this.requiresInvalidDateCheck ? (data) => data instanceof Date && data.toString() !== "Invalid Date" : (data) => data instanceof this.proto; - compiledCondition = `data instanceof ${this.serializedConstructor}${this.requiresInvalidDateCheck ? ` && data.toString() !== "Invalid Date"` : ""}`; - compiledNegation = `!(${this.compiledCondition})`; - innerToJsonSchema(ctx) { - switch (this.builtinName) { - case "Array": - return { - type: "array" - }; - case "Date": - return ctx.fallback.date?.({ code: "date", base: {} }) ?? ctx.fallback.proto({ code: "proto", base: {}, proto: this.proto }); - default: - return ctx.fallback.proto({ - code: "proto", - base: {}, - proto: this.proto - }); - } - } - expression = this.dateAllowsInvalid ? "Date | InvalidDate" : this.proto.name; - get nestableExpression() { - return this.dateAllowsInvalid ? `(${this.expression})` : this.expression; - } - domain = "object"; - get defaultShortDescription() { - return this.description; - } -}; -var Proto = { - implementation: implementation16, - Node: ProtoNode, - writeBadInvalidDateMessage: (actual) => `dateAllowsInvalid may only be specified with constructor Date (was ${actual.name})`, - writeInvalidSchemaMessage: (actual) => `instanceOf operand must be a function (was ${domainOf(actual)})` -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/union.js -var implementation17 = implementNode({ - kind: "union", - hasAssociatedError: true, - collapsibleKey: "branches", - keys: { - ordered: {}, - branches: { - child: true, - parse: (schema2, ctx) => { - const branches = []; - for (const branchSchema of schema2) { - const branchNodes = hasArkKind(branchSchema, "root") ? branchSchema.branches : ctx.$.parseSchema(branchSchema).branches; - for (const node2 of branchNodes) { - if (node2.hasKind("morph")) { - const matchingMorphIndex = branches.findIndex((matching) => matching.hasKind("morph") && matching.hasEqualMorphs(node2)); - if (matchingMorphIndex === -1) - branches.push(node2); - else { - const matchingMorph = branches[matchingMorphIndex]; - branches[matchingMorphIndex] = ctx.$.node("morph", { - ...matchingMorph.inner, - in: matchingMorph.rawIn.rawOr(node2.rawIn) - }); - } - } else - branches.push(node2); - } - } - if (!ctx.def.ordered) - branches.sort((l, r) => l.hash < r.hash ? -1 : 1); - return branches; - } - } - }, - normalize: (schema2) => isArray(schema2) ? { branches: schema2 } : schema2, - reduce: (inner, $2) => { - const reducedBranches = reduceBranches(inner); - if (reducedBranches.length === 1) - return reducedBranches[0]; - if (reducedBranches.length === inner.branches.length) - return; - return $2.node("union", { - ...inner, - branches: reducedBranches - }, { prereduced: true }); - }, - defaults: { - description: (node2) => node2.distribute((branch) => branch.description, describeBranches), - expected: (ctx) => { - const byPath = groupBy(ctx.errors, "propString"); - const pathDescriptions = Object.entries(byPath).map(([path3, errors]) => { - const branchesAtPath = []; - for (const errorAtPath of errors) - appendUnique(branchesAtPath, errorAtPath.expected); - const expected = describeBranches(branchesAtPath); - const actual = errors.every((e) => e.actual === errors[0].actual) ? errors[0].actual : printable(errors[0].data); - return `${path3 && `${path3} `}must be ${expected}${actual && ` (was ${actual})`}`; - }); - return describeBranches(pathDescriptions); - }, - problem: (ctx) => ctx.expected, - message: (ctx) => { - if (ctx.problem[0] === "[") { - return `value at ${ctx.problem}`; - } - return ctx.problem; - } - }, - intersections: { - union: (l, r, ctx) => { - if (l.isNever !== r.isNever) { - return Disjoint.init("presence", l, r); - } - let resultBranches; - if (l.ordered) { - if (r.ordered) { - throwParseError(writeOrderedIntersectionMessage(l.expression, r.expression)); - } - resultBranches = intersectBranches(r.branches, l.branches, ctx); - if (resultBranches instanceof Disjoint) - resultBranches.invert(); - } else - resultBranches = intersectBranches(l.branches, r.branches, ctx); - if (resultBranches instanceof Disjoint) - return resultBranches; - return ctx.$.parseSchema(l.ordered || r.ordered ? { - branches: resultBranches, - ordered: true - } : { branches: resultBranches }); - }, - ...defineRightwardIntersections("union", (l, r, ctx) => { - const branches = intersectBranches(l.branches, [r], ctx); - if (branches instanceof Disjoint) - return branches; - if (branches.length === 1) - return branches[0]; - return ctx.$.parseSchema(l.ordered ? { branches, ordered: true } : { branches }); - }) - } -}); -var UnionNode = class extends BaseRoot { - isBoolean = this.branches.length === 2 && this.branches[0].hasUnit(false) && this.branches[1].hasUnit(true); - get branchGroups() { - const branchGroups = []; - let firstBooleanIndex = -1; - for (const branch of this.branches) { - if (branch.hasKind("unit") && branch.domain === "boolean") { - if (firstBooleanIndex === -1) { - firstBooleanIndex = branchGroups.length; - branchGroups.push(branch); - } else - branchGroups[firstBooleanIndex] = $ark.intrinsic.boolean; - continue; - } - branchGroups.push(branch); - } - return branchGroups; - } - unitBranches = this.branches.filter((n) => n.rawIn.hasKind("unit")); - discriminant = this.discriminate(); - discriminantJson = this.discriminant ? discriminantToJson(this.discriminant) : null; - expression = this.distribute((n) => n.nestableExpression, expressBranches); - createBranchedOptimisticRootApply() { - return (data, onFail) => { - const optimisticResult = this.traverseOptimistic(data); - if (optimisticResult !== unset) - return optimisticResult; - const ctx = new Traversal(data, this.$.resolvedConfig); - this.traverseApply(data, ctx); - return ctx.finalize(onFail); - }; - } - get shallowMorphs() { - return this.branches.reduce((morphs, branch) => appendUnique(morphs, branch.shallowMorphs), []); - } - get defaultShortDescription() { - return this.distribute((branch) => branch.defaultShortDescription, describeBranches); - } - innerToJsonSchema(ctx) { - if (this.branchGroups.length === 1 && this.branchGroups[0].equals($ark.intrinsic.boolean)) - return { type: "boolean" }; - const jsonSchemaBranches = this.branchGroups.map((group2) => group2.toJsonSchemaRecurse(ctx)); - if (jsonSchemaBranches.every((branch) => ( - // iff all branches are pure unit values with no metadata, - // we can simplify the representation to an enum - Object.keys(branch).length === 1 && hasKey(branch, "const") - ))) { - return { - enum: jsonSchemaBranches.map((branch) => branch.const) - }; - } - return { - anyOf: jsonSchemaBranches - }; - } - traverseAllows = (data, ctx) => this.branches.some((b) => b.traverseAllows(data, ctx)); - traverseApply = (data, ctx) => { - const errors = []; - for (let i = 0; i < this.branches.length; i++) { - ctx.pushBranch(); - this.branches[i].traverseApply(data, ctx); - if (!ctx.hasError()) { - if (this.branches[i].includesTransform) - return ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs); - return ctx.popBranch(); - } - errors.push(ctx.popBranch().error); - } - ctx.errorFromNodeContext({ code: "union", errors, meta: this.meta }); - }; - traverseOptimistic = (data) => { - for (let i = 0; i < this.branches.length; i++) { - const branch = this.branches[i]; - if (branch.traverseAllows(data)) { - if (branch.contextFreeMorph) - return branch.contextFreeMorph(data); - return data; - } - } - return unset; - }; - compile(js) { - if (!this.discriminant || // if we have a union of two units like `boolean`, the - // undiscriminated compilation will be just as fast - this.unitBranches.length === this.branches.length && this.branches.length === 2) - return this.compileIndiscriminable(js); - let condition = this.discriminant.optionallyChainedPropString; - if (this.discriminant.kind === "domain") - condition = `typeof ${condition} === "object" ? ${condition} === null ? "null" : "object" : typeof ${condition} === "function" ? "object" : typeof ${condition}`; - const cases = this.discriminant.cases; - const caseKeys = Object.keys(cases); - const { optimistic } = js; - js.optimistic = false; - js.block(`switch(${condition})`, () => { - for (const k in cases) { - const v = cases[k]; - const caseCondition = k === "default" ? k : `case ${k}`; - let caseResult; - if (v === true) - caseResult = optimistic ? "data" : "true"; - else if (optimistic) { - if (v.rootApplyStrategy === "branchedOptimistic") - caseResult = js.invoke(v, { kind: "Optimistic" }); - else if (v.contextFreeMorph) - caseResult = `${js.invoke(v)} ? ${registeredReference(v.contextFreeMorph)}(data) : "${unset}"`; - else - caseResult = `${js.invoke(v)} ? data : "${unset}"`; - } else - caseResult = js.invoke(v); - js.line(`${caseCondition}: return ${caseResult}`); - } - return js; - }); - if (js.traversalKind === "Allows") { - js.return(optimistic ? `"${unset}"` : false); - return; - } - const expected = describeBranches(this.discriminant.kind === "domain" ? caseKeys.map((k) => { - const jsTypeOf = k.slice(1, -1); - return jsTypeOf === "function" ? domainDescriptions.object : domainDescriptions[jsTypeOf]; - }) : caseKeys); - const serializedPathSegments = this.discriminant.path.map((k) => typeof k === "symbol" ? registeredReference(k) : JSON.stringify(k)); - const serializedExpected = JSON.stringify(expected); - const serializedActual = this.discriminant.kind === "domain" ? `${serializedTypeOfDescriptions}[${condition}]` : `${serializedPrintable}(${condition})`; - js.line(`ctx.errorFromNodeContext({ - code: "predicate", - expected: ${serializedExpected}, - actual: ${serializedActual}, - relativePath: [${serializedPathSegments}], - meta: ${this.compiledMeta} -})`); - } - compileIndiscriminable(js) { - if (js.traversalKind === "Apply") { - js.const("errors", "[]"); - for (const branch of this.branches) { - js.line("ctx.pushBranch()").line(js.invoke(branch)).if("!ctx.hasError()", () => js.return(branch.includesTransform ? "ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)" : "ctx.popBranch()")).line("errors.push(ctx.popBranch().error)"); - } - js.line(`ctx.errorFromNodeContext({ code: "union", errors, meta: ${this.compiledMeta} })`); - } else { - const { optimistic } = js; - js.optimistic = false; - for (const branch of this.branches) { - js.if(`${js.invoke(branch)}`, () => js.return(optimistic ? branch.contextFreeMorph ? `${registeredReference(branch.contextFreeMorph)}(data)` : "data" : true)); - } - js.return(optimistic ? `"${unset}"` : false); - } - } - get nestableExpression() { - return this.isBoolean ? "boolean" : `(${this.expression})`; - } - discriminate() { - if (this.branches.length < 2 || this.isCyclic) - return null; - if (this.unitBranches.length === this.branches.length) { - const cases2 = flatMorph(this.unitBranches, (i, n) => [ - `${n.rawIn.serializedValue}`, - n.hasKind("morph") ? n : true - ]); - return { - kind: "unit", - path: [], - optionallyChainedPropString: "data", - cases: cases2 - }; - } - const candidates = []; - for (let lIndex = 0; lIndex < this.branches.length - 1; lIndex++) { - const l = this.branches[lIndex]; - for (let rIndex = lIndex + 1; rIndex < this.branches.length; rIndex++) { - const r = this.branches[rIndex]; - const result = intersectNodesRoot(l.rawIn, r.rawIn, l.$); - if (!(result instanceof Disjoint)) - continue; - for (const entry of result) { - if (!entry.kind || entry.optional) - continue; - let lSerialized; - let rSerialized; - if (entry.kind === "domain") { - const lValue = entry.l; - const rValue = entry.r; - lSerialized = `"${typeof lValue === "string" ? lValue : lValue.domain}"`; - rSerialized = `"${typeof rValue === "string" ? rValue : rValue.domain}"`; - } else if (entry.kind === "unit") { - lSerialized = entry.l.serializedValue; - rSerialized = entry.r.serializedValue; - } else - continue; - const matching = candidates.find((d) => arrayEquals(d.path, entry.path) && d.kind === entry.kind); - if (!matching) { - candidates.push({ - kind: entry.kind, - cases: { - [lSerialized]: { - branchIndices: [lIndex], - condition: entry.l - }, - [rSerialized]: { - branchIndices: [rIndex], - condition: entry.r - } - }, - path: entry.path - }); - } else { - if (matching.cases[lSerialized]) { - matching.cases[lSerialized].branchIndices = appendUnique(matching.cases[lSerialized].branchIndices, lIndex); - } else { - matching.cases[lSerialized] ??= { - branchIndices: [lIndex], - condition: entry.l - }; - } - if (matching.cases[rSerialized]) { - matching.cases[rSerialized].branchIndices = appendUnique(matching.cases[rSerialized].branchIndices, rIndex); - } else { - matching.cases[rSerialized] ??= { - branchIndices: [rIndex], - condition: entry.r - }; - } - } - } - } - } - const viableCandidates = this.ordered ? viableOrderedCandidates(candidates, this.branches) : candidates; - if (!viableCandidates.length) - return null; - const ctx = createCaseResolutionContext(viableCandidates, this); - const cases = {}; - for (const k in ctx.best.cases) { - const resolution = resolveCase(ctx, k); - if (resolution === null) { - cases[k] = true; - continue; - } - if (resolution.length === this.branches.length) - return null; - if (this.ordered) { - resolution.sort((l, r) => l.originalIndex - r.originalIndex); - } - const branches = resolution.map((entry) => entry.branch); - const caseNode = branches.length === 1 ? branches[0] : this.$.node("union", this.ordered ? { branches, ordered: true } : branches); - Object.assign(this.referencesById, caseNode.referencesById); - cases[k] = caseNode; - } - if (ctx.defaultEntries.length) { - const branches = ctx.defaultEntries.map((entry) => entry.branch); - cases.default = this.$.node("union", this.ordered ? { branches, ordered: true } : branches, { - prereduced: true - }); - Object.assign(this.referencesById, cases.default.referencesById); - } - return Object.assign(ctx.location, { - cases - }); - } -}; -var createCaseResolutionContext = (viableCandidates, node2) => { - const ordered = viableCandidates.sort((l, r) => l.path.length === r.path.length ? Object.keys(r.cases).length - Object.keys(l.cases).length : l.path.length - r.path.length); - const best = ordered[0]; - const location = { - kind: best.kind, - path: best.path, - optionallyChainedPropString: optionallyChainPropString(best.path) - }; - const defaultEntries = node2.branches.map((branch, originalIndex) => ({ - originalIndex, - branch - })); - return { - best, - location, - defaultEntries, - node: node2 - }; -}; -var resolveCase = (ctx, key) => { - const caseCtx = ctx.best.cases[key]; - const discriminantNode = discriminantCaseToNode(caseCtx.condition, ctx.location.path, ctx.node.$); - let resolvedEntries = []; - const nextDefaults = []; - for (let i = 0; i < ctx.defaultEntries.length; i++) { - const entry = ctx.defaultEntries[i]; - if (caseCtx.branchIndices.includes(entry.originalIndex)) { - const pruned = pruneDiscriminant(ctx.node.branches[entry.originalIndex], ctx.location); - if (pruned === null) { - resolvedEntries = null; - } else { - resolvedEntries?.push({ - originalIndex: entry.originalIndex, - branch: pruned - }); - } - } else if ( - // we shouldn't need a special case for alias to avoid the below - // once alias resolution issues are improved: - // https://github.com/arktypeio/arktype/issues/1026 - entry.branch.hasKind("alias") && discriminantNode.hasKind("domain") && discriminantNode.domain === "object" - ) - resolvedEntries?.push(entry); - else { - if (entry.branch.rawIn.overlaps(discriminantNode)) { - const overlapping = pruneDiscriminant(entry.branch, ctx.location); - resolvedEntries?.push({ - originalIndex: entry.originalIndex, - branch: overlapping - }); - } - nextDefaults.push(entry); - } - } - ctx.defaultEntries = nextDefaults; - return resolvedEntries; -}; -var viableOrderedCandidates = (candidates, originalBranches) => { - const viableCandidates = candidates.filter((candidate) => { - const caseGroups = Object.values(candidate.cases).map((caseCtx) => caseCtx.branchIndices); - for (let i = 0; i < caseGroups.length - 1; i++) { - const currentGroup = caseGroups[i]; - for (let j = i + 1; j < caseGroups.length; j++) { - const nextGroup = caseGroups[j]; - for (const currentIndex of currentGroup) { - for (const nextIndex of nextGroup) { - if (currentIndex > nextIndex) { - if (originalBranches[currentIndex].overlaps(originalBranches[nextIndex])) { - return false; - } - } - } - } - } - } - return true; - }); - return viableCandidates; -}; -var discriminantCaseToNode = (caseDiscriminant, path3, $2) => { - let node2 = caseDiscriminant === "undefined" ? $2.node("unit", { unit: void 0 }) : caseDiscriminant === "null" ? $2.node("unit", { unit: null }) : caseDiscriminant === "boolean" ? $2.units([true, false]) : caseDiscriminant; - for (let i = path3.length - 1; i >= 0; i--) { - const key = path3[i]; - node2 = $2.node("intersection", typeof key === "number" ? { - proto: "Array", - // create unknown for preceding elements (could be optimized with safe imports) - sequence: [...range(key).map((_) => ({})), node2] - } : { - domain: "object", - required: [{ key, value: node2 }] - }); - } - return node2; -}; -var optionallyChainPropString = (path3) => path3.reduce((acc, k) => acc + compileLiteralPropAccess(k, true), "data"); -var serializedTypeOfDescriptions = registeredReference(jsTypeOfDescriptions); -var serializedPrintable = registeredReference(printable); -var Union = { - implementation: implementation17, - Node: UnionNode -}; -var discriminantToJson = (discriminant) => ({ - kind: discriminant.kind, - path: discriminant.path.map((k) => typeof k === "string" ? k : compileSerializedValue(k)), - cases: flatMorph(discriminant.cases, (k, node2) => [ - k, - node2 === true ? node2 : node2.hasKind("union") && node2.discriminantJson ? node2.discriminantJson : node2.json - ]) -}); -var describeExpressionOptions = { - delimiter: " | ", - finalDelimiter: " | " -}; -var expressBranches = (expressions) => describeBranches(expressions, describeExpressionOptions); -var describeBranches = (descriptions, opts) => { - const delimiter = opts?.delimiter ?? ", "; - const finalDelimiter = opts?.finalDelimiter ?? " or "; - if (descriptions.length === 0) - return "never"; - if (descriptions.length === 1) - return descriptions[0]; - if (descriptions.length === 2 && descriptions[0] === "false" && descriptions[1] === "true" || descriptions[0] === "true" && descriptions[1] === "false") - return "boolean"; - const seen = {}; - const unique = descriptions.filter((s) => seen[s] ? false : seen[s] = true); - const last = unique.pop(); - return `${unique.join(delimiter)}${unique.length ? finalDelimiter : ""}${last}`; -}; -var intersectBranches = (l, r, ctx) => { - const batchesByR = r.map(() => []); - for (let lIndex = 0; lIndex < l.length; lIndex++) { - let candidatesByR = {}; - for (let rIndex = 0; rIndex < r.length; rIndex++) { - if (batchesByR[rIndex] === null) { - continue; - } - if (l[lIndex].equals(r[rIndex])) { - batchesByR[rIndex] = null; - candidatesByR = {}; - break; - } - const branchIntersection = intersectOrPipeNodes(l[lIndex], r[rIndex], ctx); - if (branchIntersection instanceof Disjoint) { - continue; - } - if (branchIntersection.equals(l[lIndex])) { - batchesByR[rIndex].push(l[lIndex]); - candidatesByR = {}; - break; - } - if (branchIntersection.equals(r[rIndex])) { - batchesByR[rIndex] = null; - } else { - candidatesByR[rIndex] = branchIntersection; - } - } - for (const rIndex in candidatesByR) { - batchesByR[rIndex][lIndex] = candidatesByR[rIndex]; - } - } - const resultBranches = batchesByR.flatMap( - // ensure unions returned from branchable intersections like sequence are flattened - (batch, i) => batch?.flatMap((branch) => branch.branches) ?? r[i] - ); - return resultBranches.length === 0 ? Disjoint.init("union", l, r) : resultBranches; -}; -var reduceBranches = ({ branches, ordered }) => { - if (branches.length < 2) - return branches; - const uniquenessByIndex = branches.map(() => true); - for (let i = 0; i < branches.length; i++) { - for (let j = i + 1; j < branches.length && uniquenessByIndex[i] && uniquenessByIndex[j]; j++) { - if (branches[i].equals(branches[j])) { - uniquenessByIndex[j] = false; - continue; - } - const intersection3 = intersectNodesRoot(branches[i].rawIn, branches[j].rawIn, branches[0].$); - if (intersection3 instanceof Disjoint) - continue; - if (!ordered) - assertDeterminateOverlap(branches[i], branches[j]); - if (intersection3.equals(branches[i].rawIn)) { - uniquenessByIndex[i] = !!ordered; - } else if (intersection3.equals(branches[j].rawIn)) - uniquenessByIndex[j] = false; - } - } - return branches.filter((_, i) => uniquenessByIndex[i]); -}; -var assertDeterminateOverlap = (l, r) => { - if (!l.includesTransform && !r.includesTransform) - return; - if (!arrayEquals(l.shallowMorphs, r.shallowMorphs)) { - throwParseError(writeIndiscriminableMorphMessage(l.expression, r.expression)); - } - if (!arrayEquals(l.flatMorphs, r.flatMorphs, { - isEqual: (l2, r2) => l2.propString === r2.propString && (l2.node.hasKind("morph") && r2.node.hasKind("morph") ? l2.node.hasEqualMorphs(r2.node) : l2.node.hasKind("intersection") && r2.node.hasKind("intersection") ? l2.node.structure?.structuralMorphRef === r2.node.structure?.structuralMorphRef : false) - })) { - throwParseError(writeIndiscriminableMorphMessage(l.expression, r.expression)); - } -}; -var pruneDiscriminant = (discriminantBranch, discriminantCtx) => discriminantBranch.transform((nodeKind, inner) => { - if (nodeKind === "domain" || nodeKind === "unit") - return null; - return inner; -}, { - shouldTransform: (node2, ctx) => { - const propString = optionallyChainPropString(ctx.path); - if (!discriminantCtx.optionallyChainedPropString.startsWith(propString)) - return false; - if (node2.hasKind("domain") && node2.domain === "object") - return true; - if ((node2.hasKind("domain") || discriminantCtx.kind === "unit") && propString === discriminantCtx.optionallyChainedPropString) - return true; - return node2.children.length !== 0 && node2.kind !== "index"; - } -}); -var writeIndiscriminableMorphMessage = (lDescription, rDescription) => `An unordered union of a type including a morph and a type with overlapping input is indeterminate: -Left: ${lDescription} -Right: ${rDescription}`; -var writeOrderedIntersectionMessage = (lDescription, rDescription) => `The intersection of two ordered unions is indeterminate: -Left: ${lDescription} -Right: ${rDescription}`; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/roots/unit.js -var implementation18 = implementNode({ - kind: "unit", - hasAssociatedError: true, - keys: { - unit: { - preserveUndefined: true, - serialize: (schema2) => schema2 instanceof Date ? schema2.toISOString() : defaultValueSerializer(schema2) - } - }, - normalize: (schema2) => schema2, - defaults: { - description: (node2) => printable(node2.unit), - problem: ({ expected, actual }) => `${expected === actual ? `must be reference equal to ${expected} (serialized to the same value)` : `must be ${expected} (was ${actual})`}` - }, - intersections: { - unit: (l, r) => Disjoint.init("unit", l, r), - ...defineRightwardIntersections("unit", (l, r) => { - if (r.allows(l.unit)) - return l; - const rBasis = r.hasKind("intersection") ? r.basis : r; - if (rBasis) { - const rDomain = rBasis.hasKind("domain") ? rBasis : $ark.intrinsic.object; - if (l.domain !== rDomain.domain) { - const lDomainDisjointValue = l.domain === "undefined" || l.domain === "null" || l.domain === "boolean" ? l.domain : $ark.intrinsic[l.domain]; - return Disjoint.init("domain", lDomainDisjointValue, rDomain); - } - } - return Disjoint.init("assignability", l, r.hasKind("intersection") ? r.children.find((rConstraint) => !rConstraint.allows(l.unit)) : r); - }) - } -}); -var UnitNode = class extends InternalBasis { - compiledValue = this.json.unit; - serializedValue = typeof this.unit === "string" || this.unit instanceof Date ? JSON.stringify(this.compiledValue) : `${this.compiledValue}`; - compiledCondition = compileEqualityCheck(this.unit, this.serializedValue); - compiledNegation = compileEqualityCheck(this.unit, this.serializedValue, "negated"); - expression = printable(this.unit); - domain = domainOf(this.unit); - get defaultShortDescription() { - return this.domain === "object" ? domainDescriptions.object : this.description; - } - innerToJsonSchema(ctx) { - return ( - // this is the more standard JSON schema representation, especially for Open API - this.unit === null ? { type: "null" } : $ark.intrinsic.jsonPrimitive.allows(this.unit) ? { const: this.unit } : ctx.fallback.unit({ code: "unit", base: {}, unit: this.unit }) - ); - } - traverseAllows = this.unit instanceof Date ? (data) => data instanceof Date && data.toISOString() === this.compiledValue : Number.isNaN(this.unit) ? (data) => Number.isNaN(data) : (data) => data === this.unit; -}; -var Unit = { - implementation: implementation18, - Node: UnitNode -}; -var compileEqualityCheck = (unit, serializedValue, negated) => { - if (unit instanceof Date) { - const condition = `data instanceof Date && data.toISOString() === ${serializedValue}`; - return negated ? `!(${condition})` : condition; - } - if (Number.isNaN(unit)) - return `${negated ? "!" : ""}Number.isNaN(data)`; - return `data ${negated ? "!" : "="}== ${serializedValue}`; -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/index.js -var implementation19 = implementNode({ - kind: "index", - hasAssociatedError: false, - intersectionIsOpen: true, - keys: { - signature: { - child: true, - parse: (schema2, ctx) => { - const key = ctx.$.parseSchema(schema2); - if (!key.extends($ark.intrinsic.key)) { - return throwParseError(writeInvalidPropertyKeyMessage(key.expression)); - } - const enumerableBranches = key.branches.filter((b) => b.hasKind("unit")); - if (enumerableBranches.length) { - return throwParseError(writeEnumerableIndexBranches(enumerableBranches.map((b) => printable(b.unit)))); - } - return key; - } - }, - value: { - child: true, - parse: (schema2, ctx) => ctx.$.parseSchema(schema2) - } - }, - normalize: (schema2) => schema2, - defaults: { - description: (node2) => `[${node2.signature.expression}]: ${node2.value.description}` - }, - intersections: { - index: (l, r, ctx) => { - if (l.signature.equals(r.signature)) { - const valueIntersection = intersectOrPipeNodes(l.value, r.value, ctx); - const value2 = valueIntersection instanceof Disjoint ? $ark.intrinsic.never.internal : valueIntersection; - return ctx.$.node("index", { signature: l.signature, value: value2 }); - } - if (l.signature.extends(r.signature) && l.value.subsumes(r.value)) - return r; - if (r.signature.extends(l.signature) && r.value.subsumes(l.value)) - return l; - return null; - } - } -}); -var IndexNode = class extends BaseConstraint { - impliedBasis = $ark.intrinsic.object.internal; - expression = `[${this.signature.expression}]: ${this.value.expression}`; - flatRefs = append(this.value.flatRefs.map((ref) => flatRef([this.signature, ...ref.path], ref.node)), flatRef([this.signature], this.value)); - traverseAllows = (data, ctx) => stringAndSymbolicEntriesOf(data).every((entry) => { - if (this.signature.traverseAllows(entry[0], ctx)) { - return traverseKey(entry[0], () => this.value.traverseAllows(entry[1], ctx), ctx); - } - return true; - }); - traverseApply = (data, ctx) => { - for (const entry of stringAndSymbolicEntriesOf(data)) { - if (this.signature.traverseAllows(entry[0], ctx)) { - traverseKey(entry[0], () => this.value.traverseApply(entry[1], ctx), ctx); - } - } - }; - _transform(mapper, ctx) { - ctx.path.push(this.signature); - const result = super._transform(mapper, ctx); - ctx.path.pop(); - return result; - } - compile() { - } -}; -var Index = { - implementation: implementation19, - Node: IndexNode -}; -var writeEnumerableIndexBranches = (keys) => `Index keys ${keys.join(", ")} should be specified as named props.`; -var writeInvalidPropertyKeyMessage = (indexSchema) => `Indexed key definition '${indexSchema}' must be a string or symbol`; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/required.js -var implementation20 = implementNode({ - kind: "required", - hasAssociatedError: true, - intersectionIsOpen: true, - keys: { - key: {}, - value: { - child: true, - parse: (schema2, ctx) => ctx.$.parseSchema(schema2) - } - }, - normalize: (schema2) => schema2, - defaults: { - description: (node2) => `${node2.compiledKey}: ${node2.value.description}`, - expected: (ctx) => ctx.missingValueDescription, - actual: () => "missing" - }, - intersections: { - required: intersectProps, - optional: intersectProps - } -}); -var RequiredNode = class extends BaseProp { - expression = `${this.compiledKey}: ${this.value.expression}`; - errorContext = Object.freeze({ - code: "required", - missingValueDescription: this.value.defaultShortDescription, - relativePath: [this.key], - meta: this.meta - }); - compiledErrorContext = compileObjectLiteral(this.errorContext); -}; -var Required = { - implementation: implementation20, - Node: RequiredNode -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/sequence.js -var implementation21 = implementNode({ - kind: "sequence", - hasAssociatedError: false, - collapsibleKey: "variadic", - keys: { - prefix: { - child: true, - parse: (schema2, ctx) => { - if (schema2.length === 0) - return void 0; - return schema2.map((element) => ctx.$.parseSchema(element)); - } - }, - optionals: { - child: true, - parse: (schema2, ctx) => { - if (schema2.length === 0) - return void 0; - return schema2.map((element) => ctx.$.parseSchema(element)); - } - }, - defaultables: { - child: (defaultables) => defaultables.map((element) => element[0]), - parse: (defaultables, ctx) => { - if (defaultables.length === 0) - return void 0; - return defaultables.map((element) => { - const node2 = ctx.$.parseSchema(element[0]); - assertDefaultValueAssignability(node2, element[1], null); - return [node2, element[1]]; - }); - }, - serialize: (defaults) => defaults.map((element) => [ - element[0].collapsibleJson, - defaultValueSerializer(element[1]) - ]), - reduceIo: (ioKind, inner, defaultables) => { - if (ioKind === "in") { - inner.optionals = defaultables.map((d) => d[0].rawIn); - return; - } - inner.prefix = defaultables.map((d) => d[0].rawOut); - return; - } - }, - variadic: { - child: true, - parse: (schema2, ctx) => ctx.$.parseSchema(schema2, ctx) - }, - minVariadicLength: { - // minVariadicLength is reflected in the id of this node, - // but not its IntersectionNode parent since it is superceded by the minLength - // node it implies - parse: (min) => min === 0 ? void 0 : min - }, - postfix: { - child: true, - parse: (schema2, ctx) => { - if (schema2.length === 0) - return void 0; - return schema2.map((element) => ctx.$.parseSchema(element)); - } - } - }, - normalize: (schema2) => { - if (typeof schema2 === "string") - return { variadic: schema2 }; - if ("variadic" in schema2 || "prefix" in schema2 || "defaultables" in schema2 || "optionals" in schema2 || "postfix" in schema2 || "minVariadicLength" in schema2) { - if (schema2.postfix?.length) { - if (!schema2.variadic) - return throwParseError(postfixWithoutVariadicMessage); - if (schema2.optionals?.length || schema2.defaultables?.length) - return throwParseError(postfixAfterOptionalOrDefaultableMessage); - } - if (schema2.minVariadicLength && !schema2.variadic) { - return throwParseError("minVariadicLength may not be specified without a variadic element"); - } - return schema2; - } - return { variadic: schema2 }; - }, - reduce: (raw2, $2) => { - let minVariadicLength = raw2.minVariadicLength ?? 0; - const prefix = raw2.prefix?.slice() ?? []; - const defaultables = raw2.defaultables?.slice() ?? []; - const optionals = raw2.optionals?.slice() ?? []; - const postfix = raw2.postfix?.slice() ?? []; - if (raw2.variadic) { - while (optionals[optionals.length - 1]?.equals(raw2.variadic)) - optionals.pop(); - if (optionals.length === 0 && defaultables.length === 0) { - while (prefix[prefix.length - 1]?.equals(raw2.variadic)) { - prefix.pop(); - minVariadicLength++; - } - } - while (postfix[0]?.equals(raw2.variadic)) { - postfix.shift(); - minVariadicLength++; - } - } else if (optionals.length === 0 && defaultables.length === 0) { - prefix.push(...postfix.splice(0)); - } - if ( - // if any variadic adjacent elements were moved to minVariadicLength - minVariadicLength !== raw2.minVariadicLength || // or any postfix elements were moved to prefix - raw2.prefix && raw2.prefix.length !== prefix.length - ) { - return $2.node("sequence", { - ...raw2, - // empty lists will be omitted during parsing - prefix, - defaultables, - optionals, - postfix, - minVariadicLength - }, { prereduced: true }); - } - }, - defaults: { - description: (node2) => { - if (node2.isVariadicOnly) - return `${node2.variadic.nestableExpression}[]`; - const innerDescription = node2.tuple.map((element) => element.kind === "defaultables" ? `${element.node.nestableExpression} = ${printable(element.default)}` : element.kind === "optionals" ? `${element.node.nestableExpression}?` : element.kind === "variadic" ? `...${element.node.nestableExpression}[]` : element.node.expression).join(", "); - return `[${innerDescription}]`; - } - }, - intersections: { - sequence: (l, r, ctx) => { - const rootState = _intersectSequences({ - l: l.tuple, - r: r.tuple, - disjoint: new Disjoint(), - result: [], - fixedVariants: [], - ctx - }); - const viableBranches = rootState.disjoint.length === 0 ? [rootState, ...rootState.fixedVariants] : rootState.fixedVariants; - return viableBranches.length === 0 ? rootState.disjoint : viableBranches.length === 1 ? ctx.$.node("sequence", sequenceTupleToInner(viableBranches[0].result)) : ctx.$.node("union", viableBranches.map((state) => ({ - proto: Array, - sequence: sequenceTupleToInner(state.result) - }))); - } - // exactLength, minLength, and maxLength don't need to be defined - // here since impliedSiblings guarantees they will be added - // directly to the IntersectionNode parent of the SequenceNode - // they exist on - } -}); -var SequenceNode = class extends BaseConstraint { - impliedBasis = $ark.intrinsic.Array.internal; - tuple = sequenceInnerToTuple(this.inner); - prefixLength = this.prefix?.length ?? 0; - defaultablesLength = this.defaultables?.length ?? 0; - optionalsLength = this.optionals?.length ?? 0; - postfixLength = this.postfix?.length ?? 0; - defaultablesAndOptionals = []; - prevariadic = this.tuple.filter((el) => { - if (el.kind === "defaultables" || el.kind === "optionals") { - this.defaultablesAndOptionals.push(el.node); - return true; - } - return el.kind === "prefix"; - }); - variadicOrPostfix = conflatenate(this.variadic && [this.variadic], this.postfix); - // have to wait until prevariadic and variadicOrPostfix are set to calculate - flatRefs = this.addFlatRefs(); - addFlatRefs() { - appendUniqueFlatRefs(this.flatRefs, this.prevariadic.flatMap((element, i) => append(element.node.flatRefs.map((ref) => flatRef([`${i}`, ...ref.path], ref.node)), flatRef([`${i}`], element.node)))); - appendUniqueFlatRefs(this.flatRefs, this.variadicOrPostfix.flatMap((element) => ( - // a postfix index can't be directly represented as a type - // key, so we just use the same matcher for variadic - append(element.flatRefs.map((ref) => flatRef([$ark.intrinsic.nonNegativeIntegerString.internal, ...ref.path], ref.node)), flatRef([$ark.intrinsic.nonNegativeIntegerString.internal], element)) - ))); - return this.flatRefs; - } - isVariadicOnly = this.prevariadic.length + this.postfixLength === 0; - minVariadicLength = this.inner.minVariadicLength ?? 0; - minLength = this.prefixLength + this.minVariadicLength + this.postfixLength; - minLengthNode = this.minLength === 0 ? null : this.$.node("minLength", this.minLength); - maxLength = this.variadic ? null : this.tuple.length; - maxLengthNode = this.maxLength === null ? null : this.$.node("maxLength", this.maxLength); - impliedSiblings = this.minLengthNode ? this.maxLengthNode ? [this.minLengthNode, this.maxLengthNode] : [this.minLengthNode] : this.maxLengthNode ? [this.maxLengthNode] : []; - defaultValueMorphs = getDefaultableMorphs(this); - defaultValueMorphsReference = this.defaultValueMorphs.length ? registeredReference(this.defaultValueMorphs) : void 0; - elementAtIndex(data, index) { - if (index < this.prevariadic.length) - return this.tuple[index]; - const firstPostfixIndex = data.length - this.postfixLength; - if (index >= firstPostfixIndex) - return { kind: "postfix", node: this.postfix[index - firstPostfixIndex] }; - return { - kind: "variadic", - node: this.variadic ?? throwInternalError(`Unexpected attempt to access index ${index} on ${this}`) - }; - } - // minLength/maxLength should be checked by Intersection before either traversal - traverseAllows = (data, ctx) => { - for (let i = 0; i < data.length; i++) { - if (!this.elementAtIndex(data, i).node.traverseAllows(data[i], ctx)) - return false; - } - return true; - }; - traverseApply = (data, ctx) => { - let i = 0; - for (; i < data.length; i++) { - traverseKey(i, () => this.elementAtIndex(data, i).node.traverseApply(data[i], ctx), ctx); - } - }; - get element() { - return this.cacheGetter("element", this.$.node("union", this.children)); - } - // minLength/maxLength compilation should be handled by Intersection - compile(js) { - if (this.prefix) { - for (const [i, node2] of this.prefix.entries()) - js.traverseKey(`${i}`, `data[${i}]`, node2); - } - for (const [i, node2] of this.defaultablesAndOptionals.entries()) { - const dataIndex = `${i + this.prefixLength}`; - js.if(`${dataIndex} >= data.length`, () => js.traversalKind === "Allows" ? js.return(true) : js.return()); - js.traverseKey(dataIndex, `data[${dataIndex}]`, node2); - } - if (this.variadic) { - if (this.postfix) { - js.const("firstPostfixIndex", `data.length${this.postfix ? `- ${this.postfix.length}` : ""}`); - } - js.for(`i < ${this.postfix ? "firstPostfixIndex" : "data.length"}`, () => js.traverseKey("i", "data[i]", this.variadic), this.prevariadic.length); - if (this.postfix) { - for (const [i, node2] of this.postfix.entries()) { - const keyExpression = `firstPostfixIndex + ${i}`; - js.traverseKey(keyExpression, `data[${keyExpression}]`, node2); - } - } - } - if (js.traversalKind === "Allows") - js.return(true); - } - _transform(mapper, ctx) { - ctx.path.push($ark.intrinsic.nonNegativeIntegerString.internal); - const result = super._transform(mapper, ctx); - ctx.path.pop(); - return result; - } - // this depends on tuple so needs to come after it - expression = this.description; - reduceJsonSchema(schema2, ctx) { - const isDraft07 = ctx.target === "draft-07"; - if (this.prevariadic.length) { - const prefixSchemas = this.prevariadic.map((el) => { - const valueSchema = el.node.toJsonSchemaRecurse(ctx); - if (el.kind === "defaultables") { - const value2 = typeof el.default === "function" ? el.default() : el.default; - valueSchema.default = $ark.intrinsic.jsonData.allows(value2) ? value2 : ctx.fallback.defaultValue({ - code: "defaultValue", - base: valueSchema, - value: value2 - }); - } - return valueSchema; - }); - if (isDraft07) - schema2.items = prefixSchemas; - else - schema2.prefixItems = prefixSchemas; - } - if (this.minLength) - schema2.minItems = this.minLength; - if (this.variadic) { - const variadicItemSchema = this.variadic.toJsonSchemaRecurse(ctx); - if (isDraft07 && this.prevariadic.length) - schema2.additionalItems = variadicItemSchema; - else - schema2.items = variadicItemSchema; - if (this.maxLength) - schema2.maxItems = this.maxLength; - if (this.postfix) { - const elements = this.postfix.map((el) => el.toJsonSchemaRecurse(ctx)); - schema2 = ctx.fallback.arrayPostfix({ - code: "arrayPostfix", - base: schema2, - elements - }); - } - } else { - if (isDraft07) - schema2.additionalItems = false; - else - schema2.items = false; - delete schema2.maxItems; - } - return schema2; - } -}; -var defaultableMorphsCache = {}; -var getDefaultableMorphs = (node2) => { - if (!node2.defaultables) - return []; - const morphs = []; - let cacheKey = "["; - const lastDefaultableIndex = node2.prefixLength + node2.defaultablesLength - 1; - for (let i = node2.prefixLength; i <= lastDefaultableIndex; i++) { - const [elementNode, defaultValue] = node2.defaultables[i - node2.prefixLength]; - morphs.push(computeDefaultValueMorph(i, elementNode, defaultValue)); - cacheKey += `${i}: ${elementNode.id} = ${defaultValueSerializer(defaultValue)}, `; - } - cacheKey += "]"; - return defaultableMorphsCache[cacheKey] ??= morphs; -}; -var Sequence = { - implementation: implementation21, - Node: SequenceNode -}; -var sequenceInnerToTuple = (inner) => { - const tuple2 = []; - if (inner.prefix) - for (const node2 of inner.prefix) - tuple2.push({ kind: "prefix", node: node2 }); - if (inner.defaultables) { - for (const [node2, defaultValue] of inner.defaultables) - tuple2.push({ kind: "defaultables", node: node2, default: defaultValue }); - } - if (inner.optionals) - for (const node2 of inner.optionals) - tuple2.push({ kind: "optionals", node: node2 }); - if (inner.variadic) - tuple2.push({ kind: "variadic", node: inner.variadic }); - if (inner.postfix) - for (const node2 of inner.postfix) - tuple2.push({ kind: "postfix", node: node2 }); - return tuple2; -}; -var sequenceTupleToInner = (tuple2) => tuple2.reduce((result, element) => { - if (element.kind === "variadic") - result.variadic = element.node; - else if (element.kind === "defaultables") { - result.defaultables = append(result.defaultables, [ - [element.node, element.default] - ]); - } else - result[element.kind] = append(result[element.kind], element.node); - return result; -}, {}); -var postfixAfterOptionalOrDefaultableMessage = "A postfix required element cannot follow an optional or defaultable element"; -var postfixWithoutVariadicMessage = "A postfix element requires a variadic element"; -var _intersectSequences = (s) => { - const [lHead, ...lTail] = s.l; - const [rHead, ...rTail] = s.r; - if (!lHead || !rHead) - return s; - const lHasPostfix = lTail[lTail.length - 1]?.kind === "postfix"; - const rHasPostfix = rTail[rTail.length - 1]?.kind === "postfix"; - const kind = lHead.kind === "prefix" || rHead.kind === "prefix" ? "prefix" : lHead.kind === "postfix" || rHead.kind === "postfix" ? "postfix" : lHead.kind === "variadic" && rHead.kind === "variadic" ? "variadic" : lHasPostfix || rHasPostfix ? "prefix" : lHead.kind === "defaultables" || rHead.kind === "defaultables" ? "defaultables" : "optionals"; - if (lHead.kind === "prefix" && rHead.kind === "variadic" && rHasPostfix) { - const postfixBranchResult = _intersectSequences({ - ...s, - fixedVariants: [], - r: rTail.map((element) => ({ ...element, kind: "prefix" })) - }); - if (postfixBranchResult.disjoint.length === 0) - s.fixedVariants.push(postfixBranchResult); - } else if (rHead.kind === "prefix" && lHead.kind === "variadic" && lHasPostfix) { - const postfixBranchResult = _intersectSequences({ - ...s, - fixedVariants: [], - l: lTail.map((element) => ({ ...element, kind: "prefix" })) - }); - if (postfixBranchResult.disjoint.length === 0) - s.fixedVariants.push(postfixBranchResult); - } - const result = intersectOrPipeNodes(lHead.node, rHead.node, s.ctx); - if (result instanceof Disjoint) { - if (kind === "prefix" || kind === "postfix") { - s.disjoint.push(...result.withPrefixKey( - // ideally we could handle disjoint paths more precisely here, - // but not trivial to serialize postfix elements as keys - kind === "prefix" ? s.result.length : `-${lTail.length + 1}`, - // both operands must be required for the disjoint to be considered required - elementIsRequired(lHead) && elementIsRequired(rHead) ? "required" : "optional" - )); - s.result = [...s.result, { kind, node: $ark.intrinsic.never.internal }]; - } else if (kind === "optionals" || kind === "defaultables") { - return s; - } else { - return _intersectSequences({ - ...s, - fixedVariants: [], - // if there were any optional elements, there will be no postfix elements - // so this mapping will never occur (which would be illegal otherwise) - l: lTail.map((element) => ({ ...element, kind: "prefix" })), - r: lTail.map((element) => ({ ...element, kind: "prefix" })) - }); - } - } else if (kind === "defaultables") { - if (lHead.kind === "defaultables" && rHead.kind === "defaultables" && lHead.default !== rHead.default) { - throwParseError(writeDefaultIntersectionMessage(lHead.default, rHead.default)); - } - s.result = [ - ...s.result, - { - kind, - node: result, - default: lHead.kind === "defaultables" ? lHead.default : rHead.kind === "defaultables" ? rHead.default : throwInternalError(`Unexpected defaultable intersection from ${lHead.kind} and ${rHead.kind} elements.`) - } - ]; - } else - s.result = [...s.result, { kind, node: result }]; - const lRemaining = s.l.length; - const rRemaining = s.r.length; - if (lHead.kind !== "variadic" || lRemaining >= rRemaining && (rHead.kind === "variadic" || rRemaining === 1)) - s.l = lTail; - if (rHead.kind !== "variadic" || rRemaining >= lRemaining && (lHead.kind === "variadic" || lRemaining === 1)) - s.r = rTail; - return _intersectSequences(s); -}; -var elementIsRequired = (el) => el.kind === "prefix" || el.kind === "postfix"; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/structure.js -var createStructuralWriter = (childStringProp) => (node2) => { - if (node2.props.length || node2.index) { - const parts = node2.index?.map((index) => index[childStringProp]) ?? []; - for (const prop of node2.props) - parts.push(prop[childStringProp]); - if (node2.undeclared) - parts.push(`+ (undeclared): ${node2.undeclared}`); - const objectLiteralDescription = `{ ${parts.join(", ")} }`; - return node2.sequence ? `${objectLiteralDescription} & ${node2.sequence.description}` : objectLiteralDescription; - } - return node2.sequence?.description ?? "{}"; -}; -var structuralDescription = createStructuralWriter("description"); -var structuralExpression = createStructuralWriter("expression"); -var intersectPropsAndIndex = (l, r, $2) => { - const kind = l.required ? "required" : "optional"; - if (!r.signature.allows(l.key)) - return null; - const value2 = intersectNodesRoot(l.value, r.value, $2); - if (value2 instanceof Disjoint) { - return kind === "optional" ? $2.node("optional", { - key: l.key, - value: $ark.intrinsic.never.internal - }) : value2.withPrefixKey(l.key, l.kind); - } - return null; -}; -var implementation22 = implementNode({ - kind: "structure", - hasAssociatedError: false, - normalize: (schema2) => schema2, - applyConfig: (schema2, config3) => { - if (!schema2.undeclared && config3.onUndeclaredKey !== "ignore") { - return { - ...schema2, - undeclared: config3.onUndeclaredKey - }; - } - return schema2; - }, - keys: { - required: { - child: true, - parse: constraintKeyParser("required"), - reduceIo: (ioKind, inner, nodes) => { - inner.required = append(inner.required, nodes.map((node2) => ioKind === "in" ? node2.rawIn : node2.rawOut)); - return; - } - }, - optional: { - child: true, - parse: constraintKeyParser("optional"), - reduceIo: (ioKind, inner, nodes) => { - if (ioKind === "in") { - inner.optional = nodes.map((node2) => node2.rawIn); - return; - } - for (const node2 of nodes) { - inner[node2.outProp.kind] = append(inner[node2.outProp.kind], node2.outProp.rawOut); - } - } - }, - index: { - child: true, - parse: constraintKeyParser("index") - }, - sequence: { - child: true, - parse: constraintKeyParser("sequence") - }, - undeclared: { - parse: (behavior) => behavior === "ignore" ? void 0 : behavior, - reduceIo: (ioKind, inner, value2) => { - if (value2 === "reject") { - inner.undeclared = "reject"; - return; - } - if (ioKind === "in") - delete inner.undeclared; - else - inner.undeclared = "reject"; - } - } - }, - defaults: { - description: structuralDescription - }, - intersections: { - structure: (l, r, ctx) => { - const lInner = { ...l.inner }; - const rInner = { ...r.inner }; - const disjointResult = new Disjoint(); - if (l.undeclared) { - const lKey = l.keyof(); - for (const k of r.requiredKeys) { - if (!lKey.allows(k)) { - disjointResult.add("presence", $ark.intrinsic.never.internal, r.propsByKey[k].value, { - path: [k] - }); - } - } - if (rInner.optional) - rInner.optional = rInner.optional.filter((n) => lKey.allows(n.key)); - if (rInner.index) { - rInner.index = rInner.index.flatMap((n) => { - if (n.signature.extends(lKey)) - return n; - const indexOverlap = intersectNodesRoot(lKey, n.signature, ctx.$); - if (indexOverlap instanceof Disjoint) - return []; - const normalized = normalizeIndex(indexOverlap, n.value, ctx.$); - if (normalized.required) { - rInner.required = conflatenate(rInner.required, normalized.required); - } - if (normalized.optional) { - rInner.optional = conflatenate(rInner.optional, normalized.optional); - } - return normalized.index ?? []; - }); - } - } - if (r.undeclared) { - const rKey = r.keyof(); - for (const k of l.requiredKeys) { - if (!rKey.allows(k)) { - disjointResult.add("presence", l.propsByKey[k].value, $ark.intrinsic.never.internal, { - path: [k] - }); - } - } - if (lInner.optional) - lInner.optional = lInner.optional.filter((n) => rKey.allows(n.key)); - if (lInner.index) { - lInner.index = lInner.index.flatMap((n) => { - if (n.signature.extends(rKey)) - return n; - const indexOverlap = intersectNodesRoot(rKey, n.signature, ctx.$); - if (indexOverlap instanceof Disjoint) - return []; - const normalized = normalizeIndex(indexOverlap, n.value, ctx.$); - if (normalized.required) { - lInner.required = conflatenate(lInner.required, normalized.required); - } - if (normalized.optional) { - lInner.optional = conflatenate(lInner.optional, normalized.optional); - } - return normalized.index ?? []; - }); - } - } - const baseInner = {}; - if (l.undeclared || r.undeclared) { - baseInner.undeclared = l.undeclared === "reject" || r.undeclared === "reject" ? "reject" : "delete"; - } - const childIntersectionResult = intersectConstraints({ - kind: "structure", - baseInner, - l: flattenConstraints(lInner), - r: flattenConstraints(rInner), - roots: [], - ctx - }); - if (childIntersectionResult instanceof Disjoint) - disjointResult.push(...childIntersectionResult); - if (disjointResult.length) - return disjointResult; - return childIntersectionResult; - } - }, - reduce: (inner, $2) => { - if (!inner.required && !inner.optional) - return; - const seen = {}; - let updated = false; - const newOptionalProps = inner.optional ? [...inner.optional] : []; - if (inner.required) { - for (let i = 0; i < inner.required.length; i++) { - const requiredProp = inner.required[i]; - if (requiredProp.key in seen) - throwParseError(writeDuplicateKeyMessage(requiredProp.key)); - seen[requiredProp.key] = true; - if (inner.index) { - for (const index of inner.index) { - const intersection3 = intersectPropsAndIndex(requiredProp, index, $2); - if (intersection3 instanceof Disjoint) - return intersection3; - } - } - } - } - if (inner.optional) { - for (let i = 0; i < inner.optional.length; i++) { - const optionalProp = inner.optional[i]; - if (optionalProp.key in seen) - throwParseError(writeDuplicateKeyMessage(optionalProp.key)); - seen[optionalProp.key] = true; - if (inner.index) { - for (const index of inner.index) { - const intersection3 = intersectPropsAndIndex(optionalProp, index, $2); - if (intersection3 instanceof Disjoint) - return intersection3; - if (intersection3 !== null) { - newOptionalProps[i] = intersection3; - updated = true; - } - } - } - } - } - if (updated) { - return $2.node("structure", { ...inner, optional: newOptionalProps }, { prereduced: true }); - } - } -}); -var StructureNode = class extends BaseConstraint { - impliedBasis = $ark.intrinsic.object.internal; - impliedSiblings = this.children.flatMap((n) => n.impliedSiblings ?? []); - props = conflatenate(this.required, this.optional); - propsByKey = flatMorph(this.props, (i, node2) => [node2.key, node2]); - propsByKeyReference = registeredReference(this.propsByKey); - expression = structuralExpression(this); - requiredKeys = this.required?.map((node2) => node2.key) ?? []; - optionalKeys = this.optional?.map((node2) => node2.key) ?? []; - literalKeys = [...this.requiredKeys, ...this.optionalKeys]; - _keyof; - keyof() { - if (this._keyof) - return this._keyof; - let branches = this.$.units(this.literalKeys).branches; - if (this.index) { - for (const { signature } of this.index) - branches = branches.concat(signature.branches); - } - return this._keyof = this.$.node("union", branches); - } - map(flatMapProp) { - return this.$.node("structure", this.props.flatMap(flatMapProp).reduce((structureInner, mapped) => { - const originalProp = this.propsByKey[mapped.key]; - if (isNode(mapped)) { - if (mapped.kind !== "required" && mapped.kind !== "optional") { - return throwParseError(`Map result must have kind "required" or "optional" (was ${mapped.kind})`); - } - structureInner[mapped.kind] = append(structureInner[mapped.kind], mapped); - return structureInner; - } - const mappedKind = mapped.kind ?? originalProp?.kind ?? "required"; - const mappedPropInner = flatMorph(mapped, (k, v) => k in Optional.implementation.keys ? [k, v] : []); - structureInner[mappedKind] = append(structureInner[mappedKind], this.$.node(mappedKind, mappedPropInner)); - return structureInner; - }, {})); - } - assertHasKeys(keys) { - const invalidKeys = keys.filter((k) => !typeOrTermExtends(k, this.keyof())); - if (invalidKeys.length) { - return throwParseError(writeInvalidKeysMessage(this.expression, invalidKeys)); - } - } - get(indexer, ...path3) { - let value2; - let required3 = false; - const key = indexerToKey(indexer); - if ((typeof key === "string" || typeof key === "symbol") && this.propsByKey[key]) { - value2 = this.propsByKey[key].value; - required3 = this.propsByKey[key].required; - } - if (this.index) { - for (const n of this.index) { - if (typeOrTermExtends(key, n.signature)) - value2 = value2?.and(n.value) ?? n.value; - } - } - if (this.sequence && typeOrTermExtends(key, $ark.intrinsic.nonNegativeIntegerString)) { - if (hasArkKind(key, "root")) { - if (this.sequence.variadic) - value2 = value2?.and(this.sequence.element) ?? this.sequence.element; - } else { - const index = Number.parseInt(key); - if (index < this.sequence.prevariadic.length) { - const fixedElement = this.sequence.prevariadic[index].node; - value2 = value2?.and(fixedElement) ?? fixedElement; - required3 ||= index < this.sequence.prefixLength; - } else if (this.sequence.variadic) { - const nonFixedElement = this.$.node("union", this.sequence.variadicOrPostfix); - value2 = value2?.and(nonFixedElement) ?? nonFixedElement; - } - } - } - if (!value2) { - if (this.sequence?.variadic && hasArkKind(key, "root") && key.extends($ark.intrinsic.number)) { - return throwParseError(writeNumberIndexMessage(key.expression, this.sequence.expression)); - } - return throwParseError(writeInvalidKeysMessage(this.expression, [key])); - } - const result = value2.get(...path3); - return required3 ? result : result.or($ark.intrinsic.undefined); - } - pick(...keys) { - this.assertHasKeys(keys); - return this.$.node("structure", this.filterKeys("pick", keys)); - } - omit(...keys) { - this.assertHasKeys(keys); - return this.$.node("structure", this.filterKeys("omit", keys)); - } - optionalize() { - const { required: required3, ...inner } = this.inner; - return this.$.node("structure", { - ...inner, - optional: this.props.map((prop) => prop.hasKind("required") ? this.$.node("optional", prop.inner) : prop) - }); - } - require() { - const { optional: optional3, ...inner } = this.inner; - return this.$.node("structure", { - ...inner, - required: this.props.map((prop) => prop.hasKind("optional") ? { - key: prop.key, - value: prop.value - } : prop) - }); - } - merge(r) { - const inner = this.filterKeys("omit", [r.keyof()]); - if (r.required) - inner.required = append(inner.required, r.required); - if (r.optional) - inner.optional = append(inner.optional, r.optional); - if (r.index) - inner.index = append(inner.index, r.index); - if (r.sequence) - inner.sequence = r.sequence; - if (r.undeclared) - inner.undeclared = r.undeclared; - else - delete inner.undeclared; - return this.$.node("structure", inner); - } - filterKeys(operation, keys) { - const result = makeRootAndArrayPropertiesMutable(this.inner); - const shouldKeep = (key) => { - const matchesKey = keys.some((k) => typeOrTermExtends(key, k)); - return operation === "pick" ? matchesKey : !matchesKey; - }; - if (result.required) - result.required = result.required.filter((prop) => shouldKeep(prop.key)); - if (result.optional) - result.optional = result.optional.filter((prop) => shouldKeep(prop.key)); - if (result.index) - result.index = result.index.filter((index) => shouldKeep(index.signature)); - return result; - } - traverseAllows = (data, ctx) => this._traverse("Allows", data, ctx); - traverseApply = (data, ctx) => this._traverse("Apply", data, ctx); - _traverse = (traversalKind, data, ctx) => { - const errorCount = ctx?.currentErrorCount ?? 0; - for (let i = 0; i < this.props.length; i++) { - if (traversalKind === "Allows") { - if (!this.props[i].traverseAllows(data, ctx)) - return false; - } else { - this.props[i].traverseApply(data, ctx); - if (ctx.failFast && ctx.currentErrorCount > errorCount) - return false; - } - } - if (this.sequence) { - if (traversalKind === "Allows") { - if (!this.sequence.traverseAllows(data, ctx)) - return false; - } else { - this.sequence.traverseApply(data, ctx); - if (ctx.failFast && ctx.currentErrorCount > errorCount) - return false; - } - } - if (this.index || this.undeclared === "reject") { - const keys = Object.keys(data); - keys.push(...Object.getOwnPropertySymbols(data)); - for (let i = 0; i < keys.length; i++) { - const k = keys[i]; - if (this.index) { - for (const node2 of this.index) { - if (node2.signature.traverseAllows(k, ctx)) { - if (traversalKind === "Allows") { - const result = traverseKey(k, () => node2.value.traverseAllows(data[k], ctx), ctx); - if (!result) - return false; - } else { - traverseKey(k, () => node2.value.traverseApply(data[k], ctx), ctx); - if (ctx.failFast && ctx.currentErrorCount > errorCount) - return false; - } - } - } - } - if (this.undeclared === "reject" && !this.declaresKey(k)) { - if (traversalKind === "Allows") - return false; - ctx.errorFromNodeContext({ - code: "predicate", - expected: "removed", - actual: "", - relativePath: [k], - meta: this.meta - }); - if (ctx.failFast) - return false; - } - } - } - if (this.structuralMorph && ctx && !ctx.hasError()) - ctx.queueMorphs([this.structuralMorph]); - return true; - }; - get defaultable() { - return this.cacheGetter("defaultable", this.optional?.filter((o) => o.hasDefault()) ?? []); - } - declaresKey = (k) => k in this.propsByKey || this.index?.some((n) => n.signature.allows(k)) || this.sequence !== void 0 && $ark.intrinsic.nonNegativeIntegerString.allows(k); - _compileDeclaresKey(js) { - const parts = []; - if (this.props.length) - parts.push(`k in ${this.propsByKeyReference}`); - if (this.index) { - for (const index of this.index) - parts.push(js.invoke(index.signature, { kind: "Allows", arg: "k" })); - } - if (this.sequence) - parts.push("$ark.intrinsic.nonNegativeIntegerString.allows(k)"); - return parts.join(" || ") || "false"; - } - get structuralMorph() { - return this.cacheGetter("structuralMorph", getPossibleMorph(this)); - } - structuralMorphRef = this.structuralMorph && registeredReference(this.structuralMorph); - compile(js) { - if (js.traversalKind === "Apply") - js.initializeErrorCount(); - for (const prop of this.props) { - js.check(prop); - if (js.traversalKind === "Apply") - js.returnIfFailFast(); - } - if (this.sequence) { - js.check(this.sequence); - if (js.traversalKind === "Apply") - js.returnIfFailFast(); - } - if (this.index || this.undeclared === "reject") { - js.const("keys", "Object.keys(data)"); - js.line("keys.push(...Object.getOwnPropertySymbols(data))"); - js.for("i < keys.length", () => this.compileExhaustiveEntry(js)); - } - if (js.traversalKind === "Allows") - return js.return(true); - if (this.structuralMorphRef) { - js.if("ctx && !ctx.hasError()", () => { - js.line(`ctx.queueMorphs([`); - precompileMorphs(js, this); - return js.line("])"); - }); - } - } - compileExhaustiveEntry(js) { - js.const("k", "keys[i]"); - if (this.index) { - for (const node2 of this.index) { - js.if(`${js.invoke(node2.signature, { arg: "k", kind: "Allows" })}`, () => js.traverseKey("k", "data[k]", node2.value)); - } - } - if (this.undeclared === "reject") { - js.if(`!(${this._compileDeclaresKey(js)})`, () => { - if (js.traversalKind === "Allows") - return js.return(false); - return js.line(`ctx.errorFromNodeContext({ code: "predicate", expected: "removed", actual: "", relativePath: [k], meta: ${this.compiledMeta} })`).if("ctx.failFast", () => js.return()); - }); - } - return js; - } - reduceJsonSchema(schema2, ctx) { - switch (schema2.type) { - case "object": - return this.reduceObjectJsonSchema(schema2, ctx); - case "array": - const arraySchema = this.sequence?.reduceJsonSchema(schema2, ctx) ?? schema2; - if (this.props.length || this.index) { - return ctx.fallback.arrayObject({ - code: "arrayObject", - base: arraySchema, - object: this.reduceObjectJsonSchema({ type: "object" }, ctx) - }); - } - return arraySchema; - default: - return ToJsonSchema.throwInternalOperandError("structure", schema2); - } - } - reduceObjectJsonSchema(schema2, ctx) { - if (this.props.length) { - schema2.properties = {}; - for (const prop of this.props) { - const valueSchema = prop.value.toJsonSchemaRecurse(ctx); - if (typeof prop.key === "symbol") { - ctx.fallback.symbolKey({ - code: "symbolKey", - base: schema2, - key: prop.key, - value: valueSchema, - optional: prop.optional - }); - continue; - } - if (prop.hasDefault()) { - const value2 = typeof prop.default === "function" ? prop.default() : prop.default; - valueSchema.default = $ark.intrinsic.jsonData.allows(value2) ? value2 : ctx.fallback.defaultValue({ - code: "defaultValue", - base: valueSchema, - value: value2 - }); - } - schema2.properties[prop.key] = valueSchema; - } - if (this.requiredKeys.length && schema2.properties) { - schema2.required = this.requiredKeys.filter((k) => typeof k === "string" && k in schema2.properties); - } - } - if (this.index) { - for (const index of this.index) { - const valueJsonSchema = index.value.toJsonSchemaRecurse(ctx); - if (index.signature.equals($ark.intrinsic.string)) { - schema2.additionalProperties = valueJsonSchema; - continue; - } - for (const keyBranch of index.signature.branches) { - if (!keyBranch.extends($ark.intrinsic.string)) { - schema2 = ctx.fallback.symbolKey({ - code: "symbolKey", - base: schema2, - key: null, - value: valueJsonSchema, - optional: false - }); - continue; - } - let keySchema = { type: "string" }; - if (keyBranch.hasKind("morph")) { - keySchema = ctx.fallback.morph({ - code: "morph", - base: keyBranch.rawIn.toJsonSchemaRecurse(ctx), - out: keyBranch.rawOut.toJsonSchemaRecurse(ctx) - }); - } - if (!keyBranch.hasKind("intersection")) { - return throwInternalError(`Unexpected index branch kind ${keyBranch.kind}.`); - } - const { pattern } = keyBranch.inner; - if (pattern) { - const keySchemaWithPattern = Object.assign(keySchema, { - pattern: pattern[0].rule - }); - for (let i = 1; i < pattern.length; i++) { - keySchema = ctx.fallback.patternIntersection({ - code: "patternIntersection", - base: keySchemaWithPattern, - pattern: pattern[i].rule - }); - } - schema2.patternProperties ??= {}; - schema2.patternProperties[keySchemaWithPattern.pattern] = valueJsonSchema; - } - } - } - } - if (this.undeclared && !schema2.additionalProperties) - schema2.additionalProperties = false; - return schema2; - } -}; -var defaultableMorphsCache2 = {}; -var constructStructuralMorphCacheKey = (node2) => { - let cacheKey = ""; - for (let i = 0; i < node2.defaultable.length; i++) - cacheKey += node2.defaultable[i].defaultValueMorphRef; - if (node2.sequence?.defaultValueMorphsReference) - cacheKey += node2.sequence?.defaultValueMorphsReference; - if (node2.undeclared === "delete") { - cacheKey += "delete !("; - if (node2.required) - for (const n of node2.required) - cacheKey += n.compiledKey + " | "; - if (node2.optional) - for (const n of node2.optional) - cacheKey += n.compiledKey + " | "; - if (node2.index) - for (const index of node2.index) - cacheKey += index.signature.id + " | "; - if (node2.sequence) { - if (node2.sequence.maxLength === null) - cacheKey += intrinsic.nonNegativeIntegerString.id; - else { - for (let i = 0; i < node2.sequence.tuple.length; i++) - cacheKey += i + " | "; - } - } - cacheKey += ")"; - } - return cacheKey; -}; -var getPossibleMorph = (node2) => { - const cacheKey = constructStructuralMorphCacheKey(node2); - if (!cacheKey) - return void 0; - if (defaultableMorphsCache2[cacheKey]) - return defaultableMorphsCache2[cacheKey]; - const $arkStructuralMorph = (data, ctx) => { - for (let i = 0; i < node2.defaultable.length; i++) { - if (!(node2.defaultable[i].key in data)) - node2.defaultable[i].defaultValueMorph(data, ctx); - } - if (node2.sequence?.defaultables) { - for (let i = data.length - node2.sequence.prefixLength; i < node2.sequence.defaultables.length; i++) - node2.sequence.defaultValueMorphs[i](data, ctx); - } - if (node2.undeclared === "delete") { - for (const k in data) - if (!node2.declaresKey(k)) - delete data[k]; - } - return data; - }; - return defaultableMorphsCache2[cacheKey] = $arkStructuralMorph; -}; -var precompileMorphs = (js, node2) => { - const requiresContext = node2.defaultable.some((node3) => node3.defaultValueMorph.length === 2) || node2.sequence?.defaultValueMorphs.some((morph) => morph.length === 2); - const args2 = `(data${requiresContext ? ", ctx" : ""})`; - return js.block(`${args2} => `, (js2) => { - for (let i = 0; i < node2.defaultable.length; i++) { - const { serializedKey, defaultValueMorphRef } = node2.defaultable[i]; - js2.if(`!(${serializedKey} in data)`, (js3) => js3.line(`${defaultValueMorphRef}${args2}`)); - } - if (node2.sequence?.defaultables) { - js2.for(`i < ${node2.sequence.defaultables.length}`, (js3) => js3.set(`data[i]`, 5), `data.length - ${node2.sequence.prefixLength}`); - } - if (node2.undeclared === "delete") { - js2.forIn("data", (js3) => js3.if(`!(${node2._compileDeclaresKey(js3)})`, (js4) => js4.line(`delete data[k]`))); - } - return js2.return("data"); - }); -}; -var Structure = { - implementation: implementation22, - Node: StructureNode -}; -var indexerToKey = (indexable) => { - if (hasArkKind(indexable, "root") && indexable.hasKind("unit")) - indexable = indexable.unit; - if (typeof indexable === "number") - indexable = `${indexable}`; - return indexable; -}; -var writeNumberIndexMessage = (indexExpression, sequenceExpression) => `${indexExpression} is not allowed as an array index on ${sequenceExpression}. Use the 'nonNegativeIntegerString' keyword instead.`; -var normalizeIndex = (signature, value2, $2) => { - const [enumerableBranches, nonEnumerableBranches] = spliterate(signature.branches, (k) => k.hasKind("unit")); - if (!enumerableBranches.length) - return { index: $2.node("index", { signature, value: value2 }) }; - const normalized = {}; - for (const n of enumerableBranches) { - const prop = $2.node("required", { key: n.unit, value: value2 }); - normalized[prop.kind] = append(normalized[prop.kind], prop); - } - if (nonEnumerableBranches.length) { - normalized.index = $2.node("index", { - signature: nonEnumerableBranches, - value: value2 - }); - } - return normalized; -}; -var typeKeyToString = (k) => hasArkKind(k, "root") ? k.expression : printable(k); -var writeInvalidKeysMessage = (o, keys) => `Key${keys.length === 1 ? "" : "s"} ${keys.map(typeKeyToString).join(", ")} ${keys.length === 1 ? "does" : "do"} not exist on ${o}`; -var writeDuplicateKeyMessage = (key) => `Duplicate key ${compileSerializedValue(key)}`; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/kinds.js -var nodeImplementationsByKind = { - ...boundImplementationsByKind, - alias: Alias.implementation, - domain: Domain.implementation, - unit: Unit.implementation, - proto: Proto.implementation, - union: Union.implementation, - morph: Morph.implementation, - intersection: Intersection.implementation, - divisor: Divisor.implementation, - pattern: Pattern.implementation, - predicate: Predicate.implementation, - required: Required.implementation, - optional: Optional.implementation, - index: Index.implementation, - sequence: Sequence.implementation, - structure: Structure.implementation -}; -$ark.defaultConfig = withAlphabetizedKeys(Object.assign(flatMorph(nodeImplementationsByKind, (kind, implementation23) => [ - kind, - implementation23.defaults -]), { - jitless: envHasCsp(), - clone: deepClone, - onUndeclaredKey: "ignore", - exactOptionalPropertyTypes: true, - numberAllowsNaN: false, - dateAllowsInvalid: false, - onFail: null, - keywords: {}, - toJsonSchema: ToJsonSchema.defaultConfig -})); -$ark.resolvedConfig = mergeConfigs($ark.defaultConfig, $ark.config); -var nodeClassesByKind = { - ...boundClassesByKind, - alias: Alias.Node, - domain: Domain.Node, - unit: Unit.Node, - proto: Proto.Node, - union: Union.Node, - morph: Morph.Node, - intersection: Intersection.Node, - divisor: Divisor.Node, - pattern: Pattern.Node, - predicate: Predicate.Node, - required: Required.Node, - optional: Optional.Node, - index: Index.Node, - sequence: Sequence.Node, - structure: Structure.Node -}; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/module.js -var RootModule = class extends DynamicBase { - // ensure `[arkKind]` is non-enumerable so it doesn't get spread on import/export - get [arkKind]() { - return "module"; - } -}; -var bindModule = (module, $2) => new RootModule(flatMorph(module, (alias, value2) => [ - alias, - hasArkKind(value2, "module") ? bindModule(value2, $2) : $2.bindReference(value2) -])); - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/scope.js -var schemaBranchesOf = (schema2) => isArray(schema2) ? schema2 : "branches" in schema2 && isArray(schema2.branches) ? schema2.branches : void 0; -var throwMismatchedNodeRootError = (expected, actual) => throwParseError(`Node of kind ${actual} is not valid as a ${expected} definition`); -var writeDuplicateAliasError = (alias) => `#${alias} duplicates public alias ${alias}`; -var scopesByName = {}; -$ark.ambient ??= {}; -var rawUnknownUnion; -var rootScopeFnName = "function $"; -var precompile = (references) => bindPrecompilation(references, precompileReferences(references)); -var bindPrecompilation = (references, precompiler) => { - const precompilation = precompiler.write(rootScopeFnName, 4); - const compiledTraversals = precompiler.compile()(); - for (const node2 of references) { - if (node2.precompilation) { - continue; - } - node2.traverseAllows = compiledTraversals[`${node2.id}Allows`].bind(compiledTraversals); - if (node2.isRoot() && !node2.allowsRequiresContext) { - node2.allows = node2.traverseAllows; - } - node2.traverseApply = compiledTraversals[`${node2.id}Apply`].bind(compiledTraversals); - if (compiledTraversals[`${node2.id}Optimistic`]) { - ; - node2.traverseOptimistic = compiledTraversals[`${node2.id}Optimistic`].bind(compiledTraversals); - } - node2.precompilation = precompilation; - } -}; -var precompileReferences = (references) => new CompiledFunction().return(references.reduce((js, node2) => { - const allowsCompiler = new NodeCompiler({ kind: "Allows" }).indent(); - node2.compile(allowsCompiler); - const allowsJs = allowsCompiler.write(`${node2.id}Allows`); - const applyCompiler = new NodeCompiler({ kind: "Apply" }).indent(); - node2.compile(applyCompiler); - const applyJs = applyCompiler.write(`${node2.id}Apply`); - const result = `${js}${allowsJs}, -${applyJs}, -`; - if (!node2.hasKind("union")) - return result; - const optimisticCompiler = new NodeCompiler({ - kind: "Allows", - optimistic: true - }).indent(); - node2.compile(optimisticCompiler); - const optimisticJs = optimisticCompiler.write(`${node2.id}Optimistic`); - return `${result}${optimisticJs}, -`; -}, "{\n") + "}"); -var BaseScope = class { - config; - resolvedConfig; - name; - get [arkKind]() { - return "scope"; - } - referencesById = {}; - references = []; - resolutions = {}; - exportedNames = []; - aliases = {}; - resolved = false; - nodesByHash = {}; - intrinsic; - constructor(def, config3) { - this.config = mergeConfigs($ark.config, config3); - this.resolvedConfig = mergeConfigs($ark.resolvedConfig, config3); - this.name = this.resolvedConfig.name ?? `anonymousScope${Object.keys(scopesByName).length}`; - if (this.name in scopesByName) - throwParseError(`A Scope already named ${this.name} already exists`); - scopesByName[this.name] = this; - const aliasEntries = Object.entries(def).map((entry) => this.preparseOwnAliasEntry(...entry)); - for (const [k, v] of aliasEntries) { - let name = k; - if (k[0] === "#") { - name = k.slice(1); - if (name in this.aliases) - throwParseError(writeDuplicateAliasError(name)); - this.aliases[name] = v; - } else { - if (name in this.aliases) - throwParseError(writeDuplicateAliasError(k)); - this.aliases[name] = v; - this.exportedNames.push(name); - } - if (!hasArkKind(v, "module") && !hasArkKind(v, "generic") && !isThunk(v)) { - const preparsed = this.preparseOwnDefinitionFormat(v, { alias: name }); - this.resolutions[name] = hasArkKind(preparsed, "root") ? this.bindReference(preparsed) : this.createParseContext(preparsed).id; - } - } - rawUnknownUnion ??= this.node("union", { - branches: [ - "string", - "number", - "object", - "bigint", - "symbol", - { unit: true }, - { unit: false }, - { unit: void 0 }, - { unit: null } - ] - }, { prereduced: true }); - this.nodesByHash[rawUnknownUnion.hash] = this.node("intersection", {}, { prereduced: true }); - this.intrinsic = $ark.intrinsic ? flatMorph($ark.intrinsic, (k, v) => ( - // don't include cyclic aliases from JSON scope - k.startsWith("json") ? [] : [k, this.bindReference(v)] - )) : {}; - } - cacheGetter(name, value2) { - Object.defineProperty(this, name, { value: value2 }); - return value2; - } - get internal() { - return this; - } - // json is populated when the scope is exported, so ensure it is populated - // before allowing external access - _json; - get json() { - if (!this._json) - this.export(); - return this._json; - } - defineSchema(def) { - return def; - } - generic = (...params) => { - const $2 = this; - return (def, possibleHkt) => new GenericRoot(params, possibleHkt ? new LazyGenericBody(def) : def, $2, $2, possibleHkt ?? null); - }; - units = (values, opts) => { - const uniqueValues = []; - for (const value2 of values) - if (!uniqueValues.includes(value2)) - uniqueValues.push(value2); - const branches = uniqueValues.map((unit) => this.node("unit", { unit }, opts)); - return this.node("union", branches, { - ...opts, - prereduced: true - }); - }; - lazyResolutions = []; - lazilyResolve(resolve2, syntheticAlias) { - const node2 = this.node("alias", { - reference: syntheticAlias ?? "synthetic", - resolve: resolve2 - }, { prereduced: true }); - if (!this.resolved) - this.lazyResolutions.push(node2); - return node2; - } - schema = (schema2, opts) => this.finalize(this.parseSchema(schema2, opts)); - parseSchema = (schema2, opts) => this.node(schemaKindOf(schema2), schema2, opts); - preparseNode(kinds, schema2, opts) { - let kind = typeof kinds === "string" ? kinds : schemaKindOf(schema2, kinds); - if (isNode(schema2) && schema2.kind === kind) - return schema2; - if (kind === "alias" && !opts?.prereduced) { - const { reference: reference2 } = Alias.implementation.normalize(schema2, this); - if (reference2.startsWith("$")) { - const resolution = this.resolveRoot(reference2.slice(1)); - schema2 = resolution; - kind = resolution.kind; - } - } else if (kind === "union" && hasDomain(schema2, "object")) { - const branches = schemaBranchesOf(schema2); - if (branches?.length === 1) { - schema2 = branches[0]; - kind = schemaKindOf(schema2); - } - } - if (isNode(schema2) && schema2.kind === kind) - return schema2; - const impl = nodeImplementationsByKind[kind]; - const normalizedSchema = impl.normalize?.(schema2, this) ?? schema2; - if (isNode(normalizedSchema)) { - return normalizedSchema.kind === kind ? normalizedSchema : throwMismatchedNodeRootError(kind, normalizedSchema.kind); - } - return { - ...opts, - $: this, - kind, - def: normalizedSchema, - prefix: opts.alias ?? kind - }; - } - bindReference(reference2) { - let bound; - if (isNode(reference2)) { - bound = reference2.$ === this ? reference2 : new reference2.constructor(reference2.attachments, this); - } else { - bound = reference2.$ === this ? reference2 : new GenericRoot(reference2.params, reference2.bodyDef, reference2.$, this, reference2.hkt); - } - if (!this.resolved) { - Object.assign(this.referencesById, bound.referencesById); - } - return bound; - } - resolveRoot(name) { - return this.maybeResolveRoot(name) ?? throwParseError(writeUnresolvableMessage(name)); - } - maybeResolveRoot(name) { - const result = this.maybeResolve(name); - if (hasArkKind(result, "generic")) - return; - return result; - } - /** If name is a valid reference to a submodule alias, return its resolution */ - maybeResolveSubalias(name) { - return maybeResolveSubalias(this.aliases, name) ?? maybeResolveSubalias(this.ambient, name); - } - get ambient() { - return $ark.ambient; - } - maybeResolve(name) { - const cached4 = this.resolutions[name]; - if (cached4) { - if (typeof cached4 !== "string") - return this.bindReference(cached4); - const v = nodesByRegisteredId[cached4]; - if (hasArkKind(v, "root")) - return this.resolutions[name] = v; - if (hasArkKind(v, "context")) { - if (v.phase === "resolving") { - return this.node("alias", { reference: `$${name}` }, { prereduced: true }); - } - if (v.phase === "resolved") { - return throwInternalError(`Unexpected resolved context for was uncached by its scope: ${printable(v)}`); - } - v.phase = "resolving"; - const node2 = this.bindReference(this.parseOwnDefinitionFormat(v.def, v)); - v.phase = "resolved"; - nodesByRegisteredId[node2.id] = node2; - nodesByRegisteredId[v.id] = node2; - return this.resolutions[name] = node2; - } - return throwInternalError(`Unexpected nodesById entry for ${cached4}: ${printable(v)}`); - } - let def = this.aliases[name] ?? this.ambient?.[name]; - if (!def) - return this.maybeResolveSubalias(name); - def = this.normalizeRootScopeValue(def); - if (hasArkKind(def, "generic")) - return this.resolutions[name] = this.bindReference(def); - if (hasArkKind(def, "module")) { - if (!def.root) - throwParseError(writeMissingSubmoduleAccessMessage(name)); - return this.resolutions[name] = this.bindReference(def.root); - } - return this.resolutions[name] = this.parse(def, { - alias: name - }); - } - createParseContext(input) { - const id = input.id ?? registerNodeId(input.prefix); - return nodesByRegisteredId[id] = Object.assign(input, { - [arkKind]: "context", - $: this, - id, - phase: "unresolved" - }); - } - traversal(root) { - return new Traversal(root, this.resolvedConfig); - } - import(...names) { - return new RootModule(flatMorph(this.export(...names), (alias, value2) => [ - `#${alias}`, - value2 - ])); - } - precompilation; - _exportedResolutions; - _exports; - export(...names) { - if (!this._exports) { - this._exports = {}; - for (const name of this.exportedNames) { - const def = this.aliases[name]; - this._exports[name] = hasArkKind(def, "module") ? bindModule(def, this) : bootstrapAliasReferences(this.maybeResolve(name)); - } - for (const node2 of this.lazyResolutions) - node2.resolution; - this._exportedResolutions = resolutionsOfModule(this, this._exports); - this._json = resolutionsToJson(this._exportedResolutions); - Object.assign(this.resolutions, this._exportedResolutions); - this.references = Object.values(this.referencesById); - if (!this.resolvedConfig.jitless) { - const precompiler = precompileReferences(this.references); - this.precompilation = precompiler.write(rootScopeFnName, 4); - bindPrecompilation(this.references, precompiler); - } - this.resolved = true; - } - const namesToExport = names.length ? names : this.exportedNames; - return new RootModule(flatMorph(namesToExport, (_, name) => [ - name, - this._exports[name] - ])); - } - resolve(name) { - return this.export()[name]; - } - node = (kinds, nodeSchema, opts = {}) => { - const ctxOrNode = this.preparseNode(kinds, nodeSchema, opts); - if (isNode(ctxOrNode)) - return this.bindReference(ctxOrNode); - const ctx = this.createParseContext(ctxOrNode); - const node2 = parseNode(ctx); - const bound = this.bindReference(node2); - return nodesByRegisteredId[ctx.id] = bound; - }; - parse = (def, opts = {}) => this.finalize(this.parseDefinition(def, opts)); - parseDefinition(def, opts = {}) { - if (hasArkKind(def, "root")) - return this.bindReference(def); - const ctxInputOrNode = this.preparseOwnDefinitionFormat(def, opts); - if (hasArkKind(ctxInputOrNode, "root")) - return this.bindReference(ctxInputOrNode); - const ctx = this.createParseContext(ctxInputOrNode); - nodesByRegisteredId[ctx.id] = ctx; - let node2 = this.bindReference(this.parseOwnDefinitionFormat(def, ctx)); - if (node2.isCyclic) - node2 = withId(node2, ctx.id); - nodesByRegisteredId[ctx.id] = node2; - return node2; - } - finalize(node2) { - bootstrapAliasReferences(node2); - if (!node2.precompilation && !this.resolvedConfig.jitless) - precompile(node2.references); - return node2; - } -}; -var SchemaScope = class extends BaseScope { - parseOwnDefinitionFormat(def, ctx) { - return parseNode(ctx); - } - preparseOwnDefinitionFormat(schema2, opts) { - return this.preparseNode(schemaKindOf(schema2), schema2, opts); - } - preparseOwnAliasEntry(k, v) { - return [k, v]; - } - normalizeRootScopeValue(v) { - return v; - } -}; -var bootstrapAliasReferences = (resolution) => { - const aliases = resolution.references.filter((node2) => node2.hasKind("alias")); - for (const aliasNode of aliases) { - Object.assign(aliasNode.referencesById, aliasNode.resolution.referencesById); - for (const ref of resolution.references) { - if (aliasNode.id in ref.referencesById) - Object.assign(ref.referencesById, aliasNode.referencesById); - } - } - return resolution; -}; -var resolutionsToJson = (resolutions) => flatMorph(resolutions, (k, v) => [ - k, - hasArkKind(v, "root") || hasArkKind(v, "generic") ? v.json : hasArkKind(v, "module") ? resolutionsToJson(v) : throwInternalError(`Unexpected resolution ${printable(v)}`) -]); -var maybeResolveSubalias = (base, name) => { - const dotIndex = name.indexOf("."); - if (dotIndex === -1) - return; - const dotPrefix = name.slice(0, dotIndex); - const prefixSchema = base[dotPrefix]; - if (prefixSchema === void 0) - return; - if (!hasArkKind(prefixSchema, "module")) - return throwParseError(writeNonSubmoduleDotMessage(dotPrefix)); - const subalias = name.slice(dotIndex + 1); - const resolution = prefixSchema[subalias]; - if (resolution === void 0) - return maybeResolveSubalias(prefixSchema, subalias); - if (hasArkKind(resolution, "root") || hasArkKind(resolution, "generic")) - return resolution; - if (hasArkKind(resolution, "module")) { - return resolution.root ?? throwParseError(writeMissingSubmoduleAccessMessage(name)); - } - throwInternalError(`Unexpected resolution for alias '${name}': ${printable(resolution)}`); -}; -var schemaScope = (aliases, config3) => new SchemaScope(aliases, config3); -var rootSchemaScope = new SchemaScope({}); -var resolutionsOfModule = ($2, typeSet) => { - const result = {}; - for (const k in typeSet) { - const v = typeSet[k]; - if (hasArkKind(v, "module")) { - const innerResolutions = resolutionsOfModule($2, v); - const prefixedResolutions = flatMorph(innerResolutions, (innerK, innerV) => [`${k}.${innerK}`, innerV]); - Object.assign(result, prefixedResolutions); - } else if (hasArkKind(v, "root") || hasArkKind(v, "generic")) - result[k] = v; - else - throwInternalError(`Unexpected scope resolution ${printable(v)}`); - } - return result; -}; -var writeUnresolvableMessage = (token) => `'${token}' is unresolvable`; -var writeNonSubmoduleDotMessage = (name) => `'${name}' must reference a module to be accessed using dot syntax`; -var writeMissingSubmoduleAccessMessage = (name) => `Reference to submodule '${name}' must specify an alias`; -rootSchemaScope.export(); -var rootSchema = rootSchemaScope.schema; -var node = rootSchemaScope.node; -var defineSchema = rootSchemaScope.defineSchema; -var genericNode = rootSchemaScope.generic; - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/structure/shared.js -var arrayIndexSource = `^(?:0|[1-9]\\d*)$`; -var arrayIndexMatcher = new RegExp(arrayIndexSource); -var arrayIndexMatcherReference = registeredReference(arrayIndexMatcher); - -// node_modules/.pnpm/@ark+schema@0.56.0/node_modules/@ark/schema/out/intrinsic.js -var intrinsicBases = schemaScope({ - bigint: "bigint", - // since we know this won't be reduced, it can be safely cast to a union - boolean: [{ unit: false }, { unit: true }], - false: { unit: false }, - never: [], - null: { unit: null }, - number: "number", - object: "object", - string: "string", - symbol: "symbol", - true: { unit: true }, - unknown: {}, - undefined: { unit: void 0 }, - Array, - Date -}, { prereducedAliases: true }).export(); -$ark.intrinsic = { ...intrinsicBases }; -var intrinsicRoots = schemaScope({ - integer: { - domain: "number", - divisor: 1 - }, - lengthBoundable: ["string", Array], - key: ["string", "symbol"], - nonNegativeIntegerString: { domain: "string", pattern: arrayIndexSource } -}, { prereducedAliases: true }).export(); -Object.assign($ark.intrinsic, intrinsicRoots); -var intrinsicJson = schemaScope({ - jsonPrimitive: [ - "string", - "number", - { unit: true }, - { unit: false }, - { unit: null } - ], - jsonObject: { - domain: "object", - index: { - signature: "string", - value: "$jsonData" - } - }, - jsonData: ["$jsonPrimitive", "$jsonObject"] -}, { prereducedAliases: true }).export(); -var intrinsic = { - ...intrinsicBases, - ...intrinsicRoots, - ...intrinsicJson, - emptyStructure: node("structure", {}, { prereduced: true }) -}; -$ark.intrinsic = { ...intrinsic }; - -// node_modules/.pnpm/arkregex@0.0.5/node_modules/arkregex/out/regex.js -var regex = ((src, flags) => new RegExp(src, flags)); -Object.assign(regex, { as: regex }); - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/shift/operand/date.js -var isDateLiteral = (value2) => typeof value2 === "string" && value2[0] === "d" && (value2[1] === "'" || value2[1] === '"') && value2[value2.length - 1] === value2[1]; -var isValidDate = (d) => d.toString() !== "Invalid Date"; -var extractDateLiteralSource = (literal3) => literal3.slice(2, -1); -var writeInvalidDateMessage = (source) => `'${source}' could not be parsed by the Date constructor`; -var tryParseDate = (source, errorOnFail) => maybeParseDate(source, errorOnFail); -var maybeParseDate = (source, errorOnFail) => { - const stringParsedDate = new Date(source); - if (isValidDate(stringParsedDate)) - return stringParsedDate; - const epochMillis = tryParseNumber(source); - if (epochMillis !== void 0) { - const numberParsedDate = new Date(epochMillis); - if (isValidDate(numberParsedDate)) - return numberParsedDate; - } - return errorOnFail ? throwParseError(errorOnFail === true ? writeInvalidDateMessage(source) : errorOnFail) : void 0; -}; - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/shift/operand/enclosed.js -var regexExecArray = rootSchema({ - proto: "Array", - sequence: "string", - required: { - key: "groups", - value: ["object", { unit: void 0 }] - } -}); -var parseEnclosed = (s, enclosing) => { - const enclosed = s.scanner.shiftUntilEscapable(untilLookaheadIsClosing[enclosingTokens[enclosing]]); - if (s.scanner.lookahead === "") - return s.error(writeUnterminatedEnclosedMessage(enclosed, enclosing)); - s.scanner.shift(); - if (enclosing in enclosingRegexTokens) { - let regex4; - try { - regex4 = new RegExp(enclosed); - } catch (e) { - throwParseError(String(e)); - } - s.root = s.ctx.$.node("intersection", { - domain: "string", - pattern: enclosed - }, { prereduced: true }); - if (enclosing === "x/") { - s.root = s.ctx.$.node("morph", { - in: s.root, - morphs: (s2) => regex4.exec(s2), - declaredOut: regexExecArray - }); - } - } else if (isKeyOf(enclosing, enclosingQuote)) - s.root = s.ctx.$.node("unit", { unit: enclosed }); - else { - const date5 = tryParseDate(enclosed, writeInvalidDateMessage(enclosed)); - s.root = s.ctx.$.node("unit", { meta: enclosed, unit: date5 }); - } -}; -var enclosingQuote = { - "'": 1, - '"': 1 -}; -var enclosingChar = { - "/": 1, - "'": 1, - '"': 1 -}; -var enclosingLiteralTokens = { - "d'": "'", - 'd"': '"', - "'": "'", - '"': '"' -}; -var enclosingRegexTokens = { - "/": "/", - "x/": "/" -}; -var enclosingTokens = { - ...enclosingLiteralTokens, - ...enclosingRegexTokens -}; -var untilLookaheadIsClosing = { - "'": (scanner) => scanner.lookahead === `'`, - '"': (scanner) => scanner.lookahead === `"`, - "/": (scanner) => scanner.lookahead === `/` -}; -var enclosingCharDescriptions = { - '"': "double-quote", - "'": "single-quote", - "/": "forward slash" -}; -var writeUnterminatedEnclosedMessage = (fragment, enclosingStart) => `${enclosingStart}${fragment} requires a closing ${enclosingCharDescriptions[enclosingTokens[enclosingStart]]}`; - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/ast/validate.js -var writePrefixedPrivateReferenceMessage = (name) => `Private type references should not include '#'. Use '${name}' instead.`; -var shallowOptionalMessage = "Optional definitions like 'string?' are only valid as properties in an object or tuple"; -var shallowDefaultableMessage = "Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple"; - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/shift/tokens.js -var terminatingChars = { - "<": 1, - ">": 1, - "=": 1, - "|": 1, - "&": 1, - ")": 1, - "[": 1, - "%": 1, - ",": 1, - ":": 1, - "?": 1, - "#": 1, - ...whitespaceChars -}; -var lookaheadIsFinalizing = (lookahead, unscanned) => lookahead === ">" ? unscanned[0] === "=" ? ( - // >== would only occur in an expression like Array==5 - // otherwise, >= would only occur as part of a bound like number>=5 - unscanned[1] === "=" -) : unscanned.trimStart() === "" || isKeyOf(unscanned.trimStart()[0], terminatingChars) : lookahead === "=" ? unscanned[0] !== "=" : lookahead === "," || lookahead === "?"; - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/shift/operand/genericArgs.js -var parseGenericArgs = (name, g, s) => _parseGenericArgs(name, g, s, []); -var _parseGenericArgs = (name, g, s, argNodes) => { - const argState = s.parseUntilFinalizer(); - argNodes.push(argState.root); - if (argState.finalizer === ">") { - if (argNodes.length !== g.params.length) { - return s.error(writeInvalidGenericArgCountMessage(name, g.names, argNodes.map((arg) => arg.expression))); - } - return argNodes; - } - if (argState.finalizer === ",") - return _parseGenericArgs(name, g, s, argNodes); - return argState.error(writeUnclosedGroupMessage(">")); -}; -var writeInvalidGenericArgCountMessage = (name, params, argDefs) => `${name}<${params.join(", ")}> requires exactly ${params.length} args (got ${argDefs.length}${argDefs.length === 0 ? "" : `: ${argDefs.join(", ")}`})`; - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/shift/operand/unenclosed.js -var parseUnenclosed = (s) => { - const token = s.scanner.shiftUntilLookahead(terminatingChars); - if (token === "keyof") - s.addPrefix("keyof"); - else - s.root = unenclosedToNode(s, token); -}; -var parseGenericInstantiation = (name, g, s) => { - s.scanner.shiftUntilNonWhitespace(); - const lookahead = s.scanner.shift(); - if (lookahead !== "<") - return s.error(writeInvalidGenericArgCountMessage(name, g.names, [])); - const parsedArgs = parseGenericArgs(name, g, s); - return g(...parsedArgs); -}; -var unenclosedToNode = (s, token) => maybeParseReference(s, token) ?? maybeParseUnenclosedLiteral(s, token) ?? s.error(token === "" ? s.scanner.lookahead === "#" ? writePrefixedPrivateReferenceMessage(s.shiftedBy(1).scanner.shiftUntilLookahead(terminatingChars)) : writeMissingOperandMessage(s) : writeUnresolvableMessage(token)); -var maybeParseReference = (s, token) => { - if (s.ctx.args?.[token]) { - const arg = s.ctx.args[token]; - if (typeof arg !== "string") - return arg; - return s.ctx.$.node("alias", { reference: arg }, { prereduced: true }); - } - const resolution = s.ctx.$.maybeResolve(token); - if (hasArkKind(resolution, "root")) - return resolution; - if (resolution === void 0) - return; - if (hasArkKind(resolution, "generic")) - return parseGenericInstantiation(token, resolution, s); - return throwParseError(`Unexpected resolution ${printable(resolution)}`); -}; -var maybeParseUnenclosedLiteral = (s, token) => { - const maybeNumber = tryParseWellFormedNumber(token); - if (maybeNumber !== void 0) - return s.ctx.$.node("unit", { unit: maybeNumber }); - const maybeBigint = tryParseWellFormedBigint(token); - if (maybeBigint !== void 0) - return s.ctx.$.node("unit", { unit: maybeBigint }); -}; -var writeMissingOperandMessage = (s) => { - const operator = s.previousOperator(); - return operator ? writeMissingRightOperandMessage(operator, s.scanner.unscanned) : writeExpressionExpectedMessage(s.scanner.unscanned); -}; -var writeMissingRightOperandMessage = (token, unscanned = "") => `Token '${token}' requires a right operand${unscanned ? ` before '${unscanned}'` : ""}`; -var writeExpressionExpectedMessage = (unscanned) => `Expected an expression${unscanned ? ` before '${unscanned}'` : ""}`; - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/shift/operand/operand.js -var parseOperand = (s) => s.scanner.lookahead === "" ? s.error(writeMissingOperandMessage(s)) : s.scanner.lookahead === "(" ? s.shiftedBy(1).reduceGroupOpen() : s.scanner.lookaheadIsIn(enclosingChar) ? parseEnclosed(s, s.scanner.shift()) : s.scanner.lookaheadIsIn(whitespaceChars) ? parseOperand(s.shiftedBy(1)) : s.scanner.lookahead === "d" ? s.scanner.nextLookahead in enclosingQuote ? parseEnclosed(s, `${s.scanner.shift()}${s.scanner.shift()}`) : parseUnenclosed(s) : s.scanner.lookahead === "x" ? s.scanner.nextLookahead === "/" ? s.shiftedBy(2) && parseEnclosed(s, "x/") : parseUnenclosed(s) : parseUnenclosed(s); - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/reduce/shared.js -var minComparators = { - ">": true, - ">=": true -}; -var maxComparators = { - "<": true, - "<=": true -}; -var invertedComparators = { - "<": ">", - ">": "<", - "<=": ">=", - ">=": "<=", - "==": "==" -}; -var writeOpenRangeMessage = (min, comparator) => `Left bounds are only valid when paired with right bounds (try ...${comparator}${min})`; -var writeUnpairableComparatorMessage = (comparator) => `Left-bounded expressions must specify their limits using < or <= (was ${comparator})`; -var writeMultipleLeftBoundsMessage = (openLimit, openComparator, limit, comparator) => `An expression may have at most one left bound (parsed ${openLimit}${invertedComparators[openComparator]}, ${limit}${invertedComparators[comparator]})`; - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/shift/operator/bounds.js -var parseBound = (s, start) => { - const comparator = shiftComparator(s, start); - if (s.root.hasKind("unit")) { - if (typeof s.root.unit === "number") { - s.reduceLeftBound(s.root.unit, comparator); - s.unsetRoot(); - return; - } - if (s.root.unit instanceof Date) { - const literal3 = `d'${s.root.description ?? s.root.unit.toISOString()}'`; - s.unsetRoot(); - s.reduceLeftBound(literal3, comparator); - return; - } - } - return parseRightBound(s, comparator); -}; -var comparatorStartChars = { - "<": 1, - ">": 1, - "=": 1 -}; -var shiftComparator = (s, start) => s.scanner.lookaheadIs("=") ? `${start}${s.scanner.shift()}` : start; -var getBoundKinds = (comparator, limit, root, boundKind) => { - if (root.extends($ark.intrinsic.number)) { - if (typeof limit !== "number") { - return throwParseError(writeInvalidLimitMessage(comparator, limit, boundKind)); - } - return comparator === "==" ? ["min", "max"] : comparator[0] === ">" ? ["min"] : ["max"]; - } - if (root.extends($ark.intrinsic.lengthBoundable)) { - if (typeof limit !== "number") { - return throwParseError(writeInvalidLimitMessage(comparator, limit, boundKind)); - } - return comparator === "==" ? ["exactLength"] : comparator[0] === ">" ? ["minLength"] : ["maxLength"]; - } - if (root.extends($ark.intrinsic.Date)) { - return comparator === "==" ? ["after", "before"] : comparator[0] === ">" ? ["after"] : ["before"]; - } - return throwParseError(writeUnboundableMessage(root.expression)); -}; -var openLeftBoundToRoot = (leftBound) => ({ - rule: isDateLiteral(leftBound.limit) ? extractDateLiteralSource(leftBound.limit) : leftBound.limit, - exclusive: leftBound.comparator.length === 1 -}); -var parseRightBound = (s, comparator) => { - const previousRoot = s.unsetRoot(); - const previousScannerIndex = s.scanner.location; - s.parseOperand(); - const limitNode = s.unsetRoot(); - const limitToken = s.scanner.sliceChars(previousScannerIndex, s.scanner.location); - s.root = previousRoot; - if (!limitNode.hasKind("unit") || typeof limitNode.unit !== "number" && !(limitNode.unit instanceof Date)) - return s.error(writeInvalidLimitMessage(comparator, limitToken, "right")); - const limit = limitNode.unit; - const exclusive = comparator.length === 1; - const boundKinds = getBoundKinds(comparator, typeof limit === "number" ? limit : limitToken, previousRoot, "right"); - for (const kind of boundKinds) { - s.constrainRoot(kind, comparator === "==" ? { rule: limit } : { rule: limit, exclusive }); - } - if (!s.branches.leftBound) - return; - if (!isKeyOf(comparator, maxComparators)) - return s.error(writeUnpairableComparatorMessage(comparator)); - const lowerBoundKind = getBoundKinds(s.branches.leftBound.comparator, s.branches.leftBound.limit, previousRoot, "left"); - s.constrainRoot(lowerBoundKind[0], openLeftBoundToRoot(s.branches.leftBound)); - s.branches.leftBound = null; -}; -var writeInvalidLimitMessage = (comparator, limit, boundKind) => `Comparator ${boundKind === "left" ? invertedComparators[comparator] : comparator} must be ${boundKind === "left" ? "preceded" : "followed"} by a corresponding literal (was ${limit})`; - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/shift/operator/brand.js -var parseBrand = (s) => { - s.scanner.shiftUntilNonWhitespace(); - const brandName = s.scanner.shiftUntilLookahead(terminatingChars); - s.root = s.root.brand(brandName); -}; - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/shift/operator/divisor.js -var parseDivisor = (s) => { - s.scanner.shiftUntilNonWhitespace(); - const divisorToken = s.scanner.shiftUntilLookahead(terminatingChars); - const divisor = tryParseInteger(divisorToken, { - errorOnFail: writeInvalidDivisorMessage(divisorToken) - }); - if (divisor === 0) - s.error(writeInvalidDivisorMessage(0)); - s.root = s.root.constrain("divisor", divisor); -}; -var writeInvalidDivisorMessage = (divisor) => `% operator must be followed by a non-zero integer literal (was ${divisor})`; - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/shift/operator/operator.js -var parseOperator = (s) => { - const lookahead = s.scanner.shift(); - return lookahead === "" ? s.finalize("") : lookahead === "[" ? s.scanner.shift() === "]" ? s.setRoot(s.root.array()) : s.error(incompleteArrayTokenMessage) : lookahead === "|" ? s.scanner.lookahead === ">" ? s.shiftedBy(1).pushRootToBranch("|>") : s.pushRootToBranch(lookahead) : lookahead === "&" ? s.pushRootToBranch(lookahead) : lookahead === ")" ? s.finalizeGroup() : lookaheadIsFinalizing(lookahead, s.scanner.unscanned) ? s.finalize(lookahead) : isKeyOf(lookahead, comparatorStartChars) ? parseBound(s, lookahead) : lookahead === "%" ? parseDivisor(s) : lookahead === "#" ? parseBrand(s) : lookahead in whitespaceChars ? parseOperator(s) : s.error(writeUnexpectedCharacterMessage(lookahead)); -}; -var writeUnexpectedCharacterMessage = (char, shouldBe = "") => `'${char}' is not allowed here${shouldBe && ` (should be ${shouldBe})`}`; -var incompleteArrayTokenMessage = `Missing expected ']'`; - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/shift/operator/default.js -var parseDefault = (s) => { - const baseNode = s.unsetRoot(); - s.parseOperand(); - const defaultNode = s.unsetRoot(); - if (!defaultNode.hasKind("unit")) - return s.error(writeNonLiteralDefaultMessage(defaultNode.expression)); - const defaultValue = defaultNode.unit instanceof Date ? () => new Date(defaultNode.unit) : defaultNode.unit; - return [baseNode, "=", defaultValue]; -}; -var writeNonLiteralDefaultMessage = (defaultDef) => `Default value '${defaultDef}' must be a literal value`; - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/string.js -var parseString = (def, ctx) => { - const aliasResolution = ctx.$.maybeResolveRoot(def); - if (aliasResolution) - return aliasResolution; - if (def.endsWith("[]")) { - const possibleElementResolution = ctx.$.maybeResolveRoot(def.slice(0, -2)); - if (possibleElementResolution) - return possibleElementResolution.array(); - } - const s = new RuntimeState(new Scanner(def), ctx); - const node2 = fullStringParse(s); - if (s.finalizer === ">") - throwParseError(writeUnexpectedCharacterMessage(">")); - return node2; -}; -var fullStringParse = (s) => { - s.parseOperand(); - let result = parseUntilFinalizer(s).root; - if (!result) { - return throwInternalError(`Root was unexpectedly unset after parsing string '${s.scanner.scanned}'`); - } - if (s.finalizer === "=") - result = parseDefault(s); - else if (s.finalizer === "?") - result = [result, "?"]; - s.scanner.shiftUntilNonWhitespace(); - if (s.scanner.lookahead) { - throwParseError(writeUnexpectedCharacterMessage(s.scanner.lookahead)); - } - return result; -}; -var parseUntilFinalizer = (s) => { - while (s.finalizer === void 0) - next(s); - return s; -}; -var next = (s) => s.hasRoot() ? s.parseOperator() : s.parseOperand(); - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/reduce/dynamic.js -var RuntimeState = class _RuntimeState { - root; - branches = { - prefixes: [], - leftBound: null, - intersection: null, - union: null, - pipe: null - }; - finalizer; - groups = []; - scanner; - ctx; - constructor(scanner, ctx) { - this.scanner = scanner; - this.ctx = ctx; - } - error(message) { - return throwParseError(message); - } - hasRoot() { - return this.root !== void 0; - } - setRoot(root) { - this.root = root; - } - unsetRoot() { - const value2 = this.root; - this.root = void 0; - return value2; - } - constrainRoot(...args2) { - this.root = this.root.constrain(args2[0], args2[1]); - } - finalize(finalizer) { - if (this.groups.length) - return this.error(writeUnclosedGroupMessage(")")); - this.finalizeBranches(); - this.finalizer = finalizer; - } - reduceLeftBound(limit, comparator) { - const invertedComparator = invertedComparators[comparator]; - if (!isKeyOf(invertedComparator, minComparators)) - return this.error(writeUnpairableComparatorMessage(comparator)); - if (this.branches.leftBound) { - return this.error(writeMultipleLeftBoundsMessage(this.branches.leftBound.limit, this.branches.leftBound.comparator, limit, invertedComparator)); - } - this.branches.leftBound = { - comparator: invertedComparator, - limit - }; - } - finalizeBranches() { - this.assertRangeUnset(); - if (this.branches.pipe) { - this.pushRootToBranch("|>"); - this.root = this.branches.pipe; - return; - } - if (this.branches.union) { - this.pushRootToBranch("|"); - this.root = this.branches.union; - return; - } - if (this.branches.intersection) { - this.pushRootToBranch("&"); - this.root = this.branches.intersection; - return; - } - this.applyPrefixes(); - } - finalizeGroup() { - this.finalizeBranches(); - const topBranchState = this.groups.pop(); - if (!topBranchState) { - return this.error(writeUnmatchedGroupCloseMessage(")", this.scanner.unscanned)); - } - this.branches = topBranchState; - } - addPrefix(prefix) { - this.branches.prefixes.push(prefix); - } - applyPrefixes() { - while (this.branches.prefixes.length) { - const lastPrefix = this.branches.prefixes.pop(); - this.root = lastPrefix === "keyof" ? this.root.keyof() : throwInternalError(`Unexpected prefix '${lastPrefix}'`); - } - } - pushRootToBranch(token) { - this.assertRangeUnset(); - this.applyPrefixes(); - const root = this.root; - this.root = void 0; - this.branches.intersection = this.branches.intersection?.rawAnd(root) ?? root; - if (token === "&") - return; - this.branches.union = this.branches.union?.rawOr(this.branches.intersection) ?? this.branches.intersection; - this.branches.intersection = null; - if (token === "|") - return; - this.branches.pipe = this.branches.pipe?.rawPipeOnce(this.branches.union) ?? this.branches.union; - this.branches.union = null; - } - parseUntilFinalizer() { - return parseUntilFinalizer(new _RuntimeState(this.scanner, this.ctx)); - } - parseOperator() { - return parseOperator(this); - } - parseOperand() { - return parseOperand(this); - } - assertRangeUnset() { - if (this.branches.leftBound) { - return this.error(writeOpenRangeMessage(this.branches.leftBound.limit, this.branches.leftBound.comparator)); - } - } - reduceGroupOpen() { - this.groups.push(this.branches); - this.branches = { - prefixes: [], - leftBound: null, - union: null, - intersection: null, - pipe: null - }; - } - previousOperator() { - return this.branches.leftBound?.comparator ?? this.branches.prefixes[this.branches.prefixes.length - 1] ?? (this.branches.intersection ? "&" : this.branches.union ? "|" : this.branches.pipe ? "|>" : void 0); - } - shiftedBy(count) { - this.scanner.jumpForward(count); - return this; - } -}; - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/generic.js -var emptyGenericParameterMessage = "An empty string is not a valid generic parameter name"; -var parseGenericParamName = (scanner, result, ctx) => { - scanner.shiftUntilNonWhitespace(); - const name = scanner.shiftUntilLookahead(terminatingChars); - if (name === "") { - if (scanner.lookahead === "" && result.length) - return result; - return throwParseError(emptyGenericParameterMessage); - } - scanner.shiftUntilNonWhitespace(); - return _parseOptionalConstraint(scanner, name, result, ctx); -}; -var extendsToken = "extends "; -var _parseOptionalConstraint = (scanner, name, result, ctx) => { - scanner.shiftUntilNonWhitespace(); - if (scanner.unscanned.startsWith(extendsToken)) - scanner.jumpForward(extendsToken.length); - else { - if (scanner.lookahead === ",") - scanner.shift(); - result.push(name); - return parseGenericParamName(scanner, result, ctx); - } - const s = parseUntilFinalizer(new RuntimeState(scanner, ctx)); - result.push([name, s.root]); - return parseGenericParamName(scanner, result, ctx); -}; - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/fn.js -var InternalFnParser = class extends Callable { - constructor($2) { - const attach = { - $: $2, - raw: $2.fn - }; - super((...signature) => { - const returnOperatorIndex = signature.indexOf(":"); - const lastParamIndex = returnOperatorIndex === -1 ? signature.length - 1 : returnOperatorIndex - 1; - const paramDefs = signature.slice(0, lastParamIndex + 1); - const paramTuple = $2.parse(paramDefs).assertHasKind("intersection"); - let returnType = $2.intrinsic.unknown; - if (returnOperatorIndex !== -1) { - if (returnOperatorIndex !== signature.length - 2) - return throwParseError(badFnReturnTypeMessage); - returnType = $2.parse(signature[returnOperatorIndex + 1]); - } - return (impl) => new InternalTypedFn(impl, paramTuple, returnType); - }, { attach }); - } -}; -var InternalTypedFn = class extends Callable { - raw; - params; - returns; - expression; - constructor(raw2, params, returns) { - const typedName = `typed ${raw2.name}`; - const typed = { - // assign to a key with the expected name to force it to be created that way - [typedName]: (...args2) => { - const validatedArgs = params.assert(args2); - const returned = raw2(...validatedArgs); - return returns.assert(returned); - } - }[typedName]; - super(typed); - this.raw = raw2; - this.params = params; - this.returns = returns; - let argsExpression = params.expression; - if (argsExpression[0] === "[" && argsExpression[argsExpression.length - 1] === "]") - argsExpression = argsExpression.slice(1, -1); - else if (argsExpression.endsWith("[]")) - argsExpression = `...${argsExpression}`; - this.expression = `(${argsExpression}) => ${returns?.expression ?? "unknown"}`; - } -}; -var badFnReturnTypeMessage = `":" must be followed by exactly one return type e.g: -fn("string", ":", "number")(s => s.length)`; - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/match.js -var InternalMatchParser = class extends Callable { - $; - constructor($2) { - super((...args2) => new InternalChainedMatchParser($2)(...args2), { - bind: $2 - }); - this.$ = $2; - } - in(def) { - return new InternalChainedMatchParser(this.$, def === void 0 ? void 0 : this.$.parse(def)); - } - at(key, cases) { - return new InternalChainedMatchParser(this.$).at(key, cases); - } - case(when, then) { - return new InternalChainedMatchParser(this.$).case(when, then); - } -}; -var InternalChainedMatchParser = class extends Callable { - $; - in; - key; - branches = []; - constructor($2, In) { - super((cases) => this.caseEntries(Object.entries(cases).map(([k, v]) => k === "default" ? [k, v] : [this.$.parse(k), v]))); - this.$ = $2; - this.in = In; - } - at(key, cases) { - if (this.key) - throwParseError(doubleAtMessage); - if (this.branches.length) - throwParseError(chainedAtMessage); - this.key = key; - return cases ? this.match(cases) : this; - } - case(def, resolver) { - return this.caseEntry(this.$.parse(def), resolver); - } - caseEntry(node2, resolver) { - const wrappableNode = this.key ? this.$.parse({ [this.key]: node2 }) : node2; - const branch = wrappableNode.pipe(resolver); - this.branches.push(branch); - return this; - } - match(cases) { - return this(cases); - } - strings(cases) { - return this.caseEntries(Object.entries(cases).map(([k, v]) => k === "default" ? [k, v] : [this.$.node("unit", { unit: k }), v])); - } - caseEntries(entries) { - for (let i = 0; i < entries.length; i++) { - const [k, v] = entries[i]; - if (k === "default") { - if (i !== entries.length - 1) { - throwParseError(`default may only be specified as the last key of a switch definition`); - } - return this.default(v); - } - if (typeof v !== "function") { - return throwParseError(`Value for case "${k}" must be a function (was ${domainOf(v)})`); - } - this.caseEntry(k, v); - } - return this; - } - default(defaultCase) { - if (typeof defaultCase === "function") - this.case(intrinsic.unknown, defaultCase); - const schema2 = { - branches: this.branches, - ordered: true - }; - if (defaultCase === "never" || defaultCase === "assert") - schema2.meta = { onFail: throwOnDefault }; - const cases = this.$.node("union", schema2); - if (!this.in) - return this.$.finalize(cases); - let inputValidatedCases = this.in.pipe(cases); - if (defaultCase === "never" || defaultCase === "assert") { - inputValidatedCases = inputValidatedCases.configureReferences({ - onFail: throwOnDefault - }, "self"); - } - return this.$.finalize(inputValidatedCases); - } -}; -var throwOnDefault = (errors) => errors.throw(); -var chainedAtMessage = `A key matcher must be specified before the first case i.e. match.at('foo') or match.in().at('bar')`; -var doubleAtMessage = `At most one key matcher may be specified per expression`; - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/property.js -var parseProperty = (def, ctx) => { - if (isArray(def)) { - if (def[1] === "=") - return [ctx.$.parseOwnDefinitionFormat(def[0], ctx), "=", def[2]]; - if (def[1] === "?") - return [ctx.$.parseOwnDefinitionFormat(def[0], ctx), "?"]; - } - return parseInnerDefinition(def, ctx); -}; -var invalidOptionalKeyKindMessage = `Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }`; -var invalidDefaultableKeyKindMessage = `Only required keys may specify default values, e.g. { value: 'number = 0' }`; - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/objectLiteral.js -var parseObjectLiteral = (def, ctx) => { - let spread; - const structure = {}; - const defEntries = stringAndSymbolicEntriesOf(def); - for (const [k, v] of defEntries) { - const parsedKey = preparseKey(k); - if (parsedKey.kind === "spread") { - if (!isEmptyObject(structure)) - return throwParseError(nonLeadingSpreadError); - const operand = ctx.$.parseOwnDefinitionFormat(v, ctx); - if (operand.equals(intrinsic.object)) - continue; - if (!operand.hasKind("intersection") || // still error on attempts to spread proto nodes like ...Date - !operand.basis?.equals(intrinsic.object)) { - return throwParseError(writeInvalidSpreadTypeMessage(operand.expression)); - } - spread = operand.structure; - continue; - } - if (parsedKey.kind === "undeclared") { - if (v !== "reject" && v !== "delete" && v !== "ignore") - throwParseError(writeInvalidUndeclaredBehaviorMessage(v)); - structure.undeclared = v; - continue; - } - const parsedValue = parseProperty(v, ctx); - const parsedEntryKey = parsedKey; - if (parsedKey.kind === "required") { - if (!isArray(parsedValue)) { - appendNamedProp(structure, "required", { - key: parsedKey.normalized, - value: parsedValue - }, ctx); - } else { - appendNamedProp(structure, "optional", parsedValue[1] === "=" ? { - key: parsedKey.normalized, - value: parsedValue[0], - default: parsedValue[2] - } : { - key: parsedKey.normalized, - value: parsedValue[0] - }, ctx); - } - continue; - } - if (isArray(parsedValue)) { - if (parsedValue[1] === "?") - throwParseError(invalidOptionalKeyKindMessage); - if (parsedValue[1] === "=") - throwParseError(invalidDefaultableKeyKindMessage); - } - if (parsedKey.kind === "optional") { - appendNamedProp(structure, "optional", { - key: parsedKey.normalized, - value: parsedValue - }, ctx); - continue; - } - const signature = ctx.$.parseOwnDefinitionFormat(parsedEntryKey.normalized, ctx); - const normalized = normalizeIndex(signature, parsedValue, ctx.$); - if (normalized.index) - structure.index = append(structure.index, normalized.index); - if (normalized.required) - structure.required = append(structure.required, normalized.required); - } - const structureNode = ctx.$.node("structure", structure); - return ctx.$.parseSchema({ - domain: "object", - structure: spread?.merge(structureNode) ?? structureNode - }); -}; -var appendNamedProp = (structure, kind, inner, ctx) => { - structure[kind] = append( - // doesn't seem like this cast should be necessary - structure[kind], - ctx.$.node(kind, inner) - ); -}; -var writeInvalidUndeclaredBehaviorMessage = (actual) => `Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${printable(actual)})`; -var nonLeadingSpreadError = "Spread operator may only be used as the first key in an object"; -var preparseKey = (key) => typeof key === "symbol" ? { kind: "required", normalized: key } : key[key.length - 1] === "?" ? key[key.length - 2] === Backslash ? { kind: "required", normalized: `${key.slice(0, -2)}?` } : { - kind: "optional", - normalized: key.slice(0, -1) -} : key[0] === "[" && key[key.length - 1] === "]" ? { kind: "index", normalized: key.slice(1, -1) } : key[0] === Backslash && key[1] === "[" && key[key.length - 1] === "]" ? { kind: "required", normalized: key.slice(1) } : key === "..." ? { kind: "spread" } : key === "+" ? { kind: "undeclared" } : { - kind: "required", - normalized: key === "\\..." ? "..." : key === "\\+" ? "+" : key -}; -var writeInvalidSpreadTypeMessage = (def) => `Spread operand must resolve to an object literal type (was ${def})`; - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/tupleExpressions.js -var maybeParseTupleExpression = (def, ctx) => isIndexZeroExpression(def) ? indexZeroParsers[def[0]](def, ctx) : isIndexOneExpression(def) ? indexOneParsers[def[1]](def, ctx) : null; -var parseKeyOfTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[1], ctx).keyof(); -var parseBranchTuple = (def, ctx) => { - if (def[2] === void 0) - return throwParseError(writeMissingRightOperandMessage(def[1], "")); - const l = ctx.$.parseOwnDefinitionFormat(def[0], ctx); - const r = ctx.$.parseOwnDefinitionFormat(def[2], ctx); - if (def[1] === "|") - return ctx.$.node("union", { branches: [l, r] }); - const result = def[1] === "&" ? intersectNodesRoot(l, r, ctx.$) : pipeNodesRoot(l, r, ctx.$); - if (result instanceof Disjoint) - return result.throw(); - return result; -}; -var parseArrayTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[0], ctx).array(); -var parseMorphTuple = (def, ctx) => { - if (typeof def[2] !== "function") { - return throwParseError(writeMalformedFunctionalExpressionMessage("=>", def[2])); - } - return ctx.$.parseOwnDefinitionFormat(def[0], ctx).pipe(def[2]); -}; -var writeMalformedFunctionalExpressionMessage = (operator, value2) => `${operator === ":" ? "Narrow" : "Morph"} expression requires a function following '${operator}' (was ${typeof value2})`; -var parseNarrowTuple = (def, ctx) => { - if (typeof def[2] !== "function") { - return throwParseError(writeMalformedFunctionalExpressionMessage(":", def[2])); - } - return ctx.$.parseOwnDefinitionFormat(def[0], ctx).constrain("predicate", def[2]); -}; -var parseMetaTuple = (def, ctx) => ctx.$.parseOwnDefinitionFormat(def[0], ctx).configure(def[2], def[3]); -var defineIndexOneParsers = (parsers) => parsers; -var postfixParsers = defineIndexOneParsers({ - "[]": parseArrayTuple, - "?": () => throwParseError(shallowOptionalMessage) -}); -var infixParsers = defineIndexOneParsers({ - "|": parseBranchTuple, - "&": parseBranchTuple, - ":": parseNarrowTuple, - "=>": parseMorphTuple, - "|>": parseBranchTuple, - "@": parseMetaTuple, - // since object and tuple literals parse there via `parseProperty`, - // they must be shallow if parsed directly as a tuple expression - "=": () => throwParseError(shallowDefaultableMessage) -}); -var indexOneParsers = { ...postfixParsers, ...infixParsers }; -var isIndexOneExpression = (def) => indexOneParsers[def[1]] !== void 0; -var defineIndexZeroParsers = (parsers) => parsers; -var indexZeroParsers = defineIndexZeroParsers({ - keyof: parseKeyOfTuple, - instanceof: (def, ctx) => { - if (typeof def[1] !== "function") { - return throwParseError(writeInvalidConstructorMessage(objectKindOrDomainOf(def[1]))); - } - const branches = def.slice(1).map((ctor) => typeof ctor === "function" ? ctx.$.node("proto", { proto: ctor }) : throwParseError(writeInvalidConstructorMessage(objectKindOrDomainOf(ctor)))); - return branches.length === 1 ? branches[0] : ctx.$.node("union", { branches }); - }, - "===": (def, ctx) => ctx.$.units(def.slice(1)) -}); -var isIndexZeroExpression = (def) => indexZeroParsers[def[0]] !== void 0; -var writeInvalidConstructorMessage = (actual) => `Expected a constructor following 'instanceof' operator (was ${actual})`; - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/tupleLiteral.js -var parseTupleLiteral = (def, ctx) => { - let sequences = [{}]; - let i = 0; - while (i < def.length) { - let spread = false; - if (def[i] === "..." && i < def.length - 1) { - spread = true; - i++; - } - const parsedProperty = parseProperty(def[i], ctx); - const [valueNode, operator, possibleDefaultValue] = !isArray(parsedProperty) ? [parsedProperty] : parsedProperty; - i++; - if (spread) { - if (!valueNode.extends($ark.intrinsic.Array)) - return throwParseError(writeNonArraySpreadMessage(valueNode.expression)); - sequences = sequences.flatMap((base) => ( - // since appendElement mutates base, we have to shallow-ish clone it for each branch - valueNode.distribute((branch) => appendSpreadBranch(makeRootAndArrayPropertiesMutable(base), branch)) - )); - } else { - sequences = sequences.map((base) => { - if (operator === "?") - return appendOptionalElement(base, valueNode); - if (operator === "=") - return appendDefaultableElement(base, valueNode, possibleDefaultValue); - return appendRequiredElement(base, valueNode); - }); - } - } - return ctx.$.parseSchema(sequences.map((sequence) => isEmptyObject(sequence) ? { - proto: Array, - exactLength: 0 - } : { - proto: Array, - sequence - })); -}; -var appendRequiredElement = (base, element) => { - if (base.defaultables || base.optionals) { - return throwParseError(base.variadic ? ( - // e.g. [boolean = true, ...string[], number] - postfixAfterOptionalOrDefaultableMessage - ) : requiredPostOptionalMessage); - } - if (base.variadic) { - base.postfix = append(base.postfix, element); - } else { - base.prefix = append(base.prefix, element); - } - return base; -}; -var appendOptionalElement = (base, element) => { - if (base.variadic) - return throwParseError(optionalOrDefaultableAfterVariadicMessage); - base.optionals = append(base.optionals, element); - return base; -}; -var appendDefaultableElement = (base, element, value2) => { - if (base.variadic) - return throwParseError(optionalOrDefaultableAfterVariadicMessage); - if (base.optionals) - return throwParseError(defaultablePostOptionalMessage); - base.defaultables = append(base.defaultables, [[element, value2]]); - return base; -}; -var appendVariadicElement = (base, element) => { - if (base.postfix) - throwParseError(multipleVariadicMesage); - if (base.variadic) { - if (!base.variadic.equals(element)) { - throwParseError(multipleVariadicMesage); - } - } else { - base.variadic = element.internal; - } - return base; -}; -var appendSpreadBranch = (base, branch) => { - const spread = branch.select({ method: "find", kind: "sequence" }); - if (!spread) { - return appendVariadicElement(base, $ark.intrinsic.unknown); - } - if (spread.prefix) - for (const node2 of spread.prefix) - appendRequiredElement(base, node2); - if (spread.optionals) - for (const node2 of spread.optionals) - appendOptionalElement(base, node2); - if (spread.variadic) - appendVariadicElement(base, spread.variadic); - if (spread.postfix) - for (const node2 of spread.postfix) - appendRequiredElement(base, node2); - return base; -}; -var writeNonArraySpreadMessage = (operand) => `Spread element must be an array (was ${operand})`; -var multipleVariadicMesage = "A tuple may have at most one variadic element"; -var requiredPostOptionalMessage = "A required element may not follow an optional element"; -var optionalOrDefaultableAfterVariadicMessage = "An optional element may not follow a variadic element"; -var defaultablePostOptionalMessage = "A defaultable element may not follow an optional element without a default"; - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/parser/definition.js -var parseCache = {}; -var parseInnerDefinition = (def, ctx) => { - if (typeof def === "string") { - if (ctx.args && Object.keys(ctx.args).some((k) => def.includes(k))) { - return parseString(def, ctx); - } - const scopeCache = parseCache[ctx.$.name] ??= {}; - return scopeCache[def] ??= parseString(def, ctx); - } - return hasDomain(def, "object") ? parseObject(def, ctx) : throwParseError(writeBadDefinitionTypeMessage(domainOf(def))); -}; -var parseObject = (def, ctx) => { - const objectKind = objectKindOf(def); - switch (objectKind) { - case void 0: - if (hasArkKind(def, "root")) - return def; - if ("~standard" in def) - return parseStandardSchema(def, ctx); - return parseObjectLiteral(def, ctx); - case "Array": - return parseTuple(def, ctx); - case "RegExp": - return ctx.$.node("intersection", { - domain: "string", - pattern: def - }, { prereduced: true }); - case "Function": { - const resolvedDef = isThunk(def) ? def() : def; - if (hasArkKind(resolvedDef, "root")) - return resolvedDef; - return throwParseError(writeBadDefinitionTypeMessage("Function")); - } - default: - return throwParseError(writeBadDefinitionTypeMessage(objectKind ?? printable(def))); - } -}; -var parseStandardSchema = (def, ctx) => ctx.$.intrinsic.unknown.pipe((v, ctx2) => { - const result = def["~standard"].validate(v); - if (!result.issues) - return result.value; - for (const { message, path: path3 } of result.issues) { - if (path3) { - if (path3.length) { - ctx2.error({ - problem: uncapitalize(message), - relativePath: path3.map((k) => typeof k === "object" ? k.key : k) - }); - } else { - ctx2.error({ - message - }); - } - } else { - ctx2.error({ - message - }); - } - } -}); -var parseTuple = (def, ctx) => maybeParseTupleExpression(def, ctx) ?? parseTupleLiteral(def, ctx); -var writeBadDefinitionTypeMessage = (actual) => `Type definitions must be strings or objects (was ${actual})`; - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/type.js -var InternalTypeParser = class extends Callable { - constructor($2) { - const attach = Object.assign( - { - errors: ArkErrors, - hkt: Hkt, - $: $2, - raw: $2.parse, - module: $2.constructor.module, - scope: $2.constructor.scope, - declare: $2.declare, - define: $2.define, - match: $2.match, - generic: $2.generic, - schema: $2.schema, - // this won't be defined during bootstrapping, but externally always will be - keywords: $2.ambient, - unit: $2.unit, - enumerated: $2.enumerated, - instanceOf: $2.instanceOf, - valueOf: $2.valueOf, - or: $2.or, - and: $2.and, - merge: $2.merge, - pipe: $2.pipe, - fn: $2.fn - }, - // also won't be defined during bootstrapping - $2.ambientAttachments - ); - super((...args2) => { - if (args2.length === 1) { - return $2.parse(args2[0]); - } - if (args2.length === 2 && typeof args2[0] === "string" && args2[0][0] === "<" && args2[0][args2[0].length - 1] === ">") { - const paramString = args2[0].slice(1, -1); - const params = $2.parseGenericParams(paramString, {}); - return new GenericRoot(params, args2[1], $2, $2, null); - } - return $2.parse(args2); - }, { - attach - }); - } -}; - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/scope.js -var $arkTypeRegistry = $ark; -var InternalScope = class _InternalScope extends BaseScope { - get ambientAttachments() { - if (!$arkTypeRegistry.typeAttachments) - return; - return this.cacheGetter("ambientAttachments", flatMorph($arkTypeRegistry.typeAttachments, (k, v) => [ - k, - this.bindReference(v) - ])); - } - preparseOwnAliasEntry(alias, def) { - const firstParamIndex = alias.indexOf("<"); - if (firstParamIndex === -1) { - if (hasArkKind(def, "module") || hasArkKind(def, "generic")) - return [alias, def]; - const qualifiedName = this.name === "ark" ? alias : alias === "root" ? this.name : `${this.name}.${alias}`; - const config3 = this.resolvedConfig.keywords?.[qualifiedName]; - if (config3) - def = [def, "@", config3]; - return [alias, def]; - } - if (alias[alias.length - 1] !== ">") { - throwParseError(`'>' must be the last character of a generic declaration in a scope`); - } - const name = alias.slice(0, firstParamIndex); - const paramString = alias.slice(firstParamIndex + 1, -1); - return [ - name, - // use a thunk definition for the generic so that we can parse - // constraints within the current scope - () => { - const params = this.parseGenericParams(paramString, { alias: name }); - const generic2 = parseGeneric(params, def, this); - return generic2; - } - ]; - } - parseGenericParams(def, opts) { - return parseGenericParamName(new Scanner(def), [], this.createParseContext({ - ...opts, - def, - prefix: "generic" - })); - } - normalizeRootScopeValue(resolution) { - if (isThunk(resolution) && !hasArkKind(resolution, "generic")) - return resolution(); - return resolution; - } - preparseOwnDefinitionFormat(def, opts) { - return { - ...opts, - def, - prefix: opts.alias ?? "type" - }; - } - parseOwnDefinitionFormat(def, ctx) { - const isScopeAlias = ctx.alias && ctx.alias in this.aliases; - if (!isScopeAlias && !ctx.args) - ctx.args = { this: ctx.id }; - const result = parseInnerDefinition(def, ctx); - if (isArray(result)) { - if (result[1] === "=") - return throwParseError(shallowDefaultableMessage); - if (result[1] === "?") - return throwParseError(shallowOptionalMessage); - } - return result; - } - unit = (value2) => this.units([value2]); - valueOf = (tsEnum) => this.units(enumValues(tsEnum)); - enumerated = (...values) => this.units(values); - instanceOf = (ctor) => this.node("proto", { proto: ctor }, { prereduced: true }); - or = (...defs) => this.schema(defs.map((def) => this.parse(def))); - and = (...defs) => defs.reduce((node2, def) => node2.and(this.parse(def)), this.intrinsic.unknown); - merge = (...defs) => defs.reduce((node2, def) => node2.merge(this.parse(def)), this.intrinsic.object); - pipe = (...morphs) => this.intrinsic.unknown.pipe(...morphs); - fn = new InternalFnParser(this); - match = new InternalMatchParser(this); - declare = () => ({ - type: this.type - }); - define(def) { - return def; - } - type = new InternalTypeParser(this); - static scope = ((def, config3 = {}) => new _InternalScope(def, config3)); - static module = ((def, config3 = {}) => this.scope(def, config3).export()); -}; -var scope = Object.assign(InternalScope.scope, { - define: (def) => def -}); -var Scope = InternalScope; - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/keywords/builtins.js -var MergeHkt = class extends Hkt { - description = 'merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'; -}; -var Merge = genericNode(["base", intrinsic.object], ["props", intrinsic.object])((args2) => args2.base.merge(args2.props), MergeHkt); -var arkBuiltins = Scope.module({ - Key: intrinsic.key, - Merge -}); - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/keywords/Array.js -var liftFromHkt = class extends Hkt { -}; -var liftFrom = genericNode("element")((args2) => { - const nonArrayElement = args2.element.exclude(intrinsic.Array); - const lifted = nonArrayElement.array(); - return nonArrayElement.rawOr(lifted).pipe(liftArray).distribute((branch) => branch.assertHasKind("morph").declareOut(lifted), rootSchema); -}, liftFromHkt); -var arkArray = Scope.module({ - root: intrinsic.Array, - readonly: "root", - index: intrinsic.nonNegativeIntegerString, - liftFrom -}, { - name: "Array" -}); - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/keywords/FormData.js -var value = rootSchema(["string", registry.FileConstructor]); -var parsedFormDataValue = value.rawOr(value.array()); -var parsed = rootSchema({ - meta: "an object representing parsed form data", - domain: "object", - index: { - signature: "string", - value: parsedFormDataValue - } -}); -var arkFormData = Scope.module({ - root: ["instanceof", FormData], - value, - parsed, - parse: rootSchema({ - in: FormData, - morphs: (data) => { - const result = {}; - for (const [k, v] of data) { - if (k in result) { - const existing = result[k]; - if (typeof existing === "string" || existing instanceof registry.FileConstructor) - result[k] = [existing, v]; - else - existing.push(v); - } else - result[k] = v; - } - return result; - }, - declaredOut: parsed - }) -}, { - name: "FormData" -}); - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/keywords/TypedArray.js -var TypedArray = Scope.module({ - Int8: ["instanceof", Int8Array], - Uint8: ["instanceof", Uint8Array], - Uint8Clamped: ["instanceof", Uint8ClampedArray], - Int16: ["instanceof", Int16Array], - Uint16: ["instanceof", Uint16Array], - Int32: ["instanceof", Int32Array], - Uint32: ["instanceof", Uint32Array], - Float32: ["instanceof", Float32Array], - Float64: ["instanceof", Float64Array], - BigInt64: ["instanceof", BigInt64Array], - BigUint64: ["instanceof", BigUint64Array] -}, { - name: "TypedArray" -}); - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/keywords/constructors.js -var omittedPrototypes = { - Boolean: 1, - Number: 1, - String: 1 -}; -var arkPrototypes = Scope.module({ - ...flatMorph({ ...ecmascriptConstructors, ...platformConstructors }, (k, v) => k in omittedPrototypes ? [] : [k, ["instanceof", v]]), - Array: arkArray, - TypedArray, - FormData: arkFormData -}); - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/keywords/number.js -var epoch = rootSchema({ - domain: { - domain: "number", - meta: "a number representing a Unix timestamp" - }, - divisor: { - rule: 1, - meta: `an integer representing a Unix timestamp` - }, - min: { - rule: -864e13, - meta: `a Unix timestamp after -8640000000000000` - }, - max: { - rule: 864e13, - meta: "a Unix timestamp before 8640000000000000" - }, - meta: "an integer representing a safe Unix timestamp" -}); -var integer3 = rootSchema({ - domain: "number", - divisor: 1 -}); -var number6 = Scope.module({ - root: intrinsic.number, - integer: integer3, - epoch, - safe: rootSchema({ - domain: { - domain: "number", - numberAllowsNaN: false - }, - min: Number.MIN_SAFE_INTEGER, - max: Number.MAX_SAFE_INTEGER - }), - NaN: ["===", Number.NaN], - Infinity: ["===", Number.POSITIVE_INFINITY], - NegativeInfinity: ["===", Number.NEGATIVE_INFINITY] -}, { - name: "number" -}); - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/keywords/string.js -var regexStringNode = (regex4, description, jsonSchemaFormat) => { - const schema2 = { - domain: "string", - pattern: { - rule: regex4.source, - flags: regex4.flags, - meta: description - } - }; - if (jsonSchemaFormat) - schema2.meta = { format: jsonSchemaFormat }; - return node("intersection", schema2); -}; -var stringIntegerRoot = regexStringNode(wellFormedIntegerMatcher, "a well-formed integer string"); -var stringInteger = Scope.module({ - root: stringIntegerRoot, - parse: rootSchema({ - in: stringIntegerRoot, - morphs: (s, ctx) => { - const parsed2 = Number.parseInt(s); - return Number.isSafeInteger(parsed2) ? parsed2 : ctx.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER"); - }, - declaredOut: intrinsic.integer - }) -}, { - name: "string.integer" -}); -var hex3 = regexStringNode(/^[\dA-Fa-f]+$/, "hex characters only"); -var base644 = Scope.module({ - root: regexStringNode(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/, "base64-encoded"), - url: regexStringNode(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/, "base64url-encoded") -}, { - name: "string.base64" -}); -var preformattedCapitalize = regexStringNode(/^[A-Z].*$/, "capitalized"); -var capitalize2 = Scope.module({ - root: rootSchema({ - in: "string", - morphs: (s) => s.charAt(0).toUpperCase() + s.slice(1), - declaredOut: preformattedCapitalize - }), - preformatted: preformattedCapitalize -}, { - name: "string.capitalize" -}); -var isLuhnValid = (creditCardInput) => { - const sanitized = creditCardInput.replace(/[ -]+/g, ""); - let sum = 0; - let digit; - let tmpNum; - let shouldDouble = false; - for (let i = sanitized.length - 1; i >= 0; i--) { - digit = sanitized.substring(i, i + 1); - tmpNum = Number.parseInt(digit, 10); - if (shouldDouble) { - tmpNum *= 2; - sum += tmpNum >= 10 ? tmpNum % 10 + 1 : tmpNum; - } else - sum += tmpNum; - shouldDouble = !shouldDouble; - } - return !!(sum % 10 === 0 ? sanitized : false); -}; -var creditCardMatcher = /^(?:4\d{12}(?:\d{3,6})?|5[1-5]\d{14}|(222[1-9]|22[3-9]\d|2[3-6]\d{2}|27[01]\d|2720)\d{12}|6(?:011|5\d\d)\d{12,15}|3[47]\d{13}|3(?:0[0-5]|[68]\d)\d{11}|(?:2131|1800|35\d{3})\d{11}|6[27]\d{14}|^(81\d{14,17}))$/; -var creditCard = rootSchema({ - domain: "string", - pattern: { - meta: "a credit card number", - rule: creditCardMatcher.source - }, - predicate: { - meta: "a credit card number", - predicate: isLuhnValid - } -}); -var iso8601Matcher = /^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))(T((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([,.]\d+(?!:))?)?(\17[0-5]\d([,.]\d+)?)?([Zz]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/; -var isParsableDate = (s) => !Number.isNaN(new Date(s).valueOf()); -var parsableDate = rootSchema({ - domain: "string", - predicate: { - meta: "a parsable date", - predicate: isParsableDate - } -}).assertHasKind("intersection"); -var epochRoot = stringInteger.root.internal.narrow((s, ctx) => { - const n = Number.parseInt(s); - const out = number6.epoch(n); - if (out instanceof ArkErrors) { - ctx.errors.merge(out); - return false; - } - return true; -}).configure({ - description: "an integer string representing a safe Unix timestamp" -}, "self").assertHasKind("intersection"); -var epoch2 = Scope.module({ - root: epochRoot, - parse: rootSchema({ - in: epochRoot, - morphs: (s) => new Date(s), - declaredOut: intrinsic.Date - }) -}, { - name: "string.date.epoch" -}); -var isoRoot = regexStringNode(iso8601Matcher, "an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"); -var iso = Scope.module({ - root: isoRoot, - parse: rootSchema({ - in: isoRoot, - morphs: (s) => new Date(s), - declaredOut: intrinsic.Date - }) -}, { - name: "string.date.iso" -}); -var stringDate = Scope.module({ - root: parsableDate, - parse: rootSchema({ - declaredIn: parsableDate, - in: "string", - morphs: (s, ctx) => { - const date5 = new Date(s); - if (Number.isNaN(date5.valueOf())) - return ctx.error("a parsable date"); - return date5; - }, - declaredOut: intrinsic.Date - }), - iso, - epoch: epoch2 -}, { - name: "string.date" -}); -var email4 = regexStringNode( - // considered https://colinhacks.com/essays/reasonable-email-regex but it includes a lookahead - // which breaks some integrations e.g. fast-check - // regex based on: - // https://www.regular-expressions.info/email.html - /^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/, - "an email address", - "email" -); -var ipv4Segment = "(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"; -var ipv4Address = `(${ipv4Segment}[.]){3}${ipv4Segment}`; -var ipv4Matcher = new RegExp(`^${ipv4Address}$`); -var ipv6Segment = "(?:[0-9a-fA-F]{1,4})"; -var ipv6Matcher = new RegExp(`^((?:${ipv6Segment}:){7}(?:${ipv6Segment}|:)|(?:${ipv6Segment}:){6}(?:${ipv4Address}|:${ipv6Segment}|:)|(?:${ipv6Segment}:){5}(?::${ipv4Address}|(:${ipv6Segment}){1,2}|:)|(?:${ipv6Segment}:){4}(?:(:${ipv6Segment}){0,1}:${ipv4Address}|(:${ipv6Segment}){1,3}|:)|(?:${ipv6Segment}:){3}(?:(:${ipv6Segment}){0,2}:${ipv4Address}|(:${ipv6Segment}){1,4}|:)|(?:${ipv6Segment}:){2}(?:(:${ipv6Segment}){0,3}:${ipv4Address}|(:${ipv6Segment}){1,5}|:)|(?:${ipv6Segment}:){1}(?:(:${ipv6Segment}){0,4}:${ipv4Address}|(:${ipv6Segment}){1,6}|:)|(?::((?::${ipv6Segment}){0,5}:${ipv4Address}|(?::${ipv6Segment}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`); -var ip = Scope.module({ - root: ["v4 | v6", "@", "an IP address"], - v4: regexStringNode(ipv4Matcher, "an IPv4 address", "ipv4"), - v6: regexStringNode(ipv6Matcher, "an IPv6 address", "ipv6") -}, { - name: "string.ip" -}); -var jsonStringDescription = "a JSON string"; -var writeJsonSyntaxErrorProblem = (error49) => { - if (!(error49 instanceof SyntaxError)) - throw error49; - return `must be ${jsonStringDescription} (${error49})`; -}; -var jsonRoot = rootSchema({ - meta: jsonStringDescription, - domain: "string", - predicate: { - meta: jsonStringDescription, - predicate: (s, ctx) => { - try { - JSON.parse(s); - return true; - } catch (e) { - return ctx.reject({ - code: "predicate", - expected: jsonStringDescription, - problem: writeJsonSyntaxErrorProblem(e) - }); - } - } - } -}); -var parseJson = (s, ctx) => { - if (s.length === 0) { - return ctx.error({ - code: "predicate", - expected: jsonStringDescription, - actual: "empty" - }); - } - try { - return JSON.parse(s); - } catch (e) { - return ctx.error({ - code: "predicate", - expected: jsonStringDescription, - problem: writeJsonSyntaxErrorProblem(e) - }); - } -}; -var json2 = Scope.module({ - root: jsonRoot, - parse: rootSchema({ - meta: "safe JSON string parser", - in: "string", - morphs: parseJson, - declaredOut: intrinsic.jsonObject - }) -}, { - name: "string.json" -}); -var preformattedLower = regexStringNode(/^[a-z]*$/, "only lowercase letters"); -var lower = Scope.module({ - root: rootSchema({ - in: "string", - morphs: (s) => s.toLowerCase(), - declaredOut: preformattedLower - }), - preformatted: preformattedLower -}, { - name: "string.lower" -}); -var normalizedForms = ["NFC", "NFD", "NFKC", "NFKD"]; -var preformattedNodes = flatMorph(normalizedForms, (i, form) => [ - form, - rootSchema({ - domain: "string", - predicate: (s) => s.normalize(form) === s, - meta: `${form}-normalized unicode` - }) -]); -var normalizeNodes = flatMorph(normalizedForms, (i, form) => [ - form, - rootSchema({ - in: "string", - morphs: (s) => s.normalize(form), - declaredOut: preformattedNodes[form] - }) -]); -var NFC = Scope.module({ - root: normalizeNodes.NFC, - preformatted: preformattedNodes.NFC -}, { - name: "string.normalize.NFC" -}); -var NFD = Scope.module({ - root: normalizeNodes.NFD, - preformatted: preformattedNodes.NFD -}, { - name: "string.normalize.NFD" -}); -var NFKC = Scope.module({ - root: normalizeNodes.NFKC, - preformatted: preformattedNodes.NFKC -}, { - name: "string.normalize.NFKC" -}); -var NFKD = Scope.module({ - root: normalizeNodes.NFKD, - preformatted: preformattedNodes.NFKD -}, { - name: "string.normalize.NFKD" -}); -var normalize = Scope.module({ - root: "NFC", - NFC, - NFD, - NFKC, - NFKD -}, { - name: "string.normalize" -}); -var numericRoot = regexStringNode(numericStringMatcher, "a well-formed numeric string"); -var stringNumeric = Scope.module({ - root: numericRoot, - parse: rootSchema({ - in: numericRoot, - morphs: (s) => Number.parseFloat(s), - declaredOut: intrinsic.number - }) -}, { - name: "string.numeric" -}); -var regexPatternDescription = "a regex pattern"; -var regex2 = rootSchema({ - domain: "string", - predicate: { - meta: regexPatternDescription, - predicate: (s, ctx) => { - try { - new RegExp(s); - return true; - } catch (e) { - return ctx.reject({ - code: "predicate", - expected: regexPatternDescription, - problem: String(e) - }); - } - } - }, - meta: { format: "regex" } -}); -var semverMatcher = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*))*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?$/; -var semver = regexStringNode(semverMatcher, "a semantic version (see https://semver.org/)"); -var preformattedTrim = regexStringNode( - // no leading or trailing whitespace - /^\S.*\S$|^\S?$/, - "trimmed" -); -var trim = Scope.module({ - root: rootSchema({ - in: "string", - morphs: (s) => s.trim(), - declaredOut: preformattedTrim - }), - preformatted: preformattedTrim -}, { - name: "string.trim" -}); -var preformattedUpper = regexStringNode(/^[A-Z]*$/, "only uppercase letters"); -var upper = Scope.module({ - root: rootSchema({ - in: "string", - morphs: (s) => s.toUpperCase(), - declaredOut: preformattedUpper - }), - preformatted: preformattedUpper -}, { - name: "string.upper" -}); -var isParsableUrl = (s) => URL.canParse(s); -var urlRoot = rootSchema({ - domain: "string", - predicate: { - meta: "a URL string", - predicate: isParsableUrl - }, - // URL.canParse allows a subset of the RFC-3986 URI spec - // since there is no other serializable validation, best include a format - meta: { format: "uri" } -}); -var url3 = Scope.module({ - root: urlRoot, - parse: rootSchema({ - declaredIn: urlRoot, - in: "string", - morphs: (s, ctx) => { - try { - return new URL(s); - } catch { - return ctx.error("a URL string"); - } - }, - declaredOut: rootSchema(URL) - }) -}, { - name: "string.url" -}); -var uuid5 = Scope.module({ - // the meta tuple expression ensures the error message does not delegate - // to the individual branches, which are too detailed - root: [ - "versioned | nil | max", - "@", - { description: "a UUID", format: "uuid" } - ], - "#nil": "'00000000-0000-0000-0000-000000000000'", - "#max": "'ffffffff-ffff-ffff-ffff-ffffffffffff'", - "#versioned": /[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}/i, - v1: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-1[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv1"), - v2: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-2[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv2"), - v3: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-3[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv3"), - v4: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv4"), - v5: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-5[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv5"), - v6: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-6[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv6"), - v7: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-7[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv7"), - v8: regexStringNode(/^[\da-f]{8}-[\da-f]{4}-8[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i, "a UUIDv8") -}, { - name: "string.uuid" -}); -var string5 = Scope.module({ - root: intrinsic.string, - alpha: regexStringNode(/^[A-Za-z]*$/, "only letters"), - alphanumeric: regexStringNode(/^[\dA-Za-z]*$/, "only letters and digits 0-9"), - hex: hex3, - base64: base644, - capitalize: capitalize2, - creditCard, - date: stringDate, - digits: regexStringNode(/^\d*$/, "only digits 0-9"), - email: email4, - integer: stringInteger, - ip, - json: json2, - lower, - normalize, - numeric: stringNumeric, - regex: regex2, - semver, - trim, - upper, - url: url3, - uuid: uuid5 -}, { - name: "string" -}); - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/keywords/ts.js -var arkTsKeywords = Scope.module({ - bigint: intrinsic.bigint, - boolean: intrinsic.boolean, - false: intrinsic.false, - never: intrinsic.never, - null: intrinsic.null, - number: intrinsic.number, - object: intrinsic.object, - string: intrinsic.string, - symbol: intrinsic.symbol, - true: intrinsic.true, - unknown: intrinsic.unknown, - undefined: intrinsic.undefined -}); -var unknown3 = Scope.module({ - root: intrinsic.unknown, - any: intrinsic.unknown -}, { - name: "unknown" -}); -var json3 = Scope.module({ - root: intrinsic.jsonObject, - stringify: node("morph", { - in: intrinsic.jsonObject, - morphs: (data) => JSON.stringify(data), - declaredOut: intrinsic.string - }) -}, { - name: "object.json" -}); -var object4 = Scope.module({ - root: intrinsic.object, - json: json3 -}, { - name: "object" -}); -var RecordHkt = class extends Hkt { - description = 'instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'; -}; -var Record = genericNode(["K", intrinsic.key], "V")((args2) => ({ - domain: "object", - index: { - signature: args2.K, - value: args2.V - } -}), RecordHkt); -var PickHkt = class extends Hkt { - description = 'pick a set of properties from an object like `Pick(User, "name | age")`'; -}; -var Pick = genericNode(["T", intrinsic.object], ["K", intrinsic.key])((args2) => args2.T.pick(args2.K), PickHkt); -var OmitHkt = class extends Hkt { - description = 'omit a set of properties from an object like `Omit(User, "age")`'; -}; -var Omit = genericNode(["T", intrinsic.object], ["K", intrinsic.key])((args2) => args2.T.omit(args2.K), OmitHkt); -var PartialHkt = class extends Hkt { - description = "make all named properties of an object optional like `Partial(User)`"; -}; -var Partial = genericNode(["T", intrinsic.object])((args2) => args2.T.partial(), PartialHkt); -var RequiredHkt = class extends Hkt { - description = "make all named properties of an object required like `Required(User)`"; -}; -var Required2 = genericNode(["T", intrinsic.object])((args2) => args2.T.required(), RequiredHkt); -var ExcludeHkt = class extends Hkt { - description = 'exclude branches of a union like `Exclude("boolean", "true")`'; -}; -var Exclude = genericNode("T", "U")((args2) => args2.T.exclude(args2.U), ExcludeHkt); -var ExtractHkt = class extends Hkt { - description = 'extract branches of a union like `Extract("0 | false | 1", "number")`'; -}; -var Extract = genericNode("T", "U")((args2) => args2.T.extract(args2.U), ExtractHkt); -var arkTsGenerics = Scope.module({ - Exclude, - Extract, - Omit, - Partial, - Pick, - Record, - Required: Required2 -}); - -// node_modules/.pnpm/arktype@2.2.0/node_modules/arktype/out/keywords/keywords.js -var ark = scope({ - ...arkTsKeywords, - ...arkTsGenerics, - ...arkPrototypes, - ...arkBuiltins, - string: string5, - number: number6, - object: object4, - unknown: unknown3 -}, { prereducedAliases: true, name: "ark" }); -var keywords = ark.export(); -Object.assign($arkTypeRegistry.ambient, keywords); -$arkTypeRegistry.typeAttachments = { - string: keywords.string.root, - number: keywords.number.root, - bigint: keywords.bigint, - boolean: keywords.boolean, - symbol: keywords.symbol, - undefined: keywords.undefined, - null: keywords.null, - object: keywords.object.root, - unknown: keywords.unknown.root, - false: keywords.false, - true: keywords.true, - never: keywords.never, - arrayIndex: keywords.Array.index, - Key: keywords.Key, - Record: keywords.Record, - Array: keywords.Array.root, - Date: keywords.Date -}; -var type = Object.assign( - ark.type, - // assign attachments newly parsed in keywords - // future scopes add these directly from the - // registry when their TypeParsers are instantiated - $arkTypeRegistry.typeAttachments -); -var match2 = ark.match; -var fn = ark.fn; -var generic = ark.generic; -var schema = ark.schema; -var define2 = ark.define; -var declare = ark.declare; - // utils/gitAuth.ts import { execSync } from "node:child_process"; import { createHash } from "node:crypto"; @@ -139809,3959 +144563,6 @@ function exitWithSignal(signal) { process.exit(128 + os.constants.signals[signal]); } -// utils/github.ts -var core2 = __toESM(require_core(), 1); -import { createSign } from "node:crypto"; -import { rename, writeFile } from "node:fs/promises"; -import { dirname, join } from "node:path"; - -// node_modules/.pnpm/@octokit+plugin-throttling@11.0.3_@octokit+core@7.0.5/node_modules/@octokit/plugin-throttling/dist-bundle/index.js -var import_light = __toESM(require_light(), 1); -var VERSION = "0.0.0-development"; -var noop2 = () => Promise.resolve(); -function wrapRequest(state, request2, options) { - return state.retryLimiter.schedule(doRequest, state, request2, options); -} -async function doRequest(state, request2, options) { - const { pathname } = new URL(options.url, "http://github.test"); - const isAuth = isAuthRequest(options.method, pathname); - const isWrite = !isAuth && options.method !== "GET" && options.method !== "HEAD"; - const isSearch = options.method === "GET" && pathname.startsWith("/search/"); - const isGraphQL = pathname.startsWith("/graphql"); - const retryCount = ~~request2.retryCount; - const jobOptions = retryCount > 0 ? { priority: 0, weight: 0 } : {}; - if (state.clustering) { - jobOptions.expiration = 1e3 * 60; - } - if (isWrite || isGraphQL) { - await state.write.key(state.id).schedule(jobOptions, noop2); - } - if (isWrite && state.triggersNotification(pathname)) { - await state.notifications.key(state.id).schedule(jobOptions, noop2); - } - if (isSearch) { - await state.search.key(state.id).schedule(jobOptions, noop2); - } - const req = (isAuth ? state.auth : state.global).key(state.id).schedule(jobOptions, request2, options); - if (isGraphQL) { - const res = await req; - if (res.data.errors != null && res.data.errors.some((error49) => error49.type === "RATE_LIMITED")) { - const error49 = Object.assign(new Error("GraphQL Rate Limit Exceeded"), { - response: res, - data: res.data - }); - throw error49; - } - } - return req; -} -function isAuthRequest(method, pathname) { - return method === "PATCH" && // https://docs.github.com/en/rest/apps/apps?apiVersion=2022-11-28#create-a-scoped-access-token - /^\/applications\/[^/]+\/token\/scoped$/.test(pathname) || method === "POST" && // https://docs.github.com/en/rest/apps/oauth-applications?apiVersion=2022-11-28#reset-a-token - (/^\/applications\/[^/]+\/token$/.test(pathname) || // https://docs.github.com/en/rest/apps/apps?apiVersion=2022-11-28#create-an-installation-access-token-for-an-app - /^\/app\/installations\/[^/]+\/access_tokens$/.test(pathname) || // https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/authorizing-oauth-apps - pathname === "/login/oauth/access_token"); -} -var triggers_notification_paths_default = [ - "/orgs/{org}/invitations", - "/orgs/{org}/invitations/{invitation_id}", - "/orgs/{org}/teams/{team_slug}/discussions", - "/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", - "/repos/{owner}/{repo}/collaborators/{username}", - "/repos/{owner}/{repo}/commits/{commit_sha}/comments", - "/repos/{owner}/{repo}/issues", - "/repos/{owner}/{repo}/issues/{issue_number}/comments", - "/repos/{owner}/{repo}/issues/{issue_number}/sub_issue", - "/repos/{owner}/{repo}/issues/{issue_number}/sub_issues/priority", - "/repos/{owner}/{repo}/pulls", - "/repos/{owner}/{repo}/pulls/{pull_number}/comments", - "/repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies", - "/repos/{owner}/{repo}/pulls/{pull_number}/merge", - "/repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers", - "/repos/{owner}/{repo}/pulls/{pull_number}/reviews", - "/repos/{owner}/{repo}/releases", - "/teams/{team_id}/discussions", - "/teams/{team_id}/discussions/{discussion_number}/comments" -]; -function routeMatcher(paths) { - const regexes = paths.map( - (path3) => path3.split("/").map((c) => c.startsWith("{") ? "(?:.+?)" : c).join("/") - ); - const regex22 = `^(?:${regexes.map((r) => `(?:${r})`).join("|")})[^/]*$`; - return new RegExp(regex22, "i"); -} -var regex3 = routeMatcher(triggers_notification_paths_default); -var triggersNotification = regex3.test.bind(regex3); -var groups = {}; -var createGroups = function(Bottleneck, common) { - groups.global = new Bottleneck.Group({ - id: "octokit-global", - maxConcurrent: 10, - ...common - }); - groups.auth = new Bottleneck.Group({ - id: "octokit-auth", - maxConcurrent: 1, - ...common - }); - groups.search = new Bottleneck.Group({ - id: "octokit-search", - maxConcurrent: 1, - minTime: 2e3, - ...common - }); - groups.write = new Bottleneck.Group({ - id: "octokit-write", - maxConcurrent: 1, - minTime: 1e3, - ...common - }); - groups.notifications = new Bottleneck.Group({ - id: "octokit-notifications", - maxConcurrent: 1, - minTime: 3e3, - ...common - }); -}; -function throttling(octokit, octokitOptions) { - const { - enabled = true, - Bottleneck = import_light.default, - id = "no-id", - timeout = 1e3 * 60 * 2, - // Redis TTL: 2 minutes - connection - } = octokitOptions.throttle || {}; - if (!enabled) { - return {}; - } - const common = { timeout }; - if (typeof connection !== "undefined") { - common.connection = connection; - } - if (groups.global == null) { - createGroups(Bottleneck, common); - } - const state = Object.assign( - { - clustering: connection != null, - triggersNotification, - fallbackSecondaryRateRetryAfter: 60, - retryAfterBaseValue: 1e3, - retryLimiter: new Bottleneck(), - id, - ...groups - }, - octokitOptions.throttle - ); - if (typeof state.onSecondaryRateLimit !== "function" || typeof state.onRateLimit !== "function") { - throw new Error(`octokit/plugin-throttling error: - You must pass the onSecondaryRateLimit and onRateLimit error handlers. - See https://octokit.github.io/rest.js/#throttling - - const octokit = new Octokit({ - throttle: { - onSecondaryRateLimit: (retryAfter, options) => {/* ... */}, - onRateLimit: (retryAfter, options) => {/* ... */} - } - }) - `); - } - const events = {}; - const emitter = new Bottleneck.Events(events); - events.on("secondary-limit", state.onSecondaryRateLimit); - events.on("rate-limit", state.onRateLimit); - events.on( - "error", - (e) => octokit.log.warn("Error in throttling-plugin limit handler", e) - ); - state.retryLimiter.on("failed", async function(error49, info2) { - const [state2, request2, options] = info2.args; - const { pathname } = new URL(options.url, "http://github.test"); - const shouldRetryGraphQL = pathname.startsWith("/graphql") && error49.status !== 401; - if (!(shouldRetryGraphQL || error49.status === 403 || error49.status === 429)) { - return; - } - const retryCount = ~~request2.retryCount; - request2.retryCount = retryCount; - options.request.retryCount = retryCount; - const { wantRetry, retryAfter = 0 } = await (async function() { - if (/\bsecondary rate\b/i.test(error49.message)) { - const retryAfter2 = Number(error49.response.headers["retry-after"]) || state2.fallbackSecondaryRateRetryAfter; - const wantRetry2 = await emitter.trigger( - "secondary-limit", - retryAfter2, - options, - octokit, - retryCount - ); - return { wantRetry: wantRetry2, retryAfter: retryAfter2 }; - } - if (error49.response.headers != null && error49.response.headers["x-ratelimit-remaining"] === "0" || (error49.response.data?.errors ?? []).some( - (error210) => error210.type === "RATE_LIMITED" - )) { - const rateLimitReset = new Date( - ~~error49.response.headers["x-ratelimit-reset"] * 1e3 - ).getTime(); - const retryAfter2 = Math.max( - // Add one second so we retry _after_ the reset time - // https://docs.github.com/en/rest/overview/resources-in-the-rest-api?apiVersion=2022-11-28#exceeding-the-rate-limit - Math.ceil((rateLimitReset - Date.now()) / 1e3) + 1, - 0 - ); - const wantRetry2 = await emitter.trigger( - "rate-limit", - retryAfter2, - options, - octokit, - retryCount - ); - return { wantRetry: wantRetry2, retryAfter: retryAfter2 }; - } - return {}; - })(); - if (wantRetry) { - request2.retryCount++; - return retryAfter * state2.retryAfterBaseValue; - } - }); - octokit.hook.wrap("request", wrapRequest.bind(null, state)); - return {}; -} -throttling.VERSION = VERSION; -throttling.triggersNotification = triggersNotification; - -// node_modules/.pnpm/universal-user-agent@7.0.3/node_modules/universal-user-agent/index.js -function getUserAgent() { - if (typeof navigator === "object" && "userAgent" in navigator) { - return navigator.userAgent; - } - if (typeof process === "object" && process.version !== void 0) { - return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; - } - return ""; -} - -// node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/lib/register.js -function register3(state, name, method, options) { - if (typeof method !== "function") { - throw new Error("method for before hook must be a function"); - } - if (!options) { - options = {}; - } - if (Array.isArray(name)) { - return name.reverse().reduce((callback, name2) => { - return register3.bind(null, state, name2, callback, options); - }, method)(); - } - return Promise.resolve().then(() => { - if (!state.registry[name]) { - return method(options); - } - return state.registry[name].reduce((method2, registered) => { - return registered.hook.bind(null, method2, options); - }, method)(); - }); -} - -// node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/lib/add.js -function addHook(state, kind, name, hook2) { - const orig = hook2; - if (!state.registry[name]) { - state.registry[name] = []; - } - if (kind === "before") { - hook2 = (method, options) => { - return Promise.resolve().then(orig.bind(null, options)).then(method.bind(null, options)); - }; - } - if (kind === "after") { - hook2 = (method, options) => { - let result; - return Promise.resolve().then(method.bind(null, options)).then((result_) => { - result = result_; - return orig(result, options); - }).then(() => { - return result; - }); - }; - } - if (kind === "error") { - hook2 = (method, options) => { - return Promise.resolve().then(method.bind(null, options)).catch((error49) => { - return orig(error49, options); - }); - }; - } - state.registry[name].push({ - hook: hook2, - orig - }); -} - -// node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/lib/remove.js -function removeHook(state, name, method) { - if (!state.registry[name]) { - return; - } - const index = state.registry[name].map((registered) => { - return registered.orig; - }).indexOf(method); - if (index === -1) { - return; - } - state.registry[name].splice(index, 1); -} - -// node_modules/.pnpm/before-after-hook@4.0.0/node_modules/before-after-hook/index.js -var bind = Function.bind; -var bindable = bind.bind(bind); -function bindApi(hook2, state, name) { - const removeHookRef = bindable(removeHook, null).apply( - null, - name ? [state, name] : [state] - ); - hook2.api = { remove: removeHookRef }; - hook2.remove = removeHookRef; - ["before", "error", "after", "wrap"].forEach((kind) => { - const args2 = name ? [state, kind, name] : [state, kind]; - hook2[kind] = hook2.api[kind] = bindable(addHook, null).apply(null, args2); - }); -} -function Singular() { - const singularHookName = Symbol("Singular"); - const singularHookState = { - registry: {} - }; - const singularHook = register3.bind(null, singularHookState, singularHookName); - bindApi(singularHook, singularHookState, singularHookName); - return singularHook; -} -function Collection() { - const state = { - registry: {} - }; - const hook2 = register3.bind(null, state); - bindApi(hook2, state); - return hook2; -} -var before_after_hook_default = { Singular, Collection }; - -// node_modules/.pnpm/@octokit+endpoint@11.0.1/node_modules/@octokit/endpoint/dist-bundle/index.js -var VERSION2 = "0.0.0-development"; -var userAgent = `octokit-endpoint.js/${VERSION2} ${getUserAgent()}`; -var DEFAULTS = { - method: "GET", - baseUrl: "https://api.github.com", - headers: { - accept: "application/vnd.github.v3+json", - "user-agent": userAgent - }, - mediaType: { - format: "" - } -}; -function lowercaseKeys(object5) { - if (!object5) { - return {}; - } - return Object.keys(object5).reduce((newObj, key) => { - newObj[key.toLowerCase()] = object5[key]; - return newObj; - }, {}); -} -function isPlainObject3(value2) { - if (typeof value2 !== "object" || value2 === null) return false; - if (Object.prototype.toString.call(value2) !== "[object Object]") return false; - const proto = Object.getPrototypeOf(value2); - if (proto === null) return true; - const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor; - return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value2); -} -function mergeDeep(defaults, options) { - const result = Object.assign({}, defaults); - Object.keys(options).forEach((key) => { - if (isPlainObject3(options[key])) { - if (!(key in defaults)) Object.assign(result, { [key]: options[key] }); - else result[key] = mergeDeep(defaults[key], options[key]); - } else { - Object.assign(result, { [key]: options[key] }); - } - }); - return result; -} -function removeUndefinedProperties(obj) { - for (const key in obj) { - if (obj[key] === void 0) { - delete obj[key]; - } - } - return obj; -} -function merge3(defaults, route, options) { - if (typeof route === "string") { - let [method, url4] = route.split(" "); - options = Object.assign(url4 ? { method, url: url4 } : { url: method }, options); - } else { - options = Object.assign({}, route); - } - options.headers = lowercaseKeys(options.headers); - removeUndefinedProperties(options); - removeUndefinedProperties(options.headers); - const mergedOptions = mergeDeep(defaults || {}, options); - if (options.url === "/graphql") { - if (defaults && defaults.mediaType.previews?.length) { - mergedOptions.mediaType.previews = defaults.mediaType.previews.filter( - (preview) => !mergedOptions.mediaType.previews.includes(preview) - ).concat(mergedOptions.mediaType.previews); - } - mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, "")); - } - return mergedOptions; -} -function addQueryParameters(url4, parameters) { - const separator2 = /\?/.test(url4) ? "&" : "?"; - const names = Object.keys(parameters); - if (names.length === 0) { - return url4; - } - return url4 + separator2 + names.map((name) => { - if (name === "q") { - return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); - } - return `${name}=${encodeURIComponent(parameters[name])}`; - }).join("&"); -} -var urlVariableRegex = /\{[^{}}]+\}/g; -function removeNonChars(variableName) { - return variableName.replace(/(?:^\W+)|(?:(? a.concat(b), []); -} -function omit4(object5, keysToOmit) { - const result = { __proto__: null }; - for (const key of Object.keys(object5)) { - if (keysToOmit.indexOf(key) === -1) { - result[key] = object5[key]; - } - } - return result; -} -function encodeReserved(str) { - return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) { - if (!/%[0-9A-Fa-f]/.test(part)) { - part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); - } - return part; - }).join(""); -} -function encodeUnreserved(str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { - return "%" + c.charCodeAt(0).toString(16).toUpperCase(); - }); -} -function encodeValue(operator, value2, key) { - value2 = operator === "+" || operator === "#" ? encodeReserved(value2) : encodeUnreserved(value2); - if (key) { - return encodeUnreserved(key) + "=" + value2; - } else { - return value2; - } -} -function isDefined2(value2) { - return value2 !== void 0 && value2 !== null; -} -function isKeyOperator(operator) { - return operator === ";" || operator === "&" || operator === "?"; -} -function getValues(context, operator, key, modifier) { - var value2 = context[key], result = []; - if (isDefined2(value2) && value2 !== "") { - if (typeof value2 === "string" || typeof value2 === "number" || typeof value2 === "boolean") { - value2 = value2.toString(); - if (modifier && modifier !== "*") { - value2 = value2.substring(0, parseInt(modifier, 10)); - } - result.push( - encodeValue(operator, value2, isKeyOperator(operator) ? key : "") - ); - } else { - if (modifier === "*") { - if (Array.isArray(value2)) { - value2.filter(isDefined2).forEach(function(value22) { - result.push( - encodeValue(operator, value22, isKeyOperator(operator) ? key : "") - ); - }); - } else { - Object.keys(value2).forEach(function(k) { - if (isDefined2(value2[k])) { - result.push(encodeValue(operator, value2[k], k)); - } - }); - } - } else { - const tmp = []; - if (Array.isArray(value2)) { - value2.filter(isDefined2).forEach(function(value22) { - tmp.push(encodeValue(operator, value22)); - }); - } else { - Object.keys(value2).forEach(function(k) { - if (isDefined2(value2[k])) { - tmp.push(encodeUnreserved(k)); - tmp.push(encodeValue(operator, value2[k].toString())); - } - }); - } - if (isKeyOperator(operator)) { - result.push(encodeUnreserved(key) + "=" + tmp.join(",")); - } else if (tmp.length !== 0) { - result.push(tmp.join(",")); - } - } - } - } else { - if (operator === ";") { - if (isDefined2(value2)) { - result.push(encodeUnreserved(key)); - } - } else if (value2 === "" && (operator === "&" || operator === "?")) { - result.push(encodeUnreserved(key) + "="); - } else if (value2 === "") { - result.push(""); - } - } - return result; -} -function parseUrl(template) { - return { - expand: expand.bind(null, template) - }; -} -function expand(template, context) { - var operators = ["+", "#", ".", "/", ";", "?", "&"]; - template = template.replace( - /\{([^\{\}]+)\}|([^\{\}]+)/g, - function(_, expression, literal3) { - if (expression) { - let operator = ""; - const values = []; - if (operators.indexOf(expression.charAt(0)) !== -1) { - operator = expression.charAt(0); - expression = expression.substr(1); - } - expression.split(/,/g).forEach(function(variable) { - var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); - values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); - }); - if (operator && operator !== "+") { - var separator2 = ","; - if (operator === "?") { - separator2 = "&"; - } else if (operator !== "#") { - separator2 = operator; - } - return (values.length !== 0 ? operator : "") + values.join(separator2); - } else { - return values.join(","); - } - } else { - return encodeReserved(literal3); - } - } - ); - if (template === "/") { - return template; - } else { - return template.replace(/\/$/, ""); - } -} -function parse4(options) { - let method = options.method.toUpperCase(); - let url4 = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); - let headers = Object.assign({}, options.headers); - let body; - let parameters = omit4(options, [ - "method", - "baseUrl", - "url", - "headers", - "request", - "mediaType" - ]); - const urlVariableNames = extractUrlVariableNames(url4); - url4 = parseUrl(url4).expand(parameters); - if (!/^http/.test(url4)) { - url4 = options.baseUrl + url4; - } - const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl"); - const remainingParameters = omit4(parameters, omittedParameters); - const isBinaryRequest = /application\/octet-stream/i.test(headers.accept); - if (!isBinaryRequest) { - if (options.mediaType.format) { - headers.accept = headers.accept.split(/,/).map( - (format2) => format2.replace( - /application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, - `application/vnd$1$2.${options.mediaType.format}` - ) - ).join(","); - } - if (url4.endsWith("/graphql")) { - if (options.mediaType.previews?.length) { - const previewsFromAcceptHeader = headers.accept.match(/(? { - const format2 = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; - return `application/vnd.github.${preview}-preview${format2}`; - }).join(","); - } - } - } - if (["GET", "HEAD"].includes(method)) { - url4 = addQueryParameters(url4, remainingParameters); - } else { - if ("data" in remainingParameters) { - body = remainingParameters.data; - } else { - if (Object.keys(remainingParameters).length) { - body = remainingParameters; - } - } - } - if (!headers["content-type"] && typeof body !== "undefined") { - headers["content-type"] = "application/json; charset=utf-8"; - } - if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { - body = ""; - } - return Object.assign( - { method, url: url4, headers }, - typeof body !== "undefined" ? { body } : null, - options.request ? { request: options.request } : null - ); -} -function endpointWithDefaults(defaults, route, options) { - return parse4(merge3(defaults, route, options)); -} -function withDefaults(oldDefaults, newDefaults) { - const DEFAULTS2 = merge3(oldDefaults, newDefaults); - const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2); - return Object.assign(endpoint2, { - DEFAULTS: DEFAULTS2, - defaults: withDefaults.bind(null, DEFAULTS2), - merge: merge3.bind(null, DEFAULTS2), - parse: parse4 - }); -} -var endpoint = withDefaults(null, DEFAULTS); - -// node_modules/.pnpm/@octokit+request@10.0.5/node_modules/@octokit/request/dist-bundle/index.js -var import_fast_content_type_parse = __toESM(require_fast_content_type_parse(), 1); - -// node_modules/.pnpm/@octokit+request-error@7.0.1/node_modules/@octokit/request-error/dist-src/index.js -var RequestError = class extends Error { - name; - /** - * http status code - */ - status; - /** - * Request options that lead to the error. - */ - request; - /** - * Response object if a response was received - */ - response; - constructor(message, statusCode, options) { - super(message); - this.name = "HttpError"; - this.status = Number.parseInt(statusCode); - if (Number.isNaN(this.status)) { - this.status = 0; - } - if ("response" in options) { - this.response = options.response; - } - const requestCopy = Object.assign({}, options.request); - if (options.request.headers.authorization) { - requestCopy.headers = Object.assign({}, options.request.headers, { - authorization: options.request.headers.authorization.replace( - /(? [ - name, - String(value2) - ]) - ); - let fetchResponse; - try { - fetchResponse = await fetch3(requestOptions.url, { - method: requestOptions.method, - body, - redirect: requestOptions.request?.redirect, - headers: requestHeaders, - signal: requestOptions.request?.signal, - // duplex must be set if request.body is ReadableStream or Async Iterables. - // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex. - ...requestOptions.body && { duplex: "half" } - }); - } catch (error49) { - let message = "Unknown Error"; - if (error49 instanceof Error) { - if (error49.name === "AbortError") { - error49.status = 500; - throw error49; - } - message = error49.message; - if (error49.name === "TypeError" && "cause" in error49) { - if (error49.cause instanceof Error) { - message = error49.cause.message; - } else if (typeof error49.cause === "string") { - message = error49.cause; - } - } - } - const requestError = new RequestError(message, 500, { - request: requestOptions - }); - requestError.cause = error49; - throw requestError; - } - const status = fetchResponse.status; - const url4 = fetchResponse.url; - const responseHeaders = {}; - for (const [key, value2] of fetchResponse.headers) { - responseHeaders[key] = value2; - } - const octokitResponse = { - url: url4, - status, - headers: responseHeaders, - data: "" - }; - if ("deprecation" in responseHeaders) { - const matches = responseHeaders.link && responseHeaders.link.match(/<([^<>]+)>; rel="deprecation"/); - const deprecationLink = matches && matches.pop(); - log2.warn( - `[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${responseHeaders.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` - ); - } - if (status === 204 || status === 205) { - return octokitResponse; - } - if (requestOptions.method === "HEAD") { - if (status < 400) { - return octokitResponse; - } - throw new RequestError(fetchResponse.statusText, status, { - response: octokitResponse, - request: requestOptions - }); - } - if (status === 304) { - octokitResponse.data = await getResponseData(fetchResponse); - throw new RequestError("Not modified", status, { - response: octokitResponse, - request: requestOptions - }); - } - if (status >= 400) { - octokitResponse.data = await getResponseData(fetchResponse); - throw new RequestError(toErrorMessage(octokitResponse.data), status, { - response: octokitResponse, - request: requestOptions - }); - } - octokitResponse.data = parseSuccessResponseBody ? await getResponseData(fetchResponse) : fetchResponse.body; - return octokitResponse; -} -async function getResponseData(response) { - const contentType = response.headers.get("content-type"); - if (!contentType) { - return response.text().catch(() => ""); - } - const mimetype = (0, import_fast_content_type_parse.safeParse)(contentType); - if (isJSONResponse(mimetype)) { - let text = ""; - try { - text = await response.text(); - return JSON.parse(text); - } catch (err) { - return text; - } - } else if (mimetype.type.startsWith("text/") || mimetype.parameters.charset?.toLowerCase() === "utf-8") { - return response.text().catch(() => ""); - } else { - return response.arrayBuffer().catch(() => new ArrayBuffer(0)); - } -} -function isJSONResponse(mimetype) { - return mimetype.type === "application/json" || mimetype.type === "application/scim+json"; -} -function toErrorMessage(data) { - if (typeof data === "string") { - return data; - } - if (data instanceof ArrayBuffer) { - return "Unknown error"; - } - if ("message" in data) { - const suffix2 = "documentation_url" in data ? ` - ${data.documentation_url}` : ""; - return Array.isArray(data.errors) ? `${data.message}: ${data.errors.map((v) => JSON.stringify(v)).join(", ")}${suffix2}` : `${data.message}${suffix2}`; - } - return `Unknown error: ${JSON.stringify(data)}`; -} -function withDefaults2(oldEndpoint, newDefaults) { - const endpoint2 = oldEndpoint.defaults(newDefaults); - const newApi = function(route, parameters) { - const endpointOptions = endpoint2.merge(route, parameters); - if (!endpointOptions.request || !endpointOptions.request.hook) { - return fetchWrapper(endpoint2.parse(endpointOptions)); - } - const request2 = (route2, parameters2) => { - return fetchWrapper( - endpoint2.parse(endpoint2.merge(route2, parameters2)) - ); - }; - Object.assign(request2, { - endpoint: endpoint2, - defaults: withDefaults2.bind(null, endpoint2) - }); - return endpointOptions.request.hook(request2, endpointOptions); - }; - return Object.assign(newApi, { - endpoint: endpoint2, - defaults: withDefaults2.bind(null, endpoint2) - }); -} -var request = withDefaults2(endpoint, defaults_default); - -// node_modules/.pnpm/@octokit+graphql@9.0.2/node_modules/@octokit/graphql/dist-bundle/index.js -var VERSION4 = "0.0.0-development"; -function _buildMessageForResponseErrors(data) { - return `Request failed due to following response errors: -` + data.errors.map((e) => ` - ${e.message}`).join("\n"); -} -var GraphqlResponseError = class extends Error { - constructor(request2, headers, response) { - super(_buildMessageForResponseErrors(response)); - this.request = request2; - this.headers = headers; - this.response = response; - this.errors = response.errors; - this.data = response.data; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - } - name = "GraphqlResponseError"; - errors; - data; -}; -var NON_VARIABLE_OPTIONS = [ - "method", - "baseUrl", - "url", - "headers", - "request", - "query", - "mediaType", - "operationName" -]; -var FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"]; -var GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; -function graphql(request2, query, options) { - if (options) { - if (typeof query === "string" && "query" in options) { - return Promise.reject( - new Error(`[@octokit/graphql] "query" cannot be used as variable name`) - ); - } - for (const key in options) { - if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue; - return Promise.reject( - new Error( - `[@octokit/graphql] "${key}" cannot be used as variable name` - ) - ); - } - } - const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query; - const requestOptions = Object.keys( - parsedOptions - ).reduce((result, key) => { - if (NON_VARIABLE_OPTIONS.includes(key)) { - result[key] = parsedOptions[key]; - return result; - } - if (!result.variables) { - result.variables = {}; - } - result.variables[key] = parsedOptions[key]; - return result; - }, {}); - const baseUrl = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl; - if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) { - requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql"); - } - return request2(requestOptions).then((response) => { - if (response.data.errors) { - const headers = {}; - for (const key of Object.keys(response.headers)) { - headers[key] = response.headers[key]; - } - throw new GraphqlResponseError( - requestOptions, - headers, - response.data - ); - } - return response.data.data; - }); -} -function withDefaults3(request2, newDefaults) { - const newRequest = request2.defaults(newDefaults); - const newApi = (query, options) => { - return graphql(newRequest, query, options); - }; - return Object.assign(newApi, { - defaults: withDefaults3.bind(null, newRequest), - endpoint: newRequest.endpoint - }); -} -var graphql2 = withDefaults3(request, { - headers: { - "user-agent": `octokit-graphql.js/${VERSION4} ${getUserAgent()}` - }, - method: "POST", - url: "/graphql" -}); -function withCustomRequest(customRequest) { - return withDefaults3(customRequest, { - method: "POST", - url: "/graphql" - }); -} - -// node_modules/.pnpm/@octokit+auth-token@6.0.0/node_modules/@octokit/auth-token/dist-bundle/index.js -var b64url = "(?:[a-zA-Z0-9_-]+)"; -var sep = "\\."; -var jwtRE = new RegExp(`^${b64url}${sep}${b64url}${sep}${b64url}$`); -var isJWT = jwtRE.test.bind(jwtRE); -async function auth(token) { - const isApp = isJWT(token); - const isInstallation = token.startsWith("v1.") || token.startsWith("ghs_"); - const isUserToServer = token.startsWith("ghu_"); - const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth"; - return { - type: "token", - token, - tokenType - }; -} -function withAuthorizationPrefix(token) { - if (token.split(/\./).length === 3) { - return `bearer ${token}`; - } - return `token ${token}`; -} -async function hook(token, request2, route, parameters) { - const endpoint2 = request2.endpoint.merge( - route, - parameters - ); - endpoint2.headers.authorization = withAuthorizationPrefix(token); - return request2(endpoint2); -} -var createTokenAuth = function createTokenAuth2(token) { - if (!token) { - throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); - } - if (typeof token !== "string") { - throw new Error( - "[@octokit/auth-token] Token passed to createTokenAuth is not a string" - ); - } - token = token.replace(/^(token|bearer) +/i, ""); - return Object.assign(auth.bind(null, token), { - hook: hook.bind(null, token) - }); -}; - -// node_modules/.pnpm/@octokit+core@7.0.5/node_modules/@octokit/core/dist-src/version.js -var VERSION5 = "7.0.5"; - -// node_modules/.pnpm/@octokit+core@7.0.5/node_modules/@octokit/core/dist-src/index.js -var noop3 = () => { -}; -var consoleWarn = console.warn.bind(console); -var consoleError = console.error.bind(console); -function createLogger(logger = {}) { - if (typeof logger.debug !== "function") { - logger.debug = noop3; - } - if (typeof logger.info !== "function") { - logger.info = noop3; - } - if (typeof logger.warn !== "function") { - logger.warn = consoleWarn; - } - if (typeof logger.error !== "function") { - logger.error = consoleError; - } - return logger; -} -var userAgentTrail = `octokit-core.js/${VERSION5} ${getUserAgent()}`; -var Octokit = class { - static VERSION = VERSION5; - static defaults(defaults) { - const OctokitWithDefaults = class extends this { - constructor(...args2) { - const options = args2[0] || {}; - if (typeof defaults === "function") { - super(defaults(options)); - return; - } - super( - Object.assign( - {}, - defaults, - options, - options.userAgent && defaults.userAgent ? { - userAgent: `${options.userAgent} ${defaults.userAgent}` - } : null - ) - ); - } - }; - return OctokitWithDefaults; - } - static plugins = []; - /** - * Attach a plugin (or many) to your Octokit instance. - * - * @example - * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) - */ - static plugin(...newPlugins) { - const currentPlugins = this.plugins; - const NewOctokit = class extends this { - static plugins = currentPlugins.concat( - newPlugins.filter((plugin) => !currentPlugins.includes(plugin)) - ); - }; - return NewOctokit; - } - constructor(options = {}) { - const hook2 = new before_after_hook_default.Collection(); - const requestDefaults = { - baseUrl: request.endpoint.DEFAULTS.baseUrl, - headers: {}, - request: Object.assign({}, options.request, { - // @ts-ignore internal usage only, no need to type - hook: hook2.bind(null, "request") - }), - mediaType: { - previews: [], - format: "" - } - }; - requestDefaults.headers["user-agent"] = options.userAgent ? `${options.userAgent} ${userAgentTrail}` : userAgentTrail; - if (options.baseUrl) { - requestDefaults.baseUrl = options.baseUrl; - } - if (options.previews) { - requestDefaults.mediaType.previews = options.previews; - } - if (options.timeZone) { - requestDefaults.headers["time-zone"] = options.timeZone; - } - this.request = request.defaults(requestDefaults); - this.graphql = withCustomRequest(this.request).defaults(requestDefaults); - this.log = createLogger(options.log); - this.hook = hook2; - if (!options.authStrategy) { - if (!options.auth) { - this.auth = async () => ({ - type: "unauthenticated" - }); - } else { - const auth2 = createTokenAuth(options.auth); - hook2.wrap("request", auth2.hook); - this.auth = auth2; - } - } else { - const { authStrategy, ...otherOptions } = options; - const auth2 = authStrategy( - Object.assign( - { - request: this.request, - log: this.log, - // we pass the current octokit instance as well as its constructor options - // to allow for authentication strategies that return a new octokit instance - // that shares the same internal state as the current one. The original - // requirement for this was the "event-octokit" authentication strategy - // of https://github.com/probot/octokit-auth-probot. - octokit: this, - octokitOptions: otherOptions - }, - options.auth - ) - ); - hook2.wrap("request", auth2.hook); - this.auth = auth2; - } - const classConstructor = this.constructor; - for (let i = 0; i < classConstructor.plugins.length; ++i) { - Object.assign(this, classConstructor.plugins[i](this, options)); - } - } - // assigned during constructor - request; - graphql; - log; - hook; - // TODO: type `octokit.auth` based on passed options.authStrategy - auth; -}; - -// node_modules/.pnpm/@octokit+plugin-request-log@6.0.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-request-log/dist-src/version.js -var VERSION6 = "6.0.0"; - -// node_modules/.pnpm/@octokit+plugin-request-log@6.0.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-request-log/dist-src/index.js -function requestLog(octokit) { - octokit.hook.wrap("request", (request2, options) => { - octokit.log.debug("request", options); - const start = Date.now(); - const requestOptions = octokit.request.endpoint.parse(options); - const path3 = requestOptions.url.replace(options.baseUrl, ""); - return request2(options).then((response) => { - const requestId = response.headers["x-github-request-id"]; - octokit.log.info( - `${requestOptions.method} ${path3} - ${response.status} with id ${requestId} in ${Date.now() - start}ms` - ); - return response; - }).catch((error49) => { - const requestId = error49.response?.headers["x-github-request-id"] || "UNKNOWN"; - octokit.log.error( - `${requestOptions.method} ${path3} - ${error49.status} with id ${requestId} in ${Date.now() - start}ms` - ); - throw error49; - }); - }); -} -requestLog.VERSION = VERSION6; - -// node_modules/.pnpm/@octokit+plugin-paginate-rest@13.2.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-paginate-rest/dist-bundle/index.js -var VERSION7 = "0.0.0-development"; -function normalizePaginatedListResponse(response) { - if (!response.data) { - return { - ...response, - data: [] - }; - } - const responseNeedsNormalization = ("total_count" in response.data || "total_commits" in response.data) && !("url" in response.data); - if (!responseNeedsNormalization) return response; - const incompleteResults = response.data.incomplete_results; - const repositorySelection = response.data.repository_selection; - const totalCount = response.data.total_count; - const totalCommits = response.data.total_commits; - delete response.data.incomplete_results; - delete response.data.repository_selection; - delete response.data.total_count; - delete response.data.total_commits; - const namespaceKey = Object.keys(response.data)[0]; - const data = response.data[namespaceKey]; - response.data = data; - if (typeof incompleteResults !== "undefined") { - response.data.incomplete_results = incompleteResults; - } - if (typeof repositorySelection !== "undefined") { - response.data.repository_selection = repositorySelection; - } - response.data.total_count = totalCount; - response.data.total_commits = totalCommits; - return response; -} -function iterator(octokit, route, parameters) { - const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters); - const requestMethod = typeof route === "function" ? route : octokit.request; - const method = options.method; - const headers = options.headers; - let url4 = options.url; - return { - [Symbol.asyncIterator]: () => ({ - async next() { - if (!url4) return { done: true }; - try { - const response = await requestMethod({ method, url: url4, headers }); - const normalizedResponse = normalizePaginatedListResponse(response); - url4 = ((normalizedResponse.headers.link || "").match( - /<([^<>]+)>;\s*rel="next"/ - ) || [])[1]; - if (!url4 && "total_commits" in normalizedResponse.data) { - const parsedUrl = new URL(normalizedResponse.url); - const params = parsedUrl.searchParams; - const page = parseInt(params.get("page") || "1", 10); - const per_page = parseInt(params.get("per_page") || "250", 10); - if (page * per_page < normalizedResponse.data.total_commits) { - params.set("page", String(page + 1)); - url4 = parsedUrl.toString(); - } - } - return { value: normalizedResponse }; - } catch (error49) { - if (error49.status !== 409) throw error49; - url4 = ""; - return { - value: { - status: 200, - headers: {}, - data: [] - } - }; - } - } - }) - }; -} -function paginate(octokit, route, parameters, mapFn) { - if (typeof parameters === "function") { - mapFn = parameters; - parameters = void 0; - } - return gather( - octokit, - [], - iterator(octokit, route, parameters)[Symbol.asyncIterator](), - mapFn - ); -} -function gather(octokit, results, iterator2, mapFn) { - return iterator2.next().then((result) => { - if (result.done) { - return results; - } - let earlyExit = false; - function done() { - earlyExit = true; - } - results = results.concat( - mapFn ? mapFn(result.value, done) : result.value.data - ); - if (earlyExit) { - return results; - } - return gather(octokit, results, iterator2, mapFn); - }); -} -var composePaginateRest = Object.assign(paginate, { - iterator -}); -function paginateRest(octokit) { - return { - paginate: Object.assign(paginate.bind(null, octokit), { - iterator: iterator.bind(null, octokit) - }) - }; -} -paginateRest.VERSION = VERSION7; - -// node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@16.1.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/version.js -var VERSION8 = "16.1.0"; - -// node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@16.1.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/generated/endpoints.js -var Endpoints = { - actions: { - addCustomLabelsToSelfHostedRunnerForOrg: [ - "POST /orgs/{org}/actions/runners/{runner_id}/labels" - ], - addCustomLabelsToSelfHostedRunnerForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - addRepoAccessToSelfHostedRunnerGroupInOrg: [ - "PUT /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories/{repository_id}" - ], - addSelectedRepoToOrgSecret: [ - "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" - ], - addSelectedRepoToOrgVariable: [ - "PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" - ], - approveWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve" - ], - cancelWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel" - ], - createEnvironmentVariable: [ - "POST /repos/{owner}/{repo}/environments/{environment_name}/variables" - ], - createHostedRunnerForOrg: ["POST /orgs/{org}/actions/hosted-runners"], - createOrUpdateEnvironmentSecret: [ - "PUT /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}" - ], - createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], - createOrUpdateRepoSecret: [ - "PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}" - ], - createOrgVariable: ["POST /orgs/{org}/actions/variables"], - createRegistrationTokenForOrg: [ - "POST /orgs/{org}/actions/runners/registration-token" - ], - createRegistrationTokenForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/registration-token" - ], - createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], - createRemoveTokenForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/remove-token" - ], - createRepoVariable: ["POST /repos/{owner}/{repo}/actions/variables"], - createWorkflowDispatch: [ - "POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches" - ], - deleteActionsCacheById: [ - "DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}" - ], - deleteActionsCacheByKey: [ - "DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}" - ], - deleteArtifact: [ - "DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}" - ], - deleteEnvironmentSecret: [ - "DELETE /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}" - ], - deleteEnvironmentVariable: [ - "DELETE /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}" - ], - deleteHostedRunnerForOrg: [ - "DELETE /orgs/{org}/actions/hosted-runners/{hosted_runner_id}" - ], - deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"], - deleteOrgVariable: ["DELETE /orgs/{org}/actions/variables/{name}"], - deleteRepoSecret: [ - "DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}" - ], - deleteRepoVariable: [ - "DELETE /repos/{owner}/{repo}/actions/variables/{name}" - ], - deleteSelfHostedRunnerFromOrg: [ - "DELETE /orgs/{org}/actions/runners/{runner_id}" - ], - deleteSelfHostedRunnerFromRepo: [ - "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}" - ], - deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"], - deleteWorkflowRunLogs: [ - "DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs" - ], - disableSelectedRepositoryGithubActionsOrganization: [ - "DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}" - ], - disableWorkflow: [ - "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable" - ], - downloadArtifact: [ - "GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}" - ], - downloadJobLogsForWorkflowRun: [ - "GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs" - ], - downloadWorkflowRunAttemptLogs: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs" - ], - downloadWorkflowRunLogs: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs" - ], - enableSelectedRepositoryGithubActionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/repositories/{repository_id}" - ], - enableWorkflow: [ - "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable" - ], - forceCancelWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel" - ], - generateRunnerJitconfigForOrg: [ - "POST /orgs/{org}/actions/runners/generate-jitconfig" - ], - generateRunnerJitconfigForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig" - ], - getActionsCacheList: ["GET /repos/{owner}/{repo}/actions/caches"], - getActionsCacheUsage: ["GET /repos/{owner}/{repo}/actions/cache/usage"], - getActionsCacheUsageByRepoForOrg: [ - "GET /orgs/{org}/actions/cache/usage-by-repository" - ], - getActionsCacheUsageForOrg: ["GET /orgs/{org}/actions/cache/usage"], - getAllowedActionsOrganization: [ - "GET /orgs/{org}/actions/permissions/selected-actions" - ], - getAllowedActionsRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions/selected-actions" - ], - getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], - getCustomOidcSubClaimForRepo: [ - "GET /repos/{owner}/{repo}/actions/oidc/customization/sub" - ], - getEnvironmentPublicKey: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/public-key" - ], - getEnvironmentSecret: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}" - ], - getEnvironmentVariable: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}" - ], - getGithubActionsDefaultWorkflowPermissionsOrganization: [ - "GET /orgs/{org}/actions/permissions/workflow" - ], - getGithubActionsDefaultWorkflowPermissionsRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions/workflow" - ], - getGithubActionsPermissionsOrganization: [ - "GET /orgs/{org}/actions/permissions" - ], - getGithubActionsPermissionsRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions" - ], - getHostedRunnerForOrg: [ - "GET /orgs/{org}/actions/hosted-runners/{hosted_runner_id}" - ], - getHostedRunnersGithubOwnedImagesForOrg: [ - "GET /orgs/{org}/actions/hosted-runners/images/github-owned" - ], - getHostedRunnersLimitsForOrg: [ - "GET /orgs/{org}/actions/hosted-runners/limits" - ], - getHostedRunnersMachineSpecsForOrg: [ - "GET /orgs/{org}/actions/hosted-runners/machine-sizes" - ], - getHostedRunnersPartnerImagesForOrg: [ - "GET /orgs/{org}/actions/hosted-runners/images/partner" - ], - getHostedRunnersPlatformsForOrg: [ - "GET /orgs/{org}/actions/hosted-runners/platforms" - ], - getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"], - getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"], - getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"], - getOrgVariable: ["GET /orgs/{org}/actions/variables/{name}"], - getPendingDeploymentsForRun: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" - ], - getRepoPermissions: [ - "GET /repos/{owner}/{repo}/actions/permissions", - {}, - { renamed: ["actions", "getGithubActionsPermissionsRepository"] } - ], - getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"], - getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"], - getRepoVariable: ["GET /repos/{owner}/{repo}/actions/variables/{name}"], - getReviewsForRun: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals" - ], - getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"], - getSelfHostedRunnerForRepo: [ - "GET /repos/{owner}/{repo}/actions/runners/{runner_id}" - ], - getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"], - getWorkflowAccessToRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions/access" - ], - getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"], - getWorkflowRunAttempt: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}" - ], - getWorkflowRunUsage: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing" - ], - getWorkflowUsage: [ - "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing" - ], - listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"], - listEnvironmentSecrets: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/secrets" - ], - listEnvironmentVariables: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/variables" - ], - listGithubHostedRunnersInGroupForOrg: [ - "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/hosted-runners" - ], - listHostedRunnersForOrg: ["GET /orgs/{org}/actions/hosted-runners"], - listJobsForWorkflowRun: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs" - ], - listJobsForWorkflowRunAttempt: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs" - ], - listLabelsForSelfHostedRunnerForOrg: [ - "GET /orgs/{org}/actions/runners/{runner_id}/labels" - ], - listLabelsForSelfHostedRunnerForRepo: [ - "GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - listOrgSecrets: ["GET /orgs/{org}/actions/secrets"], - listOrgVariables: ["GET /orgs/{org}/actions/variables"], - listRepoOrganizationSecrets: [ - "GET /repos/{owner}/{repo}/actions/organization-secrets" - ], - listRepoOrganizationVariables: [ - "GET /repos/{owner}/{repo}/actions/organization-variables" - ], - listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"], - listRepoVariables: ["GET /repos/{owner}/{repo}/actions/variables"], - listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"], - listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"], - listRunnerApplicationsForRepo: [ - "GET /repos/{owner}/{repo}/actions/runners/downloads" - ], - listSelectedReposForOrgSecret: [ - "GET /orgs/{org}/actions/secrets/{secret_name}/repositories" - ], - listSelectedReposForOrgVariable: [ - "GET /orgs/{org}/actions/variables/{name}/repositories" - ], - listSelectedRepositoriesEnabledGithubActionsOrganization: [ - "GET /orgs/{org}/actions/permissions/repositories" - ], - listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"], - listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"], - listWorkflowRunArtifacts: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts" - ], - listWorkflowRuns: [ - "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs" - ], - listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"], - reRunJobForWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun" - ], - reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"], - reRunWorkflowFailedJobs: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs" - ], - removeAllCustomLabelsFromSelfHostedRunnerForOrg: [ - "DELETE /orgs/{org}/actions/runners/{runner_id}/labels" - ], - removeAllCustomLabelsFromSelfHostedRunnerForRepo: [ - "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - removeCustomLabelFromSelfHostedRunnerForOrg: [ - "DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}" - ], - removeCustomLabelFromSelfHostedRunnerForRepo: [ - "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}" - ], - removeSelectedRepoFromOrgSecret: [ - "DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" - ], - removeSelectedRepoFromOrgVariable: [ - "DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" - ], - reviewCustomGatesForRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule" - ], - reviewPendingDeploymentsForRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" - ], - setAllowedActionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/selected-actions" - ], - setAllowedActionsRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions/selected-actions" - ], - setCustomLabelsForSelfHostedRunnerForOrg: [ - "PUT /orgs/{org}/actions/runners/{runner_id}/labels" - ], - setCustomLabelsForSelfHostedRunnerForRepo: [ - "PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - setCustomOidcSubClaimForRepo: [ - "PUT /repos/{owner}/{repo}/actions/oidc/customization/sub" - ], - setGithubActionsDefaultWorkflowPermissionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/workflow" - ], - setGithubActionsDefaultWorkflowPermissionsRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions/workflow" - ], - setGithubActionsPermissionsOrganization: [ - "PUT /orgs/{org}/actions/permissions" - ], - setGithubActionsPermissionsRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions" - ], - setSelectedReposForOrgSecret: [ - "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories" - ], - setSelectedReposForOrgVariable: [ - "PUT /orgs/{org}/actions/variables/{name}/repositories" - ], - setSelectedRepositoriesEnabledGithubActionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/repositories" - ], - setWorkflowAccessToRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions/access" - ], - updateEnvironmentVariable: [ - "PATCH /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}" - ], - updateHostedRunnerForOrg: [ - "PATCH /orgs/{org}/actions/hosted-runners/{hosted_runner_id}" - ], - updateOrgVariable: ["PATCH /orgs/{org}/actions/variables/{name}"], - updateRepoVariable: [ - "PATCH /repos/{owner}/{repo}/actions/variables/{name}" - ] - }, - activity: { - checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"], - deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"], - deleteThreadSubscription: [ - "DELETE /notifications/threads/{thread_id}/subscription" - ], - getFeeds: ["GET /feeds"], - getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"], - getThread: ["GET /notifications/threads/{thread_id}"], - getThreadSubscriptionForAuthenticatedUser: [ - "GET /notifications/threads/{thread_id}/subscription" - ], - listEventsForAuthenticatedUser: ["GET /users/{username}/events"], - listNotificationsForAuthenticatedUser: ["GET /notifications"], - listOrgEventsForAuthenticatedUser: [ - "GET /users/{username}/events/orgs/{org}" - ], - listPublicEvents: ["GET /events"], - listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"], - listPublicEventsForUser: ["GET /users/{username}/events/public"], - listPublicOrgEvents: ["GET /orgs/{org}/events"], - listReceivedEventsForUser: ["GET /users/{username}/received_events"], - listReceivedPublicEventsForUser: [ - "GET /users/{username}/received_events/public" - ], - listRepoEvents: ["GET /repos/{owner}/{repo}/events"], - listRepoNotificationsForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/notifications" - ], - listReposStarredByAuthenticatedUser: ["GET /user/starred"], - listReposStarredByUser: ["GET /users/{username}/starred"], - listReposWatchedByUser: ["GET /users/{username}/subscriptions"], - listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"], - listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"], - listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"], - markNotificationsAsRead: ["PUT /notifications"], - markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"], - markThreadAsDone: ["DELETE /notifications/threads/{thread_id}"], - markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"], - setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"], - setThreadSubscription: [ - "PUT /notifications/threads/{thread_id}/subscription" - ], - starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"], - unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"] - }, - apps: { - addRepoToInstallation: [ - "PUT /user/installations/{installation_id}/repositories/{repository_id}", - {}, - { renamed: ["apps", "addRepoToInstallationForAuthenticatedUser"] } - ], - addRepoToInstallationForAuthenticatedUser: [ - "PUT /user/installations/{installation_id}/repositories/{repository_id}" - ], - checkToken: ["POST /applications/{client_id}/token"], - createFromManifest: ["POST /app-manifests/{code}/conversions"], - createInstallationAccessToken: [ - "POST /app/installations/{installation_id}/access_tokens" - ], - deleteAuthorization: ["DELETE /applications/{client_id}/grant"], - deleteInstallation: ["DELETE /app/installations/{installation_id}"], - deleteToken: ["DELETE /applications/{client_id}/token"], - getAuthenticated: ["GET /app"], - getBySlug: ["GET /apps/{app_slug}"], - getInstallation: ["GET /app/installations/{installation_id}"], - getOrgInstallation: ["GET /orgs/{org}/installation"], - getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"], - getSubscriptionPlanForAccount: [ - "GET /marketplace_listing/accounts/{account_id}" - ], - getSubscriptionPlanForAccountStubbed: [ - "GET /marketplace_listing/stubbed/accounts/{account_id}" - ], - getUserInstallation: ["GET /users/{username}/installation"], - getWebhookConfigForApp: ["GET /app/hook/config"], - getWebhookDelivery: ["GET /app/hook/deliveries/{delivery_id}"], - listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"], - listAccountsForPlanStubbed: [ - "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts" - ], - listInstallationReposForAuthenticatedUser: [ - "GET /user/installations/{installation_id}/repositories" - ], - listInstallationRequestsForAuthenticatedApp: [ - "GET /app/installation-requests" - ], - listInstallations: ["GET /app/installations"], - listInstallationsForAuthenticatedUser: ["GET /user/installations"], - listPlans: ["GET /marketplace_listing/plans"], - listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"], - listReposAccessibleToInstallation: ["GET /installation/repositories"], - listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"], - listSubscriptionsForAuthenticatedUserStubbed: [ - "GET /user/marketplace_purchases/stubbed" - ], - listWebhookDeliveries: ["GET /app/hook/deliveries"], - redeliverWebhookDelivery: [ - "POST /app/hook/deliveries/{delivery_id}/attempts" - ], - removeRepoFromInstallation: [ - "DELETE /user/installations/{installation_id}/repositories/{repository_id}", - {}, - { renamed: ["apps", "removeRepoFromInstallationForAuthenticatedUser"] } - ], - removeRepoFromInstallationForAuthenticatedUser: [ - "DELETE /user/installations/{installation_id}/repositories/{repository_id}" - ], - resetToken: ["PATCH /applications/{client_id}/token"], - revokeInstallationAccessToken: ["DELETE /installation/token"], - scopeToken: ["POST /applications/{client_id}/token/scoped"], - suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"], - unsuspendInstallation: [ - "DELETE /app/installations/{installation_id}/suspended" - ], - updateWebhookConfigForApp: ["PATCH /app/hook/config"] - }, - billing: { - getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"], - getGithubActionsBillingUser: [ - "GET /users/{username}/settings/billing/actions" - ], - getGithubBillingUsageReportOrg: [ - "GET /organizations/{org}/settings/billing/usage" - ], - getGithubBillingUsageReportUser: [ - "GET /users/{username}/settings/billing/usage" - ], - getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"], - getGithubPackagesBillingUser: [ - "GET /users/{username}/settings/billing/packages" - ], - getSharedStorageBillingOrg: [ - "GET /orgs/{org}/settings/billing/shared-storage" - ], - getSharedStorageBillingUser: [ - "GET /users/{username}/settings/billing/shared-storage" - ] - }, - campaigns: { - createCampaign: ["POST /orgs/{org}/campaigns"], - deleteCampaign: ["DELETE /orgs/{org}/campaigns/{campaign_number}"], - getCampaignSummary: ["GET /orgs/{org}/campaigns/{campaign_number}"], - listOrgCampaigns: ["GET /orgs/{org}/campaigns"], - updateCampaign: ["PATCH /orgs/{org}/campaigns/{campaign_number}"] - }, - checks: { - create: ["POST /repos/{owner}/{repo}/check-runs"], - createSuite: ["POST /repos/{owner}/{repo}/check-suites"], - get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"], - getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"], - listAnnotations: [ - "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations" - ], - listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"], - listForSuite: [ - "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs" - ], - listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"], - rerequestRun: [ - "POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest" - ], - rerequestSuite: [ - "POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest" - ], - setSuitesPreferences: [ - "PATCH /repos/{owner}/{repo}/check-suites/preferences" - ], - update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"] - }, - codeScanning: { - commitAutofix: [ - "POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix/commits" - ], - createAutofix: [ - "POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix" - ], - createVariantAnalysis: [ - "POST /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses" - ], - deleteAnalysis: [ - "DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}" - ], - deleteCodeqlDatabase: [ - "DELETE /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}" - ], - getAlert: [ - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", - {}, - { renamedParameters: { alert_id: "alert_number" } } - ], - getAnalysis: [ - "GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}" - ], - getAutofix: [ - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix" - ], - getCodeqlDatabase: [ - "GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}" - ], - getDefaultSetup: ["GET /repos/{owner}/{repo}/code-scanning/default-setup"], - getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"], - getVariantAnalysis: [ - "GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}" - ], - getVariantAnalysisRepoTask: [ - "GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}/repos/{repo_owner}/{repo_name}" - ], - listAlertInstances: [ - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances" - ], - listAlertsForOrg: ["GET /orgs/{org}/code-scanning/alerts"], - listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"], - listAlertsInstances: [ - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", - {}, - { renamed: ["codeScanning", "listAlertInstances"] } - ], - listCodeqlDatabases: [ - "GET /repos/{owner}/{repo}/code-scanning/codeql/databases" - ], - listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"], - updateAlert: [ - "PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}" - ], - updateDefaultSetup: [ - "PATCH /repos/{owner}/{repo}/code-scanning/default-setup" - ], - uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"] - }, - codeSecurity: { - attachConfiguration: [ - "POST /orgs/{org}/code-security/configurations/{configuration_id}/attach" - ], - attachEnterpriseConfiguration: [ - "POST /enterprises/{enterprise}/code-security/configurations/{configuration_id}/attach" - ], - createConfiguration: ["POST /orgs/{org}/code-security/configurations"], - createConfigurationForEnterprise: [ - "POST /enterprises/{enterprise}/code-security/configurations" - ], - deleteConfiguration: [ - "DELETE /orgs/{org}/code-security/configurations/{configuration_id}" - ], - deleteConfigurationForEnterprise: [ - "DELETE /enterprises/{enterprise}/code-security/configurations/{configuration_id}" - ], - detachConfiguration: [ - "DELETE /orgs/{org}/code-security/configurations/detach" - ], - getConfiguration: [ - "GET /orgs/{org}/code-security/configurations/{configuration_id}" - ], - getConfigurationForRepository: [ - "GET /repos/{owner}/{repo}/code-security-configuration" - ], - getConfigurationsForEnterprise: [ - "GET /enterprises/{enterprise}/code-security/configurations" - ], - getConfigurationsForOrg: ["GET /orgs/{org}/code-security/configurations"], - getDefaultConfigurations: [ - "GET /orgs/{org}/code-security/configurations/defaults" - ], - getDefaultConfigurationsForEnterprise: [ - "GET /enterprises/{enterprise}/code-security/configurations/defaults" - ], - getRepositoriesForConfiguration: [ - "GET /orgs/{org}/code-security/configurations/{configuration_id}/repositories" - ], - getRepositoriesForEnterpriseConfiguration: [ - "GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}/repositories" - ], - getSingleConfigurationForEnterprise: [ - "GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}" - ], - setConfigurationAsDefault: [ - "PUT /orgs/{org}/code-security/configurations/{configuration_id}/defaults" - ], - setConfigurationAsDefaultForEnterprise: [ - "PUT /enterprises/{enterprise}/code-security/configurations/{configuration_id}/defaults" - ], - updateConfiguration: [ - "PATCH /orgs/{org}/code-security/configurations/{configuration_id}" - ], - updateEnterpriseConfiguration: [ - "PATCH /enterprises/{enterprise}/code-security/configurations/{configuration_id}" - ] - }, - codesOfConduct: { - getAllCodesOfConduct: ["GET /codes_of_conduct"], - getConductCode: ["GET /codes_of_conduct/{key}"] - }, - codespaces: { - addRepositoryForSecretForAuthenticatedUser: [ - "PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - addSelectedRepoToOrgSecret: [ - "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - checkPermissionsForDevcontainer: [ - "GET /repos/{owner}/{repo}/codespaces/permissions_check" - ], - codespaceMachinesForAuthenticatedUser: [ - "GET /user/codespaces/{codespace_name}/machines" - ], - createForAuthenticatedUser: ["POST /user/codespaces"], - createOrUpdateOrgSecret: [ - "PUT /orgs/{org}/codespaces/secrets/{secret_name}" - ], - createOrUpdateRepoSecret: [ - "PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" - ], - createOrUpdateSecretForAuthenticatedUser: [ - "PUT /user/codespaces/secrets/{secret_name}" - ], - createWithPrForAuthenticatedUser: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces" - ], - createWithRepoForAuthenticatedUser: [ - "POST /repos/{owner}/{repo}/codespaces" - ], - deleteForAuthenticatedUser: ["DELETE /user/codespaces/{codespace_name}"], - deleteFromOrganization: [ - "DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}" - ], - deleteOrgSecret: ["DELETE /orgs/{org}/codespaces/secrets/{secret_name}"], - deleteRepoSecret: [ - "DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" - ], - deleteSecretForAuthenticatedUser: [ - "DELETE /user/codespaces/secrets/{secret_name}" - ], - exportForAuthenticatedUser: [ - "POST /user/codespaces/{codespace_name}/exports" - ], - getCodespacesForUserInOrg: [ - "GET /orgs/{org}/members/{username}/codespaces" - ], - getExportDetailsForAuthenticatedUser: [ - "GET /user/codespaces/{codespace_name}/exports/{export_id}" - ], - getForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}"], - getOrgPublicKey: ["GET /orgs/{org}/codespaces/secrets/public-key"], - getOrgSecret: ["GET /orgs/{org}/codespaces/secrets/{secret_name}"], - getPublicKeyForAuthenticatedUser: [ - "GET /user/codespaces/secrets/public-key" - ], - getRepoPublicKey: [ - "GET /repos/{owner}/{repo}/codespaces/secrets/public-key" - ], - getRepoSecret: [ - "GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" - ], - getSecretForAuthenticatedUser: [ - "GET /user/codespaces/secrets/{secret_name}" - ], - listDevcontainersInRepositoryForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces/devcontainers" - ], - listForAuthenticatedUser: ["GET /user/codespaces"], - listInOrganization: [ - "GET /orgs/{org}/codespaces", - {}, - { renamedParameters: { org_id: "org" } } - ], - listInRepositoryForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces" - ], - listOrgSecrets: ["GET /orgs/{org}/codespaces/secrets"], - listRepoSecrets: ["GET /repos/{owner}/{repo}/codespaces/secrets"], - listRepositoriesForSecretForAuthenticatedUser: [ - "GET /user/codespaces/secrets/{secret_name}/repositories" - ], - listSecretsForAuthenticatedUser: ["GET /user/codespaces/secrets"], - listSelectedReposForOrgSecret: [ - "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories" - ], - preFlightWithRepoForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces/new" - ], - publishForAuthenticatedUser: [ - "POST /user/codespaces/{codespace_name}/publish" - ], - removeRepositoryForSecretForAuthenticatedUser: [ - "DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - removeSelectedRepoFromOrgSecret: [ - "DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - repoMachinesForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces/machines" - ], - setRepositoriesForSecretForAuthenticatedUser: [ - "PUT /user/codespaces/secrets/{secret_name}/repositories" - ], - setSelectedReposForOrgSecret: [ - "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories" - ], - startForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/start"], - stopForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/stop"], - stopInOrganization: [ - "POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop" - ], - updateForAuthenticatedUser: ["PATCH /user/codespaces/{codespace_name}"] - }, - copilot: { - addCopilotSeatsForTeams: [ - "POST /orgs/{org}/copilot/billing/selected_teams" - ], - addCopilotSeatsForUsers: [ - "POST /orgs/{org}/copilot/billing/selected_users" - ], - cancelCopilotSeatAssignmentForTeams: [ - "DELETE /orgs/{org}/copilot/billing/selected_teams" - ], - cancelCopilotSeatAssignmentForUsers: [ - "DELETE /orgs/{org}/copilot/billing/selected_users" - ], - copilotMetricsForOrganization: ["GET /orgs/{org}/copilot/metrics"], - copilotMetricsForTeam: ["GET /orgs/{org}/team/{team_slug}/copilot/metrics"], - getCopilotOrganizationDetails: ["GET /orgs/{org}/copilot/billing"], - getCopilotSeatDetailsForUser: [ - "GET /orgs/{org}/members/{username}/copilot" - ], - listCopilotSeats: ["GET /orgs/{org}/copilot/billing/seats"] - }, - credentials: { revoke: ["POST /credentials/revoke"] }, - dependabot: { - addSelectedRepoToOrgSecret: [ - "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" - ], - createOrUpdateOrgSecret: [ - "PUT /orgs/{org}/dependabot/secrets/{secret_name}" - ], - createOrUpdateRepoSecret: [ - "PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" - ], - deleteOrgSecret: ["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"], - deleteRepoSecret: [ - "DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" - ], - getAlert: ["GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"], - getOrgPublicKey: ["GET /orgs/{org}/dependabot/secrets/public-key"], - getOrgSecret: ["GET /orgs/{org}/dependabot/secrets/{secret_name}"], - getRepoPublicKey: [ - "GET /repos/{owner}/{repo}/dependabot/secrets/public-key" - ], - getRepoSecret: [ - "GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" - ], - listAlertsForEnterprise: [ - "GET /enterprises/{enterprise}/dependabot/alerts" - ], - listAlertsForOrg: ["GET /orgs/{org}/dependabot/alerts"], - listAlertsForRepo: ["GET /repos/{owner}/{repo}/dependabot/alerts"], - listOrgSecrets: ["GET /orgs/{org}/dependabot/secrets"], - listRepoSecrets: ["GET /repos/{owner}/{repo}/dependabot/secrets"], - listSelectedReposForOrgSecret: [ - "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories" - ], - removeSelectedRepoFromOrgSecret: [ - "DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" - ], - repositoryAccessForOrg: [ - "GET /organizations/{org}/dependabot/repository-access" - ], - setRepositoryAccessDefaultLevel: [ - "PUT /organizations/{org}/dependabot/repository-access/default-level" - ], - setSelectedReposForOrgSecret: [ - "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories" - ], - updateAlert: [ - "PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}" - ], - updateRepositoryAccessForOrg: [ - "PATCH /organizations/{org}/dependabot/repository-access" - ] - }, - dependencyGraph: { - createRepositorySnapshot: [ - "POST /repos/{owner}/{repo}/dependency-graph/snapshots" - ], - diffRange: [ - "GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}" - ], - exportSbom: ["GET /repos/{owner}/{repo}/dependency-graph/sbom"] - }, - emojis: { get: ["GET /emojis"] }, - gists: { - checkIsStarred: ["GET /gists/{gist_id}/star"], - create: ["POST /gists"], - createComment: ["POST /gists/{gist_id}/comments"], - delete: ["DELETE /gists/{gist_id}"], - deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"], - fork: ["POST /gists/{gist_id}/forks"], - get: ["GET /gists/{gist_id}"], - getComment: ["GET /gists/{gist_id}/comments/{comment_id}"], - getRevision: ["GET /gists/{gist_id}/{sha}"], - list: ["GET /gists"], - listComments: ["GET /gists/{gist_id}/comments"], - listCommits: ["GET /gists/{gist_id}/commits"], - listForUser: ["GET /users/{username}/gists"], - listForks: ["GET /gists/{gist_id}/forks"], - listPublic: ["GET /gists/public"], - listStarred: ["GET /gists/starred"], - star: ["PUT /gists/{gist_id}/star"], - unstar: ["DELETE /gists/{gist_id}/star"], - update: ["PATCH /gists/{gist_id}"], - updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"] - }, - git: { - createBlob: ["POST /repos/{owner}/{repo}/git/blobs"], - createCommit: ["POST /repos/{owner}/{repo}/git/commits"], - createRef: ["POST /repos/{owner}/{repo}/git/refs"], - createTag: ["POST /repos/{owner}/{repo}/git/tags"], - createTree: ["POST /repos/{owner}/{repo}/git/trees"], - deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"], - getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"], - getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"], - getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"], - getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"], - getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"], - listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"], - updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"] - }, - gitignore: { - getAllTemplates: ["GET /gitignore/templates"], - getTemplate: ["GET /gitignore/templates/{name}"] - }, - hostedCompute: { - createNetworkConfigurationForOrg: [ - "POST /orgs/{org}/settings/network-configurations" - ], - deleteNetworkConfigurationFromOrg: [ - "DELETE /orgs/{org}/settings/network-configurations/{network_configuration_id}" - ], - getNetworkConfigurationForOrg: [ - "GET /orgs/{org}/settings/network-configurations/{network_configuration_id}" - ], - getNetworkSettingsForOrg: [ - "GET /orgs/{org}/settings/network-settings/{network_settings_id}" - ], - listNetworkConfigurationsForOrg: [ - "GET /orgs/{org}/settings/network-configurations" - ], - updateNetworkConfigurationForOrg: [ - "PATCH /orgs/{org}/settings/network-configurations/{network_configuration_id}" - ] - }, - interactions: { - getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"], - getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"], - getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"], - getRestrictionsForYourPublicRepos: [ - "GET /user/interaction-limits", - {}, - { renamed: ["interactions", "getRestrictionsForAuthenticatedUser"] } - ], - removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"], - removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"], - removeRestrictionsForRepo: [ - "DELETE /repos/{owner}/{repo}/interaction-limits" - ], - removeRestrictionsForYourPublicRepos: [ - "DELETE /user/interaction-limits", - {}, - { renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"] } - ], - setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"], - setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"], - setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"], - setRestrictionsForYourPublicRepos: [ - "PUT /user/interaction-limits", - {}, - { renamed: ["interactions", "setRestrictionsForAuthenticatedUser"] } - ] - }, - issues: { - addAssignees: [ - "POST /repos/{owner}/{repo}/issues/{issue_number}/assignees" - ], - addBlockedByDependency: [ - "POST /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by" - ], - addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"], - addSubIssue: [ - "POST /repos/{owner}/{repo}/issues/{issue_number}/sub_issues" - ], - checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"], - checkUserCanBeAssignedToIssue: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}" - ], - create: ["POST /repos/{owner}/{repo}/issues"], - createComment: [ - "POST /repos/{owner}/{repo}/issues/{issue_number}/comments" - ], - createLabel: ["POST /repos/{owner}/{repo}/labels"], - createMilestone: ["POST /repos/{owner}/{repo}/milestones"], - deleteComment: [ - "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}" - ], - deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"], - deleteMilestone: [ - "DELETE /repos/{owner}/{repo}/milestones/{milestone_number}" - ], - get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"], - getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"], - getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"], - getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"], - getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"], - getParent: ["GET /repos/{owner}/{repo}/issues/{issue_number}/parent"], - list: ["GET /issues"], - listAssignees: ["GET /repos/{owner}/{repo}/assignees"], - listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"], - listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"], - listDependenciesBlockedBy: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by" - ], - listDependenciesBlocking: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocking" - ], - listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"], - listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"], - listEventsForTimeline: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline" - ], - listForAuthenticatedUser: ["GET /user/issues"], - listForOrg: ["GET /orgs/{org}/issues"], - listForRepo: ["GET /repos/{owner}/{repo}/issues"], - listLabelsForMilestone: [ - "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels" - ], - listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"], - listLabelsOnIssue: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/labels" - ], - listMilestones: ["GET /repos/{owner}/{repo}/milestones"], - listSubIssues: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/sub_issues" - ], - lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"], - removeAllLabels: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels" - ], - removeAssignees: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees" - ], - removeDependencyBlockedBy: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by/{issue_id}" - ], - removeLabel: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}" - ], - removeSubIssue: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/sub_issue" - ], - reprioritizeSubIssue: [ - "PATCH /repos/{owner}/{repo}/issues/{issue_number}/sub_issues/priority" - ], - setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"], - unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"], - update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"], - updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"], - updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"], - updateMilestone: [ - "PATCH /repos/{owner}/{repo}/milestones/{milestone_number}" - ] - }, - licenses: { - get: ["GET /licenses/{license}"], - getAllCommonlyUsed: ["GET /licenses"], - getForRepo: ["GET /repos/{owner}/{repo}/license"] - }, - markdown: { - render: ["POST /markdown"], - renderRaw: [ - "POST /markdown/raw", - { headers: { "content-type": "text/plain; charset=utf-8" } } - ] - }, - meta: { - get: ["GET /meta"], - getAllVersions: ["GET /versions"], - getOctocat: ["GET /octocat"], - getZen: ["GET /zen"], - root: ["GET /"] - }, - migrations: { - deleteArchiveForAuthenticatedUser: [ - "DELETE /user/migrations/{migration_id}/archive" - ], - deleteArchiveForOrg: [ - "DELETE /orgs/{org}/migrations/{migration_id}/archive" - ], - downloadArchiveForOrg: [ - "GET /orgs/{org}/migrations/{migration_id}/archive" - ], - getArchiveForAuthenticatedUser: [ - "GET /user/migrations/{migration_id}/archive" - ], - getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"], - getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"], - listForAuthenticatedUser: ["GET /user/migrations"], - listForOrg: ["GET /orgs/{org}/migrations"], - listReposForAuthenticatedUser: [ - "GET /user/migrations/{migration_id}/repositories" - ], - listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories"], - listReposForUser: [ - "GET /user/migrations/{migration_id}/repositories", - {}, - { renamed: ["migrations", "listReposForAuthenticatedUser"] } - ], - startForAuthenticatedUser: ["POST /user/migrations"], - startForOrg: ["POST /orgs/{org}/migrations"], - unlockRepoForAuthenticatedUser: [ - "DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock" - ], - unlockRepoForOrg: [ - "DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock" - ] - }, - oidc: { - getOidcCustomSubTemplateForOrg: [ - "GET /orgs/{org}/actions/oidc/customization/sub" - ], - updateOidcCustomSubTemplateForOrg: [ - "PUT /orgs/{org}/actions/oidc/customization/sub" - ] - }, - orgs: { - addSecurityManagerTeam: [ - "PUT /orgs/{org}/security-managers/teams/{team_slug}", - {}, - { - deprecated: "octokit.rest.orgs.addSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#add-a-security-manager-team" - } - ], - assignTeamToOrgRole: [ - "PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" - ], - assignUserToOrgRole: [ - "PUT /orgs/{org}/organization-roles/users/{username}/{role_id}" - ], - blockUser: ["PUT /orgs/{org}/blocks/{username}"], - cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"], - checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"], - checkMembershipForUser: ["GET /orgs/{org}/members/{username}"], - checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"], - convertMemberToOutsideCollaborator: [ - "PUT /orgs/{org}/outside_collaborators/{username}" - ], - createArtifactStorageRecord: [ - "POST /orgs/{org}/artifacts/metadata/storage-record" - ], - createInvitation: ["POST /orgs/{org}/invitations"], - createIssueType: ["POST /orgs/{org}/issue-types"], - createOrUpdateCustomProperties: ["PATCH /orgs/{org}/properties/schema"], - createOrUpdateCustomPropertiesValuesForRepos: [ - "PATCH /orgs/{org}/properties/values" - ], - createOrUpdateCustomProperty: [ - "PUT /orgs/{org}/properties/schema/{custom_property_name}" - ], - createWebhook: ["POST /orgs/{org}/hooks"], - delete: ["DELETE /orgs/{org}"], - deleteAttestationsBulk: ["POST /orgs/{org}/attestations/delete-request"], - deleteAttestationsById: [ - "DELETE /orgs/{org}/attestations/{attestation_id}" - ], - deleteAttestationsBySubjectDigest: [ - "DELETE /orgs/{org}/attestations/digest/{subject_digest}" - ], - deleteIssueType: ["DELETE /orgs/{org}/issue-types/{issue_type_id}"], - deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], - get: ["GET /orgs/{org}"], - getAllCustomProperties: ["GET /orgs/{org}/properties/schema"], - getCustomProperty: [ - "GET /orgs/{org}/properties/schema/{custom_property_name}" - ], - getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], - getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], - getOrgRole: ["GET /orgs/{org}/organization-roles/{role_id}"], - getOrgRulesetHistory: ["GET /orgs/{org}/rulesets/{ruleset_id}/history"], - getOrgRulesetVersion: [ - "GET /orgs/{org}/rulesets/{ruleset_id}/history/{version_id}" - ], - getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], - getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"], - getWebhookDelivery: [ - "GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}" - ], - list: ["GET /organizations"], - listAppInstallations: ["GET /orgs/{org}/installations"], - listArtifactStorageRecords: [ - "GET /orgs/{org}/artifacts/{subject_digest}/metadata/storage-records" - ], - listAttestations: ["GET /orgs/{org}/attestations/{subject_digest}"], - listAttestationsBulk: [ - "POST /orgs/{org}/attestations/bulk-list{?per_page,before,after}" - ], - listBlockedUsers: ["GET /orgs/{org}/blocks"], - listCustomPropertiesValuesForRepos: ["GET /orgs/{org}/properties/values"], - listFailedInvitations: ["GET /orgs/{org}/failed_invitations"], - listForAuthenticatedUser: ["GET /user/orgs"], - listForUser: ["GET /users/{username}/orgs"], - listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"], - listIssueTypes: ["GET /orgs/{org}/issue-types"], - listMembers: ["GET /orgs/{org}/members"], - listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"], - listOrgRoleTeams: ["GET /orgs/{org}/organization-roles/{role_id}/teams"], - listOrgRoleUsers: ["GET /orgs/{org}/organization-roles/{role_id}/users"], - listOrgRoles: ["GET /orgs/{org}/organization-roles"], - listOrganizationFineGrainedPermissions: [ - "GET /orgs/{org}/organization-fine-grained-permissions" - ], - listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"], - listPatGrantRepositories: [ - "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories" - ], - listPatGrantRequestRepositories: [ - "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories" - ], - listPatGrantRequests: ["GET /orgs/{org}/personal-access-token-requests"], - listPatGrants: ["GET /orgs/{org}/personal-access-tokens"], - listPendingInvitations: ["GET /orgs/{org}/invitations"], - listPublicMembers: ["GET /orgs/{org}/public_members"], - listSecurityManagerTeams: [ - "GET /orgs/{org}/security-managers", - {}, - { - deprecated: "octokit.rest.orgs.listSecurityManagerTeams() is deprecated, see https://docs.github.com/rest/orgs/security-managers#list-security-manager-teams" - } - ], - listWebhookDeliveries: ["GET /orgs/{org}/hooks/{hook_id}/deliveries"], - listWebhooks: ["GET /orgs/{org}/hooks"], - pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"], - redeliverWebhookDelivery: [ - "POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" - ], - removeCustomProperty: [ - "DELETE /orgs/{org}/properties/schema/{custom_property_name}" - ], - removeMember: ["DELETE /orgs/{org}/members/{username}"], - removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], - removeOutsideCollaborator: [ - "DELETE /orgs/{org}/outside_collaborators/{username}" - ], - removePublicMembershipForAuthenticatedUser: [ - "DELETE /orgs/{org}/public_members/{username}" - ], - removeSecurityManagerTeam: [ - "DELETE /orgs/{org}/security-managers/teams/{team_slug}", - {}, - { - deprecated: "octokit.rest.orgs.removeSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#remove-a-security-manager-team" - } - ], - reviewPatGrantRequest: [ - "POST /orgs/{org}/personal-access-token-requests/{pat_request_id}" - ], - reviewPatGrantRequestsInBulk: [ - "POST /orgs/{org}/personal-access-token-requests" - ], - revokeAllOrgRolesTeam: [ - "DELETE /orgs/{org}/organization-roles/teams/{team_slug}" - ], - revokeAllOrgRolesUser: [ - "DELETE /orgs/{org}/organization-roles/users/{username}" - ], - revokeOrgRoleTeam: [ - "DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" - ], - revokeOrgRoleUser: [ - "DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}" - ], - setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"], - setPublicMembershipForAuthenticatedUser: [ - "PUT /orgs/{org}/public_members/{username}" - ], - unblockUser: ["DELETE /orgs/{org}/blocks/{username}"], - update: ["PATCH /orgs/{org}"], - updateIssueType: ["PUT /orgs/{org}/issue-types/{issue_type_id}"], - updateMembershipForAuthenticatedUser: [ - "PATCH /user/memberships/orgs/{org}" - ], - updatePatAccess: ["POST /orgs/{org}/personal-access-tokens/{pat_id}"], - updatePatAccesses: ["POST /orgs/{org}/personal-access-tokens"], - updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"], - updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"] - }, - packages: { - deletePackageForAuthenticatedUser: [ - "DELETE /user/packages/{package_type}/{package_name}" - ], - deletePackageForOrg: [ - "DELETE /orgs/{org}/packages/{package_type}/{package_name}" - ], - deletePackageForUser: [ - "DELETE /users/{username}/packages/{package_type}/{package_name}" - ], - deletePackageVersionForAuthenticatedUser: [ - "DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - deletePackageVersionForOrg: [ - "DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - deletePackageVersionForUser: [ - "DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - getAllPackageVersionsForAPackageOwnedByAnOrg: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", - {}, - { renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"] } - ], - getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}/versions", - {}, - { - renamed: [ - "packages", - "getAllPackageVersionsForPackageOwnedByAuthenticatedUser" - ] - } - ], - getAllPackageVersionsForPackageOwnedByAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}/versions" - ], - getAllPackageVersionsForPackageOwnedByOrg: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}/versions" - ], - getAllPackageVersionsForPackageOwnedByUser: [ - "GET /users/{username}/packages/{package_type}/{package_name}/versions" - ], - getPackageForAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}" - ], - getPackageForOrganization: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}" - ], - getPackageForUser: [ - "GET /users/{username}/packages/{package_type}/{package_name}" - ], - getPackageVersionForAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - getPackageVersionForOrganization: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - getPackageVersionForUser: [ - "GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - listDockerMigrationConflictingPackagesForAuthenticatedUser: [ - "GET /user/docker/conflicts" - ], - listDockerMigrationConflictingPackagesForOrganization: [ - "GET /orgs/{org}/docker/conflicts" - ], - listDockerMigrationConflictingPackagesForUser: [ - "GET /users/{username}/docker/conflicts" - ], - listPackagesForAuthenticatedUser: ["GET /user/packages"], - listPackagesForOrganization: ["GET /orgs/{org}/packages"], - listPackagesForUser: ["GET /users/{username}/packages"], - restorePackageForAuthenticatedUser: [ - "POST /user/packages/{package_type}/{package_name}/restore{?token}" - ], - restorePackageForOrg: [ - "POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}" - ], - restorePackageForUser: [ - "POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}" - ], - restorePackageVersionForAuthenticatedUser: [ - "POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" - ], - restorePackageVersionForOrg: [ - "POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" - ], - restorePackageVersionForUser: [ - "POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" - ] - }, - privateRegistries: { - createOrgPrivateRegistry: ["POST /orgs/{org}/private-registries"], - deleteOrgPrivateRegistry: [ - "DELETE /orgs/{org}/private-registries/{secret_name}" - ], - getOrgPrivateRegistry: ["GET /orgs/{org}/private-registries/{secret_name}"], - getOrgPublicKey: ["GET /orgs/{org}/private-registries/public-key"], - listOrgPrivateRegistries: ["GET /orgs/{org}/private-registries"], - updateOrgPrivateRegistry: [ - "PATCH /orgs/{org}/private-registries/{secret_name}" - ] - }, - projects: { - addItemForOrg: ["POST /orgs/{org}/projectsV2/{project_number}/items"], - addItemForUser: ["POST /users/{user_id}/projectsV2/{project_number}/items"], - deleteItemForOrg: [ - "DELETE /orgs/{org}/projectsV2/{project_number}/items/{item_id}" - ], - deleteItemForUser: [ - "DELETE /users/{user_id}/projectsV2/{project_number}/items/{item_id}" - ], - getFieldForOrg: [ - "GET /orgs/{org}/projectsV2/{project_number}/fields/{field_id}" - ], - getFieldForUser: [ - "GET /users/{user_id}/projectsV2/{project_number}/fields/{field_id}" - ], - getForOrg: ["GET /orgs/{org}/projectsV2/{project_number}"], - getForUser: ["GET /users/{user_id}/projectsV2/{project_number}"], - getOrgItem: ["GET /orgs/{org}/projectsV2/{project_number}/items/{item_id}"], - getUserItem: [ - "GET /users/{user_id}/projectsV2/{project_number}/items/{item_id}" - ], - listFieldsForOrg: ["GET /orgs/{org}/projectsV2/{project_number}/fields"], - listFieldsForUser: [ - "GET /users/{user_id}/projectsV2/{project_number}/fields" - ], - listForOrg: ["GET /orgs/{org}/projectsV2"], - listForUser: ["GET /users/{username}/projectsV2"], - listItemsForOrg: ["GET /orgs/{org}/projectsV2/{project_number}/items"], - listItemsForUser: [ - "GET /users/{user_id}/projectsV2/{project_number}/items" - ], - updateItemForOrg: [ - "PATCH /orgs/{org}/projectsV2/{project_number}/items/{item_id}" - ], - updateItemForUser: [ - "PATCH /users/{user_id}/projectsV2/{project_number}/items/{item_id}" - ] - }, - pulls: { - checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"], - create: ["POST /repos/{owner}/{repo}/pulls"], - createReplyForReviewComment: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies" - ], - createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], - createReviewComment: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments" - ], - deletePendingReview: [ - "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" - ], - deleteReviewComment: [ - "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}" - ], - dismissReview: [ - "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals" - ], - get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"], - getReview: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" - ], - getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"], - list: ["GET /repos/{owner}/{repo}/pulls"], - listCommentsForReview: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments" - ], - listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"], - listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"], - listRequestedReviewers: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" - ], - listReviewComments: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments" - ], - listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"], - listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], - merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"], - removeRequestedReviewers: [ - "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" - ], - requestReviewers: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" - ], - submitReview: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events" - ], - update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"], - updateBranch: [ - "PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch" - ], - updateReview: [ - "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" - ], - updateReviewComment: [ - "PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}" - ] - }, - rateLimit: { get: ["GET /rate_limit"] }, - reactions: { - createForCommitComment: [ - "POST /repos/{owner}/{repo}/comments/{comment_id}/reactions" - ], - createForIssue: [ - "POST /repos/{owner}/{repo}/issues/{issue_number}/reactions" - ], - createForIssueComment: [ - "POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" - ], - createForPullRequestReviewComment: [ - "POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" - ], - createForRelease: [ - "POST /repos/{owner}/{repo}/releases/{release_id}/reactions" - ], - createForTeamDiscussionCommentInOrg: [ - "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" - ], - createForTeamDiscussionInOrg: [ - "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" - ], - deleteForCommitComment: [ - "DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}" - ], - deleteForIssue: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}" - ], - deleteForIssueComment: [ - "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}" - ], - deleteForPullRequestComment: [ - "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}" - ], - deleteForRelease: [ - "DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}" - ], - deleteForTeamDiscussion: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}" - ], - deleteForTeamDiscussionComment: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}" - ], - listForCommitComment: [ - "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions" - ], - listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"], - listForIssueComment: [ - "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" - ], - listForPullRequestReviewComment: [ - "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" - ], - listForRelease: [ - "GET /repos/{owner}/{repo}/releases/{release_id}/reactions" - ], - listForTeamDiscussionCommentInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" - ], - listForTeamDiscussionInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" - ] - }, - repos: { - acceptInvitation: [ - "PATCH /user/repository_invitations/{invitation_id}", - {}, - { renamed: ["repos", "acceptInvitationForAuthenticatedUser"] } - ], - acceptInvitationForAuthenticatedUser: [ - "PATCH /user/repository_invitations/{invitation_id}" - ], - addAppAccessRestrictions: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", - {}, - { mapToData: "apps" } - ], - addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"], - addStatusCheckContexts: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", - {}, - { mapToData: "contexts" } - ], - addTeamAccessRestrictions: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", - {}, - { mapToData: "teams" } - ], - addUserAccessRestrictions: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", - {}, - { mapToData: "users" } - ], - cancelPagesDeployment: [ - "POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel" - ], - checkAutomatedSecurityFixes: [ - "GET /repos/{owner}/{repo}/automated-security-fixes" - ], - checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"], - checkPrivateVulnerabilityReporting: [ - "GET /repos/{owner}/{repo}/private-vulnerability-reporting" - ], - checkVulnerabilityAlerts: [ - "GET /repos/{owner}/{repo}/vulnerability-alerts" - ], - codeownersErrors: ["GET /repos/{owner}/{repo}/codeowners/errors"], - compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"], - compareCommitsWithBasehead: [ - "GET /repos/{owner}/{repo}/compare/{basehead}" - ], - createAttestation: ["POST /repos/{owner}/{repo}/attestations"], - createAutolink: ["POST /repos/{owner}/{repo}/autolinks"], - createCommitComment: [ - "POST /repos/{owner}/{repo}/commits/{commit_sha}/comments" - ], - createCommitSignatureProtection: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" - ], - createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"], - createDeployKey: ["POST /repos/{owner}/{repo}/keys"], - createDeployment: ["POST /repos/{owner}/{repo}/deployments"], - createDeploymentBranchPolicy: [ - "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" - ], - createDeploymentProtectionRule: [ - "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" - ], - createDeploymentStatus: [ - "POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" - ], - createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"], - createForAuthenticatedUser: ["POST /user/repos"], - createFork: ["POST /repos/{owner}/{repo}/forks"], - createInOrg: ["POST /orgs/{org}/repos"], - createOrUpdateCustomPropertiesValues: [ - "PATCH /repos/{owner}/{repo}/properties/values" - ], - createOrUpdateEnvironment: [ - "PUT /repos/{owner}/{repo}/environments/{environment_name}" - ], - createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"], - createOrgRuleset: ["POST /orgs/{org}/rulesets"], - createPagesDeployment: ["POST /repos/{owner}/{repo}/pages/deployments"], - createPagesSite: ["POST /repos/{owner}/{repo}/pages"], - createRelease: ["POST /repos/{owner}/{repo}/releases"], - createRepoRuleset: ["POST /repos/{owner}/{repo}/rulesets"], - createUsingTemplate: [ - "POST /repos/{template_owner}/{template_repo}/generate" - ], - createWebhook: ["POST /repos/{owner}/{repo}/hooks"], - declineInvitation: [ - "DELETE /user/repository_invitations/{invitation_id}", - {}, - { renamed: ["repos", "declineInvitationForAuthenticatedUser"] } - ], - declineInvitationForAuthenticatedUser: [ - "DELETE /user/repository_invitations/{invitation_id}" - ], - delete: ["DELETE /repos/{owner}/{repo}"], - deleteAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" - ], - deleteAdminBranchProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" - ], - deleteAnEnvironment: [ - "DELETE /repos/{owner}/{repo}/environments/{environment_name}" - ], - deleteAutolink: ["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"], - deleteBranchProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection" - ], - deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"], - deleteCommitSignatureProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" - ], - deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"], - deleteDeployment: [ - "DELETE /repos/{owner}/{repo}/deployments/{deployment_id}" - ], - deleteDeploymentBranchPolicy: [ - "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" - ], - deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"], - deleteInvitation: [ - "DELETE /repos/{owner}/{repo}/invitations/{invitation_id}" - ], - deleteOrgRuleset: ["DELETE /orgs/{org}/rulesets/{ruleset_id}"], - deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages"], - deletePullRequestReviewProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" - ], - deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"], - deleteReleaseAsset: [ - "DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}" - ], - deleteRepoRuleset: ["DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}"], - deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"], - disableAutomatedSecurityFixes: [ - "DELETE /repos/{owner}/{repo}/automated-security-fixes" - ], - disableDeploymentProtectionRule: [ - "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" - ], - disablePrivateVulnerabilityReporting: [ - "DELETE /repos/{owner}/{repo}/private-vulnerability-reporting" - ], - disableVulnerabilityAlerts: [ - "DELETE /repos/{owner}/{repo}/vulnerability-alerts" - ], - downloadArchive: [ - "GET /repos/{owner}/{repo}/zipball/{ref}", - {}, - { renamed: ["repos", "downloadZipballArchive"] } - ], - downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"], - downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"], - enableAutomatedSecurityFixes: [ - "PUT /repos/{owner}/{repo}/automated-security-fixes" - ], - enablePrivateVulnerabilityReporting: [ - "PUT /repos/{owner}/{repo}/private-vulnerability-reporting" - ], - enableVulnerabilityAlerts: [ - "PUT /repos/{owner}/{repo}/vulnerability-alerts" - ], - generateReleaseNotes: [ - "POST /repos/{owner}/{repo}/releases/generate-notes" - ], - get: ["GET /repos/{owner}/{repo}"], - getAccessRestrictions: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" - ], - getAdminBranchProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" - ], - getAllDeploymentProtectionRules: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" - ], - getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"], - getAllStatusCheckContexts: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts" - ], - getAllTopics: ["GET /repos/{owner}/{repo}/topics"], - getAppsWithAccessToProtectedBranch: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps" - ], - getAutolink: ["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"], - getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"], - getBranchProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection" - ], - getBranchRules: ["GET /repos/{owner}/{repo}/rules/branches/{branch}"], - getClones: ["GET /repos/{owner}/{repo}/traffic/clones"], - getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"], - getCollaboratorPermissionLevel: [ - "GET /repos/{owner}/{repo}/collaborators/{username}/permission" - ], - getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"], - getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"], - getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"], - getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"], - getCommitSignatureProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" - ], - getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"], - getContent: ["GET /repos/{owner}/{repo}/contents/{path}"], - getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"], - getCustomDeploymentProtectionRule: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" - ], - getCustomPropertiesValues: ["GET /repos/{owner}/{repo}/properties/values"], - getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"], - getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"], - getDeploymentBranchPolicy: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" - ], - getDeploymentStatus: [ - "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}" - ], - getEnvironment: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}" - ], - getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], - getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], - getOrgRuleSuite: ["GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}"], - getOrgRuleSuites: ["GET /orgs/{org}/rulesets/rule-suites"], - getOrgRuleset: ["GET /orgs/{org}/rulesets/{ruleset_id}"], - getOrgRulesets: ["GET /orgs/{org}/rulesets"], - getPages: ["GET /repos/{owner}/{repo}/pages"], - getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"], - getPagesDeployment: [ - "GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}" - ], - getPagesHealthCheck: ["GET /repos/{owner}/{repo}/pages/health"], - getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"], - getPullRequestReviewProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" - ], - getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"], - getReadme: ["GET /repos/{owner}/{repo}/readme"], - getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"], - getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"], - getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"], - getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"], - getRepoRuleSuite: [ - "GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}" - ], - getRepoRuleSuites: ["GET /repos/{owner}/{repo}/rulesets/rule-suites"], - getRepoRuleset: ["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}"], - getRepoRulesetHistory: [ - "GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history" - ], - getRepoRulesetVersion: [ - "GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history/{version_id}" - ], - getRepoRulesets: ["GET /repos/{owner}/{repo}/rulesets"], - getStatusChecksProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" - ], - getTeamsWithAccessToProtectedBranch: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams" - ], - getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"], - getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"], - getUsersWithAccessToProtectedBranch: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users" - ], - getViews: ["GET /repos/{owner}/{repo}/traffic/views"], - getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"], - getWebhookConfigForRepo: [ - "GET /repos/{owner}/{repo}/hooks/{hook_id}/config" - ], - getWebhookDelivery: [ - "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}" - ], - listActivities: ["GET /repos/{owner}/{repo}/activity"], - listAttestations: [ - "GET /repos/{owner}/{repo}/attestations/{subject_digest}" - ], - listAutolinks: ["GET /repos/{owner}/{repo}/autolinks"], - listBranches: ["GET /repos/{owner}/{repo}/branches"], - listBranchesForHeadCommit: [ - "GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head" - ], - listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"], - listCommentsForCommit: [ - "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments" - ], - listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"], - listCommitStatusesForRef: [ - "GET /repos/{owner}/{repo}/commits/{ref}/statuses" - ], - listCommits: ["GET /repos/{owner}/{repo}/commits"], - listContributors: ["GET /repos/{owner}/{repo}/contributors"], - listCustomDeploymentRuleIntegrations: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps" - ], - listDeployKeys: ["GET /repos/{owner}/{repo}/keys"], - listDeploymentBranchPolicies: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" - ], - listDeploymentStatuses: [ - "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" - ], - listDeployments: ["GET /repos/{owner}/{repo}/deployments"], - listForAuthenticatedUser: ["GET /user/repos"], - listForOrg: ["GET /orgs/{org}/repos"], - listForUser: ["GET /users/{username}/repos"], - listForks: ["GET /repos/{owner}/{repo}/forks"], - listInvitations: ["GET /repos/{owner}/{repo}/invitations"], - listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"], - listLanguages: ["GET /repos/{owner}/{repo}/languages"], - listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"], - listPublic: ["GET /repositories"], - listPullRequestsAssociatedWithCommit: [ - "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls" - ], - listReleaseAssets: [ - "GET /repos/{owner}/{repo}/releases/{release_id}/assets" - ], - listReleases: ["GET /repos/{owner}/{repo}/releases"], - listTags: ["GET /repos/{owner}/{repo}/tags"], - listTeams: ["GET /repos/{owner}/{repo}/teams"], - listWebhookDeliveries: [ - "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries" - ], - listWebhooks: ["GET /repos/{owner}/{repo}/hooks"], - merge: ["POST /repos/{owner}/{repo}/merges"], - mergeUpstream: ["POST /repos/{owner}/{repo}/merge-upstream"], - pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"], - redeliverWebhookDelivery: [ - "POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" - ], - removeAppAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", - {}, - { mapToData: "apps" } - ], - removeCollaborator: [ - "DELETE /repos/{owner}/{repo}/collaborators/{username}" - ], - removeStatusCheckContexts: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", - {}, - { mapToData: "contexts" } - ], - removeStatusCheckProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" - ], - removeTeamAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", - {}, - { mapToData: "teams" } - ], - removeUserAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", - {}, - { mapToData: "users" } - ], - renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"], - replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics"], - requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"], - setAdminBranchProtection: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" - ], - setAppAccessRestrictions: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", - {}, - { mapToData: "apps" } - ], - setStatusCheckContexts: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", - {}, - { mapToData: "contexts" } - ], - setTeamAccessRestrictions: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", - {}, - { mapToData: "teams" } - ], - setUserAccessRestrictions: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", - {}, - { mapToData: "users" } - ], - testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"], - transfer: ["POST /repos/{owner}/{repo}/transfer"], - update: ["PATCH /repos/{owner}/{repo}"], - updateBranchProtection: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection" - ], - updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"], - updateDeploymentBranchPolicy: [ - "PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" - ], - updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"], - updateInvitation: [ - "PATCH /repos/{owner}/{repo}/invitations/{invitation_id}" - ], - updateOrgRuleset: ["PUT /orgs/{org}/rulesets/{ruleset_id}"], - updatePullRequestReviewProtection: [ - "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" - ], - updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"], - updateReleaseAsset: [ - "PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}" - ], - updateRepoRuleset: ["PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}"], - updateStatusCheckPotection: [ - "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", - {}, - { renamed: ["repos", "updateStatusCheckProtection"] } - ], - updateStatusCheckProtection: [ - "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" - ], - updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"], - updateWebhookConfigForRepo: [ - "PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config" - ], - uploadReleaseAsset: [ - "POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", - { baseUrl: "https://uploads.github.com" } - ] - }, - search: { - code: ["GET /search/code"], - commits: ["GET /search/commits"], - issuesAndPullRequests: [ - "GET /search/issues", - {}, - { - deprecated: "octokit.rest.search.issuesAndPullRequests() is deprecated, see https://docs.github.com/rest/search/search#search-issues-and-pull-requests" - } - ], - labels: ["GET /search/labels"], - repos: ["GET /search/repositories"], - topics: ["GET /search/topics"], - users: ["GET /search/users"] - }, - secretScanning: { - createPushProtectionBypass: [ - "POST /repos/{owner}/{repo}/secret-scanning/push-protection-bypasses" - ], - getAlert: [ - "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" - ], - getScanHistory: ["GET /repos/{owner}/{repo}/secret-scanning/scan-history"], - listAlertsForEnterprise: [ - "GET /enterprises/{enterprise}/secret-scanning/alerts" - ], - listAlertsForOrg: ["GET /orgs/{org}/secret-scanning/alerts"], - listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"], - listLocationsForAlert: [ - "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations" - ], - listOrgPatternConfigs: [ - "GET /orgs/{org}/secret-scanning/pattern-configurations" - ], - updateAlert: [ - "PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" - ], - updateOrgPatternConfigs: [ - "PATCH /orgs/{org}/secret-scanning/pattern-configurations" - ] - }, - securityAdvisories: { - createFork: [ - "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks" - ], - createPrivateVulnerabilityReport: [ - "POST /repos/{owner}/{repo}/security-advisories/reports" - ], - createRepositoryAdvisory: [ - "POST /repos/{owner}/{repo}/security-advisories" - ], - createRepositoryAdvisoryCveRequest: [ - "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve" - ], - getGlobalAdvisory: ["GET /advisories/{ghsa_id}"], - getRepositoryAdvisory: [ - "GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}" - ], - listGlobalAdvisories: ["GET /advisories"], - listOrgRepositoryAdvisories: ["GET /orgs/{org}/security-advisories"], - listRepositoryAdvisories: ["GET /repos/{owner}/{repo}/security-advisories"], - updateRepositoryAdvisory: [ - "PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}" - ] - }, - teams: { - addOrUpdateMembershipForUserInOrg: [ - "PUT /orgs/{org}/teams/{team_slug}/memberships/{username}" - ], - addOrUpdateRepoPermissionsInOrg: [ - "PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" - ], - checkPermissionsForRepoInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" - ], - create: ["POST /orgs/{org}/teams"], - createDiscussionCommentInOrg: [ - "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" - ], - createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"], - deleteDiscussionCommentInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" - ], - deleteDiscussionInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" - ], - deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"], - getByName: ["GET /orgs/{org}/teams/{team_slug}"], - getDiscussionCommentInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" - ], - getDiscussionInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" - ], - getMembershipForUserInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/memberships/{username}" - ], - list: ["GET /orgs/{org}/teams"], - listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"], - listDiscussionCommentsInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" - ], - listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"], - listForAuthenticatedUser: ["GET /user/teams"], - listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"], - listPendingInvitationsInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/invitations" - ], - listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"], - removeMembershipForUserInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}" - ], - removeRepoInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" - ], - updateDiscussionCommentInOrg: [ - "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" - ], - updateDiscussionInOrg: [ - "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" - ], - updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"] - }, - users: { - addEmailForAuthenticated: [ - "POST /user/emails", - {}, - { renamed: ["users", "addEmailForAuthenticatedUser"] } - ], - addEmailForAuthenticatedUser: ["POST /user/emails"], - addSocialAccountForAuthenticatedUser: ["POST /user/social_accounts"], - block: ["PUT /user/blocks/{username}"], - checkBlocked: ["GET /user/blocks/{username}"], - checkFollowingForUser: ["GET /users/{username}/following/{target_user}"], - checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"], - createGpgKeyForAuthenticated: [ - "POST /user/gpg_keys", - {}, - { renamed: ["users", "createGpgKeyForAuthenticatedUser"] } - ], - createGpgKeyForAuthenticatedUser: ["POST /user/gpg_keys"], - createPublicSshKeyForAuthenticated: [ - "POST /user/keys", - {}, - { renamed: ["users", "createPublicSshKeyForAuthenticatedUser"] } - ], - createPublicSshKeyForAuthenticatedUser: ["POST /user/keys"], - createSshSigningKeyForAuthenticatedUser: ["POST /user/ssh_signing_keys"], - deleteAttestationsBulk: [ - "POST /users/{username}/attestations/delete-request" - ], - deleteAttestationsById: [ - "DELETE /users/{username}/attestations/{attestation_id}" - ], - deleteAttestationsBySubjectDigest: [ - "DELETE /users/{username}/attestations/digest/{subject_digest}" - ], - deleteEmailForAuthenticated: [ - "DELETE /user/emails", - {}, - { renamed: ["users", "deleteEmailForAuthenticatedUser"] } - ], - deleteEmailForAuthenticatedUser: ["DELETE /user/emails"], - deleteGpgKeyForAuthenticated: [ - "DELETE /user/gpg_keys/{gpg_key_id}", - {}, - { renamed: ["users", "deleteGpgKeyForAuthenticatedUser"] } - ], - deleteGpgKeyForAuthenticatedUser: ["DELETE /user/gpg_keys/{gpg_key_id}"], - deletePublicSshKeyForAuthenticated: [ - "DELETE /user/keys/{key_id}", - {}, - { renamed: ["users", "deletePublicSshKeyForAuthenticatedUser"] } - ], - deletePublicSshKeyForAuthenticatedUser: ["DELETE /user/keys/{key_id}"], - deleteSocialAccountForAuthenticatedUser: ["DELETE /user/social_accounts"], - deleteSshSigningKeyForAuthenticatedUser: [ - "DELETE /user/ssh_signing_keys/{ssh_signing_key_id}" - ], - follow: ["PUT /user/following/{username}"], - getAuthenticated: ["GET /user"], - getById: ["GET /user/{account_id}"], - getByUsername: ["GET /users/{username}"], - getContextForUser: ["GET /users/{username}/hovercard"], - getGpgKeyForAuthenticated: [ - "GET /user/gpg_keys/{gpg_key_id}", - {}, - { renamed: ["users", "getGpgKeyForAuthenticatedUser"] } - ], - getGpgKeyForAuthenticatedUser: ["GET /user/gpg_keys/{gpg_key_id}"], - getPublicSshKeyForAuthenticated: [ - "GET /user/keys/{key_id}", - {}, - { renamed: ["users", "getPublicSshKeyForAuthenticatedUser"] } - ], - getPublicSshKeyForAuthenticatedUser: ["GET /user/keys/{key_id}"], - getSshSigningKeyForAuthenticatedUser: [ - "GET /user/ssh_signing_keys/{ssh_signing_key_id}" - ], - list: ["GET /users"], - listAttestations: ["GET /users/{username}/attestations/{subject_digest}"], - listAttestationsBulk: [ - "POST /users/{username}/attestations/bulk-list{?per_page,before,after}" - ], - listBlockedByAuthenticated: [ - "GET /user/blocks", - {}, - { renamed: ["users", "listBlockedByAuthenticatedUser"] } - ], - listBlockedByAuthenticatedUser: ["GET /user/blocks"], - listEmailsForAuthenticated: [ - "GET /user/emails", - {}, - { renamed: ["users", "listEmailsForAuthenticatedUser"] } - ], - listEmailsForAuthenticatedUser: ["GET /user/emails"], - listFollowedByAuthenticated: [ - "GET /user/following", - {}, - { renamed: ["users", "listFollowedByAuthenticatedUser"] } - ], - listFollowedByAuthenticatedUser: ["GET /user/following"], - listFollowersForAuthenticatedUser: ["GET /user/followers"], - listFollowersForUser: ["GET /users/{username}/followers"], - listFollowingForUser: ["GET /users/{username}/following"], - listGpgKeysForAuthenticated: [ - "GET /user/gpg_keys", - {}, - { renamed: ["users", "listGpgKeysForAuthenticatedUser"] } - ], - listGpgKeysForAuthenticatedUser: ["GET /user/gpg_keys"], - listGpgKeysForUser: ["GET /users/{username}/gpg_keys"], - listPublicEmailsForAuthenticated: [ - "GET /user/public_emails", - {}, - { renamed: ["users", "listPublicEmailsForAuthenticatedUser"] } - ], - listPublicEmailsForAuthenticatedUser: ["GET /user/public_emails"], - listPublicKeysForUser: ["GET /users/{username}/keys"], - listPublicSshKeysForAuthenticated: [ - "GET /user/keys", - {}, - { renamed: ["users", "listPublicSshKeysForAuthenticatedUser"] } - ], - listPublicSshKeysForAuthenticatedUser: ["GET /user/keys"], - listSocialAccountsForAuthenticatedUser: ["GET /user/social_accounts"], - listSocialAccountsForUser: ["GET /users/{username}/social_accounts"], - listSshSigningKeysForAuthenticatedUser: ["GET /user/ssh_signing_keys"], - listSshSigningKeysForUser: ["GET /users/{username}/ssh_signing_keys"], - setPrimaryEmailVisibilityForAuthenticated: [ - "PATCH /user/email/visibility", - {}, - { renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"] } - ], - setPrimaryEmailVisibilityForAuthenticatedUser: [ - "PATCH /user/email/visibility" - ], - unblock: ["DELETE /user/blocks/{username}"], - unfollow: ["DELETE /user/following/{username}"], - updateAuthenticated: ["PATCH /user"] - } -}; -var endpoints_default = Endpoints; - -// node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@16.1.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/endpoints-to-methods.js -var endpointMethodsMap = /* @__PURE__ */ new Map(); -for (const [scope2, endpoints] of Object.entries(endpoints_default)) { - for (const [methodName, endpoint2] of Object.entries(endpoints)) { - const [route, defaults, decorations] = endpoint2; - const [method, url4] = route.split(/ /); - const endpointDefaults = Object.assign( - { - method, - url: url4 - }, - defaults - ); - if (!endpointMethodsMap.has(scope2)) { - endpointMethodsMap.set(scope2, /* @__PURE__ */ new Map()); - } - endpointMethodsMap.get(scope2).set(methodName, { - scope: scope2, - methodName, - endpointDefaults, - decorations - }); - } -} -var handler = { - has({ scope: scope2 }, methodName) { - return endpointMethodsMap.get(scope2).has(methodName); - }, - getOwnPropertyDescriptor(target, methodName) { - return { - value: this.get(target, methodName), - // ensures method is in the cache - configurable: true, - writable: true, - enumerable: true - }; - }, - defineProperty(target, methodName, descriptor) { - Object.defineProperty(target.cache, methodName, descriptor); - return true; - }, - deleteProperty(target, methodName) { - delete target.cache[methodName]; - return true; - }, - ownKeys({ scope: scope2 }) { - return [...endpointMethodsMap.get(scope2).keys()]; - }, - set(target, methodName, value2) { - return target.cache[methodName] = value2; - }, - get({ octokit, scope: scope2, cache }, methodName) { - if (cache[methodName]) { - return cache[methodName]; - } - const method = endpointMethodsMap.get(scope2).get(methodName); - if (!method) { - return void 0; - } - const { endpointDefaults, decorations } = method; - if (decorations) { - cache[methodName] = decorate( - octokit, - scope2, - methodName, - endpointDefaults, - decorations - ); - } else { - cache[methodName] = octokit.request.defaults(endpointDefaults); - } - return cache[methodName]; - } -}; -function endpointsToMethods(octokit) { - const newMethods = {}; - for (const scope2 of endpointMethodsMap.keys()) { - newMethods[scope2] = new Proxy({ octokit, scope: scope2, cache: {} }, handler); - } - return newMethods; -} -function decorate(octokit, scope2, methodName, defaults, decorations) { - const requestWithDefaults = octokit.request.defaults(defaults); - function withDecorations(...args2) { - let options = requestWithDefaults.endpoint.merge(...args2); - if (decorations.mapToData) { - options = Object.assign({}, options, { - data: options[decorations.mapToData], - [decorations.mapToData]: void 0 - }); - return requestWithDefaults(options); - } - if (decorations.renamed) { - const [newScope, newMethodName] = decorations.renamed; - octokit.log.warn( - `octokit.${scope2}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()` - ); - } - if (decorations.deprecated) { - octokit.log.warn(decorations.deprecated); - } - if (decorations.renamedParameters) { - const options2 = requestWithDefaults.endpoint.merge(...args2); - for (const [name, alias] of Object.entries( - decorations.renamedParameters - )) { - if (name in options2) { - octokit.log.warn( - `"${name}" parameter is deprecated for "octokit.${scope2}.${methodName}()". Use "${alias}" instead` - ); - if (!(alias in options2)) { - options2[alias] = options2[name]; - } - delete options2[name]; - } - } - return requestWithDefaults(options2); - } - return requestWithDefaults(...args2); - } - return Object.assign(withDecorations, requestWithDefaults); -} - -// node_modules/.pnpm/@octokit+plugin-rest-endpoint-methods@16.1.0_@octokit+core@7.0.5/node_modules/@octokit/plugin-rest-endpoint-methods/dist-src/index.js -function restEndpointMethods(octokit) { - const api = endpointsToMethods(octokit); - return { - rest: api - }; -} -restEndpointMethods.VERSION = VERSION8; -function legacyRestEndpointMethods(octokit) { - const api = endpointsToMethods(octokit); - return { - ...api, - rest: api - }; -} -legacyRestEndpointMethods.VERSION = VERSION8; - -// node_modules/.pnpm/@octokit+rest@22.0.0/node_modules/@octokit/rest/dist-src/version.js -var VERSION9 = "22.0.0"; - -// node_modules/.pnpm/@octokit+rest@22.0.0/node_modules/@octokit/rest/dist-src/index.js -var Octokit2 = Octokit.plugin(requestLog, legacyRestEndpointMethods, paginateRest).defaults( - { - userAgent: `octokit-rest.js/${VERSION9}` - } -); - -// utils/apiUrl.ts -function isLocalUrl(url4) { - return url4.hostname === "localhost" || url4.hostname === "127.0.0.1"; -} -function getApiUrl() { - const raw2 = process.env.API_URL || "https://pullfrog.com"; - const parsed2 = new URL(raw2); - if (parsed2.protocol !== "https:" && !isLocalUrl(parsed2)) { - throw new Error( - `API_URL must use https:// (got ${parsed2.protocol}). only localhost is exempt.` - ); - } - log.debug(`resolved API_URL: ${raw2}`); - return raw2; -} - -// utils/apiFetch.ts -async function apiFetch(options) { - const apiUrl = getApiUrl(); - const url4 = new URL(options.path, apiUrl); - const bypassSecret = process.env.VERCEL_AUTOMATION_BYPASS_SECRET; - if (bypassSecret) { - url4.searchParams.set("x-vercel-protection-bypass", bypassSecret); - } - const headers = { - ...options.headers - }; - if (bypassSecret) { - headers["x-vercel-protection-bypass"] = bypassSecret; - } - log.debug(`api fetch: ${options.method ?? "GET"} ${url4.pathname}`); - const init = { - method: options.method ?? "GET", - headers - }; - if (options.body) init.body = options.body; - if (options.signal) init.signal = options.signal; - return fetch(url4.toString(), init); -} - -// utils/retry.ts -var defaultShouldRetry = (error49) => { - if (!(error49 instanceof Error)) return false; - return error49.name === "AbortError" || error49.message.includes("fetch failed") || error49.message.includes("ECONNRESET") || error49.message.includes("ETIMEDOUT"); -}; -async function retry(fn2, options = {}) { - const maxAttempts = options.maxAttempts ?? 3; - const delayMs = options.delayMs ?? 1e3; - const shouldRetry = options.shouldRetry ?? defaultShouldRetry; - const label = options.label ?? "operation"; - let lastError; - for (let attempt = 1; attempt <= maxAttempts; attempt++) { - try { - return await fn2(); - } catch (error49) { - lastError = error49; - if (attempt === maxAttempts || !shouldRetry(error49)) { - throw error49; - } - const delay2 = delayMs * attempt; - log.info(`\xBB ${label} failed (attempt ${attempt}/${maxAttempts}), retrying in ${delay2}ms...`); - await new Promise((resolve2) => setTimeout(resolve2, delay2)); - } - } - throw lastError; -} - -// utils/github.ts -function isObject4(value2) { - return typeof value2 === "object" && value2 !== null; -} -function isOIDCAvailable() { - return Boolean( - process.env.ACTIONS_ID_TOKEN_REQUEST_URL && process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN - ); -} -async function acquireTokenViaOIDC(opts) { - const oidcToken = await core2.getIDToken("pullfrog-api"); - const repos = [...opts?.repos ?? []]; - const targetRepo = process.env.GITHUB_REPOSITORY?.split("/")[1]; - if (targetRepo) { - repos.push(targetRepo); - } - const reposParam = repos.length ? `?repos=${repos.join(",")}` : ""; - const timeoutMs = 3e4; - const controller = new AbortController(); - const timeoutId = setTimeout(() => controller.abort(), timeoutMs); - try { - const tokenResponse = await apiFetch({ - path: `/api/github/installation-token${reposParam}`, - method: "POST", - headers: { - Authorization: `Bearer ${oidcToken}`, - "Content-Type": "application/json" - }, - body: opts?.permissions ? JSON.stringify({ permissions: opts.permissions }) : void 0, - signal: controller.signal - }); - clearTimeout(timeoutId); - if (!tokenResponse.ok) { - throw new Error(`Token exchange failed: ${tokenResponse.status} ${tokenResponse.statusText}`); - } - const tokenData = await tokenResponse.json(); - return tokenData.token; - } catch (error49) { - clearTimeout(timeoutId); - if (error49 instanceof Error && error49.name === "AbortError") { - throw new Error(`Token exchange timed out after ${timeoutMs}ms`); - } - throw error49; - } -} -var base64UrlEncode = (str) => { - return Buffer.from(str).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); -}; -var generateJWT = (appId, privateKey) => { - const now = Math.floor(Date.now() / 1e3); - const payload = { - iat: now - 60, - exp: now + 5 * 60, - iss: appId - }; - const header = { - alg: "RS256", - typ: "JWT" - }; - const encodedHeader = base64UrlEncode(JSON.stringify(header)); - const encodedPayload = base64UrlEncode(JSON.stringify(payload)); - const signaturePart = `${encodedHeader}.${encodedPayload}`; - const signature = createSign("RSA-SHA256").update(signaturePart).sign(privateKey, "base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); - return `${signaturePart}.${signature}`; -}; -var githubRequest = async (path3, options = {}) => { - const { method = "GET", headers = {}, body } = options; - const url4 = `https://api.github.com${path3}`; - const requestHeaders = { - Accept: "application/vnd.github.v3+json", - "User-Agent": "Pullfrog-Installation-Token-Generator/1.0", - ...headers - }; - const response = await fetch(url4, { - method, - headers: requestHeaders, - ...body && { body } - }); - if (!response.ok) { - const errorText = await response.text(); - throw new Error( - `GitHub API request failed: ${response.status} ${response.statusText} -${errorText}` - ); - } - return response.json(); -}; -var checkRepositoryAccess = async (token, repoOwner, repoName) => { - try { - const response = await githubRequest("/installation/repositories", { - headers: { Authorization: `token ${token}` } - }); - return response.repositories.some( - (repo) => repo.owner.login === repoOwner && repo.name === repoName - ); - } catch { - return false; - } -}; -var createInstallationToken = async (jwt2, installationId, permissions) => { - const requestOpts = { - method: "POST", - headers: { Authorization: `Bearer ${jwt2}` } - }; - if (permissions) { - requestOpts.body = JSON.stringify({ permissions }); - } - const response = await githubRequest( - `/app/installations/${installationId}/access_tokens`, - requestOpts - ); - return response.token; -}; -var findInstallationId = async (jwt2, repoOwner, repoName) => { - const installations = await githubRequest("/app/installations", { - headers: { Authorization: `Bearer ${jwt2}` } - }); - for (const installation of installations) { - try { - const tempToken = await createInstallationToken(jwt2, installation.id); - const hasAccess = await checkRepositoryAccess(tempToken, repoOwner, repoName); - if (hasAccess) { - return installation.id; - } - } catch { - } - } - throw new Error( - `No installation found with access to ${repoOwner}/${repoName}. Ensure the GitHub App is installed on the target repository.` - ); -}; -async function acquireTokenViaGitHubApp(opts) { - if (!process.env.GITHUB_APP_ID || !process.env.GITHUB_PRIVATE_KEY) { - throw new Error( - "cannot acquire token via GitHub App: GITHUB_APP_ID and GITHUB_PRIVATE_KEY must be set" - ); - } - const repoContext = parseRepoContext(); - const config3 = { - appId: process.env.GITHUB_APP_ID, - privateKey: process.env.GITHUB_PRIVATE_KEY.replace(/\\n/g, "\n"), - repoOwner: repoContext.owner, - repoName: repoContext.name - }; - const jwt2 = generateJWT(config3.appId, config3.privateKey); - const installationId = await findInstallationId(jwt2, config3.repoOwner, config3.repoName); - return await createInstallationToken(jwt2, installationId, opts?.permissions); -} -async function acquireNewToken(opts) { - if (isOIDCAvailable()) { - return await retry(() => acquireTokenViaOIDC(opts), { - label: "token exchange", - shouldRetry: (error49) => error49 instanceof Error && (error49.name === "AbortError" || error49.message.includes("fetch failed") || error49.message.includes("ECONNRESET") || error49.message.includes("ETIMEDOUT") || error49.message.includes("Token exchange failed")) - }); - } else { - return await acquireTokenViaGitHubApp(opts); - } -} -function parseRepoContext() { - const githubRepo = process.env.GITHUB_REPOSITORY; - if (!githubRepo) { - throw new Error("GITHUB_REPOSITORY environment variable is required"); - } - const [owner, name] = githubRepo.split("/"); - if (!owner || !name) { - throw new Error(`Invalid GITHUB_REPOSITORY format: ${githubRepo}. Expected 'owner/repo'`); - } - return { owner, name }; -} -function emptyResourceUsage() { - return { - requestCount: 0, - rateLimitRemaining: null, - rateLimitResetMs: null - }; -} -var usageByResource = { - core: emptyResourceUsage(), - graphql: emptyResourceUsage() -}; -function getGitHubUsageSummary() { - return { - version: 1, - github: { - core: usageByResource.core, - graphql: usageByResource.graphql - } - }; -} -async function writeGitHubUsageSummaryToFile(path3) { - const summary2 = getGitHubUsageSummary(); - const tmpPath = join(dirname(path3), `.usage-summary-${process.pid}.tmp`); - await writeFile(tmpPath, JSON.stringify(summary2)); - await rename(tmpPath, path3); -} -function createOctokit(token) { - const OctokitWithPlugins = Octokit2.plugin(throttling); - const octokit = new OctokitWithPlugins({ - auth: token, - throttle: { - onRateLimit: (_retryAfter, _options, _octokit, retryCount) => { - return retryCount <= 2; - }, - onSecondaryRateLimit: (_retryAfter, _options, _octokit, retryCount) => { - return retryCount <= 2; - } - } - }); - const onResponse = (response) => { - const resource = response.headers["x-ratelimit-resource"]; - if (!resource) { - return response; - } - usageByResource[resource] ??= emptyResourceUsage(); - const usage = usageByResource[resource]; - usage.requestCount++; - const remaining = response.headers["x-ratelimit-remaining"]; - const reset = response.headers["x-ratelimit-reset"]; - if (remaining !== void 0) { - usage.rateLimitRemaining = Number(remaining); - } - if (reset !== void 0) { - usage.rateLimitResetMs = Number(reset) * 1e3; - } - return response; - }; - octokit.hook.wrap("request", async (request2, options) => { - try { - const response = await request2(options); - onResponse(response); - return response; - } catch (error49) { - if (isObject4(error49) && "response" in error49 && isObject4(error49.response) && "headers" in error49.response && isObject4(error49.response.headers)) { - onResponse(error49.response); - } - throw error49; - } - }); - return octokit; -} - // utils/token.ts var mcpTokenValue; function getJobToken() { @@ -144270,403 +145071,6 @@ function $(cmd, args2, options) { return stdout.trim(); } -// node_modules/.pnpm/@toon-format+toon@1.4.0/node_modules/@toon-format/toon/dist/index.mjs -var LIST_ITEM_MARKER = "-"; -var LIST_ITEM_PREFIX = "- "; -var COMMA = ","; -var PIPE = "|"; -var DOT = "."; -var NULL_LITERAL = "null"; -var TRUE_LITERAL = "true"; -var FALSE_LITERAL = "false"; -var BACKSLASH = "\\"; -var DOUBLE_QUOTE = '"'; -var TAB = " "; -var DELIMITERS = { - comma: COMMA, - tab: TAB, - pipe: PIPE -}; -var DEFAULT_DELIMITER = DELIMITERS.comma; -function escapeString(value2) { - return value2.replace(/\\/g, `${BACKSLASH}${BACKSLASH}`).replace(/"/g, `${BACKSLASH}${DOUBLE_QUOTE}`).replace(/\n/g, `${BACKSLASH}n`).replace(/\r/g, `${BACKSLASH}r`).replace(/\t/g, `${BACKSLASH}t`); -} -function isBooleanOrNullLiteral(token) { - return token === TRUE_LITERAL || token === FALSE_LITERAL || token === NULL_LITERAL; -} -function normalizeValue(value2) { - if (value2 === null) return null; - if (typeof value2 === "string" || typeof value2 === "boolean") return value2; - if (typeof value2 === "number") { - if (Object.is(value2, -0)) return 0; - if (!Number.isFinite(value2)) return null; - return value2; - } - if (typeof value2 === "bigint") { - if (value2 >= Number.MIN_SAFE_INTEGER && value2 <= Number.MAX_SAFE_INTEGER) return Number(value2); - return value2.toString(); - } - if (value2 instanceof Date) return value2.toISOString(); - if (Array.isArray(value2)) return value2.map(normalizeValue); - if (value2 instanceof Set) return Array.from(value2).map(normalizeValue); - if (value2 instanceof Map) return Object.fromEntries(Array.from(value2, ([k, v]) => [String(k), normalizeValue(v)])); - if (isPlainObject5(value2)) { - const normalized = {}; - for (const key in value2) if (Object.prototype.hasOwnProperty.call(value2, key)) normalized[key] = normalizeValue(value2[key]); - return normalized; - } - return null; -} -function isJsonPrimitive(value2) { - return value2 === null || typeof value2 === "string" || typeof value2 === "number" || typeof value2 === "boolean"; -} -function isJsonArray(value2) { - return Array.isArray(value2); -} -function isJsonObject(value2) { - return value2 !== null && typeof value2 === "object" && !Array.isArray(value2); -} -function isEmptyObject2(value2) { - return Object.keys(value2).length === 0; -} -function isPlainObject5(value2) { - if (value2 === null || typeof value2 !== "object") return false; - const prototype = Object.getPrototypeOf(value2); - return prototype === null || prototype === Object.prototype; -} -function isArrayOfPrimitives(value2) { - return value2.length === 0 || value2.every((item) => isJsonPrimitive(item)); -} -function isArrayOfArrays(value2) { - return value2.length === 0 || value2.every((item) => isJsonArray(item)); -} -function isArrayOfObjects(value2) { - return value2.length === 0 || value2.every((item) => isJsonObject(item)); -} -function isValidUnquotedKey(key) { - return /^[A-Z_][\w.]*$/i.test(key); -} -function isIdentifierSegment(key) { - return /^[A-Z_]\w*$/i.test(key); -} -function isSafeUnquoted(value2, delimiter = DEFAULT_DELIMITER) { - if (!value2) return false; - if (value2 !== value2.trim()) return false; - if (isBooleanOrNullLiteral(value2) || isNumericLike(value2)) return false; - if (value2.includes(":")) return false; - if (value2.includes('"') || value2.includes("\\")) return false; - if (/[[\]{}]/.test(value2)) return false; - if (/[\n\r\t]/.test(value2)) return false; - if (value2.includes(delimiter)) return false; - if (value2.startsWith(LIST_ITEM_MARKER)) return false; - return true; -} -function isNumericLike(value2) { - return /^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i.test(value2) || /^0\d+$/.test(value2); -} -var QUOTED_KEY_MARKER = Symbol("quotedKey"); -function tryFoldKeyChain(key, value2, siblings, options, rootLiteralKeys, pathPrefix, flattenDepth) { - if (options.keyFolding !== "safe") return; - if (!isJsonObject(value2)) return; - const { segments, tail, leafValue } = collectSingleKeyChain(key, value2, flattenDepth ?? options.flattenDepth); - if (segments.length < 2) return; - if (!segments.every((seg) => isIdentifierSegment(seg))) return; - const foldedKey = buildFoldedKey(segments); - const absolutePath = pathPrefix ? `${pathPrefix}${DOT}${foldedKey}` : foldedKey; - if (siblings.includes(foldedKey)) return; - if (rootLiteralKeys && rootLiteralKeys.has(absolutePath)) return; - return { - foldedKey, - remainder: tail, - leafValue, - segmentCount: segments.length - }; -} -function collectSingleKeyChain(startKey, startValue, maxDepth) { - const segments = [startKey]; - let currentValue = startValue; - while (segments.length < maxDepth) { - if (!isJsonObject(currentValue)) break; - const keys = Object.keys(currentValue); - if (keys.length !== 1) break; - const nextKey = keys[0]; - const nextValue = currentValue[nextKey]; - segments.push(nextKey); - currentValue = nextValue; - } - if (!isJsonObject(currentValue) || isEmptyObject2(currentValue)) return { - segments, - tail: void 0, - leafValue: currentValue - }; - return { - segments, - tail: currentValue, - leafValue: currentValue - }; -} -function buildFoldedKey(segments) { - return segments.join(DOT); -} -function encodePrimitive(value2, delimiter) { - if (value2 === null) return NULL_LITERAL; - if (typeof value2 === "boolean") return String(value2); - if (typeof value2 === "number") return String(value2); - return encodeStringLiteral(value2, delimiter); -} -function encodeStringLiteral(value2, delimiter = DEFAULT_DELIMITER) { - if (isSafeUnquoted(value2, delimiter)) return value2; - return `${DOUBLE_QUOTE}${escapeString(value2)}${DOUBLE_QUOTE}`; -} -function encodeKey(key) { - if (isValidUnquotedKey(key)) return key; - return `${DOUBLE_QUOTE}${escapeString(key)}${DOUBLE_QUOTE}`; -} -function encodeAndJoinPrimitives(values, delimiter = DEFAULT_DELIMITER) { - return values.map((v) => encodePrimitive(v, delimiter)).join(delimiter); -} -function formatHeader(length, options) { - const key = options?.key; - const fields = options?.fields; - const delimiter = options?.delimiter ?? COMMA; - let header = ""; - if (key) header += encodeKey(key); - header += `[${length}${delimiter !== DEFAULT_DELIMITER ? delimiter : ""}]`; - if (fields) { - const quotedFields = fields.map((f) => encodeKey(f)); - header += `{${quotedFields.join(delimiter)}}`; - } - header += ":"; - return header; -} -function* encodeJsonValue(value2, options, depth) { - if (isJsonPrimitive(value2)) { - const encodedPrimitive = encodePrimitive(value2, options.delimiter); - if (encodedPrimitive !== "") yield encodedPrimitive; - return; - } - if (isJsonArray(value2)) yield* encodeArrayLines(void 0, value2, depth, options); - else if (isJsonObject(value2)) yield* encodeObjectLines(value2, depth, options); -} -function* encodeObjectLines(value2, depth, options, rootLiteralKeys, pathPrefix, remainingDepth) { - const keys = Object.keys(value2); - if (depth === 0 && !rootLiteralKeys) rootLiteralKeys = new Set(keys.filter((k) => k.includes("."))); - const effectiveFlattenDepth = remainingDepth ?? options.flattenDepth; - for (const [key, val] of Object.entries(value2)) yield* encodeKeyValuePairLines(key, val, depth, options, keys, rootLiteralKeys, pathPrefix, effectiveFlattenDepth); -} -function* encodeKeyValuePairLines(key, value2, depth, options, siblings, rootLiteralKeys, pathPrefix, flattenDepth) { - const currentPath = pathPrefix ? `${pathPrefix}${DOT}${key}` : key; - const effectiveFlattenDepth = flattenDepth ?? options.flattenDepth; - if (options.keyFolding === "safe" && siblings) { - const foldResult = tryFoldKeyChain(key, value2, siblings, options, rootLiteralKeys, pathPrefix, effectiveFlattenDepth); - if (foldResult) { - const { foldedKey, remainder, leafValue, segmentCount } = foldResult; - const encodedFoldedKey = encodeKey(foldedKey); - if (remainder === void 0) { - if (isJsonPrimitive(leafValue)) { - yield indentedLine(depth, `${encodedFoldedKey}: ${encodePrimitive(leafValue, options.delimiter)}`, options.indent); - return; - } else if (isJsonArray(leafValue)) { - yield* encodeArrayLines(foldedKey, leafValue, depth, options); - return; - } else if (isJsonObject(leafValue) && isEmptyObject2(leafValue)) { - yield indentedLine(depth, `${encodedFoldedKey}:`, options.indent); - return; - } - } - if (isJsonObject(remainder)) { - yield indentedLine(depth, `${encodedFoldedKey}:`, options.indent); - const remainingDepth = effectiveFlattenDepth - segmentCount; - const foldedPath = pathPrefix ? `${pathPrefix}${DOT}${foldedKey}` : foldedKey; - yield* encodeObjectLines(remainder, depth + 1, options, rootLiteralKeys, foldedPath, remainingDepth); - return; - } - } - } - const encodedKey = encodeKey(key); - if (isJsonPrimitive(value2)) yield indentedLine(depth, `${encodedKey}: ${encodePrimitive(value2, options.delimiter)}`, options.indent); - else if (isJsonArray(value2)) yield* encodeArrayLines(key, value2, depth, options); - else if (isJsonObject(value2)) { - yield indentedLine(depth, `${encodedKey}:`, options.indent); - if (!isEmptyObject2(value2)) yield* encodeObjectLines(value2, depth + 1, options, rootLiteralKeys, currentPath, effectiveFlattenDepth); - } -} -function* encodeArrayLines(key, value2, depth, options) { - if (value2.length === 0) { - yield indentedLine(depth, formatHeader(0, { - key, - delimiter: options.delimiter - }), options.indent); - return; - } - if (isArrayOfPrimitives(value2)) { - yield indentedLine(depth, encodeInlineArrayLine(value2, options.delimiter, key), options.indent); - return; - } - if (isArrayOfArrays(value2)) { - if (value2.every((arr) => isArrayOfPrimitives(arr))) { - yield* encodeArrayOfArraysAsListItemsLines(key, value2, depth, options); - return; - } - } - if (isArrayOfObjects(value2)) { - const header = extractTabularHeader(value2); - if (header) yield* encodeArrayOfObjectsAsTabularLines(key, value2, header, depth, options); - else yield* encodeMixedArrayAsListItemsLines(key, value2, depth, options); - return; - } - yield* encodeMixedArrayAsListItemsLines(key, value2, depth, options); -} -function* encodeArrayOfArraysAsListItemsLines(prefix, values, depth, options) { - yield indentedLine(depth, formatHeader(values.length, { - key: prefix, - delimiter: options.delimiter - }), options.indent); - for (const arr of values) if (isArrayOfPrimitives(arr)) { - const arrayLine = encodeInlineArrayLine(arr, options.delimiter); - yield indentedListItem(depth + 1, arrayLine, options.indent); - } -} -function encodeInlineArrayLine(values, delimiter, prefix) { - const header = formatHeader(values.length, { - key: prefix, - delimiter - }); - const joinedValue = encodeAndJoinPrimitives(values, delimiter); - if (values.length === 0) return header; - return `${header} ${joinedValue}`; -} -function* encodeArrayOfObjectsAsTabularLines(prefix, rows, header, depth, options) { - yield indentedLine(depth, formatHeader(rows.length, { - key: prefix, - fields: header, - delimiter: options.delimiter - }), options.indent); - yield* writeTabularRowsLines(rows, header, depth + 1, options); -} -function extractTabularHeader(rows) { - if (rows.length === 0) return; - const firstRow = rows[0]; - const firstKeys = Object.keys(firstRow); - if (firstKeys.length === 0) return; - if (isTabularArray(rows, firstKeys)) return firstKeys; -} -function isTabularArray(rows, header) { - for (const row of rows) { - if (Object.keys(row).length !== header.length) return false; - for (const key of header) { - if (!(key in row)) return false; - if (!isJsonPrimitive(row[key])) return false; - } - } - return true; -} -function* writeTabularRowsLines(rows, header, depth, options) { - for (const row of rows) yield indentedLine(depth, encodeAndJoinPrimitives(header.map((key) => row[key]), options.delimiter), options.indent); -} -function* encodeMixedArrayAsListItemsLines(prefix, items, depth, options) { - yield indentedLine(depth, formatHeader(items.length, { - key: prefix, - delimiter: options.delimiter - }), options.indent); - for (const item of items) yield* encodeListItemValueLines(item, depth + 1, options); -} -function* encodeObjectAsListItemLines(obj, depth, options) { - if (isEmptyObject2(obj)) { - yield indentedLine(depth, LIST_ITEM_MARKER, options.indent); - return; - } - const entries = Object.entries(obj); - if (entries.length === 1) { - const [key, value2] = entries[0]; - if (isJsonArray(value2) && isArrayOfObjects(value2)) { - const header = extractTabularHeader(value2); - if (header) { - yield indentedListItem(depth, formatHeader(value2.length, { - key, - fields: header, - delimiter: options.delimiter - }), options.indent); - yield* writeTabularRowsLines(value2, header, depth + 1, options); - return; - } - } - } - yield indentedLine(depth, LIST_ITEM_MARKER, options.indent); - yield* encodeObjectLines(obj, depth + 1, options); -} -function* encodeListItemValueLines(value2, depth, options) { - if (isJsonPrimitive(value2)) yield indentedListItem(depth, encodePrimitive(value2, options.delimiter), options.indent); - else if (isJsonArray(value2)) if (isArrayOfPrimitives(value2)) yield indentedListItem(depth, encodeInlineArrayLine(value2, options.delimiter), options.indent); - else { - yield indentedListItem(depth, formatHeader(value2.length, { delimiter: options.delimiter }), options.indent); - for (const item of value2) yield* encodeListItemValueLines(item, depth + 1, options); - } - else if (isJsonObject(value2)) yield* encodeObjectAsListItemLines(value2, depth, options); -} -function indentedLine(depth, content, indentSize) { - return " ".repeat(indentSize * depth) + content; -} -function indentedListItem(depth, content, indentSize) { - return indentedLine(depth, LIST_ITEM_PREFIX + content, indentSize); -} -function encode3(input, options) { - return Array.from(encodeLines(input, options)).join("\n"); -} -function encodeLines(input, options) { - return encodeJsonValue(normalizeValue(input), resolveOptions(options), 0); -} -function resolveOptions(options) { - return { - indent: options?.indent ?? 2, - delimiter: options?.delimiter ?? DEFAULT_DELIMITER, - keyFolding: options?.keyFolding ?? "off", - flattenDepth: options?.flattenDepth ?? Number.POSITIVE_INFINITY - }; -} - -// mcp/shared.ts -var tool = (toolDef) => toolDef; -var handleToolSuccess = (data) => { - const text = typeof data === "string" ? data : encode3(data); - return { - content: [{ type: "text", text }] - }; -}; -var handleToolError = (error49) => { - const errorMessage = error49 instanceof Error ? error49.message : String(error49); - return { - content: [ - { - type: "text", - text: `Error: ${errorMessage}` - } - ], - isError: true - }; -}; -var execute = (fn2, toolName) => { - const _fn = async (params) => { - try { - const result = await fn2(params); - return handleToolSuccess(result); - } catch (error49) { - const errorMessage = error49 instanceof Error ? error49.message : String(error49); - const prefix = toolName ? `[${toolName}]` : "tool"; - log.info(`${prefix} error: ${errorMessage}`); - log.debug(`${prefix} params: ${formatJsonValue(params)}`); - return handleToolError(error49); - } - }; - return _fn; -}; -var addTools = (_ctx, server, tools) => { - for (const tool2 of tools) { - server.addTool(tool2); - } - return server; -}; - // mcp/checkout.ts function formatFilesWithLineNumbers(files) { const output = []; @@ -145117,397 +145521,6 @@ function GetCheckSuiteLogsTool(ctx) { }); } -// utils/buildPullfrogFooter.ts -var PULLFROG_DIVIDER = ""; -var FROG_LOGO = `Pullfrog`; -function formatModelLabel(slug) { - const alias = modelAliases.find((a) => a.slug === slug); - if (!alias) return `\`${slug}\``; - return alias.isFree ? `\`${alias.displayName}\` (free)` : `\`${alias.displayName}\``; -} -function buildPullfrogFooter(params) { - const parts = []; - if (params.customParts) { - parts.push(...params.customParts); - } - if (params.workflowRunUrl) { - parts.push(`[View workflow run](${params.workflowRunUrl})`); - } else if (params.workflowRun) { - const baseUrl = `https://github.com/${params.workflowRun.owner}/${params.workflowRun.repo}/actions/runs/${params.workflowRun.runId}`; - const url4 = params.workflowRun.jobId ? `${baseUrl}/job/${params.workflowRun.jobId}` : baseUrl; - parts.push(`[View workflow run](${url4})`); - } - if (params.triggeredBy) { - parts.push("Triggered by [Pullfrog](https://pullfrog.com)"); - } - if (params.model) { - parts.push(`Using ${formatModelLabel(params.model)}`); - } - const allParts = [...parts, "[\u{1D54F}](https://x.com/pullfrogai)"]; - return ` -${PULLFROG_DIVIDER} -${FROG_LOGO}  \uFF5C ${allParts.join(" \uFF5C ")}`; -} -function stripExistingFooter(body) { - const dividerIndex = body.indexOf(PULLFROG_DIVIDER); - if (dividerIndex === -1) { - return body; - } - return body.substring(0, dividerIndex).trimEnd(); -} - -// utils/fixDoubleEscapedString.ts -function fixDoubleEscapedString(str) { - if (!str.includes("\n") && str.includes("\\n")) { - return str.replace(/\\n/g, "\n").replace(/\\t/g, " ").replace(/\\"/g, '"'); - } - return str; -} - -// mcp/comment.ts -async function updateCommentNodeId(ctx, field, nodeId) { - if (ctx.runId === void 0 || !ctx.apiToken) return; - try { - await retry( - async () => { - const response = await apiFetch({ - path: `/api/workflow-run/${ctx.runId}`, - method: "PATCH", - headers: { - authorization: `Bearer ${ctx.apiToken}`, - "content-type": "application/json" - }, - body: JSON.stringify({ [field]: nodeId }), - signal: AbortSignal.timeout(1e4) - }); - if (!response.ok) throw new Error(`PATCH workflow-run: ${response.status}`); - }, - { - maxAttempts: 3, - delayMs: 2e3, - label: `updateCommentNodeId(${field})` - } - ); - } catch (error49) { - log.warning(`updateCommentNodeId(${field}) exhausted retries: ${error49}`); - } -} -async function buildCommentFooter(params) { - const repoContext = parseRepoContext(); - const runId = process.env.GITHUB_RUN_ID ? Number.parseInt(process.env.GITHUB_RUN_ID, 10) : void 0; - let jobId; - if (runId && params.octokit) { - try { - const { data: jobs } = await params.octokit.rest.actions.listJobsForWorkflowRun({ - owner: repoContext.owner, - repo: repoContext.name, - run_id: runId - }); - jobId = jobs.jobs[0]?.id.toString(); - } catch { - } - } - return buildPullfrogFooter({ - triggeredBy: true, - workflowRun: runId ? { owner: repoContext.owner, repo: repoContext.name, runId, jobId } : void 0, - customParts: params.customParts, - model: params.model - }); -} -function buildImplementPlanLink(owner, repo, issueNumber, commentId) { - const apiUrl = getApiUrl(); - return `[Implement plan \u2794](${apiUrl}/trigger/${owner}/${repo}/${issueNumber}?action=implement&comment_id=${commentId})`; -} -async function addFooter(ctx, body) { - if (/[ \t]*\n(?!\s*\n)/i.test(body)) { - throw new Error( - "body contains
followed by a non-blank line, which breaks GitHub markdown rendering. always add a blank line after
tags." - ); - } - const bodyWithoutFooter = stripExistingFooter(fixDoubleEscapedString(body)); - const footer = await buildCommentFooter({ octokit: ctx.octokit, model: ctx.toolState?.model }); - return `${bodyWithoutFooter}${footer}`; -} -var Comment = type({ - issueNumber: type.number.describe("the issue number to comment on"), - body: type.string.describe("the comment body content"), - type: type.enumerated("Plan", "Summary", "Comment").describe( - "Plan: record as the plan for this run. Summary: record as the PR summary comment (one per PR, updated in place). Comment: regular comment (default)." - ).optional() -}); -function CreateCommentTool(ctx) { - return tool({ - name: "create_issue_comment", - description: "Create a comment on a GitHub issue or PR. For progress/plan updates on the current run use report_progress instead. Use type: 'Plan' for plan comments, type: 'Summary' for PR summary comments.", - parameters: Comment, - execute: execute(async ({ issueNumber, body, type: commentType }) => { - const bodyWithFooter = await addFooter(ctx, body); - if (commentType === "Summary" && ctx.toolState.existingSummaryCommentId) { - log.info( - `\xBB redirecting create_issue_comment(Summary) to update existing comment ${ctx.toolState.existingSummaryCommentId}` - ); - const result2 = await ctx.octokit.rest.issues.updateComment({ - owner: ctx.repo.owner, - repo: ctx.repo.name, - comment_id: ctx.toolState.existingSummaryCommentId, - body: bodyWithFooter - }); - if (result2.data.node_id) { - await updateCommentNodeId(ctx, "summaryCommentNodeId", result2.data.node_id); - } - return { - success: true, - commentId: result2.data.id, - url: result2.data.html_url, - body: result2.data.body - }; - } - const result = await ctx.octokit.rest.issues.createComment({ - owner: ctx.repo.owner, - repo: ctx.repo.name, - issue_number: issueNumber, - body: bodyWithFooter - }); - if (commentType === "Plan" && result.data.node_id) { - await updateCommentNodeId(ctx, "planCommentNodeId", result.data.node_id); - } - if (commentType === "Summary" && result.data.node_id) { - await updateCommentNodeId(ctx, "summaryCommentNodeId", result.data.node_id); - } - return { - success: true, - commentId: result.data.id, - url: result.data.html_url, - body: result.data.body - }; - }) - }); -} -var EditComment = type({ - commentId: type.number.describe("the ID of the comment to edit"), - body: type.string.describe("the new comment body content") -}); -function EditCommentTool(ctx) { - return tool({ - name: "edit_issue_comment", - description: "Edit a GitHub issue comment by its ID", - parameters: EditComment, - execute: execute(async ({ commentId, body }) => { - const bodyWithFooter = await addFooter(ctx, body); - const result = await ctx.octokit.rest.issues.updateComment({ - owner: ctx.repo.owner, - repo: ctx.repo.name, - comment_id: commentId, - body: bodyWithFooter - }); - return { - success: true, - commentId: result.data.id, - url: result.data.html_url, - body: result.data.body, - updatedAt: result.data.updated_at - }; - }) - }); -} -var ReportProgress = type({ - body: type.string.describe("the progress update content to share"), - "target_plan_comment?": type("boolean").describe( - "when true, update the existing plan comment (from select_mode lookup) instead of the progress comment; use when editing an existing plan" - ) -}); -async function reportProgress(ctx, params) { - const { body, target_plan_comment } = params; - ctx.toolState.lastProgressBody = body; - if (ctx.payload.event.silent) { - return { body, action: "skipped" }; - } - const issueNumber = ctx.payload.event.issue_number ?? ctx.toolState.issueNumber; - const isPlanMode = ctx.toolState.selectedMode === "Plan"; - if (target_plan_comment === true && ctx.toolState.existingPlanCommentId === void 0) { - log.warning("target_plan_comment requested but no existingPlanCommentId in tool state"); - } - if (target_plan_comment === true && ctx.toolState.existingPlanCommentId !== void 0) { - const commentId = ctx.toolState.existingPlanCommentId; - const customParts = isPlanMode && issueNumber !== void 0 ? [buildImplementPlanLink(ctx.repo.owner, ctx.repo.name, issueNumber, commentId)] : void 0; - const bodyWithoutFooter = stripExistingFooter(body); - const footer = await buildCommentFooter({ - octokit: ctx.octokit, - customParts, - model: ctx.toolState.model - }); - const bodyWithFooter = `${bodyWithoutFooter}${footer}`; - const result2 = await ctx.octokit.rest.issues.updateComment({ - owner: ctx.repo.owner, - repo: ctx.repo.name, - comment_id: commentId, - body: bodyWithFooter - }); - ctx.toolState.wasUpdated = true; - if (isPlanMode && result2.data.node_id) { - await updateCommentNodeId(ctx, "planCommentNodeId", result2.data.node_id); - } - return { - commentId: result2.data.id, - url: result2.data.html_url, - body: result2.data.body || "", - action: "updated" - }; - } - const existingCommentId = ctx.toolState.progressCommentId; - if (existingCommentId) { - const customParts = isPlanMode && issueNumber !== void 0 ? [buildImplementPlanLink(ctx.repo.owner, ctx.repo.name, issueNumber, existingCommentId)] : void 0; - const bodyWithoutFooter = stripExistingFooter(body); - const footer = await buildCommentFooter({ - octokit: ctx.octokit, - customParts, - model: ctx.toolState.model - }); - const bodyWithFooter = `${bodyWithoutFooter}${footer}`; - const result2 = await ctx.octokit.rest.issues.updateComment({ - owner: ctx.repo.owner, - repo: ctx.repo.name, - comment_id: existingCommentId, - body: bodyWithFooter - }); - ctx.toolState.wasUpdated = true; - if (isPlanMode && result2.data.node_id) { - await updateCommentNodeId(ctx, "planCommentNodeId", result2.data.node_id); - } - return { - commentId: result2.data.id, - url: result2.data.html_url, - body: result2.data.body || "", - action: "updated" - }; - } - if (existingCommentId === null) { - return { body, action: "skipped" }; - } - if (issueNumber === void 0) { - return { body, action: "skipped" }; - } - const initialBody = await addFooter(ctx, body); - const result = await ctx.octokit.rest.issues.createComment({ - owner: ctx.repo.owner, - repo: ctx.repo.name, - issue_number: issueNumber, - body: initialBody - }); - ctx.toolState.progressCommentId = result.data.id; - ctx.toolState.wasUpdated = true; - if (isPlanMode) { - const customParts = [ - buildImplementPlanLink(ctx.repo.owner, ctx.repo.name, issueNumber, result.data.id) - ]; - const bodyWithoutFooter = stripExistingFooter(body); - const footer = await buildCommentFooter({ - octokit: ctx.octokit, - customParts, - model: ctx.toolState.model - }); - const bodyWithPlanLink = `${bodyWithoutFooter}${footer}`; - const updateResult = await ctx.octokit.rest.issues.updateComment({ - owner: ctx.repo.owner, - repo: ctx.repo.name, - comment_id: result.data.id, - body: bodyWithPlanLink - }); - if (updateResult.data.node_id) { - await updateCommentNodeId(ctx, "planCommentNodeId", updateResult.data.node_id); - } - return { - commentId: updateResult.data.id, - url: updateResult.data.html_url, - body: updateResult.data.body || "", - action: "created" - }; - } - return { - commentId: result.data.id, - url: result.data.html_url, - body: result.data.body || "", - action: "created" - }; -} -function ReportProgressTool(ctx) { - return tool({ - name: "report_progress", - description: "Share progress on the associated GitHub issue/PR. Call this to post updates as you work. The first call creates a comment, subsequent calls update it. Use this throughout your work to keep stakeholders informed.", - parameters: ReportProgress, - execute: execute(async (params) => { - const reportParams = { body: params.body }; - if (params.target_plan_comment !== void 0) { - reportParams.target_plan_comment = params.target_plan_comment; - } - const result = await reportProgress(ctx, reportParams); - if (result.action === "skipped") { - return { - success: true, - message: "progress recorded (no GitHub comment created - this may occur for workflow_dispatch events or when there is no associated issue/PR)" - }; - } - return { - success: true, - ...result - }; - }) - }); -} -async function deleteProgressComment(ctx) { - const existingCommentId = ctx.toolState.progressCommentId; - if (!existingCommentId) { - return false; - } - try { - await ctx.octokit.rest.issues.deleteComment({ - owner: ctx.repo.owner, - repo: ctx.repo.name, - comment_id: existingCommentId - }); - } catch (error49) { - if (error49 instanceof Error && error49.message.includes("Not Found")) { - } else { - throw error49; - } - } - ctx.toolState.progressCommentId = null; - ctx.toolState.wasUpdated = true; - return true; -} -var ReplyToReviewComment = type({ - pull_number: type.number.describe("the pull request number"), - comment_id: type.number.describe("the ID of the review comment to reply to"), - body: type.string.describe( - "extremely brief reply (1 sentence max) explaining what was fixed, e.g. 'Fixed by renaming to X' or 'Added null check'" - ) -}); -function ReplyToReviewCommentTool(ctx) { - return tool({ - name: "reply_to_review_comment", - description: "Reply to a PR review comment thread (NOT issue comments \u2014 this only works for inline review comments on PR diffs). Call this for EACH comment you address in AddressReviews mode. Keep replies extremely brief (1 sentence max).", - parameters: ReplyToReviewComment, - execute: execute(async ({ pull_number, comment_id, body }) => { - const bodyWithFooter = await addFooter(ctx, body); - const result = await ctx.octokit.rest.pulls.createReplyForReviewComment({ - owner: ctx.repo.owner, - repo: ctx.repo.name, - pull_number, - comment_id, - body: bodyWithFooter - }); - ctx.toolState.wasUpdated = true; - return { - success: true, - commentId: result.data.id, - url: result.data.html_url, - body: result.data.body, - in_reply_to_id: result.data.in_reply_to_id - }; - }, "reply_to_review_comment") - }); -} - // mcp/commitInfo.ts import { writeFileSync as writeFileSync3 } from "node:fs"; import { join as join4 } from "node:path"; @@ -147043,7 +147056,7 @@ var CreatePullRequestReview = type({ function CreatePullRequestReviewTool(ctx) { return tool({ name: "create_pull_request_review", - description: `Submit a review for an existing pull request. Each call creates a permanent, visible review on the PR \u2014 NEVER submit test or diagnostic reviews. IMPORTANT: 95%+ of feedback should be in 'comments' array with file paths and line numbers. Only use 'body' for a 1-2 sentence summary with urgency and critical callouts. Use 'suggestion' to propose replacement code - MUST preserve exact indentation of original code. Example replacing lines 42-44 (3 lines) with 5 lines: { path: 'src/api.ts', start_line: 42, line: 44, suggestion: ' const result = await fetch(url);\\n if (!result.ok) {\\n log.error(result.status);\\n throw new Error("request failed");\\n }' } CONSTRAINT: Inline comments can ONLY target files and lines that appear in the PR diff. If GitHub rejects comments due to incorrect line numbers, re-read the diff and retry.`, + description: `Submit a review for an existing pull request. Each call creates a permanent, visible review on the PR \u2014 NEVER submit test or diagnostic reviews. Reviews with no body AND no comments are silently skipped (nothing to post). IMPORTANT: 95%+ of feedback should be in 'comments' array with file paths and line numbers. Only use 'body' for a 1-2 sentence summary with urgency and critical callouts. Use 'suggestion' to propose replacement code - MUST preserve exact indentation of original code. Example replacing lines 42-44 (3 lines) with 5 lines: { path: 'src/api.ts', start_line: 42, line: 44, suggestion: ' const result = await fetch(url);\\n if (!result.ok) {\\n log.error(result.status);\\n throw new Error("request failed");\\n }' } CONSTRAINT: Inline comments can ONLY target files and lines that appear in the PR diff. If GitHub rejects comments due to incorrect line numbers, re-read the diff and retry.`, parameters: CreatePullRequestReview, execute: execute(async ({ pull_number, body, approved, commit_id, comments = [] }) => { if (body) body = fixDoubleEscapedString(body); @@ -147795,10 +147808,9 @@ ${learningsStep(6)}`, 3. Self-critique: review all drafted comments and drop any that are praise, style preferences, speculative/unverified claims, about pre-existing code unrelated to the PR, or not actionable. -4. Submit a **single** review: - - call \`${ghPullfrogMcpName}/create_pull_request_review\` with all comments and a unified summary body - - call \`${ghPullfrogMcpName}/report_progress\` with the summary - - if no actionable issues found, skip the review \u2014 just call \`report_progress\` noting the PR was reviewed`, +4. Submit: + - **actionable issues found**: call \`${ghPullfrogMcpName}/create_pull_request_review\` with all comments, a 1-3 sentence summary body, and \`approved: false\`. Then call \`report_progress\` with a 1-sentence summary. + - **no actionable issues found**: do NOT submit a review. Call \`${ghPullfrogMcpName}/report_progress\` with a brief note (e.g., "Reviewed \u2014 no issues found.").`, IncrementalReview: `### Checklist 1. Checkout the PR via \`${ghPullfrogMcpName}/checkout_pr\` \u2014 this returns PR metadata and a \`diffPath\`. Read the diff to identify the major areas of change. @@ -147817,10 +147829,9 @@ ${learningsStep(6)}`, 5. Self-critique: drop any comments that are praise, style preferences, speculative, about pre-existing code, or not actionable. -6. Submit a **single** review: - - if actionable issues found: call \`${ghPullfrogMcpName}/create_pull_request_review\` with \`approved: false\`, all comments, and an **empty body** (do NOT include a summary \u2014 inline comments speak for themselves and a top-level comment clutters the PR conversation on every re-review) - - if no actionable issues found: submit with \`approved: true\` and an **empty body** (no inline comments, no summary) - - do NOT call \`${ghPullfrogMcpName}/report_progress\` \u2014 incremental reviews should be silent`, +6. Submit: + - **actionable issues found**: call \`${ghPullfrogMcpName}/create_pull_request_review\` with \`approved: false\`, all comments, and an **empty body** \u2014 inline comments speak for themselves, and a top-level body clutters the PR conversation on every re-review cycle. Then call \`report_progress\` with a 1-sentence summary. + - **no actionable issues found**: do NOT submit a review. Call \`${ghPullfrogMcpName}/report_progress\` with a brief note (e.g., "Re-reviewed \u2014 no new issues found.").`, Plan: `### Checklist 1. Analyze the task and gather context: @@ -147887,8 +147898,9 @@ ${learningsStep(4)}`, - PR metadata (title, file count, commit count, base/head branches) - format instructions from EVENT INSTRUCTIONS (if any); otherwise use default format: TL;DR, key changes list, per-change sections with plain-language \`##\` titles and before/after framing - instruct it to use the TOC to selectively read relevant diff sections, not the entire file - - instruct it to return the full summary markdown via \`${ghPullfrogMcpName}/set_output\` + - instruct it to return the full summary markdown as its final response 3. After the subagent completes, call \`${ghPullfrogMcpName}/create_issue_comment\` with \`type: "Summary"\` and the summary body. +4. Call \`${ghPullfrogMcpName}/report_progress\` with a brief note (e.g., "Posted PR summary."). ### Effort @@ -147903,8 +147915,9 @@ An existing summary comment was found for this PR. Update it rather than creatin - the diff file path and PR metadata - the existing summary body (\`previousSummaryBody\`) so it can update rather than rewrite from scratch - format instructions from EVENT INSTRUCTIONS (if any) - - instruct it to produce an updated summary reflecting the current state of the PR and return via \`${ghPullfrogMcpName}/set_output\` + - instruct it to produce an updated summary reflecting the current state of the PR and return it as its final response 4. After the subagent completes, call \`${ghPullfrogMcpName}/edit_issue_comment\` with \`commentId: existingSummaryCommentId\` (from this response) and the updated summary body. +5. Call \`${ghPullfrogMcpName}/report_progress\` with a brief note (e.g., "Updated PR summary."). ### Effort @@ -148339,6 +148352,7 @@ function initToolState(params) { } return { progressCommentId: resolvedId, + hadProgressComment: !!resolvedId, backgroundProcesses: /* @__PURE__ */ new Map(), usageEntries: [] }; @@ -148397,9 +148411,12 @@ function buildCommonTools(ctx, outputSchema) { AddLabelsTool(ctx), GitTool(ctx), GitFetchTool(ctx), - UploadFileTool(ctx), - SetOutputTool(ctx, outputSchema) + UploadFileTool(ctx) ]; + const isStandalone = ctx.payload.event.trigger === "unknown"; + if (isStandalone || outputSchema) { + tools.push(SetOutputTool(ctx, outputSchema)); + } if (ctx.payload.shell === "restricted") { tools.push(ShellTool(ctx)); tools.push(KillBackgroundTool(ctx)); @@ -148514,7 +148531,7 @@ var ModeSchema = type({ description: "string", prompt: "string" }); -var reportProgressInstruction = `Use ${ghPullfrogMcpName}/report_progress to share progress and results. Continue calling it as you make progress \u2014 it will update the same comment. Never create additional comments manually.`; +var reportProgressInstruction = `Use ${ghPullfrogMcpName}/report_progress to share your **final** results in 1-3 sentences. The completed task list is automatically preserved in a collapsible section below your summary \u2014 do not repeat individual steps in the summary. Focus on the outcome and link to any artifacts (PRs, branches). Never create additional comments manually.`; var dependencyInstallationStep = `If this task will require running tests, builds, linters, or CLI commands that need installed packages, call \`${ghPullfrogMcpName}/start_dependency_installation\` NOW. This is non-blocking and allows dependencies to install in the background while you continue. Later, call \`${ghPullfrogMcpName}/await_dependency_installation\` before running commands that need them. Skip this step if only reading code or answering questions.`; var permalinkTip = `**TIP**: To reference specific code, use GitHub permalinks: \`https://github.com/{owner}/{repo}/blob/{commit_sha}/{path}#L{start}-L{end}\`. GitHub renders these as expandable code blocks.`; function computeModes() { @@ -148542,14 +148559,12 @@ function computeModes() { 7. **COMMIT** - Commit your changes using \`${ghPullfrogMcpName}/git\` (e.g., \`git add .\` then \`git commit -m "message"\`), then push with \`${ghPullfrogMcpName}/push_branch\`. Do NOT use \`git push\` directly - it requires credentials that only the MCP tool provides. -8. **PROGRESS** - ${reportProgressInstruction} - -9. **PR** - Determine whether to create a PR (if not already on a PR branch): +8. **PR** - Determine whether to create a PR (if not already on a PR branch): - **Default behavior**: Create a PR using ${ghPullfrogMcpName}/create_pull_request with an informative title and body. If you are working in the context of an issue (check EVENT DATA for \`issue_number\` where \`is_pr\` is not true), include "Closes #" in the PR body to auto-close the issue when merged. - **Draft PR request**: If the user explicitly asks for a draft PR (e.g. "draft PR", "create as draft", "WIP"), create a PR with \`draft: true\`. - **Branch-only request**: If the user explicitly asks for a branch without a PR (e.g. "don't create a PR", "branch only", "just create a branch"), do NOT create a PR. Simply push the branch and report the branch link. -10. **FINAL REPORT** - Call report_progress one final time ONLY if you haven't already included all the important information (PR links, branch links, summary) in a previous report_progress call. If you already called report_progress with complete information including PR links after creating the PR, you do NOT need to call it again. Only make a final call if you need to add missing information. When making the final call, ensure it includes: +9. **FINAL REPORT** - ${reportProgressInstruction} Ensure the summary includes: - A summary of what was accomplished - Links to any artifacts created (PRs, branches, issues) - If you created a PR, ALWAYS include the PR link. e.g.: @@ -148561,7 +148576,6 @@ function computeModes() { [\`pullfrog/branch-name\`](https://github.com/pullfrog/scratch/tree/pullfrog/branch-name) \u2022 [Create PR \u2794](https://github.com/pullfrog/scratch/compare/main...pullfrog/branch-name?quick_pull=1&title=&body=) \`\`\` - Do NOT overwrite a good comment with links/details with a generic message like "I have completed the task. Please review the PR." If your previous report_progress call already contains all the necessary information and links, skip the final call entirely. ` }, { @@ -148613,14 +148627,13 @@ Keep the progress comment extremely brief. The summary should be 1-2 sentences m - **Impact analysis**: Identify what was removed, renamed, or deprecated in the PR. Use grep to search the broader codebase for remaining references to those things in code, tests, docs, comments, and configs. Report stale references in the review body. - Do NOT stop at "this looks reasonable." Dig until you either find a problem or have concrete evidence there isn't one. -4. **DRAFT LINE-BY-LINE COMMENTS** - Every comment must be actionable: the author should need to change something in response. 2-3 sentences max. Use the NEW line number from the diff (second column: \`| OLD | NEW | TYPE | CODE\`). If no issues found, skip to step 5. NO COMPLIMENTS. NO NITPICKING ABOUT CHANGES UNRELATED TO THE MAIN CHANGE. Non-actionable comments (praise, style preferences, minor optimizatfixons, documentation nits) must not be drafted. +4. **DRAFT LINE-BY-LINE COMMENTS** - Every comment must be actionable: the author should need to change something in response. 2-3 sentences max. Use the NEW line number from the diff (second column: \`| OLD | NEW | TYPE | CODE\`). If no issues found, skip to step 5. NO COMPLIMENTS. NO NITPICKING ABOUT CHANGES UNRELATED TO THE MAIN CHANGE. Non-actionable comments (praise, style preferences, minor optimizations, documentation nits) must not be drafted. 5. **WRITE SUMMARY** - Draft a 1-3 sentence summary for the review body. If issues were found, include urgency level and any concerns about code outside the diff. If no issues were found, write a brief approval summary (e.g., "Changes look good. No issues found."). -6. **SUBMIT** \u2014 Always submit a review via ${ghPullfrogMcpName}/create_pull_request_review: - - \`body\`: The summary from step 5 - - \`comments\`: The inline comments from step 4 - - \`approved\`: Set to \`true\` ONLY if the review contains no actionable feedback \u2014 neither inline comments nor actionable content in the body. An approval signals "no changes needed." +6. **SUBMIT** \u2014 Determine whether to submit a review: + - **Issues found**: Submit via ${ghPullfrogMcpName}/create_pull_request_review with the summary body from step 5, the inline comments from step 4, and \`approved: false\`. Then call \`report_progress\` with a 1-sentence summary (e.g., "Reviewed \u2014 found 3 issues."). + - **No issues found**: Do NOT submit a review. Call \`${ghPullfrogMcpName}/report_progress\` with a brief note (e.g., "Reviewed \u2014 no issues found."). ${permalinkTip} ` @@ -148651,12 +148664,9 @@ ${permalinkTip} 6. **DRAFT LINE-BY-LINE COMMENTS** - Every comment must be actionable. 2-3 sentences max. Use the NEW line number from the full PR diff. NO COMPLIMENTS. NO NITPICKING. -7. **WRITE SUMMARY** - Draft a 1-3 sentence summary for the review body. Focus on what changed since the last review and whether the new changes are sound. If issues were found, include urgency level. If no issues were found, write a brief approval summary. - -8. **SUBMIT** \u2014 Use ${ghPullfrogMcpName}/create_pull_request_review: - - \`body\`: The summary from step 7 - - \`comments\`: The inline comments from step 6 - - \`approved\`: Set to \`true\` ONLY if the review contains no actionable feedback \u2014 neither inline comments nor actionable content in the body. An approval signals "no changes needed." +7. **SUBMIT** \u2014 Determine whether to submit a review: + - **Issues found**: Submit via ${ghPullfrogMcpName}/create_pull_request_review with \`approved: false\`, the inline comments from step 6, and an **empty body** \u2014 inline comments speak for themselves, and a top-level body clutters the PR conversation on every re-review cycle. Then call \`report_progress\` with a 1-sentence summary (e.g., "Re-reviewed \u2014 found 2 issues in the new commits."). + - **No issues found**: Do NOT submit a review. Call \`report_progress\` with a brief note (e.g., "Re-reviewed \u2014 no new issues found."). ${permalinkTip} ` @@ -148797,9 +148807,7 @@ Your job is to fix issues THIS PR introduced, not to fix all CI failures. If in - **Draft PR request**: If the user explicitly asks for a draft PR (e.g. "draft PR", "create as draft", "WIP"), create a PR with \`draft: true\`. - **Branch-only request**: If the user explicitly asks for a branch without a PR (e.g. "don't create a PR", "branch only", "just create a branch"), do NOT create a PR. Simply push the branch and report the branch link. -5. **PROGRESS** - ${reportProgressInstruction} - -Do NOT overwrite a good comment with links/details with a generic message like "I have completed the task." If your previous report_progress call already contains all the necessary information and links, skip the final call entirely.` +5. **PROGRESS** - ${reportProgressInstruction}` }, { name: "Summarize", @@ -148814,6 +148822,8 @@ Do NOT overwrite a good comment with links/details with a generic message like " 4. **POST** - Call ${ghPullfrogMcpName}/create_issue_comment with type: 'Summary' and the summary body. +5. **PROGRESS** - ${reportProgressInstruction} + ${permalinkTip}` } ]; @@ -149160,6 +149170,13 @@ async function runOpenCode(params) { if (event.part?.state?.status === "completed" && event.part.state.output) { log.debug(` output: ${event.part.state.output}`); } + if (toolName.includes("report_progress") && params.todoTracker) { + log.debug("\xBB report_progress detected, disabling todo tracking"); + params.todoTracker.cancel(); + } + if (toolName === "todowrite" && params.todoTracker?.enabled) { + params.todoTracker.update(event.part?.state?.input); + } }, tool_result: (event) => { const toolId = event.part?.callID || event.tool_id; @@ -149284,6 +149301,11 @@ async function runOpenCode(params) { } } }); + if (result.exitCode === 0) { + await params.todoTracker?.flush(); + } else { + params.todoTracker?.cancel(); + } const duration4 = performance6.now() - startTime; log.info( `\xBB ${params.label} completed in ${Math.round(duration4)}ms with exit code ${result.exitCode}` @@ -149327,6 +149349,7 @@ ${stderrContext}`); } return { success: true, output: finalOutput || output, usage }; } catch (error49) { + params.todoTracker?.cancel(); const duration4 = performance6.now() - startTime; const errorMessage = error49 instanceof Error ? error49.message : String(error49); const isActivityTimeout = errorMessage.includes("activity timeout"); @@ -149376,7 +149399,8 @@ var opentoad = agent({ cliPath, args: args2, cwd: repoDir, - env: env2 + env: env2, + todoTracker: ctx.todoTracker }); } }); @@ -149699,7 +149723,7 @@ function buildRuntimeContext(ctx) { github_workflow: process.env.GITHUB_WORKFLOW }; const filtered = Object.fromEntries(Object.entries(data).filter(([_2, v]) => v !== void 0)); - return encode3(filtered); + return encode(filtered); } function buildEventTitleBody(event) { const sections = []; @@ -149719,7 +149743,7 @@ function buildEventMetadata(event) { if (Object.keys(restWithTrigger).length === 0) { return ""; } - return encode3(restWithTrigger); + return encode(restWithTrigger); } function getShellInstructions(shell) { switch (shell) { @@ -149829,7 +149853,13 @@ When posting comments via ${ghPullfrogMcpName}, write as a professional team mem ### Progress reporting -ALWAYS use \`report_progress\` to share your results and progress \u2014 never \`create_issue_comment\`. The \`report_progress\` tool updates the pre-created progress comment on the issue/PR. Using \`create_issue_comment\` instead creates duplicate comments and leaves the progress comment stuck in its initial state. The \`create_issue_comment\` tool is only for creating NEW standalone comments unrelated to your task progress. +**Task list**: at the start of every run, create an internal task list based on the steps in your current mode. Update it as you complete each step. The system automatically renders this list to the progress comment \u2014 you do not need to call \`report_progress\` for this. + +**\`report_progress\`**: you MUST call this exactly once at the end of every run with a brief final summary (1-3 sentences). Never call it for intermediate status updates (e.g., "Checking for changes...", "Starting review...") \u2014 the task list handles live progress automatically. Calling \`report_progress\` replaces the task list with your summary and preserves the completed task list in a collapsible section. Keep the summary concise \u2014 do not repeat what the task list already shows. Focus on the outcome (what was accomplished, links to artifacts) rather than listing individual steps. + +Never use \`create_issue_comment\` for task progress \u2014 that creates duplicate comments and leaves the progress comment stuck in its initial state. \`create_issue_comment\` is only for standalone comments unrelated to your current task (e.g., Plan comments, PR Summary comments). + +**After a PR review is submitted**, still call \`report_progress\` with your final summary. The progress comment persists as a record of what was done. ### If you get stuck @@ -149932,8 +149962,6 @@ ${ctx.modes.map((m) => `- "${m.name}": ${m.description}`).join("\n")} Follow the mode guidance to complete the task. Use your native file and shell tools for local operations, and the ${ghPullfrogMcpName} MCP tools for GitHub/git operations. -When done, call \`${ghPullfrogMcpName}/set_output\` with the final result. This makes it available as the GitHub Action output. - ### No-action cases If the task clearly requires no work, call \`${ghPullfrogMcpName}/report_progress\` directly to explain why no action is needed.`; @@ -150239,7 +150267,6 @@ async function postReviewCleanup(ctx) { "follow-up re-review dispatch" ); } - await bestEffort(() => deleteProgressComment(ctx), "delete progress comment"); } async function bestEffort(fn2, label) { try { @@ -150301,7 +150328,7 @@ async function handleAgentResult(ctx) { output: ctx.result.output }; } - if (!ctx.toolState.wasUpdated && ctx.toolState.progressCommentId && !ctx.silent) { + if (!ctx.toolState.wasUpdated && ctx.toolState.hadProgressComment && !ctx.silent) { const error49 = ctx.result.error || "agent completed without reporting progress"; try { await reportErrorToComment({ @@ -150495,6 +150522,123 @@ function parseTimeString(input) { return (hours * 3600 + minutes * 60 + seconds) * 1e3; } +// utils/todoTracking.ts +function isValidTodoStatus(value2) { + return value2 === "pending" || value2 === "in_progress" || value2 === "completed" || value2 === "cancelled"; +} +function parseTodowriteInput(input) { + if (!input || typeof input !== "object" || !("todos" in input)) return void 0; + if (!Array.isArray(input.todos)) return void 0; + const merge4 = "merge" in input && input.merge === true; + return { todos: input.todos, merge: merge4 }; +} +function parseTodoItem(entry, index) { + if (!entry || typeof entry !== "object") return void 0; + if (!("content" in entry) || typeof entry.content !== "string") return void 0; + const id = "id" in entry && typeof entry.id === "string" ? entry.id : String(index); + const status = "status" in entry && typeof entry.status === "string" && isValidTodoStatus(entry.status) ? entry.status : "pending"; + return { id, content: entry.content, status }; +} +function renderTodoMarkdown(todos) { + return todos.map((todo) => { + switch (todo.status) { + case "completed": + return `- [x] ${todo.content}`; + case "cancelled": + return `- ~~${todo.content}~~`; + case "in_progress": + return `- **\u2192** ${todo.content}`; + case "pending": + return `- [ ] ${todo.content}`; + default: + todo.status; + return `- [ ] ${todo.content}`; + } + }).join("\n"); +} +var DEBOUNCE_MS = 2e3; +function createTodoTracker(onUpdate) { + const state = /* @__PURE__ */ new Map(); + let enabled = true; + let hasPublished = false; + let debounceTimer = null; + let inflightPromise = Promise.resolve(); + function scheduleUpdate() { + if (!enabled) return; + if (debounceTimer) clearTimeout(debounceTimer); + debounceTimer = setTimeout(() => { + debounceTimer = null; + if (!enabled || state.size === 0) return; + const markdown = renderTodoMarkdown(Array.from(state.values())); + inflightPromise = inflightPromise.then(async () => { + if (!enabled) return; + await onUpdate(markdown); + hasPublished = true; + }).catch((err) => { + log.debug(`todo progress update failed: ${err}`); + }); + }, DEBOUNCE_MS); + } + return { + update(input) { + if (!enabled) return; + const parsed2 = parseTodowriteInput(input); + if (!parsed2) return; + if (!parsed2.merge) state.clear(); + for (const [index, entry] of parsed2.todos.entries()) { + const item = parseTodoItem(entry, index); + if (item) state.set(item.id, item); + } + log.debug(`\xBB todowrite: ${state.size} items tracked`); + scheduleUpdate(); + }, + async flush() { + if (debounceTimer) { + clearTimeout(debounceTimer); + debounceTimer = null; + } + if (!enabled || state.size === 0) return; + const markdown = renderTodoMarkdown(Array.from(state.values())); + inflightPromise = inflightPromise.then(async () => { + if (!enabled) return; + await onUpdate(markdown); + hasPublished = true; + }).catch((err) => { + log.debug(`todo progress flush failed: ${err}`); + }); + await inflightPromise; + }, + cancel() { + enabled = false; + if (debounceTimer) { + clearTimeout(debounceTimer); + debounceTimer = null; + } + }, + async settled() { + await inflightPromise; + }, + renderCollapsible() { + if (state.size === 0) return ""; + const todos = Array.from(state.values()); + const completed = todos.filter((t) => t.status === "completed").length; + const markdown = renderTodoMarkdown(todos); + return `
+Task list (${completed}/${todos.length} completed) + +${markdown} + +
`; + }, + get enabled() { + return enabled; + }, + get hasPublished() { + return hasPublished; + } + }; +} + // utils/workflow.ts async function resolveRun(params) { const runId = process.env.GITHUB_RUN_ID ? Number.parseInt(process.env.GITHUB_RUN_ID, 10) : void 0; @@ -150624,6 +150768,8 @@ async function main() { const octokit = createOctokit(tokenRef.mcpToken); const runInfo = await resolveRun({ octokit }); let toolContext; + let progressCallbackDisabled = false; + let todoTracker; try { var _stack = []; try { @@ -150713,11 +150859,21 @@ ${instructions.user}` : null, }); activityTimeout.promise.catch(() => { }); + todoTracker = createTodoTracker(async (body) => { + if (progressCallbackDisabled || !toolContext) return; + try { + await reportProgress(toolContext, { body }); + } catch (err) { + log.debug(`progress update failed: ${err}`); + } + }); + toolState.todoTracker = todoTracker; const agentPromise = agent2.run({ payload, mcpServerUrl: mcpHttpServer.url, tmpdir: tmpdir2, - instructions + instructions, + todoTracker }); let result; if (payload.timeout === TIMEOUT_DISABLED) { @@ -150756,6 +150912,12 @@ ${instructions.user}` : null, log.debug(`post-review cleanup failed: ${error49}`); }); } + const trackerWasLastWriter = todoTracker?.hasPublished && !toolState.finalSummaryWritten; + if (toolContext && toolState.progressCommentId && (!toolState.wasUpdated || trackerWasLastWriter)) { + await deleteProgressComment(toolContext).catch((error49) => { + log.debug(`stranded progress comment cleanup failed: ${error49}`); + }); + } await writeJobSummary(toolState); if (toolState.output) { log.info(`::pullfrog-output::${Buffer.from(toolState.output).toString("base64")}`); @@ -150774,6 +150936,8 @@ ${instructions.user}` : null, } } catch (error49) { const errorMessage = error49 instanceof Error ? error49.message : "unknown error occurred"; + progressCallbackDisabled = true; + todoTracker?.cancel(); killTrackedChildren(); log.error(errorMessage); try { diff --git a/main.ts b/main.ts index 65d2bd8..843241d 100644 --- a/main.ts +++ b/main.ts @@ -1,6 +1,7 @@ // changes to tool permissions should be reflected in wiki/granular-tools.md import * as core from "@actions/core"; +import { deleteProgressComment, reportProgress } from "./mcp/comment.ts"; import { initToolState, startMcpHttpServer, @@ -35,6 +36,7 @@ import { createTempDirectory, setupGit } from "./utils/setup.ts"; import { killTrackedChildren } from "./utils/subprocess.ts"; import { parseTimeString, TIMEOUT_DISABLED } from "./utils/time.ts"; import { Timer } from "./utils/timer.ts"; +import { createTodoTracker } from "./utils/todoTracking.ts"; import { getJobToken, resolveTokens } from "./utils/token.ts"; import { resolveRun } from "./utils/workflow.ts"; @@ -203,6 +205,8 @@ export async function main(): Promise { const runInfo = await resolveRun({ octokit }); let toolContext: ToolContext | undefined; + let progressCallbackDisabled = false; + let todoTracker: ReturnType | undefined; try { if (payload.cwd && process.cwd() !== payload.cwd) { @@ -309,11 +313,22 @@ export async function main(): Promise { checkIntervalMs: DEFAULT_ACTIVITY_CHECK_INTERVAL_MS, }); activityTimeout.promise.catch(() => {}); // prevent unhandled rejection if agent wins race + todoTracker = createTodoTracker(async (body) => { + if (progressCallbackDisabled || !toolContext) return; + try { + await reportProgress(toolContext, { body }); + } catch (err) { + log.debug(`progress update failed: ${err}`); + } + }); + toolState.todoTracker = todoTracker; + const agentPromise = agent.run({ payload, mcpServerUrl: mcpHttpServer.url, tmpdir, instructions, + todoTracker, }); // timeout enforcement: default is 1 hour, but can be overridden via flags in the prompt: @@ -355,7 +370,7 @@ export async function main(): Promise { ); } - // post-agent review cleanup: reportReviewNodeId → follow-up dispatch → delete progress comment. + // post-agent review cleanup: reportReviewNodeId → follow-up re-review dispatch. // runs after the agent exits so ordering is architecturally guaranteed (no LLM involvement). // best-effort: cleanup failures must not turn a successful agent run into a failure. if (toolContext) { @@ -364,6 +379,25 @@ export async function main(): Promise { }); } + // clean up stranded progress comments. two cases: + // 1. wasUpdated=false: nothing wrote to the comment ("Leaping into action" orphan) + // 2. tracker published a checklist but the agent never wrote a final summary + // (hasPublished=true, finalSummaryWritten=false). + // in both cases, delete the comment so it doesn't linger with stale content. + // wasUpdated is intentionally NOT set here — cleanup is not a real progress update. + // uses finalSummaryWritten (not todoTracker.enabled) so cleanup survives API failures + // in report_progress where cancel() ran but the write didn't succeed. + const trackerWasLastWriter = todoTracker?.hasPublished && !toolState.finalSummaryWritten; + if ( + toolContext && + toolState.progressCommentId && + (!toolState.wasUpdated || trackerWasLastWriter) + ) { + await deleteProgressComment(toolContext).catch((error) => { + log.debug(`stranded progress comment cleanup failed: ${error}`); + }); + } + await writeJobSummary(toolState); // emit structured output marker for test validation @@ -379,6 +413,8 @@ export async function main(): Promise { }); } catch (error) { const errorMessage = error instanceof Error ? error.message : "unknown error occurred"; + progressCallbackDisabled = true; + todoTracker?.cancel(); killTrackedChildren(); log.error(errorMessage); diff --git a/mcp/comment.ts b/mcp/comment.ts index 4cf11bb..873b5cd 100644 --- a/mcp/comment.ts +++ b/mcp/comment.ts @@ -329,7 +329,7 @@ export async function reportProgress( }; } - // null = progress comment was deliberately deleted (e.g. by create_pull_request_review) + // null = progress comment was deleted by stranded-comment cleanup in main.ts if (existingCommentId === null) { return { body, action: "skipped" }; } @@ -400,17 +400,33 @@ export function ReportProgressTool(ctx: ToolContext) { return tool({ name: "report_progress", description: - "Share progress on the associated GitHub issue/PR. Call this to post updates as you work. The first call creates a comment, subsequent calls update it. Use this throughout your work to keep stakeholders informed.", + "Share progress on the associated GitHub issue/PR. The first call creates a comment; subsequent calls update it in place. You MUST call this at the end of every run with a brief final summary (1-3 sentences). The completed task list is automatically appended in a collapsible section — do not restate individual steps.", parameters: ReportProgress, execute: execute(async (params) => { - const reportParams: { body: string; target_plan_comment?: boolean } = { body: params.body }; + let body = params.body; + + // for non-plan calls: stop auto-updates, wait for in-flight writes to settle, + // then append completed task list collapsible + if (!params.target_plan_comment && ctx.toolState.todoTracker) { + ctx.toolState.todoTracker.cancel(); + await ctx.toolState.todoTracker.settled(); + const collapsible = ctx.toolState.todoTracker.renderCollapsible(); + if (collapsible) { + body = `${body}\n\n${collapsible}`; + } + } + + const reportParams: { body: string; target_plan_comment?: boolean } = { body }; if (params.target_plan_comment !== undefined) { reportParams.target_plan_comment = params.target_plan_comment; } const result = await reportProgress(ctx, reportParams); + if (!params.target_plan_comment) { + ctx.toolState.finalSummaryWritten = true; + } + if (result.action === "skipped") { - // no-op: no comment target, but progress is still tracked for job summary return { success: true, message: @@ -428,9 +444,9 @@ export function ReportProgressTool(ctx: ToolContext) { /** * Delete the progress comment if it exists. - * Used after submitting a PR review since the review body contains all necessary info. - * Sets progressCommentId to null, which prevents future report_progress calls from - * creating a new comment (the agent may call report_progress again after this). + * Used by main.ts for stranded-comment cleanup (orphaned "Leaping into action" or + * checklist left by the todo tracker when the agent didn't call report_progress). + * Sets progressCommentId to null so subsequent report_progress calls are no-ops. */ export async function deleteProgressComment(ctx: ToolContext): Promise { const existingCommentId = ctx.toolState.progressCommentId; @@ -455,7 +471,6 @@ export async function deleteProgressComment(ctx: ToolContext): Promise // set to null (not undefined) so report_progress skips instead of creating a new comment ctx.toolState.progressCommentId = null; - ctx.toolState.wasUpdated = true; return true; } diff --git a/mcp/review.ts b/mcp/review.ts index 0c6fba6..eb3080a 100644 --- a/mcp/review.ts +++ b/mcp/review.ts @@ -70,6 +70,7 @@ export function CreatePullRequestReviewTool(ctx: ToolContext) { description: "Submit a review for an existing pull request. " + "Each call creates a permanent, visible review on the PR — NEVER submit test or diagnostic reviews. " + + "Reviews with no body AND no comments are silently skipped (nothing to post). " + "IMPORTANT: 95%+ of feedback should be in 'comments' array with file paths and line numbers. " + "Only use 'body' for a 1-2 sentence summary with urgency and critical callouts. " + "Use 'suggestion' to propose replacement code - MUST preserve exact indentation of original code. " + diff --git a/mcp/selectMode.ts b/mcp/selectMode.ts index c30738d..94324d2 100644 --- a/mcp/selectMode.ts +++ b/mcp/selectMode.ts @@ -111,10 +111,9 @@ ${learningsStep(6)}`, 3. Self-critique: review all drafted comments and drop any that are praise, style preferences, speculative/unverified claims, about pre-existing code unrelated to the PR, or not actionable. -4. Submit a **single** review: - - call \`${ghPullfrogMcpName}/create_pull_request_review\` with all comments and a unified summary body - - call \`${ghPullfrogMcpName}/report_progress\` with the summary - - if no actionable issues found, skip the review — just call \`report_progress\` noting the PR was reviewed`, +4. Submit: + - **actionable issues found**: call \`${ghPullfrogMcpName}/create_pull_request_review\` with all comments, a 1-3 sentence summary body, and \`approved: false\`. Then call \`report_progress\` with a 1-sentence summary. + - **no actionable issues found**: do NOT submit a review. Call \`${ghPullfrogMcpName}/report_progress\` with a brief note (e.g., "Reviewed — no issues found.").`, IncrementalReview: `### Checklist @@ -134,10 +133,9 @@ ${learningsStep(6)}`, 5. Self-critique: drop any comments that are praise, style preferences, speculative, about pre-existing code, or not actionable. -6. Submit a **single** review: - - if actionable issues found: call \`${ghPullfrogMcpName}/create_pull_request_review\` with \`approved: false\`, all comments, and an **empty body** (do NOT include a summary — inline comments speak for themselves and a top-level comment clutters the PR conversation on every re-review) - - if no actionable issues found: submit with \`approved: true\` and an **empty body** (no inline comments, no summary) - - do NOT call \`${ghPullfrogMcpName}/report_progress\` — incremental reviews should be silent`, +6. Submit: + - **actionable issues found**: call \`${ghPullfrogMcpName}/create_pull_request_review\` with \`approved: false\`, all comments, and an **empty body** — inline comments speak for themselves, and a top-level body clutters the PR conversation on every re-review cycle. Then call \`report_progress\` with a 1-sentence summary. + - **no actionable issues found**: do NOT submit a review. Call \`${ghPullfrogMcpName}/report_progress\` with a brief note (e.g., "Re-reviewed — no new issues found.").`, Plan: `### Checklist @@ -209,8 +207,9 @@ ${learningsStep(4)}`, - PR metadata (title, file count, commit count, base/head branches) - format instructions from EVENT INSTRUCTIONS (if any); otherwise use default format: TL;DR, key changes list, per-change sections with plain-language \`##\` titles and before/after framing - instruct it to use the TOC to selectively read relevant diff sections, not the entire file - - instruct it to return the full summary markdown via \`${ghPullfrogMcpName}/set_output\` + - instruct it to return the full summary markdown as its final response 3. After the subagent completes, call \`${ghPullfrogMcpName}/create_issue_comment\` with \`type: "Summary"\` and the summary body. +4. Call \`${ghPullfrogMcpName}/report_progress\` with a brief note (e.g., "Posted PR summary."). ### Effort @@ -226,8 +225,9 @@ An existing summary comment was found for this PR. Update it rather than creatin - the diff file path and PR metadata - the existing summary body (\`previousSummaryBody\`) so it can update rather than rewrite from scratch - format instructions from EVENT INSTRUCTIONS (if any) - - instruct it to produce an updated summary reflecting the current state of the PR and return via \`${ghPullfrogMcpName}/set_output\` + - instruct it to produce an updated summary reflecting the current state of the PR and return it as its final response 4. After the subagent completes, call \`${ghPullfrogMcpName}/edit_issue_comment\` with \`commentId: existingSummaryCommentId\` (from this response) and the updated summary body. +5. Call \`${ghPullfrogMcpName}/report_progress\` with a brief note (e.g., "Updated PR summary."). ### Effort diff --git a/mcp/server.ts b/mcp/server.ts index c4c833c..e44486f 100644 --- a/mcp/server.ts +++ b/mcp/server.ts @@ -10,6 +10,7 @@ import { log } from "../utils/cli.ts"; import type { OctokitWithPlugins } from "../utils/github.ts"; import type { ResolvedPayload } from "../utils/payload.ts"; import type { RunContextData } from "../utils/runContextData.ts"; +import type { TodoTracker } from "../utils/todoTracking.ts"; import { CheckoutPrTool } from "./checkout.ts"; import { GetCheckSuiteLogsTool } from "./checkSuite.ts"; import { @@ -81,8 +82,14 @@ export interface ToolState { }; // undefined = no comment yet, number = active comment, null = deliberately deleted progressCommentId: number | null | undefined; + // immutable snapshot: true if a progress comment was pre-created at init time. + // survives deleteProgressComment so handleAgentResult can still detect "expected but never reported". + hadProgressComment: boolean; lastProgressBody?: string; wasUpdated?: boolean; + // set after a non-plan report_progress successfully writes the final summary. + // decoupled from todoTracker.enabled so cleanup detection survives API failures. + finalSummaryWritten?: boolean; // set by select_mode when Plan + issue_number and plan-comment API returns existing plan (for report_progress target_plan_comment) existingPlanCommentId?: number; previousPlanBody?: string; @@ -91,6 +98,7 @@ export interface ToolState { output?: string; usageEntries: AgentUsage[]; model?: string | undefined; + todoTracker?: TodoTracker | undefined; } interface InitToolStateParams { @@ -107,6 +115,7 @@ export function initToolState(params: InitToolStateParams): ToolState { return { progressCommentId: resolvedId, + hadProgressComment: !!resolvedId, backgroundProcesses: new Map(), usageEntries: [], }; @@ -192,9 +201,13 @@ function buildCommonTools(ctx: ToolContext, outputSchema?: JsonSchema): Tool" in the PR body to auto-close the issue when merged. - **Draft PR request**: If the user explicitly asks for a draft PR (e.g. "draft PR", "create as draft", "WIP"), create a PR with \`draft: true\`. - **Branch-only request**: If the user explicitly asks for a branch without a PR (e.g. "don't create a PR", "branch only", "just create a branch"), do NOT create a PR. Simply push the branch and report the branch link. -10. **FINAL REPORT** - Call report_progress one final time ONLY if you haven't already included all the important information (PR links, branch links, summary) in a previous report_progress call. If you already called report_progress with complete information including PR links after creating the PR, you do NOT need to call it again. Only make a final call if you need to add missing information. When making the final call, ensure it includes: +9. **FINAL REPORT** - ${reportProgressInstruction} Ensure the summary includes: - A summary of what was accomplished - Links to any artifacts created (PRs, branches, issues) - If you created a PR, ALWAYS include the PR link. e.g.: @@ -66,7 +64,6 @@ export function computeModes(): Mode[] { [\`pullfrog/branch-name\`](https://github.com/pullfrog/scratch/tree/pullfrog/branch-name) • [Create PR ➔](https://github.com/pullfrog/scratch/compare/main...pullfrog/branch-name?quick_pull=1&title=&body=) \`\`\` - Do NOT overwrite a good comment with links/details with a generic message like "I have completed the task. Please review the PR." If your previous report_progress call already contains all the necessary information and links, skip the final call entirely. `, }, { @@ -120,14 +117,13 @@ Keep the progress comment extremely brief. The summary should be 1-2 sentences m - **Impact analysis**: Identify what was removed, renamed, or deprecated in the PR. Use grep to search the broader codebase for remaining references to those things in code, tests, docs, comments, and configs. Report stale references in the review body. - Do NOT stop at "this looks reasonable." Dig until you either find a problem or have concrete evidence there isn't one. -4. **DRAFT LINE-BY-LINE COMMENTS** - Every comment must be actionable: the author should need to change something in response. 2-3 sentences max. Use the NEW line number from the diff (second column: \`| OLD | NEW | TYPE | CODE\`). If no issues found, skip to step 5. NO COMPLIMENTS. NO NITPICKING ABOUT CHANGES UNRELATED TO THE MAIN CHANGE. Non-actionable comments (praise, style preferences, minor optimizatfixons, documentation nits) must not be drafted. +4. **DRAFT LINE-BY-LINE COMMENTS** - Every comment must be actionable: the author should need to change something in response. 2-3 sentences max. Use the NEW line number from the diff (second column: \`| OLD | NEW | TYPE | CODE\`). If no issues found, skip to step 5. NO COMPLIMENTS. NO NITPICKING ABOUT CHANGES UNRELATED TO THE MAIN CHANGE. Non-actionable comments (praise, style preferences, minor optimizations, documentation nits) must not be drafted. 5. **WRITE SUMMARY** - Draft a 1-3 sentence summary for the review body. If issues were found, include urgency level and any concerns about code outside the diff. If no issues were found, write a brief approval summary (e.g., "Changes look good. No issues found."). -6. **SUBMIT** — Always submit a review via ${ghPullfrogMcpName}/create_pull_request_review: - - \`body\`: The summary from step 5 - - \`comments\`: The inline comments from step 4 - - \`approved\`: Set to \`true\` ONLY if the review contains no actionable feedback — neither inline comments nor actionable content in the body. An approval signals "no changes needed." +6. **SUBMIT** — Determine whether to submit a review: + - **Issues found**: Submit via ${ghPullfrogMcpName}/create_pull_request_review with the summary body from step 5, the inline comments from step 4, and \`approved: false\`. Then call \`report_progress\` with a 1-sentence summary (e.g., "Reviewed — found 3 issues."). + - **No issues found**: Do NOT submit a review. Call \`${ghPullfrogMcpName}/report_progress\` with a brief note (e.g., "Reviewed — no issues found."). ${permalinkTip} `, @@ -159,12 +155,9 @@ ${permalinkTip} 6. **DRAFT LINE-BY-LINE COMMENTS** - Every comment must be actionable. 2-3 sentences max. Use the NEW line number from the full PR diff. NO COMPLIMENTS. NO NITPICKING. -7. **WRITE SUMMARY** - Draft a 1-3 sentence summary for the review body. Focus on what changed since the last review and whether the new changes are sound. If issues were found, include urgency level. If no issues were found, write a brief approval summary. - -8. **SUBMIT** — Use ${ghPullfrogMcpName}/create_pull_request_review: - - \`body\`: The summary from step 7 - - \`comments\`: The inline comments from step 6 - - \`approved\`: Set to \`true\` ONLY if the review contains no actionable feedback — neither inline comments nor actionable content in the body. An approval signals "no changes needed." +7. **SUBMIT** — Determine whether to submit a review: + - **Issues found**: Submit via ${ghPullfrogMcpName}/create_pull_request_review with \`approved: false\`, the inline comments from step 6, and an **empty body** — inline comments speak for themselves, and a top-level body clutters the PR conversation on every re-review cycle. Then call \`report_progress\` with a 1-sentence summary (e.g., "Re-reviewed — found 2 issues in the new commits."). + - **No issues found**: Do NOT submit a review. Call \`report_progress\` with a brief note (e.g., "Re-reviewed — no new issues found."). ${permalinkTip} `, @@ -308,9 +301,7 @@ Your job is to fix issues THIS PR introduced, not to fix all CI failures. If in - **Draft PR request**: If the user explicitly asks for a draft PR (e.g. "draft PR", "create as draft", "WIP"), create a PR with \`draft: true\`. - **Branch-only request**: If the user explicitly asks for a branch without a PR (e.g. "don't create a PR", "branch only", "just create a branch"), do NOT create a PR. Simply push the branch and report the branch link. -5. **PROGRESS** - ${reportProgressInstruction} - -Do NOT overwrite a good comment with links/details with a generic message like "I have completed the task." If your previous report_progress call already contains all the necessary information and links, skip the final call entirely.`, +5. **PROGRESS** - ${reportProgressInstruction}`, }, { name: "Summarize", @@ -326,6 +317,8 @@ Do NOT overwrite a good comment with links/details with a generic message like " 4. **POST** - Call ${ghPullfrogMcpName}/create_issue_comment with type: 'Summary' and the summary body. +5. **PROGRESS** - ${reportProgressInstruction} + ${permalinkTip}`, }, ]; diff --git a/post b/post index 8f445c1..6934957 100755 --- a/post +++ b/post @@ -41752,10 +41752,15 @@ async function validateStuckProgressComment(params) { repo: params.repo, comment_id: commentId }); - if (commentResult.data.body?.startsWith(LEAPING_INTO_ACTION_PREFIX)) { + const body = commentResult.data.body ?? ""; + if (body.startsWith(LEAPING_INTO_ACTION_PREFIX)) { log.info(`[post] comment ${commentId} is stuck on "Leaping into action"`); return commentId; } + if (/^- \[[ x]\] |^- \*\*→\*\* |^- ~~/.test(body)) { + log.info(`[post] comment ${commentId} is stuck on a todo checklist`); + return commentId; + } log.info(`[post] comment ${commentId} is not stuck (already updated or different content)`); return null; } catch (error2) { diff --git a/utils/instructions.ts b/utils/instructions.ts index 5489216..53b9c6a 100644 --- a/utils/instructions.ts +++ b/utils/instructions.ts @@ -212,7 +212,13 @@ When posting comments via ${ghPullfrogMcpName}, write as a professional team mem ### Progress reporting -ALWAYS use \`report_progress\` to share your results and progress — never \`create_issue_comment\`. The \`report_progress\` tool updates the pre-created progress comment on the issue/PR. Using \`create_issue_comment\` instead creates duplicate comments and leaves the progress comment stuck in its initial state. The \`create_issue_comment\` tool is only for creating NEW standalone comments unrelated to your task progress. +**Task list**: at the start of every run, create an internal task list based on the steps in your current mode. Update it as you complete each step. The system automatically renders this list to the progress comment — you do not need to call \`report_progress\` for this. + +**\`report_progress\`**: you MUST call this exactly once at the end of every run with a brief final summary (1-3 sentences). Never call it for intermediate status updates (e.g., "Checking for changes...", "Starting review...") — the task list handles live progress automatically. Calling \`report_progress\` replaces the task list with your summary and preserves the completed task list in a collapsible section. Keep the summary concise — do not repeat what the task list already shows. Focus on the outcome (what was accomplished, links to artifacts) rather than listing individual steps. + +Never use \`create_issue_comment\` for task progress — that creates duplicate comments and leaves the progress comment stuck in its initial state. \`create_issue_comment\` is only for standalone comments unrelated to your current task (e.g., Plan comments, PR Summary comments). + +**After a PR review is submitted**, still call \`report_progress\` with your final summary. The progress comment persists as a record of what was done. ### If you get stuck @@ -367,8 +373,6 @@ ${ctx.modes.map((m) => `- "${m.name}": ${m.description}`).join("\n")} Follow the mode guidance to complete the task. Use your native file and shell tools for local operations, and the ${ghPullfrogMcpName} MCP tools for GitHub/git operations. -When done, call \`${ghPullfrogMcpName}/set_output\` with the final result. This makes it available as the GitHub Action output. - ### No-action cases If the task clearly requires no work, call \`${ghPullfrogMcpName}/report_progress\` directly to explain why no action is needed.`; diff --git a/utils/postCleanup.ts b/utils/postCleanup.ts index a364e98..612644a 100644 --- a/utils/postCleanup.ts +++ b/utils/postCleanup.ts @@ -70,11 +70,20 @@ async function validateStuckProgressComment( comment_id: commentId, }); - if (commentResult.data.body?.startsWith(LEAPING_INTO_ACTION_PREFIX)) { + const body = commentResult.data.body ?? ""; + + if (body.startsWith(LEAPING_INTO_ACTION_PREFIX)) { log.info(`[post] comment ${commentId} is stuck on "Leaping into action"`); return commentId; } + // detect stranded todo checklists left by the tracker when the process was killed + // before the agent could call report_progress with a final summary + if (/^- \[[ x]\] |^- \*\*→\*\* |^- ~~/.test(body)) { + log.info(`[post] comment ${commentId} is stuck on a todo checklist`); + return commentId; + } + log.info(`[post] comment ${commentId} is not stuck (already updated or different content)`); return null; } catch (error) { diff --git a/utils/reviewCleanup.ts b/utils/reviewCleanup.ts index d5f314a..210e5aa 100644 --- a/utils/reviewCleanup.ts +++ b/utils/reviewCleanup.ts @@ -1,5 +1,4 @@ import type { WriteablePayload } from "../external.ts"; -import { deleteProgressComment } from "../mcp/comment.ts"; import { reportReviewNodeId } from "../mcp/review.ts"; import type { ToolContext } from "../mcp/server.ts"; import { log } from "./cli.ts"; @@ -34,8 +33,6 @@ export async function postReviewCleanup(ctx: ToolContext): Promise { "follow-up re-review dispatch" ); } - - await bestEffort(() => deleteProgressComment(ctx), "delete progress comment"); } async function bestEffort(fn: () => Promise, label: string): Promise { diff --git a/utils/run.ts b/utils/run.ts index ece4d1d..a8a1b40 100644 --- a/utils/run.ts +++ b/utils/run.ts @@ -19,7 +19,7 @@ export async function handleAgentResult(ctx: HandleAgentResultParams): Promise { + switch (todo.status) { + case "completed": + return `- [x] ${todo.content}`; + case "cancelled": + return `- ~~${todo.content}~~`; + case "in_progress": + return `- **→** ${todo.content}`; + case "pending": + return `- [ ] ${todo.content}`; + default: + todo.status satisfies never; + return `- [ ] ${todo.content}`; + } + }) + .join("\n"); +} + +export type TodoTracker = { + update: (input: unknown) => void; + flush: () => Promise; + cancel: () => void; + /** resolves when any in-flight onUpdate call completes */ + settled: () => Promise; + renderCollapsible: () => string; + readonly enabled: boolean; + /** true after the tracker has successfully called onUpdate at least once */ + readonly hasPublished: boolean; +}; + +const DEBOUNCE_MS = 2000; + +export function createTodoTracker(onUpdate: (body: string) => Promise): TodoTracker { + const state = new Map(); + let enabled = true; + let hasPublished = false; + let debounceTimer: ReturnType | null = null; + let inflightPromise: Promise = Promise.resolve(); + + function scheduleUpdate() { + if (!enabled) return; + if (debounceTimer) clearTimeout(debounceTimer); + debounceTimer = setTimeout(() => { + debounceTimer = null; + if (!enabled || state.size === 0) return; + const markdown = renderTodoMarkdown(Array.from(state.values())); + inflightPromise = inflightPromise + .then(async () => { + if (!enabled) return; + await onUpdate(markdown); + hasPublished = true; + }) + .catch((err) => { + log.debug(`todo progress update failed: ${err}`); + }); + }, DEBOUNCE_MS); + } + + return { + update(input: unknown) { + if (!enabled) return; + const parsed = parseTodowriteInput(input); + if (!parsed) return; + if (!parsed.merge) state.clear(); + for (const [index, entry] of parsed.todos.entries()) { + const item = parseTodoItem(entry, index); + if (item) state.set(item.id, item); + } + log.debug(`» todowrite: ${state.size} items tracked`); + scheduleUpdate(); + }, + + async flush() { + if (debounceTimer) { + clearTimeout(debounceTimer); + debounceTimer = null; + } + if (!enabled || state.size === 0) return; + const markdown = renderTodoMarkdown(Array.from(state.values())); + inflightPromise = inflightPromise + .then(async () => { + if (!enabled) return; + await onUpdate(markdown); + hasPublished = true; + }) + .catch((err) => { + log.debug(`todo progress flush failed: ${err}`); + }); + await inflightPromise; + }, + + cancel() { + enabled = false; + if (debounceTimer) { + clearTimeout(debounceTimer); + debounceTimer = null; + } + }, + + async settled() { + await inflightPromise; + }, + + renderCollapsible(): string { + if (state.size === 0) return ""; + const todos = Array.from(state.values()); + const completed = todos.filter((t) => t.status === "completed").length; + const markdown = renderTodoMarkdown(todos); + return `
\nTask list (${completed}/${todos.length} completed)\n\n${markdown}\n\n
`; + }, + + get enabled() { + return enabled; + }, + + get hasPublished() { + return hasPublished; + }, + }; +}