diff --git a/.agentic-snapshot/.gitignore b/.agentic-snapshot/.gitignore
new file mode 100644
index 00000000..e34370a3
--- /dev/null
+++ b/.agentic-snapshot/.gitignore
@@ -0,0 +1,2 @@
+# Snapshot dist files are local backups, not git-tracked
+*.js
diff --git a/.agentic-snapshot/README.md b/.agentic-snapshot/README.md
new file mode 100644
index 00000000..5e9e8bb5
--- /dev/null
+++ b/.agentic-snapshot/README.md
@@ -0,0 +1,41 @@
+# Deep Code Agentic 能力快照
+
+此目录保存了 Agentic 两大能力的备份。
+
+## 能力
+
+1. **Plan→Execute→Verify 循环** — 系统提示增强,LLM 自动先规划、每步验证、失败必修
+2. **自动错误修复循环** — 命令失败自动分析错误、注入修复提醒、重试最多 3 轮
+
+## 备份文件 (本地)
+
+- `cli.js` — CLI 构建产物
+- `prompt.js` — 带 Agentic 行为提示的 prompt 模块
+- `session.js` — 带错误修复循环的 session 模块
+- `bash-handler.js` — 带错误分析的 bash 处理器
+- `restore-agentic.bat` — 一键恢复脚本
+
+## 如何恢复
+
+### 方式 1: 运行恢复脚本
+```
+双击 .agentic-snapshot\restore-agentic.bat
+```
+
+### 方式 2: 从 Git 还原
+```bash
+git checkout 4668f5b -- packages/core/src/prompt.ts packages/core/src/session.ts packages/core/src/tools/bash-handler.ts
+cd packages/cli && npm link && cd .. && npm run build
+```
+
+### 方式 3: 手动 npm link
+```bash
+cd deepcode-cli-source/packages/cli
+npm link
+```
+
+## Git 提交
+
+```
+4668f5b feat(core): 实现两大 Agentic 核心能力
+```
diff --git a/.agentic-snapshot/bash-handler.js b/.agentic-snapshot/bash-handler.js
new file mode 100644
index 00000000..2197b075
--- /dev/null
+++ b/.agentic-snapshot/bash-handler.js
@@ -0,0 +1,434 @@
+import { spawn } from "child_process";
+import { randomUUID } from "crypto";
+import * as fs from "fs";
+import * as os from "os";
+import * as path from "path";
+import { DEFAULT_BASH_TIMEOUT_MS, clampBashTimeoutMs } from "../common/bash-timeout.js";
+import { killProcessTree } from "../common/process-tree.js";
+import { buildDisableExtglobCommand, buildShellEnv, buildShellInitCommand, resolveShellPath, rewriteWindowsNullRedirect, toNativeCwd, } from "../common/shell-utils.js";
+const MAX_OUTPUT_CHARS = 30000;
+const MAX_CAPTURE_CHARS = 10 * 1024 * 1024;
+const BACKGROUND_OUTPUT_DIR = path.join(os.tmpdir(), "deepcode-background");
+const TRAILING_BACKGROUND_OPERATOR_PATTERN = /(^|[^\\&])\s*&\s*$/;
+const sessionWorkingDirs = new Map();
+export function clearSessionWorkingDir(sessionId) {
+ if (!sessionId) {
+ return;
+ }
+ sessionWorkingDirs.delete(sessionId);
+}
+export async function handleBashTool(args, context) {
+ const rawCommand = typeof args.command === "string" ? args.command : "";
+ const runInBackground = isTrue(args.run_in_background);
+ const command = runInBackground ? stripTrailingBackgroundOperator(rawCommand) : rawCommand;
+ if (!command.trim()) {
+ return {
+ ok: false,
+ name: "bash",
+ error: 'Missing required "command" string.',
+ };
+ }
+ const startCwd = getSessionCwd(context.sessionId, context.projectRoot);
+ const { shellPath, shellArgs, marker } = buildShellCommand(command);
+ if (runInBackground) {
+ return startBackgroundShellCommand(shellPath, shellArgs, startCwd, command, marker, context);
+ }
+ const execution = await executeShellCommand(shellPath, shellArgs, startCwd, command, context);
+ const result = buildToolCommandResultWithAnalysis(execution.stdout, execution.stderr, marker, execution.exitCode, execution.signal, shellPath, startCwd, execution.timedOut, execution.timeoutMs, execution.deadlineAtMs);
+ updateSessionCwd(context.sessionId, startCwd, result.cwd);
+ if (execution.error || result.exitCode !== 0 || result.signal !== null) {
+ const errorMessage = buildErrorMessage(result.exitCode, result.signal, execution.error, execution.timedOut);
+ return formatResult({ ...result, ok: false }, "bash", errorMessage);
+ }
+ return formatResult(result, "bash");
+}
+/**
+ * Extract structured error pattern information from command output.
+ * Helps the LLM identify the root cause of failures more quickly.
+ */
+function extractErrorAnalysis(output, exitCode) {
+ if (!output || exitCode === 0) {
+ return undefined;
+ }
+ const lines = output.split(/\r?\n/);
+ const errorLines = [];
+ let lineCount = 0;
+ // Collect error-like lines (common patterns across languages/tools)
+ for (const line of lines) {
+ const lower = line.toLowerCase();
+ if (/error|exception|traceback|failed|failure|not found|syntax\s*error|cannot\s+find|undefined|ts\d+|ts error/i.test(lower)) {
+ errorLines.push(line.trim());
+ lineCount++;
+ if (lineCount >= 10)
+ break; // limit to top 10 error lines
+ }
+ }
+ if (errorLines.length === 0)
+ return undefined;
+ return errorLines.join("\n");
+}
+function buildToolCommandResultWithAnalysis(stdout, stderr, marker, exitCode, signal, shellPath, startCwd, timedOut = false, timeoutMs, deadlineAtMs) {
+ const result = buildToolCommandResult(stdout, stderr, marker, exitCode, signal, shellPath, startCwd, timedOut, timeoutMs, deadlineAtMs);
+ // Attach error analysis for failed commands
+ if (exitCode !== 0 && signal === null && !timedOut) {
+ const analysis = extractErrorAnalysis(result.output, exitCode);
+ if (analysis) {
+ // Prepend error analysis to the output so the LLM sees it first
+ result.output = `\n${analysis}\n\n\n${result.output}`;
+ }
+ }
+ return result;
+}
+function isTrue(value) {
+ return value === true || value === "true";
+}
+function stripTrailingBackgroundOperator(command) {
+ return command.replace(TRAILING_BACKGROUND_OPERATOR_PATTERN, "$1").trimEnd();
+}
+function getSessionCwd(sessionId, fallback) {
+ return sessionWorkingDirs.get(sessionId) ?? fallback;
+}
+function updateSessionCwd(sessionId, fallback, cwd) {
+ const nextCwd = cwd ?? fallback;
+ sessionWorkingDirs.set(sessionId, nextCwd);
+}
+function buildShellCommand(command) {
+ const shellPath = resolveShellPath();
+ const marker = buildMarker();
+ const initCommand = buildShellInitCommand(shellPath);
+ const disableExtglobCommand = buildDisableExtglobCommand(shellPath);
+ const normalizedCommand = rewriteWindowsNullRedirect(command);
+ const wrappedParts = [];
+ if (initCommand) {
+ wrappedParts.push(initCommand);
+ }
+ if (disableExtglobCommand) {
+ wrappedParts.push(disableExtglobCommand);
+ }
+ wrappedParts.push(normalizedCommand, "__DEEPCODE_STATUS__=$?", `printf '%s%s\\n' "${marker}" "$PWD"`, "exit $__DEEPCODE_STATUS__");
+ const wrappedCommand = `{ ${wrappedParts.join("; ")}; } < /dev/null`;
+ return { shellPath, shellArgs: ["-c", wrappedCommand], marker };
+}
+async function executeShellCommand(shellPath, shellArgs, cwd, command, context) {
+ return new Promise((resolve) => {
+ const detached = process.platform !== "win32";
+ const configuredEnv = context.createOpenAIClient?.().env ?? {};
+ const minTimeoutMs = context.bashMinTimeoutMs;
+ const initialTimeoutMs = clampBashTimeoutMs(context.bashTimeoutMs ?? DEFAULT_BASH_TIMEOUT_MS, minTimeoutMs);
+ const startedAtMs = Date.now();
+ let timeoutMs = initialTimeoutMs;
+ let deadlineAtMs = startedAtMs + timeoutMs;
+ let timedOut = false;
+ let settled = false;
+ let timeoutTimer = null;
+ const child = spawn(shellPath, shellArgs, {
+ cwd,
+ env: buildShellEnv(shellPath, configuredEnv),
+ detached,
+ windowsHide: true,
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ const pid = child.pid;
+ const getTimeoutInfo = () => ({
+ timeoutMs,
+ startedAtMs,
+ deadlineAtMs,
+ timedOut,
+ });
+ const stopTimeoutTimer = () => {
+ if (timeoutTimer) {
+ clearTimeout(timeoutTimer);
+ timeoutTimer = null;
+ }
+ };
+ const triggerTimeout = () => {
+ if (settled || timedOut || typeof pid !== "number") {
+ return;
+ }
+ timedOut = true;
+ stopTimeoutTimer();
+ killProcessTree(pid, "SIGKILL");
+ };
+ const scheduleTimeout = () => {
+ stopTimeoutTimer();
+ if (settled) {
+ return;
+ }
+ const remainingMs = Math.max(0, deadlineAtMs - Date.now());
+ timeoutTimer = setTimeout(triggerTimeout, remainingMs);
+ };
+ const timeoutControl = {
+ getInfo: getTimeoutInfo,
+ setTimeoutMs: (nextTimeoutMs) => {
+ timeoutMs = clampBashTimeoutMs(nextTimeoutMs, minTimeoutMs);
+ deadlineAtMs = startedAtMs + timeoutMs;
+ if (deadlineAtMs <= Date.now()) {
+ triggerTimeout();
+ }
+ else {
+ scheduleTimeout();
+ }
+ return getTimeoutInfo();
+ },
+ };
+ if (typeof pid === "number") {
+ context.onProcessStart?.(pid, command);
+ context.onProcessTimeoutControl?.(pid, timeoutControl);
+ scheduleTimeout();
+ }
+ let stdout = "";
+ let stderr = "";
+ let error;
+ child.stdout?.on("data", (chunk) => {
+ stdout = appendChunk(stdout, chunk);
+ const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
+ context.onProcessStdout?.(pid, text);
+ });
+ child.stderr?.on("data", (chunk) => {
+ stderr = appendChunk(stderr, chunk);
+ const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
+ context.onProcessStdout?.(pid, text);
+ });
+ child.on("error", (spawnError) => {
+ error = spawnError.message;
+ });
+ child.on("close", (code, signal) => {
+ settled = true;
+ stopTimeoutTimer();
+ if (typeof pid === "number") {
+ context.onProcessTimeoutControl?.(pid, null);
+ context.onProcessExit?.(pid);
+ }
+ resolve({
+ stdout,
+ stderr,
+ exitCode: typeof code === "number" ? code : null,
+ signal: signal ?? null,
+ error,
+ timedOut,
+ timeoutMs,
+ deadlineAtMs,
+ });
+ });
+ });
+}
+function startBackgroundShellCommand(shellPath, shellArgs, cwd, command, marker, context) {
+ fs.mkdirSync(BACKGROUND_OUTPUT_DIR, { recursive: true });
+ const taskId = `bash-${randomUUID()}`;
+ const outputPath = path.join(BACKGROUND_OUTPUT_DIR, `${taskId}.log`);
+ const startedAtMs = Date.now();
+ const detached = process.platform !== "win32";
+ const configuredEnv = context.createOpenAIClient?.().env ?? {};
+ const child = spawn(shellPath, shellArgs, {
+ cwd,
+ env: buildShellEnv(shellPath, configuredEnv),
+ detached,
+ windowsHide: true,
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ const pid = child.pid;
+ const processId = typeof pid === "number" ? pid : -1;
+ const stopCommand = typeof pid === "number" ? buildStopBackgroundProcessCommand(pid) : null;
+ let stdout = "";
+ let stderr = "";
+ let error;
+ const appendOutputFile = (chunk) => {
+ try {
+ fs.appendFileSync(outputPath, chunk);
+ }
+ catch {
+ // Keep the background process running even if temp-file writes fail.
+ }
+ };
+ if (typeof pid === "number") {
+ context.onProcessStart?.(pid, command);
+ }
+ child.stdout?.on("data", (chunk) => {
+ stdout = appendChunk(stdout, chunk);
+ appendOutputFile(chunk);
+ const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
+ if (typeof pid === "number") {
+ context.onProcessStdout?.(pid, text);
+ }
+ });
+ child.stderr?.on("data", (chunk) => {
+ stderr = appendChunk(stderr, chunk);
+ appendOutputFile(chunk);
+ const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
+ if (typeof pid === "number") {
+ context.onProcessStdout?.(pid, text);
+ }
+ });
+ child.on("error", (spawnError) => {
+ error = spawnError.message;
+ });
+ child.on("close", (code, signal) => {
+ const markerResult = stripMarker(stdout, marker);
+ const finalOutput = joinOutput(markerResult.output, stderr);
+ const result = buildToolCommandResult(stdout, stderr, marker, typeof code === "number" ? code : null, signal ?? null, shellPath, cwd);
+ updateSessionCwd(context.sessionId, cwd, result.cwd);
+ writeFinalBackgroundOutput(outputPath, finalOutput);
+ if (typeof pid === "number") {
+ context.onProcessExit?.(pid);
+ }
+ const ok = !error && result.exitCode === 0 && result.signal === null;
+ context.onBackgroundProcessComplete?.({
+ taskId,
+ processId,
+ command,
+ outputPath,
+ ok,
+ exitCode: result.exitCode,
+ signal: result.signal,
+ error: ok ? undefined : buildErrorMessage(result.exitCode, result.signal, error),
+ cwd: result.cwd,
+ shellPath,
+ startedAtMs,
+ completedAtMs: Date.now(),
+ });
+ });
+ return {
+ ok: true,
+ name: "bash",
+ output: buildBackgroundStartMessage(taskId, outputPath, stopCommand),
+ metadata: {
+ backgroundTaskId: taskId,
+ processId: typeof pid === "number" ? pid : null,
+ outputPath,
+ stopCommand,
+ cwd,
+ shellPath,
+ startCwd: cwd,
+ runInBackground: true,
+ },
+ };
+}
+function buildBackgroundStartMessage(taskId, outputPath, stopCommand) {
+ const parts = [`Command running in background with ID: ${taskId}.`];
+ if (stopCommand) {
+ parts.push(`Stop it with: ${stopCommand}`);
+ }
+ parts.push(`Output is being written to: ${outputPath}`);
+ return parts.join(" ");
+}
+function buildStopBackgroundProcessCommand(processId) {
+ if (process.platform === "win32") {
+ return `cmd.exe /c "taskkill /PID ${processId} /T /F"`;
+ }
+ return `kill -- -${processId}`;
+}
+function writeFinalBackgroundOutput(outputPath, output) {
+ try {
+ fs.writeFileSync(outputPath, output ?? "", "utf8");
+ }
+ catch {
+ // Ignore notification/output persistence failures; the tool result already returned.
+ }
+}
+function appendChunk(existing, chunk) {
+ if (existing.length >= MAX_CAPTURE_CHARS) {
+ return existing;
+ }
+ const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
+ const remaining = MAX_CAPTURE_CHARS - existing.length;
+ return `${existing}${text.slice(0, remaining)}`;
+}
+function buildMarker() {
+ const token = Math.random().toString(36).slice(2);
+ return `__DEEPCODE_PWD__${token}__`;
+}
+function buildToolCommandResult(stdout, stderr, marker, exitCode, signal, shellPath, startCwd, timedOut = false, timeoutMs, deadlineAtMs) {
+ const { output: cleanedStdout, cwd } = stripMarker(stdout, marker);
+ const combined = joinOutput(cleanedStdout, stderr);
+ const { text, truncated } = truncateOutput(combined);
+ return {
+ ok: exitCode === 0 && signal === null,
+ output: text,
+ cwd,
+ exitCode,
+ signal,
+ truncated,
+ shellPath,
+ startCwd,
+ timedOut,
+ timeoutMs,
+ deadlineAt: typeof deadlineAtMs === "number" ? new Date(deadlineAtMs).toISOString() : undefined,
+ };
+}
+function stripMarker(stdout, marker) {
+ if (!stdout) {
+ return { output: "", cwd: null };
+ }
+ const lines = stdout.split(/\r?\n/);
+ let markerIndex = -1;
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
+ if (lines[i].startsWith(marker)) {
+ markerIndex = i;
+ break;
+ }
+ }
+ if (markerIndex === -1) {
+ return { output: stdout, cwd: null };
+ }
+ const markerLine = lines[markerIndex];
+ const shellCwd = markerLine.slice(marker.length).trim();
+ const cwd = shellCwd ? toNativeCwd(shellCwd) : null;
+ lines.splice(markerIndex, 1);
+ return { output: lines.join("\n"), cwd };
+}
+function joinOutput(stdout, stderr) {
+ const trimmedStdout = stdout ?? "";
+ const trimmedStderr = stderr ?? "";
+ if (trimmedStdout && trimmedStderr) {
+ return `${trimmedStdout}\n${trimmedStderr}`;
+ }
+ return trimmedStdout || trimmedStderr;
+}
+function truncateOutput(output) {
+ if (output.length <= MAX_OUTPUT_CHARS) {
+ return { text: output, truncated: false };
+ }
+ return { text: output.slice(0, MAX_OUTPUT_CHARS), truncated: true };
+}
+function buildErrorMessage(exitCode, signal, error, timedOut = false) {
+ if (error) {
+ return error;
+ }
+ if (timedOut) {
+ return "Command timed out.";
+ }
+ if (signal) {
+ return `Command terminated by signal ${signal}.`;
+ }
+ if (exitCode !== null) {
+ return `Command failed with exit code ${exitCode}.`;
+ }
+ return "Command failed.";
+}
+function formatResult(result, name, errorMessage) {
+ const metadata = {
+ exitCode: result.exitCode,
+ signal: result.signal,
+ cwd: result.cwd,
+ truncated: result.truncated,
+ shellPath: result.shellPath,
+ startCwd: result.startCwd,
+ };
+ if (typeof result.timedOut === "boolean") {
+ metadata.timedOut = result.timedOut;
+ }
+ if (typeof result.timeoutMs === "number") {
+ metadata.timeoutMs = result.timeoutMs;
+ }
+ if (result.deadlineAt) {
+ metadata.deadlineAt = result.deadlineAt;
+ }
+ const outputValue = result.output ? result.output : undefined;
+ return {
+ ok: result.ok,
+ name,
+ output: outputValue,
+ error: errorMessage,
+ metadata,
+ };
+}
diff --git a/.agentic-snapshot/cli.js b/.agentic-snapshot/cli.js
new file mode 100644
index 00000000..3e271438
--- /dev/null
+++ b/.agentic-snapshot/cli.js
@@ -0,0 +1,105815 @@
+#!/usr/bin/env node
+import {
+ __commonJS,
+ __dirname,
+ __export,
+ __filename,
+ __name,
+ __require,
+ __toESM,
+ init_esbuild_shims
+} from "./chunks/chunk-BUBNMVFA.js";
+
+// node_modules/react/cjs/react.production.js
+var require_react_production = __commonJS({
+ "node_modules/react/cjs/react.production.js"(exports2) {
+ "use strict";
+ init_esbuild_shims();
+ var REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element");
+ var REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal");
+ var REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment");
+ var REACT_STRICT_MODE_TYPE = /* @__PURE__ */ Symbol.for("react.strict_mode");
+ var REACT_PROFILER_TYPE = /* @__PURE__ */ Symbol.for("react.profiler");
+ var REACT_CONSUMER_TYPE = /* @__PURE__ */ Symbol.for("react.consumer");
+ var REACT_CONTEXT_TYPE = /* @__PURE__ */ Symbol.for("react.context");
+ var REACT_FORWARD_REF_TYPE = /* @__PURE__ */ Symbol.for("react.forward_ref");
+ var REACT_SUSPENSE_TYPE = /* @__PURE__ */ Symbol.for("react.suspense");
+ var REACT_MEMO_TYPE = /* @__PURE__ */ Symbol.for("react.memo");
+ var REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy");
+ var REACT_ACTIVITY_TYPE = /* @__PURE__ */ Symbol.for("react.activity");
+ var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
+ function getIteratorFn(maybeIterable) {
+ if (null === maybeIterable || "object" !== typeof maybeIterable) return null;
+ maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"];
+ return "function" === typeof maybeIterable ? maybeIterable : null;
+ }
+ __name(getIteratorFn, "getIteratorFn");
+ var ReactNoopUpdateQueue = {
+ isMounted: /* @__PURE__ */ __name(function() {
+ return false;
+ }, "isMounted"),
+ enqueueForceUpdate: /* @__PURE__ */ __name(function() {
+ }, "enqueueForceUpdate"),
+ enqueueReplaceState: /* @__PURE__ */ __name(function() {
+ }, "enqueueReplaceState"),
+ enqueueSetState: /* @__PURE__ */ __name(function() {
+ }, "enqueueSetState")
+ };
+ var assign = Object.assign;
+ var emptyObject = {};
+ function Component(props, context, updater) {
+ this.props = props;
+ this.context = context;
+ this.refs = emptyObject;
+ this.updater = updater || ReactNoopUpdateQueue;
+ }
+ __name(Component, "Component");
+ Component.prototype.isReactComponent = {};
+ Component.prototype.setState = function(partialState, callback) {
+ if ("object" !== typeof partialState && "function" !== typeof partialState && null != partialState)
+ throw Error(
+ "takes an object of state variables to update or a function which returns an object of state variables."
+ );
+ this.updater.enqueueSetState(this, partialState, callback, "setState");
+ };
+ Component.prototype.forceUpdate = function(callback) {
+ this.updater.enqueueForceUpdate(this, callback, "forceUpdate");
+ };
+ function ComponentDummy() {
+ }
+ __name(ComponentDummy, "ComponentDummy");
+ ComponentDummy.prototype = Component.prototype;
+ function PureComponent2(props, context, updater) {
+ this.props = props;
+ this.context = context;
+ this.refs = emptyObject;
+ this.updater = updater || ReactNoopUpdateQueue;
+ }
+ __name(PureComponent2, "PureComponent");
+ var pureComponentPrototype = PureComponent2.prototype = new ComponentDummy();
+ pureComponentPrototype.constructor = PureComponent2;
+ assign(pureComponentPrototype, Component.prototype);
+ pureComponentPrototype.isPureReactComponent = true;
+ var isArrayImpl = Array.isArray;
+ function noop3() {
+ }
+ __name(noop3, "noop");
+ var ReactSharedInternals = { H: null, A: null, T: null, S: null };
+ var hasOwnProperty2 = Object.prototype.hasOwnProperty;
+ function ReactElement(type2, key, props) {
+ var refProp = props.ref;
+ return {
+ $$typeof: REACT_ELEMENT_TYPE,
+ type: type2,
+ key,
+ ref: void 0 !== refProp ? refProp : null,
+ props
+ };
+ }
+ __name(ReactElement, "ReactElement");
+ function cloneAndReplaceKey(oldElement, newKey) {
+ return ReactElement(oldElement.type, newKey, oldElement.props);
+ }
+ __name(cloneAndReplaceKey, "cloneAndReplaceKey");
+ function isValidElement2(object2) {
+ return "object" === typeof object2 && null !== object2 && object2.$$typeof === REACT_ELEMENT_TYPE;
+ }
+ __name(isValidElement2, "isValidElement");
+ function escape4(key) {
+ var escaperLookup = { "=": "=0", ":": "=2" };
+ return "$" + key.replace(/[=:]/g, function(match) {
+ return escaperLookup[match];
+ });
+ }
+ __name(escape4, "escape");
+ var userProvidedKeyEscapeRegex = /\/+/g;
+ function getElementKey(element, index) {
+ return "object" === typeof element && null !== element && null != element.key ? escape4("" + element.key) : index.toString(36);
+ }
+ __name(getElementKey, "getElementKey");
+ function resolveThenable(thenable) {
+ switch (thenable.status) {
+ case "fulfilled":
+ return thenable.value;
+ case "rejected":
+ throw thenable.reason;
+ default:
+ switch ("string" === typeof thenable.status ? thenable.then(noop3, noop3) : (thenable.status = "pending", thenable.then(
+ function(fulfilledValue) {
+ "pending" === thenable.status && (thenable.status = "fulfilled", thenable.value = fulfilledValue);
+ },
+ function(error51) {
+ "pending" === thenable.status && (thenable.status = "rejected", thenable.reason = error51);
+ }
+ )), thenable.status) {
+ case "fulfilled":
+ return thenable.value;
+ case "rejected":
+ throw thenable.reason;
+ }
+ }
+ throw thenable;
+ }
+ __name(resolveThenable, "resolveThenable");
+ function mapIntoArray(children, array2, escapedPrefix, nameSoFar, callback) {
+ var type2 = typeof children;
+ if ("undefined" === type2 || "boolean" === type2) children = null;
+ var invokeCallback = false;
+ if (null === children) invokeCallback = true;
+ else
+ switch (type2) {
+ case "bigint":
+ case "string":
+ case "number":
+ invokeCallback = true;
+ break;
+ case "object":
+ switch (children.$$typeof) {
+ case REACT_ELEMENT_TYPE:
+ case REACT_PORTAL_TYPE:
+ invokeCallback = true;
+ break;
+ case REACT_LAZY_TYPE:
+ return invokeCallback = children._init, mapIntoArray(
+ invokeCallback(children._payload),
+ array2,
+ escapedPrefix,
+ nameSoFar,
+ callback
+ );
+ }
+ }
+ if (invokeCallback)
+ return callback = callback(children), invokeCallback = "" === nameSoFar ? "." + getElementKey(children, 0) : nameSoFar, isArrayImpl(callback) ? (escapedPrefix = "", null != invokeCallback && (escapedPrefix = invokeCallback.replace(userProvidedKeyEscapeRegex, "$&/") + "/"), mapIntoArray(callback, array2, escapedPrefix, "", function(c) {
+ return c;
+ })) : null != callback && (isValidElement2(callback) && (callback = cloneAndReplaceKey(
+ callback,
+ escapedPrefix + (null == callback.key || children && children.key === callback.key ? "" : ("" + callback.key).replace(
+ userProvidedKeyEscapeRegex,
+ "$&/"
+ ) + "/") + invokeCallback
+ )), array2.push(callback)), 1;
+ invokeCallback = 0;
+ var nextNamePrefix = "" === nameSoFar ? "." : nameSoFar + ":";
+ if (isArrayImpl(children))
+ for (var i = 0; i < children.length; i++)
+ nameSoFar = children[i], type2 = nextNamePrefix + getElementKey(nameSoFar, i), invokeCallback += mapIntoArray(
+ nameSoFar,
+ array2,
+ escapedPrefix,
+ type2,
+ callback
+ );
+ else if (i = getIteratorFn(children), "function" === typeof i)
+ for (children = i.call(children), i = 0; !(nameSoFar = children.next()).done; )
+ nameSoFar = nameSoFar.value, type2 = nextNamePrefix + getElementKey(nameSoFar, i++), invokeCallback += mapIntoArray(
+ nameSoFar,
+ array2,
+ escapedPrefix,
+ type2,
+ callback
+ );
+ else if ("object" === type2) {
+ if ("function" === typeof children.then)
+ return mapIntoArray(
+ resolveThenable(children),
+ array2,
+ escapedPrefix,
+ nameSoFar,
+ callback
+ );
+ array2 = String(children);
+ throw Error(
+ "Objects are not valid as a React child (found: " + ("[object Object]" === array2 ? "object with keys {" + Object.keys(children).join(", ") + "}" : array2) + "). If you meant to render a collection of children, use an array instead."
+ );
+ }
+ return invokeCallback;
+ }
+ __name(mapIntoArray, "mapIntoArray");
+ function mapChildren(children, func, context) {
+ if (null == children) return children;
+ var result = [], count = 0;
+ mapIntoArray(children, result, "", "", function(child) {
+ return func.call(context, child, count++);
+ });
+ return result;
+ }
+ __name(mapChildren, "mapChildren");
+ function lazyInitializer(payload) {
+ if (-1 === payload._status) {
+ var ctor = payload._result;
+ ctor = ctor();
+ ctor.then(
+ function(moduleObject) {
+ if (0 === payload._status || -1 === payload._status)
+ payload._status = 1, payload._result = moduleObject;
+ },
+ function(error51) {
+ if (0 === payload._status || -1 === payload._status)
+ payload._status = 2, payload._result = error51;
+ }
+ );
+ -1 === payload._status && (payload._status = 0, payload._result = ctor);
+ }
+ if (1 === payload._status) return payload._result.default;
+ throw payload._result;
+ }
+ __name(lazyInitializer, "lazyInitializer");
+ var reportGlobalError = "function" === typeof reportError ? reportError : function(error51) {
+ if ("object" === typeof window && "function" === typeof window.ErrorEvent) {
+ var event = new window.ErrorEvent("error", {
+ bubbles: true,
+ cancelable: true,
+ message: "object" === typeof error51 && null !== error51 && "string" === typeof error51.message ? String(error51.message) : String(error51),
+ error: error51
+ });
+ if (!window.dispatchEvent(event)) return;
+ } else if ("object" === typeof process && "function" === typeof process.emit) {
+ process.emit("uncaughtException", error51);
+ return;
+ }
+ console.error(error51);
+ };
+ var Children2 = {
+ map: mapChildren,
+ forEach: /* @__PURE__ */ __name(function(children, forEachFunc, forEachContext) {
+ mapChildren(
+ children,
+ function() {
+ forEachFunc.apply(this, arguments);
+ },
+ forEachContext
+ );
+ }, "forEach"),
+ count: /* @__PURE__ */ __name(function(children) {
+ var n = 0;
+ mapChildren(children, function() {
+ n++;
+ });
+ return n;
+ }, "count"),
+ toArray: /* @__PURE__ */ __name(function(children) {
+ return mapChildren(children, function(child) {
+ return child;
+ }) || [];
+ }, "toArray"),
+ only: /* @__PURE__ */ __name(function(children) {
+ if (!isValidElement2(children))
+ throw Error(
+ "React.Children.only expected to receive a single React element child."
+ );
+ return children;
+ }, "only")
+ };
+ exports2.Activity = REACT_ACTIVITY_TYPE;
+ exports2.Children = Children2;
+ exports2.Component = Component;
+ exports2.Fragment = REACT_FRAGMENT_TYPE;
+ exports2.Profiler = REACT_PROFILER_TYPE;
+ exports2.PureComponent = PureComponent2;
+ exports2.StrictMode = REACT_STRICT_MODE_TYPE;
+ exports2.Suspense = REACT_SUSPENSE_TYPE;
+ exports2.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = ReactSharedInternals;
+ exports2.__COMPILER_RUNTIME = {
+ __proto__: null,
+ c: /* @__PURE__ */ __name(function(size) {
+ return ReactSharedInternals.H.useMemoCache(size);
+ }, "c")
+ };
+ exports2.cache = function(fn) {
+ return function() {
+ return fn.apply(null, arguments);
+ };
+ };
+ exports2.cacheSignal = function() {
+ return null;
+ };
+ exports2.cloneElement = function(element, config2, children) {
+ if (null === element || void 0 === element)
+ throw Error(
+ "The argument must be a React element, but you passed " + element + "."
+ );
+ var props = assign({}, element.props), key = element.key;
+ if (null != config2)
+ for (propName in void 0 !== config2.key && (key = "" + config2.key), config2)
+ !hasOwnProperty2.call(config2, propName) || "key" === propName || "__self" === propName || "__source" === propName || "ref" === propName && void 0 === config2.ref || (props[propName] = config2[propName]);
+ var propName = arguments.length - 2;
+ if (1 === propName) props.children = children;
+ else if (1 < propName) {
+ for (var childArray = Array(propName), i = 0; i < propName; i++)
+ childArray[i] = arguments[i + 2];
+ props.children = childArray;
+ }
+ return ReactElement(element.type, key, props);
+ };
+ exports2.createContext = function(defaultValue2) {
+ defaultValue2 = {
+ $$typeof: REACT_CONTEXT_TYPE,
+ _currentValue: defaultValue2,
+ _currentValue2: defaultValue2,
+ _threadCount: 0,
+ Provider: null,
+ Consumer: null
+ };
+ defaultValue2.Provider = defaultValue2;
+ defaultValue2.Consumer = {
+ $$typeof: REACT_CONSUMER_TYPE,
+ _context: defaultValue2
+ };
+ return defaultValue2;
+ };
+ exports2.createElement = function(type2, config2, children) {
+ var propName, props = {}, key = null;
+ if (null != config2)
+ for (propName in void 0 !== config2.key && (key = "" + config2.key), config2)
+ hasOwnProperty2.call(config2, propName) && "key" !== propName && "__self" !== propName && "__source" !== propName && (props[propName] = config2[propName]);
+ var childrenLength = arguments.length - 2;
+ if (1 === childrenLength) props.children = children;
+ else if (1 < childrenLength) {
+ for (var childArray = Array(childrenLength), i = 0; i < childrenLength; i++)
+ childArray[i] = arguments[i + 2];
+ props.children = childArray;
+ }
+ if (type2 && type2.defaultProps)
+ for (propName in childrenLength = type2.defaultProps, childrenLength)
+ void 0 === props[propName] && (props[propName] = childrenLength[propName]);
+ return ReactElement(type2, key, props);
+ };
+ exports2.createRef = function() {
+ return { current: null };
+ };
+ exports2.forwardRef = function(render2) {
+ return { $$typeof: REACT_FORWARD_REF_TYPE, render: render2 };
+ };
+ exports2.isValidElement = isValidElement2;
+ exports2.lazy = function(ctor) {
+ return {
+ $$typeof: REACT_LAZY_TYPE,
+ _payload: { _status: -1, _result: ctor },
+ _init: lazyInitializer
+ };
+ };
+ exports2.memo = function(type2, compare) {
+ return {
+ $$typeof: REACT_MEMO_TYPE,
+ type: type2,
+ compare: void 0 === compare ? null : compare
+ };
+ };
+ exports2.startTransition = function(scope) {
+ var prevTransition = ReactSharedInternals.T, currentTransition = {};
+ ReactSharedInternals.T = currentTransition;
+ try {
+ var returnValue = scope(), onStartTransitionFinish = ReactSharedInternals.S;
+ null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue);
+ "object" === typeof returnValue && null !== returnValue && "function" === typeof returnValue.then && returnValue.then(noop3, reportGlobalError);
+ } catch (error51) {
+ reportGlobalError(error51);
+ } finally {
+ null !== prevTransition && null !== currentTransition.types && (prevTransition.types = currentTransition.types), ReactSharedInternals.T = prevTransition;
+ }
+ };
+ exports2.unstable_useCacheRefresh = function() {
+ return ReactSharedInternals.H.useCacheRefresh();
+ };
+ exports2.use = function(usable) {
+ return ReactSharedInternals.H.use(usable);
+ };
+ exports2.useActionState = function(action, initialState, permalink) {
+ return ReactSharedInternals.H.useActionState(action, initialState, permalink);
+ };
+ exports2.useCallback = function(callback, deps) {
+ return ReactSharedInternals.H.useCallback(callback, deps);
+ };
+ exports2.useContext = function(Context) {
+ return ReactSharedInternals.H.useContext(Context);
+ };
+ exports2.useDebugValue = function() {
+ };
+ exports2.useDeferredValue = function(value, initialValue) {
+ return ReactSharedInternals.H.useDeferredValue(value, initialValue);
+ };
+ exports2.useEffect = function(create3, deps) {
+ return ReactSharedInternals.H.useEffect(create3, deps);
+ };
+ exports2.useEffectEvent = function(callback) {
+ return ReactSharedInternals.H.useEffectEvent(callback);
+ };
+ exports2.useId = function() {
+ return ReactSharedInternals.H.useId();
+ };
+ exports2.useImperativeHandle = function(ref, create3, deps) {
+ return ReactSharedInternals.H.useImperativeHandle(ref, create3, deps);
+ };
+ exports2.useInsertionEffect = function(create3, deps) {
+ return ReactSharedInternals.H.useInsertionEffect(create3, deps);
+ };
+ exports2.useLayoutEffect = function(create3, deps) {
+ return ReactSharedInternals.H.useLayoutEffect(create3, deps);
+ };
+ exports2.useMemo = function(create3, deps) {
+ return ReactSharedInternals.H.useMemo(create3, deps);
+ };
+ exports2.useOptimistic = function(passthrough, reducer) {
+ return ReactSharedInternals.H.useOptimistic(passthrough, reducer);
+ };
+ exports2.useReducer = function(reducer, initialArg, init) {
+ return ReactSharedInternals.H.useReducer(reducer, initialArg, init);
+ };
+ exports2.useRef = function(initialValue) {
+ return ReactSharedInternals.H.useRef(initialValue);
+ };
+ exports2.useState = function(initialState) {
+ return ReactSharedInternals.H.useState(initialState);
+ };
+ exports2.useSyncExternalStore = function(subscribe, getSnapshot, getServerSnapshot) {
+ return ReactSharedInternals.H.useSyncExternalStore(
+ subscribe,
+ getSnapshot,
+ getServerSnapshot
+ );
+ };
+ exports2.useTransition = function() {
+ return ReactSharedInternals.H.useTransition();
+ };
+ exports2.version = "19.2.7";
+ }
+});
+
+// node_modules/react/index.js
+var require_react = __commonJS({
+ "node_modules/react/index.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ if (true) {
+ module2.exports = require_react_production();
+ } else {
+ module2.exports = null;
+ }
+ }
+});
+
+// node_modules/signal-exit/signals.js
+var require_signals = __commonJS({
+ "node_modules/signal-exit/signals.js"(exports2, module2) {
+ init_esbuild_shims();
+ module2.exports = [
+ "SIGABRT",
+ "SIGALRM",
+ "SIGHUP",
+ "SIGINT",
+ "SIGTERM"
+ ];
+ if (process.platform !== "win32") {
+ module2.exports.push(
+ "SIGVTALRM",
+ "SIGXCPU",
+ "SIGXFSZ",
+ "SIGUSR2",
+ "SIGTRAP",
+ "SIGSYS",
+ "SIGQUIT",
+ "SIGIOT"
+ // should detect profiler and enable/disable accordingly.
+ // see #21
+ // 'SIGPROF'
+ );
+ }
+ if (process.platform === "linux") {
+ module2.exports.push(
+ "SIGIO",
+ "SIGPOLL",
+ "SIGPWR",
+ "SIGSTKFLT",
+ "SIGUNUSED"
+ );
+ }
+ }
+});
+
+// node_modules/signal-exit/index.js
+var require_signal_exit = __commonJS({
+ "node_modules/signal-exit/index.js"(exports2, module2) {
+ init_esbuild_shims();
+ var process18 = global.process;
+ var processOk = /* @__PURE__ */ __name(function(process19) {
+ return process19 && typeof process19 === "object" && typeof process19.removeListener === "function" && typeof process19.emit === "function" && typeof process19.reallyExit === "function" && typeof process19.listeners === "function" && typeof process19.kill === "function" && typeof process19.pid === "number" && typeof process19.on === "function";
+ }, "processOk");
+ if (!processOk(process18)) {
+ module2.exports = function() {
+ return function() {
+ };
+ };
+ } else {
+ assert2 = __require("assert");
+ signals = require_signals();
+ isWin = /^win/i.test(process18.platform);
+ EE = __require("events");
+ if (typeof EE !== "function") {
+ EE = EE.EventEmitter;
+ }
+ if (process18.__signal_exit_emitter__) {
+ emitter = process18.__signal_exit_emitter__;
+ } else {
+ emitter = process18.__signal_exit_emitter__ = new EE();
+ emitter.count = 0;
+ emitter.emitted = {};
+ }
+ if (!emitter.infinite) {
+ emitter.setMaxListeners(Infinity);
+ emitter.infinite = true;
+ }
+ module2.exports = function(cb, opts) {
+ if (!processOk(global.process)) {
+ return function() {
+ };
+ }
+ assert2.equal(typeof cb, "function", "a callback must be provided for exit handler");
+ if (loaded === false) {
+ load();
+ }
+ var ev = "exit";
+ if (opts && opts.alwaysLast) {
+ ev = "afterexit";
+ }
+ var remove = /* @__PURE__ */ __name(function() {
+ emitter.removeListener(ev, cb);
+ if (emitter.listeners("exit").length === 0 && emitter.listeners("afterexit").length === 0) {
+ unload();
+ }
+ }, "remove");
+ emitter.on(ev, cb);
+ return remove;
+ };
+ unload = /* @__PURE__ */ __name(function unload2() {
+ if (!loaded || !processOk(global.process)) {
+ return;
+ }
+ loaded = false;
+ signals.forEach(function(sig) {
+ try {
+ process18.removeListener(sig, sigListeners[sig]);
+ } catch (er) {
+ }
+ });
+ process18.emit = originalProcessEmit;
+ process18.reallyExit = originalProcessReallyExit;
+ emitter.count -= 1;
+ }, "unload");
+ module2.exports.unload = unload;
+ emit = /* @__PURE__ */ __name(function emit2(event, code, signal) {
+ if (emitter.emitted[event]) {
+ return;
+ }
+ emitter.emitted[event] = true;
+ emitter.emit(event, code, signal);
+ }, "emit");
+ sigListeners = {};
+ signals.forEach(function(sig) {
+ sigListeners[sig] = /* @__PURE__ */ __name(function listener() {
+ if (!processOk(global.process)) {
+ return;
+ }
+ var listeners = process18.listeners(sig);
+ if (listeners.length === emitter.count) {
+ unload();
+ emit("exit", null, sig);
+ emit("afterexit", null, sig);
+ if (isWin && sig === "SIGHUP") {
+ sig = "SIGINT";
+ }
+ process18.kill(process18.pid, sig);
+ }
+ }, "listener");
+ });
+ module2.exports.signals = function() {
+ return signals;
+ };
+ loaded = false;
+ load = /* @__PURE__ */ __name(function load2() {
+ if (loaded || !processOk(global.process)) {
+ return;
+ }
+ loaded = true;
+ emitter.count += 1;
+ signals = signals.filter(function(sig) {
+ try {
+ process18.on(sig, sigListeners[sig]);
+ return true;
+ } catch (er) {
+ return false;
+ }
+ });
+ process18.emit = processEmit;
+ process18.reallyExit = processReallyExit;
+ }, "load");
+ module2.exports.load = load;
+ originalProcessReallyExit = process18.reallyExit;
+ processReallyExit = /* @__PURE__ */ __name(function processReallyExit2(code) {
+ if (!processOk(global.process)) {
+ return;
+ }
+ process18.exitCode = code || /* istanbul ignore next */
+ 0;
+ emit("exit", process18.exitCode, null);
+ emit("afterexit", process18.exitCode, null);
+ originalProcessReallyExit.call(process18, process18.exitCode);
+ }, "processReallyExit");
+ originalProcessEmit = process18.emit;
+ processEmit = /* @__PURE__ */ __name(function processEmit2(ev, arg) {
+ if (ev === "exit" && processOk(global.process)) {
+ if (arg !== void 0) {
+ process18.exitCode = arg;
+ }
+ var ret = originalProcessEmit.apply(this, arguments);
+ emit("exit", process18.exitCode, null);
+ emit("afterexit", process18.exitCode, null);
+ return ret;
+ } else {
+ return originalProcessEmit.apply(this, arguments);
+ }
+ }, "processEmit");
+ }
+ var assert2;
+ var signals;
+ var isWin;
+ var EE;
+ var emitter;
+ var unload;
+ var emit;
+ var sigListeners;
+ var loaded;
+ var load;
+ var originalProcessReallyExit;
+ var processReallyExit;
+ var originalProcessEmit;
+ var processEmit;
+ }
+});
+
+// node_modules/react-reconciler/cjs/react-reconciler-constants.production.js
+var require_react_reconciler_constants_production = __commonJS({
+ "node_modules/react-reconciler/cjs/react-reconciler-constants.production.js"(exports2) {
+ "use strict";
+ init_esbuild_shims();
+ exports2.ConcurrentRoot = 1;
+ exports2.ContinuousEventPriority = 8;
+ exports2.DefaultEventPriority = 32;
+ exports2.DiscreteEventPriority = 2;
+ exports2.IdleEventPriority = 268435456;
+ exports2.LegacyRoot = 0;
+ exports2.NoEventPriority = 0;
+ }
+});
+
+// node_modules/react-reconciler/constants.js
+var require_constants = __commonJS({
+ "node_modules/react-reconciler/constants.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ if (true) {
+ module2.exports = require_react_reconciler_constants_production();
+ } else {
+ module2.exports = null;
+ }
+ }
+});
+
+// node_modules/scheduler/cjs/scheduler.production.js
+var require_scheduler_production = __commonJS({
+ "node_modules/scheduler/cjs/scheduler.production.js"(exports2) {
+ "use strict";
+ init_esbuild_shims();
+ function push(heap, node) {
+ var index = heap.length;
+ heap.push(node);
+ a: for (; 0 < index; ) {
+ var parentIndex = index - 1 >>> 1, parent = heap[parentIndex];
+ if (0 < compare(parent, node))
+ heap[parentIndex] = node, heap[index] = parent, index = parentIndex;
+ else break a;
+ }
+ }
+ __name(push, "push");
+ function peek(heap) {
+ return 0 === heap.length ? null : heap[0];
+ }
+ __name(peek, "peek");
+ function pop(heap) {
+ if (0 === heap.length) return null;
+ var first = heap[0], last = heap.pop();
+ if (last !== first) {
+ heap[0] = last;
+ a: for (var index = 0, length = heap.length, halfLength = length >>> 1; index < halfLength; ) {
+ var leftIndex = 2 * (index + 1) - 1, left2 = heap[leftIndex], rightIndex = leftIndex + 1, right2 = heap[rightIndex];
+ if (0 > compare(left2, last))
+ rightIndex < length && 0 > compare(right2, left2) ? (heap[index] = right2, heap[rightIndex] = last, index = rightIndex) : (heap[index] = left2, heap[leftIndex] = last, index = leftIndex);
+ else if (rightIndex < length && 0 > compare(right2, last))
+ heap[index] = right2, heap[rightIndex] = last, index = rightIndex;
+ else break a;
+ }
+ }
+ return first;
+ }
+ __name(pop, "pop");
+ function compare(a, b) {
+ var diff2 = a.sortIndex - b.sortIndex;
+ return 0 !== diff2 ? diff2 : a.id - b.id;
+ }
+ __name(compare, "compare");
+ exports2.unstable_now = void 0;
+ if ("object" === typeof performance && "function" === typeof performance.now) {
+ localPerformance = performance;
+ exports2.unstable_now = function() {
+ return localPerformance.now();
+ };
+ } else {
+ localDate = Date, initialTime = localDate.now();
+ exports2.unstable_now = function() {
+ return localDate.now() - initialTime;
+ };
+ }
+ var localPerformance;
+ var localDate;
+ var initialTime;
+ var taskQueue = [];
+ var timerQueue = [];
+ var taskIdCounter = 1;
+ var currentTask = null;
+ var currentPriorityLevel = 3;
+ var isPerformingWork = false;
+ var isHostCallbackScheduled = false;
+ var isHostTimeoutScheduled = false;
+ var needsPaint = false;
+ var localSetTimeout = "function" === typeof setTimeout ? setTimeout : null;
+ var localClearTimeout = "function" === typeof clearTimeout ? clearTimeout : null;
+ var localSetImmediate = "undefined" !== typeof setImmediate ? setImmediate : null;
+ function advanceTimers(currentTime) {
+ for (var timer = peek(timerQueue); null !== timer; ) {
+ if (null === timer.callback) pop(timerQueue);
+ else if (timer.startTime <= currentTime)
+ pop(timerQueue), timer.sortIndex = timer.expirationTime, push(taskQueue, timer);
+ else break;
+ timer = peek(timerQueue);
+ }
+ }
+ __name(advanceTimers, "advanceTimers");
+ function handleTimeout(currentTime) {
+ isHostTimeoutScheduled = false;
+ advanceTimers(currentTime);
+ if (!isHostCallbackScheduled)
+ if (null !== peek(taskQueue))
+ isHostCallbackScheduled = true, isMessageLoopRunning || (isMessageLoopRunning = true, schedulePerformWorkUntilDeadline());
+ else {
+ var firstTimer = peek(timerQueue);
+ null !== firstTimer && requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
+ }
+ }
+ __name(handleTimeout, "handleTimeout");
+ var isMessageLoopRunning = false;
+ var taskTimeoutID = -1;
+ var frameInterval = 5;
+ var startTime = -1;
+ function shouldYieldToHost() {
+ return needsPaint ? true : exports2.unstable_now() - startTime < frameInterval ? false : true;
+ }
+ __name(shouldYieldToHost, "shouldYieldToHost");
+ function performWorkUntilDeadline() {
+ needsPaint = false;
+ if (isMessageLoopRunning) {
+ var currentTime = exports2.unstable_now();
+ startTime = currentTime;
+ var hasMoreWork = true;
+ try {
+ a: {
+ isHostCallbackScheduled = false;
+ isHostTimeoutScheduled && (isHostTimeoutScheduled = false, localClearTimeout(taskTimeoutID), taskTimeoutID = -1);
+ isPerformingWork = true;
+ var previousPriorityLevel = currentPriorityLevel;
+ try {
+ b: {
+ advanceTimers(currentTime);
+ for (currentTask = peek(taskQueue); null !== currentTask && !(currentTask.expirationTime > currentTime && shouldYieldToHost()); ) {
+ var callback = currentTask.callback;
+ if ("function" === typeof callback) {
+ currentTask.callback = null;
+ currentPriorityLevel = currentTask.priorityLevel;
+ var continuationCallback = callback(
+ currentTask.expirationTime <= currentTime
+ );
+ currentTime = exports2.unstable_now();
+ if ("function" === typeof continuationCallback) {
+ currentTask.callback = continuationCallback;
+ advanceTimers(currentTime);
+ hasMoreWork = true;
+ break b;
+ }
+ currentTask === peek(taskQueue) && pop(taskQueue);
+ advanceTimers(currentTime);
+ } else pop(taskQueue);
+ currentTask = peek(taskQueue);
+ }
+ if (null !== currentTask) hasMoreWork = true;
+ else {
+ var firstTimer = peek(timerQueue);
+ null !== firstTimer && requestHostTimeout(
+ handleTimeout,
+ firstTimer.startTime - currentTime
+ );
+ hasMoreWork = false;
+ }
+ }
+ break a;
+ } finally {
+ currentTask = null, currentPriorityLevel = previousPriorityLevel, isPerformingWork = false;
+ }
+ hasMoreWork = void 0;
+ }
+ } finally {
+ hasMoreWork ? schedulePerformWorkUntilDeadline() : isMessageLoopRunning = false;
+ }
+ }
+ }
+ __name(performWorkUntilDeadline, "performWorkUntilDeadline");
+ var schedulePerformWorkUntilDeadline;
+ if ("function" === typeof localSetImmediate)
+ schedulePerformWorkUntilDeadline = /* @__PURE__ */ __name(function() {
+ localSetImmediate(performWorkUntilDeadline);
+ }, "schedulePerformWorkUntilDeadline");
+ else if ("undefined" !== typeof MessageChannel) {
+ channel = new MessageChannel(), port = channel.port2;
+ channel.port1.onmessage = performWorkUntilDeadline;
+ schedulePerformWorkUntilDeadline = /* @__PURE__ */ __name(function() {
+ port.postMessage(null);
+ }, "schedulePerformWorkUntilDeadline");
+ } else
+ schedulePerformWorkUntilDeadline = /* @__PURE__ */ __name(function() {
+ localSetTimeout(performWorkUntilDeadline, 0);
+ }, "schedulePerformWorkUntilDeadline");
+ var channel;
+ var port;
+ function requestHostTimeout(callback, ms) {
+ taskTimeoutID = localSetTimeout(function() {
+ callback(exports2.unstable_now());
+ }, ms);
+ }
+ __name(requestHostTimeout, "requestHostTimeout");
+ exports2.unstable_IdlePriority = 5;
+ exports2.unstable_ImmediatePriority = 1;
+ exports2.unstable_LowPriority = 4;
+ exports2.unstable_NormalPriority = 3;
+ exports2.unstable_Profiling = null;
+ exports2.unstable_UserBlockingPriority = 2;
+ exports2.unstable_cancelCallback = function(task) {
+ task.callback = null;
+ };
+ exports2.unstable_forceFrameRate = function(fps) {
+ 0 > fps || 125 < fps ? console.error(
+ "forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"
+ ) : frameInterval = 0 < fps ? Math.floor(1e3 / fps) : 5;
+ };
+ exports2.unstable_getCurrentPriorityLevel = function() {
+ return currentPriorityLevel;
+ };
+ exports2.unstable_next = function(eventHandler) {
+ switch (currentPriorityLevel) {
+ case 1:
+ case 2:
+ case 3:
+ var priorityLevel = 3;
+ break;
+ default:
+ priorityLevel = currentPriorityLevel;
+ }
+ var previousPriorityLevel = currentPriorityLevel;
+ currentPriorityLevel = priorityLevel;
+ try {
+ return eventHandler();
+ } finally {
+ currentPriorityLevel = previousPriorityLevel;
+ }
+ };
+ exports2.unstable_requestPaint = function() {
+ needsPaint = true;
+ };
+ exports2.unstable_runWithPriority = function(priorityLevel, eventHandler) {
+ switch (priorityLevel) {
+ case 1:
+ case 2:
+ case 3:
+ case 4:
+ case 5:
+ break;
+ default:
+ priorityLevel = 3;
+ }
+ var previousPriorityLevel = currentPriorityLevel;
+ currentPriorityLevel = priorityLevel;
+ try {
+ return eventHandler();
+ } finally {
+ currentPriorityLevel = previousPriorityLevel;
+ }
+ };
+ exports2.unstable_scheduleCallback = function(priorityLevel, callback, options2) {
+ var currentTime = exports2.unstable_now();
+ "object" === typeof options2 && null !== options2 ? (options2 = options2.delay, options2 = "number" === typeof options2 && 0 < options2 ? currentTime + options2 : currentTime) : options2 = currentTime;
+ switch (priorityLevel) {
+ case 1:
+ var timeout = -1;
+ break;
+ case 2:
+ timeout = 250;
+ break;
+ case 5:
+ timeout = 1073741823;
+ break;
+ case 4:
+ timeout = 1e4;
+ break;
+ default:
+ timeout = 5e3;
+ }
+ timeout = options2 + timeout;
+ priorityLevel = {
+ id: taskIdCounter++,
+ callback,
+ priorityLevel,
+ startTime: options2,
+ expirationTime: timeout,
+ sortIndex: -1
+ };
+ options2 > currentTime ? (priorityLevel.sortIndex = options2, push(timerQueue, priorityLevel), null === peek(taskQueue) && priorityLevel === peek(timerQueue) && (isHostTimeoutScheduled ? (localClearTimeout(taskTimeoutID), taskTimeoutID = -1) : isHostTimeoutScheduled = true, requestHostTimeout(handleTimeout, options2 - currentTime))) : (priorityLevel.sortIndex = timeout, push(taskQueue, priorityLevel), isHostCallbackScheduled || isPerformingWork || (isHostCallbackScheduled = true, isMessageLoopRunning || (isMessageLoopRunning = true, schedulePerformWorkUntilDeadline())));
+ return priorityLevel;
+ };
+ exports2.unstable_shouldYield = shouldYieldToHost;
+ exports2.unstable_wrapCallback = function(callback) {
+ var parentPriorityLevel = currentPriorityLevel;
+ return function() {
+ var previousPriorityLevel = currentPriorityLevel;
+ currentPriorityLevel = parentPriorityLevel;
+ try {
+ return callback.apply(this, arguments);
+ } finally {
+ currentPriorityLevel = previousPriorityLevel;
+ }
+ };
+ };
+ }
+});
+
+// node_modules/scheduler/index.js
+var require_scheduler = __commonJS({
+ "node_modules/scheduler/index.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ if (true) {
+ module2.exports = require_scheduler_production();
+ } else {
+ module2.exports = null;
+ }
+ }
+});
+
+// node_modules/react-reconciler/cjs/react-reconciler.production.js
+var require_react_reconciler_production = __commonJS({
+ "node_modules/react-reconciler/cjs/react-reconciler.production.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ module2.exports = function($$$config) {
+ function createFiber(tag, pendingProps, key, mode) {
+ return new FiberNode(tag, pendingProps, key, mode);
+ }
+ __name(createFiber, "createFiber");
+ function noop3() {
+ }
+ __name(noop3, "noop");
+ function formatProdErrorMessage(code) {
+ var url2 = "https://react.dev/errors/" + code;
+ if (1 < arguments.length) {
+ url2 += "?args[]=" + encodeURIComponent(arguments[1]);
+ for (var i = 2; i < arguments.length; i++)
+ url2 += "&args[]=" + encodeURIComponent(arguments[i]);
+ }
+ return "Minified React error #" + code + "; visit " + url2 + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings.";
+ }
+ __name(formatProdErrorMessage, "formatProdErrorMessage");
+ function getNearestMountedFiber(fiber) {
+ var node = fiber, nearestMounted = fiber;
+ if (fiber.alternate) for (; node.return; ) node = node.return;
+ else {
+ fiber = node;
+ do
+ node = fiber, 0 !== (node.flags & 4098) && (nearestMounted = node.return), fiber = node.return;
+ while (fiber);
+ }
+ return 3 === node.tag ? nearestMounted : null;
+ }
+ __name(getNearestMountedFiber, "getNearestMountedFiber");
+ function assertIsMounted(fiber) {
+ if (getNearestMountedFiber(fiber) !== fiber)
+ throw Error(formatProdErrorMessage(188));
+ }
+ __name(assertIsMounted, "assertIsMounted");
+ function findCurrentFiberUsingSlowPath(fiber) {
+ var alternate = fiber.alternate;
+ if (!alternate) {
+ alternate = getNearestMountedFiber(fiber);
+ if (null === alternate) throw Error(formatProdErrorMessage(188));
+ return alternate !== fiber ? null : fiber;
+ }
+ for (var a = fiber, b = alternate; ; ) {
+ var parentA = a.return;
+ if (null === parentA) break;
+ var parentB = parentA.alternate;
+ if (null === parentB) {
+ b = parentA.return;
+ if (null !== b) {
+ a = b;
+ continue;
+ }
+ break;
+ }
+ if (parentA.child === parentB.child) {
+ for (parentB = parentA.child; parentB; ) {
+ if (parentB === a) return assertIsMounted(parentA), fiber;
+ if (parentB === b) return assertIsMounted(parentA), alternate;
+ parentB = parentB.sibling;
+ }
+ throw Error(formatProdErrorMessage(188));
+ }
+ if (a.return !== b.return) a = parentA, b = parentB;
+ else {
+ for (var didFindChild = false, child$0 = parentA.child; child$0; ) {
+ if (child$0 === a) {
+ didFindChild = true;
+ a = parentA;
+ b = parentB;
+ break;
+ }
+ if (child$0 === b) {
+ didFindChild = true;
+ b = parentA;
+ a = parentB;
+ break;
+ }
+ child$0 = child$0.sibling;
+ }
+ if (!didFindChild) {
+ for (child$0 = parentB.child; child$0; ) {
+ if (child$0 === a) {
+ didFindChild = true;
+ a = parentB;
+ b = parentA;
+ break;
+ }
+ if (child$0 === b) {
+ didFindChild = true;
+ b = parentB;
+ a = parentA;
+ break;
+ }
+ child$0 = child$0.sibling;
+ }
+ if (!didFindChild) throw Error(formatProdErrorMessage(189));
+ }
+ }
+ if (a.alternate !== b) throw Error(formatProdErrorMessage(190));
+ }
+ if (3 !== a.tag) throw Error(formatProdErrorMessage(188));
+ return a.stateNode.current === a ? fiber : alternate;
+ }
+ __name(findCurrentFiberUsingSlowPath, "findCurrentFiberUsingSlowPath");
+ function findCurrentHostFiberImpl(node) {
+ var tag = node.tag;
+ if (5 === tag || 26 === tag || 27 === tag || 6 === tag) return node;
+ for (node = node.child; null !== node; ) {
+ tag = findCurrentHostFiberImpl(node);
+ if (null !== tag) return tag;
+ node = node.sibling;
+ }
+ return null;
+ }
+ __name(findCurrentHostFiberImpl, "findCurrentHostFiberImpl");
+ function findCurrentHostFiberWithNoPortalsImpl(node) {
+ var tag = node.tag;
+ if (5 === tag || 26 === tag || 27 === tag || 6 === tag) return node;
+ for (node = node.child; null !== node; ) {
+ if (4 !== node.tag && (tag = findCurrentHostFiberWithNoPortalsImpl(node), null !== tag))
+ return tag;
+ node = node.sibling;
+ }
+ return null;
+ }
+ __name(findCurrentHostFiberWithNoPortalsImpl, "findCurrentHostFiberWithNoPortalsImpl");
+ function getIteratorFn(maybeIterable) {
+ if (null === maybeIterable || "object" !== typeof maybeIterable)
+ return null;
+ maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"];
+ return "function" === typeof maybeIterable ? maybeIterable : null;
+ }
+ __name(getIteratorFn, "getIteratorFn");
+ function getComponentNameFromType(type2) {
+ if (null == type2) return null;
+ if ("function" === typeof type2)
+ return type2.$$typeof === REACT_CLIENT_REFERENCE ? null : type2.displayName || type2.name || null;
+ if ("string" === typeof type2) return type2;
+ switch (type2) {
+ case REACT_FRAGMENT_TYPE:
+ return "Fragment";
+ case REACT_PROFILER_TYPE:
+ return "Profiler";
+ case REACT_STRICT_MODE_TYPE:
+ return "StrictMode";
+ case REACT_SUSPENSE_TYPE:
+ return "Suspense";
+ case REACT_SUSPENSE_LIST_TYPE:
+ return "SuspenseList";
+ case REACT_ACTIVITY_TYPE:
+ return "Activity";
+ }
+ if ("object" === typeof type2)
+ switch (type2.$$typeof) {
+ case REACT_PORTAL_TYPE:
+ return "Portal";
+ case REACT_CONTEXT_TYPE:
+ return type2.displayName || "Context";
+ case REACT_CONSUMER_TYPE:
+ return (type2._context.displayName || "Context") + ".Consumer";
+ case REACT_FORWARD_REF_TYPE:
+ var innerType = type2.render;
+ type2 = type2.displayName;
+ type2 || (type2 = innerType.displayName || innerType.name || "", type2 = "" !== type2 ? "ForwardRef(" + type2 + ")" : "ForwardRef");
+ return type2;
+ case REACT_MEMO_TYPE:
+ return innerType = type2.displayName || null, null !== innerType ? innerType : getComponentNameFromType(type2.type) || "Memo";
+ case REACT_LAZY_TYPE:
+ innerType = type2._payload;
+ type2 = type2._init;
+ try {
+ return getComponentNameFromType(type2(innerType));
+ } catch (x) {
+ }
+ }
+ return null;
+ }
+ __name(getComponentNameFromType, "getComponentNameFromType");
+ function createCursor(defaultValue2) {
+ return { current: defaultValue2 };
+ }
+ __name(createCursor, "createCursor");
+ function pop(cursor) {
+ 0 > index$jscomp$0 || (cursor.current = valueStack[index$jscomp$0], valueStack[index$jscomp$0] = null, index$jscomp$0--);
+ }
+ __name(pop, "pop");
+ function push(cursor, value) {
+ index$jscomp$0++;
+ valueStack[index$jscomp$0] = cursor.current;
+ cursor.current = value;
+ }
+ __name(push, "push");
+ function clz32Fallback(x) {
+ x >>>= 0;
+ return 0 === x ? 32 : 31 - (log$1(x) / LN2 | 0) | 0;
+ }
+ __name(clz32Fallback, "clz32Fallback");
+ function getHighestPriorityLanes(lanes) {
+ var pendingSyncLanes = lanes & 42;
+ if (0 !== pendingSyncLanes) return pendingSyncLanes;
+ switch (lanes & -lanes) {
+ case 1:
+ return 1;
+ case 2:
+ return 2;
+ case 4:
+ return 4;
+ case 8:
+ return 8;
+ case 16:
+ return 16;
+ case 32:
+ return 32;
+ case 64:
+ return 64;
+ case 128:
+ return 128;
+ case 256:
+ case 512:
+ case 1024:
+ case 2048:
+ case 4096:
+ case 8192:
+ case 16384:
+ case 32768:
+ case 65536:
+ case 131072:
+ return lanes & 261888;
+ case 262144:
+ case 524288:
+ case 1048576:
+ case 2097152:
+ return lanes & 3932160;
+ case 4194304:
+ case 8388608:
+ case 16777216:
+ case 33554432:
+ return lanes & 62914560;
+ case 67108864:
+ return 67108864;
+ case 134217728:
+ return 134217728;
+ case 268435456:
+ return 268435456;
+ case 536870912:
+ return 536870912;
+ case 1073741824:
+ return 0;
+ default:
+ return lanes;
+ }
+ }
+ __name(getHighestPriorityLanes, "getHighestPriorityLanes");
+ function getNextLanes(root, wipLanes, rootHasPendingCommit) {
+ var pendingLanes = root.pendingLanes;
+ if (0 === pendingLanes) return 0;
+ var nextLanes = 0, suspendedLanes = root.suspendedLanes, pingedLanes = root.pingedLanes;
+ root = root.warmLanes;
+ var nonIdlePendingLanes = pendingLanes & 134217727;
+ 0 !== nonIdlePendingLanes ? (pendingLanes = nonIdlePendingLanes & ~suspendedLanes, 0 !== pendingLanes ? nextLanes = getHighestPriorityLanes(pendingLanes) : (pingedLanes &= nonIdlePendingLanes, 0 !== pingedLanes ? nextLanes = getHighestPriorityLanes(pingedLanes) : rootHasPendingCommit || (rootHasPendingCommit = nonIdlePendingLanes & ~root, 0 !== rootHasPendingCommit && (nextLanes = getHighestPriorityLanes(rootHasPendingCommit))))) : (nonIdlePendingLanes = pendingLanes & ~suspendedLanes, 0 !== nonIdlePendingLanes ? nextLanes = getHighestPriorityLanes(nonIdlePendingLanes) : 0 !== pingedLanes ? nextLanes = getHighestPriorityLanes(pingedLanes) : rootHasPendingCommit || (rootHasPendingCommit = pendingLanes & ~root, 0 !== rootHasPendingCommit && (nextLanes = getHighestPriorityLanes(rootHasPendingCommit))));
+ return 0 === nextLanes ? 0 : 0 !== wipLanes && wipLanes !== nextLanes && 0 === (wipLanes & suspendedLanes) && (suspendedLanes = nextLanes & -nextLanes, rootHasPendingCommit = wipLanes & -wipLanes, suspendedLanes >= rootHasPendingCommit || 32 === suspendedLanes && 0 !== (rootHasPendingCommit & 4194048)) ? wipLanes : nextLanes;
+ }
+ __name(getNextLanes, "getNextLanes");
+ function checkIfRootIsPrerendering(root, renderLanes2) {
+ return 0 === (root.pendingLanes & ~(root.suspendedLanes & ~root.pingedLanes) & renderLanes2);
+ }
+ __name(checkIfRootIsPrerendering, "checkIfRootIsPrerendering");
+ function computeExpirationTime(lane, currentTime) {
+ switch (lane) {
+ case 1:
+ case 2:
+ case 4:
+ case 8:
+ case 64:
+ return currentTime + 250;
+ case 16:
+ case 32:
+ case 128:
+ case 256:
+ case 512:
+ case 1024:
+ case 2048:
+ case 4096:
+ case 8192:
+ case 16384:
+ case 32768:
+ case 65536:
+ case 131072:
+ case 262144:
+ case 524288:
+ case 1048576:
+ case 2097152:
+ return currentTime + 5e3;
+ case 4194304:
+ case 8388608:
+ case 16777216:
+ case 33554432:
+ return -1;
+ case 67108864:
+ case 134217728:
+ case 268435456:
+ case 536870912:
+ case 1073741824:
+ return -1;
+ default:
+ return -1;
+ }
+ }
+ __name(computeExpirationTime, "computeExpirationTime");
+ function claimNextRetryLane() {
+ var lane = nextRetryLane;
+ nextRetryLane <<= 1;
+ 0 === (nextRetryLane & 62914560) && (nextRetryLane = 4194304);
+ return lane;
+ }
+ __name(claimNextRetryLane, "claimNextRetryLane");
+ function createLaneMap(initial) {
+ for (var laneMap = [], i = 0; 31 > i; i++) laneMap.push(initial);
+ return laneMap;
+ }
+ __name(createLaneMap, "createLaneMap");
+ function markRootUpdated$1(root, updateLane) {
+ root.pendingLanes |= updateLane;
+ 268435456 !== updateLane && (root.suspendedLanes = 0, root.pingedLanes = 0, root.warmLanes = 0);
+ }
+ __name(markRootUpdated$1, "markRootUpdated$1");
+ function markRootFinished(root, finishedLanes, remainingLanes, spawnedLane, updatedLanes, suspendedRetryLanes) {
+ var previouslyPendingLanes = root.pendingLanes;
+ root.pendingLanes = remainingLanes;
+ root.suspendedLanes = 0;
+ root.pingedLanes = 0;
+ root.warmLanes = 0;
+ root.expiredLanes &= remainingLanes;
+ root.entangledLanes &= remainingLanes;
+ root.errorRecoveryDisabledLanes &= remainingLanes;
+ root.shellSuspendCounter = 0;
+ var entanglements = root.entanglements, expirationTimes = root.expirationTimes, hiddenUpdates = root.hiddenUpdates;
+ for (remainingLanes = previouslyPendingLanes & ~remainingLanes; 0 < remainingLanes; ) {
+ var index$5 = 31 - clz32(remainingLanes), lane = 1 << index$5;
+ entanglements[index$5] = 0;
+ expirationTimes[index$5] = -1;
+ var hiddenUpdatesForLane = hiddenUpdates[index$5];
+ if (null !== hiddenUpdatesForLane)
+ for (hiddenUpdates[index$5] = null, index$5 = 0; index$5 < hiddenUpdatesForLane.length; index$5++) {
+ var update = hiddenUpdatesForLane[index$5];
+ null !== update && (update.lane &= -536870913);
+ }
+ remainingLanes &= ~lane;
+ }
+ 0 !== spawnedLane && markSpawnedDeferredLane(root, spawnedLane, 0);
+ 0 !== suspendedRetryLanes && 0 === updatedLanes && 0 !== root.tag && (root.suspendedLanes |= suspendedRetryLanes & ~(previouslyPendingLanes & ~finishedLanes));
+ }
+ __name(markRootFinished, "markRootFinished");
+ function markSpawnedDeferredLane(root, spawnedLane, entangledLanes) {
+ root.pendingLanes |= spawnedLane;
+ root.suspendedLanes &= ~spawnedLane;
+ var spawnedLaneIndex = 31 - clz32(spawnedLane);
+ root.entangledLanes |= spawnedLane;
+ root.entanglements[spawnedLaneIndex] = root.entanglements[spawnedLaneIndex] | 1073741824 | entangledLanes & 261930;
+ }
+ __name(markSpawnedDeferredLane, "markSpawnedDeferredLane");
+ function markRootEntangled(root, entangledLanes) {
+ var rootEntangledLanes = root.entangledLanes |= entangledLanes;
+ for (root = root.entanglements; rootEntangledLanes; ) {
+ var index$6 = 31 - clz32(rootEntangledLanes), lane = 1 << index$6;
+ lane & entangledLanes | root[index$6] & entangledLanes && (root[index$6] |= entangledLanes);
+ rootEntangledLanes &= ~lane;
+ }
+ }
+ __name(markRootEntangled, "markRootEntangled");
+ function getBumpedLaneForHydration(root, renderLanes2) {
+ var renderLane = renderLanes2 & -renderLanes2;
+ renderLane = 0 !== (renderLane & 42) ? 1 : getBumpedLaneForHydrationByLane(renderLane);
+ return 0 !== (renderLane & (root.suspendedLanes | renderLanes2)) ? 0 : renderLane;
+ }
+ __name(getBumpedLaneForHydration, "getBumpedLaneForHydration");
+ function getBumpedLaneForHydrationByLane(lane) {
+ switch (lane) {
+ case 2:
+ lane = 1;
+ break;
+ case 8:
+ lane = 4;
+ break;
+ case 32:
+ lane = 16;
+ break;
+ case 256:
+ case 512:
+ case 1024:
+ case 2048:
+ case 4096:
+ case 8192:
+ case 16384:
+ case 32768:
+ case 65536:
+ case 131072:
+ case 262144:
+ case 524288:
+ case 1048576:
+ case 2097152:
+ case 4194304:
+ case 8388608:
+ case 16777216:
+ case 33554432:
+ lane = 128;
+ break;
+ case 268435456:
+ lane = 134217728;
+ break;
+ default:
+ lane = 0;
+ }
+ return lane;
+ }
+ __name(getBumpedLaneForHydrationByLane, "getBumpedLaneForHydrationByLane");
+ function lanesToEventPriority(lanes) {
+ lanes &= -lanes;
+ return 2 < lanes ? 8 < lanes ? 0 !== (lanes & 134217727) ? 32 : 268435456 : 8 : 2;
+ }
+ __name(lanesToEventPriority, "lanesToEventPriority");
+ function setIsStrictModeForDevtools(newIsStrictMode) {
+ "function" === typeof log && unstable_setDisableYieldValue(newIsStrictMode);
+ if (injectedHook && "function" === typeof injectedHook.setStrictMode)
+ try {
+ injectedHook.setStrictMode(rendererID, newIsStrictMode);
+ } catch (err) {
+ }
+ }
+ __name(setIsStrictModeForDevtools, "setIsStrictModeForDevtools");
+ function is(x, y) {
+ return x === y && (0 !== x || 1 / x === 1 / y) || x !== x && y !== y;
+ }
+ __name(is, "is");
+ function describeBuiltInComponentFrame(name) {
+ if (void 0 === prefix)
+ try {
+ throw Error();
+ } catch (x) {
+ var match = x.stack.trim().match(/\n( *(at )?)/);
+ prefix = match && match[1] || "";
+ suffix = -1 < x.stack.indexOf("\n at") ? " ()" : -1 < x.stack.indexOf("@") ? "@unknown:0:0" : "";
+ }
+ return "\n" + prefix + name + suffix;
+ }
+ __name(describeBuiltInComponentFrame, "describeBuiltInComponentFrame");
+ function describeNativeComponentFrame(fn, construct) {
+ if (!fn || reentry) return "";
+ reentry = true;
+ var previousPrepareStackTrace = Error.prepareStackTrace;
+ Error.prepareStackTrace = void 0;
+ try {
+ var RunInRootFrame = {
+ DetermineComponentFrameRoot: /* @__PURE__ */ __name(function() {
+ try {
+ if (construct) {
+ var Fake = /* @__PURE__ */ __name(function() {
+ throw Error();
+ }, "Fake");
+ Object.defineProperty(Fake.prototype, "props", {
+ set: /* @__PURE__ */ __name(function() {
+ throw Error();
+ }, "set")
+ });
+ if ("object" === typeof Reflect && Reflect.construct) {
+ try {
+ Reflect.construct(Fake, []);
+ } catch (x) {
+ var control = x;
+ }
+ Reflect.construct(fn, [], Fake);
+ } else {
+ try {
+ Fake.call();
+ } catch (x$8) {
+ control = x$8;
+ }
+ fn.call(Fake.prototype);
+ }
+ } else {
+ try {
+ throw Error();
+ } catch (x$9) {
+ control = x$9;
+ }
+ (Fake = fn()) && "function" === typeof Fake.catch && Fake.catch(function() {
+ });
+ }
+ } catch (sample) {
+ if (sample && control && "string" === typeof sample.stack)
+ return [sample.stack, control.stack];
+ }
+ return [null, null];
+ }, "DetermineComponentFrameRoot")
+ };
+ RunInRootFrame.DetermineComponentFrameRoot.displayName = "DetermineComponentFrameRoot";
+ var namePropDescriptor = Object.getOwnPropertyDescriptor(
+ RunInRootFrame.DetermineComponentFrameRoot,
+ "name"
+ );
+ namePropDescriptor && namePropDescriptor.configurable && Object.defineProperty(
+ RunInRootFrame.DetermineComponentFrameRoot,
+ "name",
+ { value: "DetermineComponentFrameRoot" }
+ );
+ var _RunInRootFrame$Deter = RunInRootFrame.DetermineComponentFrameRoot(), sampleStack = _RunInRootFrame$Deter[0], controlStack = _RunInRootFrame$Deter[1];
+ if (sampleStack && controlStack) {
+ var sampleLines = sampleStack.split("\n"), controlLines = controlStack.split("\n");
+ for (namePropDescriptor = RunInRootFrame = 0; RunInRootFrame < sampleLines.length && !sampleLines[RunInRootFrame].includes("DetermineComponentFrameRoot"); )
+ RunInRootFrame++;
+ for (; namePropDescriptor < controlLines.length && !controlLines[namePropDescriptor].includes(
+ "DetermineComponentFrameRoot"
+ ); )
+ namePropDescriptor++;
+ if (RunInRootFrame === sampleLines.length || namePropDescriptor === controlLines.length)
+ for (RunInRootFrame = sampleLines.length - 1, namePropDescriptor = controlLines.length - 1; 1 <= RunInRootFrame && 0 <= namePropDescriptor && sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]; )
+ namePropDescriptor--;
+ for (; 1 <= RunInRootFrame && 0 <= namePropDescriptor; RunInRootFrame--, namePropDescriptor--)
+ if (sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]) {
+ if (1 !== RunInRootFrame || 1 !== namePropDescriptor) {
+ do
+ if (RunInRootFrame--, namePropDescriptor--, 0 > namePropDescriptor || sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]) {
+ var frame = "\n" + sampleLines[RunInRootFrame].replace(" at new ", " at ");
+ fn.displayName && frame.includes("") && (frame = frame.replace("", fn.displayName));
+ return frame;
+ }
+ while (1 <= RunInRootFrame && 0 <= namePropDescriptor);
+ }
+ break;
+ }
+ }
+ } finally {
+ reentry = false, Error.prepareStackTrace = previousPrepareStackTrace;
+ }
+ return (previousPrepareStackTrace = fn ? fn.displayName || fn.name : "") ? describeBuiltInComponentFrame(previousPrepareStackTrace) : "";
+ }
+ __name(describeNativeComponentFrame, "describeNativeComponentFrame");
+ function describeFiber(fiber, childFiber) {
+ switch (fiber.tag) {
+ case 26:
+ case 27:
+ case 5:
+ return describeBuiltInComponentFrame(fiber.type);
+ case 16:
+ return describeBuiltInComponentFrame("Lazy");
+ case 13:
+ return fiber.child !== childFiber && null !== childFiber ? describeBuiltInComponentFrame("Suspense Fallback") : describeBuiltInComponentFrame("Suspense");
+ case 19:
+ return describeBuiltInComponentFrame("SuspenseList");
+ case 0:
+ case 15:
+ return describeNativeComponentFrame(fiber.type, false);
+ case 11:
+ return describeNativeComponentFrame(fiber.type.render, false);
+ case 1:
+ return describeNativeComponentFrame(fiber.type, true);
+ case 31:
+ return describeBuiltInComponentFrame("Activity");
+ default:
+ return "";
+ }
+ }
+ __name(describeFiber, "describeFiber");
+ function getStackByFiberInDevAndProd(workInProgress2) {
+ try {
+ var info = "", previous = null;
+ do
+ info += describeFiber(workInProgress2, previous), previous = workInProgress2, workInProgress2 = workInProgress2.return;
+ while (workInProgress2);
+ return info;
+ } catch (x) {
+ return "\nError generating stack: " + x.message + "\n" + x.stack;
+ }
+ }
+ __name(getStackByFiberInDevAndProd, "getStackByFiberInDevAndProd");
+ function createCapturedValueAtFiber(value, source) {
+ if ("object" === typeof value && null !== value) {
+ var existing = CapturedStacks.get(value);
+ if (void 0 !== existing) return existing;
+ source = {
+ value,
+ source,
+ stack: getStackByFiberInDevAndProd(source)
+ };
+ CapturedStacks.set(value, source);
+ return source;
+ }
+ return {
+ value,
+ source,
+ stack: getStackByFiberInDevAndProd(source)
+ };
+ }
+ __name(createCapturedValueAtFiber, "createCapturedValueAtFiber");
+ function pushTreeFork(workInProgress2, totalChildren) {
+ forkStack[forkStackIndex++] = treeForkCount;
+ forkStack[forkStackIndex++] = treeForkProvider;
+ treeForkProvider = workInProgress2;
+ treeForkCount = totalChildren;
+ }
+ __name(pushTreeFork, "pushTreeFork");
+ function pushTreeId(workInProgress2, totalChildren, index) {
+ idStack[idStackIndex++] = treeContextId;
+ idStack[idStackIndex++] = treeContextOverflow;
+ idStack[idStackIndex++] = treeContextProvider;
+ treeContextProvider = workInProgress2;
+ var baseIdWithLeadingBit = treeContextId;
+ workInProgress2 = treeContextOverflow;
+ var baseLength = 32 - clz32(baseIdWithLeadingBit) - 1;
+ baseIdWithLeadingBit &= ~(1 << baseLength);
+ index += 1;
+ var length = 32 - clz32(totalChildren) + baseLength;
+ if (30 < length) {
+ var numberOfOverflowBits = baseLength - baseLength % 5;
+ length = (baseIdWithLeadingBit & (1 << numberOfOverflowBits) - 1).toString(32);
+ baseIdWithLeadingBit >>= numberOfOverflowBits;
+ baseLength -= numberOfOverflowBits;
+ treeContextId = 1 << 32 - clz32(totalChildren) + baseLength | index << baseLength | baseIdWithLeadingBit;
+ treeContextOverflow = length + workInProgress2;
+ } else
+ treeContextId = 1 << length | index << baseLength | baseIdWithLeadingBit, treeContextOverflow = workInProgress2;
+ }
+ __name(pushTreeId, "pushTreeId");
+ function pushMaterializedTreeId(workInProgress2) {
+ null !== workInProgress2.return && (pushTreeFork(workInProgress2, 1), pushTreeId(workInProgress2, 1, 0));
+ }
+ __name(pushMaterializedTreeId, "pushMaterializedTreeId");
+ function popTreeContext(workInProgress2) {
+ for (; workInProgress2 === treeForkProvider; )
+ treeForkProvider = forkStack[--forkStackIndex], forkStack[forkStackIndex] = null, treeForkCount = forkStack[--forkStackIndex], forkStack[forkStackIndex] = null;
+ for (; workInProgress2 === treeContextProvider; )
+ treeContextProvider = idStack[--idStackIndex], idStack[idStackIndex] = null, treeContextOverflow = idStack[--idStackIndex], idStack[idStackIndex] = null, treeContextId = idStack[--idStackIndex], idStack[idStackIndex] = null;
+ }
+ __name(popTreeContext, "popTreeContext");
+ function restoreSuspendedTreeContext(workInProgress2, suspendedContext) {
+ idStack[idStackIndex++] = treeContextId;
+ idStack[idStackIndex++] = treeContextOverflow;
+ idStack[idStackIndex++] = treeContextProvider;
+ treeContextId = suspendedContext.id;
+ treeContextOverflow = suspendedContext.overflow;
+ treeContextProvider = workInProgress2;
+ }
+ __name(restoreSuspendedTreeContext, "restoreSuspendedTreeContext");
+ function pushHostContainer(fiber, nextRootInstance) {
+ push(rootInstanceStackCursor, nextRootInstance);
+ push(contextFiberStackCursor, fiber);
+ push(contextStackCursor, null);
+ fiber = getRootHostContext(nextRootInstance);
+ pop(contextStackCursor);
+ push(contextStackCursor, fiber);
+ }
+ __name(pushHostContainer, "pushHostContainer");
+ function popHostContainer() {
+ pop(contextStackCursor);
+ pop(contextFiberStackCursor);
+ pop(rootInstanceStackCursor);
+ }
+ __name(popHostContainer, "popHostContainer");
+ function pushHostContext(fiber) {
+ null !== fiber.memoizedState && push(hostTransitionProviderCursor, fiber);
+ var context = contextStackCursor.current, nextContext = getChildHostContext(context, fiber.type);
+ context !== nextContext && (push(contextFiberStackCursor, fiber), push(contextStackCursor, nextContext));
+ }
+ __name(pushHostContext, "pushHostContext");
+ function popHostContext(fiber) {
+ contextFiberStackCursor.current === fiber && (pop(contextStackCursor), pop(contextFiberStackCursor));
+ hostTransitionProviderCursor.current === fiber && (pop(hostTransitionProviderCursor), isPrimaryRenderer ? HostTransitionContext._currentValue = NotPendingTransition : HostTransitionContext._currentValue2 = NotPendingTransition);
+ }
+ __name(popHostContext, "popHostContext");
+ function throwOnHydrationMismatch(fiber) {
+ var error51 = Error(
+ formatProdErrorMessage(
+ 418,
+ 1 < arguments.length && void 0 !== arguments[1] && arguments[1] ? "text" : "HTML",
+ ""
+ )
+ );
+ queueHydrationError(createCapturedValueAtFiber(error51, fiber));
+ throw HydrationMismatchException;
+ }
+ __name(throwOnHydrationMismatch, "throwOnHydrationMismatch");
+ function prepareToHydrateHostInstance(fiber, hostContext) {
+ if (!supportsHydration) throw Error(formatProdErrorMessage(175));
+ hydrateInstance(
+ fiber.stateNode,
+ fiber.type,
+ fiber.memoizedProps,
+ hostContext,
+ fiber
+ ) || throwOnHydrationMismatch(fiber, true);
+ }
+ __name(prepareToHydrateHostInstance, "prepareToHydrateHostInstance");
+ function popToNextHostParent(fiber) {
+ for (hydrationParentFiber = fiber.return; hydrationParentFiber; )
+ switch (hydrationParentFiber.tag) {
+ case 5:
+ case 31:
+ case 13:
+ rootOrSingletonContext = false;
+ return;
+ case 27:
+ case 3:
+ rootOrSingletonContext = true;
+ return;
+ default:
+ hydrationParentFiber = hydrationParentFiber.return;
+ }
+ }
+ __name(popToNextHostParent, "popToNextHostParent");
+ function popHydrationState(fiber) {
+ if (!supportsHydration || fiber !== hydrationParentFiber) return false;
+ if (!isHydrating) return popToNextHostParent(fiber), isHydrating = true, false;
+ var tag = fiber.tag;
+ supportsSingletons ? 3 !== tag && 27 !== tag && (5 !== tag || shouldDeleteUnhydratedTailInstances(fiber.type) && !shouldSetTextContent(fiber.type, fiber.memoizedProps)) && nextHydratableInstance && throwOnHydrationMismatch(fiber) : 3 !== tag && (5 !== tag || shouldDeleteUnhydratedTailInstances(fiber.type) && !shouldSetTextContent(fiber.type, fiber.memoizedProps)) && nextHydratableInstance && throwOnHydrationMismatch(fiber);
+ popToNextHostParent(fiber);
+ if (13 === tag) {
+ if (!supportsHydration) throw Error(formatProdErrorMessage(316));
+ fiber = fiber.memoizedState;
+ fiber = null !== fiber ? fiber.dehydrated : null;
+ if (!fiber) throw Error(formatProdErrorMessage(317));
+ nextHydratableInstance = getNextHydratableInstanceAfterSuspenseInstance(fiber);
+ } else if (31 === tag) {
+ fiber = fiber.memoizedState;
+ fiber = null !== fiber ? fiber.dehydrated : null;
+ if (!fiber) throw Error(formatProdErrorMessage(317));
+ nextHydratableInstance = getNextHydratableInstanceAfterActivityInstance(fiber);
+ } else
+ nextHydratableInstance = supportsSingletons && 27 === tag ? getNextHydratableSiblingAfterSingleton(
+ fiber.type,
+ nextHydratableInstance
+ ) : hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null;
+ return true;
+ }
+ __name(popHydrationState, "popHydrationState");
+ function resetHydrationState() {
+ supportsHydration && (nextHydratableInstance = hydrationParentFiber = null, isHydrating = false);
+ }
+ __name(resetHydrationState, "resetHydrationState");
+ function upgradeHydrationErrorsToRecoverable() {
+ var queuedErrors = hydrationErrors;
+ null !== queuedErrors && (null === workInProgressRootRecoverableErrors ? workInProgressRootRecoverableErrors = queuedErrors : workInProgressRootRecoverableErrors.push.apply(
+ workInProgressRootRecoverableErrors,
+ queuedErrors
+ ), hydrationErrors = null);
+ return queuedErrors;
+ }
+ __name(upgradeHydrationErrorsToRecoverable, "upgradeHydrationErrorsToRecoverable");
+ function queueHydrationError(error51) {
+ null === hydrationErrors ? hydrationErrors = [error51] : hydrationErrors.push(error51);
+ }
+ __name(queueHydrationError, "queueHydrationError");
+ function pushProvider(providerFiber, context, nextValue) {
+ isPrimaryRenderer ? (push(valueCursor, context._currentValue), context._currentValue = nextValue) : (push(valueCursor, context._currentValue2), context._currentValue2 = nextValue);
+ }
+ __name(pushProvider, "pushProvider");
+ function popProvider(context) {
+ var currentValue = valueCursor.current;
+ isPrimaryRenderer ? context._currentValue = currentValue : context._currentValue2 = currentValue;
+ pop(valueCursor);
+ }
+ __name(popProvider, "popProvider");
+ function scheduleContextWorkOnParentPath(parent, renderLanes2, propagationRoot) {
+ for (; null !== parent; ) {
+ var alternate = parent.alternate;
+ (parent.childLanes & renderLanes2) !== renderLanes2 ? (parent.childLanes |= renderLanes2, null !== alternate && (alternate.childLanes |= renderLanes2)) : null !== alternate && (alternate.childLanes & renderLanes2) !== renderLanes2 && (alternate.childLanes |= renderLanes2);
+ if (parent === propagationRoot) break;
+ parent = parent.return;
+ }
+ }
+ __name(scheduleContextWorkOnParentPath, "scheduleContextWorkOnParentPath");
+ function propagateContextChanges(workInProgress2, contexts, renderLanes2, forcePropagateEntireTree) {
+ var fiber = workInProgress2.child;
+ null !== fiber && (fiber.return = workInProgress2);
+ for (; null !== fiber; ) {
+ var list = fiber.dependencies;
+ if (null !== list) {
+ var nextFiber = fiber.child;
+ list = list.firstContext;
+ a: for (; null !== list; ) {
+ var dependency = list;
+ list = fiber;
+ for (var i = 0; i < contexts.length; i++)
+ if (dependency.context === contexts[i]) {
+ list.lanes |= renderLanes2;
+ dependency = list.alternate;
+ null !== dependency && (dependency.lanes |= renderLanes2);
+ scheduleContextWorkOnParentPath(
+ list.return,
+ renderLanes2,
+ workInProgress2
+ );
+ forcePropagateEntireTree || (nextFiber = null);
+ break a;
+ }
+ list = dependency.next;
+ }
+ } else if (18 === fiber.tag) {
+ nextFiber = fiber.return;
+ if (null === nextFiber) throw Error(formatProdErrorMessage(341));
+ nextFiber.lanes |= renderLanes2;
+ list = nextFiber.alternate;
+ null !== list && (list.lanes |= renderLanes2);
+ scheduleContextWorkOnParentPath(nextFiber, renderLanes2, workInProgress2);
+ nextFiber = null;
+ } else nextFiber = fiber.child;
+ if (null !== nextFiber) nextFiber.return = fiber;
+ else
+ for (nextFiber = fiber; null !== nextFiber; ) {
+ if (nextFiber === workInProgress2) {
+ nextFiber = null;
+ break;
+ }
+ fiber = nextFiber.sibling;
+ if (null !== fiber) {
+ fiber.return = nextFiber.return;
+ nextFiber = fiber;
+ break;
+ }
+ nextFiber = nextFiber.return;
+ }
+ fiber = nextFiber;
+ }
+ }
+ __name(propagateContextChanges, "propagateContextChanges");
+ function propagateParentContextChanges(current, workInProgress2, renderLanes2, forcePropagateEntireTree) {
+ current = null;
+ for (var parent = workInProgress2, isInsidePropagationBailout = false; null !== parent; ) {
+ if (!isInsidePropagationBailout) {
+ if (0 !== (parent.flags & 524288)) isInsidePropagationBailout = true;
+ else if (0 !== (parent.flags & 262144)) break;
+ }
+ if (10 === parent.tag) {
+ var currentParent = parent.alternate;
+ if (null === currentParent) throw Error(formatProdErrorMessage(387));
+ currentParent = currentParent.memoizedProps;
+ if (null !== currentParent) {
+ var context = parent.type;
+ objectIs(parent.pendingProps.value, currentParent.value) || (null !== current ? current.push(context) : current = [context]);
+ }
+ } else if (parent === hostTransitionProviderCursor.current) {
+ currentParent = parent.alternate;
+ if (null === currentParent) throw Error(formatProdErrorMessage(387));
+ currentParent.memoizedState.memoizedState !== parent.memoizedState.memoizedState && (null !== current ? current.push(HostTransitionContext) : current = [HostTransitionContext]);
+ }
+ parent = parent.return;
+ }
+ null !== current && propagateContextChanges(
+ workInProgress2,
+ current,
+ renderLanes2,
+ forcePropagateEntireTree
+ );
+ workInProgress2.flags |= 262144;
+ }
+ __name(propagateParentContextChanges, "propagateParentContextChanges");
+ function checkIfContextChanged(currentDependencies) {
+ for (currentDependencies = currentDependencies.firstContext; null !== currentDependencies; ) {
+ var context = currentDependencies.context;
+ if (!objectIs(
+ isPrimaryRenderer ? context._currentValue : context._currentValue2,
+ currentDependencies.memoizedValue
+ ))
+ return true;
+ currentDependencies = currentDependencies.next;
+ }
+ return false;
+ }
+ __name(checkIfContextChanged, "checkIfContextChanged");
+ function prepareToReadContext(workInProgress2) {
+ currentlyRenderingFiber$1 = workInProgress2;
+ lastContextDependency = null;
+ workInProgress2 = workInProgress2.dependencies;
+ null !== workInProgress2 && (workInProgress2.firstContext = null);
+ }
+ __name(prepareToReadContext, "prepareToReadContext");
+ function readContext(context) {
+ return readContextForConsumer(currentlyRenderingFiber$1, context);
+ }
+ __name(readContext, "readContext");
+ function readContextDuringReconciliation(consumer, context) {
+ null === currentlyRenderingFiber$1 && prepareToReadContext(consumer);
+ return readContextForConsumer(consumer, context);
+ }
+ __name(readContextDuringReconciliation, "readContextDuringReconciliation");
+ function readContextForConsumer(consumer, context) {
+ var value = isPrimaryRenderer ? context._currentValue : context._currentValue2;
+ context = { context, memoizedValue: value, next: null };
+ if (null === lastContextDependency) {
+ if (null === consumer) throw Error(formatProdErrorMessage(308));
+ lastContextDependency = context;
+ consumer.dependencies = { lanes: 0, firstContext: context };
+ consumer.flags |= 524288;
+ } else lastContextDependency = lastContextDependency.next = context;
+ return value;
+ }
+ __name(readContextForConsumer, "readContextForConsumer");
+ function createCache() {
+ return {
+ controller: new AbortControllerLocal(),
+ data: /* @__PURE__ */ new Map(),
+ refCount: 0
+ };
+ }
+ __name(createCache, "createCache");
+ function releaseCache(cache3) {
+ cache3.refCount--;
+ 0 === cache3.refCount && scheduleCallback$2(NormalPriority, function() {
+ cache3.controller.abort();
+ });
+ }
+ __name(releaseCache, "releaseCache");
+ function noop$1() {
+ }
+ __name(noop$1, "noop$1");
+ function ensureRootIsScheduled(root) {
+ root !== lastScheduledRoot && null === root.next && (null === lastScheduledRoot ? firstScheduledRoot = lastScheduledRoot = root : lastScheduledRoot = lastScheduledRoot.next = root);
+ mightHavePendingSyncWork = true;
+ didScheduleMicrotask || (didScheduleMicrotask = true, scheduleImmediateRootScheduleTask());
+ }
+ __name(ensureRootIsScheduled, "ensureRootIsScheduled");
+ function flushSyncWorkAcrossRoots_impl(syncTransitionLanes, onlyLegacy) {
+ if (!isFlushingWork && mightHavePendingSyncWork) {
+ isFlushingWork = true;
+ do {
+ var didPerformSomeWork = false;
+ for (var root = firstScheduledRoot; null !== root; ) {
+ if (!onlyLegacy)
+ if (0 !== syncTransitionLanes) {
+ var pendingLanes = root.pendingLanes;
+ if (0 === pendingLanes) var JSCompiler_inline_result = 0;
+ else {
+ var suspendedLanes = root.suspendedLanes, pingedLanes = root.pingedLanes;
+ JSCompiler_inline_result = (1 << 31 - clz32(42 | syncTransitionLanes) + 1) - 1;
+ JSCompiler_inline_result &= pendingLanes & ~(suspendedLanes & ~pingedLanes);
+ JSCompiler_inline_result = JSCompiler_inline_result & 201326741 ? JSCompiler_inline_result & 201326741 | 1 : JSCompiler_inline_result ? JSCompiler_inline_result | 2 : 0;
+ }
+ 0 !== JSCompiler_inline_result && (didPerformSomeWork = true, performSyncWorkOnRoot(root, JSCompiler_inline_result));
+ } else
+ JSCompiler_inline_result = workInProgressRootRenderLanes, JSCompiler_inline_result = getNextLanes(
+ root,
+ root === workInProgressRoot ? JSCompiler_inline_result : 0,
+ null !== root.cancelPendingCommit || root.timeoutHandle !== noTimeout
+ ), 0 === (JSCompiler_inline_result & 3) || checkIfRootIsPrerendering(root, JSCompiler_inline_result) || (didPerformSomeWork = true, performSyncWorkOnRoot(root, JSCompiler_inline_result));
+ root = root.next;
+ }
+ } while (didPerformSomeWork);
+ isFlushingWork = false;
+ }
+ }
+ __name(flushSyncWorkAcrossRoots_impl, "flushSyncWorkAcrossRoots_impl");
+ function processRootScheduleInImmediateTask() {
+ processRootScheduleInMicrotask();
+ }
+ __name(processRootScheduleInImmediateTask, "processRootScheduleInImmediateTask");
+ function processRootScheduleInMicrotask() {
+ mightHavePendingSyncWork = didScheduleMicrotask = false;
+ var syncTransitionLanes = 0;
+ 0 !== currentEventTransitionLane && shouldAttemptEagerTransition() && (syncTransitionLanes = currentEventTransitionLane);
+ for (var currentTime = now(), prev = null, root = firstScheduledRoot; null !== root; ) {
+ var next = root.next, nextLanes = scheduleTaskForRootDuringMicrotask(root, currentTime);
+ if (0 === nextLanes)
+ root.next = null, null === prev ? firstScheduledRoot = next : prev.next = next, null === next && (lastScheduledRoot = prev);
+ else if (prev = root, 0 !== syncTransitionLanes || 0 !== (nextLanes & 3))
+ mightHavePendingSyncWork = true;
+ root = next;
+ }
+ 0 !== pendingEffectsStatus && 5 !== pendingEffectsStatus || flushSyncWorkAcrossRoots_impl(syncTransitionLanes, false);
+ 0 !== currentEventTransitionLane && (currentEventTransitionLane = 0);
+ }
+ __name(processRootScheduleInMicrotask, "processRootScheduleInMicrotask");
+ function scheduleTaskForRootDuringMicrotask(root, currentTime) {
+ for (var suspendedLanes = root.suspendedLanes, pingedLanes = root.pingedLanes, expirationTimes = root.expirationTimes, lanes = root.pendingLanes & -62914561; 0 < lanes; ) {
+ var index$3 = 31 - clz32(lanes), lane = 1 << index$3, expirationTime = expirationTimes[index$3];
+ if (-1 === expirationTime) {
+ if (0 === (lane & suspendedLanes) || 0 !== (lane & pingedLanes))
+ expirationTimes[index$3] = computeExpirationTime(lane, currentTime);
+ } else expirationTime <= currentTime && (root.expiredLanes |= lane);
+ lanes &= ~lane;
+ }
+ currentTime = workInProgressRoot;
+ suspendedLanes = workInProgressRootRenderLanes;
+ suspendedLanes = getNextLanes(
+ root,
+ root === currentTime ? suspendedLanes : 0,
+ null !== root.cancelPendingCommit || root.timeoutHandle !== noTimeout
+ );
+ pingedLanes = root.callbackNode;
+ if (0 === suspendedLanes || root === currentTime && (2 === workInProgressSuspendedReason || 9 === workInProgressSuspendedReason) || null !== root.cancelPendingCommit)
+ return null !== pingedLanes && null !== pingedLanes && cancelCallback$1(pingedLanes), root.callbackNode = null, root.callbackPriority = 0;
+ if (0 === (suspendedLanes & 3) || checkIfRootIsPrerendering(root, suspendedLanes)) {
+ currentTime = suspendedLanes & -suspendedLanes;
+ if (currentTime === root.callbackPriority) return currentTime;
+ null !== pingedLanes && cancelCallback$1(pingedLanes);
+ switch (lanesToEventPriority(suspendedLanes)) {
+ case 2:
+ case 8:
+ suspendedLanes = UserBlockingPriority;
+ break;
+ case 32:
+ suspendedLanes = NormalPriority$1;
+ break;
+ case 268435456:
+ suspendedLanes = IdlePriority;
+ break;
+ default:
+ suspendedLanes = NormalPriority$1;
+ }
+ pingedLanes = performWorkOnRootViaSchedulerTask.bind(null, root);
+ suspendedLanes = scheduleCallback$3(suspendedLanes, pingedLanes);
+ root.callbackPriority = currentTime;
+ root.callbackNode = suspendedLanes;
+ return currentTime;
+ }
+ null !== pingedLanes && null !== pingedLanes && cancelCallback$1(pingedLanes);
+ root.callbackPriority = 2;
+ root.callbackNode = null;
+ return 2;
+ }
+ __name(scheduleTaskForRootDuringMicrotask, "scheduleTaskForRootDuringMicrotask");
+ function performWorkOnRootViaSchedulerTask(root, didTimeout) {
+ if (0 !== pendingEffectsStatus && 5 !== pendingEffectsStatus)
+ return root.callbackNode = null, root.callbackPriority = 0, null;
+ var originalCallbackNode = root.callbackNode;
+ if (flushPendingEffects() && root.callbackNode !== originalCallbackNode)
+ return null;
+ var workInProgressRootRenderLanes$jscomp$0 = workInProgressRootRenderLanes;
+ workInProgressRootRenderLanes$jscomp$0 = getNextLanes(
+ root,
+ root === workInProgressRoot ? workInProgressRootRenderLanes$jscomp$0 : 0,
+ null !== root.cancelPendingCommit || root.timeoutHandle !== noTimeout
+ );
+ if (0 === workInProgressRootRenderLanes$jscomp$0) return null;
+ performWorkOnRoot(root, workInProgressRootRenderLanes$jscomp$0, didTimeout);
+ scheduleTaskForRootDuringMicrotask(root, now());
+ return null != root.callbackNode && root.callbackNode === originalCallbackNode ? performWorkOnRootViaSchedulerTask.bind(null, root) : null;
+ }
+ __name(performWorkOnRootViaSchedulerTask, "performWorkOnRootViaSchedulerTask");
+ function performSyncWorkOnRoot(root, lanes) {
+ if (flushPendingEffects()) return null;
+ performWorkOnRoot(root, lanes, true);
+ }
+ __name(performSyncWorkOnRoot, "performSyncWorkOnRoot");
+ function scheduleImmediateRootScheduleTask() {
+ supportsMicrotasks ? scheduleMicrotask(function() {
+ 0 !== (executionContext & 6) ? scheduleCallback$3(
+ ImmediatePriority,
+ processRootScheduleInImmediateTask
+ ) : processRootScheduleInMicrotask();
+ }) : scheduleCallback$3(
+ ImmediatePriority,
+ processRootScheduleInImmediateTask
+ );
+ }
+ __name(scheduleImmediateRootScheduleTask, "scheduleImmediateRootScheduleTask");
+ function requestTransitionLane() {
+ if (0 === currentEventTransitionLane) {
+ var actionScopeLane = currentEntangledLane;
+ 0 === actionScopeLane && (actionScopeLane = nextTransitionUpdateLane, nextTransitionUpdateLane <<= 1, 0 === (nextTransitionUpdateLane & 261888) && (nextTransitionUpdateLane = 256));
+ currentEventTransitionLane = actionScopeLane;
+ }
+ return currentEventTransitionLane;
+ }
+ __name(requestTransitionLane, "requestTransitionLane");
+ function entangleAsyncAction(transition, thenable) {
+ if (null === currentEntangledListeners) {
+ var entangledListeners = currentEntangledListeners = [];
+ currentEntangledPendingCount = 0;
+ currentEntangledLane = requestTransitionLane();
+ currentEntangledActionThenable = {
+ status: "pending",
+ value: void 0,
+ then: /* @__PURE__ */ __name(function(resolve16) {
+ entangledListeners.push(resolve16);
+ }, "then")
+ };
+ }
+ currentEntangledPendingCount++;
+ thenable.then(pingEngtangledActionScope, pingEngtangledActionScope);
+ return thenable;
+ }
+ __name(entangleAsyncAction, "entangleAsyncAction");
+ function pingEngtangledActionScope() {
+ if (0 === --currentEntangledPendingCount && null !== currentEntangledListeners) {
+ null !== currentEntangledActionThenable && (currentEntangledActionThenable.status = "fulfilled");
+ var listeners = currentEntangledListeners;
+ currentEntangledListeners = null;
+ currentEntangledLane = 0;
+ currentEntangledActionThenable = null;
+ for (var i = 0; i < listeners.length; i++) (0, listeners[i])();
+ }
+ }
+ __name(pingEngtangledActionScope, "pingEngtangledActionScope");
+ function chainThenableValue(thenable, result) {
+ var listeners = [], thenableWithOverride = {
+ status: "pending",
+ value: null,
+ reason: null,
+ then: /* @__PURE__ */ __name(function(resolve16) {
+ listeners.push(resolve16);
+ }, "then")
+ };
+ thenable.then(
+ function() {
+ thenableWithOverride.status = "fulfilled";
+ thenableWithOverride.value = result;
+ for (var i = 0; i < listeners.length; i++) (0, listeners[i])(result);
+ },
+ function(error51) {
+ thenableWithOverride.status = "rejected";
+ thenableWithOverride.reason = error51;
+ for (error51 = 0; error51 < listeners.length; error51++)
+ (0, listeners[error51])(void 0);
+ }
+ );
+ return thenableWithOverride;
+ }
+ __name(chainThenableValue, "chainThenableValue");
+ function peekCacheFromPool() {
+ var cacheResumedFromPreviousRender = resumedCache.current;
+ return null !== cacheResumedFromPreviousRender ? cacheResumedFromPreviousRender : workInProgressRoot.pooledCache;
+ }
+ __name(peekCacheFromPool, "peekCacheFromPool");
+ function pushTransition(offscreenWorkInProgress, prevCachePool) {
+ null === prevCachePool ? push(resumedCache, resumedCache.current) : push(resumedCache, prevCachePool.pool);
+ }
+ __name(pushTransition, "pushTransition");
+ function getSuspendedCache() {
+ var cacheFromPool = peekCacheFromPool();
+ return null === cacheFromPool ? null : {
+ parent: isPrimaryRenderer ? CacheContext._currentValue : CacheContext._currentValue2,
+ pool: cacheFromPool
+ };
+ }
+ __name(getSuspendedCache, "getSuspendedCache");
+ function shallowEqual(objA, objB) {
+ if (objectIs(objA, objB)) return true;
+ if ("object" !== typeof objA || null === objA || "object" !== typeof objB || null === objB)
+ return false;
+ var keysA = Object.keys(objA), keysB = Object.keys(objB);
+ if (keysA.length !== keysB.length) return false;
+ for (keysB = 0; keysB < keysA.length; keysB++) {
+ var currentKey = keysA[keysB];
+ if (!hasOwnProperty2.call(objB, currentKey) || !objectIs(objA[currentKey], objB[currentKey]))
+ return false;
+ }
+ return true;
+ }
+ __name(shallowEqual, "shallowEqual");
+ function isThenableResolved(thenable) {
+ thenable = thenable.status;
+ return "fulfilled" === thenable || "rejected" === thenable;
+ }
+ __name(isThenableResolved, "isThenableResolved");
+ function trackUsedThenable(thenableState2, thenable, index) {
+ index = thenableState2[index];
+ void 0 === index ? thenableState2.push(thenable) : index !== thenable && (thenable.then(noop$1, noop$1), thenable = index);
+ switch (thenable.status) {
+ case "fulfilled":
+ return thenable.value;
+ case "rejected":
+ throw thenableState2 = thenable.reason, checkIfUseWrappedInAsyncCatch(thenableState2), thenableState2;
+ default:
+ if ("string" === typeof thenable.status) thenable.then(noop$1, noop$1);
+ else {
+ thenableState2 = workInProgressRoot;
+ if (null !== thenableState2 && 100 < thenableState2.shellSuspendCounter)
+ throw Error(formatProdErrorMessage(482));
+ thenableState2 = thenable;
+ thenableState2.status = "pending";
+ thenableState2.then(
+ function(fulfilledValue) {
+ if ("pending" === thenable.status) {
+ var fulfilledThenable = thenable;
+ fulfilledThenable.status = "fulfilled";
+ fulfilledThenable.value = fulfilledValue;
+ }
+ },
+ function(error51) {
+ if ("pending" === thenable.status) {
+ var rejectedThenable = thenable;
+ rejectedThenable.status = "rejected";
+ rejectedThenable.reason = error51;
+ }
+ }
+ );
+ }
+ switch (thenable.status) {
+ case "fulfilled":
+ return thenable.value;
+ case "rejected":
+ throw thenableState2 = thenable.reason, checkIfUseWrappedInAsyncCatch(thenableState2), thenableState2;
+ }
+ suspendedThenable = thenable;
+ throw SuspenseException;
+ }
+ }
+ __name(trackUsedThenable, "trackUsedThenable");
+ function resolveLazy(lazyType) {
+ try {
+ var init = lazyType._init;
+ return init(lazyType._payload);
+ } catch (x) {
+ if (null !== x && "object" === typeof x && "function" === typeof x.then)
+ throw suspendedThenable = x, SuspenseException;
+ throw x;
+ }
+ }
+ __name(resolveLazy, "resolveLazy");
+ function getSuspendedThenable() {
+ if (null === suspendedThenable) throw Error(formatProdErrorMessage(459));
+ var thenable = suspendedThenable;
+ suspendedThenable = null;
+ return thenable;
+ }
+ __name(getSuspendedThenable, "getSuspendedThenable");
+ function checkIfUseWrappedInAsyncCatch(rejectedReason) {
+ if (rejectedReason === SuspenseException || rejectedReason === SuspenseActionException)
+ throw Error(formatProdErrorMessage(483));
+ }
+ __name(checkIfUseWrappedInAsyncCatch, "checkIfUseWrappedInAsyncCatch");
+ function unwrapThenable(thenable) {
+ var index = thenableIndexCounter$1;
+ thenableIndexCounter$1 += 1;
+ null === thenableState$1 && (thenableState$1 = []);
+ return trackUsedThenable(thenableState$1, thenable, index);
+ }
+ __name(unwrapThenable, "unwrapThenable");
+ function coerceRef(workInProgress2, element) {
+ element = element.props.ref;
+ workInProgress2.ref = void 0 !== element ? element : null;
+ }
+ __name(coerceRef, "coerceRef");
+ function throwOnInvalidObjectTypeImpl(returnFiber, newChild) {
+ if (newChild.$$typeof === REACT_LEGACY_ELEMENT_TYPE)
+ throw Error(formatProdErrorMessage(525));
+ returnFiber = Object.prototype.toString.call(newChild);
+ throw Error(
+ formatProdErrorMessage(
+ 31,
+ "[object Object]" === returnFiber ? "object with keys {" + Object.keys(newChild).join(", ") + "}" : returnFiber
+ )
+ );
+ }
+ __name(throwOnInvalidObjectTypeImpl, "throwOnInvalidObjectTypeImpl");
+ function createChildReconciler(shouldTrackSideEffects) {
+ function deleteChild(returnFiber, childToDelete) {
+ if (shouldTrackSideEffects) {
+ var deletions = returnFiber.deletions;
+ null === deletions ? (returnFiber.deletions = [childToDelete], returnFiber.flags |= 16) : deletions.push(childToDelete);
+ }
+ }
+ __name(deleteChild, "deleteChild");
+ function deleteRemainingChildren(returnFiber, currentFirstChild) {
+ if (!shouldTrackSideEffects) return null;
+ for (; null !== currentFirstChild; )
+ deleteChild(returnFiber, currentFirstChild), currentFirstChild = currentFirstChild.sibling;
+ return null;
+ }
+ __name(deleteRemainingChildren, "deleteRemainingChildren");
+ function mapRemainingChildren(currentFirstChild) {
+ for (var existingChildren = /* @__PURE__ */ new Map(); null !== currentFirstChild; )
+ null !== currentFirstChild.key ? existingChildren.set(currentFirstChild.key, currentFirstChild) : existingChildren.set(currentFirstChild.index, currentFirstChild), currentFirstChild = currentFirstChild.sibling;
+ return existingChildren;
+ }
+ __name(mapRemainingChildren, "mapRemainingChildren");
+ function useFiber(fiber, pendingProps) {
+ fiber = createWorkInProgress(fiber, pendingProps);
+ fiber.index = 0;
+ fiber.sibling = null;
+ return fiber;
+ }
+ __name(useFiber, "useFiber");
+ function placeChild(newFiber, lastPlacedIndex, newIndex) {
+ newFiber.index = newIndex;
+ if (!shouldTrackSideEffects)
+ return newFiber.flags |= 1048576, lastPlacedIndex;
+ newIndex = newFiber.alternate;
+ if (null !== newIndex)
+ return newIndex = newIndex.index, newIndex < lastPlacedIndex ? (newFiber.flags |= 67108866, lastPlacedIndex) : newIndex;
+ newFiber.flags |= 67108866;
+ return lastPlacedIndex;
+ }
+ __name(placeChild, "placeChild");
+ function placeSingleChild(newFiber) {
+ shouldTrackSideEffects && null === newFiber.alternate && (newFiber.flags |= 67108866);
+ return newFiber;
+ }
+ __name(placeSingleChild, "placeSingleChild");
+ function updateTextNode(returnFiber, current, textContent, lanes) {
+ if (null === current || 6 !== current.tag)
+ return current = createFiberFromText(textContent, returnFiber.mode, lanes), current.return = returnFiber, current;
+ current = useFiber(current, textContent);
+ current.return = returnFiber;
+ return current;
+ }
+ __name(updateTextNode, "updateTextNode");
+ function updateElement(returnFiber, current, element, lanes) {
+ var elementType = element.type;
+ if (elementType === REACT_FRAGMENT_TYPE)
+ return updateFragment(
+ returnFiber,
+ current,
+ element.props.children,
+ lanes,
+ element.key
+ );
+ if (null !== current && (current.elementType === elementType || "object" === typeof elementType && null !== elementType && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === current.type))
+ return current = useFiber(current, element.props), coerceRef(current, element), current.return = returnFiber, current;
+ current = createFiberFromTypeAndProps(
+ element.type,
+ element.key,
+ element.props,
+ null,
+ returnFiber.mode,
+ lanes
+ );
+ coerceRef(current, element);
+ current.return = returnFiber;
+ return current;
+ }
+ __name(updateElement, "updateElement");
+ function updatePortal(returnFiber, current, portal, lanes) {
+ if (null === current || 4 !== current.tag || current.stateNode.containerInfo !== portal.containerInfo || current.stateNode.implementation !== portal.implementation)
+ return current = createFiberFromPortal(portal, returnFiber.mode, lanes), current.return = returnFiber, current;
+ current = useFiber(current, portal.children || []);
+ current.return = returnFiber;
+ return current;
+ }
+ __name(updatePortal, "updatePortal");
+ function updateFragment(returnFiber, current, fragment, lanes, key) {
+ if (null === current || 7 !== current.tag)
+ return current = createFiberFromFragment(
+ fragment,
+ returnFiber.mode,
+ lanes,
+ key
+ ), current.return = returnFiber, current;
+ current = useFiber(current, fragment);
+ current.return = returnFiber;
+ return current;
+ }
+ __name(updateFragment, "updateFragment");
+ function createChild(returnFiber, newChild, lanes) {
+ if ("string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild)
+ return newChild = createFiberFromText(
+ "" + newChild,
+ returnFiber.mode,
+ lanes
+ ), newChild.return = returnFiber, newChild;
+ if ("object" === typeof newChild && null !== newChild) {
+ switch (newChild.$$typeof) {
+ case REACT_ELEMENT_TYPE:
+ return lanes = createFiberFromTypeAndProps(
+ newChild.type,
+ newChild.key,
+ newChild.props,
+ null,
+ returnFiber.mode,
+ lanes
+ ), coerceRef(lanes, newChild), lanes.return = returnFiber, lanes;
+ case REACT_PORTAL_TYPE:
+ return newChild = createFiberFromPortal(
+ newChild,
+ returnFiber.mode,
+ lanes
+ ), newChild.return = returnFiber, newChild;
+ case REACT_LAZY_TYPE:
+ return newChild = resolveLazy(newChild), createChild(returnFiber, newChild, lanes);
+ }
+ if (isArrayImpl(newChild) || getIteratorFn(newChild))
+ return newChild = createFiberFromFragment(
+ newChild,
+ returnFiber.mode,
+ lanes,
+ null
+ ), newChild.return = returnFiber, newChild;
+ if ("function" === typeof newChild.then)
+ return createChild(returnFiber, unwrapThenable(newChild), lanes);
+ if (newChild.$$typeof === REACT_CONTEXT_TYPE)
+ return createChild(
+ returnFiber,
+ readContextDuringReconciliation(returnFiber, newChild),
+ lanes
+ );
+ throwOnInvalidObjectTypeImpl(returnFiber, newChild);
+ }
+ return null;
+ }
+ __name(createChild, "createChild");
+ function updateSlot(returnFiber, oldFiber, newChild, lanes) {
+ var key = null !== oldFiber ? oldFiber.key : null;
+ if ("string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild)
+ return null !== key ? null : updateTextNode(returnFiber, oldFiber, "" + newChild, lanes);
+ if ("object" === typeof newChild && null !== newChild) {
+ switch (newChild.$$typeof) {
+ case REACT_ELEMENT_TYPE:
+ return newChild.key === key ? updateElement(returnFiber, oldFiber, newChild, lanes) : null;
+ case REACT_PORTAL_TYPE:
+ return newChild.key === key ? updatePortal(returnFiber, oldFiber, newChild, lanes) : null;
+ case REACT_LAZY_TYPE:
+ return newChild = resolveLazy(newChild), updateSlot(returnFiber, oldFiber, newChild, lanes);
+ }
+ if (isArrayImpl(newChild) || getIteratorFn(newChild))
+ return null !== key ? null : updateFragment(returnFiber, oldFiber, newChild, lanes, null);
+ if ("function" === typeof newChild.then)
+ return updateSlot(
+ returnFiber,
+ oldFiber,
+ unwrapThenable(newChild),
+ lanes
+ );
+ if (newChild.$$typeof === REACT_CONTEXT_TYPE)
+ return updateSlot(
+ returnFiber,
+ oldFiber,
+ readContextDuringReconciliation(returnFiber, newChild),
+ lanes
+ );
+ throwOnInvalidObjectTypeImpl(returnFiber, newChild);
+ }
+ return null;
+ }
+ __name(updateSlot, "updateSlot");
+ function updateFromMap(existingChildren, returnFiber, newIdx, newChild, lanes) {
+ if ("string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild)
+ return existingChildren = existingChildren.get(newIdx) || null, updateTextNode(returnFiber, existingChildren, "" + newChild, lanes);
+ if ("object" === typeof newChild && null !== newChild) {
+ switch (newChild.$$typeof) {
+ case REACT_ELEMENT_TYPE:
+ return existingChildren = existingChildren.get(
+ null === newChild.key ? newIdx : newChild.key
+ ) || null, updateElement(returnFiber, existingChildren, newChild, lanes);
+ case REACT_PORTAL_TYPE:
+ return existingChildren = existingChildren.get(
+ null === newChild.key ? newIdx : newChild.key
+ ) || null, updatePortal(returnFiber, existingChildren, newChild, lanes);
+ case REACT_LAZY_TYPE:
+ return newChild = resolveLazy(newChild), updateFromMap(
+ existingChildren,
+ returnFiber,
+ newIdx,
+ newChild,
+ lanes
+ );
+ }
+ if (isArrayImpl(newChild) || getIteratorFn(newChild))
+ return existingChildren = existingChildren.get(newIdx) || null, updateFragment(returnFiber, existingChildren, newChild, lanes, null);
+ if ("function" === typeof newChild.then)
+ return updateFromMap(
+ existingChildren,
+ returnFiber,
+ newIdx,
+ unwrapThenable(newChild),
+ lanes
+ );
+ if (newChild.$$typeof === REACT_CONTEXT_TYPE)
+ return updateFromMap(
+ existingChildren,
+ returnFiber,
+ newIdx,
+ readContextDuringReconciliation(returnFiber, newChild),
+ lanes
+ );
+ throwOnInvalidObjectTypeImpl(returnFiber, newChild);
+ }
+ return null;
+ }
+ __name(updateFromMap, "updateFromMap");
+ function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, lanes) {
+ for (var resultingFirstChild = null, previousNewFiber = null, oldFiber = currentFirstChild, newIdx = currentFirstChild = 0, nextOldFiber = null; null !== oldFiber && newIdx < newChildren.length; newIdx++) {
+ oldFiber.index > newIdx ? (nextOldFiber = oldFiber, oldFiber = null) : nextOldFiber = oldFiber.sibling;
+ var newFiber = updateSlot(
+ returnFiber,
+ oldFiber,
+ newChildren[newIdx],
+ lanes
+ );
+ if (null === newFiber) {
+ null === oldFiber && (oldFiber = nextOldFiber);
+ break;
+ }
+ shouldTrackSideEffects && oldFiber && null === newFiber.alternate && deleteChild(returnFiber, oldFiber);
+ currentFirstChild = placeChild(newFiber, currentFirstChild, newIdx);
+ null === previousNewFiber ? resultingFirstChild = newFiber : previousNewFiber.sibling = newFiber;
+ previousNewFiber = newFiber;
+ oldFiber = nextOldFiber;
+ }
+ if (newIdx === newChildren.length)
+ return deleteRemainingChildren(returnFiber, oldFiber), isHydrating && pushTreeFork(returnFiber, newIdx), resultingFirstChild;
+ if (null === oldFiber) {
+ for (; newIdx < newChildren.length; newIdx++)
+ oldFiber = createChild(returnFiber, newChildren[newIdx], lanes), null !== oldFiber && (currentFirstChild = placeChild(
+ oldFiber,
+ currentFirstChild,
+ newIdx
+ ), null === previousNewFiber ? resultingFirstChild = oldFiber : previousNewFiber.sibling = oldFiber, previousNewFiber = oldFiber);
+ isHydrating && pushTreeFork(returnFiber, newIdx);
+ return resultingFirstChild;
+ }
+ for (oldFiber = mapRemainingChildren(oldFiber); newIdx < newChildren.length; newIdx++)
+ nextOldFiber = updateFromMap(
+ oldFiber,
+ returnFiber,
+ newIdx,
+ newChildren[newIdx],
+ lanes
+ ), null !== nextOldFiber && (shouldTrackSideEffects && null !== nextOldFiber.alternate && oldFiber.delete(
+ null === nextOldFiber.key ? newIdx : nextOldFiber.key
+ ), currentFirstChild = placeChild(
+ nextOldFiber,
+ currentFirstChild,
+ newIdx
+ ), null === previousNewFiber ? resultingFirstChild = nextOldFiber : previousNewFiber.sibling = nextOldFiber, previousNewFiber = nextOldFiber);
+ shouldTrackSideEffects && oldFiber.forEach(function(child) {
+ return deleteChild(returnFiber, child);
+ });
+ isHydrating && pushTreeFork(returnFiber, newIdx);
+ return resultingFirstChild;
+ }
+ __name(reconcileChildrenArray, "reconcileChildrenArray");
+ function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildren, lanes) {
+ if (null == newChildren) throw Error(formatProdErrorMessage(151));
+ for (var resultingFirstChild = null, previousNewFiber = null, oldFiber = currentFirstChild, newIdx = currentFirstChild = 0, nextOldFiber = null, step = newChildren.next(); null !== oldFiber && !step.done; newIdx++, step = newChildren.next()) {
+ oldFiber.index > newIdx ? (nextOldFiber = oldFiber, oldFiber = null) : nextOldFiber = oldFiber.sibling;
+ var newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes);
+ if (null === newFiber) {
+ null === oldFiber && (oldFiber = nextOldFiber);
+ break;
+ }
+ shouldTrackSideEffects && oldFiber && null === newFiber.alternate && deleteChild(returnFiber, oldFiber);
+ currentFirstChild = placeChild(newFiber, currentFirstChild, newIdx);
+ null === previousNewFiber ? resultingFirstChild = newFiber : previousNewFiber.sibling = newFiber;
+ previousNewFiber = newFiber;
+ oldFiber = nextOldFiber;
+ }
+ if (step.done)
+ return deleteRemainingChildren(returnFiber, oldFiber), isHydrating && pushTreeFork(returnFiber, newIdx), resultingFirstChild;
+ if (null === oldFiber) {
+ for (; !step.done; newIdx++, step = newChildren.next())
+ step = createChild(returnFiber, step.value, lanes), null !== step && (currentFirstChild = placeChild(
+ step,
+ currentFirstChild,
+ newIdx
+ ), null === previousNewFiber ? resultingFirstChild = step : previousNewFiber.sibling = step, previousNewFiber = step);
+ isHydrating && pushTreeFork(returnFiber, newIdx);
+ return resultingFirstChild;
+ }
+ for (oldFiber = mapRemainingChildren(oldFiber); !step.done; newIdx++, step = newChildren.next())
+ step = updateFromMap(
+ oldFiber,
+ returnFiber,
+ newIdx,
+ step.value,
+ lanes
+ ), null !== step && (shouldTrackSideEffects && null !== step.alternate && oldFiber.delete(null === step.key ? newIdx : step.key), currentFirstChild = placeChild(step, currentFirstChild, newIdx), null === previousNewFiber ? resultingFirstChild = step : previousNewFiber.sibling = step, previousNewFiber = step);
+ shouldTrackSideEffects && oldFiber.forEach(function(child) {
+ return deleteChild(returnFiber, child);
+ });
+ isHydrating && pushTreeFork(returnFiber, newIdx);
+ return resultingFirstChild;
+ }
+ __name(reconcileChildrenIterator, "reconcileChildrenIterator");
+ function reconcileChildFibersImpl(returnFiber, currentFirstChild, newChild, lanes) {
+ "object" === typeof newChild && null !== newChild && newChild.type === REACT_FRAGMENT_TYPE && null === newChild.key && (newChild = newChild.props.children);
+ if ("object" === typeof newChild && null !== newChild) {
+ switch (newChild.$$typeof) {
+ case REACT_ELEMENT_TYPE:
+ a: {
+ for (var key = newChild.key; null !== currentFirstChild; ) {
+ if (currentFirstChild.key === key) {
+ key = newChild.type;
+ if (key === REACT_FRAGMENT_TYPE) {
+ if (7 === currentFirstChild.tag) {
+ deleteRemainingChildren(
+ returnFiber,
+ currentFirstChild.sibling
+ );
+ lanes = useFiber(
+ currentFirstChild,
+ newChild.props.children
+ );
+ lanes.return = returnFiber;
+ returnFiber = lanes;
+ break a;
+ }
+ } else if (currentFirstChild.elementType === key || "object" === typeof key && null !== key && key.$$typeof === REACT_LAZY_TYPE && resolveLazy(key) === currentFirstChild.type) {
+ deleteRemainingChildren(
+ returnFiber,
+ currentFirstChild.sibling
+ );
+ lanes = useFiber(currentFirstChild, newChild.props);
+ coerceRef(lanes, newChild);
+ lanes.return = returnFiber;
+ returnFiber = lanes;
+ break a;
+ }
+ deleteRemainingChildren(returnFiber, currentFirstChild);
+ break;
+ } else deleteChild(returnFiber, currentFirstChild);
+ currentFirstChild = currentFirstChild.sibling;
+ }
+ newChild.type === REACT_FRAGMENT_TYPE ? (lanes = createFiberFromFragment(
+ newChild.props.children,
+ returnFiber.mode,
+ lanes,
+ newChild.key
+ ), lanes.return = returnFiber, returnFiber = lanes) : (lanes = createFiberFromTypeAndProps(
+ newChild.type,
+ newChild.key,
+ newChild.props,
+ null,
+ returnFiber.mode,
+ lanes
+ ), coerceRef(lanes, newChild), lanes.return = returnFiber, returnFiber = lanes);
+ }
+ return placeSingleChild(returnFiber);
+ case REACT_PORTAL_TYPE:
+ a: {
+ for (key = newChild.key; null !== currentFirstChild; ) {
+ if (currentFirstChild.key === key)
+ if (4 === currentFirstChild.tag && currentFirstChild.stateNode.containerInfo === newChild.containerInfo && currentFirstChild.stateNode.implementation === newChild.implementation) {
+ deleteRemainingChildren(
+ returnFiber,
+ currentFirstChild.sibling
+ );
+ lanes = useFiber(
+ currentFirstChild,
+ newChild.children || []
+ );
+ lanes.return = returnFiber;
+ returnFiber = lanes;
+ break a;
+ } else {
+ deleteRemainingChildren(returnFiber, currentFirstChild);
+ break;
+ }
+ else deleteChild(returnFiber, currentFirstChild);
+ currentFirstChild = currentFirstChild.sibling;
+ }
+ lanes = createFiberFromPortal(newChild, returnFiber.mode, lanes);
+ lanes.return = returnFiber;
+ returnFiber = lanes;
+ }
+ return placeSingleChild(returnFiber);
+ case REACT_LAZY_TYPE:
+ return newChild = resolveLazy(newChild), reconcileChildFibersImpl(
+ returnFiber,
+ currentFirstChild,
+ newChild,
+ lanes
+ );
+ }
+ if (isArrayImpl(newChild))
+ return reconcileChildrenArray(
+ returnFiber,
+ currentFirstChild,
+ newChild,
+ lanes
+ );
+ if (getIteratorFn(newChild)) {
+ key = getIteratorFn(newChild);
+ if ("function" !== typeof key)
+ throw Error(formatProdErrorMessage(150));
+ newChild = key.call(newChild);
+ return reconcileChildrenIterator(
+ returnFiber,
+ currentFirstChild,
+ newChild,
+ lanes
+ );
+ }
+ if ("function" === typeof newChild.then)
+ return reconcileChildFibersImpl(
+ returnFiber,
+ currentFirstChild,
+ unwrapThenable(newChild),
+ lanes
+ );
+ if (newChild.$$typeof === REACT_CONTEXT_TYPE)
+ return reconcileChildFibersImpl(
+ returnFiber,
+ currentFirstChild,
+ readContextDuringReconciliation(returnFiber, newChild),
+ lanes
+ );
+ throwOnInvalidObjectTypeImpl(returnFiber, newChild);
+ }
+ return "string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild ? (newChild = "" + newChild, null !== currentFirstChild && 6 === currentFirstChild.tag ? (deleteRemainingChildren(returnFiber, currentFirstChild.sibling), lanes = useFiber(currentFirstChild, newChild), lanes.return = returnFiber, returnFiber = lanes) : (deleteRemainingChildren(returnFiber, currentFirstChild), lanes = createFiberFromText(newChild, returnFiber.mode, lanes), lanes.return = returnFiber, returnFiber = lanes), placeSingleChild(returnFiber)) : deleteRemainingChildren(returnFiber, currentFirstChild);
+ }
+ __name(reconcileChildFibersImpl, "reconcileChildFibersImpl");
+ return function(returnFiber, currentFirstChild, newChild, lanes) {
+ try {
+ thenableIndexCounter$1 = 0;
+ var firstChildFiber = reconcileChildFibersImpl(
+ returnFiber,
+ currentFirstChild,
+ newChild,
+ lanes
+ );
+ thenableState$1 = null;
+ return firstChildFiber;
+ } catch (x) {
+ if (x === SuspenseException || x === SuspenseActionException) throw x;
+ var fiber = createFiber(29, x, null, returnFiber.mode);
+ fiber.lanes = lanes;
+ fiber.return = returnFiber;
+ return fiber;
+ } finally {
+ }
+ };
+ }
+ __name(createChildReconciler, "createChildReconciler");
+ function finishQueueingConcurrentUpdates() {
+ for (var endIndex = concurrentQueuesIndex, i = concurrentlyUpdatedLanes = concurrentQueuesIndex = 0; i < endIndex; ) {
+ var fiber = concurrentQueues[i];
+ concurrentQueues[i++] = null;
+ var queue = concurrentQueues[i];
+ concurrentQueues[i++] = null;
+ var update = concurrentQueues[i];
+ concurrentQueues[i++] = null;
+ var lane = concurrentQueues[i];
+ concurrentQueues[i++] = null;
+ if (null !== queue && null !== update) {
+ var pending = queue.pending;
+ null === pending ? update.next = update : (update.next = pending.next, pending.next = update);
+ queue.pending = update;
+ }
+ 0 !== lane && markUpdateLaneFromFiberToRoot(fiber, update, lane);
+ }
+ }
+ __name(finishQueueingConcurrentUpdates, "finishQueueingConcurrentUpdates");
+ function enqueueUpdate$1(fiber, queue, update, lane) {
+ concurrentQueues[concurrentQueuesIndex++] = fiber;
+ concurrentQueues[concurrentQueuesIndex++] = queue;
+ concurrentQueues[concurrentQueuesIndex++] = update;
+ concurrentQueues[concurrentQueuesIndex++] = lane;
+ concurrentlyUpdatedLanes |= lane;
+ fiber.lanes |= lane;
+ fiber = fiber.alternate;
+ null !== fiber && (fiber.lanes |= lane);
+ }
+ __name(enqueueUpdate$1, "enqueueUpdate$1");
+ function enqueueConcurrentHookUpdate(fiber, queue, update, lane) {
+ enqueueUpdate$1(fiber, queue, update, lane);
+ return getRootForUpdatedFiber(fiber);
+ }
+ __name(enqueueConcurrentHookUpdate, "enqueueConcurrentHookUpdate");
+ function enqueueConcurrentRenderForLane(fiber, lane) {
+ enqueueUpdate$1(fiber, null, null, lane);
+ return getRootForUpdatedFiber(fiber);
+ }
+ __name(enqueueConcurrentRenderForLane, "enqueueConcurrentRenderForLane");
+ function markUpdateLaneFromFiberToRoot(sourceFiber, update, lane) {
+ sourceFiber.lanes |= lane;
+ var alternate = sourceFiber.alternate;
+ null !== alternate && (alternate.lanes |= lane);
+ for (var isHidden2 = false, parent = sourceFiber.return; null !== parent; )
+ parent.childLanes |= lane, alternate = parent.alternate, null !== alternate && (alternate.childLanes |= lane), 22 === parent.tag && (sourceFiber = parent.stateNode, null === sourceFiber || sourceFiber._visibility & 1 || (isHidden2 = true)), sourceFiber = parent, parent = parent.return;
+ return 3 === sourceFiber.tag ? (parent = sourceFiber.stateNode, isHidden2 && null !== update && (isHidden2 = 31 - clz32(lane), sourceFiber = parent.hiddenUpdates, alternate = sourceFiber[isHidden2], null === alternate ? sourceFiber[isHidden2] = [update] : alternate.push(update), update.lane = lane | 536870912), parent) : null;
+ }
+ __name(markUpdateLaneFromFiberToRoot, "markUpdateLaneFromFiberToRoot");
+ function getRootForUpdatedFiber(sourceFiber) {
+ if (50 < nestedUpdateCount)
+ throw nestedUpdateCount = 0, rootWithNestedUpdates = null, Error(formatProdErrorMessage(185));
+ for (var parent = sourceFiber.return; null !== parent; )
+ sourceFiber = parent, parent = sourceFiber.return;
+ return 3 === sourceFiber.tag ? sourceFiber.stateNode : null;
+ }
+ __name(getRootForUpdatedFiber, "getRootForUpdatedFiber");
+ function initializeUpdateQueue(fiber) {
+ fiber.updateQueue = {
+ baseState: fiber.memoizedState,
+ firstBaseUpdate: null,
+ lastBaseUpdate: null,
+ shared: { pending: null, lanes: 0, hiddenCallbacks: null },
+ callbacks: null
+ };
+ }
+ __name(initializeUpdateQueue, "initializeUpdateQueue");
+ function cloneUpdateQueue(current, workInProgress2) {
+ current = current.updateQueue;
+ workInProgress2.updateQueue === current && (workInProgress2.updateQueue = {
+ baseState: current.baseState,
+ firstBaseUpdate: current.firstBaseUpdate,
+ lastBaseUpdate: current.lastBaseUpdate,
+ shared: current.shared,
+ callbacks: null
+ });
+ }
+ __name(cloneUpdateQueue, "cloneUpdateQueue");
+ function createUpdate(lane) {
+ return { lane, tag: 0, payload: null, callback: null, next: null };
+ }
+ __name(createUpdate, "createUpdate");
+ function enqueueUpdate(fiber, update, lane) {
+ var updateQueue = fiber.updateQueue;
+ if (null === updateQueue) return null;
+ updateQueue = updateQueue.shared;
+ if (0 !== (executionContext & 2)) {
+ var pending = updateQueue.pending;
+ null === pending ? update.next = update : (update.next = pending.next, pending.next = update);
+ updateQueue.pending = update;
+ update = getRootForUpdatedFiber(fiber);
+ markUpdateLaneFromFiberToRoot(fiber, null, lane);
+ return update;
+ }
+ enqueueUpdate$1(fiber, updateQueue, update, lane);
+ return getRootForUpdatedFiber(fiber);
+ }
+ __name(enqueueUpdate, "enqueueUpdate");
+ function entangleTransitions(root, fiber, lane) {
+ fiber = fiber.updateQueue;
+ if (null !== fiber && (fiber = fiber.shared, 0 !== (lane & 4194048))) {
+ var queueLanes = fiber.lanes;
+ queueLanes &= root.pendingLanes;
+ lane |= queueLanes;
+ fiber.lanes = lane;
+ markRootEntangled(root, lane);
+ }
+ }
+ __name(entangleTransitions, "entangleTransitions");
+ function enqueueCapturedUpdate(workInProgress2, capturedUpdate) {
+ var queue = workInProgress2.updateQueue, current = workInProgress2.alternate;
+ if (null !== current && (current = current.updateQueue, queue === current)) {
+ var newFirst = null, newLast = null;
+ queue = queue.firstBaseUpdate;
+ if (null !== queue) {
+ do {
+ var clone2 = {
+ lane: queue.lane,
+ tag: queue.tag,
+ payload: queue.payload,
+ callback: null,
+ next: null
+ };
+ null === newLast ? newFirst = newLast = clone2 : newLast = newLast.next = clone2;
+ queue = queue.next;
+ } while (null !== queue);
+ null === newLast ? newFirst = newLast = capturedUpdate : newLast = newLast.next = capturedUpdate;
+ } else newFirst = newLast = capturedUpdate;
+ queue = {
+ baseState: current.baseState,
+ firstBaseUpdate: newFirst,
+ lastBaseUpdate: newLast,
+ shared: current.shared,
+ callbacks: current.callbacks
+ };
+ workInProgress2.updateQueue = queue;
+ return;
+ }
+ workInProgress2 = queue.lastBaseUpdate;
+ null === workInProgress2 ? queue.firstBaseUpdate = capturedUpdate : workInProgress2.next = capturedUpdate;
+ queue.lastBaseUpdate = capturedUpdate;
+ }
+ __name(enqueueCapturedUpdate, "enqueueCapturedUpdate");
+ function suspendIfUpdateReadFromEntangledAsyncAction() {
+ if (didReadFromEntangledAsyncAction) {
+ var entangledActionThenable = currentEntangledActionThenable;
+ if (null !== entangledActionThenable) throw entangledActionThenable;
+ }
+ }
+ __name(suspendIfUpdateReadFromEntangledAsyncAction, "suspendIfUpdateReadFromEntangledAsyncAction");
+ function processUpdateQueue(workInProgress$jscomp$0, props, instance$jscomp$0, renderLanes2) {
+ didReadFromEntangledAsyncAction = false;
+ var queue = workInProgress$jscomp$0.updateQueue;
+ hasForceUpdate = false;
+ var firstBaseUpdate = queue.firstBaseUpdate, lastBaseUpdate = queue.lastBaseUpdate, pendingQueue = queue.shared.pending;
+ if (null !== pendingQueue) {
+ queue.shared.pending = null;
+ var lastPendingUpdate = pendingQueue, firstPendingUpdate = lastPendingUpdate.next;
+ lastPendingUpdate.next = null;
+ null === lastBaseUpdate ? firstBaseUpdate = firstPendingUpdate : lastBaseUpdate.next = firstPendingUpdate;
+ lastBaseUpdate = lastPendingUpdate;
+ var current = workInProgress$jscomp$0.alternate;
+ null !== current && (current = current.updateQueue, pendingQueue = current.lastBaseUpdate, pendingQueue !== lastBaseUpdate && (null === pendingQueue ? current.firstBaseUpdate = firstPendingUpdate : pendingQueue.next = firstPendingUpdate, current.lastBaseUpdate = lastPendingUpdate));
+ }
+ if (null !== firstBaseUpdate) {
+ var newState = queue.baseState;
+ lastBaseUpdate = 0;
+ current = firstPendingUpdate = lastPendingUpdate = null;
+ pendingQueue = firstBaseUpdate;
+ do {
+ var updateLane = pendingQueue.lane & -536870913, isHiddenUpdate = updateLane !== pendingQueue.lane;
+ if (isHiddenUpdate ? (workInProgressRootRenderLanes & updateLane) === updateLane : (renderLanes2 & updateLane) === updateLane) {
+ 0 !== updateLane && updateLane === currentEntangledLane && (didReadFromEntangledAsyncAction = true);
+ null !== current && (current = current.next = {
+ lane: 0,
+ tag: pendingQueue.tag,
+ payload: pendingQueue.payload,
+ callback: null,
+ next: null
+ });
+ a: {
+ var workInProgress2 = workInProgress$jscomp$0, update = pendingQueue;
+ updateLane = props;
+ var instance = instance$jscomp$0;
+ switch (update.tag) {
+ case 1:
+ workInProgress2 = update.payload;
+ if ("function" === typeof workInProgress2) {
+ newState = workInProgress2.call(
+ instance,
+ newState,
+ updateLane
+ );
+ break a;
+ }
+ newState = workInProgress2;
+ break a;
+ case 3:
+ workInProgress2.flags = workInProgress2.flags & -65537 | 128;
+ case 0:
+ workInProgress2 = update.payload;
+ updateLane = "function" === typeof workInProgress2 ? workInProgress2.call(instance, newState, updateLane) : workInProgress2;
+ if (null === updateLane || void 0 === updateLane) break a;
+ newState = assign({}, newState, updateLane);
+ break a;
+ case 2:
+ hasForceUpdate = true;
+ }
+ }
+ updateLane = pendingQueue.callback;
+ null !== updateLane && (workInProgress$jscomp$0.flags |= 64, isHiddenUpdate && (workInProgress$jscomp$0.flags |= 8192), isHiddenUpdate = queue.callbacks, null === isHiddenUpdate ? queue.callbacks = [updateLane] : isHiddenUpdate.push(updateLane));
+ } else
+ isHiddenUpdate = {
+ lane: updateLane,
+ tag: pendingQueue.tag,
+ payload: pendingQueue.payload,
+ callback: pendingQueue.callback,
+ next: null
+ }, null === current ? (firstPendingUpdate = current = isHiddenUpdate, lastPendingUpdate = newState) : current = current.next = isHiddenUpdate, lastBaseUpdate |= updateLane;
+ pendingQueue = pendingQueue.next;
+ if (null === pendingQueue)
+ if (pendingQueue = queue.shared.pending, null === pendingQueue)
+ break;
+ else
+ isHiddenUpdate = pendingQueue, pendingQueue = isHiddenUpdate.next, isHiddenUpdate.next = null, queue.lastBaseUpdate = isHiddenUpdate, queue.shared.pending = null;
+ } while (1);
+ null === current && (lastPendingUpdate = newState);
+ queue.baseState = lastPendingUpdate;
+ queue.firstBaseUpdate = firstPendingUpdate;
+ queue.lastBaseUpdate = current;
+ null === firstBaseUpdate && (queue.shared.lanes = 0);
+ workInProgressRootSkippedLanes |= lastBaseUpdate;
+ workInProgress$jscomp$0.lanes = lastBaseUpdate;
+ workInProgress$jscomp$0.memoizedState = newState;
+ }
+ }
+ __name(processUpdateQueue, "processUpdateQueue");
+ function callCallback(callback, context) {
+ if ("function" !== typeof callback)
+ throw Error(formatProdErrorMessage(191, callback));
+ callback.call(context);
+ }
+ __name(callCallback, "callCallback");
+ function commitCallbacks(updateQueue, context) {
+ var callbacks = updateQueue.callbacks;
+ if (null !== callbacks)
+ for (updateQueue.callbacks = null, updateQueue = 0; updateQueue < callbacks.length; updateQueue++)
+ callCallback(callbacks[updateQueue], context);
+ }
+ __name(commitCallbacks, "commitCallbacks");
+ function pushHiddenContext(fiber, context) {
+ fiber = entangledRenderLanes;
+ push(prevEntangledRenderLanesCursor, fiber);
+ push(currentTreeHiddenStackCursor, context);
+ entangledRenderLanes = fiber | context.baseLanes;
+ }
+ __name(pushHiddenContext, "pushHiddenContext");
+ function reuseHiddenContextOnStack() {
+ push(prevEntangledRenderLanesCursor, entangledRenderLanes);
+ push(currentTreeHiddenStackCursor, currentTreeHiddenStackCursor.current);
+ }
+ __name(reuseHiddenContextOnStack, "reuseHiddenContextOnStack");
+ function popHiddenContext() {
+ entangledRenderLanes = prevEntangledRenderLanesCursor.current;
+ pop(currentTreeHiddenStackCursor);
+ pop(prevEntangledRenderLanesCursor);
+ }
+ __name(popHiddenContext, "popHiddenContext");
+ function pushPrimaryTreeSuspenseHandler(handler) {
+ var current = handler.alternate;
+ push(suspenseStackCursor, suspenseStackCursor.current & 1);
+ push(suspenseHandlerStackCursor, handler);
+ null === shellBoundary && (null === current || null !== currentTreeHiddenStackCursor.current ? shellBoundary = handler : null !== current.memoizedState && (shellBoundary = handler));
+ }
+ __name(pushPrimaryTreeSuspenseHandler, "pushPrimaryTreeSuspenseHandler");
+ function pushDehydratedActivitySuspenseHandler(fiber) {
+ push(suspenseStackCursor, suspenseStackCursor.current);
+ push(suspenseHandlerStackCursor, fiber);
+ null === shellBoundary && (shellBoundary = fiber);
+ }
+ __name(pushDehydratedActivitySuspenseHandler, "pushDehydratedActivitySuspenseHandler");
+ function pushOffscreenSuspenseHandler(fiber) {
+ 22 === fiber.tag ? (push(suspenseStackCursor, suspenseStackCursor.current), push(suspenseHandlerStackCursor, fiber), null === shellBoundary && (shellBoundary = fiber)) : reuseSuspenseHandlerOnStack(fiber);
+ }
+ __name(pushOffscreenSuspenseHandler, "pushOffscreenSuspenseHandler");
+ function reuseSuspenseHandlerOnStack() {
+ push(suspenseStackCursor, suspenseStackCursor.current);
+ push(suspenseHandlerStackCursor, suspenseHandlerStackCursor.current);
+ }
+ __name(reuseSuspenseHandlerOnStack, "reuseSuspenseHandlerOnStack");
+ function popSuspenseHandler(fiber) {
+ pop(suspenseHandlerStackCursor);
+ shellBoundary === fiber && (shellBoundary = null);
+ pop(suspenseStackCursor);
+ }
+ __name(popSuspenseHandler, "popSuspenseHandler");
+ function findFirstSuspended(row) {
+ for (var node = row; null !== node; ) {
+ if (13 === node.tag) {
+ var state = node.memoizedState;
+ if (null !== state && (state = state.dehydrated, null === state || isSuspenseInstancePending(state) || isSuspenseInstanceFallback(state)))
+ return node;
+ } else if (19 === node.tag && ("forwards" === node.memoizedProps.revealOrder || "backwards" === node.memoizedProps.revealOrder || "unstable_legacy-backwards" === node.memoizedProps.revealOrder || "together" === node.memoizedProps.revealOrder)) {
+ if (0 !== (node.flags & 128)) return node;
+ } else if (null !== node.child) {
+ node.child.return = node;
+ node = node.child;
+ continue;
+ }
+ if (node === row) break;
+ for (; null === node.sibling; ) {
+ if (null === node.return || node.return === row) return null;
+ node = node.return;
+ }
+ node.sibling.return = node.return;
+ node = node.sibling;
+ }
+ return null;
+ }
+ __name(findFirstSuspended, "findFirstSuspended");
+ function throwInvalidHookError() {
+ throw Error(formatProdErrorMessage(321));
+ }
+ __name(throwInvalidHookError, "throwInvalidHookError");
+ function areHookInputsEqual(nextDeps, prevDeps) {
+ if (null === prevDeps) return false;
+ for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++)
+ if (!objectIs(nextDeps[i], prevDeps[i])) return false;
+ return true;
+ }
+ __name(areHookInputsEqual, "areHookInputsEqual");
+ function renderWithHooks(current, workInProgress2, Component, props, secondArg, nextRenderLanes) {
+ renderLanes = nextRenderLanes;
+ currentlyRenderingFiber = workInProgress2;
+ workInProgress2.memoizedState = null;
+ workInProgress2.updateQueue = null;
+ workInProgress2.lanes = 0;
+ ReactSharedInternals.H = null === current || null === current.memoizedState ? HooksDispatcherOnMount : HooksDispatcherOnUpdate;
+ shouldDoubleInvokeUserFnsInHooksDEV = false;
+ nextRenderLanes = Component(props, secondArg);
+ shouldDoubleInvokeUserFnsInHooksDEV = false;
+ didScheduleRenderPhaseUpdateDuringThisPass && (nextRenderLanes = renderWithHooksAgain(
+ workInProgress2,
+ Component,
+ props,
+ secondArg
+ ));
+ finishRenderingHooks(current);
+ return nextRenderLanes;
+ }
+ __name(renderWithHooks, "renderWithHooks");
+ function finishRenderingHooks(current) {
+ ReactSharedInternals.H = ContextOnlyDispatcher;
+ var didRenderTooFewHooks = null !== currentHook && null !== currentHook.next;
+ renderLanes = 0;
+ workInProgressHook = currentHook = currentlyRenderingFiber = null;
+ didScheduleRenderPhaseUpdate = false;
+ thenableIndexCounter = 0;
+ thenableState = null;
+ if (didRenderTooFewHooks) throw Error(formatProdErrorMessage(300));
+ null === current || didReceiveUpdate || (current = current.dependencies, null !== current && checkIfContextChanged(current) && (didReceiveUpdate = true));
+ }
+ __name(finishRenderingHooks, "finishRenderingHooks");
+ function renderWithHooksAgain(workInProgress2, Component, props, secondArg) {
+ currentlyRenderingFiber = workInProgress2;
+ var numberOfReRenders = 0;
+ do {
+ didScheduleRenderPhaseUpdateDuringThisPass && (thenableState = null);
+ thenableIndexCounter = 0;
+ didScheduleRenderPhaseUpdateDuringThisPass = false;
+ if (25 <= numberOfReRenders) throw Error(formatProdErrorMessage(301));
+ numberOfReRenders += 1;
+ workInProgressHook = currentHook = null;
+ if (null != workInProgress2.updateQueue) {
+ var children = workInProgress2.updateQueue;
+ children.lastEffect = null;
+ children.events = null;
+ children.stores = null;
+ null != children.memoCache && (children.memoCache.index = 0);
+ }
+ ReactSharedInternals.H = HooksDispatcherOnRerender;
+ children = Component(props, secondArg);
+ } while (didScheduleRenderPhaseUpdateDuringThisPass);
+ return children;
+ }
+ __name(renderWithHooksAgain, "renderWithHooksAgain");
+ function TransitionAwareHostComponent() {
+ var dispatcher = ReactSharedInternals.H, maybeThenable = dispatcher.useState()[0];
+ maybeThenable = "function" === typeof maybeThenable.then ? useThenable(maybeThenable) : maybeThenable;
+ dispatcher = dispatcher.useState()[0];
+ (null !== currentHook ? currentHook.memoizedState : null) !== dispatcher && (currentlyRenderingFiber.flags |= 1024);
+ return maybeThenable;
+ }
+ __name(TransitionAwareHostComponent, "TransitionAwareHostComponent");
+ function checkDidRenderIdHook() {
+ var didRenderIdHook = 0 !== localIdCounter;
+ localIdCounter = 0;
+ return didRenderIdHook;
+ }
+ __name(checkDidRenderIdHook, "checkDidRenderIdHook");
+ function bailoutHooks(current, workInProgress2, lanes) {
+ workInProgress2.updateQueue = current.updateQueue;
+ workInProgress2.flags &= -2053;
+ current.lanes &= ~lanes;
+ }
+ __name(bailoutHooks, "bailoutHooks");
+ function resetHooksOnUnwind(workInProgress2) {
+ if (didScheduleRenderPhaseUpdate) {
+ for (workInProgress2 = workInProgress2.memoizedState; null !== workInProgress2; ) {
+ var queue = workInProgress2.queue;
+ null !== queue && (queue.pending = null);
+ workInProgress2 = workInProgress2.next;
+ }
+ didScheduleRenderPhaseUpdate = false;
+ }
+ renderLanes = 0;
+ workInProgressHook = currentHook = currentlyRenderingFiber = null;
+ didScheduleRenderPhaseUpdateDuringThisPass = false;
+ thenableIndexCounter = localIdCounter = 0;
+ thenableState = null;
+ }
+ __name(resetHooksOnUnwind, "resetHooksOnUnwind");
+ function mountWorkInProgressHook() {
+ var hook = {
+ memoizedState: null,
+ baseState: null,
+ baseQueue: null,
+ queue: null,
+ next: null
+ };
+ null === workInProgressHook ? currentlyRenderingFiber.memoizedState = workInProgressHook = hook : workInProgressHook = workInProgressHook.next = hook;
+ return workInProgressHook;
+ }
+ __name(mountWorkInProgressHook, "mountWorkInProgressHook");
+ function updateWorkInProgressHook() {
+ if (null === currentHook) {
+ var nextCurrentHook = currentlyRenderingFiber.alternate;
+ nextCurrentHook = null !== nextCurrentHook ? nextCurrentHook.memoizedState : null;
+ } else nextCurrentHook = currentHook.next;
+ var nextWorkInProgressHook = null === workInProgressHook ? currentlyRenderingFiber.memoizedState : workInProgressHook.next;
+ if (null !== nextWorkInProgressHook)
+ workInProgressHook = nextWorkInProgressHook, currentHook = nextCurrentHook;
+ else {
+ if (null === nextCurrentHook) {
+ if (null === currentlyRenderingFiber.alternate)
+ throw Error(formatProdErrorMessage(467));
+ throw Error(formatProdErrorMessage(310));
+ }
+ currentHook = nextCurrentHook;
+ nextCurrentHook = {
+ memoizedState: currentHook.memoizedState,
+ baseState: currentHook.baseState,
+ baseQueue: currentHook.baseQueue,
+ queue: currentHook.queue,
+ next: null
+ };
+ null === workInProgressHook ? currentlyRenderingFiber.memoizedState = workInProgressHook = nextCurrentHook : workInProgressHook = workInProgressHook.next = nextCurrentHook;
+ }
+ return workInProgressHook;
+ }
+ __name(updateWorkInProgressHook, "updateWorkInProgressHook");
+ function createFunctionComponentUpdateQueue() {
+ return { lastEffect: null, events: null, stores: null, memoCache: null };
+ }
+ __name(createFunctionComponentUpdateQueue, "createFunctionComponentUpdateQueue");
+ function useThenable(thenable) {
+ var index = thenableIndexCounter;
+ thenableIndexCounter += 1;
+ null === thenableState && (thenableState = []);
+ thenable = trackUsedThenable(thenableState, thenable, index);
+ index = currentlyRenderingFiber;
+ null === (null === workInProgressHook ? index.memoizedState : workInProgressHook.next) && (index = index.alternate, ReactSharedInternals.H = null === index || null === index.memoizedState ? HooksDispatcherOnMount : HooksDispatcherOnUpdate);
+ return thenable;
+ }
+ __name(useThenable, "useThenable");
+ function use(usable) {
+ if (null !== usable && "object" === typeof usable) {
+ if ("function" === typeof usable.then) return useThenable(usable);
+ if (usable.$$typeof === REACT_CONTEXT_TYPE) return readContext(usable);
+ }
+ throw Error(formatProdErrorMessage(438, String(usable)));
+ }
+ __name(use, "use");
+ function useMemoCache(size) {
+ var memoCache = null, updateQueue = currentlyRenderingFiber.updateQueue;
+ null !== updateQueue && (memoCache = updateQueue.memoCache);
+ if (null == memoCache) {
+ var current = currentlyRenderingFiber.alternate;
+ null !== current && (current = current.updateQueue, null !== current && (current = current.memoCache, null != current && (memoCache = {
+ data: current.data.map(function(array2) {
+ return array2.slice();
+ }),
+ index: 0
+ })));
+ }
+ null == memoCache && (memoCache = { data: [], index: 0 });
+ null === updateQueue && (updateQueue = createFunctionComponentUpdateQueue(), currentlyRenderingFiber.updateQueue = updateQueue);
+ updateQueue.memoCache = memoCache;
+ updateQueue = memoCache.data[memoCache.index];
+ if (void 0 === updateQueue)
+ for (updateQueue = memoCache.data[memoCache.index] = Array(size), current = 0; current < size; current++)
+ updateQueue[current] = REACT_MEMO_CACHE_SENTINEL;
+ memoCache.index++;
+ return updateQueue;
+ }
+ __name(useMemoCache, "useMemoCache");
+ function basicStateReducer(state, action) {
+ return "function" === typeof action ? action(state) : action;
+ }
+ __name(basicStateReducer, "basicStateReducer");
+ function updateReducer(reducer) {
+ var hook = updateWorkInProgressHook();
+ return updateReducerImpl(hook, currentHook, reducer);
+ }
+ __name(updateReducer, "updateReducer");
+ function updateReducerImpl(hook, current, reducer) {
+ var queue = hook.queue;
+ if (null === queue) throw Error(formatProdErrorMessage(311));
+ queue.lastRenderedReducer = reducer;
+ var baseQueue = hook.baseQueue, pendingQueue = queue.pending;
+ if (null !== pendingQueue) {
+ if (null !== baseQueue) {
+ var baseFirst = baseQueue.next;
+ baseQueue.next = pendingQueue.next;
+ pendingQueue.next = baseFirst;
+ }
+ current.baseQueue = baseQueue = pendingQueue;
+ queue.pending = null;
+ }
+ pendingQueue = hook.baseState;
+ if (null === baseQueue) hook.memoizedState = pendingQueue;
+ else {
+ current = baseQueue.next;
+ var newBaseQueueFirst = baseFirst = null, newBaseQueueLast = null, update = current, didReadFromEntangledAsyncAction$51 = false;
+ do {
+ var updateLane = update.lane & -536870913;
+ if (updateLane !== update.lane ? (workInProgressRootRenderLanes & updateLane) === updateLane : (renderLanes & updateLane) === updateLane) {
+ var revertLane = update.revertLane;
+ if (0 === revertLane)
+ null !== newBaseQueueLast && (newBaseQueueLast = newBaseQueueLast.next = {
+ lane: 0,
+ revertLane: 0,
+ gesture: null,
+ action: update.action,
+ hasEagerState: update.hasEagerState,
+ eagerState: update.eagerState,
+ next: null
+ }), updateLane === currentEntangledLane && (didReadFromEntangledAsyncAction$51 = true);
+ else if ((renderLanes & revertLane) === revertLane) {
+ update = update.next;
+ revertLane === currentEntangledLane && (didReadFromEntangledAsyncAction$51 = true);
+ continue;
+ } else
+ updateLane = {
+ lane: 0,
+ revertLane: update.revertLane,
+ gesture: null,
+ action: update.action,
+ hasEagerState: update.hasEagerState,
+ eagerState: update.eagerState,
+ next: null
+ }, null === newBaseQueueLast ? (newBaseQueueFirst = newBaseQueueLast = updateLane, baseFirst = pendingQueue) : newBaseQueueLast = newBaseQueueLast.next = updateLane, currentlyRenderingFiber.lanes |= revertLane, workInProgressRootSkippedLanes |= revertLane;
+ updateLane = update.action;
+ shouldDoubleInvokeUserFnsInHooksDEV && reducer(pendingQueue, updateLane);
+ pendingQueue = update.hasEagerState ? update.eagerState : reducer(pendingQueue, updateLane);
+ } else
+ revertLane = {
+ lane: updateLane,
+ revertLane: update.revertLane,
+ gesture: update.gesture,
+ action: update.action,
+ hasEagerState: update.hasEagerState,
+ eagerState: update.eagerState,
+ next: null
+ }, null === newBaseQueueLast ? (newBaseQueueFirst = newBaseQueueLast = revertLane, baseFirst = pendingQueue) : newBaseQueueLast = newBaseQueueLast.next = revertLane, currentlyRenderingFiber.lanes |= updateLane, workInProgressRootSkippedLanes |= updateLane;
+ update = update.next;
+ } while (null !== update && update !== current);
+ null === newBaseQueueLast ? baseFirst = pendingQueue : newBaseQueueLast.next = newBaseQueueFirst;
+ if (!objectIs(pendingQueue, hook.memoizedState) && (didReceiveUpdate = true, didReadFromEntangledAsyncAction$51 && (reducer = currentEntangledActionThenable, null !== reducer)))
+ throw reducer;
+ hook.memoizedState = pendingQueue;
+ hook.baseState = baseFirst;
+ hook.baseQueue = newBaseQueueLast;
+ queue.lastRenderedState = pendingQueue;
+ }
+ null === baseQueue && (queue.lanes = 0);
+ return [hook.memoizedState, queue.dispatch];
+ }
+ __name(updateReducerImpl, "updateReducerImpl");
+ function rerenderReducer(reducer) {
+ var hook = updateWorkInProgressHook(), queue = hook.queue;
+ if (null === queue) throw Error(formatProdErrorMessage(311));
+ queue.lastRenderedReducer = reducer;
+ var dispatch = queue.dispatch, lastRenderPhaseUpdate = queue.pending, newState = hook.memoizedState;
+ if (null !== lastRenderPhaseUpdate) {
+ queue.pending = null;
+ var update = lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
+ do
+ newState = reducer(newState, update.action), update = update.next;
+ while (update !== lastRenderPhaseUpdate);
+ objectIs(newState, hook.memoizedState) || (didReceiveUpdate = true);
+ hook.memoizedState = newState;
+ null === hook.baseQueue && (hook.baseState = newState);
+ queue.lastRenderedState = newState;
+ }
+ return [newState, dispatch];
+ }
+ __name(rerenderReducer, "rerenderReducer");
+ function updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
+ var fiber = currentlyRenderingFiber, hook = updateWorkInProgressHook(), isHydrating$jscomp$0 = isHydrating;
+ if (isHydrating$jscomp$0) {
+ if (void 0 === getServerSnapshot)
+ throw Error(formatProdErrorMessage(407));
+ getServerSnapshot = getServerSnapshot();
+ } else getServerSnapshot = getSnapshot();
+ var snapshotChanged = !objectIs(
+ (currentHook || hook).memoizedState,
+ getServerSnapshot
+ );
+ snapshotChanged && (hook.memoizedState = getServerSnapshot, didReceiveUpdate = true);
+ hook = hook.queue;
+ updateEffect(subscribeToStore.bind(null, fiber, hook, subscribe), [
+ subscribe
+ ]);
+ if (hook.getSnapshot !== getSnapshot || snapshotChanged || null !== workInProgressHook && workInProgressHook.memoizedState.tag & 1) {
+ fiber.flags |= 2048;
+ pushSimpleEffect(
+ 9,
+ { destroy: void 0 },
+ updateStoreInstance.bind(
+ null,
+ fiber,
+ hook,
+ getServerSnapshot,
+ getSnapshot
+ ),
+ null
+ );
+ if (null === workInProgressRoot) throw Error(formatProdErrorMessage(349));
+ isHydrating$jscomp$0 || 0 !== (renderLanes & 127) || pushStoreConsistencyCheck(fiber, getSnapshot, getServerSnapshot);
+ }
+ return getServerSnapshot;
+ }
+ __name(updateSyncExternalStore, "updateSyncExternalStore");
+ function pushStoreConsistencyCheck(fiber, getSnapshot, renderedSnapshot) {
+ fiber.flags |= 16384;
+ fiber = { getSnapshot, value: renderedSnapshot };
+ getSnapshot = currentlyRenderingFiber.updateQueue;
+ null === getSnapshot ? (getSnapshot = createFunctionComponentUpdateQueue(), currentlyRenderingFiber.updateQueue = getSnapshot, getSnapshot.stores = [fiber]) : (renderedSnapshot = getSnapshot.stores, null === renderedSnapshot ? getSnapshot.stores = [fiber] : renderedSnapshot.push(fiber));
+ }
+ __name(pushStoreConsistencyCheck, "pushStoreConsistencyCheck");
+ function updateStoreInstance(fiber, inst, nextSnapshot, getSnapshot) {
+ inst.value = nextSnapshot;
+ inst.getSnapshot = getSnapshot;
+ checkIfSnapshotChanged(inst) && forceStoreRerender(fiber);
+ }
+ __name(updateStoreInstance, "updateStoreInstance");
+ function subscribeToStore(fiber, inst, subscribe) {
+ return subscribe(function() {
+ checkIfSnapshotChanged(inst) && forceStoreRerender(fiber);
+ });
+ }
+ __name(subscribeToStore, "subscribeToStore");
+ function checkIfSnapshotChanged(inst) {
+ var latestGetSnapshot = inst.getSnapshot;
+ inst = inst.value;
+ try {
+ var nextValue = latestGetSnapshot();
+ return !objectIs(inst, nextValue);
+ } catch (error51) {
+ return true;
+ }
+ }
+ __name(checkIfSnapshotChanged, "checkIfSnapshotChanged");
+ function forceStoreRerender(fiber) {
+ var root = enqueueConcurrentRenderForLane(fiber, 2);
+ null !== root && scheduleUpdateOnFiber(root, fiber, 2);
+ }
+ __name(forceStoreRerender, "forceStoreRerender");
+ function mountStateImpl(initialState) {
+ var hook = mountWorkInProgressHook();
+ if ("function" === typeof initialState) {
+ var initialStateInitializer = initialState;
+ initialState = initialStateInitializer();
+ if (shouldDoubleInvokeUserFnsInHooksDEV) {
+ setIsStrictModeForDevtools(true);
+ try {
+ initialStateInitializer();
+ } finally {
+ setIsStrictModeForDevtools(false);
+ }
+ }
+ }
+ hook.memoizedState = hook.baseState = initialState;
+ hook.queue = {
+ pending: null,
+ lanes: 0,
+ dispatch: null,
+ lastRenderedReducer: basicStateReducer,
+ lastRenderedState: initialState
+ };
+ return hook;
+ }
+ __name(mountStateImpl, "mountStateImpl");
+ function updateOptimisticImpl(hook, current, passthrough, reducer) {
+ hook.baseState = passthrough;
+ return updateReducerImpl(
+ hook,
+ currentHook,
+ "function" === typeof reducer ? reducer : basicStateReducer
+ );
+ }
+ __name(updateOptimisticImpl, "updateOptimisticImpl");
+ function dispatchActionState(fiber, actionQueue, setPendingState, setState, payload) {
+ if (isRenderPhaseUpdate(fiber)) throw Error(formatProdErrorMessage(485));
+ fiber = actionQueue.action;
+ if (null !== fiber) {
+ var actionNode = {
+ payload,
+ action: fiber,
+ next: null,
+ isTransition: true,
+ status: "pending",
+ value: null,
+ reason: null,
+ listeners: [],
+ then: /* @__PURE__ */ __name(function(listener) {
+ actionNode.listeners.push(listener);
+ }, "then")
+ };
+ null !== ReactSharedInternals.T ? setPendingState(true) : actionNode.isTransition = false;
+ setState(actionNode);
+ setPendingState = actionQueue.pending;
+ null === setPendingState ? (actionNode.next = actionQueue.pending = actionNode, runActionStateAction(actionQueue, actionNode)) : (actionNode.next = setPendingState.next, actionQueue.pending = setPendingState.next = actionNode);
+ }
+ }
+ __name(dispatchActionState, "dispatchActionState");
+ function runActionStateAction(actionQueue, node) {
+ var action = node.action, payload = node.payload, prevState = actionQueue.state;
+ if (node.isTransition) {
+ var prevTransition = ReactSharedInternals.T, currentTransition = {};
+ ReactSharedInternals.T = currentTransition;
+ try {
+ var returnValue = action(prevState, payload), onStartTransitionFinish = ReactSharedInternals.S;
+ null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue);
+ handleActionReturnValue(actionQueue, node, returnValue);
+ } catch (error51) {
+ onActionError(actionQueue, node, error51);
+ } finally {
+ null !== prevTransition && null !== currentTransition.types && (prevTransition.types = currentTransition.types), ReactSharedInternals.T = prevTransition;
+ }
+ } else
+ try {
+ prevTransition = action(prevState, payload), handleActionReturnValue(actionQueue, node, prevTransition);
+ } catch (error$55) {
+ onActionError(actionQueue, node, error$55);
+ }
+ }
+ __name(runActionStateAction, "runActionStateAction");
+ function handleActionReturnValue(actionQueue, node, returnValue) {
+ null !== returnValue && "object" === typeof returnValue && "function" === typeof returnValue.then ? returnValue.then(
+ function(nextState) {
+ onActionSuccess(actionQueue, node, nextState);
+ },
+ function(error51) {
+ return onActionError(actionQueue, node, error51);
+ }
+ ) : onActionSuccess(actionQueue, node, returnValue);
+ }
+ __name(handleActionReturnValue, "handleActionReturnValue");
+ function onActionSuccess(actionQueue, actionNode, nextState) {
+ actionNode.status = "fulfilled";
+ actionNode.value = nextState;
+ notifyActionListeners(actionNode);
+ actionQueue.state = nextState;
+ actionNode = actionQueue.pending;
+ null !== actionNode && (nextState = actionNode.next, nextState === actionNode ? actionQueue.pending = null : (nextState = nextState.next, actionNode.next = nextState, runActionStateAction(actionQueue, nextState)));
+ }
+ __name(onActionSuccess, "onActionSuccess");
+ function onActionError(actionQueue, actionNode, error51) {
+ var last = actionQueue.pending;
+ actionQueue.pending = null;
+ if (null !== last) {
+ last = last.next;
+ do
+ actionNode.status = "rejected", actionNode.reason = error51, notifyActionListeners(actionNode), actionNode = actionNode.next;
+ while (actionNode !== last);
+ }
+ actionQueue.action = null;
+ }
+ __name(onActionError, "onActionError");
+ function notifyActionListeners(actionNode) {
+ actionNode = actionNode.listeners;
+ for (var i = 0; i < actionNode.length; i++) (0, actionNode[i])();
+ }
+ __name(notifyActionListeners, "notifyActionListeners");
+ function actionStateReducer(oldState, newState) {
+ return newState;
+ }
+ __name(actionStateReducer, "actionStateReducer");
+ function mountActionState(action, initialStateProp) {
+ if (isHydrating) {
+ var ssrFormState = workInProgressRoot.formState;
+ if (null !== ssrFormState) {
+ a: {
+ var JSCompiler_inline_result = currentlyRenderingFiber;
+ if (isHydrating) {
+ if (nextHydratableInstance) {
+ var markerInstance = canHydrateFormStateMarker(
+ nextHydratableInstance,
+ rootOrSingletonContext
+ );
+ if (markerInstance) {
+ nextHydratableInstance = getNextHydratableSibling(markerInstance);
+ JSCompiler_inline_result = isFormStateMarkerMatching(markerInstance);
+ break a;
+ }
+ }
+ throwOnHydrationMismatch(JSCompiler_inline_result);
+ }
+ JSCompiler_inline_result = false;
+ }
+ JSCompiler_inline_result && (initialStateProp = ssrFormState[0]);
+ }
+ }
+ ssrFormState = mountWorkInProgressHook();
+ ssrFormState.memoizedState = ssrFormState.baseState = initialStateProp;
+ JSCompiler_inline_result = {
+ pending: null,
+ lanes: 0,
+ dispatch: null,
+ lastRenderedReducer: actionStateReducer,
+ lastRenderedState: initialStateProp
+ };
+ ssrFormState.queue = JSCompiler_inline_result;
+ ssrFormState = dispatchSetState.bind(
+ null,
+ currentlyRenderingFiber,
+ JSCompiler_inline_result
+ );
+ JSCompiler_inline_result.dispatch = ssrFormState;
+ JSCompiler_inline_result = mountStateImpl(false);
+ var setPendingState = dispatchOptimisticSetState.bind(
+ null,
+ currentlyRenderingFiber,
+ false,
+ JSCompiler_inline_result.queue
+ );
+ JSCompiler_inline_result = mountWorkInProgressHook();
+ markerInstance = {
+ state: initialStateProp,
+ dispatch: null,
+ action,
+ pending: null
+ };
+ JSCompiler_inline_result.queue = markerInstance;
+ ssrFormState = dispatchActionState.bind(
+ null,
+ currentlyRenderingFiber,
+ markerInstance,
+ setPendingState,
+ ssrFormState
+ );
+ markerInstance.dispatch = ssrFormState;
+ JSCompiler_inline_result.memoizedState = action;
+ return [initialStateProp, ssrFormState, false];
+ }
+ __name(mountActionState, "mountActionState");
+ function updateActionState(action) {
+ var stateHook = updateWorkInProgressHook();
+ return updateActionStateImpl(stateHook, currentHook, action);
+ }
+ __name(updateActionState, "updateActionState");
+ function updateActionStateImpl(stateHook, currentStateHook, action) {
+ currentStateHook = updateReducerImpl(
+ stateHook,
+ currentStateHook,
+ actionStateReducer
+ )[0];
+ stateHook = updateReducer(basicStateReducer)[0];
+ if ("object" === typeof currentStateHook && null !== currentStateHook && "function" === typeof currentStateHook.then)
+ try {
+ var state = useThenable(currentStateHook);
+ } catch (x) {
+ if (x === SuspenseException) throw SuspenseActionException;
+ throw x;
+ }
+ else state = currentStateHook;
+ currentStateHook = updateWorkInProgressHook();
+ var actionQueue = currentStateHook.queue, dispatch = actionQueue.dispatch;
+ action !== currentStateHook.memoizedState && (currentlyRenderingFiber.flags |= 2048, pushSimpleEffect(
+ 9,
+ { destroy: void 0 },
+ actionStateActionEffect.bind(null, actionQueue, action),
+ null
+ ));
+ return [state, dispatch, stateHook];
+ }
+ __name(updateActionStateImpl, "updateActionStateImpl");
+ function actionStateActionEffect(actionQueue, action) {
+ actionQueue.action = action;
+ }
+ __name(actionStateActionEffect, "actionStateActionEffect");
+ function rerenderActionState(action) {
+ var stateHook = updateWorkInProgressHook(), currentStateHook = currentHook;
+ if (null !== currentStateHook)
+ return updateActionStateImpl(stateHook, currentStateHook, action);
+ updateWorkInProgressHook();
+ stateHook = stateHook.memoizedState;
+ currentStateHook = updateWorkInProgressHook();
+ var dispatch = currentStateHook.queue.dispatch;
+ currentStateHook.memoizedState = action;
+ return [stateHook, dispatch, false];
+ }
+ __name(rerenderActionState, "rerenderActionState");
+ function pushSimpleEffect(tag, inst, create3, deps) {
+ tag = { tag, create: create3, deps, inst, next: null };
+ inst = currentlyRenderingFiber.updateQueue;
+ null === inst && (inst = createFunctionComponentUpdateQueue(), currentlyRenderingFiber.updateQueue = inst);
+ create3 = inst.lastEffect;
+ null === create3 ? inst.lastEffect = tag.next = tag : (deps = create3.next, create3.next = tag, tag.next = deps, inst.lastEffect = tag);
+ return tag;
+ }
+ __name(pushSimpleEffect, "pushSimpleEffect");
+ function updateRef() {
+ return updateWorkInProgressHook().memoizedState;
+ }
+ __name(updateRef, "updateRef");
+ function mountEffectImpl(fiberFlags, hookFlags, create3, deps) {
+ var hook = mountWorkInProgressHook();
+ currentlyRenderingFiber.flags |= fiberFlags;
+ hook.memoizedState = pushSimpleEffect(
+ 1 | hookFlags,
+ { destroy: void 0 },
+ create3,
+ void 0 === deps ? null : deps
+ );
+ }
+ __name(mountEffectImpl, "mountEffectImpl");
+ function updateEffectImpl(fiberFlags, hookFlags, create3, deps) {
+ var hook = updateWorkInProgressHook();
+ deps = void 0 === deps ? null : deps;
+ var inst = hook.memoizedState.inst;
+ null !== currentHook && null !== deps && areHookInputsEqual(deps, currentHook.memoizedState.deps) ? hook.memoizedState = pushSimpleEffect(hookFlags, inst, create3, deps) : (currentlyRenderingFiber.flags |= fiberFlags, hook.memoizedState = pushSimpleEffect(
+ 1 | hookFlags,
+ inst,
+ create3,
+ deps
+ ));
+ }
+ __name(updateEffectImpl, "updateEffectImpl");
+ function mountEffect(create3, deps) {
+ mountEffectImpl(8390656, 8, create3, deps);
+ }
+ __name(mountEffect, "mountEffect");
+ function updateEffect(create3, deps) {
+ updateEffectImpl(2048, 8, create3, deps);
+ }
+ __name(updateEffect, "updateEffect");
+ function useEffectEventImpl(payload) {
+ currentlyRenderingFiber.flags |= 4;
+ var componentUpdateQueue = currentlyRenderingFiber.updateQueue;
+ if (null === componentUpdateQueue)
+ componentUpdateQueue = createFunctionComponentUpdateQueue(), currentlyRenderingFiber.updateQueue = componentUpdateQueue, componentUpdateQueue.events = [payload];
+ else {
+ var events = componentUpdateQueue.events;
+ null === events ? componentUpdateQueue.events = [payload] : events.push(payload);
+ }
+ }
+ __name(useEffectEventImpl, "useEffectEventImpl");
+ function updateEvent(callback) {
+ var ref = updateWorkInProgressHook().memoizedState;
+ useEffectEventImpl({ ref, nextImpl: callback });
+ return function() {
+ if (0 !== (executionContext & 2))
+ throw Error(formatProdErrorMessage(440));
+ return ref.impl.apply(void 0, arguments);
+ };
+ }
+ __name(updateEvent, "updateEvent");
+ function updateInsertionEffect(create3, deps) {
+ return updateEffectImpl(4, 2, create3, deps);
+ }
+ __name(updateInsertionEffect, "updateInsertionEffect");
+ function updateLayoutEffect(create3, deps) {
+ return updateEffectImpl(4, 4, create3, deps);
+ }
+ __name(updateLayoutEffect, "updateLayoutEffect");
+ function imperativeHandleEffect(create3, ref) {
+ if ("function" === typeof ref) {
+ create3 = create3();
+ var refCleanup = ref(create3);
+ return function() {
+ "function" === typeof refCleanup ? refCleanup() : ref(null);
+ };
+ }
+ if (null !== ref && void 0 !== ref)
+ return create3 = create3(), ref.current = create3, function() {
+ ref.current = null;
+ };
+ }
+ __name(imperativeHandleEffect, "imperativeHandleEffect");
+ function updateImperativeHandle(ref, create3, deps) {
+ deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null;
+ updateEffectImpl(
+ 4,
+ 4,
+ imperativeHandleEffect.bind(null, create3, ref),
+ deps
+ );
+ }
+ __name(updateImperativeHandle, "updateImperativeHandle");
+ function mountDebugValue() {
+ }
+ __name(mountDebugValue, "mountDebugValue");
+ function updateCallback(callback, deps) {
+ var hook = updateWorkInProgressHook();
+ deps = void 0 === deps ? null : deps;
+ var prevState = hook.memoizedState;
+ if (null !== deps && areHookInputsEqual(deps, prevState[1]))
+ return prevState[0];
+ hook.memoizedState = [callback, deps];
+ return callback;
+ }
+ __name(updateCallback, "updateCallback");
+ function updateMemo(nextCreate, deps) {
+ var hook = updateWorkInProgressHook();
+ deps = void 0 === deps ? null : deps;
+ var prevState = hook.memoizedState;
+ if (null !== deps && areHookInputsEqual(deps, prevState[1]))
+ return prevState[0];
+ prevState = nextCreate();
+ if (shouldDoubleInvokeUserFnsInHooksDEV) {
+ setIsStrictModeForDevtools(true);
+ try {
+ nextCreate();
+ } finally {
+ setIsStrictModeForDevtools(false);
+ }
+ }
+ hook.memoizedState = [prevState, deps];
+ return prevState;
+ }
+ __name(updateMemo, "updateMemo");
+ function mountDeferredValueImpl(hook, value, initialValue) {
+ if (void 0 === initialValue || 0 !== (renderLanes & 1073741824) && 0 === (workInProgressRootRenderLanes & 261930))
+ return hook.memoizedState = value;
+ hook.memoizedState = initialValue;
+ hook = requestDeferredLane();
+ currentlyRenderingFiber.lanes |= hook;
+ workInProgressRootSkippedLanes |= hook;
+ return initialValue;
+ }
+ __name(mountDeferredValueImpl, "mountDeferredValueImpl");
+ function updateDeferredValueImpl(hook, prevValue, value, initialValue) {
+ if (objectIs(value, prevValue)) return value;
+ if (null !== currentTreeHiddenStackCursor.current)
+ return hook = mountDeferredValueImpl(hook, value, initialValue), objectIs(hook, prevValue) || (didReceiveUpdate = true), hook;
+ if (0 === (renderLanes & 42) || 0 !== (renderLanes & 1073741824) && 0 === (workInProgressRootRenderLanes & 261930))
+ return didReceiveUpdate = true, hook.memoizedState = value;
+ hook = requestDeferredLane();
+ currentlyRenderingFiber.lanes |= hook;
+ workInProgressRootSkippedLanes |= hook;
+ return prevValue;
+ }
+ __name(updateDeferredValueImpl, "updateDeferredValueImpl");
+ function startTransition(fiber, queue, pendingState, finishedState, callback) {
+ var previousPriority = getCurrentUpdatePriority();
+ setCurrentUpdatePriority(
+ 0 !== previousPriority && 8 > previousPriority ? previousPriority : 8
+ );
+ var prevTransition = ReactSharedInternals.T, currentTransition = {};
+ ReactSharedInternals.T = currentTransition;
+ dispatchOptimisticSetState(fiber, false, queue, pendingState);
+ try {
+ var returnValue = callback(), onStartTransitionFinish = ReactSharedInternals.S;
+ null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue);
+ if (null !== returnValue && "object" === typeof returnValue && "function" === typeof returnValue.then) {
+ var thenableForFinishedState = chainThenableValue(
+ returnValue,
+ finishedState
+ );
+ dispatchSetStateInternal(
+ fiber,
+ queue,
+ thenableForFinishedState,
+ requestUpdateLane(fiber)
+ );
+ } else
+ dispatchSetStateInternal(
+ fiber,
+ queue,
+ finishedState,
+ requestUpdateLane(fiber)
+ );
+ } catch (error51) {
+ dispatchSetStateInternal(
+ fiber,
+ queue,
+ { then: /* @__PURE__ */ __name(function() {
+ }, "then"), status: "rejected", reason: error51 },
+ requestUpdateLane()
+ );
+ } finally {
+ setCurrentUpdatePriority(previousPriority), null !== prevTransition && null !== currentTransition.types && (prevTransition.types = currentTransition.types), ReactSharedInternals.T = prevTransition;
+ }
+ }
+ __name(startTransition, "startTransition");
+ function ensureFormComponentIsStateful(formFiber) {
+ var existingStateHook = formFiber.memoizedState;
+ if (null !== existingStateHook) return existingStateHook;
+ existingStateHook = {
+ memoizedState: NotPendingTransition,
+ baseState: NotPendingTransition,
+ baseQueue: null,
+ queue: {
+ pending: null,
+ lanes: 0,
+ dispatch: null,
+ lastRenderedReducer: basicStateReducer,
+ lastRenderedState: NotPendingTransition
+ },
+ next: null
+ };
+ var initialResetState = {};
+ existingStateHook.next = {
+ memoizedState: initialResetState,
+ baseState: initialResetState,
+ baseQueue: null,
+ queue: {
+ pending: null,
+ lanes: 0,
+ dispatch: null,
+ lastRenderedReducer: basicStateReducer,
+ lastRenderedState: initialResetState
+ },
+ next: null
+ };
+ formFiber.memoizedState = existingStateHook;
+ formFiber = formFiber.alternate;
+ null !== formFiber && (formFiber.memoizedState = existingStateHook);
+ return existingStateHook;
+ }
+ __name(ensureFormComponentIsStateful, "ensureFormComponentIsStateful");
+ function useHostTransitionStatus() {
+ return readContext(HostTransitionContext);
+ }
+ __name(useHostTransitionStatus, "useHostTransitionStatus");
+ function updateId() {
+ return updateWorkInProgressHook().memoizedState;
+ }
+ __name(updateId, "updateId");
+ function updateRefresh() {
+ return updateWorkInProgressHook().memoizedState;
+ }
+ __name(updateRefresh, "updateRefresh");
+ function refreshCache(fiber) {
+ for (var provider = fiber.return; null !== provider; ) {
+ switch (provider.tag) {
+ case 24:
+ case 3:
+ var lane = requestUpdateLane();
+ fiber = createUpdate(lane);
+ var root = enqueueUpdate(provider, fiber, lane);
+ null !== root && (scheduleUpdateOnFiber(root, provider, lane), entangleTransitions(root, provider, lane));
+ provider = { cache: createCache() };
+ fiber.payload = provider;
+ return;
+ }
+ provider = provider.return;
+ }
+ }
+ __name(refreshCache, "refreshCache");
+ function dispatchReducerAction(fiber, queue, action) {
+ var lane = requestUpdateLane();
+ action = {
+ lane,
+ revertLane: 0,
+ gesture: null,
+ action,
+ hasEagerState: false,
+ eagerState: null,
+ next: null
+ };
+ isRenderPhaseUpdate(fiber) ? enqueueRenderPhaseUpdate(queue, action) : (action = enqueueConcurrentHookUpdate(fiber, queue, action, lane), null !== action && (scheduleUpdateOnFiber(action, fiber, lane), entangleTransitionUpdate(action, queue, lane)));
+ }
+ __name(dispatchReducerAction, "dispatchReducerAction");
+ function dispatchSetState(fiber, queue, action) {
+ var lane = requestUpdateLane();
+ dispatchSetStateInternal(fiber, queue, action, lane);
+ }
+ __name(dispatchSetState, "dispatchSetState");
+ function dispatchSetStateInternal(fiber, queue, action, lane) {
+ var update = {
+ lane,
+ revertLane: 0,
+ gesture: null,
+ action,
+ hasEagerState: false,
+ eagerState: null,
+ next: null
+ };
+ if (isRenderPhaseUpdate(fiber)) enqueueRenderPhaseUpdate(queue, update);
+ else {
+ var alternate = fiber.alternate;
+ if (0 === fiber.lanes && (null === alternate || 0 === alternate.lanes) && (alternate = queue.lastRenderedReducer, null !== alternate))
+ try {
+ var currentState = queue.lastRenderedState, eagerState = alternate(currentState, action);
+ update.hasEagerState = true;
+ update.eagerState = eagerState;
+ if (objectIs(eagerState, currentState))
+ return enqueueUpdate$1(fiber, queue, update, 0), null === workInProgressRoot && finishQueueingConcurrentUpdates(), false;
+ } catch (error51) {
+ } finally {
+ }
+ action = enqueueConcurrentHookUpdate(fiber, queue, update, lane);
+ if (null !== action)
+ return scheduleUpdateOnFiber(action, fiber, lane), entangleTransitionUpdate(action, queue, lane), true;
+ }
+ return false;
+ }
+ __name(dispatchSetStateInternal, "dispatchSetStateInternal");
+ function dispatchOptimisticSetState(fiber, throwIfDuringRender, queue, action) {
+ action = {
+ lane: 2,
+ revertLane: requestTransitionLane(),
+ gesture: null,
+ action,
+ hasEagerState: false,
+ eagerState: null,
+ next: null
+ };
+ if (isRenderPhaseUpdate(fiber)) {
+ if (throwIfDuringRender) throw Error(formatProdErrorMessage(479));
+ } else
+ throwIfDuringRender = enqueueConcurrentHookUpdate(
+ fiber,
+ queue,
+ action,
+ 2
+ ), null !== throwIfDuringRender && scheduleUpdateOnFiber(throwIfDuringRender, fiber, 2);
+ }
+ __name(dispatchOptimisticSetState, "dispatchOptimisticSetState");
+ function isRenderPhaseUpdate(fiber) {
+ var alternate = fiber.alternate;
+ return fiber === currentlyRenderingFiber || null !== alternate && alternate === currentlyRenderingFiber;
+ }
+ __name(isRenderPhaseUpdate, "isRenderPhaseUpdate");
+ function enqueueRenderPhaseUpdate(queue, update) {
+ didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate = true;
+ var pending = queue.pending;
+ null === pending ? update.next = update : (update.next = pending.next, pending.next = update);
+ queue.pending = update;
+ }
+ __name(enqueueRenderPhaseUpdate, "enqueueRenderPhaseUpdate");
+ function entangleTransitionUpdate(root, queue, lane) {
+ if (0 !== (lane & 4194048)) {
+ var queueLanes = queue.lanes;
+ queueLanes &= root.pendingLanes;
+ lane |= queueLanes;
+ queue.lanes = lane;
+ markRootEntangled(root, lane);
+ }
+ }
+ __name(entangleTransitionUpdate, "entangleTransitionUpdate");
+ function applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, nextProps) {
+ ctor = workInProgress2.memoizedState;
+ getDerivedStateFromProps = getDerivedStateFromProps(nextProps, ctor);
+ getDerivedStateFromProps = null === getDerivedStateFromProps || void 0 === getDerivedStateFromProps ? ctor : assign({}, ctor, getDerivedStateFromProps);
+ workInProgress2.memoizedState = getDerivedStateFromProps;
+ 0 === workInProgress2.lanes && (workInProgress2.updateQueue.baseState = getDerivedStateFromProps);
+ }
+ __name(applyDerivedStateFromProps, "applyDerivedStateFromProps");
+ function checkShouldComponentUpdate(workInProgress2, ctor, oldProps, newProps, oldState, newState, nextContext) {
+ workInProgress2 = workInProgress2.stateNode;
+ return "function" === typeof workInProgress2.shouldComponentUpdate ? workInProgress2.shouldComponentUpdate(newProps, newState, nextContext) : ctor.prototype && ctor.prototype.isPureReactComponent ? !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState) : true;
+ }
+ __name(checkShouldComponentUpdate, "checkShouldComponentUpdate");
+ function callComponentWillReceiveProps(workInProgress2, instance, newProps, nextContext) {
+ workInProgress2 = instance.state;
+ "function" === typeof instance.componentWillReceiveProps && instance.componentWillReceiveProps(newProps, nextContext);
+ "function" === typeof instance.UNSAFE_componentWillReceiveProps && instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
+ instance.state !== workInProgress2 && classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
+ }
+ __name(callComponentWillReceiveProps, "callComponentWillReceiveProps");
+ function resolveClassComponentProps(Component, baseProps) {
+ var newProps = baseProps;
+ if ("ref" in baseProps) {
+ newProps = {};
+ for (var propName in baseProps)
+ "ref" !== propName && (newProps[propName] = baseProps[propName]);
+ }
+ if (Component = Component.defaultProps) {
+ newProps === baseProps && (newProps = assign({}, newProps));
+ for (var propName$57 in Component)
+ void 0 === newProps[propName$57] && (newProps[propName$57] = Component[propName$57]);
+ }
+ return newProps;
+ }
+ __name(resolveClassComponentProps, "resolveClassComponentProps");
+ function logUncaughtError(root, errorInfo) {
+ try {
+ var onUncaughtError = root.onUncaughtError;
+ onUncaughtError(errorInfo.value, { componentStack: errorInfo.stack });
+ } catch (e) {
+ setTimeout(function() {
+ throw e;
+ });
+ }
+ }
+ __name(logUncaughtError, "logUncaughtError");
+ function logCaughtError(root, boundary, errorInfo) {
+ try {
+ var onCaughtError = root.onCaughtError;
+ onCaughtError(errorInfo.value, {
+ componentStack: errorInfo.stack,
+ errorBoundary: 1 === boundary.tag ? boundary.stateNode : null
+ });
+ } catch (e) {
+ setTimeout(function() {
+ throw e;
+ });
+ }
+ }
+ __name(logCaughtError, "logCaughtError");
+ function createRootErrorUpdate(root, errorInfo, lane) {
+ lane = createUpdate(lane);
+ lane.tag = 3;
+ lane.payload = { element: null };
+ lane.callback = function() {
+ logUncaughtError(root, errorInfo);
+ };
+ return lane;
+ }
+ __name(createRootErrorUpdate, "createRootErrorUpdate");
+ function createClassErrorUpdate(lane) {
+ lane = createUpdate(lane);
+ lane.tag = 3;
+ return lane;
+ }
+ __name(createClassErrorUpdate, "createClassErrorUpdate");
+ function initializeClassErrorUpdate(update, root, fiber, errorInfo) {
+ var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
+ if ("function" === typeof getDerivedStateFromError) {
+ var error51 = errorInfo.value;
+ update.payload = function() {
+ return getDerivedStateFromError(error51);
+ };
+ update.callback = function() {
+ logCaughtError(root, fiber, errorInfo);
+ };
+ }
+ var inst = fiber.stateNode;
+ null !== inst && "function" === typeof inst.componentDidCatch && (update.callback = function() {
+ logCaughtError(root, fiber, errorInfo);
+ "function" !== typeof getDerivedStateFromError && (null === legacyErrorBoundariesThatAlreadyFailed ? legacyErrorBoundariesThatAlreadyFailed = /* @__PURE__ */ new Set([this]) : legacyErrorBoundariesThatAlreadyFailed.add(this));
+ var stack = errorInfo.stack;
+ this.componentDidCatch(errorInfo.value, {
+ componentStack: null !== stack ? stack : ""
+ });
+ });
+ }
+ __name(initializeClassErrorUpdate, "initializeClassErrorUpdate");
+ function throwException(root, returnFiber, sourceFiber, value, rootRenderLanes) {
+ sourceFiber.flags |= 32768;
+ if (null !== value && "object" === typeof value && "function" === typeof value.then) {
+ returnFiber = sourceFiber.alternate;
+ null !== returnFiber && propagateParentContextChanges(
+ returnFiber,
+ sourceFiber,
+ rootRenderLanes,
+ true
+ );
+ sourceFiber = suspenseHandlerStackCursor.current;
+ if (null !== sourceFiber) {
+ switch (sourceFiber.tag) {
+ case 31:
+ case 13:
+ return null === shellBoundary ? renderDidSuspendDelayIfPossible() : null === sourceFiber.alternate && 0 === workInProgressRootExitStatus && (workInProgressRootExitStatus = 3), sourceFiber.flags &= -257, sourceFiber.flags |= 65536, sourceFiber.lanes = rootRenderLanes, value === noopSuspenseyCommitThenable ? sourceFiber.flags |= 16384 : (returnFiber = sourceFiber.updateQueue, null === returnFiber ? sourceFiber.updateQueue = /* @__PURE__ */ new Set([value]) : returnFiber.add(value), attachPingListener(root, value, rootRenderLanes)), false;
+ case 22:
+ return sourceFiber.flags |= 65536, value === noopSuspenseyCommitThenable ? sourceFiber.flags |= 16384 : (returnFiber = sourceFiber.updateQueue, null === returnFiber ? (returnFiber = {
+ transitions: null,
+ markerInstances: null,
+ retryQueue: /* @__PURE__ */ new Set([value])
+ }, sourceFiber.updateQueue = returnFiber) : (sourceFiber = returnFiber.retryQueue, null === sourceFiber ? returnFiber.retryQueue = /* @__PURE__ */ new Set([value]) : sourceFiber.add(value)), attachPingListener(root, value, rootRenderLanes)), false;
+ }
+ throw Error(formatProdErrorMessage(435, sourceFiber.tag));
+ }
+ attachPingListener(root, value, rootRenderLanes);
+ renderDidSuspendDelayIfPossible();
+ return false;
+ }
+ if (isHydrating)
+ return returnFiber = suspenseHandlerStackCursor.current, null !== returnFiber ? (0 === (returnFiber.flags & 65536) && (returnFiber.flags |= 256), returnFiber.flags |= 65536, returnFiber.lanes = rootRenderLanes, value !== HydrationMismatchException && (root = Error(formatProdErrorMessage(422), { cause: value }), queueHydrationError(
+ createCapturedValueAtFiber(root, sourceFiber)
+ ))) : (value !== HydrationMismatchException && (returnFiber = Error(formatProdErrorMessage(423), {
+ cause: value
+ }), queueHydrationError(
+ createCapturedValueAtFiber(returnFiber, sourceFiber)
+ )), root = root.current.alternate, root.flags |= 65536, rootRenderLanes &= -rootRenderLanes, root.lanes |= rootRenderLanes, value = createCapturedValueAtFiber(value, sourceFiber), rootRenderLanes = createRootErrorUpdate(
+ root.stateNode,
+ value,
+ rootRenderLanes
+ ), enqueueCapturedUpdate(root, rootRenderLanes), 4 !== workInProgressRootExitStatus && (workInProgressRootExitStatus = 2)), false;
+ var wrapperError = Error(formatProdErrorMessage(520), { cause: value });
+ wrapperError = createCapturedValueAtFiber(wrapperError, sourceFiber);
+ null === workInProgressRootConcurrentErrors ? workInProgressRootConcurrentErrors = [wrapperError] : workInProgressRootConcurrentErrors.push(wrapperError);
+ 4 !== workInProgressRootExitStatus && (workInProgressRootExitStatus = 2);
+ if (null === returnFiber) return true;
+ value = createCapturedValueAtFiber(value, sourceFiber);
+ sourceFiber = returnFiber;
+ do {
+ switch (sourceFiber.tag) {
+ case 3:
+ return sourceFiber.flags |= 65536, root = rootRenderLanes & -rootRenderLanes, sourceFiber.lanes |= root, root = createRootErrorUpdate(sourceFiber.stateNode, value, root), enqueueCapturedUpdate(sourceFiber, root), false;
+ case 1:
+ if (returnFiber = sourceFiber.type, wrapperError = sourceFiber.stateNode, 0 === (sourceFiber.flags & 128) && ("function" === typeof returnFiber.getDerivedStateFromError || null !== wrapperError && "function" === typeof wrapperError.componentDidCatch && (null === legacyErrorBoundariesThatAlreadyFailed || !legacyErrorBoundariesThatAlreadyFailed.has(
+ wrapperError
+ ))))
+ return sourceFiber.flags |= 65536, rootRenderLanes &= -rootRenderLanes, sourceFiber.lanes |= rootRenderLanes, rootRenderLanes = createClassErrorUpdate(rootRenderLanes), initializeClassErrorUpdate(
+ rootRenderLanes,
+ root,
+ sourceFiber,
+ value
+ ), enqueueCapturedUpdate(sourceFiber, rootRenderLanes), false;
+ }
+ sourceFiber = sourceFiber.return;
+ } while (null !== sourceFiber);
+ return false;
+ }
+ __name(throwException, "throwException");
+ function reconcileChildren(current, workInProgress2, nextChildren, renderLanes2) {
+ workInProgress2.child = null === current ? mountChildFibers(workInProgress2, null, nextChildren, renderLanes2) : reconcileChildFibers(
+ workInProgress2,
+ current.child,
+ nextChildren,
+ renderLanes2
+ );
+ }
+ __name(reconcileChildren, "reconcileChildren");
+ function updateForwardRef(current, workInProgress2, Component, nextProps, renderLanes2) {
+ Component = Component.render;
+ var ref = workInProgress2.ref;
+ if ("ref" in nextProps) {
+ var propsWithoutRef = {};
+ for (var key in nextProps)
+ "ref" !== key && (propsWithoutRef[key] = nextProps[key]);
+ } else propsWithoutRef = nextProps;
+ prepareToReadContext(workInProgress2);
+ nextProps = renderWithHooks(
+ current,
+ workInProgress2,
+ Component,
+ propsWithoutRef,
+ ref,
+ renderLanes2
+ );
+ key = checkDidRenderIdHook();
+ if (null !== current && !didReceiveUpdate)
+ return bailoutHooks(current, workInProgress2, renderLanes2), bailoutOnAlreadyFinishedWork(current, workInProgress2, renderLanes2);
+ isHydrating && key && pushMaterializedTreeId(workInProgress2);
+ workInProgress2.flags |= 1;
+ reconcileChildren(current, workInProgress2, nextProps, renderLanes2);
+ return workInProgress2.child;
+ }
+ __name(updateForwardRef, "updateForwardRef");
+ function updateMemoComponent(current, workInProgress2, Component, nextProps, renderLanes2) {
+ if (null === current) {
+ var type2 = Component.type;
+ if ("function" === typeof type2 && !shouldConstruct(type2) && void 0 === type2.defaultProps && null === Component.compare)
+ return workInProgress2.tag = 15, workInProgress2.type = type2, updateSimpleMemoComponent(
+ current,
+ workInProgress2,
+ type2,
+ nextProps,
+ renderLanes2
+ );
+ current = createFiberFromTypeAndProps(
+ Component.type,
+ null,
+ nextProps,
+ workInProgress2,
+ workInProgress2.mode,
+ renderLanes2
+ );
+ current.ref = workInProgress2.ref;
+ current.return = workInProgress2;
+ return workInProgress2.child = current;
+ }
+ type2 = current.child;
+ if (!checkScheduledUpdateOrContext(current, renderLanes2)) {
+ var prevProps = type2.memoizedProps;
+ Component = Component.compare;
+ Component = null !== Component ? Component : shallowEqual;
+ if (Component(prevProps, nextProps) && current.ref === workInProgress2.ref)
+ return bailoutOnAlreadyFinishedWork(
+ current,
+ workInProgress2,
+ renderLanes2
+ );
+ }
+ workInProgress2.flags |= 1;
+ current = createWorkInProgress(type2, nextProps);
+ current.ref = workInProgress2.ref;
+ current.return = workInProgress2;
+ return workInProgress2.child = current;
+ }
+ __name(updateMemoComponent, "updateMemoComponent");
+ function updateSimpleMemoComponent(current, workInProgress2, Component, nextProps, renderLanes2) {
+ if (null !== current) {
+ var prevProps = current.memoizedProps;
+ if (shallowEqual(prevProps, nextProps) && current.ref === workInProgress2.ref)
+ if (didReceiveUpdate = false, workInProgress2.pendingProps = nextProps = prevProps, checkScheduledUpdateOrContext(current, renderLanes2))
+ 0 !== (current.flags & 131072) && (didReceiveUpdate = true);
+ else
+ return workInProgress2.lanes = current.lanes, bailoutOnAlreadyFinishedWork(current, workInProgress2, renderLanes2);
+ }
+ return updateFunctionComponent(
+ current,
+ workInProgress2,
+ Component,
+ nextProps,
+ renderLanes2
+ );
+ }
+ __name(updateSimpleMemoComponent, "updateSimpleMemoComponent");
+ function updateOffscreenComponent(current, workInProgress2, renderLanes2, nextProps) {
+ var nextChildren = nextProps.children, prevState = null !== current ? current.memoizedState : null;
+ null === current && null === workInProgress2.stateNode && (workInProgress2.stateNode = {
+ _visibility: 1,
+ _pendingMarkers: null,
+ _retryCache: null,
+ _transitions: null
+ });
+ if ("hidden" === nextProps.mode) {
+ if (0 !== (workInProgress2.flags & 128)) {
+ prevState = null !== prevState ? prevState.baseLanes | renderLanes2 : renderLanes2;
+ if (null !== current) {
+ nextProps = workInProgress2.child = current.child;
+ for (nextChildren = 0; null !== nextProps; )
+ nextChildren = nextChildren | nextProps.lanes | nextProps.childLanes, nextProps = nextProps.sibling;
+ nextProps = nextChildren & ~prevState;
+ } else nextProps = 0, workInProgress2.child = null;
+ return deferHiddenOffscreenComponent(
+ current,
+ workInProgress2,
+ prevState,
+ renderLanes2,
+ nextProps
+ );
+ }
+ if (0 !== (renderLanes2 & 536870912))
+ workInProgress2.memoizedState = { baseLanes: 0, cachePool: null }, null !== current && pushTransition(
+ workInProgress2,
+ null !== prevState ? prevState.cachePool : null
+ ), null !== prevState ? pushHiddenContext(workInProgress2, prevState) : reuseHiddenContextOnStack(), pushOffscreenSuspenseHandler(workInProgress2);
+ else
+ return nextProps = workInProgress2.lanes = 536870912, deferHiddenOffscreenComponent(
+ current,
+ workInProgress2,
+ null !== prevState ? prevState.baseLanes | renderLanes2 : renderLanes2,
+ renderLanes2,
+ nextProps
+ );
+ } else
+ null !== prevState ? (pushTransition(workInProgress2, prevState.cachePool), pushHiddenContext(workInProgress2, prevState), reuseSuspenseHandlerOnStack(workInProgress2), workInProgress2.memoizedState = null) : (null !== current && pushTransition(workInProgress2, null), reuseHiddenContextOnStack(), reuseSuspenseHandlerOnStack(workInProgress2));
+ reconcileChildren(current, workInProgress2, nextChildren, renderLanes2);
+ return workInProgress2.child;
+ }
+ __name(updateOffscreenComponent, "updateOffscreenComponent");
+ function bailoutOffscreenComponent(current, workInProgress2) {
+ null !== current && 22 === current.tag || null !== workInProgress2.stateNode || (workInProgress2.stateNode = {
+ _visibility: 1,
+ _pendingMarkers: null,
+ _retryCache: null,
+ _transitions: null
+ });
+ return workInProgress2.sibling;
+ }
+ __name(bailoutOffscreenComponent, "bailoutOffscreenComponent");
+ function deferHiddenOffscreenComponent(current, workInProgress2, nextBaseLanes, renderLanes2, remainingChildLanes) {
+ var JSCompiler_inline_result = peekCacheFromPool();
+ JSCompiler_inline_result = null === JSCompiler_inline_result ? null : {
+ parent: isPrimaryRenderer ? CacheContext._currentValue : CacheContext._currentValue2,
+ pool: JSCompiler_inline_result
+ };
+ workInProgress2.memoizedState = {
+ baseLanes: nextBaseLanes,
+ cachePool: JSCompiler_inline_result
+ };
+ null !== current && pushTransition(workInProgress2, null);
+ reuseHiddenContextOnStack();
+ pushOffscreenSuspenseHandler(workInProgress2);
+ null !== current && propagateParentContextChanges(current, workInProgress2, renderLanes2, true);
+ workInProgress2.childLanes = remainingChildLanes;
+ return null;
+ }
+ __name(deferHiddenOffscreenComponent, "deferHiddenOffscreenComponent");
+ function mountActivityChildren(workInProgress2, nextProps) {
+ nextProps = mountWorkInProgressOffscreenFiber(
+ { mode: nextProps.mode, children: nextProps.children },
+ workInProgress2.mode
+ );
+ nextProps.ref = workInProgress2.ref;
+ workInProgress2.child = nextProps;
+ nextProps.return = workInProgress2;
+ return nextProps;
+ }
+ __name(mountActivityChildren, "mountActivityChildren");
+ function retryActivityComponentWithoutHydrating(current, workInProgress2, renderLanes2) {
+ reconcileChildFibers(workInProgress2, current.child, null, renderLanes2);
+ current = mountActivityChildren(
+ workInProgress2,
+ workInProgress2.pendingProps
+ );
+ current.flags |= 2;
+ popSuspenseHandler(workInProgress2);
+ workInProgress2.memoizedState = null;
+ return current;
+ }
+ __name(retryActivityComponentWithoutHydrating, "retryActivityComponentWithoutHydrating");
+ function updateActivityComponent(current, workInProgress2, renderLanes2) {
+ var nextProps = workInProgress2.pendingProps, didSuspend = 0 !== (workInProgress2.flags & 128);
+ workInProgress2.flags &= -129;
+ if (null === current) {
+ if (isHydrating) {
+ if ("hidden" === nextProps.mode)
+ return current = mountActivityChildren(workInProgress2, nextProps), workInProgress2.lanes = 536870912, bailoutOffscreenComponent(null, current);
+ pushDehydratedActivitySuspenseHandler(workInProgress2);
+ (current = nextHydratableInstance) ? (current = canHydrateActivityInstance(
+ current,
+ rootOrSingletonContext
+ ), null !== current && (workInProgress2.memoizedState = {
+ dehydrated: current,
+ treeContext: null !== treeContextProvider ? { id: treeContextId, overflow: treeContextOverflow } : null,
+ retryLane: 536870912,
+ hydrationErrors: null
+ }, renderLanes2 = createFiberFromDehydratedFragment(current), renderLanes2.return = workInProgress2, workInProgress2.child = renderLanes2, hydrationParentFiber = workInProgress2, nextHydratableInstance = null)) : current = null;
+ if (null === current) throw throwOnHydrationMismatch(workInProgress2);
+ workInProgress2.lanes = 536870912;
+ return null;
+ }
+ return mountActivityChildren(workInProgress2, nextProps);
+ }
+ var prevState = current.memoizedState;
+ if (null !== prevState) {
+ var dehydrated = prevState.dehydrated;
+ pushDehydratedActivitySuspenseHandler(workInProgress2);
+ if (didSuspend)
+ if (workInProgress2.flags & 256)
+ workInProgress2.flags &= -257, workInProgress2 = retryActivityComponentWithoutHydrating(
+ current,
+ workInProgress2,
+ renderLanes2
+ );
+ else if (null !== workInProgress2.memoizedState)
+ workInProgress2.child = current.child, workInProgress2.flags |= 128, workInProgress2 = null;
+ else throw Error(formatProdErrorMessage(558));
+ else if (didReceiveUpdate || propagateParentContextChanges(
+ current,
+ workInProgress2,
+ renderLanes2,
+ false
+ ), didSuspend = 0 !== (renderLanes2 & current.childLanes), didReceiveUpdate || didSuspend) {
+ nextProps = workInProgressRoot;
+ if (null !== nextProps && (dehydrated = getBumpedLaneForHydration(nextProps, renderLanes2), 0 !== dehydrated && dehydrated !== prevState.retryLane))
+ throw prevState.retryLane = dehydrated, enqueueConcurrentRenderForLane(current, dehydrated), scheduleUpdateOnFiber(nextProps, current, dehydrated), SelectiveHydrationException;
+ renderDidSuspendDelayIfPossible();
+ workInProgress2 = retryActivityComponentWithoutHydrating(
+ current,
+ workInProgress2,
+ renderLanes2
+ );
+ } else
+ current = prevState.treeContext, supportsHydration && (nextHydratableInstance = getFirstHydratableChildWithinActivityInstance(dehydrated), hydrationParentFiber = workInProgress2, isHydrating = true, hydrationErrors = null, rootOrSingletonContext = false, null !== current && restoreSuspendedTreeContext(workInProgress2, current)), workInProgress2 = mountActivityChildren(workInProgress2, nextProps), workInProgress2.flags |= 4096;
+ return workInProgress2;
+ }
+ current = createWorkInProgress(current.child, {
+ mode: nextProps.mode,
+ children: nextProps.children
+ });
+ current.ref = workInProgress2.ref;
+ workInProgress2.child = current;
+ current.return = workInProgress2;
+ return current;
+ }
+ __name(updateActivityComponent, "updateActivityComponent");
+ function markRef(current, workInProgress2) {
+ var ref = workInProgress2.ref;
+ if (null === ref)
+ null !== current && null !== current.ref && (workInProgress2.flags |= 4194816);
+ else {
+ if ("function" !== typeof ref && "object" !== typeof ref)
+ throw Error(formatProdErrorMessage(284));
+ if (null === current || current.ref !== ref)
+ workInProgress2.flags |= 4194816;
+ }
+ }
+ __name(markRef, "markRef");
+ function updateFunctionComponent(current, workInProgress2, Component, nextProps, renderLanes2) {
+ prepareToReadContext(workInProgress2);
+ Component = renderWithHooks(
+ current,
+ workInProgress2,
+ Component,
+ nextProps,
+ void 0,
+ renderLanes2
+ );
+ nextProps = checkDidRenderIdHook();
+ if (null !== current && !didReceiveUpdate)
+ return bailoutHooks(current, workInProgress2, renderLanes2), bailoutOnAlreadyFinishedWork(current, workInProgress2, renderLanes2);
+ isHydrating && nextProps && pushMaterializedTreeId(workInProgress2);
+ workInProgress2.flags |= 1;
+ reconcileChildren(current, workInProgress2, Component, renderLanes2);
+ return workInProgress2.child;
+ }
+ __name(updateFunctionComponent, "updateFunctionComponent");
+ function replayFunctionComponent(current, workInProgress2, nextProps, Component, secondArg, renderLanes2) {
+ prepareToReadContext(workInProgress2);
+ workInProgress2.updateQueue = null;
+ nextProps = renderWithHooksAgain(
+ workInProgress2,
+ Component,
+ nextProps,
+ secondArg
+ );
+ finishRenderingHooks(current);
+ Component = checkDidRenderIdHook();
+ if (null !== current && !didReceiveUpdate)
+ return bailoutHooks(current, workInProgress2, renderLanes2), bailoutOnAlreadyFinishedWork(current, workInProgress2, renderLanes2);
+ isHydrating && Component && pushMaterializedTreeId(workInProgress2);
+ workInProgress2.flags |= 1;
+ reconcileChildren(current, workInProgress2, nextProps, renderLanes2);
+ return workInProgress2.child;
+ }
+ __name(replayFunctionComponent, "replayFunctionComponent");
+ function updateClassComponent(current, workInProgress2, Component, nextProps, renderLanes2) {
+ prepareToReadContext(workInProgress2);
+ if (null === workInProgress2.stateNode) {
+ var context = emptyContextObject, contextType = Component.contextType;
+ "object" === typeof contextType && null !== contextType && (context = readContext(contextType));
+ context = new Component(nextProps, context);
+ workInProgress2.memoizedState = null !== context.state && void 0 !== context.state ? context.state : null;
+ context.updater = classComponentUpdater;
+ workInProgress2.stateNode = context;
+ context._reactInternals = workInProgress2;
+ context = workInProgress2.stateNode;
+ context.props = nextProps;
+ context.state = workInProgress2.memoizedState;
+ context.refs = {};
+ initializeUpdateQueue(workInProgress2);
+ contextType = Component.contextType;
+ context.context = "object" === typeof contextType && null !== contextType ? readContext(contextType) : emptyContextObject;
+ context.state = workInProgress2.memoizedState;
+ contextType = Component.getDerivedStateFromProps;
+ "function" === typeof contextType && (applyDerivedStateFromProps(
+ workInProgress2,
+ Component,
+ contextType,
+ nextProps
+ ), context.state = workInProgress2.memoizedState);
+ "function" === typeof Component.getDerivedStateFromProps || "function" === typeof context.getSnapshotBeforeUpdate || "function" !== typeof context.UNSAFE_componentWillMount && "function" !== typeof context.componentWillMount || (contextType = context.state, "function" === typeof context.componentWillMount && context.componentWillMount(), "function" === typeof context.UNSAFE_componentWillMount && context.UNSAFE_componentWillMount(), contextType !== context.state && classComponentUpdater.enqueueReplaceState(
+ context,
+ context.state,
+ null
+ ), processUpdateQueue(workInProgress2, nextProps, context, renderLanes2), suspendIfUpdateReadFromEntangledAsyncAction(), context.state = workInProgress2.memoizedState);
+ "function" === typeof context.componentDidMount && (workInProgress2.flags |= 4194308);
+ nextProps = true;
+ } else if (null === current) {
+ context = workInProgress2.stateNode;
+ var unresolvedOldProps = workInProgress2.memoizedProps, oldProps = resolveClassComponentProps(Component, unresolvedOldProps);
+ context.props = oldProps;
+ var oldContext = context.context, contextType$jscomp$0 = Component.contextType;
+ contextType = emptyContextObject;
+ "object" === typeof contextType$jscomp$0 && null !== contextType$jscomp$0 && (contextType = readContext(contextType$jscomp$0));
+ var getDerivedStateFromProps = Component.getDerivedStateFromProps;
+ contextType$jscomp$0 = "function" === typeof getDerivedStateFromProps || "function" === typeof context.getSnapshotBeforeUpdate;
+ unresolvedOldProps = workInProgress2.pendingProps !== unresolvedOldProps;
+ contextType$jscomp$0 || "function" !== typeof context.UNSAFE_componentWillReceiveProps && "function" !== typeof context.componentWillReceiveProps || (unresolvedOldProps || oldContext !== contextType) && callComponentWillReceiveProps(
+ workInProgress2,
+ context,
+ nextProps,
+ contextType
+ );
+ hasForceUpdate = false;
+ var oldState = workInProgress2.memoizedState;
+ context.state = oldState;
+ processUpdateQueue(workInProgress2, nextProps, context, renderLanes2);
+ suspendIfUpdateReadFromEntangledAsyncAction();
+ oldContext = workInProgress2.memoizedState;
+ unresolvedOldProps || oldState !== oldContext || hasForceUpdate ? ("function" === typeof getDerivedStateFromProps && (applyDerivedStateFromProps(
+ workInProgress2,
+ Component,
+ getDerivedStateFromProps,
+ nextProps
+ ), oldContext = workInProgress2.memoizedState), (oldProps = hasForceUpdate || checkShouldComponentUpdate(
+ workInProgress2,
+ Component,
+ oldProps,
+ nextProps,
+ oldState,
+ oldContext,
+ contextType
+ )) ? (contextType$jscomp$0 || "function" !== typeof context.UNSAFE_componentWillMount && "function" !== typeof context.componentWillMount || ("function" === typeof context.componentWillMount && context.componentWillMount(), "function" === typeof context.UNSAFE_componentWillMount && context.UNSAFE_componentWillMount()), "function" === typeof context.componentDidMount && (workInProgress2.flags |= 4194308)) : ("function" === typeof context.componentDidMount && (workInProgress2.flags |= 4194308), workInProgress2.memoizedProps = nextProps, workInProgress2.memoizedState = oldContext), context.props = nextProps, context.state = oldContext, context.context = contextType, nextProps = oldProps) : ("function" === typeof context.componentDidMount && (workInProgress2.flags |= 4194308), nextProps = false);
+ } else {
+ context = workInProgress2.stateNode;
+ cloneUpdateQueue(current, workInProgress2);
+ contextType = workInProgress2.memoizedProps;
+ contextType$jscomp$0 = resolveClassComponentProps(Component, contextType);
+ context.props = contextType$jscomp$0;
+ getDerivedStateFromProps = workInProgress2.pendingProps;
+ oldState = context.context;
+ oldContext = Component.contextType;
+ oldProps = emptyContextObject;
+ "object" === typeof oldContext && null !== oldContext && (oldProps = readContext(oldContext));
+ unresolvedOldProps = Component.getDerivedStateFromProps;
+ (oldContext = "function" === typeof unresolvedOldProps || "function" === typeof context.getSnapshotBeforeUpdate) || "function" !== typeof context.UNSAFE_componentWillReceiveProps && "function" !== typeof context.componentWillReceiveProps || (contextType !== getDerivedStateFromProps || oldState !== oldProps) && callComponentWillReceiveProps(
+ workInProgress2,
+ context,
+ nextProps,
+ oldProps
+ );
+ hasForceUpdate = false;
+ oldState = workInProgress2.memoizedState;
+ context.state = oldState;
+ processUpdateQueue(workInProgress2, nextProps, context, renderLanes2);
+ suspendIfUpdateReadFromEntangledAsyncAction();
+ var newState = workInProgress2.memoizedState;
+ contextType !== getDerivedStateFromProps || oldState !== newState || hasForceUpdate || null !== current && null !== current.dependencies && checkIfContextChanged(current.dependencies) ? ("function" === typeof unresolvedOldProps && (applyDerivedStateFromProps(
+ workInProgress2,
+ Component,
+ unresolvedOldProps,
+ nextProps
+ ), newState = workInProgress2.memoizedState), (contextType$jscomp$0 = hasForceUpdate || checkShouldComponentUpdate(
+ workInProgress2,
+ Component,
+ contextType$jscomp$0,
+ nextProps,
+ oldState,
+ newState,
+ oldProps
+ ) || null !== current && null !== current.dependencies && checkIfContextChanged(current.dependencies)) ? (oldContext || "function" !== typeof context.UNSAFE_componentWillUpdate && "function" !== typeof context.componentWillUpdate || ("function" === typeof context.componentWillUpdate && context.componentWillUpdate(nextProps, newState, oldProps), "function" === typeof context.UNSAFE_componentWillUpdate && context.UNSAFE_componentWillUpdate(
+ nextProps,
+ newState,
+ oldProps
+ )), "function" === typeof context.componentDidUpdate && (workInProgress2.flags |= 4), "function" === typeof context.getSnapshotBeforeUpdate && (workInProgress2.flags |= 1024)) : ("function" !== typeof context.componentDidUpdate || contextType === current.memoizedProps && oldState === current.memoizedState || (workInProgress2.flags |= 4), "function" !== typeof context.getSnapshotBeforeUpdate || contextType === current.memoizedProps && oldState === current.memoizedState || (workInProgress2.flags |= 1024), workInProgress2.memoizedProps = nextProps, workInProgress2.memoizedState = newState), context.props = nextProps, context.state = newState, context.context = oldProps, nextProps = contextType$jscomp$0) : ("function" !== typeof context.componentDidUpdate || contextType === current.memoizedProps && oldState === current.memoizedState || (workInProgress2.flags |= 4), "function" !== typeof context.getSnapshotBeforeUpdate || contextType === current.memoizedProps && oldState === current.memoizedState || (workInProgress2.flags |= 1024), nextProps = false);
+ }
+ context = nextProps;
+ markRef(current, workInProgress2);
+ nextProps = 0 !== (workInProgress2.flags & 128);
+ context || nextProps ? (context = workInProgress2.stateNode, Component = nextProps && "function" !== typeof Component.getDerivedStateFromError ? null : context.render(), workInProgress2.flags |= 1, null !== current && nextProps ? (workInProgress2.child = reconcileChildFibers(
+ workInProgress2,
+ current.child,
+ null,
+ renderLanes2
+ ), workInProgress2.child = reconcileChildFibers(
+ workInProgress2,
+ null,
+ Component,
+ renderLanes2
+ )) : reconcileChildren(current, workInProgress2, Component, renderLanes2), workInProgress2.memoizedState = context.state, current = workInProgress2.child) : current = bailoutOnAlreadyFinishedWork(
+ current,
+ workInProgress2,
+ renderLanes2
+ );
+ return current;
+ }
+ __name(updateClassComponent, "updateClassComponent");
+ function mountHostRootWithoutHydrating(current, workInProgress2, nextChildren, renderLanes2) {
+ resetHydrationState();
+ workInProgress2.flags |= 256;
+ reconcileChildren(current, workInProgress2, nextChildren, renderLanes2);
+ return workInProgress2.child;
+ }
+ __name(mountHostRootWithoutHydrating, "mountHostRootWithoutHydrating");
+ function mountSuspenseOffscreenState(renderLanes2) {
+ return { baseLanes: renderLanes2, cachePool: getSuspendedCache() };
+ }
+ __name(mountSuspenseOffscreenState, "mountSuspenseOffscreenState");
+ function getRemainingWorkInPrimaryTree(current, primaryTreeDidDefer, renderLanes2) {
+ current = null !== current ? current.childLanes & ~renderLanes2 : 0;
+ primaryTreeDidDefer && (current |= workInProgressDeferredLane);
+ return current;
+ }
+ __name(getRemainingWorkInPrimaryTree, "getRemainingWorkInPrimaryTree");
+ function updateSuspenseComponent(current, workInProgress2, renderLanes2) {
+ var nextProps = workInProgress2.pendingProps, showFallback = false, didSuspend = 0 !== (workInProgress2.flags & 128), JSCompiler_temp;
+ (JSCompiler_temp = didSuspend) || (JSCompiler_temp = null !== current && null === current.memoizedState ? false : 0 !== (suspenseStackCursor.current & 2));
+ JSCompiler_temp && (showFallback = true, workInProgress2.flags &= -129);
+ JSCompiler_temp = 0 !== (workInProgress2.flags & 32);
+ workInProgress2.flags &= -33;
+ if (null === current) {
+ if (isHydrating) {
+ showFallback ? pushPrimaryTreeSuspenseHandler(workInProgress2) : reuseSuspenseHandlerOnStack(workInProgress2);
+ (current = nextHydratableInstance) ? (current = canHydrateSuspenseInstance(
+ current,
+ rootOrSingletonContext
+ ), null !== current && (workInProgress2.memoizedState = {
+ dehydrated: current,
+ treeContext: null !== treeContextProvider ? { id: treeContextId, overflow: treeContextOverflow } : null,
+ retryLane: 536870912,
+ hydrationErrors: null
+ }, renderLanes2 = createFiberFromDehydratedFragment(current), renderLanes2.return = workInProgress2, workInProgress2.child = renderLanes2, hydrationParentFiber = workInProgress2, nextHydratableInstance = null)) : current = null;
+ if (null === current) throw throwOnHydrationMismatch(workInProgress2);
+ isSuspenseInstanceFallback(current) ? workInProgress2.lanes = 32 : workInProgress2.lanes = 536870912;
+ return null;
+ }
+ var nextPrimaryChildren = nextProps.children;
+ nextProps = nextProps.fallback;
+ if (showFallback)
+ return reuseSuspenseHandlerOnStack(workInProgress2), showFallback = workInProgress2.mode, nextPrimaryChildren = mountWorkInProgressOffscreenFiber(
+ { mode: "hidden", children: nextPrimaryChildren },
+ showFallback
+ ), nextProps = createFiberFromFragment(
+ nextProps,
+ showFallback,
+ renderLanes2,
+ null
+ ), nextPrimaryChildren.return = workInProgress2, nextProps.return = workInProgress2, nextPrimaryChildren.sibling = nextProps, workInProgress2.child = nextPrimaryChildren, nextProps = workInProgress2.child, nextProps.memoizedState = mountSuspenseOffscreenState(renderLanes2), nextProps.childLanes = getRemainingWorkInPrimaryTree(
+ current,
+ JSCompiler_temp,
+ renderLanes2
+ ), workInProgress2.memoizedState = SUSPENDED_MARKER, bailoutOffscreenComponent(null, nextProps);
+ pushPrimaryTreeSuspenseHandler(workInProgress2);
+ return mountSuspensePrimaryChildren(workInProgress2, nextPrimaryChildren);
+ }
+ var prevState = current.memoizedState;
+ if (null !== prevState && (nextPrimaryChildren = prevState.dehydrated, null !== nextPrimaryChildren)) {
+ if (didSuspend)
+ workInProgress2.flags & 256 ? (pushPrimaryTreeSuspenseHandler(workInProgress2), workInProgress2.flags &= -257, workInProgress2 = retrySuspenseComponentWithoutHydrating(
+ current,
+ workInProgress2,
+ renderLanes2
+ )) : null !== workInProgress2.memoizedState ? (reuseSuspenseHandlerOnStack(workInProgress2), workInProgress2.child = current.child, workInProgress2.flags |= 128, workInProgress2 = null) : (reuseSuspenseHandlerOnStack(workInProgress2), nextPrimaryChildren = nextProps.fallback, showFallback = workInProgress2.mode, nextProps = mountWorkInProgressOffscreenFiber(
+ { mode: "visible", children: nextProps.children },
+ showFallback
+ ), nextPrimaryChildren = createFiberFromFragment(
+ nextPrimaryChildren,
+ showFallback,
+ renderLanes2,
+ null
+ ), nextPrimaryChildren.flags |= 2, nextProps.return = workInProgress2, nextPrimaryChildren.return = workInProgress2, nextProps.sibling = nextPrimaryChildren, workInProgress2.child = nextProps, reconcileChildFibers(
+ workInProgress2,
+ current.child,
+ null,
+ renderLanes2
+ ), nextProps = workInProgress2.child, nextProps.memoizedState = mountSuspenseOffscreenState(renderLanes2), nextProps.childLanes = getRemainingWorkInPrimaryTree(
+ current,
+ JSCompiler_temp,
+ renderLanes2
+ ), workInProgress2.memoizedState = SUSPENDED_MARKER, workInProgress2 = bailoutOffscreenComponent(null, nextProps));
+ else if (pushPrimaryTreeSuspenseHandler(workInProgress2), isSuspenseInstanceFallback(nextPrimaryChildren))
+ JSCompiler_temp = getSuspenseInstanceFallbackErrorDetails(nextPrimaryChildren).digest, nextProps = Error(formatProdErrorMessage(419)), nextProps.stack = "", nextProps.digest = JSCompiler_temp, queueHydrationError({ value: nextProps, source: null, stack: null }), workInProgress2 = retrySuspenseComponentWithoutHydrating(
+ current,
+ workInProgress2,
+ renderLanes2
+ );
+ else if (didReceiveUpdate || propagateParentContextChanges(
+ current,
+ workInProgress2,
+ renderLanes2,
+ false
+ ), JSCompiler_temp = 0 !== (renderLanes2 & current.childLanes), didReceiveUpdate || JSCompiler_temp) {
+ JSCompiler_temp = workInProgressRoot;
+ if (null !== JSCompiler_temp && (nextProps = getBumpedLaneForHydration(
+ JSCompiler_temp,
+ renderLanes2
+ ), 0 !== nextProps && nextProps !== prevState.retryLane))
+ throw prevState.retryLane = nextProps, enqueueConcurrentRenderForLane(current, nextProps), scheduleUpdateOnFiber(JSCompiler_temp, current, nextProps), SelectiveHydrationException;
+ isSuspenseInstancePending(nextPrimaryChildren) || renderDidSuspendDelayIfPossible();
+ workInProgress2 = retrySuspenseComponentWithoutHydrating(
+ current,
+ workInProgress2,
+ renderLanes2
+ );
+ } else
+ isSuspenseInstancePending(nextPrimaryChildren) ? (workInProgress2.flags |= 192, workInProgress2.child = current.child, workInProgress2 = null) : (current = prevState.treeContext, supportsHydration && (nextHydratableInstance = getFirstHydratableChildWithinSuspenseInstance(
+ nextPrimaryChildren
+ ), hydrationParentFiber = workInProgress2, isHydrating = true, hydrationErrors = null, rootOrSingletonContext = false, null !== current && restoreSuspendedTreeContext(workInProgress2, current)), workInProgress2 = mountSuspensePrimaryChildren(
+ workInProgress2,
+ nextProps.children
+ ), workInProgress2.flags |= 4096);
+ return workInProgress2;
+ }
+ if (showFallback)
+ return reuseSuspenseHandlerOnStack(workInProgress2), nextPrimaryChildren = nextProps.fallback, showFallback = workInProgress2.mode, prevState = current.child, didSuspend = prevState.sibling, nextProps = createWorkInProgress(prevState, {
+ mode: "hidden",
+ children: nextProps.children
+ }), nextProps.subtreeFlags = prevState.subtreeFlags & 65011712, null !== didSuspend ? nextPrimaryChildren = createWorkInProgress(
+ didSuspend,
+ nextPrimaryChildren
+ ) : (nextPrimaryChildren = createFiberFromFragment(
+ nextPrimaryChildren,
+ showFallback,
+ renderLanes2,
+ null
+ ), nextPrimaryChildren.flags |= 2), nextPrimaryChildren.return = workInProgress2, nextProps.return = workInProgress2, nextProps.sibling = nextPrimaryChildren, workInProgress2.child = nextProps, bailoutOffscreenComponent(null, nextProps), nextProps = workInProgress2.child, nextPrimaryChildren = current.child.memoizedState, null === nextPrimaryChildren ? nextPrimaryChildren = mountSuspenseOffscreenState(renderLanes2) : (showFallback = nextPrimaryChildren.cachePool, null !== showFallback ? (prevState = isPrimaryRenderer ? CacheContext._currentValue : CacheContext._currentValue2, showFallback = showFallback.parent !== prevState ? { parent: prevState, pool: prevState } : showFallback) : showFallback = getSuspendedCache(), nextPrimaryChildren = {
+ baseLanes: nextPrimaryChildren.baseLanes | renderLanes2,
+ cachePool: showFallback
+ }), nextProps.memoizedState = nextPrimaryChildren, nextProps.childLanes = getRemainingWorkInPrimaryTree(
+ current,
+ JSCompiler_temp,
+ renderLanes2
+ ), workInProgress2.memoizedState = SUSPENDED_MARKER, bailoutOffscreenComponent(current.child, nextProps);
+ pushPrimaryTreeSuspenseHandler(workInProgress2);
+ renderLanes2 = current.child;
+ current = renderLanes2.sibling;
+ renderLanes2 = createWorkInProgress(renderLanes2, {
+ mode: "visible",
+ children: nextProps.children
+ });
+ renderLanes2.return = workInProgress2;
+ renderLanes2.sibling = null;
+ null !== current && (JSCompiler_temp = workInProgress2.deletions, null === JSCompiler_temp ? (workInProgress2.deletions = [current], workInProgress2.flags |= 16) : JSCompiler_temp.push(current));
+ workInProgress2.child = renderLanes2;
+ workInProgress2.memoizedState = null;
+ return renderLanes2;
+ }
+ __name(updateSuspenseComponent, "updateSuspenseComponent");
+ function mountSuspensePrimaryChildren(workInProgress2, primaryChildren) {
+ primaryChildren = mountWorkInProgressOffscreenFiber(
+ { mode: "visible", children: primaryChildren },
+ workInProgress2.mode
+ );
+ primaryChildren.return = workInProgress2;
+ return workInProgress2.child = primaryChildren;
+ }
+ __name(mountSuspensePrimaryChildren, "mountSuspensePrimaryChildren");
+ function mountWorkInProgressOffscreenFiber(offscreenProps, mode) {
+ offscreenProps = createFiber(22, offscreenProps, null, mode);
+ offscreenProps.lanes = 0;
+ return offscreenProps;
+ }
+ __name(mountWorkInProgressOffscreenFiber, "mountWorkInProgressOffscreenFiber");
+ function retrySuspenseComponentWithoutHydrating(current, workInProgress2, renderLanes2) {
+ reconcileChildFibers(workInProgress2, current.child, null, renderLanes2);
+ current = mountSuspensePrimaryChildren(
+ workInProgress2,
+ workInProgress2.pendingProps.children
+ );
+ current.flags |= 2;
+ workInProgress2.memoizedState = null;
+ return current;
+ }
+ __name(retrySuspenseComponentWithoutHydrating, "retrySuspenseComponentWithoutHydrating");
+ function scheduleSuspenseWorkOnFiber(fiber, renderLanes2, propagationRoot) {
+ fiber.lanes |= renderLanes2;
+ var alternate = fiber.alternate;
+ null !== alternate && (alternate.lanes |= renderLanes2);
+ scheduleContextWorkOnParentPath(fiber.return, renderLanes2, propagationRoot);
+ }
+ __name(scheduleSuspenseWorkOnFiber, "scheduleSuspenseWorkOnFiber");
+ function initSuspenseListRenderState(workInProgress2, isBackwards, tail, lastContentRow, tailMode, treeForkCount2) {
+ var renderState = workInProgress2.memoizedState;
+ null === renderState ? workInProgress2.memoizedState = {
+ isBackwards,
+ rendering: null,
+ renderingStartTime: 0,
+ last: lastContentRow,
+ tail,
+ tailMode,
+ treeForkCount: treeForkCount2
+ } : (renderState.isBackwards = isBackwards, renderState.rendering = null, renderState.renderingStartTime = 0, renderState.last = lastContentRow, renderState.tail = tail, renderState.tailMode = tailMode, renderState.treeForkCount = treeForkCount2);
+ }
+ __name(initSuspenseListRenderState, "initSuspenseListRenderState");
+ function updateSuspenseListComponent(current, workInProgress2, renderLanes2) {
+ var nextProps = workInProgress2.pendingProps, revealOrder = nextProps.revealOrder, tailMode = nextProps.tail;
+ nextProps = nextProps.children;
+ var suspenseContext = suspenseStackCursor.current, shouldForceFallback = 0 !== (suspenseContext & 2);
+ shouldForceFallback ? (suspenseContext = suspenseContext & 1 | 2, workInProgress2.flags |= 128) : suspenseContext &= 1;
+ push(suspenseStackCursor, suspenseContext);
+ reconcileChildren(current, workInProgress2, nextProps, renderLanes2);
+ nextProps = isHydrating ? treeForkCount : 0;
+ if (!shouldForceFallback && null !== current && 0 !== (current.flags & 128))
+ a: for (current = workInProgress2.child; null !== current; ) {
+ if (13 === current.tag)
+ null !== current.memoizedState && scheduleSuspenseWorkOnFiber(current, renderLanes2, workInProgress2);
+ else if (19 === current.tag)
+ scheduleSuspenseWorkOnFiber(current, renderLanes2, workInProgress2);
+ else if (null !== current.child) {
+ current.child.return = current;
+ current = current.child;
+ continue;
+ }
+ if (current === workInProgress2) break a;
+ for (; null === current.sibling; ) {
+ if (null === current.return || current.return === workInProgress2)
+ break a;
+ current = current.return;
+ }
+ current.sibling.return = current.return;
+ current = current.sibling;
+ }
+ switch (revealOrder) {
+ case "forwards":
+ renderLanes2 = workInProgress2.child;
+ for (revealOrder = null; null !== renderLanes2; )
+ current = renderLanes2.alternate, null !== current && null === findFirstSuspended(current) && (revealOrder = renderLanes2), renderLanes2 = renderLanes2.sibling;
+ renderLanes2 = revealOrder;
+ null === renderLanes2 ? (revealOrder = workInProgress2.child, workInProgress2.child = null) : (revealOrder = renderLanes2.sibling, renderLanes2.sibling = null);
+ initSuspenseListRenderState(
+ workInProgress2,
+ false,
+ revealOrder,
+ renderLanes2,
+ tailMode,
+ nextProps
+ );
+ break;
+ case "backwards":
+ case "unstable_legacy-backwards":
+ renderLanes2 = null;
+ revealOrder = workInProgress2.child;
+ for (workInProgress2.child = null; null !== revealOrder; ) {
+ current = revealOrder.alternate;
+ if (null !== current && null === findFirstSuspended(current)) {
+ workInProgress2.child = revealOrder;
+ break;
+ }
+ current = revealOrder.sibling;
+ revealOrder.sibling = renderLanes2;
+ renderLanes2 = revealOrder;
+ revealOrder = current;
+ }
+ initSuspenseListRenderState(
+ workInProgress2,
+ true,
+ renderLanes2,
+ null,
+ tailMode,
+ nextProps
+ );
+ break;
+ case "together":
+ initSuspenseListRenderState(
+ workInProgress2,
+ false,
+ null,
+ null,
+ void 0,
+ nextProps
+ );
+ break;
+ default:
+ workInProgress2.memoizedState = null;
+ }
+ return workInProgress2.child;
+ }
+ __name(updateSuspenseListComponent, "updateSuspenseListComponent");
+ function bailoutOnAlreadyFinishedWork(current, workInProgress2, renderLanes2) {
+ null !== current && (workInProgress2.dependencies = current.dependencies);
+ workInProgressRootSkippedLanes |= workInProgress2.lanes;
+ if (0 === (renderLanes2 & workInProgress2.childLanes))
+ if (null !== current) {
+ if (propagateParentContextChanges(
+ current,
+ workInProgress2,
+ renderLanes2,
+ false
+ ), 0 === (renderLanes2 & workInProgress2.childLanes))
+ return null;
+ } else return null;
+ if (null !== current && workInProgress2.child !== current.child)
+ throw Error(formatProdErrorMessage(153));
+ if (null !== workInProgress2.child) {
+ current = workInProgress2.child;
+ renderLanes2 = createWorkInProgress(current, current.pendingProps);
+ workInProgress2.child = renderLanes2;
+ for (renderLanes2.return = workInProgress2; null !== current.sibling; )
+ current = current.sibling, renderLanes2 = renderLanes2.sibling = createWorkInProgress(current, current.pendingProps), renderLanes2.return = workInProgress2;
+ renderLanes2.sibling = null;
+ }
+ return workInProgress2.child;
+ }
+ __name(bailoutOnAlreadyFinishedWork, "bailoutOnAlreadyFinishedWork");
+ function checkScheduledUpdateOrContext(current, renderLanes2) {
+ if (0 !== (current.lanes & renderLanes2)) return true;
+ current = current.dependencies;
+ return null !== current && checkIfContextChanged(current) ? true : false;
+ }
+ __name(checkScheduledUpdateOrContext, "checkScheduledUpdateOrContext");
+ function attemptEarlyBailoutIfNoScheduledUpdate(current, workInProgress2, renderLanes2) {
+ switch (workInProgress2.tag) {
+ case 3:
+ pushHostContainer(
+ workInProgress2,
+ workInProgress2.stateNode.containerInfo
+ );
+ pushProvider(workInProgress2, CacheContext, current.memoizedState.cache);
+ resetHydrationState();
+ break;
+ case 27:
+ case 5:
+ pushHostContext(workInProgress2);
+ break;
+ case 4:
+ pushHostContainer(
+ workInProgress2,
+ workInProgress2.stateNode.containerInfo
+ );
+ break;
+ case 10:
+ pushProvider(
+ workInProgress2,
+ workInProgress2.type,
+ workInProgress2.memoizedProps.value
+ );
+ break;
+ case 31:
+ if (null !== workInProgress2.memoizedState)
+ return workInProgress2.flags |= 128, pushDehydratedActivitySuspenseHandler(workInProgress2), null;
+ break;
+ case 13:
+ var state$82 = workInProgress2.memoizedState;
+ if (null !== state$82) {
+ if (null !== state$82.dehydrated)
+ return pushPrimaryTreeSuspenseHandler(workInProgress2), workInProgress2.flags |= 128, null;
+ if (0 !== (renderLanes2 & workInProgress2.child.childLanes))
+ return updateSuspenseComponent(
+ current,
+ workInProgress2,
+ renderLanes2
+ );
+ pushPrimaryTreeSuspenseHandler(workInProgress2);
+ current = bailoutOnAlreadyFinishedWork(
+ current,
+ workInProgress2,
+ renderLanes2
+ );
+ return null !== current ? current.sibling : null;
+ }
+ pushPrimaryTreeSuspenseHandler(workInProgress2);
+ break;
+ case 19:
+ var didSuspendBefore = 0 !== (current.flags & 128);
+ state$82 = 0 !== (renderLanes2 & workInProgress2.childLanes);
+ state$82 || (propagateParentContextChanges(
+ current,
+ workInProgress2,
+ renderLanes2,
+ false
+ ), state$82 = 0 !== (renderLanes2 & workInProgress2.childLanes));
+ if (didSuspendBefore) {
+ if (state$82)
+ return updateSuspenseListComponent(
+ current,
+ workInProgress2,
+ renderLanes2
+ );
+ workInProgress2.flags |= 128;
+ }
+ didSuspendBefore = workInProgress2.memoizedState;
+ null !== didSuspendBefore && (didSuspendBefore.rendering = null, didSuspendBefore.tail = null, didSuspendBefore.lastEffect = null);
+ push(suspenseStackCursor, suspenseStackCursor.current);
+ if (state$82) break;
+ else return null;
+ case 22:
+ return workInProgress2.lanes = 0, updateOffscreenComponent(
+ current,
+ workInProgress2,
+ renderLanes2,
+ workInProgress2.pendingProps
+ );
+ case 24:
+ pushProvider(workInProgress2, CacheContext, current.memoizedState.cache);
+ }
+ return bailoutOnAlreadyFinishedWork(current, workInProgress2, renderLanes2);
+ }
+ __name(attemptEarlyBailoutIfNoScheduledUpdate, "attemptEarlyBailoutIfNoScheduledUpdate");
+ function beginWork(current, workInProgress2, renderLanes2) {
+ if (null !== current)
+ if (current.memoizedProps !== workInProgress2.pendingProps)
+ didReceiveUpdate = true;
+ else {
+ if (!checkScheduledUpdateOrContext(current, renderLanes2) && 0 === (workInProgress2.flags & 128))
+ return didReceiveUpdate = false, attemptEarlyBailoutIfNoScheduledUpdate(
+ current,
+ workInProgress2,
+ renderLanes2
+ );
+ didReceiveUpdate = 0 !== (current.flags & 131072) ? true : false;
+ }
+ else
+ didReceiveUpdate = false, isHydrating && 0 !== (workInProgress2.flags & 1048576) && pushTreeId(workInProgress2, treeForkCount, workInProgress2.index);
+ workInProgress2.lanes = 0;
+ switch (workInProgress2.tag) {
+ case 16:
+ a: {
+ var props = workInProgress2.pendingProps;
+ current = resolveLazy(workInProgress2.elementType);
+ workInProgress2.type = current;
+ if ("function" === typeof current)
+ shouldConstruct(current) ? (props = resolveClassComponentProps(current, props), workInProgress2.tag = 1, workInProgress2 = updateClassComponent(
+ null,
+ workInProgress2,
+ current,
+ props,
+ renderLanes2
+ )) : (workInProgress2.tag = 0, workInProgress2 = updateFunctionComponent(
+ null,
+ workInProgress2,
+ current,
+ props,
+ renderLanes2
+ ));
+ else {
+ if (void 0 !== current && null !== current) {
+ var $$typeof = current.$$typeof;
+ if ($$typeof === REACT_FORWARD_REF_TYPE) {
+ workInProgress2.tag = 11;
+ workInProgress2 = updateForwardRef(
+ null,
+ workInProgress2,
+ current,
+ props,
+ renderLanes2
+ );
+ break a;
+ } else if ($$typeof === REACT_MEMO_TYPE) {
+ workInProgress2.tag = 14;
+ workInProgress2 = updateMemoComponent(
+ null,
+ workInProgress2,
+ current,
+ props,
+ renderLanes2
+ );
+ break a;
+ }
+ }
+ workInProgress2 = getComponentNameFromType(current) || current;
+ throw Error(formatProdErrorMessage(306, workInProgress2, ""));
+ }
+ }
+ return workInProgress2;
+ case 0:
+ return updateFunctionComponent(
+ current,
+ workInProgress2,
+ workInProgress2.type,
+ workInProgress2.pendingProps,
+ renderLanes2
+ );
+ case 1:
+ return props = workInProgress2.type, $$typeof = resolveClassComponentProps(
+ props,
+ workInProgress2.pendingProps
+ ), updateClassComponent(
+ current,
+ workInProgress2,
+ props,
+ $$typeof,
+ renderLanes2
+ );
+ case 3:
+ a: {
+ pushHostContainer(
+ workInProgress2,
+ workInProgress2.stateNode.containerInfo
+ );
+ if (null === current) throw Error(formatProdErrorMessage(387));
+ var nextProps = workInProgress2.pendingProps;
+ $$typeof = workInProgress2.memoizedState;
+ props = $$typeof.element;
+ cloneUpdateQueue(current, workInProgress2);
+ processUpdateQueue(workInProgress2, nextProps, null, renderLanes2);
+ var nextState = workInProgress2.memoizedState;
+ nextProps = nextState.cache;
+ pushProvider(workInProgress2, CacheContext, nextProps);
+ nextProps !== $$typeof.cache && propagateContextChanges(
+ workInProgress2,
+ [CacheContext],
+ renderLanes2,
+ true
+ );
+ suspendIfUpdateReadFromEntangledAsyncAction();
+ nextProps = nextState.element;
+ if (supportsHydration && $$typeof.isDehydrated)
+ if ($$typeof = {
+ element: nextProps,
+ isDehydrated: false,
+ cache: nextState.cache
+ }, workInProgress2.updateQueue.baseState = $$typeof, workInProgress2.memoizedState = $$typeof, workInProgress2.flags & 256) {
+ workInProgress2 = mountHostRootWithoutHydrating(
+ current,
+ workInProgress2,
+ nextProps,
+ renderLanes2
+ );
+ break a;
+ } else if (nextProps !== props) {
+ props = createCapturedValueAtFiber(
+ Error(formatProdErrorMessage(424)),
+ workInProgress2
+ );
+ queueHydrationError(props);
+ workInProgress2 = mountHostRootWithoutHydrating(
+ current,
+ workInProgress2,
+ nextProps,
+ renderLanes2
+ );
+ break a;
+ } else
+ for (supportsHydration && (nextHydratableInstance = getFirstHydratableChildWithinContainer(
+ workInProgress2.stateNode.containerInfo
+ ), hydrationParentFiber = workInProgress2, isHydrating = true, hydrationErrors = null, rootOrSingletonContext = true), renderLanes2 = mountChildFibers(
+ workInProgress2,
+ null,
+ nextProps,
+ renderLanes2
+ ), workInProgress2.child = renderLanes2; renderLanes2; )
+ renderLanes2.flags = renderLanes2.flags & -3 | 4096, renderLanes2 = renderLanes2.sibling;
+ else {
+ resetHydrationState();
+ if (nextProps === props) {
+ workInProgress2 = bailoutOnAlreadyFinishedWork(
+ current,
+ workInProgress2,
+ renderLanes2
+ );
+ break a;
+ }
+ reconcileChildren(current, workInProgress2, nextProps, renderLanes2);
+ }
+ workInProgress2 = workInProgress2.child;
+ }
+ return workInProgress2;
+ case 26:
+ if (supportsResources)
+ return markRef(current, workInProgress2), null === current ? (renderLanes2 = getResource(
+ workInProgress2.type,
+ null,
+ workInProgress2.pendingProps,
+ null
+ )) ? workInProgress2.memoizedState = renderLanes2 : isHydrating || (workInProgress2.stateNode = createHoistableInstance(
+ workInProgress2.type,
+ workInProgress2.pendingProps,
+ rootInstanceStackCursor.current,
+ workInProgress2
+ )) : workInProgress2.memoizedState = getResource(
+ workInProgress2.type,
+ current.memoizedProps,
+ workInProgress2.pendingProps,
+ current.memoizedState
+ ), null;
+ case 27:
+ if (supportsSingletons)
+ return pushHostContext(workInProgress2), null === current && supportsSingletons && isHydrating && (props = workInProgress2.stateNode = resolveSingletonInstance(
+ workInProgress2.type,
+ workInProgress2.pendingProps,
+ rootInstanceStackCursor.current,
+ contextStackCursor.current,
+ false
+ ), hydrationParentFiber = workInProgress2, rootOrSingletonContext = true, nextHydratableInstance = getFirstHydratableChildWithinSingleton(
+ workInProgress2.type,
+ props,
+ nextHydratableInstance
+ )), reconcileChildren(
+ current,
+ workInProgress2,
+ workInProgress2.pendingProps.children,
+ renderLanes2
+ ), markRef(current, workInProgress2), null === current && (workInProgress2.flags |= 4194304), workInProgress2.child;
+ case 5:
+ if (null === current && isHydrating) {
+ validateHydratableInstance(
+ workInProgress2.type,
+ workInProgress2.pendingProps,
+ contextStackCursor.current
+ );
+ if ($$typeof = props = nextHydratableInstance)
+ props = canHydrateInstance(
+ props,
+ workInProgress2.type,
+ workInProgress2.pendingProps,
+ rootOrSingletonContext
+ ), null !== props ? (workInProgress2.stateNode = props, hydrationParentFiber = workInProgress2, nextHydratableInstance = getFirstHydratableChild(props), rootOrSingletonContext = false, $$typeof = true) : $$typeof = false;
+ $$typeof || throwOnHydrationMismatch(workInProgress2);
+ }
+ pushHostContext(workInProgress2);
+ $$typeof = workInProgress2.type;
+ nextProps = workInProgress2.pendingProps;
+ nextState = null !== current ? current.memoizedProps : null;
+ props = nextProps.children;
+ shouldSetTextContent($$typeof, nextProps) ? props = null : null !== nextState && shouldSetTextContent($$typeof, nextState) && (workInProgress2.flags |= 32);
+ null !== workInProgress2.memoizedState && ($$typeof = renderWithHooks(
+ current,
+ workInProgress2,
+ TransitionAwareHostComponent,
+ null,
+ null,
+ renderLanes2
+ ), isPrimaryRenderer ? HostTransitionContext._currentValue = $$typeof : HostTransitionContext._currentValue2 = $$typeof);
+ markRef(current, workInProgress2);
+ reconcileChildren(current, workInProgress2, props, renderLanes2);
+ return workInProgress2.child;
+ case 6:
+ if (null === current && isHydrating) {
+ validateHydratableTextInstance(
+ workInProgress2.pendingProps,
+ contextStackCursor.current
+ );
+ if (current = renderLanes2 = nextHydratableInstance)
+ renderLanes2 = canHydrateTextInstance(
+ renderLanes2,
+ workInProgress2.pendingProps,
+ rootOrSingletonContext
+ ), null !== renderLanes2 ? (workInProgress2.stateNode = renderLanes2, hydrationParentFiber = workInProgress2, nextHydratableInstance = null, current = true) : current = false;
+ current || throwOnHydrationMismatch(workInProgress2);
+ }
+ return null;
+ case 13:
+ return updateSuspenseComponent(current, workInProgress2, renderLanes2);
+ case 4:
+ return pushHostContainer(
+ workInProgress2,
+ workInProgress2.stateNode.containerInfo
+ ), props = workInProgress2.pendingProps, null === current ? workInProgress2.child = reconcileChildFibers(
+ workInProgress2,
+ null,
+ props,
+ renderLanes2
+ ) : reconcileChildren(current, workInProgress2, props, renderLanes2), workInProgress2.child;
+ case 11:
+ return updateForwardRef(
+ current,
+ workInProgress2,
+ workInProgress2.type,
+ workInProgress2.pendingProps,
+ renderLanes2
+ );
+ case 7:
+ return reconcileChildren(
+ current,
+ workInProgress2,
+ workInProgress2.pendingProps,
+ renderLanes2
+ ), workInProgress2.child;
+ case 8:
+ return reconcileChildren(
+ current,
+ workInProgress2,
+ workInProgress2.pendingProps.children,
+ renderLanes2
+ ), workInProgress2.child;
+ case 12:
+ return reconcileChildren(
+ current,
+ workInProgress2,
+ workInProgress2.pendingProps.children,
+ renderLanes2
+ ), workInProgress2.child;
+ case 10:
+ return props = workInProgress2.pendingProps, pushProvider(workInProgress2, workInProgress2.type, props.value), reconcileChildren(
+ current,
+ workInProgress2,
+ props.children,
+ renderLanes2
+ ), workInProgress2.child;
+ case 9:
+ return $$typeof = workInProgress2.type._context, props = workInProgress2.pendingProps.children, prepareToReadContext(workInProgress2), $$typeof = readContext($$typeof), props = props($$typeof), workInProgress2.flags |= 1, reconcileChildren(current, workInProgress2, props, renderLanes2), workInProgress2.child;
+ case 14:
+ return updateMemoComponent(
+ current,
+ workInProgress2,
+ workInProgress2.type,
+ workInProgress2.pendingProps,
+ renderLanes2
+ );
+ case 15:
+ return updateSimpleMemoComponent(
+ current,
+ workInProgress2,
+ workInProgress2.type,
+ workInProgress2.pendingProps,
+ renderLanes2
+ );
+ case 19:
+ return updateSuspenseListComponent(
+ current,
+ workInProgress2,
+ renderLanes2
+ );
+ case 31:
+ return updateActivityComponent(current, workInProgress2, renderLanes2);
+ case 22:
+ return updateOffscreenComponent(
+ current,
+ workInProgress2,
+ renderLanes2,
+ workInProgress2.pendingProps
+ );
+ case 24:
+ return prepareToReadContext(workInProgress2), props = readContext(CacheContext), null === current ? ($$typeof = peekCacheFromPool(), null === $$typeof && ($$typeof = workInProgressRoot, nextProps = createCache(), $$typeof.pooledCache = nextProps, nextProps.refCount++, null !== nextProps && ($$typeof.pooledCacheLanes |= renderLanes2), $$typeof = nextProps), workInProgress2.memoizedState = {
+ parent: props,
+ cache: $$typeof
+ }, initializeUpdateQueue(workInProgress2), pushProvider(workInProgress2, CacheContext, $$typeof)) : (0 !== (current.lanes & renderLanes2) && (cloneUpdateQueue(current, workInProgress2), processUpdateQueue(workInProgress2, null, null, renderLanes2), suspendIfUpdateReadFromEntangledAsyncAction()), $$typeof = current.memoizedState, nextProps = workInProgress2.memoizedState, $$typeof.parent !== props ? ($$typeof = { parent: props, cache: props }, workInProgress2.memoizedState = $$typeof, 0 === workInProgress2.lanes && (workInProgress2.memoizedState = workInProgress2.updateQueue.baseState = $$typeof), pushProvider(workInProgress2, CacheContext, props)) : (props = nextProps.cache, pushProvider(workInProgress2, CacheContext, props), props !== $$typeof.cache && propagateContextChanges(
+ workInProgress2,
+ [CacheContext],
+ renderLanes2,
+ true
+ ))), reconcileChildren(
+ current,
+ workInProgress2,
+ workInProgress2.pendingProps.children,
+ renderLanes2
+ ), workInProgress2.child;
+ case 29:
+ throw workInProgress2.pendingProps;
+ }
+ throw Error(formatProdErrorMessage(156, workInProgress2.tag));
+ }
+ __name(beginWork, "beginWork");
+ function markUpdate(workInProgress2) {
+ workInProgress2.flags |= 4;
+ }
+ __name(markUpdate, "markUpdate");
+ function markCloned(workInProgress2) {
+ supportsPersistence && (workInProgress2.flags |= 8);
+ }
+ __name(markCloned, "markCloned");
+ function doesRequireClone(current, completedWork) {
+ if (null !== current && current.child === completedWork.child) return false;
+ if (0 !== (completedWork.flags & 16)) return true;
+ for (current = completedWork.child; null !== current; ) {
+ if (0 !== (current.flags & 8218) || 0 !== (current.subtreeFlags & 8218))
+ return true;
+ current = current.sibling;
+ }
+ return false;
+ }
+ __name(doesRequireClone, "doesRequireClone");
+ function appendAllChildren(parent, workInProgress2, needsVisibilityToggle, isHidden2) {
+ if (supportsMutation)
+ for (needsVisibilityToggle = workInProgress2.child; null !== needsVisibilityToggle; ) {
+ if (5 === needsVisibilityToggle.tag || 6 === needsVisibilityToggle.tag)
+ appendInitialChild(parent, needsVisibilityToggle.stateNode);
+ else if (!(4 === needsVisibilityToggle.tag || supportsSingletons && 27 === needsVisibilityToggle.tag) && null !== needsVisibilityToggle.child) {
+ needsVisibilityToggle.child.return = needsVisibilityToggle;
+ needsVisibilityToggle = needsVisibilityToggle.child;
+ continue;
+ }
+ if (needsVisibilityToggle === workInProgress2) break;
+ for (; null === needsVisibilityToggle.sibling; ) {
+ if (null === needsVisibilityToggle.return || needsVisibilityToggle.return === workInProgress2)
+ return;
+ needsVisibilityToggle = needsVisibilityToggle.return;
+ }
+ needsVisibilityToggle.sibling.return = needsVisibilityToggle.return;
+ needsVisibilityToggle = needsVisibilityToggle.sibling;
+ }
+ else if (supportsPersistence)
+ for (var node$85 = workInProgress2.child; null !== node$85; ) {
+ if (5 === node$85.tag) {
+ var instance = node$85.stateNode;
+ needsVisibilityToggle && isHidden2 && (instance = cloneHiddenInstance(
+ instance,
+ node$85.type,
+ node$85.memoizedProps
+ ));
+ appendInitialChild(parent, instance);
+ } else if (6 === node$85.tag)
+ instance = node$85.stateNode, needsVisibilityToggle && isHidden2 && (instance = cloneHiddenTextInstance(
+ instance,
+ node$85.memoizedProps
+ )), appendInitialChild(parent, instance);
+ else if (4 !== node$85.tag) {
+ if (22 === node$85.tag && null !== node$85.memoizedState)
+ instance = node$85.child, null !== instance && (instance.return = node$85), appendAllChildren(parent, node$85, true, true);
+ else if (null !== node$85.child) {
+ node$85.child.return = node$85;
+ node$85 = node$85.child;
+ continue;
+ }
+ }
+ if (node$85 === workInProgress2) break;
+ for (; null === node$85.sibling; ) {
+ if (null === node$85.return || node$85.return === workInProgress2)
+ return;
+ node$85 = node$85.return;
+ }
+ node$85.sibling.return = node$85.return;
+ node$85 = node$85.sibling;
+ }
+ }
+ __name(appendAllChildren, "appendAllChildren");
+ function appendAllChildrenToContainer(containerChildSet, workInProgress2, needsVisibilityToggle, isHidden2) {
+ var hasOffscreenComponentChild = false;
+ if (supportsPersistence)
+ for (var node = workInProgress2.child; null !== node; ) {
+ if (5 === node.tag) {
+ var instance = node.stateNode;
+ needsVisibilityToggle && isHidden2 && (instance = cloneHiddenInstance(
+ instance,
+ node.type,
+ node.memoizedProps
+ ));
+ appendChildToContainerChildSet(containerChildSet, instance);
+ } else if (6 === node.tag)
+ instance = node.stateNode, needsVisibilityToggle && isHidden2 && (instance = cloneHiddenTextInstance(
+ instance,
+ node.memoizedProps
+ )), appendChildToContainerChildSet(containerChildSet, instance);
+ else if (4 !== node.tag) {
+ if (22 === node.tag && null !== node.memoizedState)
+ hasOffscreenComponentChild = node.child, null !== hasOffscreenComponentChild && (hasOffscreenComponentChild.return = node), appendAllChildrenToContainer(containerChildSet, node, true, true), hasOffscreenComponentChild = true;
+ else if (null !== node.child) {
+ node.child.return = node;
+ node = node.child;
+ continue;
+ }
+ }
+ if (node === workInProgress2) break;
+ for (; null === node.sibling; ) {
+ if (null === node.return || node.return === workInProgress2)
+ return hasOffscreenComponentChild;
+ node = node.return;
+ }
+ node.sibling.return = node.return;
+ node = node.sibling;
+ }
+ return hasOffscreenComponentChild;
+ }
+ __name(appendAllChildrenToContainer, "appendAllChildrenToContainer");
+ function updateHostContainer(current, workInProgress2) {
+ if (supportsPersistence && doesRequireClone(current, workInProgress2)) {
+ current = workInProgress2.stateNode;
+ var container = current.containerInfo, newChildSet = createContainerChildSet();
+ appendAllChildrenToContainer(newChildSet, workInProgress2, false, false);
+ current.pendingChildren = newChildSet;
+ markUpdate(workInProgress2);
+ finalizeContainerChildren(container, newChildSet);
+ }
+ }
+ __name(updateHostContainer, "updateHostContainer");
+ function updateHostComponent(current, workInProgress2, type2, newProps) {
+ if (supportsMutation)
+ current.memoizedProps !== newProps && markUpdate(workInProgress2);
+ else if (supportsPersistence) {
+ var currentInstance = current.stateNode, oldProps$88 = current.memoizedProps;
+ if ((current = doesRequireClone(current, workInProgress2)) || oldProps$88 !== newProps) {
+ var currentHostContext = contextStackCursor.current;
+ oldProps$88 = cloneInstance(
+ currentInstance,
+ type2,
+ oldProps$88,
+ newProps,
+ !current,
+ null
+ );
+ oldProps$88 === currentInstance ? workInProgress2.stateNode = currentInstance : (markCloned(workInProgress2), finalizeInitialChildren(
+ oldProps$88,
+ type2,
+ newProps,
+ currentHostContext
+ ) && markUpdate(workInProgress2), workInProgress2.stateNode = oldProps$88, current && appendAllChildren(oldProps$88, workInProgress2, false, false));
+ } else workInProgress2.stateNode = currentInstance;
+ }
+ }
+ __name(updateHostComponent, "updateHostComponent");
+ function preloadInstanceAndSuspendIfNeeded(workInProgress2, type2, oldProps, newProps, renderLanes2) {
+ if (0 !== (workInProgress2.mode & 32) && (null === oldProps ? maySuspendCommit(type2, newProps) : maySuspendCommitOnUpdate(type2, oldProps, newProps))) {
+ if (workInProgress2.flags |= 16777216, (renderLanes2 & 335544128) === renderLanes2 || maySuspendCommitInSyncRender(type2, newProps))
+ if (preloadInstance(workInProgress2.stateNode, type2, newProps))
+ workInProgress2.flags |= 8192;
+ else if (shouldRemainOnPreviousScreen()) workInProgress2.flags |= 8192;
+ else
+ throw suspendedThenable = noopSuspenseyCommitThenable, SuspenseyCommitException;
+ } else workInProgress2.flags &= -16777217;
+ }
+ __name(preloadInstanceAndSuspendIfNeeded, "preloadInstanceAndSuspendIfNeeded");
+ function preloadResourceAndSuspendIfNeeded(workInProgress2, resource) {
+ if (mayResourceSuspendCommit(resource)) {
+ if (workInProgress2.flags |= 16777216, !preloadResource(resource))
+ if (shouldRemainOnPreviousScreen()) workInProgress2.flags |= 8192;
+ else
+ throw suspendedThenable = noopSuspenseyCommitThenable, SuspenseyCommitException;
+ } else workInProgress2.flags &= -16777217;
+ }
+ __name(preloadResourceAndSuspendIfNeeded, "preloadResourceAndSuspendIfNeeded");
+ function scheduleRetryEffect(workInProgress2, retryQueue) {
+ null !== retryQueue && (workInProgress2.flags |= 4);
+ workInProgress2.flags & 16384 && (retryQueue = 22 !== workInProgress2.tag ? claimNextRetryLane() : 536870912, workInProgress2.lanes |= retryQueue, workInProgressSuspendedRetryLanes |= retryQueue);
+ }
+ __name(scheduleRetryEffect, "scheduleRetryEffect");
+ function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) {
+ if (!isHydrating)
+ switch (renderState.tailMode) {
+ case "hidden":
+ hasRenderedATailFallback = renderState.tail;
+ for (var lastTailNode = null; null !== hasRenderedATailFallback; )
+ null !== hasRenderedATailFallback.alternate && (lastTailNode = hasRenderedATailFallback), hasRenderedATailFallback = hasRenderedATailFallback.sibling;
+ null === lastTailNode ? renderState.tail = null : lastTailNode.sibling = null;
+ break;
+ case "collapsed":
+ lastTailNode = renderState.tail;
+ for (var lastTailNode$90 = null; null !== lastTailNode; )
+ null !== lastTailNode.alternate && (lastTailNode$90 = lastTailNode), lastTailNode = lastTailNode.sibling;
+ null === lastTailNode$90 ? hasRenderedATailFallback || null === renderState.tail ? renderState.tail = null : renderState.tail.sibling = null : lastTailNode$90.sibling = null;
+ }
+ }
+ __name(cutOffTailIfNeeded, "cutOffTailIfNeeded");
+ function bubbleProperties(completedWork) {
+ var didBailout = null !== completedWork.alternate && completedWork.alternate.child === completedWork.child, newChildLanes = 0, subtreeFlags = 0;
+ if (didBailout)
+ for (var child$91 = completedWork.child; null !== child$91; )
+ newChildLanes |= child$91.lanes | child$91.childLanes, subtreeFlags |= child$91.subtreeFlags & 65011712, subtreeFlags |= child$91.flags & 65011712, child$91.return = completedWork, child$91 = child$91.sibling;
+ else
+ for (child$91 = completedWork.child; null !== child$91; )
+ newChildLanes |= child$91.lanes | child$91.childLanes, subtreeFlags |= child$91.subtreeFlags, subtreeFlags |= child$91.flags, child$91.return = completedWork, child$91 = child$91.sibling;
+ completedWork.subtreeFlags |= subtreeFlags;
+ completedWork.childLanes = newChildLanes;
+ return didBailout;
+ }
+ __name(bubbleProperties, "bubbleProperties");
+ function completeWork(current, workInProgress2, renderLanes2) {
+ var newProps = workInProgress2.pendingProps;
+ popTreeContext(workInProgress2);
+ switch (workInProgress2.tag) {
+ case 16:
+ case 15:
+ case 0:
+ case 11:
+ case 7:
+ case 8:
+ case 12:
+ case 9:
+ case 14:
+ return bubbleProperties(workInProgress2), null;
+ case 1:
+ return bubbleProperties(workInProgress2), null;
+ case 3:
+ renderLanes2 = workInProgress2.stateNode;
+ newProps = null;
+ null !== current && (newProps = current.memoizedState.cache);
+ workInProgress2.memoizedState.cache !== newProps && (workInProgress2.flags |= 2048);
+ popProvider(CacheContext);
+ popHostContainer();
+ renderLanes2.pendingContext && (renderLanes2.context = renderLanes2.pendingContext, renderLanes2.pendingContext = null);
+ if (null === current || null === current.child)
+ popHydrationState(workInProgress2) ? markUpdate(workInProgress2) : null === current || current.memoizedState.isDehydrated && 0 === (workInProgress2.flags & 256) || (workInProgress2.flags |= 1024, upgradeHydrationErrorsToRecoverable());
+ updateHostContainer(current, workInProgress2);
+ bubbleProperties(workInProgress2);
+ return null;
+ case 26:
+ if (supportsResources) {
+ var type2 = workInProgress2.type, nextResource = workInProgress2.memoizedState;
+ null === current ? (markUpdate(workInProgress2), null !== nextResource ? (bubbleProperties(workInProgress2), preloadResourceAndSuspendIfNeeded(
+ workInProgress2,
+ nextResource
+ )) : (bubbleProperties(workInProgress2), preloadInstanceAndSuspendIfNeeded(
+ workInProgress2,
+ type2,
+ null,
+ newProps,
+ renderLanes2
+ ))) : nextResource ? nextResource !== current.memoizedState ? (markUpdate(workInProgress2), bubbleProperties(workInProgress2), preloadResourceAndSuspendIfNeeded(
+ workInProgress2,
+ nextResource
+ )) : (bubbleProperties(workInProgress2), workInProgress2.flags &= -16777217) : (nextResource = current.memoizedProps, supportsMutation ? nextResource !== newProps && markUpdate(workInProgress2) : updateHostComponent(
+ current,
+ workInProgress2,
+ type2,
+ newProps
+ ), bubbleProperties(workInProgress2), preloadInstanceAndSuspendIfNeeded(
+ workInProgress2,
+ type2,
+ nextResource,
+ newProps,
+ renderLanes2
+ ));
+ return null;
+ }
+ case 27:
+ if (supportsSingletons) {
+ popHostContext(workInProgress2);
+ renderLanes2 = rootInstanceStackCursor.current;
+ type2 = workInProgress2.type;
+ if (null !== current && null != workInProgress2.stateNode)
+ supportsMutation ? current.memoizedProps !== newProps && markUpdate(workInProgress2) : updateHostComponent(current, workInProgress2, type2, newProps);
+ else {
+ if (!newProps) {
+ if (null === workInProgress2.stateNode)
+ throw Error(formatProdErrorMessage(166));
+ bubbleProperties(workInProgress2);
+ return null;
+ }
+ current = contextStackCursor.current;
+ popHydrationState(workInProgress2) ? prepareToHydrateHostInstance(workInProgress2, current) : (current = resolveSingletonInstance(
+ type2,
+ newProps,
+ renderLanes2,
+ current,
+ true
+ ), workInProgress2.stateNode = current, markUpdate(workInProgress2));
+ }
+ bubbleProperties(workInProgress2);
+ return null;
+ }
+ case 5:
+ popHostContext(workInProgress2);
+ type2 = workInProgress2.type;
+ if (null !== current && null != workInProgress2.stateNode)
+ updateHostComponent(current, workInProgress2, type2, newProps);
+ else {
+ if (!newProps) {
+ if (null === workInProgress2.stateNode)
+ throw Error(formatProdErrorMessage(166));
+ bubbleProperties(workInProgress2);
+ return null;
+ }
+ nextResource = contextStackCursor.current;
+ if (popHydrationState(workInProgress2))
+ prepareToHydrateHostInstance(workInProgress2, nextResource), finalizeHydratedChildren(
+ workInProgress2.stateNode,
+ type2,
+ newProps,
+ nextResource
+ ) && (workInProgress2.flags |= 64);
+ else {
+ var instance$101 = createInstance(
+ type2,
+ newProps,
+ rootInstanceStackCursor.current,
+ nextResource,
+ workInProgress2
+ );
+ markCloned(workInProgress2);
+ appendAllChildren(instance$101, workInProgress2, false, false);
+ workInProgress2.stateNode = instance$101;
+ finalizeInitialChildren(
+ instance$101,
+ type2,
+ newProps,
+ nextResource
+ ) && markUpdate(workInProgress2);
+ }
+ }
+ bubbleProperties(workInProgress2);
+ preloadInstanceAndSuspendIfNeeded(
+ workInProgress2,
+ workInProgress2.type,
+ null === current ? null : current.memoizedProps,
+ workInProgress2.pendingProps,
+ renderLanes2
+ );
+ return null;
+ case 6:
+ if (current && null != workInProgress2.stateNode)
+ renderLanes2 = current.memoizedProps, supportsMutation ? renderLanes2 !== newProps && markUpdate(workInProgress2) : supportsPersistence && (renderLanes2 !== newProps ? (current = rootInstanceStackCursor.current, renderLanes2 = contextStackCursor.current, markCloned(workInProgress2), workInProgress2.stateNode = createTextInstance(
+ newProps,
+ current,
+ renderLanes2,
+ workInProgress2
+ )) : workInProgress2.stateNode = current.stateNode);
+ else {
+ if ("string" !== typeof newProps && null === workInProgress2.stateNode)
+ throw Error(formatProdErrorMessage(166));
+ current = rootInstanceStackCursor.current;
+ renderLanes2 = contextStackCursor.current;
+ if (popHydrationState(workInProgress2)) {
+ if (!supportsHydration) throw Error(formatProdErrorMessage(176));
+ current = workInProgress2.stateNode;
+ renderLanes2 = workInProgress2.memoizedProps;
+ newProps = null;
+ type2 = hydrationParentFiber;
+ if (null !== type2)
+ switch (type2.tag) {
+ case 27:
+ case 5:
+ newProps = type2.memoizedProps;
+ }
+ hydrateTextInstance(
+ current,
+ renderLanes2,
+ workInProgress2,
+ newProps
+ ) || throwOnHydrationMismatch(workInProgress2, true);
+ } else
+ markCloned(workInProgress2), workInProgress2.stateNode = createTextInstance(
+ newProps,
+ current,
+ renderLanes2,
+ workInProgress2
+ );
+ }
+ bubbleProperties(workInProgress2);
+ return null;
+ case 31:
+ renderLanes2 = workInProgress2.memoizedState;
+ if (null === current || null !== current.memoizedState) {
+ newProps = popHydrationState(workInProgress2);
+ if (null !== renderLanes2) {
+ if (null === current) {
+ if (!newProps) throw Error(formatProdErrorMessage(318));
+ if (!supportsHydration) throw Error(formatProdErrorMessage(556));
+ current = workInProgress2.memoizedState;
+ current = null !== current ? current.dehydrated : null;
+ if (!current) throw Error(formatProdErrorMessage(557));
+ hydrateActivityInstance(current, workInProgress2);
+ } else
+ resetHydrationState(), 0 === (workInProgress2.flags & 128) && (workInProgress2.memoizedState = null), workInProgress2.flags |= 4;
+ bubbleProperties(workInProgress2);
+ current = false;
+ } else
+ renderLanes2 = upgradeHydrationErrorsToRecoverable(), null !== current && null !== current.memoizedState && (current.memoizedState.hydrationErrors = renderLanes2), current = true;
+ if (!current) {
+ if (workInProgress2.flags & 256)
+ return popSuspenseHandler(workInProgress2), workInProgress2;
+ popSuspenseHandler(workInProgress2);
+ return null;
+ }
+ if (0 !== (workInProgress2.flags & 128))
+ throw Error(formatProdErrorMessage(558));
+ }
+ bubbleProperties(workInProgress2);
+ return null;
+ case 13:
+ newProps = workInProgress2.memoizedState;
+ if (null === current || null !== current.memoizedState && null !== current.memoizedState.dehydrated) {
+ type2 = popHydrationState(workInProgress2);
+ if (null !== newProps && null !== newProps.dehydrated) {
+ if (null === current) {
+ if (!type2) throw Error(formatProdErrorMessage(318));
+ if (!supportsHydration) throw Error(formatProdErrorMessage(344));
+ type2 = workInProgress2.memoizedState;
+ type2 = null !== type2 ? type2.dehydrated : null;
+ if (!type2) throw Error(formatProdErrorMessage(317));
+ hydrateSuspenseInstance(type2, workInProgress2);
+ } else
+ resetHydrationState(), 0 === (workInProgress2.flags & 128) && (workInProgress2.memoizedState = null), workInProgress2.flags |= 4;
+ bubbleProperties(workInProgress2);
+ type2 = false;
+ } else
+ type2 = upgradeHydrationErrorsToRecoverable(), null !== current && null !== current.memoizedState && (current.memoizedState.hydrationErrors = type2), type2 = true;
+ if (!type2) {
+ if (workInProgress2.flags & 256)
+ return popSuspenseHandler(workInProgress2), workInProgress2;
+ popSuspenseHandler(workInProgress2);
+ return null;
+ }
+ }
+ popSuspenseHandler(workInProgress2);
+ if (0 !== (workInProgress2.flags & 128))
+ return workInProgress2.lanes = renderLanes2, workInProgress2;
+ renderLanes2 = null !== newProps;
+ current = null !== current && null !== current.memoizedState;
+ renderLanes2 && (newProps = workInProgress2.child, type2 = null, null !== newProps.alternate && null !== newProps.alternate.memoizedState && null !== newProps.alternate.memoizedState.cachePool && (type2 = newProps.alternate.memoizedState.cachePool.pool), nextResource = null, null !== newProps.memoizedState && null !== newProps.memoizedState.cachePool && (nextResource = newProps.memoizedState.cachePool.pool), nextResource !== type2 && (newProps.flags |= 2048));
+ renderLanes2 !== current && renderLanes2 && (workInProgress2.child.flags |= 8192);
+ scheduleRetryEffect(workInProgress2, workInProgress2.updateQueue);
+ bubbleProperties(workInProgress2);
+ return null;
+ case 4:
+ return popHostContainer(), updateHostContainer(current, workInProgress2), null === current && preparePortalMount(workInProgress2.stateNode.containerInfo), bubbleProperties(workInProgress2), null;
+ case 10:
+ return popProvider(workInProgress2.type), bubbleProperties(workInProgress2), null;
+ case 19:
+ pop(suspenseStackCursor);
+ newProps = workInProgress2.memoizedState;
+ if (null === newProps) return bubbleProperties(workInProgress2), null;
+ type2 = 0 !== (workInProgress2.flags & 128);
+ nextResource = newProps.rendering;
+ if (null === nextResource)
+ if (type2) cutOffTailIfNeeded(newProps, false);
+ else {
+ if (0 !== workInProgressRootExitStatus || null !== current && 0 !== (current.flags & 128))
+ for (current = workInProgress2.child; null !== current; ) {
+ nextResource = findFirstSuspended(current);
+ if (null !== nextResource) {
+ workInProgress2.flags |= 128;
+ cutOffTailIfNeeded(newProps, false);
+ current = nextResource.updateQueue;
+ workInProgress2.updateQueue = current;
+ scheduleRetryEffect(workInProgress2, current);
+ workInProgress2.subtreeFlags = 0;
+ current = renderLanes2;
+ for (renderLanes2 = workInProgress2.child; null !== renderLanes2; )
+ resetWorkInProgress(renderLanes2, current), renderLanes2 = renderLanes2.sibling;
+ push(
+ suspenseStackCursor,
+ suspenseStackCursor.current & 1 | 2
+ );
+ isHydrating && pushTreeFork(workInProgress2, newProps.treeForkCount);
+ return workInProgress2.child;
+ }
+ current = current.sibling;
+ }
+ null !== newProps.tail && now() > workInProgressRootRenderTargetTime && (workInProgress2.flags |= 128, type2 = true, cutOffTailIfNeeded(newProps, false), workInProgress2.lanes = 4194304);
+ }
+ else {
+ if (!type2)
+ if (current = findFirstSuspended(nextResource), null !== current) {
+ if (workInProgress2.flags |= 128, type2 = true, current = current.updateQueue, workInProgress2.updateQueue = current, scheduleRetryEffect(workInProgress2, current), cutOffTailIfNeeded(newProps, true), null === newProps.tail && "hidden" === newProps.tailMode && !nextResource.alternate && !isHydrating)
+ return bubbleProperties(workInProgress2), null;
+ } else
+ 2 * now() - newProps.renderingStartTime > workInProgressRootRenderTargetTime && 536870912 !== renderLanes2 && (workInProgress2.flags |= 128, type2 = true, cutOffTailIfNeeded(newProps, false), workInProgress2.lanes = 4194304);
+ newProps.isBackwards ? (nextResource.sibling = workInProgress2.child, workInProgress2.child = nextResource) : (current = newProps.last, null !== current ? current.sibling = nextResource : workInProgress2.child = nextResource, newProps.last = nextResource);
+ }
+ if (null !== newProps.tail)
+ return current = newProps.tail, newProps.rendering = current, newProps.tail = current.sibling, newProps.renderingStartTime = now(), current.sibling = null, renderLanes2 = suspenseStackCursor.current, push(
+ suspenseStackCursor,
+ type2 ? renderLanes2 & 1 | 2 : renderLanes2 & 1
+ ), isHydrating && pushTreeFork(workInProgress2, newProps.treeForkCount), current;
+ bubbleProperties(workInProgress2);
+ return null;
+ case 22:
+ case 23:
+ return popSuspenseHandler(workInProgress2), popHiddenContext(), newProps = null !== workInProgress2.memoizedState, null !== current ? null !== current.memoizedState !== newProps && (workInProgress2.flags |= 8192) : newProps && (workInProgress2.flags |= 8192), newProps ? 0 !== (renderLanes2 & 536870912) && 0 === (workInProgress2.flags & 128) && (bubbleProperties(workInProgress2), workInProgress2.subtreeFlags & 6 && (workInProgress2.flags |= 8192)) : bubbleProperties(workInProgress2), renderLanes2 = workInProgress2.updateQueue, null !== renderLanes2 && scheduleRetryEffect(workInProgress2, renderLanes2.retryQueue), renderLanes2 = null, null !== current && null !== current.memoizedState && null !== current.memoizedState.cachePool && (renderLanes2 = current.memoizedState.cachePool.pool), newProps = null, null !== workInProgress2.memoizedState && null !== workInProgress2.memoizedState.cachePool && (newProps = workInProgress2.memoizedState.cachePool.pool), newProps !== renderLanes2 && (workInProgress2.flags |= 2048), null !== current && pop(resumedCache), null;
+ case 24:
+ return renderLanes2 = null, null !== current && (renderLanes2 = current.memoizedState.cache), workInProgress2.memoizedState.cache !== renderLanes2 && (workInProgress2.flags |= 2048), popProvider(CacheContext), bubbleProperties(workInProgress2), null;
+ case 25:
+ return null;
+ case 30:
+ return null;
+ }
+ throw Error(formatProdErrorMessage(156, workInProgress2.tag));
+ }
+ __name(completeWork, "completeWork");
+ function unwindWork(current, workInProgress2) {
+ popTreeContext(workInProgress2);
+ switch (workInProgress2.tag) {
+ case 1:
+ return current = workInProgress2.flags, current & 65536 ? (workInProgress2.flags = current & -65537 | 128, workInProgress2) : null;
+ case 3:
+ return popProvider(CacheContext), popHostContainer(), current = workInProgress2.flags, 0 !== (current & 65536) && 0 === (current & 128) ? (workInProgress2.flags = current & -65537 | 128, workInProgress2) : null;
+ case 26:
+ case 27:
+ case 5:
+ return popHostContext(workInProgress2), null;
+ case 31:
+ if (null !== workInProgress2.memoizedState) {
+ popSuspenseHandler(workInProgress2);
+ if (null === workInProgress2.alternate)
+ throw Error(formatProdErrorMessage(340));
+ resetHydrationState();
+ }
+ current = workInProgress2.flags;
+ return current & 65536 ? (workInProgress2.flags = current & -65537 | 128, workInProgress2) : null;
+ case 13:
+ popSuspenseHandler(workInProgress2);
+ current = workInProgress2.memoizedState;
+ if (null !== current && null !== current.dehydrated) {
+ if (null === workInProgress2.alternate)
+ throw Error(formatProdErrorMessage(340));
+ resetHydrationState();
+ }
+ current = workInProgress2.flags;
+ return current & 65536 ? (workInProgress2.flags = current & -65537 | 128, workInProgress2) : null;
+ case 19:
+ return pop(suspenseStackCursor), null;
+ case 4:
+ return popHostContainer(), null;
+ case 10:
+ return popProvider(workInProgress2.type), null;
+ case 22:
+ case 23:
+ return popSuspenseHandler(workInProgress2), popHiddenContext(), null !== current && pop(resumedCache), current = workInProgress2.flags, current & 65536 ? (workInProgress2.flags = current & -65537 | 128, workInProgress2) : null;
+ case 24:
+ return popProvider(CacheContext), null;
+ case 25:
+ return null;
+ default:
+ return null;
+ }
+ }
+ __name(unwindWork, "unwindWork");
+ function unwindInterruptedWork(current, interruptedWork) {
+ popTreeContext(interruptedWork);
+ switch (interruptedWork.tag) {
+ case 3:
+ popProvider(CacheContext);
+ popHostContainer();
+ break;
+ case 26:
+ case 27:
+ case 5:
+ popHostContext(interruptedWork);
+ break;
+ case 4:
+ popHostContainer();
+ break;
+ case 31:
+ null !== interruptedWork.memoizedState && popSuspenseHandler(interruptedWork);
+ break;
+ case 13:
+ popSuspenseHandler(interruptedWork);
+ break;
+ case 19:
+ pop(suspenseStackCursor);
+ break;
+ case 10:
+ popProvider(interruptedWork.type);
+ break;
+ case 22:
+ case 23:
+ popSuspenseHandler(interruptedWork);
+ popHiddenContext();
+ null !== current && pop(resumedCache);
+ break;
+ case 24:
+ popProvider(CacheContext);
+ }
+ }
+ __name(unwindInterruptedWork, "unwindInterruptedWork");
+ function commitHookEffectListMount(flags, finishedWork) {
+ try {
+ var updateQueue = finishedWork.updateQueue, lastEffect = null !== updateQueue ? updateQueue.lastEffect : null;
+ if (null !== lastEffect) {
+ var firstEffect = lastEffect.next;
+ updateQueue = firstEffect;
+ do {
+ if ((updateQueue.tag & flags) === flags) {
+ lastEffect = void 0;
+ var create3 = updateQueue.create, inst = updateQueue.inst;
+ lastEffect = create3();
+ inst.destroy = lastEffect;
+ }
+ updateQueue = updateQueue.next;
+ } while (updateQueue !== firstEffect);
+ }
+ } catch (error51) {
+ captureCommitPhaseError(finishedWork, finishedWork.return, error51);
+ }
+ }
+ __name(commitHookEffectListMount, "commitHookEffectListMount");
+ function commitHookEffectListUnmount(flags, finishedWork, nearestMountedAncestor$jscomp$0) {
+ try {
+ var updateQueue = finishedWork.updateQueue, lastEffect = null !== updateQueue ? updateQueue.lastEffect : null;
+ if (null !== lastEffect) {
+ var firstEffect = lastEffect.next;
+ updateQueue = firstEffect;
+ do {
+ if ((updateQueue.tag & flags) === flags) {
+ var inst = updateQueue.inst, destroy = inst.destroy;
+ if (void 0 !== destroy) {
+ inst.destroy = void 0;
+ lastEffect = finishedWork;
+ var nearestMountedAncestor = nearestMountedAncestor$jscomp$0, destroy_ = destroy;
+ try {
+ destroy_();
+ } catch (error51) {
+ captureCommitPhaseError(
+ lastEffect,
+ nearestMountedAncestor,
+ error51
+ );
+ }
+ }
+ }
+ updateQueue = updateQueue.next;
+ } while (updateQueue !== firstEffect);
+ }
+ } catch (error51) {
+ captureCommitPhaseError(finishedWork, finishedWork.return, error51);
+ }
+ }
+ __name(commitHookEffectListUnmount, "commitHookEffectListUnmount");
+ function commitClassCallbacks(finishedWork) {
+ var updateQueue = finishedWork.updateQueue;
+ if (null !== updateQueue) {
+ var instance = finishedWork.stateNode;
+ try {
+ commitCallbacks(updateQueue, instance);
+ } catch (error51) {
+ captureCommitPhaseError(finishedWork, finishedWork.return, error51);
+ }
+ }
+ }
+ __name(commitClassCallbacks, "commitClassCallbacks");
+ function safelyCallComponentWillUnmount(current, nearestMountedAncestor, instance) {
+ instance.props = resolveClassComponentProps(
+ current.type,
+ current.memoizedProps
+ );
+ instance.state = current.memoizedState;
+ try {
+ instance.componentWillUnmount();
+ } catch (error51) {
+ captureCommitPhaseError(current, nearestMountedAncestor, error51);
+ }
+ }
+ __name(safelyCallComponentWillUnmount, "safelyCallComponentWillUnmount");
+ function safelyAttachRef(current, nearestMountedAncestor) {
+ try {
+ var ref = current.ref;
+ if (null !== ref) {
+ switch (current.tag) {
+ case 26:
+ case 27:
+ case 5:
+ var instanceToUse = getPublicInstance(current.stateNode);
+ break;
+ case 30:
+ instanceToUse = current.stateNode;
+ break;
+ default:
+ instanceToUse = current.stateNode;
+ }
+ "function" === typeof ref ? current.refCleanup = ref(instanceToUse) : ref.current = instanceToUse;
+ }
+ } catch (error51) {
+ captureCommitPhaseError(current, nearestMountedAncestor, error51);
+ }
+ }
+ __name(safelyAttachRef, "safelyAttachRef");
+ function safelyDetachRef(current, nearestMountedAncestor) {
+ var ref = current.ref, refCleanup = current.refCleanup;
+ if (null !== ref)
+ if ("function" === typeof refCleanup)
+ try {
+ refCleanup();
+ } catch (error51) {
+ captureCommitPhaseError(current, nearestMountedAncestor, error51);
+ } finally {
+ current.refCleanup = null, current = current.alternate, null != current && (current.refCleanup = null);
+ }
+ else if ("function" === typeof ref)
+ try {
+ ref(null);
+ } catch (error$124) {
+ captureCommitPhaseError(current, nearestMountedAncestor, error$124);
+ }
+ else ref.current = null;
+ }
+ __name(safelyDetachRef, "safelyDetachRef");
+ function commitHostMount(finishedWork) {
+ var type2 = finishedWork.type, props = finishedWork.memoizedProps, instance = finishedWork.stateNode;
+ try {
+ commitMount(instance, type2, props, finishedWork);
+ } catch (error51) {
+ captureCommitPhaseError(finishedWork, finishedWork.return, error51);
+ }
+ }
+ __name(commitHostMount, "commitHostMount");
+ function commitHostUpdate(finishedWork, newProps, oldProps) {
+ try {
+ commitUpdate(
+ finishedWork.stateNode,
+ finishedWork.type,
+ oldProps,
+ newProps,
+ finishedWork
+ );
+ } catch (error51) {
+ captureCommitPhaseError(finishedWork, finishedWork.return, error51);
+ }
+ }
+ __name(commitHostUpdate, "commitHostUpdate");
+ function isHostParent(fiber) {
+ return 5 === fiber.tag || 3 === fiber.tag || (supportsResources ? 26 === fiber.tag : false) || (supportsSingletons ? 27 === fiber.tag && isSingletonScope(fiber.type) : false) || 4 === fiber.tag;
+ }
+ __name(isHostParent, "isHostParent");
+ function getHostSibling(fiber) {
+ a: for (; ; ) {
+ for (; null === fiber.sibling; ) {
+ if (null === fiber.return || isHostParent(fiber.return)) return null;
+ fiber = fiber.return;
+ }
+ fiber.sibling.return = fiber.return;
+ for (fiber = fiber.sibling; 5 !== fiber.tag && 6 !== fiber.tag && 18 !== fiber.tag; ) {
+ if (supportsSingletons && 27 === fiber.tag && isSingletonScope(fiber.type))
+ continue a;
+ if (fiber.flags & 2) continue a;
+ if (null === fiber.child || 4 === fiber.tag) continue a;
+ else fiber.child.return = fiber, fiber = fiber.child;
+ }
+ if (!(fiber.flags & 2)) return fiber.stateNode;
+ }
+ }
+ __name(getHostSibling, "getHostSibling");
+ function insertOrAppendPlacementNodeIntoContainer(node, before, parent) {
+ var tag = node.tag;
+ if (5 === tag || 6 === tag)
+ node = node.stateNode, before ? insertInContainerBefore(parent, node, before) : appendChildToContainer(parent, node);
+ else if (4 !== tag && (supportsSingletons && 27 === tag && isSingletonScope(node.type) && (parent = node.stateNode, before = null), node = node.child, null !== node))
+ for (insertOrAppendPlacementNodeIntoContainer(node, before, parent), node = node.sibling; null !== node; )
+ insertOrAppendPlacementNodeIntoContainer(node, before, parent), node = node.sibling;
+ }
+ __name(insertOrAppendPlacementNodeIntoContainer, "insertOrAppendPlacementNodeIntoContainer");
+ function insertOrAppendPlacementNode(node, before, parent) {
+ var tag = node.tag;
+ if (5 === tag || 6 === tag)
+ node = node.stateNode, before ? insertBefore(parent, node, before) : appendChild(parent, node);
+ else if (4 !== tag && (supportsSingletons && 27 === tag && isSingletonScope(node.type) && (parent = node.stateNode), node = node.child, null !== node))
+ for (insertOrAppendPlacementNode(node, before, parent), node = node.sibling; null !== node; )
+ insertOrAppendPlacementNode(node, before, parent), node = node.sibling;
+ }
+ __name(insertOrAppendPlacementNode, "insertOrAppendPlacementNode");
+ function commitHostPortalContainerChildren(portal, finishedWork, pendingChildren) {
+ portal = portal.containerInfo;
+ try {
+ replaceContainerChildren(portal, pendingChildren);
+ } catch (error51) {
+ captureCommitPhaseError(finishedWork, finishedWork.return, error51);
+ }
+ }
+ __name(commitHostPortalContainerChildren, "commitHostPortalContainerChildren");
+ function commitHostSingletonAcquisition(finishedWork) {
+ var singleton = finishedWork.stateNode, props = finishedWork.memoizedProps;
+ try {
+ acquireSingletonInstance(
+ finishedWork.type,
+ props,
+ singleton,
+ finishedWork
+ );
+ } catch (error51) {
+ captureCommitPhaseError(finishedWork, finishedWork.return, error51);
+ }
+ }
+ __name(commitHostSingletonAcquisition, "commitHostSingletonAcquisition");
+ function commitBeforeMutationEffects(root, firstChild) {
+ prepareForCommit(root.containerInfo);
+ for (nextEffect = firstChild; null !== nextEffect; )
+ if (root = nextEffect, firstChild = root.child, 0 !== (root.subtreeFlags & 1028) && null !== firstChild)
+ firstChild.return = root, nextEffect = firstChild;
+ else
+ for (; null !== nextEffect; ) {
+ root = nextEffect;
+ var current = root.alternate;
+ firstChild = root.flags;
+ switch (root.tag) {
+ case 0:
+ if (0 !== (firstChild & 4) && (firstChild = root.updateQueue, firstChild = null !== firstChild ? firstChild.events : null, null !== firstChild))
+ for (var ii = 0; ii < firstChild.length; ii++) {
+ var _eventPayloads$ii = firstChild[ii];
+ _eventPayloads$ii.ref.impl = _eventPayloads$ii.nextImpl;
+ }
+ break;
+ case 11:
+ case 15:
+ break;
+ case 1:
+ if (0 !== (firstChild & 1024) && null !== current) {
+ firstChild = void 0;
+ ii = root;
+ _eventPayloads$ii = current.memoizedProps;
+ current = current.memoizedState;
+ var instance = ii.stateNode;
+ try {
+ var resolvedPrevProps = resolveClassComponentProps(
+ ii.type,
+ _eventPayloads$ii
+ );
+ firstChild = instance.getSnapshotBeforeUpdate(
+ resolvedPrevProps,
+ current
+ );
+ instance.__reactInternalSnapshotBeforeUpdate = firstChild;
+ } catch (error51) {
+ captureCommitPhaseError(ii, ii.return, error51);
+ }
+ }
+ break;
+ case 3:
+ 0 !== (firstChild & 1024) && supportsMutation && clearContainer(root.stateNode.containerInfo);
+ break;
+ case 5:
+ case 26:
+ case 27:
+ case 6:
+ case 4:
+ case 17:
+ break;
+ default:
+ if (0 !== (firstChild & 1024))
+ throw Error(formatProdErrorMessage(163));
+ }
+ firstChild = root.sibling;
+ if (null !== firstChild) {
+ firstChild.return = root.return;
+ nextEffect = firstChild;
+ break;
+ }
+ nextEffect = root.return;
+ }
+ }
+ __name(commitBeforeMutationEffects, "commitBeforeMutationEffects");
+ function commitLayoutEffectOnFiber(finishedRoot, current, finishedWork) {
+ var flags = finishedWork.flags;
+ switch (finishedWork.tag) {
+ case 0:
+ case 11:
+ case 15:
+ recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
+ flags & 4 && commitHookEffectListMount(5, finishedWork);
+ break;
+ case 1:
+ recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
+ if (flags & 4)
+ if (finishedRoot = finishedWork.stateNode, null === current)
+ try {
+ finishedRoot.componentDidMount();
+ } catch (error51) {
+ captureCommitPhaseError(finishedWork, finishedWork.return, error51);
+ }
+ else {
+ var prevProps = resolveClassComponentProps(
+ finishedWork.type,
+ current.memoizedProps
+ );
+ current = current.memoizedState;
+ try {
+ finishedRoot.componentDidUpdate(
+ prevProps,
+ current,
+ finishedRoot.__reactInternalSnapshotBeforeUpdate
+ );
+ } catch (error$123) {
+ captureCommitPhaseError(
+ finishedWork,
+ finishedWork.return,
+ error$123
+ );
+ }
+ }
+ flags & 64 && commitClassCallbacks(finishedWork);
+ flags & 512 && safelyAttachRef(finishedWork, finishedWork.return);
+ break;
+ case 3:
+ recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
+ if (flags & 64 && (flags = finishedWork.updateQueue, null !== flags)) {
+ finishedRoot = null;
+ if (null !== finishedWork.child)
+ switch (finishedWork.child.tag) {
+ case 27:
+ case 5:
+ finishedRoot = getPublicInstance(finishedWork.child.stateNode);
+ break;
+ case 1:
+ finishedRoot = finishedWork.child.stateNode;
+ }
+ try {
+ commitCallbacks(flags, finishedRoot);
+ } catch (error51) {
+ captureCommitPhaseError(finishedWork, finishedWork.return, error51);
+ }
+ }
+ break;
+ case 27:
+ supportsSingletons && null === current && flags & 4 && commitHostSingletonAcquisition(finishedWork);
+ case 26:
+ case 5:
+ recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
+ if (null === current) {
+ if (flags & 4) commitHostMount(finishedWork);
+ else if (flags & 64) {
+ finishedRoot = finishedWork.type;
+ current = finishedWork.memoizedProps;
+ prevProps = finishedWork.stateNode;
+ try {
+ commitHydratedInstance(
+ prevProps,
+ finishedRoot,
+ current,
+ finishedWork
+ );
+ } catch (error51) {
+ captureCommitPhaseError(finishedWork, finishedWork.return, error51);
+ }
+ }
+ }
+ flags & 512 && safelyAttachRef(finishedWork, finishedWork.return);
+ break;
+ case 12:
+ recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
+ break;
+ case 31:
+ recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
+ flags & 4 && commitActivityHydrationCallbacks(finishedRoot, finishedWork);
+ break;
+ case 13:
+ recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
+ flags & 4 && commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
+ flags & 64 && (flags = finishedWork.memoizedState, null !== flags && (flags = flags.dehydrated, null !== flags && (finishedWork = retryDehydratedSuspenseBoundary.bind(
+ null,
+ finishedWork
+ ), registerSuspenseInstanceRetry(flags, finishedWork))));
+ break;
+ case 22:
+ flags = null !== finishedWork.memoizedState || offscreenSubtreeIsHidden;
+ if (!flags) {
+ current = null !== current && null !== current.memoizedState || offscreenSubtreeWasHidden;
+ prevProps = offscreenSubtreeIsHidden;
+ var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
+ offscreenSubtreeIsHidden = flags;
+ (offscreenSubtreeWasHidden = current) && !prevOffscreenSubtreeWasHidden ? recursivelyTraverseReappearLayoutEffects(
+ finishedRoot,
+ finishedWork,
+ 0 !== (finishedWork.subtreeFlags & 8772)
+ ) : recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
+ offscreenSubtreeIsHidden = prevProps;
+ offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
+ }
+ break;
+ case 30:
+ break;
+ default:
+ recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
+ }
+ }
+ __name(commitLayoutEffectOnFiber, "commitLayoutEffectOnFiber");
+ function detachFiberAfterEffects(fiber) {
+ var alternate = fiber.alternate;
+ null !== alternate && (fiber.alternate = null, detachFiberAfterEffects(alternate));
+ fiber.child = null;
+ fiber.deletions = null;
+ fiber.sibling = null;
+ 5 === fiber.tag && (alternate = fiber.stateNode, null !== alternate && detachDeletedInstance(alternate));
+ fiber.stateNode = null;
+ fiber.return = null;
+ fiber.dependencies = null;
+ fiber.memoizedProps = null;
+ fiber.memoizedState = null;
+ fiber.pendingProps = null;
+ fiber.stateNode = null;
+ fiber.updateQueue = null;
+ }
+ __name(detachFiberAfterEffects, "detachFiberAfterEffects");
+ function recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, parent) {
+ for (parent = parent.child; null !== parent; )
+ commitDeletionEffectsOnFiber(
+ finishedRoot,
+ nearestMountedAncestor,
+ parent
+ ), parent = parent.sibling;
+ }
+ __name(recursivelyTraverseDeletionEffects, "recursivelyTraverseDeletionEffects");
+ function commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, deletedFiber) {
+ if (injectedHook && "function" === typeof injectedHook.onCommitFiberUnmount)
+ try {
+ injectedHook.onCommitFiberUnmount(rendererID, deletedFiber);
+ } catch (err) {
+ }
+ switch (deletedFiber.tag) {
+ case 26:
+ if (supportsResources) {
+ offscreenSubtreeWasHidden || safelyDetachRef(deletedFiber, nearestMountedAncestor);
+ recursivelyTraverseDeletionEffects(
+ finishedRoot,
+ nearestMountedAncestor,
+ deletedFiber
+ );
+ deletedFiber.memoizedState ? releaseResource(deletedFiber.memoizedState) : deletedFiber.stateNode && unmountHoistable(deletedFiber.stateNode);
+ break;
+ }
+ case 27:
+ if (supportsSingletons) {
+ offscreenSubtreeWasHidden || safelyDetachRef(deletedFiber, nearestMountedAncestor);
+ var prevHostParent = hostParent, prevHostParentIsContainer = hostParentIsContainer;
+ isSingletonScope(deletedFiber.type) && (hostParent = deletedFiber.stateNode, hostParentIsContainer = false);
+ recursivelyTraverseDeletionEffects(
+ finishedRoot,
+ nearestMountedAncestor,
+ deletedFiber
+ );
+ releaseSingletonInstance(deletedFiber.stateNode);
+ hostParent = prevHostParent;
+ hostParentIsContainer = prevHostParentIsContainer;
+ break;
+ }
+ case 5:
+ offscreenSubtreeWasHidden || safelyDetachRef(deletedFiber, nearestMountedAncestor);
+ case 6:
+ if (supportsMutation) {
+ if (prevHostParent = hostParent, prevHostParentIsContainer = hostParentIsContainer, hostParent = null, recursivelyTraverseDeletionEffects(
+ finishedRoot,
+ nearestMountedAncestor,
+ deletedFiber
+ ), hostParent = prevHostParent, hostParentIsContainer = prevHostParentIsContainer, null !== hostParent)
+ if (hostParentIsContainer)
+ try {
+ removeChildFromContainer(hostParent, deletedFiber.stateNode);
+ } catch (error51) {
+ captureCommitPhaseError(
+ deletedFiber,
+ nearestMountedAncestor,
+ error51
+ );
+ }
+ else
+ try {
+ removeChild(hostParent, deletedFiber.stateNode);
+ } catch (error51) {
+ captureCommitPhaseError(
+ deletedFiber,
+ nearestMountedAncestor,
+ error51
+ );
+ }
+ } else
+ recursivelyTraverseDeletionEffects(
+ finishedRoot,
+ nearestMountedAncestor,
+ deletedFiber
+ );
+ break;
+ case 18:
+ supportsMutation && null !== hostParent && (hostParentIsContainer ? clearSuspenseBoundaryFromContainer(
+ hostParent,
+ deletedFiber.stateNode
+ ) : clearSuspenseBoundary(hostParent, deletedFiber.stateNode));
+ break;
+ case 4:
+ supportsMutation ? (prevHostParent = hostParent, prevHostParentIsContainer = hostParentIsContainer, hostParent = deletedFiber.stateNode.containerInfo, hostParentIsContainer = true, recursivelyTraverseDeletionEffects(
+ finishedRoot,
+ nearestMountedAncestor,
+ deletedFiber
+ ), hostParent = prevHostParent, hostParentIsContainer = prevHostParentIsContainer) : (supportsPersistence && commitHostPortalContainerChildren(
+ deletedFiber.stateNode,
+ deletedFiber,
+ createContainerChildSet()
+ ), recursivelyTraverseDeletionEffects(
+ finishedRoot,
+ nearestMountedAncestor,
+ deletedFiber
+ ));
+ break;
+ case 0:
+ case 11:
+ case 14:
+ case 15:
+ commitHookEffectListUnmount(2, deletedFiber, nearestMountedAncestor);
+ offscreenSubtreeWasHidden || commitHookEffectListUnmount(4, deletedFiber, nearestMountedAncestor);
+ recursivelyTraverseDeletionEffects(
+ finishedRoot,
+ nearestMountedAncestor,
+ deletedFiber
+ );
+ break;
+ case 1:
+ offscreenSubtreeWasHidden || (safelyDetachRef(deletedFiber, nearestMountedAncestor), prevHostParent = deletedFiber.stateNode, "function" === typeof prevHostParent.componentWillUnmount && safelyCallComponentWillUnmount(
+ deletedFiber,
+ nearestMountedAncestor,
+ prevHostParent
+ ));
+ recursivelyTraverseDeletionEffects(
+ finishedRoot,
+ nearestMountedAncestor,
+ deletedFiber
+ );
+ break;
+ case 21:
+ recursivelyTraverseDeletionEffects(
+ finishedRoot,
+ nearestMountedAncestor,
+ deletedFiber
+ );
+ break;
+ case 22:
+ offscreenSubtreeWasHidden = (prevHostParent = offscreenSubtreeWasHidden) || null !== deletedFiber.memoizedState;
+ recursivelyTraverseDeletionEffects(
+ finishedRoot,
+ nearestMountedAncestor,
+ deletedFiber
+ );
+ offscreenSubtreeWasHidden = prevHostParent;
+ break;
+ default:
+ recursivelyTraverseDeletionEffects(
+ finishedRoot,
+ nearestMountedAncestor,
+ deletedFiber
+ );
+ }
+ }
+ __name(commitDeletionEffectsOnFiber, "commitDeletionEffectsOnFiber");
+ function commitActivityHydrationCallbacks(finishedRoot, finishedWork) {
+ if (supportsHydration && null === finishedWork.memoizedState && (finishedRoot = finishedWork.alternate, null !== finishedRoot && (finishedRoot = finishedRoot.memoizedState, null !== finishedRoot))) {
+ finishedRoot = finishedRoot.dehydrated;
+ try {
+ commitHydratedActivityInstance(finishedRoot);
+ } catch (error51) {
+ captureCommitPhaseError(finishedWork, finishedWork.return, error51);
+ }
+ }
+ }
+ __name(commitActivityHydrationCallbacks, "commitActivityHydrationCallbacks");
+ function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) {
+ if (supportsHydration && null === finishedWork.memoizedState && (finishedRoot = finishedWork.alternate, null !== finishedRoot && (finishedRoot = finishedRoot.memoizedState, null !== finishedRoot && (finishedRoot = finishedRoot.dehydrated, null !== finishedRoot))))
+ try {
+ commitHydratedSuspenseInstance(finishedRoot);
+ } catch (error51) {
+ captureCommitPhaseError(finishedWork, finishedWork.return, error51);
+ }
+ }
+ __name(commitSuspenseHydrationCallbacks, "commitSuspenseHydrationCallbacks");
+ function getRetryCache(finishedWork) {
+ switch (finishedWork.tag) {
+ case 31:
+ case 13:
+ case 19:
+ var retryCache = finishedWork.stateNode;
+ null === retryCache && (retryCache = finishedWork.stateNode = new PossiblyWeakSet());
+ return retryCache;
+ case 22:
+ return finishedWork = finishedWork.stateNode, retryCache = finishedWork._retryCache, null === retryCache && (retryCache = finishedWork._retryCache = new PossiblyWeakSet()), retryCache;
+ default:
+ throw Error(formatProdErrorMessage(435, finishedWork.tag));
+ }
+ }
+ __name(getRetryCache, "getRetryCache");
+ function attachSuspenseRetryListeners(finishedWork, wakeables) {
+ var retryCache = getRetryCache(finishedWork);
+ wakeables.forEach(function(wakeable) {
+ if (!retryCache.has(wakeable)) {
+ retryCache.add(wakeable);
+ var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable);
+ wakeable.then(retry, retry);
+ }
+ });
+ }
+ __name(attachSuspenseRetryListeners, "attachSuspenseRetryListeners");
+ function recursivelyTraverseMutationEffects(root$jscomp$0, parentFiber) {
+ var deletions = parentFiber.deletions;
+ if (null !== deletions)
+ for (var i = 0; i < deletions.length; i++) {
+ var childToDelete = deletions[i], root = root$jscomp$0, returnFiber = parentFiber;
+ if (supportsMutation) {
+ var parent = returnFiber;
+ a: for (; null !== parent; ) {
+ switch (parent.tag) {
+ case 27:
+ if (supportsSingletons) {
+ if (isSingletonScope(parent.type)) {
+ hostParent = parent.stateNode;
+ hostParentIsContainer = false;
+ break a;
+ }
+ break;
+ }
+ case 5:
+ hostParent = parent.stateNode;
+ hostParentIsContainer = false;
+ break a;
+ case 3:
+ case 4:
+ hostParent = parent.stateNode.containerInfo;
+ hostParentIsContainer = true;
+ break a;
+ }
+ parent = parent.return;
+ }
+ if (null === hostParent) throw Error(formatProdErrorMessage(160));
+ commitDeletionEffectsOnFiber(root, returnFiber, childToDelete);
+ hostParent = null;
+ hostParentIsContainer = false;
+ } else commitDeletionEffectsOnFiber(root, returnFiber, childToDelete);
+ root = childToDelete.alternate;
+ null !== root && (root.return = null);
+ childToDelete.return = null;
+ }
+ if (parentFiber.subtreeFlags & 13886)
+ for (parentFiber = parentFiber.child; null !== parentFiber; )
+ commitMutationEffectsOnFiber(parentFiber, root$jscomp$0), parentFiber = parentFiber.sibling;
+ }
+ __name(recursivelyTraverseMutationEffects, "recursivelyTraverseMutationEffects");
+ function commitMutationEffectsOnFiber(finishedWork, root) {
+ var current = finishedWork.alternate, flags = finishedWork.flags;
+ switch (finishedWork.tag) {
+ case 0:
+ case 11:
+ case 14:
+ case 15:
+ recursivelyTraverseMutationEffects(root, finishedWork);
+ commitReconciliationEffects(finishedWork);
+ flags & 4 && (commitHookEffectListUnmount(3, finishedWork, finishedWork.return), commitHookEffectListMount(3, finishedWork), commitHookEffectListUnmount(5, finishedWork, finishedWork.return));
+ break;
+ case 1:
+ recursivelyTraverseMutationEffects(root, finishedWork);
+ commitReconciliationEffects(finishedWork);
+ flags & 512 && (offscreenSubtreeWasHidden || null === current || safelyDetachRef(current, current.return));
+ flags & 64 && offscreenSubtreeIsHidden && (finishedWork = finishedWork.updateQueue, null !== finishedWork && (flags = finishedWork.callbacks, null !== flags && (current = finishedWork.shared.hiddenCallbacks, finishedWork.shared.hiddenCallbacks = null === current ? flags : current.concat(flags))));
+ break;
+ case 26:
+ if (supportsResources) {
+ var hoistableRoot = currentHoistableRoot;
+ recursivelyTraverseMutationEffects(root, finishedWork);
+ commitReconciliationEffects(finishedWork);
+ flags & 512 && (offscreenSubtreeWasHidden || null === current || safelyDetachRef(current, current.return));
+ if (flags & 4) {
+ flags = null !== current ? current.memoizedState : null;
+ var newResource = finishedWork.memoizedState;
+ null === current ? null === newResource ? null === finishedWork.stateNode ? finishedWork.stateNode = hydrateHoistable(
+ hoistableRoot,
+ finishedWork.type,
+ finishedWork.memoizedProps,
+ finishedWork
+ ) : mountHoistable(
+ hoistableRoot,
+ finishedWork.type,
+ finishedWork.stateNode
+ ) : finishedWork.stateNode = acquireResource(
+ hoistableRoot,
+ newResource,
+ finishedWork.memoizedProps
+ ) : flags !== newResource ? (null === flags ? null !== current.stateNode && unmountHoistable(current.stateNode) : releaseResource(flags), null === newResource ? mountHoistable(
+ hoistableRoot,
+ finishedWork.type,
+ finishedWork.stateNode
+ ) : acquireResource(
+ hoistableRoot,
+ newResource,
+ finishedWork.memoizedProps
+ )) : null === newResource && null !== finishedWork.stateNode && commitHostUpdate(
+ finishedWork,
+ finishedWork.memoizedProps,
+ current.memoizedProps
+ );
+ }
+ break;
+ }
+ case 27:
+ if (supportsSingletons) {
+ recursivelyTraverseMutationEffects(root, finishedWork);
+ commitReconciliationEffects(finishedWork);
+ flags & 512 && (offscreenSubtreeWasHidden || null === current || safelyDetachRef(current, current.return));
+ null !== current && flags & 4 && commitHostUpdate(
+ finishedWork,
+ finishedWork.memoizedProps,
+ current.memoizedProps
+ );
+ break;
+ }
+ case 5:
+ recursivelyTraverseMutationEffects(root, finishedWork);
+ commitReconciliationEffects(finishedWork);
+ flags & 512 && (offscreenSubtreeWasHidden || null === current || safelyDetachRef(current, current.return));
+ if (supportsMutation) {
+ if (finishedWork.flags & 32) {
+ hoistableRoot = finishedWork.stateNode;
+ try {
+ resetTextContent(hoistableRoot);
+ } catch (error51) {
+ captureCommitPhaseError(finishedWork, finishedWork.return, error51);
+ }
+ }
+ flags & 4 && null != finishedWork.stateNode && (hoistableRoot = finishedWork.memoizedProps, commitHostUpdate(
+ finishedWork,
+ hoistableRoot,
+ null !== current ? current.memoizedProps : hoistableRoot
+ ));
+ flags & 1024 && (needsFormReset = true);
+ } else
+ supportsPersistence && null !== finishedWork.alternate && (finishedWork.alternate.stateNode = finishedWork.stateNode);
+ break;
+ case 6:
+ recursivelyTraverseMutationEffects(root, finishedWork);
+ commitReconciliationEffects(finishedWork);
+ if (flags & 4 && supportsMutation) {
+ if (null === finishedWork.stateNode)
+ throw Error(formatProdErrorMessage(162));
+ flags = finishedWork.memoizedProps;
+ current = null !== current ? current.memoizedProps : flags;
+ hoistableRoot = finishedWork.stateNode;
+ try {
+ commitTextUpdate(hoistableRoot, current, flags);
+ } catch (error51) {
+ captureCommitPhaseError(finishedWork, finishedWork.return, error51);
+ }
+ }
+ break;
+ case 3:
+ supportsResources ? (prepareToCommitHoistables(), hoistableRoot = currentHoistableRoot, currentHoistableRoot = getHoistableRoot(root.containerInfo), recursivelyTraverseMutationEffects(root, finishedWork), currentHoistableRoot = hoistableRoot) : recursivelyTraverseMutationEffects(root, finishedWork);
+ commitReconciliationEffects(finishedWork);
+ if (flags & 4) {
+ if (supportsMutation && supportsHydration && null !== current && current.memoizedState.isDehydrated)
+ try {
+ commitHydratedContainer(root.containerInfo);
+ } catch (error51) {
+ captureCommitPhaseError(finishedWork, finishedWork.return, error51);
+ }
+ if (supportsPersistence) {
+ flags = root.containerInfo;
+ current = root.pendingChildren;
+ try {
+ replaceContainerChildren(flags, current);
+ } catch (error51) {
+ captureCommitPhaseError(finishedWork, finishedWork.return, error51);
+ }
+ }
+ }
+ needsFormReset && (needsFormReset = false, recursivelyResetForms(finishedWork));
+ break;
+ case 4:
+ supportsResources ? (current = currentHoistableRoot, currentHoistableRoot = getHoistableRoot(
+ finishedWork.stateNode.containerInfo
+ ), recursivelyTraverseMutationEffects(root, finishedWork), commitReconciliationEffects(finishedWork), currentHoistableRoot = current) : (recursivelyTraverseMutationEffects(root, finishedWork), commitReconciliationEffects(finishedWork));
+ flags & 4 && supportsPersistence && commitHostPortalContainerChildren(
+ finishedWork.stateNode,
+ finishedWork,
+ finishedWork.stateNode.pendingChildren
+ );
+ break;
+ case 12:
+ recursivelyTraverseMutationEffects(root, finishedWork);
+ commitReconciliationEffects(finishedWork);
+ break;
+ case 31:
+ recursivelyTraverseMutationEffects(root, finishedWork);
+ commitReconciliationEffects(finishedWork);
+ flags & 4 && (flags = finishedWork.updateQueue, null !== flags && (finishedWork.updateQueue = null, attachSuspenseRetryListeners(finishedWork, flags)));
+ break;
+ case 13:
+ recursivelyTraverseMutationEffects(root, finishedWork);
+ commitReconciliationEffects(finishedWork);
+ finishedWork.child.flags & 8192 && null !== finishedWork.memoizedState !== (null !== current && null !== current.memoizedState) && (globalMostRecentFallbackTime = now());
+ flags & 4 && (flags = finishedWork.updateQueue, null !== flags && (finishedWork.updateQueue = null, attachSuspenseRetryListeners(finishedWork, flags)));
+ break;
+ case 22:
+ hoistableRoot = null !== finishedWork.memoizedState;
+ var wasHidden = null !== current && null !== current.memoizedState, prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden, prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
+ offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden || hoistableRoot;
+ offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || wasHidden;
+ recursivelyTraverseMutationEffects(root, finishedWork);
+ offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
+ offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden;
+ commitReconciliationEffects(finishedWork);
+ if (flags & 8192 && (root = finishedWork.stateNode, root._visibility = hoistableRoot ? root._visibility & -2 : root._visibility | 1, hoistableRoot && (null === current || wasHidden || offscreenSubtreeIsHidden || offscreenSubtreeWasHidden || recursivelyTraverseDisappearLayoutEffects(finishedWork)), supportsMutation)) {
+ a: if (current = null, supportsMutation)
+ for (root = finishedWork; ; ) {
+ if (5 === root.tag || supportsResources && 26 === root.tag) {
+ if (null === current) {
+ wasHidden = current = root;
+ try {
+ newResource = wasHidden.stateNode, hoistableRoot ? hideInstance(newResource) : unhideInstance(
+ wasHidden.stateNode,
+ wasHidden.memoizedProps
+ );
+ } catch (error51) {
+ captureCommitPhaseError(wasHidden, wasHidden.return, error51);
+ }
+ }
+ } else if (6 === root.tag) {
+ if (null === current) {
+ wasHidden = root;
+ try {
+ var instance = wasHidden.stateNode;
+ hoistableRoot ? hideTextInstance(instance) : unhideTextInstance(instance, wasHidden.memoizedProps);
+ } catch (error51) {
+ captureCommitPhaseError(wasHidden, wasHidden.return, error51);
+ }
+ }
+ } else if (18 === root.tag) {
+ if (null === current) {
+ wasHidden = root;
+ try {
+ var instance$jscomp$0 = wasHidden.stateNode;
+ hoistableRoot ? hideDehydratedBoundary(instance$jscomp$0) : unhideDehydratedBoundary(wasHidden.stateNode);
+ } catch (error51) {
+ captureCommitPhaseError(wasHidden, wasHidden.return, error51);
+ }
+ }
+ } else if ((22 !== root.tag && 23 !== root.tag || null === root.memoizedState || root === finishedWork) && null !== root.child) {
+ root.child.return = root;
+ root = root.child;
+ continue;
+ }
+ if (root === finishedWork) break a;
+ for (; null === root.sibling; ) {
+ if (null === root.return || root.return === finishedWork)
+ break a;
+ current === root && (current = null);
+ root = root.return;
+ }
+ current === root && (current = null);
+ root.sibling.return = root.return;
+ root = root.sibling;
+ }
+ }
+ flags & 4 && (flags = finishedWork.updateQueue, null !== flags && (current = flags.retryQueue, null !== current && (flags.retryQueue = null, attachSuspenseRetryListeners(finishedWork, current))));
+ break;
+ case 19:
+ recursivelyTraverseMutationEffects(root, finishedWork);
+ commitReconciliationEffects(finishedWork);
+ flags & 4 && (flags = finishedWork.updateQueue, null !== flags && (finishedWork.updateQueue = null, attachSuspenseRetryListeners(finishedWork, flags)));
+ break;
+ case 30:
+ break;
+ case 21:
+ break;
+ default:
+ recursivelyTraverseMutationEffects(root, finishedWork), commitReconciliationEffects(finishedWork);
+ }
+ }
+ __name(commitMutationEffectsOnFiber, "commitMutationEffectsOnFiber");
+ function commitReconciliationEffects(finishedWork) {
+ var flags = finishedWork.flags;
+ if (flags & 2) {
+ try {
+ for (var hostParentFiber, parentFiber = finishedWork.return; null !== parentFiber; ) {
+ if (isHostParent(parentFiber)) {
+ hostParentFiber = parentFiber;
+ break;
+ }
+ parentFiber = parentFiber.return;
+ }
+ if (supportsMutation) {
+ if (null == hostParentFiber) throw Error(formatProdErrorMessage(160));
+ switch (hostParentFiber.tag) {
+ case 27:
+ if (supportsSingletons) {
+ var parent = hostParentFiber.stateNode, before = getHostSibling(finishedWork);
+ insertOrAppendPlacementNode(finishedWork, before, parent);
+ break;
+ }
+ case 5:
+ var parent$125 = hostParentFiber.stateNode;
+ hostParentFiber.flags & 32 && (resetTextContent(parent$125), hostParentFiber.flags &= -33);
+ var before$126 = getHostSibling(finishedWork);
+ insertOrAppendPlacementNode(finishedWork, before$126, parent$125);
+ break;
+ case 3:
+ case 4:
+ var parent$127 = hostParentFiber.stateNode.containerInfo, before$128 = getHostSibling(finishedWork);
+ insertOrAppendPlacementNodeIntoContainer(
+ finishedWork,
+ before$128,
+ parent$127
+ );
+ break;
+ default:
+ throw Error(formatProdErrorMessage(161));
+ }
+ }
+ } catch (error51) {
+ captureCommitPhaseError(finishedWork, finishedWork.return, error51);
+ }
+ finishedWork.flags &= -3;
+ }
+ flags & 4096 && (finishedWork.flags &= -4097);
+ }
+ __name(commitReconciliationEffects, "commitReconciliationEffects");
+ function recursivelyResetForms(parentFiber) {
+ if (parentFiber.subtreeFlags & 1024)
+ for (parentFiber = parentFiber.child; null !== parentFiber; ) {
+ var fiber = parentFiber;
+ recursivelyResetForms(fiber);
+ 5 === fiber.tag && fiber.flags & 1024 && resetFormInstance(fiber.stateNode);
+ parentFiber = parentFiber.sibling;
+ }
+ }
+ __name(recursivelyResetForms, "recursivelyResetForms");
+ function recursivelyTraverseLayoutEffects(root, parentFiber) {
+ if (parentFiber.subtreeFlags & 8772)
+ for (parentFiber = parentFiber.child; null !== parentFiber; )
+ commitLayoutEffectOnFiber(root, parentFiber.alternate, parentFiber), parentFiber = parentFiber.sibling;
+ }
+ __name(recursivelyTraverseLayoutEffects, "recursivelyTraverseLayoutEffects");
+ function recursivelyTraverseDisappearLayoutEffects(parentFiber) {
+ for (parentFiber = parentFiber.child; null !== parentFiber; ) {
+ var finishedWork = parentFiber;
+ switch (finishedWork.tag) {
+ case 0:
+ case 11:
+ case 14:
+ case 15:
+ commitHookEffectListUnmount(4, finishedWork, finishedWork.return);
+ recursivelyTraverseDisappearLayoutEffects(finishedWork);
+ break;
+ case 1:
+ safelyDetachRef(finishedWork, finishedWork.return);
+ var instance = finishedWork.stateNode;
+ "function" === typeof instance.componentWillUnmount && safelyCallComponentWillUnmount(
+ finishedWork,
+ finishedWork.return,
+ instance
+ );
+ recursivelyTraverseDisappearLayoutEffects(finishedWork);
+ break;
+ case 27:
+ supportsSingletons && releaseSingletonInstance(finishedWork.stateNode);
+ case 26:
+ case 5:
+ safelyDetachRef(finishedWork, finishedWork.return);
+ recursivelyTraverseDisappearLayoutEffects(finishedWork);
+ break;
+ case 22:
+ null === finishedWork.memoizedState && recursivelyTraverseDisappearLayoutEffects(finishedWork);
+ break;
+ case 30:
+ recursivelyTraverseDisappearLayoutEffects(finishedWork);
+ break;
+ default:
+ recursivelyTraverseDisappearLayoutEffects(finishedWork);
+ }
+ parentFiber = parentFiber.sibling;
+ }
+ }
+ __name(recursivelyTraverseDisappearLayoutEffects, "recursivelyTraverseDisappearLayoutEffects");
+ function recursivelyTraverseReappearLayoutEffects(finishedRoot$jscomp$0, parentFiber, includeWorkInProgressEffects) {
+ includeWorkInProgressEffects = includeWorkInProgressEffects && 0 !== (parentFiber.subtreeFlags & 8772);
+ for (parentFiber = parentFiber.child; null !== parentFiber; ) {
+ var current = parentFiber.alternate, finishedRoot = finishedRoot$jscomp$0, finishedWork = parentFiber, flags = finishedWork.flags;
+ switch (finishedWork.tag) {
+ case 0:
+ case 11:
+ case 15:
+ recursivelyTraverseReappearLayoutEffects(
+ finishedRoot,
+ finishedWork,
+ includeWorkInProgressEffects
+ );
+ commitHookEffectListMount(4, finishedWork);
+ break;
+ case 1:
+ recursivelyTraverseReappearLayoutEffects(
+ finishedRoot,
+ finishedWork,
+ includeWorkInProgressEffects
+ );
+ current = finishedWork;
+ finishedRoot = current.stateNode;
+ if ("function" === typeof finishedRoot.componentDidMount)
+ try {
+ finishedRoot.componentDidMount();
+ } catch (error51) {
+ captureCommitPhaseError(current, current.return, error51);
+ }
+ current = finishedWork;
+ finishedRoot = current.updateQueue;
+ if (null !== finishedRoot) {
+ var instance = current.stateNode;
+ try {
+ var hiddenCallbacks = finishedRoot.shared.hiddenCallbacks;
+ if (null !== hiddenCallbacks)
+ for (finishedRoot.shared.hiddenCallbacks = null, finishedRoot = 0; finishedRoot < hiddenCallbacks.length; finishedRoot++)
+ callCallback(hiddenCallbacks[finishedRoot], instance);
+ } catch (error51) {
+ captureCommitPhaseError(current, current.return, error51);
+ }
+ }
+ includeWorkInProgressEffects && flags & 64 && commitClassCallbacks(finishedWork);
+ safelyAttachRef(finishedWork, finishedWork.return);
+ break;
+ case 27:
+ supportsSingletons && commitHostSingletonAcquisition(finishedWork);
+ case 26:
+ case 5:
+ recursivelyTraverseReappearLayoutEffects(
+ finishedRoot,
+ finishedWork,
+ includeWorkInProgressEffects
+ );
+ includeWorkInProgressEffects && null === current && flags & 4 && commitHostMount(finishedWork);
+ safelyAttachRef(finishedWork, finishedWork.return);
+ break;
+ case 12:
+ recursivelyTraverseReappearLayoutEffects(
+ finishedRoot,
+ finishedWork,
+ includeWorkInProgressEffects
+ );
+ break;
+ case 31:
+ recursivelyTraverseReappearLayoutEffects(
+ finishedRoot,
+ finishedWork,
+ includeWorkInProgressEffects
+ );
+ includeWorkInProgressEffects && flags & 4 && commitActivityHydrationCallbacks(finishedRoot, finishedWork);
+ break;
+ case 13:
+ recursivelyTraverseReappearLayoutEffects(
+ finishedRoot,
+ finishedWork,
+ includeWorkInProgressEffects
+ );
+ includeWorkInProgressEffects && flags & 4 && commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
+ break;
+ case 22:
+ null === finishedWork.memoizedState && recursivelyTraverseReappearLayoutEffects(
+ finishedRoot,
+ finishedWork,
+ includeWorkInProgressEffects
+ );
+ safelyAttachRef(finishedWork, finishedWork.return);
+ break;
+ case 30:
+ break;
+ default:
+ recursivelyTraverseReappearLayoutEffects(
+ finishedRoot,
+ finishedWork,
+ includeWorkInProgressEffects
+ );
+ }
+ parentFiber = parentFiber.sibling;
+ }
+ }
+ __name(recursivelyTraverseReappearLayoutEffects, "recursivelyTraverseReappearLayoutEffects");
+ function commitOffscreenPassiveMountEffects(current, finishedWork) {
+ var previousCache = null;
+ null !== current && null !== current.memoizedState && null !== current.memoizedState.cachePool && (previousCache = current.memoizedState.cachePool.pool);
+ current = null;
+ null !== finishedWork.memoizedState && null !== finishedWork.memoizedState.cachePool && (current = finishedWork.memoizedState.cachePool.pool);
+ current !== previousCache && (null != current && current.refCount++, null != previousCache && releaseCache(previousCache));
+ }
+ __name(commitOffscreenPassiveMountEffects, "commitOffscreenPassiveMountEffects");
+ function commitCachePassiveMountEffect(current, finishedWork) {
+ current = null;
+ null !== finishedWork.alternate && (current = finishedWork.alternate.memoizedState.cache);
+ finishedWork = finishedWork.memoizedState.cache;
+ finishedWork !== current && (finishedWork.refCount++, null != current && releaseCache(current));
+ }
+ __name(commitCachePassiveMountEffect, "commitCachePassiveMountEffect");
+ function recursivelyTraversePassiveMountEffects(root, parentFiber, committedLanes, committedTransitions) {
+ if (parentFiber.subtreeFlags & 10256)
+ for (parentFiber = parentFiber.child; null !== parentFiber; )
+ commitPassiveMountOnFiber(
+ root,
+ parentFiber,
+ committedLanes,
+ committedTransitions
+ ), parentFiber = parentFiber.sibling;
+ }
+ __name(recursivelyTraversePassiveMountEffects, "recursivelyTraversePassiveMountEffects");
+ function commitPassiveMountOnFiber(finishedRoot, finishedWork, committedLanes, committedTransitions) {
+ var flags = finishedWork.flags;
+ switch (finishedWork.tag) {
+ case 0:
+ case 11:
+ case 15:
+ recursivelyTraversePassiveMountEffects(
+ finishedRoot,
+ finishedWork,
+ committedLanes,
+ committedTransitions
+ );
+ flags & 2048 && commitHookEffectListMount(9, finishedWork);
+ break;
+ case 1:
+ recursivelyTraversePassiveMountEffects(
+ finishedRoot,
+ finishedWork,
+ committedLanes,
+ committedTransitions
+ );
+ break;
+ case 3:
+ recursivelyTraversePassiveMountEffects(
+ finishedRoot,
+ finishedWork,
+ committedLanes,
+ committedTransitions
+ );
+ flags & 2048 && (finishedRoot = null, null !== finishedWork.alternate && (finishedRoot = finishedWork.alternate.memoizedState.cache), finishedWork = finishedWork.memoizedState.cache, finishedWork !== finishedRoot && (finishedWork.refCount++, null != finishedRoot && releaseCache(finishedRoot)));
+ break;
+ case 12:
+ if (flags & 2048) {
+ recursivelyTraversePassiveMountEffects(
+ finishedRoot,
+ finishedWork,
+ committedLanes,
+ committedTransitions
+ );
+ finishedRoot = finishedWork.stateNode;
+ try {
+ var _finishedWork$memoize2 = finishedWork.memoizedProps, id = _finishedWork$memoize2.id, onPostCommit = _finishedWork$memoize2.onPostCommit;
+ "function" === typeof onPostCommit && onPostCommit(
+ id,
+ null === finishedWork.alternate ? "mount" : "update",
+ finishedRoot.passiveEffectDuration,
+ -0
+ );
+ } catch (error51) {
+ captureCommitPhaseError(finishedWork, finishedWork.return, error51);
+ }
+ } else
+ recursivelyTraversePassiveMountEffects(
+ finishedRoot,
+ finishedWork,
+ committedLanes,
+ committedTransitions
+ );
+ break;
+ case 31:
+ recursivelyTraversePassiveMountEffects(
+ finishedRoot,
+ finishedWork,
+ committedLanes,
+ committedTransitions
+ );
+ break;
+ case 13:
+ recursivelyTraversePassiveMountEffects(
+ finishedRoot,
+ finishedWork,
+ committedLanes,
+ committedTransitions
+ );
+ break;
+ case 23:
+ break;
+ case 22:
+ _finishedWork$memoize2 = finishedWork.stateNode;
+ id = finishedWork.alternate;
+ null !== finishedWork.memoizedState ? _finishedWork$memoize2._visibility & 2 ? recursivelyTraversePassiveMountEffects(
+ finishedRoot,
+ finishedWork,
+ committedLanes,
+ committedTransitions
+ ) : recursivelyTraverseAtomicPassiveEffects(
+ finishedRoot,
+ finishedWork
+ ) : _finishedWork$memoize2._visibility & 2 ? recursivelyTraversePassiveMountEffects(
+ finishedRoot,
+ finishedWork,
+ committedLanes,
+ committedTransitions
+ ) : (_finishedWork$memoize2._visibility |= 2, recursivelyTraverseReconnectPassiveEffects(
+ finishedRoot,
+ finishedWork,
+ committedLanes,
+ committedTransitions,
+ 0 !== (finishedWork.subtreeFlags & 10256) || false
+ ));
+ flags & 2048 && commitOffscreenPassiveMountEffects(id, finishedWork);
+ break;
+ case 24:
+ recursivelyTraversePassiveMountEffects(
+ finishedRoot,
+ finishedWork,
+ committedLanes,
+ committedTransitions
+ );
+ flags & 2048 && commitCachePassiveMountEffect(finishedWork.alternate, finishedWork);
+ break;
+ default:
+ recursivelyTraversePassiveMountEffects(
+ finishedRoot,
+ finishedWork,
+ committedLanes,
+ committedTransitions
+ );
+ }
+ }
+ __name(commitPassiveMountOnFiber, "commitPassiveMountOnFiber");
+ function recursivelyTraverseReconnectPassiveEffects(finishedRoot$jscomp$0, parentFiber, committedLanes$jscomp$0, committedTransitions$jscomp$0, includeWorkInProgressEffects) {
+ includeWorkInProgressEffects = includeWorkInProgressEffects && (0 !== (parentFiber.subtreeFlags & 10256) || false);
+ for (parentFiber = parentFiber.child; null !== parentFiber; ) {
+ var finishedRoot = finishedRoot$jscomp$0, finishedWork = parentFiber, committedLanes = committedLanes$jscomp$0, committedTransitions = committedTransitions$jscomp$0, flags = finishedWork.flags;
+ switch (finishedWork.tag) {
+ case 0:
+ case 11:
+ case 15:
+ recursivelyTraverseReconnectPassiveEffects(
+ finishedRoot,
+ finishedWork,
+ committedLanes,
+ committedTransitions,
+ includeWorkInProgressEffects
+ );
+ commitHookEffectListMount(8, finishedWork);
+ break;
+ case 23:
+ break;
+ case 22:
+ var instance = finishedWork.stateNode;
+ null !== finishedWork.memoizedState ? instance._visibility & 2 ? recursivelyTraverseReconnectPassiveEffects(
+ finishedRoot,
+ finishedWork,
+ committedLanes,
+ committedTransitions,
+ includeWorkInProgressEffects
+ ) : recursivelyTraverseAtomicPassiveEffects(
+ finishedRoot,
+ finishedWork
+ ) : (instance._visibility |= 2, recursivelyTraverseReconnectPassiveEffects(
+ finishedRoot,
+ finishedWork,
+ committedLanes,
+ committedTransitions,
+ includeWorkInProgressEffects
+ ));
+ includeWorkInProgressEffects && flags & 2048 && commitOffscreenPassiveMountEffects(
+ finishedWork.alternate,
+ finishedWork
+ );
+ break;
+ case 24:
+ recursivelyTraverseReconnectPassiveEffects(
+ finishedRoot,
+ finishedWork,
+ committedLanes,
+ committedTransitions,
+ includeWorkInProgressEffects
+ );
+ includeWorkInProgressEffects && flags & 2048 && commitCachePassiveMountEffect(finishedWork.alternate, finishedWork);
+ break;
+ default:
+ recursivelyTraverseReconnectPassiveEffects(
+ finishedRoot,
+ finishedWork,
+ committedLanes,
+ committedTransitions,
+ includeWorkInProgressEffects
+ );
+ }
+ parentFiber = parentFiber.sibling;
+ }
+ }
+ __name(recursivelyTraverseReconnectPassiveEffects, "recursivelyTraverseReconnectPassiveEffects");
+ function recursivelyTraverseAtomicPassiveEffects(finishedRoot$jscomp$0, parentFiber) {
+ if (parentFiber.subtreeFlags & 10256)
+ for (parentFiber = parentFiber.child; null !== parentFiber; ) {
+ var finishedRoot = finishedRoot$jscomp$0, finishedWork = parentFiber, flags = finishedWork.flags;
+ switch (finishedWork.tag) {
+ case 22:
+ recursivelyTraverseAtomicPassiveEffects(finishedRoot, finishedWork);
+ flags & 2048 && commitOffscreenPassiveMountEffects(
+ finishedWork.alternate,
+ finishedWork
+ );
+ break;
+ case 24:
+ recursivelyTraverseAtomicPassiveEffects(finishedRoot, finishedWork);
+ flags & 2048 && commitCachePassiveMountEffect(
+ finishedWork.alternate,
+ finishedWork
+ );
+ break;
+ default:
+ recursivelyTraverseAtomicPassiveEffects(finishedRoot, finishedWork);
+ }
+ parentFiber = parentFiber.sibling;
+ }
+ }
+ __name(recursivelyTraverseAtomicPassiveEffects, "recursivelyTraverseAtomicPassiveEffects");
+ function recursivelyAccumulateSuspenseyCommit(parentFiber, committedLanes, suspendedState) {
+ if (parentFiber.subtreeFlags & suspenseyCommitFlag)
+ for (parentFiber = parentFiber.child; null !== parentFiber; )
+ accumulateSuspenseyCommitOnFiber(
+ parentFiber,
+ committedLanes,
+ suspendedState
+ ), parentFiber = parentFiber.sibling;
+ }
+ __name(recursivelyAccumulateSuspenseyCommit, "recursivelyAccumulateSuspenseyCommit");
+ function accumulateSuspenseyCommitOnFiber(fiber, committedLanes, suspendedState) {
+ switch (fiber.tag) {
+ case 26:
+ recursivelyAccumulateSuspenseyCommit(
+ fiber,
+ committedLanes,
+ suspendedState
+ );
+ if (fiber.flags & suspenseyCommitFlag)
+ if (null !== fiber.memoizedState)
+ suspendResource(
+ suspendedState,
+ currentHoistableRoot,
+ fiber.memoizedState,
+ fiber.memoizedProps
+ );
+ else {
+ var instance = fiber.stateNode, type2 = fiber.type;
+ fiber = fiber.memoizedProps;
+ ((committedLanes & 335544128) === committedLanes || maySuspendCommitInSyncRender(type2, fiber)) && suspendInstance(suspendedState, instance, type2, fiber);
+ }
+ break;
+ case 5:
+ recursivelyAccumulateSuspenseyCommit(
+ fiber,
+ committedLanes,
+ suspendedState
+ );
+ fiber.flags & suspenseyCommitFlag && (instance = fiber.stateNode, type2 = fiber.type, fiber = fiber.memoizedProps, ((committedLanes & 335544128) === committedLanes || maySuspendCommitInSyncRender(type2, fiber)) && suspendInstance(suspendedState, instance, type2, fiber));
+ break;
+ case 3:
+ case 4:
+ supportsResources ? (instance = currentHoistableRoot, currentHoistableRoot = getHoistableRoot(
+ fiber.stateNode.containerInfo
+ ), recursivelyAccumulateSuspenseyCommit(
+ fiber,
+ committedLanes,
+ suspendedState
+ ), currentHoistableRoot = instance) : recursivelyAccumulateSuspenseyCommit(
+ fiber,
+ committedLanes,
+ suspendedState
+ );
+ break;
+ case 22:
+ null === fiber.memoizedState && (instance = fiber.alternate, null !== instance && null !== instance.memoizedState ? (instance = suspenseyCommitFlag, suspenseyCommitFlag = 16777216, recursivelyAccumulateSuspenseyCommit(
+ fiber,
+ committedLanes,
+ suspendedState
+ ), suspenseyCommitFlag = instance) : recursivelyAccumulateSuspenseyCommit(
+ fiber,
+ committedLanes,
+ suspendedState
+ ));
+ break;
+ default:
+ recursivelyAccumulateSuspenseyCommit(
+ fiber,
+ committedLanes,
+ suspendedState
+ );
+ }
+ }
+ __name(accumulateSuspenseyCommitOnFiber, "accumulateSuspenseyCommitOnFiber");
+ function detachAlternateSiblings(parentFiber) {
+ var previousFiber = parentFiber.alternate;
+ if (null !== previousFiber && (parentFiber = previousFiber.child, null !== parentFiber)) {
+ previousFiber.child = null;
+ do
+ previousFiber = parentFiber.sibling, parentFiber.sibling = null, parentFiber = previousFiber;
+ while (null !== parentFiber);
+ }
+ }
+ __name(detachAlternateSiblings, "detachAlternateSiblings");
+ function recursivelyTraversePassiveUnmountEffects(parentFiber) {
+ var deletions = parentFiber.deletions;
+ if (0 !== (parentFiber.flags & 16)) {
+ if (null !== deletions)
+ for (var i = 0; i < deletions.length; i++) {
+ var childToDelete = deletions[i];
+ nextEffect = childToDelete;
+ commitPassiveUnmountEffectsInsideOfDeletedTree_begin(
+ childToDelete,
+ parentFiber
+ );
+ }
+ detachAlternateSiblings(parentFiber);
+ }
+ if (parentFiber.subtreeFlags & 10256)
+ for (parentFiber = parentFiber.child; null !== parentFiber; )
+ commitPassiveUnmountOnFiber(parentFiber), parentFiber = parentFiber.sibling;
+ }
+ __name(recursivelyTraversePassiveUnmountEffects, "recursivelyTraversePassiveUnmountEffects");
+ function commitPassiveUnmountOnFiber(finishedWork) {
+ switch (finishedWork.tag) {
+ case 0:
+ case 11:
+ case 15:
+ recursivelyTraversePassiveUnmountEffects(finishedWork);
+ finishedWork.flags & 2048 && commitHookEffectListUnmount(9, finishedWork, finishedWork.return);
+ break;
+ case 3:
+ recursivelyTraversePassiveUnmountEffects(finishedWork);
+ break;
+ case 12:
+ recursivelyTraversePassiveUnmountEffects(finishedWork);
+ break;
+ case 22:
+ var instance = finishedWork.stateNode;
+ null !== finishedWork.memoizedState && instance._visibility & 2 && (null === finishedWork.return || 13 !== finishedWork.return.tag) ? (instance._visibility &= -3, recursivelyTraverseDisconnectPassiveEffects(finishedWork)) : recursivelyTraversePassiveUnmountEffects(finishedWork);
+ break;
+ default:
+ recursivelyTraversePassiveUnmountEffects(finishedWork);
+ }
+ }
+ __name(commitPassiveUnmountOnFiber, "commitPassiveUnmountOnFiber");
+ function recursivelyTraverseDisconnectPassiveEffects(parentFiber) {
+ var deletions = parentFiber.deletions;
+ if (0 !== (parentFiber.flags & 16)) {
+ if (null !== deletions)
+ for (var i = 0; i < deletions.length; i++) {
+ var childToDelete = deletions[i];
+ nextEffect = childToDelete;
+ commitPassiveUnmountEffectsInsideOfDeletedTree_begin(
+ childToDelete,
+ parentFiber
+ );
+ }
+ detachAlternateSiblings(parentFiber);
+ }
+ for (parentFiber = parentFiber.child; null !== parentFiber; ) {
+ deletions = parentFiber;
+ switch (deletions.tag) {
+ case 0:
+ case 11:
+ case 15:
+ commitHookEffectListUnmount(8, deletions, deletions.return);
+ recursivelyTraverseDisconnectPassiveEffects(deletions);
+ break;
+ case 22:
+ i = deletions.stateNode;
+ i._visibility & 2 && (i._visibility &= -3, recursivelyTraverseDisconnectPassiveEffects(deletions));
+ break;
+ default:
+ recursivelyTraverseDisconnectPassiveEffects(deletions);
+ }
+ parentFiber = parentFiber.sibling;
+ }
+ }
+ __name(recursivelyTraverseDisconnectPassiveEffects, "recursivelyTraverseDisconnectPassiveEffects");
+ function commitPassiveUnmountEffectsInsideOfDeletedTree_begin(deletedSubtreeRoot, nearestMountedAncestor) {
+ for (; null !== nextEffect; ) {
+ var fiber = nextEffect;
+ switch (fiber.tag) {
+ case 0:
+ case 11:
+ case 15:
+ commitHookEffectListUnmount(8, fiber, nearestMountedAncestor);
+ break;
+ case 23:
+ case 22:
+ if (null !== fiber.memoizedState && null !== fiber.memoizedState.cachePool) {
+ var cache3 = fiber.memoizedState.cachePool.pool;
+ null != cache3 && cache3.refCount++;
+ }
+ break;
+ case 24:
+ releaseCache(fiber.memoizedState.cache);
+ }
+ cache3 = fiber.child;
+ if (null !== cache3) cache3.return = fiber, nextEffect = cache3;
+ else
+ a: for (fiber = deletedSubtreeRoot; null !== nextEffect; ) {
+ cache3 = nextEffect;
+ var sibling = cache3.sibling, returnFiber = cache3.return;
+ detachFiberAfterEffects(cache3);
+ if (cache3 === fiber) {
+ nextEffect = null;
+ break a;
+ }
+ if (null !== sibling) {
+ sibling.return = returnFiber;
+ nextEffect = sibling;
+ break a;
+ }
+ nextEffect = returnFiber;
+ }
+ }
+ }
+ __name(commitPassiveUnmountEffectsInsideOfDeletedTree_begin, "commitPassiveUnmountEffectsInsideOfDeletedTree_begin");
+ function findFiberRootForHostRoot(hostRoot) {
+ var maybeFiber = getInstanceFromNode(hostRoot);
+ if (null != maybeFiber) {
+ if ("string" !== typeof maybeFiber.memoizedProps["data-testname"])
+ throw Error(formatProdErrorMessage(364));
+ return maybeFiber;
+ }
+ hostRoot = findFiberRoot(hostRoot);
+ if (null === hostRoot) throw Error(formatProdErrorMessage(362));
+ return hostRoot.stateNode.current;
+ }
+ __name(findFiberRootForHostRoot, "findFiberRootForHostRoot");
+ function matchSelector(fiber$jscomp$0, selector) {
+ var tag = fiber$jscomp$0.tag;
+ switch (selector.$$typeof) {
+ case COMPONENT_TYPE:
+ if (fiber$jscomp$0.type === selector.value) return true;
+ break;
+ case HAS_PSEUDO_CLASS_TYPE:
+ a: {
+ selector = selector.value;
+ fiber$jscomp$0 = [fiber$jscomp$0, 0];
+ for (tag = 0; tag < fiber$jscomp$0.length; ) {
+ var fiber = fiber$jscomp$0[tag++], tag$jscomp$0 = fiber.tag, selectorIndex = fiber$jscomp$0[tag++], selector$jscomp$0 = selector[selectorIndex];
+ if (5 !== tag$jscomp$0 && 26 !== tag$jscomp$0 && 27 !== tag$jscomp$0 || !isHiddenSubtree(fiber)) {
+ for (; null != selector$jscomp$0 && matchSelector(fiber, selector$jscomp$0); )
+ selectorIndex++, selector$jscomp$0 = selector[selectorIndex];
+ if (selectorIndex === selector.length) {
+ selector = true;
+ break a;
+ } else
+ for (fiber = fiber.child; null !== fiber; )
+ fiber$jscomp$0.push(fiber, selectorIndex), fiber = fiber.sibling;
+ }
+ }
+ selector = false;
+ }
+ return selector;
+ case ROLE_TYPE:
+ if ((5 === tag || 26 === tag || 27 === tag) && matchAccessibilityRole(fiber$jscomp$0.stateNode, selector.value))
+ return true;
+ break;
+ case TEXT_TYPE:
+ if (5 === tag || 6 === tag || 26 === tag || 27 === tag) {
+ if (fiber$jscomp$0 = getTextContent(fiber$jscomp$0), null !== fiber$jscomp$0 && 0 <= fiber$jscomp$0.indexOf(selector.value))
+ return true;
+ }
+ break;
+ case TEST_NAME_TYPE:
+ if (5 === tag || 26 === tag || 27 === tag) {
+ if (fiber$jscomp$0 = fiber$jscomp$0.memoizedProps["data-testname"], "string" === typeof fiber$jscomp$0 && fiber$jscomp$0.toLowerCase() === selector.value.toLowerCase())
+ return true;
+ }
+ break;
+ default:
+ throw Error(formatProdErrorMessage(365));
+ }
+ return false;
+ }
+ __name(matchSelector, "matchSelector");
+ function selectorToString(selector) {
+ switch (selector.$$typeof) {
+ case COMPONENT_TYPE:
+ return "<" + (getComponentNameFromType(selector.value) || "Unknown") + ">";
+ case HAS_PSEUDO_CLASS_TYPE:
+ return ":has(" + (selectorToString(selector) || "") + ")";
+ case ROLE_TYPE:
+ return '[role="' + selector.value + '"]';
+ case TEXT_TYPE:
+ return '"' + selector.value + '"';
+ case TEST_NAME_TYPE:
+ return '[data-testname="' + selector.value + '"]';
+ default:
+ throw Error(formatProdErrorMessage(365));
+ }
+ }
+ __name(selectorToString, "selectorToString");
+ function findPaths(root, selectors) {
+ var matchingFibers = [];
+ root = [root, 0];
+ for (var index = 0; index < root.length; ) {
+ var fiber = root[index++], tag = fiber.tag, selectorIndex = root[index++], selector = selectors[selectorIndex];
+ if (5 !== tag && 26 !== tag && 27 !== tag || !isHiddenSubtree(fiber)) {
+ for (; null != selector && matchSelector(fiber, selector); )
+ selectorIndex++, selector = selectors[selectorIndex];
+ if (selectorIndex === selectors.length) matchingFibers.push(fiber);
+ else
+ for (fiber = fiber.child; null !== fiber; )
+ root.push(fiber, selectorIndex), fiber = fiber.sibling;
+ }
+ }
+ return matchingFibers;
+ }
+ __name(findPaths, "findPaths");
+ function findAllNodes(hostRoot, selectors) {
+ if (!supportsTestSelectors) throw Error(formatProdErrorMessage(363));
+ hostRoot = findFiberRootForHostRoot(hostRoot);
+ hostRoot = findPaths(hostRoot, selectors);
+ selectors = [];
+ hostRoot = Array.from(hostRoot);
+ for (var index = 0; index < hostRoot.length; ) {
+ var node = hostRoot[index++], tag = node.tag;
+ if (5 === tag || 26 === tag || 27 === tag)
+ isHiddenSubtree(node) || selectors.push(node.stateNode);
+ else
+ for (node = node.child; null !== node; )
+ hostRoot.push(node), node = node.sibling;
+ }
+ return selectors;
+ }
+ __name(findAllNodes, "findAllNodes");
+ function requestUpdateLane() {
+ return 0 !== (executionContext & 2) && 0 !== workInProgressRootRenderLanes ? workInProgressRootRenderLanes & -workInProgressRootRenderLanes : null !== ReactSharedInternals.T ? requestTransitionLane() : resolveUpdatePriority();
+ }
+ __name(requestUpdateLane, "requestUpdateLane");
+ function requestDeferredLane() {
+ if (0 === workInProgressDeferredLane)
+ if (0 === (workInProgressRootRenderLanes & 536870912) || isHydrating) {
+ var lane = nextTransitionDeferredLane;
+ nextTransitionDeferredLane <<= 1;
+ 0 === (nextTransitionDeferredLane & 3932160) && (nextTransitionDeferredLane = 262144);
+ workInProgressDeferredLane = lane;
+ } else workInProgressDeferredLane = 536870912;
+ lane = suspenseHandlerStackCursor.current;
+ null !== lane && (lane.flags |= 32);
+ return workInProgressDeferredLane;
+ }
+ __name(requestDeferredLane, "requestDeferredLane");
+ function scheduleUpdateOnFiber(root, fiber, lane) {
+ if (root === workInProgressRoot && (2 === workInProgressSuspendedReason || 9 === workInProgressSuspendedReason) || null !== root.cancelPendingCommit)
+ prepareFreshStack(root, 0), markRootSuspended(
+ root,
+ workInProgressRootRenderLanes,
+ workInProgressDeferredLane,
+ false
+ );
+ markRootUpdated$1(root, lane);
+ if (0 === (executionContext & 2) || root !== workInProgressRoot)
+ root === workInProgressRoot && (0 === (executionContext & 2) && (workInProgressRootInterleavedUpdatedLanes |= lane), 4 === workInProgressRootExitStatus && markRootSuspended(
+ root,
+ workInProgressRootRenderLanes,
+ workInProgressDeferredLane,
+ false
+ )), ensureRootIsScheduled(root);
+ }
+ __name(scheduleUpdateOnFiber, "scheduleUpdateOnFiber");
+ function performWorkOnRoot(root$jscomp$0, lanes, forceSync) {
+ if (0 !== (executionContext & 6)) throw Error(formatProdErrorMessage(327));
+ var shouldTimeSlice = !forceSync && 0 === (lanes & 127) && 0 === (lanes & root$jscomp$0.expiredLanes) || checkIfRootIsPrerendering(root$jscomp$0, lanes), exitStatus = shouldTimeSlice ? renderRootConcurrent(root$jscomp$0, lanes) : renderRootSync(root$jscomp$0, lanes, true), renderWasConcurrent = shouldTimeSlice;
+ do {
+ if (0 === exitStatus) {
+ workInProgressRootIsPrerendering && !shouldTimeSlice && markRootSuspended(root$jscomp$0, lanes, 0, false);
+ break;
+ } else {
+ forceSync = root$jscomp$0.current.alternate;
+ if (renderWasConcurrent && !isRenderConsistentWithExternalStores(forceSync)) {
+ exitStatus = renderRootSync(root$jscomp$0, lanes, false);
+ renderWasConcurrent = false;
+ continue;
+ }
+ if (2 === exitStatus) {
+ renderWasConcurrent = lanes;
+ if (root$jscomp$0.errorRecoveryDisabledLanes & renderWasConcurrent)
+ var JSCompiler_inline_result = 0;
+ else
+ JSCompiler_inline_result = root$jscomp$0.pendingLanes & -536870913, JSCompiler_inline_result = 0 !== JSCompiler_inline_result ? JSCompiler_inline_result : JSCompiler_inline_result & 536870912 ? 536870912 : 0;
+ if (0 !== JSCompiler_inline_result) {
+ lanes = JSCompiler_inline_result;
+ a: {
+ var root = root$jscomp$0;
+ exitStatus = workInProgressRootConcurrentErrors;
+ var wasRootDehydrated = supportsHydration && root.current.memoizedState.isDehydrated;
+ wasRootDehydrated && (prepareFreshStack(root, JSCompiler_inline_result).flags |= 256);
+ JSCompiler_inline_result = renderRootSync(
+ root,
+ JSCompiler_inline_result,
+ false
+ );
+ if (2 !== JSCompiler_inline_result) {
+ if (workInProgressRootDidAttachPingListener && !wasRootDehydrated) {
+ root.errorRecoveryDisabledLanes |= renderWasConcurrent;
+ workInProgressRootInterleavedUpdatedLanes |= renderWasConcurrent;
+ exitStatus = 4;
+ break a;
+ }
+ renderWasConcurrent = workInProgressRootRecoverableErrors;
+ workInProgressRootRecoverableErrors = exitStatus;
+ null !== renderWasConcurrent && (null === workInProgressRootRecoverableErrors ? workInProgressRootRecoverableErrors = renderWasConcurrent : workInProgressRootRecoverableErrors.push.apply(
+ workInProgressRootRecoverableErrors,
+ renderWasConcurrent
+ ));
+ }
+ exitStatus = JSCompiler_inline_result;
+ }
+ renderWasConcurrent = false;
+ if (2 !== exitStatus) continue;
+ }
+ }
+ if (1 === exitStatus) {
+ prepareFreshStack(root$jscomp$0, 0);
+ markRootSuspended(root$jscomp$0, lanes, 0, true);
+ break;
+ }
+ a: {
+ shouldTimeSlice = root$jscomp$0;
+ renderWasConcurrent = exitStatus;
+ switch (renderWasConcurrent) {
+ case 0:
+ case 1:
+ throw Error(formatProdErrorMessage(345));
+ case 4:
+ if ((lanes & 4194048) !== lanes) break;
+ case 6:
+ markRootSuspended(
+ shouldTimeSlice,
+ lanes,
+ workInProgressDeferredLane,
+ !workInProgressRootDidSkipSuspendedSiblings
+ );
+ break a;
+ case 2:
+ workInProgressRootRecoverableErrors = null;
+ break;
+ case 3:
+ case 5:
+ break;
+ default:
+ throw Error(formatProdErrorMessage(329));
+ }
+ if ((lanes & 62914560) === lanes && (exitStatus = globalMostRecentFallbackTime + 300 - now(), 10 < exitStatus)) {
+ markRootSuspended(
+ shouldTimeSlice,
+ lanes,
+ workInProgressDeferredLane,
+ !workInProgressRootDidSkipSuspendedSiblings
+ );
+ if (0 !== getNextLanes(shouldTimeSlice, 0, true)) break a;
+ pendingEffectsLanes = lanes;
+ shouldTimeSlice.timeoutHandle = scheduleTimeout(
+ commitRootWhenReady.bind(
+ null,
+ shouldTimeSlice,
+ forceSync,
+ workInProgressRootRecoverableErrors,
+ workInProgressTransitions,
+ workInProgressRootDidIncludeRecursiveRenderUpdate,
+ lanes,
+ workInProgressDeferredLane,
+ workInProgressRootInterleavedUpdatedLanes,
+ workInProgressSuspendedRetryLanes,
+ workInProgressRootDidSkipSuspendedSiblings,
+ renderWasConcurrent,
+ "Throttled",
+ -0,
+ 0
+ ),
+ exitStatus
+ );
+ break a;
+ }
+ commitRootWhenReady(
+ shouldTimeSlice,
+ forceSync,
+ workInProgressRootRecoverableErrors,
+ workInProgressTransitions,
+ workInProgressRootDidIncludeRecursiveRenderUpdate,
+ lanes,
+ workInProgressDeferredLane,
+ workInProgressRootInterleavedUpdatedLanes,
+ workInProgressSuspendedRetryLanes,
+ workInProgressRootDidSkipSuspendedSiblings,
+ renderWasConcurrent,
+ null,
+ -0,
+ 0
+ );
+ }
+ }
+ break;
+ } while (1);
+ ensureRootIsScheduled(root$jscomp$0);
+ }
+ __name(performWorkOnRoot, "performWorkOnRoot");
+ function commitRootWhenReady(root, finishedWork, recoverableErrors, transitions, didIncludeRenderPhaseUpdate, lanes, spawnedLane, updatedLanes, suspendedRetryLanes, didSkipSuspendedSiblings, exitStatus, suspendedCommitReason, completedRenderStartTime, completedRenderEndTime) {
+ root.timeoutHandle = noTimeout;
+ suspendedCommitReason = finishedWork.subtreeFlags;
+ if (suspendedCommitReason & 8192 || 16785408 === (suspendedCommitReason & 16785408)) {
+ suspendedCommitReason = startSuspendingCommit();
+ accumulateSuspenseyCommitOnFiber(
+ finishedWork,
+ lanes,
+ suspendedCommitReason
+ );
+ var timeoutOffset = (lanes & 62914560) === lanes ? globalMostRecentFallbackTime - now() : (lanes & 4194048) === lanes ? globalMostRecentTransitionTime - now() : 0;
+ timeoutOffset = waitForCommitToBeReady(
+ suspendedCommitReason,
+ timeoutOffset
+ );
+ if (null !== timeoutOffset) {
+ pendingEffectsLanes = lanes;
+ root.cancelPendingCommit = timeoutOffset(
+ commitRoot.bind(
+ null,
+ root,
+ finishedWork,
+ lanes,
+ recoverableErrors,
+ transitions,
+ didIncludeRenderPhaseUpdate,
+ spawnedLane,
+ updatedLanes,
+ suspendedRetryLanes,
+ exitStatus,
+ suspendedCommitReason,
+ null,
+ completedRenderStartTime,
+ completedRenderEndTime
+ )
+ );
+ markRootSuspended(root, lanes, spawnedLane, !didSkipSuspendedSiblings);
+ return;
+ }
+ }
+ commitRoot(
+ root,
+ finishedWork,
+ lanes,
+ recoverableErrors,
+ transitions,
+ didIncludeRenderPhaseUpdate,
+ spawnedLane,
+ updatedLanes,
+ suspendedRetryLanes
+ );
+ }
+ __name(commitRootWhenReady, "commitRootWhenReady");
+ function isRenderConsistentWithExternalStores(finishedWork) {
+ for (var node = finishedWork; ; ) {
+ var tag = node.tag;
+ if ((0 === tag || 11 === tag || 15 === tag) && node.flags & 16384 && (tag = node.updateQueue, null !== tag && (tag = tag.stores, null !== tag)))
+ for (var i = 0; i < tag.length; i++) {
+ var check3 = tag[i], getSnapshot = check3.getSnapshot;
+ check3 = check3.value;
+ try {
+ if (!objectIs(getSnapshot(), check3)) return false;
+ } catch (error51) {
+ return false;
+ }
+ }
+ tag = node.child;
+ if (node.subtreeFlags & 16384 && null !== tag)
+ tag.return = node, node = tag;
+ else {
+ if (node === finishedWork) break;
+ for (; null === node.sibling; ) {
+ if (null === node.return || node.return === finishedWork) return true;
+ node = node.return;
+ }
+ node.sibling.return = node.return;
+ node = node.sibling;
+ }
+ }
+ return true;
+ }
+ __name(isRenderConsistentWithExternalStores, "isRenderConsistentWithExternalStores");
+ function markRootSuspended(root, suspendedLanes, spawnedLane, didAttemptEntireTree) {
+ suspendedLanes &= ~workInProgressRootPingedLanes;
+ suspendedLanes &= ~workInProgressRootInterleavedUpdatedLanes;
+ root.suspendedLanes |= suspendedLanes;
+ root.pingedLanes &= ~suspendedLanes;
+ didAttemptEntireTree && (root.warmLanes |= suspendedLanes);
+ didAttemptEntireTree = root.expirationTimes;
+ for (var lanes = suspendedLanes; 0 < lanes; ) {
+ var index$4 = 31 - clz32(lanes), lane = 1 << index$4;
+ didAttemptEntireTree[index$4] = -1;
+ lanes &= ~lane;
+ }
+ 0 !== spawnedLane && markSpawnedDeferredLane(root, spawnedLane, suspendedLanes);
+ }
+ __name(markRootSuspended, "markRootSuspended");
+ function flushSyncWork() {
+ return 0 === (executionContext & 6) ? (flushSyncWorkAcrossRoots_impl(0, false), false) : true;
+ }
+ __name(flushSyncWork, "flushSyncWork");
+ function resetWorkInProgressStack() {
+ if (null !== workInProgress) {
+ if (0 === workInProgressSuspendedReason)
+ var interruptedWork = workInProgress.return;
+ else
+ interruptedWork = workInProgress, lastContextDependency = currentlyRenderingFiber$1 = null, resetHooksOnUnwind(interruptedWork), thenableState$1 = null, thenableIndexCounter$1 = 0, interruptedWork = workInProgress;
+ for (; null !== interruptedWork; )
+ unwindInterruptedWork(interruptedWork.alternate, interruptedWork), interruptedWork = interruptedWork.return;
+ workInProgress = null;
+ }
+ }
+ __name(resetWorkInProgressStack, "resetWorkInProgressStack");
+ function prepareFreshStack(root, lanes) {
+ var timeoutHandle = root.timeoutHandle;
+ timeoutHandle !== noTimeout && (root.timeoutHandle = noTimeout, cancelTimeout(timeoutHandle));
+ timeoutHandle = root.cancelPendingCommit;
+ null !== timeoutHandle && (root.cancelPendingCommit = null, timeoutHandle());
+ pendingEffectsLanes = 0;
+ resetWorkInProgressStack();
+ workInProgressRoot = root;
+ workInProgress = timeoutHandle = createWorkInProgress(root.current, null);
+ workInProgressRootRenderLanes = lanes;
+ workInProgressSuspendedReason = 0;
+ workInProgressThrownValue = null;
+ workInProgressRootDidSkipSuspendedSiblings = false;
+ workInProgressRootIsPrerendering = checkIfRootIsPrerendering(root, lanes);
+ workInProgressRootDidAttachPingListener = false;
+ workInProgressSuspendedRetryLanes = workInProgressDeferredLane = workInProgressRootPingedLanes = workInProgressRootInterleavedUpdatedLanes = workInProgressRootSkippedLanes = workInProgressRootExitStatus = 0;
+ workInProgressRootRecoverableErrors = workInProgressRootConcurrentErrors = null;
+ workInProgressRootDidIncludeRecursiveRenderUpdate = false;
+ 0 !== (lanes & 8) && (lanes |= lanes & 32);
+ var allEntangledLanes = root.entangledLanes;
+ if (0 !== allEntangledLanes)
+ for (root = root.entanglements, allEntangledLanes &= lanes; 0 < allEntangledLanes; ) {
+ var index$2 = 31 - clz32(allEntangledLanes), lane = 1 << index$2;
+ lanes |= root[index$2];
+ allEntangledLanes &= ~lane;
+ }
+ entangledRenderLanes = lanes;
+ finishQueueingConcurrentUpdates();
+ return timeoutHandle;
+ }
+ __name(prepareFreshStack, "prepareFreshStack");
+ function handleThrow(root, thrownValue) {
+ currentlyRenderingFiber = null;
+ ReactSharedInternals.H = ContextOnlyDispatcher;
+ thrownValue === SuspenseException || thrownValue === SuspenseActionException ? (thrownValue = getSuspendedThenable(), workInProgressSuspendedReason = 3) : thrownValue === SuspenseyCommitException ? (thrownValue = getSuspendedThenable(), workInProgressSuspendedReason = 4) : workInProgressSuspendedReason = thrownValue === SelectiveHydrationException ? 8 : null !== thrownValue && "object" === typeof thrownValue && "function" === typeof thrownValue.then ? 6 : 1;
+ workInProgressThrownValue = thrownValue;
+ null === workInProgress && (workInProgressRootExitStatus = 1, logUncaughtError(
+ root,
+ createCapturedValueAtFiber(thrownValue, root.current)
+ ));
+ }
+ __name(handleThrow, "handleThrow");
+ function shouldRemainOnPreviousScreen() {
+ var handler = suspenseHandlerStackCursor.current;
+ return null === handler ? true : (workInProgressRootRenderLanes & 4194048) === workInProgressRootRenderLanes ? null === shellBoundary ? true : false : (workInProgressRootRenderLanes & 62914560) === workInProgressRootRenderLanes || 0 !== (workInProgressRootRenderLanes & 536870912) ? handler === shellBoundary : false;
+ }
+ __name(shouldRemainOnPreviousScreen, "shouldRemainOnPreviousScreen");
+ function pushDispatcher() {
+ var prevDispatcher = ReactSharedInternals.H;
+ ReactSharedInternals.H = ContextOnlyDispatcher;
+ return null === prevDispatcher ? ContextOnlyDispatcher : prevDispatcher;
+ }
+ __name(pushDispatcher, "pushDispatcher");
+ function pushAsyncDispatcher() {
+ var prevAsyncDispatcher = ReactSharedInternals.A;
+ ReactSharedInternals.A = DefaultAsyncDispatcher;
+ return prevAsyncDispatcher;
+ }
+ __name(pushAsyncDispatcher, "pushAsyncDispatcher");
+ function renderDidSuspendDelayIfPossible() {
+ workInProgressRootExitStatus = 4;
+ workInProgressRootDidSkipSuspendedSiblings || (workInProgressRootRenderLanes & 4194048) !== workInProgressRootRenderLanes && null !== suspenseHandlerStackCursor.current || (workInProgressRootIsPrerendering = true);
+ 0 === (workInProgressRootSkippedLanes & 134217727) && 0 === (workInProgressRootInterleavedUpdatedLanes & 134217727) || null === workInProgressRoot || markRootSuspended(
+ workInProgressRoot,
+ workInProgressRootRenderLanes,
+ workInProgressDeferredLane,
+ false
+ );
+ }
+ __name(renderDidSuspendDelayIfPossible, "renderDidSuspendDelayIfPossible");
+ function renderRootSync(root, lanes, shouldYieldForPrerendering) {
+ var prevExecutionContext = executionContext;
+ executionContext |= 2;
+ var prevDispatcher = pushDispatcher(), prevAsyncDispatcher = pushAsyncDispatcher();
+ if (workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes)
+ workInProgressTransitions = null, prepareFreshStack(root, lanes);
+ lanes = false;
+ var exitStatus = workInProgressRootExitStatus;
+ a: do
+ try {
+ if (0 !== workInProgressSuspendedReason && null !== workInProgress) {
+ var unitOfWork = workInProgress, thrownValue = workInProgressThrownValue;
+ switch (workInProgressSuspendedReason) {
+ case 8:
+ resetWorkInProgressStack();
+ exitStatus = 6;
+ break a;
+ case 3:
+ case 2:
+ case 9:
+ case 6:
+ null === suspenseHandlerStackCursor.current && (lanes = true);
+ var reason = workInProgressSuspendedReason;
+ workInProgressSuspendedReason = 0;
+ workInProgressThrownValue = null;
+ throwAndUnwindWorkLoop(root, unitOfWork, thrownValue, reason);
+ if (shouldYieldForPrerendering && workInProgressRootIsPrerendering) {
+ exitStatus = 0;
+ break a;
+ }
+ break;
+ default:
+ reason = workInProgressSuspendedReason, workInProgressSuspendedReason = 0, workInProgressThrownValue = null, throwAndUnwindWorkLoop(root, unitOfWork, thrownValue, reason);
+ }
+ }
+ workLoopSync();
+ exitStatus = workInProgressRootExitStatus;
+ break;
+ } catch (thrownValue$152) {
+ handleThrow(root, thrownValue$152);
+ }
+ while (1);
+ lanes && root.shellSuspendCounter++;
+ lastContextDependency = currentlyRenderingFiber$1 = null;
+ executionContext = prevExecutionContext;
+ ReactSharedInternals.H = prevDispatcher;
+ ReactSharedInternals.A = prevAsyncDispatcher;
+ null === workInProgress && (workInProgressRoot = null, workInProgressRootRenderLanes = 0, finishQueueingConcurrentUpdates());
+ return exitStatus;
+ }
+ __name(renderRootSync, "renderRootSync");
+ function workLoopSync() {
+ for (; null !== workInProgress; ) performUnitOfWork(workInProgress);
+ }
+ __name(workLoopSync, "workLoopSync");
+ function renderRootConcurrent(root, lanes) {
+ var prevExecutionContext = executionContext;
+ executionContext |= 2;
+ var prevDispatcher = pushDispatcher(), prevAsyncDispatcher = pushAsyncDispatcher();
+ workInProgressRoot !== root || workInProgressRootRenderLanes !== lanes ? (workInProgressTransitions = null, workInProgressRootRenderTargetTime = now() + 500, prepareFreshStack(root, lanes)) : workInProgressRootIsPrerendering = checkIfRootIsPrerendering(
+ root,
+ lanes
+ );
+ a: do
+ try {
+ if (0 !== workInProgressSuspendedReason && null !== workInProgress) {
+ lanes = workInProgress;
+ var thrownValue = workInProgressThrownValue;
+ b: switch (workInProgressSuspendedReason) {
+ case 1:
+ workInProgressSuspendedReason = 0;
+ workInProgressThrownValue = null;
+ throwAndUnwindWorkLoop(root, lanes, thrownValue, 1);
+ break;
+ case 2:
+ case 9:
+ if (isThenableResolved(thrownValue)) {
+ workInProgressSuspendedReason = 0;
+ workInProgressThrownValue = null;
+ replaySuspendedUnitOfWork(lanes);
+ break;
+ }
+ lanes = /* @__PURE__ */ __name(function() {
+ 2 !== workInProgressSuspendedReason && 9 !== workInProgressSuspendedReason || workInProgressRoot !== root || (workInProgressSuspendedReason = 7);
+ ensureRootIsScheduled(root);
+ }, "lanes");
+ thrownValue.then(lanes, lanes);
+ break a;
+ case 3:
+ workInProgressSuspendedReason = 7;
+ break a;
+ case 4:
+ workInProgressSuspendedReason = 5;
+ break a;
+ case 7:
+ isThenableResolved(thrownValue) ? (workInProgressSuspendedReason = 0, workInProgressThrownValue = null, replaySuspendedUnitOfWork(lanes)) : (workInProgressSuspendedReason = 0, workInProgressThrownValue = null, throwAndUnwindWorkLoop(root, lanes, thrownValue, 7));
+ break;
+ case 5:
+ var resource = null;
+ switch (workInProgress.tag) {
+ case 26:
+ resource = workInProgress.memoizedState;
+ case 5:
+ case 27:
+ var hostFiber = workInProgress, type2 = hostFiber.type, props = hostFiber.pendingProps;
+ if (resource ? preloadResource(resource) : preloadInstance(hostFiber.stateNode, type2, props)) {
+ workInProgressSuspendedReason = 0;
+ workInProgressThrownValue = null;
+ var sibling = hostFiber.sibling;
+ if (null !== sibling) workInProgress = sibling;
+ else {
+ var returnFiber = hostFiber.return;
+ null !== returnFiber ? (workInProgress = returnFiber, completeUnitOfWork(returnFiber)) : workInProgress = null;
+ }
+ break b;
+ }
+ }
+ workInProgressSuspendedReason = 0;
+ workInProgressThrownValue = null;
+ throwAndUnwindWorkLoop(root, lanes, thrownValue, 5);
+ break;
+ case 6:
+ workInProgressSuspendedReason = 0;
+ workInProgressThrownValue = null;
+ throwAndUnwindWorkLoop(root, lanes, thrownValue, 6);
+ break;
+ case 8:
+ resetWorkInProgressStack();
+ workInProgressRootExitStatus = 6;
+ break a;
+ default:
+ throw Error(formatProdErrorMessage(462));
+ }
+ }
+ workLoopConcurrentByScheduler();
+ break;
+ } catch (thrownValue$154) {
+ handleThrow(root, thrownValue$154);
+ }
+ while (1);
+ lastContextDependency = currentlyRenderingFiber$1 = null;
+ ReactSharedInternals.H = prevDispatcher;
+ ReactSharedInternals.A = prevAsyncDispatcher;
+ executionContext = prevExecutionContext;
+ if (null !== workInProgress) return 0;
+ workInProgressRoot = null;
+ workInProgressRootRenderLanes = 0;
+ finishQueueingConcurrentUpdates();
+ return workInProgressRootExitStatus;
+ }
+ __name(renderRootConcurrent, "renderRootConcurrent");
+ function workLoopConcurrentByScheduler() {
+ for (; null !== workInProgress && !shouldYield(); )
+ performUnitOfWork(workInProgress);
+ }
+ __name(workLoopConcurrentByScheduler, "workLoopConcurrentByScheduler");
+ function performUnitOfWork(unitOfWork) {
+ var next = beginWork(
+ unitOfWork.alternate,
+ unitOfWork,
+ entangledRenderLanes
+ );
+ unitOfWork.memoizedProps = unitOfWork.pendingProps;
+ null === next ? completeUnitOfWork(unitOfWork) : workInProgress = next;
+ }
+ __name(performUnitOfWork, "performUnitOfWork");
+ function replaySuspendedUnitOfWork(unitOfWork) {
+ var next = unitOfWork;
+ var current = next.alternate;
+ switch (next.tag) {
+ case 15:
+ case 0:
+ next = replayFunctionComponent(
+ current,
+ next,
+ next.pendingProps,
+ next.type,
+ void 0,
+ workInProgressRootRenderLanes
+ );
+ break;
+ case 11:
+ next = replayFunctionComponent(
+ current,
+ next,
+ next.pendingProps,
+ next.type.render,
+ next.ref,
+ workInProgressRootRenderLanes
+ );
+ break;
+ case 5:
+ resetHooksOnUnwind(next);
+ default:
+ unwindInterruptedWork(current, next), next = workInProgress = resetWorkInProgress(next, entangledRenderLanes), next = beginWork(current, next, entangledRenderLanes);
+ }
+ unitOfWork.memoizedProps = unitOfWork.pendingProps;
+ null === next ? completeUnitOfWork(unitOfWork) : workInProgress = next;
+ }
+ __name(replaySuspendedUnitOfWork, "replaySuspendedUnitOfWork");
+ function throwAndUnwindWorkLoop(root, unitOfWork, thrownValue, suspendedReason) {
+ lastContextDependency = currentlyRenderingFiber$1 = null;
+ resetHooksOnUnwind(unitOfWork);
+ thenableState$1 = null;
+ thenableIndexCounter$1 = 0;
+ var returnFiber = unitOfWork.return;
+ try {
+ if (throwException(
+ root,
+ returnFiber,
+ unitOfWork,
+ thrownValue,
+ workInProgressRootRenderLanes
+ )) {
+ workInProgressRootExitStatus = 1;
+ logUncaughtError(
+ root,
+ createCapturedValueAtFiber(thrownValue, root.current)
+ );
+ workInProgress = null;
+ return;
+ }
+ } catch (error51) {
+ if (null !== returnFiber) throw workInProgress = returnFiber, error51;
+ workInProgressRootExitStatus = 1;
+ logUncaughtError(
+ root,
+ createCapturedValueAtFiber(thrownValue, root.current)
+ );
+ workInProgress = null;
+ return;
+ }
+ if (unitOfWork.flags & 32768) {
+ if (isHydrating || 1 === suspendedReason) root = true;
+ else if (workInProgressRootIsPrerendering || 0 !== (workInProgressRootRenderLanes & 536870912))
+ root = false;
+ else if (workInProgressRootDidSkipSuspendedSiblings = root = true, 2 === suspendedReason || 9 === suspendedReason || 3 === suspendedReason || 6 === suspendedReason)
+ suspendedReason = suspenseHandlerStackCursor.current, null !== suspendedReason && 13 === suspendedReason.tag && (suspendedReason.flags |= 16384);
+ unwindUnitOfWork(unitOfWork, root);
+ } else completeUnitOfWork(unitOfWork);
+ }
+ __name(throwAndUnwindWorkLoop, "throwAndUnwindWorkLoop");
+ function completeUnitOfWork(unitOfWork) {
+ var completedWork = unitOfWork;
+ do {
+ if (0 !== (completedWork.flags & 32768)) {
+ unwindUnitOfWork(
+ completedWork,
+ workInProgressRootDidSkipSuspendedSiblings
+ );
+ return;
+ }
+ unitOfWork = completedWork.return;
+ var next = completeWork(
+ completedWork.alternate,
+ completedWork,
+ entangledRenderLanes
+ );
+ if (null !== next) {
+ workInProgress = next;
+ return;
+ }
+ completedWork = completedWork.sibling;
+ if (null !== completedWork) {
+ workInProgress = completedWork;
+ return;
+ }
+ workInProgress = completedWork = unitOfWork;
+ } while (null !== completedWork);
+ 0 === workInProgressRootExitStatus && (workInProgressRootExitStatus = 5);
+ }
+ __name(completeUnitOfWork, "completeUnitOfWork");
+ function unwindUnitOfWork(unitOfWork, skipSiblings) {
+ do {
+ var next = unwindWork(unitOfWork.alternate, unitOfWork);
+ if (null !== next) {
+ next.flags &= 32767;
+ workInProgress = next;
+ return;
+ }
+ next = unitOfWork.return;
+ null !== next && (next.flags |= 32768, next.subtreeFlags = 0, next.deletions = null);
+ if (!skipSiblings && (unitOfWork = unitOfWork.sibling, null !== unitOfWork)) {
+ workInProgress = unitOfWork;
+ return;
+ }
+ workInProgress = unitOfWork = next;
+ } while (null !== unitOfWork);
+ workInProgressRootExitStatus = 6;
+ workInProgress = null;
+ }
+ __name(unwindUnitOfWork, "unwindUnitOfWork");
+ function commitRoot(root, finishedWork, lanes, recoverableErrors, transitions, didIncludeRenderPhaseUpdate, spawnedLane, updatedLanes, suspendedRetryLanes) {
+ root.cancelPendingCommit = null;
+ do
+ flushPendingEffects();
+ while (0 !== pendingEffectsStatus);
+ if (0 !== (executionContext & 6)) throw Error(formatProdErrorMessage(327));
+ if (null !== finishedWork) {
+ if (finishedWork === root.current)
+ throw Error(formatProdErrorMessage(177));
+ didIncludeRenderPhaseUpdate = finishedWork.lanes | finishedWork.childLanes;
+ didIncludeRenderPhaseUpdate |= concurrentlyUpdatedLanes;
+ markRootFinished(
+ root,
+ lanes,
+ didIncludeRenderPhaseUpdate,
+ spawnedLane,
+ updatedLanes,
+ suspendedRetryLanes
+ );
+ root === workInProgressRoot && (workInProgress = workInProgressRoot = null, workInProgressRootRenderLanes = 0);
+ pendingFinishedWork = finishedWork;
+ pendingEffectsRoot = root;
+ pendingEffectsLanes = lanes;
+ pendingEffectsRemainingLanes = didIncludeRenderPhaseUpdate;
+ pendingPassiveTransitions = transitions;
+ pendingRecoverableErrors = recoverableErrors;
+ 0 !== (finishedWork.subtreeFlags & 10256) || 0 !== (finishedWork.flags & 10256) ? (root.callbackNode = null, root.callbackPriority = 0, scheduleCallback(NormalPriority$1, function() {
+ flushPassiveEffects();
+ return null;
+ })) : (root.callbackNode = null, root.callbackPriority = 0);
+ recoverableErrors = 0 !== (finishedWork.flags & 13878);
+ if (0 !== (finishedWork.subtreeFlags & 13878) || recoverableErrors) {
+ recoverableErrors = ReactSharedInternals.T;
+ ReactSharedInternals.T = null;
+ transitions = getCurrentUpdatePriority();
+ setCurrentUpdatePriority(2);
+ spawnedLane = executionContext;
+ executionContext |= 4;
+ try {
+ commitBeforeMutationEffects(root, finishedWork, lanes);
+ } finally {
+ executionContext = spawnedLane, setCurrentUpdatePriority(transitions), ReactSharedInternals.T = recoverableErrors;
+ }
+ }
+ pendingEffectsStatus = 1;
+ flushMutationEffects();
+ flushLayoutEffects();
+ flushSpawnedWork();
+ }
+ }
+ __name(commitRoot, "commitRoot");
+ function flushMutationEffects() {
+ if (1 === pendingEffectsStatus) {
+ pendingEffectsStatus = 0;
+ var root = pendingEffectsRoot, finishedWork = pendingFinishedWork, rootMutationHasEffect = 0 !== (finishedWork.flags & 13878);
+ if (0 !== (finishedWork.subtreeFlags & 13878) || rootMutationHasEffect) {
+ rootMutationHasEffect = ReactSharedInternals.T;
+ ReactSharedInternals.T = null;
+ var previousPriority = getCurrentUpdatePriority();
+ setCurrentUpdatePriority(2);
+ var prevExecutionContext = executionContext;
+ executionContext |= 4;
+ try {
+ commitMutationEffectsOnFiber(finishedWork, root), resetAfterCommit(root.containerInfo);
+ } finally {
+ executionContext = prevExecutionContext, setCurrentUpdatePriority(previousPriority), ReactSharedInternals.T = rootMutationHasEffect;
+ }
+ }
+ root.current = finishedWork;
+ pendingEffectsStatus = 2;
+ }
+ }
+ __name(flushMutationEffects, "flushMutationEffects");
+ function flushLayoutEffects() {
+ if (2 === pendingEffectsStatus) {
+ pendingEffectsStatus = 0;
+ var root = pendingEffectsRoot, finishedWork = pendingFinishedWork, rootHasLayoutEffect = 0 !== (finishedWork.flags & 8772);
+ if (0 !== (finishedWork.subtreeFlags & 8772) || rootHasLayoutEffect) {
+ rootHasLayoutEffect = ReactSharedInternals.T;
+ ReactSharedInternals.T = null;
+ var previousPriority = getCurrentUpdatePriority();
+ setCurrentUpdatePriority(2);
+ var prevExecutionContext = executionContext;
+ executionContext |= 4;
+ try {
+ commitLayoutEffectOnFiber(root, finishedWork.alternate, finishedWork);
+ } finally {
+ executionContext = prevExecutionContext, setCurrentUpdatePriority(previousPriority), ReactSharedInternals.T = rootHasLayoutEffect;
+ }
+ }
+ pendingEffectsStatus = 3;
+ }
+ }
+ __name(flushLayoutEffects, "flushLayoutEffects");
+ function flushSpawnedWork() {
+ if (4 === pendingEffectsStatus || 3 === pendingEffectsStatus) {
+ pendingEffectsStatus = 0;
+ requestPaint();
+ var root = pendingEffectsRoot, finishedWork = pendingFinishedWork, lanes = pendingEffectsLanes, recoverableErrors = pendingRecoverableErrors;
+ 0 !== (finishedWork.subtreeFlags & 10256) || 0 !== (finishedWork.flags & 10256) ? pendingEffectsStatus = 5 : (pendingEffectsStatus = 0, pendingFinishedWork = pendingEffectsRoot = null, releaseRootPooledCache(root, root.pendingLanes));
+ var remainingLanes = root.pendingLanes;
+ 0 === remainingLanes && (legacyErrorBoundariesThatAlreadyFailed = null);
+ lanesToEventPriority(lanes);
+ finishedWork = finishedWork.stateNode;
+ if (injectedHook && "function" === typeof injectedHook.onCommitFiberRoot)
+ try {
+ injectedHook.onCommitFiberRoot(
+ rendererID,
+ finishedWork,
+ void 0,
+ 128 === (finishedWork.current.flags & 128)
+ );
+ } catch (err) {
+ }
+ if (null !== recoverableErrors) {
+ finishedWork = ReactSharedInternals.T;
+ remainingLanes = getCurrentUpdatePriority();
+ setCurrentUpdatePriority(2);
+ ReactSharedInternals.T = null;
+ try {
+ for (var onRecoverableError = root.onRecoverableError, i = 0; i < recoverableErrors.length; i++) {
+ var recoverableError = recoverableErrors[i];
+ onRecoverableError(recoverableError.value, {
+ componentStack: recoverableError.stack
+ });
+ }
+ } finally {
+ ReactSharedInternals.T = finishedWork, setCurrentUpdatePriority(remainingLanes);
+ }
+ }
+ 0 !== (pendingEffectsLanes & 3) && flushPendingEffects();
+ ensureRootIsScheduled(root);
+ remainingLanes = root.pendingLanes;
+ 0 !== (lanes & 261930) && 0 !== (remainingLanes & 42) ? root === rootWithNestedUpdates ? nestedUpdateCount++ : (nestedUpdateCount = 0, rootWithNestedUpdates = root) : nestedUpdateCount = 0;
+ supportsHydration && flushHydrationEvents();
+ flushSyncWorkAcrossRoots_impl(0, false);
+ }
+ }
+ __name(flushSpawnedWork, "flushSpawnedWork");
+ function releaseRootPooledCache(root, remainingLanes) {
+ 0 === (root.pooledCacheLanes &= remainingLanes) && (remainingLanes = root.pooledCache, null != remainingLanes && (root.pooledCache = null, releaseCache(remainingLanes)));
+ }
+ __name(releaseRootPooledCache, "releaseRootPooledCache");
+ function flushPendingEffects() {
+ flushMutationEffects();
+ flushLayoutEffects();
+ flushSpawnedWork();
+ return flushPassiveEffects();
+ }
+ __name(flushPendingEffects, "flushPendingEffects");
+ function flushPassiveEffects() {
+ if (5 !== pendingEffectsStatus) return false;
+ var root = pendingEffectsRoot, remainingLanes = pendingEffectsRemainingLanes;
+ pendingEffectsRemainingLanes = 0;
+ var renderPriority = lanesToEventPriority(pendingEffectsLanes), priority = 32 > renderPriority ? 32 : renderPriority;
+ renderPriority = ReactSharedInternals.T;
+ var previousPriority = getCurrentUpdatePriority();
+ try {
+ setCurrentUpdatePriority(priority);
+ ReactSharedInternals.T = null;
+ priority = pendingPassiveTransitions;
+ pendingPassiveTransitions = null;
+ var root$jscomp$0 = pendingEffectsRoot, lanes = pendingEffectsLanes;
+ pendingEffectsStatus = 0;
+ pendingFinishedWork = pendingEffectsRoot = null;
+ pendingEffectsLanes = 0;
+ if (0 !== (executionContext & 6))
+ throw Error(formatProdErrorMessage(331));
+ var prevExecutionContext = executionContext;
+ executionContext |= 4;
+ commitPassiveUnmountOnFiber(root$jscomp$0.current);
+ commitPassiveMountOnFiber(
+ root$jscomp$0,
+ root$jscomp$0.current,
+ lanes,
+ priority
+ );
+ executionContext = prevExecutionContext;
+ flushSyncWorkAcrossRoots_impl(0, false);
+ if (injectedHook && "function" === typeof injectedHook.onPostCommitFiberRoot)
+ try {
+ injectedHook.onPostCommitFiberRoot(rendererID, root$jscomp$0);
+ } catch (err) {
+ }
+ return true;
+ } finally {
+ setCurrentUpdatePriority(previousPriority), ReactSharedInternals.T = renderPriority, releaseRootPooledCache(root, remainingLanes);
+ }
+ }
+ __name(flushPassiveEffects, "flushPassiveEffects");
+ function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error51) {
+ sourceFiber = createCapturedValueAtFiber(error51, sourceFiber);
+ sourceFiber = createRootErrorUpdate(rootFiber.stateNode, sourceFiber, 2);
+ rootFiber = enqueueUpdate(rootFiber, sourceFiber, 2);
+ null !== rootFiber && (markRootUpdated$1(rootFiber, 2), ensureRootIsScheduled(rootFiber));
+ }
+ __name(captureCommitPhaseErrorOnRoot, "captureCommitPhaseErrorOnRoot");
+ function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error51) {
+ if (3 === sourceFiber.tag)
+ captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error51);
+ else
+ for (; null !== nearestMountedAncestor; ) {
+ if (3 === nearestMountedAncestor.tag) {
+ captureCommitPhaseErrorOnRoot(
+ nearestMountedAncestor,
+ sourceFiber,
+ error51
+ );
+ break;
+ } else if (1 === nearestMountedAncestor.tag) {
+ var instance = nearestMountedAncestor.stateNode;
+ if ("function" === typeof nearestMountedAncestor.type.getDerivedStateFromError || "function" === typeof instance.componentDidCatch && (null === legacyErrorBoundariesThatAlreadyFailed || !legacyErrorBoundariesThatAlreadyFailed.has(instance))) {
+ sourceFiber = createCapturedValueAtFiber(error51, sourceFiber);
+ error51 = createClassErrorUpdate(2);
+ instance = enqueueUpdate(nearestMountedAncestor, error51, 2);
+ null !== instance && (initializeClassErrorUpdate(
+ error51,
+ instance,
+ nearestMountedAncestor,
+ sourceFiber
+ ), markRootUpdated$1(instance, 2), ensureRootIsScheduled(instance));
+ break;
+ }
+ }
+ nearestMountedAncestor = nearestMountedAncestor.return;
+ }
+ }
+ __name(captureCommitPhaseError, "captureCommitPhaseError");
+ function attachPingListener(root, wakeable, lanes) {
+ var pingCache = root.pingCache;
+ if (null === pingCache) {
+ pingCache = root.pingCache = new PossiblyWeakMap();
+ var threadIDs = /* @__PURE__ */ new Set();
+ pingCache.set(wakeable, threadIDs);
+ } else
+ threadIDs = pingCache.get(wakeable), void 0 === threadIDs && (threadIDs = /* @__PURE__ */ new Set(), pingCache.set(wakeable, threadIDs));
+ threadIDs.has(lanes) || (workInProgressRootDidAttachPingListener = true, threadIDs.add(lanes), root = pingSuspendedRoot.bind(null, root, wakeable, lanes), wakeable.then(root, root));
+ }
+ __name(attachPingListener, "attachPingListener");
+ function pingSuspendedRoot(root, wakeable, pingedLanes) {
+ var pingCache = root.pingCache;
+ null !== pingCache && pingCache.delete(wakeable);
+ root.pingedLanes |= root.suspendedLanes & pingedLanes;
+ root.warmLanes &= ~pingedLanes;
+ workInProgressRoot === root && (workInProgressRootRenderLanes & pingedLanes) === pingedLanes && (4 === workInProgressRootExitStatus || 3 === workInProgressRootExitStatus && (workInProgressRootRenderLanes & 62914560) === workInProgressRootRenderLanes && 300 > now() - globalMostRecentFallbackTime ? 0 === (executionContext & 2) && prepareFreshStack(root, 0) : workInProgressRootPingedLanes |= pingedLanes, workInProgressSuspendedRetryLanes === workInProgressRootRenderLanes && (workInProgressSuspendedRetryLanes = 0));
+ ensureRootIsScheduled(root);
+ }
+ __name(pingSuspendedRoot, "pingSuspendedRoot");
+ function retryTimedOutBoundary(boundaryFiber, retryLane) {
+ 0 === retryLane && (retryLane = claimNextRetryLane());
+ boundaryFiber = enqueueConcurrentRenderForLane(boundaryFiber, retryLane);
+ null !== boundaryFiber && (markRootUpdated$1(boundaryFiber, retryLane), ensureRootIsScheduled(boundaryFiber));
+ }
+ __name(retryTimedOutBoundary, "retryTimedOutBoundary");
+ function retryDehydratedSuspenseBoundary(boundaryFiber) {
+ var suspenseState = boundaryFiber.memoizedState, retryLane = 0;
+ null !== suspenseState && (retryLane = suspenseState.retryLane);
+ retryTimedOutBoundary(boundaryFiber, retryLane);
+ }
+ __name(retryDehydratedSuspenseBoundary, "retryDehydratedSuspenseBoundary");
+ function resolveRetryWakeable(boundaryFiber, wakeable) {
+ var retryLane = 0;
+ switch (boundaryFiber.tag) {
+ case 31:
+ case 13:
+ var retryCache = boundaryFiber.stateNode;
+ var suspenseState = boundaryFiber.memoizedState;
+ null !== suspenseState && (retryLane = suspenseState.retryLane);
+ break;
+ case 19:
+ retryCache = boundaryFiber.stateNode;
+ break;
+ case 22:
+ retryCache = boundaryFiber.stateNode._retryCache;
+ break;
+ default:
+ throw Error(formatProdErrorMessage(314));
+ }
+ null !== retryCache && retryCache.delete(wakeable);
+ retryTimedOutBoundary(boundaryFiber, retryLane);
+ }
+ __name(resolveRetryWakeable, "resolveRetryWakeable");
+ function scheduleCallback(priorityLevel, callback) {
+ return scheduleCallback$3(priorityLevel, callback);
+ }
+ __name(scheduleCallback, "scheduleCallback");
+ function FiberNode(tag, pendingProps, key, mode) {
+ this.tag = tag;
+ this.key = key;
+ this.sibling = this.child = this.return = this.stateNode = this.type = this.elementType = null;
+ this.index = 0;
+ this.refCleanup = this.ref = null;
+ this.pendingProps = pendingProps;
+ this.dependencies = this.memoizedState = this.updateQueue = this.memoizedProps = null;
+ this.mode = mode;
+ this.subtreeFlags = this.flags = 0;
+ this.deletions = null;
+ this.childLanes = this.lanes = 0;
+ this.alternate = null;
+ }
+ __name(FiberNode, "FiberNode");
+ function shouldConstruct(Component) {
+ Component = Component.prototype;
+ return !(!Component || !Component.isReactComponent);
+ }
+ __name(shouldConstruct, "shouldConstruct");
+ function createWorkInProgress(current, pendingProps) {
+ var workInProgress2 = current.alternate;
+ null === workInProgress2 ? (workInProgress2 = createFiber(
+ current.tag,
+ pendingProps,
+ current.key,
+ current.mode
+ ), workInProgress2.elementType = current.elementType, workInProgress2.type = current.type, workInProgress2.stateNode = current.stateNode, workInProgress2.alternate = current, current.alternate = workInProgress2) : (workInProgress2.pendingProps = pendingProps, workInProgress2.type = current.type, workInProgress2.flags = 0, workInProgress2.subtreeFlags = 0, workInProgress2.deletions = null);
+ workInProgress2.flags = current.flags & 65011712;
+ workInProgress2.childLanes = current.childLanes;
+ workInProgress2.lanes = current.lanes;
+ workInProgress2.child = current.child;
+ workInProgress2.memoizedProps = current.memoizedProps;
+ workInProgress2.memoizedState = current.memoizedState;
+ workInProgress2.updateQueue = current.updateQueue;
+ pendingProps = current.dependencies;
+ workInProgress2.dependencies = null === pendingProps ? null : {
+ lanes: pendingProps.lanes,
+ firstContext: pendingProps.firstContext
+ };
+ workInProgress2.sibling = current.sibling;
+ workInProgress2.index = current.index;
+ workInProgress2.ref = current.ref;
+ workInProgress2.refCleanup = current.refCleanup;
+ return workInProgress2;
+ }
+ __name(createWorkInProgress, "createWorkInProgress");
+ function resetWorkInProgress(workInProgress2, renderLanes2) {
+ workInProgress2.flags &= 65011714;
+ var current = workInProgress2.alternate;
+ null === current ? (workInProgress2.childLanes = 0, workInProgress2.lanes = renderLanes2, workInProgress2.child = null, workInProgress2.subtreeFlags = 0, workInProgress2.memoizedProps = null, workInProgress2.memoizedState = null, workInProgress2.updateQueue = null, workInProgress2.dependencies = null, workInProgress2.stateNode = null) : (workInProgress2.childLanes = current.childLanes, workInProgress2.lanes = current.lanes, workInProgress2.child = current.child, workInProgress2.subtreeFlags = 0, workInProgress2.deletions = null, workInProgress2.memoizedProps = current.memoizedProps, workInProgress2.memoizedState = current.memoizedState, workInProgress2.updateQueue = current.updateQueue, workInProgress2.type = current.type, renderLanes2 = current.dependencies, workInProgress2.dependencies = null === renderLanes2 ? null : {
+ lanes: renderLanes2.lanes,
+ firstContext: renderLanes2.firstContext
+ });
+ return workInProgress2;
+ }
+ __name(resetWorkInProgress, "resetWorkInProgress");
+ function createFiberFromTypeAndProps(type2, key, pendingProps, owner, mode, lanes) {
+ var fiberTag = 0;
+ owner = type2;
+ if ("function" === typeof type2) shouldConstruct(type2) && (fiberTag = 1);
+ else if ("string" === typeof type2)
+ fiberTag = supportsResources && supportsSingletons ? isHostHoistableType(type2, pendingProps, contextStackCursor.current) ? 26 : isHostSingletonType(type2) ? 27 : 5 : supportsResources ? isHostHoistableType(
+ type2,
+ pendingProps,
+ contextStackCursor.current
+ ) ? 26 : 5 : supportsSingletons ? isHostSingletonType(type2) ? 27 : 5 : 5;
+ else
+ a: switch (type2) {
+ case REACT_ACTIVITY_TYPE:
+ return type2 = createFiber(31, pendingProps, key, mode), type2.elementType = REACT_ACTIVITY_TYPE, type2.lanes = lanes, type2;
+ case REACT_FRAGMENT_TYPE:
+ return createFiberFromFragment(
+ pendingProps.children,
+ mode,
+ lanes,
+ key
+ );
+ case REACT_STRICT_MODE_TYPE:
+ fiberTag = 8;
+ mode |= 24;
+ break;
+ case REACT_PROFILER_TYPE:
+ return type2 = createFiber(12, pendingProps, key, mode | 2), type2.elementType = REACT_PROFILER_TYPE, type2.lanes = lanes, type2;
+ case REACT_SUSPENSE_TYPE:
+ return type2 = createFiber(13, pendingProps, key, mode), type2.elementType = REACT_SUSPENSE_TYPE, type2.lanes = lanes, type2;
+ case REACT_SUSPENSE_LIST_TYPE:
+ return type2 = createFiber(19, pendingProps, key, mode), type2.elementType = REACT_SUSPENSE_LIST_TYPE, type2.lanes = lanes, type2;
+ default:
+ if ("object" === typeof type2 && null !== type2)
+ switch (type2.$$typeof) {
+ case REACT_CONTEXT_TYPE:
+ fiberTag = 10;
+ break a;
+ case REACT_CONSUMER_TYPE:
+ fiberTag = 9;
+ break a;
+ case REACT_FORWARD_REF_TYPE:
+ fiberTag = 11;
+ break a;
+ case REACT_MEMO_TYPE:
+ fiberTag = 14;
+ break a;
+ case REACT_LAZY_TYPE:
+ fiberTag = 16;
+ owner = null;
+ break a;
+ }
+ fiberTag = 29;
+ pendingProps = Error(
+ formatProdErrorMessage(
+ 130,
+ null === type2 ? "null" : typeof type2,
+ ""
+ )
+ );
+ owner = null;
+ }
+ key = createFiber(fiberTag, pendingProps, key, mode);
+ key.elementType = type2;
+ key.type = owner;
+ key.lanes = lanes;
+ return key;
+ }
+ __name(createFiberFromTypeAndProps, "createFiberFromTypeAndProps");
+ function createFiberFromFragment(elements, mode, lanes, key) {
+ elements = createFiber(7, elements, key, mode);
+ elements.lanes = lanes;
+ return elements;
+ }
+ __name(createFiberFromFragment, "createFiberFromFragment");
+ function createFiberFromText(content, mode, lanes) {
+ content = createFiber(6, content, null, mode);
+ content.lanes = lanes;
+ return content;
+ }
+ __name(createFiberFromText, "createFiberFromText");
+ function createFiberFromDehydratedFragment(dehydratedNode) {
+ var fiber = createFiber(18, null, null, 0);
+ fiber.stateNode = dehydratedNode;
+ return fiber;
+ }
+ __name(createFiberFromDehydratedFragment, "createFiberFromDehydratedFragment");
+ function createFiberFromPortal(portal, mode, lanes) {
+ mode = createFiber(
+ 4,
+ null !== portal.children ? portal.children : [],
+ portal.key,
+ mode
+ );
+ mode.lanes = lanes;
+ mode.stateNode = {
+ containerInfo: portal.containerInfo,
+ pendingChildren: null,
+ implementation: portal.implementation
+ };
+ return mode;
+ }
+ __name(createFiberFromPortal, "createFiberFromPortal");
+ function FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onUncaughtError, onCaughtError, onRecoverableError, onDefaultTransitionIndicator, formState) {
+ this.tag = 1;
+ this.containerInfo = containerInfo;
+ this.pingCache = this.current = this.pendingChildren = null;
+ this.timeoutHandle = noTimeout;
+ this.callbackNode = this.next = this.pendingContext = this.context = this.cancelPendingCommit = null;
+ this.callbackPriority = 0;
+ this.expirationTimes = createLaneMap(-1);
+ this.entangledLanes = this.shellSuspendCounter = this.errorRecoveryDisabledLanes = this.expiredLanes = this.warmLanes = this.pingedLanes = this.suspendedLanes = this.pendingLanes = 0;
+ this.entanglements = createLaneMap(0);
+ this.hiddenUpdates = createLaneMap(null);
+ this.identifierPrefix = identifierPrefix;
+ this.onUncaughtError = onUncaughtError;
+ this.onCaughtError = onCaughtError;
+ this.onRecoverableError = onRecoverableError;
+ this.pooledCache = null;
+ this.pooledCacheLanes = 0;
+ this.formState = formState;
+ this.incompleteTransitions = /* @__PURE__ */ new Map();
+ }
+ __name(FiberRootNode, "FiberRootNode");
+ function createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, identifierPrefix, formState, onUncaughtError, onCaughtError, onRecoverableError, onDefaultTransitionIndicator) {
+ containerInfo = new FiberRootNode(
+ containerInfo,
+ tag,
+ hydrate,
+ identifierPrefix,
+ onUncaughtError,
+ onCaughtError,
+ onRecoverableError,
+ onDefaultTransitionIndicator,
+ formState
+ );
+ tag = 1;
+ true === isStrictMode && (tag |= 24);
+ isStrictMode = createFiber(3, null, null, tag);
+ containerInfo.current = isStrictMode;
+ isStrictMode.stateNode = containerInfo;
+ tag = createCache();
+ tag.refCount++;
+ containerInfo.pooledCache = tag;
+ tag.refCount++;
+ isStrictMode.memoizedState = {
+ element: initialChildren,
+ isDehydrated: hydrate,
+ cache: tag
+ };
+ initializeUpdateQueue(isStrictMode);
+ return containerInfo;
+ }
+ __name(createFiberRoot, "createFiberRoot");
+ function getContextForSubtree(parentComponent) {
+ if (!parentComponent) return emptyContextObject;
+ parentComponent = emptyContextObject;
+ return parentComponent;
+ }
+ __name(getContextForSubtree, "getContextForSubtree");
+ function findHostInstance(component) {
+ var fiber = component._reactInternals;
+ if (void 0 === fiber) {
+ if ("function" === typeof component.render)
+ throw Error(formatProdErrorMessage(188));
+ component = Object.keys(component).join(",");
+ throw Error(formatProdErrorMessage(268, component));
+ }
+ component = findCurrentFiberUsingSlowPath(fiber);
+ component = null !== component ? findCurrentHostFiberImpl(component) : null;
+ return null === component ? null : getPublicInstance(component.stateNode);
+ }
+ __name(findHostInstance, "findHostInstance");
+ function updateContainerImpl(rootFiber, lane, element, container, parentComponent, callback) {
+ parentComponent = getContextForSubtree(parentComponent);
+ null === container.context ? container.context = parentComponent : container.pendingContext = parentComponent;
+ container = createUpdate(lane);
+ container.payload = { element };
+ callback = void 0 === callback ? null : callback;
+ null !== callback && (container.callback = callback);
+ element = enqueueUpdate(rootFiber, container, lane);
+ null !== element && (scheduleUpdateOnFiber(element, rootFiber, lane), entangleTransitions(element, rootFiber, lane));
+ }
+ __name(updateContainerImpl, "updateContainerImpl");
+ function markRetryLaneImpl(fiber, retryLane) {
+ fiber = fiber.memoizedState;
+ if (null !== fiber && null !== fiber.dehydrated) {
+ var a = fiber.retryLane;
+ fiber.retryLane = 0 !== a && a < retryLane ? a : retryLane;
+ }
+ }
+ __name(markRetryLaneImpl, "markRetryLaneImpl");
+ function markRetryLaneIfNotHydrated(fiber, retryLane) {
+ markRetryLaneImpl(fiber, retryLane);
+ (fiber = fiber.alternate) && markRetryLaneImpl(fiber, retryLane);
+ }
+ __name(markRetryLaneIfNotHydrated, "markRetryLaneIfNotHydrated");
+ var exports3 = {};
+ "use strict";
+ var React29 = require_react(), Scheduler2 = require_scheduler(), assign = Object.assign, REACT_LEGACY_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.element"), REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = /* @__PURE__ */ Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = /* @__PURE__ */ Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = /* @__PURE__ */ Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = /* @__PURE__ */ Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = /* @__PURE__ */ Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = /* @__PURE__ */ Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = /* @__PURE__ */ Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = /* @__PURE__ */ Symbol.for("react.memo"), REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy");
+ /* @__PURE__ */ Symbol.for("react.scope");
+ var REACT_ACTIVITY_TYPE = /* @__PURE__ */ Symbol.for("react.activity");
+ /* @__PURE__ */ Symbol.for("react.legacy_hidden");
+ /* @__PURE__ */ Symbol.for("react.tracing_marker");
+ var REACT_MEMO_CACHE_SENTINEL = /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel");
+ /* @__PURE__ */ Symbol.for("react.view_transition");
+ var MAYBE_ITERATOR_SYMBOL = Symbol.iterator, REACT_CLIENT_REFERENCE = /* @__PURE__ */ Symbol.for("react.client.reference"), isArrayImpl = Array.isArray, ReactSharedInternals = React29.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, rendererVersion = $$$config.rendererVersion, rendererPackageName = $$$config.rendererPackageName, extraDevToolsConfig = $$$config.extraDevToolsConfig, getPublicInstance = $$$config.getPublicInstance, getRootHostContext = $$$config.getRootHostContext, getChildHostContext = $$$config.getChildHostContext, prepareForCommit = $$$config.prepareForCommit, resetAfterCommit = $$$config.resetAfterCommit, createInstance = $$$config.createInstance;
+ $$$config.cloneMutableInstance;
+ var appendInitialChild = $$$config.appendInitialChild, finalizeInitialChildren = $$$config.finalizeInitialChildren, shouldSetTextContent = $$$config.shouldSetTextContent, createTextInstance = $$$config.createTextInstance;
+ $$$config.cloneMutableTextInstance;
+ var scheduleTimeout = $$$config.scheduleTimeout, cancelTimeout = $$$config.cancelTimeout, noTimeout = $$$config.noTimeout, isPrimaryRenderer = $$$config.isPrimaryRenderer;
+ $$$config.warnsIfNotActing;
+ var supportsMutation = $$$config.supportsMutation, supportsPersistence = $$$config.supportsPersistence, supportsHydration = $$$config.supportsHydration, getInstanceFromNode = $$$config.getInstanceFromNode;
+ $$$config.beforeActiveInstanceBlur;
+ var preparePortalMount = $$$config.preparePortalMount;
+ $$$config.prepareScopeUpdate;
+ $$$config.getInstanceFromScope;
+ var setCurrentUpdatePriority = $$$config.setCurrentUpdatePriority, getCurrentUpdatePriority = $$$config.getCurrentUpdatePriority, resolveUpdatePriority = $$$config.resolveUpdatePriority;
+ $$$config.trackSchedulerEvent;
+ $$$config.resolveEventType;
+ $$$config.resolveEventTimeStamp;
+ var shouldAttemptEagerTransition = $$$config.shouldAttemptEagerTransition, detachDeletedInstance = $$$config.detachDeletedInstance;
+ $$$config.requestPostPaintCallback;
+ var maySuspendCommit = $$$config.maySuspendCommit, maySuspendCommitOnUpdate = $$$config.maySuspendCommitOnUpdate, maySuspendCommitInSyncRender = $$$config.maySuspendCommitInSyncRender, preloadInstance = $$$config.preloadInstance, startSuspendingCommit = $$$config.startSuspendingCommit, suspendInstance = $$$config.suspendInstance;
+ $$$config.suspendOnActiveViewTransition;
+ var waitForCommitToBeReady = $$$config.waitForCommitToBeReady;
+ $$$config.getSuspendedCommitReason;
+ var NotPendingTransition = $$$config.NotPendingTransition, HostTransitionContext = $$$config.HostTransitionContext, resetFormInstance = $$$config.resetFormInstance;
+ $$$config.bindToConsole;
+ var supportsMicrotasks = $$$config.supportsMicrotasks, scheduleMicrotask = $$$config.scheduleMicrotask, supportsTestSelectors = $$$config.supportsTestSelectors, findFiberRoot = $$$config.findFiberRoot, getBoundingRect = $$$config.getBoundingRect, getTextContent = $$$config.getTextContent, isHiddenSubtree = $$$config.isHiddenSubtree, matchAccessibilityRole = $$$config.matchAccessibilityRole, setFocusIfFocusable = $$$config.setFocusIfFocusable, setupIntersectionObserver = $$$config.setupIntersectionObserver, appendChild = $$$config.appendChild, appendChildToContainer = $$$config.appendChildToContainer, commitTextUpdate = $$$config.commitTextUpdate, commitMount = $$$config.commitMount, commitUpdate = $$$config.commitUpdate, insertBefore = $$$config.insertBefore, insertInContainerBefore = $$$config.insertInContainerBefore, removeChild = $$$config.removeChild, removeChildFromContainer = $$$config.removeChildFromContainer, resetTextContent = $$$config.resetTextContent, hideInstance = $$$config.hideInstance, hideTextInstance = $$$config.hideTextInstance, unhideInstance = $$$config.unhideInstance, unhideTextInstance = $$$config.unhideTextInstance;
+ $$$config.cancelViewTransitionName;
+ $$$config.cancelRootViewTransitionName;
+ $$$config.restoreRootViewTransitionName;
+ $$$config.cloneRootViewTransitionContainer;
+ $$$config.removeRootViewTransitionClone;
+ $$$config.measureClonedInstance;
+ $$$config.hasInstanceChanged;
+ $$$config.hasInstanceAffectedParent;
+ $$$config.startViewTransition;
+ $$$config.startGestureTransition;
+ $$$config.stopViewTransition;
+ $$$config.getCurrentGestureOffset;
+ $$$config.createViewTransitionInstance;
+ var clearContainer = $$$config.clearContainer;
+ $$$config.createFragmentInstance;
+ $$$config.updateFragmentInstanceFiber;
+ $$$config.commitNewChildToFragmentInstance;
+ $$$config.deleteChildFromFragmentInstance;
+ var cloneInstance = $$$config.cloneInstance, createContainerChildSet = $$$config.createContainerChildSet, appendChildToContainerChildSet = $$$config.appendChildToContainerChildSet, finalizeContainerChildren = $$$config.finalizeContainerChildren, replaceContainerChildren = $$$config.replaceContainerChildren, cloneHiddenInstance = $$$config.cloneHiddenInstance, cloneHiddenTextInstance = $$$config.cloneHiddenTextInstance, isSuspenseInstancePending = $$$config.isSuspenseInstancePending, isSuspenseInstanceFallback = $$$config.isSuspenseInstanceFallback, getSuspenseInstanceFallbackErrorDetails = $$$config.getSuspenseInstanceFallbackErrorDetails, registerSuspenseInstanceRetry = $$$config.registerSuspenseInstanceRetry, canHydrateFormStateMarker = $$$config.canHydrateFormStateMarker, isFormStateMarkerMatching = $$$config.isFormStateMarkerMatching, getNextHydratableSibling = $$$config.getNextHydratableSibling, getNextHydratableSiblingAfterSingleton = $$$config.getNextHydratableSiblingAfterSingleton, getFirstHydratableChild = $$$config.getFirstHydratableChild, getFirstHydratableChildWithinContainer = $$$config.getFirstHydratableChildWithinContainer, getFirstHydratableChildWithinActivityInstance = $$$config.getFirstHydratableChildWithinActivityInstance, getFirstHydratableChildWithinSuspenseInstance = $$$config.getFirstHydratableChildWithinSuspenseInstance, getFirstHydratableChildWithinSingleton = $$$config.getFirstHydratableChildWithinSingleton, canHydrateInstance = $$$config.canHydrateInstance, canHydrateTextInstance = $$$config.canHydrateTextInstance, canHydrateActivityInstance = $$$config.canHydrateActivityInstance, canHydrateSuspenseInstance = $$$config.canHydrateSuspenseInstance, hydrateInstance = $$$config.hydrateInstance, hydrateTextInstance = $$$config.hydrateTextInstance, hydrateActivityInstance = $$$config.hydrateActivityInstance, hydrateSuspenseInstance = $$$config.hydrateSuspenseInstance, getNextHydratableInstanceAfterActivityInstance = $$$config.getNextHydratableInstanceAfterActivityInstance, getNextHydratableInstanceAfterSuspenseInstance = $$$config.getNextHydratableInstanceAfterSuspenseInstance, commitHydratedInstance = $$$config.commitHydratedInstance, commitHydratedContainer = $$$config.commitHydratedContainer, commitHydratedActivityInstance = $$$config.commitHydratedActivityInstance, commitHydratedSuspenseInstance = $$$config.commitHydratedSuspenseInstance, finalizeHydratedChildren = $$$config.finalizeHydratedChildren, flushHydrationEvents = $$$config.flushHydrationEvents;
+ $$$config.clearActivityBoundary;
+ var clearSuspenseBoundary = $$$config.clearSuspenseBoundary;
+ $$$config.clearActivityBoundaryFromContainer;
+ var clearSuspenseBoundaryFromContainer = $$$config.clearSuspenseBoundaryFromContainer, hideDehydratedBoundary = $$$config.hideDehydratedBoundary, unhideDehydratedBoundary = $$$config.unhideDehydratedBoundary, shouldDeleteUnhydratedTailInstances = $$$config.shouldDeleteUnhydratedTailInstances;
+ $$$config.diffHydratedPropsForDevWarnings;
+ $$$config.diffHydratedTextForDevWarnings;
+ $$$config.describeHydratableInstanceForDevWarnings;
+ var validateHydratableInstance = $$$config.validateHydratableInstance, validateHydratableTextInstance = $$$config.validateHydratableTextInstance, supportsResources = $$$config.supportsResources, isHostHoistableType = $$$config.isHostHoistableType, getHoistableRoot = $$$config.getHoistableRoot, getResource = $$$config.getResource, acquireResource = $$$config.acquireResource, releaseResource = $$$config.releaseResource, hydrateHoistable = $$$config.hydrateHoistable, mountHoistable = $$$config.mountHoistable, unmountHoistable = $$$config.unmountHoistable, createHoistableInstance = $$$config.createHoistableInstance, prepareToCommitHoistables = $$$config.prepareToCommitHoistables, mayResourceSuspendCommit = $$$config.mayResourceSuspendCommit, preloadResource = $$$config.preloadResource, suspendResource = $$$config.suspendResource, supportsSingletons = $$$config.supportsSingletons, resolveSingletonInstance = $$$config.resolveSingletonInstance, acquireSingletonInstance = $$$config.acquireSingletonInstance, releaseSingletonInstance = $$$config.releaseSingletonInstance, isHostSingletonType = $$$config.isHostSingletonType, isSingletonScope = $$$config.isSingletonScope, valueStack = [], index$jscomp$0 = -1, emptyContextObject = {}, clz32 = Math.clz32 ? Math.clz32 : clz32Fallback, log$1 = Math.log, LN2 = Math.LN2, nextTransitionUpdateLane = 256, nextTransitionDeferredLane = 262144, nextRetryLane = 4194304, scheduleCallback$3 = Scheduler2.unstable_scheduleCallback, cancelCallback$1 = Scheduler2.unstable_cancelCallback, shouldYield = Scheduler2.unstable_shouldYield, requestPaint = Scheduler2.unstable_requestPaint, now = Scheduler2.unstable_now, ImmediatePriority = Scheduler2.unstable_ImmediatePriority, UserBlockingPriority = Scheduler2.unstable_UserBlockingPriority, NormalPriority$1 = Scheduler2.unstable_NormalPriority, IdlePriority = Scheduler2.unstable_IdlePriority, log = Scheduler2.log, unstable_setDisableYieldValue = Scheduler2.unstable_setDisableYieldValue, rendererID = null, injectedHook = null, objectIs = "function" === typeof Object.is ? Object.is : is, reportGlobalError = "function" === typeof reportError ? reportError : function(error51) {
+ if ("object" === typeof window && "function" === typeof window.ErrorEvent) {
+ var event = new window.ErrorEvent("error", {
+ bubbles: true,
+ cancelable: true,
+ message: "object" === typeof error51 && null !== error51 && "string" === typeof error51.message ? String(error51.message) : String(error51),
+ error: error51
+ });
+ if (!window.dispatchEvent(event)) return;
+ } else if ("object" === typeof process && "function" === typeof process.emit) {
+ process.emit("uncaughtException", error51);
+ return;
+ }
+ console.error(error51);
+ }, hasOwnProperty2 = Object.prototype.hasOwnProperty, prefix, suffix, reentry = false, CapturedStacks = /* @__PURE__ */ new WeakMap(), forkStack = [], forkStackIndex = 0, treeForkProvider = null, treeForkCount = 0, idStack = [], idStackIndex = 0, treeContextProvider = null, treeContextId = 1, treeContextOverflow = "", contextStackCursor = createCursor(null), contextFiberStackCursor = createCursor(null), rootInstanceStackCursor = createCursor(null), hostTransitionProviderCursor = createCursor(null), hydrationParentFiber = null, nextHydratableInstance = null, isHydrating = false, hydrationErrors = null, rootOrSingletonContext = false, HydrationMismatchException = Error(formatProdErrorMessage(519)), valueCursor = createCursor(null), currentlyRenderingFiber$1 = null, lastContextDependency = null, AbortControllerLocal = "undefined" !== typeof AbortController ? AbortController : function() {
+ var listeners = [], signal = this.signal = {
+ aborted: false,
+ addEventListener: /* @__PURE__ */ __name(function(type2, listener) {
+ listeners.push(listener);
+ }, "addEventListener")
+ };
+ this.abort = function() {
+ signal.aborted = true;
+ listeners.forEach(function(listener) {
+ return listener();
+ });
+ };
+ }, scheduleCallback$2 = Scheduler2.unstable_scheduleCallback, NormalPriority = Scheduler2.unstable_NormalPriority, CacheContext = {
+ $$typeof: REACT_CONTEXT_TYPE,
+ Consumer: null,
+ Provider: null,
+ _currentValue: null,
+ _currentValue2: null,
+ _threadCount: 0
+ }, firstScheduledRoot = null, lastScheduledRoot = null, didScheduleMicrotask = false, mightHavePendingSyncWork = false, isFlushingWork = false, currentEventTransitionLane = 0, currentEntangledListeners = null, currentEntangledPendingCount = 0, currentEntangledLane = 0, currentEntangledActionThenable = null, prevOnStartTransitionFinish = ReactSharedInternals.S;
+ ReactSharedInternals.S = function(transition, returnValue) {
+ globalMostRecentTransitionTime = now();
+ "object" === typeof returnValue && null !== returnValue && "function" === typeof returnValue.then && entangleAsyncAction(transition, returnValue);
+ null !== prevOnStartTransitionFinish && prevOnStartTransitionFinish(transition, returnValue);
+ };
+ var resumedCache = createCursor(null), SuspenseException = Error(formatProdErrorMessage(460)), SuspenseyCommitException = Error(formatProdErrorMessage(474)), SuspenseActionException = Error(formatProdErrorMessage(542)), noopSuspenseyCommitThenable = { then: /* @__PURE__ */ __name(function() {
+ }, "then") }, suspendedThenable = null, thenableState$1 = null, thenableIndexCounter$1 = 0, reconcileChildFibers = createChildReconciler(true), mountChildFibers = createChildReconciler(false), concurrentQueues = [], concurrentQueuesIndex = 0, concurrentlyUpdatedLanes = 0, hasForceUpdate = false, didReadFromEntangledAsyncAction = false, currentTreeHiddenStackCursor = createCursor(null), prevEntangledRenderLanesCursor = createCursor(0), suspenseHandlerStackCursor = createCursor(null), shellBoundary = null, suspenseStackCursor = createCursor(0), renderLanes = 0, currentlyRenderingFiber = null, currentHook = null, workInProgressHook = null, didScheduleRenderPhaseUpdate = false, didScheduleRenderPhaseUpdateDuringThisPass = false, shouldDoubleInvokeUserFnsInHooksDEV = false, localIdCounter = 0, thenableIndexCounter = 0, thenableState = null, globalClientIdCounter = 0, ContextOnlyDispatcher = {
+ readContext,
+ use,
+ useCallback: throwInvalidHookError,
+ useContext: throwInvalidHookError,
+ useEffect: throwInvalidHookError,
+ useImperativeHandle: throwInvalidHookError,
+ useLayoutEffect: throwInvalidHookError,
+ useInsertionEffect: throwInvalidHookError,
+ useMemo: throwInvalidHookError,
+ useReducer: throwInvalidHookError,
+ useRef: throwInvalidHookError,
+ useState: throwInvalidHookError,
+ useDebugValue: throwInvalidHookError,
+ useDeferredValue: throwInvalidHookError,
+ useTransition: throwInvalidHookError,
+ useSyncExternalStore: throwInvalidHookError,
+ useId: throwInvalidHookError,
+ useHostTransitionStatus: throwInvalidHookError,
+ useFormState: throwInvalidHookError,
+ useActionState: throwInvalidHookError,
+ useOptimistic: throwInvalidHookError,
+ useMemoCache: throwInvalidHookError,
+ useCacheRefresh: throwInvalidHookError
+ };
+ ContextOnlyDispatcher.useEffectEvent = throwInvalidHookError;
+ var HooksDispatcherOnMount = {
+ readContext,
+ use,
+ useCallback: /* @__PURE__ */ __name(function(callback, deps) {
+ mountWorkInProgressHook().memoizedState = [
+ callback,
+ void 0 === deps ? null : deps
+ ];
+ return callback;
+ }, "useCallback"),
+ useContext: readContext,
+ useEffect: mountEffect,
+ useImperativeHandle: /* @__PURE__ */ __name(function(ref, create3, deps) {
+ deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null;
+ mountEffectImpl(
+ 4194308,
+ 4,
+ imperativeHandleEffect.bind(null, create3, ref),
+ deps
+ );
+ }, "useImperativeHandle"),
+ useLayoutEffect: /* @__PURE__ */ __name(function(create3, deps) {
+ return mountEffectImpl(4194308, 4, create3, deps);
+ }, "useLayoutEffect"),
+ useInsertionEffect: /* @__PURE__ */ __name(function(create3, deps) {
+ mountEffectImpl(4, 2, create3, deps);
+ }, "useInsertionEffect"),
+ useMemo: /* @__PURE__ */ __name(function(nextCreate, deps) {
+ var hook = mountWorkInProgressHook();
+ deps = void 0 === deps ? null : deps;
+ var nextValue = nextCreate();
+ if (shouldDoubleInvokeUserFnsInHooksDEV) {
+ setIsStrictModeForDevtools(true);
+ try {
+ nextCreate();
+ } finally {
+ setIsStrictModeForDevtools(false);
+ }
+ }
+ hook.memoizedState = [nextValue, deps];
+ return nextValue;
+ }, "useMemo"),
+ useReducer: /* @__PURE__ */ __name(function(reducer, initialArg, init) {
+ var hook = mountWorkInProgressHook();
+ if (void 0 !== init) {
+ var initialState = init(initialArg);
+ if (shouldDoubleInvokeUserFnsInHooksDEV) {
+ setIsStrictModeForDevtools(true);
+ try {
+ init(initialArg);
+ } finally {
+ setIsStrictModeForDevtools(false);
+ }
+ }
+ } else initialState = initialArg;
+ hook.memoizedState = hook.baseState = initialState;
+ reducer = {
+ pending: null,
+ lanes: 0,
+ dispatch: null,
+ lastRenderedReducer: reducer,
+ lastRenderedState: initialState
+ };
+ hook.queue = reducer;
+ reducer = reducer.dispatch = dispatchReducerAction.bind(
+ null,
+ currentlyRenderingFiber,
+ reducer
+ );
+ return [hook.memoizedState, reducer];
+ }, "useReducer"),
+ useRef: /* @__PURE__ */ __name(function(initialValue) {
+ var hook = mountWorkInProgressHook();
+ initialValue = { current: initialValue };
+ return hook.memoizedState = initialValue;
+ }, "useRef"),
+ useState: /* @__PURE__ */ __name(function(initialState) {
+ initialState = mountStateImpl(initialState);
+ var queue = initialState.queue, dispatch = dispatchSetState.bind(
+ null,
+ currentlyRenderingFiber,
+ queue
+ );
+ queue.dispatch = dispatch;
+ return [initialState.memoizedState, dispatch];
+ }, "useState"),
+ useDebugValue: mountDebugValue,
+ useDeferredValue: /* @__PURE__ */ __name(function(value, initialValue) {
+ var hook = mountWorkInProgressHook();
+ return mountDeferredValueImpl(hook, value, initialValue);
+ }, "useDeferredValue"),
+ useTransition: /* @__PURE__ */ __name(function() {
+ var stateHook = mountStateImpl(false);
+ stateHook = startTransition.bind(
+ null,
+ currentlyRenderingFiber,
+ stateHook.queue,
+ true,
+ false
+ );
+ mountWorkInProgressHook().memoizedState = stateHook;
+ return [false, stateHook];
+ }, "useTransition"),
+ useSyncExternalStore: /* @__PURE__ */ __name(function(subscribe, getSnapshot, getServerSnapshot) {
+ var fiber = currentlyRenderingFiber, hook = mountWorkInProgressHook();
+ if (isHydrating) {
+ if (void 0 === getServerSnapshot)
+ throw Error(formatProdErrorMessage(407));
+ getServerSnapshot = getServerSnapshot();
+ } else {
+ getServerSnapshot = getSnapshot();
+ if (null === workInProgressRoot)
+ throw Error(formatProdErrorMessage(349));
+ 0 !== (workInProgressRootRenderLanes & 127) || pushStoreConsistencyCheck(fiber, getSnapshot, getServerSnapshot);
+ }
+ hook.memoizedState = getServerSnapshot;
+ var inst = { value: getServerSnapshot, getSnapshot };
+ hook.queue = inst;
+ mountEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [
+ subscribe
+ ]);
+ fiber.flags |= 2048;
+ pushSimpleEffect(
+ 9,
+ { destroy: void 0 },
+ updateStoreInstance.bind(
+ null,
+ fiber,
+ inst,
+ getServerSnapshot,
+ getSnapshot
+ ),
+ null
+ );
+ return getServerSnapshot;
+ }, "useSyncExternalStore"),
+ useId: /* @__PURE__ */ __name(function() {
+ var hook = mountWorkInProgressHook(), identifierPrefix = workInProgressRoot.identifierPrefix;
+ if (isHydrating) {
+ var JSCompiler_inline_result = treeContextOverflow;
+ var idWithLeadingBit = treeContextId;
+ JSCompiler_inline_result = (idWithLeadingBit & ~(1 << 32 - clz32(idWithLeadingBit) - 1)).toString(32) + JSCompiler_inline_result;
+ identifierPrefix = "_" + identifierPrefix + "R_" + JSCompiler_inline_result;
+ JSCompiler_inline_result = localIdCounter++;
+ 0 < JSCompiler_inline_result && (identifierPrefix += "H" + JSCompiler_inline_result.toString(32));
+ identifierPrefix += "_";
+ } else
+ JSCompiler_inline_result = globalClientIdCounter++, identifierPrefix = "_" + identifierPrefix + "r_" + JSCompiler_inline_result.toString(32) + "_";
+ return hook.memoizedState = identifierPrefix;
+ }, "useId"),
+ useHostTransitionStatus,
+ useFormState: mountActionState,
+ useActionState: mountActionState,
+ useOptimistic: /* @__PURE__ */ __name(function(passthrough) {
+ var hook = mountWorkInProgressHook();
+ hook.memoizedState = hook.baseState = passthrough;
+ var queue = {
+ pending: null,
+ lanes: 0,
+ dispatch: null,
+ lastRenderedReducer: null,
+ lastRenderedState: null
+ };
+ hook.queue = queue;
+ hook = dispatchOptimisticSetState.bind(
+ null,
+ currentlyRenderingFiber,
+ true,
+ queue
+ );
+ queue.dispatch = hook;
+ return [passthrough, hook];
+ }, "useOptimistic"),
+ useMemoCache,
+ useCacheRefresh: /* @__PURE__ */ __name(function() {
+ return mountWorkInProgressHook().memoizedState = refreshCache.bind(
+ null,
+ currentlyRenderingFiber
+ );
+ }, "useCacheRefresh"),
+ useEffectEvent: /* @__PURE__ */ __name(function(callback) {
+ var hook = mountWorkInProgressHook(), ref = { impl: callback };
+ hook.memoizedState = ref;
+ return function() {
+ if (0 !== (executionContext & 2))
+ throw Error(formatProdErrorMessage(440));
+ return ref.impl.apply(void 0, arguments);
+ };
+ }, "useEffectEvent")
+ }, HooksDispatcherOnUpdate = {
+ readContext,
+ use,
+ useCallback: updateCallback,
+ useContext: readContext,
+ useEffect: updateEffect,
+ useImperativeHandle: updateImperativeHandle,
+ useInsertionEffect: updateInsertionEffect,
+ useLayoutEffect: updateLayoutEffect,
+ useMemo: updateMemo,
+ useReducer: updateReducer,
+ useRef: updateRef,
+ useState: /* @__PURE__ */ __name(function() {
+ return updateReducer(basicStateReducer);
+ }, "useState"),
+ useDebugValue: mountDebugValue,
+ useDeferredValue: /* @__PURE__ */ __name(function(value, initialValue) {
+ var hook = updateWorkInProgressHook();
+ return updateDeferredValueImpl(
+ hook,
+ currentHook.memoizedState,
+ value,
+ initialValue
+ );
+ }, "useDeferredValue"),
+ useTransition: /* @__PURE__ */ __name(function() {
+ var booleanOrThenable = updateReducer(basicStateReducer)[0], start = updateWorkInProgressHook().memoizedState;
+ return [
+ "boolean" === typeof booleanOrThenable ? booleanOrThenable : useThenable(booleanOrThenable),
+ start
+ ];
+ }, "useTransition"),
+ useSyncExternalStore: updateSyncExternalStore,
+ useId: updateId,
+ useHostTransitionStatus,
+ useFormState: updateActionState,
+ useActionState: updateActionState,
+ useOptimistic: /* @__PURE__ */ __name(function(passthrough, reducer) {
+ var hook = updateWorkInProgressHook();
+ return updateOptimisticImpl(hook, currentHook, passthrough, reducer);
+ }, "useOptimistic"),
+ useMemoCache,
+ useCacheRefresh: updateRefresh
+ };
+ HooksDispatcherOnUpdate.useEffectEvent = updateEvent;
+ var HooksDispatcherOnRerender = {
+ readContext,
+ use,
+ useCallback: updateCallback,
+ useContext: readContext,
+ useEffect: updateEffect,
+ useImperativeHandle: updateImperativeHandle,
+ useInsertionEffect: updateInsertionEffect,
+ useLayoutEffect: updateLayoutEffect,
+ useMemo: updateMemo,
+ useReducer: rerenderReducer,
+ useRef: updateRef,
+ useState: /* @__PURE__ */ __name(function() {
+ return rerenderReducer(basicStateReducer);
+ }, "useState"),
+ useDebugValue: mountDebugValue,
+ useDeferredValue: /* @__PURE__ */ __name(function(value, initialValue) {
+ var hook = updateWorkInProgressHook();
+ return null === currentHook ? mountDeferredValueImpl(hook, value, initialValue) : updateDeferredValueImpl(
+ hook,
+ currentHook.memoizedState,
+ value,
+ initialValue
+ );
+ }, "useDeferredValue"),
+ useTransition: /* @__PURE__ */ __name(function() {
+ var booleanOrThenable = rerenderReducer(basicStateReducer)[0], start = updateWorkInProgressHook().memoizedState;
+ return [
+ "boolean" === typeof booleanOrThenable ? booleanOrThenable : useThenable(booleanOrThenable),
+ start
+ ];
+ }, "useTransition"),
+ useSyncExternalStore: updateSyncExternalStore,
+ useId: updateId,
+ useHostTransitionStatus,
+ useFormState: rerenderActionState,
+ useActionState: rerenderActionState,
+ useOptimistic: /* @__PURE__ */ __name(function(passthrough, reducer) {
+ var hook = updateWorkInProgressHook();
+ if (null !== currentHook)
+ return updateOptimisticImpl(hook, currentHook, passthrough, reducer);
+ hook.baseState = passthrough;
+ return [passthrough, hook.queue.dispatch];
+ }, "useOptimistic"),
+ useMemoCache,
+ useCacheRefresh: updateRefresh
+ };
+ HooksDispatcherOnRerender.useEffectEvent = updateEvent;
+ var classComponentUpdater = {
+ enqueueSetState: /* @__PURE__ */ __name(function(inst, payload, callback) {
+ inst = inst._reactInternals;
+ var lane = requestUpdateLane(), update = createUpdate(lane);
+ update.payload = payload;
+ void 0 !== callback && null !== callback && (update.callback = callback);
+ payload = enqueueUpdate(inst, update, lane);
+ null !== payload && (scheduleUpdateOnFiber(payload, inst, lane), entangleTransitions(payload, inst, lane));
+ }, "enqueueSetState"),
+ enqueueReplaceState: /* @__PURE__ */ __name(function(inst, payload, callback) {
+ inst = inst._reactInternals;
+ var lane = requestUpdateLane(), update = createUpdate(lane);
+ update.tag = 1;
+ update.payload = payload;
+ void 0 !== callback && null !== callback && (update.callback = callback);
+ payload = enqueueUpdate(inst, update, lane);
+ null !== payload && (scheduleUpdateOnFiber(payload, inst, lane), entangleTransitions(payload, inst, lane));
+ }, "enqueueReplaceState"),
+ enqueueForceUpdate: /* @__PURE__ */ __name(function(inst, callback) {
+ inst = inst._reactInternals;
+ var lane = requestUpdateLane(), update = createUpdate(lane);
+ update.tag = 2;
+ void 0 !== callback && null !== callback && (update.callback = callback);
+ callback = enqueueUpdate(inst, update, lane);
+ null !== callback && (scheduleUpdateOnFiber(callback, inst, lane), entangleTransitions(callback, inst, lane));
+ }, "enqueueForceUpdate")
+ }, SelectiveHydrationException = Error(formatProdErrorMessage(461)), didReceiveUpdate = false, SUSPENDED_MARKER = {
+ dehydrated: null,
+ treeContext: null,
+ retryLane: 0,
+ hydrationErrors: null
+ }, offscreenSubtreeIsHidden = false, offscreenSubtreeWasHidden = false, needsFormReset = false, PossiblyWeakSet = "function" === typeof WeakSet ? WeakSet : Set, nextEffect = null, hostParent = null, hostParentIsContainer = false, currentHoistableRoot = null, suspenseyCommitFlag = 8192, DefaultAsyncDispatcher = {
+ getCacheForType: /* @__PURE__ */ __name(function(resourceType) {
+ var cache3 = readContext(CacheContext), cacheForType = cache3.data.get(resourceType);
+ void 0 === cacheForType && (cacheForType = resourceType(), cache3.data.set(resourceType, cacheForType));
+ return cacheForType;
+ }, "getCacheForType"),
+ cacheSignal: /* @__PURE__ */ __name(function() {
+ return readContext(CacheContext).controller.signal;
+ }, "cacheSignal")
+ }, COMPONENT_TYPE = 0, HAS_PSEUDO_CLASS_TYPE = 1, ROLE_TYPE = 2, TEST_NAME_TYPE = 3, TEXT_TYPE = 4;
+ if ("function" === typeof Symbol && Symbol.for) {
+ var symbolFor = Symbol.for;
+ COMPONENT_TYPE = symbolFor("selector.component");
+ HAS_PSEUDO_CLASS_TYPE = symbolFor("selector.has_pseudo_class");
+ ROLE_TYPE = symbolFor("selector.role");
+ TEST_NAME_TYPE = symbolFor("selector.test_id");
+ TEXT_TYPE = symbolFor("selector.text");
+ }
+ var PossiblyWeakMap = "function" === typeof WeakMap ? WeakMap : Map, executionContext = 0, workInProgressRoot = null, workInProgress = null, workInProgressRootRenderLanes = 0, workInProgressSuspendedReason = 0, workInProgressThrownValue = null, workInProgressRootDidSkipSuspendedSiblings = false, workInProgressRootIsPrerendering = false, workInProgressRootDidAttachPingListener = false, entangledRenderLanes = 0, workInProgressRootExitStatus = 0, workInProgressRootSkippedLanes = 0, workInProgressRootInterleavedUpdatedLanes = 0, workInProgressRootPingedLanes = 0, workInProgressDeferredLane = 0, workInProgressSuspendedRetryLanes = 0, workInProgressRootConcurrentErrors = null, workInProgressRootRecoverableErrors = null, workInProgressRootDidIncludeRecursiveRenderUpdate = false, globalMostRecentFallbackTime = 0, globalMostRecentTransitionTime = 0, workInProgressRootRenderTargetTime = Infinity, workInProgressTransitions = null, legacyErrorBoundariesThatAlreadyFailed = null, pendingEffectsStatus = 0, pendingEffectsRoot = null, pendingFinishedWork = null, pendingEffectsLanes = 0, pendingEffectsRemainingLanes = 0, pendingPassiveTransitions = null, pendingRecoverableErrors = null, nestedUpdateCount = 0, rootWithNestedUpdates = null;
+ exports3.attemptContinuousHydration = function(fiber) {
+ if (13 === fiber.tag || 31 === fiber.tag) {
+ var root = enqueueConcurrentRenderForLane(fiber, 67108864);
+ null !== root && scheduleUpdateOnFiber(root, fiber, 67108864);
+ markRetryLaneIfNotHydrated(fiber, 67108864);
+ }
+ };
+ exports3.attemptHydrationAtCurrentPriority = function(fiber) {
+ if (13 === fiber.tag || 31 === fiber.tag) {
+ var lane = requestUpdateLane();
+ lane = getBumpedLaneForHydrationByLane(lane);
+ var root = enqueueConcurrentRenderForLane(fiber, lane);
+ null !== root && scheduleUpdateOnFiber(root, fiber, lane);
+ markRetryLaneIfNotHydrated(fiber, lane);
+ }
+ };
+ exports3.attemptSynchronousHydration = function(fiber) {
+ switch (fiber.tag) {
+ case 3:
+ fiber = fiber.stateNode;
+ if (fiber.current.memoizedState.isDehydrated) {
+ var lanes = getHighestPriorityLanes(fiber.pendingLanes);
+ if (0 !== lanes) {
+ fiber.pendingLanes |= 2;
+ for (fiber.entangledLanes |= 2; lanes; ) {
+ var lane = 1 << 31 - clz32(lanes);
+ fiber.entanglements[1] |= lane;
+ lanes &= ~lane;
+ }
+ ensureRootIsScheduled(fiber);
+ 0 === (executionContext & 6) && (workInProgressRootRenderTargetTime = now() + 500, flushSyncWorkAcrossRoots_impl(0, false));
+ }
+ }
+ break;
+ case 31:
+ case 13:
+ lanes = enqueueConcurrentRenderForLane(fiber, 2), null !== lanes && scheduleUpdateOnFiber(lanes, fiber, 2), flushSyncWork(), markRetryLaneIfNotHydrated(fiber, 2);
+ }
+ };
+ exports3.batchedUpdates = function(fn, a) {
+ return fn(a);
+ };
+ exports3.createComponentSelector = function(component) {
+ return { $$typeof: COMPONENT_TYPE, value: component };
+ };
+ exports3.createContainer = function(containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onUncaughtError, onCaughtError, onRecoverableError, onDefaultTransitionIndicator) {
+ return createFiberRoot(
+ containerInfo,
+ tag,
+ false,
+ null,
+ hydrationCallbacks,
+ isStrictMode,
+ identifierPrefix,
+ null,
+ onUncaughtError,
+ onCaughtError,
+ onRecoverableError,
+ onDefaultTransitionIndicator
+ );
+ };
+ exports3.createHasPseudoClassSelector = function(selectors) {
+ return { $$typeof: HAS_PSEUDO_CLASS_TYPE, value: selectors };
+ };
+ exports3.createHydrationContainer = function(initialChildren, callback, containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onUncaughtError, onCaughtError, onRecoverableError, onDefaultTransitionIndicator, transitionCallbacks, formState) {
+ initialChildren = createFiberRoot(
+ containerInfo,
+ tag,
+ true,
+ initialChildren,
+ hydrationCallbacks,
+ isStrictMode,
+ identifierPrefix,
+ formState,
+ onUncaughtError,
+ onCaughtError,
+ onRecoverableError,
+ onDefaultTransitionIndicator
+ );
+ initialChildren.context = getContextForSubtree(null);
+ containerInfo = initialChildren.current;
+ tag = requestUpdateLane();
+ tag = getBumpedLaneForHydrationByLane(tag);
+ hydrationCallbacks = createUpdate(tag);
+ hydrationCallbacks.callback = void 0 !== callback && null !== callback ? callback : null;
+ enqueueUpdate(containerInfo, hydrationCallbacks, tag);
+ callback = tag;
+ initialChildren.current.lanes = callback;
+ markRootUpdated$1(initialChildren, callback);
+ ensureRootIsScheduled(initialChildren);
+ return initialChildren;
+ };
+ exports3.createPortal = function(children, containerInfo, implementation) {
+ var key = 3 < arguments.length && void 0 !== arguments[3] ? arguments[3] : null;
+ return {
+ $$typeof: REACT_PORTAL_TYPE,
+ key: null == key ? null : "" + key,
+ children,
+ containerInfo,
+ implementation
+ };
+ };
+ exports3.createRoleSelector = function(role) {
+ return { $$typeof: ROLE_TYPE, value: role };
+ };
+ exports3.createTestNameSelector = function(id) {
+ return { $$typeof: TEST_NAME_TYPE, value: id };
+ };
+ exports3.createTextSelector = function(text) {
+ return { $$typeof: TEXT_TYPE, value: text };
+ };
+ exports3.defaultOnCaughtError = function(error51) {
+ console.error(error51);
+ };
+ exports3.defaultOnRecoverableError = function(error51) {
+ reportGlobalError(error51);
+ };
+ exports3.defaultOnUncaughtError = function(error51) {
+ reportGlobalError(error51);
+ };
+ exports3.deferredUpdates = function(fn) {
+ var prevTransition = ReactSharedInternals.T, previousPriority = getCurrentUpdatePriority();
+ try {
+ return setCurrentUpdatePriority(32), ReactSharedInternals.T = null, fn();
+ } finally {
+ setCurrentUpdatePriority(previousPriority), ReactSharedInternals.T = prevTransition;
+ }
+ };
+ exports3.discreteUpdates = function(fn, a, b, c, d) {
+ var prevTransition = ReactSharedInternals.T, previousPriority = getCurrentUpdatePriority();
+ try {
+ return setCurrentUpdatePriority(2), ReactSharedInternals.T = null, fn(a, b, c, d);
+ } finally {
+ setCurrentUpdatePriority(previousPriority), ReactSharedInternals.T = prevTransition, 0 === executionContext && (workInProgressRootRenderTargetTime = now() + 500);
+ }
+ };
+ exports3.findAllNodes = findAllNodes;
+ exports3.findBoundingRects = function(hostRoot, selectors) {
+ if (!supportsTestSelectors) throw Error(formatProdErrorMessage(363));
+ selectors = findAllNodes(hostRoot, selectors);
+ hostRoot = [];
+ for (var i = 0; i < selectors.length; i++)
+ hostRoot.push(getBoundingRect(selectors[i]));
+ for (selectors = hostRoot.length - 1; 0 < selectors; selectors--) {
+ i = hostRoot[selectors];
+ for (var targetLeft = i.x, targetRight = targetLeft + i.width, targetTop = i.y, targetBottom = targetTop + i.height, j = selectors - 1; 0 <= j; j--)
+ if (selectors !== j) {
+ var otherRect = hostRoot[j], otherLeft = otherRect.x, otherRight = otherLeft + otherRect.width, otherTop = otherRect.y, otherBottom = otherTop + otherRect.height;
+ if (targetLeft >= otherLeft && targetTop >= otherTop && targetRight <= otherRight && targetBottom <= otherBottom) {
+ hostRoot.splice(selectors, 1);
+ break;
+ } else if (!(targetLeft !== otherLeft || i.width !== otherRect.width || otherBottom < targetTop || otherTop > targetBottom)) {
+ otherTop > targetTop && (otherRect.height += otherTop - targetTop, otherRect.y = targetTop);
+ otherBottom < targetBottom && (otherRect.height = targetBottom - otherTop);
+ hostRoot.splice(selectors, 1);
+ break;
+ } else if (!(targetTop !== otherTop || i.height !== otherRect.height || otherRight < targetLeft || otherLeft > targetRight)) {
+ otherLeft > targetLeft && (otherRect.width += otherLeft - targetLeft, otherRect.x = targetLeft);
+ otherRight < targetRight && (otherRect.width = targetRight - otherLeft);
+ hostRoot.splice(selectors, 1);
+ break;
+ }
+ }
+ }
+ return hostRoot;
+ };
+ exports3.findHostInstance = findHostInstance;
+ exports3.findHostInstanceWithNoPortals = function(fiber) {
+ fiber = findCurrentFiberUsingSlowPath(fiber);
+ fiber = null !== fiber ? findCurrentHostFiberWithNoPortalsImpl(fiber) : null;
+ return null === fiber ? null : getPublicInstance(fiber.stateNode);
+ };
+ exports3.findHostInstanceWithWarning = function(component) {
+ return findHostInstance(component);
+ };
+ exports3.flushPassiveEffects = flushPendingEffects;
+ exports3.flushSyncFromReconciler = function(fn) {
+ var prevExecutionContext = executionContext;
+ executionContext |= 1;
+ var prevTransition = ReactSharedInternals.T, previousPriority = getCurrentUpdatePriority();
+ try {
+ if (setCurrentUpdatePriority(2), ReactSharedInternals.T = null, fn)
+ return fn();
+ } finally {
+ setCurrentUpdatePriority(previousPriority), ReactSharedInternals.T = prevTransition, executionContext = prevExecutionContext, 0 === (executionContext & 6) && flushSyncWorkAcrossRoots_impl(0, false);
+ }
+ };
+ exports3.flushSyncWork = flushSyncWork;
+ exports3.focusWithin = function(hostRoot, selectors) {
+ if (!supportsTestSelectors) throw Error(formatProdErrorMessage(363));
+ hostRoot = findFiberRootForHostRoot(hostRoot);
+ selectors = findPaths(hostRoot, selectors);
+ selectors = Array.from(selectors);
+ for (hostRoot = 0; hostRoot < selectors.length; ) {
+ var fiber = selectors[hostRoot++], tag = fiber.tag;
+ if (!isHiddenSubtree(fiber)) {
+ if ((5 === tag || 26 === tag || 27 === tag) && setFocusIfFocusable(fiber.stateNode))
+ return true;
+ for (fiber = fiber.child; null !== fiber; )
+ selectors.push(fiber), fiber = fiber.sibling;
+ }
+ }
+ return false;
+ };
+ exports3.getFindAllNodesFailureDescription = function(hostRoot, selectors) {
+ if (!supportsTestSelectors) throw Error(formatProdErrorMessage(363));
+ var maxSelectorIndex = 0, matchedNames = [];
+ hostRoot = [findFiberRootForHostRoot(hostRoot), 0];
+ for (var index = 0; index < hostRoot.length; ) {
+ var fiber = hostRoot[index++], tag = fiber.tag, selectorIndex = hostRoot[index++], selector = selectors[selectorIndex];
+ if (5 !== tag && 26 !== tag && 27 !== tag || !isHiddenSubtree(fiber)) {
+ if (matchSelector(fiber, selector) && (matchedNames.push(selectorToString(selector)), selectorIndex++, selectorIndex > maxSelectorIndex && (maxSelectorIndex = selectorIndex)), selectorIndex < selectors.length)
+ for (fiber = fiber.child; null !== fiber; )
+ hostRoot.push(fiber, selectorIndex), fiber = fiber.sibling;
+ }
+ }
+ if (maxSelectorIndex < selectors.length) {
+ for (hostRoot = []; maxSelectorIndex < selectors.length; maxSelectorIndex++)
+ hostRoot.push(selectorToString(selectors[maxSelectorIndex]));
+ return "findAllNodes was able to match part of the selector:\n " + (matchedNames.join(" > ") + "\n\nNo matching component was found for:\n ") + hostRoot.join(" > ");
+ }
+ return null;
+ };
+ exports3.getPublicRootInstance = function(container) {
+ container = container.current;
+ if (!container.child) return null;
+ switch (container.child.tag) {
+ case 27:
+ case 5:
+ return getPublicInstance(container.child.stateNode);
+ default:
+ return container.child.stateNode;
+ }
+ };
+ exports3.injectIntoDevTools = function() {
+ var internals = {
+ bundleType: 0,
+ version: rendererVersion,
+ rendererPackageName,
+ currentDispatcherRef: ReactSharedInternals,
+ reconcilerVersion: "19.2.0"
+ };
+ null !== extraDevToolsConfig && (internals.rendererConfig = extraDevToolsConfig);
+ if ("undefined" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__) internals = false;
+ else {
+ var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
+ if (hook.isDisabled || !hook.supportsFiber) internals = true;
+ else {
+ try {
+ rendererID = hook.inject(internals), injectedHook = hook;
+ } catch (err) {
+ }
+ internals = hook.checkDCE ? true : false;
+ }
+ }
+ return internals;
+ };
+ exports3.isAlreadyRendering = function() {
+ return 0 !== (executionContext & 6);
+ };
+ exports3.observeVisibleRects = function(hostRoot, selectors, callback, options2) {
+ if (!supportsTestSelectors) throw Error(formatProdErrorMessage(363));
+ hostRoot = findAllNodes(hostRoot, selectors);
+ var disconnect = setupIntersectionObserver(
+ hostRoot,
+ callback,
+ options2
+ ).disconnect;
+ return {
+ disconnect: /* @__PURE__ */ __name(function() {
+ disconnect();
+ }, "disconnect")
+ };
+ };
+ exports3.shouldError = function() {
+ return null;
+ };
+ exports3.shouldSuspend = function() {
+ return false;
+ };
+ exports3.startHostTransition = function(formFiber, pendingState, action, formData) {
+ if (5 !== formFiber.tag) throw Error(formatProdErrorMessage(476));
+ var queue = ensureFormComponentIsStateful(formFiber).queue;
+ startTransition(
+ formFiber,
+ queue,
+ pendingState,
+ NotPendingTransition,
+ null === action ? noop3 : function() {
+ var stateHook = ensureFormComponentIsStateful(formFiber);
+ null === stateHook.next && (stateHook = formFiber.alternate.memoizedState);
+ dispatchSetStateInternal(
+ formFiber,
+ stateHook.next.queue,
+ {},
+ requestUpdateLane()
+ );
+ return action(formData);
+ }
+ );
+ };
+ exports3.updateContainer = function(element, container, parentComponent, callback) {
+ var current = container.current, lane = requestUpdateLane();
+ updateContainerImpl(
+ current,
+ lane,
+ element,
+ container,
+ parentComponent,
+ callback
+ );
+ return lane;
+ };
+ exports3.updateContainerSync = function(element, container, parentComponent, callback) {
+ updateContainerImpl(
+ container.current,
+ 2,
+ element,
+ container,
+ parentComponent,
+ callback
+ );
+ return 2;
+ };
+ return exports3;
+ };
+ module2.exports.default = module2.exports;
+ Object.defineProperty(module2.exports, "__esModule", { value: true });
+ }
+});
+
+// node_modules/react-reconciler/index.js
+var require_react_reconciler = __commonJS({
+ "node_modules/react-reconciler/index.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ if (true) {
+ module2.exports = require_react_reconciler_production();
+ } else {
+ module2.exports = null;
+ }
+ }
+});
+
+// node_modules/mimic-fn/index.js
+var require_mimic_fn = __commonJS({
+ "node_modules/mimic-fn/index.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var mimicFn = /* @__PURE__ */ __name((to, from) => {
+ for (const prop of Reflect.ownKeys(from)) {
+ Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop));
+ }
+ return to;
+ }, "mimicFn");
+ module2.exports = mimicFn;
+ module2.exports.default = mimicFn;
+ }
+});
+
+// node_modules/onetime/index.js
+var require_onetime = __commonJS({
+ "node_modules/onetime/index.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var mimicFn = require_mimic_fn();
+ var calledFunctions = /* @__PURE__ */ new WeakMap();
+ var onetime2 = /* @__PURE__ */ __name((function_, options2 = {}) => {
+ if (typeof function_ !== "function") {
+ throw new TypeError("Expected a function");
+ }
+ let returnValue;
+ let callCount = 0;
+ const functionName = function_.displayName || function_.name || "";
+ const onetime3 = /* @__PURE__ */ __name(function(...arguments_) {
+ calledFunctions.set(onetime3, ++callCount);
+ if (callCount === 1) {
+ returnValue = function_.apply(this, arguments_);
+ function_ = null;
+ } else if (options2.throw === true) {
+ throw new Error(`Function \`${functionName}\` can only be called once`);
+ }
+ return returnValue;
+ }, "onetime");
+ mimicFn(onetime3, function_);
+ calledFunctions.set(onetime3, callCount);
+ return onetime3;
+ }, "onetime");
+ module2.exports = onetime2;
+ module2.exports.default = onetime2;
+ module2.exports.callCount = (function_) => {
+ if (!calledFunctions.has(function_)) {
+ throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);
+ }
+ return calledFunctions.get(function_);
+ };
+ }
+});
+
+// node_modules/stack-utils/node_modules/escape-string-regexp/index.js
+var require_escape_string_regexp = __commonJS({
+ "node_modules/stack-utils/node_modules/escape-string-regexp/index.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var matchOperatorsRegex = /[|\\{}()[\]^$+*?.-]/g;
+ module2.exports = (string4) => {
+ if (typeof string4 !== "string") {
+ throw new TypeError("Expected a string");
+ }
+ return string4.replace(matchOperatorsRegex, "\\$&");
+ };
+ }
+});
+
+// node_modules/stack-utils/index.js
+var require_stack_utils = __commonJS({
+ "node_modules/stack-utils/index.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var escapeStringRegexp = require_escape_string_regexp();
+ var cwd2 = typeof process === "object" && process && typeof process.cwd === "function" ? process.cwd() : ".";
+ var natives = [].concat(
+ __require("module").builtinModules,
+ "bootstrap_node",
+ "node"
+ ).map((n) => new RegExp(`(?:\\((?:node:)?${n}(?:\\.js)?:\\d+:\\d+\\)$|^\\s*at (?:node:)?${n}(?:\\.js)?:\\d+:\\d+$)`));
+ natives.push(
+ /\((?:node:)?internal\/[^:]+:\d+:\d+\)$/,
+ /\s*at (?:node:)?internal\/[^:]+:\d+:\d+$/,
+ /\/\.node-spawn-wrap-\w+-\w+\/node:\d+:\d+\)?$/
+ );
+ var StackUtils2 = class _StackUtils {
+ static {
+ __name(this, "StackUtils");
+ }
+ constructor(opts) {
+ opts = {
+ ignoredPackages: [],
+ ...opts
+ };
+ if ("internals" in opts === false) {
+ opts.internals = _StackUtils.nodeInternals();
+ }
+ if ("cwd" in opts === false) {
+ opts.cwd = cwd2;
+ }
+ this._cwd = opts.cwd.replace(/\\/g, "/");
+ this._internals = [].concat(
+ opts.internals,
+ ignoredPackagesRegExp(opts.ignoredPackages)
+ );
+ this._wrapCallSite = opts.wrapCallSite || false;
+ }
+ static nodeInternals() {
+ return [...natives];
+ }
+ clean(stack, indent = 0) {
+ indent = " ".repeat(indent);
+ if (!Array.isArray(stack)) {
+ stack = stack.split("\n");
+ }
+ if (!/^\s*at /.test(stack[0]) && /^\s*at /.test(stack[1])) {
+ stack = stack.slice(1);
+ }
+ let outdent = false;
+ let lastNonAtLine = null;
+ const result = [];
+ stack.forEach((st) => {
+ st = st.replace(/\\/g, "/");
+ if (this._internals.some((internal) => internal.test(st))) {
+ return;
+ }
+ const isAtLine = /^\s*at /.test(st);
+ if (outdent) {
+ st = st.trimEnd().replace(/^(\s+)at /, "$1");
+ } else {
+ st = st.trim();
+ if (isAtLine) {
+ st = st.slice(3);
+ }
+ }
+ st = st.replace(`${this._cwd}/`, "");
+ if (st) {
+ if (isAtLine) {
+ if (lastNonAtLine) {
+ result.push(lastNonAtLine);
+ lastNonAtLine = null;
+ }
+ result.push(st);
+ } else {
+ outdent = true;
+ lastNonAtLine = st;
+ }
+ }
+ });
+ return result.map((line) => `${indent}${line}
+`).join("");
+ }
+ captureString(limit2, fn = this.captureString) {
+ if (typeof limit2 === "function") {
+ fn = limit2;
+ limit2 = Infinity;
+ }
+ const { stackTraceLimit } = Error;
+ if (limit2) {
+ Error.stackTraceLimit = limit2;
+ }
+ const obj = {};
+ Error.captureStackTrace(obj, fn);
+ const { stack } = obj;
+ Error.stackTraceLimit = stackTraceLimit;
+ return this.clean(stack);
+ }
+ capture(limit2, fn = this.capture) {
+ if (typeof limit2 === "function") {
+ fn = limit2;
+ limit2 = Infinity;
+ }
+ const { prepareStackTrace, stackTraceLimit } = Error;
+ Error.prepareStackTrace = (obj2, site) => {
+ if (this._wrapCallSite) {
+ return site.map(this._wrapCallSite);
+ }
+ return site;
+ };
+ if (limit2) {
+ Error.stackTraceLimit = limit2;
+ }
+ const obj = {};
+ Error.captureStackTrace(obj, fn);
+ const { stack } = obj;
+ Object.assign(Error, { prepareStackTrace, stackTraceLimit });
+ return stack;
+ }
+ at(fn = this.at) {
+ const [site] = this.capture(1, fn);
+ if (!site) {
+ return {};
+ }
+ const res = {
+ line: site.getLineNumber(),
+ column: site.getColumnNumber()
+ };
+ setFile(res, site.getFileName(), this._cwd);
+ if (site.isConstructor()) {
+ Object.defineProperty(res, "constructor", {
+ value: true,
+ configurable: true
+ });
+ }
+ if (site.isEval()) {
+ res.evalOrigin = site.getEvalOrigin();
+ }
+ if (site.isNative()) {
+ res.native = true;
+ }
+ let typename;
+ try {
+ typename = site.getTypeName();
+ } catch (_) {
+ }
+ if (typename && typename !== "Object" && typename !== "[object Object]") {
+ res.type = typename;
+ }
+ const fname = site.getFunctionName();
+ if (fname) {
+ res.function = fname;
+ }
+ const meth = site.getMethodName();
+ if (meth && fname !== meth) {
+ res.method = meth;
+ }
+ return res;
+ }
+ parseLine(line) {
+ const match = line && line.match(re);
+ if (!match) {
+ return null;
+ }
+ const ctor = match[1] === "new";
+ let fname = match[2];
+ const evalOrigin = match[3];
+ const evalFile = match[4];
+ const evalLine = Number(match[5]);
+ const evalCol = Number(match[6]);
+ let file2 = match[7];
+ const lnum = match[8];
+ const col = match[9];
+ const native = match[10] === "native";
+ const closeParen = match[11] === ")";
+ let method;
+ const res = {};
+ if (lnum) {
+ res.line = Number(lnum);
+ }
+ if (col) {
+ res.column = Number(col);
+ }
+ if (closeParen && file2) {
+ let closes = 0;
+ for (let i = file2.length - 1; i > 0; i--) {
+ if (file2.charAt(i) === ")") {
+ closes++;
+ } else if (file2.charAt(i) === "(" && file2.charAt(i - 1) === " ") {
+ closes--;
+ if (closes === -1 && file2.charAt(i - 1) === " ") {
+ const before = file2.slice(0, i - 1);
+ const after = file2.slice(i + 1);
+ file2 = after;
+ fname += ` (${before}`;
+ break;
+ }
+ }
+ }
+ }
+ if (fname) {
+ const methodMatch = fname.match(methodRe);
+ if (methodMatch) {
+ fname = methodMatch[1];
+ method = methodMatch[2];
+ }
+ }
+ setFile(res, file2, this._cwd);
+ if (ctor) {
+ Object.defineProperty(res, "constructor", {
+ value: true,
+ configurable: true
+ });
+ }
+ if (evalOrigin) {
+ res.evalOrigin = evalOrigin;
+ res.evalLine = evalLine;
+ res.evalColumn = evalCol;
+ res.evalFile = evalFile && evalFile.replace(/\\/g, "/");
+ }
+ if (native) {
+ res.native = true;
+ }
+ if (fname) {
+ res.function = fname;
+ }
+ if (method && fname !== method) {
+ res.method = method;
+ }
+ return res;
+ }
+ };
+ function setFile(result, filename, cwd3) {
+ if (filename) {
+ filename = filename.replace(/\\/g, "/");
+ if (filename.startsWith(`${cwd3}/`)) {
+ filename = filename.slice(cwd3.length + 1);
+ }
+ result.file = filename;
+ }
+ }
+ __name(setFile, "setFile");
+ function ignoredPackagesRegExp(ignoredPackages) {
+ if (ignoredPackages.length === 0) {
+ return [];
+ }
+ const packages = ignoredPackages.map((mod) => escapeStringRegexp(mod));
+ return new RegExp(`[/\\\\]node_modules[/\\\\](?:${packages.join("|")})[/\\\\][^:]+:\\d+:\\d+`);
+ }
+ __name(ignoredPackagesRegExp, "ignoredPackagesRegExp");
+ var re = new RegExp(
+ "^(?:\\s*at )?(?:(new) )?(?:(.*?) \\()?(?:eval at ([^ ]+) \\((.+?):(\\d+):(\\d+)\\), )?(?:(.+?):(\\d+):(\\d+)|(native))(\\)?)$"
+ );
+ var methodRe = /^(.*?) \[as (.*?)\]$/;
+ module2.exports = StackUtils2;
+ }
+});
+
+// node_modules/kind-of/index.js
+var require_kind_of = __commonJS({
+ "node_modules/kind-of/index.js"(exports2, module2) {
+ init_esbuild_shims();
+ var toString = Object.prototype.toString;
+ module2.exports = /* @__PURE__ */ __name(function kindOf(val) {
+ if (val === void 0) return "undefined";
+ if (val === null) return "null";
+ var type2 = typeof val;
+ if (type2 === "boolean") return "boolean";
+ if (type2 === "string") return "string";
+ if (type2 === "number") return "number";
+ if (type2 === "symbol") return "symbol";
+ if (type2 === "function") {
+ return isGeneratorFn(val) ? "generatorfunction" : "function";
+ }
+ if (isArray2(val)) return "array";
+ if (isBuffer(val)) return "buffer";
+ if (isArguments(val)) return "arguments";
+ if (isDate(val)) return "date";
+ if (isError(val)) return "error";
+ if (isRegexp(val)) return "regexp";
+ switch (ctorName(val)) {
+ case "Symbol":
+ return "symbol";
+ case "Promise":
+ return "promise";
+ // Set, Map, WeakSet, WeakMap
+ case "WeakMap":
+ return "weakmap";
+ case "WeakSet":
+ return "weakset";
+ case "Map":
+ return "map";
+ case "Set":
+ return "set";
+ // 8-bit typed arrays
+ case "Int8Array":
+ return "int8array";
+ case "Uint8Array":
+ return "uint8array";
+ case "Uint8ClampedArray":
+ return "uint8clampedarray";
+ // 16-bit typed arrays
+ case "Int16Array":
+ return "int16array";
+ case "Uint16Array":
+ return "uint16array";
+ // 32-bit typed arrays
+ case "Int32Array":
+ return "int32array";
+ case "Uint32Array":
+ return "uint32array";
+ case "Float32Array":
+ return "float32array";
+ case "Float64Array":
+ return "float64array";
+ }
+ if (isGeneratorObj(val)) {
+ return "generator";
+ }
+ type2 = toString.call(val);
+ switch (type2) {
+ case "[object Object]":
+ return "object";
+ // iterators
+ case "[object Map Iterator]":
+ return "mapiterator";
+ case "[object Set Iterator]":
+ return "setiterator";
+ case "[object String Iterator]":
+ return "stringiterator";
+ case "[object Array Iterator]":
+ return "arrayiterator";
+ }
+ return type2.slice(8, -1).toLowerCase().replace(/\s/g, "");
+ }, "kindOf");
+ function ctorName(val) {
+ return typeof val.constructor === "function" ? val.constructor.name : null;
+ }
+ __name(ctorName, "ctorName");
+ function isArray2(val) {
+ if (Array.isArray) return Array.isArray(val);
+ return val instanceof Array;
+ }
+ __name(isArray2, "isArray");
+ function isError(val) {
+ return val instanceof Error || typeof val.message === "string" && val.constructor && typeof val.constructor.stackTraceLimit === "number";
+ }
+ __name(isError, "isError");
+ function isDate(val) {
+ if (val instanceof Date) return true;
+ return typeof val.toDateString === "function" && typeof val.getDate === "function" && typeof val.setDate === "function";
+ }
+ __name(isDate, "isDate");
+ function isRegexp(val) {
+ if (val instanceof RegExp) return true;
+ return typeof val.flags === "string" && typeof val.ignoreCase === "boolean" && typeof val.multiline === "boolean" && typeof val.global === "boolean";
+ }
+ __name(isRegexp, "isRegexp");
+ function isGeneratorFn(name, val) {
+ return ctorName(name) === "GeneratorFunction";
+ }
+ __name(isGeneratorFn, "isGeneratorFn");
+ function isGeneratorObj(val) {
+ return typeof val.throw === "function" && typeof val.return === "function" && typeof val.next === "function";
+ }
+ __name(isGeneratorObj, "isGeneratorObj");
+ function isArguments(val) {
+ try {
+ if (typeof val.length === "number" && typeof val.callee === "function") {
+ return true;
+ }
+ } catch (err) {
+ if (err.message.indexOf("callee") !== -1) {
+ return true;
+ }
+ }
+ return false;
+ }
+ __name(isArguments, "isArguments");
+ function isBuffer(val) {
+ if (val.constructor && typeof val.constructor.isBuffer === "function") {
+ return val.constructor.isBuffer(val);
+ }
+ return false;
+ }
+ __name(isBuffer, "isBuffer");
+ }
+});
+
+// node_modules/is-extendable/index.js
+var require_is_extendable = __commonJS({
+ "node_modules/is-extendable/index.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ module2.exports = /* @__PURE__ */ __name(function isExtendable(val) {
+ return typeof val !== "undefined" && val !== null && (typeof val === "object" || typeof val === "function");
+ }, "isExtendable");
+ }
+});
+
+// node_modules/extend-shallow/index.js
+var require_extend_shallow = __commonJS({
+ "node_modules/extend-shallow/index.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var isObject2 = require_is_extendable();
+ module2.exports = /* @__PURE__ */ __name(function extend2(o) {
+ if (!isObject2(o)) {
+ o = {};
+ }
+ var len = arguments.length;
+ for (var i = 1; i < len; i++) {
+ var obj = arguments[i];
+ if (isObject2(obj)) {
+ assign(o, obj);
+ }
+ }
+ return o;
+ }, "extend");
+ function assign(a, b) {
+ for (var key in b) {
+ if (hasOwn3(b, key)) {
+ a[key] = b[key];
+ }
+ }
+ }
+ __name(assign, "assign");
+ function hasOwn3(obj, key) {
+ return Object.prototype.hasOwnProperty.call(obj, key);
+ }
+ __name(hasOwn3, "hasOwn");
+ }
+});
+
+// node_modules/section-matter/index.js
+var require_section_matter = __commonJS({
+ "node_modules/section-matter/index.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var typeOf = require_kind_of();
+ var extend2 = require_extend_shallow();
+ module2.exports = function(input, options2) {
+ if (typeof options2 === "function") {
+ options2 = { parse: options2 };
+ }
+ var file2 = toObject(input);
+ var defaults2 = { section_delimiter: "---", parse: identity };
+ var opts = extend2({}, defaults2, options2);
+ var delim = opts.section_delimiter;
+ var lines = file2.content.split(/\r?\n/);
+ var sections = null;
+ var section = createSection();
+ var content = [];
+ var stack = [];
+ function initSections(val) {
+ file2.content = val;
+ sections = [];
+ content = [];
+ }
+ __name(initSections, "initSections");
+ function closeSection(val) {
+ if (stack.length) {
+ section.key = getKey(stack[0], delim);
+ section.content = val;
+ opts.parse(section, sections);
+ sections.push(section);
+ section = createSection();
+ content = [];
+ stack = [];
+ }
+ }
+ __name(closeSection, "closeSection");
+ for (var i = 0; i < lines.length; i++) {
+ var line = lines[i];
+ var len = stack.length;
+ var ln = line.trim();
+ if (isDelimiter(ln, delim)) {
+ if (ln.length === 3 && i !== 0) {
+ if (len === 0 || len === 2) {
+ content.push(line);
+ continue;
+ }
+ stack.push(ln);
+ section.data = content.join("\n");
+ content = [];
+ continue;
+ }
+ if (sections === null) {
+ initSections(content.join("\n"));
+ }
+ if (len === 2) {
+ closeSection(content.join("\n"));
+ }
+ stack.push(ln);
+ continue;
+ }
+ content.push(line);
+ }
+ if (sections === null) {
+ initSections(content.join("\n"));
+ } else {
+ closeSection(content.join("\n"));
+ }
+ file2.sections = sections;
+ return file2;
+ };
+ function isDelimiter(line, delim) {
+ if (line.slice(0, delim.length) !== delim) {
+ return false;
+ }
+ if (line.charAt(delim.length + 1) === delim.slice(-1)) {
+ return false;
+ }
+ return true;
+ }
+ __name(isDelimiter, "isDelimiter");
+ function toObject(input) {
+ if (typeOf(input) !== "object") {
+ input = { content: input };
+ }
+ if (typeof input.content !== "string" && !isBuffer(input.content)) {
+ throw new TypeError("expected a buffer or string");
+ }
+ input.content = input.content.toString();
+ input.sections = [];
+ return input;
+ }
+ __name(toObject, "toObject");
+ function getKey(val, delim) {
+ return val ? val.slice(delim.length).trim() : "";
+ }
+ __name(getKey, "getKey");
+ function createSection() {
+ return { key: "", data: "", content: "" };
+ }
+ __name(createSection, "createSection");
+ function identity(val) {
+ return val;
+ }
+ __name(identity, "identity");
+ function isBuffer(val) {
+ if (val && val.constructor && typeof val.constructor.isBuffer === "function") {
+ return val.constructor.isBuffer(val);
+ }
+ return false;
+ }
+ __name(isBuffer, "isBuffer");
+ }
+});
+
+// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/common.js
+var require_common = __commonJS({
+ "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/common.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ function isNothing(subject) {
+ return typeof subject === "undefined" || subject === null;
+ }
+ __name(isNothing, "isNothing");
+ function isObject2(subject) {
+ return typeof subject === "object" && subject !== null;
+ }
+ __name(isObject2, "isObject");
+ function toArray(sequence) {
+ if (Array.isArray(sequence)) return sequence;
+ else if (isNothing(sequence)) return [];
+ return [sequence];
+ }
+ __name(toArray, "toArray");
+ function extend2(target, source) {
+ var index, length, key, sourceKeys;
+ if (source) {
+ sourceKeys = Object.keys(source);
+ for (index = 0, length = sourceKeys.length; index < length; index += 1) {
+ key = sourceKeys[index];
+ target[key] = source[key];
+ }
+ }
+ return target;
+ }
+ __name(extend2, "extend");
+ function repeat(string4, count) {
+ var result = "", cycle;
+ for (cycle = 0; cycle < count; cycle += 1) {
+ result += string4;
+ }
+ return result;
+ }
+ __name(repeat, "repeat");
+ function isNegativeZero(number4) {
+ return number4 === 0 && Number.NEGATIVE_INFINITY === 1 / number4;
+ }
+ __name(isNegativeZero, "isNegativeZero");
+ module2.exports.isNothing = isNothing;
+ module2.exports.isObject = isObject2;
+ module2.exports.toArray = toArray;
+ module2.exports.repeat = repeat;
+ module2.exports.isNegativeZero = isNegativeZero;
+ module2.exports.extend = extend2;
+ }
+});
+
+// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/exception.js
+var require_exception = __commonJS({
+ "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/exception.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ function YAMLException(reason, mark) {
+ Error.call(this);
+ this.name = "YAMLException";
+ this.reason = reason;
+ this.mark = mark;
+ this.message = (this.reason || "(unknown reason)") + (this.mark ? " " + this.mark.toString() : "");
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, this.constructor);
+ } else {
+ this.stack = new Error().stack || "";
+ }
+ }
+ __name(YAMLException, "YAMLException");
+ YAMLException.prototype = Object.create(Error.prototype);
+ YAMLException.prototype.constructor = YAMLException;
+ YAMLException.prototype.toString = /* @__PURE__ */ __name(function toString(compact) {
+ var result = this.name + ": ";
+ result += this.reason || "(unknown reason)";
+ if (!compact && this.mark) {
+ result += " " + this.mark.toString();
+ }
+ return result;
+ }, "toString");
+ module2.exports = YAMLException;
+ }
+});
+
+// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/mark.js
+var require_mark = __commonJS({
+ "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/mark.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var common = require_common();
+ function Mark(name, buffer, position, line, column) {
+ this.name = name;
+ this.buffer = buffer;
+ this.position = position;
+ this.line = line;
+ this.column = column;
+ }
+ __name(Mark, "Mark");
+ Mark.prototype.getSnippet = /* @__PURE__ */ __name(function getSnippet2(indent, maxLength) {
+ var head, start, tail, end, snippet;
+ if (!this.buffer) return null;
+ indent = indent || 4;
+ maxLength = maxLength || 75;
+ head = "";
+ start = this.position;
+ while (start > 0 && "\0\r\n\x85\u2028\u2029".indexOf(this.buffer.charAt(start - 1)) === -1) {
+ start -= 1;
+ if (this.position - start > maxLength / 2 - 1) {
+ head = " ... ";
+ start += 5;
+ break;
+ }
+ }
+ tail = "";
+ end = this.position;
+ while (end < this.buffer.length && "\0\r\n\x85\u2028\u2029".indexOf(this.buffer.charAt(end)) === -1) {
+ end += 1;
+ if (end - this.position > maxLength / 2 - 1) {
+ tail = " ... ";
+ end -= 5;
+ break;
+ }
+ }
+ snippet = this.buffer.slice(start, end);
+ return common.repeat(" ", indent) + head + snippet + tail + "\n" + common.repeat(" ", indent + this.position - start + head.length) + "^";
+ }, "getSnippet");
+ Mark.prototype.toString = /* @__PURE__ */ __name(function toString(compact) {
+ var snippet, where = "";
+ if (this.name) {
+ where += 'in "' + this.name + '" ';
+ }
+ where += "at line " + (this.line + 1) + ", column " + (this.column + 1);
+ if (!compact) {
+ snippet = this.getSnippet();
+ if (snippet) {
+ where += ":\n" + snippet;
+ }
+ }
+ return where;
+ }, "toString");
+ module2.exports = Mark;
+ }
+});
+
+// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type.js
+var require_type = __commonJS({
+ "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var YAMLException = require_exception();
+ var TYPE_CONSTRUCTOR_OPTIONS = [
+ "kind",
+ "resolve",
+ "construct",
+ "instanceOf",
+ "predicate",
+ "represent",
+ "defaultStyle",
+ "styleAliases"
+ ];
+ var YAML_NODE_KINDS = [
+ "scalar",
+ "sequence",
+ "mapping"
+ ];
+ function compileStyleAliases(map2) {
+ var result = {};
+ if (map2 !== null) {
+ Object.keys(map2).forEach(function(style) {
+ map2[style].forEach(function(alias) {
+ result[String(alias)] = style;
+ });
+ });
+ }
+ return result;
+ }
+ __name(compileStyleAliases, "compileStyleAliases");
+ function Type(tag, options2) {
+ options2 = options2 || {};
+ Object.keys(options2).forEach(function(name) {
+ if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
+ throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');
+ }
+ });
+ this.tag = tag;
+ this.kind = options2["kind"] || null;
+ this.resolve = options2["resolve"] || function() {
+ return true;
+ };
+ this.construct = options2["construct"] || function(data) {
+ return data;
+ };
+ this.instanceOf = options2["instanceOf"] || null;
+ this.predicate = options2["predicate"] || null;
+ this.represent = options2["represent"] || null;
+ this.defaultStyle = options2["defaultStyle"] || null;
+ this.styleAliases = compileStyleAliases(options2["styleAliases"] || null);
+ if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
+ throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
+ }
+ }
+ __name(Type, "Type");
+ module2.exports = Type;
+ }
+});
+
+// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/schema.js
+var require_schema = __commonJS({
+ "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/schema.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var common = require_common();
+ var YAMLException = require_exception();
+ var Type = require_type();
+ function compileList(schema, name, result) {
+ var exclude = [];
+ schema.include.forEach(function(includedSchema) {
+ result = compileList(includedSchema, name, result);
+ });
+ schema[name].forEach(function(currentType) {
+ result.forEach(function(previousType, previousIndex) {
+ if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) {
+ exclude.push(previousIndex);
+ }
+ });
+ result.push(currentType);
+ });
+ return result.filter(function(type2, index) {
+ return exclude.indexOf(index) === -1;
+ });
+ }
+ __name(compileList, "compileList");
+ function compileMap() {
+ var result = {
+ scalar: {},
+ sequence: {},
+ mapping: {},
+ fallback: {}
+ }, index, length;
+ function collectType(type2) {
+ result[type2.kind][type2.tag] = result["fallback"][type2.tag] = type2;
+ }
+ __name(collectType, "collectType");
+ for (index = 0, length = arguments.length; index < length; index += 1) {
+ arguments[index].forEach(collectType);
+ }
+ return result;
+ }
+ __name(compileMap, "compileMap");
+ function Schema(definition) {
+ this.include = definition.include || [];
+ this.implicit = definition.implicit || [];
+ this.explicit = definition.explicit || [];
+ this.implicit.forEach(function(type2) {
+ if (type2.loadKind && type2.loadKind !== "scalar") {
+ throw new YAMLException("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");
+ }
+ });
+ this.compiledImplicit = compileList(this, "implicit", []);
+ this.compiledExplicit = compileList(this, "explicit", []);
+ this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit);
+ }
+ __name(Schema, "Schema");
+ Schema.DEFAULT = null;
+ Schema.create = /* @__PURE__ */ __name(function createSchema() {
+ var schemas, types;
+ switch (arguments.length) {
+ case 1:
+ schemas = Schema.DEFAULT;
+ types = arguments[0];
+ break;
+ case 2:
+ schemas = arguments[0];
+ types = arguments[1];
+ break;
+ default:
+ throw new YAMLException("Wrong number of arguments for Schema.create function");
+ }
+ schemas = common.toArray(schemas);
+ types = common.toArray(types);
+ if (!schemas.every(function(schema) {
+ return schema instanceof Schema;
+ })) {
+ throw new YAMLException("Specified list of super schemas (or a single Schema object) contains a non-Schema object.");
+ }
+ if (!types.every(function(type2) {
+ return type2 instanceof Type;
+ })) {
+ throw new YAMLException("Specified list of YAML types (or a single Type object) contains a non-Type object.");
+ }
+ return new Schema({
+ include: schemas,
+ explicit: types
+ });
+ }, "createSchema");
+ module2.exports = Schema;
+ }
+});
+
+// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/str.js
+var require_str = __commonJS({
+ "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/str.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var Type = require_type();
+ module2.exports = new Type("tag:yaml.org,2002:str", {
+ kind: "scalar",
+ construct: /* @__PURE__ */ __name(function(data) {
+ return data !== null ? data : "";
+ }, "construct")
+ });
+ }
+});
+
+// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/seq.js
+var require_seq = __commonJS({
+ "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/seq.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var Type = require_type();
+ module2.exports = new Type("tag:yaml.org,2002:seq", {
+ kind: "sequence",
+ construct: /* @__PURE__ */ __name(function(data) {
+ return data !== null ? data : [];
+ }, "construct")
+ });
+ }
+});
+
+// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/map.js
+var require_map = __commonJS({
+ "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/map.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var Type = require_type();
+ module2.exports = new Type("tag:yaml.org,2002:map", {
+ kind: "mapping",
+ construct: /* @__PURE__ */ __name(function(data) {
+ return data !== null ? data : {};
+ }, "construct")
+ });
+ }
+});
+
+// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/schema/failsafe.js
+var require_failsafe = __commonJS({
+ "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/schema/failsafe.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var Schema = require_schema();
+ module2.exports = new Schema({
+ explicit: [
+ require_str(),
+ require_seq(),
+ require_map()
+ ]
+ });
+ }
+});
+
+// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/null.js
+var require_null = __commonJS({
+ "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/null.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var Type = require_type();
+ function resolveYamlNull(data) {
+ if (data === null) return true;
+ var max = data.length;
+ return max === 1 && data === "~" || max === 4 && (data === "null" || data === "Null" || data === "NULL");
+ }
+ __name(resolveYamlNull, "resolveYamlNull");
+ function constructYamlNull() {
+ return null;
+ }
+ __name(constructYamlNull, "constructYamlNull");
+ function isNull(object2) {
+ return object2 === null;
+ }
+ __name(isNull, "isNull");
+ module2.exports = new Type("tag:yaml.org,2002:null", {
+ kind: "scalar",
+ resolve: resolveYamlNull,
+ construct: constructYamlNull,
+ predicate: isNull,
+ represent: {
+ canonical: /* @__PURE__ */ __name(function() {
+ return "~";
+ }, "canonical"),
+ lowercase: /* @__PURE__ */ __name(function() {
+ return "null";
+ }, "lowercase"),
+ uppercase: /* @__PURE__ */ __name(function() {
+ return "NULL";
+ }, "uppercase"),
+ camelcase: /* @__PURE__ */ __name(function() {
+ return "Null";
+ }, "camelcase")
+ },
+ defaultStyle: "lowercase"
+ });
+ }
+});
+
+// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/bool.js
+var require_bool = __commonJS({
+ "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/bool.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var Type = require_type();
+ function resolveYamlBoolean(data) {
+ if (data === null) return false;
+ var max = data.length;
+ return max === 4 && (data === "true" || data === "True" || data === "TRUE") || max === 5 && (data === "false" || data === "False" || data === "FALSE");
+ }
+ __name(resolveYamlBoolean, "resolveYamlBoolean");
+ function constructYamlBoolean(data) {
+ return data === "true" || data === "True" || data === "TRUE";
+ }
+ __name(constructYamlBoolean, "constructYamlBoolean");
+ function isBoolean2(object2) {
+ return Object.prototype.toString.call(object2) === "[object Boolean]";
+ }
+ __name(isBoolean2, "isBoolean");
+ module2.exports = new Type("tag:yaml.org,2002:bool", {
+ kind: "scalar",
+ resolve: resolveYamlBoolean,
+ construct: constructYamlBoolean,
+ predicate: isBoolean2,
+ represent: {
+ lowercase: /* @__PURE__ */ __name(function(object2) {
+ return object2 ? "true" : "false";
+ }, "lowercase"),
+ uppercase: /* @__PURE__ */ __name(function(object2) {
+ return object2 ? "TRUE" : "FALSE";
+ }, "uppercase"),
+ camelcase: /* @__PURE__ */ __name(function(object2) {
+ return object2 ? "True" : "False";
+ }, "camelcase")
+ },
+ defaultStyle: "lowercase"
+ });
+ }
+});
+
+// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/int.js
+var require_int = __commonJS({
+ "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/int.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var common = require_common();
+ var Type = require_type();
+ function isHexCode(c) {
+ return 48 <= c && c <= 57 || 65 <= c && c <= 70 || 97 <= c && c <= 102;
+ }
+ __name(isHexCode, "isHexCode");
+ function isOctCode(c) {
+ return 48 <= c && c <= 55;
+ }
+ __name(isOctCode, "isOctCode");
+ function isDecCode(c) {
+ return 48 <= c && c <= 57;
+ }
+ __name(isDecCode, "isDecCode");
+ function resolveYamlInteger(data) {
+ if (data === null) return false;
+ var max = data.length, index = 0, hasDigits = false, ch;
+ if (!max) return false;
+ ch = data[index];
+ if (ch === "-" || ch === "+") {
+ ch = data[++index];
+ }
+ if (ch === "0") {
+ if (index + 1 === max) return true;
+ ch = data[++index];
+ if (ch === "b") {
+ index++;
+ for (; index < max; index++) {
+ ch = data[index];
+ if (ch === "_") continue;
+ if (ch !== "0" && ch !== "1") return false;
+ hasDigits = true;
+ }
+ return hasDigits && ch !== "_";
+ }
+ if (ch === "x") {
+ index++;
+ for (; index < max; index++) {
+ ch = data[index];
+ if (ch === "_") continue;
+ if (!isHexCode(data.charCodeAt(index))) return false;
+ hasDigits = true;
+ }
+ return hasDigits && ch !== "_";
+ }
+ for (; index < max; index++) {
+ ch = data[index];
+ if (ch === "_") continue;
+ if (!isOctCode(data.charCodeAt(index))) return false;
+ hasDigits = true;
+ }
+ return hasDigits && ch !== "_";
+ }
+ if (ch === "_") return false;
+ for (; index < max; index++) {
+ ch = data[index];
+ if (ch === "_") continue;
+ if (ch === ":") break;
+ if (!isDecCode(data.charCodeAt(index))) {
+ return false;
+ }
+ hasDigits = true;
+ }
+ if (!hasDigits || ch === "_") return false;
+ if (ch !== ":") return true;
+ return /^(:[0-5]?[0-9])+$/.test(data.slice(index));
+ }
+ __name(resolveYamlInteger, "resolveYamlInteger");
+ function constructYamlInteger(data) {
+ var value = data, sign = 1, ch, base, digits = [];
+ if (value.indexOf("_") !== -1) {
+ value = value.replace(/_/g, "");
+ }
+ ch = value[0];
+ if (ch === "-" || ch === "+") {
+ if (ch === "-") sign = -1;
+ value = value.slice(1);
+ ch = value[0];
+ }
+ if (value === "0") return 0;
+ if (ch === "0") {
+ if (value[1] === "b") return sign * parseInt(value.slice(2), 2);
+ if (value[1] === "x") return sign * parseInt(value, 16);
+ return sign * parseInt(value, 8);
+ }
+ if (value.indexOf(":") !== -1) {
+ value.split(":").forEach(function(v) {
+ digits.unshift(parseInt(v, 10));
+ });
+ value = 0;
+ base = 1;
+ digits.forEach(function(d) {
+ value += d * base;
+ base *= 60;
+ });
+ return sign * value;
+ }
+ return sign * parseInt(value, 10);
+ }
+ __name(constructYamlInteger, "constructYamlInteger");
+ function isInteger(object2) {
+ return Object.prototype.toString.call(object2) === "[object Number]" && (object2 % 1 === 0 && !common.isNegativeZero(object2));
+ }
+ __name(isInteger, "isInteger");
+ module2.exports = new Type("tag:yaml.org,2002:int", {
+ kind: "scalar",
+ resolve: resolveYamlInteger,
+ construct: constructYamlInteger,
+ predicate: isInteger,
+ represent: {
+ binary: /* @__PURE__ */ __name(function(obj) {
+ return obj >= 0 ? "0b" + obj.toString(2) : "-0b" + obj.toString(2).slice(1);
+ }, "binary"),
+ octal: /* @__PURE__ */ __name(function(obj) {
+ return obj >= 0 ? "0" + obj.toString(8) : "-0" + obj.toString(8).slice(1);
+ }, "octal"),
+ decimal: /* @__PURE__ */ __name(function(obj) {
+ return obj.toString(10);
+ }, "decimal"),
+ /* eslint-disable max-len */
+ hexadecimal: /* @__PURE__ */ __name(function(obj) {
+ return obj >= 0 ? "0x" + obj.toString(16).toUpperCase() : "-0x" + obj.toString(16).toUpperCase().slice(1);
+ }, "hexadecimal")
+ },
+ defaultStyle: "decimal",
+ styleAliases: {
+ binary: [2, "bin"],
+ octal: [8, "oct"],
+ decimal: [10, "dec"],
+ hexadecimal: [16, "hex"]
+ }
+ });
+ }
+});
+
+// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/float.js
+var require_float = __commonJS({
+ "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/float.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var common = require_common();
+ var Type = require_type();
+ var YAML_FLOAT_PATTERN = new RegExp(
+ // 2.5e4, 2.5 and integers
+ "^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"
+ );
+ function resolveYamlFloat(data) {
+ if (data === null) return false;
+ if (!YAML_FLOAT_PATTERN.test(data) || // Quick hack to not allow integers end with `_`
+ // Probably should update regexp & check speed
+ data[data.length - 1] === "_") {
+ return false;
+ }
+ return true;
+ }
+ __name(resolveYamlFloat, "resolveYamlFloat");
+ function constructYamlFloat(data) {
+ var value, sign, base, digits;
+ value = data.replace(/_/g, "").toLowerCase();
+ sign = value[0] === "-" ? -1 : 1;
+ digits = [];
+ if ("+-".indexOf(value[0]) >= 0) {
+ value = value.slice(1);
+ }
+ if (value === ".inf") {
+ return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
+ } else if (value === ".nan") {
+ return NaN;
+ } else if (value.indexOf(":") >= 0) {
+ value.split(":").forEach(function(v) {
+ digits.unshift(parseFloat(v, 10));
+ });
+ value = 0;
+ base = 1;
+ digits.forEach(function(d) {
+ value += d * base;
+ base *= 60;
+ });
+ return sign * value;
+ }
+ return sign * parseFloat(value, 10);
+ }
+ __name(constructYamlFloat, "constructYamlFloat");
+ var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
+ function representYamlFloat(object2, style) {
+ var res;
+ if (isNaN(object2)) {
+ switch (style) {
+ case "lowercase":
+ return ".nan";
+ case "uppercase":
+ return ".NAN";
+ case "camelcase":
+ return ".NaN";
+ }
+ } else if (Number.POSITIVE_INFINITY === object2) {
+ switch (style) {
+ case "lowercase":
+ return ".inf";
+ case "uppercase":
+ return ".INF";
+ case "camelcase":
+ return ".Inf";
+ }
+ } else if (Number.NEGATIVE_INFINITY === object2) {
+ switch (style) {
+ case "lowercase":
+ return "-.inf";
+ case "uppercase":
+ return "-.INF";
+ case "camelcase":
+ return "-.Inf";
+ }
+ } else if (common.isNegativeZero(object2)) {
+ return "-0.0";
+ }
+ res = object2.toString(10);
+ return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace("e", ".e") : res;
+ }
+ __name(representYamlFloat, "representYamlFloat");
+ function isFloat(object2) {
+ return Object.prototype.toString.call(object2) === "[object Number]" && (object2 % 1 !== 0 || common.isNegativeZero(object2));
+ }
+ __name(isFloat, "isFloat");
+ module2.exports = new Type("tag:yaml.org,2002:float", {
+ kind: "scalar",
+ resolve: resolveYamlFloat,
+ construct: constructYamlFloat,
+ predicate: isFloat,
+ represent: representYamlFloat,
+ defaultStyle: "lowercase"
+ });
+ }
+});
+
+// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/schema/json.js
+var require_json = __commonJS({
+ "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/schema/json.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var Schema = require_schema();
+ module2.exports = new Schema({
+ include: [
+ require_failsafe()
+ ],
+ implicit: [
+ require_null(),
+ require_bool(),
+ require_int(),
+ require_float()
+ ]
+ });
+ }
+});
+
+// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/schema/core.js
+var require_core = __commonJS({
+ "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/schema/core.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var Schema = require_schema();
+ module2.exports = new Schema({
+ include: [
+ require_json()
+ ]
+ });
+ }
+});
+
+// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/timestamp.js
+var require_timestamp = __commonJS({
+ "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/timestamp.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var Type = require_type();
+ var YAML_DATE_REGEXP = new RegExp(
+ "^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"
+ );
+ var YAML_TIMESTAMP_REGEXP = new RegExp(
+ "^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$"
+ );
+ function resolveYamlTimestamp(data) {
+ if (data === null) return false;
+ if (YAML_DATE_REGEXP.exec(data) !== null) return true;
+ if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;
+ return false;
+ }
+ __name(resolveYamlTimestamp, "resolveYamlTimestamp");
+ function constructYamlTimestamp(data) {
+ var match, year, month, day, hour, minute, second, fraction = 0, delta = null, tz_hour, tz_minute, date5;
+ match = YAML_DATE_REGEXP.exec(data);
+ if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);
+ if (match === null) throw new Error("Date resolve error");
+ year = +match[1];
+ month = +match[2] - 1;
+ day = +match[3];
+ if (!match[4]) {
+ return new Date(Date.UTC(year, month, day));
+ }
+ hour = +match[4];
+ minute = +match[5];
+ second = +match[6];
+ if (match[7]) {
+ fraction = match[7].slice(0, 3);
+ while (fraction.length < 3) {
+ fraction += "0";
+ }
+ fraction = +fraction;
+ }
+ if (match[9]) {
+ tz_hour = +match[10];
+ tz_minute = +(match[11] || 0);
+ delta = (tz_hour * 60 + tz_minute) * 6e4;
+ if (match[9] === "-") delta = -delta;
+ }
+ date5 = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
+ if (delta) date5.setTime(date5.getTime() - delta);
+ return date5;
+ }
+ __name(constructYamlTimestamp, "constructYamlTimestamp");
+ function representYamlTimestamp(object2) {
+ return object2.toISOString();
+ }
+ __name(representYamlTimestamp, "representYamlTimestamp");
+ module2.exports = new Type("tag:yaml.org,2002:timestamp", {
+ kind: "scalar",
+ resolve: resolveYamlTimestamp,
+ construct: constructYamlTimestamp,
+ instanceOf: Date,
+ represent: representYamlTimestamp
+ });
+ }
+});
+
+// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/merge.js
+var require_merge = __commonJS({
+ "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/merge.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var Type = require_type();
+ function resolveYamlMerge(data) {
+ return data === "<<" || data === null;
+ }
+ __name(resolveYamlMerge, "resolveYamlMerge");
+ module2.exports = new Type("tag:yaml.org,2002:merge", {
+ kind: "scalar",
+ resolve: resolveYamlMerge
+ });
+ }
+});
+
+// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/binary.js
+var require_binary = __commonJS({
+ "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/binary.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var NodeBuffer;
+ try {
+ _require = __require;
+ NodeBuffer = _require("buffer").Buffer;
+ } catch (__) {
+ }
+ var _require;
+ var Type = require_type();
+ var BASE64_MAP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r";
+ function resolveYamlBinary(data) {
+ if (data === null) return false;
+ var code, idx, bitlen = 0, max = data.length, map2 = BASE64_MAP;
+ for (idx = 0; idx < max; idx++) {
+ code = map2.indexOf(data.charAt(idx));
+ if (code > 64) continue;
+ if (code < 0) return false;
+ bitlen += 6;
+ }
+ return bitlen % 8 === 0;
+ }
+ __name(resolveYamlBinary, "resolveYamlBinary");
+ function constructYamlBinary(data) {
+ var idx, tailbits, input = data.replace(/[\r\n=]/g, ""), max = input.length, map2 = BASE64_MAP, bits = 0, result = [];
+ for (idx = 0; idx < max; idx++) {
+ if (idx % 4 === 0 && idx) {
+ result.push(bits >> 16 & 255);
+ result.push(bits >> 8 & 255);
+ result.push(bits & 255);
+ }
+ bits = bits << 6 | map2.indexOf(input.charAt(idx));
+ }
+ tailbits = max % 4 * 6;
+ if (tailbits === 0) {
+ result.push(bits >> 16 & 255);
+ result.push(bits >> 8 & 255);
+ result.push(bits & 255);
+ } else if (tailbits === 18) {
+ result.push(bits >> 10 & 255);
+ result.push(bits >> 2 & 255);
+ } else if (tailbits === 12) {
+ result.push(bits >> 4 & 255);
+ }
+ if (NodeBuffer) {
+ return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result);
+ }
+ return result;
+ }
+ __name(constructYamlBinary, "constructYamlBinary");
+ function representYamlBinary(object2) {
+ var result = "", bits = 0, idx, tail, max = object2.length, map2 = BASE64_MAP;
+ for (idx = 0; idx < max; idx++) {
+ if (idx % 3 === 0 && idx) {
+ result += map2[bits >> 18 & 63];
+ result += map2[bits >> 12 & 63];
+ result += map2[bits >> 6 & 63];
+ result += map2[bits & 63];
+ }
+ bits = (bits << 8) + object2[idx];
+ }
+ tail = max % 3;
+ if (tail === 0) {
+ result += map2[bits >> 18 & 63];
+ result += map2[bits >> 12 & 63];
+ result += map2[bits >> 6 & 63];
+ result += map2[bits & 63];
+ } else if (tail === 2) {
+ result += map2[bits >> 10 & 63];
+ result += map2[bits >> 4 & 63];
+ result += map2[bits << 2 & 63];
+ result += map2[64];
+ } else if (tail === 1) {
+ result += map2[bits >> 2 & 63];
+ result += map2[bits << 4 & 63];
+ result += map2[64];
+ result += map2[64];
+ }
+ return result;
+ }
+ __name(representYamlBinary, "representYamlBinary");
+ function isBinary(object2) {
+ return NodeBuffer && NodeBuffer.isBuffer(object2);
+ }
+ __name(isBinary, "isBinary");
+ module2.exports = new Type("tag:yaml.org,2002:binary", {
+ kind: "scalar",
+ resolve: resolveYamlBinary,
+ construct: constructYamlBinary,
+ predicate: isBinary,
+ represent: representYamlBinary
+ });
+ }
+});
+
+// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/omap.js
+var require_omap = __commonJS({
+ "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/omap.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var Type = require_type();
+ var _hasOwnProperty = Object.prototype.hasOwnProperty;
+ var _toString = Object.prototype.toString;
+ function resolveYamlOmap(data) {
+ if (data === null) return true;
+ var objectKeys2 = [], index, length, pair, pairKey, pairHasKey, object2 = data;
+ for (index = 0, length = object2.length; index < length; index += 1) {
+ pair = object2[index];
+ pairHasKey = false;
+ if (_toString.call(pair) !== "[object Object]") return false;
+ for (pairKey in pair) {
+ if (_hasOwnProperty.call(pair, pairKey)) {
+ if (!pairHasKey) pairHasKey = true;
+ else return false;
+ }
+ }
+ if (!pairHasKey) return false;
+ if (objectKeys2.indexOf(pairKey) === -1) objectKeys2.push(pairKey);
+ else return false;
+ }
+ return true;
+ }
+ __name(resolveYamlOmap, "resolveYamlOmap");
+ function constructYamlOmap(data) {
+ return data !== null ? data : [];
+ }
+ __name(constructYamlOmap, "constructYamlOmap");
+ module2.exports = new Type("tag:yaml.org,2002:omap", {
+ kind: "sequence",
+ resolve: resolveYamlOmap,
+ construct: constructYamlOmap
+ });
+ }
+});
+
+// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/pairs.js
+var require_pairs = __commonJS({
+ "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/pairs.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var Type = require_type();
+ var _toString = Object.prototype.toString;
+ function resolveYamlPairs(data) {
+ if (data === null) return true;
+ var index, length, pair, keys, result, object2 = data;
+ result = new Array(object2.length);
+ for (index = 0, length = object2.length; index < length; index += 1) {
+ pair = object2[index];
+ if (_toString.call(pair) !== "[object Object]") return false;
+ keys = Object.keys(pair);
+ if (keys.length !== 1) return false;
+ result[index] = [keys[0], pair[keys[0]]];
+ }
+ return true;
+ }
+ __name(resolveYamlPairs, "resolveYamlPairs");
+ function constructYamlPairs(data) {
+ if (data === null) return [];
+ var index, length, pair, keys, result, object2 = data;
+ result = new Array(object2.length);
+ for (index = 0, length = object2.length; index < length; index += 1) {
+ pair = object2[index];
+ keys = Object.keys(pair);
+ result[index] = [keys[0], pair[keys[0]]];
+ }
+ return result;
+ }
+ __name(constructYamlPairs, "constructYamlPairs");
+ module2.exports = new Type("tag:yaml.org,2002:pairs", {
+ kind: "sequence",
+ resolve: resolveYamlPairs,
+ construct: constructYamlPairs
+ });
+ }
+});
+
+// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/set.js
+var require_set = __commonJS({
+ "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/set.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var Type = require_type();
+ var _hasOwnProperty = Object.prototype.hasOwnProperty;
+ function resolveYamlSet(data) {
+ if (data === null) return true;
+ var key, object2 = data;
+ for (key in object2) {
+ if (_hasOwnProperty.call(object2, key)) {
+ if (object2[key] !== null) return false;
+ }
+ }
+ return true;
+ }
+ __name(resolveYamlSet, "resolveYamlSet");
+ function constructYamlSet(data) {
+ return data !== null ? data : {};
+ }
+ __name(constructYamlSet, "constructYamlSet");
+ module2.exports = new Type("tag:yaml.org,2002:set", {
+ kind: "mapping",
+ resolve: resolveYamlSet,
+ construct: constructYamlSet
+ });
+ }
+});
+
+// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/schema/default_safe.js
+var require_default_safe = __commonJS({
+ "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/schema/default_safe.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var Schema = require_schema();
+ module2.exports = new Schema({
+ include: [
+ require_core()
+ ],
+ implicit: [
+ require_timestamp(),
+ require_merge()
+ ],
+ explicit: [
+ require_binary(),
+ require_omap(),
+ require_pairs(),
+ require_set()
+ ]
+ });
+ }
+});
+
+// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/js/undefined.js
+var require_undefined = __commonJS({
+ "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/js/undefined.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var Type = require_type();
+ function resolveJavascriptUndefined() {
+ return true;
+ }
+ __name(resolveJavascriptUndefined, "resolveJavascriptUndefined");
+ function constructJavascriptUndefined() {
+ return void 0;
+ }
+ __name(constructJavascriptUndefined, "constructJavascriptUndefined");
+ function representJavascriptUndefined() {
+ return "";
+ }
+ __name(representJavascriptUndefined, "representJavascriptUndefined");
+ function isUndefined(object2) {
+ return typeof object2 === "undefined";
+ }
+ __name(isUndefined, "isUndefined");
+ module2.exports = new Type("tag:yaml.org,2002:js/undefined", {
+ kind: "scalar",
+ resolve: resolveJavascriptUndefined,
+ construct: constructJavascriptUndefined,
+ predicate: isUndefined,
+ represent: representJavascriptUndefined
+ });
+ }
+});
+
+// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/js/regexp.js
+var require_regexp = __commonJS({
+ "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/js/regexp.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var Type = require_type();
+ function resolveJavascriptRegExp(data) {
+ if (data === null) return false;
+ if (data.length === 0) return false;
+ var regexp = data, tail = /\/([gim]*)$/.exec(data), modifiers = "";
+ if (regexp[0] === "/") {
+ if (tail) modifiers = tail[1];
+ if (modifiers.length > 3) return false;
+ if (regexp[regexp.length - modifiers.length - 1] !== "/") return false;
+ }
+ return true;
+ }
+ __name(resolveJavascriptRegExp, "resolveJavascriptRegExp");
+ function constructJavascriptRegExp(data) {
+ var regexp = data, tail = /\/([gim]*)$/.exec(data), modifiers = "";
+ if (regexp[0] === "/") {
+ if (tail) modifiers = tail[1];
+ regexp = regexp.slice(1, regexp.length - modifiers.length - 1);
+ }
+ return new RegExp(regexp, modifiers);
+ }
+ __name(constructJavascriptRegExp, "constructJavascriptRegExp");
+ function representJavascriptRegExp(object2) {
+ var result = "/" + object2.source + "/";
+ if (object2.global) result += "g";
+ if (object2.multiline) result += "m";
+ if (object2.ignoreCase) result += "i";
+ return result;
+ }
+ __name(representJavascriptRegExp, "representJavascriptRegExp");
+ function isRegExp(object2) {
+ return Object.prototype.toString.call(object2) === "[object RegExp]";
+ }
+ __name(isRegExp, "isRegExp");
+ module2.exports = new Type("tag:yaml.org,2002:js/regexp", {
+ kind: "scalar",
+ resolve: resolveJavascriptRegExp,
+ construct: constructJavascriptRegExp,
+ predicate: isRegExp,
+ represent: representJavascriptRegExp
+ });
+ }
+});
+
+// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/js/function.js
+var require_function = __commonJS({
+ "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/type/js/function.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var esprima;
+ try {
+ _require = __require;
+ esprima = _require("esprima");
+ } catch (_) {
+ if (typeof window !== "undefined") esprima = window.esprima;
+ }
+ var _require;
+ var Type = require_type();
+ function resolveJavascriptFunction(data) {
+ if (data === null) return false;
+ try {
+ var source = "(" + data + ")", ast = esprima.parse(source, { range: true });
+ if (ast.type !== "Program" || ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement" || ast.body[0].expression.type !== "ArrowFunctionExpression" && ast.body[0].expression.type !== "FunctionExpression") {
+ return false;
+ }
+ return true;
+ } catch (err) {
+ return false;
+ }
+ }
+ __name(resolveJavascriptFunction, "resolveJavascriptFunction");
+ function constructJavascriptFunction(data) {
+ var source = "(" + data + ")", ast = esprima.parse(source, { range: true }), params = [], body;
+ if (ast.type !== "Program" || ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement" || ast.body[0].expression.type !== "ArrowFunctionExpression" && ast.body[0].expression.type !== "FunctionExpression") {
+ throw new Error("Failed to resolve function");
+ }
+ ast.body[0].expression.params.forEach(function(param) {
+ params.push(param.name);
+ });
+ body = ast.body[0].expression.body.range;
+ if (ast.body[0].expression.body.type === "BlockStatement") {
+ return new Function(params, source.slice(body[0] + 1, body[1] - 1));
+ }
+ return new Function(params, "return " + source.slice(body[0], body[1]));
+ }
+ __name(constructJavascriptFunction, "constructJavascriptFunction");
+ function representJavascriptFunction(object2) {
+ return object2.toString();
+ }
+ __name(representJavascriptFunction, "representJavascriptFunction");
+ function isFunction2(object2) {
+ return Object.prototype.toString.call(object2) === "[object Function]";
+ }
+ __name(isFunction2, "isFunction");
+ module2.exports = new Type("tag:yaml.org,2002:js/function", {
+ kind: "scalar",
+ resolve: resolveJavascriptFunction,
+ construct: constructJavascriptFunction,
+ predicate: isFunction2,
+ represent: representJavascriptFunction
+ });
+ }
+});
+
+// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/schema/default_full.js
+var require_default_full = __commonJS({
+ "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/schema/default_full.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var Schema = require_schema();
+ module2.exports = Schema.DEFAULT = new Schema({
+ include: [
+ require_default_safe()
+ ],
+ explicit: [
+ require_undefined(),
+ require_regexp(),
+ require_function()
+ ]
+ });
+ }
+});
+
+// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/loader.js
+var require_loader = __commonJS({
+ "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/loader.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var common = require_common();
+ var YAMLException = require_exception();
+ var Mark = require_mark();
+ var DEFAULT_SAFE_SCHEMA = require_default_safe();
+ var DEFAULT_FULL_SCHEMA = require_default_full();
+ var _hasOwnProperty = Object.prototype.hasOwnProperty;
+ var CONTEXT_FLOW_IN = 1;
+ var CONTEXT_FLOW_OUT = 2;
+ var CONTEXT_BLOCK_IN = 3;
+ var CONTEXT_BLOCK_OUT = 4;
+ var CHOMPING_CLIP = 1;
+ var CHOMPING_STRIP = 2;
+ var CHOMPING_KEEP = 3;
+ var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
+ var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
+ var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/;
+ var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i;
+ var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;
+ function _class(obj) {
+ return Object.prototype.toString.call(obj);
+ }
+ __name(_class, "_class");
+ function is_EOL(c) {
+ return c === 10 || c === 13;
+ }
+ __name(is_EOL, "is_EOL");
+ function is_WHITE_SPACE(c) {
+ return c === 9 || c === 32;
+ }
+ __name(is_WHITE_SPACE, "is_WHITE_SPACE");
+ function is_WS_OR_EOL(c) {
+ return c === 9 || c === 32 || c === 10 || c === 13;
+ }
+ __name(is_WS_OR_EOL, "is_WS_OR_EOL");
+ function is_FLOW_INDICATOR(c) {
+ return c === 44 || c === 91 || c === 93 || c === 123 || c === 125;
+ }
+ __name(is_FLOW_INDICATOR, "is_FLOW_INDICATOR");
+ function fromHexCode(c) {
+ var lc;
+ if (48 <= c && c <= 57) {
+ return c - 48;
+ }
+ lc = c | 32;
+ if (97 <= lc && lc <= 102) {
+ return lc - 97 + 10;
+ }
+ return -1;
+ }
+ __name(fromHexCode, "fromHexCode");
+ function escapedHexLen(c) {
+ if (c === 120) {
+ return 2;
+ }
+ if (c === 117) {
+ return 4;
+ }
+ if (c === 85) {
+ return 8;
+ }
+ return 0;
+ }
+ __name(escapedHexLen, "escapedHexLen");
+ function fromDecimalCode(c) {
+ if (48 <= c && c <= 57) {
+ return c - 48;
+ }
+ return -1;
+ }
+ __name(fromDecimalCode, "fromDecimalCode");
+ function simpleEscapeSequence(c) {
+ return c === 48 ? "\0" : c === 97 ? "\x07" : c === 98 ? "\b" : c === 116 ? " " : c === 9 ? " " : c === 110 ? "\n" : c === 118 ? "\v" : c === 102 ? "\f" : c === 114 ? "\r" : c === 101 ? "\x1B" : c === 32 ? " " : c === 34 ? '"' : c === 47 ? "/" : c === 92 ? "\\" : c === 78 ? "\x85" : c === 95 ? "\xA0" : c === 76 ? "\u2028" : c === 80 ? "\u2029" : "";
+ }
+ __name(simpleEscapeSequence, "simpleEscapeSequence");
+ function charFromCodepoint(c) {
+ if (c <= 65535) {
+ return String.fromCharCode(c);
+ }
+ return String.fromCharCode(
+ (c - 65536 >> 10) + 55296,
+ (c - 65536 & 1023) + 56320
+ );
+ }
+ __name(charFromCodepoint, "charFromCodepoint");
+ function setProperty(object2, key, value) {
+ if (key === "__proto__") {
+ Object.defineProperty(object2, key, {
+ configurable: true,
+ enumerable: true,
+ writable: true,
+ value
+ });
+ } else {
+ object2[key] = value;
+ }
+ }
+ __name(setProperty, "setProperty");
+ var simpleEscapeCheck = new Array(256);
+ var simpleEscapeMap = new Array(256);
+ for (i = 0; i < 256; i++) {
+ simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;
+ simpleEscapeMap[i] = simpleEscapeSequence(i);
+ }
+ var i;
+ function State(input, options2) {
+ this.input = input;
+ this.filename = options2["filename"] || null;
+ this.schema = options2["schema"] || DEFAULT_FULL_SCHEMA;
+ this.onWarning = options2["onWarning"] || null;
+ this.legacy = options2["legacy"] || false;
+ this.json = options2["json"] || false;
+ this.listener = options2["listener"] || null;
+ this.implicitTypes = this.schema.compiledImplicit;
+ this.typeMap = this.schema.compiledTypeMap;
+ this.length = input.length;
+ this.position = 0;
+ this.line = 0;
+ this.lineStart = 0;
+ this.lineIndent = 0;
+ this.documents = [];
+ }
+ __name(State, "State");
+ function generateError(state, message) {
+ return new YAMLException(
+ message,
+ new Mark(state.filename, state.input, state.position, state.line, state.position - state.lineStart)
+ );
+ }
+ __name(generateError, "generateError");
+ function throwError(state, message) {
+ throw generateError(state, message);
+ }
+ __name(throwError, "throwError");
+ function throwWarning(state, message) {
+ if (state.onWarning) {
+ state.onWarning.call(null, generateError(state, message));
+ }
+ }
+ __name(throwWarning, "throwWarning");
+ var directiveHandlers = {
+ YAML: /* @__PURE__ */ __name(function handleYamlDirective(state, name, args) {
+ var match, major, minor;
+ if (state.version !== null) {
+ throwError(state, "duplication of %YAML directive");
+ }
+ if (args.length !== 1) {
+ throwError(state, "YAML directive accepts exactly one argument");
+ }
+ match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
+ if (match === null) {
+ throwError(state, "ill-formed argument of the YAML directive");
+ }
+ major = parseInt(match[1], 10);
+ minor = parseInt(match[2], 10);
+ if (major !== 1) {
+ throwError(state, "unacceptable YAML version of the document");
+ }
+ state.version = args[0];
+ state.checkLineBreaks = minor < 2;
+ if (minor !== 1 && minor !== 2) {
+ throwWarning(state, "unsupported YAML version of the document");
+ }
+ }, "handleYamlDirective"),
+ TAG: /* @__PURE__ */ __name(function handleTagDirective(state, name, args) {
+ var handle, prefix;
+ if (args.length !== 2) {
+ throwError(state, "TAG directive accepts exactly two arguments");
+ }
+ handle = args[0];
+ prefix = args[1];
+ if (!PATTERN_TAG_HANDLE.test(handle)) {
+ throwError(state, "ill-formed tag handle (first argument) of the TAG directive");
+ }
+ if (_hasOwnProperty.call(state.tagMap, handle)) {
+ throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle');
+ }
+ if (!PATTERN_TAG_URI.test(prefix)) {
+ throwError(state, "ill-formed tag prefix (second argument) of the TAG directive");
+ }
+ state.tagMap[handle] = prefix;
+ }, "handleTagDirective")
+ };
+ function captureSegment(state, start, end, checkJson) {
+ var _position, _length2, _character, _result;
+ if (start < end) {
+ _result = state.input.slice(start, end);
+ if (checkJson) {
+ for (_position = 0, _length2 = _result.length; _position < _length2; _position += 1) {
+ _character = _result.charCodeAt(_position);
+ if (!(_character === 9 || 32 <= _character && _character <= 1114111)) {
+ throwError(state, "expected valid JSON character");
+ }
+ }
+ } else if (PATTERN_NON_PRINTABLE.test(_result)) {
+ throwError(state, "the stream contains non-printable characters");
+ }
+ state.result += _result;
+ }
+ }
+ __name(captureSegment, "captureSegment");
+ function mergeMappings(state, destination, source, overridableKeys) {
+ var sourceKeys, key, index, quantity;
+ if (!common.isObject(source)) {
+ throwError(state, "cannot merge mappings; the provided source object is unacceptable");
+ }
+ sourceKeys = Object.keys(source);
+ for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {
+ key = sourceKeys[index];
+ if (!_hasOwnProperty.call(destination, key)) {
+ setProperty(destination, key, source[key]);
+ overridableKeys[key] = true;
+ }
+ }
+ }
+ __name(mergeMappings, "mergeMappings");
+ function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) {
+ var index, quantity;
+ if (Array.isArray(keyNode)) {
+ keyNode = Array.prototype.slice.call(keyNode);
+ for (index = 0, quantity = keyNode.length; index < quantity; index += 1) {
+ if (Array.isArray(keyNode[index])) {
+ throwError(state, "nested arrays are not supported inside keys");
+ }
+ if (typeof keyNode === "object" && _class(keyNode[index]) === "[object Object]") {
+ keyNode[index] = "[object Object]";
+ }
+ }
+ }
+ if (typeof keyNode === "object" && _class(keyNode) === "[object Object]") {
+ keyNode = "[object Object]";
+ }
+ keyNode = String(keyNode);
+ if (_result === null) {
+ _result = {};
+ }
+ if (keyTag === "tag:yaml.org,2002:merge") {
+ if (Array.isArray(valueNode)) {
+ for (index = 0, quantity = valueNode.length; index < quantity; index += 1) {
+ mergeMappings(state, _result, valueNode[index], overridableKeys);
+ }
+ } else {
+ mergeMappings(state, _result, valueNode, overridableKeys);
+ }
+ } else {
+ if (!state.json && !_hasOwnProperty.call(overridableKeys, keyNode) && _hasOwnProperty.call(_result, keyNode)) {
+ state.line = startLine || state.line;
+ state.position = startPos || state.position;
+ throwError(state, "duplicated mapping key");
+ }
+ setProperty(_result, keyNode, valueNode);
+ delete overridableKeys[keyNode];
+ }
+ return _result;
+ }
+ __name(storeMappingPair, "storeMappingPair");
+ function readLineBreak(state) {
+ var ch;
+ ch = state.input.charCodeAt(state.position);
+ if (ch === 10) {
+ state.position++;
+ } else if (ch === 13) {
+ state.position++;
+ if (state.input.charCodeAt(state.position) === 10) {
+ state.position++;
+ }
+ } else {
+ throwError(state, "a line break is expected");
+ }
+ state.line += 1;
+ state.lineStart = state.position;
+ }
+ __name(readLineBreak, "readLineBreak");
+ function skipSeparationSpace(state, allowComments, checkIndent) {
+ var lineBreaks = 0, ch = state.input.charCodeAt(state.position);
+ while (ch !== 0) {
+ while (is_WHITE_SPACE(ch)) {
+ ch = state.input.charCodeAt(++state.position);
+ }
+ if (allowComments && ch === 35) {
+ do {
+ ch = state.input.charCodeAt(++state.position);
+ } while (ch !== 10 && ch !== 13 && ch !== 0);
+ }
+ if (is_EOL(ch)) {
+ readLineBreak(state);
+ ch = state.input.charCodeAt(state.position);
+ lineBreaks++;
+ state.lineIndent = 0;
+ while (ch === 32) {
+ state.lineIndent++;
+ ch = state.input.charCodeAt(++state.position);
+ }
+ } else {
+ break;
+ }
+ }
+ if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {
+ throwWarning(state, "deficient indentation");
+ }
+ return lineBreaks;
+ }
+ __name(skipSeparationSpace, "skipSeparationSpace");
+ function testDocumentSeparator(state) {
+ var _position = state.position, ch;
+ ch = state.input.charCodeAt(_position);
+ if ((ch === 45 || ch === 46) && ch === state.input.charCodeAt(_position + 1) && ch === state.input.charCodeAt(_position + 2)) {
+ _position += 3;
+ ch = state.input.charCodeAt(_position);
+ if (ch === 0 || is_WS_OR_EOL(ch)) {
+ return true;
+ }
+ }
+ return false;
+ }
+ __name(testDocumentSeparator, "testDocumentSeparator");
+ function writeFoldedLines(state, count) {
+ if (count === 1) {
+ state.result += " ";
+ } else if (count > 1) {
+ state.result += common.repeat("\n", count - 1);
+ }
+ }
+ __name(writeFoldedLines, "writeFoldedLines");
+ function readPlainScalar(state, nodeIndent, withinFlowCollection) {
+ var preceding, following, captureStart, captureEnd, hasPendingContent, _line, _lineStart, _lineIndent, _kind = state.kind, _result = state.result, ch;
+ ch = state.input.charCodeAt(state.position);
+ if (is_WS_OR_EOL(ch) || is_FLOW_INDICATOR(ch) || ch === 35 || ch === 38 || ch === 42 || ch === 33 || ch === 124 || ch === 62 || ch === 39 || ch === 34 || ch === 37 || ch === 64 || ch === 96) {
+ return false;
+ }
+ if (ch === 63 || ch === 45) {
+ following = state.input.charCodeAt(state.position + 1);
+ if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) {
+ return false;
+ }
+ }
+ state.kind = "scalar";
+ state.result = "";
+ captureStart = captureEnd = state.position;
+ hasPendingContent = false;
+ while (ch !== 0) {
+ if (ch === 58) {
+ following = state.input.charCodeAt(state.position + 1);
+ if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) {
+ break;
+ }
+ } else if (ch === 35) {
+ preceding = state.input.charCodeAt(state.position - 1);
+ if (is_WS_OR_EOL(preceding)) {
+ break;
+ }
+ } else if (state.position === state.lineStart && testDocumentSeparator(state) || withinFlowCollection && is_FLOW_INDICATOR(ch)) {
+ break;
+ } else if (is_EOL(ch)) {
+ _line = state.line;
+ _lineStart = state.lineStart;
+ _lineIndent = state.lineIndent;
+ skipSeparationSpace(state, false, -1);
+ if (state.lineIndent >= nodeIndent) {
+ hasPendingContent = true;
+ ch = state.input.charCodeAt(state.position);
+ continue;
+ } else {
+ state.position = captureEnd;
+ state.line = _line;
+ state.lineStart = _lineStart;
+ state.lineIndent = _lineIndent;
+ break;
+ }
+ }
+ if (hasPendingContent) {
+ captureSegment(state, captureStart, captureEnd, false);
+ writeFoldedLines(state, state.line - _line);
+ captureStart = captureEnd = state.position;
+ hasPendingContent = false;
+ }
+ if (!is_WHITE_SPACE(ch)) {
+ captureEnd = state.position + 1;
+ }
+ ch = state.input.charCodeAt(++state.position);
+ }
+ captureSegment(state, captureStart, captureEnd, false);
+ if (state.result) {
+ return true;
+ }
+ state.kind = _kind;
+ state.result = _result;
+ return false;
+ }
+ __name(readPlainScalar, "readPlainScalar");
+ function readSingleQuotedScalar(state, nodeIndent) {
+ var ch, captureStart, captureEnd;
+ ch = state.input.charCodeAt(state.position);
+ if (ch !== 39) {
+ return false;
+ }
+ state.kind = "scalar";
+ state.result = "";
+ state.position++;
+ captureStart = captureEnd = state.position;
+ while ((ch = state.input.charCodeAt(state.position)) !== 0) {
+ if (ch === 39) {
+ captureSegment(state, captureStart, state.position, true);
+ ch = state.input.charCodeAt(++state.position);
+ if (ch === 39) {
+ captureStart = state.position;
+ state.position++;
+ captureEnd = state.position;
+ } else {
+ return true;
+ }
+ } else if (is_EOL(ch)) {
+ captureSegment(state, captureStart, captureEnd, true);
+ writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
+ captureStart = captureEnd = state.position;
+ } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
+ throwError(state, "unexpected end of the document within a single quoted scalar");
+ } else {
+ state.position++;
+ captureEnd = state.position;
+ }
+ }
+ throwError(state, "unexpected end of the stream within a single quoted scalar");
+ }
+ __name(readSingleQuotedScalar, "readSingleQuotedScalar");
+ function readDoubleQuotedScalar(state, nodeIndent) {
+ var captureStart, captureEnd, hexLength, hexResult, tmp, ch;
+ ch = state.input.charCodeAt(state.position);
+ if (ch !== 34) {
+ return false;
+ }
+ state.kind = "scalar";
+ state.result = "";
+ state.position++;
+ captureStart = captureEnd = state.position;
+ while ((ch = state.input.charCodeAt(state.position)) !== 0) {
+ if (ch === 34) {
+ captureSegment(state, captureStart, state.position, true);
+ state.position++;
+ return true;
+ } else if (ch === 92) {
+ captureSegment(state, captureStart, state.position, true);
+ ch = state.input.charCodeAt(++state.position);
+ if (is_EOL(ch)) {
+ skipSeparationSpace(state, false, nodeIndent);
+ } else if (ch < 256 && simpleEscapeCheck[ch]) {
+ state.result += simpleEscapeMap[ch];
+ state.position++;
+ } else if ((tmp = escapedHexLen(ch)) > 0) {
+ hexLength = tmp;
+ hexResult = 0;
+ for (; hexLength > 0; hexLength--) {
+ ch = state.input.charCodeAt(++state.position);
+ if ((tmp = fromHexCode(ch)) >= 0) {
+ hexResult = (hexResult << 4) + tmp;
+ } else {
+ throwError(state, "expected hexadecimal character");
+ }
+ }
+ state.result += charFromCodepoint(hexResult);
+ state.position++;
+ } else {
+ throwError(state, "unknown escape sequence");
+ }
+ captureStart = captureEnd = state.position;
+ } else if (is_EOL(ch)) {
+ captureSegment(state, captureStart, captureEnd, true);
+ writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
+ captureStart = captureEnd = state.position;
+ } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
+ throwError(state, "unexpected end of the document within a double quoted scalar");
+ } else {
+ state.position++;
+ captureEnd = state.position;
+ }
+ }
+ throwError(state, "unexpected end of the stream within a double quoted scalar");
+ }
+ __name(readDoubleQuotedScalar, "readDoubleQuotedScalar");
+ function readFlowCollection(state, nodeIndent) {
+ var readNext = true, _line, _tag = state.tag, _result, _anchor = state.anchor, following, terminator, isPair, isExplicitPair, isMapping, overridableKeys = {}, keyNode, keyTag, valueNode, ch;
+ ch = state.input.charCodeAt(state.position);
+ if (ch === 91) {
+ terminator = 93;
+ isMapping = false;
+ _result = [];
+ } else if (ch === 123) {
+ terminator = 125;
+ isMapping = true;
+ _result = {};
+ } else {
+ return false;
+ }
+ if (state.anchor !== null) {
+ state.anchorMap[state.anchor] = _result;
+ }
+ ch = state.input.charCodeAt(++state.position);
+ while (ch !== 0) {
+ skipSeparationSpace(state, true, nodeIndent);
+ ch = state.input.charCodeAt(state.position);
+ if (ch === terminator) {
+ state.position++;
+ state.tag = _tag;
+ state.anchor = _anchor;
+ state.kind = isMapping ? "mapping" : "sequence";
+ state.result = _result;
+ return true;
+ } else if (!readNext) {
+ throwError(state, "missed comma between flow collection entries");
+ }
+ keyTag = keyNode = valueNode = null;
+ isPair = isExplicitPair = false;
+ if (ch === 63) {
+ following = state.input.charCodeAt(state.position + 1);
+ if (is_WS_OR_EOL(following)) {
+ isPair = isExplicitPair = true;
+ state.position++;
+ skipSeparationSpace(state, true, nodeIndent);
+ }
+ }
+ _line = state.line;
+ composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
+ keyTag = state.tag;
+ keyNode = state.result;
+ skipSeparationSpace(state, true, nodeIndent);
+ ch = state.input.charCodeAt(state.position);
+ if ((isExplicitPair || state.line === _line) && ch === 58) {
+ isPair = true;
+ ch = state.input.charCodeAt(++state.position);
+ skipSeparationSpace(state, true, nodeIndent);
+ composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
+ valueNode = state.result;
+ }
+ if (isMapping) {
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode);
+ } else if (isPair) {
+ _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode));
+ } else {
+ _result.push(keyNode);
+ }
+ skipSeparationSpace(state, true, nodeIndent);
+ ch = state.input.charCodeAt(state.position);
+ if (ch === 44) {
+ readNext = true;
+ ch = state.input.charCodeAt(++state.position);
+ } else {
+ readNext = false;
+ }
+ }
+ throwError(state, "unexpected end of the stream within a flow collection");
+ }
+ __name(readFlowCollection, "readFlowCollection");
+ function readBlockScalar(state, nodeIndent) {
+ var captureStart, folding, chomping = CHOMPING_CLIP, didReadContent = false, detectedIndent = false, textIndent = nodeIndent, emptyLines = 0, atMoreIndented = false, tmp, ch;
+ ch = state.input.charCodeAt(state.position);
+ if (ch === 124) {
+ folding = false;
+ } else if (ch === 62) {
+ folding = true;
+ } else {
+ return false;
+ }
+ state.kind = "scalar";
+ state.result = "";
+ while (ch !== 0) {
+ ch = state.input.charCodeAt(++state.position);
+ if (ch === 43 || ch === 45) {
+ if (CHOMPING_CLIP === chomping) {
+ chomping = ch === 43 ? CHOMPING_KEEP : CHOMPING_STRIP;
+ } else {
+ throwError(state, "repeat of a chomping mode identifier");
+ }
+ } else if ((tmp = fromDecimalCode(ch)) >= 0) {
+ if (tmp === 0) {
+ throwError(state, "bad explicit indentation width of a block scalar; it cannot be less than one");
+ } else if (!detectedIndent) {
+ textIndent = nodeIndent + tmp - 1;
+ detectedIndent = true;
+ } else {
+ throwError(state, "repeat of an indentation width identifier");
+ }
+ } else {
+ break;
+ }
+ }
+ if (is_WHITE_SPACE(ch)) {
+ do {
+ ch = state.input.charCodeAt(++state.position);
+ } while (is_WHITE_SPACE(ch));
+ if (ch === 35) {
+ do {
+ ch = state.input.charCodeAt(++state.position);
+ } while (!is_EOL(ch) && ch !== 0);
+ }
+ }
+ while (ch !== 0) {
+ readLineBreak(state);
+ state.lineIndent = 0;
+ ch = state.input.charCodeAt(state.position);
+ while ((!detectedIndent || state.lineIndent < textIndent) && ch === 32) {
+ state.lineIndent++;
+ ch = state.input.charCodeAt(++state.position);
+ }
+ if (!detectedIndent && state.lineIndent > textIndent) {
+ textIndent = state.lineIndent;
+ }
+ if (is_EOL(ch)) {
+ emptyLines++;
+ continue;
+ }
+ if (state.lineIndent < textIndent) {
+ if (chomping === CHOMPING_KEEP) {
+ state.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
+ } else if (chomping === CHOMPING_CLIP) {
+ if (didReadContent) {
+ state.result += "\n";
+ }
+ }
+ break;
+ }
+ if (folding) {
+ if (is_WHITE_SPACE(ch)) {
+ atMoreIndented = true;
+ state.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
+ } else if (atMoreIndented) {
+ atMoreIndented = false;
+ state.result += common.repeat("\n", emptyLines + 1);
+ } else if (emptyLines === 0) {
+ if (didReadContent) {
+ state.result += " ";
+ }
+ } else {
+ state.result += common.repeat("\n", emptyLines);
+ }
+ } else {
+ state.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
+ }
+ didReadContent = true;
+ detectedIndent = true;
+ emptyLines = 0;
+ captureStart = state.position;
+ while (!is_EOL(ch) && ch !== 0) {
+ ch = state.input.charCodeAt(++state.position);
+ }
+ captureSegment(state, captureStart, state.position, false);
+ }
+ return true;
+ }
+ __name(readBlockScalar, "readBlockScalar");
+ function readBlockSequence(state, nodeIndent) {
+ var _line, _tag = state.tag, _anchor = state.anchor, _result = [], following, detected = false, ch;
+ if (state.anchor !== null) {
+ state.anchorMap[state.anchor] = _result;
+ }
+ ch = state.input.charCodeAt(state.position);
+ while (ch !== 0) {
+ if (ch !== 45) {
+ break;
+ }
+ following = state.input.charCodeAt(state.position + 1);
+ if (!is_WS_OR_EOL(following)) {
+ break;
+ }
+ detected = true;
+ state.position++;
+ if (skipSeparationSpace(state, true, -1)) {
+ if (state.lineIndent <= nodeIndent) {
+ _result.push(null);
+ ch = state.input.charCodeAt(state.position);
+ continue;
+ }
+ }
+ _line = state.line;
+ composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);
+ _result.push(state.result);
+ skipSeparationSpace(state, true, -1);
+ ch = state.input.charCodeAt(state.position);
+ if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) {
+ throwError(state, "bad indentation of a sequence entry");
+ } else if (state.lineIndent < nodeIndent) {
+ break;
+ }
+ }
+ if (detected) {
+ state.tag = _tag;
+ state.anchor = _anchor;
+ state.kind = "sequence";
+ state.result = _result;
+ return true;
+ }
+ return false;
+ }
+ __name(readBlockSequence, "readBlockSequence");
+ function readBlockMapping(state, nodeIndent, flowIndent) {
+ var following, allowCompact, _line, _pos, _tag = state.tag, _anchor = state.anchor, _result = {}, overridableKeys = {}, keyTag = null, keyNode = null, valueNode = null, atExplicitKey = false, detected = false, ch;
+ if (state.anchor !== null) {
+ state.anchorMap[state.anchor] = _result;
+ }
+ ch = state.input.charCodeAt(state.position);
+ while (ch !== 0) {
+ following = state.input.charCodeAt(state.position + 1);
+ _line = state.line;
+ _pos = state.position;
+ if ((ch === 63 || ch === 58) && is_WS_OR_EOL(following)) {
+ if (ch === 63) {
+ if (atExplicitKey) {
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
+ keyTag = keyNode = valueNode = null;
+ }
+ detected = true;
+ atExplicitKey = true;
+ allowCompact = true;
+ } else if (atExplicitKey) {
+ atExplicitKey = false;
+ allowCompact = true;
+ } else {
+ throwError(state, "incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line");
+ }
+ state.position += 1;
+ ch = following;
+ } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {
+ if (state.line === _line) {
+ ch = state.input.charCodeAt(state.position);
+ while (is_WHITE_SPACE(ch)) {
+ ch = state.input.charCodeAt(++state.position);
+ }
+ if (ch === 58) {
+ ch = state.input.charCodeAt(++state.position);
+ if (!is_WS_OR_EOL(ch)) {
+ throwError(state, "a whitespace character is expected after the key-value separator within a block mapping");
+ }
+ if (atExplicitKey) {
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
+ keyTag = keyNode = valueNode = null;
+ }
+ detected = true;
+ atExplicitKey = false;
+ allowCompact = false;
+ keyTag = state.tag;
+ keyNode = state.result;
+ } else if (detected) {
+ throwError(state, "can not read an implicit mapping pair; a colon is missed");
+ } else {
+ state.tag = _tag;
+ state.anchor = _anchor;
+ return true;
+ }
+ } else if (detected) {
+ throwError(state, "can not read a block mapping entry; a multiline key may not be an implicit key");
+ } else {
+ state.tag = _tag;
+ state.anchor = _anchor;
+ return true;
+ }
+ } else {
+ break;
+ }
+ if (state.line === _line || state.lineIndent > nodeIndent) {
+ if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {
+ if (atExplicitKey) {
+ keyNode = state.result;
+ } else {
+ valueNode = state.result;
+ }
+ }
+ if (!atExplicitKey) {
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos);
+ keyTag = keyNode = valueNode = null;
+ }
+ skipSeparationSpace(state, true, -1);
+ ch = state.input.charCodeAt(state.position);
+ }
+ if (state.lineIndent > nodeIndent && ch !== 0) {
+ throwError(state, "bad indentation of a mapping entry");
+ } else if (state.lineIndent < nodeIndent) {
+ break;
+ }
+ }
+ if (atExplicitKey) {
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null);
+ }
+ if (detected) {
+ state.tag = _tag;
+ state.anchor = _anchor;
+ state.kind = "mapping";
+ state.result = _result;
+ }
+ return detected;
+ }
+ __name(readBlockMapping, "readBlockMapping");
+ function readTagProperty(state) {
+ var _position, isVerbatim = false, isNamed = false, tagHandle, tagName, ch;
+ ch = state.input.charCodeAt(state.position);
+ if (ch !== 33) return false;
+ if (state.tag !== null) {
+ throwError(state, "duplication of a tag property");
+ }
+ ch = state.input.charCodeAt(++state.position);
+ if (ch === 60) {
+ isVerbatim = true;
+ ch = state.input.charCodeAt(++state.position);
+ } else if (ch === 33) {
+ isNamed = true;
+ tagHandle = "!!";
+ ch = state.input.charCodeAt(++state.position);
+ } else {
+ tagHandle = "!";
+ }
+ _position = state.position;
+ if (isVerbatim) {
+ do {
+ ch = state.input.charCodeAt(++state.position);
+ } while (ch !== 0 && ch !== 62);
+ if (state.position < state.length) {
+ tagName = state.input.slice(_position, state.position);
+ ch = state.input.charCodeAt(++state.position);
+ } else {
+ throwError(state, "unexpected end of the stream within a verbatim tag");
+ }
+ } else {
+ while (ch !== 0 && !is_WS_OR_EOL(ch)) {
+ if (ch === 33) {
+ if (!isNamed) {
+ tagHandle = state.input.slice(_position - 1, state.position + 1);
+ if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
+ throwError(state, "named tag handle cannot contain such characters");
+ }
+ isNamed = true;
+ _position = state.position + 1;
+ } else {
+ throwError(state, "tag suffix cannot contain exclamation marks");
+ }
+ }
+ ch = state.input.charCodeAt(++state.position);
+ }
+ tagName = state.input.slice(_position, state.position);
+ if (PATTERN_FLOW_INDICATORS.test(tagName)) {
+ throwError(state, "tag suffix cannot contain flow indicator characters");
+ }
+ }
+ if (tagName && !PATTERN_TAG_URI.test(tagName)) {
+ throwError(state, "tag name cannot contain such characters: " + tagName);
+ }
+ if (isVerbatim) {
+ state.tag = tagName;
+ } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) {
+ state.tag = state.tagMap[tagHandle] + tagName;
+ } else if (tagHandle === "!") {
+ state.tag = "!" + tagName;
+ } else if (tagHandle === "!!") {
+ state.tag = "tag:yaml.org,2002:" + tagName;
+ } else {
+ throwError(state, 'undeclared tag handle "' + tagHandle + '"');
+ }
+ return true;
+ }
+ __name(readTagProperty, "readTagProperty");
+ function readAnchorProperty(state) {
+ var _position, ch;
+ ch = state.input.charCodeAt(state.position);
+ if (ch !== 38) return false;
+ if (state.anchor !== null) {
+ throwError(state, "duplication of an anchor property");
+ }
+ ch = state.input.charCodeAt(++state.position);
+ _position = state.position;
+ while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
+ ch = state.input.charCodeAt(++state.position);
+ }
+ if (state.position === _position) {
+ throwError(state, "name of an anchor node must contain at least one character");
+ }
+ state.anchor = state.input.slice(_position, state.position);
+ return true;
+ }
+ __name(readAnchorProperty, "readAnchorProperty");
+ function readAlias(state) {
+ var _position, alias, ch;
+ ch = state.input.charCodeAt(state.position);
+ if (ch !== 42) return false;
+ ch = state.input.charCodeAt(++state.position);
+ _position = state.position;
+ while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
+ ch = state.input.charCodeAt(++state.position);
+ }
+ if (state.position === _position) {
+ throwError(state, "name of an alias node must contain at least one character");
+ }
+ alias = state.input.slice(_position, state.position);
+ if (!_hasOwnProperty.call(state.anchorMap, alias)) {
+ throwError(state, 'unidentified alias "' + alias + '"');
+ }
+ state.result = state.anchorMap[alias];
+ skipSeparationSpace(state, true, -1);
+ return true;
+ }
+ __name(readAlias, "readAlias");
+ function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {
+ var allowBlockStyles, allowBlockScalars, allowBlockCollections, indentStatus = 1, atNewLine = false, hasContent = false, typeIndex, typeQuantity, type2, flowIndent, blockIndent;
+ if (state.listener !== null) {
+ state.listener("open", state);
+ }
+ state.tag = null;
+ state.anchor = null;
+ state.kind = null;
+ state.result = null;
+ allowBlockStyles = allowBlockScalars = allowBlockCollections = CONTEXT_BLOCK_OUT === nodeContext || CONTEXT_BLOCK_IN === nodeContext;
+ if (allowToSeek) {
+ if (skipSeparationSpace(state, true, -1)) {
+ atNewLine = true;
+ if (state.lineIndent > parentIndent) {
+ indentStatus = 1;
+ } else if (state.lineIndent === parentIndent) {
+ indentStatus = 0;
+ } else if (state.lineIndent < parentIndent) {
+ indentStatus = -1;
+ }
+ }
+ }
+ if (indentStatus === 1) {
+ while (readTagProperty(state) || readAnchorProperty(state)) {
+ if (skipSeparationSpace(state, true, -1)) {
+ atNewLine = true;
+ allowBlockCollections = allowBlockStyles;
+ if (state.lineIndent > parentIndent) {
+ indentStatus = 1;
+ } else if (state.lineIndent === parentIndent) {
+ indentStatus = 0;
+ } else if (state.lineIndent < parentIndent) {
+ indentStatus = -1;
+ }
+ } else {
+ allowBlockCollections = false;
+ }
+ }
+ }
+ if (allowBlockCollections) {
+ allowBlockCollections = atNewLine || allowCompact;
+ }
+ if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {
+ if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {
+ flowIndent = parentIndent;
+ } else {
+ flowIndent = parentIndent + 1;
+ }
+ blockIndent = state.position - state.lineStart;
+ if (indentStatus === 1) {
+ if (allowBlockCollections && (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent)) || readFlowCollection(state, flowIndent)) {
+ hasContent = true;
+ } else {
+ if (allowBlockScalars && readBlockScalar(state, flowIndent) || readSingleQuotedScalar(state, flowIndent) || readDoubleQuotedScalar(state, flowIndent)) {
+ hasContent = true;
+ } else if (readAlias(state)) {
+ hasContent = true;
+ if (state.tag !== null || state.anchor !== null) {
+ throwError(state, "alias node should not have any properties");
+ }
+ } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {
+ hasContent = true;
+ if (state.tag === null) {
+ state.tag = "?";
+ }
+ }
+ if (state.anchor !== null) {
+ state.anchorMap[state.anchor] = state.result;
+ }
+ }
+ } else if (indentStatus === 0) {
+ hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);
+ }
+ }
+ if (state.tag !== null && state.tag !== "!") {
+ if (state.tag === "?") {
+ if (state.result !== null && state.kind !== "scalar") {
+ throwError(state, 'unacceptable node kind for !> tag; it should be "scalar", not "' + state.kind + '"');
+ }
+ for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {
+ type2 = state.implicitTypes[typeIndex];
+ if (type2.resolve(state.result)) {
+ state.result = type2.construct(state.result);
+ state.tag = type2.tag;
+ if (state.anchor !== null) {
+ state.anchorMap[state.anchor] = state.result;
+ }
+ break;
+ }
+ }
+ } else if (_hasOwnProperty.call(state.typeMap[state.kind || "fallback"], state.tag)) {
+ type2 = state.typeMap[state.kind || "fallback"][state.tag];
+ if (state.result !== null && type2.kind !== state.kind) {
+ throwError(state, "unacceptable node kind for !<" + state.tag + '> tag; it should be "' + type2.kind + '", not "' + state.kind + '"');
+ }
+ if (!type2.resolve(state.result)) {
+ throwError(state, "cannot resolve a node with !<" + state.tag + "> explicit tag");
+ } else {
+ state.result = type2.construct(state.result);
+ if (state.anchor !== null) {
+ state.anchorMap[state.anchor] = state.result;
+ }
+ }
+ } else {
+ throwError(state, "unknown tag !<" + state.tag + ">");
+ }
+ }
+ if (state.listener !== null) {
+ state.listener("close", state);
+ }
+ return state.tag !== null || state.anchor !== null || hasContent;
+ }
+ __name(composeNode, "composeNode");
+ function readDocument(state) {
+ var documentStart = state.position, _position, directiveName, directiveArgs, hasDirectives = false, ch;
+ state.version = null;
+ state.checkLineBreaks = state.legacy;
+ state.tagMap = {};
+ state.anchorMap = {};
+ while ((ch = state.input.charCodeAt(state.position)) !== 0) {
+ skipSeparationSpace(state, true, -1);
+ ch = state.input.charCodeAt(state.position);
+ if (state.lineIndent > 0 || ch !== 37) {
+ break;
+ }
+ hasDirectives = true;
+ ch = state.input.charCodeAt(++state.position);
+ _position = state.position;
+ while (ch !== 0 && !is_WS_OR_EOL(ch)) {
+ ch = state.input.charCodeAt(++state.position);
+ }
+ directiveName = state.input.slice(_position, state.position);
+ directiveArgs = [];
+ if (directiveName.length < 1) {
+ throwError(state, "directive name must not be less than one character in length");
+ }
+ while (ch !== 0) {
+ while (is_WHITE_SPACE(ch)) {
+ ch = state.input.charCodeAt(++state.position);
+ }
+ if (ch === 35) {
+ do {
+ ch = state.input.charCodeAt(++state.position);
+ } while (ch !== 0 && !is_EOL(ch));
+ break;
+ }
+ if (is_EOL(ch)) break;
+ _position = state.position;
+ while (ch !== 0 && !is_WS_OR_EOL(ch)) {
+ ch = state.input.charCodeAt(++state.position);
+ }
+ directiveArgs.push(state.input.slice(_position, state.position));
+ }
+ if (ch !== 0) readLineBreak(state);
+ if (_hasOwnProperty.call(directiveHandlers, directiveName)) {
+ directiveHandlers[directiveName](state, directiveName, directiveArgs);
+ } else {
+ throwWarning(state, 'unknown document directive "' + directiveName + '"');
+ }
+ }
+ skipSeparationSpace(state, true, -1);
+ if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 45 && state.input.charCodeAt(state.position + 1) === 45 && state.input.charCodeAt(state.position + 2) === 45) {
+ state.position += 3;
+ skipSeparationSpace(state, true, -1);
+ } else if (hasDirectives) {
+ throwError(state, "directives end mark is expected");
+ }
+ composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);
+ skipSeparationSpace(state, true, -1);
+ if (state.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {
+ throwWarning(state, "non-ASCII line breaks are interpreted as content");
+ }
+ state.documents.push(state.result);
+ if (state.position === state.lineStart && testDocumentSeparator(state)) {
+ if (state.input.charCodeAt(state.position) === 46) {
+ state.position += 3;
+ skipSeparationSpace(state, true, -1);
+ }
+ return;
+ }
+ if (state.position < state.length - 1) {
+ throwError(state, "end of the stream or a document separator is expected");
+ } else {
+ return;
+ }
+ }
+ __name(readDocument, "readDocument");
+ function loadDocuments(input, options2) {
+ input = String(input);
+ options2 = options2 || {};
+ if (input.length !== 0) {
+ if (input.charCodeAt(input.length - 1) !== 10 && input.charCodeAt(input.length - 1) !== 13) {
+ input += "\n";
+ }
+ if (input.charCodeAt(0) === 65279) {
+ input = input.slice(1);
+ }
+ }
+ var state = new State(input, options2);
+ var nullpos = input.indexOf("\0");
+ if (nullpos !== -1) {
+ state.position = nullpos;
+ throwError(state, "null byte is not allowed in input");
+ }
+ state.input += "\0";
+ while (state.input.charCodeAt(state.position) === 32) {
+ state.lineIndent += 1;
+ state.position += 1;
+ }
+ while (state.position < state.length - 1) {
+ readDocument(state);
+ }
+ return state.documents;
+ }
+ __name(loadDocuments, "loadDocuments");
+ function loadAll(input, iterator, options2) {
+ if (iterator !== null && typeof iterator === "object" && typeof options2 === "undefined") {
+ options2 = iterator;
+ iterator = null;
+ }
+ var documents = loadDocuments(input, options2);
+ if (typeof iterator !== "function") {
+ return documents;
+ }
+ for (var index = 0, length = documents.length; index < length; index += 1) {
+ iterator(documents[index]);
+ }
+ }
+ __name(loadAll, "loadAll");
+ function load(input, options2) {
+ var documents = loadDocuments(input, options2);
+ if (documents.length === 0) {
+ return void 0;
+ } else if (documents.length === 1) {
+ return documents[0];
+ }
+ throw new YAMLException("expected a single document in the stream, but found more");
+ }
+ __name(load, "load");
+ function safeLoadAll(input, iterator, options2) {
+ if (typeof iterator === "object" && iterator !== null && typeof options2 === "undefined") {
+ options2 = iterator;
+ iterator = null;
+ }
+ return loadAll(input, iterator, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options2));
+ }
+ __name(safeLoadAll, "safeLoadAll");
+ function safeLoad(input, options2) {
+ return load(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options2));
+ }
+ __name(safeLoad, "safeLoad");
+ module2.exports.loadAll = loadAll;
+ module2.exports.load = load;
+ module2.exports.safeLoadAll = safeLoadAll;
+ module2.exports.safeLoad = safeLoad;
+ }
+});
+
+// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/dumper.js
+var require_dumper = __commonJS({
+ "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml/dumper.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var common = require_common();
+ var YAMLException = require_exception();
+ var DEFAULT_FULL_SCHEMA = require_default_full();
+ var DEFAULT_SAFE_SCHEMA = require_default_safe();
+ var _toString = Object.prototype.toString;
+ var _hasOwnProperty = Object.prototype.hasOwnProperty;
+ var CHAR_TAB = 9;
+ var CHAR_LINE_FEED = 10;
+ var CHAR_CARRIAGE_RETURN = 13;
+ var CHAR_SPACE = 32;
+ var CHAR_EXCLAMATION = 33;
+ var CHAR_DOUBLE_QUOTE = 34;
+ var CHAR_SHARP = 35;
+ var CHAR_PERCENT = 37;
+ var CHAR_AMPERSAND = 38;
+ var CHAR_SINGLE_QUOTE = 39;
+ var CHAR_ASTERISK = 42;
+ var CHAR_COMMA = 44;
+ var CHAR_MINUS = 45;
+ var CHAR_COLON = 58;
+ var CHAR_EQUALS = 61;
+ var CHAR_GREATER_THAN = 62;
+ var CHAR_QUESTION = 63;
+ var CHAR_COMMERCIAL_AT = 64;
+ var CHAR_LEFT_SQUARE_BRACKET = 91;
+ var CHAR_RIGHT_SQUARE_BRACKET = 93;
+ var CHAR_GRAVE_ACCENT = 96;
+ var CHAR_LEFT_CURLY_BRACKET = 123;
+ var CHAR_VERTICAL_LINE = 124;
+ var CHAR_RIGHT_CURLY_BRACKET = 125;
+ var ESCAPE_SEQUENCES = {};
+ ESCAPE_SEQUENCES[0] = "\\0";
+ ESCAPE_SEQUENCES[7] = "\\a";
+ ESCAPE_SEQUENCES[8] = "\\b";
+ ESCAPE_SEQUENCES[9] = "\\t";
+ ESCAPE_SEQUENCES[10] = "\\n";
+ ESCAPE_SEQUENCES[11] = "\\v";
+ ESCAPE_SEQUENCES[12] = "\\f";
+ ESCAPE_SEQUENCES[13] = "\\r";
+ ESCAPE_SEQUENCES[27] = "\\e";
+ ESCAPE_SEQUENCES[34] = '\\"';
+ ESCAPE_SEQUENCES[92] = "\\\\";
+ ESCAPE_SEQUENCES[133] = "\\N";
+ ESCAPE_SEQUENCES[160] = "\\_";
+ ESCAPE_SEQUENCES[8232] = "\\L";
+ ESCAPE_SEQUENCES[8233] = "\\P";
+ var DEPRECATED_BOOLEANS_SYNTAX = [
+ "y",
+ "Y",
+ "yes",
+ "Yes",
+ "YES",
+ "on",
+ "On",
+ "ON",
+ "n",
+ "N",
+ "no",
+ "No",
+ "NO",
+ "off",
+ "Off",
+ "OFF"
+ ];
+ function compileStyleMap(schema, map2) {
+ var result, keys, index, length, tag, style, type2;
+ if (map2 === null) return {};
+ result = {};
+ keys = Object.keys(map2);
+ for (index = 0, length = keys.length; index < length; index += 1) {
+ tag = keys[index];
+ style = String(map2[tag]);
+ if (tag.slice(0, 2) === "!!") {
+ tag = "tag:yaml.org,2002:" + tag.slice(2);
+ }
+ type2 = schema.compiledTypeMap["fallback"][tag];
+ if (type2 && _hasOwnProperty.call(type2.styleAliases, style)) {
+ style = type2.styleAliases[style];
+ }
+ result[tag] = style;
+ }
+ return result;
+ }
+ __name(compileStyleMap, "compileStyleMap");
+ function encodeHex(character) {
+ var string4, handle, length;
+ string4 = character.toString(16).toUpperCase();
+ if (character <= 255) {
+ handle = "x";
+ length = 2;
+ } else if (character <= 65535) {
+ handle = "u";
+ length = 4;
+ } else if (character <= 4294967295) {
+ handle = "U";
+ length = 8;
+ } else {
+ throw new YAMLException("code point within a string may not be greater than 0xFFFFFFFF");
+ }
+ return "\\" + handle + common.repeat("0", length - string4.length) + string4;
+ }
+ __name(encodeHex, "encodeHex");
+ function State(options2) {
+ this.schema = options2["schema"] || DEFAULT_FULL_SCHEMA;
+ this.indent = Math.max(1, options2["indent"] || 2);
+ this.noArrayIndent = options2["noArrayIndent"] || false;
+ this.skipInvalid = options2["skipInvalid"] || false;
+ this.flowLevel = common.isNothing(options2["flowLevel"]) ? -1 : options2["flowLevel"];
+ this.styleMap = compileStyleMap(this.schema, options2["styles"] || null);
+ this.sortKeys = options2["sortKeys"] || false;
+ this.lineWidth = options2["lineWidth"] || 80;
+ this.noRefs = options2["noRefs"] || false;
+ this.noCompatMode = options2["noCompatMode"] || false;
+ this.condenseFlow = options2["condenseFlow"] || false;
+ this.implicitTypes = this.schema.compiledImplicit;
+ this.explicitTypes = this.schema.compiledExplicit;
+ this.tag = null;
+ this.result = "";
+ this.duplicates = [];
+ this.usedDuplicates = null;
+ }
+ __name(State, "State");
+ function indentString2(string4, spaces) {
+ var ind = common.repeat(" ", spaces), position = 0, next = -1, result = "", line, length = string4.length;
+ while (position < length) {
+ next = string4.indexOf("\n", position);
+ if (next === -1) {
+ line = string4.slice(position);
+ position = length;
+ } else {
+ line = string4.slice(position, next + 1);
+ position = next + 1;
+ }
+ if (line.length && line !== "\n") result += ind;
+ result += line;
+ }
+ return result;
+ }
+ __name(indentString2, "indentString");
+ function generateNextLine(state, level) {
+ return "\n" + common.repeat(" ", state.indent * level);
+ }
+ __name(generateNextLine, "generateNextLine");
+ function testImplicitResolving(state, str3) {
+ var index, length, type2;
+ for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {
+ type2 = state.implicitTypes[index];
+ if (type2.resolve(str3)) {
+ return true;
+ }
+ }
+ return false;
+ }
+ __name(testImplicitResolving, "testImplicitResolving");
+ function isWhitespace2(c) {
+ return c === CHAR_SPACE || c === CHAR_TAB;
+ }
+ __name(isWhitespace2, "isWhitespace");
+ function isPrintable(c) {
+ return 32 <= c && c <= 126 || 161 <= c && c <= 55295 && c !== 8232 && c !== 8233 || 57344 <= c && c <= 65533 && c !== 65279 || 65536 <= c && c <= 1114111;
+ }
+ __name(isPrintable, "isPrintable");
+ function isNsChar(c) {
+ return isPrintable(c) && !isWhitespace2(c) && c !== 65279 && c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED;
+ }
+ __name(isNsChar, "isNsChar");
+ function isPlainSafe(c, prev) {
+ return isPrintable(c) && c !== 65279 && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET && c !== CHAR_COLON && (c !== CHAR_SHARP || prev && isNsChar(prev));
+ }
+ __name(isPlainSafe, "isPlainSafe");
+ function isPlainSafeFirst(c) {
+ return isPrintable(c) && c !== 65279 && !isWhitespace2(c) && c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET && c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_EQUALS && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE && c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT;
+ }
+ __name(isPlainSafeFirst, "isPlainSafeFirst");
+ function needIndentIndicator(string4) {
+ var leadingSpaceRe = /^\n* /;
+ return leadingSpaceRe.test(string4);
+ }
+ __name(needIndentIndicator, "needIndentIndicator");
+ var STYLE_PLAIN = 1;
+ var STYLE_SINGLE = 2;
+ var STYLE_LITERAL = 3;
+ var STYLE_FOLDED = 4;
+ var STYLE_DOUBLE = 5;
+ function chooseScalarStyle(string4, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) {
+ var i;
+ var char, prev_char;
+ var hasLineBreak = false;
+ var hasFoldableLine = false;
+ var shouldTrackWidth = lineWidth !== -1;
+ var previousLineBreak = -1;
+ var plain = isPlainSafeFirst(string4.charCodeAt(0)) && !isWhitespace2(string4.charCodeAt(string4.length - 1));
+ if (singleLineOnly) {
+ for (i = 0; i < string4.length; i++) {
+ char = string4.charCodeAt(i);
+ if (!isPrintable(char)) {
+ return STYLE_DOUBLE;
+ }
+ prev_char = i > 0 ? string4.charCodeAt(i - 1) : null;
+ plain = plain && isPlainSafe(char, prev_char);
+ }
+ } else {
+ for (i = 0; i < string4.length; i++) {
+ char = string4.charCodeAt(i);
+ if (char === CHAR_LINE_FEED) {
+ hasLineBreak = true;
+ if (shouldTrackWidth) {
+ hasFoldableLine = hasFoldableLine || // Foldable line = too long, and not more-indented.
+ i - previousLineBreak - 1 > lineWidth && string4[previousLineBreak + 1] !== " ";
+ previousLineBreak = i;
+ }
+ } else if (!isPrintable(char)) {
+ return STYLE_DOUBLE;
+ }
+ prev_char = i > 0 ? string4.charCodeAt(i - 1) : null;
+ plain = plain && isPlainSafe(char, prev_char);
+ }
+ hasFoldableLine = hasFoldableLine || shouldTrackWidth && (i - previousLineBreak - 1 > lineWidth && string4[previousLineBreak + 1] !== " ");
+ }
+ if (!hasLineBreak && !hasFoldableLine) {
+ return plain && !testAmbiguousType(string4) ? STYLE_PLAIN : STYLE_SINGLE;
+ }
+ if (indentPerLevel > 9 && needIndentIndicator(string4)) {
+ return STYLE_DOUBLE;
+ }
+ return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
+ }
+ __name(chooseScalarStyle, "chooseScalarStyle");
+ function writeScalar(state, string4, level, iskey) {
+ state.dump = (function() {
+ if (string4.length === 0) {
+ return "''";
+ }
+ if (!state.noCompatMode && DEPRECATED_BOOLEANS_SYNTAX.indexOf(string4) !== -1) {
+ return "'" + string4 + "'";
+ }
+ var indent = state.indent * Math.max(1, level);
+ var lineWidth = state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);
+ var singleLineOnly = iskey || state.flowLevel > -1 && level >= state.flowLevel;
+ function testAmbiguity(string5) {
+ return testImplicitResolving(state, string5);
+ }
+ __name(testAmbiguity, "testAmbiguity");
+ switch (chooseScalarStyle(string4, singleLineOnly, state.indent, lineWidth, testAmbiguity)) {
+ case STYLE_PLAIN:
+ return string4;
+ case STYLE_SINGLE:
+ return "'" + string4.replace(/'/g, "''") + "'";
+ case STYLE_LITERAL:
+ return "|" + blockHeader(string4, state.indent) + dropEndingNewline(indentString2(string4, indent));
+ case STYLE_FOLDED:
+ return ">" + blockHeader(string4, state.indent) + dropEndingNewline(indentString2(foldString(string4, lineWidth), indent));
+ case STYLE_DOUBLE:
+ return '"' + escapeString(string4, lineWidth) + '"';
+ default:
+ throw new YAMLException("impossible error: invalid scalar style");
+ }
+ })();
+ }
+ __name(writeScalar, "writeScalar");
+ function blockHeader(string4, indentPerLevel) {
+ var indentIndicator = needIndentIndicator(string4) ? String(indentPerLevel) : "";
+ var clip = string4[string4.length - 1] === "\n";
+ var keep = clip && (string4[string4.length - 2] === "\n" || string4 === "\n");
+ var chomp = keep ? "+" : clip ? "" : "-";
+ return indentIndicator + chomp + "\n";
+ }
+ __name(blockHeader, "blockHeader");
+ function dropEndingNewline(string4) {
+ return string4[string4.length - 1] === "\n" ? string4.slice(0, -1) : string4;
+ }
+ __name(dropEndingNewline, "dropEndingNewline");
+ function foldString(string4, width) {
+ var lineRe = /(\n+)([^\n]*)/g;
+ var result = (function() {
+ var nextLF = string4.indexOf("\n");
+ nextLF = nextLF !== -1 ? nextLF : string4.length;
+ lineRe.lastIndex = nextLF;
+ return foldLine(string4.slice(0, nextLF), width);
+ })();
+ var prevMoreIndented = string4[0] === "\n" || string4[0] === " ";
+ var moreIndented;
+ var match;
+ while (match = lineRe.exec(string4)) {
+ var prefix = match[1], line = match[2];
+ moreIndented = line[0] === " ";
+ result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") + foldLine(line, width);
+ prevMoreIndented = moreIndented;
+ }
+ return result;
+ }
+ __name(foldString, "foldString");
+ function foldLine(line, width) {
+ if (line === "" || line[0] === " ") return line;
+ var breakRe = / [^ ]/g;
+ var match;
+ var start = 0, end, curr = 0, next = 0;
+ var result = "";
+ while (match = breakRe.exec(line)) {
+ next = match.index;
+ if (next - start > width) {
+ end = curr > start ? curr : next;
+ result += "\n" + line.slice(start, end);
+ start = end + 1;
+ }
+ curr = next;
+ }
+ result += "\n";
+ if (line.length - start > width && curr > start) {
+ result += line.slice(start, curr) + "\n" + line.slice(curr + 1);
+ } else {
+ result += line.slice(start);
+ }
+ return result.slice(1);
+ }
+ __name(foldLine, "foldLine");
+ function escapeString(string4) {
+ var result = "";
+ var char, nextChar;
+ var escapeSeq;
+ for (var i = 0; i < string4.length; i++) {
+ char = string4.charCodeAt(i);
+ if (char >= 55296 && char <= 56319) {
+ nextChar = string4.charCodeAt(i + 1);
+ if (nextChar >= 56320 && nextChar <= 57343) {
+ result += encodeHex((char - 55296) * 1024 + nextChar - 56320 + 65536);
+ i++;
+ continue;
+ }
+ }
+ escapeSeq = ESCAPE_SEQUENCES[char];
+ result += !escapeSeq && isPrintable(char) ? string4[i] : escapeSeq || encodeHex(char);
+ }
+ return result;
+ }
+ __name(escapeString, "escapeString");
+ function writeFlowSequence(state, level, object2) {
+ var _result = "", _tag = state.tag, index, length;
+ for (index = 0, length = object2.length; index < length; index += 1) {
+ if (writeNode(state, level, object2[index], false, false)) {
+ if (index !== 0) _result += "," + (!state.condenseFlow ? " " : "");
+ _result += state.dump;
+ }
+ }
+ state.tag = _tag;
+ state.dump = "[" + _result + "]";
+ }
+ __name(writeFlowSequence, "writeFlowSequence");
+ function writeBlockSequence(state, level, object2, compact) {
+ var _result = "", _tag = state.tag, index, length;
+ for (index = 0, length = object2.length; index < length; index += 1) {
+ if (writeNode(state, level + 1, object2[index], true, true)) {
+ if (!compact || index !== 0) {
+ _result += generateNextLine(state, level);
+ }
+ if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
+ _result += "-";
+ } else {
+ _result += "- ";
+ }
+ _result += state.dump;
+ }
+ }
+ state.tag = _tag;
+ state.dump = _result || "[]";
+ }
+ __name(writeBlockSequence, "writeBlockSequence");
+ function writeFlowMapping(state, level, object2) {
+ var _result = "", _tag = state.tag, objectKeyList = Object.keys(object2), index, length, objectKey, objectValue, pairBuffer;
+ for (index = 0, length = objectKeyList.length; index < length; index += 1) {
+ pairBuffer = "";
+ if (index !== 0) pairBuffer += ", ";
+ if (state.condenseFlow) pairBuffer += '"';
+ objectKey = objectKeyList[index];
+ objectValue = object2[objectKey];
+ if (!writeNode(state, level, objectKey, false, false)) {
+ continue;
+ }
+ if (state.dump.length > 1024) pairBuffer += "? ";
+ pairBuffer += state.dump + (state.condenseFlow ? '"' : "") + ":" + (state.condenseFlow ? "" : " ");
+ if (!writeNode(state, level, objectValue, false, false)) {
+ continue;
+ }
+ pairBuffer += state.dump;
+ _result += pairBuffer;
+ }
+ state.tag = _tag;
+ state.dump = "{" + _result + "}";
+ }
+ __name(writeFlowMapping, "writeFlowMapping");
+ function writeBlockMapping(state, level, object2, compact) {
+ var _result = "", _tag = state.tag, objectKeyList = Object.keys(object2), index, length, objectKey, objectValue, explicitPair, pairBuffer;
+ if (state.sortKeys === true) {
+ objectKeyList.sort();
+ } else if (typeof state.sortKeys === "function") {
+ objectKeyList.sort(state.sortKeys);
+ } else if (state.sortKeys) {
+ throw new YAMLException("sortKeys must be a boolean or a function");
+ }
+ for (index = 0, length = objectKeyList.length; index < length; index += 1) {
+ pairBuffer = "";
+ if (!compact || index !== 0) {
+ pairBuffer += generateNextLine(state, level);
+ }
+ objectKey = objectKeyList[index];
+ objectValue = object2[objectKey];
+ if (!writeNode(state, level + 1, objectKey, true, true, true)) {
+ continue;
+ }
+ explicitPair = state.tag !== null && state.tag !== "?" || state.dump && state.dump.length > 1024;
+ if (explicitPair) {
+ if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
+ pairBuffer += "?";
+ } else {
+ pairBuffer += "? ";
+ }
+ }
+ pairBuffer += state.dump;
+ if (explicitPair) {
+ pairBuffer += generateNextLine(state, level);
+ }
+ if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
+ continue;
+ }
+ if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
+ pairBuffer += ":";
+ } else {
+ pairBuffer += ": ";
+ }
+ pairBuffer += state.dump;
+ _result += pairBuffer;
+ }
+ state.tag = _tag;
+ state.dump = _result || "{}";
+ }
+ __name(writeBlockMapping, "writeBlockMapping");
+ function detectType(state, object2, explicit) {
+ var _result, typeList, index, length, type2, style;
+ typeList = explicit ? state.explicitTypes : state.implicitTypes;
+ for (index = 0, length = typeList.length; index < length; index += 1) {
+ type2 = typeList[index];
+ if ((type2.instanceOf || type2.predicate) && (!type2.instanceOf || typeof object2 === "object" && object2 instanceof type2.instanceOf) && (!type2.predicate || type2.predicate(object2))) {
+ state.tag = explicit ? type2.tag : "?";
+ if (type2.represent) {
+ style = state.styleMap[type2.tag] || type2.defaultStyle;
+ if (_toString.call(type2.represent) === "[object Function]") {
+ _result = type2.represent(object2, style);
+ } else if (_hasOwnProperty.call(type2.represent, style)) {
+ _result = type2.represent[style](object2, style);
+ } else {
+ throw new YAMLException("!<" + type2.tag + '> tag resolver accepts not "' + style + '" style');
+ }
+ state.dump = _result;
+ }
+ return true;
+ }
+ }
+ return false;
+ }
+ __name(detectType, "detectType");
+ function writeNode(state, level, object2, block, compact, iskey) {
+ state.tag = null;
+ state.dump = object2;
+ if (!detectType(state, object2, false)) {
+ detectType(state, object2, true);
+ }
+ var type2 = _toString.call(state.dump);
+ if (block) {
+ block = state.flowLevel < 0 || state.flowLevel > level;
+ }
+ var objectOrArray = type2 === "[object Object]" || type2 === "[object Array]", duplicateIndex, duplicate;
+ if (objectOrArray) {
+ duplicateIndex = state.duplicates.indexOf(object2);
+ duplicate = duplicateIndex !== -1;
+ }
+ if (state.tag !== null && state.tag !== "?" || duplicate || state.indent !== 2 && level > 0) {
+ compact = false;
+ }
+ if (duplicate && state.usedDuplicates[duplicateIndex]) {
+ state.dump = "*ref_" + duplicateIndex;
+ } else {
+ if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
+ state.usedDuplicates[duplicateIndex] = true;
+ }
+ if (type2 === "[object Object]") {
+ if (block && Object.keys(state.dump).length !== 0) {
+ writeBlockMapping(state, level, state.dump, compact);
+ if (duplicate) {
+ state.dump = "&ref_" + duplicateIndex + state.dump;
+ }
+ } else {
+ writeFlowMapping(state, level, state.dump);
+ if (duplicate) {
+ state.dump = "&ref_" + duplicateIndex + " " + state.dump;
+ }
+ }
+ } else if (type2 === "[object Array]") {
+ var arrayLevel = state.noArrayIndent && level > 0 ? level - 1 : level;
+ if (block && state.dump.length !== 0) {
+ writeBlockSequence(state, arrayLevel, state.dump, compact);
+ if (duplicate) {
+ state.dump = "&ref_" + duplicateIndex + state.dump;
+ }
+ } else {
+ writeFlowSequence(state, arrayLevel, state.dump);
+ if (duplicate) {
+ state.dump = "&ref_" + duplicateIndex + " " + state.dump;
+ }
+ }
+ } else if (type2 === "[object String]") {
+ if (state.tag !== "?") {
+ writeScalar(state, state.dump, level, iskey);
+ }
+ } else {
+ if (state.skipInvalid) return false;
+ throw new YAMLException("unacceptable kind of an object to dump " + type2);
+ }
+ if (state.tag !== null && state.tag !== "?") {
+ state.dump = "!<" + state.tag + "> " + state.dump;
+ }
+ }
+ return true;
+ }
+ __name(writeNode, "writeNode");
+ function getDuplicateReferences(object2, state) {
+ var objects = [], duplicatesIndexes = [], index, length;
+ inspectNode(object2, objects, duplicatesIndexes);
+ for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {
+ state.duplicates.push(objects[duplicatesIndexes[index]]);
+ }
+ state.usedDuplicates = new Array(length);
+ }
+ __name(getDuplicateReferences, "getDuplicateReferences");
+ function inspectNode(object2, objects, duplicatesIndexes) {
+ var objectKeyList, index, length;
+ if (object2 !== null && typeof object2 === "object") {
+ index = objects.indexOf(object2);
+ if (index !== -1) {
+ if (duplicatesIndexes.indexOf(index) === -1) {
+ duplicatesIndexes.push(index);
+ }
+ } else {
+ objects.push(object2);
+ if (Array.isArray(object2)) {
+ for (index = 0, length = object2.length; index < length; index += 1) {
+ inspectNode(object2[index], objects, duplicatesIndexes);
+ }
+ } else {
+ objectKeyList = Object.keys(object2);
+ for (index = 0, length = objectKeyList.length; index < length; index += 1) {
+ inspectNode(object2[objectKeyList[index]], objects, duplicatesIndexes);
+ }
+ }
+ }
+ }
+ }
+ __name(inspectNode, "inspectNode");
+ function dump(input, options2) {
+ options2 = options2 || {};
+ var state = new State(options2);
+ if (!state.noRefs) getDuplicateReferences(input, state);
+ if (writeNode(state, 0, input, true, true)) return state.dump + "\n";
+ return "";
+ }
+ __name(dump, "dump");
+ function safeDump(input, options2) {
+ return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options2));
+ }
+ __name(safeDump, "safeDump");
+ module2.exports.dump = dump;
+ module2.exports.safeDump = safeDump;
+ }
+});
+
+// node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml.js
+var require_js_yaml = __commonJS({
+ "node_modules/gray-matter/node_modules/js-yaml/lib/js-yaml.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var loader = require_loader();
+ var dumper = require_dumper();
+ function deprecated(name) {
+ return function() {
+ throw new Error("Function " + name + " is deprecated and cannot be used.");
+ };
+ }
+ __name(deprecated, "deprecated");
+ module2.exports.Type = require_type();
+ module2.exports.Schema = require_schema();
+ module2.exports.FAILSAFE_SCHEMA = require_failsafe();
+ module2.exports.JSON_SCHEMA = require_json();
+ module2.exports.CORE_SCHEMA = require_core();
+ module2.exports.DEFAULT_SAFE_SCHEMA = require_default_safe();
+ module2.exports.DEFAULT_FULL_SCHEMA = require_default_full();
+ module2.exports.load = loader.load;
+ module2.exports.loadAll = loader.loadAll;
+ module2.exports.safeLoad = loader.safeLoad;
+ module2.exports.safeLoadAll = loader.safeLoadAll;
+ module2.exports.dump = dumper.dump;
+ module2.exports.safeDump = dumper.safeDump;
+ module2.exports.YAMLException = require_exception();
+ module2.exports.MINIMAL_SCHEMA = require_failsafe();
+ module2.exports.SAFE_SCHEMA = require_default_safe();
+ module2.exports.DEFAULT_SCHEMA = require_default_full();
+ module2.exports.scan = deprecated("scan");
+ module2.exports.parse = deprecated("parse");
+ module2.exports.compose = deprecated("compose");
+ module2.exports.addConstructor = deprecated("addConstructor");
+ }
+});
+
+// node_modules/gray-matter/node_modules/js-yaml/index.js
+var require_js_yaml2 = __commonJS({
+ "node_modules/gray-matter/node_modules/js-yaml/index.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var yaml2 = require_js_yaml();
+ module2.exports = yaml2;
+ }
+});
+
+// node_modules/gray-matter/lib/engines.js
+var require_engines = __commonJS({
+ "node_modules/gray-matter/lib/engines.js"(exports, module) {
+ "use strict";
+ init_esbuild_shims();
+ var yaml = require_js_yaml2();
+ var engines = exports = module.exports;
+ engines.yaml = {
+ parse: yaml.safeLoad.bind(yaml),
+ stringify: yaml.safeDump.bind(yaml)
+ };
+ engines.json = {
+ parse: JSON.parse.bind(JSON),
+ stringify: /* @__PURE__ */ __name(function(obj, options2) {
+ const opts = Object.assign({ replacer: null, space: 2 }, options2);
+ return JSON.stringify(obj, opts.replacer, opts.space);
+ }, "stringify")
+ };
+ engines.javascript = {
+ parse: /* @__PURE__ */ __name(function parse(str, options, wrap) {
+ try {
+ if (wrap !== false) {
+ str = "(function() {\nreturn " + str.trim() + ";\n}());";
+ }
+ return eval(str) || {};
+ } catch (err) {
+ if (wrap !== false && /(unexpected|identifier)/i.test(err.message)) {
+ return parse(str, options, false);
+ }
+ throw new SyntaxError(err);
+ }
+ }, "parse"),
+ stringify: /* @__PURE__ */ __name(function() {
+ throw new Error("stringifying JavaScript is not supported");
+ }, "stringify")
+ };
+ }
+});
+
+// node_modules/strip-bom-string/index.js
+var require_strip_bom_string = __commonJS({
+ "node_modules/strip-bom-string/index.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ module2.exports = function(str3) {
+ if (typeof str3 === "string" && str3.charAt(0) === "\uFEFF") {
+ return str3.slice(1);
+ }
+ return str3;
+ };
+ }
+});
+
+// node_modules/gray-matter/lib/utils.js
+var require_utils = __commonJS({
+ "node_modules/gray-matter/lib/utils.js"(exports2) {
+ "use strict";
+ init_esbuild_shims();
+ var stripBom = require_strip_bom_string();
+ var typeOf = require_kind_of();
+ exports2.define = function(obj, key, val) {
+ Reflect.defineProperty(obj, key, {
+ enumerable: false,
+ configurable: true,
+ writable: true,
+ value: val
+ });
+ };
+ exports2.isBuffer = function(val) {
+ return typeOf(val) === "buffer";
+ };
+ exports2.isObject = function(val) {
+ return typeOf(val) === "object";
+ };
+ exports2.toBuffer = function(input) {
+ return typeof input === "string" ? Buffer.from(input) : input;
+ };
+ exports2.toString = function(input) {
+ if (exports2.isBuffer(input)) return stripBom(String(input));
+ if (typeof input !== "string") {
+ throw new TypeError("expected input to be a string or buffer");
+ }
+ return stripBom(input);
+ };
+ exports2.arrayify = function(val) {
+ return val ? Array.isArray(val) ? val : [val] : [];
+ };
+ exports2.startsWith = function(str3, substr, len) {
+ if (typeof len !== "number") len = substr.length;
+ return str3.slice(0, len) === substr;
+ };
+ }
+});
+
+// node_modules/gray-matter/lib/defaults.js
+var require_defaults = __commonJS({
+ "node_modules/gray-matter/lib/defaults.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var engines2 = require_engines();
+ var utils2 = require_utils();
+ module2.exports = function(options2) {
+ const opts = Object.assign({}, options2);
+ opts.delimiters = utils2.arrayify(opts.delims || opts.delimiters || "---");
+ if (opts.delimiters.length === 1) {
+ opts.delimiters.push(opts.delimiters[0]);
+ }
+ opts.language = (opts.language || opts.lang || "yaml").toLowerCase();
+ opts.engines = Object.assign({}, engines2, opts.parsers, opts.engines);
+ return opts;
+ };
+ }
+});
+
+// node_modules/gray-matter/lib/engine.js
+var require_engine = __commonJS({
+ "node_modules/gray-matter/lib/engine.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ module2.exports = function(name, options2) {
+ let engine = options2.engines[name] || options2.engines[aliase(name)];
+ if (typeof engine === "undefined") {
+ throw new Error('gray-matter engine "' + name + '" is not registered');
+ }
+ if (typeof engine === "function") {
+ engine = { parse: engine };
+ }
+ return engine;
+ };
+ function aliase(name) {
+ switch (name.toLowerCase()) {
+ case "js":
+ case "javascript":
+ return "javascript";
+ case "coffee":
+ case "coffeescript":
+ case "cson":
+ return "coffee";
+ case "yaml":
+ case "yml":
+ return "yaml";
+ default: {
+ return name;
+ }
+ }
+ }
+ __name(aliase, "aliase");
+ }
+});
+
+// node_modules/gray-matter/lib/stringify.js
+var require_stringify = __commonJS({
+ "node_modules/gray-matter/lib/stringify.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var typeOf = require_kind_of();
+ var getEngine = require_engine();
+ var defaults2 = require_defaults();
+ module2.exports = function(file2, data, options2) {
+ if (data == null && options2 == null) {
+ switch (typeOf(file2)) {
+ case "object":
+ data = file2.data;
+ options2 = {};
+ break;
+ case "string":
+ return file2;
+ default: {
+ throw new TypeError("expected file to be a string or object");
+ }
+ }
+ }
+ const str3 = file2.content;
+ const opts = defaults2(options2);
+ if (data == null) {
+ if (!opts.data) return file2;
+ data = opts.data;
+ }
+ const language = file2.language || opts.language;
+ const engine = getEngine(language, opts);
+ if (typeof engine.stringify !== "function") {
+ throw new TypeError('expected "' + language + '.stringify" to be a function');
+ }
+ data = Object.assign({}, file2.data, data);
+ const open = opts.delimiters[0];
+ const close = opts.delimiters[1];
+ const matter3 = engine.stringify(data, options2).trim();
+ let buf = "";
+ if (matter3 !== "{}") {
+ buf = newline(open) + newline(matter3) + newline(close);
+ }
+ if (typeof file2.excerpt === "string" && file2.excerpt !== "") {
+ if (str3.indexOf(file2.excerpt.trim()) === -1) {
+ buf += newline(file2.excerpt) + newline(close);
+ }
+ }
+ return buf + newline(str3);
+ };
+ function newline(str3) {
+ return str3.slice(-1) !== "\n" ? str3 + "\n" : str3;
+ }
+ __name(newline, "newline");
+ }
+});
+
+// node_modules/gray-matter/lib/excerpt.js
+var require_excerpt = __commonJS({
+ "node_modules/gray-matter/lib/excerpt.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var defaults2 = require_defaults();
+ module2.exports = function(file2, options2) {
+ const opts = defaults2(options2);
+ if (file2.data == null) {
+ file2.data = {};
+ }
+ if (typeof opts.excerpt === "function") {
+ return opts.excerpt(file2, opts);
+ }
+ const sep7 = file2.data.excerpt_separator || opts.excerpt_separator;
+ if (sep7 == null && (opts.excerpt === false || opts.excerpt == null)) {
+ return file2;
+ }
+ const delimiter = typeof opts.excerpt === "string" ? opts.excerpt : sep7 || opts.delimiters[0];
+ const idx = file2.content.indexOf(delimiter);
+ if (idx !== -1) {
+ file2.excerpt = file2.content.slice(0, idx);
+ }
+ return file2;
+ };
+ }
+});
+
+// node_modules/gray-matter/lib/to-file.js
+var require_to_file = __commonJS({
+ "node_modules/gray-matter/lib/to-file.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var typeOf = require_kind_of();
+ var stringify2 = require_stringify();
+ var utils2 = require_utils();
+ module2.exports = function(file2) {
+ if (typeOf(file2) !== "object") {
+ file2 = { content: file2 };
+ }
+ if (typeOf(file2.data) !== "object") {
+ file2.data = {};
+ }
+ if (file2.contents && file2.content == null) {
+ file2.content = file2.contents;
+ }
+ utils2.define(file2, "orig", utils2.toBuffer(file2.content));
+ utils2.define(file2, "language", file2.language || "");
+ utils2.define(file2, "matter", file2.matter || "");
+ utils2.define(file2, "stringify", function(data, options2) {
+ if (options2 && options2.language) {
+ file2.language = options2.language;
+ }
+ return stringify2(file2, data, options2);
+ });
+ file2.content = utils2.toString(file2.content);
+ file2.isEmpty = false;
+ file2.excerpt = "";
+ return file2;
+ };
+ }
+});
+
+// node_modules/gray-matter/lib/parse.js
+var require_parse = __commonJS({
+ "node_modules/gray-matter/lib/parse.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var getEngine = require_engine();
+ var defaults2 = require_defaults();
+ module2.exports = function(language, str3, options2) {
+ const opts = defaults2(options2);
+ const engine = getEngine(language, opts);
+ if (typeof engine.parse !== "function") {
+ throw new TypeError('expected "' + language + '.parse" to be a function');
+ }
+ return engine.parse(str3, opts);
+ };
+ }
+});
+
+// node_modules/gray-matter/index.js
+var require_gray_matter = __commonJS({
+ "node_modules/gray-matter/index.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var fs22 = __require("fs");
+ var sections = require_section_matter();
+ var defaults2 = require_defaults();
+ var stringify2 = require_stringify();
+ var excerpt = require_excerpt();
+ var engines2 = require_engines();
+ var toFile2 = require_to_file();
+ var parse4 = require_parse();
+ var utils2 = require_utils();
+ function matter3(input, options2) {
+ if (input === "") {
+ return { data: {}, content: input, excerpt: "", orig: input };
+ }
+ let file2 = toFile2(input);
+ const cached2 = matter3.cache[file2.content];
+ if (!options2) {
+ if (cached2) {
+ file2 = Object.assign({}, cached2);
+ file2.orig = cached2.orig;
+ return file2;
+ }
+ matter3.cache[file2.content] = file2;
+ }
+ return parseMatter(file2, options2);
+ }
+ __name(matter3, "matter");
+ function parseMatter(file2, options2) {
+ const opts = defaults2(options2);
+ const open = opts.delimiters[0];
+ const close = "\n" + opts.delimiters[1];
+ let str3 = file2.content;
+ if (opts.language) {
+ file2.language = opts.language;
+ }
+ const openLen = open.length;
+ if (!utils2.startsWith(str3, open, openLen)) {
+ excerpt(file2, opts);
+ return file2;
+ }
+ if (str3.charAt(openLen) === open.slice(-1)) {
+ return file2;
+ }
+ str3 = str3.slice(openLen);
+ const len = str3.length;
+ const language = matter3.language(str3, opts);
+ if (language.name) {
+ file2.language = language.name;
+ str3 = str3.slice(language.raw.length);
+ }
+ let closeIndex = str3.indexOf(close);
+ if (closeIndex === -1) {
+ closeIndex = len;
+ }
+ file2.matter = str3.slice(0, closeIndex);
+ const block = file2.matter.replace(/^\s*#[^\n]+/gm, "").trim();
+ if (block === "") {
+ file2.isEmpty = true;
+ file2.empty = file2.content;
+ file2.data = {};
+ } else {
+ file2.data = parse4(file2.language, file2.matter, opts);
+ }
+ if (closeIndex === len) {
+ file2.content = "";
+ } else {
+ file2.content = str3.slice(closeIndex + close.length);
+ if (file2.content[0] === "\r") {
+ file2.content = file2.content.slice(1);
+ }
+ if (file2.content[0] === "\n") {
+ file2.content = file2.content.slice(1);
+ }
+ }
+ excerpt(file2, opts);
+ if (opts.sections === true || typeof opts.section === "function") {
+ sections(file2, opts.section);
+ }
+ return file2;
+ }
+ __name(parseMatter, "parseMatter");
+ matter3.engines = engines2;
+ matter3.stringify = function(file2, data, options2) {
+ if (typeof file2 === "string") file2 = matter3(file2, options2);
+ return stringify2(file2, data, options2);
+ };
+ matter3.read = function(filepath, options2) {
+ const str3 = fs22.readFileSync(filepath, "utf8");
+ const file2 = matter3(str3, options2);
+ file2.path = filepath;
+ return file2;
+ };
+ matter3.test = function(str3, options2) {
+ return utils2.startsWith(str3, defaults2(options2).delimiters[0]);
+ };
+ matter3.language = function(str3, options2) {
+ const opts = defaults2(options2);
+ const open = opts.delimiters[0];
+ if (matter3.test(str3)) {
+ str3 = str3.slice(open.length);
+ }
+ const language = str3.slice(0, str3.search(/\r?\n/));
+ return {
+ raw: language,
+ name: language ? language.trim() : ""
+ };
+ };
+ matter3.cache = {};
+ matter3.clearCache = function() {
+ matter3.cache = {};
+ };
+ module2.exports = matter3;
+ }
+});
+
+// packages/core/node_modules/ignore/index.js
+var require_ignore = __commonJS({
+ "packages/core/node_modules/ignore/index.js"(exports2, module2) {
+ init_esbuild_shims();
+ function makeArray(subject) {
+ return Array.isArray(subject) ? subject : [subject];
+ }
+ __name(makeArray, "makeArray");
+ var UNDEFINED = void 0;
+ var EMPTY2 = "";
+ var SPACE = " ";
+ var ESCAPE2 = "\\";
+ var REGEX_TEST_BLANK_LINE = /^\s+$/;
+ var REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/;
+ var REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
+ var REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
+ var REGEX_SPLITALL_CRLF = /\r?\n/g;
+ var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
+ var REGEX_TEST_TRAILING_SLASH = /\/$/;
+ var SLASH = "/";
+ var TMP_KEY_IGNORE = "node-ignore";
+ if (typeof Symbol !== "undefined") {
+ TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
+ }
+ var KEY_IGNORE = TMP_KEY_IGNORE;
+ var define2 = /* @__PURE__ */ __name((object2, key, value) => {
+ Object.defineProperty(object2, key, { value });
+ return value;
+ }, "define");
+ var REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g;
+ var RETURN_FALSE = /* @__PURE__ */ __name(() => false, "RETURN_FALSE");
+ var sanitizeRange = /* @__PURE__ */ __name((range) => range.replace(
+ REGEX_REGEXP_RANGE,
+ (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) ? match : EMPTY2
+ ), "sanitizeRange");
+ var cleanRangeBackSlash = /* @__PURE__ */ __name((slashes) => {
+ const { length } = slashes;
+ return slashes.slice(0, length - length % 2);
+ }, "cleanRangeBackSlash");
+ var REPLACERS = [
+ [
+ // Remove BOM
+ // TODO:
+ // Other similar zero-width characters?
+ /^\uFEFF/,
+ () => EMPTY2
+ ],
+ // > Trailing spaces are ignored unless they are quoted with backslash ("\")
+ [
+ // (a\ ) -> (a )
+ // (a ) -> (a)
+ // (a ) -> (a)
+ // (a \ ) -> (a )
+ /((?:\\\\)*?)(\\?\s+)$/,
+ (_, m1, m2) => m1 + (m2.indexOf("\\") === 0 ? SPACE : EMPTY2)
+ ],
+ // Replace (\ ) with ' '
+ // (\ ) -> ' '
+ // (\\ ) -> '\\ '
+ // (\\\ ) -> '\\ '
+ [
+ /(\\+?)\s/g,
+ (_, m1) => {
+ const { length } = m1;
+ return m1.slice(0, length - length % 2) + SPACE;
+ }
+ ],
+ // Escape metacharacters
+ // which is written down by users but means special for regular expressions.
+ // > There are 12 characters with special meanings:
+ // > - the backslash \,
+ // > - the caret ^,
+ // > - the dollar sign $,
+ // > - the period or dot .,
+ // > - the vertical bar or pipe symbol |,
+ // > - the question mark ?,
+ // > - the asterisk or star *,
+ // > - the plus sign +,
+ // > - the opening parenthesis (,
+ // > - the closing parenthesis ),
+ // > - and the opening square bracket [,
+ // > - the opening curly brace {,
+ // > These special characters are often called "metacharacters".
+ [
+ /[\\$.|*+(){^]/g,
+ (match) => `\\${match}`
+ ],
+ [
+ // > a question mark (?) matches a single character
+ /(?!\\)\?/g,
+ () => "[^/]"
+ ],
+ // leading slash
+ [
+ // > A leading slash matches the beginning of the pathname.
+ // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
+ // A leading slash matches the beginning of the pathname
+ /^\//,
+ () => "^"
+ ],
+ // replace special metacharacter slash after the leading slash
+ [
+ /\//g,
+ () => "\\/"
+ ],
+ [
+ // > A leading "**" followed by a slash means match in all directories.
+ // > For example, "**/foo" matches file or directory "foo" anywhere,
+ // > the same as pattern "foo".
+ // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
+ // > under directory "foo".
+ // Notice that the '*'s have been replaced as '\\*'
+ /^\^*\\\*\\\*\\\//,
+ // '**/foo' <-> 'foo'
+ () => "^(?:.*\\/)?"
+ ],
+ // starting
+ [
+ // there will be no leading '/'
+ // (which has been replaced by section "leading slash")
+ // If starts with '**', adding a '^' to the regular expression also works
+ /^(?=[^^])/,
+ /* @__PURE__ */ __name(function startingReplacer() {
+ return !/\/(?!$)/.test(this) ? "(?:^|\\/)" : "^";
+ }, "startingReplacer")
+ ],
+ // two globstars
+ [
+ // Use lookahead assertions so that we could match more than one `'/**'`
+ /\\\/\\\*\\\*(?=\\\/|$)/g,
+ // Zero, one or several directories
+ // should not use '*', or it will be replaced by the next replacer
+ // Check if it is not the last `'/**'`
+ (_, index, str3) => index + 6 < str3.length ? "(?:\\/[^\\/]+)*" : "\\/.+"
+ ],
+ // normal intermediate wildcards
+ [
+ // Never replace escaped '*'
+ // ignore rule '\*' will match the path '*'
+ // 'abc.*/' -> go
+ // 'abc.*' -> skip this rule,
+ // coz trailing single wildcard will be handed by [trailing wildcard]
+ /(^|[^\\]+)(\\\*)+(?=.+)/g,
+ // '*.js' matches '.js'
+ // '*.js' doesn't match 'abc'
+ (_, p1, p2) => {
+ const unescaped = p2.replace(/\\\*/g, "[^\\/]*");
+ return p1 + unescaped;
+ }
+ ],
+ [
+ // unescape, revert step 3 except for back slash
+ // For example, if a user escape a '\\*',
+ // after step 3, the result will be '\\\\\\*'
+ /\\\\\\(?=[$.|*+(){^])/g,
+ () => ESCAPE2
+ ],
+ [
+ // '\\\\' -> '\\'
+ /\\\\/g,
+ () => ESCAPE2
+ ],
+ [
+ // > The range notation, e.g. [a-zA-Z],
+ // > can be used to match one of the characters in a range.
+ // `\` is escaped by step 3
+ /(\\)?\[([^\]/]*?)(\\*)($|\])/g,
+ (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE2 ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` : close === "]" ? endEscape.length % 2 === 0 ? `[${sanitizeRange(range)}${endEscape}]` : "[]" : "[]"
+ ],
+ // ending
+ [
+ // 'js' will not match 'js.'
+ // 'ab' will not match 'abc'
+ /(?:[^*])$/,
+ // WTF!
+ // https://git-scm.com/docs/gitignore
+ // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)
+ // which re-fixes #24, #38
+ // > If there is a separator at the end of the pattern then the pattern
+ // > will only match directories, otherwise the pattern can match both
+ // > files and directories.
+ // 'js*' will not match 'a.js'
+ // 'js/' will not match 'a.js'
+ // 'js' will match 'a.js' and 'a.js/'
+ (match) => /\/$/.test(match) ? `${match}$` : `${match}(?=$|\\/$)`
+ ]
+ ];
+ var REGEX_REPLACE_TRAILING_WILDCARD = /(^|\\\/)?\\\*$/;
+ var MODE_IGNORE = "regex";
+ var MODE_CHECK_IGNORE = "checkRegex";
+ var UNDERSCORE = "_";
+ var TRAILING_WILD_CARD_REPLACERS = {
+ [MODE_IGNORE](_, p1) {
+ const prefix = p1 ? `${p1}[^/]+` : "[^/]*";
+ return `${prefix}(?=$|\\/$)`;
+ },
+ [MODE_CHECK_IGNORE](_, p1) {
+ const prefix = p1 ? `${p1}[^/]*` : "[^/]*";
+ return `${prefix}(?=$|\\/$)`;
+ }
+ };
+ var makeRegexPrefix = /* @__PURE__ */ __name((pattern) => REPLACERS.reduce(
+ (prev, [matcher, replacer]) => prev.replace(matcher, replacer.bind(pattern)),
+ pattern
+ ), "makeRegexPrefix");
+ var isString = /* @__PURE__ */ __name((subject) => typeof subject === "string", "isString");
+ var checkPattern = /* @__PURE__ */ __name((pattern) => pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) && pattern.indexOf("#") !== 0, "checkPattern");
+ var splitPattern = /* @__PURE__ */ __name((pattern) => pattern.split(REGEX_SPLITALL_CRLF).filter(Boolean), "splitPattern");
+ var IgnoreRule = class {
+ static {
+ __name(this, "IgnoreRule");
+ }
+ constructor(pattern, mark, body, ignoreCase, negative, prefix) {
+ this.pattern = pattern;
+ this.mark = mark;
+ this.negative = negative;
+ define2(this, "body", body);
+ define2(this, "ignoreCase", ignoreCase);
+ define2(this, "regexPrefix", prefix);
+ }
+ get regex() {
+ const key = UNDERSCORE + MODE_IGNORE;
+ if (this[key]) {
+ return this[key];
+ }
+ return this._make(MODE_IGNORE, key);
+ }
+ get checkRegex() {
+ const key = UNDERSCORE + MODE_CHECK_IGNORE;
+ if (this[key]) {
+ return this[key];
+ }
+ return this._make(MODE_CHECK_IGNORE, key);
+ }
+ _make(mode, key) {
+ const str3 = this.regexPrefix.replace(
+ REGEX_REPLACE_TRAILING_WILDCARD,
+ // It does not need to bind pattern
+ TRAILING_WILD_CARD_REPLACERS[mode]
+ );
+ const regex2 = this.ignoreCase ? new RegExp(str3, "i") : new RegExp(str3);
+ return define2(this, key, regex2);
+ }
+ };
+ var createRule = /* @__PURE__ */ __name(({
+ pattern,
+ mark
+ }, ignoreCase) => {
+ let negative = false;
+ let body = pattern;
+ if (body.indexOf("!") === 0) {
+ negative = true;
+ body = body.substr(1);
+ }
+ body = body.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, "!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, "#");
+ const regexPrefix = makeRegexPrefix(body);
+ return new IgnoreRule(
+ pattern,
+ mark,
+ body,
+ ignoreCase,
+ negative,
+ regexPrefix
+ );
+ }, "createRule");
+ var RuleManager = class {
+ static {
+ __name(this, "RuleManager");
+ }
+ constructor(ignoreCase) {
+ this._ignoreCase = ignoreCase;
+ this._rules = [];
+ }
+ _add(pattern) {
+ if (pattern && pattern[KEY_IGNORE]) {
+ this._rules = this._rules.concat(pattern._rules._rules);
+ this._added = true;
+ return;
+ }
+ if (isString(pattern)) {
+ pattern = {
+ pattern
+ };
+ }
+ if (checkPattern(pattern.pattern)) {
+ const rule = createRule(pattern, this._ignoreCase);
+ this._added = true;
+ this._rules.push(rule);
+ }
+ }
+ // @param {Array | string | Ignore} pattern
+ add(pattern) {
+ this._added = false;
+ makeArray(
+ isString(pattern) ? splitPattern(pattern) : pattern
+ ).forEach(this._add, this);
+ return this._added;
+ }
+ // Test one single path without recursively checking parent directories
+ //
+ // - checkUnignored `boolean` whether should check if the path is unignored,
+ // setting `checkUnignored` to `false` could reduce additional
+ // path matching.
+ // - check `string` either `MODE_IGNORE` or `MODE_CHECK_IGNORE`
+ // @returns {TestResult} true if a file is ignored
+ test(path27, checkUnignored, mode) {
+ let ignored = false;
+ let unignored = false;
+ let matchedRule;
+ this._rules.forEach((rule) => {
+ const { negative } = rule;
+ if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) {
+ return;
+ }
+ const matched = rule[mode].test(path27);
+ if (!matched) {
+ return;
+ }
+ ignored = !negative;
+ unignored = negative;
+ matchedRule = negative ? UNDEFINED : rule;
+ });
+ const ret = {
+ ignored,
+ unignored
+ };
+ if (matchedRule) {
+ ret.rule = matchedRule;
+ }
+ return ret;
+ }
+ };
+ var throwError = /* @__PURE__ */ __name((message, Ctor) => {
+ throw new Ctor(message);
+ }, "throwError");
+ var checkPath = /* @__PURE__ */ __name((path27, originalPath, doThrow) => {
+ if (!isString(path27)) {
+ return doThrow(
+ `path must be a string, but got \`${originalPath}\``,
+ TypeError
+ );
+ }
+ if (!path27) {
+ return doThrow(`path must not be empty`, TypeError);
+ }
+ if (checkPath.isNotRelative(path27)) {
+ const r = "`path.relative()`d";
+ return doThrow(
+ `path should be a ${r} string, but got "${originalPath}"`,
+ RangeError
+ );
+ }
+ return true;
+ }, "checkPath");
+ var isNotRelative = /* @__PURE__ */ __name((path27) => REGEX_TEST_INVALID_PATH.test(path27), "isNotRelative");
+ checkPath.isNotRelative = isNotRelative;
+ checkPath.convert = (p) => p;
+ var Ignore = class {
+ static {
+ __name(this, "Ignore");
+ }
+ constructor({
+ ignorecase = true,
+ ignoreCase = ignorecase,
+ allowRelativePaths = false
+ } = {}) {
+ define2(this, KEY_IGNORE, true);
+ this._rules = new RuleManager(ignoreCase);
+ this._strictPathCheck = !allowRelativePaths;
+ this._initCache();
+ }
+ _initCache() {
+ this._ignoreCache = /* @__PURE__ */ Object.create(null);
+ this._testCache = /* @__PURE__ */ Object.create(null);
+ }
+ add(pattern) {
+ if (this._rules.add(pattern)) {
+ this._initCache();
+ }
+ return this;
+ }
+ // legacy
+ addPattern(pattern) {
+ return this.add(pattern);
+ }
+ // @returns {TestResult}
+ _test(originalPath, cache3, checkUnignored, slices) {
+ const path27 = originalPath && checkPath.convert(originalPath);
+ checkPath(
+ path27,
+ originalPath,
+ this._strictPathCheck ? throwError : RETURN_FALSE
+ );
+ return this._t(path27, cache3, checkUnignored, slices);
+ }
+ checkIgnore(path27) {
+ if (!REGEX_TEST_TRAILING_SLASH.test(path27)) {
+ return this.test(path27);
+ }
+ const slices = path27.split(SLASH).filter(Boolean);
+ slices.pop();
+ if (slices.length) {
+ const parent = this._t(
+ slices.join(SLASH) + SLASH,
+ this._testCache,
+ true,
+ slices
+ );
+ if (parent.ignored) {
+ return parent;
+ }
+ }
+ return this._rules.test(path27, false, MODE_CHECK_IGNORE);
+ }
+ _t(path27, cache3, checkUnignored, slices) {
+ if (path27 in cache3) {
+ return cache3[path27];
+ }
+ if (!slices) {
+ slices = path27.split(SLASH).filter(Boolean);
+ }
+ slices.pop();
+ if (!slices.length) {
+ return cache3[path27] = this._rules.test(path27, checkUnignored, MODE_IGNORE);
+ }
+ const parent = this._t(
+ slices.join(SLASH) + SLASH,
+ cache3,
+ checkUnignored,
+ slices
+ );
+ return cache3[path27] = parent.ignored ? parent : this._rules.test(path27, checkUnignored, MODE_IGNORE);
+ }
+ ignores(path27) {
+ return this._test(path27, this._ignoreCache, false).ignored;
+ }
+ createFilter() {
+ return (path27) => !this.ignores(path27);
+ }
+ filter(paths) {
+ return makeArray(paths).filter(this.createFilter());
+ }
+ // @returns {TestResult}
+ test(path27) {
+ return this._test(path27, this._testCache, true);
+ }
+ };
+ var factory = /* @__PURE__ */ __name((options2) => new Ignore(options2), "factory");
+ var isPathValid = /* @__PURE__ */ __name((path27) => checkPath(path27 && checkPath.convert(path27), path27, RETURN_FALSE), "isPathValid");
+ var setupWindows = /* @__PURE__ */ __name(() => {
+ const makePosix = /* @__PURE__ */ __name((str3) => /^\\\\\?\\/.test(str3) || /["<>|\u0000-\u001F]+/u.test(str3) ? str3 : str3.replace(/\\/g, "/"), "makePosix");
+ checkPath.convert = makePosix;
+ const REGEX_TEST_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
+ checkPath.isNotRelative = (path27) => REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path27) || isNotRelative(path27);
+ }, "setupWindows");
+ if (
+ // Detect `process` so that it can run in browsers.
+ typeof process !== "undefined" && process.platform === "win32"
+ ) {
+ setupWindows();
+ }
+ module2.exports = factory;
+ factory.default = factory;
+ module2.exports.isPathValid = isPathValid;
+ define2(module2.exports, /* @__PURE__ */ Symbol.for("setupWindows"), setupWindows);
+ }
+});
+
+// node_modules/undici/lib/core/symbols.js
+var require_symbols = __commonJS({
+ "node_modules/undici/lib/core/symbols.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ module2.exports = {
+ kClose: /* @__PURE__ */ Symbol("close"),
+ kDestroy: /* @__PURE__ */ Symbol("destroy"),
+ kDispatch: /* @__PURE__ */ Symbol("dispatch"),
+ kUrl: /* @__PURE__ */ Symbol("url"),
+ kWriting: /* @__PURE__ */ Symbol("writing"),
+ kResuming: /* @__PURE__ */ Symbol("resuming"),
+ kQueue: /* @__PURE__ */ Symbol("queue"),
+ kConnect: /* @__PURE__ */ Symbol("connect"),
+ kConnecting: /* @__PURE__ */ Symbol("connecting"),
+ kKeepAliveDefaultTimeout: /* @__PURE__ */ Symbol("default keep alive timeout"),
+ kKeepAliveMaxTimeout: /* @__PURE__ */ Symbol("max keep alive timeout"),
+ kKeepAliveTimeoutThreshold: /* @__PURE__ */ Symbol("keep alive timeout threshold"),
+ kKeepAliveTimeoutValue: /* @__PURE__ */ Symbol("keep alive timeout"),
+ kKeepAlive: /* @__PURE__ */ Symbol("keep alive"),
+ kHeadersTimeout: /* @__PURE__ */ Symbol("headers timeout"),
+ kBodyTimeout: /* @__PURE__ */ Symbol("body timeout"),
+ kServerName: /* @__PURE__ */ Symbol("server name"),
+ kLocalAddress: /* @__PURE__ */ Symbol("local address"),
+ kHost: /* @__PURE__ */ Symbol("host"),
+ kNoRef: /* @__PURE__ */ Symbol("no ref"),
+ kBodyUsed: /* @__PURE__ */ Symbol("used"),
+ kBody: /* @__PURE__ */ Symbol("abstracted request body"),
+ kRunning: /* @__PURE__ */ Symbol("running"),
+ kBlocking: /* @__PURE__ */ Symbol("blocking"),
+ kPending: /* @__PURE__ */ Symbol("pending"),
+ kSize: /* @__PURE__ */ Symbol("size"),
+ kBusy: /* @__PURE__ */ Symbol("busy"),
+ kQueued: /* @__PURE__ */ Symbol("queued"),
+ kFree: /* @__PURE__ */ Symbol("free"),
+ kConnected: /* @__PURE__ */ Symbol("connected"),
+ kClosed: /* @__PURE__ */ Symbol("closed"),
+ kNeedDrain: /* @__PURE__ */ Symbol("need drain"),
+ kReset: /* @__PURE__ */ Symbol("reset"),
+ kDestroyed: /* @__PURE__ */ Symbol.for("nodejs.stream.destroyed"),
+ kResume: /* @__PURE__ */ Symbol("resume"),
+ kOnError: /* @__PURE__ */ Symbol("on error"),
+ kMaxHeadersSize: /* @__PURE__ */ Symbol("max headers size"),
+ kRunningIdx: /* @__PURE__ */ Symbol("running index"),
+ kPendingIdx: /* @__PURE__ */ Symbol("pending index"),
+ kError: /* @__PURE__ */ Symbol("error"),
+ kClients: /* @__PURE__ */ Symbol("clients"),
+ kClient: /* @__PURE__ */ Symbol("client"),
+ kParser: /* @__PURE__ */ Symbol("parser"),
+ kOnDestroyed: /* @__PURE__ */ Symbol("destroy callbacks"),
+ kPipelining: /* @__PURE__ */ Symbol("pipelining"),
+ kSocket: /* @__PURE__ */ Symbol("socket"),
+ kHostHeader: /* @__PURE__ */ Symbol("host header"),
+ kConnector: /* @__PURE__ */ Symbol("connector"),
+ kStrictContentLength: /* @__PURE__ */ Symbol("strict content length"),
+ kMaxRedirections: /* @__PURE__ */ Symbol("maxRedirections"),
+ kMaxRequests: /* @__PURE__ */ Symbol("maxRequestsPerClient"),
+ kProxy: /* @__PURE__ */ Symbol("proxy agent options"),
+ kCounter: /* @__PURE__ */ Symbol("socket request counter"),
+ kMaxResponseSize: /* @__PURE__ */ Symbol("max response size"),
+ kHTTP2Session: /* @__PURE__ */ Symbol("http2Session"),
+ kHTTP2SessionState: /* @__PURE__ */ Symbol("http2Session state"),
+ kRetryHandlerDefaultRetry: /* @__PURE__ */ Symbol("retry agent default retry"),
+ kConstruct: /* @__PURE__ */ Symbol("constructable"),
+ kListeners: /* @__PURE__ */ Symbol("listeners"),
+ kHTTPContext: /* @__PURE__ */ Symbol("http context"),
+ kMaxConcurrentStreams: /* @__PURE__ */ Symbol("max concurrent streams"),
+ kHTTP2InitialWindowSize: /* @__PURE__ */ Symbol("http2 initial window size"),
+ kHTTP2ConnectionWindowSize: /* @__PURE__ */ Symbol("http2 connection window size"),
+ kEnableConnectProtocol: /* @__PURE__ */ Symbol("http2session connect protocol"),
+ kRemoteSettings: /* @__PURE__ */ Symbol("http2session remote settings"),
+ kHTTP2Stream: /* @__PURE__ */ Symbol("http2session client stream"),
+ kPingInterval: /* @__PURE__ */ Symbol("ping interval"),
+ kNoProxyAgent: /* @__PURE__ */ Symbol("no proxy agent"),
+ kHttpProxyAgent: /* @__PURE__ */ Symbol("http proxy agent"),
+ kHttpsProxyAgent: /* @__PURE__ */ Symbol("https proxy agent"),
+ kSocks5ProxyAgent: /* @__PURE__ */ Symbol("socks5 proxy agent")
+ };
+ }
+});
+
+// node_modules/undici/lib/util/timers.js
+var require_timers = __commonJS({
+ "node_modules/undici/lib/util/timers.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var fastNow = 0;
+ var RESOLUTION_MS = 1e3;
+ var TICK_MS = (RESOLUTION_MS >> 1) - 1;
+ var fastNowTimeout;
+ var kFastTimer = /* @__PURE__ */ Symbol("kFastTimer");
+ var fastTimers = [];
+ var NOT_IN_LIST = -2;
+ var TO_BE_CLEARED = -1;
+ var PENDING = 0;
+ var ACTIVE = 1;
+ function onTick() {
+ fastNow += TICK_MS;
+ let idx = 0;
+ let len = fastTimers.length;
+ while (idx < len) {
+ const timer = fastTimers[idx];
+ if (timer._state === PENDING) {
+ timer._idleStart = fastNow - TICK_MS;
+ timer._state = ACTIVE;
+ } else if (timer._state === ACTIVE && fastNow >= timer._idleStart + timer._idleTimeout) {
+ timer._state = TO_BE_CLEARED;
+ timer._idleStart = -1;
+ timer._onTimeout(timer._timerArg);
+ }
+ if (timer._state === TO_BE_CLEARED) {
+ timer._state = NOT_IN_LIST;
+ if (--len !== 0) {
+ fastTimers[idx] = fastTimers[len];
+ }
+ } else {
+ ++idx;
+ }
+ }
+ fastTimers.length = len;
+ if (fastTimers.length !== 0) {
+ refreshTimeout();
+ }
+ }
+ __name(onTick, "onTick");
+ function refreshTimeout() {
+ if (fastNowTimeout?.refresh) {
+ fastNowTimeout.refresh();
+ } else {
+ clearTimeout(fastNowTimeout);
+ fastNowTimeout = setTimeout(onTick, TICK_MS);
+ fastNowTimeout?.unref();
+ }
+ }
+ __name(refreshTimeout, "refreshTimeout");
+ var FastTimer = class {
+ static {
+ __name(this, "FastTimer");
+ }
+ [kFastTimer] = true;
+ /**
+ * The state of the timer, which can be one of the following:
+ * - NOT_IN_LIST (-2)
+ * - TO_BE_CLEARED (-1)
+ * - PENDING (0)
+ * - ACTIVE (1)
+ *
+ * @type {-2|-1|0|1}
+ * @private
+ */
+ _state = NOT_IN_LIST;
+ /**
+ * The number of milliseconds to wait before calling the callback.
+ *
+ * @type {number}
+ * @private
+ */
+ _idleTimeout = -1;
+ /**
+ * The time in milliseconds when the timer was started. This value is used to
+ * calculate when the timer should expire.
+ *
+ * @type {number}
+ * @default -1
+ * @private
+ */
+ _idleStart = -1;
+ /**
+ * The function to be executed when the timer expires.
+ * @type {Function}
+ * @private
+ */
+ _onTimeout;
+ /**
+ * The argument to be passed to the callback when the timer expires.
+ *
+ * @type {*}
+ * @private
+ */
+ _timerArg;
+ /**
+ * @constructor
+ * @param {Function} callback A function to be executed after the timer
+ * expires.
+ * @param {number} delay The time, in milliseconds that the timer should wait
+ * before the specified function or code is executed.
+ * @param {*} arg
+ */
+ constructor(callback, delay, arg) {
+ this._onTimeout = callback;
+ this._idleTimeout = delay;
+ this._timerArg = arg;
+ this.refresh();
+ }
+ /**
+ * Sets the timer's start time to the current time, and reschedules the timer
+ * to call its callback at the previously specified duration adjusted to the
+ * current time.
+ * Using this on a timer that has already called its callback will reactivate
+ * the timer.
+ *
+ * @returns {void}
+ */
+ refresh() {
+ if (this._state === NOT_IN_LIST) {
+ fastTimers.push(this);
+ }
+ if (!fastNowTimeout || fastTimers.length === 1) {
+ refreshTimeout();
+ }
+ this._state = PENDING;
+ }
+ /**
+ * The `clear` method cancels the timer, preventing it from executing.
+ *
+ * @returns {void}
+ * @private
+ */
+ clear() {
+ this._state = TO_BE_CLEARED;
+ this._idleStart = -1;
+ }
+ };
+ module2.exports = {
+ /**
+ * The setTimeout() method sets a timer which executes a function once the
+ * timer expires.
+ * @param {Function} callback A function to be executed after the timer
+ * expires.
+ * @param {number} delay The time, in milliseconds that the timer should
+ * wait before the specified function or code is executed.
+ * @param {*} [arg] An optional argument to be passed to the callback function
+ * when the timer expires.
+ * @returns {NodeJS.Timeout|FastTimer}
+ */
+ setTimeout(callback, delay, arg) {
+ return delay <= RESOLUTION_MS ? setTimeout(callback, delay, arg) : new FastTimer(callback, delay, arg);
+ },
+ /**
+ * The clearTimeout method cancels an instantiated Timer previously created
+ * by calling setTimeout.
+ *
+ * @param {NodeJS.Timeout|FastTimer} timeout
+ */
+ clearTimeout(timeout) {
+ if (timeout[kFastTimer]) {
+ timeout.clear();
+ } else {
+ clearTimeout(timeout);
+ }
+ },
+ /**
+ * The setFastTimeout() method sets a fastTimer which executes a function once
+ * the timer expires.
+ * @param {Function} callback A function to be executed after the timer
+ * expires.
+ * @param {number} delay The time, in milliseconds that the timer should
+ * wait before the specified function or code is executed.
+ * @param {*} [arg] An optional argument to be passed to the callback function
+ * when the timer expires.
+ * @returns {FastTimer}
+ */
+ setFastTimeout(callback, delay, arg) {
+ return new FastTimer(callback, delay, arg);
+ },
+ /**
+ * The clearTimeout method cancels an instantiated FastTimer previously
+ * created by calling setFastTimeout.
+ *
+ * @param {FastTimer} timeout
+ */
+ clearFastTimeout(timeout) {
+ timeout.clear();
+ },
+ /**
+ * The now method returns the value of the internal fast timer clock.
+ *
+ * @returns {number}
+ */
+ now() {
+ return fastNow;
+ },
+ /**
+ * Trigger the onTick function to process the fastTimers array.
+ * Exported for testing purposes only.
+ * Marking as deprecated to discourage any use outside of testing.
+ * @deprecated
+ * @param {number} [delay=0] The delay in milliseconds to add to the now value.
+ */
+ tick(delay = 0) {
+ fastNow += delay - RESOLUTION_MS + 1;
+ onTick();
+ onTick();
+ },
+ /**
+ * Reset FastTimers.
+ * Exported for testing purposes only.
+ * Marking as deprecated to discourage any use outside of testing.
+ * @deprecated
+ */
+ reset() {
+ fastNow = 0;
+ fastTimers.length = 0;
+ clearTimeout(fastNowTimeout);
+ fastNowTimeout = null;
+ },
+ /**
+ * Exporting for testing purposes only.
+ * Marking as deprecated to discourage any use outside of testing.
+ * @deprecated
+ */
+ kFastTimer
+ };
+ }
+});
+
+// node_modules/undici/lib/core/errors.js
+var require_errors = __commonJS({
+ "node_modules/undici/lib/core/errors.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var kUndiciError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR");
+ var UndiciError = class extends Error {
+ static {
+ __name(this, "UndiciError");
+ }
+ constructor(message, options2) {
+ super(message, options2);
+ this.name = "UndiciError";
+ this.code = "UND_ERR";
+ }
+ static [Symbol.hasInstance](instance) {
+ return instance && instance[kUndiciError] === true;
+ }
+ get [kUndiciError]() {
+ return true;
+ }
+ };
+ var kConnectTimeoutError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_CONNECT_TIMEOUT");
+ var ConnectTimeoutError = class extends UndiciError {
+ static {
+ __name(this, "ConnectTimeoutError");
+ }
+ constructor(message) {
+ super(message);
+ this.name = "ConnectTimeoutError";
+ this.message = message || "Connect Timeout Error";
+ this.code = "UND_ERR_CONNECT_TIMEOUT";
+ }
+ static [Symbol.hasInstance](instance) {
+ return instance && instance[kConnectTimeoutError] === true;
+ }
+ get [kConnectTimeoutError]() {
+ return true;
+ }
+ };
+ var kHeadersTimeoutError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_HEADERS_TIMEOUT");
+ var HeadersTimeoutError = class extends UndiciError {
+ static {
+ __name(this, "HeadersTimeoutError");
+ }
+ constructor(message) {
+ super(message);
+ this.name = "HeadersTimeoutError";
+ this.message = message || "Headers Timeout Error";
+ this.code = "UND_ERR_HEADERS_TIMEOUT";
+ }
+ static [Symbol.hasInstance](instance) {
+ return instance && instance[kHeadersTimeoutError] === true;
+ }
+ get [kHeadersTimeoutError]() {
+ return true;
+ }
+ };
+ var kHeadersOverflowError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_HEADERS_OVERFLOW");
+ var HeadersOverflowError = class extends UndiciError {
+ static {
+ __name(this, "HeadersOverflowError");
+ }
+ constructor(message) {
+ super(message);
+ this.name = "HeadersOverflowError";
+ this.message = message || "Headers Overflow Error";
+ this.code = "UND_ERR_HEADERS_OVERFLOW";
+ }
+ static [Symbol.hasInstance](instance) {
+ return instance && instance[kHeadersOverflowError] === true;
+ }
+ get [kHeadersOverflowError]() {
+ return true;
+ }
+ };
+ var kBodyTimeoutError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_BODY_TIMEOUT");
+ var BodyTimeoutError = class extends UndiciError {
+ static {
+ __name(this, "BodyTimeoutError");
+ }
+ constructor(message) {
+ super(message);
+ this.name = "BodyTimeoutError";
+ this.message = message || "Body Timeout Error";
+ this.code = "UND_ERR_BODY_TIMEOUT";
+ }
+ static [Symbol.hasInstance](instance) {
+ return instance && instance[kBodyTimeoutError] === true;
+ }
+ get [kBodyTimeoutError]() {
+ return true;
+ }
+ };
+ var kInvalidArgumentError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_INVALID_ARG");
+ var InvalidArgumentError = class extends UndiciError {
+ static {
+ __name(this, "InvalidArgumentError");
+ }
+ constructor(message) {
+ super(message);
+ this.name = "InvalidArgumentError";
+ this.message = message || "Invalid Argument Error";
+ this.code = "UND_ERR_INVALID_ARG";
+ }
+ static [Symbol.hasInstance](instance) {
+ return instance && instance[kInvalidArgumentError] === true;
+ }
+ get [kInvalidArgumentError]() {
+ return true;
+ }
+ };
+ var kInvalidReturnValueError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_INVALID_RETURN_VALUE");
+ var InvalidReturnValueError = class extends UndiciError {
+ static {
+ __name(this, "InvalidReturnValueError");
+ }
+ constructor(message) {
+ super(message);
+ this.name = "InvalidReturnValueError";
+ this.message = message || "Invalid Return Value Error";
+ this.code = "UND_ERR_INVALID_RETURN_VALUE";
+ }
+ static [Symbol.hasInstance](instance) {
+ return instance && instance[kInvalidReturnValueError] === true;
+ }
+ get [kInvalidReturnValueError]() {
+ return true;
+ }
+ };
+ var kAbortError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_ABORT");
+ var AbortError = class extends UndiciError {
+ static {
+ __name(this, "AbortError");
+ }
+ constructor(message) {
+ super(message);
+ this.name = "AbortError";
+ this.message = message || "The operation was aborted";
+ this.code = "UND_ERR_ABORT";
+ }
+ static [Symbol.hasInstance](instance) {
+ return instance && instance[kAbortError] === true;
+ }
+ get [kAbortError]() {
+ return true;
+ }
+ };
+ var kRequestAbortedError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_ABORTED");
+ var RequestAbortedError = class extends AbortError {
+ static {
+ __name(this, "RequestAbortedError");
+ }
+ constructor(message) {
+ super(message);
+ this.name = "AbortError";
+ this.message = message || "Request aborted";
+ this.code = "UND_ERR_ABORTED";
+ }
+ static [Symbol.hasInstance](instance) {
+ return instance && instance[kRequestAbortedError] === true;
+ }
+ get [kRequestAbortedError]() {
+ return true;
+ }
+ };
+ var kInformationalError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_INFO");
+ var InformationalError = class extends UndiciError {
+ static {
+ __name(this, "InformationalError");
+ }
+ constructor(message) {
+ super(message);
+ this.name = "InformationalError";
+ this.message = message || "Request information";
+ this.code = "UND_ERR_INFO";
+ }
+ static [Symbol.hasInstance](instance) {
+ return instance && instance[kInformationalError] === true;
+ }
+ get [kInformationalError]() {
+ return true;
+ }
+ };
+ var kRequestContentLengthMismatchError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_REQ_CONTENT_LENGTH_MISMATCH");
+ var RequestContentLengthMismatchError = class extends UndiciError {
+ static {
+ __name(this, "RequestContentLengthMismatchError");
+ }
+ constructor(message) {
+ super(message);
+ this.name = "RequestContentLengthMismatchError";
+ this.message = message || "Request body length does not match content-length header";
+ this.code = "UND_ERR_REQ_CONTENT_LENGTH_MISMATCH";
+ }
+ static [Symbol.hasInstance](instance) {
+ return instance && instance[kRequestContentLengthMismatchError] === true;
+ }
+ get [kRequestContentLengthMismatchError]() {
+ return true;
+ }
+ };
+ var kResponseContentLengthMismatchError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_RES_CONTENT_LENGTH_MISMATCH");
+ var ResponseContentLengthMismatchError = class extends UndiciError {
+ static {
+ __name(this, "ResponseContentLengthMismatchError");
+ }
+ constructor(message) {
+ super(message);
+ this.name = "ResponseContentLengthMismatchError";
+ this.message = message || "Response body length does not match content-length header";
+ this.code = "UND_ERR_RES_CONTENT_LENGTH_MISMATCH";
+ }
+ static [Symbol.hasInstance](instance) {
+ return instance && instance[kResponseContentLengthMismatchError] === true;
+ }
+ get [kResponseContentLengthMismatchError]() {
+ return true;
+ }
+ };
+ var kClientDestroyedError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_DESTROYED");
+ var ClientDestroyedError = class extends UndiciError {
+ static {
+ __name(this, "ClientDestroyedError");
+ }
+ constructor(message) {
+ super(message);
+ this.name = "ClientDestroyedError";
+ this.message = message || "The client is destroyed";
+ this.code = "UND_ERR_DESTROYED";
+ }
+ static [Symbol.hasInstance](instance) {
+ return instance && instance[kClientDestroyedError] === true;
+ }
+ get [kClientDestroyedError]() {
+ return true;
+ }
+ };
+ var kClientClosedError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_CLOSED");
+ var ClientClosedError = class extends UndiciError {
+ static {
+ __name(this, "ClientClosedError");
+ }
+ constructor(message) {
+ super(message);
+ this.name = "ClientClosedError";
+ this.message = message || "The client is closed";
+ this.code = "UND_ERR_CLOSED";
+ }
+ static [Symbol.hasInstance](instance) {
+ return instance && instance[kClientClosedError] === true;
+ }
+ get [kClientClosedError]() {
+ return true;
+ }
+ };
+ var kSocketError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_SOCKET");
+ var SocketError = class extends UndiciError {
+ static {
+ __name(this, "SocketError");
+ }
+ constructor(message, socket) {
+ super(message);
+ this.name = "SocketError";
+ this.message = message || "Socket error";
+ this.code = "UND_ERR_SOCKET";
+ this.socket = socket;
+ }
+ static [Symbol.hasInstance](instance) {
+ return instance && instance[kSocketError] === true;
+ }
+ get [kSocketError]() {
+ return true;
+ }
+ };
+ var kNotSupportedError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_NOT_SUPPORTED");
+ var NotSupportedError = class extends UndiciError {
+ static {
+ __name(this, "NotSupportedError");
+ }
+ constructor(message) {
+ super(message);
+ this.name = "NotSupportedError";
+ this.message = message || "Not supported error";
+ this.code = "UND_ERR_NOT_SUPPORTED";
+ }
+ static [Symbol.hasInstance](instance) {
+ return instance && instance[kNotSupportedError] === true;
+ }
+ get [kNotSupportedError]() {
+ return true;
+ }
+ };
+ var kBalancedPoolMissingUpstreamError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_BPL_MISSING_UPSTREAM");
+ var BalancedPoolMissingUpstreamError = class extends UndiciError {
+ static {
+ __name(this, "BalancedPoolMissingUpstreamError");
+ }
+ constructor(message) {
+ super(message);
+ this.name = "MissingUpstreamError";
+ this.message = message || "No upstream has been added to the BalancedPool";
+ this.code = "UND_ERR_BPL_MISSING_UPSTREAM";
+ }
+ static [Symbol.hasInstance](instance) {
+ return instance && instance[kBalancedPoolMissingUpstreamError] === true;
+ }
+ get [kBalancedPoolMissingUpstreamError]() {
+ return true;
+ }
+ };
+ var kHTTPParserError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_HTTP_PARSER");
+ var HTTPParserError = class extends Error {
+ static {
+ __name(this, "HTTPParserError");
+ }
+ constructor(message, code, data) {
+ super(message);
+ this.name = "HTTPParserError";
+ this.code = code ? `HPE_${code}` : void 0;
+ this.data = data ? data.toString() : void 0;
+ }
+ static [Symbol.hasInstance](instance) {
+ return instance && instance[kHTTPParserError] === true;
+ }
+ get [kHTTPParserError]() {
+ return true;
+ }
+ };
+ var kResponseExceededMaxSizeError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_RES_EXCEEDED_MAX_SIZE");
+ var ResponseExceededMaxSizeError = class extends UndiciError {
+ static {
+ __name(this, "ResponseExceededMaxSizeError");
+ }
+ constructor(message) {
+ super(message);
+ this.name = "ResponseExceededMaxSizeError";
+ this.message = message || "Response content exceeded max size";
+ this.code = "UND_ERR_RES_EXCEEDED_MAX_SIZE";
+ }
+ static [Symbol.hasInstance](instance) {
+ return instance && instance[kResponseExceededMaxSizeError] === true;
+ }
+ get [kResponseExceededMaxSizeError]() {
+ return true;
+ }
+ };
+ var kRequestRetryError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_REQ_RETRY");
+ var RequestRetryError = class extends UndiciError {
+ static {
+ __name(this, "RequestRetryError");
+ }
+ constructor(message, code, { headers, data }) {
+ super(message);
+ this.name = "RequestRetryError";
+ this.message = message || "Request retry error";
+ this.code = "UND_ERR_REQ_RETRY";
+ this.statusCode = code;
+ this.data = data;
+ this.headers = headers;
+ }
+ static [Symbol.hasInstance](instance) {
+ return instance && instance[kRequestRetryError] === true;
+ }
+ get [kRequestRetryError]() {
+ return true;
+ }
+ };
+ var kResponseError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_RESPONSE");
+ var ResponseError = class extends UndiciError {
+ static {
+ __name(this, "ResponseError");
+ }
+ constructor(message, code, { headers, body }) {
+ super(message);
+ this.name = "ResponseError";
+ this.message = message || "Response error";
+ this.code = "UND_ERR_RESPONSE";
+ this.statusCode = code;
+ this.body = body;
+ this.headers = headers;
+ }
+ static [Symbol.hasInstance](instance) {
+ return instance && instance[kResponseError] === true;
+ }
+ get [kResponseError]() {
+ return true;
+ }
+ };
+ var kSecureProxyConnectionError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_PRX_TLS");
+ var SecureProxyConnectionError = class extends UndiciError {
+ static {
+ __name(this, "SecureProxyConnectionError");
+ }
+ constructor(cause, message, options2 = {}) {
+ super(message, { cause, ...options2 });
+ this.name = "SecureProxyConnectionError";
+ this.message = message || "Secure Proxy Connection failed";
+ this.code = "UND_ERR_PRX_TLS";
+ this.cause = cause;
+ }
+ static [Symbol.hasInstance](instance) {
+ return instance && instance[kSecureProxyConnectionError] === true;
+ }
+ get [kSecureProxyConnectionError]() {
+ return true;
+ }
+ };
+ var kMaxOriginsReachedError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_MAX_ORIGINS_REACHED");
+ var MaxOriginsReachedError = class extends UndiciError {
+ static {
+ __name(this, "MaxOriginsReachedError");
+ }
+ constructor(message) {
+ super(message);
+ this.name = "MaxOriginsReachedError";
+ this.message = message || "Maximum allowed origins reached";
+ this.code = "UND_ERR_MAX_ORIGINS_REACHED";
+ }
+ static [Symbol.hasInstance](instance) {
+ return instance && instance[kMaxOriginsReachedError] === true;
+ }
+ get [kMaxOriginsReachedError]() {
+ return true;
+ }
+ };
+ var Socks5ProxyError = class extends UndiciError {
+ static {
+ __name(this, "Socks5ProxyError");
+ }
+ constructor(message, code) {
+ super(message);
+ this.name = "Socks5ProxyError";
+ this.message = message || "SOCKS5 proxy error";
+ this.code = code || "UND_ERR_SOCKS5";
+ }
+ };
+ var kMessageSizeExceededError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_WS_MESSAGE_SIZE_EXCEEDED");
+ var MessageSizeExceededError = class extends UndiciError {
+ static {
+ __name(this, "MessageSizeExceededError");
+ }
+ constructor(message) {
+ super(message);
+ this.name = "MessageSizeExceededError";
+ this.message = message || "Max decompressed message size exceeded";
+ this.code = "UND_ERR_WS_MESSAGE_SIZE_EXCEEDED";
+ }
+ static [Symbol.hasInstance](instance) {
+ return instance && instance[kMessageSizeExceededError] === true;
+ }
+ get [kMessageSizeExceededError]() {
+ return true;
+ }
+ };
+ module2.exports = {
+ AbortError,
+ HTTPParserError,
+ UndiciError,
+ HeadersTimeoutError,
+ HeadersOverflowError,
+ BodyTimeoutError,
+ RequestContentLengthMismatchError,
+ ConnectTimeoutError,
+ InvalidArgumentError,
+ InvalidReturnValueError,
+ RequestAbortedError,
+ ClientDestroyedError,
+ ClientClosedError,
+ InformationalError,
+ SocketError,
+ NotSupportedError,
+ ResponseContentLengthMismatchError,
+ BalancedPoolMissingUpstreamError,
+ ResponseExceededMaxSizeError,
+ RequestRetryError,
+ ResponseError,
+ SecureProxyConnectionError,
+ MaxOriginsReachedError,
+ Socks5ProxyError,
+ MessageSizeExceededError
+ };
+ }
+});
+
+// node_modules/undici/lib/core/constants.js
+var require_constants2 = __commonJS({
+ "node_modules/undici/lib/core/constants.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var wellknownHeaderNames = (
+ /** @type {const} */
+ [
+ "Accept",
+ "Accept-Encoding",
+ "Accept-Language",
+ "Accept-Ranges",
+ "Access-Control-Allow-Credentials",
+ "Access-Control-Allow-Headers",
+ "Access-Control-Allow-Methods",
+ "Access-Control-Allow-Origin",
+ "Access-Control-Expose-Headers",
+ "Access-Control-Max-Age",
+ "Access-Control-Request-Headers",
+ "Access-Control-Request-Method",
+ "Age",
+ "Allow",
+ "Alt-Svc",
+ "Alt-Used",
+ "Authorization",
+ "Cache-Control",
+ "Clear-Site-Data",
+ "Connection",
+ "Content-Disposition",
+ "Content-Encoding",
+ "Content-Language",
+ "Content-Length",
+ "Content-Location",
+ "Content-Range",
+ "Content-Security-Policy",
+ "Content-Security-Policy-Report-Only",
+ "Content-Type",
+ "Cookie",
+ "Cross-Origin-Embedder-Policy",
+ "Cross-Origin-Opener-Policy",
+ "Cross-Origin-Resource-Policy",
+ "Date",
+ "Device-Memory",
+ "Downlink",
+ "ECT",
+ "ETag",
+ "Expect",
+ "Expect-CT",
+ "Expires",
+ "Forwarded",
+ "From",
+ "Host",
+ "If-Match",
+ "If-Modified-Since",
+ "If-None-Match",
+ "If-Range",
+ "If-Unmodified-Since",
+ "Keep-Alive",
+ "Last-Modified",
+ "Link",
+ "Location",
+ "Max-Forwards",
+ "Origin",
+ "Permissions-Policy",
+ "Pragma",
+ "Proxy-Authenticate",
+ "Proxy-Authorization",
+ "RTT",
+ "Range",
+ "Referer",
+ "Referrer-Policy",
+ "Refresh",
+ "Retry-After",
+ "Sec-WebSocket-Accept",
+ "Sec-WebSocket-Extensions",
+ "Sec-WebSocket-Key",
+ "Sec-WebSocket-Protocol",
+ "Sec-WebSocket-Version",
+ "Server",
+ "Server-Timing",
+ "Service-Worker-Allowed",
+ "Service-Worker-Navigation-Preload",
+ "Set-Cookie",
+ "SourceMap",
+ "Strict-Transport-Security",
+ "Supports-Loading-Mode",
+ "TE",
+ "Timing-Allow-Origin",
+ "Trailer",
+ "Transfer-Encoding",
+ "Upgrade",
+ "Upgrade-Insecure-Requests",
+ "User-Agent",
+ "Vary",
+ "Via",
+ "WWW-Authenticate",
+ "X-Content-Type-Options",
+ "X-DNS-Prefetch-Control",
+ "X-Frame-Options",
+ "X-Permitted-Cross-Domain-Policies",
+ "X-Powered-By",
+ "X-Requested-With",
+ "X-XSS-Protection"
+ ]
+ );
+ var headerNameLowerCasedRecord = {};
+ Object.setPrototypeOf(headerNameLowerCasedRecord, null);
+ var wellknownHeaderNameBuffers = {};
+ Object.setPrototypeOf(wellknownHeaderNameBuffers, null);
+ function getHeaderNameAsBuffer(header) {
+ let buffer = wellknownHeaderNameBuffers[header];
+ if (buffer === void 0) {
+ buffer = Buffer.from(header);
+ }
+ return buffer;
+ }
+ __name(getHeaderNameAsBuffer, "getHeaderNameAsBuffer");
+ for (let i = 0; i < wellknownHeaderNames.length; ++i) {
+ const key = wellknownHeaderNames[i];
+ const lowerCasedKey = key.toLowerCase();
+ headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] = lowerCasedKey;
+ }
+ module2.exports = {
+ wellknownHeaderNames,
+ headerNameLowerCasedRecord,
+ getHeaderNameAsBuffer
+ };
+ }
+});
+
+// node_modules/undici/lib/core/tree.js
+var require_tree = __commonJS({
+ "node_modules/undici/lib/core/tree.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var {
+ wellknownHeaderNames,
+ headerNameLowerCasedRecord
+ } = require_constants2();
+ var TstNode = class _TstNode {
+ static {
+ __name(this, "TstNode");
+ }
+ /** @type {any} */
+ value = null;
+ /** @type {null | TstNode} */
+ left = null;
+ /** @type {null | TstNode} */
+ middle = null;
+ /** @type {null | TstNode} */
+ right = null;
+ /** @type {number} */
+ code;
+ /**
+ * @param {string} key
+ * @param {any} value
+ * @param {number} index
+ */
+ constructor(key, value, index) {
+ if (index === void 0 || index >= key.length) {
+ throw new TypeError("Unreachable");
+ }
+ const code = this.code = key.charCodeAt(index);
+ if (code > 127) {
+ throw new TypeError("key must be ascii string");
+ }
+ if (key.length !== ++index) {
+ this.middle = new _TstNode(key, value, index);
+ } else {
+ this.value = value;
+ }
+ }
+ /**
+ * @param {string} key
+ * @param {any} value
+ * @returns {void}
+ */
+ add(key, value) {
+ const length = key.length;
+ if (length === 0) {
+ throw new TypeError("Unreachable");
+ }
+ let index = 0;
+ let node = this;
+ while (true) {
+ const code = key.charCodeAt(index);
+ if (code > 127) {
+ throw new TypeError("key must be ascii string");
+ }
+ if (node.code === code) {
+ if (length === ++index) {
+ node.value = value;
+ break;
+ } else if (node.middle !== null) {
+ node = node.middle;
+ } else {
+ node.middle = new _TstNode(key, value, index);
+ break;
+ }
+ } else if (node.code < code) {
+ if (node.left !== null) {
+ node = node.left;
+ } else {
+ node.left = new _TstNode(key, value, index);
+ break;
+ }
+ } else if (node.right !== null) {
+ node = node.right;
+ } else {
+ node.right = new _TstNode(key, value, index);
+ break;
+ }
+ }
+ }
+ /**
+ * @param {Uint8Array} key
+ * @returns {TstNode | null}
+ */
+ search(key) {
+ const keylength = key.length;
+ let index = 0;
+ let node = this;
+ while (node !== null && index < keylength) {
+ let code = key[index];
+ if (code <= 90 && code >= 65) {
+ code |= 32;
+ }
+ while (node !== null) {
+ if (code === node.code) {
+ if (keylength === ++index) {
+ return node;
+ }
+ node = node.middle;
+ break;
+ }
+ node = node.code < code ? node.left : node.right;
+ }
+ }
+ return null;
+ }
+ };
+ var TernarySearchTree = class {
+ static {
+ __name(this, "TernarySearchTree");
+ }
+ /** @type {TstNode | null} */
+ node = null;
+ /**
+ * @param {string} key
+ * @param {any} value
+ * @returns {void}
+ * */
+ insert(key, value) {
+ if (this.node === null) {
+ this.node = new TstNode(key, value, 0);
+ } else {
+ this.node.add(key, value);
+ }
+ }
+ /**
+ * @param {Uint8Array} key
+ * @returns {any}
+ */
+ lookup(key) {
+ return this.node?.search(key)?.value ?? null;
+ }
+ };
+ var tree = new TernarySearchTree();
+ for (let i = 0; i < wellknownHeaderNames.length; ++i) {
+ const key = headerNameLowerCasedRecord[wellknownHeaderNames[i]];
+ tree.insert(key, key);
+ }
+ module2.exports = {
+ TernarySearchTree,
+ tree
+ };
+ }
+});
+
+// node_modules/undici/lib/core/util.js
+var require_util = __commonJS({
+ "node_modules/undici/lib/core/util.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var assert2 = __require("node:assert");
+ var { kDestroyed, kBodyUsed, kListeners, kBody } = require_symbols();
+ var { IncomingMessage } = __require("node:http");
+ var stream = __require("node:stream");
+ var net = __require("node:net");
+ var { stringify: stringify2 } = __require("node:querystring");
+ var { EventEmitter: EE } = __require("node:events");
+ var timers = require_timers();
+ var { InvalidArgumentError, ConnectTimeoutError } = require_errors();
+ var { headerNameLowerCasedRecord } = require_constants2();
+ var { tree } = require_tree();
+ var [nodeMajor, nodeMinor] = process.versions.node.split(".", 2).map((v) => Number(v));
+ var BodyAsyncIterable = class {
+ static {
+ __name(this, "BodyAsyncIterable");
+ }
+ constructor(body) {
+ this[kBody] = body;
+ this[kBodyUsed] = false;
+ }
+ async *[Symbol.asyncIterator]() {
+ assert2(!this[kBodyUsed], "disturbed");
+ this[kBodyUsed] = true;
+ yield* this[kBody];
+ }
+ };
+ function noop3() {
+ }
+ __name(noop3, "noop");
+ function wrapRequestBody(body) {
+ if (isStream(body)) {
+ if (bodyLength(body) === 0) {
+ body.on("data", function() {
+ assert2(false);
+ });
+ }
+ if (typeof body.readableDidRead !== "boolean") {
+ body[kBodyUsed] = false;
+ EE.prototype.on.call(body, "data", function() {
+ this[kBodyUsed] = true;
+ });
+ }
+ return body;
+ } else if (body && typeof body.pipeTo === "function") {
+ return new BodyAsyncIterable(body);
+ } else if (body && isFormDataLike(body)) {
+ return body;
+ } else if (body && typeof body !== "string" && !ArrayBuffer.isView(body) && isIterable(body)) {
+ return new BodyAsyncIterable(body);
+ } else {
+ return body;
+ }
+ }
+ __name(wrapRequestBody, "wrapRequestBody");
+ function isStream(obj) {
+ return obj && typeof obj === "object" && typeof obj.pipe === "function" && typeof obj.on === "function";
+ }
+ __name(isStream, "isStream");
+ function isBlobLike2(object2) {
+ if (object2 === null) {
+ return false;
+ } else if (object2 instanceof Blob) {
+ return true;
+ } else if (typeof object2 !== "object") {
+ return false;
+ } else {
+ const sTag = object2[Symbol.toStringTag];
+ return (sTag === "Blob" || sTag === "File") && ("stream" in object2 && typeof object2.stream === "function" || "arrayBuffer" in object2 && typeof object2.arrayBuffer === "function");
+ }
+ }
+ __name(isBlobLike2, "isBlobLike");
+ function pathHasQueryOrFragment(url2) {
+ return url2.includes("?") || url2.includes("#");
+ }
+ __name(pathHasQueryOrFragment, "pathHasQueryOrFragment");
+ function serializePathWithQuery(url2, queryParams) {
+ if (pathHasQueryOrFragment(url2)) {
+ throw new Error('Query params cannot be passed when url already contains "?" or "#".');
+ }
+ const stringified = stringify2(queryParams);
+ if (stringified) {
+ url2 += "?" + stringified;
+ }
+ return url2;
+ }
+ __name(serializePathWithQuery, "serializePathWithQuery");
+ function isValidPort(port) {
+ const value = parseInt(port, 10);
+ return value === Number(port) && value >= 0 && value <= 65535;
+ }
+ __name(isValidPort, "isValidPort");
+ function isHttpOrHttpsPrefixed(value) {
+ return value != null && value[0] === "h" && value[1] === "t" && value[2] === "t" && value[3] === "p" && (value[4] === ":" || value[4] === "s" && value[5] === ":");
+ }
+ __name(isHttpOrHttpsPrefixed, "isHttpOrHttpsPrefixed");
+ function parseURL(url2) {
+ if (typeof url2 === "string") {
+ url2 = new URL(url2);
+ if (!isHttpOrHttpsPrefixed(url2.origin || url2.protocol)) {
+ throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`.");
+ }
+ return url2;
+ }
+ if (!url2 || typeof url2 !== "object") {
+ throw new InvalidArgumentError("Invalid URL: The URL argument must be a non-null object.");
+ }
+ if (!(url2 instanceof URL)) {
+ if (url2.port != null && url2.port !== "" && isValidPort(url2.port) === false) {
+ throw new InvalidArgumentError("Invalid URL: port must be a valid integer or a string representation of an integer.");
+ }
+ if (url2.path != null && typeof url2.path !== "string") {
+ throw new InvalidArgumentError("Invalid URL path: the path must be a string or null/undefined.");
+ }
+ if (url2.pathname != null && typeof url2.pathname !== "string") {
+ throw new InvalidArgumentError("Invalid URL pathname: the pathname must be a string or null/undefined.");
+ }
+ if (url2.hostname != null && typeof url2.hostname !== "string") {
+ throw new InvalidArgumentError("Invalid URL hostname: the hostname must be a string or null/undefined.");
+ }
+ if (url2.origin != null && typeof url2.origin !== "string") {
+ throw new InvalidArgumentError("Invalid URL origin: the origin must be a string or null/undefined.");
+ }
+ if (!isHttpOrHttpsPrefixed(url2.origin || url2.protocol)) {
+ throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`.");
+ }
+ const port = url2.port != null ? url2.port : url2.protocol === "https:" ? 443 : 80;
+ let origin = url2.origin != null ? url2.origin : `${url2.protocol || ""}//${url2.hostname || ""}:${port}`;
+ let path27 = url2.path != null ? url2.path : `${url2.pathname || ""}${url2.search || ""}`;
+ if (origin[origin.length - 1] === "/") {
+ origin = origin.slice(0, origin.length - 1);
+ }
+ if (path27 && path27[0] !== "/") {
+ path27 = `/${path27}`;
+ }
+ return new URL(`${origin}${path27}`);
+ }
+ if (!isHttpOrHttpsPrefixed(url2.origin || url2.protocol)) {
+ throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`.");
+ }
+ return url2;
+ }
+ __name(parseURL, "parseURL");
+ function parseOrigin(url2) {
+ url2 = parseURL(url2);
+ if (url2.pathname !== "/" || url2.search || url2.hash) {
+ throw new InvalidArgumentError("invalid url");
+ }
+ return url2;
+ }
+ __name(parseOrigin, "parseOrigin");
+ function getHostname(host) {
+ if (host[0] === "[") {
+ const idx2 = host.indexOf("]");
+ assert2(idx2 !== -1);
+ return host.substring(1, idx2);
+ }
+ const idx = host.indexOf(":");
+ if (idx === -1) return host;
+ return host.substring(0, idx);
+ }
+ __name(getHostname, "getHostname");
+ function getServerName(host) {
+ if (!host) {
+ return null;
+ }
+ assert2(typeof host === "string");
+ const servername = getHostname(host);
+ if (net.isIP(servername)) {
+ return "";
+ }
+ return servername;
+ }
+ __name(getServerName, "getServerName");
+ function deepClone(obj) {
+ return JSON.parse(JSON.stringify(obj));
+ }
+ __name(deepClone, "deepClone");
+ function isAsyncIterable2(obj) {
+ return !!(obj != null && typeof obj[Symbol.asyncIterator] === "function");
+ }
+ __name(isAsyncIterable2, "isAsyncIterable");
+ function isIterable(obj) {
+ return !!(obj != null && (typeof obj[Symbol.iterator] === "function" || typeof obj[Symbol.asyncIterator] === "function"));
+ }
+ __name(isIterable, "isIterable");
+ function hasSafeIterator(obj) {
+ const prototype = Object.getPrototypeOf(obj);
+ const ownIterator = Object.prototype.hasOwnProperty.call(obj, Symbol.iterator);
+ return ownIterator || prototype != null && prototype !== Object.prototype && typeof obj[Symbol.iterator] === "function";
+ }
+ __name(hasSafeIterator, "hasSafeIterator");
+ function bodyLength(body) {
+ if (body == null) {
+ return 0;
+ } else if (isStream(body)) {
+ const state = body._readableState;
+ return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length) ? state.length : null;
+ } else if (isBlobLike2(body)) {
+ return body.size != null ? body.size : null;
+ } else if (isBuffer(body)) {
+ return body.byteLength;
+ }
+ return null;
+ }
+ __name(bodyLength, "bodyLength");
+ function isDestroyed(body) {
+ return body && !!(body.destroyed || body[kDestroyed] || stream.isDestroyed?.(body));
+ }
+ __name(isDestroyed, "isDestroyed");
+ function destroy(stream2, err) {
+ if (stream2 == null || !isStream(stream2) || isDestroyed(stream2)) {
+ return;
+ }
+ if (typeof stream2.destroy === "function") {
+ if (Object.getPrototypeOf(stream2).constructor === IncomingMessage) {
+ stream2.socket = null;
+ }
+ stream2.destroy(err);
+ } else if (err) {
+ queueMicrotask(() => {
+ stream2.emit("error", err);
+ });
+ }
+ if (stream2.destroyed !== true) {
+ stream2[kDestroyed] = true;
+ }
+ }
+ __name(destroy, "destroy");
+ var KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/;
+ function parseKeepAliveTimeout(val) {
+ const m = val.match(KEEPALIVE_TIMEOUT_EXPR);
+ return m ? parseInt(m[1], 10) * 1e3 : null;
+ }
+ __name(parseKeepAliveTimeout, "parseKeepAliveTimeout");
+ function headerNameToString(value) {
+ return typeof value === "string" ? headerNameLowerCasedRecord[value] ?? value.toLowerCase() : tree.lookup(value) ?? value.toString("latin1").toLowerCase();
+ }
+ __name(headerNameToString, "headerNameToString");
+ function bufferToLowerCasedHeaderName(value) {
+ return tree.lookup(value) ?? value.toString("latin1").toLowerCase();
+ }
+ __name(bufferToLowerCasedHeaderName, "bufferToLowerCasedHeaderName");
+ function parseHeaders(headers, obj) {
+ if (obj === void 0) obj = {};
+ for (let i = 0; i < headers.length; i += 2) {
+ const key = headerNameToString(headers[i]);
+ let val = obj[key];
+ if (val !== void 0) {
+ if (!Object.hasOwn(obj, key)) {
+ const headersValue = typeof headers[i + 1] === "string" ? headers[i + 1] : Array.isArray(headers[i + 1]) ? headers[i + 1].map((x) => x.toString("latin1")) : headers[i + 1].toString("latin1");
+ if (key === "__proto__") {
+ Object.defineProperty(obj, key, {
+ value: headersValue,
+ enumerable: true,
+ configurable: true,
+ writable: true
+ });
+ } else {
+ obj[key] = headersValue;
+ }
+ } else {
+ if (typeof val === "string") {
+ val = [val];
+ obj[key] = val;
+ }
+ val.push(headers[i + 1].toString("latin1"));
+ }
+ } else {
+ const headersValue = typeof headers[i + 1] === "string" ? headers[i + 1] : Array.isArray(headers[i + 1]) ? headers[i + 1].map((x) => x.toString("latin1")) : headers[i + 1].toString("latin1");
+ obj[key] = headersValue;
+ }
+ }
+ return obj;
+ }
+ __name(parseHeaders, "parseHeaders");
+ function parseRawHeaders(headers) {
+ const headersLength = headers.length;
+ const ret = new Array(headersLength);
+ let key;
+ let val;
+ for (let n = 0; n < headersLength; n += 2) {
+ key = headers[n];
+ val = headers[n + 1];
+ typeof key !== "string" && (key = key.toString());
+ typeof val !== "string" && (val = val.toString("latin1"));
+ ret[n] = key;
+ ret[n + 1] = val;
+ }
+ return ret;
+ }
+ __name(parseRawHeaders, "parseRawHeaders");
+ function encodeRawHeaders(headers) {
+ if (!Array.isArray(headers)) {
+ throw new TypeError("expected headers to be an array");
+ }
+ return headers.map((x) => Buffer.from(x));
+ }
+ __name(encodeRawHeaders, "encodeRawHeaders");
+ function isBuffer(buffer) {
+ return buffer instanceof Uint8Array || Buffer.isBuffer(buffer);
+ }
+ __name(isBuffer, "isBuffer");
+ function assertRequestHandler(handler, method, upgrade) {
+ if (!handler || typeof handler !== "object") {
+ throw new InvalidArgumentError("handler must be an object");
+ }
+ if (typeof handler.onRequestStart === "function") {
+ return;
+ }
+ if (typeof handler.onConnect !== "function") {
+ throw new InvalidArgumentError("invalid onConnect method");
+ }
+ if (typeof handler.onError !== "function") {
+ throw new InvalidArgumentError("invalid onError method");
+ }
+ if (typeof handler.onBodySent !== "function" && handler.onBodySent !== void 0) {
+ throw new InvalidArgumentError("invalid onBodySent method");
+ }
+ if (upgrade || method === "CONNECT") {
+ if (typeof handler.onUpgrade !== "function") {
+ throw new InvalidArgumentError("invalid onUpgrade method");
+ }
+ } else {
+ if (typeof handler.onHeaders !== "function") {
+ throw new InvalidArgumentError("invalid onHeaders method");
+ }
+ if (typeof handler.onData !== "function") {
+ throw new InvalidArgumentError("invalid onData method");
+ }
+ if (typeof handler.onComplete !== "function") {
+ throw new InvalidArgumentError("invalid onComplete method");
+ }
+ }
+ }
+ __name(assertRequestHandler, "assertRequestHandler");
+ function isDisturbed(body) {
+ return !!(body && (stream.isDisturbed(body) || body[kBodyUsed]));
+ }
+ __name(isDisturbed, "isDisturbed");
+ function getSocketInfo(socket) {
+ return {
+ localAddress: socket.localAddress,
+ localPort: socket.localPort,
+ remoteAddress: socket.remoteAddress,
+ remotePort: socket.remotePort,
+ remoteFamily: socket.remoteFamily,
+ timeout: socket.timeout,
+ bytesWritten: socket.bytesWritten,
+ bytesRead: socket.bytesRead
+ };
+ }
+ __name(getSocketInfo, "getSocketInfo");
+ function ReadableStreamFrom2(iterable) {
+ let iterator;
+ return new ReadableStream(
+ {
+ start() {
+ iterator = iterable[Symbol.asyncIterator]();
+ },
+ pull(controller) {
+ return iterator.next().then(({ done, value }) => {
+ if (done) {
+ return queueMicrotask(() => {
+ controller.close();
+ controller.byobRequest?.respond(0);
+ });
+ } else {
+ const buf = Buffer.isBuffer(value) ? value : Buffer.from(value);
+ if (buf.byteLength) {
+ return controller.enqueue(new Uint8Array(buf));
+ } else {
+ return this.pull(controller);
+ }
+ }
+ });
+ },
+ cancel() {
+ return iterator.return();
+ },
+ type: "bytes"
+ }
+ );
+ }
+ __name(ReadableStreamFrom2, "ReadableStreamFrom");
+ function isFormDataLike(object2) {
+ return object2 && typeof object2 === "object" && typeof object2.append === "function" && typeof object2.delete === "function" && typeof object2.get === "function" && typeof object2.getAll === "function" && typeof object2.has === "function" && typeof object2.set === "function" && object2[Symbol.toStringTag] === "FormData";
+ }
+ __name(isFormDataLike, "isFormDataLike");
+ function addAbortListener(signal, listener) {
+ if ("addEventListener" in signal) {
+ signal.addEventListener("abort", listener, { once: true });
+ return () => signal.removeEventListener("abort", listener);
+ }
+ signal.once("abort", listener);
+ return () => signal.removeListener("abort", listener);
+ }
+ __name(addAbortListener, "addAbortListener");
+ var validTokenChars = new Uint8Array([
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ // 0-15
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ // 16-31
+ 0,
+ 1,
+ 0,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 0,
+ 0,
+ 1,
+ 1,
+ 0,
+ 1,
+ 1,
+ 0,
+ // 32-47 (!"#$%&'()*+,-./)
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ // 48-63 (0-9:;<=>?)
+ 0,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ // 64-79 (@A-O)
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 0,
+ 0,
+ 0,
+ 1,
+ 1,
+ // 80-95 (P-Z[\]^_)
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ // 96-111 (`a-o)
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 0,
+ // 112-127 (p-z{|}~)
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ // 128-143
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ // 144-159
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ // 160-175
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ // 176-191
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ // 192-207
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ // 208-223
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ // 224-239
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0
+ // 240-255
+ ]);
+ function isTokenCharCode(c) {
+ return validTokenChars[c] === 1;
+ }
+ __name(isTokenCharCode, "isTokenCharCode");
+ var tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/;
+ function isValidHTTPToken(characters) {
+ if (characters.length >= 12) return tokenRegExp.test(characters);
+ if (characters.length === 0) return false;
+ for (let i = 0; i < characters.length; i++) {
+ if (validTokenChars[characters.charCodeAt(i)] !== 1) {
+ return false;
+ }
+ }
+ return true;
+ }
+ __name(isValidHTTPToken, "isValidHTTPToken");
+ var headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
+ function isValidHeaderValue(characters) {
+ return !headerCharRegex.test(characters);
+ }
+ __name(isValidHeaderValue, "isValidHeaderValue");
+ var rangeHeaderRegex = /^bytes (\d+)-(\d+)\/(\d+)?$/;
+ function parseRangeHeader(range) {
+ if (range == null || range === "") return { start: 0, end: null, size: null };
+ const m = range ? range.match(rangeHeaderRegex) : null;
+ return m ? {
+ start: parseInt(m[1]),
+ end: m[2] ? parseInt(m[2]) : null,
+ size: m[3] ? parseInt(m[3]) : null
+ } : null;
+ }
+ __name(parseRangeHeader, "parseRangeHeader");
+ function addListener(obj, name, listener) {
+ const listeners = obj[kListeners] ??= [];
+ listeners.push([name, listener]);
+ obj.on(name, listener);
+ return obj;
+ }
+ __name(addListener, "addListener");
+ function removeAllListeners(obj) {
+ if (obj[kListeners] != null) {
+ for (const [name, listener] of obj[kListeners]) {
+ obj.removeListener(name, listener);
+ }
+ obj[kListeners] = null;
+ }
+ return obj;
+ }
+ __name(removeAllListeners, "removeAllListeners");
+ function errorRequest(client, request, err) {
+ try {
+ request.onError(err);
+ assert2(request.aborted);
+ } catch (err2) {
+ client.emit("error", err2);
+ }
+ }
+ __name(errorRequest, "errorRequest");
+ var setupConnectTimeout = process.platform === "win32" ? (socketWeakRef, opts) => {
+ if (!opts.timeout) {
+ return noop3;
+ }
+ let s1 = null;
+ let s2 = null;
+ const fastTimer = timers.setFastTimeout(() => {
+ s1 = setImmediate(() => {
+ s2 = setImmediate(() => onConnectTimeout(socketWeakRef.deref(), opts));
+ });
+ }, opts.timeout);
+ return () => {
+ timers.clearFastTimeout(fastTimer);
+ clearImmediate(s1);
+ clearImmediate(s2);
+ };
+ } : (socketWeakRef, opts) => {
+ if (!opts.timeout) {
+ return noop3;
+ }
+ let s1 = null;
+ const fastTimer = timers.setFastTimeout(() => {
+ s1 = setImmediate(() => {
+ onConnectTimeout(socketWeakRef.deref(), opts);
+ });
+ }, opts.timeout);
+ return () => {
+ timers.clearFastTimeout(fastTimer);
+ clearImmediate(s1);
+ };
+ };
+ function onConnectTimeout(socket, opts) {
+ if (socket == null) {
+ return;
+ }
+ let message = "Connect Timeout Error";
+ if (Array.isArray(socket.autoSelectFamilyAttemptedAddresses)) {
+ message += ` (attempted addresses: ${socket.autoSelectFamilyAttemptedAddresses.join(", ")},`;
+ } else {
+ message += ` (attempted address: ${opts.hostname}:${opts.port},`;
+ }
+ message += ` timeout: ${opts.timeout}ms)`;
+ destroy(socket, new ConnectTimeoutError(message));
+ }
+ __name(onConnectTimeout, "onConnectTimeout");
+ function getProtocolFromUrlString(urlString) {
+ if (urlString[0] === "h" && urlString[1] === "t" && urlString[2] === "t" && urlString[3] === "p") {
+ switch (urlString[4]) {
+ case ":":
+ return "http:";
+ case "s":
+ if (urlString[5] === ":") {
+ return "https:";
+ }
+ }
+ }
+ return urlString.slice(0, urlString.indexOf(":") + 1);
+ }
+ __name(getProtocolFromUrlString, "getProtocolFromUrlString");
+ var kEnumerableProperty = /* @__PURE__ */ Object.create(null);
+ kEnumerableProperty.enumerable = true;
+ var normalizedMethodRecordsBase = {
+ delete: "DELETE",
+ DELETE: "DELETE",
+ get: "GET",
+ GET: "GET",
+ head: "HEAD",
+ HEAD: "HEAD",
+ options: "OPTIONS",
+ OPTIONS: "OPTIONS",
+ post: "POST",
+ POST: "POST",
+ put: "PUT",
+ PUT: "PUT"
+ };
+ var normalizedMethodRecords = {
+ ...normalizedMethodRecordsBase,
+ patch: "patch",
+ PATCH: "PATCH"
+ };
+ Object.setPrototypeOf(normalizedMethodRecordsBase, null);
+ Object.setPrototypeOf(normalizedMethodRecords, null);
+ module2.exports = {
+ kEnumerableProperty,
+ isDisturbed,
+ isBlobLike: isBlobLike2,
+ parseOrigin,
+ parseURL,
+ getServerName,
+ isStream,
+ isIterable,
+ hasSafeIterator,
+ isAsyncIterable: isAsyncIterable2,
+ isDestroyed,
+ headerNameToString,
+ bufferToLowerCasedHeaderName,
+ addListener,
+ removeAllListeners,
+ errorRequest,
+ parseRawHeaders,
+ encodeRawHeaders,
+ parseHeaders,
+ parseKeepAliveTimeout,
+ destroy,
+ bodyLength,
+ deepClone,
+ ReadableStreamFrom: ReadableStreamFrom2,
+ isBuffer,
+ assertRequestHandler,
+ getSocketInfo,
+ isFormDataLike,
+ pathHasQueryOrFragment,
+ serializePathWithQuery,
+ addAbortListener,
+ isValidHTTPToken,
+ isValidHeaderValue,
+ isTokenCharCode,
+ parseRangeHeader,
+ normalizedMethodRecordsBase,
+ normalizedMethodRecords,
+ isValidPort,
+ isHttpOrHttpsPrefixed,
+ nodeMajor,
+ nodeMinor,
+ safeHTTPMethods: Object.freeze(["GET", "HEAD", "OPTIONS", "TRACE"]),
+ wrapRequestBody,
+ setupConnectTimeout,
+ getProtocolFromUrlString
+ };
+ }
+});
+
+// node_modules/undici/lib/util/stats.js
+var require_stats = __commonJS({
+ "node_modules/undici/lib/util/stats.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var {
+ kConnected,
+ kPending,
+ kRunning,
+ kSize,
+ kFree,
+ kQueued
+ } = require_symbols();
+ var ClientStats = class {
+ static {
+ __name(this, "ClientStats");
+ }
+ constructor(client) {
+ this.connected = client[kConnected];
+ this.pending = client[kPending];
+ this.running = client[kRunning];
+ this.size = client[kSize];
+ }
+ };
+ var PoolStats = class {
+ static {
+ __name(this, "PoolStats");
+ }
+ constructor(pool) {
+ this.connected = pool[kConnected];
+ this.free = pool[kFree];
+ this.pending = pool[kPending];
+ this.queued = pool[kQueued];
+ this.running = pool[kRunning];
+ this.size = pool[kSize];
+ }
+ };
+ module2.exports = { ClientStats, PoolStats };
+ }
+});
+
+// node_modules/undici/lib/core/diagnostics.js
+var require_diagnostics = __commonJS({
+ "node_modules/undici/lib/core/diagnostics.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var diagnosticsChannel = __require("node:diagnostics_channel");
+ var util = __require("node:util");
+ var undiciDebugLog = util.debuglog("undici");
+ var fetchDebuglog = util.debuglog("fetch");
+ var websocketDebuglog = util.debuglog("websocket");
+ var channels = {
+ // Client
+ beforeConnect: diagnosticsChannel.channel("undici:client:beforeConnect"),
+ connected: diagnosticsChannel.channel("undici:client:connected"),
+ connectError: diagnosticsChannel.channel("undici:client:connectError"),
+ sendHeaders: diagnosticsChannel.channel("undici:client:sendHeaders"),
+ // Request
+ create: diagnosticsChannel.channel("undici:request:create"),
+ bodySent: diagnosticsChannel.channel("undici:request:bodySent"),
+ bodyChunkSent: diagnosticsChannel.channel("undici:request:bodyChunkSent"),
+ bodyChunkReceived: diagnosticsChannel.channel("undici:request:bodyChunkReceived"),
+ headers: diagnosticsChannel.channel("undici:request:headers"),
+ trailers: diagnosticsChannel.channel("undici:request:trailers"),
+ error: diagnosticsChannel.channel("undici:request:error"),
+ // WebSocket
+ open: diagnosticsChannel.channel("undici:websocket:open"),
+ close: diagnosticsChannel.channel("undici:websocket:close"),
+ socketError: diagnosticsChannel.channel("undici:websocket:socket_error"),
+ ping: diagnosticsChannel.channel("undici:websocket:ping"),
+ pong: diagnosticsChannel.channel("undici:websocket:pong"),
+ // ProxyAgent
+ proxyConnected: diagnosticsChannel.channel("undici:proxy:connected")
+ };
+ var isTrackingClientEvents = false;
+ function trackClientEvents(debugLog = undiciDebugLog) {
+ if (isTrackingClientEvents) {
+ return;
+ }
+ if (channels.beforeConnect.hasSubscribers || channels.connected.hasSubscribers || channels.connectError.hasSubscribers || channels.sendHeaders.hasSubscribers) {
+ isTrackingClientEvents = true;
+ return;
+ }
+ isTrackingClientEvents = true;
+ diagnosticsChannel.subscribe(
+ "undici:client:beforeConnect",
+ (evt) => {
+ const {
+ connectParams: { version: version2, protocol, port, host }
+ } = evt;
+ debugLog(
+ "connecting to %s%s using %s%s",
+ host,
+ port ? `:${port}` : "",
+ protocol,
+ version2
+ );
+ }
+ );
+ diagnosticsChannel.subscribe(
+ "undici:client:connected",
+ (evt) => {
+ const {
+ connectParams: { version: version2, protocol, port, host }
+ } = evt;
+ debugLog(
+ "connected to %s%s using %s%s",
+ host,
+ port ? `:${port}` : "",
+ protocol,
+ version2
+ );
+ }
+ );
+ diagnosticsChannel.subscribe(
+ "undici:client:connectError",
+ (evt) => {
+ const {
+ connectParams: { version: version2, protocol, port, host },
+ error: error51
+ } = evt;
+ debugLog(
+ "connection to %s%s using %s%s errored - %s",
+ host,
+ port ? `:${port}` : "",
+ protocol,
+ version2,
+ error51.message
+ );
+ }
+ );
+ diagnosticsChannel.subscribe(
+ "undici:client:sendHeaders",
+ (evt) => {
+ const {
+ request: { method, path: path27, origin }
+ } = evt;
+ debugLog("sending request to %s %s%s", method, origin, path27);
+ }
+ );
+ }
+ __name(trackClientEvents, "trackClientEvents");
+ var isTrackingRequestEvents = false;
+ function trackRequestEvents(debugLog = undiciDebugLog) {
+ if (isTrackingRequestEvents) {
+ return;
+ }
+ if (channels.headers.hasSubscribers || channels.trailers.hasSubscribers || channels.error.hasSubscribers) {
+ isTrackingRequestEvents = true;
+ return;
+ }
+ isTrackingRequestEvents = true;
+ diagnosticsChannel.subscribe(
+ "undici:request:headers",
+ (evt) => {
+ const {
+ request: { method, path: path27, origin },
+ response: { statusCode }
+ } = evt;
+ debugLog(
+ "received response to %s %s%s - HTTP %d",
+ method,
+ origin,
+ path27,
+ statusCode
+ );
+ }
+ );
+ diagnosticsChannel.subscribe(
+ "undici:request:trailers",
+ (evt) => {
+ const {
+ request: { method, path: path27, origin }
+ } = evt;
+ debugLog("trailers received from %s %s%s", method, origin, path27);
+ }
+ );
+ diagnosticsChannel.subscribe(
+ "undici:request:error",
+ (evt) => {
+ const {
+ request: { method, path: path27, origin },
+ error: error51
+ } = evt;
+ debugLog(
+ "request to %s %s%s errored - %s",
+ method,
+ origin,
+ path27,
+ error51.message
+ );
+ }
+ );
+ }
+ __name(trackRequestEvents, "trackRequestEvents");
+ var isTrackingWebSocketEvents = false;
+ function trackWebSocketEvents(debugLog = websocketDebuglog) {
+ if (isTrackingWebSocketEvents) {
+ return;
+ }
+ if (channels.open.hasSubscribers || channels.close.hasSubscribers || channels.socketError.hasSubscribers || channels.ping.hasSubscribers || channels.pong.hasSubscribers) {
+ isTrackingWebSocketEvents = true;
+ return;
+ }
+ isTrackingWebSocketEvents = true;
+ diagnosticsChannel.subscribe(
+ "undici:websocket:open",
+ (evt) => {
+ if (evt.address != null) {
+ const { address, port } = evt.address;
+ debugLog("connection opened %s%s", address, port ? `:${port}` : "");
+ } else {
+ debugLog("connection opened");
+ }
+ }
+ );
+ diagnosticsChannel.subscribe(
+ "undici:websocket:close",
+ (evt) => {
+ const { websocket, code, reason } = evt;
+ debugLog(
+ "closed connection to %s - %s %s",
+ websocket.url,
+ code,
+ reason
+ );
+ }
+ );
+ diagnosticsChannel.subscribe(
+ "undici:websocket:socket_error",
+ (err) => {
+ debugLog("connection errored - %s", err.message);
+ }
+ );
+ diagnosticsChannel.subscribe(
+ "undici:websocket:ping",
+ (evt) => {
+ debugLog("ping received");
+ }
+ );
+ diagnosticsChannel.subscribe(
+ "undici:websocket:pong",
+ (evt) => {
+ debugLog("pong received");
+ }
+ );
+ }
+ __name(trackWebSocketEvents, "trackWebSocketEvents");
+ if (undiciDebugLog.enabled || fetchDebuglog.enabled) {
+ trackClientEvents(fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog);
+ trackRequestEvents(fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog);
+ }
+ if (websocketDebuglog.enabled) {
+ trackClientEvents(undiciDebugLog.enabled ? undiciDebugLog : websocketDebuglog);
+ trackWebSocketEvents(websocketDebuglog);
+ }
+ module2.exports = {
+ channels
+ };
+ }
+});
+
+// node_modules/undici/lib/core/request.js
+var require_request = __commonJS({
+ "node_modules/undici/lib/core/request.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var {
+ InvalidArgumentError,
+ NotSupportedError
+ } = require_errors();
+ var assert2 = __require("node:assert");
+ var {
+ isValidHTTPToken,
+ isValidHeaderValue,
+ isStream,
+ destroy,
+ isBuffer,
+ isFormDataLike,
+ isIterable,
+ hasSafeIterator,
+ isBlobLike: isBlobLike2,
+ serializePathWithQuery,
+ assertRequestHandler,
+ getServerName,
+ normalizedMethodRecords,
+ getProtocolFromUrlString
+ } = require_util();
+ var { channels } = require_diagnostics();
+ var { headerNameLowerCasedRecord } = require_constants2();
+ var invalidPathRegex = /[^\u0021-\u00ff]/;
+ function isValidContentLengthHeaderValue(val) {
+ if (typeof val !== "string" || val.length === 0) {
+ return false;
+ }
+ for (let i = 0; i < val.length; i++) {
+ const charCode = val.charCodeAt(i);
+ if (charCode < 48 || charCode > 57) {
+ return false;
+ }
+ }
+ return true;
+ }
+ __name(isValidContentLengthHeaderValue, "isValidContentLengthHeaderValue");
+ var kHandler = /* @__PURE__ */ Symbol("handler");
+ var Request = class {
+ static {
+ __name(this, "Request");
+ }
+ constructor(origin, {
+ path: path27,
+ method,
+ body,
+ headers,
+ query,
+ idempotent,
+ blocking,
+ upgrade,
+ headersTimeout,
+ bodyTimeout,
+ reset: reset2,
+ expectContinue,
+ servername,
+ throwOnError,
+ maxRedirections,
+ typeOfService
+ }, handler) {
+ if (typeof path27 !== "string") {
+ throw new InvalidArgumentError("path must be a string");
+ } else if (path27[0] !== "/" && !(path27.startsWith("http://") || path27.startsWith("https://")) && method !== "CONNECT") {
+ throw new InvalidArgumentError("path must be an absolute URL or start with a slash");
+ } else if (invalidPathRegex.test(path27)) {
+ throw new InvalidArgumentError("invalid request path");
+ }
+ if (typeof method !== "string") {
+ throw new InvalidArgumentError("method must be a string");
+ } else if (normalizedMethodRecords[method] === void 0 && !isValidHTTPToken(method)) {
+ throw new InvalidArgumentError("invalid request method");
+ }
+ if (upgrade && typeof upgrade !== "string") {
+ throw new InvalidArgumentError("upgrade must be a string");
+ }
+ if (upgrade && !isValidHeaderValue(upgrade)) {
+ throw new InvalidArgumentError("invalid upgrade header");
+ }
+ if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) {
+ throw new InvalidArgumentError("invalid headersTimeout");
+ }
+ if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) {
+ throw new InvalidArgumentError("invalid bodyTimeout");
+ }
+ if (reset2 != null && typeof reset2 !== "boolean") {
+ throw new InvalidArgumentError("invalid reset");
+ }
+ if (expectContinue != null && typeof expectContinue !== "boolean") {
+ throw new InvalidArgumentError("invalid expectContinue");
+ }
+ if (throwOnError != null) {
+ throw new InvalidArgumentError("invalid throwOnError");
+ }
+ if (maxRedirections != null && maxRedirections !== 0) {
+ throw new InvalidArgumentError("maxRedirections is not supported, use the redirect interceptor");
+ }
+ if (typeOfService != null && (!Number.isInteger(typeOfService) || typeOfService < 0 || typeOfService > 255)) {
+ throw new InvalidArgumentError("typeOfService must be an integer between 0 and 255");
+ }
+ this.headersTimeout = headersTimeout;
+ this.bodyTimeout = bodyTimeout;
+ this.method = method;
+ this.typeOfService = typeOfService ?? 0;
+ this.abort = null;
+ if (body == null) {
+ this.body = null;
+ } else if (isStream(body)) {
+ this.body = body;
+ const rState = this.body._readableState;
+ if (!rState || !rState.autoDestroy) {
+ this.endHandler = /* @__PURE__ */ __name(function autoDestroy() {
+ destroy(this);
+ }, "autoDestroy");
+ this.body.on("end", this.endHandler);
+ }
+ this.errorHandler = (err) => {
+ if (this.abort) {
+ this.abort(err);
+ } else {
+ this.error = err;
+ }
+ };
+ this.body.on("error", this.errorHandler);
+ } else if (isBuffer(body)) {
+ this.body = body.byteLength ? body : null;
+ } else if (ArrayBuffer.isView(body)) {
+ this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null;
+ } else if (body instanceof ArrayBuffer) {
+ this.body = body.byteLength ? Buffer.from(body) : null;
+ } else if (typeof body === "string") {
+ this.body = body.length ? Buffer.from(body) : null;
+ } else if (isFormDataLike(body) || isIterable(body) || isBlobLike2(body)) {
+ this.body = body;
+ } else {
+ throw new InvalidArgumentError("body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable");
+ }
+ this.completed = false;
+ this.aborted = false;
+ this.upgrade = upgrade || null;
+ this.path = query ? serializePathWithQuery(path27, query) : path27;
+ this.origin = origin;
+ this.protocol = getProtocolFromUrlString(origin);
+ this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent;
+ this.blocking = blocking ?? this.method !== "HEAD";
+ this.reset = reset2 == null ? null : reset2;
+ this.host = null;
+ this.contentLength = null;
+ this.contentType = null;
+ this.headers = [];
+ this.expectContinue = expectContinue != null ? expectContinue : false;
+ if (Array.isArray(headers)) {
+ if (headers.length % 2 !== 0) {
+ throw new InvalidArgumentError("headers array must be even");
+ }
+ for (let i = 0; i < headers.length; i += 2) {
+ processHeader(this, headers[i], headers[i + 1]);
+ }
+ } else if (headers && typeof headers === "object") {
+ if (hasSafeIterator(headers)) {
+ for (const header of headers) {
+ if (!Array.isArray(header) || header.length !== 2) {
+ throw new InvalidArgumentError("headers must be in key-value pair format");
+ }
+ processHeader(this, header[0], header[1]);
+ }
+ } else {
+ const keys = Object.keys(headers);
+ for (let i = 0; i < keys.length; ++i) {
+ processHeader(this, keys[i], headers[keys[i]]);
+ }
+ }
+ } else if (headers != null) {
+ throw new InvalidArgumentError("headers must be an object or an array");
+ }
+ assertRequestHandler(handler, method, upgrade);
+ this.servername = servername || getServerName(this.host) || null;
+ this[kHandler] = handler;
+ if (channels.create.hasSubscribers) {
+ channels.create.publish({ request: this });
+ }
+ }
+ onBodySent(chunk) {
+ if (channels.bodyChunkSent.hasSubscribers) {
+ channels.bodyChunkSent.publish({ request: this, chunk });
+ }
+ if (this[kHandler].onBodySent) {
+ try {
+ return this[kHandler].onBodySent(chunk);
+ } catch (err) {
+ this.abort(err);
+ }
+ }
+ }
+ onRequestSent() {
+ if (channels.bodySent.hasSubscribers) {
+ channels.bodySent.publish({ request: this });
+ }
+ if (this[kHandler].onRequestSent) {
+ try {
+ return this[kHandler].onRequestSent();
+ } catch (err) {
+ this.abort(err);
+ }
+ }
+ }
+ onConnect(abort) {
+ assert2(!this.aborted);
+ assert2(!this.completed);
+ if (this.error) {
+ abort(this.error);
+ } else {
+ this.abort = abort;
+ return this[kHandler].onConnect(abort);
+ }
+ }
+ onResponseStarted() {
+ return this[kHandler].onResponseStarted?.();
+ }
+ onHeaders(statusCode, headers, resume, statusText) {
+ assert2(!this.aborted);
+ assert2(!this.completed);
+ if (channels.headers.hasSubscribers) {
+ channels.headers.publish({ request: this, response: { statusCode, headers, statusText } });
+ }
+ try {
+ return this[kHandler].onHeaders(statusCode, headers, resume, statusText);
+ } catch (err) {
+ this.abort(err);
+ }
+ }
+ onData(chunk) {
+ assert2(!this.aborted);
+ assert2(!this.completed);
+ if (channels.bodyChunkReceived.hasSubscribers) {
+ channels.bodyChunkReceived.publish({ request: this, chunk });
+ }
+ try {
+ return this[kHandler].onData(chunk);
+ } catch (err) {
+ this.abort(err);
+ return false;
+ }
+ }
+ onUpgrade(statusCode, headers, socket) {
+ assert2(!this.aborted);
+ assert2(!this.completed);
+ return this[kHandler].onUpgrade(statusCode, headers, socket);
+ }
+ onComplete(trailers) {
+ this.onFinally();
+ assert2(!this.aborted);
+ assert2(!this.completed);
+ this.completed = true;
+ if (channels.trailers.hasSubscribers) {
+ channels.trailers.publish({ request: this, trailers });
+ }
+ try {
+ return this[kHandler].onComplete(trailers);
+ } catch (err) {
+ this.onError(err);
+ }
+ }
+ onError(error51) {
+ this.onFinally();
+ if (channels.error.hasSubscribers) {
+ channels.error.publish({ request: this, error: error51 });
+ }
+ if (this.aborted) {
+ return;
+ }
+ this.aborted = true;
+ return this[kHandler].onError(error51);
+ }
+ onFinally() {
+ if (this.errorHandler) {
+ this.body.off("error", this.errorHandler);
+ this.errorHandler = null;
+ }
+ if (this.endHandler) {
+ this.body.off("end", this.endHandler);
+ this.endHandler = null;
+ }
+ }
+ addHeader(key, value) {
+ processHeader(this, key, value);
+ return this;
+ }
+ };
+ function processHeader(request, key, val) {
+ if (val && (typeof val === "object" && !Array.isArray(val))) {
+ throw new InvalidArgumentError(`invalid ${key} header`);
+ } else if (val === void 0) {
+ return;
+ }
+ let headerName = headerNameLowerCasedRecord[key];
+ if (headerName === void 0) {
+ headerName = key.toLowerCase();
+ if (headerNameLowerCasedRecord[headerName] === void 0 && !isValidHTTPToken(headerName)) {
+ throw new InvalidArgumentError("invalid header key");
+ }
+ }
+ if (Array.isArray(val)) {
+ const arr = [];
+ for (let i = 0; i < val.length; i++) {
+ if (typeof val[i] === "string") {
+ if (!isValidHeaderValue(val[i])) {
+ throw new InvalidArgumentError(`invalid ${key} header`);
+ }
+ arr.push(val[i]);
+ } else if (val[i] === null) {
+ arr.push("");
+ } else if (typeof val[i] === "object") {
+ throw new InvalidArgumentError(`invalid ${key} header`);
+ } else {
+ arr.push(`${val[i]}`);
+ }
+ }
+ val = arr;
+ } else if (typeof val === "string") {
+ if (!isValidHeaderValue(val)) {
+ throw new InvalidArgumentError(`invalid ${key} header`);
+ }
+ } else if (val === null) {
+ val = "";
+ } else {
+ val = `${val}`;
+ }
+ if (headerName === "host") {
+ if (request.host !== null) {
+ throw new InvalidArgumentError("duplicate host header");
+ }
+ if (typeof val !== "string") {
+ throw new InvalidArgumentError("invalid host header");
+ }
+ request.host = val;
+ } else if (headerName === "content-length") {
+ if (request.contentLength !== null) {
+ throw new InvalidArgumentError("duplicate content-length header");
+ }
+ if (!isValidContentLengthHeaderValue(val)) {
+ throw new InvalidArgumentError("invalid content-length header");
+ }
+ request.contentLength = parseInt(val, 10);
+ } else if (request.contentType === null && headerName === "content-type") {
+ request.contentType = val;
+ request.headers.push(key, val);
+ } else if (headerName === "transfer-encoding" || headerName === "keep-alive" || headerName === "upgrade") {
+ throw new InvalidArgumentError(`invalid ${headerName} header`);
+ } else if (headerName === "connection") {
+ const value = typeof val === "string" ? val : null;
+ if (value === null) {
+ throw new InvalidArgumentError("invalid connection header");
+ }
+ for (const token of value.toLowerCase().split(",")) {
+ const trimmed = token.trim();
+ if (!isValidHTTPToken(trimmed)) {
+ throw new InvalidArgumentError("invalid connection header");
+ }
+ if (trimmed === "close") {
+ request.reset = true;
+ }
+ }
+ } else if (headerName === "expect") {
+ throw new NotSupportedError("expect header not supported");
+ } else {
+ request.headers.push(key, val);
+ }
+ }
+ __name(processHeader, "processHeader");
+ module2.exports = Request;
+ }
+});
+
+// node_modules/undici/lib/handler/wrap-handler.js
+var require_wrap_handler = __commonJS({
+ "node_modules/undici/lib/handler/wrap-handler.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { InvalidArgumentError } = require_errors();
+ module2.exports = class WrapHandler {
+ static {
+ __name(this, "WrapHandler");
+ }
+ #handler;
+ constructor(handler) {
+ this.#handler = handler;
+ }
+ static wrap(handler) {
+ return handler.onRequestStart ? handler : new WrapHandler(handler);
+ }
+ // Unwrap Interface
+ onConnect(abort, context) {
+ return this.#handler.onConnect?.(abort, context);
+ }
+ onResponseStarted() {
+ return this.#handler.onResponseStarted?.();
+ }
+ onHeaders(statusCode, rawHeaders, resume, statusMessage) {
+ return this.#handler.onHeaders?.(statusCode, rawHeaders, resume, statusMessage);
+ }
+ onUpgrade(statusCode, rawHeaders, socket) {
+ return this.#handler.onUpgrade?.(statusCode, rawHeaders, socket);
+ }
+ onData(data) {
+ return this.#handler.onData?.(data);
+ }
+ onComplete(trailers) {
+ return this.#handler.onComplete?.(trailers);
+ }
+ onError(err) {
+ if (!this.#handler.onError) {
+ throw err;
+ }
+ return this.#handler.onError?.(err);
+ }
+ // Wrap Interface
+ onRequestStart(controller, context) {
+ this.#handler.onConnect?.((reason) => controller.abort(reason), context);
+ }
+ onRequestUpgrade(controller, statusCode, headers, socket) {
+ const rawHeaders = [];
+ for (const [key, val] of Object.entries(headers)) {
+ rawHeaders.push(Buffer.from(key, "latin1"), toRawHeaderValue(val));
+ }
+ this.#handler.onUpgrade?.(statusCode, rawHeaders, socket);
+ }
+ onResponseStart(controller, statusCode, headers, statusMessage) {
+ const rawHeaders = [];
+ for (const [key, val] of Object.entries(headers)) {
+ rawHeaders.push(Buffer.from(key, "latin1"), toRawHeaderValue(val));
+ }
+ if (this.#handler.onHeaders?.(statusCode, rawHeaders, () => controller.resume(), statusMessage) === false) {
+ controller.pause();
+ }
+ }
+ onResponseData(controller, data) {
+ if (this.#handler.onData?.(data) === false) {
+ controller.pause();
+ }
+ }
+ onResponseEnd(controller, trailers) {
+ const rawTrailers = [];
+ for (const [key, val] of Object.entries(trailers)) {
+ rawTrailers.push(Buffer.from(key, "latin1"), toRawHeaderValue(val));
+ }
+ this.#handler.onComplete?.(rawTrailers);
+ }
+ onResponseError(controller, err) {
+ if (!this.#handler.onError) {
+ throw new InvalidArgumentError("invalid onError method");
+ }
+ this.#handler.onError?.(err);
+ }
+ };
+ function toRawHeaderValue(value) {
+ return Array.isArray(value) ? value.map((item) => Buffer.from(item, "latin1")) : Buffer.from(value, "latin1");
+ }
+ __name(toRawHeaderValue, "toRawHeaderValue");
+ }
+});
+
+// node_modules/undici/lib/dispatcher/dispatcher.js
+var require_dispatcher = __commonJS({
+ "node_modules/undici/lib/dispatcher/dispatcher.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var EventEmitter3 = __require("node:events");
+ var WrapHandler = require_wrap_handler();
+ var wrapInterceptor = /* @__PURE__ */ __name((dispatch) => (opts, handler) => dispatch(opts, WrapHandler.wrap(handler)), "wrapInterceptor");
+ var Dispatcher = class extends EventEmitter3 {
+ static {
+ __name(this, "Dispatcher");
+ }
+ dispatch() {
+ throw new Error("not implemented");
+ }
+ close() {
+ throw new Error("not implemented");
+ }
+ destroy() {
+ throw new Error("not implemented");
+ }
+ compose(...args) {
+ const interceptors = Array.isArray(args[0]) ? args[0] : args;
+ let dispatch = this.dispatch.bind(this);
+ for (const interceptor of interceptors) {
+ if (interceptor == null) {
+ continue;
+ }
+ if (typeof interceptor !== "function") {
+ throw new TypeError(`invalid interceptor, expected function received ${typeof interceptor}`);
+ }
+ dispatch = interceptor(dispatch);
+ dispatch = wrapInterceptor(dispatch);
+ if (dispatch == null || typeof dispatch !== "function" || dispatch.length !== 2) {
+ throw new TypeError("invalid interceptor");
+ }
+ }
+ return new Proxy(this, {
+ get: /* @__PURE__ */ __name((target, key) => key === "dispatch" ? dispatch : target[key], "get")
+ });
+ }
+ };
+ module2.exports = Dispatcher;
+ }
+});
+
+// node_modules/undici/lib/handler/unwrap-handler.js
+var require_unwrap_handler = __commonJS({
+ "node_modules/undici/lib/handler/unwrap-handler.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { parseHeaders } = require_util();
+ var { InvalidArgumentError } = require_errors();
+ var kResume = /* @__PURE__ */ Symbol("resume");
+ var UnwrapController = class {
+ static {
+ __name(this, "UnwrapController");
+ }
+ #paused = false;
+ #reason = null;
+ #aborted = false;
+ #abort;
+ [kResume] = null;
+ rawHeaders = null;
+ rawTrailers = null;
+ constructor(abort) {
+ this.#abort = abort;
+ }
+ pause() {
+ this.#paused = true;
+ }
+ resume() {
+ if (this.#paused) {
+ this.#paused = false;
+ this[kResume]?.();
+ }
+ }
+ abort(reason) {
+ if (!this.#aborted) {
+ this.#aborted = true;
+ this.#reason = reason;
+ this.#abort(reason);
+ }
+ }
+ get aborted() {
+ return this.#aborted;
+ }
+ get reason() {
+ return this.#reason;
+ }
+ get paused() {
+ return this.#paused;
+ }
+ };
+ module2.exports = class UnwrapHandler {
+ static {
+ __name(this, "UnwrapHandler");
+ }
+ #handler;
+ #controller;
+ constructor(handler) {
+ this.#handler = handler;
+ }
+ static unwrap(handler) {
+ return !handler.onRequestStart ? handler : new UnwrapHandler(handler);
+ }
+ onConnect(abort, context) {
+ this.#controller = new UnwrapController(abort);
+ this.#handler.onRequestStart?.(this.#controller, context);
+ }
+ onResponseStarted() {
+ return this.#handler.onResponseStarted?.();
+ }
+ onUpgrade(statusCode, rawHeaders, socket) {
+ this.#controller.rawHeaders = rawHeaders;
+ this.#handler.onRequestUpgrade?.(this.#controller, statusCode, parseHeaders(rawHeaders), socket);
+ }
+ onHeaders(statusCode, rawHeaders, resume, statusMessage) {
+ this.#controller[kResume] = resume;
+ this.#controller.rawHeaders = rawHeaders;
+ this.#handler.onResponseStart?.(this.#controller, statusCode, parseHeaders(rawHeaders), statusMessage);
+ return !this.#controller.paused;
+ }
+ onData(data) {
+ this.#handler.onResponseData?.(this.#controller, data);
+ return !this.#controller.paused;
+ }
+ onComplete(rawTrailers) {
+ this.#controller.rawTrailers = rawTrailers;
+ this.#handler.onResponseEnd?.(this.#controller, parseHeaders(rawTrailers));
+ }
+ onError(err) {
+ if (!this.#handler.onResponseError) {
+ throw new InvalidArgumentError("invalid onError method");
+ }
+ this.#handler.onResponseError?.(this.#controller, err);
+ }
+ };
+ }
+});
+
+// node_modules/undici/lib/dispatcher/dispatcher-base.js
+var require_dispatcher_base = __commonJS({
+ "node_modules/undici/lib/dispatcher/dispatcher-base.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var Dispatcher = require_dispatcher();
+ var UnwrapHandler = require_unwrap_handler();
+ var {
+ ClientDestroyedError,
+ ClientClosedError,
+ InvalidArgumentError
+ } = require_errors();
+ var { kDestroy, kClose, kClosed, kDestroyed, kDispatch } = require_symbols();
+ var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed");
+ var kOnClosed = /* @__PURE__ */ Symbol("onClosed");
+ var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions");
+ var DispatcherBase = class extends Dispatcher {
+ static {
+ __name(this, "DispatcherBase");
+ }
+ /** @type {boolean} */
+ [kDestroyed] = false;
+ /** @type {Array|null} */
+ [kOnClosed] = null;
+ /**
+ * @param {import('../../types/dispatcher').DispatcherOptions} [opts]
+ */
+ constructor(opts) {
+ super();
+ this[kWebSocketOptions] = opts?.webSocket ?? {};
+ }
+ /**
+ * @returns {import('../../types/dispatcher').WebSocketOptions}
+ */
+ get webSocketOptions() {
+ return {
+ maxFragments: this[kWebSocketOptions].maxFragments ?? 131072,
+ maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024
+ // 128 MB default
+ };
+ }
+ /** @returns {boolean} */
+ get destroyed() {
+ return this[kDestroyed];
+ }
+ /** @returns {boolean} */
+ get closed() {
+ return this[kClosed];
+ }
+ close(callback) {
+ if (callback === void 0) {
+ return new Promise((resolve16, reject) => {
+ this.close((err, data) => {
+ return err ? reject(err) : resolve16(data);
+ });
+ });
+ }
+ if (typeof callback !== "function") {
+ throw new InvalidArgumentError("invalid callback");
+ }
+ if (this[kDestroyed]) {
+ const err = new ClientDestroyedError();
+ queueMicrotask(() => callback(err, null));
+ return;
+ }
+ if (this[kClosed]) {
+ if (this[kOnClosed]) {
+ this[kOnClosed].push(callback);
+ } else {
+ queueMicrotask(() => callback(null, null));
+ }
+ return;
+ }
+ this[kClosed] = true;
+ this[kOnClosed] ??= [];
+ this[kOnClosed].push(callback);
+ const onClosed = /* @__PURE__ */ __name(() => {
+ const callbacks = this[kOnClosed];
+ this[kOnClosed] = null;
+ for (let i = 0; i < callbacks.length; i++) {
+ callbacks[i](null, null);
+ }
+ }, "onClosed");
+ this[kClose]().then(() => this.destroy()).then(() => queueMicrotask(onClosed));
+ }
+ destroy(err, callback) {
+ if (typeof err === "function") {
+ callback = err;
+ err = null;
+ }
+ if (callback === void 0) {
+ return new Promise((resolve16, reject) => {
+ this.destroy(err, (err2, data) => {
+ return err2 ? reject(err2) : resolve16(data);
+ });
+ });
+ }
+ if (typeof callback !== "function") {
+ throw new InvalidArgumentError("invalid callback");
+ }
+ if (this[kDestroyed]) {
+ if (this[kOnDestroyed]) {
+ this[kOnDestroyed].push(callback);
+ } else {
+ queueMicrotask(() => callback(null, null));
+ }
+ return;
+ }
+ if (!err) {
+ err = new ClientDestroyedError();
+ }
+ this[kDestroyed] = true;
+ this[kOnDestroyed] ??= [];
+ this[kOnDestroyed].push(callback);
+ const onDestroyed = /* @__PURE__ */ __name(() => {
+ const callbacks = this[kOnDestroyed];
+ this[kOnDestroyed] = null;
+ for (let i = 0; i < callbacks.length; i++) {
+ callbacks[i](null, null);
+ }
+ }, "onDestroyed");
+ this[kDestroy](err).then(() => queueMicrotask(onDestroyed));
+ }
+ dispatch(opts, handler) {
+ if (!handler || typeof handler !== "object") {
+ throw new InvalidArgumentError("handler must be an object");
+ }
+ handler = UnwrapHandler.unwrap(handler);
+ try {
+ if (!opts || typeof opts !== "object") {
+ throw new InvalidArgumentError("opts must be an object.");
+ }
+ if (this[kDestroyed] || this[kOnDestroyed]) {
+ throw new ClientDestroyedError();
+ }
+ if (this[kClosed]) {
+ throw new ClientClosedError();
+ }
+ return this[kDispatch](opts, handler);
+ } catch (err) {
+ if (typeof handler.onError !== "function") {
+ throw err;
+ }
+ handler.onError(err);
+ return false;
+ }
+ }
+ };
+ module2.exports = DispatcherBase;
+ }
+});
+
+// node_modules/undici/lib/core/connect.js
+var require_connect = __commonJS({
+ "node_modules/undici/lib/core/connect.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var net = __require("node:net");
+ var assert2 = __require("node:assert");
+ var util = require_util();
+ var { InvalidArgumentError } = require_errors();
+ var tls;
+ var SessionCache = class WeakSessionCache {
+ static {
+ __name(this, "WeakSessionCache");
+ }
+ constructor(maxCachedSessions) {
+ this._maxCachedSessions = maxCachedSessions;
+ this._sessionCache = /* @__PURE__ */ new Map();
+ this._sessionRegistry = new FinalizationRegistry((key) => {
+ if (this._sessionCache.size < this._maxCachedSessions) {
+ return;
+ }
+ const ref = this._sessionCache.get(key);
+ if (ref !== void 0 && ref.deref() === void 0) {
+ this._sessionCache.delete(key);
+ }
+ });
+ }
+ get(sessionKey) {
+ const ref = this._sessionCache.get(sessionKey);
+ return ref ? ref.deref() : null;
+ }
+ set(sessionKey, session) {
+ if (this._maxCachedSessions === 0) {
+ return;
+ }
+ if (this._sessionCache.has(sessionKey)) {
+ this._sessionCache.delete(sessionKey);
+ } else if (this._sessionCache.size >= this._maxCachedSessions) {
+ for (const [key, ref] of this._sessionCache) {
+ if (ref.deref() === void 0) {
+ this._sessionCache.delete(key);
+ return;
+ }
+ }
+ const oldest = this._sessionCache.keys().next();
+ if (!oldest.done) {
+ this._sessionCache.delete(oldest.value);
+ }
+ }
+ this._sessionCache.set(sessionKey, new WeakRef(session));
+ this._sessionRegistry.register(session, sessionKey);
+ }
+ };
+ function buildConnector({ allowH2, useH2c, maxCachedSessions, socketPath, timeout, session: customSession, ...opts }) {
+ if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) {
+ throw new InvalidArgumentError("maxCachedSessions must be a positive integer or zero");
+ }
+ const options2 = { path: socketPath, ...opts };
+ const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions);
+ timeout = timeout == null ? 1e4 : timeout;
+ allowH2 = allowH2 != null ? allowH2 : false;
+ return /* @__PURE__ */ __name(function connect({ hostname: hostname4, host, protocol, port, servername, localAddress, httpSocket }, callback) {
+ let socket;
+ if (protocol === "https:") {
+ if (!tls) {
+ tls = __require("node:tls");
+ }
+ servername = servername || options2.servername || util.getServerName(host) || null;
+ const sessionKey = servername || hostname4;
+ assert2(sessionKey);
+ const session = customSession || sessionCache.get(sessionKey) || null;
+ port = port || 443;
+ socket = tls.connect({
+ highWaterMark: 16384,
+ // TLS in node can't have bigger HWM anyway...
+ ...options2,
+ servername,
+ session,
+ localAddress,
+ ALPNProtocols: allowH2 ? ["http/1.1", "h2"] : ["http/1.1"],
+ socket: httpSocket,
+ // upgrade socket connection
+ port,
+ host: hostname4
+ });
+ socket.on("session", function(session2) {
+ sessionCache.set(sessionKey, session2);
+ });
+ } else {
+ assert2(!httpSocket, "httpSocket can only be sent on TLS update");
+ port = port || 80;
+ socket = net.connect({
+ highWaterMark: 64 * 1024,
+ // Same as nodejs fs streams.
+ ...options2,
+ localAddress,
+ port,
+ host: hostname4
+ });
+ if (useH2c === true) {
+ socket.alpnProtocol = "h2";
+ }
+ }
+ if (options2.keepAlive == null || options2.keepAlive) {
+ const keepAliveInitialDelay = options2.keepAliveInitialDelay === void 0 ? 6e4 : options2.keepAliveInitialDelay;
+ socket.setKeepAlive(true, keepAliveInitialDelay);
+ }
+ const clearConnectTimeout = util.setupConnectTimeout(new WeakRef(socket), { timeout, hostname: hostname4, port });
+ socket.setNoDelay(true).once(protocol === "https:" ? "secureConnect" : "connect", function() {
+ queueMicrotask(clearConnectTimeout);
+ if (callback) {
+ const cb = callback;
+ callback = null;
+ cb(null, this);
+ }
+ }).on("error", function(err) {
+ queueMicrotask(clearConnectTimeout);
+ if (callback) {
+ const cb = callback;
+ callback = null;
+ cb(err);
+ }
+ });
+ return socket;
+ }, "connect");
+ }
+ __name(buildConnector, "buildConnector");
+ module2.exports = buildConnector;
+ }
+});
+
+// node_modules/undici/lib/llhttp/utils.js
+var require_utils2 = __commonJS({
+ "node_modules/undici/lib/llhttp/utils.js"(exports2) {
+ "use strict";
+ init_esbuild_shims();
+ Object.defineProperty(exports2, "__esModule", { value: true });
+ exports2.enumToMap = enumToMap;
+ function enumToMap(obj, filter = [], exceptions = []) {
+ const emptyFilter = (filter?.length ?? 0) === 0;
+ const emptyExceptions = (exceptions?.length ?? 0) === 0;
+ return Object.fromEntries(Object.entries(obj).filter(([, value]) => {
+ return typeof value === "number" && (emptyFilter || filter.includes(value)) && (emptyExceptions || !exceptions.includes(value));
+ }));
+ }
+ __name(enumToMap, "enumToMap");
+ }
+});
+
+// node_modules/undici/lib/llhttp/constants.js
+var require_constants3 = __commonJS({
+ "node_modules/undici/lib/llhttp/constants.js"(exports2) {
+ "use strict";
+ init_esbuild_shims();
+ Object.defineProperty(exports2, "__esModule", { value: true });
+ exports2.SPECIAL_HEADERS = exports2.MINOR = exports2.MAJOR = exports2.HTAB_SP_VCHAR_OBS_TEXT = exports2.QUOTED_STRING = exports2.CONNECTION_TOKEN_CHARS = exports2.HEADER_CHARS = exports2.TOKEN = exports2.HEX = exports2.URL_CHAR = exports2.USERINFO_CHARS = exports2.MARK = exports2.ALPHANUM = exports2.NUM = exports2.HEX_MAP = exports2.NUM_MAP = exports2.ALPHA = exports2.STATUSES_HTTP = exports2.H_METHOD_MAP = exports2.METHOD_MAP = exports2.METHODS_RTSP = exports2.METHODS_ICE = exports2.METHODS_HTTP = exports2.HEADER_STATE = exports2.FINISH = exports2.STATUSES = exports2.METHODS = exports2.LENIENT_FLAGS = exports2.FLAGS = exports2.TYPE = exports2.ERROR = void 0;
+ var utils_1 = require_utils2();
+ exports2.ERROR = {
+ OK: 0,
+ INTERNAL: 1,
+ STRICT: 2,
+ CR_EXPECTED: 25,
+ LF_EXPECTED: 3,
+ UNEXPECTED_CONTENT_LENGTH: 4,
+ UNEXPECTED_SPACE: 30,
+ CLOSED_CONNECTION: 5,
+ INVALID_METHOD: 6,
+ INVALID_URL: 7,
+ INVALID_CONSTANT: 8,
+ INVALID_VERSION: 9,
+ INVALID_HEADER_TOKEN: 10,
+ INVALID_CONTENT_LENGTH: 11,
+ INVALID_CHUNK_SIZE: 12,
+ INVALID_STATUS: 13,
+ INVALID_EOF_STATE: 14,
+ INVALID_TRANSFER_ENCODING: 15,
+ CB_MESSAGE_BEGIN: 16,
+ CB_HEADERS_COMPLETE: 17,
+ CB_MESSAGE_COMPLETE: 18,
+ CB_CHUNK_HEADER: 19,
+ CB_CHUNK_COMPLETE: 20,
+ PAUSED: 21,
+ PAUSED_UPGRADE: 22,
+ PAUSED_H2_UPGRADE: 23,
+ USER: 24,
+ CB_URL_COMPLETE: 26,
+ CB_STATUS_COMPLETE: 27,
+ CB_METHOD_COMPLETE: 32,
+ CB_VERSION_COMPLETE: 33,
+ CB_HEADER_FIELD_COMPLETE: 28,
+ CB_HEADER_VALUE_COMPLETE: 29,
+ CB_CHUNK_EXTENSION_NAME_COMPLETE: 34,
+ CB_CHUNK_EXTENSION_VALUE_COMPLETE: 35,
+ CB_RESET: 31,
+ CB_PROTOCOL_COMPLETE: 38
+ };
+ exports2.TYPE = {
+ BOTH: 0,
+ // default
+ REQUEST: 1,
+ RESPONSE: 2
+ };
+ exports2.FLAGS = {
+ CONNECTION_KEEP_ALIVE: 1 << 0,
+ CONNECTION_CLOSE: 1 << 1,
+ CONNECTION_UPGRADE: 1 << 2,
+ CHUNKED: 1 << 3,
+ UPGRADE: 1 << 4,
+ CONTENT_LENGTH: 1 << 5,
+ SKIPBODY: 1 << 6,
+ TRAILING: 1 << 7,
+ // 1 << 8 is unused
+ TRANSFER_ENCODING: 1 << 9
+ };
+ exports2.LENIENT_FLAGS = {
+ HEADERS: 1 << 0,
+ CHUNKED_LENGTH: 1 << 1,
+ KEEP_ALIVE: 1 << 2,
+ TRANSFER_ENCODING: 1 << 3,
+ VERSION: 1 << 4,
+ DATA_AFTER_CLOSE: 1 << 5,
+ OPTIONAL_LF_AFTER_CR: 1 << 6,
+ OPTIONAL_CRLF_AFTER_CHUNK: 1 << 7,
+ OPTIONAL_CR_BEFORE_LF: 1 << 8,
+ SPACES_AFTER_CHUNK_SIZE: 1 << 9
+ };
+ exports2.METHODS = {
+ "DELETE": 0,
+ "GET": 1,
+ "HEAD": 2,
+ "POST": 3,
+ "PUT": 4,
+ /* pathological */
+ "CONNECT": 5,
+ "OPTIONS": 6,
+ "TRACE": 7,
+ /* WebDAV */
+ "COPY": 8,
+ "LOCK": 9,
+ "MKCOL": 10,
+ "MOVE": 11,
+ "PROPFIND": 12,
+ "PROPPATCH": 13,
+ "SEARCH": 14,
+ "UNLOCK": 15,
+ "BIND": 16,
+ "REBIND": 17,
+ "UNBIND": 18,
+ "ACL": 19,
+ /* subversion */
+ "REPORT": 20,
+ "MKACTIVITY": 21,
+ "CHECKOUT": 22,
+ "MERGE": 23,
+ /* upnp */
+ "M-SEARCH": 24,
+ "NOTIFY": 25,
+ "SUBSCRIBE": 26,
+ "UNSUBSCRIBE": 27,
+ /* RFC-5789 */
+ "PATCH": 28,
+ "PURGE": 29,
+ /* CalDAV */
+ "MKCALENDAR": 30,
+ /* RFC-2068, section 19.6.1.2 */
+ "LINK": 31,
+ "UNLINK": 32,
+ /* icecast */
+ "SOURCE": 33,
+ /* RFC-7540, section 11.6 */
+ "PRI": 34,
+ /* RFC-2326 RTSP */
+ "DESCRIBE": 35,
+ "ANNOUNCE": 36,
+ "SETUP": 37,
+ "PLAY": 38,
+ "PAUSE": 39,
+ "TEARDOWN": 40,
+ "GET_PARAMETER": 41,
+ "SET_PARAMETER": 42,
+ "REDIRECT": 43,
+ "RECORD": 44,
+ /* RAOP */
+ "FLUSH": 45,
+ /* DRAFT https://www.ietf.org/archive/id/draft-ietf-httpbis-safe-method-w-body-02.html */
+ "QUERY": 46
+ };
+ exports2.STATUSES = {
+ CONTINUE: 100,
+ SWITCHING_PROTOCOLS: 101,
+ PROCESSING: 102,
+ EARLY_HINTS: 103,
+ RESPONSE_IS_STALE: 110,
+ // Unofficial
+ REVALIDATION_FAILED: 111,
+ // Unofficial
+ DISCONNECTED_OPERATION: 112,
+ // Unofficial
+ HEURISTIC_EXPIRATION: 113,
+ // Unofficial
+ MISCELLANEOUS_WARNING: 199,
+ // Unofficial
+ OK: 200,
+ CREATED: 201,
+ ACCEPTED: 202,
+ NON_AUTHORITATIVE_INFORMATION: 203,
+ NO_CONTENT: 204,
+ RESET_CONTENT: 205,
+ PARTIAL_CONTENT: 206,
+ MULTI_STATUS: 207,
+ ALREADY_REPORTED: 208,
+ TRANSFORMATION_APPLIED: 214,
+ // Unofficial
+ IM_USED: 226,
+ MISCELLANEOUS_PERSISTENT_WARNING: 299,
+ // Unofficial
+ MULTIPLE_CHOICES: 300,
+ MOVED_PERMANENTLY: 301,
+ FOUND: 302,
+ SEE_OTHER: 303,
+ NOT_MODIFIED: 304,
+ USE_PROXY: 305,
+ SWITCH_PROXY: 306,
+ // No longer used
+ TEMPORARY_REDIRECT: 307,
+ PERMANENT_REDIRECT: 308,
+ BAD_REQUEST: 400,
+ UNAUTHORIZED: 401,
+ PAYMENT_REQUIRED: 402,
+ FORBIDDEN: 403,
+ NOT_FOUND: 404,
+ METHOD_NOT_ALLOWED: 405,
+ NOT_ACCEPTABLE: 406,
+ PROXY_AUTHENTICATION_REQUIRED: 407,
+ REQUEST_TIMEOUT: 408,
+ CONFLICT: 409,
+ GONE: 410,
+ LENGTH_REQUIRED: 411,
+ PRECONDITION_FAILED: 412,
+ PAYLOAD_TOO_LARGE: 413,
+ URI_TOO_LONG: 414,
+ UNSUPPORTED_MEDIA_TYPE: 415,
+ RANGE_NOT_SATISFIABLE: 416,
+ EXPECTATION_FAILED: 417,
+ IM_A_TEAPOT: 418,
+ PAGE_EXPIRED: 419,
+ // Unofficial
+ ENHANCE_YOUR_CALM: 420,
+ // Unofficial
+ MISDIRECTED_REQUEST: 421,
+ UNPROCESSABLE_ENTITY: 422,
+ LOCKED: 423,
+ FAILED_DEPENDENCY: 424,
+ TOO_EARLY: 425,
+ UPGRADE_REQUIRED: 426,
+ PRECONDITION_REQUIRED: 428,
+ TOO_MANY_REQUESTS: 429,
+ REQUEST_HEADER_FIELDS_TOO_LARGE_UNOFFICIAL: 430,
+ // Unofficial
+ REQUEST_HEADER_FIELDS_TOO_LARGE: 431,
+ LOGIN_TIMEOUT: 440,
+ // Unofficial
+ NO_RESPONSE: 444,
+ // Unofficial
+ RETRY_WITH: 449,
+ // Unofficial
+ BLOCKED_BY_PARENTAL_CONTROL: 450,
+ // Unofficial
+ UNAVAILABLE_FOR_LEGAL_REASONS: 451,
+ CLIENT_CLOSED_LOAD_BALANCED_REQUEST: 460,
+ // Unofficial
+ INVALID_X_FORWARDED_FOR: 463,
+ // Unofficial
+ REQUEST_HEADER_TOO_LARGE: 494,
+ // Unofficial
+ SSL_CERTIFICATE_ERROR: 495,
+ // Unofficial
+ SSL_CERTIFICATE_REQUIRED: 496,
+ // Unofficial
+ HTTP_REQUEST_SENT_TO_HTTPS_PORT: 497,
+ // Unofficial
+ INVALID_TOKEN: 498,
+ // Unofficial
+ CLIENT_CLOSED_REQUEST: 499,
+ // Unofficial
+ INTERNAL_SERVER_ERROR: 500,
+ NOT_IMPLEMENTED: 501,
+ BAD_GATEWAY: 502,
+ SERVICE_UNAVAILABLE: 503,
+ GATEWAY_TIMEOUT: 504,
+ HTTP_VERSION_NOT_SUPPORTED: 505,
+ VARIANT_ALSO_NEGOTIATES: 506,
+ INSUFFICIENT_STORAGE: 507,
+ LOOP_DETECTED: 508,
+ BANDWIDTH_LIMIT_EXCEEDED: 509,
+ NOT_EXTENDED: 510,
+ NETWORK_AUTHENTICATION_REQUIRED: 511,
+ WEB_SERVER_UNKNOWN_ERROR: 520,
+ // Unofficial
+ WEB_SERVER_IS_DOWN: 521,
+ // Unofficial
+ CONNECTION_TIMEOUT: 522,
+ // Unofficial
+ ORIGIN_IS_UNREACHABLE: 523,
+ // Unofficial
+ TIMEOUT_OCCURED: 524,
+ // Unofficial
+ SSL_HANDSHAKE_FAILED: 525,
+ // Unofficial
+ INVALID_SSL_CERTIFICATE: 526,
+ // Unofficial
+ RAILGUN_ERROR: 527,
+ // Unofficial
+ SITE_IS_OVERLOADED: 529,
+ // Unofficial
+ SITE_IS_FROZEN: 530,
+ // Unofficial
+ IDENTITY_PROVIDER_AUTHENTICATION_ERROR: 561,
+ // Unofficial
+ NETWORK_READ_TIMEOUT: 598,
+ // Unofficial
+ NETWORK_CONNECT_TIMEOUT: 599
+ // Unofficial
+ };
+ exports2.FINISH = {
+ SAFE: 0,
+ SAFE_WITH_CB: 1,
+ UNSAFE: 2
+ };
+ exports2.HEADER_STATE = {
+ GENERAL: 0,
+ CONNECTION: 1,
+ CONTENT_LENGTH: 2,
+ TRANSFER_ENCODING: 3,
+ UPGRADE: 4,
+ CONNECTION_KEEP_ALIVE: 5,
+ CONNECTION_CLOSE: 6,
+ CONNECTION_UPGRADE: 7,
+ TRANSFER_ENCODING_CHUNKED: 8
+ };
+ exports2.METHODS_HTTP = [
+ exports2.METHODS.DELETE,
+ exports2.METHODS.GET,
+ exports2.METHODS.HEAD,
+ exports2.METHODS.POST,
+ exports2.METHODS.PUT,
+ exports2.METHODS.CONNECT,
+ exports2.METHODS.OPTIONS,
+ exports2.METHODS.TRACE,
+ exports2.METHODS.COPY,
+ exports2.METHODS.LOCK,
+ exports2.METHODS.MKCOL,
+ exports2.METHODS.MOVE,
+ exports2.METHODS.PROPFIND,
+ exports2.METHODS.PROPPATCH,
+ exports2.METHODS.SEARCH,
+ exports2.METHODS.UNLOCK,
+ exports2.METHODS.BIND,
+ exports2.METHODS.REBIND,
+ exports2.METHODS.UNBIND,
+ exports2.METHODS.ACL,
+ exports2.METHODS.REPORT,
+ exports2.METHODS.MKACTIVITY,
+ exports2.METHODS.CHECKOUT,
+ exports2.METHODS.MERGE,
+ exports2.METHODS["M-SEARCH"],
+ exports2.METHODS.NOTIFY,
+ exports2.METHODS.SUBSCRIBE,
+ exports2.METHODS.UNSUBSCRIBE,
+ exports2.METHODS.PATCH,
+ exports2.METHODS.PURGE,
+ exports2.METHODS.MKCALENDAR,
+ exports2.METHODS.LINK,
+ exports2.METHODS.UNLINK,
+ exports2.METHODS.PRI,
+ // TODO(indutny): should we allow it with HTTP?
+ exports2.METHODS.SOURCE,
+ exports2.METHODS.QUERY
+ ];
+ exports2.METHODS_ICE = [
+ exports2.METHODS.SOURCE
+ ];
+ exports2.METHODS_RTSP = [
+ exports2.METHODS.OPTIONS,
+ exports2.METHODS.DESCRIBE,
+ exports2.METHODS.ANNOUNCE,
+ exports2.METHODS.SETUP,
+ exports2.METHODS.PLAY,
+ exports2.METHODS.PAUSE,
+ exports2.METHODS.TEARDOWN,
+ exports2.METHODS.GET_PARAMETER,
+ exports2.METHODS.SET_PARAMETER,
+ exports2.METHODS.REDIRECT,
+ exports2.METHODS.RECORD,
+ exports2.METHODS.FLUSH,
+ // For AirPlay
+ exports2.METHODS.GET,
+ exports2.METHODS.POST
+ ];
+ exports2.METHOD_MAP = (0, utils_1.enumToMap)(exports2.METHODS);
+ exports2.H_METHOD_MAP = Object.fromEntries(Object.entries(exports2.METHODS).filter(([k]) => k.startsWith("H")));
+ exports2.STATUSES_HTTP = [
+ exports2.STATUSES.CONTINUE,
+ exports2.STATUSES.SWITCHING_PROTOCOLS,
+ exports2.STATUSES.PROCESSING,
+ exports2.STATUSES.EARLY_HINTS,
+ exports2.STATUSES.RESPONSE_IS_STALE,
+ exports2.STATUSES.REVALIDATION_FAILED,
+ exports2.STATUSES.DISCONNECTED_OPERATION,
+ exports2.STATUSES.HEURISTIC_EXPIRATION,
+ exports2.STATUSES.MISCELLANEOUS_WARNING,
+ exports2.STATUSES.OK,
+ exports2.STATUSES.CREATED,
+ exports2.STATUSES.ACCEPTED,
+ exports2.STATUSES.NON_AUTHORITATIVE_INFORMATION,
+ exports2.STATUSES.NO_CONTENT,
+ exports2.STATUSES.RESET_CONTENT,
+ exports2.STATUSES.PARTIAL_CONTENT,
+ exports2.STATUSES.MULTI_STATUS,
+ exports2.STATUSES.ALREADY_REPORTED,
+ exports2.STATUSES.TRANSFORMATION_APPLIED,
+ exports2.STATUSES.IM_USED,
+ exports2.STATUSES.MISCELLANEOUS_PERSISTENT_WARNING,
+ exports2.STATUSES.MULTIPLE_CHOICES,
+ exports2.STATUSES.MOVED_PERMANENTLY,
+ exports2.STATUSES.FOUND,
+ exports2.STATUSES.SEE_OTHER,
+ exports2.STATUSES.NOT_MODIFIED,
+ exports2.STATUSES.USE_PROXY,
+ exports2.STATUSES.SWITCH_PROXY,
+ exports2.STATUSES.TEMPORARY_REDIRECT,
+ exports2.STATUSES.PERMANENT_REDIRECT,
+ exports2.STATUSES.BAD_REQUEST,
+ exports2.STATUSES.UNAUTHORIZED,
+ exports2.STATUSES.PAYMENT_REQUIRED,
+ exports2.STATUSES.FORBIDDEN,
+ exports2.STATUSES.NOT_FOUND,
+ exports2.STATUSES.METHOD_NOT_ALLOWED,
+ exports2.STATUSES.NOT_ACCEPTABLE,
+ exports2.STATUSES.PROXY_AUTHENTICATION_REQUIRED,
+ exports2.STATUSES.REQUEST_TIMEOUT,
+ exports2.STATUSES.CONFLICT,
+ exports2.STATUSES.GONE,
+ exports2.STATUSES.LENGTH_REQUIRED,
+ exports2.STATUSES.PRECONDITION_FAILED,
+ exports2.STATUSES.PAYLOAD_TOO_LARGE,
+ exports2.STATUSES.URI_TOO_LONG,
+ exports2.STATUSES.UNSUPPORTED_MEDIA_TYPE,
+ exports2.STATUSES.RANGE_NOT_SATISFIABLE,
+ exports2.STATUSES.EXPECTATION_FAILED,
+ exports2.STATUSES.IM_A_TEAPOT,
+ exports2.STATUSES.PAGE_EXPIRED,
+ exports2.STATUSES.ENHANCE_YOUR_CALM,
+ exports2.STATUSES.MISDIRECTED_REQUEST,
+ exports2.STATUSES.UNPROCESSABLE_ENTITY,
+ exports2.STATUSES.LOCKED,
+ exports2.STATUSES.FAILED_DEPENDENCY,
+ exports2.STATUSES.TOO_EARLY,
+ exports2.STATUSES.UPGRADE_REQUIRED,
+ exports2.STATUSES.PRECONDITION_REQUIRED,
+ exports2.STATUSES.TOO_MANY_REQUESTS,
+ exports2.STATUSES.REQUEST_HEADER_FIELDS_TOO_LARGE_UNOFFICIAL,
+ exports2.STATUSES.REQUEST_HEADER_FIELDS_TOO_LARGE,
+ exports2.STATUSES.LOGIN_TIMEOUT,
+ exports2.STATUSES.NO_RESPONSE,
+ exports2.STATUSES.RETRY_WITH,
+ exports2.STATUSES.BLOCKED_BY_PARENTAL_CONTROL,
+ exports2.STATUSES.UNAVAILABLE_FOR_LEGAL_REASONS,
+ exports2.STATUSES.CLIENT_CLOSED_LOAD_BALANCED_REQUEST,
+ exports2.STATUSES.INVALID_X_FORWARDED_FOR,
+ exports2.STATUSES.REQUEST_HEADER_TOO_LARGE,
+ exports2.STATUSES.SSL_CERTIFICATE_ERROR,
+ exports2.STATUSES.SSL_CERTIFICATE_REQUIRED,
+ exports2.STATUSES.HTTP_REQUEST_SENT_TO_HTTPS_PORT,
+ exports2.STATUSES.INVALID_TOKEN,
+ exports2.STATUSES.CLIENT_CLOSED_REQUEST,
+ exports2.STATUSES.INTERNAL_SERVER_ERROR,
+ exports2.STATUSES.NOT_IMPLEMENTED,
+ exports2.STATUSES.BAD_GATEWAY,
+ exports2.STATUSES.SERVICE_UNAVAILABLE,
+ exports2.STATUSES.GATEWAY_TIMEOUT,
+ exports2.STATUSES.HTTP_VERSION_NOT_SUPPORTED,
+ exports2.STATUSES.VARIANT_ALSO_NEGOTIATES,
+ exports2.STATUSES.INSUFFICIENT_STORAGE,
+ exports2.STATUSES.LOOP_DETECTED,
+ exports2.STATUSES.BANDWIDTH_LIMIT_EXCEEDED,
+ exports2.STATUSES.NOT_EXTENDED,
+ exports2.STATUSES.NETWORK_AUTHENTICATION_REQUIRED,
+ exports2.STATUSES.WEB_SERVER_UNKNOWN_ERROR,
+ exports2.STATUSES.WEB_SERVER_IS_DOWN,
+ exports2.STATUSES.CONNECTION_TIMEOUT,
+ exports2.STATUSES.ORIGIN_IS_UNREACHABLE,
+ exports2.STATUSES.TIMEOUT_OCCURED,
+ exports2.STATUSES.SSL_HANDSHAKE_FAILED,
+ exports2.STATUSES.INVALID_SSL_CERTIFICATE,
+ exports2.STATUSES.RAILGUN_ERROR,
+ exports2.STATUSES.SITE_IS_OVERLOADED,
+ exports2.STATUSES.SITE_IS_FROZEN,
+ exports2.STATUSES.IDENTITY_PROVIDER_AUTHENTICATION_ERROR,
+ exports2.STATUSES.NETWORK_READ_TIMEOUT,
+ exports2.STATUSES.NETWORK_CONNECT_TIMEOUT
+ ];
+ exports2.ALPHA = [];
+ for (let i = "A".charCodeAt(0); i <= "Z".charCodeAt(0); i++) {
+ exports2.ALPHA.push(String.fromCharCode(i));
+ exports2.ALPHA.push(String.fromCharCode(i + 32));
+ }
+ exports2.NUM_MAP = {
+ 0: 0,
+ 1: 1,
+ 2: 2,
+ 3: 3,
+ 4: 4,
+ 5: 5,
+ 6: 6,
+ 7: 7,
+ 8: 8,
+ 9: 9
+ };
+ exports2.HEX_MAP = {
+ 0: 0,
+ 1: 1,
+ 2: 2,
+ 3: 3,
+ 4: 4,
+ 5: 5,
+ 6: 6,
+ 7: 7,
+ 8: 8,
+ 9: 9,
+ A: 10,
+ B: 11,
+ C: 12,
+ D: 13,
+ E: 14,
+ F: 15,
+ a: 10,
+ b: 11,
+ c: 12,
+ d: 13,
+ e: 14,
+ f: 15
+ };
+ exports2.NUM = [
+ "0",
+ "1",
+ "2",
+ "3",
+ "4",
+ "5",
+ "6",
+ "7",
+ "8",
+ "9"
+ ];
+ exports2.ALPHANUM = exports2.ALPHA.concat(exports2.NUM);
+ exports2.MARK = ["-", "_", ".", "!", "~", "*", "'", "(", ")"];
+ exports2.USERINFO_CHARS = exports2.ALPHANUM.concat(exports2.MARK).concat(["%", ";", ":", "&", "=", "+", "$", ","]);
+ exports2.URL_CHAR = [
+ "!",
+ '"',
+ "$",
+ "%",
+ "&",
+ "'",
+ "(",
+ ")",
+ "*",
+ "+",
+ ",",
+ "-",
+ ".",
+ "/",
+ ":",
+ ";",
+ "<",
+ "=",
+ ">",
+ "@",
+ "[",
+ "\\",
+ "]",
+ "^",
+ "_",
+ "`",
+ "{",
+ "|",
+ "}",
+ "~"
+ ].concat(exports2.ALPHANUM);
+ exports2.HEX = exports2.NUM.concat(["a", "b", "c", "d", "e", "f", "A", "B", "C", "D", "E", "F"]);
+ exports2.TOKEN = [
+ "!",
+ "#",
+ "$",
+ "%",
+ "&",
+ "'",
+ "*",
+ "+",
+ "-",
+ ".",
+ "^",
+ "_",
+ "`",
+ "|",
+ "~"
+ ].concat(exports2.ALPHANUM);
+ exports2.HEADER_CHARS = [" "];
+ for (let i = 32; i <= 255; i++) {
+ if (i !== 127) {
+ exports2.HEADER_CHARS.push(i);
+ }
+ }
+ exports2.CONNECTION_TOKEN_CHARS = exports2.HEADER_CHARS.filter((c) => c !== 44);
+ exports2.QUOTED_STRING = [" ", " "];
+ for (let i = 33; i <= 255; i++) {
+ if (i !== 34 && i !== 92) {
+ exports2.QUOTED_STRING.push(i);
+ }
+ }
+ exports2.HTAB_SP_VCHAR_OBS_TEXT = [" ", " "];
+ for (let i = 33; i <= 126; i++) {
+ exports2.HTAB_SP_VCHAR_OBS_TEXT.push(i);
+ }
+ for (let i = 128; i <= 255; i++) {
+ exports2.HTAB_SP_VCHAR_OBS_TEXT.push(i);
+ }
+ exports2.MAJOR = exports2.NUM_MAP;
+ exports2.MINOR = exports2.MAJOR;
+ exports2.SPECIAL_HEADERS = {
+ "connection": exports2.HEADER_STATE.CONNECTION,
+ "content-length": exports2.HEADER_STATE.CONTENT_LENGTH,
+ "proxy-connection": exports2.HEADER_STATE.CONNECTION,
+ "transfer-encoding": exports2.HEADER_STATE.TRANSFER_ENCODING,
+ "upgrade": exports2.HEADER_STATE.UPGRADE
+ };
+ exports2.default = {
+ ERROR: exports2.ERROR,
+ TYPE: exports2.TYPE,
+ FLAGS: exports2.FLAGS,
+ LENIENT_FLAGS: exports2.LENIENT_FLAGS,
+ METHODS: exports2.METHODS,
+ STATUSES: exports2.STATUSES,
+ FINISH: exports2.FINISH,
+ HEADER_STATE: exports2.HEADER_STATE,
+ ALPHA: exports2.ALPHA,
+ NUM_MAP: exports2.NUM_MAP,
+ HEX_MAP: exports2.HEX_MAP,
+ NUM: exports2.NUM,
+ ALPHANUM: exports2.ALPHANUM,
+ MARK: exports2.MARK,
+ USERINFO_CHARS: exports2.USERINFO_CHARS,
+ URL_CHAR: exports2.URL_CHAR,
+ HEX: exports2.HEX,
+ TOKEN: exports2.TOKEN,
+ HEADER_CHARS: exports2.HEADER_CHARS,
+ CONNECTION_TOKEN_CHARS: exports2.CONNECTION_TOKEN_CHARS,
+ QUOTED_STRING: exports2.QUOTED_STRING,
+ HTAB_SP_VCHAR_OBS_TEXT: exports2.HTAB_SP_VCHAR_OBS_TEXT,
+ MAJOR: exports2.MAJOR,
+ MINOR: exports2.MINOR,
+ SPECIAL_HEADERS: exports2.SPECIAL_HEADERS,
+ METHODS_HTTP: exports2.METHODS_HTTP,
+ METHODS_ICE: exports2.METHODS_ICE,
+ METHODS_RTSP: exports2.METHODS_RTSP,
+ METHOD_MAP: exports2.METHOD_MAP,
+ H_METHOD_MAP: exports2.H_METHOD_MAP,
+ STATUSES_HTTP: exports2.STATUSES_HTTP
+ };
+ }
+});
+
+// node_modules/undici/lib/llhttp/llhttp-wasm.js
+var require_llhttp_wasm = __commonJS({
+ "node_modules/undici/lib/llhttp/llhttp-wasm.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { Buffer: Buffer2 } = __require("node:buffer");
+ var wasmBase64 = "AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAn9/AGABfwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAAzU0BQYAAAMAAAAAAAADAQMAAwMDAAACAAAAAAICAgICAgICAgIBAQEBAQEBAQEBAwAAAwAAAAQFAXABExMFAwEAAgYIAX8BQcDZBAsHxQcoBm1lbW9yeQIAC19pbml0aWFsaXplAAgZX19pbmRpcmVjdF9mdW5jdGlvbl90YWJsZQEAC2xsaHR0cF9pbml0AAkYbGxodHRwX3Nob3VsZF9rZWVwX2FsaXZlADcMbGxodHRwX2FsbG9jAAsGbWFsbG9jADkLbGxodHRwX2ZyZWUADARmcmVlAAwPbGxodHRwX2dldF90eXBlAA0VbGxodHRwX2dldF9odHRwX21ham9yAA4VbGxodHRwX2dldF9odHRwX21pbm9yAA8RbGxodHRwX2dldF9tZXRob2QAEBZsbGh0dHBfZ2V0X3N0YXR1c19jb2RlABESbGxodHRwX2dldF91cGdyYWRlABIMbGxodHRwX3Jlc2V0ABMObGxodHRwX2V4ZWN1dGUAFBRsbGh0dHBfc2V0dGluZ3NfaW5pdAAVDWxsaHR0cF9maW5pc2gAFgxsbGh0dHBfcGF1c2UAFw1sbGh0dHBfcmVzdW1lABgbbGxodHRwX3Jlc3VtZV9hZnRlcl91cGdyYWRlABkQbGxodHRwX2dldF9lcnJubwAaF2xsaHR0cF9nZXRfZXJyb3JfcmVhc29uABsXbGxodHRwX3NldF9lcnJvcl9yZWFzb24AHBRsbGh0dHBfZ2V0X2Vycm9yX3BvcwAdEWxsaHR0cF9lcnJub19uYW1lAB4SbGxodHRwX21ldGhvZF9uYW1lAB8SbGxodHRwX3N0YXR1c19uYW1lACAabGxodHRw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AXRrQT5qIQILIAEgAjYCHCABQgA3AhAgAkECdEH01wBqIQACQEHI1QAoAgAiA0EBIAJ0IgdxRQRAIAAgATYCAEHI1QAgAyAHcjYCACABIAA2AhggASABNgIIIAEgATYCDAwBCyAEQRkgAkEBdmtBACACQR9HG3QhAiAAKAIAIQACQANAIAAiAygCBEF4cSAERg0BIAJBHXYhACACQQF0IQIgAyAAQQRxakEQaiIHKAIAIgANAAsgByABNgIAIAEgAzYCGCABIAE2AgwgASABNgIIDAELIAMoAggiACABNgIMIAMgATYCCCABQQA2AhggASADNgIMIAEgADYCCAtB5NUAQeTVACgCAEEBayIAQX8gABs2AgALCwcAIAAtACgLBwAgAC0AKgsHACAALQArCwcAIAAtACkLBwAgAC8BNAsHACAALQAwC0ABBH8gACgCGCEBIAAvAS4hAiAALQAoIQMgACgCOCEEIAAQOCAAIAQ2AjggACADOgAoIAAgAjsBLiAAIAE2AhgL5YUCAgd/A34gASACaiEEAkAgACIDKAIMIgANACADKAIEBEAgAyABNgIECyMAQRBrIgkkAAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAC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C0HjAQwHC0HXAQwGC0HYAQwFC0HZAQwEC0HaAQwDC0HbAQwCC0HdAQwBC0HcAQshAgNAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCADAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJ/AkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAMCfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAg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ogKiAqICogKiAqICogKiAqICogKiAqICogIAogILIAQgAUEBaiIBRw0AC0HJACECDOwCCyABQQFqIQEgA0Evai0AAEEBcQ2lAiADQQA2AhwgAyABNgIUIANBlxA2AhAgA0EKNgIMQQAhAgzrAgsgASAERwRAA0AgAS0AAEEgRw0VIAQgAUEBaiIBRw0AC0H4ACECDOsCC0H4ACECDOoCCyADQQI6ACgMOAtBACECIANBADYCHCADQb8LNgIQIANBAjYCDCADIAFBAWo2AhQM6AILQQAhAgzOAgtBDSECDM0CC0ETIQIMzAILQRUhAgzLAgtBFiECDMoCC0EYIQIMyQILQRkhAgzIAgtBGiECDMcCC0EbIQIMxgILQRwhAgzFAgtBHSECDMQCC0EeIQIMwwILQR8hAgzCAgtBICECDMECC0EiIQIMwAILQSMhAgy/AgtBJSECDL4CC0HlACECDL0CCyADQT02AhwgAyABNgIUIAMgADYCDEEAIQIM1QILIANBGzYCHCADIAE2AhQgA0GkHDYCECADQRU2AgxBACECDNQCCyADQSA2AhwgAyABNgIUIANBmBo2AhAgA0EVNgIMQQAhAgzTAgsgA0ETNgIcIAMgATYCFCADQZgaNgIQIANBFTYCDEEAIQIM0gILIANBCzYCHCADIAE2AhQgA0GYGjYCECADQRU2AgxBACECDNECCyADQRA2AhwgAyABNgIUIANBmBo2AhAgA0EVNgIMQQAhAgzQAgsgA0EgNgIcIAMgATYCFCADQaQcNgIQIANBFTYCDEEAIQIMzwILIANBCzYCHCADIAE2AhQgA0GkHDYCECADQRU2AgxBACECDM4CCyADQQw2AhwgAyABNgIUIANBpBw2AhAgA0EVNgIMQQAhAgzNAgtBACECIANBADYCHCADIAE2AhQgA0HdDjYCECADQRI2AgwMzAILAkADQAJAIAEtAABBCmsOBAACAgACCyAEIAFBAWoiAUcNAAtB/QEhAgzMAgsCQAJAIAMtADZBAUcNAEEAIQACQCADKAI4IgJFDQAgAigCYCICRQ0AIAMgAhEAACEACyAARQ0AIABBFUcNASADQfwBNgIcIAMgATYCFCADQdwZNgIQIANBFTYCDEEAIQIMzQILQdwBIQIMswILIANBADYCHCADIAE2AhQgA0H5CzYCECADQR82AgxBACECDMsCCwJAAkAgAy0AKEEBaw4CBAEAC0HbASECDLICC0HUASECDLECCyADQQI6ADFBACEAAkAgAygCOCICRQ0AIAIoAgAiAkUNACADIAIRAAAhAAsgAEUEQEHdASECDLECCyAAQRVHBEAgA0EANgIcIAMgATYCFCADQbQMNgIQIANBEDYCDEEAIQIMygILIANB+wE2AhwgAyABNgIUIANBgRo2AhAgA0EVNgIMQQAhAgzJAgsgASAERgRAQfoBIQIMyQILIAEtAABByABGDQEgA0EBOgAoC0HAASECDK4CC0HaASECDK0CCyABIARHBEAgA0EMNgIIIAMgATYCBEHZASECDK0CC0H5ASECDMUCCyABIARGBEBB+AEhAgzFAgsgAS0AAEHIAEcNBCABQQFqIQFB2AEhAgyrAgsgASAERgRAQfcBIQIMxAILAkACQCABLQAAQcUAaw4QAAUFBQUFBQUFBQUFBQUFAQULIAFBAWohAUHWASECDKsCCyABQQFqIQFB1wEhAgyqAgtB9gEhAiABIARGDcICIAMoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQbrVAGotAABHDQMgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADMMCCyADKAIEIQAgA0IANwMAIAMgACAGQQFqIgEQLiIARQRAQeMBIQIMqgILIANB9QE2AhwgAyABNgIUIAMgADYCDEEAIQIMwgILQfQBIQIgASAERg3BAiADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEG41QBqLQAARw0CIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzCAgsgA0GBBDsBKCADKAIEIQAgA0IANwMAIAMgACAGQQFqIgEQLiIADQMMAgsgA0EANgIAC0EAIQIgA0EANgIcIAMgATYCFCADQeUfNgIQIANBCDYCDAy/AgtB1QEhAgylAgsgA0HzATYCHCADIAE2AhQgAyAANgIMQQAhAgy9AgtBACEAAkAgAygCOCICRQ0AIAIoAkAiAkUNACADIAIRAAAhAAsgAEUNbiAAQRVHBEAgA0EANgIcIAMgATYCFCADQYIPNgIQIANBIDYCDEEAIQIMvQILIANBjwE2AhwgAyABNgIUIANB7Bs2AhAgA0EVNgIMQQAhAgy8AgsgASAERwRAIANBDTYCCCADIAE2AgRB0wEhAgyjAgtB8gEhAgy7AgsgASAERgRAQfEBIQIMuwILAkACQAJAIAEtAABByABrDgsAAQgICAgICAgIAggLIAFBAWohAUHQASECDKMCCyABQQFqIQFB0QEhAgyiAgsgAUEBaiEBQdIBIQIMoQILQfABIQIgASAERg25AiADKAIAIgAgBCABa2ohBiABIABrQQJqIQUDQCABLQAAIABBtdUAai0AAEcNBCAAQQJGDQMgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAY2AgAMuQILQe8BIQIgASAERg24AiADKAIAIgAgBCABa2ohBiABIABrQQFqIQUDQCABLQAAIABBs9UAai0AAEcNAyAAQQFGDQIgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAY2AgAMuAILQe4BIQIgASAERg23AiADKAIAIgAgBCABa2ohBiABIABrQQJqIQUDQCABLQAAIABBsNUAai0AAEcNAiAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAY2AgAMtwILIAMoAgQhACADQgA3AwAgAyAAIAVBAWoiARArIgBFDQIgA0HsATYCHCADIAE2AhQgAyAANgIMQQAhAgy2AgsgA0EANgIACyADKAIEIQAgA0EANgIEIAMgACABECsiAEUNnAIgA0HtATYCHCADIAE2AhQgAyAANgIMQQAhAgy0AgtBzwEhAgyaAgtBACEAAkAgAygCOCICRQ0AIAIoAjQiAkUNACADIAIRAAAhAAsCQCAABEAgAEEVRg0BIANBADYCHCADIAE2AhQgA0HqDTYCECADQSY2AgxBACECDLQCC0HOASECDJoCCyADQesBNgIcIAMgATYCFCADQYAbNgIQIANBFTYCDEEAIQIMsgILIAEgBEYEQEHrASECDLICCyABLQAAQS9GBEAgAUEBaiEBDAELIANBADYCHCADIAE2AhQgA0GyODYCECADQQg2AgxBACECDLECC0HNASECDJcCCyABIARHBEAgA0EONgIIIAMgATYCBEHMASECDJcCC0HqASECDK8CCyABIARGBEBB6QEhAgyvAgsgAS0AAEEwayIAQf8BcUEKSQRAIAMgADoAKiABQQFqIQFBywEhAgyWAgsgAygCBCEAIANBADYCBCADIAAgARAvIgBFDZcCIANB6AE2AhwgAyABNgIUIAMgADYCDEEAIQIMrgILIAEgBEYEQEHnASECDK4CCwJAIAEtAABBLkYEQCABQQFqIQEMAQsgAygCBCEAIANBADYCBCADIAAgARAvIgBFDZgCIANB5gE2AhwgAyABNgIUIAMgADYCDEEAIQIMrgILQcoBIQIMlAILIAEgBEYEQEHlASECDK0CC0EAIQBBASEFQQEhB0EAIQICQAJAAkACQAJAAn8CQAJAAkACQAJAAkACQCABLQAAQTBrDgoKCQABAgMEBQYICwtBAgwGC0EDDAULQQQMBAtBBQwDC0EGDAILQQcMAQtBCAshAkEAIQVBACEHDAILQQkhAkEBIQBBACEFQQAhBwwBC0EAIQVBASECCyADIAI6ACsgAUEBaiEBAkACQCADLQAuQRBxDQACQAJAAkAgAy0AKg4DAQACBAsgB0UNAwwCCyAADQEMAgsgBUUNAQsgAygCBCEAIANBADYCBCADIAAgARAvIgBFDQIgA0HiATYCHCADIAE2AhQgAyAANgIMQQAhAgyvAgsgAygCBCEAIANBADYCBCADIAAgARAvIgBFDZoCIANB4wE2AhwgAyABNgIUIAMgADYCDEEAIQIMrgILIAMoAgQhACADQQA2AgQgAyAAIAEQLyIARQ2YAiADQeQBNgIcIAMgATYCFCADIAA2AgwMrQILQckBIQIMkwILQQAhAAJAIAMoAjgiAkUNACACKAJEIgJFDQAgAyACEQAAIQALAkAgAARAIABBFUYNASADQQA2AhwgAyABNgIUIANBpA02AhAgA0EhNgIMQQAhAgytAgtByAEhAgyTAgsgA0HhATYCHCADIAE2AhQgA0HQGjYCECADQRU2AgxBACECDKsCCyABIARGBEBB4QEhAgyrAgsCQCABLQAAQSBGBEAgA0EAOwE0IAFBAWohAQwBCyADQQA2AhwgAyABNgIUIANBmRE2AhAgA0EJNgIMQQAhAgyrAgtBxwEhAgyRAgsgASAERgRAQeABIQIMqgILAkAgAS0AAEEwa0H/AXEiAkEKSQRAIAFBAWohAQJAIAMvATQiAEGZM0sNACADIABBCmwiADsBNCAAQf7/A3EgAkH//wNzSw0AIAMgACACajsBNAwCC0EAIQIgA0EANgIcIAMgATYCFCADQZUeNgIQIANBDTYCDAyrAgsgA0EANgIcIAMgATYCFCADQZUeNgIQIANBDTYCDEEAIQIMqgILQcYBIQIMkAILIAEgBEYEQEHfASECDKkCCwJAIAEtAABBMGtB/wFxIgJBCkkEQCABQQFqIQECQCADLwE0IgBBmTNLDQAgAyAAQQpsIgA7ATQgAEH+/wNxIAJB//8Dc0sNACADIAAgAmo7ATQMAgtBACECIANBADYCHCADIAE2AhQgA0GVHjYCECADQQ02AgwMqgILIANBADYCHCADIAE2AhQgA0GVHjYCECADQQ02AgxBACECDKkCC0HFASECDI8CCyABIARGBEBB3gEhAgyoAgsCQCABLQAAQTBrQf8BcSICQQpJBEAgAUEBaiEBAkAgAy8BNCIAQZkzSw0AIAMgAEEKbCIAOwE0IABB/v8DcSACQf//A3NLDQAgAyAAIAJqOwE0DAILQQAhAiADQQA2AhwgAyABNgIUIANBlR42AhAgA0ENNgIMDKkCCyADQQA2AhwgAyABNgIUIANBlR42AhAgA0ENNgIMQQAhAgyoAgtBxAEhAgyOAgsgASAERgRAQd0BIQIMpwILAkACQAJAAkAgAS0AAEEKaw4XAgMDAAMDAwMDAwMDAwMDAwMDAwMDAwEDCyABQQFqDAULIAFBAWohAUHDASECDI8CCyABQQFqIQEgA0Evai0AAEEBcQ0IIANBADYCHCADIAE2AhQgA0GNCzYCECADQQ02AgxBACECDKcCCyADQQA2AhwgAyABNgIUIANBjQs2AhAgA0ENNgIMQQAhAgymAgsgASAERwRAIANBDzYCCCADIAE2AgRBASECDI0CC0HcASECDKUCCwJAAkADQAJAIAEtAABBCmsOBAIAAAMACyAEIAFBAWoiAUcNAAtB2wEhAgymAgsgAygCBCEAIANBADYCBCADIAAgARAtIgBFBEAgAUEBaiEBDAQLIANB2gE2AhwgAyAANgIMIAMgAUEBajYCFEEAIQIMpQILIAMoAgQhACADQQA2AgQgAyAAIAEQLSIADQEgAUEBagshAUHBASECDIoCCyADQdkBNgIcIAMgADYCDCADIAFBAWo2AhRBACECDKICC0HCASECDIgCCyADQS9qLQAAQQFxDQEgA0EANgIcIAMgATYCFCADQeQcNgIQIANBGTYCDEEAIQIMoAILIAEgBEYEQEHZASEC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IAFBAWohAUGeASECDOQBCyABQQFqIQFBnwEhAgzjAQtBtwEhAiABIARGDfsBIAMoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQezUAGotAABHDSggAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADPwBCyADQQA2AgAgBkEBaiEBQQ0MKAtBtgEhAiABIARGDfoBIAMoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQaHVAGotAABHDScgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADPsBCyADQQA2AgAgBkEBaiEBQQwMJwtBtQEhAiABIARGDfkBIAMoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQerUAGotAABHDSYgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADPoBCyADQQA2AgAgBkEBaiEBQQMMJgtBtAEhAiABIARGDfgBIAMoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQejUAGotAABHDSUgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADPkBCyADQQA2AgAgBkEBaiEBQSYMJQsgASAERgRAQbMBIQIM+AELAkACQCABLQAAQdQAaw4CAAEnCyABQQFqIQFBmQEhAgzfAQsgAUEBaiEBQZoBIQIM3gELQbIBIQIgASAERg32ASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHm1ABqLQAARw0jIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAz3AQsgA0EANgIAIAZBAWohAUEnDCMLQbEBIQIgASAERg31ASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHk1ABqLQAARw0iIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAz2AQsgA0EANgIAIAZBAWohAUEcDCILQbABIQIgASAERg30ASADKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEHe1ABqLQAARw0hIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAz1AQsgA0EANgIAIAZBAWohAUEGDCELQa8BIQIgASAERg3zASADKAIAIgAgBCABa2ohBSABIABrQQRqIQYCQANAIAEtAAAgAEHZ1ABqLQAARw0gIABBBEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAz0AQsgA0EANgIAIAZBAWohAUEZDCALIAEgBEYEQEGuASECDPMBCwJAAkACQAJAIAEtAABBLWsOIwAkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJAEkJCQkJAIkJCQDJAsgAUEBaiEBQY4BIQIM3AELIAFBAWohAUGPASECDNsBCyABQQFqIQFBlAEhAgzaAQsgAUEBaiEBQZUBIQIM2QELQa0BIQIgASAERg3xASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHX1ABqLQAARw0eIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzyAQsgA0EANgIAIAZBAWohAUELDB4LIAEgBEYEQEGsASECDPEBCwJAAkAgAS0AAEHBAGsOAwAgASALIAFBAWohAUGQASECDNgBCyABQQFqIQFBkwEhAgzXAQsgASAERgRAQasBIQIM8AELAkACQCABLQAAQcEAaw4PAB8fHx8fHx8fHx8fHx8BHwsgAUEBaiEBQZEBIQIM1wELIAFBAWohAUGSASECDNYBCyABIARGBEBBqgEhAgzvAQsgAS0AAEHMAEcNHCABQQFqIQFBCgwbC0GpASECIAEgBEYN7QEgAygCACIAIAQgAWtqIQUgASAAa0EFaiEGAkADQCABLQAAIABB0dQAai0AAEcNGiAAQQVGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM7gELIANBADYCACAGQQFqIQFBHgwaC0GoASECIAEgBEYN7AEgAygCACIAIAQgAWtqIQUgASAAa0EGaiEGAkADQCABLQAAIABBytQAai0AAEcNGSAAQQZGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM7QELIANBADYCACAGQQFqIQFBFQwZC0GnASECIAEgBEYN6wEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBx9QAai0AAEcNGCAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM7AELIANBADYCACAGQQFqIQFBFwwYC0GmASECIAEgBEYN6gEgAygCACIAIAQgAWtqIQUgASAAa0EFaiEGAkADQCABLQAAIABBwdQAai0AAEcNFyAAQQVGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM6wELIANBADYCACAGQQFqIQFBGAwXCyABIARGBEBBpQEhAgzqAQsCQAJAIAEtAABByQBrDgcAGRkZGRkBGQsgAUEBaiEBQYsBIQIM0QELIAFBAWohAUGMASECDNABC0GkASECIAEgBEYN6AEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBptUAai0AAEcNFSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM6QELIANBADYCACAGQQFqIQFBCQwVC0GjASECIAEgBEYN5wEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBpNUAai0AAEcNFCAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM6AELIANBADYCACAGQQFqIQFBHwwUC0GiASECIAEgBEYN5gEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBvtQAai0AAEcNEyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM5wELIANBADYCACAGQQFqIQFBAgwTC0GhASECIAEgBEYN5QEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGA0AgAS0AACAAQbzUAGotAABHDREgAEEBRg0CIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADOUBCyABIARGBEBBoAEhAgzlAQtBASABLQAAQd8ARw0RGiABQQFqIQFBhwEhAgzLAQsgA0EANgIAIAZBAWohAUGIASECDMoBC0GfASECIAEgBEYN4gEgAygCACIAIAQgAWtqIQUgASAAa0EIaiEGAkADQCABLQAAIABBhNUAai0AAEcNDyAAQQhGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM4wELIANBADYCACAGQQFqIQFBKQwPC0GeASECIAEgBEYN4QEgAygCACIAIAQgAWtqIQUgASAAa0EDaiEGAkADQCABLQAAIABBuNQAai0AAEcNDiAAQQNGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM4gELIANBADYCACAGQQFqIQFBLQwOCyABIARGBEBBnQEhAgzhAQsgAS0AAEHFAEcNDiABQQFqIQFBhAEhAgzHAQsgASAERgRAQZwBIQIM4AELAkACQCABLQAAQcwAaw4IAA8PDw8PDwEPCyABQQFqIQFBggEhAgzHAQsgAUEBaiEBQYMBIQIMxgELQZsBIQIgASAERg3eASADKAIAIgAgBCABa2ohBSABIABrQQRqIQYCQANAIAEtAAAgAEGz1ABqLQAARw0LIABBBEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzfAQsgA0EANgIAIAZBAWohAUEjDAsLQZoBIQIgASAERg3dASADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGw1ABqLQAARw0KIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzeAQsgA0EANgIAIAZBAWohAUEADAoLIAEgBEYEQEGZASECDN0BCwJAAkAgAS0AAEHIAGsOCAAMDAwMDAwBDAsgAUEBaiEBQf0AIQIMxAELIAFBAWohAUGAASECDMMBCyABIARGBEBBmAEhAgzcAQsCQAJAIAEtAABBzgBrDgMACwELCyABQQFqIQFB/gAhAgzDAQsgAUEBaiEBQf8AIQIMwgELIAEgBEYEQEGXASECDNsBCyABLQAAQdkARw0IIAFBAWohAUEIDAcLQZYBIQIgASAERg3ZASADKAIAIgAgBCABa2ohBSABIABrQQNqIQYCQANAIAEtAAAgAEGs1ABqLQAARw0GIABBA0YNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzaAQsgA0EANgIAIAZBAWohAUEFDAYLQZUBIQIgASAERg3YASADKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEGm1ABqLQAARw0FIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzZAQsgA0EANgIAIAZBAWohAUEWDAULQZQBIQIgASAERg3XASADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGh1QBqLQAARw0EIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzYAQsgA0EANgIAIAZBAWohAUEQDAQLIAEgBEYEQEGTASECDNcBCwJAAkAgAS0AAEHDAGsODAAGBgYGBgYGBgYGAQYLIAFBAWohAUH5ACECDL4BCyABQQFqIQFB+gAhAgy9AQtBkgEhAiABIARGDdUBIAMoAgAiACAEIAFraiEFIAEgAGtBBWohBgJAA0AgAS0AACAAQaDUAGotAABHDQIgAEEFRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADNYBCyADQQA2AgAgBkEBaiEBQSQMAgsgA0EANgIADAILIAEgBEYEQEGRASECDNQBCyABLQAAQcwARw0BIAFBAWohAUETCzoAKSADKAIEIQAgA0EANgIEIAMgACABEC4iAA0CDAELQQAhAiADQQA2AhwgAyABNgIUIANB/h82AhAgA0EGNgIMDNEBC0H4ACECDLcBCyADQZABNgIcIAMgATYCFCADIAA2AgxBACECDM8BC0EAIQACQCADKAI4IgJFDQAgAigCQCICRQ0AIAMgAhEAACEACyAARQ0AIABBFUYNASADQQA2AhwgAyABNgIUIANBgg82AhAgA0EgNgIMQQAhAgzOAQtB9wAhAgy0AQsgA0GPATYCHCADIAE2AhQgA0HsGzYCECADQRU2AgxBACECDMwBCyABIARGBEBBjwEhAgzMAQsCQCABLQAAQSBGBEAgAUEBaiEBDAELIANBADYCHCADIAE2AhQgA0GbHzYCECADQQY2AgxBACECDMwBC0ECIQIMsgELA0AgAS0AAEEgRw0CIAQgAUEBaiIBRw0AC0GOASECDMoBCyABIARGBEBBjQEhAgzKAQsCQCABLQAAQQlrDgRKAABKAAtB9QAhAgywAQsgAy0AKUEFRgRAQfYAIQIMsAELQfQAIQIMrwELIAEgBEYEQEGMASECDMgBCyADQRA2AgggAyABNgIEDAoLIAEgBEYEQEGLASECDMcBCwJAIAEtAABBCWsOBEcAAEcAC0HzACECDK0BCyABIARHBEAgA0EQNgIIIAMgATYCBEHxACECDK0BC0GKASECDMUBCwJAIAEgBEcEQANAIAEtAABBoNAAai0AACIAQQNHBEACQCAAQQFrDgJJAAQLQfAAIQIMrwELIAQgAUEBaiIBRw0AC0GIASEC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BCABQQFqIgFHDQALQfsAIQIMpwELIAMoAgQhACADQQA2AgQgAyAAIAEQLCIARQ0DIANB2wA2AhwgAyABNgIUIAMgADYCDEEAIQIMpgELIAMoAgQhACADQQA2AgQgAyAAIAEQLCIARQ0DIANB3QA2AhwgAyABNgIUIAMgADYCDEEAIQIMpQELIAMoAgQhACADQQA2AgQgAyAAIAEQLCIARQ0DIANB+gA2AhwgAyABNgIUIAMgADYCDEEAIQIMpAELIANBADYCHCADIAE2AhQgA0G8CjYCECADQQc2AgxBACECDKMBC0HPACECDIkBC0HRACECDIgBC0HnACECDIcBCyABIARGBEBB+gAhAgygAQsCQCABLQAAQQlrDgQgAAAgAAsgAUEBaiEBQeYAIQIMhgELIAEgBEYEQEH5ACECDJ8BCwJAIAEtAABBCWsOBB8AAB8AC0EAIQACQCADKAI4IgJFDQAgAigCOCICRQ0AIAMgAhEAACEACyAARQRAQeIBIQIMhgELIABBFUcEQCADQQA2AhwgAyABNgIUIANByQ02AhAgA0EaNgIMQQAhAgyfAQsgA0H4ADYCHCADIAE2AhQgA0HqGjYCECADQRU2AgxBACECDJ4BCyABIARHBEAgA0ENNgIIIAMgATYCBEHkACECDIUBC0H3ACECDJ0BCyABIARGBEBB9gAhAgydAQsCQAJAAkAgAS0AAEHIAGsOCwABCwsLCwsLCwsCCwsgAUEBaiEBQd0AIQIMhQELIAFBAWohAUHgACECDIQBCyABQQFqIQFB4wAhAgyDAQtB9QAhAiABIARGDZsBIAMoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQbXVAGotAABHDQggAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADJwBCyADKAIEIQAgA0IANwMAIAMgACAGQQFqIgEQKyIABEAgA0H0ADYCHCADIAE2AhQgAyAANgIMQQAhAgycAQtB4gAhAgyCAQtBACEAAkAgAygCOCICRQ0AIAIoAjQiAkUNACADIAIRAAAhAAsCQCAABEAgAEEVRg0BIANBADYCHCADIAE2AhQgA0HqDTYCECADQSY2AgxBACECDJwBC0HhACECDIIBCyADQfMANgIcIAMgATYCFCADQYAbNgIQIANBFTYCDEEAIQIMmgELIAMtACkiAEEja0ELSQ0JAkAgAEEGSw0AQQEgAHRBygBxRQ0ADAoLQQAhAiADQQA2AhwgAyABNgIUIANB7Qk2AhAgA0EINgIMDJkBC0HyACECIAEgBEYNmAEgAygCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBs9UAai0AAEcNBSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMmQELIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARArIgAEQCADQfEANgIcIAMgATYCFCADIAA2AgxBACECDJkBC0HfACECDH8LQQAhAAJAIAMoAjgiAkUNACACKAI0IgJFDQAgAyACEQAAIQALAkAgAARAIABBFUYNASADQQA2AhwgAyABNgIUIANB6g02AhAgA0EmNgIMQQAhAgyZAQtB3gAhAgx/CyADQfAANgIcIAMgATYCFCADQYAbNgIQIANBFTYCDEEAIQIMlwELIAMtAClBIUYNBiADQQA2AhwgAyABNgIUIANBkQo2AhAgA0EINgIMQQAhAgyWAQtB7wAhAiABIARGDZUBIAMoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQbDVAGotAABHDQIgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADJYBCyADKAIEIQAgA0IANwMAIAMgACAGQQFqIgEQKyIARQ0CIANB7QA2AhwgAyABNgIUIAMgADYCDEEAIQIMlQELIANBADYCAAsgAygCBCEAIANBADYCBCADIAAgARArIgBFDYABIANB7gA2AhwgAyABNgIUIAMgADYCDEEAIQIMkwELQdwAIQIMeQtBACEAAkAgAygCOCICRQ0AIAIoAjQiAkUNACADIAIRAAAhAAsCQCAABEAgAEEVRg0BIANBADYCHCADIAE2AhQgA0HqDTYCECADQSY2AgxBACECDJMBC0HbACECDHkLIANB7AA2AhwgAyABNgIUIANBgBs2AhAgA0EVNgIMQQAhAgyRAQsgAy0AKSIAQSNJDQAgAEEuRg0AIANBADYCHCADIAE2AhQgA0HJCTYCECADQQg2AgxBACECDJABC0HaACECDHYLIAEgBEYEQEHrACECDI8BCwJAIAEtAABBL0YEQCABQQFqIQEMAQsgA0EANgIcIAMgATYCFCADQbI4NgIQIANBCDYCDEEAIQIMjwELQdkAIQIMdQsgASAERwRAIANBDjYCCCADIAE2AgRB2AAhAgx1C0HqACECDI0BCyABIARGBEBB6QAhAgyNAQsgAS0AAEEwayIAQf8BcUEKSQRAIAMgADoAKiABQQFqIQFB1wAhAgx0CyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNeiADQegANgIcIAMgATYCFCADIAA2AgxBACECDIwBCyABIARGBEBB5wAhAgyMAQsCQCABLQAAQS5GBEAgAUEBaiEBDAELIAMoAgQhACADQQA2AgQgAyAAIAEQLyIARQ17IANB5gA2AhwgAyABNgIUIAMgADYCDEEAIQIMjAELQdYAIQIMcgsgASAERgRAQeUAIQIMiwELQQAhAEEBIQVBASEHQQAhAgJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAIAEtAABBMGsOCgoJAAECAwQFBggLC0ECDAYLQQMMBQtBBAwEC0EFDAMLQQYMAgtBBwwBC0EICyECQQAhBUEAIQcMAgtBCSECQQEhAEEAIQVBACEHDAELQQAhBUEBIQILIAMgAjoAKyABQQFqIQECQAJAIAMtAC5BEHENAAJAAkACQCADLQAqDgMBAAIECyAHRQ0DDAILIAANAQwCCyAFRQ0BCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNAiADQeIANgIcIAMgATYCFCADIAA2AgxBACECDI0BCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNfSADQeMANgIcIAMgATYCFCADIAA2AgxBACECDIwBCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNeyADQeQANgIcIAMgATYCFCADIAA2AgwMiwELQdQAIQIMcQsgAy0AKUEiRg2GAUHTACECDHALQQAhAAJAIAMoAjgiAkUNACACKAJEIgJFDQAgAyACEQAAIQALIABFBEBB1QAhAgxwCyAAQRVHBEAgA0EANgIcIAMgATYCFCADQaQNNgIQIANBITYCDEEAIQIMiQELIANB4QA2AhwgAyABNgIUIANB0Bo2AhAgA0EVNgIMQQAhAgyIAQsgASAERgRAQeAAIQIMiAELAkACQAJAAkACQCABLQAAQQprDgQBBAQABAsgAUEBaiEBDAELIAFBAWohASADQS9qLQAAQQFxRQ0BC0HSACECDHALIANBADYCHCADIAE2AhQgA0G2ETYCECADQQk2AgxBACECDIgBCyADQQA2AhwgAyABNgIUIANBthE2AhAgA0EJNgIMQQAhAgyHAQsgASAERgRAQd8AIQIMhwELIAEtAABBCkYEQCABQQFqIQEMCQsgAy0ALkHAAHENCCADQQA2AhwgAyABNgIUIANBthE2AhAgA0ECNgIMQQAhAgyGAQsgASAERgRAQd0AIQIMhgELIAEtAAAiAkENRgRAIAFBAWohAUHQACECDG0LIAEhACACQQlrDgQFAQEFAQsgBCABIgBGBEBB3AAhAgyFAQsgAC0AAEEKRw0AIABBAWoMAgtBACECIANBADYCHCADIAA2AhQgA0HKLTYCECADQQc2AgwMgwELIAEgBEYEQEHbACECDIMBCwJAIAEtAABBCWsOBAMAAAMACyABQQFqCyEBQc4AIQIMaAsgASAERgRAQdoAIQIMgQELIAEtAABBCWsOBAABAQABC0EAIQIgA0EANgIcIANBmhI2AhAgA0EHNgIMIAMgAUEBajYCFAx/CyADQYASOwEqQQAhAAJAIAMoAjgiAkUNACACKAI4IgJFDQAgAyACEQAAIQALIABFDQAgAEEVRw0BIANB2QA2AhwgAyABNgIUIANB6ho2AhAgA0EVNgIMQQAhAgx+C0HNACECDGQLIANBADYCHCADIAE2AhQgA0HJDTYCECADQRo2AgxBACECDHwLIAEgBEYEQEHZACECDHwLIAEtAABBIEcNPSABQQFqIQEgAy0ALkEBcQ09IANBADYCHCADIAE2AhQgA0HCHDYCECADQR42AgxBACECDHsLIAEgBEYEQEHYACECDHsLAkACQAJAAkACQCABLQAAIgBBCmsOBAIDAwABCyABQQFqIQFBLCECDGULIABBOkcNASADQQA2AhwgAyABNgIUIANB5xE2AhAgA0EKNgIMQQAhAgx9CyABQQFqIQEgA0Evai0AAEEBcUUNcyADLQAyQYABcUUEQCADQTJqIQIgAxA1QQAhAAJAIAMoAjgiBkUNACAGKAIoIgZFDQAgAyAGEQAAIQALAkACQCAADhZNTEsBAQEBAQEBAQEBAQEBAQEBAQEAAQsgA0EpNgIcIAMgATYCFCADQawZNgIQIANBFTYCDEEAIQIMfgsg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c3BvbnNlIHN0YXR1cwBFeHBlY3RlZCBMRiBhZnRlciBoZWFkZXJzAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMAVXNlciBjYWxsYmFjayBlcnJvcgBgb25fcmVzZXRgIGNhbGxiYWNrIGVycm9yAGBvbl9jaHVua19oZWFkZXJgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXNzYWdlX2JlZ2luYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlYCBjYWxsYmFjayBlcnJvcgBgb25fc3RhdHVzX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fdmVyc2lvbl9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX3VybF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX3Byb3RvY29sX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9oZWFkZXJfdmFsdWVfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXNzYWdlX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fbWV0aG9kX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25faGVhZGVyX2ZpZWxkX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfZXh0ZW5zaW9uX25hbWVgIGNhbGxiYWNrIGVycm9yAFVuZXhwZWN0ZWQgY2hhciBpbiB1cmwgc2VydmVyAEludmFsaWQgaGVhZGVyIHZhbHVlIGNoYXIASW52YWxpZCBoZWFkZXIgZmllbGQgY2hhcgBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3ZlcnNpb24ASW52YWxpZCBtaW5vciB2ZXJzaW9uAEludmFsaWQgbWFqb3IgdmVyc2lvbgBFeHBlY3RlZCBzcGFjZSBhZnRlciB2ZXJzaW9uAEV4cGVjdGVkIENSTEYgYWZ0ZXIgdmVyc2lvbgBJbnZhbGlkIEhUVFAgdmVyc2lvbgBJbnZhbGlkIGhlYWRlciB0b2tlbgBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3VybABJbnZhbGlkIGNoYXJhY3RlcnMgaW4gdXJsAFVuZXhwZWN0ZWQgc3RhcnQgY2hhciBpbiB1cmwARG91YmxlIEAgaW4gdXJsAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fcHJvdG9jb2wARW1wdHkgQ29udGVudC1MZW5ndGgASW52YWxpZCBjaGFyYWN0ZXIgaW4gQ29udGVudC1MZW5ndGgAVHJhbnNmZXItRW5jb2RpbmcgY2FuJ3QgYmUgcHJlc2VudCB3aXRoIENvbnRlbnQtTGVuZ3RoAER1cGxpY2F0ZSBDb250ZW50LUxlbmd0aABJbnZhbGlkIGNoYXIgaW4gdXJsIHBhdGgAQ29udGVudC1MZW5ndGggY2FuJ3QgYmUgcHJlc2VudCB3aXRoIFRyYW5zZmVyLUVuY29kaW5nAE1pc3NpbmcgZXhwZWN0ZWQgQ1IgYWZ0ZXIgY2h1bmsgc2l6ZQBFeHBlY3RlZCBMRiBhZnRlciBjaHVuayBzaXplAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIHNpemUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfdmFsdWUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9jaHVua19leHRlbnNpb25fdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyB2YWx1ZQBVbmV4cGVjdGVkIHdoaXRlc3BhY2UgYWZ0ZXIgaGVhZGVyIHZhbHVlAE1pc3NpbmcgZXhwZWN0ZWQgQ1IgYWZ0ZXIgaGVhZGVyIHZhbHVlAE1pc3NpbmcgZXhwZWN0ZWQgTEYgYWZ0ZXIgaGVhZGVyIHZhbHVlAEludmFsaWQgYFRyYW5zZmVyLUVuY29kaW5nYCBoZWFkZXIgdmFsdWUATWlzc2luZyBleHBlY3RlZCBDUiBhZnRlciBjaHVuayBleHRlbnNpb24gdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyBxdW90ZSB2YWx1ZQBJbnZhbGlkIHF1b3RlZC1wYWlyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGVkIHZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGVkIHZhbHVlAFBhdXNlZCBieSBvbl9oZWFkZXJzX2NvbXBsZXRlAEludmFsaWQgRU9GIHN0YXRlAG9uX3Jlc2V0IHBhdXNlAG9uX2NodW5rX2hlYWRlciBwYXVzZQBvbl9tZXNzYWdlX2JlZ2luIHBhdXNlAG9uX2NodW5rX2V4dGVuc2lvbl92YWx1ZSBwYXVzZQBvbl9zdGF0dXNfY29tcGxldGUgcGF1c2UAb25fdmVyc2lvbl9jb21wbGV0ZSBwYXVzZQBvbl91cmxfY29tcGxldGUgcGF1c2UAb25fcHJvdG9jb2xfY29tcGxldGUgcGF1c2UAb25fY2h1bmtfY29tcGxldGUgcGF1c2UAb25faGVhZGVyX3ZhbHVlX2NvbXBsZXRlIHBhdXNlAG9uX21lc3NhZ2VfY29tcGxldGUgcGF1c2UAb25fbWV0aG9kX2NvbXBsZXRlIHBhdXNlAG9uX2hlYWRlcl9maWVsZF9jb21wbGV0ZSBwYXVzZQBvbl9jaHVua19leHRlbnNpb25fbmFtZSBwYXVzZQBVbmV4cGVjdGVkIHNwYWNlIGFmdGVyIHN0YXJ0IGxpbmUATWlzc2luZyBleHBlY3RlZCBDUiBhZnRlciByZXNwb25zZSBsaW5lAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fY2h1bmtfZXh0ZW5zaW9uX25hbWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyBuYW1lAE1pc3NpbmcgZXhwZWN0ZWQgQ1IgYWZ0ZXIgY2h1bmsgZXh0ZW5zaW9uIG5hbWUASW52YWxpZCBzdGF0dXMgY29kZQBQYXVzZSBvbiBDT05ORUNUL1VwZ3JhZGUAUGF1c2Ugb24gUFJJL1VwZ3JhZGUARXhwZWN0ZWQgSFRUUC8yIENvbm5lY3Rpb24gUHJlZmFjZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX21ldGhvZABFeHBlY3RlZCBzcGFjZSBhZnRlciBtZXRob2QAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfZmllbGQAUGF1c2VkAEludmFsaWQgd29yZCBlbmNvdW50ZXJlZABJbnZhbGlkIG1ldGhvZCBlbmNvdW50ZXJlZABNaXNzaW5nIGV4cGVjdGVkIENSIGFmdGVyIGNodW5rIGRhdGEARXhwZWN0ZWQgTEYgYWZ0ZXIgY2h1bmsgZGF0YQBVbmV4cGVjdGVkIGNoYXIgaW4gdXJsIHNjaGVtYQBSZXF1ZXN0IGhhcyBpbnZhbGlkIGBUcmFuc2Zlci1FbmNvZGluZ2AARGF0YSBhZnRlciBgQ29ubmVjdGlvbjogY2xvc2VgAFNXSVRDSF9QUk9YWQBVU0VfUFJPWFkATUtBQ1RJVklUWQBVTlBST0NFU1NBQkxFX0VOVElUWQBRVUVSWQBDT1BZAE1PVkVEX1BFUk1BTkVOVExZAFRPT19FQVJMWQBOT1RJRlkARkFJTEVEX0RFUEVOREVOQ1kAQkFEX0dBVEVXQVkAUExBWQBQVVQAQ0hFQ0tPVVQAR0FURVdBWV9USU1FT1VUAFJFUVVFU1RfVElNRU9VVABORVRXT1JLX0NPTk5FQ1RfVElNRU9VVABDT05ORUNUSU9OX1RJTUVPVVQATE9HSU5fVElNRU9VVABORVRXT1JLX1JFQURfVElNRU9VVABQT1NUAE1JU0RJUkVDVEVEX1JFUVVFU1QAQ0xJRU5UX0NMT1NFRF9SRVFVRVNUAENMSUVOVF9DTE9TRURfTE9BRF9CQUxBTkNFRF9SRVFVRVNUAEJBRF9SRVFVRVNUAEhUVFBfUkVRVUVTVF9TRU5UX1RPX0hUVFBTX1BPUlQAUkVQT1JUAElNX0FfVEVBUE9UAFJFU0VUX0NPTlRFTlQATk9fQ09OVEVOVABQQVJUSUFMX0NPTlRFTlQASFBFX0lOVkFMSURfQ09OU1RBTlQASFBFX0NCX1JFU0VUAEdFVABIUEVfU1RSSUNUAENPTkZMSUNUAFRFTVBPUkFSWV9SRURJUkVDVABQRVJNQU5FTlRfUkVESVJFQ1QAQ09OTkVDVABNVUxUSV9TVEFUVVMASFBFX0lOVkFMSURfU1RBVFVTAFRPT19NQU5ZX1JFUVVFU1RTAEVBUkxZX0hJTlRTAFVOQVZBSUxBQkxFX0ZPUl9MRUdBTF9SRUFTT05TAE9QVElPTlMAU1dJVENISU5HX1BST1RPQ09MUwBWQVJJQU5UX0FMU09fTkVHT1RJQVRFUwBNVUxUSVBMRV9DSE9JQ0VTAElOVEVSTkFMX1NFUlZFUl9FUlJPUgBXRUJfU0VSVkVSX1VOS05PV05fRVJST1IAUkFJTEdVTl9FUlJPUgBJREVOVElUWV9QUk9WSURFUl9BVVRIRU5USUNBVElPTl9FUlJPUgBTU0xfQ0VSVElGSUNBVEVfRVJST1IASU5WQUxJRF9YX0ZPUldBUkRFRF9GT1IAU0VUX1BBUkFNRVRFUgBHRVRfUEFSQU1FVEVSAEhQRV9VU0VSAFNFRV9PVEhFUgBIUEVfQ0JfQ0hVTktfSEVBREVSAEV4cGVjdGVkIExGIGFmdGVyIENSAE1LQ0FMRU5EQVIAU0VUVVAAV0VCX1NFUlZFUl9JU19ET1dOAFRFQVJET1dOAEhQRV9DTE9TRURfQ09OTkVDVElPTgBIRVVSSVNUSUNfRVhQSVJBVElPTgBESVNDT05ORUNURURfT1BFUkFUSU9OAE5PTl9BVVRIT1JJVEFUSVZFX0lORk9STUFUSU9OAEhQRV9JTlZBTElEX1ZFUlNJT04ASFBFX0NCX01FU1NBR0VfQkVHSU4AU0lURV9JU19GUk9aRU4ASFBFX0lOVkFMSURfSEVBREVSX1RPS0VOAElOVkFMSURfVE9LRU4ARk9SQklEREVOAEVOSEFOQ0VfWU9VUl9DQUxNAEhQRV9JTlZBTElEX1VSTABCTE9DS0VEX0JZX1BBUkVOVEFMX0NPTlRST0wATUtDT0wAQUNMAEhQRV9JTlRFUk5BTABSRVFVRVNUX0hFQURFUl9GSUVMRFNfVE9PX0xBUkdFX1VOT0ZGSUNJQUwASFBFX09LAFVOTElOSwBVTkxPQ0sAUFJJAFJFVFJZX1dJVEgASFBFX0lOVkFMSURfQ09OVEVOVF9MRU5HVEgASFBFX1VORVhQRUNURURfQ09OVEVOVF9MRU5HVEgARkxVU0gAUFJPUFBBVENIAE0tU0VBUkNIAFVSSV9UT09fTE9ORwBQUk9DRVNTSU5HAE1JU0NFTExBTkVPVVNfUEVSU0lTVEVOVF9XQVJOSU5HAE1JU0NFTExBTkVPVVNfV0FSTklORwBIUEVfSU5WQUxJRF9UUkFOU0ZFUl9FTkNPRElORwBFeHBlY3RlZCBDUkxGAEhQRV9JTlZBTElEX0NIVU5LX1NJWkUATU9WRQBDT05USU5VRQBIUEVfQ0JfU1RBVFVTX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJTX0NPTVBMRVRFAEhQRV9DQl9WRVJTSU9OX0NPTVBMRVRFAEhQRV9DQl9VUkxfQ09NUExFVEUASFBFX0NCX1BST1RPQ09MX0NPTVBMRVRFAEhQRV9DQl9DSFVOS19DT01QTEVURQBIUEVfQ0JfSEVBREVSX1ZBTFVFX0NPTVBMRVRFAEhQRV9DQl9DSFVOS19FWFRFTlNJT05fVkFMVUVfQ09NUExFVEUASFBFX0NCX0NIVU5LX0VYVEVOU0lPTl9OQU1FX0NPTVBMRVRFAEhQRV9DQl9NRVNTQUdFX0NPTVBMRVRFAEhQRV9DQl9NRVRIT0RfQ09NUExFVEUASFBFX0NCX0hFQURFUl9GSUVMRF9DT01QTEVURQBERUxFVEUASFBFX0lOVkFMSURfRU9GX1NUQVRFAElOVkFMSURfU1NMX0NFUlRJRklDQVRFAFBBVVNFAE5PX1JFU1BPTlNFAFVOU1VQUE9SVEVEX01FRElBX1RZUEUAR09ORQBOT1RfQUNDRVBUQUJMRQBTRVJWSUNFX1VOQVZBSUxBQkxFAFJBTkdFX05PVF9TQVRJU0ZJQUJMRQBPUklHSU5fSVNfVU5SRUFDSEFCTEUAUkVTUE9OU0VfSVNfU1RBTEUAUFVSR0UATUVSR0UAUkVRVUVTVF9IRUFERVJfRklFTERTX1RPT19MQVJHRQBSRVFVRVNUX0hFQURFUl9UT09fTEFSR0UAUEFZTE9BRF9UT09fTEFSR0UASU5TVUZGSUNJRU5UX1NUT1JBR0UASFBFX1BBVVNFRF9VUEdSQURFAEhQRV9QQVVTRURfSDJfVVBHUkFERQBTT1VSQ0UAQU5OT1VOQ0UAVFJBQ0UASFBFX1VORVhQRUNURURfU1BBQ0UAREVTQ1JJQkUAVU5TVUJTQ1JJQkUAUkVDT1JEAEhQRV9JTlZBTElEX01FVEhPRABOT1RfRk9VTkQAUFJPUEZJTkQAVU5CSU5EAFJFQklORABVTkFVVEhPUklaRUQATUVUSE9EX05PVF9BTExPV0VEAEhUVFBfVkVSU0lPTl9OT1RfU1VQUE9SVEVEAEFMUkVBRFlfUkVQT1JURUQAQUNDRVBURUQATk9UX0lNUExFTUVOVEVEAExPT1BfREVURUNURUQASFBFX0NSX0VYUEVDVEVEAEhQRV9MRl9FWFBFQ1RFRABDUkVBVEVEAElNX1VTRUQASFBFX1BBVVNFRABUSU1FT1VUX09DQ1VSRUQAUEFZTUVOVF9SRVFVSVJFRABQUkVDT05ESVRJT05fUkVRVUlSRUQAUFJPWFlfQVVUSEVOVElDQVRJT05fUkVRVUlSRUQATkVUV09SS19BVVRIRU5USUNBVElPTl9SRVFVSVJFRABMRU5HVEhfUkVRVUlSRUQAU1NMX0NFUlRJRklDQVRFX1JFUVVJUkVEAFVQR1JBREVfUkVRVUlSRUQAUEFHRV9FWFBJUkVEAFBSRUNPTkRJVElPTl9GQUlMRUQARVhQRUNUQVRJT05fRkFJTEVEAFJFVkFMSURBVElPTl9GQUlMRUQAU1NMX0hBTkRTSEFLRV9GQUlMRUQATE9DS0VEAFRSQU5TRk9STUFUSU9OX0FQUExJRUQATk9UX01PRElGSUVEAE5PVF9FWFRFTkRFRABCQU5EV0lEVEhfTElNSVRfRVhDRUVERUQAU0lURV9JU19PVkVSTE9BREVEAEhFQUQARXhwZWN0ZWQgSFRUUC8sIFJUU1AvIG9yIElDRS8A5xUAAK8VAACkEgAAkhoAACYWAACeFAAA2xkAAHkVAAB+EgAA/hQAADYVAAALFgAA2BYAAPMSAABCGAAArBYAABIVAAAUFwAA7xcAAEgUAABxFwAAshoAAGsZAAB+GQAANRQAAIIaAABEFwAA/RYAAB4YAACHFwAAqhkAAJMSAAAHGAAALBcAAMoXAACkFwAA5xUAAOcVAABYFwAAOxgAAKASAAAtHAAAwxEAAEgRAADeEgAAQhMAAKQZAAD9EAAA9xUAAKUVAADvFgAA+BkAAEoWAABWFgAA9RUAAAoaAAAIGgAAARoAAKsVAABCEgAA1xAAAEwRAAAFGQAAVBYAAB4RAADKGQAAyBkAAE4WAAD/GAAAcRQAAPAVAADuFQAAlBkAAPwVAAC/GQAAmxkAAHwUAABDEQAAcBgAAJUUAAAnFAAAGRQAANUSAADUGQAARBYAAPcQAEG5OwsBAQBB0DsL4AEBAQIBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQBBuj0LBAEAAAIAQdE9C14DBAMDAwMDAAADAwADAwADAwMDAwMDAwMDAAUAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAwADAEG6PwsEAQAAAgBB0T8LXgMAAwMDAwMAAAMDAAMDAAMDAwMDAwMDAwMABAAFAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwADAAMAQbDBAAsNbG9zZWVlcC1hbGl2ZQBBycEACwEBAEHgwQAL4AEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQBBycMACwEBAEHgwwAL5wEBAQEBAQEBAQEBAQECAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAWNodW5rZWQAQfHFAAteAQABAQEBAQAAAQEAAQEAAQEBAQEBAQEBAQAAAAAAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEAAQBB0McACyFlY3Rpb25lbnQtbGVuZ3Rob25yb3h5LWNvbm5lY3Rpb24AQYDIAAsgcmFuc2Zlci1lbmNvZGluZ3BncmFkZQ0KDQpTTQ0KDQoAQanIAAsFAQIAAQMAQcDIAAtfBAUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUAQanKAAsFAQIAAQMAQcDKAAtfBAUFBgUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUAQanMAAsEAQAAAQBBwcwAC14CAgACAgICAgICAgICAgICAgICAgICAgICAgICAgIAAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAEGpzgALBQECAAEDAEHAzgALXwQFAAAFBQUFBQUFBQUFBQYFBQUFBQUFBQUFBQUABQAHCAUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQAFAAUABQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUAAAAFAEGp0AALBQEBAAEBAEHA0AALAQEAQdrQAAtBAgAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAQanSAAsFAQEAAQEAQcDSAAsBAQBBytIACwYCAAAAAAIAQeHSAAs6AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwBBoNQAC50BTk9VTkNFRUNLT1VUTkVDVEVURUNSSUJFTFVTSEVURUFEU0VBUkNIUkdFQ1RJVklUWUxFTkRBUlZFT1RJRllQVElPTlNDSFNFQVlTVEFUQ0hHRVVFUllPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFVFRQQ0VUU1BBRFRQLw==";
+ var wasmBuffer;
+ Object.defineProperty(module2, "exports", {
+ get: /* @__PURE__ */ __name(() => {
+ return wasmBuffer ? wasmBuffer : wasmBuffer = Buffer2.from(wasmBase64, "base64");
+ }, "get")
+ });
+ }
+});
+
+// node_modules/undici/lib/llhttp/llhttp_simd-wasm.js
+var require_llhttp_simd_wasm = __commonJS({
+ "node_modules/undici/lib/llhttp/llhttp_simd-wasm.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { Buffer: Buffer2 } = __require("node:buffer");
+ var wasmBase64 = "AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAn9/AGABfwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAAzU0BQYAAAMAAAAAAAADAQMAAwMDAAACAAAAAAICAgICAgICAgIBAQEBAQEBAQEBAwAAAwAAAAQFAXABExMFAwEAAgYIAX8BQcDZBAsHxQcoBm1lbW9yeQIAC19pbml0aWFsaXplAAgZX19pbmRpcmVjdF9mdW5jdGlvbl90YWJsZQEAC2xsaHR0cF9pbml0AAkYbGxodHRwX3Nob3VsZF9rZWVwX2FsaXZlADcMbGxodHRwX2FsbG9jAAsGbWFsbG9jADkLbGxodHRwX2ZyZWUADARmcmVlAAwPbGxodHRwX2dldF90eXBlAA0VbGxodHRwX2dldF9odHRwX21ham9yAA4VbGxodHRwX2dldF9odHRwX21pbm9yAA8RbGxodHRwX2dldF9tZXRob2QAEBZsbGh0dHBfZ2V0X3N0YXR1c19jb2RlABESbGxodHRwX2dldF91cGdyYWRlABIMbGxodHRwX3Jlc2V0ABMObGxodHRwX2V4ZWN1dGUAFBRsbGh0dHBfc2V0dGluZ3NfaW5pdAAVDWxsaHR0cF9maW5pc2gAFgxsbGh0dHBfcGF1c2UAFw1sbGh0dHBfcmVzdW1lABgbbGxodHRwX3Jlc3VtZV9hZnRlcl91cGdyYWRlABkQbGxodHRwX2dldF9lcnJubwAaF2xsaHR0cF9nZXRfZXJyb3JfcmVhc29uABsXbGxodHRwX3NldF9lcnJvcl9yZWFzb24AHBRsbGh0dHBfZ2V0X2Vycm9yX3BvcwAdEWxsaHR0cF9lcnJub19uYW1lAB4SbGxodHRwX21ldGhvZF9uYW1lAB8SbGxodHRwX3N0YXR1c19uYW1lACAabGxodHRw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AXRrQT5qIQILIAEgAjYCHCABQgA3AhAgAkECdEH01wBqIQACQEHI1QAoAgAiA0EBIAJ0IgdxRQRAIAAgATYCAEHI1QAgAyAHcjYCACABIAA2AhggASABNgIIIAEgATYCDAwBCyAEQRkgAkEBdmtBACACQR9HG3QhAiAAKAIAIQACQANAIAAiAygCBEF4cSAERg0BIAJBHXYhACACQQF0IQIgAyAAQQRxakEQaiIHKAIAIgANAAsgByABNgIAIAEgAzYCGCABIAE2AgwgASABNgIIDAELIAMoAggiACABNgIMIAMgATYCCCABQQA2AhggASADNgIMIAEgADYCCAtB5NUAQeTVACgCAEEBayIAQX8gABs2AgALCwcAIAAtACgLBwAgAC0AKgsHACAALQArCwcAIAAtACkLBwAgAC8BNAsHACAALQAwC0ABBH8gACgCGCEBIAAvAS4hAiAALQAoIQMgACgCOCEEIAAQOCAAIAQ2AjggACADOgAoIAAgAjsBLiAAIAE2AhgLhocCAwd/A34BeyABIAJqIQQCQCAAIgMoAgwiAA0AIAMoAgQEQCADIAE2AgQLIwBBEGsiCSQAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAC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DAgLQeMBDAcLQdcBDAYLQdgBDAULQdkBDAQLQdoBDAMLQdsBDAILQd0BDAELQdwBCyECA0ACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAMCfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAn8CQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAwJ/AkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJ/AkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAC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A0EXNgIcIAMgADYCDCADIAFBAWo2AhQM+AILIABBFUYNI0EAIQIgA0EANgIcIAMgATYCFCADQdYMNgIQIANBIzYCDAz3AgsgAygCBCEAQQAhAiADQQA2AgQgAyAAIAEQNCIARQRAIAFBAWohAQwdCyADQRk2AhwgAyAANgIMIAMgAUEBajYCFAz2AgsgAygCBCEAQQAhAiADQQA2AgQgAyAAIAEQNCIARQRAIAFBAWohAQzvAgsgA0EaNgIcIAMgADYCDCADIAFBAWo2AhQM9QILIABBFUYNH0EAIQIgA0EANgIcIAMgATYCFCADQdAPNgIQIANBIjYCDAz0AgsgAygCBCEAIANBADYCBCADIAAgARAzIgBFBEAgAUEBaiEBDBsLIANBHDYCHCADIAA2AgwgAyABQQFqNgIUQQAhAgzzAgsgAygCBCEAIANBADYCBCADIAAgARAzIgBFBEAgAUEBaiEBDOsCCyADQR02AhwgAyAANgIMIAMgAUEBajYCFEEAIQIM8gILIABBO0cNASABQQFqIQELQSYhAgzXAgtBACECIANBADYCHCADIAE2AhQgA0GfFTYCECADQQw2AgwM7wILIAEgBEcEQANAIAEtAABBIEcNhAIgBCABQQFqIgFHDQALQSwhAgzvAgtBLCECDO4CCyABIARGBEBBNCECDO4CCwJAAkADQAJAIAEtAABBCmsOBAIAAAMACyAEIAFBAWoiAUcNAAtBNCECDO8CCyADKAIEIQAgA0EANgIEIAMgACABEDEiAEUNnwIgA0EyNgIcIAMgATYCFCADIAA2AgxBACECDO4CCyADKAIEIQAgA0EANgIEIAMgACABEDEiAEUEQCABQQFqIQEMnwILIANBMjYCHCADIAA2AgwgAyABQQFqNgIUQQAhAgztAgsgASAERwRAAkADQCABLQAAQTBrIgBB/wFxQQpPBEBBOiECDNcCCyADKQMgIgtCmbPmzJmz5swZVg0BIAMgC0IKfiIKNwMgIAogAK1C/wGDIgtCf4VWDQEgAyAKIAt8NwMgIAQgAUEBaiIBRw0AC0HAACECDO4CCyADKAIEIQAgA0EANgIEIAMgACABQQFqIgEQMSIADRcM4gILQcAAIQIM7AILIAEgBEYEQEHJACECDOwCCwJAA0ACQCABLQAAQQlrDhgAAqICogKpAqICogKiAqICogKiAqICogKiAqICogKiAqICogKiAqICogKiAgCiAgsgBCABQQFqIgFHDQALQckAIQIM7AILIAFBAWohASADQS9qLQAAQQFxDaUCIANBADYCHCADIAE2AhQgA0GXEDYCECADQQo2AgxBACECDOsCCyABIARHBEADQCABLQAAQSBHDRUgBCABQQFqIgFHDQALQfgAIQIM6wILQfgAIQIM6gILIANBAjoAKAw4C0EAIQIgA0EANgIcIANBvws2AhAgA0ECNgIMIAMgAUEBajYCFAzoAgtBACECDM4CC0ENIQIMzQILQRMhAgzMAgtBFSECDMsCC0EWIQIMygILQRghAgzJAgtBGSECDMgCC0EaIQIMxwILQRshAgzGAgtBHCECDMUCC0EdIQIMxAILQR4hAgzDAgtBHyECDMICC0EgIQIMwQILQSIhAgzAAgtBIyECDL8CC0ElIQIMvgILQeUAIQIMvQILIANBPTYCHCADIAE2AhQgAyAANgIMQQAhAgzVAgsgA0EbNgIcIAMgATYCFCADQaQcNgIQIANBFTYCDEEAIQIM1AILIANBIDYCHCADIAE2AhQgA0GYGjYCECADQRU2AgxBACECDNMCCyADQRM2AhwgAyABNgIUIANBmBo2AhAgA0EVNgIMQQAhAgzSAgsgA0ELNgIcIAMgATYCFCADQZgaNgIQIANBFTYCDEEAIQIM0QILIANBEDYCHCADIAE2AhQgA0GYGjYCECADQRU2AgxBACECDNACCyADQSA2AhwgAyABNgIUIANBpBw2AhAgA0EVNgIMQQAhAgzPAgsgA0ELNgIcIAMgATYCFCADQaQcNgIQIANBFTYCDEEAIQIMzgILIANBDDYCHCADIAE2AhQgA0GkHDYCECADQRU2AgxBACECDM0CC0EAIQIgA0EANgIcIAMgATYCFCADQd0ONgIQIANBEjYCDAzMAgsCQANAAkAgAS0AAEEKaw4EAAICAAILIAQgAUEBaiIBRw0AC0H9ASECDMwCCwJAAkAgAy0ANkEBRw0AQQAhAAJAIAMoAjgiAkUNACACKAJgIgJFDQAgAyACEQAAIQALIABFDQAgAEEVRw0BIANB/AE2AhwgAyABNgIUIANB3Bk2AhAgA0EVNgIMQQAhAgzNAgtB3AEhAgyzAgsgA0EANgIcIAMgATYCFCADQfkLNgIQIANBHzYCDEEAIQIMywILAkACQCADLQAoQQFrDgIEAQALQdsBIQIMsgILQdQBIQIMsQILIANBAjoAMUEAIQACQCADKAI4IgJFDQAgAigCACICRQ0AIAMgAhEAACEACyAARQRAQd0BIQIMsQILIABBFUcEQCADQQA2AhwgAyABNgIUIANBtAw2AhAgA0EQNgIMQQAhAgzKAgsgA0H7ATYCHCADIAE2AhQgA0GBGjYCECADQRU2AgxBACECDMkCCyABIARGBEBB+gEhAgzJAgsgAS0AAEHIAEYNASADQQE6ACgLQcABIQIMrgILQdoBIQIMrQILIAEgBEcEQCADQQw2AgggAyABNgIEQdkBIQIMrQILQfkBIQIMxQILIAEgBEYEQEH4ASECDMUCCyABLQAAQcgARw0EIAFBAWohAUHYASECDKsCCyABIARGBEBB9wEhAgzEAgsCQAJAIAEtAABBxQBrDhAABQUFBQUFBQUFBQUFBQUBBQsgAUEBaiEBQdYBIQIMqwILIAFBAWohAUHXASECDKoCC0H2ASECIAEgBEYNwgIgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABButUAai0AAEcNAyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMwwILIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARAuIgBFBEBB4wEhAgyqAgsgA0H1ATYCHCADIAE2AhQgAyAANgIMQQAhAgzCAgtB9AEhAiABIARGDcECIAMoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQbjVAGotAABHDQIgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADMICCyADQYEEOwEoIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARAuIgANAwwCCyADQQA2AgALQQAhAiADQQA2AhwgAyABNgIUIANB5R82AhAgA0EINgIMDL8CC0HVASECDKUCCyADQfMBNgIcIAMgATYCFCADIAA2AgxBACECDL0CC0EAIQACQCADKAI4IgJFDQAgAigCQCICRQ0AIAMgAhEAACEACyAARQ1uIABBFUcEQCADQQA2AhwgAyABNgIUIANBgg82AhAgA0EgNgIMQQAhAgy9AgsgA0GPATYCHCADIAE2AhQgA0HsGzYCECADQRU2AgxBACECDLwCCyABIARHBEAgA0ENNgIIIAMgATYCBEHTASECDKMCC0HyASECDLsCCyABIARGBEBB8QEhAgy7AgsCQAJAAkAgAS0AAEHIAGsOCwABCAgICAgICAgCCAsgAUEBaiEBQdABIQIMowILIAFBAWohAUHRASECDKICCyABQQFqIQFB0gEhAgyhAgtB8AEhAiABIARGDbkCIAMoAgAiACAEIAFraiEGIAEgAGtBAmohBQNAIAEtAAAgAEG11QBqLQAARw0EIABBAkYNAyAAQQFqIQAgBCABQQFqIgFHDQALIAMgBjYCAAy5AgtB7wEhAiABIARGDbgCIAMoAgAiACAEIAFraiEGIAEgAGtBAWohBQNAIAEtAAAgAEGz1QBqLQAARw0DIABBAUYNAiAAQQFqIQAgBCABQQFqIgFHDQALIAMgBjYCAAy4AgtB7gEhAiABIARGDbcCIAMoAgAiACAEIAFraiEGIAEgAGtBAmohBQNAIAEtAAAgAEGw1QBqLQAARw0CIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBjYCAAy3AgsgAygCBCEAIANCADcDACADIAAgBUEBaiIBECsiAEUNAiADQewBNgIcIAMgATYCFCADIAA2AgxBACECDLYCCyADQQA2AgALIAMoAgQhACADQQA2AgQgAyAAIAEQKyIARQ2cAiADQe0BNgIcIAMgATYCFCADIAA2AgxBACECDLQCC0HPASECDJoCC0EAIQACQCADKAI4IgJFDQAgAigCNCICRQ0AIAMgAhEAACEACwJAIAAEQCAAQRVGDQEgA0EANgIcIAMgATYCFCADQeoNNgIQIANBJjYCDEEAIQIMtAILQc4BIQIMmgILIANB6wE2AhwgAyABNgIUIANBgBs2AhAgA0EVNgIMQQAhAgyyAgsgASAERgRAQesBIQIMsgILIAEtAABBL0YEQCABQQFqIQEMAQsgA0EANgIcIAMgATYCFCADQbI4NgIQIANBCDYCDEEAIQIMsQILQc0BIQIMlwILIAEgBEcEQCADQQ42AgggAyABNgIEQcwBIQIMlwILQeoBIQIMrwILIAEgBEYEQEHpASECDK8CCyABLQAAQTBrIgBB/wFxQQpJBEAgAyAAOgAqIAFBAWohAUHLASECDJYCCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNlwIgA0HoATYCHCADIAE2AhQgAyAANgIMQQAhAgyuAgsgASAERgRAQecBIQIMrgILAkAgAS0AAEEuRgRAIAFBAWohAQwBCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNmAIgA0HmATYCHCADIAE2AhQgAyAANgIMQQAhAgyuAgtBygEhAgyUAgsgASAERgRAQeUBIQIMrQILQQAhAEEBIQVBASEHQQAhAgJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAIAEtAABBMGsOCgoJAAECAwQFBggLC0ECDAYLQQMMBQtBBAwEC0EFDAMLQQYMAgtBBwwBC0EICyECQQAhBUEAIQcMAgtBCSECQQEhAEEAIQVBACEHDAELQQAhBUEBIQILIAMgAjoAKyABQQFqIQECQAJAIAMtAC5BEHENAAJAAkACQCADLQAqDgMBAAIECyAHRQ0DDAILIAANAQwCCyAFRQ0BCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNAiADQeIBNgIcIAMgATYCFCADIAA2AgxBACECDK8CCyADKAIEIQAgA0EANgIEIAMgACABEC8iAEUNmgIgA0HjATYCHCADIAE2AhQgAyAANgIMQQAhAgyuAgsgAygCBCEAIANBADYCBCADIAAgARAvIgBFDZgCIANB5AE2AhwgAyABNgIUIAMgADYCDAytAgtByQEhAgyTAgtBACEAAkAgAygCOCICRQ0AIAIoAkQiAkUNACADIAIRAAAhAAsCQCAABEAgAEEVRg0BIANBADYCHCADIAE2AhQgA0GkDTYCECADQSE2AgxBACECDK0CC0HIASECDJMCCyADQeEBNgIcIAMgATYCFCADQdAaNgIQIANBFTYCDEEAIQIMqwILIAEgBEYEQEHhASECDKsCCwJAIAEtAABBIEYEQCADQQA7ATQgAUEBaiEBDAELIANBADYCHCADIAE2AhQgA0GZETYCECADQQk2AgxBACECDKsCC0HHASECDJECCyABIARGBEBB4AEhAgyqAgsCQCABLQAAQTBrQf8BcSICQQpJBEAgAUEBaiEBAkAgAy8BNCIAQZkzSw0AIAMgAEEKbCIAOwE0IABB/v8DcSACQf//A3NLDQAgAyAAIAJqOwE0DAILQQAhAiADQQA2AhwgAyABNgIUIANBlR42AhAgA0ENNgIMDKsCCyADQQA2AhwgAyABNgIUIANBlR42AhAgA0ENNgIMQQAhAgyqAgtBxgEhAgyQAgsgASAERgRAQd8BIQIMqQILAkAgAS0AAEEwa0H/AXEiAkEKSQRAIAFBAWohAQJAIAMvATQiAEGZM0sNACADIABBCmwiADsBNCAAQf7/A3EgAkH//wNzSw0AIAMgACACajsBNAwCC0EAIQIgA0EANgIcIAMgATYCFCADQZUeNgIQIANBDTYCDAyqAgsgA0EANgIcIAMgATYCFCADQZUeNgIQIANBDTYCDEEAIQIMqQILQcUBIQIMjwILIAEgBEYEQEHeASECDKgCCwJAIAEtAABBMGtB/wFxIgJBCkkEQCABQQFqIQECQCADLwE0IgBBmTNLDQAgAyAAQQpsIgA7ATQgAEH+/wNxIAJB//8Dc0sNACADIAAgAmo7ATQMAgtBACECIANBADYCHCADIAE2AhQgA0GVHjYCECADQQ02AgwMqQILIANBADYCHCADIAE2AhQgA0GVHjYCECADQQ02AgxBACECDKgCC0HEASECDI4CCyABIARGBEBB3QEhAgynAgsCQAJAAkACQCABLQAAQQprDhcCAwMAAwMDAwMDAwMDAwMDAwMDAwMDAQMLIAFBAWoMBQsgAUEBaiEBQcMBIQIMjwILIAFBAWohASADQS9qLQAAQQFxDQggA0EANgIcIAMgATYCFCADQY0LNgIQIANBDTYCDEEAIQIMpwILIANBADYCHCADIAE2AhQgA0GNCzYCECADQQ02AgxBACECDKYCCyABIARHBEAgA0EPNgIIIAMgATYCBEEBIQIMjQILQdwBIQIMpQILAkACQANAAkAgAS0AAEEKaw4EAgAAAwALIAQgAUEBaiIBRw0AC0HbASECDKYCCyADKAIEIQAgA0EANgIEIAMgACABEC0iAEUEQCABQQFqIQEMBAsgA0HaATYCHCADIAA2AgwgAyABQQFqNgIUQQAhAgylAgsgAygCBCEAIANBADYCBCADIAAgARAtIgANASABQQFqCyEBQcEBIQIMigILIANB2QE2AhwgAyAANgIMIAMgAUEBajYCFEEAIQIMogILQcIBIQIMiAILIANBL2otAABBAXENASADQQA2AhwgAyABNgIUIANB5Bw2AhAgA0EZNgIMQQAhAgygAgsgASAERgRAQdkB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CyADIAU2AgAMkAILIANBADYCACAGQQFqIQFBGgw8C0HKASECIAEgBEYNjgIgAygCACIAIAQgAWtqIQUgASAAa0EDaiEGAkADQCABLQAAIABBjdUAai0AAEcNOyAAQQNGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMjwILIANBADYCACAGQQFqIQFBIQw7CyABIARGBEBByQEhAgyOAgsCQAJAIAEtAABBwQBrDhQAPT09PT09PT09PT09PT09PT09AT0LIAFBAWohAUGtASECDPUBCyABQQFqIQFBsAEhAgz0AQsgASAERgRAQcgBIQIMjQILAkACQCABLQAAQdUAaw4LADw8PDw8PDw8PAE8CyABQQFqIQFBrgEhAgz0AQsgAUEBaiEBQa8BIQIM8wELQccBIQIgASAERg2LAiADKAIAIgAgBCABa2ohBSABIABrQQhqIQYCQANAIAEtAAAgAEGE1QBqLQAARw04IABBCEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyMAgsgA0EANgIAIAZBAWohAUEqDDgLIAEgBEYEQEHGASECDIsCCyABLQAAQdAARw04IAFBAWohAUElDDcLQcUBIQIgASAERg2JAiADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGB1QBqLQAARw02IABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyKAgsgA0EANgIAIAZBAWohAUEODDYLIAEgBEYEQEHEASECDIkCCyABLQAAQcUARw02IAFBAWohAUGrASECDO8BCyABIARGBEBBwwEhAgyIAgsCQAJAAkACQCABLQAAQcIAaw4PAAECOTk5OTk5OTk5OTkDOQsgAUEBaiEBQacBIQIM8QELIAFBAWohAUGoASECDPABCyABQQFqIQFBqQEhAgzvAQsgAUEBaiEBQaoBIQIM7gELQcIBIQIgASAERg2GAiADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEH+1ABqLQAARw0zIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyHAgsgA0EANgIAIAZBAWohAUEUDDMLQcEBIQIgASAERg2FAiADKAIAIgAgBCABa2ohBSABIABrQQRqIQYCQANA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BTYCAAzsAQsgA0EANgIAIAZBAWohAUEXDBgLQaYBIQIgASAERg3qASADKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEHB1ABqLQAARw0XIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzrAQsgA0EANgIAIAZBAWohAUEYDBcLIAEgBEYEQEGlASECDOoBCwJAAkAgAS0AAEHJAGsOBwAZGRkZGQEZCyABQQFqIQFBiwEhAgzRAQsgAUEBaiEBQYwBIQIM0AELQaQBIQIgASAERg3oASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGm1QBqLQAARw0VIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzpAQsgA0EANgIAIAZBAWohAUEJDBULQaMBIQIgASAERg3nASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGk1QBqLQAARw0UIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzoAQsgA0EANgIAIAZBAWohAUEfDBQLQaIBIQIgASAERg3mASADKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEG+1ABqLQAARw0TIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAznAQsgA0EANgIAIAZBAWohAUECDBMLQaEBIQIgASAERg3lASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYDQCABLQAAIABBvNQAai0AAEcNESAAQQFGDQIgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM5QELIAEgBEYEQEGgASECDOUBC0EBIAEtAABB3wBHDREaIAFBAWohAUGHASECDMsBCyADQQA2AgAgBkEBaiEBQYgBIQIMygELQZ8BIQIgASAERg3iASADKAIAIgAgBCABa2ohBSABIABrQQhqIQYCQANAIAEtAAAgAEGE1QBqLQAARw0PIABBCEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAzjAQsgA0EANgIAIAZBAWohAUEpDA8LQZ4BIQIgASAERg3hASADKAIAIgAgBCABa2ohBSABIABrQQNqIQYCQANAIAEtAAAgAEG41ABqLQAARw0OIABBA0YNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAziAQsgA0EANgIAIAZBAWohAUEtDA4LIAEgBEYEQEGdASECDOEBCyABLQAAQcUARw0OIAFBAWohAUGEASECDMcBCyABIARGBEBBnAEhAgzgAQsCQAJAIAEtAABBzABrDggADw8PDw8PAQ8LIAFBAWohAUGCASECDMcBCyABQQFqIQFBgwEhAgzGAQtBmwEhAiABIARGDd4BIAMoAgAiACAEIAFraiEFIAEgAGtBBGohBgJAA0AgAS0AACAAQbPUAGotAABHDQsgAEEERg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADN8BCyADQQA2AgAgBkEBaiEBQSMMCwtBmgEhAiABIARGDd0BIAMoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQbDUAGotAABHDQogAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADN4BCyADQQA2AgAgBkEBaiEBQQAMCgsgASAERgRAQZkBIQIM3QELAkACQCABLQAAQcgAaw4IAAwMDAwMDAEMCyABQQFqIQFB/QAhAgzEAQsgAUEBaiEBQYABIQIMwwELIAEgBEYEQEGYASECDNwBCwJAAkAgAS0AAEHOAGsOAwALAQsLIAFBAWohAUH+ACECDMMBCyABQQFqIQFB/wAhAgzCAQsgASAERgRAQZcBIQIM2wELIAEtAABB2QBHDQggAUEBaiEBQQgMBwtBlgEhAiABIARGDdkBIAMoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQazUAGotAABHDQYgAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADNoBCyADQQA2AgAgBkEBaiEBQQUMBgtBlQEhAiABIARGDdgBIAMoAgAiACAEIAFraiEFIAEgAGtBBWohBgJAA0AgAS0AACAAQabUAGotAABHDQUgAEEFRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADNkBCyADQQA2AgAgBkEBaiEBQRYMBQtBlAEhAiABIARGDdcBIAMoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQaHVAGotAABHDQQgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAyAFNgIADNgBCyADQQA2AgAgBkEBaiEBQRAMBAsgASAERgRAQZMBIQIM1wELAkACQCABLQAAQcMAaw4MAAYGBgYGBgYGBgYBBgsgAUEBaiEBQfkAIQIMvgELIAFBAWohAUH6ACECDL0BC0GSASECIAEgBEYN1QEgAygCACIAIAQgAWtqIQUgASAAa0EFaiEGAkADQCABLQAAIABBoNQAai0AAEcNAiAAQQVGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAM1gELIANBADYCACAGQQFqIQFBJAwCCyADQQA2AgAMAgsgASAERgRAQZEBIQIM1AELIAEtAABBzABHDQEgAUEBaiEBQRMLOgApIAMoAgQhACADQQA2AgQgAyAAIAEQLiIADQIMAQtBACECIANBADYCHCADIAE2AhQgA0H+HzYCECADQQY2AgwM0QELQfgAIQIMtwELIANBkAE2AhwgAyABNgIUIAMgADYCDEEAIQIMzwELQQAhAAJAIAMoAjgiAkUNACACKAJAIgJFDQAgAyACEQAAIQALIABFDQAgAEEVRg0BIANBADYCHCADIAE2AhQgA0GCDzYCECADQSA2AgxBACECDM4BC0H3ACECDLQBCyADQY8BNgIcIAMgATYCFCADQewbNgIQIANBFTYCDEEAIQIMzAELIAEgBEYEQEGPASECDMwBCwJAIAEtAABBIEYEQCABQQFqIQEMAQsgA0EANgIcIAMgATYCFCADQZsfNgIQIANBBjYCDEEAIQIMzAELQQIhAgyyAQsDQCABLQAAQSBHDQIgBCABQQFqIgFHDQALQY4BIQIMygELIAEgBEYEQEGNASECDMoBCwJAIAEtAABBCWsOBEoAAEoAC0H1ACECDLABCyADLQApQQVGBEBB9gAhAgywAQtB9AAhAgyvAQsgASAERgRAQYwBIQIMyAELIANBEDYCCCADIAE2AgQMCgsgASAERgRAQYsBIQIMxwELAkAgAS0AAEEJaw4ERwAARwALQfMAIQIMrQELIAEgBEcEQCADQRA2AgggAyABNgIEQfEAIQIMrQELQYoBIQIMxQELAkAgASAERwRAA0AgAS0AAEGg0ABqLQAAIgBBA0cEQAJAIABBAWsOAkkABAtB8AAhAgyvAQsgBCABQQFqIgFHDQALQYgBIQIMxgELQYgBIQIMxQELIANBADYCHCADIAE2AhQgA0HbIDYCECADQQc2AgxBACECDMQBCyABIARGBEBBiQEhAgzEAQsCQAJAAkAgAS0AAEGg0gBqLQAAQQFrDgNGAgABC0HyACECDKwBCyADQQA2AhwgAyABNgIUIANBtBI2AhAgA0EHNgIMQQAhAgzEAQtB6gAhAgyqAQsgASAERwRAIAFBAWohAUHvACECDKoBC0GHASECDMIBCyAEIAEiAEYEQEGGASECDMIBCyAALQAAIgFBL0YEQCAAQQFqIQFB7gAhAgypAQsgAUEJayICQRdLDQEgACEBQQEgAnRBm4CABHENQQwBCyAEIAEiAEYEQEGFASECDMEBCyAALQAAQS9HDQAgAEEBaiEBDAMLQQAhAiADQQA2AhwgAyAANgIUIANB2yA2AhAgA0EHNgIMDL8BCwJAAkACQAJAAkADQCABLQAAQaDOAGotAAAiAEEFRwRAAkACQCAAQQFrDghHBQYHCAAEAQgLQesAIQIMrQELIAFBAWohAUHtACECDKwBCyAEIAFBAWoiAUcNAAtBhAEhAgzDAQsgAUEBagwUCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNHiADQdsANgIcIAMgATYCFCADIAA2AgxBACECDMEBCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNHiADQd0ANgIcIAMgATYCFCADIAA2AgxBACECDMABCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNHiADQfoANgIcIAMgATYCFCADIAA2AgxBACECDL8BCyADQQA2AhwgAyABNgIUIANB+Q82AhAgA0EHNgIMQQAhAgy+AQsgASAERgRAQYMBIQIMvgELAkAgAS0AAEGgzgBqLQAAQQFrDgg+BAUGAAgCAwcLIAFBAWohAQtBAyECDKMBCyABQQFqDA0LQQAhAiADQQA2AhwgA0HREjYCECADQQc2AgwgAyABQQFqNgIUDLoBCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNFiADQdsANgIcIAMgATYCFCADIAA2AgxBACECDLkBCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNFiADQd0ANgIcIAMgATYCFCADIAA2AgxBACECDLgBCyADKAIEIQAgA0EANgIEIAMgACABECwiAEUNFiADQfoANgIcIAMgATYCFCADIAA2AgxBACECDLcBCyADQQA2AhwgAyABNgIUIANB+Q82AhAgA0EHNgIMQQAhAgy2AQtB7AAhAgycAQsgASAERgRAQYIBIQIMtQELIAFBAWoMAgsgASAERgRAQYEBIQIMtAELIAFBAWoMAQsgASAERg0BIAFBAWoLIQFBBCECDJgBC0GAASECDLABCwNAIAEtAABBoMwAai0AACIAQQJHBEAgAEEBRwRAQekAIQIMmQELDDELIAQgAUEBaiIBRw0AC0H/ACECDK8BCyABIARGBEBB/gAhAgyvAQsCQCABLQAAQQlrDjcvAwYvBAYGBgYGBgYGBgYGBgYGBgYGBgUGBgIGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYGBgYABgsgAUEBagshAUEFIQIMlAELIAFBAWoMBgsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDQggA0HbADYCHCADIAE2AhQgAyAANgIMQQAhAgyrAQsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDQggA0HdADYCHCADIAE2AhQgAyAANgIMQQAhAgyqAQsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDQggA0H6ADYCHCADIAE2AhQgAyAANgIMQQAhAgypAQsgA0EANgIcIAMgATYCFCADQY0UNgIQIANBBzYCDEEAIQIMqAELAkACQAJAAkADQCABLQAAQaDKAGotAAAiAEEFRwRAAkAgAEEBaw4GLgMEBQYABgtB6AAhAgyUAQsgBCABQQFqIgFHDQALQf0AIQIMqwELIAMoAgQhACADQQA2AgQgAyAAIAEQLCIARQ0HIANB2wA2AhwgAyABNgIUIAMgADYCDEEAIQIMqgELIAMoAgQhACADQQA2AgQgAyAAIAEQLCIARQ0HIANB3QA2AhwgAyABNgIUIAMgADYCDEEAIQIMqQELIAMoAgQhACADQQA2AgQgAyAAIAEQLCIARQ0HIANB+gA2AhwgAyABNgIUIAMgADYCDEEAIQIMqAELIANBADYCHCADIAE2AhQgA0HkCDYCECADQQc2AgxBACECDKcBCyABIARGDQEgAUEBagshAUEGIQIMjAELQfwAIQIMpAELAkACQAJAAkADQCABLQAAQaDIAGotAAAiAEEFRwRAIABBAWsOBCkCAwQFCyAEIAFBAWoiAUcNAAtB+wAhAgynAQsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDQMgA0HbADYCHCADIAE2AhQgAyAANgIMQQAhAgymAQsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDQMgA0HdADYCHCADIAE2AhQgAyAANgIMQQAhAgylAQsgAygCBCEAIANBADYCBCADIAAgARAsIgBFDQMgA0H6ADYCHCADIAE2AhQgAyAANgIMQQAhAgykAQsgA0EANgIcIAMgATYCFCADQbwKNgIQIANBBzYCDEEAIQIMowELQc8AIQIMiQELQdEAIQIMiAELQecAIQIMhwELIAEgBEYEQEH6ACECDKABCwJAIAEtAABBCWsOBCAAACAACyABQQFqIQFB5gAhAgyGAQsgASAERgRAQfkAIQIMnwELAkAgAS0AAEEJaw4EHwAAHwALQQAhAAJAIAMoAjgiAkUNACACKAI4IgJFDQAgAyACEQAAIQALIABFBEBB4gEhAgyGAQsgAEEVRwRAIANBADYCHCADIAE2AhQgA0HJDTYCECADQRo2AgxBACECDJ8BCyADQfgANgIcIAMgATYCFCADQeoaNgIQIANBFTYCDEEAIQIMngELIAEgBEcEQCADQQ02AgggAyABNgIEQeQAIQIMhQELQfcAIQIMnQELIAEgBEYEQEH2ACECDJ0BCwJAAkACQCABLQAAQcgAaw4LAAELCwsLCwsLCwILCyABQQFqIQFB3QAhAgyFAQsgAUEBaiEBQeAAIQIMhAELIAFBAWohAUHjACECDIMBC0H1ACECIAEgBEYNmwEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBtdUAai0AAEcNCCAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMnAELIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARArIgAEQCADQfQANgIcIAMgATYCFCADIAA2AgxBACECDJwBC0HiACECDIIBC0EAIQACQCADKAI4IgJFDQAgAigCNCICRQ0AIAMgAhEAACEACwJAIAAEQCAAQRVGDQEgA0EANgIcIAMgATYCFCADQeoNNgIQIANBJjYCDEEAIQIMnAELQeEAIQIMggELIANB8wA2AhwgAyABNgIUIANBgBs2AhAgA0EVNgIMQQAhAgyaAQsgAy0AKSIAQSNrQQtJDQkCQCAAQQZLDQBBASAAdEHKAHFFDQAMCgtBACECIANBADYCHCADIAE2AhQgA0HtCTYCECADQQg2AgwMmQELQfIAIQIgASAERg2YASADKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGz1QBqLQAARw0FIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAMgBTYCAAyZAQsgAygCBCEAIANCADcDACADIAAgBkEBaiIBECsiAARAIANB8QA2AhwgAyABNgIUIAMgADYCDEEAIQIMmQELQd8AIQIMfwtBACEAAkAgAygCOCICRQ0AIAIoAjQiAkUNACADIAIRAAAhAAsCQCAABEAgAEEVRg0BIANBADYCHCADIAE2AhQgA0HqDTYCECADQSY2AgxBACECDJkBC0HeACECDH8LIANB8AA2AhwgAyABNgIUIANBgBs2AhAgA0EVNgIMQQAhAgyXAQsgAy0AKUEhRg0GIANBADYCHCADIAE2AhQgA0GRCjYCECADQQg2AgxBACECDJYBC0HvACECIAEgBEYNlQEgAygCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABBsNUAai0AAEcNAiAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyADIAU2AgAMlgELIAMoAgQhACADQgA3AwAgAyAAIAZBAWoiARArIgBFDQIgA0HtADYCHCADIAE2AhQgAyAANgIMQQAhAgyVAQsgA0EANgIACyADKAIEIQAgA0EANgIEIAMgACABECsiAEUNgAEgA0HuADYCHCADIAE2AhQgAyAANgIMQQAhAgyTAQtB3AAhAgx5C0EAIQACQCADKAI4IgJFDQAgAigCNCICRQ0AIAMgAhEAACEACwJAIAAEQCAAQRVGDQEgA0EANgIcIAMgATYCFCADQeoNNgIQIANBJjYCDEEAIQIMkwELQdsAIQIMeQsgA0HsADYCHCADIAE2AhQgA0GAGzYCECADQRU2AgxBACECDJEBCyADLQApIgBBI0kNACAAQS5GDQAgA0EANgIcIAMgATYCFCADQckJNgIQIANBCDYCDEEAIQIMkAELQdoAIQIMdgsgASAERgRAQesAIQIMjwELAkAgAS0AAEEvRgRAIAFBAWohAQwBCyAD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ciBIVFRQL3gueCByZXF1ZXN0AEludmFsaWQgbWV0aG9kIGZvciBSVFNQL3gueCByZXF1ZXN0AEV4cGVjdGVkIFNPVVJDRSBtZXRob2QgZm9yIElDRS94LnggcmVxdWVzdABJbnZhbGlkIGNoYXIgaW4gdXJsIGZyYWdtZW50IHN0YXJ0AEV4cGVjdGVkIGRvdABTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3N0YXR1cwBJbnZhbGlkIHJlc3BvbnNlIHN0YXR1cwBFeHBlY3RlZCBMRiBhZnRlciBoZWFkZXJzAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMAVXNlciBjYWxsYmFjayBlcnJvcgBgb25fcmVzZXRgIGNhbGxiYWNrIGVycm9yAGBvbl9jaHVua19oZWFkZXJgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXNzYWdlX2JlZ2luYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlYCBjYWxsYmFjayBlcnJvcgBgb25fc3RhdHVzX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fdmVyc2lvbl9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX3VybF9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX3Byb3RvY29sX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9oZWFkZXJfdmFsdWVfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXNzYWdlX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fbWV0aG9kX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25faGVhZGVyX2ZpZWxkX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfZXh0ZW5zaW9uX25hbWVgIGNhbGxiYWNrIGVycm9yAFVuZXhwZWN0ZWQgY2hhciBpbiB1cmwgc2VydmVyAEludmFsaWQgaGVhZGVyIHZhbHVlIGNoYXIASW52YWxpZCBoZWFkZXIgZmllbGQgY2hhcgBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3ZlcnNpb24ASW52YWxpZCBtaW5vciB2ZXJzaW9uAEludmFsaWQgbWFqb3IgdmVyc2lvbgBFeHBlY3RlZCBzcGFjZSBhZnRlciB2ZXJzaW9uAEV4cGVjdGVkIENSTEYgYWZ0ZXIgdmVyc2lvbgBJbnZhbGlkIEhUVFAgdmVyc2lvbgBJbnZhbGlkIGhlYWRlciB0b2tlbgBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3VybABJbnZhbGlkIGNoYXJhY3RlcnMgaW4gdXJsAFVuZXhwZWN0ZWQgc3RhcnQgY2hhciBpbiB1cmwARG91YmxlIEAgaW4gdXJsAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fcHJvdG9jb2wARW1wdHkgQ29udGVudC1MZW5ndGgASW52YWxpZCBjaGFyYWN0ZXIgaW4gQ29udGVudC1MZW5ndGgAVHJhbnNmZXItRW5jb2RpbmcgY2FuJ3QgYmUgcHJlc2VudCB3aXRoIENvbnRlbnQtTGVuZ3RoAER1cGxpY2F0ZSBDb250ZW50LUxlbmd0aABJbnZhbGlkIGNoYXIgaW4gdXJsIHBhdGgAQ29udGVudC1MZW5ndGggY2FuJ3QgYmUgcHJlc2VudCB3aXRoIFRyYW5zZmVyLUVuY29kaW5nAE1pc3NpbmcgZXhwZWN0ZWQgQ1IgYWZ0ZXIgY2h1bmsgc2l6ZQBFeHBlY3RlZCBMRiBhZnRlciBjaHVuayBzaXplAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIHNpemUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfdmFsdWUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9jaHVua19leHRlbnNpb25fdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyB2YWx1ZQBVbmV4cGVjdGVkIHdoaXRlc3BhY2UgYWZ0ZXIgaGVhZGVyIHZhbHVlAE1pc3NpbmcgZXhwZWN0ZWQgQ1IgYWZ0ZXIgaGVhZGVyIHZhbHVlAE1pc3NpbmcgZXhwZWN0ZWQgTEYgYWZ0ZXIgaGVhZGVyIHZhbHVlAEludmFsaWQgYFRyYW5zZmVyLUVuY29kaW5nYCBoZWFkZXIgdmFsdWUATWlzc2luZyBleHBlY3RlZCBDUiBhZnRlciBjaHVuayBleHRlbnNpb24gdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyBxdW90ZSB2YWx1ZQBJbnZhbGlkIHF1b3RlZC1wYWlyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGVkIHZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGVkIHZhbHVlAFBhdXNlZCBieSBvbl9oZWFkZXJzX2NvbXBsZXRlAEludmFsaWQgRU9GIHN0YXRlAG9uX3Jlc2V0IHBhdXNlAG9uX2NodW5rX2hlYWRlciBwYXVzZQBvbl9tZXNzYWdlX2JlZ2luIHBhdXNlAG9uX2NodW5rX2V4dGVuc2lvbl92YWx1ZSBwYXVzZQBvbl9zdGF0dXNfY29tcGxldGUgcGF1c2UAb25fdmVyc2lvbl9jb21wbGV0ZSBwYXVzZQBvbl91cmxfY29tcGxldGUgcGF1c2UAb25fcHJvdG9jb2xfY29tcGxldGUgcGF1c2UAb25fY2h1bmtfY29tcGxldGUgcGF1c2UAb25faGVhZGVyX3ZhbHVlX2NvbXBsZXRlIHBhdXNlAG9uX21lc3NhZ2VfY29tcGxldGUgcGF1c2UAb25fbWV0aG9kX2NvbXBsZXRlIHBhdXNlAG9uX2hlYWRlcl9maWVsZF9jb21wbGV0ZSBwYXVzZQBvbl9jaHVua19leHRlbnNpb25fbmFtZSBwYXVzZQBVbmV4cGVjdGVkIHNwYWNlIGFmdGVyIHN0YXJ0IGxpbmUATWlzc2luZyBleHBlY3RlZCBDUiBhZnRlciByZXNwb25zZSBsaW5lAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fY2h1bmtfZXh0ZW5zaW9uX25hbWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyBuYW1lAE1pc3NpbmcgZXhwZWN0ZWQgQ1IgYWZ0ZXIgY2h1bmsgZXh0ZW5zaW9uIG5hbWUASW52YWxpZCBzdGF0dXMgY29kZQBQYXVzZSBvbiBDT05ORUNUL1VwZ3JhZGUAUGF1c2Ugb24gUFJJL1VwZ3JhZGUARXhwZWN0ZWQgSFRUUC8yIENvbm5lY3Rpb24gUHJlZmFjZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX21ldGhvZABFeHBlY3RlZCBzcGFjZSBhZnRlciBtZXRob2QAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfZmllbGQAUGF1c2VkAEludmFsaWQgd29yZCBlbmNvdW50ZXJlZABJbnZhbGlkIG1ldGhvZCBlbmNvdW50ZXJlZABNaXNzaW5nIGV4cGVjdGVkIENSIGFmdGVyIGNodW5rIGRhdGEARXhwZWN0ZWQgTEYgYWZ0ZXIgY2h1bmsgZGF0YQBVbmV4cGVjdGVkIGNoYXIgaW4gdXJsIHNjaGVtYQBSZXF1ZXN0IGhhcyBpbnZhbGlkIGBUcmFuc2Zlci1FbmNvZGluZ2AARGF0YSBhZnRlciBgQ29ubmVjdGlvbjogY2xvc2VgAFNXSVRDSF9QUk9YWQBVU0VfUFJPWFkATUtBQ1RJVklUWQBVTlBST0NFU1NBQkxFX0VOVElUWQBRVUVSWQBDT1BZAE1PVkVEX1BFUk1BTkVOVExZAFRPT19FQVJMWQBOT1RJRlkARkFJTEVEX0RFUEVOREVOQ1kAQkFEX0dBVEVXQVkAUExBWQBQVVQAQ0hFQ0tPVVQAR0FURVdBWV9USU1FT1VUAFJFUVVFU1RfVElNRU9VVABORVRXT1JLX0NPTk5FQ1RfVElNRU9VVABDT05ORUNUSU9OX1RJTUVPVVQATE9HSU5fVElNRU9VVABORVRXT1JLX1JFQURfVElNRU9VVABQT1NUAE1JU0RJUkVDVEVEX1JFUVVFU1QAQ0xJRU5UX0NMT1NFRF9SRVFVRVNUAENMSUVOVF9DTE9TRURfTE9BRF9CQUxBTkNFRF9SRVFVRVNUAEJBRF9SRVFVRVNUAEhUVFBfUkVRVUVTVF9TRU5UX1RPX0hUVFBTX1BPUlQAUkVQT1JUAElNX0FfVEVBUE9UAFJFU0VUX0NPTlRFTlQATk9fQ09OVEVOVABQQVJUSUFMX0NPTlRFTlQASFBFX0lOVkFMSURfQ09OU1RBTlQASFBFX0NCX1JFU0VUAEdFVABIUEVfU1RSSUNUAENPTkZMSUNUAFRFTVBPUkFSWV9SRURJUkVDVABQRVJNQU5FTlRfUkVESVJFQ1QAQ09OTkVDVABNVUxUSV9TVEFUVVMASFBFX0lOVkFMSURfU1RBVFVTAFRPT19NQU5ZX1JFUVVFU1RTAEVBUkxZX0hJTlRTAFVOQVZBSUxBQkxFX0ZPUl9MRUdBTF9SRUFTT05TAE9QVElPTlMAU1dJVENISU5HX1BST1RPQ09MUwBWQVJJQU5UX0FMU09fTkVHT1RJQVRFUwBNVUxUSVBMRV9DSE9JQ0VTAElOVEVSTkFMX1NFUlZFUl9FUlJPUgBXRUJfU0VSVkVSX1VOS05PV05fRVJST1IAUkFJTEdVTl9FUlJPUgBJREVOVElUWV9QUk9WSURFUl9BVVRIRU5USUNBVElPTl9FUlJPUgBTU0xfQ0VSVElGSUNBVEVfRVJST1IASU5WQUxJRF9YX0ZPUldBUkRFRF9GT1IAU0VUX1BBUkFNRVRFUgBHRVRfUEFSQU1FVEVSAEhQRV9VU0VSAFNFRV9PVEhFUgBIUEVfQ0JfQ0hVTktfSEVBREVSAEV4cGVjdGVkIExGIGFmdGVyIENSAE1LQ0FMRU5EQVIAU0VUVVAAV0VCX1NFUlZFUl9JU19ET1dOAFRFQVJET1dOAEhQRV9DTE9TRURfQ09OTkVDVElPTgBIRVVSSVNUSUNfRVhQSVJBVElPTgBESVNDT05ORUNURURfT1BFUkFUSU9OAE5PTl9BVVRIT1JJVEFUSVZFX0lORk9STUFUSU9OAEhQRV9JTlZBTElEX1ZFUlNJT04ASFBFX0NCX01FU1NBR0VfQkVHSU4AU0lURV9JU19GUk9aRU4ASFBFX0lOVkFMSURfSEVBREVSX1RPS0VOAElOVkFMSURfVE9LRU4ARk9SQklEREVOAEVOSEFOQ0VfWU9VUl9DQUxNAEhQRV9JTlZBTElEX1VSTABCTE9DS0VEX0JZX1BBUkVOVEFMX0NPTlRST0wATUtDT0wAQUNMAEhQRV9JTlRFUk5BTABSRVFVRVNUX0hFQURFUl9GSUVMRFNfVE9PX0xBUkdFX1VOT0ZGSUNJQUwASFBFX09LAFVOTElOSwBVTkxPQ0sAUFJJAFJFVFJZX1dJVEgASFBFX0lOVkFMSURfQ09OVEVOVF9MRU5HVEgASFBFX1VORVhQRUNURURfQ09OVEVOVF9MRU5HVEgARkxVU0gAUFJPUFBBVENIAE0tU0VBUkNIAFVSSV9UT09fTE9ORwBQUk9DRVNTSU5HAE1JU0NFTExBTkVPVVNfUEVSU0lTVEVOVF9XQVJOSU5HAE1JU0NFTExBTkVPVVNfV0FSTklORwBIUEVfSU5WQUxJRF9UUkFOU0ZFUl9FTkNPRElORwBFeHBlY3RlZCBDUkxGAEhQRV9JTlZBTElEX0NIVU5LX1NJWkUATU9WRQBDT05USU5VRQBIUEVfQ0JfU1RBVFVTX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJTX0NPTVBMRVRFAEhQRV9DQl9WRVJTSU9OX0NPTVBMRVRFAEhQRV9DQl9VUkxfQ09NUExFVEUASFBFX0NCX1BST1RPQ09MX0NPTVBMRVRFAEhQRV9DQl9DSFVOS19DT01QTEVURQBIUEVfQ0JfSEVBREVSX1ZBTFVFX0NPTVBMRVRFAEhQRV9DQl9DSFVOS19FWFRFTlNJT05fVkFMVUVfQ09NUExFVEUASFBFX0NCX0NIVU5LX0VYVEVOU0lPTl9OQU1FX0NPTVBMRVRFAEhQRV9DQl9NRVNTQUdFX0NPTVBMRVRFAEhQRV9DQl9NRVRIT0RfQ09NUExFVEUASFBFX0NCX0hFQURFUl9GSUVMRF9DT01QTEVURQBERUxFVEUASFBFX0lOVkFMSURfRU9GX1NUQVRFAElOVkFMSURfU1NMX0NFUlRJRklDQVRFAFBBVVNFAE5PX1JFU1BPTlNFAFVOU1VQUE9SVEVEX01FRElBX1RZUEUAR09ORQBOT1RfQUNDRVBUQUJMRQBTRVJWSUNFX1VOQVZBSUxBQkxFAFJBTkdFX05PVF9TQVRJU0ZJQUJMRQBPUklHSU5fSVNfVU5SRUFDSEFCTEUAUkVTUE9OU0VfSVNfU1RBTEUAUFVSR0UATUVSR0UAUkVRVUVTVF9IRUFERVJfRklFTERTX1RPT19MQVJHRQBSRVFVRVNUX0hFQURFUl9UT09fTEFSR0UAUEFZTE9BRF9UT09fTEFSR0UASU5TVUZGSUNJRU5UX1NUT1JBR0UASFBFX1BBVVNFRF9VUEdSQURFAEhQRV9QQVVTRURfSDJfVVBHUkFERQBTT1VSQ0UAQU5OT1VOQ0UAVFJBQ0UASFBFX1VORVhQRUNURURfU1BBQ0UAREVTQ1JJQkUAVU5TVUJTQ1JJQkUAUkVDT1JEAEhQRV9JTlZBTElEX01FVEhPRABOT1RfRk9VTkQAUFJPUEZJTkQAVU5CSU5EAFJFQklORABVTkFVVEhPUklaRUQATUVUSE9EX05PVF9BTExPV0VEAEhUVFBfVkVSU0lPTl9OT1RfU1VQUE9SVEVEAEFMUkVBRFlfUkVQT1JURUQAQUNDRVBURUQATk9UX0lNUExFTUVOVEVEAExPT1BfREVURUNURUQASFBFX0NSX0VYUEVDVEVEAEhQRV9MRl9FWFBFQ1RFRABDUkVBVEVEAElNX1VTRUQASFBFX1BBVVNFRABUSU1FT1VUX09DQ1VSRUQAUEFZTUVOVF9SRVFVSVJFRABQUkVDT05ESVRJT05fUkVRVUlSRUQAUFJPWFlfQVVUSEVOVElDQVRJT05fUkVRVUlSRUQATkVUV09SS19BVVRIRU5USUNBVElPTl9SRVFVSVJFRABMRU5HVEhfUkVRVUlSRUQAU1NMX0NFUlRJRklDQVRFX1JFUVVJUkVEAFVQR1JBREVfUkVRVUlSRUQAUEFHRV9FWFBJUkVEAFBSRUNPTkRJVElPTl9GQUlMRUQARVhQRUNUQVRJT05fRkFJTEVEAFJFVkFMSURBVElPTl9GQUlMRUQAU1NMX0hBTkRTSEFLRV9GQUlMRUQATE9DS0VEAFRSQU5TRk9STUFUSU9OX0FQUExJRUQATk9UX01PRElGSUVEAE5PVF9FWFRFTkRFRABCQU5EV0lEVEhfTElNSVRfRVhDRUVERUQAU0lURV9JU19PVkVSTE9BREVEAEhFQUQARXhwZWN0ZWQgSFRUUC8sIFJUU1AvIG9yIElDRS8A5xUAAK8VAACkEgAAkhoAACYWAACeFAAA2xkAAHkVAAB+EgAA/hQAADYVAAALFgAA2BYAAPMSAABCGAAArBYAABIVAAAUFwAA7xcAAEgUAABxFwAAshoAAGsZAAB+GQAANRQAAIIaAABEFwAA/RYAAB4YAACHFwAAqhkAAJMSAAAHGAAALBcAAMoXAACkFwAA5xUAAOcVAABYFwAAOxgAAKASAAAtHAAAwxEAAEgRAADeEgAAQhMAAKQZAAD9EAAA9xUAAKUVAADvFgAA+BkAAEoWAABWFgAA9RUAAAoaAAAIGgAAARoAAKsVAABCEgAA1xAAAEwRAAAFGQAAVBYAAB4RAADKGQAAyBkAAE4WAAD/GAAAcRQAAPAVAADuFQAAlBkAAPwVAAC/GQAAmxkAAHwUAABDEQAAcBgAAJUUAAAnFAAAGRQAANUSAADUGQAARBYAAPcQAEG5OwsBAQBB0DsL4AEBAQIBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQBBuj0LBAEAAAIAQdE9C14DBAMDAwMDAAADAwADAwADAwMDAwMDAwMDAAUAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAwADAEG6PwsEAQAAAgBB0T8LXgMAAwMDAwMAAAMDAAMDAAMDAwMDAwMDAwMABAAFAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwADAAMAQbDBAAsNbG9zZWVlcC1hbGl2ZQBBycEACwEBAEHgwQAL4AEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQBBycMACwEBAEHgwwAL5wEBAQEBAQEBAQEBAQECAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAWNodW5rZWQAQfHFAAteAQABAQEBAQAAAQEAAQEAAQEBAQEBAQEBAQAAAAAAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEAAQBB0McACyFlY3Rpb25lbnQtbGVuZ3Rob25yb3h5LWNvbm5lY3Rpb24AQYDIAAsgcmFuc2Zlci1lbmNvZGluZ3BncmFkZQ0KDQpTTQ0KDQoAQanIAAsFAQIAAQMAQcDIAAtfBAUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUAQanKAAsFAQIAAQMAQcDKAAtfBAUFBgUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUAQanMAAsEAQAAAQBBwcwAC14CAgACAgICAgICAgICAgICAgICAgICAgICAgICAgIAAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAEGpzgALBQECAAEDAEHAzgALXwQFAAAFBQUFBQUFBQUFBQYFBQUFBQUFBQUFBQUABQAHCAUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQAFAAUABQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUAAAAFAEGp0AALBQEBAAEBAEHA0AALAQEAQdrQAAtBAgAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAQanSAAsFAQEAAQEAQcDSAAsBAQBBytIACwYCAAAAAAIAQeHSAAs6AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwBBoNQAC50BTk9VTkNFRUNLT1VUTkVDVEVURUNSSUJFTFVTSEVURUFEU0VBUkNIUkdFQ1RJVklUWUxFTkRBUlZFT1RJRllQVElPTlNDSFNFQVlTVEFUQ0hHRVVFUllPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFVFRQQ0VUU1BBRFRQLw==";
+ var wasmBuffer;
+ Object.defineProperty(module2, "exports", {
+ get: /* @__PURE__ */ __name(() => {
+ return wasmBuffer ? wasmBuffer : wasmBuffer = Buffer2.from(wasmBase64, "base64");
+ }, "get")
+ });
+ }
+});
+
+// node_modules/undici/lib/web/fetch/constants.js
+var require_constants4 = __commonJS({
+ "node_modules/undici/lib/web/fetch/constants.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var corsSafeListedMethods = (
+ /** @type {const} */
+ ["GET", "HEAD", "POST"]
+ );
+ var corsSafeListedMethodsSet = new Set(corsSafeListedMethods);
+ var nullBodyStatus = (
+ /** @type {const} */
+ [101, 204, 205, 304]
+ );
+ var redirectStatus = (
+ /** @type {const} */
+ [301, 302, 303, 307, 308]
+ );
+ var redirectStatusSet = new Set(redirectStatus);
+ var badPorts = (
+ /** @type {const} */
+ [
+ "1",
+ "7",
+ "9",
+ "11",
+ "13",
+ "15",
+ "17",
+ "19",
+ "20",
+ "21",
+ "22",
+ "23",
+ "25",
+ "37",
+ "42",
+ "43",
+ "53",
+ "69",
+ "77",
+ "79",
+ "87",
+ "95",
+ "101",
+ "102",
+ "103",
+ "104",
+ "109",
+ "110",
+ "111",
+ "113",
+ "115",
+ "117",
+ "119",
+ "123",
+ "135",
+ "137",
+ "139",
+ "143",
+ "161",
+ "179",
+ "389",
+ "427",
+ "465",
+ "512",
+ "513",
+ "514",
+ "515",
+ "526",
+ "530",
+ "531",
+ "532",
+ "540",
+ "548",
+ "554",
+ "556",
+ "563",
+ "587",
+ "601",
+ "636",
+ "989",
+ "990",
+ "993",
+ "995",
+ "1719",
+ "1720",
+ "1723",
+ "2049",
+ "3659",
+ "4045",
+ "4190",
+ "5060",
+ "5061",
+ "6000",
+ "6566",
+ "6665",
+ "6666",
+ "6667",
+ "6668",
+ "6669",
+ "6679",
+ "6697",
+ "10080"
+ ]
+ );
+ var badPortsSet = new Set(badPorts);
+ var referrerPolicyTokens = (
+ /** @type {const} */
+ [
+ "no-referrer",
+ "no-referrer-when-downgrade",
+ "same-origin",
+ "origin",
+ "strict-origin",
+ "origin-when-cross-origin",
+ "strict-origin-when-cross-origin",
+ "unsafe-url"
+ ]
+ );
+ var referrerPolicy = (
+ /** @type {const} */
+ [
+ "",
+ ...referrerPolicyTokens
+ ]
+ );
+ var referrerPolicyTokensSet = new Set(referrerPolicyTokens);
+ var requestRedirect = (
+ /** @type {const} */
+ ["follow", "manual", "error"]
+ );
+ var safeMethods = (
+ /** @type {const} */
+ ["GET", "HEAD", "OPTIONS", "TRACE"]
+ );
+ var safeMethodsSet = new Set(safeMethods);
+ var requestMode = (
+ /** @type {const} */
+ ["navigate", "same-origin", "no-cors", "cors"]
+ );
+ var requestCredentials = (
+ /** @type {const} */
+ ["omit", "same-origin", "include"]
+ );
+ var requestCache = (
+ /** @type {const} */
+ [
+ "default",
+ "no-store",
+ "reload",
+ "no-cache",
+ "force-cache",
+ "only-if-cached"
+ ]
+ );
+ var requestBodyHeader = (
+ /** @type {const} */
+ [
+ "content-encoding",
+ "content-language",
+ "content-location",
+ "content-type",
+ // See https://github.com/nodejs/undici/issues/2021
+ // 'Content-Length' is a forbidden header name, which is typically
+ // removed in the Headers implementation. However, undici doesn't
+ // filter out headers, so we add it here.
+ "content-length"
+ ]
+ );
+ var requestDuplex = (
+ /** @type {const} */
+ [
+ "half"
+ ]
+ );
+ var forbiddenMethods = (
+ /** @type {const} */
+ ["CONNECT", "TRACE", "TRACK"]
+ );
+ var forbiddenMethodsSet = new Set(forbiddenMethods);
+ var subresource = (
+ /** @type {const} */
+ [
+ "audio",
+ "audioworklet",
+ "font",
+ "image",
+ "manifest",
+ "paintworklet",
+ "script",
+ "style",
+ "track",
+ "video",
+ "xslt",
+ ""
+ ]
+ );
+ var subresourceSet = new Set(subresource);
+ module2.exports = {
+ subresource,
+ forbiddenMethods,
+ requestBodyHeader,
+ referrerPolicy,
+ requestRedirect,
+ requestMode,
+ requestCredentials,
+ requestCache,
+ redirectStatus,
+ corsSafeListedMethods,
+ nullBodyStatus,
+ safeMethods,
+ badPorts,
+ requestDuplex,
+ subresourceSet,
+ badPortsSet,
+ redirectStatusSet,
+ corsSafeListedMethodsSet,
+ safeMethodsSet,
+ forbiddenMethodsSet,
+ referrerPolicyTokens: referrerPolicyTokensSet
+ };
+ }
+});
+
+// node_modules/undici/lib/web/fetch/global.js
+var require_global = __commonJS({
+ "node_modules/undici/lib/web/fetch/global.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var globalOrigin = /* @__PURE__ */ Symbol.for("undici.globalOrigin.1");
+ function getGlobalOrigin() {
+ return globalThis[globalOrigin];
+ }
+ __name(getGlobalOrigin, "getGlobalOrigin");
+ function setGlobalOrigin(newOrigin) {
+ if (newOrigin === void 0) {
+ Object.defineProperty(globalThis, globalOrigin, {
+ value: void 0,
+ writable: true,
+ enumerable: false,
+ configurable: false
+ });
+ return;
+ }
+ const parsedURL = new URL(newOrigin);
+ if (parsedURL.protocol !== "http:" && parsedURL.protocol !== "https:") {
+ throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`);
+ }
+ Object.defineProperty(globalThis, globalOrigin, {
+ value: parsedURL,
+ writable: true,
+ enumerable: false,
+ configurable: false
+ });
+ }
+ __name(setGlobalOrigin, "setGlobalOrigin");
+ module2.exports = {
+ getGlobalOrigin,
+ setGlobalOrigin
+ };
+ }
+});
+
+// node_modules/undici/lib/encoding/index.js
+var require_encoding = __commonJS({
+ "node_modules/undici/lib/encoding/index.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var textDecoder2 = new TextDecoder();
+ function utf8DecodeBytes(buffer) {
+ if (buffer.length === 0) {
+ return "";
+ }
+ if (buffer[0] === 239 && buffer[1] === 187 && buffer[2] === 191) {
+ buffer = buffer.subarray(3);
+ }
+ const output = textDecoder2.decode(buffer);
+ return output;
+ }
+ __name(utf8DecodeBytes, "utf8DecodeBytes");
+ module2.exports = {
+ utf8DecodeBytes
+ };
+ }
+});
+
+// node_modules/undici/lib/web/infra/index.js
+var require_infra = __commonJS({
+ "node_modules/undici/lib/web/infra/index.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var assert2 = __require("node:assert");
+ var { utf8DecodeBytes } = require_encoding();
+ function collectASequenceOfCodePoints(condition, input, position) {
+ let result = "";
+ while (position.position < input.length && condition(input[position.position])) {
+ result += input[position.position];
+ position.position++;
+ }
+ return result;
+ }
+ __name(collectASequenceOfCodePoints, "collectASequenceOfCodePoints");
+ function collectASequenceOfCodePointsFast(char, input, position) {
+ const idx = input.indexOf(char, position.position);
+ const start = position.position;
+ if (idx === -1) {
+ position.position = input.length;
+ return input.slice(start);
+ }
+ position.position = idx;
+ return input.slice(start, position.position);
+ }
+ __name(collectASequenceOfCodePointsFast, "collectASequenceOfCodePointsFast");
+ var ASCII_WHITESPACE_REPLACE_REGEX = /[\u0009\u000A\u000C\u000D\u0020]/g;
+ function forgivingBase64(data) {
+ data = data.replace(ASCII_WHITESPACE_REPLACE_REGEX, "");
+ let dataLength = data.length;
+ if (dataLength % 4 === 0) {
+ if (data.charCodeAt(dataLength - 1) === 61) {
+ --dataLength;
+ if (data.charCodeAt(dataLength - 1) === 61) {
+ --dataLength;
+ }
+ }
+ }
+ if (dataLength % 4 === 1) {
+ return "failure";
+ }
+ if (/[^+/0-9A-Za-z]/.test(data.length === dataLength ? data : data.substring(0, dataLength))) {
+ return "failure";
+ }
+ const buffer = Buffer.from(data, "base64");
+ return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
+ }
+ __name(forgivingBase64, "forgivingBase64");
+ function isASCIIWhitespace(char) {
+ return char === 9 || // \t
+ char === 10 || // \n
+ char === 12 || // \f
+ char === 13 || // \r
+ char === 32;
+ }
+ __name(isASCIIWhitespace, "isASCIIWhitespace");
+ function isomorphicDecode(input) {
+ const length = input.length;
+ if ((2 << 15) - 1 > length) {
+ return String.fromCharCode.apply(null, input);
+ }
+ let result = "";
+ let i = 0;
+ let addition = (2 << 15) - 1;
+ while (i < length) {
+ if (i + addition > length) {
+ addition = length - i;
+ }
+ result += String.fromCharCode.apply(null, input.subarray(i, i += addition));
+ }
+ return result;
+ }
+ __name(isomorphicDecode, "isomorphicDecode");
+ var invalidIsomorphicEncodeValueRegex = /[^\x00-\xFF]/;
+ function isomorphicEncode(input) {
+ assert2(!invalidIsomorphicEncodeValueRegex.test(input));
+ return input;
+ }
+ __name(isomorphicEncode, "isomorphicEncode");
+ function parseJSONFromBytes(bytes) {
+ return JSON.parse(utf8DecodeBytes(bytes));
+ }
+ __name(parseJSONFromBytes, "parseJSONFromBytes");
+ function removeASCIIWhitespace(str3, leading = true, trailing = true) {
+ return removeChars(str3, leading, trailing, isASCIIWhitespace);
+ }
+ __name(removeASCIIWhitespace, "removeASCIIWhitespace");
+ function removeChars(str3, leading, trailing, predicate) {
+ let lead = 0;
+ let trail = str3.length - 1;
+ if (leading) {
+ while (lead < str3.length && predicate(str3.charCodeAt(lead))) lead++;
+ }
+ if (trailing) {
+ while (trail > 0 && predicate(str3.charCodeAt(trail))) trail--;
+ }
+ return lead === 0 && trail === str3.length - 1 ? str3 : str3.slice(lead, trail + 1);
+ }
+ __name(removeChars, "removeChars");
+ function serializeJavascriptValueToJSONString(value) {
+ const result = JSON.stringify(value);
+ if (result === void 0) {
+ throw new TypeError("Value is not JSON serializable");
+ }
+ assert2(typeof result === "string");
+ return result;
+ }
+ __name(serializeJavascriptValueToJSONString, "serializeJavascriptValueToJSONString");
+ module2.exports = {
+ collectASequenceOfCodePoints,
+ collectASequenceOfCodePointsFast,
+ forgivingBase64,
+ isASCIIWhitespace,
+ isomorphicDecode,
+ isomorphicEncode,
+ parseJSONFromBytes,
+ removeASCIIWhitespace,
+ removeChars,
+ serializeJavascriptValueToJSONString
+ };
+ }
+});
+
+// node_modules/undici/lib/web/fetch/data-url.js
+var require_data_url = __commonJS({
+ "node_modules/undici/lib/web/fetch/data-url.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var assert2 = __require("node:assert");
+ var { forgivingBase64, collectASequenceOfCodePoints, collectASequenceOfCodePointsFast, isomorphicDecode, removeASCIIWhitespace, removeChars } = require_infra();
+ var encoder = new TextEncoder();
+ var HTTP_TOKEN_CODEPOINTS = /^[-!#$%&'*+.^_|~A-Za-z0-9]+$/u;
+ var HTTP_WHITESPACE_REGEX = /[\u000A\u000D\u0009\u0020]/u;
+ var HTTP_QUOTED_STRING_TOKENS = /^[\u0009\u0020-\u007E\u0080-\u00FF]+$/u;
+ function dataURLProcessor(dataURL) {
+ assert2(dataURL.protocol === "data:");
+ let input = URLSerializer(dataURL, true);
+ input = input.slice(5);
+ const position = { position: 0 };
+ let mimeType = collectASequenceOfCodePointsFast(
+ ",",
+ input,
+ position
+ );
+ const mimeTypeLength = mimeType.length;
+ mimeType = removeASCIIWhitespace(mimeType, true, true);
+ if (position.position >= input.length) {
+ return "failure";
+ }
+ position.position++;
+ const encodedBody = input.slice(mimeTypeLength + 1);
+ let body = stringPercentDecode(encodedBody);
+ if (/;(?:\u0020*)base64$/ui.test(mimeType)) {
+ const stringBody = isomorphicDecode(body);
+ body = forgivingBase64(stringBody);
+ if (body === "failure") {
+ return "failure";
+ }
+ mimeType = mimeType.slice(0, -6);
+ mimeType = mimeType.replace(/(\u0020+)$/u, "");
+ mimeType = mimeType.slice(0, -1);
+ }
+ if (mimeType.startsWith(";")) {
+ mimeType = "text/plain" + mimeType;
+ }
+ let mimeTypeRecord = parseMIMEType(mimeType);
+ if (mimeTypeRecord === "failure") {
+ mimeTypeRecord = parseMIMEType("text/plain;charset=US-ASCII");
+ }
+ return { mimeType: mimeTypeRecord, body };
+ }
+ __name(dataURLProcessor, "dataURLProcessor");
+ function URLSerializer(url2, excludeFragment = false) {
+ if (!excludeFragment) {
+ return url2.href;
+ }
+ const href = url2.href;
+ const hashLength = url2.hash.length;
+ const serialized = hashLength === 0 ? href : href.substring(0, href.length - hashLength);
+ if (!hashLength && href.endsWith("#")) {
+ return serialized.slice(0, -1);
+ }
+ return serialized;
+ }
+ __name(URLSerializer, "URLSerializer");
+ function stringPercentDecode(input) {
+ const bytes = encoder.encode(input);
+ return percentDecode(bytes);
+ }
+ __name(stringPercentDecode, "stringPercentDecode");
+ function isHexCharByte(byte) {
+ return byte >= 48 && byte <= 57 || byte >= 65 && byte <= 70 || byte >= 97 && byte <= 102;
+ }
+ __name(isHexCharByte, "isHexCharByte");
+ function hexByteToNumber(byte) {
+ return (
+ // 0-9
+ byte >= 48 && byte <= 57 ? byte - 48 : (byte & 223) - 55
+ );
+ }
+ __name(hexByteToNumber, "hexByteToNumber");
+ function percentDecode(input) {
+ const length = input.length;
+ const output = new Uint8Array(length);
+ let j = 0;
+ let i = 0;
+ while (i < length) {
+ const byte = input[i];
+ if (byte !== 37) {
+ output[j++] = byte;
+ } else if (byte === 37 && !(isHexCharByte(input[i + 1]) && isHexCharByte(input[i + 2]))) {
+ output[j++] = 37;
+ } else {
+ output[j++] = hexByteToNumber(input[i + 1]) << 4 | hexByteToNumber(input[i + 2]);
+ i += 2;
+ }
+ ++i;
+ }
+ return length === j ? output : output.subarray(0, j);
+ }
+ __name(percentDecode, "percentDecode");
+ function parseMIMEType(input) {
+ input = removeHTTPWhitespace(input, true, true);
+ const position = { position: 0 };
+ const type2 = collectASequenceOfCodePointsFast(
+ "/",
+ input,
+ position
+ );
+ if (type2.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type2)) {
+ return "failure";
+ }
+ if (position.position >= input.length) {
+ return "failure";
+ }
+ position.position++;
+ let subtype = collectASequenceOfCodePointsFast(
+ ";",
+ input,
+ position
+ );
+ subtype = removeHTTPWhitespace(subtype, false, true);
+ if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) {
+ return "failure";
+ }
+ const typeLowercase = type2.toLowerCase();
+ const subtypeLowercase = subtype.toLowerCase();
+ const mimeType = {
+ type: typeLowercase,
+ subtype: subtypeLowercase,
+ /** @type {Map} */
+ parameters: /* @__PURE__ */ new Map(),
+ // https://mimesniff.spec.whatwg.org/#mime-type-essence
+ essence: `${typeLowercase}/${subtypeLowercase}`
+ };
+ while (position.position < input.length) {
+ position.position++;
+ collectASequenceOfCodePoints(
+ // https://fetch.spec.whatwg.org/#http-whitespace
+ (char) => HTTP_WHITESPACE_REGEX.test(char),
+ input,
+ position
+ );
+ let parameterName = collectASequenceOfCodePoints(
+ (char) => char !== ";" && char !== "=",
+ input,
+ position
+ );
+ parameterName = parameterName.toLowerCase();
+ if (position.position < input.length) {
+ if (input[position.position] === ";") {
+ continue;
+ }
+ position.position++;
+ }
+ if (position.position >= input.length) {
+ break;
+ }
+ let parameterValue = null;
+ if (input[position.position] === '"') {
+ parameterValue = collectAnHTTPQuotedString(input, position, true);
+ collectASequenceOfCodePointsFast(
+ ";",
+ input,
+ position
+ );
+ } else {
+ parameterValue = collectASequenceOfCodePointsFast(
+ ";",
+ input,
+ position
+ );
+ parameterValue = removeHTTPWhitespace(parameterValue, false, true);
+ if (parameterValue.length === 0) {
+ continue;
+ }
+ }
+ if (parameterName.length !== 0 && HTTP_TOKEN_CODEPOINTS.test(parameterName) && (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) && !mimeType.parameters.has(parameterName)) {
+ mimeType.parameters.set(parameterName, parameterValue);
+ }
+ }
+ return mimeType;
+ }
+ __name(parseMIMEType, "parseMIMEType");
+ function collectAnHTTPQuotedString(input, position, extractValue = false) {
+ const positionStart = position.position;
+ let value = "";
+ assert2(input[position.position] === '"');
+ position.position++;
+ while (true) {
+ value += collectASequenceOfCodePoints(
+ (char) => char !== '"' && char !== "\\",
+ input,
+ position
+ );
+ if (position.position >= input.length) {
+ break;
+ }
+ const quoteOrBackslash = input[position.position];
+ position.position++;
+ if (quoteOrBackslash === "\\") {
+ if (position.position >= input.length) {
+ value += "\\";
+ break;
+ }
+ value += input[position.position];
+ position.position++;
+ } else {
+ assert2(quoteOrBackslash === '"');
+ break;
+ }
+ }
+ if (extractValue) {
+ return value;
+ }
+ return input.slice(positionStart, position.position);
+ }
+ __name(collectAnHTTPQuotedString, "collectAnHTTPQuotedString");
+ function serializeAMimeType(mimeType) {
+ assert2(mimeType !== "failure");
+ const { parameters, essence } = mimeType;
+ let serialization = essence;
+ for (let [name, value] of parameters.entries()) {
+ serialization += ";";
+ serialization += name;
+ serialization += "=";
+ if (!HTTP_TOKEN_CODEPOINTS.test(value)) {
+ value = value.replace(/[\\"]/ug, "\\$&");
+ value = '"' + value;
+ value += '"';
+ }
+ serialization += value;
+ }
+ return serialization;
+ }
+ __name(serializeAMimeType, "serializeAMimeType");
+ function isHTTPWhiteSpace(char) {
+ return char === 13 || char === 10 || char === 9 || char === 32;
+ }
+ __name(isHTTPWhiteSpace, "isHTTPWhiteSpace");
+ function removeHTTPWhitespace(str3, leading = true, trailing = true) {
+ return removeChars(str3, leading, trailing, isHTTPWhiteSpace);
+ }
+ __name(removeHTTPWhitespace, "removeHTTPWhitespace");
+ function minimizeSupportedMimeType(mimeType) {
+ switch (mimeType.essence) {
+ case "application/ecmascript":
+ case "application/javascript":
+ case "application/x-ecmascript":
+ case "application/x-javascript":
+ case "text/ecmascript":
+ case "text/javascript":
+ case "text/javascript1.0":
+ case "text/javascript1.1":
+ case "text/javascript1.2":
+ case "text/javascript1.3":
+ case "text/javascript1.4":
+ case "text/javascript1.5":
+ case "text/jscript":
+ case "text/livescript":
+ case "text/x-ecmascript":
+ case "text/x-javascript":
+ return "text/javascript";
+ case "application/json":
+ case "text/json":
+ return "application/json";
+ case "image/svg+xml":
+ return "image/svg+xml";
+ case "text/xml":
+ case "application/xml":
+ return "application/xml";
+ }
+ if (mimeType.subtype.endsWith("+json")) {
+ return "application/json";
+ }
+ if (mimeType.subtype.endsWith("+xml")) {
+ return "application/xml";
+ }
+ return "";
+ }
+ __name(minimizeSupportedMimeType, "minimizeSupportedMimeType");
+ module2.exports = {
+ dataURLProcessor,
+ URLSerializer,
+ stringPercentDecode,
+ parseMIMEType,
+ collectAnHTTPQuotedString,
+ serializeAMimeType,
+ removeHTTPWhitespace,
+ minimizeSupportedMimeType,
+ HTTP_TOKEN_CODEPOINTS
+ };
+ }
+});
+
+// node_modules/undici/lib/util/runtime-features.js
+var require_runtime_features = __commonJS({
+ "node_modules/undici/lib/util/runtime-features.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var lazyLoaders = {
+ __proto__: null,
+ "node:crypto": /* @__PURE__ */ __name(() => __require("node:crypto"), "node:crypto"),
+ "node:sqlite": /* @__PURE__ */ __name(() => __require("node:sqlite"), "node:sqlite"),
+ "node:worker_threads": /* @__PURE__ */ __name(() => __require("node:worker_threads"), "node:worker_threads"),
+ "node:zlib": /* @__PURE__ */ __name(() => __require("node:zlib"), "node:zlib")
+ };
+ function detectRuntimeFeatureByNodeModule(moduleName) {
+ try {
+ lazyLoaders[moduleName]();
+ return true;
+ } catch (err) {
+ if (err.code !== "ERR_UNKNOWN_BUILTIN_MODULE" && err.code !== "ERR_NO_CRYPTO") {
+ throw err;
+ }
+ return false;
+ }
+ }
+ __name(detectRuntimeFeatureByNodeModule, "detectRuntimeFeatureByNodeModule");
+ function detectRuntimeFeatureByExportedProperty(moduleName, property) {
+ const module3 = lazyLoaders[moduleName]();
+ return typeof module3[property] !== "undefined";
+ }
+ __name(detectRuntimeFeatureByExportedProperty, "detectRuntimeFeatureByExportedProperty");
+ var runtimeFeaturesByExportedProperty = (
+ /** @type {const} */
+ ["markAsUncloneable", "zstd"]
+ );
+ var exportedPropertyLookup = {
+ markAsUncloneable: ["node:worker_threads", "markAsUncloneable"],
+ zstd: ["node:zlib", "createZstdDecompress"]
+ };
+ var runtimeFeaturesAsNodeModule = (
+ /** @type {const} */
+ ["crypto", "sqlite"]
+ );
+ var features = (
+ /** @type {const} */
+ [
+ ...runtimeFeaturesAsNodeModule,
+ ...runtimeFeaturesByExportedProperty
+ ]
+ );
+ function detectRuntimeFeature(feature) {
+ if (runtimeFeaturesAsNodeModule.includes(
+ /** @type {RuntimeFeatureByNodeModule} */
+ feature
+ )) {
+ return detectRuntimeFeatureByNodeModule(`node:${feature}`);
+ } else if (runtimeFeaturesByExportedProperty.includes(
+ /** @type {RuntimeFeatureByExportedProperty} */
+ feature
+ )) {
+ const [moduleName, property] = exportedPropertyLookup[feature];
+ return detectRuntimeFeatureByExportedProperty(moduleName, property);
+ }
+ throw new TypeError(`unknown feature: ${feature}`);
+ }
+ __name(detectRuntimeFeature, "detectRuntimeFeature");
+ var RuntimeFeatures = class {
+ static {
+ __name(this, "RuntimeFeatures");
+ }
+ /** @type {Map} */
+ #map = /* @__PURE__ */ new Map();
+ /**
+ * Clears all cached feature detections.
+ */
+ clear() {
+ this.#map.clear();
+ }
+ /**
+ * @param {Feature} feature
+ * @returns {boolean}
+ */
+ has(feature) {
+ return this.#map.get(feature) ?? this.#detectRuntimeFeature(feature);
+ }
+ /**
+ * @param {Feature} feature
+ * @param {boolean} value
+ */
+ set(feature, value) {
+ if (features.includes(feature) === false) {
+ throw new TypeError(`unknown feature: ${feature}`);
+ }
+ this.#map.set(feature, value);
+ }
+ /**
+ * @param {Feature} feature
+ * @returns {boolean}
+ */
+ #detectRuntimeFeature(feature) {
+ const result = detectRuntimeFeature(feature);
+ this.#map.set(feature, result);
+ return result;
+ }
+ };
+ var instance = new RuntimeFeatures();
+ module2.exports.runtimeFeatures = instance;
+ module2.exports.default = instance;
+ }
+});
+
+// node_modules/undici/lib/web/webidl/index.js
+var require_webidl = __commonJS({
+ "node_modules/undici/lib/web/webidl/index.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var assert2 = __require("node:assert");
+ var { types, inspect: inspect2 } = __require("node:util");
+ var { runtimeFeatures } = require_runtime_features();
+ var UNDEFINED = 1;
+ var BOOLEAN = 2;
+ var STRING = 3;
+ var SYMBOL = 4;
+ var NUMBER = 5;
+ var BIGINT = 6;
+ var NULL2 = 7;
+ var OBJECT = 8;
+ var FunctionPrototypeSymbolHasInstance = Function.call.bind(Function.prototype[Symbol.hasInstance]);
+ var webidl = {
+ converters: {},
+ util: {},
+ errors: {},
+ is: {}
+ };
+ webidl.errors.exception = function(message) {
+ return new TypeError(`${message.header}: ${message.message}`);
+ };
+ webidl.errors.conversionFailed = function(opts) {
+ const plural = opts.types.length === 1 ? "" : " one of";
+ const message = `${opts.argument} could not be converted to${plural}: ${opts.types.join(", ")}.`;
+ return webidl.errors.exception({
+ header: opts.prefix,
+ message
+ });
+ };
+ webidl.errors.invalidArgument = function(context) {
+ return webidl.errors.exception({
+ header: context.prefix,
+ message: `"${context.value}" is an invalid ${context.type}.`
+ });
+ };
+ webidl.brandCheck = function(V, I) {
+ if (!FunctionPrototypeSymbolHasInstance(I, V)) {
+ const err = new TypeError("Illegal invocation");
+ err.code = "ERR_INVALID_THIS";
+ throw err;
+ }
+ };
+ webidl.brandCheckMultiple = function(List) {
+ const prototypes = List.map((c) => webidl.util.MakeTypeAssertion(c));
+ return (V) => {
+ if (prototypes.every((typeCheck) => !typeCheck(V))) {
+ const err = new TypeError("Illegal invocation");
+ err.code = "ERR_INVALID_THIS";
+ throw err;
+ }
+ };
+ };
+ webidl.argumentLengthCheck = function({ length }, min, ctx) {
+ if (length < min) {
+ throw webidl.errors.exception({
+ message: `${min} argument${min !== 1 ? "s" : ""} required, but${length ? " only" : ""} ${length} found.`,
+ header: ctx
+ });
+ }
+ };
+ webidl.illegalConstructor = function() {
+ throw webidl.errors.exception({
+ header: "TypeError",
+ message: "Illegal constructor"
+ });
+ };
+ webidl.util.MakeTypeAssertion = function(I) {
+ return (O) => FunctionPrototypeSymbolHasInstance(I, O);
+ };
+ webidl.util.Type = function(V) {
+ switch (typeof V) {
+ case "undefined":
+ return UNDEFINED;
+ case "boolean":
+ return BOOLEAN;
+ case "string":
+ return STRING;
+ case "symbol":
+ return SYMBOL;
+ case "number":
+ return NUMBER;
+ case "bigint":
+ return BIGINT;
+ case "function":
+ case "object": {
+ if (V === null) {
+ return NULL2;
+ }
+ return OBJECT;
+ }
+ }
+ };
+ webidl.util.Types = {
+ UNDEFINED,
+ BOOLEAN,
+ STRING,
+ SYMBOL,
+ NUMBER,
+ BIGINT,
+ NULL: NULL2,
+ OBJECT
+ };
+ webidl.util.TypeValueToString = function(o) {
+ switch (webidl.util.Type(o)) {
+ case UNDEFINED:
+ return "Undefined";
+ case BOOLEAN:
+ return "Boolean";
+ case STRING:
+ return "String";
+ case SYMBOL:
+ return "Symbol";
+ case NUMBER:
+ return "Number";
+ case BIGINT:
+ return "BigInt";
+ case NULL2:
+ return "Null";
+ case OBJECT:
+ return "Object";
+ }
+ };
+ webidl.util.markAsUncloneable = runtimeFeatures.has("markAsUncloneable") ? __require("node:worker_threads").markAsUncloneable : () => {
+ };
+ webidl.util.ConvertToInt = function(V, bitLength, signedness, flags) {
+ let upperBound;
+ let lowerBound;
+ if (bitLength === 64) {
+ upperBound = Math.pow(2, 53) - 1;
+ if (signedness === "unsigned") {
+ lowerBound = 0;
+ } else {
+ lowerBound = Math.pow(-2, 53) + 1;
+ }
+ } else if (signedness === "unsigned") {
+ lowerBound = 0;
+ upperBound = Math.pow(2, bitLength) - 1;
+ } else {
+ lowerBound = -Math.pow(2, bitLength - 1);
+ upperBound = Math.pow(2, bitLength - 1) - 1;
+ }
+ let x = Number(V);
+ if (x === 0) {
+ x = 0;
+ }
+ if (webidl.util.HasFlag(flags, webidl.attributes.EnforceRange)) {
+ if (Number.isNaN(x) || x === Number.POSITIVE_INFINITY || x === Number.NEGATIVE_INFINITY) {
+ throw webidl.errors.exception({
+ header: "Integer conversion",
+ message: `Could not convert ${webidl.util.Stringify(V)} to an integer.`
+ });
+ }
+ x = webidl.util.IntegerPart(x);
+ if (x < lowerBound || x > upperBound) {
+ throw webidl.errors.exception({
+ header: "Integer conversion",
+ message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.`
+ });
+ }
+ return x;
+ }
+ if (!Number.isNaN(x) && webidl.util.HasFlag(flags, webidl.attributes.Clamp)) {
+ x = Math.min(Math.max(x, lowerBound), upperBound);
+ if (Math.floor(x) % 2 === 0) {
+ x = Math.floor(x);
+ } else {
+ x = Math.ceil(x);
+ }
+ return x;
+ }
+ if (Number.isNaN(x) || x === 0 && Object.is(0, x) || x === Number.POSITIVE_INFINITY || x === Number.NEGATIVE_INFINITY) {
+ return 0;
+ }
+ x = webidl.util.IntegerPart(x);
+ x = x % Math.pow(2, bitLength);
+ if (signedness === "signed" && x >= Math.pow(2, bitLength - 1)) {
+ return x - Math.pow(2, bitLength);
+ }
+ return x;
+ };
+ webidl.util.IntegerPart = function(n) {
+ const r = Math.floor(Math.abs(n));
+ if (n < 0) {
+ return -1 * r;
+ }
+ return r;
+ };
+ webidl.util.Stringify = function(V) {
+ const type2 = webidl.util.Type(V);
+ switch (type2) {
+ case SYMBOL:
+ return `Symbol(${V.description})`;
+ case OBJECT:
+ return inspect2(V);
+ case STRING:
+ return `"${V}"`;
+ case BIGINT:
+ return `${V}n`;
+ default:
+ return `${V}`;
+ }
+ };
+ webidl.util.IsResizableArrayBuffer = function(V) {
+ if (types.isArrayBuffer(V)) {
+ return V.resizable;
+ }
+ if (types.isSharedArrayBuffer(V)) {
+ return V.growable;
+ }
+ throw webidl.errors.exception({
+ header: "IsResizableArrayBuffer",
+ message: `"${webidl.util.Stringify(V)}" is not an array buffer.`
+ });
+ };
+ webidl.util.HasFlag = function(flags, attributes) {
+ return typeof flags === "number" && (flags & attributes) === attributes;
+ };
+ webidl.sequenceConverter = function(converter) {
+ return (V, prefix, argument, Iterable) => {
+ if (webidl.util.Type(V) !== OBJECT) {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: `${argument} (${webidl.util.Stringify(V)}) is not iterable.`
+ });
+ }
+ const method = typeof Iterable === "function" ? Iterable() : V?.[Symbol.iterator]?.();
+ const seq = [];
+ let index = 0;
+ if (method === void 0 || typeof method.next !== "function") {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: `${argument} is not iterable.`
+ });
+ }
+ while (true) {
+ const { done, value } = method.next();
+ if (done) {
+ break;
+ }
+ seq.push(converter(value, prefix, `${argument}[${index++}]`));
+ }
+ return seq;
+ };
+ };
+ webidl.recordConverter = function(keyConverter, valueConverter) {
+ return (O, prefix, argument) => {
+ if (webidl.util.Type(O) !== OBJECT) {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: `${argument} ("${webidl.util.TypeValueToString(O)}") is not an Object.`
+ });
+ }
+ const result = {};
+ if (!types.isProxy(O)) {
+ const keys2 = [...Object.getOwnPropertyNames(O), ...Object.getOwnPropertySymbols(O)];
+ for (const key of keys2) {
+ const keyName2 = webidl.util.Stringify(key);
+ const typedKey = keyConverter(key, prefix, `Key ${keyName2} in ${argument}`);
+ const typedValue = valueConverter(O[key], prefix, `${argument}[${keyName2}]`);
+ result[typedKey] = typedValue;
+ }
+ return result;
+ }
+ const keys = Reflect.ownKeys(O);
+ for (const key of keys) {
+ const desc = Reflect.getOwnPropertyDescriptor(O, key);
+ if (desc?.enumerable) {
+ const typedKey = keyConverter(key, prefix, argument);
+ const typedValue = valueConverter(O[key], prefix, argument);
+ result[typedKey] = typedValue;
+ }
+ }
+ return result;
+ };
+ };
+ webidl.interfaceConverter = function(TypeCheck, name) {
+ return (V, prefix, argument) => {
+ if (!TypeCheck(V)) {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: `Expected ${argument} ("${webidl.util.Stringify(V)}") to be an instance of ${name}.`
+ });
+ }
+ return V;
+ };
+ };
+ webidl.dictionaryConverter = function(converters) {
+ converters.sort((a, b) => (a.key > b.key) - (a.key < b.key));
+ return (dictionary, prefix, argument) => {
+ const dict = {};
+ if (dictionary != null && webidl.util.Type(dictionary) !== OBJECT) {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: `Expected ${dictionary} to be one of: Null, Undefined, Object.`
+ });
+ }
+ for (const options2 of converters) {
+ const { key, defaultValue: defaultValue2, required: required2, converter } = options2;
+ if (required2 === true) {
+ if (dictionary == null || !Object.hasOwn(dictionary, key)) {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: `Missing required key "${key}".`
+ });
+ }
+ }
+ let value = dictionary?.[key];
+ const hasDefault = defaultValue2 !== void 0;
+ if (hasDefault && value === void 0) {
+ value = defaultValue2();
+ }
+ if (required2 || hasDefault || value !== void 0) {
+ value = converter(value, prefix, `${argument}.${key}`);
+ if (options2.allowedValues && !options2.allowedValues.includes(value)) {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: `${value} is not an accepted type. Expected one of ${options2.allowedValues.join(", ")}.`
+ });
+ }
+ dict[key] = value;
+ }
+ }
+ return dict;
+ };
+ };
+ webidl.nullableConverter = function(converter) {
+ return (V, prefix, argument) => {
+ if (V === null) {
+ return V;
+ }
+ return converter(V, prefix, argument);
+ };
+ };
+ webidl.is.USVString = function(value) {
+ return typeof value === "string" && value.isWellFormed();
+ };
+ webidl.is.ReadableStream = webidl.util.MakeTypeAssertion(ReadableStream);
+ webidl.is.Blob = webidl.util.MakeTypeAssertion(Blob);
+ webidl.is.URLSearchParams = webidl.util.MakeTypeAssertion(URLSearchParams);
+ webidl.is.File = webidl.util.MakeTypeAssertion(File);
+ webidl.is.URL = webidl.util.MakeTypeAssertion(URL);
+ webidl.is.AbortSignal = webidl.util.MakeTypeAssertion(AbortSignal);
+ webidl.is.MessagePort = webidl.util.MakeTypeAssertion(MessagePort);
+ webidl.is.BufferSource = function(V) {
+ return types.isArrayBuffer(V) || ArrayBuffer.isView(V) && types.isArrayBuffer(V.buffer);
+ };
+ webidl.util.getCopyOfBytesHeldByBufferSource = function(bufferSource) {
+ const jsBufferSource = bufferSource;
+ let jsArrayBuffer = jsBufferSource;
+ let offset = 0;
+ let length = 0;
+ if (types.isTypedArray(jsBufferSource) || types.isDataView(jsBufferSource)) {
+ jsArrayBuffer = jsBufferSource.buffer;
+ offset = jsBufferSource.byteOffset;
+ length = jsBufferSource.byteLength;
+ } else {
+ assert2(types.isAnyArrayBuffer(jsBufferSource));
+ length = jsBufferSource.byteLength;
+ }
+ if (jsArrayBuffer.detached) {
+ return new Uint8Array(0);
+ }
+ const bytes = new Uint8Array(length);
+ const view = new Uint8Array(jsArrayBuffer, offset, length);
+ bytes.set(view);
+ return bytes;
+ };
+ webidl.converters.DOMString = function(V, prefix, argument, flags) {
+ if (V === null && webidl.util.HasFlag(flags, webidl.attributes.LegacyNullToEmptyString)) {
+ return "";
+ }
+ if (typeof V === "symbol") {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: `${argument} is a symbol, which cannot be converted to a DOMString.`
+ });
+ }
+ return String(V);
+ };
+ webidl.converters.ByteString = function(V, prefix, argument) {
+ if (typeof V === "symbol") {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: `${argument} is a symbol, which cannot be converted to a ByteString.`
+ });
+ }
+ const x = String(V);
+ for (let index = 0; index < x.length; index++) {
+ if (x.charCodeAt(index) > 255) {
+ throw new TypeError(
+ `Cannot convert argument to a ByteString because the character at index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.`
+ );
+ }
+ }
+ return x;
+ };
+ webidl.converters.USVString = function(value) {
+ if (typeof value === "string") {
+ return value.toWellFormed();
+ }
+ return `${value}`.toWellFormed();
+ };
+ webidl.converters.boolean = function(V) {
+ const x = Boolean(V);
+ return x;
+ };
+ webidl.converters.any = function(V) {
+ return V;
+ };
+ webidl.converters["long long"] = function(V, prefix, argument) {
+ const x = webidl.util.ConvertToInt(V, 64, "signed", 0, prefix, argument);
+ return x;
+ };
+ webidl.converters["unsigned long long"] = function(V, prefix, argument) {
+ const x = webidl.util.ConvertToInt(V, 64, "unsigned", 0, prefix, argument);
+ return x;
+ };
+ webidl.converters["unsigned long"] = function(V, prefix, argument) {
+ const x = webidl.util.ConvertToInt(V, 32, "unsigned", 0, prefix, argument);
+ return x;
+ };
+ webidl.converters["unsigned short"] = function(V, prefix, argument, flags) {
+ const x = webidl.util.ConvertToInt(V, 16, "unsigned", flags, prefix, argument);
+ return x;
+ };
+ webidl.converters.ArrayBuffer = function(V, prefix, argument, flags) {
+ if (webidl.util.Type(V) !== OBJECT || !types.isArrayBuffer(V)) {
+ throw webidl.errors.conversionFailed({
+ prefix,
+ argument: `${argument} ("${webidl.util.Stringify(V)}")`,
+ types: ["ArrayBuffer"]
+ });
+ }
+ if (!webidl.util.HasFlag(flags, webidl.attributes.AllowResizable) && webidl.util.IsResizableArrayBuffer(V)) {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: `${argument} cannot be a resizable ArrayBuffer.`
+ });
+ }
+ return V;
+ };
+ webidl.converters.SharedArrayBuffer = function(V, prefix, argument, flags) {
+ if (webidl.util.Type(V) !== OBJECT || !types.isSharedArrayBuffer(V)) {
+ throw webidl.errors.conversionFailed({
+ prefix,
+ argument: `${argument} ("${webidl.util.Stringify(V)}")`,
+ types: ["SharedArrayBuffer"]
+ });
+ }
+ if (!webidl.util.HasFlag(flags, webidl.attributes.AllowResizable) && webidl.util.IsResizableArrayBuffer(V)) {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: `${argument} cannot be a resizable SharedArrayBuffer.`
+ });
+ }
+ return V;
+ };
+ webidl.converters.TypedArray = function(V, T, prefix, argument, flags) {
+ if (webidl.util.Type(V) !== OBJECT || !types.isTypedArray(V) || V.constructor.name !== T.name) {
+ throw webidl.errors.conversionFailed({
+ prefix,
+ argument: `${argument} ("${webidl.util.Stringify(V)}")`,
+ types: [T.name]
+ });
+ }
+ if (!webidl.util.HasFlag(flags, webidl.attributes.AllowShared) && types.isSharedArrayBuffer(V.buffer)) {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: `${argument} cannot be a view on a shared array buffer.`
+ });
+ }
+ if (!webidl.util.HasFlag(flags, webidl.attributes.AllowResizable) && webidl.util.IsResizableArrayBuffer(V.buffer)) {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: `${argument} cannot be a view on a resizable array buffer.`
+ });
+ }
+ return V;
+ };
+ webidl.converters.DataView = function(V, prefix, argument, flags) {
+ if (webidl.util.Type(V) !== OBJECT || !types.isDataView(V)) {
+ throw webidl.errors.conversionFailed({
+ prefix,
+ argument: `${argument} ("${webidl.util.Stringify(V)}")`,
+ types: ["DataView"]
+ });
+ }
+ if (!webidl.util.HasFlag(flags, webidl.attributes.AllowShared) && types.isSharedArrayBuffer(V.buffer)) {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: `${argument} cannot be a view on a shared array buffer.`
+ });
+ }
+ if (!webidl.util.HasFlag(flags, webidl.attributes.AllowResizable) && webidl.util.IsResizableArrayBuffer(V.buffer)) {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: `${argument} cannot be a view on a resizable array buffer.`
+ });
+ }
+ return V;
+ };
+ webidl.converters.ArrayBufferView = function(V, prefix, argument, flags) {
+ if (webidl.util.Type(V) !== OBJECT || !types.isArrayBufferView(V)) {
+ throw webidl.errors.conversionFailed({
+ prefix,
+ argument: `${argument} ("${webidl.util.Stringify(V)}")`,
+ types: ["ArrayBufferView"]
+ });
+ }
+ if (!webidl.util.HasFlag(flags, webidl.attributes.AllowShared) && types.isSharedArrayBuffer(V.buffer)) {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: `${argument} cannot be a view on a shared array buffer.`
+ });
+ }
+ if (!webidl.util.HasFlag(flags, webidl.attributes.AllowResizable) && webidl.util.IsResizableArrayBuffer(V.buffer)) {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: `${argument} cannot be a view on a resizable array buffer.`
+ });
+ }
+ return V;
+ };
+ webidl.converters.BufferSource = function(V, prefix, argument, flags) {
+ if (types.isArrayBuffer(V)) {
+ return webidl.converters.ArrayBuffer(V, prefix, argument, flags);
+ }
+ if (types.isArrayBufferView(V)) {
+ flags &= ~webidl.attributes.AllowShared;
+ return webidl.converters.ArrayBufferView(V, prefix, argument, flags);
+ }
+ if (types.isSharedArrayBuffer(V)) {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: `${argument} cannot be a SharedArrayBuffer.`
+ });
+ }
+ throw webidl.errors.conversionFailed({
+ prefix,
+ argument: `${argument} ("${webidl.util.Stringify(V)}")`,
+ types: ["ArrayBuffer", "ArrayBufferView"]
+ });
+ };
+ webidl.converters.AllowSharedBufferSource = function(V, prefix, argument, flags) {
+ if (types.isArrayBuffer(V)) {
+ return webidl.converters.ArrayBuffer(V, prefix, argument, flags);
+ }
+ if (types.isSharedArrayBuffer(V)) {
+ return webidl.converters.SharedArrayBuffer(V, prefix, argument, flags);
+ }
+ if (types.isArrayBufferView(V)) {
+ flags |= webidl.attributes.AllowShared;
+ return webidl.converters.ArrayBufferView(V, prefix, argument, flags);
+ }
+ throw webidl.errors.conversionFailed({
+ prefix,
+ argument: `${argument} ("${webidl.util.Stringify(V)}")`,
+ types: ["ArrayBuffer", "SharedArrayBuffer", "ArrayBufferView"]
+ });
+ };
+ webidl.converters["sequence"] = webidl.sequenceConverter(
+ webidl.converters.ByteString
+ );
+ webidl.converters["sequence>"] = webidl.sequenceConverter(
+ webidl.converters["sequence"]
+ );
+ webidl.converters["record"] = webidl.recordConverter(
+ webidl.converters.ByteString,
+ webidl.converters.ByteString
+ );
+ webidl.converters.Blob = webidl.interfaceConverter(webidl.is.Blob, "Blob");
+ webidl.converters.AbortSignal = webidl.interfaceConverter(
+ webidl.is.AbortSignal,
+ "AbortSignal"
+ );
+ webidl.converters.EventHandlerNonNull = function(V) {
+ if (webidl.util.Type(V) !== OBJECT) {
+ return null;
+ }
+ if (typeof V === "function") {
+ return V;
+ }
+ return () => {
+ };
+ };
+ webidl.attributes = {
+ Clamp: 1 << 0,
+ EnforceRange: 1 << 1,
+ AllowShared: 1 << 2,
+ AllowResizable: 1 << 3,
+ LegacyNullToEmptyString: 1 << 4
+ };
+ module2.exports = {
+ webidl
+ };
+ }
+});
+
+// node_modules/undici/lib/web/fetch/util.js
+var require_util2 = __commonJS({
+ "node_modules/undici/lib/web/fetch/util.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { Transform: Transform2 } = __require("node:stream");
+ var zlib = __require("node:zlib");
+ var { redirectStatusSet, referrerPolicyTokens, badPortsSet } = require_constants4();
+ var { getGlobalOrigin } = require_global();
+ var { collectAnHTTPQuotedString, parseMIMEType } = require_data_url();
+ var { performance: performance2 } = __require("node:perf_hooks");
+ var { ReadableStreamFrom: ReadableStreamFrom2, isValidHTTPToken, normalizedMethodRecordsBase } = require_util();
+ var assert2 = __require("node:assert");
+ var { isUint8Array } = __require("node:util/types");
+ var { webidl } = require_webidl();
+ var { isomorphicEncode, collectASequenceOfCodePoints, removeChars } = require_infra();
+ function responseURL(response) {
+ const urlList = response.urlList;
+ const length = urlList.length;
+ return length === 0 ? null : urlList[length - 1].toString();
+ }
+ __name(responseURL, "responseURL");
+ function responseLocationURL(response, requestFragment) {
+ if (!redirectStatusSet.has(response.status)) {
+ return null;
+ }
+ let location = response.headersList.get("location", true);
+ if (location !== null && isValidHeaderValue(location)) {
+ if (!isValidEncodedURL(location)) {
+ location = normalizeBinaryStringToUtf8(location);
+ }
+ location = new URL(location, responseURL(response));
+ }
+ if (location && !location.hash) {
+ location.hash = requestFragment;
+ }
+ return location;
+ }
+ __name(responseLocationURL, "responseLocationURL");
+ function isValidEncodedURL(url2) {
+ for (let i = 0; i < url2.length; ++i) {
+ const code = url2.charCodeAt(i);
+ if (code > 126 || // Non-US-ASCII + DEL
+ code < 32) {
+ return false;
+ }
+ }
+ return true;
+ }
+ __name(isValidEncodedURL, "isValidEncodedURL");
+ function normalizeBinaryStringToUtf8(value) {
+ return Buffer.from(value, "binary").toString("utf8");
+ }
+ __name(normalizeBinaryStringToUtf8, "normalizeBinaryStringToUtf8");
+ function requestCurrentURL(request) {
+ return request.urlList[request.urlList.length - 1];
+ }
+ __name(requestCurrentURL, "requestCurrentURL");
+ function requestBadPort(request) {
+ const url2 = requestCurrentURL(request);
+ if (urlIsHttpHttpsScheme(url2) && badPortsSet.has(url2.port)) {
+ return "blocked";
+ }
+ return "allowed";
+ }
+ __name(requestBadPort, "requestBadPort");
+ function isErrorLike(object2) {
+ return object2 instanceof Error || (object2?.constructor?.name === "Error" || object2?.constructor?.name === "DOMException");
+ }
+ __name(isErrorLike, "isErrorLike");
+ function isValidReasonPhrase(statusText) {
+ for (let i = 0; i < statusText.length; ++i) {
+ const c = statusText.charCodeAt(i);
+ if (!(c === 9 || // HTAB
+ c >= 32 && c <= 126 || // SP / VCHAR
+ c >= 128 && c <= 255)) {
+ return false;
+ }
+ }
+ return true;
+ }
+ __name(isValidReasonPhrase, "isValidReasonPhrase");
+ var isValidHeaderName = isValidHTTPToken;
+ function isValidHeaderValue(potentialValue) {
+ return (potentialValue[0] === " " || potentialValue[0] === " " || potentialValue[potentialValue.length - 1] === " " || potentialValue[potentialValue.length - 1] === " " || potentialValue.includes("\n") || potentialValue.includes("\r") || potentialValue.includes("\0")) === false;
+ }
+ __name(isValidHeaderValue, "isValidHeaderValue");
+ function parseReferrerPolicy(actualResponse) {
+ const policyHeader = (actualResponse.headersList.get("referrer-policy", true) ?? "").split(",");
+ let policy = "";
+ if (policyHeader.length) {
+ for (let i = policyHeader.length; i !== 0; i--) {
+ const token = policyHeader[i - 1].trim();
+ if (referrerPolicyTokens.has(token)) {
+ policy = token;
+ break;
+ }
+ }
+ }
+ return policy;
+ }
+ __name(parseReferrerPolicy, "parseReferrerPolicy");
+ function setRequestReferrerPolicyOnRedirect(request, actualResponse) {
+ const policy = parseReferrerPolicy(actualResponse);
+ if (policy !== "") {
+ request.referrerPolicy = policy;
+ }
+ }
+ __name(setRequestReferrerPolicyOnRedirect, "setRequestReferrerPolicyOnRedirect");
+ function crossOriginResourcePolicyCheck() {
+ return "allowed";
+ }
+ __name(crossOriginResourcePolicyCheck, "crossOriginResourcePolicyCheck");
+ function corsCheck() {
+ return "success";
+ }
+ __name(corsCheck, "corsCheck");
+ function TAOCheck() {
+ return "success";
+ }
+ __name(TAOCheck, "TAOCheck");
+ function appendFetchMetadata(httpRequest) {
+ let header = null;
+ header = httpRequest.mode;
+ httpRequest.headersList.set("sec-fetch-mode", header, true);
+ }
+ __name(appendFetchMetadata, "appendFetchMetadata");
+ function appendRequestOriginHeader(request) {
+ let serializedOrigin = request.origin;
+ if (serializedOrigin === "client" || serializedOrigin === void 0) {
+ return;
+ }
+ if (request.responseTainting === "cors" || request.mode === "websocket") {
+ request.headersList.append("origin", serializedOrigin, true);
+ } else if (request.method !== "GET" && request.method !== "HEAD") {
+ switch (request.referrerPolicy) {
+ case "no-referrer":
+ serializedOrigin = null;
+ break;
+ case "no-referrer-when-downgrade":
+ case "strict-origin":
+ case "strict-origin-when-cross-origin":
+ if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) {
+ serializedOrigin = null;
+ }
+ break;
+ case "same-origin":
+ if (!sameOrigin(request, requestCurrentURL(request))) {
+ serializedOrigin = null;
+ }
+ break;
+ default:
+ }
+ request.headersList.append("origin", serializedOrigin, true);
+ }
+ }
+ __name(appendRequestOriginHeader, "appendRequestOriginHeader");
+ function coarsenTime(timestamp, crossOriginIsolatedCapability) {
+ return timestamp;
+ }
+ __name(coarsenTime, "coarsenTime");
+ function clampAndCoarsenConnectionTimingInfo(connectionTimingInfo, defaultStartTime, crossOriginIsolatedCapability) {
+ if (!connectionTimingInfo?.startTime || connectionTimingInfo.startTime < defaultStartTime) {
+ return {
+ domainLookupStartTime: defaultStartTime,
+ domainLookupEndTime: defaultStartTime,
+ connectionStartTime: defaultStartTime,
+ connectionEndTime: defaultStartTime,
+ secureConnectionStartTime: defaultStartTime,
+ ALPNNegotiatedProtocol: connectionTimingInfo?.ALPNNegotiatedProtocol
+ };
+ }
+ return {
+ domainLookupStartTime: coarsenTime(connectionTimingInfo.domainLookupStartTime, crossOriginIsolatedCapability),
+ domainLookupEndTime: coarsenTime(connectionTimingInfo.domainLookupEndTime, crossOriginIsolatedCapability),
+ connectionStartTime: coarsenTime(connectionTimingInfo.connectionStartTime, crossOriginIsolatedCapability),
+ connectionEndTime: coarsenTime(connectionTimingInfo.connectionEndTime, crossOriginIsolatedCapability),
+ secureConnectionStartTime: coarsenTime(connectionTimingInfo.secureConnectionStartTime, crossOriginIsolatedCapability),
+ ALPNNegotiatedProtocol: connectionTimingInfo.ALPNNegotiatedProtocol
+ };
+ }
+ __name(clampAndCoarsenConnectionTimingInfo, "clampAndCoarsenConnectionTimingInfo");
+ function coarsenedSharedCurrentTime(crossOriginIsolatedCapability) {
+ return coarsenTime(performance2.now(), crossOriginIsolatedCapability);
+ }
+ __name(coarsenedSharedCurrentTime, "coarsenedSharedCurrentTime");
+ function createOpaqueTimingInfo(timingInfo) {
+ return {
+ startTime: timingInfo.startTime ?? 0,
+ redirectStartTime: 0,
+ redirectEndTime: 0,
+ postRedirectStartTime: timingInfo.startTime ?? 0,
+ finalServiceWorkerStartTime: 0,
+ finalNetworkResponseStartTime: 0,
+ finalNetworkRequestStartTime: 0,
+ endTime: 0,
+ encodedBodySize: 0,
+ decodedBodySize: 0,
+ finalConnectionTimingInfo: null
+ };
+ }
+ __name(createOpaqueTimingInfo, "createOpaqueTimingInfo");
+ function makePolicyContainer() {
+ return {
+ referrerPolicy: "strict-origin-when-cross-origin"
+ };
+ }
+ __name(makePolicyContainer, "makePolicyContainer");
+ function clonePolicyContainer(policyContainer) {
+ return {
+ referrerPolicy: policyContainer.referrerPolicy
+ };
+ }
+ __name(clonePolicyContainer, "clonePolicyContainer");
+ function determineRequestsReferrer(request) {
+ const policy = request.referrerPolicy;
+ assert2(policy);
+ let referrerSource = null;
+ if (request.referrer === "client") {
+ const globalOrigin = getGlobalOrigin();
+ if (!globalOrigin || globalOrigin.origin === "null") {
+ return "no-referrer";
+ }
+ referrerSource = new URL(globalOrigin);
+ } else if (webidl.is.URL(request.referrer)) {
+ referrerSource = request.referrer;
+ }
+ let referrerURL = stripURLForReferrer(referrerSource);
+ const referrerOrigin = stripURLForReferrer(referrerSource, true);
+ if (referrerURL.toString().length > 4096) {
+ referrerURL = referrerOrigin;
+ }
+ switch (policy) {
+ case "no-referrer":
+ return "no-referrer";
+ case "origin":
+ if (referrerOrigin != null) {
+ return referrerOrigin;
+ }
+ return stripURLForReferrer(referrerSource, true);
+ case "unsafe-url":
+ return referrerURL;
+ case "strict-origin": {
+ const currentURL = requestCurrentURL(request);
+ if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) {
+ return "no-referrer";
+ }
+ return referrerOrigin;
+ }
+ case "strict-origin-when-cross-origin": {
+ const currentURL = requestCurrentURL(request);
+ if (sameOrigin(referrerURL, currentURL)) {
+ return referrerURL;
+ }
+ if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) {
+ return "no-referrer";
+ }
+ return referrerOrigin;
+ }
+ case "same-origin":
+ if (sameOrigin(request, referrerURL)) {
+ return referrerURL;
+ }
+ return "no-referrer";
+ case "origin-when-cross-origin":
+ if (sameOrigin(request, referrerURL)) {
+ return referrerURL;
+ }
+ return referrerOrigin;
+ case "no-referrer-when-downgrade": {
+ const currentURL = requestCurrentURL(request);
+ if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) {
+ return "no-referrer";
+ }
+ return referrerURL;
+ }
+ }
+ }
+ __name(determineRequestsReferrer, "determineRequestsReferrer");
+ function stripURLForReferrer(url2, originOnly = false) {
+ assert2(webidl.is.URL(url2));
+ url2 = new URL(url2);
+ if (urlIsLocal(url2)) {
+ return "no-referrer";
+ }
+ url2.username = "";
+ url2.password = "";
+ url2.hash = "";
+ if (originOnly === true) {
+ url2.pathname = "";
+ url2.search = "";
+ }
+ return url2;
+ }
+ __name(stripURLForReferrer, "stripURLForReferrer");
+ var isPotentialleTrustworthyIPv4 = RegExp.prototype.test.bind(/^127\.(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){2}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)$/);
+ var isPotentiallyTrustworthyIPv6 = RegExp.prototype.test.bind(/^(?:(?:0{1,4}:){7}|(?:0{1,4}:){1,6}:|::)0{0,3}1$/);
+ function isOriginIPPotentiallyTrustworthy(origin) {
+ if (origin.includes(":")) {
+ if (origin[0] === "[" && origin[origin.length - 1] === "]") {
+ origin = origin.slice(1, -1);
+ }
+ return isPotentiallyTrustworthyIPv6(origin);
+ }
+ return isPotentialleTrustworthyIPv4(origin);
+ }
+ __name(isOriginIPPotentiallyTrustworthy, "isOriginIPPotentiallyTrustworthy");
+ function isOriginPotentiallyTrustworthy(origin) {
+ if (origin == null || origin === "null") {
+ return false;
+ }
+ origin = new URL(origin);
+ if (origin.protocol === "https:" || origin.protocol === "wss:") {
+ return true;
+ }
+ if (isOriginIPPotentiallyTrustworthy(origin.hostname)) {
+ return true;
+ }
+ if (origin.hostname === "localhost" || origin.hostname === "localhost.") {
+ return true;
+ }
+ if (origin.hostname.endsWith(".localhost") || origin.hostname.endsWith(".localhost.")) {
+ return true;
+ }
+ if (origin.protocol === "file:") {
+ return true;
+ }
+ return false;
+ }
+ __name(isOriginPotentiallyTrustworthy, "isOriginPotentiallyTrustworthy");
+ function isURLPotentiallyTrustworthy(url2) {
+ if (!webidl.is.URL(url2)) {
+ return false;
+ }
+ if (url2.href === "about:blank" || url2.href === "about:srcdoc") {
+ return true;
+ }
+ if (url2.protocol === "data:") return true;
+ if (url2.protocol === "blob:") return true;
+ return isOriginPotentiallyTrustworthy(url2.origin);
+ }
+ __name(isURLPotentiallyTrustworthy, "isURLPotentiallyTrustworthy");
+ function tryUpgradeRequestToAPotentiallyTrustworthyURL(request) {
+ }
+ __name(tryUpgradeRequestToAPotentiallyTrustworthyURL, "tryUpgradeRequestToAPotentiallyTrustworthyURL");
+ function sameOrigin(A, B) {
+ if (A.origin === B.origin && A.origin === "null") {
+ return true;
+ }
+ if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) {
+ return true;
+ }
+ return false;
+ }
+ __name(sameOrigin, "sameOrigin");
+ function isAborted(fetchParams) {
+ return fetchParams.controller.state === "aborted";
+ }
+ __name(isAborted, "isAborted");
+ function isCancelled(fetchParams) {
+ return fetchParams.controller.state === "aborted" || fetchParams.controller.state === "terminated";
+ }
+ __name(isCancelled, "isCancelled");
+ function normalizeMethod(method) {
+ return normalizedMethodRecordsBase[method.toLowerCase()] ?? method;
+ }
+ __name(normalizeMethod, "normalizeMethod");
+ var esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()));
+ function createIterator(name, kInternalIterator, keyIndex = 0, valueIndex = 1) {
+ class FastIterableIterator {
+ static {
+ __name(this, "FastIterableIterator");
+ }
+ /** @type {any} */
+ #target;
+ /** @type {'key' | 'value' | 'key+value'} */
+ #kind;
+ /** @type {number} */
+ #index;
+ /**
+ * @see https://webidl.spec.whatwg.org/#dfn-default-iterator-object
+ * @param {unknown} target
+ * @param {'key' | 'value' | 'key+value'} kind
+ */
+ constructor(target, kind) {
+ this.#target = target;
+ this.#kind = kind;
+ this.#index = 0;
+ }
+ next() {
+ if (typeof this !== "object" || this === null || !(#target in this)) {
+ throw new TypeError(
+ `'next' called on an object that does not implement interface ${name} Iterator.`
+ );
+ }
+ const index = this.#index;
+ const values = kInternalIterator(this.#target);
+ const len = values.length;
+ if (index >= len) {
+ return {
+ value: void 0,
+ done: true
+ };
+ }
+ const { [keyIndex]: key, [valueIndex]: value } = values[index];
+ this.#index = index + 1;
+ let result;
+ switch (this.#kind) {
+ case "key":
+ result = key;
+ break;
+ case "value":
+ result = value;
+ break;
+ case "key+value":
+ result = [key, value];
+ break;
+ }
+ return {
+ value: result,
+ done: false
+ };
+ }
+ }
+ delete FastIterableIterator.prototype.constructor;
+ Object.setPrototypeOf(FastIterableIterator.prototype, esIteratorPrototype);
+ Object.defineProperties(FastIterableIterator.prototype, {
+ [Symbol.toStringTag]: {
+ writable: false,
+ enumerable: false,
+ configurable: true,
+ value: `${name} Iterator`
+ },
+ next: { writable: true, enumerable: true, configurable: true }
+ });
+ return function(target, kind) {
+ return new FastIterableIterator(target, kind);
+ };
+ }
+ __name(createIterator, "createIterator");
+ function iteratorMixin(name, object2, kInternalIterator, keyIndex = 0, valueIndex = 1) {
+ const makeIterator = createIterator(name, kInternalIterator, keyIndex, valueIndex);
+ const properties = {
+ keys: {
+ writable: true,
+ enumerable: true,
+ configurable: true,
+ value: /* @__PURE__ */ __name(function keys() {
+ webidl.brandCheck(this, object2);
+ return makeIterator(this, "key");
+ }, "keys")
+ },
+ values: {
+ writable: true,
+ enumerable: true,
+ configurable: true,
+ value: /* @__PURE__ */ __name(function values() {
+ webidl.brandCheck(this, object2);
+ return makeIterator(this, "value");
+ }, "values")
+ },
+ entries: {
+ writable: true,
+ enumerable: true,
+ configurable: true,
+ value: /* @__PURE__ */ __name(function entries() {
+ webidl.brandCheck(this, object2);
+ return makeIterator(this, "key+value");
+ }, "entries")
+ },
+ forEach: {
+ writable: true,
+ enumerable: true,
+ configurable: true,
+ value: /* @__PURE__ */ __name(function forEach(callbackfn, thisArg = globalThis) {
+ webidl.brandCheck(this, object2);
+ webidl.argumentLengthCheck(arguments, 1, `${name}.forEach`);
+ if (typeof callbackfn !== "function") {
+ throw new TypeError(
+ `Failed to execute 'forEach' on '${name}': parameter 1 is not of type 'Function'.`
+ );
+ }
+ for (const { 0: key, 1: value } of makeIterator(this, "key+value")) {
+ callbackfn.call(thisArg, value, key, this);
+ }
+ }, "forEach")
+ }
+ };
+ return Object.defineProperties(object2.prototype, {
+ ...properties,
+ [Symbol.iterator]: {
+ writable: true,
+ enumerable: false,
+ configurable: true,
+ value: properties.entries.value
+ }
+ });
+ }
+ __name(iteratorMixin, "iteratorMixin");
+ function fullyReadBody(body, processBody, processBodyError) {
+ const successSteps = processBody;
+ const errorSteps = processBodyError;
+ try {
+ const reader = body.stream.getReader();
+ readAllBytes(reader, successSteps, errorSteps);
+ } catch (e) {
+ errorSteps(e);
+ }
+ }
+ __name(fullyReadBody, "fullyReadBody");
+ function readableStreamClose(controller) {
+ try {
+ controller.close();
+ controller.byobRequest?.respond(0);
+ } catch (err) {
+ if (!err.message.includes("Controller is already closed") && !err.message.includes("ReadableStream is already closed")) {
+ throw err;
+ }
+ }
+ }
+ __name(readableStreamClose, "readableStreamClose");
+ async function readAllBytes(reader, successSteps, failureSteps) {
+ try {
+ const bytes = [];
+ let byteLength = 0;
+ do {
+ const { done, value: chunk } = await reader.read();
+ if (done) {
+ successSteps(Buffer.concat(bytes, byteLength));
+ return;
+ }
+ if (!isUint8Array(chunk)) {
+ failureSteps(new TypeError("Received non-Uint8Array chunk"));
+ return;
+ }
+ bytes.push(chunk);
+ byteLength += chunk.length;
+ } while (true);
+ } catch (e) {
+ failureSteps(e);
+ }
+ }
+ __name(readAllBytes, "readAllBytes");
+ function urlIsLocal(url2) {
+ assert2("protocol" in url2);
+ const protocol = url2.protocol;
+ return protocol === "about:" || protocol === "blob:" || protocol === "data:";
+ }
+ __name(urlIsLocal, "urlIsLocal");
+ function urlHasHttpsScheme(url2) {
+ return typeof url2 === "string" && url2[5] === ":" && url2[0] === "h" && url2[1] === "t" && url2[2] === "t" && url2[3] === "p" && url2[4] === "s" || url2.protocol === "https:";
+ }
+ __name(urlHasHttpsScheme, "urlHasHttpsScheme");
+ function urlIsHttpHttpsScheme(url2) {
+ assert2("protocol" in url2);
+ const protocol = url2.protocol;
+ return protocol === "http:" || protocol === "https:";
+ }
+ __name(urlIsHttpHttpsScheme, "urlIsHttpHttpsScheme");
+ function simpleRangeHeaderValue(value, allowWhitespace) {
+ const data = value;
+ if (!data.startsWith("bytes")) {
+ return "failure";
+ }
+ const position = { position: 5 };
+ if (allowWhitespace) {
+ collectASequenceOfCodePoints(
+ (char) => char === " " || char === " ",
+ data,
+ position
+ );
+ }
+ if (data.charCodeAt(position.position) !== 61) {
+ return "failure";
+ }
+ position.position++;
+ if (allowWhitespace) {
+ collectASequenceOfCodePoints(
+ (char) => char === " " || char === " ",
+ data,
+ position
+ );
+ }
+ const rangeStart = collectASequenceOfCodePoints(
+ (char) => {
+ const code = char.charCodeAt(0);
+ return code >= 48 && code <= 57;
+ },
+ data,
+ position
+ );
+ const rangeStartValue = rangeStart.length ? Number(rangeStart) : null;
+ if (allowWhitespace) {
+ collectASequenceOfCodePoints(
+ (char) => char === " " || char === " ",
+ data,
+ position
+ );
+ }
+ if (data.charCodeAt(position.position) !== 45) {
+ return "failure";
+ }
+ position.position++;
+ if (allowWhitespace) {
+ collectASequenceOfCodePoints(
+ (char) => char === " " || char === " ",
+ data,
+ position
+ );
+ }
+ const rangeEnd = collectASequenceOfCodePoints(
+ (char) => {
+ const code = char.charCodeAt(0);
+ return code >= 48 && code <= 57;
+ },
+ data,
+ position
+ );
+ const rangeEndValue = rangeEnd.length ? Number(rangeEnd) : null;
+ if (position.position < data.length) {
+ return "failure";
+ }
+ if (rangeEndValue === null && rangeStartValue === null) {
+ return "failure";
+ }
+ if (rangeStartValue > rangeEndValue) {
+ return "failure";
+ }
+ return { rangeStartValue, rangeEndValue };
+ }
+ __name(simpleRangeHeaderValue, "simpleRangeHeaderValue");
+ function buildContentRange(rangeStart, rangeEnd, fullLength) {
+ let contentRange = "bytes ";
+ contentRange += isomorphicEncode(`${rangeStart}`);
+ contentRange += "-";
+ contentRange += isomorphicEncode(`${rangeEnd}`);
+ contentRange += "/";
+ contentRange += isomorphicEncode(`${fullLength}`);
+ return contentRange;
+ }
+ __name(buildContentRange, "buildContentRange");
+ var InflateStream = class extends Transform2 {
+ static {
+ __name(this, "InflateStream");
+ }
+ #zlibOptions;
+ /** @param {zlib.ZlibOptions} [zlibOptions] */
+ constructor(zlibOptions) {
+ super();
+ this.#zlibOptions = zlibOptions;
+ }
+ _transform(chunk, encoding, callback) {
+ if (!this._inflateStream) {
+ if (chunk.length === 0) {
+ callback();
+ return;
+ }
+ this._inflateStream = (chunk[0] & 15) === 8 ? zlib.createInflate(this.#zlibOptions) : zlib.createInflateRaw(this.#zlibOptions);
+ this._inflateStream.on("data", this.push.bind(this));
+ this._inflateStream.on("end", () => this.push(null));
+ this._inflateStream.on("error", (err) => this.destroy(err));
+ }
+ this._inflateStream.write(chunk, encoding, callback);
+ }
+ _final(callback) {
+ if (this._inflateStream) {
+ this._inflateStream.end();
+ this._inflateStream = null;
+ }
+ callback();
+ }
+ };
+ function createInflate(zlibOptions) {
+ return new InflateStream(zlibOptions);
+ }
+ __name(createInflate, "createInflate");
+ function extractMimeType(headers) {
+ let charset = null;
+ let essence = null;
+ let mimeType = null;
+ const values = getDecodeSplit("content-type", headers);
+ if (values === null) {
+ return "failure";
+ }
+ for (const value of values) {
+ const temporaryMimeType = parseMIMEType(value);
+ if (temporaryMimeType === "failure" || temporaryMimeType.essence === "*/*") {
+ continue;
+ }
+ mimeType = temporaryMimeType;
+ if (mimeType.essence !== essence) {
+ charset = null;
+ if (mimeType.parameters.has("charset")) {
+ charset = mimeType.parameters.get("charset");
+ }
+ essence = mimeType.essence;
+ } else if (!mimeType.parameters.has("charset") && charset !== null) {
+ mimeType.parameters.set("charset", charset);
+ }
+ }
+ if (mimeType == null) {
+ return "failure";
+ }
+ return mimeType;
+ }
+ __name(extractMimeType, "extractMimeType");
+ function gettingDecodingSplitting(value) {
+ const input = value;
+ const position = { position: 0 };
+ const values = [];
+ let temporaryValue = "";
+ while (position.position < input.length) {
+ temporaryValue += collectASequenceOfCodePoints(
+ (char) => char !== '"' && char !== ",",
+ input,
+ position
+ );
+ if (position.position < input.length) {
+ if (input.charCodeAt(position.position) === 34) {
+ temporaryValue += collectAnHTTPQuotedString(
+ input,
+ position
+ );
+ if (position.position < input.length) {
+ continue;
+ }
+ } else {
+ assert2(input.charCodeAt(position.position) === 44);
+ position.position++;
+ }
+ }
+ temporaryValue = removeChars(temporaryValue, true, true, (char) => char === 9 || char === 32);
+ values.push(temporaryValue);
+ temporaryValue = "";
+ }
+ return values;
+ }
+ __name(gettingDecodingSplitting, "gettingDecodingSplitting");
+ function getDecodeSplit(name, list) {
+ const value = list.get(name, true);
+ if (value === null) {
+ return null;
+ }
+ return gettingDecodingSplitting(value);
+ }
+ __name(getDecodeSplit, "getDecodeSplit");
+ function hasAuthenticationEntry(request) {
+ return false;
+ }
+ __name(hasAuthenticationEntry, "hasAuthenticationEntry");
+ function includesCredentials(url2) {
+ return !!(url2.username || url2.password);
+ }
+ __name(includesCredentials, "includesCredentials");
+ function isTraversableNavigable(navigable) {
+ return navigable != null && navigable !== "client" && navigable !== "no-traversable";
+ }
+ __name(isTraversableNavigable, "isTraversableNavigable");
+ var EnvironmentSettingsObjectBase = class {
+ static {
+ __name(this, "EnvironmentSettingsObjectBase");
+ }
+ get baseUrl() {
+ return getGlobalOrigin();
+ }
+ get origin() {
+ return this.baseUrl?.origin;
+ }
+ policyContainer = makePolicyContainer();
+ };
+ var EnvironmentSettingsObject = class {
+ static {
+ __name(this, "EnvironmentSettingsObject");
+ }
+ settingsObject = new EnvironmentSettingsObjectBase();
+ };
+ var environmentSettingsObject = new EnvironmentSettingsObject();
+ module2.exports = {
+ isAborted,
+ isCancelled,
+ isValidEncodedURL,
+ ReadableStreamFrom: ReadableStreamFrom2,
+ tryUpgradeRequestToAPotentiallyTrustworthyURL,
+ clampAndCoarsenConnectionTimingInfo,
+ coarsenedSharedCurrentTime,
+ determineRequestsReferrer,
+ makePolicyContainer,
+ clonePolicyContainer,
+ appendFetchMetadata,
+ appendRequestOriginHeader,
+ TAOCheck,
+ corsCheck,
+ crossOriginResourcePolicyCheck,
+ createOpaqueTimingInfo,
+ setRequestReferrerPolicyOnRedirect,
+ isValidHTTPToken,
+ requestBadPort,
+ requestCurrentURL,
+ responseURL,
+ responseLocationURL,
+ isURLPotentiallyTrustworthy,
+ isValidReasonPhrase,
+ sameOrigin,
+ normalizeMethod,
+ iteratorMixin,
+ createIterator,
+ isValidHeaderName,
+ isValidHeaderValue,
+ isErrorLike,
+ fullyReadBody,
+ readableStreamClose,
+ urlIsLocal,
+ urlHasHttpsScheme,
+ urlIsHttpHttpsScheme,
+ readAllBytes,
+ simpleRangeHeaderValue,
+ buildContentRange,
+ createInflate,
+ extractMimeType,
+ getDecodeSplit,
+ environmentSettingsObject,
+ isOriginIPPotentiallyTrustworthy,
+ hasAuthenticationEntry,
+ includesCredentials,
+ isTraversableNavigable
+ };
+ }
+});
+
+// node_modules/undici/lib/web/fetch/formdata.js
+var require_formdata = __commonJS({
+ "node_modules/undici/lib/web/fetch/formdata.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { iteratorMixin } = require_util2();
+ var { kEnumerableProperty } = require_util();
+ var { webidl } = require_webidl();
+ var nodeUtil = __require("node:util");
+ var FormData2 = class _FormData {
+ static {
+ __name(this, "FormData");
+ }
+ #state = [];
+ constructor(form = void 0) {
+ webidl.util.markAsUncloneable(this);
+ if (form !== void 0) {
+ throw webidl.errors.conversionFailed({
+ prefix: "FormData constructor",
+ argument: "Argument 1",
+ types: ["undefined"]
+ });
+ }
+ }
+ append(name, value, filename = void 0) {
+ webidl.brandCheck(this, _FormData);
+ const prefix = "FormData.append";
+ webidl.argumentLengthCheck(arguments, 2, prefix);
+ name = webidl.converters.USVString(name);
+ if (arguments.length === 3 || webidl.is.Blob(value)) {
+ value = webidl.converters.Blob(value, prefix, "value");
+ if (filename !== void 0) {
+ filename = webidl.converters.USVString(filename);
+ }
+ } else {
+ value = webidl.converters.USVString(value);
+ }
+ const entry = makeEntry(name, value, filename);
+ this.#state.push(entry);
+ }
+ delete(name) {
+ webidl.brandCheck(this, _FormData);
+ const prefix = "FormData.delete";
+ webidl.argumentLengthCheck(arguments, 1, prefix);
+ name = webidl.converters.USVString(name);
+ this.#state = this.#state.filter((entry) => entry.name !== name);
+ }
+ get(name) {
+ webidl.brandCheck(this, _FormData);
+ const prefix = "FormData.get";
+ webidl.argumentLengthCheck(arguments, 1, prefix);
+ name = webidl.converters.USVString(name);
+ const idx = this.#state.findIndex((entry) => entry.name === name);
+ if (idx === -1) {
+ return null;
+ }
+ return this.#state[idx].value;
+ }
+ getAll(name) {
+ webidl.brandCheck(this, _FormData);
+ const prefix = "FormData.getAll";
+ webidl.argumentLengthCheck(arguments, 1, prefix);
+ name = webidl.converters.USVString(name);
+ return this.#state.filter((entry) => entry.name === name).map((entry) => entry.value);
+ }
+ has(name) {
+ webidl.brandCheck(this, _FormData);
+ const prefix = "FormData.has";
+ webidl.argumentLengthCheck(arguments, 1, prefix);
+ name = webidl.converters.USVString(name);
+ return this.#state.findIndex((entry) => entry.name === name) !== -1;
+ }
+ set(name, value, filename = void 0) {
+ webidl.brandCheck(this, _FormData);
+ const prefix = "FormData.set";
+ webidl.argumentLengthCheck(arguments, 2, prefix);
+ name = webidl.converters.USVString(name);
+ if (arguments.length === 3 || webidl.is.Blob(value)) {
+ value = webidl.converters.Blob(value, prefix, "value");
+ if (filename !== void 0) {
+ filename = webidl.converters.USVString(filename);
+ }
+ } else {
+ value = webidl.converters.USVString(value);
+ }
+ const entry = makeEntry(name, value, filename);
+ const idx = this.#state.findIndex((entry2) => entry2.name === name);
+ if (idx !== -1) {
+ this.#state = [
+ ...this.#state.slice(0, idx),
+ entry,
+ ...this.#state.slice(idx + 1).filter((entry2) => entry2.name !== name)
+ ];
+ } else {
+ this.#state.push(entry);
+ }
+ }
+ [nodeUtil.inspect.custom](depth, options2) {
+ const state = this.#state.reduce((a, b) => {
+ if (a[b.name]) {
+ if (Array.isArray(a[b.name])) {
+ a[b.name].push(b.value);
+ } else {
+ a[b.name] = [a[b.name], b.value];
+ }
+ } else {
+ a[b.name] = b.value;
+ }
+ return a;
+ }, { __proto__: null });
+ options2.depth ??= depth;
+ options2.colors ??= true;
+ const output = nodeUtil.formatWithOptions(options2, state);
+ return `FormData ${output.slice(output.indexOf("]") + 2)}`;
+ }
+ /**
+ * @param {FormData} formData
+ */
+ static getFormDataState(formData) {
+ return formData.#state;
+ }
+ /**
+ * @param {FormData} formData
+ * @param {any[]} newState
+ */
+ static setFormDataState(formData, newState) {
+ formData.#state = newState;
+ }
+ };
+ var { getFormDataState, setFormDataState } = FormData2;
+ Reflect.deleteProperty(FormData2, "getFormDataState");
+ Reflect.deleteProperty(FormData2, "setFormDataState");
+ iteratorMixin("FormData", FormData2, getFormDataState, "name", "value");
+ Object.defineProperties(FormData2.prototype, {
+ append: kEnumerableProperty,
+ delete: kEnumerableProperty,
+ get: kEnumerableProperty,
+ getAll: kEnumerableProperty,
+ has: kEnumerableProperty,
+ set: kEnumerableProperty,
+ [Symbol.toStringTag]: {
+ value: "FormData",
+ configurable: true
+ }
+ });
+ function makeEntry(name, value, filename) {
+ if (typeof value === "string") {
+ } else {
+ if (!webidl.is.File(value)) {
+ value = new File([value], "blob", { type: value.type });
+ }
+ if (filename !== void 0) {
+ const options2 = {
+ type: value.type,
+ lastModified: value.lastModified
+ };
+ value = new File([value], filename, options2);
+ }
+ }
+ return { name, value };
+ }
+ __name(makeEntry, "makeEntry");
+ webidl.is.FormData = webidl.util.MakeTypeAssertion(FormData2);
+ module2.exports = { FormData: FormData2, makeEntry, setFormDataState };
+ }
+});
+
+// node_modules/undici/lib/web/fetch/formdata-parser.js
+var require_formdata_parser = __commonJS({
+ "node_modules/undici/lib/web/fetch/formdata-parser.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { bufferToLowerCasedHeaderName } = require_util();
+ var { HTTP_TOKEN_CODEPOINTS } = require_data_url();
+ var { makeEntry } = require_formdata();
+ var { webidl } = require_webidl();
+ var assert2 = __require("node:assert");
+ var { isomorphicDecode } = require_infra();
+ var dd = Buffer.from("--");
+ var decoder = new TextDecoder();
+ var decoderIgnoreBOM = new TextDecoder("utf-8", { ignoreBOM: true });
+ function isAsciiString(chars) {
+ for (let i = 0; i < chars.length; ++i) {
+ if ((chars.charCodeAt(i) & ~127) !== 0) {
+ return false;
+ }
+ }
+ return true;
+ }
+ __name(isAsciiString, "isAsciiString");
+ function validateBoundary(boundary) {
+ const length = boundary.length;
+ if (length < 27 || length > 70) {
+ return false;
+ }
+ for (let i = 0; i < length; ++i) {
+ const cp = boundary.charCodeAt(i);
+ if (!(cp >= 48 && cp <= 57 || cp >= 65 && cp <= 90 || cp >= 97 && cp <= 122 || cp === 39 || cp === 45 || cp === 95)) {
+ return false;
+ }
+ }
+ return true;
+ }
+ __name(validateBoundary, "validateBoundary");
+ function multipartFormDataParser(input, mimeType) {
+ assert2(mimeType !== "failure" && mimeType.essence === "multipart/form-data");
+ const boundaryString = mimeType.parameters.get("boundary");
+ if (boundaryString === void 0) {
+ throw parsingError("missing boundary in content-type header");
+ }
+ const boundary = Buffer.from(`--${boundaryString}`, "utf8");
+ const entryList = [];
+ const position = { position: 0 };
+ const firstBoundaryIndex = input.indexOf(boundary);
+ if (firstBoundaryIndex === -1) {
+ throw parsingError("no boundary found in multipart body");
+ }
+ position.position = firstBoundaryIndex;
+ while (true) {
+ if (input.subarray(position.position, position.position + boundary.length).equals(boundary)) {
+ position.position += boundary.length;
+ } else {
+ throw parsingError("expected a value starting with -- and the boundary");
+ }
+ if (bufferStartsWith(input, dd, position)) {
+ return entryList;
+ }
+ if (input[position.position] !== 13 || input[position.position + 1] !== 10) {
+ throw parsingError("expected CRLF");
+ }
+ position.position += 2;
+ const result = parseMultipartFormDataHeaders(input, position);
+ let { name, filename, contentType, encoding } = result;
+ position.position += 2;
+ let body;
+ {
+ const boundaryIndex = input.indexOf(boundary.subarray(2), position.position);
+ if (boundaryIndex === -1) {
+ throw parsingError("expected boundary after body");
+ }
+ body = input.subarray(position.position, boundaryIndex - 4);
+ position.position += body.length;
+ if (encoding === "base64") {
+ body = Buffer.from(body.toString(), "base64");
+ }
+ }
+ if (input[position.position] !== 13 || input[position.position + 1] !== 10) {
+ throw parsingError("expected CRLF");
+ } else {
+ position.position += 2;
+ }
+ let value;
+ if (filename !== null) {
+ contentType ??= "text/plain";
+ if (!isAsciiString(contentType)) {
+ contentType = "";
+ }
+ value = new File([body], filename, { type: contentType });
+ } else {
+ value = decoderIgnoreBOM.decode(Buffer.from(body));
+ }
+ assert2(webidl.is.USVString(name));
+ assert2(typeof value === "string" && webidl.is.USVString(value) || webidl.is.File(value));
+ entryList.push(makeEntry(name, value, filename));
+ }
+ }
+ __name(multipartFormDataParser, "multipartFormDataParser");
+ function parseContentDispositionAttribute(input, position) {
+ if (input[position.position] === 59) {
+ position.position++;
+ }
+ collectASequenceOfBytes(
+ (char) => char === 32 || char === 9,
+ input,
+ position
+ );
+ const attributeName = collectASequenceOfBytes(
+ (char) => isToken(char) && char !== 61 && char !== 42,
+ // not = or *
+ input,
+ position
+ );
+ if (attributeName.length === 0) {
+ return null;
+ }
+ const attrNameStr = attributeName.toString("ascii").toLowerCase();
+ const isExtended = input[position.position] === 42;
+ if (isExtended) {
+ position.position++;
+ }
+ if (input[position.position] !== 61) {
+ return null;
+ }
+ position.position++;
+ collectASequenceOfBytes(
+ (char) => char === 32 || char === 9,
+ input,
+ position
+ );
+ let value;
+ if (isExtended) {
+ const headerValue = collectASequenceOfBytes(
+ (char) => char !== 32 && char !== 13 && char !== 10 && char !== 59,
+ // not space, CRLF, or ;
+ input,
+ position
+ );
+ if (headerValue[0] !== 117 && headerValue[0] !== 85 || // u or U
+ headerValue[1] !== 116 && headerValue[1] !== 84 || // t or T
+ headerValue[2] !== 102 && headerValue[2] !== 70 || // f or F
+ headerValue[3] !== 45 || // -
+ headerValue[4] !== 56) {
+ throw parsingError("unknown encoding, expected utf-8''");
+ }
+ value = decodeURIComponent(decoder.decode(headerValue.subarray(7)));
+ } else if (input[position.position] === 34) {
+ position.position++;
+ const quotedValue = collectASequenceOfBytes(
+ (char) => char !== 10 && char !== 13 && char !== 34,
+ // not LF, CR, or "
+ input,
+ position
+ );
+ if (input[position.position] !== 34) {
+ throw parsingError("Closing quote not found");
+ }
+ position.position++;
+ value = decoder.decode(quotedValue).replace(/%0A/ig, "\n").replace(/%0D/ig, "\r").replace(/%22/g, '"');
+ } else {
+ const tokenValue = collectASequenceOfBytes(
+ (char) => isToken(char) && char !== 59,
+ // not ;
+ input,
+ position
+ );
+ value = decoder.decode(tokenValue);
+ }
+ return { name: attrNameStr, value, extended: isExtended };
+ }
+ __name(parseContentDispositionAttribute, "parseContentDispositionAttribute");
+ function parseMultipartFormDataHeaders(input, position) {
+ let name = null;
+ let filename = null;
+ let contentType = null;
+ let encoding = null;
+ while (true) {
+ if (input[position.position] === 13 && input[position.position + 1] === 10) {
+ if (name === null) {
+ throw parsingError("header name is null");
+ }
+ return { name, filename, contentType, encoding };
+ }
+ let headerName = collectASequenceOfBytes(
+ (char) => char !== 10 && char !== 13 && char !== 58,
+ input,
+ position
+ );
+ headerName = removeChars(headerName, true, true, (char) => char === 9 || char === 32);
+ if (!HTTP_TOKEN_CODEPOINTS.test(headerName.toString())) {
+ throw parsingError("header name does not match the field-name token production");
+ }
+ if (input[position.position] !== 58) {
+ throw parsingError("expected :");
+ }
+ position.position++;
+ collectASequenceOfBytes(
+ (char) => char === 32 || char === 9,
+ input,
+ position
+ );
+ switch (bufferToLowerCasedHeaderName(headerName)) {
+ case "content-disposition": {
+ name = filename = null;
+ let filenameIsExtended = false;
+ const dispositionType = collectASequenceOfBytes(
+ (char) => isToken(char),
+ input,
+ position
+ );
+ if (dispositionType.toString("ascii").toLowerCase() !== "form-data") {
+ throw parsingError("expected form-data for content-disposition header");
+ }
+ while (position.position < input.length && (input[position.position] !== 13 || input[position.position + 1] !== 10)) {
+ const attribute = parseContentDispositionAttribute(input, position);
+ if (!attribute) {
+ break;
+ }
+ if (attribute.name === "name") {
+ name = attribute.value;
+ } else if (attribute.name === "filename") {
+ if (attribute.extended) {
+ filename = attribute.value;
+ filenameIsExtended = true;
+ } else if (!filenameIsExtended) {
+ filename = attribute.value;
+ }
+ }
+ }
+ if (name === null) {
+ throw parsingError("name attribute is required in content-disposition header");
+ }
+ break;
+ }
+ case "content-type": {
+ let headerValue = collectASequenceOfBytes(
+ (char) => char !== 10 && char !== 13,
+ input,
+ position
+ );
+ headerValue = removeChars(headerValue, false, true, (char) => char === 9 || char === 32);
+ contentType = isomorphicDecode(headerValue);
+ break;
+ }
+ case "content-transfer-encoding": {
+ let headerValue = collectASequenceOfBytes(
+ (char) => char !== 10 && char !== 13,
+ input,
+ position
+ );
+ headerValue = removeChars(headerValue, false, true, (char) => char === 9 || char === 32);
+ encoding = isomorphicDecode(headerValue);
+ break;
+ }
+ default: {
+ collectASequenceOfBytes(
+ (char) => char !== 10 && char !== 13,
+ input,
+ position
+ );
+ }
+ }
+ if (input[position.position] !== 13 || input[position.position + 1] !== 10) {
+ throw parsingError("expected CRLF");
+ } else {
+ position.position += 2;
+ }
+ }
+ }
+ __name(parseMultipartFormDataHeaders, "parseMultipartFormDataHeaders");
+ function collectASequenceOfBytes(condition, input, position) {
+ let start = position.position;
+ while (start < input.length && condition(input[start])) {
+ ++start;
+ }
+ return input.subarray(position.position, position.position = start);
+ }
+ __name(collectASequenceOfBytes, "collectASequenceOfBytes");
+ function removeChars(buf, leading, trailing, predicate) {
+ let lead = 0;
+ let trail = buf.length - 1;
+ if (leading) {
+ while (lead < buf.length && predicate(buf[lead])) lead++;
+ }
+ if (trailing) {
+ while (trail > 0 && predicate(buf[trail])) trail--;
+ }
+ return lead === 0 && trail === buf.length - 1 ? buf : buf.subarray(lead, trail + 1);
+ }
+ __name(removeChars, "removeChars");
+ function bufferStartsWith(buffer, start, position) {
+ if (buffer.length < start.length) {
+ return false;
+ }
+ for (let i = 0; i < start.length; i++) {
+ if (start[i] !== buffer[position.position + i]) {
+ return false;
+ }
+ }
+ return true;
+ }
+ __name(bufferStartsWith, "bufferStartsWith");
+ function parsingError(cause) {
+ return new TypeError("Failed to parse body as FormData.", { cause: new TypeError(cause) });
+ }
+ __name(parsingError, "parsingError");
+ function isCTL(char) {
+ return char <= 31 || char === 127;
+ }
+ __name(isCTL, "isCTL");
+ function isTSpecial(char) {
+ return char === 40 || // (
+ char === 41 || // )
+ char === 60 || // <
+ char === 62 || // >
+ char === 64 || // @
+ char === 44 || // ,
+ char === 59 || // ;
+ char === 58 || // :
+ char === 92 || // \
+ char === 34 || // "
+ char === 47 || // /
+ char === 91 || // [
+ char === 93 || // ]
+ char === 63 || // ?
+ char === 61;
+ }
+ __name(isTSpecial, "isTSpecial");
+ function isToken(char) {
+ return char <= 127 && // ascii
+ char !== 32 && // space
+ char !== 9 && !isCTL(char) && !isTSpecial(char);
+ }
+ __name(isToken, "isToken");
+ module2.exports = {
+ multipartFormDataParser,
+ validateBoundary
+ };
+ }
+});
+
+// node_modules/undici/lib/util/promise.js
+var require_promise = __commonJS({
+ "node_modules/undici/lib/util/promise.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ function createDeferredPromise() {
+ let res;
+ let rej;
+ const promise2 = new Promise((resolve16, reject) => {
+ res = resolve16;
+ rej = reject;
+ });
+ return { promise: promise2, resolve: res, reject: rej };
+ }
+ __name(createDeferredPromise, "createDeferredPromise");
+ module2.exports = {
+ createDeferredPromise
+ };
+ }
+});
+
+// node_modules/undici/lib/web/fetch/body.js
+var require_body = __commonJS({
+ "node_modules/undici/lib/web/fetch/body.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var util = require_util();
+ var {
+ ReadableStreamFrom: ReadableStreamFrom2,
+ readableStreamClose,
+ fullyReadBody,
+ extractMimeType
+ } = require_util2();
+ var { FormData: FormData2, setFormDataState } = require_formdata();
+ var { webidl } = require_webidl();
+ var assert2 = __require("node:assert");
+ var { isErrored, isDisturbed } = __require("node:stream");
+ var { isUint8Array } = __require("node:util/types");
+ var { serializeAMimeType } = require_data_url();
+ var { multipartFormDataParser } = require_formdata_parser();
+ var { createDeferredPromise } = require_promise();
+ var { parseJSONFromBytes } = require_infra();
+ var { utf8DecodeBytes } = require_encoding();
+ var { runtimeFeatures } = require_runtime_features();
+ var random = runtimeFeatures.has("crypto") ? __require("node:crypto").randomInt : (max) => Math.floor(Math.random() * max);
+ var textEncoder2 = new TextEncoder();
+ function noop3() {
+ }
+ __name(noop3, "noop");
+ var streamRegistry = new FinalizationRegistry((weakRef) => {
+ const stream = weakRef.deref();
+ if (stream && !stream.locked && !isDisturbed(stream) && !isErrored(stream)) {
+ stream.cancel("Response object has been garbage collected").catch(noop3);
+ }
+ });
+ function extractBody(object2, keepalive = false) {
+ let stream = null;
+ let controller = null;
+ if (webidl.is.ReadableStream(object2)) {
+ stream = object2;
+ } else if (webidl.is.Blob(object2)) {
+ stream = object2.stream();
+ } else {
+ stream = new ReadableStream({
+ pull() {
+ },
+ start(c) {
+ controller = c;
+ },
+ cancel() {
+ },
+ type: "bytes"
+ });
+ }
+ assert2(webidl.is.ReadableStream(stream));
+ let action = null;
+ let source = null;
+ let length = null;
+ let type2 = null;
+ if (typeof object2 === "string") {
+ source = object2;
+ type2 = "text/plain;charset=UTF-8";
+ } else if (webidl.is.URLSearchParams(object2)) {
+ source = object2.toString();
+ type2 = "application/x-www-form-urlencoded;charset=UTF-8";
+ } else if (webidl.is.BufferSource(object2)) {
+ source = webidl.util.getCopyOfBytesHeldByBufferSource(object2);
+ } else if (webidl.is.FormData(object2)) {
+ const boundary = `----formdata-undici-0${`${random(1e11)}`.padStart(11, "0")}`;
+ const prefix = `--${boundary}\r
+Content-Disposition: form-data`;
+ const formdataEscape = /* @__PURE__ */ __name((str3) => str3.replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22"), "formdataEscape");
+ const normalizeLinefeeds = /* @__PURE__ */ __name((value) => value.replace(/\r?\n|\r/g, "\r\n"), "normalizeLinefeeds");
+ const blobParts = [];
+ const rn = new Uint8Array([13, 10]);
+ length = 0;
+ let hasUnknownSizeValue = false;
+ for (const [name, value] of object2) {
+ if (typeof value === "string") {
+ const chunk2 = textEncoder2.encode(prefix + `; name="${formdataEscape(normalizeLinefeeds(name))}"\r
+\r
+${normalizeLinefeeds(value)}\r
+`);
+ blobParts.push(chunk2);
+ length += chunk2.byteLength;
+ } else {
+ const chunk2 = textEncoder2.encode(`${prefix}; name="${formdataEscape(normalizeLinefeeds(name))}"` + (value.name ? `; filename="${formdataEscape(value.name)}"` : "") + `\r
+Content-Type: ${value.type || "application/octet-stream"}\r
+\r
+`);
+ blobParts.push(chunk2, value, rn);
+ if (typeof value.size === "number") {
+ length += chunk2.byteLength + value.size + rn.byteLength;
+ } else {
+ hasUnknownSizeValue = true;
+ }
+ }
+ }
+ const chunk = textEncoder2.encode(`--${boundary}--\r
+`);
+ blobParts.push(chunk);
+ length += chunk.byteLength;
+ if (hasUnknownSizeValue) {
+ length = null;
+ }
+ source = object2;
+ action = /* @__PURE__ */ __name(async function* () {
+ for (const part of blobParts) {
+ if (part.stream) {
+ yield* part.stream();
+ } else {
+ yield part;
+ }
+ }
+ }, "action");
+ type2 = `multipart/form-data; boundary=${boundary}`;
+ } else if (webidl.is.Blob(object2)) {
+ source = object2;
+ length = object2.size;
+ if (object2.type) {
+ type2 = object2.type;
+ }
+ } else if (typeof object2[Symbol.asyncIterator] === "function") {
+ if (keepalive) {
+ throw new TypeError("keepalive");
+ }
+ if (util.isDisturbed(object2) || object2.locked) {
+ throw new TypeError(
+ "Response body object should not be disturbed or locked"
+ );
+ }
+ stream = webidl.is.ReadableStream(object2) ? object2 : ReadableStreamFrom2(object2);
+ }
+ if (typeof source === "string" || isUint8Array(source)) {
+ action = /* @__PURE__ */ __name(() => {
+ length = typeof source === "string" ? Buffer.byteLength(source) : source.length;
+ return source;
+ }, "action");
+ }
+ if (action != null) {
+ ;
+ (async () => {
+ const result = action();
+ const iterator = result?.[Symbol.asyncIterator]?.();
+ if (iterator) {
+ for await (const bytes of iterator) {
+ if (isErrored(stream)) break;
+ if (bytes.length) {
+ controller.enqueue(new Uint8Array(bytes));
+ }
+ }
+ } else if (result?.length && !isErrored(stream)) {
+ controller.enqueue(typeof result === "string" ? textEncoder2.encode(result) : new Uint8Array(result));
+ }
+ queueMicrotask(() => readableStreamClose(controller));
+ })();
+ }
+ const body = { stream, source, length };
+ return [body, type2];
+ }
+ __name(extractBody, "extractBody");
+ function safelyExtractBody(object2, keepalive = false) {
+ if (webidl.is.ReadableStream(object2)) {
+ assert2(!util.isDisturbed(object2), "The body has already been consumed.");
+ assert2(!object2.locked, "The stream is locked.");
+ }
+ return extractBody(object2, keepalive);
+ }
+ __name(safelyExtractBody, "safelyExtractBody");
+ function cloneBody(body) {
+ const { 0: out1, 1: out2 } = body.stream.tee();
+ body.stream = out1;
+ return {
+ stream: out2,
+ length: body.length,
+ source: body.source
+ };
+ }
+ __name(cloneBody, "cloneBody");
+ function bodyMixinMethods(instance, getInternalState) {
+ const methods = {
+ blob() {
+ return consumeBody(this, (bytes) => {
+ let mimeType = bodyMimeType(getInternalState(this));
+ if (mimeType === null) {
+ mimeType = "";
+ } else if (mimeType) {
+ mimeType = serializeAMimeType(mimeType);
+ }
+ return new Blob([bytes], { type: mimeType });
+ }, instance, getInternalState);
+ },
+ arrayBuffer() {
+ return consumeBody(this, (bytes) => {
+ return new Uint8Array(bytes).buffer;
+ }, instance, getInternalState);
+ },
+ text() {
+ return consumeBody(this, utf8DecodeBytes, instance, getInternalState);
+ },
+ json() {
+ return consumeBody(this, parseJSONFromBytes, instance, getInternalState);
+ },
+ formData() {
+ return consumeBody(this, (value) => {
+ const mimeType = bodyMimeType(getInternalState(this));
+ if (mimeType !== null) {
+ switch (mimeType.essence) {
+ case "multipart/form-data": {
+ const parsed = multipartFormDataParser(value, mimeType);
+ const fd = new FormData2();
+ setFormDataState(fd, parsed);
+ return fd;
+ }
+ case "application/x-www-form-urlencoded": {
+ const entries = new URLSearchParams(value.toString());
+ const fd = new FormData2();
+ for (const [name, value2] of entries) {
+ fd.append(name, value2);
+ }
+ return fd;
+ }
+ }
+ }
+ throw new TypeError(
+ 'Content-Type was not one of "multipart/form-data" or "application/x-www-form-urlencoded".'
+ );
+ }, instance, getInternalState);
+ },
+ bytes() {
+ return consumeBody(this, (bytes) => {
+ return new Uint8Array(bytes);
+ }, instance, getInternalState);
+ }
+ };
+ return methods;
+ }
+ __name(bodyMixinMethods, "bodyMixinMethods");
+ function mixinBody(prototype, getInternalState) {
+ Object.assign(prototype.prototype, bodyMixinMethods(prototype, getInternalState));
+ }
+ __name(mixinBody, "mixinBody");
+ function consumeBody(object2, convertBytesToJSValue, instance, getInternalState) {
+ try {
+ webidl.brandCheck(object2, instance);
+ } catch (e) {
+ return Promise.reject(e);
+ }
+ object2 = getInternalState(object2);
+ if (bodyUnusable(object2)) {
+ return Promise.reject(new TypeError("Body is unusable: Body has already been read"));
+ }
+ const promise2 = createDeferredPromise();
+ const errorSteps = promise2.reject;
+ const successSteps = /* @__PURE__ */ __name((data) => {
+ try {
+ promise2.resolve(convertBytesToJSValue(data));
+ } catch (e) {
+ errorSteps(e);
+ }
+ }, "successSteps");
+ if (object2.body == null) {
+ successSteps(Buffer.allocUnsafe(0));
+ return promise2.promise;
+ }
+ fullyReadBody(object2.body, successSteps, errorSteps);
+ return promise2.promise;
+ }
+ __name(consumeBody, "consumeBody");
+ function bodyUnusable(object2) {
+ const body = object2.body;
+ return body != null && (body.stream.locked || util.isDisturbed(body.stream));
+ }
+ __name(bodyUnusable, "bodyUnusable");
+ function bodyMimeType(requestOrResponse) {
+ const headers = requestOrResponse.headersList;
+ const mimeType = extractMimeType(headers);
+ if (mimeType === "failure") {
+ return null;
+ }
+ return mimeType;
+ }
+ __name(bodyMimeType, "bodyMimeType");
+ module2.exports = {
+ extractBody,
+ safelyExtractBody,
+ cloneBody,
+ mixinBody,
+ streamRegistry,
+ bodyUnusable
+ };
+ }
+});
+
+// node_modules/undici/lib/dispatcher/client-h1.js
+var require_client_h1 = __commonJS({
+ "node_modules/undici/lib/dispatcher/client-h1.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var assert2 = __require("node:assert");
+ var util = require_util();
+ var { channels } = require_diagnostics();
+ var timers = require_timers();
+ var {
+ RequestContentLengthMismatchError,
+ ResponseContentLengthMismatchError,
+ RequestAbortedError,
+ HeadersTimeoutError,
+ HeadersOverflowError,
+ SocketError,
+ InformationalError,
+ BodyTimeoutError,
+ HTTPParserError,
+ ResponseExceededMaxSizeError
+ } = require_errors();
+ var {
+ kUrl,
+ kReset: kReset2,
+ kClient,
+ kParser,
+ kBlocking,
+ kRunning,
+ kPending,
+ kSize,
+ kWriting,
+ kQueue,
+ kNoRef,
+ kKeepAliveDefaultTimeout,
+ kHostHeader,
+ kPendingIdx,
+ kRunningIdx,
+ kError,
+ kPipelining,
+ kSocket,
+ kKeepAliveTimeoutValue,
+ kMaxHeadersSize,
+ kKeepAliveMaxTimeout,
+ kKeepAliveTimeoutThreshold,
+ kHeadersTimeout,
+ kBodyTimeout,
+ kStrictContentLength,
+ kMaxRequests,
+ kCounter,
+ kMaxResponseSize,
+ kOnError,
+ kResume,
+ kHTTPContext,
+ kClosed
+ } = require_symbols();
+ var constants2 = require_constants3();
+ var EMPTY_BUF = Buffer.alloc(0);
+ var FastBuffer = Buffer[Symbol.species];
+ var removeAllListeners = util.removeAllListeners;
+ var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation");
+ var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout");
+ var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed");
+ var extractBody;
+ function lazyllhttp() {
+ const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0;
+ let mod;
+ let useWasmSIMD = process.arch !== "ppc64";
+ if (process.env.UNDICI_NO_WASM_SIMD === "1") {
+ useWasmSIMD = false;
+ } else if (process.env.UNDICI_NO_WASM_SIMD === "0") {
+ useWasmSIMD = true;
+ }
+ if (useWasmSIMD) {
+ try {
+ mod = new WebAssembly.Module(require_llhttp_simd_wasm());
+ } catch {
+ }
+ }
+ if (!mod) {
+ mod = new WebAssembly.Module(llhttpWasmData || require_llhttp_wasm());
+ }
+ return new WebAssembly.Instance(mod, {
+ env: {
+ /**
+ * @param {number} p
+ * @param {number} at
+ * @param {number} len
+ * @returns {number}
+ */
+ wasm_on_url: /* @__PURE__ */ __name((p, at, len) => {
+ return 0;
+ }, "wasm_on_url"),
+ /**
+ * @param {number} p
+ * @param {number} at
+ * @param {number} len
+ * @returns {number}
+ */
+ wasm_on_status: /* @__PURE__ */ __name((p, at, len) => {
+ assert2(currentParser.ptr === p);
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset;
+ return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len));
+ }, "wasm_on_status"),
+ /**
+ * @param {number} p
+ * @returns {number}
+ */
+ wasm_on_message_begin: /* @__PURE__ */ __name((p) => {
+ assert2(currentParser.ptr === p);
+ return currentParser.onMessageBegin();
+ }, "wasm_on_message_begin"),
+ /**
+ * @param {number} p
+ * @param {number} at
+ * @param {number} len
+ * @returns {number}
+ */
+ wasm_on_header_field: /* @__PURE__ */ __name((p, at, len) => {
+ assert2(currentParser.ptr === p);
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset;
+ return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len));
+ }, "wasm_on_header_field"),
+ /**
+ * @param {number} p
+ * @param {number} at
+ * @param {number} len
+ * @returns {number}
+ */
+ wasm_on_header_value: /* @__PURE__ */ __name((p, at, len) => {
+ assert2(currentParser.ptr === p);
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset;
+ return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len));
+ }, "wasm_on_header_value"),
+ /**
+ * @param {number} p
+ * @param {number} statusCode
+ * @param {0|1} upgrade
+ * @param {0|1} shouldKeepAlive
+ * @returns {number}
+ */
+ wasm_on_headers_complete: /* @__PURE__ */ __name((p, statusCode, upgrade, shouldKeepAlive) => {
+ assert2(currentParser.ptr === p);
+ return currentParser.onHeadersComplete(statusCode, upgrade === 1, shouldKeepAlive === 1);
+ }, "wasm_on_headers_complete"),
+ /**
+ * @param {number} p
+ * @param {number} at
+ * @param {number} len
+ * @returns {number}
+ */
+ wasm_on_body: /* @__PURE__ */ __name((p, at, len) => {
+ assert2(currentParser.ptr === p);
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset;
+ return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len));
+ }, "wasm_on_body"),
+ /**
+ * @param {number} p
+ * @returns {number}
+ */
+ wasm_on_message_complete: /* @__PURE__ */ __name((p) => {
+ assert2(currentParser.ptr === p);
+ return currentParser.onMessageComplete();
+ }, "wasm_on_message_complete")
+ }
+ });
+ }
+ __name(lazyllhttp, "lazyllhttp");
+ var llhttpInstance = null;
+ var currentParser = null;
+ var currentBufferRef = null;
+ var currentBufferSize = 0;
+ var currentBufferPtr = null;
+ var USE_NATIVE_TIMER = 0;
+ var USE_FAST_TIMER = 1;
+ var TIMEOUT_HEADERS = 2 | USE_FAST_TIMER;
+ var TIMEOUT_BODY = 4 | USE_FAST_TIMER;
+ var TIMEOUT_KEEP_ALIVE = 8 | USE_NATIVE_TIMER;
+ var Parser2 = class {
+ static {
+ __name(this, "Parser");
+ }
+ /**
+ * @param {import('./client.js')} client
+ * @param {import('net').Socket} socket
+ * @param {*} llhttp
+ */
+ constructor(client, socket, { exports: exports3 }) {
+ this.llhttp = exports3;
+ this.ptr = this.llhttp.llhttp_alloc(constants2.TYPE.RESPONSE);
+ this.client = client;
+ this.socket = socket;
+ this.timeout = null;
+ this.timeoutWeakRef = new WeakRef(this);
+ this.timeoutValue = null;
+ this.timeoutType = null;
+ this.statusCode = 0;
+ this.statusText = "";
+ this.upgrade = false;
+ this.headers = [];
+ this.headersSize = 0;
+ this.headersMaxSize = client[kMaxHeadersSize];
+ this.shouldKeepAlive = false;
+ this.paused = false;
+ this.resume = this.resume.bind(this);
+ this.bytesRead = 0;
+ this.keepAlive = "";
+ this.contentLength = "";
+ this.connection = "";
+ this.maxResponseSize = client[kMaxResponseSize];
+ }
+ setTimeout(delay, type2) {
+ if (delay !== this.timeoutValue || type2 & USE_FAST_TIMER ^ this.timeoutType & USE_FAST_TIMER) {
+ if (this.timeout) {
+ timers.clearTimeout(this.timeout);
+ this.timeout = null;
+ }
+ if (delay) {
+ if (type2 & USE_FAST_TIMER) {
+ this.timeout = timers.setFastTimeout(onParserTimeout, delay, this.timeoutWeakRef);
+ } else {
+ this.timeout = setTimeout(onParserTimeout, delay, this.timeoutWeakRef);
+ this.timeout?.unref();
+ }
+ }
+ this.timeoutValue = delay;
+ } else if (this.timeout) {
+ if (this.timeout.refresh) {
+ this.timeout.refresh();
+ }
+ }
+ this.timeoutType = type2;
+ }
+ resume() {
+ if (this.socket.destroyed || !this.paused) {
+ return;
+ }
+ assert2(this.ptr != null);
+ assert2(currentParser === null);
+ this.llhttp.llhttp_resume(this.ptr);
+ assert2(this.timeoutType === TIMEOUT_BODY);
+ if (this.timeout) {
+ if (this.timeout.refresh) {
+ this.timeout.refresh();
+ }
+ }
+ this.paused = false;
+ this.execute(this.socket.read() || EMPTY_BUF);
+ this.readMore();
+ }
+ readMore() {
+ while (!this.paused && this.ptr) {
+ const chunk = this.socket.read();
+ if (chunk === null) {
+ break;
+ }
+ this.execute(chunk);
+ }
+ }
+ /**
+ * @param {Buffer} chunk
+ */
+ execute(chunk) {
+ assert2(currentParser === null);
+ assert2(this.ptr != null);
+ assert2(!this.paused);
+ const { socket, llhttp } = this;
+ if (chunk.length > currentBufferSize) {
+ if (currentBufferPtr) {
+ llhttp.free(currentBufferPtr);
+ }
+ currentBufferSize = Math.ceil(chunk.length / 4096) * 4096;
+ currentBufferPtr = llhttp.malloc(currentBufferSize);
+ }
+ new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(chunk);
+ try {
+ let ret;
+ try {
+ currentBufferRef = chunk;
+ currentParser = this;
+ ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, chunk.length);
+ } finally {
+ currentParser = null;
+ currentBufferRef = null;
+ }
+ if (ret !== constants2.ERROR.OK) {
+ const data = chunk.subarray(llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr);
+ if (ret === constants2.ERROR.PAUSED_UPGRADE) {
+ this.onUpgrade(data);
+ } else if (ret === constants2.ERROR.PAUSED) {
+ this.paused = true;
+ socket.unshift(data);
+ } else {
+ throw this.createError(ret, data);
+ }
+ }
+ } catch (err) {
+ util.destroy(socket, err);
+ }
+ }
+ finish() {
+ assert2(currentParser === null);
+ assert2(this.ptr != null);
+ assert2(!this.paused);
+ const { llhttp } = this;
+ let ret;
+ try {
+ currentParser = this;
+ ret = llhttp.llhttp_finish(this.ptr);
+ } finally {
+ currentParser = null;
+ }
+ if (ret === constants2.ERROR.OK) {
+ return null;
+ }
+ if (ret === constants2.ERROR.PAUSED || ret === constants2.ERROR.PAUSED_UPGRADE) {
+ this.paused = true;
+ return null;
+ }
+ return this.createError(ret, EMPTY_BUF);
+ }
+ createError(ret, data) {
+ const { llhttp, contentLength, bytesRead } = this;
+ if (contentLength && bytesRead !== parseInt(contentLength, 10)) {
+ return new ResponseContentLengthMismatchError();
+ }
+ const ptr = llhttp.llhttp_get_error_reason(this.ptr);
+ let message = "";
+ if (ptr) {
+ const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0);
+ message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")";
+ }
+ return new HTTPParserError(message, constants2.ERROR[ret], data);
+ }
+ destroy() {
+ assert2(currentParser === null);
+ assert2(this.ptr != null);
+ this.llhttp.llhttp_free(this.ptr);
+ this.ptr = null;
+ this.timeout && timers.clearTimeout(this.timeout);
+ this.timeout = null;
+ this.timeoutValue = null;
+ this.timeoutType = null;
+ this.paused = false;
+ }
+ /**
+ * @param {Buffer} buf
+ * @returns {0}
+ */
+ onStatus(buf) {
+ this.statusText = buf.toString();
+ return 0;
+ }
+ /**
+ * @returns {0|-1}
+ */
+ onMessageBegin() {
+ const { socket, client } = this;
+ if (socket.destroyed) {
+ return -1;
+ }
+ if (client[kRunning] === 0) {
+ util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket)));
+ return -1;
+ }
+ const request = client[kQueue][client[kRunningIdx]];
+ if (!request) {
+ return -1;
+ }
+ request.onResponseStarted();
+ return 0;
+ }
+ /**
+ * @param {Buffer} buf
+ * @returns {number}
+ */
+ onHeaderField(buf) {
+ const len = this.headers.length;
+ if ((len & 1) === 0) {
+ this.headers.push(buf);
+ } else {
+ this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]);
+ }
+ this.trackHeader(buf.length);
+ return 0;
+ }
+ /**
+ * @param {Buffer} buf
+ * @returns {number}
+ */
+ onHeaderValue(buf) {
+ let len = this.headers.length;
+ if ((len & 1) === 1) {
+ this.headers.push(buf);
+ len += 1;
+ } else {
+ this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]);
+ }
+ const key = this.headers[len - 2];
+ if (key.length === 10) {
+ const headerName = util.bufferToLowerCasedHeaderName(key);
+ if (headerName === "keep-alive") {
+ this.keepAlive += buf.toString();
+ } else if (headerName === "connection") {
+ this.connection += buf.toString();
+ }
+ } else if (key.length === 14 && util.bufferToLowerCasedHeaderName(key) === "content-length") {
+ this.contentLength += buf.toString();
+ }
+ this.trackHeader(buf.length);
+ return 0;
+ }
+ /**
+ * @param {number} len
+ */
+ trackHeader(len) {
+ this.headersSize += len;
+ if (this.headersSize >= this.headersMaxSize) {
+ util.destroy(this.socket, new HeadersOverflowError());
+ }
+ }
+ /**
+ * @param {Buffer} head
+ */
+ onUpgrade(head) {
+ const { upgrade, client, socket, headers, statusCode } = this;
+ assert2(upgrade);
+ assert2(client[kSocket] === socket);
+ assert2(!socket.destroyed);
+ assert2(!this.paused);
+ assert2((headers.length & 1) === 0);
+ const request = client[kQueue][client[kRunningIdx]];
+ assert2(request);
+ assert2(request.upgrade || request.method === "CONNECT");
+ this.statusCode = 0;
+ this.statusText = "";
+ this.shouldKeepAlive = false;
+ this.headers = [];
+ this.headersSize = 0;
+ socket.unshift(head);
+ socket[kParser].destroy();
+ socket[kParser] = null;
+ socket[kClient] = null;
+ socket[kError] = null;
+ removeAllListeners(socket);
+ client[kSocket] = null;
+ client[kHTTPContext] = null;
+ client[kQueue][client[kRunningIdx]++] = null;
+ client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade"));
+ try {
+ request.onUpgrade(statusCode, headers, socket);
+ } catch (err) {
+ util.destroy(socket, err);
+ }
+ client[kResume]();
+ }
+ /**
+ * @param {number} statusCode
+ * @param {boolean} upgrade
+ * @param {boolean} shouldKeepAlive
+ * @returns {number}
+ */
+ onHeadersComplete(statusCode, upgrade, shouldKeepAlive) {
+ const { client, socket, headers, statusText } = this;
+ if (socket.destroyed) {
+ return -1;
+ }
+ if (client[kRunning] === 0) {
+ util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket)));
+ return -1;
+ }
+ const request = client[kQueue][client[kRunningIdx]];
+ if (!request) {
+ return -1;
+ }
+ assert2(!this.upgrade);
+ assert2(this.statusCode < 200);
+ if (statusCode === 100) {
+ util.destroy(socket, new SocketError("bad response", util.getSocketInfo(socket)));
+ return -1;
+ }
+ if (upgrade && !request.upgrade) {
+ util.destroy(socket, new SocketError("bad upgrade", util.getSocketInfo(socket)));
+ return -1;
+ }
+ assert2(this.timeoutType === TIMEOUT_HEADERS);
+ this.statusCode = statusCode;
+ this.shouldKeepAlive = shouldKeepAlive || // Override llhttp value which does not allow keepAlive for HEAD.
+ request.method === "HEAD" && !socket[kReset2] && this.connection.toLowerCase() === "keep-alive";
+ if (this.statusCode >= 200) {
+ const bodyTimeout = request.bodyTimeout != null ? request.bodyTimeout : client[kBodyTimeout];
+ this.setTimeout(bodyTimeout, TIMEOUT_BODY);
+ } else if (this.timeout) {
+ if (this.timeout.refresh) {
+ this.timeout.refresh();
+ }
+ }
+ if (request.method === "CONNECT") {
+ assert2(client[kRunning] === 1);
+ this.upgrade = true;
+ return 2;
+ }
+ if (upgrade) {
+ assert2(client[kRunning] === 1);
+ this.upgrade = true;
+ return 2;
+ }
+ assert2((this.headers.length & 1) === 0);
+ this.headers = [];
+ this.headersSize = 0;
+ if (this.shouldKeepAlive && client[kPipelining]) {
+ const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null;
+ if (keepAliveTimeout != null) {
+ const timeout = Math.min(
+ keepAliveTimeout - client[kKeepAliveTimeoutThreshold],
+ client[kKeepAliveMaxTimeout]
+ );
+ if (timeout <= 0) {
+ socket[kReset2] = true;
+ } else {
+ client[kKeepAliveTimeoutValue] = timeout;
+ }
+ } else {
+ client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout];
+ }
+ } else {
+ socket[kReset2] = true;
+ }
+ const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false;
+ if (request.aborted) {
+ return -1;
+ }
+ if (request.method === "HEAD") {
+ return 1;
+ }
+ if (statusCode < 200) {
+ return 1;
+ }
+ if (socket[kBlocking]) {
+ socket[kBlocking] = false;
+ client[kResume]();
+ }
+ return pause ? constants2.ERROR.PAUSED : 0;
+ }
+ /**
+ * @param {Buffer} buf
+ * @returns {number}
+ */
+ onBody(buf) {
+ const { client, socket, statusCode, maxResponseSize } = this;
+ if (socket.destroyed) {
+ return -1;
+ }
+ const request = client[kQueue][client[kRunningIdx]];
+ assert2(request);
+ assert2(this.timeoutType === TIMEOUT_BODY);
+ if (this.timeout) {
+ if (this.timeout.refresh) {
+ this.timeout.refresh();
+ }
+ }
+ assert2(statusCode >= 200);
+ if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) {
+ util.destroy(socket, new ResponseExceededMaxSizeError());
+ return -1;
+ }
+ this.bytesRead += buf.length;
+ if (request.onData(buf) === false) {
+ return constants2.ERROR.PAUSED;
+ }
+ return 0;
+ }
+ /**
+ * @returns {number}
+ */
+ onMessageComplete() {
+ const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this;
+ if (socket.destroyed && (!statusCode || shouldKeepAlive)) {
+ return -1;
+ }
+ if (upgrade) {
+ return 0;
+ }
+ assert2(statusCode >= 100);
+ assert2((this.headers.length & 1) === 0);
+ const request = client[kQueue][client[kRunningIdx]];
+ assert2(request);
+ this.statusCode = 0;
+ this.statusText = "";
+ this.bytesRead = 0;
+ this.contentLength = "";
+ this.keepAlive = "";
+ this.connection = "";
+ this.headers = [];
+ this.headersSize = 0;
+ if (statusCode < 200) {
+ return 0;
+ }
+ if (request.method !== "HEAD" && contentLength && bytesRead !== parseInt(contentLength, 10)) {
+ util.destroy(socket, new ResponseContentLengthMismatchError());
+ return -1;
+ }
+ request.onComplete(headers);
+ client[kQueue][client[kRunningIdx]++] = null;
+ socket[kSocketUsed] = client[kPending] === 0;
+ if (socket[kWriting]) {
+ assert2(client[kRunning] === 0);
+ util.destroy(socket, new InformationalError("reset"));
+ return constants2.ERROR.PAUSED;
+ } else if (!shouldKeepAlive) {
+ util.destroy(socket, new InformationalError("reset"));
+ return constants2.ERROR.PAUSED;
+ } else if (socket[kReset2] && client[kRunning] === 0) {
+ util.destroy(socket, new InformationalError("reset"));
+ return constants2.ERROR.PAUSED;
+ } else if (client[kPipelining] == null || client[kPipelining] === 1) {
+ setImmediate(client[kResume]);
+ } else {
+ client[kResume]();
+ }
+ return 0;
+ }
+ };
+ function onParserTimeout(parserWeakRef) {
+ const parser2 = parserWeakRef.deref();
+ if (!parser2) {
+ return;
+ }
+ const { socket, timeoutType, client, paused } = parser2;
+ if (timeoutType === TIMEOUT_HEADERS) {
+ if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) {
+ assert2(!paused, "cannot be paused while waiting for headers");
+ util.destroy(socket, new HeadersTimeoutError());
+ }
+ } else if (timeoutType === TIMEOUT_BODY) {
+ if (!paused) {
+ util.destroy(socket, new BodyTimeoutError());
+ }
+ } else if (timeoutType === TIMEOUT_KEEP_ALIVE) {
+ assert2(client[kRunning] === 0 && client[kKeepAliveTimeoutValue]);
+ util.destroy(socket, new InformationalError("socket idle timeout"));
+ }
+ }
+ __name(onParserTimeout, "onParserTimeout");
+ function connectH1(client, socket) {
+ client[kSocket] = socket;
+ if (!llhttpInstance) {
+ llhttpInstance = lazyllhttp();
+ }
+ if (socket.errored) {
+ throw socket.errored;
+ }
+ if (socket.destroyed) {
+ throw new SocketError("destroyed");
+ }
+ socket[kNoRef] = false;
+ socket[kWriting] = false;
+ socket[kReset2] = false;
+ socket[kBlocking] = false;
+ socket[kIdleSocketValidation] = 0;
+ socket[kIdleSocketValidationTimeout] = null;
+ socket[kSocketUsed] = false;
+ socket[kParser] = new Parser2(client, socket, llhttpInstance);
+ util.addListener(socket, "error", onHttpSocketError);
+ util.addListener(socket, "readable", onHttpSocketReadable);
+ util.addListener(socket, "end", onHttpSocketEnd);
+ util.addListener(socket, "close", onHttpSocketClose);
+ socket[kClosed] = false;
+ socket.on("close", onSocketClose);
+ return {
+ version: "h1",
+ defaultPipelining: 1,
+ write(request) {
+ return writeH1(client, request);
+ },
+ resume() {
+ resumeH1(client);
+ },
+ /**
+ * @param {Error|undefined} err
+ * @param {() => void} callback
+ */
+ destroy(err, callback) {
+ if (socket[kClosed]) {
+ queueMicrotask(callback);
+ } else {
+ socket.on("close", callback);
+ socket.destroy(err);
+ }
+ },
+ /**
+ * @returns {boolean}
+ */
+ get destroyed() {
+ return socket.destroyed;
+ },
+ /**
+ * @param {import('../core/request.js')} request
+ * @returns {boolean}
+ */
+ busy(request) {
+ if (socket[kWriting] || socket[kReset2] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) {
+ return true;
+ }
+ if (request) {
+ if (client[kRunning] > 0 && !request.idempotent) {
+ return true;
+ }
+ if (client[kRunning] > 0 && (request.upgrade || request.method === "CONNECT")) {
+ return true;
+ }
+ if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 && (util.isStream(request.body) || util.isAsyncIterable(request.body) || util.isFormDataLike(request.body))) {
+ return true;
+ }
+ }
+ return false;
+ }
+ };
+ }
+ __name(connectH1, "connectH1");
+ function onHttpSocketError(err) {
+ assert2(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
+ const parser2 = this[kParser];
+ if (err.code === "ECONNRESET" && parser2.statusCode && !parser2.shouldKeepAlive) {
+ const parserErr = parser2.finish();
+ if (parserErr) {
+ this[kError] = parserErr;
+ this[kClient][kOnError](parserErr);
+ }
+ return;
+ }
+ this[kError] = err;
+ this[kClient][kOnError](err);
+ }
+ __name(onHttpSocketError, "onHttpSocketError");
+ function onHttpSocketReadable() {
+ this[kParser]?.readMore();
+ }
+ __name(onHttpSocketReadable, "onHttpSocketReadable");
+ function onHttpSocketEnd() {
+ const parser2 = this[kParser];
+ if (parser2.statusCode && !parser2.shouldKeepAlive) {
+ const parserErr = parser2.finish();
+ if (parserErr) {
+ util.destroy(this, parserErr);
+ }
+ return;
+ }
+ util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this)));
+ }
+ __name(onHttpSocketEnd, "onHttpSocketEnd");
+ function onHttpSocketClose() {
+ const parser2 = this[kParser];
+ clearIdleSocketValidation(this);
+ if (parser2) {
+ if (!this[kError] && parser2.statusCode && !parser2.shouldKeepAlive) {
+ this[kError] = parser2.finish() || this[kError];
+ }
+ this[kParser].destroy();
+ this[kParser] = null;
+ }
+ const err = this[kError] || new SocketError("closed", util.getSocketInfo(this));
+ const client = this[kClient];
+ client[kSocket] = null;
+ client[kHTTPContext] = null;
+ if (client.destroyed) {
+ assert2(client[kPending] === 0);
+ const requests = client[kQueue].splice(client[kRunningIdx]);
+ for (let i = 0; i < requests.length; i++) {
+ const request = requests[i];
+ util.errorRequest(client, request, err);
+ }
+ } else if (client[kRunning] > 0 && err.code !== "UND_ERR_INFO") {
+ const request = client[kQueue][client[kRunningIdx]];
+ client[kQueue][client[kRunningIdx]++] = null;
+ util.errorRequest(client, request, err);
+ }
+ client[kPendingIdx] = client[kRunningIdx];
+ assert2(client[kRunning] === 0);
+ client.emit("disconnect", client[kUrl], [client], err);
+ client[kResume]();
+ }
+ __name(onHttpSocketClose, "onHttpSocketClose");
+ function onSocketClose() {
+ this[kClosed] = true;
+ }
+ __name(onSocketClose, "onSocketClose");
+ function clearIdleSocketValidation(socket) {
+ if (socket[kIdleSocketValidationTimeout]) {
+ clearTimeout(socket[kIdleSocketValidationTimeout]);
+ socket[kIdleSocketValidationTimeout] = null;
+ }
+ socket[kIdleSocketValidation] = 0;
+ }
+ __name(clearIdleSocketValidation, "clearIdleSocketValidation");
+ function scheduleIdleSocketValidation(client, socket) {
+ socket[kIdleSocketValidation] = 1;
+ socket[kIdleSocketValidationTimeout] = setTimeout(() => {
+ socket[kIdleSocketValidationTimeout] = null;
+ socket[kIdleSocketValidation] = 2;
+ if (client[kSocket] === socket && !socket.destroyed) {
+ client[kResume]();
+ }
+ }, 0);
+ socket[kIdleSocketValidationTimeout].unref?.();
+ }
+ __name(scheduleIdleSocketValidation, "scheduleIdleSocketValidation");
+ function resumeH1(client) {
+ const socket = client[kSocket];
+ if (socket && !socket.destroyed) {
+ if (client[kSize] === 0) {
+ if (!socket[kNoRef] && socket.unref) {
+ socket.unref();
+ socket[kNoRef] = true;
+ }
+ } else if (socket[kNoRef] && socket.ref) {
+ socket.ref();
+ socket[kNoRef] = false;
+ }
+ if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) {
+ if (socket[kIdleSocketValidation] === 0) {
+ scheduleIdleSocketValidation(client, socket);
+ socket[kParser].readMore();
+ if (socket.destroyed) {
+ return;
+ }
+ return;
+ }
+ if (socket[kIdleSocketValidation] === 1) {
+ socket[kParser].readMore();
+ if (socket.destroyed) {
+ return;
+ }
+ return;
+ }
+ }
+ if (client[kRunning] === 0) {
+ socket[kParser].readMore();
+ if (socket.destroyed) {
+ return;
+ }
+ }
+ if (client[kSize] === 0) {
+ if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) {
+ socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE);
+ }
+ } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) {
+ if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) {
+ const request = client[kQueue][client[kRunningIdx]];
+ const headersTimeout = request.headersTimeout != null ? request.headersTimeout : client[kHeadersTimeout];
+ socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS);
+ }
+ }
+ }
+ }
+ __name(resumeH1, "resumeH1");
+ function shouldSendContentLength(method) {
+ return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT";
+ }
+ __name(shouldSendContentLength, "shouldSendContentLength");
+ function writeH1(client, request) {
+ const { method, path: path27, host, upgrade, blocking, reset: reset2 } = request;
+ let { body, headers, contentLength } = request;
+ const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH" || method === "QUERY" || method === "PROPFIND" || method === "PROPPATCH";
+ if (util.isFormDataLike(body)) {
+ if (!extractBody) {
+ extractBody = require_body().extractBody;
+ }
+ const [bodyStream, contentType] = extractBody(body);
+ if (request.contentType == null) {
+ headers.push("content-type", contentType);
+ }
+ body = bodyStream.stream;
+ contentLength = bodyStream.length;
+ } else if (util.isBlobLike(body) && request.contentType == null && body.type) {
+ headers.push("content-type", body.type);
+ }
+ if (body && typeof body.read === "function") {
+ body.read(0);
+ }
+ const bodyLength = util.bodyLength(body);
+ contentLength = bodyLength ?? contentLength;
+ if (contentLength === null) {
+ contentLength = request.contentLength;
+ }
+ if (contentLength === 0 && !expectsPayload) {
+ contentLength = null;
+ }
+ if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) {
+ if (client[kStrictContentLength]) {
+ util.errorRequest(client, request, new RequestContentLengthMismatchError());
+ return false;
+ }
+ process.emitWarning(new RequestContentLengthMismatchError());
+ }
+ const socket = client[kSocket];
+ clearIdleSocketValidation(socket);
+ const abort = /* @__PURE__ */ __name((err) => {
+ if (request.aborted || request.completed) {
+ return;
+ }
+ util.errorRequest(client, request, err || new RequestAbortedError());
+ util.destroy(body);
+ util.destroy(socket, new InformationalError("aborted"));
+ }, "abort");
+ try {
+ request.onConnect(abort);
+ } catch (err) {
+ util.errorRequest(client, request, err);
+ }
+ if (request.aborted) {
+ return false;
+ }
+ if (method === "HEAD") {
+ socket[kReset2] = true;
+ }
+ if (upgrade || method === "CONNECT") {
+ socket[kReset2] = true;
+ }
+ if (reset2 != null) {
+ socket[kReset2] = reset2;
+ }
+ if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) {
+ socket[kReset2] = true;
+ }
+ if (blocking) {
+ socket[kBlocking] = true;
+ }
+ if (socket.setTypeOfService) {
+ socket.setTypeOfService(request.typeOfService);
+ }
+ let header = `${method} ${path27} HTTP/1.1\r
+`;
+ if (typeof host === "string") {
+ header += `host: ${host}\r
+`;
+ } else {
+ header += client[kHostHeader];
+ }
+ if (upgrade) {
+ header += `connection: upgrade\r
+upgrade: ${upgrade}\r
+`;
+ } else if (client[kPipelining] && !socket[kReset2]) {
+ header += "connection: keep-alive\r\n";
+ } else {
+ header += "connection: close\r\n";
+ }
+ if (Array.isArray(headers)) {
+ for (let n = 0; n < headers.length; n += 2) {
+ const key = headers[n + 0];
+ const val = headers[n + 1];
+ if (Array.isArray(val)) {
+ for (let i = 0; i < val.length; i++) {
+ header += `${key}: ${val[i]}\r
+`;
+ }
+ } else {
+ header += `${key}: ${val}\r
+`;
+ }
+ }
+ }
+ if (channels.sendHeaders.hasSubscribers) {
+ channels.sendHeaders.publish({ request, headers: header, socket });
+ }
+ if (!body || bodyLength === 0) {
+ writeBuffer(abort, null, client, request, socket, contentLength, header, expectsPayload);
+ } else if (util.isBuffer(body)) {
+ writeBuffer(abort, body, client, request, socket, contentLength, header, expectsPayload);
+ } else if (util.isBlobLike(body)) {
+ if (typeof body.stream === "function") {
+ writeIterable(abort, body.stream(), client, request, socket, contentLength, header, expectsPayload);
+ } else {
+ writeBlob(abort, body, client, request, socket, contentLength, header, expectsPayload);
+ }
+ } else if (util.isStream(body)) {
+ writeStream(abort, body, client, request, socket, contentLength, header, expectsPayload);
+ } else if (util.isIterable(body)) {
+ writeIterable(abort, body, client, request, socket, contentLength, header, expectsPayload);
+ } else {
+ assert2(false);
+ }
+ return true;
+ }
+ __name(writeH1, "writeH1");
+ function writeStream(abort, body, client, request, socket, contentLength, header, expectsPayload) {
+ assert2(contentLength !== 0 || client[kRunning] === 0, "stream body cannot be pipelined");
+ let finished = false;
+ const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header });
+ const onData = /* @__PURE__ */ __name(function(chunk) {
+ if (finished) {
+ return;
+ }
+ try {
+ if (!writer.write(chunk) && this.pause) {
+ this.pause();
+ }
+ } catch (err) {
+ util.destroy(this, err);
+ }
+ }, "onData");
+ const onDrain = /* @__PURE__ */ __name(function() {
+ if (finished) {
+ return;
+ }
+ if (body.resume) {
+ body.resume();
+ }
+ }, "onDrain");
+ const onClose = /* @__PURE__ */ __name(function() {
+ queueMicrotask(() => {
+ body.removeListener("error", onFinished);
+ });
+ if (!finished) {
+ const err = new RequestAbortedError();
+ queueMicrotask(() => onFinished(err));
+ }
+ }, "onClose");
+ const onFinished = /* @__PURE__ */ __name(function(err) {
+ if (finished) {
+ return;
+ }
+ finished = true;
+ assert2(socket.destroyed || socket[kWriting] && client[kRunning] <= 1);
+ socket.off("drain", onDrain).off("error", onFinished);
+ body.removeListener("data", onData).removeListener("end", onFinished).removeListener("close", onClose);
+ if (!err) {
+ try {
+ writer.end();
+ } catch (er) {
+ err = er;
+ }
+ }
+ writer.destroy(err);
+ if (err && (err.code !== "UND_ERR_INFO" || err.message !== "reset")) {
+ util.destroy(body, err);
+ } else {
+ util.destroy(body);
+ }
+ }, "onFinished");
+ body.on("data", onData).on("end", onFinished).on("error", onFinished).on("close", onClose);
+ if (body.resume) {
+ body.resume();
+ }
+ socket.on("drain", onDrain).on("error", onFinished);
+ if (body.errorEmitted ?? body.errored) {
+ setImmediate(onFinished, body.errored);
+ } else if (body.endEmitted ?? body.readableEnded) {
+ setImmediate(onFinished, null);
+ }
+ if (body.closeEmitted ?? body.closed) {
+ setImmediate(onClose);
+ }
+ }
+ __name(writeStream, "writeStream");
+ function writeBuffer(abort, body, client, request, socket, contentLength, header, expectsPayload) {
+ try {
+ if (!body) {
+ if (contentLength === 0) {
+ socket.write(`${header}content-length: 0\r
+\r
+`, "latin1");
+ } else {
+ assert2(contentLength === null, "no body must not have content length");
+ socket.write(`${header}\r
+`, "latin1");
+ }
+ } else if (util.isBuffer(body)) {
+ assert2(contentLength === body.byteLength, "buffer body must have content length");
+ socket.cork();
+ socket.write(`${header}content-length: ${contentLength}\r
+\r
+`, "latin1");
+ socket.write(body);
+ socket.uncork();
+ request.onBodySent(body);
+ if (!expectsPayload && request.reset !== false) {
+ socket[kReset2] = true;
+ }
+ }
+ request.onRequestSent();
+ client[kResume]();
+ } catch (err) {
+ abort(err);
+ }
+ }
+ __name(writeBuffer, "writeBuffer");
+ async function writeBlob(abort, body, client, request, socket, contentLength, header, expectsPayload) {
+ assert2(contentLength === body.size, "blob body must have content length");
+ try {
+ if (contentLength != null && contentLength !== body.size) {
+ throw new RequestContentLengthMismatchError();
+ }
+ const buffer = Buffer.from(await body.arrayBuffer());
+ socket.cork();
+ socket.write(`${header}content-length: ${contentLength}\r
+\r
+`, "latin1");
+ socket.write(buffer);
+ socket.uncork();
+ request.onBodySent(buffer);
+ request.onRequestSent();
+ if (!expectsPayload && request.reset !== false) {
+ socket[kReset2] = true;
+ }
+ client[kResume]();
+ } catch (err) {
+ abort(err);
+ }
+ }
+ __name(writeBlob, "writeBlob");
+ async function writeIterable(abort, body, client, request, socket, contentLength, header, expectsPayload) {
+ assert2(contentLength !== 0 || client[kRunning] === 0, "iterator body cannot be pipelined");
+ let callback = null;
+ function onDrain() {
+ if (callback) {
+ const cb = callback;
+ callback = null;
+ cb();
+ }
+ }
+ __name(onDrain, "onDrain");
+ const waitForDrain = /* @__PURE__ */ __name(() => new Promise((resolve16, reject) => {
+ assert2(callback === null);
+ if (socket[kError]) {
+ reject(socket[kError]);
+ } else {
+ callback = resolve16;
+ }
+ }), "waitForDrain");
+ socket.on("close", onDrain).on("drain", onDrain);
+ const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header });
+ try {
+ for await (const chunk of body) {
+ if (socket[kError]) {
+ throw socket[kError];
+ }
+ if (!writer.write(chunk)) {
+ await waitForDrain();
+ }
+ }
+ writer.end();
+ } catch (err) {
+ writer.destroy(err);
+ } finally {
+ socket.off("close", onDrain).off("drain", onDrain);
+ }
+ }
+ __name(writeIterable, "writeIterable");
+ var AsyncWriter = class {
+ static {
+ __name(this, "AsyncWriter");
+ }
+ /**
+ *
+ * @param {object} arg
+ * @param {AbortCallback} arg.abort
+ * @param {import('net').Socket} arg.socket
+ * @param {import('../core/request.js')} arg.request
+ * @param {number} arg.contentLength
+ * @param {import('./client.js')} arg.client
+ * @param {boolean} arg.expectsPayload
+ * @param {string} arg.header
+ */
+ constructor({ abort, socket, request, contentLength, client, expectsPayload, header }) {
+ this.socket = socket;
+ this.request = request;
+ this.contentLength = contentLength;
+ this.client = client;
+ this.bytesWritten = 0;
+ this.expectsPayload = expectsPayload;
+ this.header = header;
+ this.abort = abort;
+ socket[kWriting] = true;
+ }
+ /**
+ * @param {Buffer} chunk
+ * @returns
+ */
+ write(chunk) {
+ const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this;
+ if (socket[kError]) {
+ throw socket[kError];
+ }
+ if (socket.destroyed) {
+ return false;
+ }
+ const len = Buffer.byteLength(chunk);
+ if (!len) {
+ return true;
+ }
+ if (contentLength !== null && bytesWritten + len > contentLength) {
+ if (client[kStrictContentLength]) {
+ throw new RequestContentLengthMismatchError();
+ }
+ process.emitWarning(new RequestContentLengthMismatchError());
+ }
+ socket.cork();
+ if (bytesWritten === 0) {
+ if (!expectsPayload && request.reset !== false) {
+ socket[kReset2] = true;
+ }
+ if (contentLength === null) {
+ socket.write(`${header}transfer-encoding: chunked\r
+`, "latin1");
+ } else {
+ socket.write(`${header}content-length: ${contentLength}\r
+\r
+`, "latin1");
+ }
+ }
+ if (contentLength === null) {
+ socket.write(`\r
+${len.toString(16)}\r
+`, "latin1");
+ }
+ this.bytesWritten += len;
+ const ret = socket.write(chunk);
+ socket.uncork();
+ request.onBodySent(chunk);
+ if (!ret) {
+ if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
+ if (socket[kParser].timeout.refresh) {
+ socket[kParser].timeout.refresh();
+ }
+ }
+ }
+ return ret;
+ }
+ /**
+ * @returns {void}
+ */
+ end() {
+ const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this;
+ request.onRequestSent();
+ socket[kWriting] = false;
+ if (socket[kError]) {
+ throw socket[kError];
+ }
+ if (socket.destroyed) {
+ return;
+ }
+ if (bytesWritten === 0) {
+ if (expectsPayload) {
+ socket.write(`${header}content-length: 0\r
+\r
+`, "latin1");
+ } else {
+ socket.write(`${header}\r
+`, "latin1");
+ }
+ } else if (contentLength === null) {
+ socket.write("\r\n0\r\n\r\n", "latin1");
+ }
+ if (contentLength !== null && bytesWritten !== contentLength) {
+ if (client[kStrictContentLength]) {
+ throw new RequestContentLengthMismatchError();
+ } else {
+ process.emitWarning(new RequestContentLengthMismatchError());
+ }
+ }
+ if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
+ if (socket[kParser].timeout.refresh) {
+ socket[kParser].timeout.refresh();
+ }
+ }
+ client[kResume]();
+ }
+ /**
+ * @param {Error} [err]
+ * @returns {void}
+ */
+ destroy(err) {
+ const { socket, client, abort } = this;
+ socket[kWriting] = false;
+ if (err) {
+ assert2(client[kRunning] <= 1, "pipeline should only contain this request");
+ abort(err);
+ }
+ }
+ };
+ module2.exports = connectH1;
+ }
+});
+
+// node_modules/undici/lib/dispatcher/client-h2.js
+var require_client_h2 = __commonJS({
+ "node_modules/undici/lib/dispatcher/client-h2.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var assert2 = __require("node:assert");
+ var { pipeline } = __require("node:stream");
+ var util = require_util();
+ var {
+ RequestContentLengthMismatchError,
+ RequestAbortedError,
+ SocketError,
+ InformationalError,
+ InvalidArgumentError
+ } = require_errors();
+ var {
+ kUrl,
+ kReset: kReset2,
+ kClient,
+ kRunning,
+ kPending,
+ kQueue,
+ kPendingIdx,
+ kRunningIdx,
+ kError,
+ kSocket,
+ kStrictContentLength,
+ kOnError,
+ kMaxConcurrentStreams,
+ kPingInterval,
+ kHTTP2Session,
+ kHTTP2InitialWindowSize,
+ kHTTP2ConnectionWindowSize,
+ kResume,
+ kSize,
+ kHTTPContext,
+ kClosed,
+ kBodyTimeout,
+ kEnableConnectProtocol,
+ kRemoteSettings,
+ kHTTP2Stream,
+ kHTTP2SessionState
+ } = require_symbols();
+ var { channels } = require_diagnostics();
+ var kOpenStreams = /* @__PURE__ */ Symbol("open streams");
+ var extractBody;
+ var http2;
+ try {
+ http2 = __require("node:http2");
+ } catch {
+ http2 = { constants: {} };
+ }
+ var {
+ constants: {
+ HTTP2_HEADER_AUTHORITY,
+ HTTP2_HEADER_METHOD,
+ HTTP2_HEADER_PATH,
+ HTTP2_HEADER_SCHEME,
+ HTTP2_HEADER_CONTENT_LENGTH,
+ HTTP2_HEADER_EXPECT,
+ HTTP2_HEADER_STATUS,
+ HTTP2_HEADER_PROTOCOL,
+ NGHTTP2_REFUSED_STREAM,
+ NGHTTP2_CANCEL
+ }
+ } = http2;
+ function parseH2Headers(headers) {
+ const result = [];
+ for (const [name, value] of Object.entries(headers)) {
+ if (Array.isArray(value)) {
+ for (const subvalue of value) {
+ result.push(Buffer.from(name), Buffer.from(subvalue));
+ }
+ } else {
+ result.push(Buffer.from(name), Buffer.from(value));
+ }
+ }
+ return result;
+ }
+ __name(parseH2Headers, "parseH2Headers");
+ function connectH2(client, socket) {
+ client[kSocket] = socket;
+ const http2InitialWindowSize = client[kHTTP2InitialWindowSize];
+ const http2ConnectionWindowSize = client[kHTTP2ConnectionWindowSize];
+ const session = http2.connect(client[kUrl], {
+ createConnection: /* @__PURE__ */ __name(() => socket, "createConnection"),
+ peerMaxConcurrentStreams: client[kMaxConcurrentStreams],
+ settings: {
+ // TODO(metcoder95): add support for PUSH
+ enablePush: false,
+ ...http2InitialWindowSize != null ? { initialWindowSize: http2InitialWindowSize } : null
+ }
+ });
+ client[kSocket] = socket;
+ session[kOpenStreams] = 0;
+ session[kClient] = client;
+ session[kSocket] = socket;
+ session[kHTTP2SessionState] = {
+ ping: {
+ interval: client[kPingInterval] === 0 ? null : setInterval(onHttp2SendPing, client[kPingInterval], session).unref()
+ }
+ };
+ session[kEnableConnectProtocol] = false;
+ session[kRemoteSettings] = false;
+ if (http2ConnectionWindowSize) {
+ util.addListener(session, "connect", applyConnectionWindowSize.bind(session, http2ConnectionWindowSize));
+ }
+ util.addListener(session, "error", onHttp2SessionError);
+ util.addListener(session, "frameError", onHttp2FrameError);
+ util.addListener(session, "end", onHttp2SessionEnd);
+ util.addListener(session, "goaway", onHttp2SessionGoAway);
+ util.addListener(session, "close", onHttp2SessionClose);
+ util.addListener(session, "remoteSettings", onHttp2RemoteSettings);
+ session.unref();
+ client[kHTTP2Session] = session;
+ socket[kHTTP2Session] = session;
+ util.addListener(socket, "error", onHttp2SocketError);
+ util.addListener(socket, "end", onHttp2SocketEnd);
+ util.addListener(socket, "close", onHttp2SocketClose);
+ socket[kClosed] = false;
+ socket.on("close", onSocketClose);
+ return {
+ version: "h2",
+ defaultPipelining: Infinity,
+ /**
+ * @param {import('../core/request.js')} request
+ * @returns {boolean}
+ */
+ write(request) {
+ return writeH2(client, request);
+ },
+ /**
+ * @returns {void}
+ */
+ resume() {
+ resumeH2(client);
+ },
+ /**
+ * @param {Error | null} err
+ * @param {() => void} callback
+ */
+ destroy(err, callback) {
+ if (socket[kClosed]) {
+ queueMicrotask(callback);
+ } else {
+ socket.destroy(err).on("close", callback);
+ }
+ },
+ /**
+ * @type {boolean}
+ */
+ get destroyed() {
+ return socket.destroyed;
+ },
+ /**
+ * @param {import('../core/request.js')} request
+ * @returns {boolean}
+ */
+ busy(request) {
+ if (request != null) {
+ if (client[kRunning] > 0) {
+ if (request.idempotent === false) return true;
+ if ((request.upgrade === "websocket" || request.method === "CONNECT") && session[kRemoteSettings] === false) return true;
+ if (util.bodyLength(request.body) !== 0 && (util.isStream(request.body) || util.isAsyncIterable(request.body) || util.isFormDataLike(request.body))) return true;
+ } else {
+ return (request.upgrade === "websocket" || request.method === "CONNECT") && session[kRemoteSettings] === false;
+ }
+ }
+ return false;
+ }
+ };
+ }
+ __name(connectH2, "connectH2");
+ function resumeH2(client) {
+ const socket = client[kSocket];
+ if (socket?.destroyed === false) {
+ if (client[kSize] === 0 || client[kMaxConcurrentStreams] === 0) {
+ socket.unref();
+ client[kHTTP2Session].unref();
+ } else {
+ socket.ref();
+ client[kHTTP2Session].ref();
+ }
+ }
+ }
+ __name(resumeH2, "resumeH2");
+ function applyConnectionWindowSize(connectionWindowSize) {
+ try {
+ if (typeof this.setLocalWindowSize === "function") {
+ this.setLocalWindowSize(connectionWindowSize);
+ }
+ } catch {
+ }
+ }
+ __name(applyConnectionWindowSize, "applyConnectionWindowSize");
+ function onHttp2RemoteSettings(settings) {
+ this[kClient][kMaxConcurrentStreams] = settings.maxConcurrentStreams ?? this[kClient][kMaxConcurrentStreams];
+ if (this[kRemoteSettings] === true && this[kEnableConnectProtocol] === true && settings.enableConnectProtocol === false) {
+ const err = new InformationalError("HTTP/2: Server disabled extended CONNECT protocol against RFC-8441");
+ this[kSocket][kError] = err;
+ this[kClient][kOnError](err);
+ return;
+ }
+ this[kEnableConnectProtocol] = settings.enableConnectProtocol ?? this[kEnableConnectProtocol];
+ this[kRemoteSettings] = true;
+ this[kClient][kResume]();
+ }
+ __name(onHttp2RemoteSettings, "onHttp2RemoteSettings");
+ function onHttp2SendPing(session) {
+ const state = session[kHTTP2SessionState];
+ if ((session.closed || session.destroyed) && state.ping.interval != null) {
+ clearInterval(state.ping.interval);
+ state.ping.interval = null;
+ return;
+ }
+ session.ping(onPing.bind(session));
+ function onPing(err, duration3) {
+ const client = this[kClient];
+ const socket = this[kClient];
+ if (err != null) {
+ const error51 = new InformationalError(`HTTP/2: "PING" errored - type ${err.message}`);
+ socket[kError] = error51;
+ client[kOnError](error51);
+ } else {
+ client.emit("ping", duration3);
+ }
+ }
+ __name(onPing, "onPing");
+ }
+ __name(onHttp2SendPing, "onHttp2SendPing");
+ function onHttp2SessionError(err) {
+ assert2(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
+ this[kSocket][kError] = err;
+ this[kClient][kOnError](err);
+ }
+ __name(onHttp2SessionError, "onHttp2SessionError");
+ function onHttp2FrameError(type2, code, id) {
+ if (id === 0) {
+ const err = new InformationalError(`HTTP/2: "frameError" received - type ${type2}, code ${code}`);
+ this[kSocket][kError] = err;
+ this[kClient][kOnError](err);
+ }
+ }
+ __name(onHttp2FrameError, "onHttp2FrameError");
+ function onHttp2SessionEnd() {
+ const err = new SocketError("other side closed", util.getSocketInfo(this[kSocket]));
+ this.destroy(err);
+ util.destroy(this[kSocket], err);
+ }
+ __name(onHttp2SessionEnd, "onHttp2SessionEnd");
+ function onHttp2SessionGoAway(errorCode) {
+ const err = this[kError] || new SocketError(`HTTP/2: "GOAWAY" frame received with code ${errorCode}`, util.getSocketInfo(this[kSocket]));
+ const client = this[kClient];
+ client[kSocket] = null;
+ client[kHTTPContext] = null;
+ this.close();
+ this[kHTTP2Session] = null;
+ util.destroy(this[kSocket], err);
+ if (client[kRunningIdx] < client[kQueue].length) {
+ const request = client[kQueue][client[kRunningIdx]];
+ client[kQueue][client[kRunningIdx]++] = null;
+ util.errorRequest(client, request, err);
+ client[kPendingIdx] = client[kRunningIdx];
+ }
+ assert2(client[kRunning] === 0);
+ client.emit("disconnect", client[kUrl], [client], err);
+ client.emit("connectionError", client[kUrl], [client], err);
+ client[kResume]();
+ }
+ __name(onHttp2SessionGoAway, "onHttp2SessionGoAway");
+ function onHttp2SessionClose() {
+ const { [kClient]: client, [kHTTP2SessionState]: state } = this;
+ const { [kSocket]: socket } = client;
+ const err = this[kSocket][kError] || this[kError] || new SocketError("closed", util.getSocketInfo(socket));
+ client[kSocket] = null;
+ client[kHTTPContext] = null;
+ if (state.ping.interval != null) {
+ clearInterval(state.ping.interval);
+ state.ping.interval = null;
+ }
+ if (client.destroyed) {
+ assert2(client[kPending] === 0);
+ const requests = client[kQueue].splice(client[kRunningIdx]);
+ for (let i = 0; i < requests.length; i++) {
+ const request = requests[i];
+ util.errorRequest(client, request, err);
+ }
+ }
+ }
+ __name(onHttp2SessionClose, "onHttp2SessionClose");
+ function onHttp2SocketClose() {
+ const err = this[kError] || new SocketError("closed", util.getSocketInfo(this));
+ const client = this[kHTTP2Session][kClient];
+ client[kSocket] = null;
+ client[kHTTPContext] = null;
+ if (this[kHTTP2Session] !== null) {
+ this[kHTTP2Session].destroy(err);
+ }
+ client[kPendingIdx] = client[kRunningIdx];
+ assert2(client[kRunning] === 0);
+ client.emit("disconnect", client[kUrl], [client], err);
+ client[kResume]();
+ }
+ __name(onHttp2SocketClose, "onHttp2SocketClose");
+ function onHttp2SocketError(err) {
+ assert2(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
+ this[kError] = err;
+ this[kClient][kOnError](err);
+ }
+ __name(onHttp2SocketError, "onHttp2SocketError");
+ function onHttp2SocketEnd() {
+ util.destroy(this, new SocketError("other side closed", util.getSocketInfo(this)));
+ }
+ __name(onHttp2SocketEnd, "onHttp2SocketEnd");
+ function onSocketClose() {
+ this[kClosed] = true;
+ }
+ __name(onSocketClose, "onSocketClose");
+ function shouldSendContentLength(method) {
+ return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT";
+ }
+ __name(shouldSendContentLength, "shouldSendContentLength");
+ function writeH2(client, request) {
+ const requestTimeout = request.bodyTimeout ?? client[kBodyTimeout];
+ const session = client[kHTTP2Session];
+ const { method, path: path27, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request;
+ let { body } = request;
+ if (upgrade != null && upgrade !== "websocket") {
+ util.errorRequest(client, request, new InvalidArgumentError(`Custom upgrade "${upgrade}" not supported over HTTP/2`));
+ return false;
+ }
+ const headers = {};
+ for (let n = 0; n < reqHeaders.length; n += 2) {
+ const key = reqHeaders[n + 0];
+ const val = reqHeaders[n + 1];
+ if (key === "cookie") {
+ if (headers[key] != null) {
+ headers[key] = Array.isArray(headers[key]) ? (headers[key].push(val), headers[key]) : [headers[key], val];
+ } else {
+ headers[key] = val;
+ }
+ continue;
+ }
+ if (Array.isArray(val)) {
+ for (let i = 0; i < val.length; i++) {
+ if (headers[key]) {
+ headers[key] += `, ${val[i]}`;
+ } else {
+ headers[key] = val[i];
+ }
+ }
+ } else if (headers[key]) {
+ headers[key] += `, ${val}`;
+ } else {
+ headers[key] = val;
+ }
+ }
+ let stream = null;
+ const { hostname: hostname4, port } = client[kUrl];
+ headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname4}${port ? `:${port}` : ""}`;
+ headers[HTTP2_HEADER_METHOD] = method;
+ const abort = /* @__PURE__ */ __name((err) => {
+ if (request.aborted || request.completed) {
+ return;
+ }
+ err = err || new RequestAbortedError();
+ util.errorRequest(client, request, err);
+ if (stream != null) {
+ stream.removeAllListeners("data");
+ stream.close();
+ client[kOnError](err);
+ client[kResume]();
+ }
+ util.destroy(body, err);
+ }, "abort");
+ try {
+ request.onConnect(abort);
+ } catch (err) {
+ util.errorRequest(client, request, err);
+ }
+ if (request.aborted) {
+ return false;
+ }
+ if (upgrade || method === "CONNECT") {
+ session.ref();
+ if (upgrade === "websocket") {
+ if (session[kEnableConnectProtocol] === false) {
+ util.errorRequest(client, request, new InformationalError("HTTP/2: Extended CONNECT protocol not supported by server"));
+ session.unref();
+ return false;
+ }
+ headers[HTTP2_HEADER_METHOD] = "CONNECT";
+ headers[HTTP2_HEADER_PROTOCOL] = "websocket";
+ headers[HTTP2_HEADER_PATH] = path27;
+ if (protocol === "ws:" || protocol === "wss:") {
+ headers[HTTP2_HEADER_SCHEME] = protocol === "ws:" ? "http" : "https";
+ } else {
+ headers[HTTP2_HEADER_SCHEME] = protocol === "http:" ? "http" : "https";
+ }
+ stream = session.request(headers, { endStream: false, signal });
+ stream[kHTTP2Stream] = true;
+ stream.once("response", (headers2, _flags) => {
+ const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers2;
+ request.onUpgrade(statusCode, parseH2Headers(realHeaders), stream);
+ ++session[kOpenStreams];
+ client[kQueue][client[kRunningIdx]++] = null;
+ });
+ stream.on("error", () => {
+ if (stream.rstCode === NGHTTP2_REFUSED_STREAM || stream.rstCode === NGHTTP2_CANCEL) {
+ abort(new InformationalError(`HTTP/2: "stream error" received - code ${stream.rstCode}`));
+ }
+ });
+ stream.once("close", () => {
+ session[kOpenStreams] -= 1;
+ if (session[kOpenStreams] === 0) session.unref();
+ });
+ stream.setTimeout(requestTimeout);
+ return true;
+ }
+ stream = session.request(headers, { endStream: false, signal });
+ stream[kHTTP2Stream] = true;
+ stream.on("response", (headers2) => {
+ const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers2;
+ request.onUpgrade(statusCode, parseH2Headers(realHeaders), stream);
+ ++session[kOpenStreams];
+ client[kQueue][client[kRunningIdx]++] = null;
+ });
+ stream.once("close", () => {
+ session[kOpenStreams] -= 1;
+ if (session[kOpenStreams] === 0) session.unref();
+ });
+ stream.setTimeout(requestTimeout);
+ return true;
+ }
+ headers[HTTP2_HEADER_PATH] = path27;
+ headers[HTTP2_HEADER_SCHEME] = protocol === "http:" ? "http" : "https";
+ const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH";
+ if (body && typeof body.read === "function") {
+ body.read(0);
+ }
+ let contentLength = util.bodyLength(body);
+ if (util.isFormDataLike(body)) {
+ extractBody ??= require_body().extractBody;
+ const [bodyStream, contentType] = extractBody(body);
+ headers["content-type"] = contentType;
+ body = bodyStream.stream;
+ contentLength = bodyStream.length;
+ }
+ if (contentLength == null) {
+ contentLength = request.contentLength;
+ }
+ if (!expectsPayload) {
+ contentLength = null;
+ }
+ if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) {
+ if (client[kStrictContentLength]) {
+ util.errorRequest(client, request, new RequestContentLengthMismatchError());
+ return false;
+ }
+ process.emitWarning(new RequestContentLengthMismatchError());
+ }
+ if (contentLength != null) {
+ assert2(body || contentLength === 0, "no body must not have content length");
+ headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`;
+ }
+ session.ref();
+ if (channels.sendHeaders.hasSubscribers) {
+ let header = "";
+ for (const key in headers) {
+ header += `${key}: ${headers[key]}\r
+`;
+ }
+ channels.sendHeaders.publish({ request, headers: header, socket: session[kSocket] });
+ }
+ const shouldEndStream = method === "GET" || method === "HEAD" || body === null;
+ if (expectContinue) {
+ headers[HTTP2_HEADER_EXPECT] = "100-continue";
+ stream = session.request(headers, { endStream: shouldEndStream, signal });
+ stream[kHTTP2Stream] = true;
+ stream.once("continue", writeBodyH2);
+ } else {
+ stream = session.request(headers, {
+ endStream: shouldEndStream,
+ signal
+ });
+ stream[kHTTP2Stream] = true;
+ writeBodyH2();
+ }
+ ++session[kOpenStreams];
+ stream.setTimeout(requestTimeout);
+ let responseReceived = false;
+ stream.once("response", (headers2) => {
+ const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers2;
+ request.onResponseStarted();
+ responseReceived = true;
+ if (request.aborted) {
+ stream.removeAllListeners("data");
+ return;
+ }
+ if (request.onHeaders(Number(statusCode), parseH2Headers(realHeaders), stream.resume.bind(stream), "") === false) {
+ stream.pause();
+ }
+ stream.on("data", (chunk) => {
+ if (request.aborted || request.completed) {
+ return;
+ }
+ if (request.onData(chunk) === false) {
+ stream.pause();
+ }
+ });
+ });
+ stream.once("end", () => {
+ stream.removeAllListeners("data");
+ if (responseReceived) {
+ if (!request.aborted && !request.completed) {
+ request.onComplete({});
+ }
+ client[kQueue][client[kRunningIdx]++] = null;
+ client[kResume]();
+ } else {
+ abort(new InformationalError("HTTP/2: stream half-closed (remote)"));
+ client[kQueue][client[kRunningIdx]++] = null;
+ client[kPendingIdx] = client[kRunningIdx];
+ client[kResume]();
+ }
+ });
+ stream.once("close", () => {
+ stream.removeAllListeners("data");
+ session[kOpenStreams] -= 1;
+ if (session[kOpenStreams] === 0) {
+ session.unref();
+ }
+ });
+ stream.once("error", function(err) {
+ stream.removeAllListeners("data");
+ abort(err);
+ });
+ stream.once("frameError", (type2, code) => {
+ stream.removeAllListeners("data");
+ abort(new InformationalError(`HTTP/2: "frameError" received - type ${type2}, code ${code}`));
+ });
+ stream.on("aborted", () => {
+ stream.removeAllListeners("data");
+ });
+ stream.on("timeout", () => {
+ const err = new InformationalError(`HTTP/2: "stream timeout after ${requestTimeout}"`);
+ stream.removeAllListeners("data");
+ session[kOpenStreams] -= 1;
+ if (session[kOpenStreams] === 0) {
+ session.unref();
+ }
+ abort(err);
+ });
+ stream.once("trailers", (trailers) => {
+ if (request.aborted || request.completed) {
+ return;
+ }
+ stream.removeAllListeners("data");
+ request.onComplete(trailers);
+ });
+ return true;
+ function writeBodyH2() {
+ if (!body || contentLength === 0) {
+ writeBuffer(
+ abort,
+ stream,
+ null,
+ client,
+ request,
+ client[kSocket],
+ contentLength,
+ expectsPayload
+ );
+ } else if (util.isBuffer(body)) {
+ writeBuffer(
+ abort,
+ stream,
+ body,
+ client,
+ request,
+ client[kSocket],
+ contentLength,
+ expectsPayload
+ );
+ } else if (util.isBlobLike(body)) {
+ if (typeof body.stream === "function") {
+ writeIterable(
+ abort,
+ stream,
+ body.stream(),
+ client,
+ request,
+ client[kSocket],
+ contentLength,
+ expectsPayload
+ );
+ } else {
+ writeBlob(
+ abort,
+ stream,
+ body,
+ client,
+ request,
+ client[kSocket],
+ contentLength,
+ expectsPayload
+ );
+ }
+ } else if (util.isStream(body)) {
+ writeStream(
+ abort,
+ client[kSocket],
+ expectsPayload,
+ stream,
+ body,
+ client,
+ request,
+ contentLength
+ );
+ } else if (util.isIterable(body)) {
+ writeIterable(
+ abort,
+ stream,
+ body,
+ client,
+ request,
+ client[kSocket],
+ contentLength,
+ expectsPayload
+ );
+ } else {
+ assert2(false);
+ }
+ }
+ __name(writeBodyH2, "writeBodyH2");
+ }
+ __name(writeH2, "writeH2");
+ function writeBuffer(abort, h2stream, body, client, request, socket, contentLength, expectsPayload) {
+ try {
+ if (body != null && util.isBuffer(body)) {
+ assert2(contentLength === body.byteLength, "buffer body must have content length");
+ h2stream.cork();
+ h2stream.write(body);
+ h2stream.uncork();
+ h2stream.end();
+ request.onBodySent(body);
+ }
+ if (!expectsPayload) {
+ socket[kReset2] = true;
+ }
+ request.onRequestSent();
+ client[kResume]();
+ } catch (error51) {
+ abort(error51);
+ }
+ }
+ __name(writeBuffer, "writeBuffer");
+ function writeStream(abort, socket, expectsPayload, h2stream, body, client, request, contentLength) {
+ assert2(contentLength !== 0 || client[kRunning] === 0, "stream body cannot be pipelined");
+ const pipe2 = pipeline(
+ body,
+ h2stream,
+ (err) => {
+ if (err) {
+ util.destroy(pipe2, err);
+ abort(err);
+ } else {
+ util.removeAllListeners(pipe2);
+ request.onRequestSent();
+ if (!expectsPayload) {
+ socket[kReset2] = true;
+ }
+ client[kResume]();
+ }
+ }
+ );
+ util.addListener(pipe2, "data", onPipeData);
+ function onPipeData(chunk) {
+ request.onBodySent(chunk);
+ }
+ __name(onPipeData, "onPipeData");
+ }
+ __name(writeStream, "writeStream");
+ async function writeBlob(abort, h2stream, body, client, request, socket, contentLength, expectsPayload) {
+ assert2(contentLength === body.size, "blob body must have content length");
+ try {
+ if (contentLength != null && contentLength !== body.size) {
+ throw new RequestContentLengthMismatchError();
+ }
+ const buffer = Buffer.from(await body.arrayBuffer());
+ h2stream.cork();
+ h2stream.write(buffer);
+ h2stream.uncork();
+ h2stream.end();
+ request.onBodySent(buffer);
+ request.onRequestSent();
+ if (!expectsPayload) {
+ socket[kReset2] = true;
+ }
+ client[kResume]();
+ } catch (err) {
+ abort(err);
+ }
+ }
+ __name(writeBlob, "writeBlob");
+ async function writeIterable(abort, h2stream, body, client, request, socket, contentLength, expectsPayload) {
+ assert2(contentLength !== 0 || client[kRunning] === 0, "iterator body cannot be pipelined");
+ let callback = null;
+ function onDrain() {
+ if (callback) {
+ const cb = callback;
+ callback = null;
+ cb();
+ }
+ }
+ __name(onDrain, "onDrain");
+ const waitForDrain = /* @__PURE__ */ __name(() => new Promise((resolve16, reject) => {
+ assert2(callback === null);
+ if (socket[kError]) {
+ reject(socket[kError]);
+ } else {
+ callback = resolve16;
+ }
+ }), "waitForDrain");
+ h2stream.on("close", onDrain).on("drain", onDrain);
+ try {
+ for await (const chunk of body) {
+ if (socket[kError]) {
+ throw socket[kError];
+ }
+ const res = h2stream.write(chunk);
+ request.onBodySent(chunk);
+ if (!res) {
+ await waitForDrain();
+ }
+ }
+ h2stream.end();
+ request.onRequestSent();
+ if (!expectsPayload) {
+ socket[kReset2] = true;
+ }
+ client[kResume]();
+ } catch (err) {
+ abort(err);
+ } finally {
+ h2stream.off("close", onDrain).off("drain", onDrain);
+ }
+ }
+ __name(writeIterable, "writeIterable");
+ module2.exports = connectH2;
+ }
+});
+
+// node_modules/undici/lib/dispatcher/client.js
+var require_client = __commonJS({
+ "node_modules/undici/lib/dispatcher/client.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var assert2 = __require("node:assert");
+ var net = __require("node:net");
+ var http = __require("node:http");
+ var util = require_util();
+ var { ClientStats } = require_stats();
+ var { channels } = require_diagnostics();
+ var Request = require_request();
+ var DispatcherBase = require_dispatcher_base();
+ var {
+ InvalidArgumentError,
+ InformationalError,
+ ClientDestroyedError
+ } = require_errors();
+ var buildConnector = require_connect();
+ var {
+ kUrl,
+ kServerName,
+ kClient,
+ kBusy,
+ kConnect,
+ kResuming,
+ kRunning,
+ kPending,
+ kSize,
+ kQueue,
+ kConnected,
+ kConnecting,
+ kNeedDrain,
+ kKeepAliveDefaultTimeout,
+ kHostHeader,
+ kPendingIdx,
+ kRunningIdx,
+ kError,
+ kPipelining,
+ kKeepAliveTimeoutValue,
+ kMaxHeadersSize,
+ kKeepAliveMaxTimeout,
+ kKeepAliveTimeoutThreshold,
+ kHeadersTimeout,
+ kBodyTimeout,
+ kStrictContentLength,
+ kConnector,
+ kMaxRequests,
+ kCounter,
+ kClose,
+ kDestroy,
+ kDispatch,
+ kLocalAddress,
+ kMaxResponseSize,
+ kOnError,
+ kHTTPContext,
+ kMaxConcurrentStreams,
+ kHTTP2InitialWindowSize,
+ kHTTP2ConnectionWindowSize,
+ kResume,
+ kPingInterval
+ } = require_symbols();
+ var connectH1 = require_client_h1();
+ var connectH2 = require_client_h2();
+ var kClosedResolve = /* @__PURE__ */ Symbol("kClosedResolve");
+ var getDefaultNodeMaxHeaderSize = http && http.maxHeaderSize && Number.isInteger(http.maxHeaderSize) && http.maxHeaderSize > 0 ? () => http.maxHeaderSize : () => {
+ throw new InvalidArgumentError("http module not available or http.maxHeaderSize invalid");
+ };
+ var noop3 = /* @__PURE__ */ __name(() => {
+ }, "noop");
+ function getPipelining(client) {
+ return client[kPipelining] ?? client[kHTTPContext]?.defaultPipelining ?? 1;
+ }
+ __name(getPipelining, "getPipelining");
+ var Client = class extends DispatcherBase {
+ static {
+ __name(this, "Client");
+ }
+ /**
+ *
+ * @param {string|URL} url
+ * @param {import('../../types/client.js').Client.Options} options
+ */
+ constructor(url2, {
+ maxHeaderSize,
+ headersTimeout,
+ socketTimeout,
+ requestTimeout,
+ connectTimeout,
+ bodyTimeout,
+ idleTimeout,
+ keepAlive,
+ keepAliveTimeout,
+ maxKeepAliveTimeout,
+ keepAliveMaxTimeout,
+ keepAliveTimeoutThreshold,
+ socketPath,
+ pipelining,
+ tls,
+ strictContentLength,
+ maxCachedSessions,
+ connect: connect2,
+ maxRequestsPerClient,
+ localAddress,
+ maxResponseSize,
+ autoSelectFamily,
+ autoSelectFamilyAttemptTimeout,
+ // h2
+ maxConcurrentStreams,
+ allowH2,
+ useH2c,
+ initialWindowSize,
+ connectionWindowSize,
+ pingInterval,
+ webSocket
+ } = {}) {
+ if (keepAlive !== void 0) {
+ throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead");
+ }
+ if (socketTimeout !== void 0) {
+ throw new InvalidArgumentError("unsupported socketTimeout, use headersTimeout & bodyTimeout instead");
+ }
+ if (requestTimeout !== void 0) {
+ throw new InvalidArgumentError("unsupported requestTimeout, use headersTimeout & bodyTimeout instead");
+ }
+ if (idleTimeout !== void 0) {
+ throw new InvalidArgumentError("unsupported idleTimeout, use keepAliveTimeout instead");
+ }
+ if (maxKeepAliveTimeout !== void 0) {
+ throw new InvalidArgumentError("unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead");
+ }
+ if (maxHeaderSize != null) {
+ if (!Number.isInteger(maxHeaderSize) || maxHeaderSize < 1) {
+ throw new InvalidArgumentError("invalid maxHeaderSize");
+ }
+ } else {
+ maxHeaderSize = getDefaultNodeMaxHeaderSize();
+ }
+ if (socketPath != null && typeof socketPath !== "string") {
+ throw new InvalidArgumentError("invalid socketPath");
+ }
+ if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) {
+ throw new InvalidArgumentError("invalid connectTimeout");
+ }
+ if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) {
+ throw new InvalidArgumentError("invalid keepAliveTimeout");
+ }
+ if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) {
+ throw new InvalidArgumentError("invalid keepAliveMaxTimeout");
+ }
+ if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) {
+ throw new InvalidArgumentError("invalid keepAliveTimeoutThreshold");
+ }
+ if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) {
+ throw new InvalidArgumentError("headersTimeout must be a positive integer or zero");
+ }
+ if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) {
+ throw new InvalidArgumentError("bodyTimeout must be a positive integer or zero");
+ }
+ if (connect2 != null && typeof connect2 !== "function" && typeof connect2 !== "object") {
+ throw new InvalidArgumentError("connect must be a function or an object");
+ }
+ if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) {
+ throw new InvalidArgumentError("maxRequestsPerClient must be a positive number");
+ }
+ if (localAddress != null && (typeof localAddress !== "string" || net.isIP(localAddress) === 0)) {
+ throw new InvalidArgumentError("localAddress must be valid string IP address");
+ }
+ if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) {
+ throw new InvalidArgumentError("maxResponseSize must be a positive number");
+ }
+ if (autoSelectFamilyAttemptTimeout != null && (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1)) {
+ throw new InvalidArgumentError("autoSelectFamilyAttemptTimeout must be a positive number");
+ }
+ if (allowH2 != null && typeof allowH2 !== "boolean") {
+ throw new InvalidArgumentError("allowH2 must be a valid boolean value");
+ }
+ if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== "number" || maxConcurrentStreams < 1)) {
+ throw new InvalidArgumentError("maxConcurrentStreams must be a positive integer, greater than 0");
+ }
+ if (useH2c != null && typeof useH2c !== "boolean") {
+ throw new InvalidArgumentError("useH2c must be a valid boolean value");
+ }
+ if (initialWindowSize != null && (!Number.isInteger(initialWindowSize) || initialWindowSize < 1)) {
+ throw new InvalidArgumentError("initialWindowSize must be a positive integer, greater than 0");
+ }
+ if (connectionWindowSize != null && (!Number.isInteger(connectionWindowSize) || connectionWindowSize < 1)) {
+ throw new InvalidArgumentError("connectionWindowSize must be a positive integer, greater than 0");
+ }
+ if (pingInterval != null && (typeof pingInterval !== "number" || !Number.isInteger(pingInterval) || pingInterval < 0)) {
+ throw new InvalidArgumentError("pingInterval must be a positive integer, greater or equal to 0");
+ }
+ super({ webSocket });
+ if (typeof connect2 !== "function") {
+ connect2 = buildConnector({
+ ...tls,
+ maxCachedSessions,
+ allowH2,
+ useH2c,
+ socketPath,
+ timeout: connectTimeout,
+ ...typeof autoSelectFamily === "boolean" ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : void 0,
+ ...connect2
+ });
+ } else {
+ const customConnect = connect2;
+ connect2 = /* @__PURE__ */ __name((opts, callback) => customConnect({
+ ...opts,
+ ...socketPath != null ? { socketPath } : null,
+ ...allowH2 != null ? { allowH2 } : null
+ }, callback), "connect");
+ }
+ this[kUrl] = util.parseOrigin(url2);
+ this[kConnector] = connect2;
+ this[kPipelining] = pipelining != null ? pipelining : 1;
+ this[kMaxHeadersSize] = maxHeaderSize;
+ this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout;
+ this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 6e5 : keepAliveMaxTimeout;
+ this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 2e3 : keepAliveTimeoutThreshold;
+ this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout];
+ this[kServerName] = null;
+ this[kLocalAddress] = localAddress != null ? localAddress : null;
+ this[kResuming] = 0;
+ this[kNeedDrain] = 0;
+ this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ""}\r
+`;
+ this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 3e5;
+ this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 3e5;
+ this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength;
+ this[kMaxRequests] = maxRequestsPerClient;
+ this[kClosedResolve] = null;
+ this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1;
+ this[kHTTPContext] = null;
+ this[kMaxConcurrentStreams] = maxConcurrentStreams != null ? maxConcurrentStreams : 100;
+ this[kHTTP2InitialWindowSize] = initialWindowSize != null ? initialWindowSize : 262144;
+ this[kHTTP2ConnectionWindowSize] = connectionWindowSize != null ? connectionWindowSize : 524288;
+ this[kPingInterval] = pingInterval != null ? pingInterval : 6e4;
+ this[kQueue] = [];
+ this[kRunningIdx] = 0;
+ this[kPendingIdx] = 0;
+ this[kResume] = (sync) => resume(this, sync);
+ this[kOnError] = (err) => onError(this, err);
+ }
+ get pipelining() {
+ return this[kPipelining];
+ }
+ set pipelining(value) {
+ this[kPipelining] = value;
+ this[kResume](true);
+ }
+ get stats() {
+ return new ClientStats(this);
+ }
+ get [kPending]() {
+ return this[kQueue].length - this[kPendingIdx];
+ }
+ get [kRunning]() {
+ return this[kPendingIdx] - this[kRunningIdx];
+ }
+ get [kSize]() {
+ return this[kQueue].length - this[kRunningIdx];
+ }
+ get [kConnected]() {
+ return !!this[kHTTPContext] && !this[kConnecting] && !this[kHTTPContext].destroyed;
+ }
+ get [kBusy]() {
+ return Boolean(
+ this[kHTTPContext]?.busy(null) || this[kSize] >= (getPipelining(this) || 1) || this[kPending] > 0
+ );
+ }
+ [kConnect](cb) {
+ connect(this);
+ this.once("connect", cb);
+ }
+ [kDispatch](opts, handler) {
+ const request = new Request(this[kUrl].origin, opts, handler);
+ this[kQueue].push(request);
+ if (this[kResuming]) {
+ } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) {
+ this[kResuming] = 1;
+ queueMicrotask(() => resume(this));
+ } else {
+ this[kResume](true);
+ }
+ if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) {
+ this[kNeedDrain] = 2;
+ }
+ return this[kNeedDrain] < 2;
+ }
+ [kClose]() {
+ return new Promise((resolve16) => {
+ if (this[kSize]) {
+ this[kClosedResolve] = resolve16;
+ } else {
+ resolve16(null);
+ }
+ });
+ }
+ [kDestroy](err) {
+ return new Promise((resolve16) => {
+ const requests = this[kQueue].splice(this[kPendingIdx]);
+ for (let i = 0; i < requests.length; i++) {
+ const request = requests[i];
+ util.errorRequest(this, request, err);
+ }
+ const callback = /* @__PURE__ */ __name(() => {
+ if (this[kClosedResolve]) {
+ this[kClosedResolve]();
+ this[kClosedResolve] = null;
+ }
+ resolve16(null);
+ }, "callback");
+ if (this[kHTTPContext]) {
+ this[kHTTPContext].destroy(err, callback);
+ this[kHTTPContext] = null;
+ } else {
+ queueMicrotask(callback);
+ }
+ this[kResume]();
+ });
+ }
+ };
+ function onError(client, err) {
+ if (client[kRunning] === 0 && err.code !== "UND_ERR_INFO" && err.code !== "UND_ERR_SOCKET") {
+ assert2(client[kPendingIdx] === client[kRunningIdx]);
+ const requests = client[kQueue].splice(client[kRunningIdx]);
+ for (let i = 0; i < requests.length; i++) {
+ const request = requests[i];
+ util.errorRequest(client, request, err);
+ }
+ assert2(client[kSize] === 0);
+ }
+ }
+ __name(onError, "onError");
+ function connect(client) {
+ assert2(!client[kConnecting]);
+ assert2(!client[kHTTPContext]);
+ let { host, hostname: hostname4, protocol, port } = client[kUrl];
+ if (hostname4[0] === "[") {
+ const idx = hostname4.indexOf("]");
+ assert2(idx !== -1);
+ const ip = hostname4.substring(1, idx);
+ assert2(net.isIPv6(ip));
+ hostname4 = ip;
+ }
+ client[kConnecting] = true;
+ if (channels.beforeConnect.hasSubscribers) {
+ channels.beforeConnect.publish({
+ connectParams: {
+ host,
+ hostname: hostname4,
+ protocol,
+ port,
+ version: client[kHTTPContext]?.version,
+ servername: client[kServerName],
+ localAddress: client[kLocalAddress]
+ },
+ connector: client[kConnector]
+ });
+ }
+ try {
+ client[kConnector]({
+ host,
+ hostname: hostname4,
+ protocol,
+ port,
+ servername: client[kServerName],
+ localAddress: client[kLocalAddress]
+ }, (err, socket) => {
+ if (err) {
+ handleConnectError(client, err, { host, hostname: hostname4, protocol, port });
+ client[kResume]();
+ return;
+ }
+ if (client.destroyed) {
+ util.destroy(socket.on("error", noop3), new ClientDestroyedError());
+ client[kResume]();
+ return;
+ }
+ assert2(socket);
+ try {
+ client[kHTTPContext] = socket.alpnProtocol === "h2" ? connectH2(client, socket) : connectH1(client, socket);
+ } catch (err2) {
+ socket.destroy().on("error", noop3);
+ handleConnectError(client, err2, { host, hostname: hostname4, protocol, port });
+ client[kResume]();
+ return;
+ }
+ client[kConnecting] = false;
+ socket[kCounter] = 0;
+ socket[kMaxRequests] = client[kMaxRequests];
+ socket[kClient] = client;
+ socket[kError] = null;
+ if (channels.connected.hasSubscribers) {
+ channels.connected.publish({
+ connectParams: {
+ host,
+ hostname: hostname4,
+ protocol,
+ port,
+ version: client[kHTTPContext]?.version,
+ servername: client[kServerName],
+ localAddress: client[kLocalAddress]
+ },
+ connector: client[kConnector],
+ socket
+ });
+ }
+ client.emit("connect", client[kUrl], [client]);
+ client[kResume]();
+ });
+ } catch (err) {
+ handleConnectError(client, err, { host, hostname: hostname4, protocol, port });
+ client[kResume]();
+ }
+ }
+ __name(connect, "connect");
+ function handleConnectError(client, err, { host, hostname: hostname4, protocol, port }) {
+ if (client.destroyed) {
+ return;
+ }
+ client[kConnecting] = false;
+ if (channels.connectError.hasSubscribers) {
+ channels.connectError.publish({
+ connectParams: {
+ host,
+ hostname: hostname4,
+ protocol,
+ port,
+ version: client[kHTTPContext]?.version,
+ servername: client[kServerName],
+ localAddress: client[kLocalAddress]
+ },
+ connector: client[kConnector],
+ error: err
+ });
+ }
+ if (err.code === "ERR_TLS_CERT_ALTNAME_INVALID") {
+ assert2(client[kRunning] === 0);
+ while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) {
+ const request = client[kQueue][client[kPendingIdx]++];
+ util.errorRequest(client, request, err);
+ }
+ } else {
+ onError(client, err);
+ }
+ client.emit("connectionError", client[kUrl], [client], err);
+ }
+ __name(handleConnectError, "handleConnectError");
+ function emitDrain(client) {
+ client[kNeedDrain] = 0;
+ client.emit("drain", client[kUrl], [client]);
+ }
+ __name(emitDrain, "emitDrain");
+ function resume(client, sync) {
+ if (client[kResuming] === 2) {
+ return;
+ }
+ client[kResuming] = 2;
+ _resume(client, sync);
+ client[kResuming] = 0;
+ if (client[kRunningIdx] > 256) {
+ client[kQueue].splice(0, client[kRunningIdx]);
+ client[kPendingIdx] -= client[kRunningIdx];
+ client[kRunningIdx] = 0;
+ }
+ }
+ __name(resume, "resume");
+ function _resume(client, sync) {
+ while (true) {
+ if (client.destroyed) {
+ assert2(client[kPending] === 0);
+ return;
+ }
+ if (client[kClosedResolve] && !client[kSize]) {
+ client[kClosedResolve]();
+ client[kClosedResolve] = null;
+ return;
+ }
+ if (client[kHTTPContext]) {
+ client[kHTTPContext].resume();
+ }
+ if (client[kBusy]) {
+ client[kNeedDrain] = 2;
+ } else if (client[kNeedDrain] === 2) {
+ if (sync) {
+ client[kNeedDrain] = 1;
+ queueMicrotask(() => emitDrain(client));
+ } else {
+ emitDrain(client);
+ }
+ continue;
+ }
+ if (client[kPending] === 0) {
+ return;
+ }
+ if (client[kRunning] >= (getPipelining(client) || 1)) {
+ return;
+ }
+ const request = client[kQueue][client[kPendingIdx]];
+ if (request === null) {
+ return;
+ }
+ if (client[kUrl].protocol === "https:" && client[kServerName] !== request.servername) {
+ if (client[kRunning] > 0) {
+ return;
+ }
+ client[kServerName] = request.servername;
+ client[kHTTPContext]?.destroy(new InformationalError("servername changed"), () => {
+ client[kHTTPContext] = null;
+ resume(client);
+ });
+ }
+ if (client[kConnecting]) {
+ return;
+ }
+ if (!client[kHTTPContext]) {
+ connect(client);
+ return;
+ }
+ if (client[kHTTPContext].destroyed) {
+ return;
+ }
+ if (client[kHTTPContext].busy(request)) {
+ return;
+ }
+ if (!request.aborted && client[kHTTPContext].write(request)) {
+ client[kPendingIdx]++;
+ } else {
+ client[kQueue].splice(client[kPendingIdx], 1);
+ }
+ }
+ }
+ __name(_resume, "_resume");
+ module2.exports = Client;
+ }
+});
+
+// node_modules/undici/lib/dispatcher/fixed-queue.js
+var require_fixed_queue = __commonJS({
+ "node_modules/undici/lib/dispatcher/fixed-queue.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var kSize = 2048;
+ var kMask = kSize - 1;
+ var FixedCircularBuffer = class {
+ static {
+ __name(this, "FixedCircularBuffer");
+ }
+ /** @type {number} */
+ bottom = 0;
+ /** @type {number} */
+ top = 0;
+ /** @type {Array} */
+ list = new Array(kSize).fill(void 0);
+ /** @type {T|null} */
+ next = null;
+ /** @returns {boolean} */
+ isEmpty() {
+ return this.top === this.bottom;
+ }
+ /** @returns {boolean} */
+ isFull() {
+ return (this.top + 1 & kMask) === this.bottom;
+ }
+ /**
+ * @param {T} data
+ * @returns {void}
+ */
+ push(data) {
+ this.list[this.top] = data;
+ this.top = this.top + 1 & kMask;
+ }
+ /** @returns {T|null} */
+ shift() {
+ const nextItem = this.list[this.bottom];
+ if (nextItem === void 0) {
+ return null;
+ }
+ this.list[this.bottom] = void 0;
+ this.bottom = this.bottom + 1 & kMask;
+ return nextItem;
+ }
+ };
+ module2.exports = class FixedQueue {
+ static {
+ __name(this, "FixedQueue");
+ }
+ constructor() {
+ this.head = this.tail = new FixedCircularBuffer();
+ }
+ /** @returns {boolean} */
+ isEmpty() {
+ return this.head.isEmpty();
+ }
+ /** @param {T} data */
+ push(data) {
+ if (this.head.isFull()) {
+ this.head = this.head.next = new FixedCircularBuffer();
+ }
+ this.head.push(data);
+ }
+ /** @returns {T|null} */
+ shift() {
+ const tail = this.tail;
+ const next = tail.shift();
+ if (tail.isEmpty() && tail.next !== null) {
+ this.tail = tail.next;
+ tail.next = null;
+ }
+ return next;
+ }
+ };
+ }
+});
+
+// node_modules/undici/lib/dispatcher/pool-base.js
+var require_pool_base = __commonJS({
+ "node_modules/undici/lib/dispatcher/pool-base.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { PoolStats } = require_stats();
+ var DispatcherBase = require_dispatcher_base();
+ var FixedQueue = require_fixed_queue();
+ var { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = require_symbols();
+ var kClients = /* @__PURE__ */ Symbol("clients");
+ var kNeedDrain = /* @__PURE__ */ Symbol("needDrain");
+ var kQueue = /* @__PURE__ */ Symbol("queue");
+ var kClosedResolve = /* @__PURE__ */ Symbol("closed resolve");
+ var kOnDrain = /* @__PURE__ */ Symbol("onDrain");
+ var kOnConnect = /* @__PURE__ */ Symbol("onConnect");
+ var kOnDisconnect = /* @__PURE__ */ Symbol("onDisconnect");
+ var kOnConnectionError = /* @__PURE__ */ Symbol("onConnectionError");
+ var kGetDispatcher = /* @__PURE__ */ Symbol("get dispatcher");
+ var kAddClient = /* @__PURE__ */ Symbol("add client");
+ var kRemoveClient = /* @__PURE__ */ Symbol("remove client");
+ var PoolBase = class extends DispatcherBase {
+ static {
+ __name(this, "PoolBase");
+ }
+ [kQueue] = new FixedQueue();
+ [kQueued] = 0;
+ [kClients] = [];
+ [kNeedDrain] = false;
+ [kOnDrain](client, origin, targets) {
+ const queue = this[kQueue];
+ let needDrain = false;
+ while (!needDrain) {
+ const item = queue.shift();
+ if (!item) {
+ break;
+ }
+ this[kQueued]--;
+ needDrain = !client.dispatch(item.opts, item.handler);
+ }
+ client[kNeedDrain] = needDrain;
+ if (!needDrain && this[kNeedDrain]) {
+ this[kNeedDrain] = false;
+ this.emit("drain", origin, [this, ...targets]);
+ }
+ if (this[kClosedResolve] && queue.isEmpty()) {
+ const closeAll = [];
+ for (let i = 0; i < this[kClients].length; i++) {
+ const client2 = this[kClients][i];
+ if (!client2.destroyed) {
+ closeAll.push(client2.close());
+ }
+ }
+ return Promise.all(closeAll).then(this[kClosedResolve]);
+ }
+ }
+ [kOnConnect] = (origin, targets) => {
+ this.emit("connect", origin, [this, ...targets]);
+ };
+ [kOnDisconnect] = (origin, targets, err) => {
+ this.emit("disconnect", origin, [this, ...targets], err);
+ };
+ [kOnConnectionError] = (origin, targets, err) => {
+ this.emit("connectionError", origin, [this, ...targets], err);
+ };
+ get [kBusy]() {
+ return this[kNeedDrain];
+ }
+ get [kConnected]() {
+ let ret = 0;
+ for (const { [kConnected]: connected } of this[kClients]) {
+ ret += connected;
+ }
+ return ret;
+ }
+ get [kFree]() {
+ let ret = 0;
+ for (const { [kConnected]: connected, [kNeedDrain]: needDrain } of this[kClients]) {
+ ret += connected && !needDrain;
+ }
+ return ret;
+ }
+ get [kPending]() {
+ let ret = this[kQueued];
+ for (const { [kPending]: pending } of this[kClients]) {
+ ret += pending;
+ }
+ return ret;
+ }
+ get [kRunning]() {
+ let ret = 0;
+ for (const { [kRunning]: running } of this[kClients]) {
+ ret += running;
+ }
+ return ret;
+ }
+ get [kSize]() {
+ let ret = this[kQueued];
+ for (const { [kSize]: size } of this[kClients]) {
+ ret += size;
+ }
+ return ret;
+ }
+ get stats() {
+ return new PoolStats(this);
+ }
+ [kClose]() {
+ if (this[kQueue].isEmpty()) {
+ const closeAll = [];
+ for (let i = 0; i < this[kClients].length; i++) {
+ const client = this[kClients][i];
+ if (!client.destroyed) {
+ closeAll.push(client.close());
+ }
+ }
+ return Promise.all(closeAll);
+ } else {
+ return new Promise((resolve16) => {
+ this[kClosedResolve] = resolve16;
+ });
+ }
+ }
+ [kDestroy](err) {
+ while (true) {
+ const item = this[kQueue].shift();
+ if (!item) {
+ break;
+ }
+ item.handler.onError(err);
+ }
+ const destroyAll = new Array(this[kClients].length);
+ for (let i = 0; i < this[kClients].length; i++) {
+ destroyAll[i] = this[kClients][i].destroy(err);
+ }
+ return Promise.all(destroyAll);
+ }
+ [kDispatch](opts, handler) {
+ const dispatcher = this[kGetDispatcher]();
+ if (!dispatcher) {
+ this[kNeedDrain] = true;
+ this[kQueue].push({ opts, handler });
+ this[kQueued]++;
+ } else if (!dispatcher.dispatch(opts, handler)) {
+ dispatcher[kNeedDrain] = true;
+ this[kNeedDrain] = !this[kGetDispatcher]();
+ }
+ return !this[kNeedDrain];
+ }
+ [kAddClient](client) {
+ client.on("drain", this[kOnDrain].bind(this, client)).on("connect", this[kOnConnect]).on("disconnect", this[kOnDisconnect]).on("connectionError", this[kOnConnectionError]);
+ this[kClients].push(client);
+ if (this[kNeedDrain]) {
+ queueMicrotask(() => {
+ if (this[kNeedDrain]) {
+ this[kOnDrain](client, client[kUrl], [client, this]);
+ }
+ });
+ }
+ return this;
+ }
+ [kRemoveClient](client) {
+ client.close(() => {
+ const idx = this[kClients].indexOf(client);
+ if (idx !== -1) {
+ this[kClients].splice(idx, 1);
+ }
+ });
+ this[kNeedDrain] = this[kClients].some((dispatcher) => !dispatcher[kNeedDrain] && dispatcher.closed !== true && dispatcher.destroyed !== true);
+ }
+ };
+ module2.exports = {
+ PoolBase,
+ kClients,
+ kNeedDrain,
+ kAddClient,
+ kRemoveClient,
+ kGetDispatcher
+ };
+ }
+});
+
+// node_modules/undici/lib/dispatcher/pool.js
+var require_pool = __commonJS({
+ "node_modules/undici/lib/dispatcher/pool.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var {
+ PoolBase,
+ kClients,
+ kNeedDrain,
+ kAddClient,
+ kGetDispatcher,
+ kRemoveClient
+ } = require_pool_base();
+ var Client = require_client();
+ var {
+ InvalidArgumentError
+ } = require_errors();
+ var util = require_util();
+ var { kUrl } = require_symbols();
+ var buildConnector = require_connect();
+ var kOptions = /* @__PURE__ */ Symbol("options");
+ var kConnections = /* @__PURE__ */ Symbol("connections");
+ var kFactory = /* @__PURE__ */ Symbol("factory");
+ function defaultFactory(origin, opts) {
+ return new Client(origin, opts);
+ }
+ __name(defaultFactory, "defaultFactory");
+ var Pool = class extends PoolBase {
+ static {
+ __name(this, "Pool");
+ }
+ constructor(origin, {
+ connections,
+ factory = defaultFactory,
+ connect,
+ connectTimeout,
+ tls,
+ maxCachedSessions,
+ socketPath,
+ autoSelectFamily,
+ autoSelectFamilyAttemptTimeout,
+ allowH2,
+ clientTtl,
+ ...options2
+ } = {}) {
+ if (connections != null && (!Number.isFinite(connections) || connections < 0)) {
+ throw new InvalidArgumentError("invalid connections");
+ }
+ if (typeof factory !== "function") {
+ throw new InvalidArgumentError("factory must be a function.");
+ }
+ if (connect != null && typeof connect !== "function" && typeof connect !== "object") {
+ throw new InvalidArgumentError("connect must be a function or an object");
+ }
+ if (typeof connect !== "function") {
+ connect = buildConnector({
+ ...tls,
+ maxCachedSessions,
+ allowH2,
+ socketPath,
+ timeout: connectTimeout,
+ ...typeof autoSelectFamily === "boolean" ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : void 0,
+ ...connect
+ });
+ }
+ super(options2);
+ this[kConnections] = connections || null;
+ this[kUrl] = util.parseOrigin(origin);
+ this[kOptions] = { ...util.deepClone(options2), connect, allowH2, clientTtl, socketPath };
+ this[kOptions].interceptors = options2.interceptors ? { ...options2.interceptors } : void 0;
+ this[kFactory] = factory;
+ this.on("connect", (origin2, targets) => {
+ if (clientTtl != null && clientTtl > 0) {
+ for (const target of targets) {
+ Object.assign(target, { ttl: Date.now() });
+ }
+ }
+ });
+ this.on("connectionError", (origin2, targets, error51) => {
+ for (const target of targets) {
+ const idx = this[kClients].indexOf(target);
+ if (idx !== -1) {
+ this[kClients].splice(idx, 1);
+ }
+ }
+ });
+ }
+ [kGetDispatcher]() {
+ const clientTtlOption = this[kOptions].clientTtl;
+ for (const client of this[kClients]) {
+ if (clientTtlOption != null && clientTtlOption > 0 && client.ttl && Date.now() - client.ttl > clientTtlOption) {
+ this[kRemoveClient](client);
+ } else if (!client[kNeedDrain]) {
+ return client;
+ }
+ }
+ if (!this[kConnections] || this[kClients].length < this[kConnections]) {
+ const dispatcher = this[kFactory](this[kUrl], this[kOptions]);
+ this[kAddClient](dispatcher);
+ return dispatcher;
+ }
+ }
+ };
+ module2.exports = Pool;
+ }
+});
+
+// node_modules/undici/lib/dispatcher/balanced-pool.js
+var require_balanced_pool = __commonJS({
+ "node_modules/undici/lib/dispatcher/balanced-pool.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var {
+ BalancedPoolMissingUpstreamError,
+ InvalidArgumentError
+ } = require_errors();
+ var {
+ PoolBase,
+ kClients,
+ kNeedDrain,
+ kAddClient,
+ kRemoveClient,
+ kGetDispatcher
+ } = require_pool_base();
+ var Pool = require_pool();
+ var { kUrl } = require_symbols();
+ var util = require_util();
+ var kFactory = /* @__PURE__ */ Symbol("factory");
+ var kOptions = /* @__PURE__ */ Symbol("options");
+ var kGreatestCommonDivisor = /* @__PURE__ */ Symbol("kGreatestCommonDivisor");
+ var kCurrentWeight = /* @__PURE__ */ Symbol("kCurrentWeight");
+ var kIndex = /* @__PURE__ */ Symbol("kIndex");
+ var kWeight = /* @__PURE__ */ Symbol("kWeight");
+ var kMaxWeightPerServer = /* @__PURE__ */ Symbol("kMaxWeightPerServer");
+ var kErrorPenalty = /* @__PURE__ */ Symbol("kErrorPenalty");
+ function getGreatestCommonDivisor(a, b) {
+ if (a === 0) return b;
+ while (b !== 0) {
+ const t = b;
+ b = a % b;
+ a = t;
+ }
+ return a;
+ }
+ __name(getGreatestCommonDivisor, "getGreatestCommonDivisor");
+ function defaultFactory(origin, opts) {
+ return new Pool(origin, opts);
+ }
+ __name(defaultFactory, "defaultFactory");
+ var BalancedPool = class extends PoolBase {
+ static {
+ __name(this, "BalancedPool");
+ }
+ constructor(upstreams = [], { factory = defaultFactory, ...opts } = {}) {
+ if (typeof factory !== "function") {
+ throw new InvalidArgumentError("factory must be a function.");
+ }
+ super(opts);
+ this[kOptions] = { ...util.deepClone(opts) };
+ this[kOptions].interceptors = opts.interceptors ? { ...opts.interceptors } : void 0;
+ this[kIndex] = -1;
+ this[kCurrentWeight] = 0;
+ this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100;
+ this[kErrorPenalty] = this[kOptions].errorPenalty || 15;
+ if (!Array.isArray(upstreams)) {
+ upstreams = [upstreams];
+ }
+ this[kFactory] = factory;
+ for (const upstream of upstreams) {
+ this.addUpstream(upstream);
+ }
+ this._updateBalancedPoolStats();
+ }
+ addUpstream(upstream) {
+ const upstreamOrigin = util.parseOrigin(upstream).origin;
+ if (this[kClients].find((pool2) => pool2[kUrl].origin === upstreamOrigin && pool2.closed !== true && pool2.destroyed !== true)) {
+ return this;
+ }
+ const pool = this[kFactory](upstreamOrigin, this[kOptions]);
+ this[kAddClient](pool);
+ pool.on("connect", () => {
+ pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty]);
+ });
+ pool.on("connectionError", () => {
+ pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]);
+ this._updateBalancedPoolStats();
+ });
+ pool.on("disconnect", (...args) => {
+ const err = args[2];
+ if (err && err.code === "UND_ERR_SOCKET") {
+ pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]);
+ this._updateBalancedPoolStats();
+ }
+ });
+ for (const client of this[kClients]) {
+ client[kWeight] = this[kMaxWeightPerServer];
+ }
+ this._updateBalancedPoolStats();
+ return this;
+ }
+ _updateBalancedPoolStats() {
+ let result = 0;
+ for (let i = 0; i < this[kClients].length; i++) {
+ result = getGreatestCommonDivisor(this[kClients][i][kWeight], result);
+ }
+ this[kGreatestCommonDivisor] = result;
+ }
+ removeUpstream(upstream) {
+ const upstreamOrigin = util.parseOrigin(upstream).origin;
+ const pool = this[kClients].find((pool2) => pool2[kUrl].origin === upstreamOrigin && pool2.closed !== true && pool2.destroyed !== true);
+ if (pool) {
+ this[kRemoveClient](pool);
+ }
+ return this;
+ }
+ getUpstream(upstream) {
+ const upstreamOrigin = util.parseOrigin(upstream).origin;
+ return this[kClients].find((pool) => pool[kUrl].origin === upstreamOrigin && pool.closed !== true && pool.destroyed !== true);
+ }
+ get upstreams() {
+ return this[kClients].filter((dispatcher) => dispatcher.closed !== true && dispatcher.destroyed !== true).map((p) => p[kUrl].origin);
+ }
+ [kGetDispatcher]() {
+ if (this[kClients].length === 0) {
+ throw new BalancedPoolMissingUpstreamError();
+ }
+ const dispatcher = this[kClients].find((dispatcher2) => !dispatcher2[kNeedDrain] && dispatcher2.closed !== true && dispatcher2.destroyed !== true);
+ if (!dispatcher) {
+ return;
+ }
+ const allClientsBusy = this[kClients].map((pool) => pool[kNeedDrain]).reduce((a, b) => a && b, true);
+ if (allClientsBusy) {
+ return;
+ }
+ let counter = 0;
+ let maxWeightIndex = this[kClients].findIndex((pool) => !pool[kNeedDrain]);
+ while (counter++ < this[kClients].length) {
+ this[kIndex] = (this[kIndex] + 1) % this[kClients].length;
+ const pool = this[kClients][this[kIndex]];
+ if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) {
+ maxWeightIndex = this[kIndex];
+ }
+ if (this[kIndex] === 0) {
+ this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor];
+ if (this[kCurrentWeight] <= 0) {
+ this[kCurrentWeight] = this[kMaxWeightPerServer];
+ }
+ }
+ if (pool[kWeight] >= this[kCurrentWeight] && !pool[kNeedDrain]) {
+ return pool;
+ }
+ }
+ this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight];
+ this[kIndex] = maxWeightIndex;
+ return this[kClients][maxWeightIndex];
+ }
+ };
+ module2.exports = BalancedPool;
+ }
+});
+
+// node_modules/undici/lib/dispatcher/round-robin-pool.js
+var require_round_robin_pool = __commonJS({
+ "node_modules/undici/lib/dispatcher/round-robin-pool.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var {
+ PoolBase,
+ kClients,
+ kNeedDrain,
+ kAddClient,
+ kGetDispatcher,
+ kRemoveClient
+ } = require_pool_base();
+ var Client = require_client();
+ var {
+ InvalidArgumentError
+ } = require_errors();
+ var util = require_util();
+ var { kUrl } = require_symbols();
+ var buildConnector = require_connect();
+ var kOptions = /* @__PURE__ */ Symbol("options");
+ var kConnections = /* @__PURE__ */ Symbol("connections");
+ var kFactory = /* @__PURE__ */ Symbol("factory");
+ var kIndex = /* @__PURE__ */ Symbol("index");
+ function defaultFactory(origin, opts) {
+ return new Client(origin, opts);
+ }
+ __name(defaultFactory, "defaultFactory");
+ var RoundRobinPool = class extends PoolBase {
+ static {
+ __name(this, "RoundRobinPool");
+ }
+ constructor(origin, {
+ connections,
+ factory = defaultFactory,
+ connect,
+ connectTimeout,
+ tls,
+ maxCachedSessions,
+ socketPath,
+ autoSelectFamily,
+ autoSelectFamilyAttemptTimeout,
+ allowH2,
+ clientTtl,
+ ...options2
+ } = {}) {
+ if (connections != null && (!Number.isFinite(connections) || connections < 0)) {
+ throw new InvalidArgumentError("invalid connections");
+ }
+ if (typeof factory !== "function") {
+ throw new InvalidArgumentError("factory must be a function.");
+ }
+ if (connect != null && typeof connect !== "function" && typeof connect !== "object") {
+ throw new InvalidArgumentError("connect must be a function or an object");
+ }
+ if (typeof connect !== "function") {
+ connect = buildConnector({
+ ...tls,
+ maxCachedSessions,
+ allowH2,
+ socketPath,
+ timeout: connectTimeout,
+ ...typeof autoSelectFamily === "boolean" ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : void 0,
+ ...connect
+ });
+ }
+ super();
+ this[kConnections] = connections || null;
+ this[kUrl] = util.parseOrigin(origin);
+ this[kOptions] = { ...util.deepClone(options2), connect, allowH2, clientTtl, socketPath };
+ this[kOptions].interceptors = options2.interceptors ? { ...options2.interceptors } : void 0;
+ this[kFactory] = factory;
+ this[kIndex] = -1;
+ this.on("connect", (origin2, targets) => {
+ if (clientTtl != null && clientTtl > 0) {
+ for (const target of targets) {
+ Object.assign(target, { ttl: Date.now() });
+ }
+ }
+ });
+ this.on("connectionError", (origin2, targets, error51) => {
+ for (const target of targets) {
+ const idx = this[kClients].indexOf(target);
+ if (idx !== -1) {
+ this[kClients].splice(idx, 1);
+ }
+ }
+ });
+ }
+ [kGetDispatcher]() {
+ const clientTtlOption = this[kOptions].clientTtl;
+ const clientsLength = this[kClients].length;
+ if (clientsLength === 0) {
+ const dispatcher = this[kFactory](this[kUrl], this[kOptions]);
+ this[kAddClient](dispatcher);
+ return dispatcher;
+ }
+ let checked = 0;
+ while (checked < clientsLength) {
+ this[kIndex] = (this[kIndex] + 1) % clientsLength;
+ const client = this[kClients][this[kIndex]];
+ if (clientTtlOption != null && clientTtlOption > 0 && client.ttl && Date.now() - client.ttl > clientTtlOption) {
+ this[kRemoveClient](client);
+ checked++;
+ continue;
+ }
+ if (!client[kNeedDrain]) {
+ return client;
+ }
+ checked++;
+ }
+ if (!this[kConnections] || clientsLength < this[kConnections]) {
+ const dispatcher = this[kFactory](this[kUrl], this[kOptions]);
+ this[kAddClient](dispatcher);
+ return dispatcher;
+ }
+ }
+ };
+ module2.exports = RoundRobinPool;
+ }
+});
+
+// node_modules/undici/lib/dispatcher/agent.js
+var require_agent = __commonJS({
+ "node_modules/undici/lib/dispatcher/agent.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { InvalidArgumentError, MaxOriginsReachedError } = require_errors();
+ var { kClients, kRunning, kClose, kDestroy, kDispatch, kUrl } = require_symbols();
+ var DispatcherBase = require_dispatcher_base();
+ var Pool = require_pool();
+ var Client = require_client();
+ var util = require_util();
+ var kOnConnect = /* @__PURE__ */ Symbol("onConnect");
+ var kOnDisconnect = /* @__PURE__ */ Symbol("onDisconnect");
+ var kOnConnectionError = /* @__PURE__ */ Symbol("onConnectionError");
+ var kOnDrain = /* @__PURE__ */ Symbol("onDrain");
+ var kFactory = /* @__PURE__ */ Symbol("factory");
+ var kOptions = /* @__PURE__ */ Symbol("options");
+ var kOrigins = /* @__PURE__ */ Symbol("origins");
+ function defaultFactory(origin, opts) {
+ return opts && opts.connections === 1 ? new Client(origin, opts) : new Pool(origin, opts);
+ }
+ __name(defaultFactory, "defaultFactory");
+ var Agent2 = class extends DispatcherBase {
+ static {
+ __name(this, "Agent");
+ }
+ constructor({ factory = defaultFactory, maxOrigins = Infinity, connect, ...options2 } = {}) {
+ if (typeof factory !== "function") {
+ throw new InvalidArgumentError("factory must be a function.");
+ }
+ if (connect != null && typeof connect !== "function" && typeof connect !== "object") {
+ throw new InvalidArgumentError("connect must be a function or an object");
+ }
+ if (typeof maxOrigins !== "number" || Number.isNaN(maxOrigins) || maxOrigins <= 0) {
+ throw new InvalidArgumentError("maxOrigins must be a number greater than 0");
+ }
+ super(options2);
+ if (connect && typeof connect !== "function") {
+ connect = { ...connect };
+ }
+ this[kOptions] = { ...util.deepClone(options2), maxOrigins, connect };
+ this[kFactory] = factory;
+ this[kClients] = /* @__PURE__ */ new Map();
+ this[kOrigins] = /* @__PURE__ */ new Set();
+ this[kOnDrain] = (origin, targets) => {
+ this.emit("drain", origin, [this, ...targets]);
+ };
+ this[kOnConnect] = (origin, targets) => {
+ this.emit("connect", origin, [this, ...targets]);
+ };
+ this[kOnDisconnect] = (origin, targets, err) => {
+ this.emit("disconnect", origin, [this, ...targets], err);
+ };
+ this[kOnConnectionError] = (origin, targets, err) => {
+ this.emit("connectionError", origin, [this, ...targets], err);
+ };
+ }
+ get [kRunning]() {
+ let ret = 0;
+ for (const { dispatcher } of this[kClients].values()) {
+ ret += dispatcher[kRunning];
+ }
+ return ret;
+ }
+ [kDispatch](opts, handler) {
+ let key;
+ if (opts.origin && (typeof opts.origin === "string" || opts.origin instanceof URL)) {
+ key = String(opts.origin);
+ } else {
+ throw new InvalidArgumentError("opts.origin must be a non-empty string or URL.");
+ }
+ if (this[kOrigins].size >= this[kOptions].maxOrigins && !this[kOrigins].has(key)) {
+ throw new MaxOriginsReachedError();
+ }
+ const result = this[kClients].get(key);
+ let dispatcher = result && result.dispatcher;
+ if (!dispatcher) {
+ const closeClientIfUnused = /* @__PURE__ */ __name((connected) => {
+ const result2 = this[kClients].get(key);
+ if (result2) {
+ if (connected) result2.count -= 1;
+ if (result2.count <= 0) {
+ this[kClients].delete(key);
+ if (!result2.dispatcher.destroyed) {
+ result2.dispatcher.close();
+ }
+ }
+ this[kOrigins].delete(key);
+ }
+ }, "closeClientIfUnused");
+ dispatcher = this[kFactory](opts.origin, this[kOptions]).on("drain", this[kOnDrain]).on("connect", (origin, targets) => {
+ const result2 = this[kClients].get(key);
+ if (result2) {
+ result2.count += 1;
+ }
+ this[kOnConnect](origin, targets);
+ }).on("disconnect", (origin, targets, err) => {
+ closeClientIfUnused(true);
+ this[kOnDisconnect](origin, targets, err);
+ }).on("connectionError", (origin, targets, err) => {
+ closeClientIfUnused(false);
+ this[kOnConnectionError](origin, targets, err);
+ });
+ this[kClients].set(key, { count: 0, dispatcher });
+ this[kOrigins].add(key);
+ }
+ return dispatcher.dispatch(opts, handler);
+ }
+ [kClose]() {
+ const closePromises = [];
+ for (const { dispatcher } of this[kClients].values()) {
+ closePromises.push(dispatcher.close());
+ }
+ this[kClients].clear();
+ return Promise.all(closePromises);
+ }
+ [kDestroy](err) {
+ const destroyPromises = [];
+ for (const { dispatcher } of this[kClients].values()) {
+ destroyPromises.push(dispatcher.destroy(err));
+ }
+ this[kClients].clear();
+ return Promise.all(destroyPromises);
+ }
+ get stats() {
+ const allClientStats = {};
+ for (const { dispatcher } of this[kClients].values()) {
+ if (dispatcher.stats) {
+ allClientStats[dispatcher[kUrl].origin] = dispatcher.stats;
+ }
+ }
+ return allClientStats;
+ }
+ };
+ module2.exports = Agent2;
+ }
+});
+
+// node_modules/undici/lib/core/socks5-utils.js
+var require_socks5_utils = __commonJS({
+ "node_modules/undici/lib/core/socks5-utils.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { Buffer: Buffer2 } = __require("node:buffer");
+ var net = __require("node:net");
+ var { InvalidArgumentError } = require_errors();
+ function parseAddress(address) {
+ if (net.isIPv4(address)) {
+ const parts = address.split(".").map(Number);
+ return {
+ type: 1,
+ // IPv4
+ buffer: Buffer2.from(parts)
+ };
+ }
+ if (net.isIPv6(address)) {
+ return {
+ type: 4,
+ // IPv6
+ buffer: parseIPv6(address)
+ };
+ }
+ const domainBuffer = Buffer2.from(address, "utf8");
+ if (domainBuffer.length > 255) {
+ throw new InvalidArgumentError("Domain name too long (max 255 bytes)");
+ }
+ return {
+ type: 3,
+ // Domain
+ buffer: Buffer2.concat([Buffer2.from([domainBuffer.length]), domainBuffer])
+ };
+ }
+ __name(parseAddress, "parseAddress");
+ function parseIPv6(address) {
+ const buffer = Buffer2.alloc(16);
+ let normalizedAddress = address;
+ if (address.includes(".")) {
+ const lastColonIndex = address.lastIndexOf(":");
+ const ipv4Part = address.slice(lastColonIndex + 1);
+ if (net.isIPv4(ipv4Part)) {
+ const octets = ipv4Part.split(".").map(Number);
+ const high = (octets[0] << 8 | octets[1]).toString(16);
+ const low = (octets[2] << 8 | octets[3]).toString(16);
+ normalizedAddress = `${address.slice(0, lastColonIndex)}:${high}:${low}`;
+ }
+ }
+ const doubleColonIndex = normalizedAddress.indexOf("::");
+ if (doubleColonIndex !== -1) {
+ const before = normalizedAddress.slice(0, doubleColonIndex);
+ const after = normalizedAddress.slice(doubleColonIndex + 2);
+ const beforeParts = before === "" ? [] : before.split(":");
+ const afterParts = after === "" ? [] : after.split(":");
+ let bufferIndex = 0;
+ for (const part of beforeParts) {
+ buffer.writeUInt16BE(parseInt(part, 16), bufferIndex);
+ bufferIndex += 2;
+ }
+ bufferIndex = 16 - afterParts.length * 2;
+ for (const part of afterParts) {
+ buffer.writeUInt16BE(parseInt(part, 16), bufferIndex);
+ bufferIndex += 2;
+ }
+ } else {
+ const parts = normalizedAddress.split(":");
+ for (let i = 0; i < parts.length; i++) {
+ buffer.writeUInt16BE(parseInt(parts[i], 16), i * 2);
+ }
+ }
+ return buffer;
+ }
+ __name(parseIPv6, "parseIPv6");
+ function buildAddressBuffer(type2, addressBuffer, port) {
+ const portBuffer = Buffer2.allocUnsafe(2);
+ portBuffer.writeUInt16BE(port, 0);
+ return Buffer2.concat([
+ Buffer2.from([type2]),
+ addressBuffer,
+ portBuffer
+ ]);
+ }
+ __name(buildAddressBuffer, "buildAddressBuffer");
+ function parseResponseAddress(buffer, offset = 0) {
+ if (buffer.length < offset + 1) {
+ throw new InvalidArgumentError("Buffer too small to contain address type");
+ }
+ const addressType = buffer[offset];
+ let address;
+ let currentOffset = offset + 1;
+ switch (addressType) {
+ case 1: {
+ if (buffer.length < currentOffset + 6) {
+ throw new InvalidArgumentError("Buffer too small for IPv4 address");
+ }
+ address = Array.from(buffer.subarray(currentOffset, currentOffset + 4)).join(".");
+ currentOffset += 4;
+ break;
+ }
+ case 3: {
+ if (buffer.length < currentOffset + 1) {
+ throw new InvalidArgumentError("Buffer too small for domain length");
+ }
+ const domainLength = buffer[currentOffset];
+ currentOffset += 1;
+ if (buffer.length < currentOffset + domainLength + 2) {
+ throw new InvalidArgumentError("Buffer too small for domain address");
+ }
+ address = buffer.subarray(currentOffset, currentOffset + domainLength).toString("utf8");
+ currentOffset += domainLength;
+ break;
+ }
+ case 4: {
+ if (buffer.length < currentOffset + 18) {
+ throw new InvalidArgumentError("Buffer too small for IPv6 address");
+ }
+ const parts = [];
+ for (let i = 0; i < 8; i++) {
+ const value = buffer.readUInt16BE(currentOffset + i * 2);
+ parts.push(value.toString(16));
+ }
+ address = parts.join(":");
+ currentOffset += 16;
+ break;
+ }
+ default:
+ throw new InvalidArgumentError(`Invalid address type: ${addressType}`);
+ }
+ if (buffer.length < currentOffset + 2) {
+ throw new InvalidArgumentError("Buffer too small for port");
+ }
+ const port = buffer.readUInt16BE(currentOffset);
+ currentOffset += 2;
+ return {
+ address,
+ port,
+ bytesRead: currentOffset - offset
+ };
+ }
+ __name(parseResponseAddress, "parseResponseAddress");
+ function createReplyError(replyCode) {
+ const messages = {
+ 1: "General SOCKS server failure",
+ 2: "Connection not allowed by ruleset",
+ 3: "Network unreachable",
+ 4: "Host unreachable",
+ 5: "Connection refused",
+ 6: "TTL expired",
+ 7: "Command not supported",
+ 8: "Address type not supported"
+ };
+ const message = messages[replyCode] || `Unknown SOCKS5 error code: ${replyCode}`;
+ const error51 = new Error(message);
+ error51.code = `SOCKS5_${replyCode}`;
+ return error51;
+ }
+ __name(createReplyError, "createReplyError");
+ module2.exports = {
+ parseAddress,
+ parseIPv6,
+ buildAddressBuffer,
+ parseResponseAddress,
+ createReplyError
+ };
+ }
+});
+
+// node_modules/undici/lib/core/socks5-client.js
+var require_socks5_client = __commonJS({
+ "node_modules/undici/lib/core/socks5-client.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { EventEmitter: EventEmitter3 } = __require("node:events");
+ var { Buffer: Buffer2 } = __require("node:buffer");
+ var { InvalidArgumentError, Socks5ProxyError } = require_errors();
+ var { debuglog } = __require("node:util");
+ var { parseAddress } = require_socks5_utils();
+ var debug = debuglog("undici:socks5");
+ var EMPTY_BUFFER2 = Buffer2.alloc(0);
+ var SOCKS_VERSION = 5;
+ var AUTH_METHODS = {
+ NO_AUTH: 0,
+ GSSAPI: 1,
+ USERNAME_PASSWORD: 2,
+ NO_ACCEPTABLE: 255
+ };
+ var COMMANDS = {
+ CONNECT: 1,
+ BIND: 2,
+ UDP_ASSOCIATE: 3
+ };
+ var ADDRESS_TYPES = {
+ IPV4: 1,
+ DOMAIN: 3,
+ IPV6: 4
+ };
+ var REPLY_CODES = {
+ SUCCEEDED: 0,
+ GENERAL_FAILURE: 1,
+ CONNECTION_NOT_ALLOWED: 2,
+ NETWORK_UNREACHABLE: 3,
+ HOST_UNREACHABLE: 4,
+ CONNECTION_REFUSED: 5,
+ TTL_EXPIRED: 6,
+ COMMAND_NOT_SUPPORTED: 7,
+ ADDRESS_TYPE_NOT_SUPPORTED: 8
+ };
+ var STATES = {
+ INITIAL: "initial",
+ HANDSHAKING: "handshaking",
+ AUTHENTICATING: "authenticating",
+ AUTHENTICATED: "authenticated",
+ CONNECTING: "connecting",
+ CONNECTED: "connected",
+ ERROR: "error",
+ CLOSED: "closed"
+ };
+ var Socks5Client = class extends EventEmitter3 {
+ static {
+ __name(this, "Socks5Client");
+ }
+ constructor(socket, options2 = {}) {
+ super();
+ if (!socket) {
+ throw new InvalidArgumentError("socket is required");
+ }
+ this.socket = socket;
+ this.options = options2;
+ this.state = STATES.INITIAL;
+ this.buffer = EMPTY_BUFFER2;
+ this.onSocketData = this.onData.bind(this);
+ this.onSocketError = this.onError.bind(this);
+ this.onSocketClose = this.onClose.bind(this);
+ this.authMethods = [];
+ if (options2.username && options2.password) {
+ this.authMethods.push(AUTH_METHODS.USERNAME_PASSWORD);
+ }
+ this.authMethods.push(AUTH_METHODS.NO_AUTH);
+ this.socket.on("data", this.onSocketData);
+ this.socket.on("error", this.onSocketError);
+ this.socket.on("close", this.onSocketClose);
+ }
+ /**
+ * Handle incoming data from the socket
+ */
+ onData(data) {
+ debug("received data", data.length, "bytes in state", this.state);
+ this.buffer = Buffer2.concat([this.buffer, data]);
+ try {
+ switch (this.state) {
+ case STATES.HANDSHAKING:
+ this.handleHandshakeResponse();
+ break;
+ case STATES.AUTHENTICATING:
+ this.handleAuthResponse();
+ break;
+ case STATES.CONNECTING:
+ this.handleConnectResponse();
+ break;
+ }
+ } catch (err) {
+ this.onError(err);
+ }
+ }
+ /**
+ * Handle socket errors
+ */
+ onError(err) {
+ debug("socket error", err);
+ this.state = STATES.ERROR;
+ this.emit("error", err);
+ this.destroy();
+ }
+ /**
+ * Handle socket close
+ */
+ onClose() {
+ debug("socket closed");
+ this.state = STATES.CLOSED;
+ this.emit("close");
+ }
+ /**
+ * Destroy the client and underlying socket
+ */
+ destroy() {
+ if (this.socket && !this.socket.destroyed) {
+ this.socket.destroy();
+ }
+ }
+ markAuthenticated() {
+ this.state = STATES.AUTHENTICATED;
+ this.emit("authenticated");
+ }
+ /**
+ * Start the SOCKS5 handshake
+ */
+ handshake() {
+ if (this.state !== STATES.INITIAL) {
+ throw new InvalidArgumentError("Handshake already started");
+ }
+ debug("starting handshake with", this.authMethods.length, "auth methods");
+ this.state = STATES.HANDSHAKING;
+ const request = Buffer2.alloc(2 + this.authMethods.length);
+ request[0] = SOCKS_VERSION;
+ request[1] = this.authMethods.length;
+ this.authMethods.forEach((method, i) => {
+ request[2 + i] = method;
+ });
+ this.socket.write(request);
+ }
+ /**
+ * Handle handshake response from server
+ */
+ handleHandshakeResponse() {
+ if (this.buffer.length < 2) {
+ return;
+ }
+ const version2 = this.buffer[0];
+ const method = this.buffer[1];
+ if (version2 !== SOCKS_VERSION) {
+ throw new Socks5ProxyError(`Invalid SOCKS version: ${version2}`, "UND_ERR_SOCKS5_VERSION");
+ }
+ if (method === AUTH_METHODS.NO_ACCEPTABLE) {
+ throw new Socks5ProxyError("No acceptable authentication method", "UND_ERR_SOCKS5_AUTH_REJECTED");
+ }
+ this.buffer = this.buffer.subarray(2);
+ debug("server selected auth method", method);
+ if (method === AUTH_METHODS.NO_AUTH) {
+ this.markAuthenticated();
+ } else if (method === AUTH_METHODS.USERNAME_PASSWORD) {
+ this.state = STATES.AUTHENTICATING;
+ this.sendAuthRequest();
+ } else {
+ throw new Socks5ProxyError(`Unsupported authentication method: ${method}`, "UND_ERR_SOCKS5_AUTH_METHOD");
+ }
+ }
+ /**
+ * Send username/password authentication request
+ */
+ sendAuthRequest() {
+ const { username, password } = this.options;
+ if (!username || !password) {
+ throw new InvalidArgumentError("Username and password required for authentication");
+ }
+ debug("sending username/password auth");
+ const usernameBuffer = Buffer2.from(username);
+ const passwordBuffer = Buffer2.from(password);
+ if (usernameBuffer.length > 255 || passwordBuffer.length > 255) {
+ throw new InvalidArgumentError("Username or password too long");
+ }
+ const request = Buffer2.alloc(3 + usernameBuffer.length + passwordBuffer.length);
+ request[0] = 1;
+ request[1] = usernameBuffer.length;
+ usernameBuffer.copy(request, 2);
+ request[2 + usernameBuffer.length] = passwordBuffer.length;
+ passwordBuffer.copy(request, 3 + usernameBuffer.length);
+ this.socket.write(request);
+ }
+ /**
+ * Handle authentication response
+ */
+ handleAuthResponse() {
+ if (this.buffer.length < 2) {
+ return;
+ }
+ const version2 = this.buffer[0];
+ const status = this.buffer[1];
+ if (version2 !== 1) {
+ throw new Socks5ProxyError(`Invalid auth sub-negotiation version: ${version2}`, "UND_ERR_SOCKS5_AUTH_VERSION");
+ }
+ if (status !== 0) {
+ throw new Socks5ProxyError("Authentication failed", "UND_ERR_SOCKS5_AUTH_FAILED");
+ }
+ this.buffer = this.buffer.subarray(2);
+ debug("authentication successful");
+ this.markAuthenticated();
+ }
+ /**
+ * Send CONNECT command
+ * @param {string} address - Target address (IP or domain)
+ * @param {number} port - Target port
+ */
+ connect(address, port) {
+ if (this.state === STATES.CONNECTING || this.state === STATES.CONNECTED) {
+ throw new InvalidArgumentError("Connection already in progress");
+ }
+ if (this.state !== STATES.AUTHENTICATED) {
+ throw new InvalidArgumentError("Client must be authenticated before CONNECT");
+ }
+ debug("connecting to", address, port);
+ this.state = STATES.CONNECTING;
+ const request = this.buildConnectRequest(COMMANDS.CONNECT, address, port);
+ this.socket.write(request);
+ }
+ /**
+ * Build a SOCKS5 request
+ */
+ buildConnectRequest(command2, address, port) {
+ const { type: addressType, buffer: addressBuffer } = parseAddress(address);
+ const request = Buffer2.alloc(4 + addressBuffer.length + 2);
+ request[0] = SOCKS_VERSION;
+ request[1] = command2;
+ request[2] = 0;
+ request[3] = addressType;
+ addressBuffer.copy(request, 4);
+ request.writeUInt16BE(port, 4 + addressBuffer.length);
+ return request;
+ }
+ /**
+ * Handle CONNECT response
+ */
+ handleConnectResponse() {
+ if (this.buffer.length < 4) {
+ return;
+ }
+ const version2 = this.buffer[0];
+ const reply = this.buffer[1];
+ const addressType = this.buffer[3];
+ if (version2 !== SOCKS_VERSION) {
+ throw new Socks5ProxyError(`Invalid SOCKS version in reply: ${version2}`, "UND_ERR_SOCKS5_REPLY_VERSION");
+ }
+ let responseLength = 4;
+ if (addressType === ADDRESS_TYPES.IPV4) {
+ responseLength += 4 + 2;
+ } else if (addressType === ADDRESS_TYPES.DOMAIN) {
+ if (this.buffer.length < 5) {
+ return;
+ }
+ responseLength += 1 + this.buffer[4] + 2;
+ } else if (addressType === ADDRESS_TYPES.IPV6) {
+ responseLength += 16 + 2;
+ } else {
+ throw new Socks5ProxyError(`Invalid address type in reply: ${addressType}`, "UND_ERR_SOCKS5_ADDR_TYPE");
+ }
+ if (this.buffer.length < responseLength) {
+ return;
+ }
+ if (reply !== REPLY_CODES.SUCCEEDED) {
+ const errorMessage = this.getReplyErrorMessage(reply);
+ throw new Socks5ProxyError(`SOCKS5 connection failed: ${errorMessage}`, `UND_ERR_SOCKS5_REPLY_${reply}`);
+ }
+ let boundAddress;
+ let offset = 4;
+ if (addressType === ADDRESS_TYPES.IPV4) {
+ boundAddress = Array.from(this.buffer.subarray(offset, offset + 4)).join(".");
+ offset += 4;
+ } else if (addressType === ADDRESS_TYPES.DOMAIN) {
+ const domainLength = this.buffer[offset];
+ offset += 1;
+ boundAddress = this.buffer.subarray(offset, offset + domainLength).toString();
+ offset += domainLength;
+ } else if (addressType === ADDRESS_TYPES.IPV6) {
+ const parts = [];
+ for (let i = 0; i < 8; i++) {
+ const value = this.buffer.readUInt16BE(offset + i * 2);
+ parts.push(value.toString(16));
+ }
+ boundAddress = parts.join(":");
+ offset += 16;
+ }
+ const boundPort = this.buffer.readUInt16BE(offset);
+ this.buffer = EMPTY_BUFFER2;
+ this.state = STATES.CONNECTED;
+ this.socket.removeListener("data", this.onSocketData);
+ debug("connected, bound address:", boundAddress, "port:", boundPort);
+ this.emit("connected", { address: boundAddress, port: boundPort });
+ }
+ /**
+ * Get human-readable error message for reply code
+ */
+ getReplyErrorMessage(reply) {
+ switch (reply) {
+ case REPLY_CODES.GENERAL_FAILURE:
+ return "General SOCKS server failure";
+ case REPLY_CODES.CONNECTION_NOT_ALLOWED:
+ return "Connection not allowed by ruleset";
+ case REPLY_CODES.NETWORK_UNREACHABLE:
+ return "Network unreachable";
+ case REPLY_CODES.HOST_UNREACHABLE:
+ return "Host unreachable";
+ case REPLY_CODES.CONNECTION_REFUSED:
+ return "Connection refused";
+ case REPLY_CODES.TTL_EXPIRED:
+ return "TTL expired";
+ case REPLY_CODES.COMMAND_NOT_SUPPORTED:
+ return "Command not supported";
+ case REPLY_CODES.ADDRESS_TYPE_NOT_SUPPORTED:
+ return "Address type not supported";
+ default:
+ return `Unknown error code: ${reply}`;
+ }
+ }
+ };
+ module2.exports = {
+ Socks5Client,
+ AUTH_METHODS,
+ COMMANDS,
+ ADDRESS_TYPES,
+ REPLY_CODES,
+ STATES
+ };
+ }
+});
+
+// node_modules/undici/lib/dispatcher/socks5-proxy-agent.js
+var require_socks5_proxy_agent = __commonJS({
+ "node_modules/undici/lib/dispatcher/socks5-proxy-agent.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { URL: URL2 } = __require("node:url");
+ var tls;
+ var DispatcherBase = require_dispatcher_base();
+ var { InvalidArgumentError } = require_errors();
+ var { Socks5Client, STATES } = require_socks5_client();
+ var { kDispatch, kClose, kDestroy } = require_symbols();
+ var Pool = require_pool();
+ var buildConnector = require_connect();
+ var { debuglog } = __require("node:util");
+ var debug = debuglog("undici:socks5-proxy");
+ var kProxyUrl = /* @__PURE__ */ Symbol("proxy url");
+ var kProxyHeaders = /* @__PURE__ */ Symbol("proxy headers");
+ var kProxyAuth = /* @__PURE__ */ Symbol("proxy auth");
+ var kProxyProtocol = /* @__PURE__ */ Symbol("proxy protocol");
+ var kPools = /* @__PURE__ */ Symbol("pools");
+ var kConnector = /* @__PURE__ */ Symbol("connector");
+ var kRequestTls = /* @__PURE__ */ Symbol("request tls settings");
+ var experimentalWarningEmitted = false;
+ var Socks5ProxyAgent = class extends DispatcherBase {
+ static {
+ __name(this, "Socks5ProxyAgent");
+ }
+ constructor(proxyUrl, options2 = {}) {
+ super();
+ if (!experimentalWarningEmitted) {
+ process.emitWarning(
+ "SOCKS5 proxy support is experimental and subject to change",
+ "ExperimentalWarning"
+ );
+ experimentalWarningEmitted = true;
+ }
+ if (!proxyUrl) {
+ throw new InvalidArgumentError("Proxy URL is mandatory");
+ }
+ const url2 = typeof proxyUrl === "string" ? new URL2(proxyUrl) : proxyUrl;
+ if (url2.protocol !== "socks5:" && url2.protocol !== "socks:") {
+ throw new InvalidArgumentError("Proxy URL must use socks5:// or socks:// protocol");
+ }
+ this[kProxyUrl] = url2;
+ this[kProxyHeaders] = options2.headers || {};
+ this[kProxyProtocol] = options2.proxyTls ? "https:" : "http:";
+ this[kRequestTls] = options2.requestTls;
+ this[kProxyAuth] = {
+ username: options2.username || (url2.username ? decodeURIComponent(url2.username) : null),
+ password: options2.password || (url2.password ? decodeURIComponent(url2.password) : null)
+ };
+ this[kConnector] = options2.connect || buildConnector({
+ ...options2.proxyTls,
+ servername: options2.proxyTls?.servername || url2.hostname
+ });
+ this[kPools] = /* @__PURE__ */ new Map();
+ }
+ /**
+ * Create a SOCKS5 connection to the proxy
+ */
+ async createSocks5Connection(targetHost, targetPort) {
+ const proxyHost = this[kProxyUrl].hostname;
+ const proxyPort = parseInt(this[kProxyUrl].port) || 1080;
+ debug("creating SOCKS5 connection to", proxyHost, proxyPort);
+ const socket = await new Promise((resolve16, reject) => {
+ this[kConnector]({
+ hostname: proxyHost,
+ host: proxyHost,
+ port: proxyPort,
+ protocol: this[kProxyProtocol]
+ }, (err, socket2) => {
+ if (err) {
+ reject(err);
+ } else {
+ resolve16(socket2);
+ }
+ });
+ });
+ const socks5Client = new Socks5Client(socket, this[kProxyAuth]);
+ socks5Client.on("error", (err) => {
+ debug("SOCKS5 error:", err);
+ socket.destroy();
+ });
+ await socks5Client.handshake();
+ await new Promise((resolve16, reject) => {
+ const timeout = setTimeout(() => {
+ reject(new Error("SOCKS5 authentication timeout"));
+ }, 5e3);
+ const onAuthenticated = /* @__PURE__ */ __name(() => {
+ clearTimeout(timeout);
+ socks5Client.removeListener("error", onError);
+ resolve16();
+ }, "onAuthenticated");
+ const onError = /* @__PURE__ */ __name((err) => {
+ clearTimeout(timeout);
+ socks5Client.removeListener("authenticated", onAuthenticated);
+ reject(err);
+ }, "onError");
+ if (socks5Client.state === STATES.AUTHENTICATED) {
+ clearTimeout(timeout);
+ resolve16();
+ } else {
+ socks5Client.once("authenticated", onAuthenticated);
+ socks5Client.once("error", onError);
+ }
+ });
+ await socks5Client.connect(targetHost, targetPort);
+ await new Promise((resolve16, reject) => {
+ const timeout = setTimeout(() => {
+ reject(new Error("SOCKS5 connection timeout"));
+ }, 5e3);
+ const onConnected = /* @__PURE__ */ __name((info) => {
+ debug("SOCKS5 tunnel established to", targetHost, targetPort, "via", info);
+ clearTimeout(timeout);
+ socks5Client.removeListener("error", onError);
+ resolve16();
+ }, "onConnected");
+ const onError = /* @__PURE__ */ __name((err) => {
+ clearTimeout(timeout);
+ socks5Client.removeListener("connected", onConnected);
+ reject(err);
+ }, "onError");
+ socks5Client.once("connected", onConnected);
+ socks5Client.once("error", onError);
+ });
+ return socket;
+ }
+ /**
+ * Dispatch a request through the SOCKS5 proxy
+ */
+ [kDispatch](opts, handler) {
+ const { origin } = opts;
+ debug("dispatching request to", origin, "via SOCKS5");
+ try {
+ const originKey = String(origin);
+ let pool = this[kPools].get(originKey);
+ if (!pool || pool.destroyed || pool.closed) {
+ pool = new Pool(origin, {
+ pipelining: opts.pipelining,
+ connections: opts.connections,
+ connect: /* @__PURE__ */ __name(async (connectOpts, callback) => {
+ try {
+ const url2 = new URL2(origin);
+ const targetHost = url2.hostname;
+ const targetPort = parseInt(url2.port) || (url2.protocol === "https:" ? 443 : 80);
+ debug("establishing SOCKS5 connection to", targetHost, targetPort);
+ const socket = await this.createSocks5Connection(targetHost, targetPort);
+ let finalSocket = socket;
+ if (url2.protocol === "https:") {
+ if (!tls) {
+ tls = __require("node:tls");
+ }
+ debug("upgrading to TLS");
+ finalSocket = tls.connect({
+ ...this[kRequestTls],
+ socket,
+ servername: this[kRequestTls]?.servername || targetHost
+ });
+ await new Promise((resolve16, reject) => {
+ finalSocket.once("secureConnect", resolve16);
+ finalSocket.once("error", reject);
+ });
+ }
+ callback(null, finalSocket);
+ } catch (err) {
+ debug("SOCKS5 connection error:", err);
+ callback(err);
+ }
+ }, "connect")
+ });
+ this[kPools].set(originKey, pool);
+ }
+ return pool[kDispatch](opts, handler);
+ } catch (err) {
+ debug("dispatch error:", err);
+ if (typeof handler.onResponseError === "function") {
+ handler.onResponseError(null, err);
+ return false;
+ } else if (typeof handler.onError === "function") {
+ handler.onError(err);
+ return false;
+ } else {
+ throw err;
+ }
+ }
+ }
+ async [kClose]() {
+ const closePromises = [];
+ for (const pool of this[kPools].values()) {
+ closePromises.push(pool.close());
+ }
+ this[kPools].clear();
+ await Promise.all(closePromises);
+ }
+ async [kDestroy](err) {
+ const destroyPromises = [];
+ for (const pool of this[kPools].values()) {
+ destroyPromises.push(pool.destroy(err));
+ }
+ this[kPools].clear();
+ await Promise.all(destroyPromises);
+ }
+ };
+ module2.exports = Socks5ProxyAgent;
+ }
+});
+
+// node_modules/undici/lib/dispatcher/proxy-agent.js
+var require_proxy_agent = __commonJS({
+ "node_modules/undici/lib/dispatcher/proxy-agent.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { kProxy, kClose, kDestroy, kDispatch } = require_symbols();
+ var Agent2 = require_agent();
+ var Pool = require_pool();
+ var DispatcherBase = require_dispatcher_base();
+ var { InvalidArgumentError, RequestAbortedError, SecureProxyConnectionError } = require_errors();
+ var buildConnector = require_connect();
+ var Client = require_client();
+ var { channels } = require_diagnostics();
+ var Socks5ProxyAgent = require_socks5_proxy_agent();
+ var kAgent = /* @__PURE__ */ Symbol("proxy agent");
+ var kClient = /* @__PURE__ */ Symbol("proxy client");
+ var kProxyHeaders = /* @__PURE__ */ Symbol("proxy headers");
+ var kRequestTls = /* @__PURE__ */ Symbol("request tls settings");
+ var kProxyTls = /* @__PURE__ */ Symbol("proxy tls settings");
+ var kConnectEndpoint = /* @__PURE__ */ Symbol("connect endpoint function");
+ var kTunnelProxy = /* @__PURE__ */ Symbol("tunnel proxy");
+ function defaultProtocolPort(protocol) {
+ return protocol === "https:" ? 443 : 80;
+ }
+ __name(defaultProtocolPort, "defaultProtocolPort");
+ function defaultFactory(origin, opts) {
+ return new Pool(origin, opts);
+ }
+ __name(defaultFactory, "defaultFactory");
+ var noop3 = /* @__PURE__ */ __name(() => {
+ }, "noop");
+ function defaultAgentFactory(origin, opts) {
+ if (opts.connections === 1) {
+ return new Client(origin, opts);
+ }
+ return new Pool(origin, opts);
+ }
+ __name(defaultAgentFactory, "defaultAgentFactory");
+ var Http1ProxyWrapper = class extends DispatcherBase {
+ static {
+ __name(this, "Http1ProxyWrapper");
+ }
+ #client;
+ constructor(proxyUrl, { headers = {}, connect, factory }) {
+ if (!proxyUrl) {
+ throw new InvalidArgumentError("Proxy URL is mandatory");
+ }
+ super();
+ this[kProxyHeaders] = headers;
+ if (factory) {
+ this.#client = factory(proxyUrl, { connect });
+ } else {
+ this.#client = new Client(proxyUrl, { connect });
+ }
+ }
+ [kDispatch](opts, handler) {
+ const onHeaders = handler.onHeaders;
+ handler.onHeaders = function(statusCode, data, resume) {
+ if (statusCode === 407) {
+ if (typeof handler.onError === "function") {
+ handler.onError(new InvalidArgumentError("Proxy Authentication Required (407)"));
+ }
+ return;
+ }
+ if (onHeaders) onHeaders.call(this, statusCode, data, resume);
+ };
+ const {
+ origin,
+ path: path27 = "/",
+ headers = {}
+ } = opts;
+ opts.path = origin + path27;
+ if (!("host" in headers) && !("Host" in headers)) {
+ const { host } = new URL(origin);
+ headers.host = host;
+ }
+ opts.headers = { ...this[kProxyHeaders], ...headers };
+ return this.#client[kDispatch](opts, handler);
+ }
+ [kClose]() {
+ return this.#client.close();
+ }
+ [kDestroy](err) {
+ return this.#client.destroy(err);
+ }
+ };
+ var ProxyAgent = class extends DispatcherBase {
+ static {
+ __name(this, "ProxyAgent");
+ }
+ constructor(opts) {
+ if (!opts || typeof opts === "object" && !(opts instanceof URL) && !opts.uri) {
+ throw new InvalidArgumentError("Proxy uri is mandatory");
+ }
+ const { clientFactory = defaultFactory } = opts;
+ if (typeof clientFactory !== "function") {
+ throw new InvalidArgumentError("Proxy opts.clientFactory must be a function.");
+ }
+ const { proxyTunnel = true } = opts;
+ super();
+ const url2 = this.#getUrl(opts);
+ const { href, origin, port, protocol, username, password, hostname: proxyHostname } = url2;
+ this[kProxy] = { uri: href, protocol };
+ this[kRequestTls] = opts.requestTls;
+ this[kProxyTls] = opts.proxyTls;
+ this[kProxyHeaders] = opts.headers || {};
+ this[kTunnelProxy] = proxyTunnel;
+ if (opts.auth && opts.token) {
+ throw new InvalidArgumentError("opts.auth cannot be used in combination with opts.token");
+ } else if (opts.auth) {
+ this[kProxyHeaders]["proxy-authorization"] = `Basic ${opts.auth}`;
+ } else if (opts.token) {
+ this[kProxyHeaders]["proxy-authorization"] = opts.token;
+ } else if (username && password) {
+ this[kProxyHeaders]["proxy-authorization"] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString("base64")}`;
+ }
+ const connect = buildConnector({ ...opts.proxyTls });
+ this[kConnectEndpoint] = buildConnector({ ...opts.requestTls });
+ const agentFactory = opts.factory || defaultAgentFactory;
+ const factory = /* @__PURE__ */ __name((origin2, options2) => {
+ const { protocol: protocol2 } = new URL(origin2);
+ if (this[kProxy].protocol === "socks5:" || this[kProxy].protocol === "socks:") {
+ return new Socks5ProxyAgent(this[kProxy].uri, {
+ headers: this[kProxyHeaders],
+ connect,
+ factory: agentFactory,
+ username: opts.username || username,
+ password: opts.password || password,
+ proxyTls: opts.proxyTls,
+ requestTls: opts.requestTls
+ });
+ }
+ if (!this[kTunnelProxy] && protocol2 === "http:" && this[kProxy].protocol === "http:") {
+ return new Http1ProxyWrapper(this[kProxy].uri, {
+ headers: this[kProxyHeaders],
+ connect,
+ factory: agentFactory
+ });
+ }
+ return agentFactory(origin2, options2);
+ }, "factory");
+ if (protocol === "socks5:" || protocol === "socks:") {
+ this[kClient] = null;
+ } else {
+ this[kClient] = clientFactory(url2, { connect });
+ }
+ this[kAgent] = new Agent2({
+ ...opts,
+ factory,
+ connect: /* @__PURE__ */ __name(async (opts2, callback) => {
+ if (!this[kClient]) {
+ callback(new InvalidArgumentError("Cannot establish tunnel connection without a proxy client"));
+ return;
+ }
+ let requestedPath = opts2.host;
+ if (!opts2.port) {
+ requestedPath += `:${defaultProtocolPort(opts2.protocol)}`;
+ }
+ try {
+ const connectParams = {
+ origin,
+ port,
+ path: requestedPath,
+ signal: opts2.signal,
+ headers: {
+ ...this[kProxyHeaders],
+ host: opts2.host,
+ ...opts2.connections == null || opts2.connections > 0 ? { "proxy-connection": "keep-alive" } : {}
+ },
+ servername: this[kProxyTls]?.servername || proxyHostname
+ };
+ const { socket, statusCode } = await this[kClient].connect(connectParams);
+ if (statusCode !== 200) {
+ socket.on("error", noop3).destroy();
+ callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`));
+ return;
+ }
+ if (channels.proxyConnected.hasSubscribers) {
+ channels.proxyConnected.publish({
+ socket,
+ connectParams
+ });
+ }
+ if (opts2.protocol !== "https:") {
+ callback(null, socket);
+ return;
+ }
+ let servername;
+ if (this[kRequestTls]) {
+ servername = this[kRequestTls].servername;
+ } else {
+ servername = opts2.servername;
+ }
+ this[kConnectEndpoint]({ ...opts2, servername, httpSocket: socket }, callback);
+ } catch (err) {
+ if (err.code === "ERR_TLS_CERT_ALTNAME_INVALID") {
+ callback(new SecureProxyConnectionError(err));
+ } else {
+ callback(err);
+ }
+ }
+ }, "connect")
+ });
+ }
+ dispatch(opts, handler) {
+ const headers = buildHeaders2(opts.headers);
+ throwIfProxyAuthIsSent(headers);
+ if (headers && !("host" in headers) && !("Host" in headers)) {
+ const { host } = new URL(opts.origin);
+ headers.host = host;
+ }
+ return this[kAgent].dispatch(
+ {
+ ...opts,
+ headers
+ },
+ handler
+ );
+ }
+ /**
+ * @param {import('../../types/proxy-agent').ProxyAgent.Options | string | URL} opts
+ * @returns {URL}
+ */
+ #getUrl(opts) {
+ if (typeof opts === "string") {
+ return new URL(opts);
+ } else if (opts instanceof URL) {
+ return opts;
+ } else {
+ return new URL(opts.uri);
+ }
+ }
+ [kClose]() {
+ const promises = [this[kAgent].close()];
+ if (this[kClient]) {
+ promises.push(this[kClient].close());
+ }
+ return Promise.all(promises);
+ }
+ [kDestroy]() {
+ const promises = [this[kAgent].destroy()];
+ if (this[kClient]) {
+ promises.push(this[kClient].destroy());
+ }
+ return Promise.all(promises);
+ }
+ };
+ function buildHeaders2(headers) {
+ if (Array.isArray(headers)) {
+ const headersPair = {};
+ for (let i = 0; i < headers.length; i += 2) {
+ headersPair[headers[i]] = headers[i + 1];
+ }
+ return headersPair;
+ }
+ return headers;
+ }
+ __name(buildHeaders2, "buildHeaders");
+ function throwIfProxyAuthIsSent(headers) {
+ const existProxyAuth = headers && Object.keys(headers).find((key) => key.toLowerCase() === "proxy-authorization");
+ if (existProxyAuth) {
+ throw new InvalidArgumentError("Proxy-Authorization should be sent in ProxyAgent constructor");
+ }
+ }
+ __name(throwIfProxyAuthIsSent, "throwIfProxyAuthIsSent");
+ module2.exports = ProxyAgent;
+ }
+});
+
+// node_modules/undici/lib/dispatcher/env-http-proxy-agent.js
+var require_env_http_proxy_agent = __commonJS({
+ "node_modules/undici/lib/dispatcher/env-http-proxy-agent.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var DispatcherBase = require_dispatcher_base();
+ var { kClose, kDestroy, kClosed, kDestroyed, kDispatch, kNoProxyAgent, kHttpProxyAgent, kHttpsProxyAgent } = require_symbols();
+ var ProxyAgent = require_proxy_agent();
+ var Agent2 = require_agent();
+ var DEFAULT_PORTS = {
+ "http:": 80,
+ "https:": 443
+ };
+ var EnvHttpProxyAgent = class extends DispatcherBase {
+ static {
+ __name(this, "EnvHttpProxyAgent");
+ }
+ #noProxyValue = null;
+ #noProxyEntries = null;
+ #opts = null;
+ constructor(opts = {}) {
+ super();
+ this.#opts = opts;
+ const { httpProxy, httpsProxy, noProxy, ...agentOpts } = opts;
+ this[kNoProxyAgent] = new Agent2(agentOpts);
+ const HTTP_PROXY = httpProxy ?? process.env.http_proxy ?? process.env.HTTP_PROXY;
+ if (HTTP_PROXY) {
+ this[kHttpProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTP_PROXY });
+ } else {
+ this[kHttpProxyAgent] = this[kNoProxyAgent];
+ }
+ const HTTPS_PROXY = httpsProxy ?? process.env.https_proxy ?? process.env.HTTPS_PROXY;
+ if (HTTPS_PROXY) {
+ this[kHttpsProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTPS_PROXY });
+ } else {
+ this[kHttpsProxyAgent] = this[kHttpProxyAgent];
+ }
+ this.#parseNoProxy();
+ }
+ [kDispatch](opts, handler) {
+ const url2 = new URL(opts.origin);
+ const agent = this.#getProxyAgentForUrl(url2);
+ return agent.dispatch(opts, handler);
+ }
+ [kClose]() {
+ return Promise.all([
+ this[kNoProxyAgent].close(),
+ !this[kHttpProxyAgent][kClosed] && this[kHttpProxyAgent].close(),
+ !this[kHttpsProxyAgent][kClosed] && this[kHttpsProxyAgent].close()
+ ]);
+ }
+ [kDestroy](err) {
+ return Promise.all([
+ this[kNoProxyAgent].destroy(err),
+ !this[kHttpProxyAgent][kDestroyed] && this[kHttpProxyAgent].destroy(err),
+ !this[kHttpsProxyAgent][kDestroyed] && this[kHttpsProxyAgent].destroy(err)
+ ]);
+ }
+ #getProxyAgentForUrl(url2) {
+ let { protocol, host: hostname4, port } = url2;
+ hostname4 = hostname4.replace(/:\d*$/, "").toLowerCase();
+ port = Number.parseInt(port, 10) || DEFAULT_PORTS[protocol] || 0;
+ if (!this.#shouldProxy(hostname4, port)) {
+ return this[kNoProxyAgent];
+ }
+ if (protocol === "https:") {
+ return this[kHttpsProxyAgent];
+ }
+ return this[kHttpProxyAgent];
+ }
+ #shouldProxy(hostname4, port) {
+ if (this.#noProxyChanged) {
+ this.#parseNoProxy();
+ }
+ if (this.#noProxyEntries.length === 0) {
+ return true;
+ }
+ if (this.#noProxyValue === "*") {
+ return false;
+ }
+ for (let i = 0; i < this.#noProxyEntries.length; i++) {
+ const entry = this.#noProxyEntries[i];
+ if (entry.port && entry.port !== port) {
+ continue;
+ }
+ if (hostname4 === entry.hostname) {
+ return false;
+ }
+ if (hostname4.slice(-(entry.hostname.length + 1)) === `.${entry.hostname}`) {
+ return false;
+ }
+ }
+ return true;
+ }
+ #parseNoProxy() {
+ const noProxyValue = this.#opts.noProxy ?? this.#noProxyEnv;
+ const noProxySplit = noProxyValue.split(/[,\s]/);
+ const noProxyEntries = [];
+ for (let i = 0; i < noProxySplit.length; i++) {
+ const entry = noProxySplit[i];
+ if (!entry) {
+ continue;
+ }
+ const parsed = entry.match(/^(.+):(\d+)$/);
+ noProxyEntries.push({
+ // strip leading dot or asterisk with dot
+ hostname: (parsed ? parsed[1] : entry).replace(/^\*?\./, "").toLowerCase(),
+ port: parsed ? Number.parseInt(parsed[2], 10) : 0
+ });
+ }
+ this.#noProxyValue = noProxyValue;
+ this.#noProxyEntries = noProxyEntries;
+ }
+ get #noProxyChanged() {
+ if (this.#opts.noProxy !== void 0) {
+ return false;
+ }
+ return this.#noProxyValue !== this.#noProxyEnv;
+ }
+ get #noProxyEnv() {
+ return process.env.no_proxy ?? process.env.NO_PROXY ?? "";
+ }
+ };
+ module2.exports = EnvHttpProxyAgent;
+ }
+});
+
+// node_modules/undici/lib/handler/retry-handler.js
+var require_retry_handler = __commonJS({
+ "node_modules/undici/lib/handler/retry-handler.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var assert2 = __require("node:assert");
+ var { kRetryHandlerDefaultRetry } = require_symbols();
+ var { RequestRetryError } = require_errors();
+ var WrapHandler = require_wrap_handler();
+ var {
+ isDisturbed,
+ parseRangeHeader,
+ wrapRequestBody
+ } = require_util();
+ function calculateRetryAfterHeader(retryAfter) {
+ const retryTime = new Date(retryAfter).getTime();
+ return isNaN(retryTime) ? 0 : retryTime - Date.now();
+ }
+ __name(calculateRetryAfterHeader, "calculateRetryAfterHeader");
+ var RetryHandler = class _RetryHandler {
+ static {
+ __name(this, "RetryHandler");
+ }
+ constructor(opts, { dispatch, handler }) {
+ const { retryOptions, ...dispatchOpts } = opts;
+ const {
+ // Retry scoped
+ retry: retryFn,
+ maxRetries,
+ maxTimeout,
+ minTimeout,
+ timeoutFactor,
+ // Response scoped
+ methods,
+ errorCodes,
+ retryAfter,
+ statusCodes,
+ throwOnError
+ } = retryOptions ?? {};
+ this.error = null;
+ this.dispatch = dispatch;
+ this.handler = WrapHandler.wrap(handler);
+ this.opts = { ...dispatchOpts, body: wrapRequestBody(opts.body) };
+ this.retryOpts = {
+ throwOnError: throwOnError ?? true,
+ retry: retryFn ?? _RetryHandler[kRetryHandlerDefaultRetry],
+ retryAfter: retryAfter ?? true,
+ maxTimeout: maxTimeout ?? 30 * 1e3,
+ // 30s,
+ minTimeout: minTimeout ?? 500,
+ // .5s
+ timeoutFactor: timeoutFactor ?? 2,
+ maxRetries: maxRetries ?? 5,
+ // What errors we should retry
+ methods: methods ?? ["GET", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE"],
+ // Indicates which errors to retry
+ statusCodes: statusCodes ?? [500, 502, 503, 504, 429],
+ // List of errors to retry
+ errorCodes: errorCodes ?? [
+ "ECONNRESET",
+ "ECONNREFUSED",
+ "ENOTFOUND",
+ "ENETDOWN",
+ "ENETUNREACH",
+ "EHOSTDOWN",
+ "EHOSTUNREACH",
+ "EPIPE",
+ "UND_ERR_SOCKET"
+ ]
+ };
+ this.retryCount = 0;
+ this.retryCountCheckpoint = 0;
+ this.headersSent = false;
+ this.start = 0;
+ this.end = null;
+ this.etag = null;
+ }
+ onResponseStartWithRetry(controller, statusCode, headers, statusMessage, err) {
+ if (this.retryOpts.throwOnError) {
+ if (this.retryOpts.statusCodes.includes(statusCode) === false) {
+ this.headersSent = true;
+ this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
+ } else {
+ this.error = err;
+ }
+ return;
+ }
+ if (isDisturbed(this.opts.body)) {
+ this.headersSent = true;
+ this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
+ return;
+ }
+ function shouldRetry(passedErr) {
+ if (passedErr) {
+ this.headersSent = true;
+ this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
+ controller.resume();
+ return;
+ }
+ this.error = err;
+ controller.resume();
+ }
+ __name(shouldRetry, "shouldRetry");
+ controller.pause();
+ this.retryOpts.retry(
+ err,
+ {
+ state: { counter: this.retryCount },
+ opts: { retryOptions: this.retryOpts, ...this.opts }
+ },
+ shouldRetry.bind(this)
+ );
+ }
+ onRequestStart(controller, context) {
+ if (!this.headersSent) {
+ this.handler.onRequestStart?.(controller, context);
+ }
+ }
+ onRequestUpgrade(controller, statusCode, headers, socket) {
+ this.handler.onRequestUpgrade?.(controller, statusCode, headers, socket);
+ }
+ static [kRetryHandlerDefaultRetry](err, { state, opts }, cb) {
+ const { statusCode, code, headers } = err;
+ const { method, retryOptions } = opts;
+ const {
+ maxRetries,
+ minTimeout,
+ maxTimeout,
+ timeoutFactor,
+ statusCodes,
+ errorCodes,
+ methods
+ } = retryOptions;
+ const { counter } = state;
+ if (code && code !== "UND_ERR_REQ_RETRY" && !errorCodes.includes(code)) {
+ cb(err);
+ return;
+ }
+ if (Array.isArray(methods) && !methods.includes(method)) {
+ cb(err);
+ return;
+ }
+ if (statusCode != null && Array.isArray(statusCodes) && !statusCodes.includes(statusCode)) {
+ cb(err);
+ return;
+ }
+ if (counter > maxRetries) {
+ cb(err);
+ return;
+ }
+ let retryAfterHeader = headers?.["retry-after"];
+ if (retryAfterHeader) {
+ retryAfterHeader = Number(retryAfterHeader);
+ retryAfterHeader = Number.isNaN(retryAfterHeader) ? calculateRetryAfterHeader(headers["retry-after"]) : retryAfterHeader * 1e3;
+ }
+ const retryTimeout = retryAfterHeader > 0 ? Math.min(retryAfterHeader, maxTimeout) : Math.min(minTimeout * timeoutFactor ** (counter - 1), maxTimeout);
+ setTimeout(() => cb(null), retryTimeout);
+ }
+ onResponseStart(controller, statusCode, headers, statusMessage) {
+ this.error = null;
+ this.retryCount += 1;
+ if (statusCode >= 300) {
+ const err = new RequestRetryError("Request failed", statusCode, {
+ headers,
+ data: {
+ count: this.retryCount
+ }
+ });
+ this.onResponseStartWithRetry(controller, statusCode, headers, statusMessage, err);
+ return;
+ }
+ if (this.headersSent) {
+ if (statusCode !== 206 && (this.start > 0 || statusCode !== 200)) {
+ throw new RequestRetryError("server does not support the range header and the payload was partially consumed", statusCode, {
+ headers,
+ data: { count: this.retryCount }
+ });
+ }
+ const contentRange = parseRangeHeader(headers["content-range"]);
+ if (!contentRange) {
+ throw new RequestRetryError("Content-Range mismatch", statusCode, {
+ headers,
+ data: { count: this.retryCount }
+ });
+ }
+ if (this.etag != null && this.etag !== headers.etag) {
+ throw new RequestRetryError("ETag mismatch", statusCode, {
+ headers,
+ data: { count: this.retryCount }
+ });
+ }
+ const { start, size, end = size ? size - 1 : null } = contentRange;
+ assert2(this.start === start, "content-range mismatch");
+ assert2(this.end == null || this.end === end, "content-range mismatch");
+ return;
+ }
+ if (this.end == null) {
+ if (statusCode === 206) {
+ const range = parseRangeHeader(headers["content-range"]);
+ if (range == null) {
+ this.headersSent = true;
+ this.handler.onResponseStart?.(
+ controller,
+ statusCode,
+ headers,
+ statusMessage
+ );
+ return;
+ }
+ const { start, size, end = size ? size - 1 : null } = range;
+ assert2(
+ start != null && Number.isFinite(start),
+ "content-range mismatch"
+ );
+ assert2(end != null && Number.isFinite(end), "invalid content-length");
+ this.start = start;
+ this.end = end;
+ }
+ if (this.end == null) {
+ const contentLength = headers["content-length"];
+ this.end = contentLength != null ? Number(contentLength) - 1 : null;
+ }
+ assert2(Number.isFinite(this.start));
+ assert2(
+ this.end == null || Number.isFinite(this.end),
+ "invalid content-length"
+ );
+ this.resume = true;
+ this.etag = headers.etag != null ? headers.etag : null;
+ if (this.etag != null && this.etag[0] === "W" && this.etag[1] === "/") {
+ this.etag = null;
+ }
+ this.headersSent = true;
+ this.handler.onResponseStart?.(
+ controller,
+ statusCode,
+ headers,
+ statusMessage
+ );
+ } else {
+ throw new RequestRetryError("Request failed", statusCode, {
+ headers,
+ data: { count: this.retryCount }
+ });
+ }
+ }
+ onResponseData(controller, chunk) {
+ if (this.error) {
+ return;
+ }
+ this.start += chunk.length;
+ this.handler.onResponseData?.(controller, chunk);
+ }
+ onResponseEnd(controller, trailers) {
+ if (this.error && this.retryOpts.throwOnError) {
+ throw this.error;
+ }
+ if (!this.error) {
+ this.retryCount = 0;
+ return this.handler.onResponseEnd?.(controller, trailers);
+ }
+ this.retry(controller);
+ }
+ retry(controller) {
+ if (this.start !== 0) {
+ const headers = { range: `bytes=${this.start}-${this.end ?? ""}` };
+ if (this.etag != null) {
+ headers["if-match"] = this.etag;
+ }
+ this.opts = {
+ ...this.opts,
+ headers: {
+ ...this.opts.headers,
+ ...headers
+ }
+ };
+ }
+ try {
+ this.retryCountCheckpoint = this.retryCount;
+ this.dispatch(this.opts, this);
+ } catch (err) {
+ this.handler.onResponseError?.(controller, err);
+ }
+ }
+ onResponseError(controller, err) {
+ if (controller?.aborted || isDisturbed(this.opts.body)) {
+ this.handler.onResponseError?.(controller, err);
+ return;
+ }
+ function shouldRetry(returnedErr) {
+ if (!returnedErr) {
+ this.retry(controller);
+ return;
+ }
+ this.handler?.onResponseError?.(controller, returnedErr);
+ }
+ __name(shouldRetry, "shouldRetry");
+ if (this.retryCount - this.retryCountCheckpoint > 0) {
+ this.retryCount = this.retryCountCheckpoint + (this.retryCount - this.retryCountCheckpoint);
+ } else {
+ this.retryCount += 1;
+ }
+ this.retryOpts.retry(
+ err,
+ {
+ state: { counter: this.retryCount },
+ opts: { retryOptions: this.retryOpts, ...this.opts }
+ },
+ shouldRetry.bind(this)
+ );
+ }
+ };
+ module2.exports = RetryHandler;
+ }
+});
+
+// node_modules/undici/lib/dispatcher/retry-agent.js
+var require_retry_agent = __commonJS({
+ "node_modules/undici/lib/dispatcher/retry-agent.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var Dispatcher = require_dispatcher();
+ var RetryHandler = require_retry_handler();
+ var RetryAgent = class extends Dispatcher {
+ static {
+ __name(this, "RetryAgent");
+ }
+ #agent = null;
+ #options = null;
+ constructor(agent, options2 = {}) {
+ super(options2);
+ this.#agent = agent;
+ this.#options = options2;
+ }
+ dispatch(opts, handler) {
+ const retry = new RetryHandler({
+ ...opts,
+ retryOptions: this.#options
+ }, {
+ dispatch: this.#agent.dispatch.bind(this.#agent),
+ handler
+ });
+ return this.#agent.dispatch(opts, retry);
+ }
+ close() {
+ return this.#agent.close();
+ }
+ destroy() {
+ return this.#agent.destroy();
+ }
+ };
+ module2.exports = RetryAgent;
+ }
+});
+
+// node_modules/undici/lib/dispatcher/h2c-client.js
+var require_h2c_client = __commonJS({
+ "node_modules/undici/lib/dispatcher/h2c-client.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { InvalidArgumentError } = require_errors();
+ var Client = require_client();
+ var H2CClient = class extends Client {
+ static {
+ __name(this, "H2CClient");
+ }
+ constructor(origin, clientOpts) {
+ if (typeof origin === "string") {
+ origin = new URL(origin);
+ }
+ if (origin.protocol !== "http:") {
+ throw new InvalidArgumentError(
+ "h2c-client: Only h2c protocol is supported"
+ );
+ }
+ const { maxConcurrentStreams, pipelining, ...opts } = clientOpts ?? {};
+ let defaultMaxConcurrentStreams = 100;
+ let defaultPipelining = 100;
+ if (maxConcurrentStreams != null && Number.isInteger(maxConcurrentStreams) && maxConcurrentStreams > 0) {
+ defaultMaxConcurrentStreams = maxConcurrentStreams;
+ }
+ if (pipelining != null && Number.isInteger(pipelining) && pipelining > 0) {
+ defaultPipelining = pipelining;
+ }
+ if (defaultPipelining > defaultMaxConcurrentStreams) {
+ throw new InvalidArgumentError(
+ "h2c-client: pipelining cannot be greater than maxConcurrentStreams"
+ );
+ }
+ super(origin, {
+ ...opts,
+ maxConcurrentStreams: defaultMaxConcurrentStreams,
+ pipelining: defaultPipelining,
+ allowH2: true,
+ useH2c: true
+ });
+ }
+ };
+ module2.exports = H2CClient;
+ }
+});
+
+// node_modules/undici/lib/api/readable.js
+var require_readable = __commonJS({
+ "node_modules/undici/lib/api/readable.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var assert2 = __require("node:assert");
+ var { Readable } = __require("node:stream");
+ var { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError } = require_errors();
+ var util = require_util();
+ var { ReadableStreamFrom: ReadableStreamFrom2 } = require_util();
+ var kConsume = /* @__PURE__ */ Symbol("kConsume");
+ var kReading = /* @__PURE__ */ Symbol("kReading");
+ var kBody = /* @__PURE__ */ Symbol("kBody");
+ var kAbort = /* @__PURE__ */ Symbol("kAbort");
+ var kContentType = /* @__PURE__ */ Symbol("kContentType");
+ var kContentLength = /* @__PURE__ */ Symbol("kContentLength");
+ var kUsed = /* @__PURE__ */ Symbol("kUsed");
+ var kBytesRead = /* @__PURE__ */ Symbol("kBytesRead");
+ var noop3 = /* @__PURE__ */ __name(() => {
+ }, "noop");
+ var BodyReadable = class extends Readable {
+ static {
+ __name(this, "BodyReadable");
+ }
+ /**
+ * @param {object} opts
+ * @param {(this: Readable, size: number) => void} opts.resume
+ * @param {() => (void | null)} opts.abort
+ * @param {string} [opts.contentType = '']
+ * @param {number} [opts.contentLength]
+ * @param {number} [opts.highWaterMark = 64 * 1024]
+ */
+ constructor({
+ resume,
+ abort,
+ contentType = "",
+ contentLength,
+ highWaterMark = 64 * 1024
+ // Same as nodejs fs streams.
+ }) {
+ super({
+ autoDestroy: true,
+ read: resume,
+ highWaterMark
+ });
+ this._readableState.dataEmitted = false;
+ this[kAbort] = abort;
+ this[kConsume] = null;
+ this[kBytesRead] = 0;
+ this[kBody] = null;
+ this[kUsed] = false;
+ this[kContentType] = contentType;
+ this[kContentLength] = Number.isFinite(contentLength) ? contentLength : null;
+ this[kReading] = false;
+ }
+ /**
+ * @param {Error|null} err
+ * @param {(error:(Error|null)) => void} callback
+ * @returns {void}
+ */
+ _destroy(err, callback) {
+ if (!err && !this._readableState.endEmitted) {
+ err = new RequestAbortedError();
+ }
+ if (err) {
+ this[kAbort]();
+ }
+ if (!this[kUsed]) {
+ setImmediate(callback, err);
+ } else {
+ callback(err);
+ }
+ }
+ /**
+ * @param {string|symbol} event
+ * @param {(...args: any[]) => void} listener
+ * @returns {this}
+ */
+ on(event, listener) {
+ if (event === "data" || event === "readable") {
+ this[kReading] = true;
+ this[kUsed] = true;
+ }
+ return super.on(event, listener);
+ }
+ /**
+ * @param {string|symbol} event
+ * @param {(...args: any[]) => void} listener
+ * @returns {this}
+ */
+ addListener(event, listener) {
+ return this.on(event, listener);
+ }
+ /**
+ * @param {string|symbol} event
+ * @param {(...args: any[]) => void} listener
+ * @returns {this}
+ */
+ off(event, listener) {
+ const ret = super.off(event, listener);
+ if (event === "data" || event === "readable") {
+ this[kReading] = this.listenerCount("data") > 0 || this.listenerCount("readable") > 0;
+ }
+ return ret;
+ }
+ /**
+ * @param {string|symbol} event
+ * @param {(...args: any[]) => void} listener
+ * @returns {this}
+ */
+ removeListener(event, listener) {
+ return this.off(event, listener);
+ }
+ /**
+ * @param {Buffer|null} chunk
+ * @returns {boolean}
+ */
+ push(chunk) {
+ if (chunk) {
+ this[kBytesRead] += chunk.length;
+ if (this[kConsume]) {
+ consumePush(this[kConsume], chunk);
+ return this[kReading] ? super.push(chunk) : true;
+ }
+ }
+ return super.push(chunk);
+ }
+ /**
+ * Consumes and returns the body as a string.
+ *
+ * @see https://fetch.spec.whatwg.org/#dom-body-text
+ * @returns {Promise}
+ */
+ text() {
+ return consume(this, "text");
+ }
+ /**
+ * Consumes and returns the body as a JavaScript Object.
+ *
+ * @see https://fetch.spec.whatwg.org/#dom-body-json
+ * @returns {Promise}
+ */
+ json() {
+ return consume(this, "json");
+ }
+ /**
+ * Consumes and returns the body as a Blob
+ *
+ * @see https://fetch.spec.whatwg.org/#dom-body-blob
+ * @returns {Promise}
+ */
+ blob() {
+ return consume(this, "blob");
+ }
+ /**
+ * Consumes and returns the body as an Uint8Array.
+ *
+ * @see https://fetch.spec.whatwg.org/#dom-body-bytes
+ * @returns {Promise}
+ */
+ bytes() {
+ return consume(this, "bytes");
+ }
+ /**
+ * Consumes and returns the body as an ArrayBuffer.
+ *
+ * @see https://fetch.spec.whatwg.org/#dom-body-arraybuffer
+ * @returns {Promise}
+ */
+ arrayBuffer() {
+ return consume(this, "arrayBuffer");
+ }
+ /**
+ * Not implemented
+ *
+ * @see https://fetch.spec.whatwg.org/#dom-body-formdata
+ * @throws {NotSupportedError}
+ */
+ async formData() {
+ throw new NotSupportedError();
+ }
+ /**
+ * Returns true if the body is not null and the body has been consumed.
+ * Otherwise, returns false.
+ *
+ * @see https://fetch.spec.whatwg.org/#dom-body-bodyused
+ * @readonly
+ * @returns {boolean}
+ */
+ get bodyUsed() {
+ return util.isDisturbed(this);
+ }
+ /**
+ * @see https://fetch.spec.whatwg.org/#dom-body-body
+ * @readonly
+ * @returns {ReadableStream}
+ */
+ get body() {
+ if (!this[kBody]) {
+ this[kBody] = ReadableStreamFrom2(this);
+ if (this[kConsume]) {
+ this[kBody].getReader();
+ assert2(this[kBody].locked);
+ }
+ }
+ return this[kBody];
+ }
+ /**
+ * Dumps the response body by reading `limit` number of bytes.
+ * @param {object} opts
+ * @param {number} [opts.limit = 131072] Number of bytes to read.
+ * @param {AbortSignal} [opts.signal] An AbortSignal to cancel the dump.
+ * @returns {Promise}
+ */
+ dump(opts) {
+ const signal = opts?.signal;
+ if (signal != null && (typeof signal !== "object" || !("aborted" in signal))) {
+ return Promise.reject(new InvalidArgumentError("signal must be an AbortSignal"));
+ }
+ const limit2 = opts?.limit && Number.isFinite(opts.limit) ? opts.limit : 128 * 1024;
+ if (signal?.aborted) {
+ return Promise.reject(signal.reason ?? new AbortError());
+ }
+ if (this._readableState.closeEmitted) {
+ return Promise.resolve(null);
+ }
+ return new Promise((resolve16, reject) => {
+ if (this[kContentLength] && this[kContentLength] > limit2 || this[kBytesRead] > limit2) {
+ this.destroy(new AbortError());
+ }
+ if (signal) {
+ const onAbort = /* @__PURE__ */ __name(() => {
+ this.destroy(signal.reason ?? new AbortError());
+ }, "onAbort");
+ signal.addEventListener("abort", onAbort);
+ this.on("close", function() {
+ signal.removeEventListener("abort", onAbort);
+ if (signal.aborted) {
+ reject(signal.reason ?? new AbortError());
+ } else {
+ resolve16(null);
+ }
+ });
+ } else {
+ this.on("close", resolve16);
+ }
+ this.on("error", noop3).on("data", () => {
+ if (this[kBytesRead] > limit2) {
+ this.destroy();
+ }
+ }).resume();
+ });
+ }
+ /**
+ * @param {BufferEncoding} encoding
+ * @returns {this}
+ */
+ setEncoding(encoding) {
+ if (Buffer.isEncoding(encoding)) {
+ this._readableState.encoding = encoding;
+ }
+ return this;
+ }
+ };
+ function isLocked(bodyReadable) {
+ return bodyReadable[kBody]?.locked === true || bodyReadable[kConsume] !== null;
+ }
+ __name(isLocked, "isLocked");
+ function isUnusable(bodyReadable) {
+ return util.isDisturbed(bodyReadable) || isLocked(bodyReadable);
+ }
+ __name(isUnusable, "isUnusable");
+ function consume(stream, type2) {
+ assert2(!stream[kConsume]);
+ return new Promise((resolve16, reject) => {
+ if (isUnusable(stream)) {
+ const rState = stream._readableState;
+ if (rState.destroyed && rState.closeEmitted === false) {
+ stream.on("error", reject).on("close", () => {
+ reject(new TypeError("unusable"));
+ });
+ } else {
+ reject(rState.errored ?? new TypeError("unusable"));
+ }
+ } else {
+ queueMicrotask(() => {
+ stream[kConsume] = {
+ type: type2,
+ stream,
+ resolve: resolve16,
+ reject,
+ length: 0,
+ body: []
+ };
+ stream.on("error", function(err) {
+ consumeFinish(this[kConsume], err);
+ }).on("close", function() {
+ if (this[kConsume].body !== null) {
+ consumeFinish(this[kConsume], new RequestAbortedError());
+ }
+ });
+ consumeStart(stream[kConsume]);
+ });
+ }
+ });
+ }
+ __name(consume, "consume");
+ function consumeStart(consume2) {
+ if (consume2.body === null) {
+ return;
+ }
+ const { _readableState: state } = consume2.stream;
+ if (state.bufferIndex) {
+ const start = state.bufferIndex;
+ const end = state.buffer.length;
+ for (let n = start; n < end; n++) {
+ consumePush(consume2, state.buffer[n]);
+ }
+ } else {
+ for (const chunk of state.buffer) {
+ consumePush(consume2, chunk);
+ }
+ }
+ if (state.endEmitted) {
+ consumeEnd(this[kConsume], this._readableState.encoding);
+ } else {
+ consume2.stream.on("end", function() {
+ consumeEnd(this[kConsume], this._readableState.encoding);
+ });
+ }
+ consume2.stream.resume();
+ while (consume2.stream.read() != null) {
+ }
+ }
+ __name(consumeStart, "consumeStart");
+ function chunksDecode(chunks, length, encoding) {
+ if (chunks.length === 0 || length === 0) {
+ return "";
+ }
+ const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, length);
+ const bufferLength = buffer.length;
+ const start = bufferLength > 2 && buffer[0] === 239 && buffer[1] === 187 && buffer[2] === 191 ? 3 : 0;
+ if (!encoding || encoding === "utf8" || encoding === "utf-8") {
+ return buffer.utf8Slice(start, bufferLength);
+ } else {
+ return buffer.subarray(start, bufferLength).toString(encoding);
+ }
+ }
+ __name(chunksDecode, "chunksDecode");
+ function chunksConcat(chunks, length) {
+ if (chunks.length === 0 || length === 0) {
+ return new Uint8Array(0);
+ }
+ if (chunks.length === 1) {
+ return new Uint8Array(chunks[0]);
+ }
+ const buffer = new Uint8Array(Buffer.allocUnsafeSlow(length).buffer);
+ let offset = 0;
+ for (let i = 0; i < chunks.length; ++i) {
+ const chunk = chunks[i];
+ buffer.set(chunk, offset);
+ offset += chunk.length;
+ }
+ return buffer;
+ }
+ __name(chunksConcat, "chunksConcat");
+ function consumeEnd(consume2, encoding) {
+ const { type: type2, body, resolve: resolve16, stream, length } = consume2;
+ try {
+ if (type2 === "text") {
+ resolve16(chunksDecode(body, length, encoding));
+ } else if (type2 === "json") {
+ resolve16(JSON.parse(chunksDecode(body, length, encoding)));
+ } else if (type2 === "arrayBuffer") {
+ resolve16(chunksConcat(body, length).buffer);
+ } else if (type2 === "blob") {
+ resolve16(new Blob(body, { type: stream[kContentType] }));
+ } else if (type2 === "bytes") {
+ resolve16(chunksConcat(body, length));
+ }
+ consumeFinish(consume2);
+ } catch (err) {
+ stream.destroy(err);
+ }
+ }
+ __name(consumeEnd, "consumeEnd");
+ function consumePush(consume2, chunk) {
+ consume2.length += chunk.length;
+ consume2.body.push(chunk);
+ }
+ __name(consumePush, "consumePush");
+ function consumeFinish(consume2, err) {
+ if (consume2.body === null) {
+ return;
+ }
+ if (err) {
+ consume2.reject(err);
+ } else {
+ consume2.resolve();
+ }
+ consume2.type = null;
+ consume2.stream = null;
+ consume2.resolve = null;
+ consume2.reject = null;
+ consume2.length = 0;
+ consume2.body = null;
+ }
+ __name(consumeFinish, "consumeFinish");
+ module2.exports = {
+ Readable: BodyReadable,
+ chunksDecode
+ };
+ }
+});
+
+// node_modules/undici/lib/api/api-request.js
+var require_api_request = __commonJS({
+ "node_modules/undici/lib/api/api-request.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var assert2 = __require("node:assert");
+ var { AsyncResource } = __require("node:async_hooks");
+ var { Readable } = require_readable();
+ var { InvalidArgumentError, RequestAbortedError } = require_errors();
+ var util = require_util();
+ function noop3() {
+ }
+ __name(noop3, "noop");
+ var RequestHandler = class extends AsyncResource {
+ static {
+ __name(this, "RequestHandler");
+ }
+ constructor(opts, callback) {
+ if (!opts || typeof opts !== "object") {
+ throw new InvalidArgumentError("invalid opts");
+ }
+ const { signal, method, opaque, body, onInfo, responseHeaders, highWaterMark } = opts;
+ try {
+ if (typeof callback !== "function") {
+ throw new InvalidArgumentError("invalid callback");
+ }
+ if (highWaterMark != null && (!Number.isFinite(highWaterMark) || highWaterMark < 0)) {
+ throw new InvalidArgumentError("invalid highWaterMark");
+ }
+ if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") {
+ throw new InvalidArgumentError("signal must be an EventEmitter or EventTarget");
+ }
+ if (method === "CONNECT") {
+ throw new InvalidArgumentError("invalid method");
+ }
+ if (onInfo && typeof onInfo !== "function") {
+ throw new InvalidArgumentError("invalid onInfo callback");
+ }
+ super("UNDICI_REQUEST");
+ } catch (err) {
+ if (util.isStream(body)) {
+ util.destroy(body.on("error", noop3), err);
+ }
+ throw err;
+ }
+ this.method = method;
+ this.responseHeaders = responseHeaders || null;
+ this.opaque = opaque || null;
+ this.callback = callback;
+ this.res = null;
+ this.abort = null;
+ this.body = body;
+ this.trailers = {};
+ this.context = null;
+ this.onInfo = onInfo || null;
+ this.highWaterMark = highWaterMark;
+ this.reason = null;
+ this.removeAbortListener = null;
+ if (signal?.aborted) {
+ this.reason = signal.reason ?? new RequestAbortedError();
+ } else if (signal) {
+ this.removeAbortListener = util.addAbortListener(signal, () => {
+ this.reason = signal.reason ?? new RequestAbortedError();
+ if (this.res) {
+ util.destroy(this.res.on("error", noop3), this.reason);
+ } else if (this.abort) {
+ this.abort(this.reason);
+ }
+ });
+ }
+ }
+ onConnect(abort, context) {
+ if (this.reason) {
+ abort(this.reason);
+ return;
+ }
+ assert2(this.callback);
+ this.abort = abort;
+ this.context = context;
+ }
+ onHeaders(statusCode, rawHeaders, resume, statusMessage) {
+ const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this;
+ const headers = responseHeaders === "raw" ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders);
+ if (statusCode < 200) {
+ if (this.onInfo) {
+ this.onInfo({ statusCode, headers });
+ }
+ return;
+ }
+ const parsedHeaders = responseHeaders === "raw" ? util.parseHeaders(rawHeaders) : headers;
+ const contentType = parsedHeaders["content-type"];
+ const contentLength = parsedHeaders["content-length"];
+ const res = new Readable({
+ resume,
+ abort,
+ contentType,
+ contentLength: this.method !== "HEAD" && contentLength ? Number(contentLength) : null,
+ highWaterMark
+ });
+ if (this.removeAbortListener) {
+ res.on("close", this.removeAbortListener);
+ this.removeAbortListener = null;
+ }
+ this.callback = null;
+ this.res = res;
+ if (callback !== null) {
+ try {
+ this.runInAsyncScope(callback, null, null, {
+ statusCode,
+ statusText: statusMessage,
+ headers,
+ trailers: this.trailers,
+ opaque,
+ body: res,
+ context
+ });
+ } catch (err) {
+ this.res = null;
+ util.destroy(res.on("error", noop3), err);
+ queueMicrotask(() => {
+ throw err;
+ });
+ }
+ }
+ }
+ onData(chunk) {
+ return this.res.push(chunk);
+ }
+ onComplete(trailers) {
+ util.parseHeaders(trailers, this.trailers);
+ this.res.push(null);
+ }
+ onError(err) {
+ const { res, callback, body, opaque } = this;
+ if (callback) {
+ this.callback = null;
+ queueMicrotask(() => {
+ this.runInAsyncScope(callback, null, err, { opaque });
+ });
+ }
+ if (res) {
+ this.res = null;
+ queueMicrotask(() => {
+ util.destroy(res.on("error", noop3), err);
+ });
+ }
+ if (body) {
+ this.body = null;
+ if (util.isStream(body)) {
+ body.on("error", noop3);
+ util.destroy(body, err);
+ }
+ }
+ if (this.removeAbortListener) {
+ this.removeAbortListener();
+ this.removeAbortListener = null;
+ }
+ }
+ };
+ function request(opts, callback) {
+ if (callback === void 0) {
+ return new Promise((resolve16, reject) => {
+ request.call(this, opts, (err, data) => {
+ return err ? reject(err) : resolve16(data);
+ });
+ });
+ }
+ try {
+ const handler = new RequestHandler(opts, callback);
+ this.dispatch(opts, handler);
+ } catch (err) {
+ if (typeof callback !== "function") {
+ throw err;
+ }
+ const opaque = opts?.opaque;
+ queueMicrotask(() => callback(err, { opaque }));
+ }
+ }
+ __name(request, "request");
+ module2.exports = request;
+ module2.exports.RequestHandler = RequestHandler;
+ }
+});
+
+// node_modules/undici/lib/api/abort-signal.js
+var require_abort_signal = __commonJS({
+ "node_modules/undici/lib/api/abort-signal.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { addAbortListener } = require_util();
+ var { RequestAbortedError } = require_errors();
+ var kListener = /* @__PURE__ */ Symbol("kListener");
+ var kSignal = /* @__PURE__ */ Symbol("kSignal");
+ function abort(self2) {
+ if (self2.abort) {
+ self2.abort(self2[kSignal]?.reason);
+ } else {
+ self2.reason = self2[kSignal]?.reason ?? new RequestAbortedError();
+ }
+ removeSignal(self2);
+ }
+ __name(abort, "abort");
+ function addSignal(self2, signal) {
+ self2.reason = null;
+ self2[kSignal] = null;
+ self2[kListener] = null;
+ if (!signal) {
+ return;
+ }
+ if (signal.aborted) {
+ abort(self2);
+ return;
+ }
+ self2[kSignal] = signal;
+ self2[kListener] = () => {
+ abort(self2);
+ };
+ addAbortListener(self2[kSignal], self2[kListener]);
+ }
+ __name(addSignal, "addSignal");
+ function removeSignal(self2) {
+ if (!self2[kSignal]) {
+ return;
+ }
+ if ("removeEventListener" in self2[kSignal]) {
+ self2[kSignal].removeEventListener("abort", self2[kListener]);
+ } else {
+ self2[kSignal].removeListener("abort", self2[kListener]);
+ }
+ self2[kSignal] = null;
+ self2[kListener] = null;
+ }
+ __name(removeSignal, "removeSignal");
+ module2.exports = {
+ addSignal,
+ removeSignal
+ };
+ }
+});
+
+// node_modules/undici/lib/api/api-stream.js
+var require_api_stream = __commonJS({
+ "node_modules/undici/lib/api/api-stream.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var assert2 = __require("node:assert");
+ var { finished } = __require("node:stream");
+ var { AsyncResource } = __require("node:async_hooks");
+ var { InvalidArgumentError, InvalidReturnValueError } = require_errors();
+ var util = require_util();
+ var { addSignal, removeSignal } = require_abort_signal();
+ function noop3() {
+ }
+ __name(noop3, "noop");
+ var StreamHandler = class extends AsyncResource {
+ static {
+ __name(this, "StreamHandler");
+ }
+ constructor(opts, factory, callback) {
+ if (!opts || typeof opts !== "object") {
+ throw new InvalidArgumentError("invalid opts");
+ }
+ const { signal, method, opaque, body, onInfo, responseHeaders } = opts;
+ try {
+ if (typeof callback !== "function") {
+ throw new InvalidArgumentError("invalid callback");
+ }
+ if (typeof factory !== "function") {
+ throw new InvalidArgumentError("invalid factory");
+ }
+ if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") {
+ throw new InvalidArgumentError("signal must be an EventEmitter or EventTarget");
+ }
+ if (method === "CONNECT") {
+ throw new InvalidArgumentError("invalid method");
+ }
+ if (onInfo && typeof onInfo !== "function") {
+ throw new InvalidArgumentError("invalid onInfo callback");
+ }
+ super("UNDICI_STREAM");
+ } catch (err) {
+ if (util.isStream(body)) {
+ util.destroy(body.on("error", noop3), err);
+ }
+ throw err;
+ }
+ this.responseHeaders = responseHeaders || null;
+ this.opaque = opaque || null;
+ this.factory = factory;
+ this.callback = callback;
+ this.res = null;
+ this.abort = null;
+ this.context = null;
+ this.trailers = null;
+ this.body = body;
+ this.onInfo = onInfo || null;
+ if (util.isStream(body)) {
+ body.on("error", (err) => {
+ this.onError(err);
+ });
+ }
+ addSignal(this, signal);
+ }
+ onConnect(abort, context) {
+ if (this.reason) {
+ abort(this.reason);
+ return;
+ }
+ assert2(this.callback);
+ this.abort = abort;
+ this.context = context;
+ }
+ onHeaders(statusCode, rawHeaders, resume, statusMessage) {
+ const { factory, opaque, context, responseHeaders } = this;
+ const headers = responseHeaders === "raw" ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders);
+ if (statusCode < 200) {
+ if (this.onInfo) {
+ this.onInfo({ statusCode, headers });
+ }
+ return;
+ }
+ this.factory = null;
+ if (factory === null) {
+ return;
+ }
+ const res = this.runInAsyncScope(factory, null, {
+ statusCode,
+ headers,
+ opaque,
+ context
+ });
+ if (!res || typeof res.write !== "function" || typeof res.end !== "function" || typeof res.on !== "function") {
+ throw new InvalidReturnValueError("expected Writable");
+ }
+ finished(res, { readable: false }, (err) => {
+ const { callback, res: res2, opaque: opaque2, trailers, abort } = this;
+ this.res = null;
+ if (err || !res2?.readable) {
+ util.destroy(res2, err);
+ }
+ this.callback = null;
+ this.runInAsyncScope(callback, null, err || null, { opaque: opaque2, trailers });
+ if (err) {
+ abort();
+ }
+ });
+ res.on("drain", resume);
+ this.res = res;
+ const needDrain = res.writableNeedDrain !== void 0 ? res.writableNeedDrain : res._writableState?.needDrain;
+ return needDrain !== true;
+ }
+ onData(chunk) {
+ const { res } = this;
+ return res ? res.write(chunk) : true;
+ }
+ onComplete(trailers) {
+ const { res } = this;
+ removeSignal(this);
+ if (!res) {
+ return;
+ }
+ this.trailers = util.parseHeaders(trailers);
+ res.end();
+ }
+ onError(err) {
+ const { res, callback, opaque, body } = this;
+ removeSignal(this);
+ this.factory = null;
+ if (res) {
+ this.res = null;
+ util.destroy(res, err);
+ } else if (callback) {
+ this.callback = null;
+ queueMicrotask(() => {
+ this.runInAsyncScope(callback, null, err, { opaque });
+ });
+ }
+ if (body) {
+ this.body = null;
+ util.destroy(body, err);
+ }
+ }
+ };
+ function stream(opts, factory, callback) {
+ if (callback === void 0) {
+ return new Promise((resolve16, reject) => {
+ stream.call(this, opts, factory, (err, data) => {
+ return err ? reject(err) : resolve16(data);
+ });
+ });
+ }
+ try {
+ const handler = new StreamHandler(opts, factory, callback);
+ this.dispatch(opts, handler);
+ } catch (err) {
+ if (typeof callback !== "function") {
+ throw err;
+ }
+ const opaque = opts?.opaque;
+ queueMicrotask(() => callback(err, { opaque }));
+ }
+ }
+ __name(stream, "stream");
+ module2.exports = stream;
+ }
+});
+
+// node_modules/undici/lib/api/api-pipeline.js
+var require_api_pipeline = __commonJS({
+ "node_modules/undici/lib/api/api-pipeline.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var {
+ Readable,
+ Duplex,
+ PassThrough: PassThrough2
+ } = __require("node:stream");
+ var assert2 = __require("node:assert");
+ var { AsyncResource } = __require("node:async_hooks");
+ var {
+ InvalidArgumentError,
+ InvalidReturnValueError,
+ RequestAbortedError
+ } = require_errors();
+ var util = require_util();
+ var { addSignal, removeSignal } = require_abort_signal();
+ function noop3() {
+ }
+ __name(noop3, "noop");
+ var kResume = /* @__PURE__ */ Symbol("resume");
+ var PipelineRequest = class extends Readable {
+ static {
+ __name(this, "PipelineRequest");
+ }
+ constructor() {
+ super({ autoDestroy: true });
+ this[kResume] = null;
+ }
+ _read() {
+ const { [kResume]: resume } = this;
+ if (resume) {
+ this[kResume] = null;
+ resume();
+ }
+ }
+ _destroy(err, callback) {
+ this._read();
+ callback(err);
+ }
+ };
+ var PipelineResponse = class extends Readable {
+ static {
+ __name(this, "PipelineResponse");
+ }
+ constructor(resume) {
+ super({ autoDestroy: true });
+ this[kResume] = resume;
+ }
+ _read() {
+ this[kResume]();
+ }
+ _destroy(err, callback) {
+ if (!err && !this._readableState.endEmitted) {
+ err = new RequestAbortedError();
+ }
+ callback(err);
+ }
+ };
+ var PipelineHandler = class extends AsyncResource {
+ static {
+ __name(this, "PipelineHandler");
+ }
+ constructor(opts, handler) {
+ if (!opts || typeof opts !== "object") {
+ throw new InvalidArgumentError("invalid opts");
+ }
+ if (typeof handler !== "function") {
+ throw new InvalidArgumentError("invalid handler");
+ }
+ const { signal, method, opaque, onInfo, responseHeaders } = opts;
+ if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") {
+ throw new InvalidArgumentError("signal must be an EventEmitter or EventTarget");
+ }
+ if (method === "CONNECT") {
+ throw new InvalidArgumentError("invalid method");
+ }
+ if (onInfo && typeof onInfo !== "function") {
+ throw new InvalidArgumentError("invalid onInfo callback");
+ }
+ super("UNDICI_PIPELINE");
+ this.opaque = opaque || null;
+ this.responseHeaders = responseHeaders || null;
+ this.handler = handler;
+ this.abort = null;
+ this.context = null;
+ this.onInfo = onInfo || null;
+ this.req = new PipelineRequest().on("error", noop3);
+ this.ret = new Duplex({
+ readableObjectMode: opts.objectMode,
+ autoDestroy: true,
+ read: /* @__PURE__ */ __name(() => {
+ const { body } = this;
+ if (body?.resume) {
+ body.resume();
+ }
+ }, "read"),
+ write: /* @__PURE__ */ __name((chunk, encoding, callback) => {
+ const { req } = this;
+ if (req.push(chunk, encoding) || req._readableState.destroyed) {
+ callback();
+ } else {
+ req[kResume] = callback;
+ }
+ }, "write"),
+ destroy: /* @__PURE__ */ __name((err, callback) => {
+ const { body, req, res, ret, abort } = this;
+ if (!err && !ret._readableState.endEmitted) {
+ err = new RequestAbortedError();
+ }
+ if (abort && err) {
+ abort();
+ }
+ util.destroy(body, err);
+ util.destroy(req, err);
+ util.destroy(res, err);
+ removeSignal(this);
+ callback(err);
+ }, "destroy")
+ }).on("prefinish", () => {
+ const { req } = this;
+ req.push(null);
+ });
+ this.res = null;
+ addSignal(this, signal);
+ }
+ onConnect(abort, context) {
+ const { res } = this;
+ if (this.reason) {
+ abort(this.reason);
+ return;
+ }
+ assert2(!res, "pipeline cannot be retried");
+ this.abort = abort;
+ this.context = context;
+ }
+ onHeaders(statusCode, rawHeaders, resume) {
+ const { opaque, handler, context } = this;
+ if (statusCode < 200) {
+ if (this.onInfo) {
+ const headers = this.responseHeaders === "raw" ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders);
+ this.onInfo({ statusCode, headers });
+ }
+ return;
+ }
+ this.res = new PipelineResponse(resume);
+ let body;
+ try {
+ this.handler = null;
+ const headers = this.responseHeaders === "raw" ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders);
+ body = this.runInAsyncScope(handler, null, {
+ statusCode,
+ headers,
+ opaque,
+ body: this.res,
+ context
+ });
+ } catch (err) {
+ this.res.on("error", noop3);
+ throw err;
+ }
+ if (!body || typeof body.on !== "function") {
+ throw new InvalidReturnValueError("expected Readable");
+ }
+ body.on("data", (chunk) => {
+ const { ret, body: body2 } = this;
+ if (!ret.push(chunk) && body2.pause) {
+ body2.pause();
+ }
+ }).on("error", (err) => {
+ const { ret } = this;
+ util.destroy(ret, err);
+ }).on("end", () => {
+ const { ret } = this;
+ ret.push(null);
+ }).on("close", () => {
+ const { ret } = this;
+ if (!ret._readableState.ended) {
+ util.destroy(ret, new RequestAbortedError());
+ }
+ });
+ this.body = body;
+ }
+ onData(chunk) {
+ const { res } = this;
+ return res.push(chunk);
+ }
+ onComplete(trailers) {
+ const { res } = this;
+ res.push(null);
+ }
+ onError(err) {
+ const { ret } = this;
+ this.handler = null;
+ util.destroy(ret, err);
+ }
+ };
+ function pipeline(opts, handler) {
+ try {
+ const pipelineHandler = new PipelineHandler(opts, handler);
+ this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler);
+ return pipelineHandler.ret;
+ } catch (err) {
+ return new PassThrough2().destroy(err);
+ }
+ }
+ __name(pipeline, "pipeline");
+ module2.exports = pipeline;
+ }
+});
+
+// node_modules/undici/lib/api/api-upgrade.js
+var require_api_upgrade = __commonJS({
+ "node_modules/undici/lib/api/api-upgrade.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { InvalidArgumentError, SocketError } = require_errors();
+ var { AsyncResource } = __require("node:async_hooks");
+ var assert2 = __require("node:assert");
+ var util = require_util();
+ var { kHTTP2Stream } = require_symbols();
+ var { addSignal, removeSignal } = require_abort_signal();
+ var UpgradeHandler = class extends AsyncResource {
+ static {
+ __name(this, "UpgradeHandler");
+ }
+ constructor(opts, callback) {
+ if (!opts || typeof opts !== "object") {
+ throw new InvalidArgumentError("invalid opts");
+ }
+ if (typeof callback !== "function") {
+ throw new InvalidArgumentError("invalid callback");
+ }
+ const { signal, opaque, responseHeaders } = opts;
+ if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") {
+ throw new InvalidArgumentError("signal must be an EventEmitter or EventTarget");
+ }
+ super("UNDICI_UPGRADE");
+ this.responseHeaders = responseHeaders || null;
+ this.opaque = opaque || null;
+ this.callback = callback;
+ this.abort = null;
+ this.context = null;
+ addSignal(this, signal);
+ }
+ onConnect(abort, context) {
+ if (this.reason) {
+ abort(this.reason);
+ return;
+ }
+ assert2(this.callback);
+ this.abort = abort;
+ this.context = null;
+ }
+ onHeaders() {
+ throw new SocketError("bad upgrade", null);
+ }
+ onUpgrade(statusCode, rawHeaders, socket) {
+ assert2(socket[kHTTP2Stream] === true ? statusCode === 200 : statusCode === 101);
+ const { callback, opaque, context } = this;
+ removeSignal(this);
+ this.callback = null;
+ const headers = this.responseHeaders === "raw" ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders);
+ this.runInAsyncScope(callback, null, null, {
+ headers,
+ socket,
+ opaque,
+ context
+ });
+ }
+ onError(err) {
+ const { callback, opaque } = this;
+ removeSignal(this);
+ if (callback) {
+ this.callback = null;
+ queueMicrotask(() => {
+ this.runInAsyncScope(callback, null, err, { opaque });
+ });
+ }
+ }
+ };
+ function upgrade(opts, callback) {
+ if (callback === void 0) {
+ return new Promise((resolve16, reject) => {
+ upgrade.call(this, opts, (err, data) => {
+ return err ? reject(err) : resolve16(data);
+ });
+ });
+ }
+ try {
+ const upgradeHandler = new UpgradeHandler(opts, callback);
+ const upgradeOpts = {
+ ...opts,
+ method: opts.method || "GET",
+ upgrade: opts.protocol || "Websocket"
+ };
+ this.dispatch(upgradeOpts, upgradeHandler);
+ } catch (err) {
+ if (typeof callback !== "function") {
+ throw err;
+ }
+ const opaque = opts?.opaque;
+ queueMicrotask(() => callback(err, { opaque }));
+ }
+ }
+ __name(upgrade, "upgrade");
+ module2.exports = upgrade;
+ }
+});
+
+// node_modules/undici/lib/api/api-connect.js
+var require_api_connect = __commonJS({
+ "node_modules/undici/lib/api/api-connect.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var assert2 = __require("node:assert");
+ var { AsyncResource } = __require("node:async_hooks");
+ var { InvalidArgumentError, SocketError } = require_errors();
+ var util = require_util();
+ var { addSignal, removeSignal } = require_abort_signal();
+ var ConnectHandler = class extends AsyncResource {
+ static {
+ __name(this, "ConnectHandler");
+ }
+ constructor(opts, callback) {
+ if (!opts || typeof opts !== "object") {
+ throw new InvalidArgumentError("invalid opts");
+ }
+ if (typeof callback !== "function") {
+ throw new InvalidArgumentError("invalid callback");
+ }
+ const { signal, opaque, responseHeaders } = opts;
+ if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") {
+ throw new InvalidArgumentError("signal must be an EventEmitter or EventTarget");
+ }
+ super("UNDICI_CONNECT");
+ this.opaque = opaque || null;
+ this.responseHeaders = responseHeaders || null;
+ this.callback = callback;
+ this.abort = null;
+ addSignal(this, signal);
+ }
+ onConnect(abort, context) {
+ if (this.reason) {
+ abort(this.reason);
+ return;
+ }
+ assert2(this.callback);
+ this.abort = abort;
+ this.context = context;
+ }
+ onHeaders() {
+ throw new SocketError("bad connect", null);
+ }
+ onUpgrade(statusCode, rawHeaders, socket) {
+ const { callback, opaque, context } = this;
+ removeSignal(this);
+ this.callback = null;
+ let headers = rawHeaders;
+ if (headers != null) {
+ headers = this.responseHeaders === "raw" ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders);
+ }
+ this.runInAsyncScope(callback, null, null, {
+ statusCode,
+ headers,
+ socket,
+ opaque,
+ context
+ });
+ }
+ onError(err) {
+ const { callback, opaque } = this;
+ removeSignal(this);
+ if (callback) {
+ this.callback = null;
+ queueMicrotask(() => {
+ this.runInAsyncScope(callback, null, err, { opaque });
+ });
+ }
+ }
+ };
+ function connect(opts, callback) {
+ if (callback === void 0) {
+ return new Promise((resolve16, reject) => {
+ connect.call(this, opts, (err, data) => {
+ return err ? reject(err) : resolve16(data);
+ });
+ });
+ }
+ try {
+ const connectHandler = new ConnectHandler(opts, callback);
+ const connectOptions = { ...opts, method: "CONNECT" };
+ this.dispatch(connectOptions, connectHandler);
+ } catch (err) {
+ if (typeof callback !== "function") {
+ throw err;
+ }
+ const opaque = opts?.opaque;
+ queueMicrotask(() => callback(err, { opaque }));
+ }
+ }
+ __name(connect, "connect");
+ module2.exports = connect;
+ }
+});
+
+// node_modules/undici/lib/api/index.js
+var require_api = __commonJS({
+ "node_modules/undici/lib/api/index.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ module2.exports.request = require_api_request();
+ module2.exports.stream = require_api_stream();
+ module2.exports.pipeline = require_api_pipeline();
+ module2.exports.upgrade = require_api_upgrade();
+ module2.exports.connect = require_api_connect();
+ }
+});
+
+// node_modules/undici/lib/mock/mock-errors.js
+var require_mock_errors = __commonJS({
+ "node_modules/undici/lib/mock/mock-errors.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { UndiciError } = require_errors();
+ var kMockNotMatchedError = /* @__PURE__ */ Symbol.for("undici.error.UND_MOCK_ERR_MOCK_NOT_MATCHED");
+ var MockNotMatchedError = class extends UndiciError {
+ static {
+ __name(this, "MockNotMatchedError");
+ }
+ constructor(message) {
+ super(message);
+ this.name = "MockNotMatchedError";
+ this.message = message || "The request does not match any registered mock dispatches";
+ this.code = "UND_MOCK_ERR_MOCK_NOT_MATCHED";
+ }
+ static [Symbol.hasInstance](instance) {
+ return instance && instance[kMockNotMatchedError] === true;
+ }
+ get [kMockNotMatchedError]() {
+ return true;
+ }
+ };
+ module2.exports = {
+ MockNotMatchedError
+ };
+ }
+});
+
+// node_modules/undici/lib/mock/mock-symbols.js
+var require_mock_symbols = __commonJS({
+ "node_modules/undici/lib/mock/mock-symbols.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ module2.exports = {
+ kAgent: /* @__PURE__ */ Symbol("agent"),
+ kOptions: /* @__PURE__ */ Symbol("options"),
+ kFactory: /* @__PURE__ */ Symbol("factory"),
+ kDispatches: /* @__PURE__ */ Symbol("dispatches"),
+ kDispatchKey: /* @__PURE__ */ Symbol("dispatch key"),
+ kDefaultHeaders: /* @__PURE__ */ Symbol("default headers"),
+ kDefaultTrailers: /* @__PURE__ */ Symbol("default trailers"),
+ kContentLength: /* @__PURE__ */ Symbol("content length"),
+ kMockAgent: /* @__PURE__ */ Symbol("mock agent"),
+ kMockAgentSet: /* @__PURE__ */ Symbol("mock agent set"),
+ kMockAgentGet: /* @__PURE__ */ Symbol("mock agent get"),
+ kMockDispatch: /* @__PURE__ */ Symbol("mock dispatch"),
+ kClose: /* @__PURE__ */ Symbol("close"),
+ kOriginalClose: /* @__PURE__ */ Symbol("original agent close"),
+ kOriginalDispatch: /* @__PURE__ */ Symbol("original dispatch"),
+ kOrigin: /* @__PURE__ */ Symbol("origin"),
+ kIsMockActive: /* @__PURE__ */ Symbol("is mock active"),
+ kNetConnect: /* @__PURE__ */ Symbol("net connect"),
+ kGetNetConnect: /* @__PURE__ */ Symbol("get net connect"),
+ kConnected: /* @__PURE__ */ Symbol("connected"),
+ kIgnoreTrailingSlash: /* @__PURE__ */ Symbol("ignore trailing slash"),
+ kMockAgentMockCallHistoryInstance: /* @__PURE__ */ Symbol("mock agent mock call history name"),
+ kMockAgentRegisterCallHistory: /* @__PURE__ */ Symbol("mock agent register mock call history"),
+ kMockAgentAddCallHistoryLog: /* @__PURE__ */ Symbol("mock agent add call history log"),
+ kMockAgentIsCallHistoryEnabled: /* @__PURE__ */ Symbol("mock agent is call history enabled"),
+ kMockAgentAcceptsNonStandardSearchParameters: /* @__PURE__ */ Symbol("mock agent accepts non standard search parameters"),
+ kMockCallHistoryAddLog: /* @__PURE__ */ Symbol("mock call history add log"),
+ kTotalDispatchCount: /* @__PURE__ */ Symbol("total dispatch count")
+ };
+ }
+});
+
+// node_modules/undici/lib/mock/mock-utils.js
+var require_mock_utils = __commonJS({
+ "node_modules/undici/lib/mock/mock-utils.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { MockNotMatchedError } = require_mock_errors();
+ var {
+ kDispatches,
+ kMockAgent,
+ kOriginalDispatch,
+ kOrigin,
+ kGetNetConnect,
+ kTotalDispatchCount
+ } = require_mock_symbols();
+ var { serializePathWithQuery } = require_util();
+ var { STATUS_CODES } = __require("node:http");
+ var {
+ types: {
+ isPromise: isPromise2
+ }
+ } = __require("node:util");
+ var { InvalidArgumentError } = require_errors();
+ function matchValue(match, value) {
+ if (typeof match === "string") {
+ return match === value;
+ }
+ if (match instanceof RegExp) {
+ return match.test(value);
+ }
+ if (typeof match === "function") {
+ return match(value) === true;
+ }
+ return false;
+ }
+ __name(matchValue, "matchValue");
+ function lowerCaseEntries(headers) {
+ return Object.fromEntries(
+ Object.entries(headers).map(([headerName, headerValue]) => {
+ return [headerName.toLocaleLowerCase(), headerValue];
+ })
+ );
+ }
+ __name(lowerCaseEntries, "lowerCaseEntries");
+ function getHeaderByName(headers, key) {
+ if (Array.isArray(headers)) {
+ for (let i = 0; i < headers.length; i += 2) {
+ if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) {
+ return headers[i + 1];
+ }
+ }
+ return void 0;
+ } else if (typeof headers.get === "function") {
+ return headers.get(key);
+ } else {
+ return lowerCaseEntries(headers)[key.toLocaleLowerCase()];
+ }
+ }
+ __name(getHeaderByName, "getHeaderByName");
+ function buildHeadersFromArray(headers) {
+ const clone2 = headers.slice();
+ const entries = [];
+ for (let index = 0; index < clone2.length; index += 2) {
+ entries.push([clone2[index], clone2[index + 1]]);
+ }
+ return Object.fromEntries(entries);
+ }
+ __name(buildHeadersFromArray, "buildHeadersFromArray");
+ function matchHeaders(mockDispatch2, headers) {
+ if (typeof mockDispatch2.headers === "function") {
+ if (Array.isArray(headers)) {
+ headers = buildHeadersFromArray(headers);
+ }
+ return mockDispatch2.headers(headers ? lowerCaseEntries(headers) : {});
+ }
+ if (typeof mockDispatch2.headers === "undefined") {
+ return true;
+ }
+ if (typeof headers !== "object" || typeof mockDispatch2.headers !== "object") {
+ return false;
+ }
+ for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch2.headers)) {
+ const headerValue = getHeaderByName(headers, matchHeaderName);
+ if (!matchValue(matchHeaderValue, headerValue)) {
+ return false;
+ }
+ }
+ return true;
+ }
+ __name(matchHeaders, "matchHeaders");
+ function normalizeSearchParams(query) {
+ if (typeof query !== "string") {
+ return query;
+ }
+ const originalQp = new URLSearchParams(query);
+ const normalizedQp = new URLSearchParams();
+ for (let [key, value] of originalQp.entries()) {
+ key = key.replace("[]", "");
+ const valueRepresentsString = /^(['"]).*\1$/.test(value);
+ if (valueRepresentsString) {
+ normalizedQp.append(key, value);
+ continue;
+ }
+ if (value.includes(",")) {
+ const values = value.split(",");
+ for (const v of values) {
+ normalizedQp.append(key, v);
+ }
+ continue;
+ }
+ normalizedQp.append(key, value);
+ }
+ return normalizedQp;
+ }
+ __name(normalizeSearchParams, "normalizeSearchParams");
+ function safeUrl(path27) {
+ if (typeof path27 !== "string") {
+ return path27;
+ }
+ const pathSegments = path27.split("?", 3);
+ if (pathSegments.length !== 2) {
+ return path27;
+ }
+ const qp = new URLSearchParams(pathSegments.pop());
+ qp.sort();
+ return [...pathSegments, qp.toString()].join("?");
+ }
+ __name(safeUrl, "safeUrl");
+ function matchKey(mockDispatch2, { path: path27, method, body, headers }) {
+ const pathMatch = matchValue(mockDispatch2.path, path27);
+ const methodMatch = matchValue(mockDispatch2.method, method);
+ const bodyMatch = typeof mockDispatch2.body !== "undefined" ? matchValue(mockDispatch2.body, body) : true;
+ const headersMatch = matchHeaders(mockDispatch2, headers);
+ return pathMatch && methodMatch && bodyMatch && headersMatch;
+ }
+ __name(matchKey, "matchKey");
+ function getResponseData(data) {
+ if (Buffer.isBuffer(data)) {
+ return data;
+ } else if (data instanceof Uint8Array) {
+ return data;
+ } else if (data instanceof ArrayBuffer) {
+ return data;
+ } else if (typeof data === "object") {
+ return JSON.stringify(data);
+ } else if (data) {
+ return data.toString();
+ } else {
+ return "";
+ }
+ }
+ __name(getResponseData, "getResponseData");
+ function getMockDispatch(mockDispatches, key) {
+ const basePath = key.query ? serializePathWithQuery(key.path, key.query) : key.path;
+ const resolvedPath = typeof basePath === "string" ? safeUrl(basePath) : basePath;
+ const resolvedPathWithoutTrailingSlash = removeTrailingSlash(resolvedPath);
+ let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path27, ignoreTrailingSlash }) => {
+ return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path27)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path27), resolvedPath);
+ });
+ if (matchedMockDispatches.length === 0) {
+ throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`);
+ }
+ matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method));
+ if (matchedMockDispatches.length === 0) {
+ throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}' on path '${resolvedPath}'`);
+ }
+ matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== "undefined" ? matchValue(body, key.body) : true);
+ if (matchedMockDispatches.length === 0) {
+ throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}' on path '${resolvedPath}'`);
+ }
+ matchedMockDispatches = matchedMockDispatches.filter((mockDispatch2) => matchHeaders(mockDispatch2, key.headers));
+ if (matchedMockDispatches.length === 0) {
+ const headers = typeof key.headers === "object" ? JSON.stringify(key.headers) : key.headers;
+ throw new MockNotMatchedError(`Mock dispatch not matched for headers '${headers}' on path '${resolvedPath}'`);
+ }
+ return matchedMockDispatches[0];
+ }
+ __name(getMockDispatch, "getMockDispatch");
+ function addMockDispatch(mockDispatches, key, data, opts) {
+ const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false, ...opts };
+ const replyData = typeof data === "function" ? { callback: data } : { ...data };
+ const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } };
+ mockDispatches.push(newMockDispatch);
+ mockDispatches[kTotalDispatchCount] = (mockDispatches[kTotalDispatchCount] || 0) + 1;
+ return newMockDispatch;
+ }
+ __name(addMockDispatch, "addMockDispatch");
+ function deleteMockDispatch(mockDispatches, key) {
+ const index = mockDispatches.findIndex((dispatch) => {
+ if (!dispatch.consumed) {
+ return false;
+ }
+ return matchKey(dispatch, key);
+ });
+ if (index !== -1) {
+ mockDispatches.splice(index, 1);
+ }
+ }
+ __name(deleteMockDispatch, "deleteMockDispatch");
+ function removeTrailingSlash(path27) {
+ while (path27.endsWith("/")) {
+ path27 = path27.slice(0, -1);
+ }
+ if (path27.length === 0) {
+ path27 = "/";
+ }
+ return path27;
+ }
+ __name(removeTrailingSlash, "removeTrailingSlash");
+ function buildKey(opts) {
+ const { path: path27, method, body, headers, query } = opts;
+ return {
+ path: path27,
+ method,
+ body,
+ headers,
+ query
+ };
+ }
+ __name(buildKey, "buildKey");
+ function generateKeyValues(data) {
+ const keys = Object.keys(data);
+ const result = [];
+ for (let i = 0; i < keys.length; ++i) {
+ const key = keys[i];
+ const value = data[key];
+ const name = Buffer.from(`${key}`);
+ if (Array.isArray(value)) {
+ for (let j = 0; j < value.length; ++j) {
+ result.push(name, Buffer.from(`${value[j]}`));
+ }
+ } else {
+ result.push(name, Buffer.from(`${value}`));
+ }
+ }
+ return result;
+ }
+ __name(generateKeyValues, "generateKeyValues");
+ function getStatusText(statusCode) {
+ return STATUS_CODES[statusCode] || "unknown";
+ }
+ __name(getStatusText, "getStatusText");
+ async function getResponse(body) {
+ const buffers = [];
+ for await (const data of body) {
+ buffers.push(data);
+ }
+ return Buffer.concat(buffers).toString("utf8");
+ }
+ __name(getResponse, "getResponse");
+ function mockDispatch(opts, handler) {
+ const key = buildKey(opts);
+ const mockDispatch2 = getMockDispatch(this[kDispatches], key);
+ mockDispatch2.timesInvoked++;
+ if (mockDispatch2.data.callback) {
+ mockDispatch2.data = { ...mockDispatch2.data, ...mockDispatch2.data.callback(opts) };
+ }
+ const { data: { statusCode, data, headers, trailers, error: error51 }, delay, persist } = mockDispatch2;
+ const { timesInvoked, times } = mockDispatch2;
+ mockDispatch2.consumed = !persist && timesInvoked >= times;
+ mockDispatch2.pending = timesInvoked < times;
+ if (error51 !== null) {
+ deleteMockDispatch(this[kDispatches], key);
+ handler.onError(error51);
+ return true;
+ }
+ let aborted2 = false;
+ let timer = null;
+ function abort(err) {
+ if (aborted2) {
+ return;
+ }
+ aborted2 = true;
+ if (timer !== null) {
+ clearTimeout(timer);
+ timer = null;
+ }
+ handler.onError(err);
+ }
+ __name(abort, "abort");
+ handler.onConnect?.(abort, null);
+ if (typeof delay === "number" && delay > 0) {
+ timer = setTimeout(() => {
+ timer = null;
+ handleReply(this[kDispatches]);
+ }, delay);
+ } else {
+ handleReply(this[kDispatches]);
+ }
+ function handleReply(mockDispatches, _data = data) {
+ if (aborted2) {
+ return;
+ }
+ const optsHeaders = Array.isArray(opts.headers) ? buildHeadersFromArray(opts.headers) : opts.headers;
+ const body = typeof _data === "function" ? _data({ ...opts, headers: optsHeaders }) : _data;
+ if (isPromise2(body)) {
+ return body.then((newData) => handleReply(mockDispatches, newData));
+ }
+ if (aborted2) {
+ return;
+ }
+ const responseData = getResponseData(body);
+ const responseHeaders = generateKeyValues(headers);
+ const responseTrailers = generateKeyValues(trailers);
+ handler.onHeaders?.(statusCode, responseHeaders, resume, getStatusText(statusCode));
+ handler.onData?.(Buffer.from(responseData));
+ handler.onComplete?.(responseTrailers);
+ deleteMockDispatch(mockDispatches, key);
+ }
+ __name(handleReply, "handleReply");
+ function resume() {
+ }
+ __name(resume, "resume");
+ return true;
+ }
+ __name(mockDispatch, "mockDispatch");
+ function buildMockDispatch() {
+ const agent = this[kMockAgent];
+ const origin = this[kOrigin];
+ const originalDispatch = this[kOriginalDispatch];
+ return /* @__PURE__ */ __name(function dispatch(opts, handler) {
+ if (agent.isMockActive) {
+ try {
+ mockDispatch.call(this, opts, handler);
+ } catch (error51) {
+ if (error51.code === "UND_MOCK_ERR_MOCK_NOT_MATCHED") {
+ const netConnect = agent[kGetNetConnect]();
+ const totalInterceptsCount = this[kDispatches][kTotalDispatchCount] || this[kDispatches].length;
+ const pendingInterceptsCount = this[kDispatches].filter(({ consumed }) => !consumed).length;
+ const interceptsMessage = `, ${pendingInterceptsCount} interceptor(s) remaining out of ${totalInterceptsCount} defined`;
+ if (netConnect === false) {
+ throw new MockNotMatchedError(`${error51.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)${interceptsMessage}`);
+ }
+ if (checkNetConnect(netConnect, origin)) {
+ originalDispatch.call(this, opts, handler);
+ } else {
+ throw new MockNotMatchedError(`${error51.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)${interceptsMessage}`);
+ }
+ } else {
+ throw error51;
+ }
+ }
+ } else {
+ originalDispatch.call(this, opts, handler);
+ }
+ }, "dispatch");
+ }
+ __name(buildMockDispatch, "buildMockDispatch");
+ function checkNetConnect(netConnect, origin) {
+ const url2 = new URL(origin);
+ if (netConnect === true) {
+ return true;
+ } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url2.host))) {
+ return true;
+ }
+ return false;
+ }
+ __name(checkNetConnect, "checkNetConnect");
+ function normalizeOrigin(origin) {
+ if (typeof origin !== "string" && !(origin instanceof URL)) {
+ return origin;
+ }
+ if (origin instanceof URL) {
+ return origin.origin;
+ }
+ return origin.toLowerCase();
+ }
+ __name(normalizeOrigin, "normalizeOrigin");
+ function buildAndValidateMockOptions(opts) {
+ const { agent, ...mockOptions } = opts;
+ if ("enableCallHistory" in mockOptions && typeof mockOptions.enableCallHistory !== "boolean") {
+ throw new InvalidArgumentError("options.enableCallHistory must to be a boolean");
+ }
+ if ("acceptNonStandardSearchParameters" in mockOptions && typeof mockOptions.acceptNonStandardSearchParameters !== "boolean") {
+ throw new InvalidArgumentError("options.acceptNonStandardSearchParameters must to be a boolean");
+ }
+ if ("ignoreTrailingSlash" in mockOptions && typeof mockOptions.ignoreTrailingSlash !== "boolean") {
+ throw new InvalidArgumentError("options.ignoreTrailingSlash must to be a boolean");
+ }
+ return mockOptions;
+ }
+ __name(buildAndValidateMockOptions, "buildAndValidateMockOptions");
+ module2.exports = {
+ getResponseData,
+ getMockDispatch,
+ addMockDispatch,
+ deleteMockDispatch,
+ buildKey,
+ generateKeyValues,
+ matchValue,
+ getResponse,
+ getStatusText,
+ mockDispatch,
+ buildMockDispatch,
+ checkNetConnect,
+ buildAndValidateMockOptions,
+ getHeaderByName,
+ buildHeadersFromArray,
+ normalizeSearchParams,
+ normalizeOrigin
+ };
+ }
+});
+
+// node_modules/undici/lib/mock/mock-interceptor.js
+var require_mock_interceptor = __commonJS({
+ "node_modules/undici/lib/mock/mock-interceptor.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { getResponseData, buildKey, addMockDispatch } = require_mock_utils();
+ var {
+ kDispatches,
+ kDispatchKey,
+ kDefaultHeaders,
+ kDefaultTrailers,
+ kContentLength,
+ kMockDispatch,
+ kIgnoreTrailingSlash
+ } = require_mock_symbols();
+ var { InvalidArgumentError } = require_errors();
+ var { serializePathWithQuery } = require_util();
+ var MockScope = class {
+ static {
+ __name(this, "MockScope");
+ }
+ constructor(mockDispatch) {
+ this[kMockDispatch] = mockDispatch;
+ }
+ /**
+ * Delay a reply by a set amount in ms.
+ */
+ delay(waitInMs) {
+ if (typeof waitInMs !== "number" || !Number.isInteger(waitInMs) || waitInMs <= 0) {
+ throw new InvalidArgumentError("waitInMs must be a valid integer > 0");
+ }
+ this[kMockDispatch].delay = waitInMs;
+ return this;
+ }
+ /**
+ * For a defined reply, never mark as consumed.
+ */
+ persist() {
+ this[kMockDispatch].persist = true;
+ return this;
+ }
+ /**
+ * Allow one to define a reply for a set amount of matching requests.
+ */
+ times(repeatTimes) {
+ if (typeof repeatTimes !== "number" || !Number.isInteger(repeatTimes) || repeatTimes <= 0) {
+ throw new InvalidArgumentError("repeatTimes must be a valid integer > 0");
+ }
+ this[kMockDispatch].times = repeatTimes;
+ return this;
+ }
+ };
+ var MockInterceptor = class {
+ static {
+ __name(this, "MockInterceptor");
+ }
+ constructor(opts, mockDispatches) {
+ if (typeof opts !== "object") {
+ throw new InvalidArgumentError("opts must be an object");
+ }
+ if (typeof opts.path === "undefined") {
+ throw new InvalidArgumentError("opts.path must be defined");
+ }
+ if (typeof opts.method === "undefined") {
+ opts.method = "GET";
+ }
+ if (typeof opts.path === "string") {
+ if (opts.query) {
+ opts.path = serializePathWithQuery(opts.path, opts.query);
+ } else {
+ const parsedURL = new URL(opts.path, "data://");
+ opts.path = parsedURL.pathname + parsedURL.search;
+ }
+ }
+ if (typeof opts.method === "string") {
+ opts.method = opts.method.toUpperCase();
+ }
+ this[kDispatchKey] = buildKey(opts);
+ this[kDispatches] = mockDispatches;
+ this[kIgnoreTrailingSlash] = opts.ignoreTrailingSlash ?? false;
+ this[kDefaultHeaders] = {};
+ this[kDefaultTrailers] = {};
+ this[kContentLength] = false;
+ }
+ createMockScopeDispatchData({ statusCode, data, responseOptions }) {
+ const responseData = getResponseData(data);
+ const contentLength = this[kContentLength] ? { "content-length": responseData.length } : {};
+ const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers };
+ const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers };
+ return { statusCode, data, headers, trailers };
+ }
+ validateReplyParameters(replyParameters) {
+ if (typeof replyParameters.statusCode === "undefined") {
+ throw new InvalidArgumentError("statusCode must be defined");
+ }
+ if (typeof replyParameters.responseOptions !== "object" || replyParameters.responseOptions === null) {
+ throw new InvalidArgumentError("responseOptions must be an object");
+ }
+ }
+ /**
+ * Mock an undici request with a defined reply.
+ */
+ reply(replyOptionsCallbackOrStatusCode) {
+ if (typeof replyOptionsCallbackOrStatusCode === "function") {
+ const wrappedDefaultsCallback = /* @__PURE__ */ __name((opts) => {
+ const resolvedData = replyOptionsCallbackOrStatusCode(opts);
+ if (typeof resolvedData !== "object" || resolvedData === null) {
+ throw new InvalidArgumentError("reply options callback must return an object");
+ }
+ const replyParameters2 = { data: "", responseOptions: {}, ...resolvedData };
+ this.validateReplyParameters(replyParameters2);
+ return {
+ ...this.createMockScopeDispatchData(replyParameters2)
+ };
+ }, "wrappedDefaultsCallback");
+ const newMockDispatch2 = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback, { ignoreTrailingSlash: this[kIgnoreTrailingSlash] });
+ return new MockScope(newMockDispatch2);
+ }
+ const replyParameters = {
+ statusCode: replyOptionsCallbackOrStatusCode,
+ data: arguments[1] === void 0 ? "" : arguments[1],
+ responseOptions: arguments[2] === void 0 ? {} : arguments[2]
+ };
+ this.validateReplyParameters(replyParameters);
+ const dispatchData = this.createMockScopeDispatchData(replyParameters);
+ const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData, { ignoreTrailingSlash: this[kIgnoreTrailingSlash] });
+ return new MockScope(newMockDispatch);
+ }
+ /**
+ * Mock an undici request with a defined error.
+ */
+ replyWithError(error51) {
+ if (typeof error51 === "undefined") {
+ throw new InvalidArgumentError("error must be defined");
+ }
+ const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error: error51 }, { ignoreTrailingSlash: this[kIgnoreTrailingSlash] });
+ return new MockScope(newMockDispatch);
+ }
+ /**
+ * Set default reply headers on the interceptor for subsequent replies
+ */
+ defaultReplyHeaders(headers) {
+ if (typeof headers === "undefined") {
+ throw new InvalidArgumentError("headers must be defined");
+ }
+ this[kDefaultHeaders] = headers;
+ return this;
+ }
+ /**
+ * Set default reply trailers on the interceptor for subsequent replies
+ */
+ defaultReplyTrailers(trailers) {
+ if (typeof trailers === "undefined") {
+ throw new InvalidArgumentError("trailers must be defined");
+ }
+ this[kDefaultTrailers] = trailers;
+ return this;
+ }
+ /**
+ * Set reply content length header for replies on the interceptor
+ */
+ replyContentLength() {
+ this[kContentLength] = true;
+ return this;
+ }
+ };
+ module2.exports.MockInterceptor = MockInterceptor;
+ module2.exports.MockScope = MockScope;
+ }
+});
+
+// node_modules/undici/lib/mock/mock-client.js
+var require_mock_client = __commonJS({
+ "node_modules/undici/lib/mock/mock-client.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { promisify: promisify2 } = __require("node:util");
+ var Client = require_client();
+ var { buildMockDispatch } = require_mock_utils();
+ var {
+ kDispatches,
+ kMockAgent,
+ kClose,
+ kOriginalClose,
+ kOrigin,
+ kOriginalDispatch,
+ kConnected,
+ kIgnoreTrailingSlash
+ } = require_mock_symbols();
+ var { MockInterceptor } = require_mock_interceptor();
+ var Symbols = require_symbols();
+ var { InvalidArgumentError } = require_errors();
+ var MockClient = class extends Client {
+ static {
+ __name(this, "MockClient");
+ }
+ constructor(origin, opts) {
+ if (!opts || !opts.agent || typeof opts.agent.dispatch !== "function") {
+ throw new InvalidArgumentError("Argument opts.agent must implement Agent");
+ }
+ super(origin, opts);
+ this[kMockAgent] = opts.agent;
+ this[kOrigin] = origin;
+ this[kIgnoreTrailingSlash] = opts.ignoreTrailingSlash ?? false;
+ this[kDispatches] = [];
+ this[kConnected] = 1;
+ this[kOriginalDispatch] = this.dispatch;
+ this[kOriginalClose] = this.close.bind(this);
+ this.dispatch = buildMockDispatch.call(this);
+ this.close = this[kClose];
+ }
+ get [Symbols.kConnected]() {
+ return this[kConnected];
+ }
+ /**
+ * Sets up the base interceptor for mocking replies from undici.
+ */
+ intercept(opts) {
+ return new MockInterceptor(
+ opts && { ignoreTrailingSlash: this[kIgnoreTrailingSlash], ...opts },
+ this[kDispatches]
+ );
+ }
+ cleanMocks() {
+ this[kDispatches] = [];
+ }
+ async [kClose]() {
+ await promisify2(this[kOriginalClose])();
+ this[kConnected] = 0;
+ this[kMockAgent][Symbols.kClients].delete(this[kOrigin]);
+ }
+ };
+ module2.exports = MockClient;
+ }
+});
+
+// node_modules/undici/lib/mock/mock-call-history.js
+var require_mock_call_history = __commonJS({
+ "node_modules/undici/lib/mock/mock-call-history.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { kMockCallHistoryAddLog } = require_mock_symbols();
+ var { InvalidArgumentError } = require_errors();
+ function handleFilterCallsWithOptions(criteria, options2, handler, store, allLogs) {
+ switch (options2.operator) {
+ case "OR":
+ store.push(...handler(criteria, allLogs));
+ return store;
+ case "AND":
+ return handler(criteria, store);
+ default:
+ throw new InvalidArgumentError("options.operator must to be a case insensitive string equal to 'OR' or 'AND'");
+ }
+ }
+ __name(handleFilterCallsWithOptions, "handleFilterCallsWithOptions");
+ function buildAndValidateFilterCallsOptions(options2 = {}) {
+ const finalOptions = {};
+ if ("operator" in options2) {
+ if (typeof options2.operator !== "string" || options2.operator.toUpperCase() !== "OR" && options2.operator.toUpperCase() !== "AND") {
+ throw new InvalidArgumentError("options.operator must to be a case insensitive string equal to 'OR' or 'AND'");
+ }
+ return {
+ ...finalOptions,
+ operator: options2.operator.toUpperCase()
+ };
+ }
+ return finalOptions;
+ }
+ __name(buildAndValidateFilterCallsOptions, "buildAndValidateFilterCallsOptions");
+ function makeFilterCalls(parameterName) {
+ return (parameterValue, logs) => {
+ if (typeof parameterValue === "string" || parameterValue == null) {
+ return logs.filter((log) => {
+ return log[parameterName] === parameterValue;
+ });
+ }
+ if (parameterValue instanceof RegExp) {
+ return logs.filter((log) => {
+ return parameterValue.test(log[parameterName]);
+ });
+ }
+ throw new InvalidArgumentError(`${parameterName} parameter should be one of string, regexp, undefined or null`);
+ };
+ }
+ __name(makeFilterCalls, "makeFilterCalls");
+ function computeUrlWithMaybeSearchParameters(requestInit) {
+ try {
+ const url2 = new URL(requestInit.path, requestInit.origin);
+ if (url2.search.length !== 0) {
+ return url2;
+ }
+ url2.search = new URLSearchParams(requestInit.query).toString();
+ return url2;
+ } catch (error51) {
+ throw new InvalidArgumentError("An error occurred when computing MockCallHistoryLog.url", { cause: error51 });
+ }
+ }
+ __name(computeUrlWithMaybeSearchParameters, "computeUrlWithMaybeSearchParameters");
+ var MockCallHistoryLog = class {
+ static {
+ __name(this, "MockCallHistoryLog");
+ }
+ constructor(requestInit = {}) {
+ this.body = requestInit.body;
+ this.headers = requestInit.headers;
+ this.method = requestInit.method;
+ const url2 = computeUrlWithMaybeSearchParameters(requestInit);
+ this.fullUrl = url2.toString();
+ this.origin = url2.origin;
+ this.path = url2.pathname;
+ this.searchParams = Object.fromEntries(url2.searchParams);
+ this.protocol = url2.protocol;
+ this.host = url2.host;
+ this.port = url2.port;
+ this.hash = url2.hash;
+ }
+ toMap() {
+ return /* @__PURE__ */ new Map(
+ [
+ ["protocol", this.protocol],
+ ["host", this.host],
+ ["port", this.port],
+ ["origin", this.origin],
+ ["path", this.path],
+ ["hash", this.hash],
+ ["searchParams", this.searchParams],
+ ["fullUrl", this.fullUrl],
+ ["method", this.method],
+ ["body", this.body],
+ ["headers", this.headers]
+ ]
+ );
+ }
+ toString() {
+ const options2 = { betweenKeyValueSeparator: "->", betweenPairSeparator: "|" };
+ let result = "";
+ this.toMap().forEach((value, key) => {
+ if (typeof value === "string" || value === void 0 || value === null) {
+ result = `${result}${key}${options2.betweenKeyValueSeparator}${value}${options2.betweenPairSeparator}`;
+ }
+ if (typeof value === "object" && value !== null || Array.isArray(value)) {
+ result = `${result}${key}${options2.betweenKeyValueSeparator}${JSON.stringify(value)}${options2.betweenPairSeparator}`;
+ }
+ });
+ return result.slice(0, -1);
+ }
+ };
+ var MockCallHistory = class {
+ static {
+ __name(this, "MockCallHistory");
+ }
+ logs = [];
+ calls() {
+ return this.logs;
+ }
+ firstCall() {
+ return this.logs.at(0);
+ }
+ lastCall() {
+ return this.logs.at(-1);
+ }
+ nthCall(number4) {
+ if (typeof number4 !== "number") {
+ throw new InvalidArgumentError("nthCall must be called with a number");
+ }
+ if (!Number.isInteger(number4)) {
+ throw new InvalidArgumentError("nthCall must be called with an integer");
+ }
+ if (Math.sign(number4) !== 1) {
+ throw new InvalidArgumentError("nthCall must be called with a positive value. use firstCall or lastCall instead");
+ }
+ return this.logs.at(number4 - 1);
+ }
+ filterCalls(criteria, options2) {
+ if (this.logs.length === 0) {
+ return this.logs;
+ }
+ if (typeof criteria === "function") {
+ return this.logs.filter(criteria);
+ }
+ if (criteria instanceof RegExp) {
+ return this.logs.filter((log) => {
+ return criteria.test(log.toString());
+ });
+ }
+ if (typeof criteria === "object" && criteria !== null) {
+ if (Object.keys(criteria).length === 0) {
+ return this.logs;
+ }
+ const finalOptions = { operator: "OR", ...buildAndValidateFilterCallsOptions(options2) };
+ let maybeDuplicatedLogsFiltered = finalOptions.operator === "AND" ? this.logs : [];
+ if ("protocol" in criteria) {
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.protocol, finalOptions, this.filterCallsByProtocol, maybeDuplicatedLogsFiltered, this.logs);
+ }
+ if ("host" in criteria) {
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.host, finalOptions, this.filterCallsByHost, maybeDuplicatedLogsFiltered, this.logs);
+ }
+ if ("port" in criteria) {
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.port, finalOptions, this.filterCallsByPort, maybeDuplicatedLogsFiltered, this.logs);
+ }
+ if ("origin" in criteria) {
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.origin, finalOptions, this.filterCallsByOrigin, maybeDuplicatedLogsFiltered, this.logs);
+ }
+ if ("path" in criteria) {
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.path, finalOptions, this.filterCallsByPath, maybeDuplicatedLogsFiltered, this.logs);
+ }
+ if ("hash" in criteria) {
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.hash, finalOptions, this.filterCallsByHash, maybeDuplicatedLogsFiltered, this.logs);
+ }
+ if ("fullUrl" in criteria) {
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.fullUrl, finalOptions, this.filterCallsByFullUrl, maybeDuplicatedLogsFiltered, this.logs);
+ }
+ if ("method" in criteria) {
+ maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.method, finalOptions, this.filterCallsByMethod, maybeDuplicatedLogsFiltered, this.logs);
+ }
+ const uniqLogsFiltered = [...new Set(maybeDuplicatedLogsFiltered)];
+ return uniqLogsFiltered;
+ }
+ throw new InvalidArgumentError("criteria parameter should be one of function, regexp, or object");
+ }
+ filterCallsByProtocol = makeFilterCalls.call(this, "protocol");
+ filterCallsByHost = makeFilterCalls.call(this, "host");
+ filterCallsByPort = makeFilterCalls.call(this, "port");
+ filterCallsByOrigin = makeFilterCalls.call(this, "origin");
+ filterCallsByPath = makeFilterCalls.call(this, "path");
+ filterCallsByHash = makeFilterCalls.call(this, "hash");
+ filterCallsByFullUrl = makeFilterCalls.call(this, "fullUrl");
+ filterCallsByMethod = makeFilterCalls.call(this, "method");
+ clear() {
+ this.logs = [];
+ }
+ [kMockCallHistoryAddLog](requestInit) {
+ const log = new MockCallHistoryLog(requestInit);
+ this.logs.push(log);
+ return log;
+ }
+ *[Symbol.iterator]() {
+ for (const log of this.calls()) {
+ yield log;
+ }
+ }
+ };
+ module2.exports.MockCallHistory = MockCallHistory;
+ module2.exports.MockCallHistoryLog = MockCallHistoryLog;
+ }
+});
+
+// node_modules/undici/lib/mock/mock-pool.js
+var require_mock_pool = __commonJS({
+ "node_modules/undici/lib/mock/mock-pool.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { promisify: promisify2 } = __require("node:util");
+ var Pool = require_pool();
+ var { buildMockDispatch } = require_mock_utils();
+ var {
+ kDispatches,
+ kMockAgent,
+ kClose,
+ kOriginalClose,
+ kOrigin,
+ kOriginalDispatch,
+ kConnected,
+ kIgnoreTrailingSlash
+ } = require_mock_symbols();
+ var { MockInterceptor } = require_mock_interceptor();
+ var Symbols = require_symbols();
+ var { InvalidArgumentError } = require_errors();
+ var MockPool = class extends Pool {
+ static {
+ __name(this, "MockPool");
+ }
+ constructor(origin, opts) {
+ if (!opts || !opts.agent || typeof opts.agent.dispatch !== "function") {
+ throw new InvalidArgumentError("Argument opts.agent must implement Agent");
+ }
+ super(origin, opts);
+ this[kMockAgent] = opts.agent;
+ this[kOrigin] = origin;
+ this[kIgnoreTrailingSlash] = opts.ignoreTrailingSlash ?? false;
+ this[kDispatches] = [];
+ this[kConnected] = 1;
+ this[kOriginalDispatch] = this.dispatch;
+ this[kOriginalClose] = this.close.bind(this);
+ this.dispatch = buildMockDispatch.call(this);
+ this.close = this[kClose];
+ }
+ get [Symbols.kConnected]() {
+ return this[kConnected];
+ }
+ /**
+ * Sets up the base interceptor for mocking replies from undici.
+ */
+ intercept(opts) {
+ return new MockInterceptor(
+ opts && { ignoreTrailingSlash: this[kIgnoreTrailingSlash], ...opts },
+ this[kDispatches]
+ );
+ }
+ cleanMocks() {
+ this[kDispatches] = [];
+ }
+ async [kClose]() {
+ await promisify2(this[kOriginalClose])();
+ this[kConnected] = 0;
+ this[kMockAgent][Symbols.kClients].delete(this[kOrigin]);
+ }
+ };
+ module2.exports = MockPool;
+ }
+});
+
+// node_modules/undici/lib/mock/pending-interceptors-formatter.js
+var require_pending_interceptors_formatter = __commonJS({
+ "node_modules/undici/lib/mock/pending-interceptors-formatter.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { Transform: Transform2 } = __require("node:stream");
+ var { Console } = __require("node:console");
+ var PERSISTENT = process.versions.icu ? "\u2705" : "Y ";
+ var NOT_PERSISTENT = process.versions.icu ? "\u274C" : "N ";
+ module2.exports = class PendingInterceptorsFormatter {
+ static {
+ __name(this, "PendingInterceptorsFormatter");
+ }
+ constructor({ disableColors } = {}) {
+ this.transform = new Transform2({
+ transform(chunk, _enc, cb) {
+ cb(null, chunk);
+ }
+ });
+ this.logger = new Console({
+ stdout: this.transform,
+ inspectOptions: {
+ colors: !disableColors && !process.env.CI
+ }
+ });
+ }
+ format(pendingInterceptors) {
+ const withPrettyHeaders = pendingInterceptors.map(
+ ({ method, path: path27, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
+ Method: method,
+ Origin: origin,
+ Path: path27,
+ "Status code": statusCode,
+ Persistent: persist ? PERSISTENT : NOT_PERSISTENT,
+ Invocations: timesInvoked,
+ Remaining: persist ? Infinity : times - timesInvoked
+ })
+ );
+ this.logger.table(withPrettyHeaders);
+ return this.transform.read().toString();
+ }
+ };
+ }
+});
+
+// node_modules/undici/lib/mock/mock-agent.js
+var require_mock_agent = __commonJS({
+ "node_modules/undici/lib/mock/mock-agent.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { kClients } = require_symbols();
+ var Agent2 = require_agent();
+ var {
+ kAgent,
+ kMockAgentSet,
+ kMockAgentGet,
+ kDispatches,
+ kIsMockActive,
+ kNetConnect,
+ kGetNetConnect,
+ kOptions,
+ kFactory,
+ kMockAgentRegisterCallHistory,
+ kMockAgentIsCallHistoryEnabled,
+ kMockAgentAddCallHistoryLog,
+ kMockAgentMockCallHistoryInstance,
+ kMockAgentAcceptsNonStandardSearchParameters,
+ kMockCallHistoryAddLog,
+ kIgnoreTrailingSlash
+ } = require_mock_symbols();
+ var MockClient = require_mock_client();
+ var MockPool = require_mock_pool();
+ var { matchValue, normalizeSearchParams, buildAndValidateMockOptions, normalizeOrigin } = require_mock_utils();
+ var { InvalidArgumentError, UndiciError } = require_errors();
+ var Dispatcher = require_dispatcher();
+ var PendingInterceptorsFormatter = require_pending_interceptors_formatter();
+ var { MockCallHistory } = require_mock_call_history();
+ var MockAgent = class extends Dispatcher {
+ static {
+ __name(this, "MockAgent");
+ }
+ constructor(opts = {}) {
+ super(opts);
+ const mockOptions = buildAndValidateMockOptions(opts);
+ this[kNetConnect] = true;
+ this[kIsMockActive] = true;
+ this[kMockAgentIsCallHistoryEnabled] = mockOptions.enableCallHistory ?? false;
+ this[kMockAgentAcceptsNonStandardSearchParameters] = mockOptions.acceptNonStandardSearchParameters ?? false;
+ this[kIgnoreTrailingSlash] = mockOptions.ignoreTrailingSlash ?? false;
+ if (opts?.agent && typeof opts.agent.dispatch !== "function") {
+ throw new InvalidArgumentError("Argument opts.agent must implement Agent");
+ }
+ const agent = opts?.agent ? opts.agent : new Agent2(opts);
+ this[kAgent] = agent;
+ this[kClients] = agent[kClients];
+ this[kOptions] = mockOptions;
+ if (this[kMockAgentIsCallHistoryEnabled]) {
+ this[kMockAgentRegisterCallHistory]();
+ }
+ }
+ get(origin) {
+ const normalizedOrigin = normalizeOrigin(origin);
+ const originKey = this[kIgnoreTrailingSlash] ? normalizedOrigin.replace(/\/$/, "") : normalizedOrigin;
+ let dispatcher = this[kMockAgentGet](originKey);
+ if (!dispatcher) {
+ dispatcher = this[kFactory](originKey);
+ this[kMockAgentSet](originKey, dispatcher);
+ }
+ return dispatcher;
+ }
+ dispatch(opts, handler) {
+ opts.origin = normalizeOrigin(opts.origin);
+ this.get(opts.origin);
+ this[kMockAgentAddCallHistoryLog](opts);
+ const acceptNonStandardSearchParameters = this[kMockAgentAcceptsNonStandardSearchParameters];
+ const dispatchOpts = { ...opts };
+ if (acceptNonStandardSearchParameters && dispatchOpts.path) {
+ const [path27, searchParams] = dispatchOpts.path.split("?");
+ const normalizedSearchParams = normalizeSearchParams(searchParams, acceptNonStandardSearchParameters);
+ dispatchOpts.path = `${path27}?${normalizedSearchParams}`;
+ }
+ return this[kAgent].dispatch(dispatchOpts, handler);
+ }
+ async close() {
+ this.clearCallHistory();
+ await this[kAgent].close();
+ this[kClients].clear();
+ }
+ deactivate() {
+ this[kIsMockActive] = false;
+ }
+ activate() {
+ this[kIsMockActive] = true;
+ }
+ enableNetConnect(matcher) {
+ if (typeof matcher === "string" || typeof matcher === "function" || matcher instanceof RegExp) {
+ if (Array.isArray(this[kNetConnect])) {
+ this[kNetConnect].push(matcher);
+ } else {
+ this[kNetConnect] = [matcher];
+ }
+ } else if (typeof matcher === "undefined") {
+ this[kNetConnect] = true;
+ } else {
+ throw new InvalidArgumentError("Unsupported matcher. Must be one of String|Function|RegExp.");
+ }
+ }
+ disableNetConnect() {
+ this[kNetConnect] = false;
+ }
+ enableCallHistory() {
+ this[kMockAgentIsCallHistoryEnabled] = true;
+ return this;
+ }
+ disableCallHistory() {
+ this[kMockAgentIsCallHistoryEnabled] = false;
+ return this;
+ }
+ getCallHistory() {
+ return this[kMockAgentMockCallHistoryInstance];
+ }
+ clearCallHistory() {
+ if (this[kMockAgentMockCallHistoryInstance] !== void 0) {
+ this[kMockAgentMockCallHistoryInstance].clear();
+ }
+ }
+ // This is required to bypass issues caused by using global symbols - see:
+ // https://github.com/nodejs/undici/issues/1447
+ get isMockActive() {
+ return this[kIsMockActive];
+ }
+ [kMockAgentRegisterCallHistory]() {
+ if (this[kMockAgentMockCallHistoryInstance] === void 0) {
+ this[kMockAgentMockCallHistoryInstance] = new MockCallHistory();
+ }
+ }
+ [kMockAgentAddCallHistoryLog](opts) {
+ if (this[kMockAgentIsCallHistoryEnabled]) {
+ this[kMockAgentRegisterCallHistory]();
+ this[kMockAgentMockCallHistoryInstance][kMockCallHistoryAddLog](opts);
+ }
+ }
+ [kMockAgentSet](origin, dispatcher) {
+ this[kClients].set(origin, { count: 0, dispatcher });
+ }
+ [kFactory](origin) {
+ const mockOptions = Object.assign({ agent: this }, this[kOptions]);
+ return this[kOptions] && this[kOptions].connections === 1 ? new MockClient(origin, mockOptions) : new MockPool(origin, mockOptions);
+ }
+ [kMockAgentGet](origin) {
+ const result = this[kClients].get(origin);
+ if (result?.dispatcher) {
+ return result.dispatcher;
+ }
+ if (typeof origin !== "string") {
+ const dispatcher = this[kFactory]("http://localhost:9999");
+ this[kMockAgentSet](origin, dispatcher);
+ return dispatcher;
+ }
+ for (const [keyMatcher, result2] of Array.from(this[kClients])) {
+ if (result2 && typeof keyMatcher !== "string" && matchValue(keyMatcher, origin)) {
+ const dispatcher = this[kFactory](origin);
+ this[kMockAgentSet](origin, dispatcher);
+ dispatcher[kDispatches] = result2.dispatcher[kDispatches];
+ return dispatcher;
+ }
+ }
+ }
+ [kGetNetConnect]() {
+ return this[kNetConnect];
+ }
+ pendingInterceptors() {
+ const mockAgentClients = this[kClients];
+ return Array.from(mockAgentClients.entries()).flatMap(([origin, result]) => result.dispatcher[kDispatches].map((dispatch) => ({ ...dispatch, origin }))).filter(({ pending }) => pending);
+ }
+ assertNoPendingInterceptors({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) {
+ const pending = this.pendingInterceptors();
+ if (pending.length === 0) {
+ return;
+ }
+ throw new UndiciError(
+ pending.length === 1 ? `1 interceptor is pending:
+
+${pendingInterceptorsFormatter.format(pending)}`.trim() : `${pending.length} interceptors are pending:
+
+${pendingInterceptorsFormatter.format(pending)}`.trim()
+ );
+ }
+ };
+ module2.exports = MockAgent;
+ }
+});
+
+// node_modules/undici/lib/mock/snapshot-utils.js
+var require_snapshot_utils = __commonJS({
+ "node_modules/undici/lib/mock/snapshot-utils.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { InvalidArgumentError } = require_errors();
+ var { runtimeFeatures } = require_runtime_features();
+ function createHeaderFilters(matchOptions = {}) {
+ const { ignoreHeaders = [], excludeHeaders = [], matchHeaders = [], caseSensitive = false } = matchOptions;
+ return {
+ ignore: new Set(ignoreHeaders.map((header) => caseSensitive ? header : header.toLowerCase())),
+ exclude: new Set(excludeHeaders.map((header) => caseSensitive ? header : header.toLowerCase())),
+ match: new Set(matchHeaders.map((header) => caseSensitive ? header : header.toLowerCase()))
+ };
+ }
+ __name(createHeaderFilters, "createHeaderFilters");
+ var crypto4 = runtimeFeatures.has("crypto") ? __require("node:crypto") : null;
+ var hashId = crypto4?.hash ? (value) => crypto4.hash("sha256", value, "base64url") : (value) => Buffer.from(value).toString("base64url");
+ function isUndiciHeaders(headers) {
+ return Array.isArray(headers) && (headers.length & 1) === 0;
+ }
+ __name(isUndiciHeaders, "isUndiciHeaders");
+ function isUrlExcludedFactory(excludePatterns = []) {
+ if (excludePatterns.length === 0) {
+ return () => false;
+ }
+ return /* @__PURE__ */ __name(function isUrlExcluded(url2) {
+ let urlLowerCased;
+ for (const pattern of excludePatterns) {
+ if (typeof pattern === "string") {
+ if (!urlLowerCased) {
+ urlLowerCased = url2.toLowerCase();
+ }
+ if (urlLowerCased.includes(pattern.toLowerCase())) {
+ return true;
+ }
+ } else if (pattern instanceof RegExp) {
+ if (pattern.test(url2)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }, "isUrlExcluded");
+ }
+ __name(isUrlExcludedFactory, "isUrlExcludedFactory");
+ function normalizeHeaders(headers) {
+ const normalizedHeaders = {};
+ if (!headers) return normalizedHeaders;
+ if (isUndiciHeaders(headers)) {
+ for (let i = 0; i < headers.length; i += 2) {
+ const key = headers[i];
+ const value = headers[i + 1];
+ if (key && value !== void 0) {
+ const keyStr = Buffer.isBuffer(key) ? key.toString() : key;
+ const valueStr = Buffer.isBuffer(value) ? value.toString() : value;
+ normalizedHeaders[keyStr.toLowerCase()] = valueStr;
+ }
+ }
+ return normalizedHeaders;
+ }
+ if (headers && typeof headers === "object") {
+ for (const [key, value] of Object.entries(headers)) {
+ if (key && typeof key === "string") {
+ normalizedHeaders[key.toLowerCase()] = Array.isArray(value) ? value.join(", ") : String(value);
+ }
+ }
+ }
+ return normalizedHeaders;
+ }
+ __name(normalizeHeaders, "normalizeHeaders");
+ var validSnapshotModes = (
+ /** @type {const} */
+ ["record", "playback", "update"]
+ );
+ function validateSnapshotMode(mode) {
+ if (!validSnapshotModes.includes(mode)) {
+ throw new InvalidArgumentError(`Invalid snapshot mode: ${mode}. Must be one of: ${validSnapshotModes.join(", ")}`);
+ }
+ }
+ __name(validateSnapshotMode, "validateSnapshotMode");
+ module2.exports = {
+ createHeaderFilters,
+ hashId,
+ isUndiciHeaders,
+ normalizeHeaders,
+ isUrlExcludedFactory,
+ validateSnapshotMode
+ };
+ }
+});
+
+// node_modules/undici/lib/mock/snapshot-recorder.js
+var require_snapshot_recorder = __commonJS({
+ "node_modules/undici/lib/mock/snapshot-recorder.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { writeFile: writeFile2, readFile, mkdir } = __require("node:fs/promises");
+ var { dirname: dirname13, resolve: resolve16 } = __require("node:path");
+ var { setTimeout: setTimeout2, clearTimeout: clearTimeout2 } = __require("node:timers");
+ var { InvalidArgumentError, UndiciError } = require_errors();
+ var { hashId, isUrlExcludedFactory, normalizeHeaders, createHeaderFilters } = require_snapshot_utils();
+ function formatRequestKey(opts, headerFilters, matchOptions = {}) {
+ const url2 = new URL(opts.path, opts.origin);
+ const normalized = opts._normalizedHeaders || normalizeHeaders(opts.headers);
+ if (!opts._normalizedHeaders) {
+ opts._normalizedHeaders = normalized;
+ }
+ return {
+ method: opts.method || "GET",
+ url: matchOptions.matchQuery !== false ? url2.toString() : `${url2.origin}${url2.pathname}`,
+ headers: filterHeadersForMatching(normalized, headerFilters, matchOptions),
+ body: matchOptions.matchBody !== false && opts.body ? String(opts.body) : ""
+ };
+ }
+ __name(formatRequestKey, "formatRequestKey");
+ function filterHeadersForMatching(headers, headerFilters, matchOptions = {}) {
+ if (!headers || typeof headers !== "object") return {};
+ const {
+ caseSensitive = false
+ } = matchOptions;
+ const filtered = {};
+ const { ignore: ignore3, exclude, match } = headerFilters;
+ for (const [key, value] of Object.entries(headers)) {
+ const headerKey = caseSensitive ? key : key.toLowerCase();
+ if (exclude.has(headerKey)) continue;
+ if (ignore3.has(headerKey)) continue;
+ if (match.size !== 0) {
+ if (!match.has(headerKey)) continue;
+ }
+ filtered[headerKey] = value;
+ }
+ return filtered;
+ }
+ __name(filterHeadersForMatching, "filterHeadersForMatching");
+ function filterHeadersForStorage(headers, headerFilters, matchOptions = {}) {
+ if (!headers || typeof headers !== "object") return {};
+ const {
+ caseSensitive = false
+ } = matchOptions;
+ const filtered = {};
+ const { exclude: excludeSet } = headerFilters;
+ for (const [key, value] of Object.entries(headers)) {
+ const headerKey = caseSensitive ? key : key.toLowerCase();
+ if (excludeSet.has(headerKey)) continue;
+ filtered[headerKey] = value;
+ }
+ return filtered;
+ }
+ __name(filterHeadersForStorage, "filterHeadersForStorage");
+ function createRequestHash(formattedRequest) {
+ const parts = [
+ formattedRequest.method,
+ formattedRequest.url
+ ];
+ if (formattedRequest.headers && typeof formattedRequest.headers === "object") {
+ const headerKeys = Object.keys(formattedRequest.headers).sort();
+ for (const key of headerKeys) {
+ const values = Array.isArray(formattedRequest.headers[key]) ? formattedRequest.headers[key] : [formattedRequest.headers[key]];
+ parts.push(key);
+ for (const value of values.sort()) {
+ parts.push(String(value));
+ }
+ }
+ }
+ parts.push(formattedRequest.body);
+ const content = parts.join("|");
+ return hashId(content);
+ }
+ __name(createRequestHash, "createRequestHash");
+ var SnapshotRecorder = class {
+ static {
+ __name(this, "SnapshotRecorder");
+ }
+ /** @type {NodeJS.Timeout | null} */
+ #flushTimeout;
+ /** @type {import('./snapshot-utils').IsUrlExcluded} */
+ #isUrlExcluded;
+ /** @type {Map} */
+ #snapshots = /* @__PURE__ */ new Map();
+ /** @type {string|undefined} */
+ #snapshotPath;
+ /** @type {number} */
+ #maxSnapshots = Infinity;
+ /** @type {boolean} */
+ #autoFlush = false;
+ /** @type {import('./snapshot-utils').HeaderFilters} */
+ #headerFilters;
+ /**
+ * Creates a new SnapshotRecorder instance
+ * @param {SnapshotRecorderOptions&SnapshotRecorderMatchOptions} [options={}] - Configuration options for the recorder
+ */
+ constructor(options2 = {}) {
+ this.#snapshotPath = options2.snapshotPath;
+ this.#maxSnapshots = options2.maxSnapshots || Infinity;
+ this.#autoFlush = options2.autoFlush || false;
+ this.flushInterval = options2.flushInterval || 3e4;
+ this._flushTimer = null;
+ this.matchOptions = {
+ matchHeaders: options2.matchHeaders || [],
+ // empty means match all headers
+ ignoreHeaders: options2.ignoreHeaders || [],
+ excludeHeaders: options2.excludeHeaders || [],
+ matchBody: options2.matchBody !== false,
+ // default: true
+ matchQuery: options2.matchQuery !== false,
+ // default: true
+ caseSensitive: options2.caseSensitive || false
+ };
+ this.#headerFilters = createHeaderFilters(this.matchOptions);
+ this.shouldRecord = options2.shouldRecord || (() => true);
+ this.shouldPlayback = options2.shouldPlayback || (() => true);
+ this.#isUrlExcluded = isUrlExcludedFactory(options2.excludeUrls);
+ if (this.#autoFlush && this.#snapshotPath) {
+ this.#startAutoFlush();
+ }
+ }
+ /**
+ * Records a request-response interaction
+ * @param {SnapshotRequestOptions} requestOpts - Request options
+ * @param {SnapshotEntryResponse} response - Response data to record
+ * @return {Promise} - Resolves when the recording is complete
+ */
+ async record(requestOpts, response) {
+ if (!this.shouldRecord(requestOpts)) {
+ return;
+ }
+ if (this.isUrlExcluded(requestOpts)) {
+ return;
+ }
+ const request = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions);
+ const hash2 = createRequestHash(request);
+ const normalizedHeaders = normalizeHeaders(response.headers);
+ const responseData = {
+ statusCode: response.statusCode,
+ headers: filterHeadersForStorage(normalizedHeaders, this.#headerFilters, this.matchOptions),
+ body: Buffer.isBuffer(response.body) ? response.body.toString("base64") : Buffer.from(String(response.body || "")).toString("base64"),
+ trailers: response.trailers
+ };
+ if (this.#snapshots.size >= this.#maxSnapshots && !this.#snapshots.has(hash2)) {
+ const oldestKey = this.#snapshots.keys().next().value;
+ this.#snapshots.delete(oldestKey);
+ }
+ const existingSnapshot = this.#snapshots.get(hash2);
+ if (existingSnapshot && existingSnapshot.responses) {
+ existingSnapshot.responses.push(responseData);
+ existingSnapshot.timestamp = (/* @__PURE__ */ new Date()).toISOString();
+ } else {
+ this.#snapshots.set(hash2, {
+ request,
+ responses: [responseData],
+ // Always store as array for consistency
+ callCount: 0,
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
+ });
+ }
+ if (this.#autoFlush && this.#snapshotPath) {
+ this.#scheduleFlush();
+ }
+ }
+ /**
+ * Checks if a URL should be excluded from recording/playback
+ * @param {SnapshotRequestOptions} requestOpts - Request options to check
+ * @returns {boolean} - True if URL is excluded
+ */
+ isUrlExcluded(requestOpts) {
+ const url2 = new URL(requestOpts.path, requestOpts.origin).toString();
+ return this.#isUrlExcluded(url2);
+ }
+ /**
+ * Finds a matching snapshot for the given request
+ * Returns the appropriate response based on call count for sequential responses
+ *
+ * @param {SnapshotRequestOptions} requestOpts - Request options to match
+ * @returns {SnapshotEntry&Record<'response', SnapshotEntryResponse>|undefined} - Matching snapshot response or undefined if not found
+ */
+ findSnapshot(requestOpts) {
+ if (!this.shouldPlayback(requestOpts)) {
+ return void 0;
+ }
+ if (this.isUrlExcluded(requestOpts)) {
+ return void 0;
+ }
+ const request = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions);
+ const hash2 = createRequestHash(request);
+ const snapshot = this.#snapshots.get(hash2);
+ if (!snapshot) return void 0;
+ const currentCallCount = snapshot.callCount || 0;
+ const responseIndex = Math.min(currentCallCount, snapshot.responses.length - 1);
+ snapshot.callCount = currentCallCount + 1;
+ return {
+ ...snapshot,
+ response: snapshot.responses[responseIndex]
+ };
+ }
+ /**
+ * Loads snapshots from file
+ * @param {string} [filePath] - Optional file path to load snapshots from
+ * @return {Promise} - Resolves when snapshots are loaded
+ */
+ async loadSnapshots(filePath) {
+ const path27 = filePath || this.#snapshotPath;
+ if (!path27) {
+ throw new InvalidArgumentError("Snapshot path is required");
+ }
+ try {
+ const data = await readFile(resolve16(path27), "utf8");
+ const parsed = JSON.parse(data);
+ if (Array.isArray(parsed)) {
+ this.#snapshots.clear();
+ for (const { hash: hash2, snapshot } of parsed) {
+ this.#snapshots.set(hash2, snapshot);
+ }
+ } else {
+ this.#snapshots = new Map(Object.entries(parsed));
+ }
+ } catch (error51) {
+ if (error51.code === "ENOENT") {
+ this.#snapshots.clear();
+ } else {
+ throw new UndiciError(`Failed to load snapshots from ${path27}`, { cause: error51 });
+ }
+ }
+ }
+ /**
+ * Saves snapshots to file
+ *
+ * @param {string} [filePath] - Optional file path to save snapshots
+ * @returns {Promise} - Resolves when snapshots are saved
+ */
+ async saveSnapshots(filePath) {
+ const path27 = filePath || this.#snapshotPath;
+ if (!path27) {
+ throw new InvalidArgumentError("Snapshot path is required");
+ }
+ const resolvedPath = resolve16(path27);
+ await mkdir(dirname13(resolvedPath), { recursive: true });
+ const data = Array.from(this.#snapshots.entries()).map(([hash2, snapshot]) => ({
+ hash: hash2,
+ snapshot
+ }));
+ await writeFile2(resolvedPath, JSON.stringify(data, null, 2), { flush: true });
+ }
+ /**
+ * Clears all recorded snapshots
+ * @returns {void}
+ */
+ clear() {
+ this.#snapshots.clear();
+ }
+ /**
+ * Gets all recorded snapshots
+ * @return {Array} - Array of all recorded snapshots
+ */
+ getSnapshots() {
+ return Array.from(this.#snapshots.values());
+ }
+ /**
+ * Gets snapshot count
+ * @return {number} - Number of recorded snapshots
+ */
+ size() {
+ return this.#snapshots.size;
+ }
+ /**
+ * Resets call counts for all snapshots (useful for test cleanup)
+ * @returns {void}
+ */
+ resetCallCounts() {
+ for (const snapshot of this.#snapshots.values()) {
+ snapshot.callCount = 0;
+ }
+ }
+ /**
+ * Deletes a specific snapshot by request options
+ * @param {SnapshotRequestOptions} requestOpts - Request options to match
+ * @returns {boolean} - True if snapshot was deleted, false if not found
+ */
+ deleteSnapshot(requestOpts) {
+ const request = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions);
+ const hash2 = createRequestHash(request);
+ return this.#snapshots.delete(hash2);
+ }
+ /**
+ * Gets information about a specific snapshot
+ * @param {SnapshotRequestOptions} requestOpts - Request options to match
+ * @returns {SnapshotInfo|null} - Snapshot information or null if not found
+ */
+ getSnapshotInfo(requestOpts) {
+ const request = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions);
+ const hash2 = createRequestHash(request);
+ const snapshot = this.#snapshots.get(hash2);
+ if (!snapshot) return null;
+ return {
+ hash: hash2,
+ request: snapshot.request,
+ responseCount: snapshot.responses ? snapshot.responses.length : snapshot.response ? 1 : 0,
+ // .response for legacy snapshots
+ callCount: snapshot.callCount || 0,
+ timestamp: snapshot.timestamp
+ };
+ }
+ /**
+ * Replaces all snapshots with new data (full replacement)
+ * @param {Array<{hash: string; snapshot: SnapshotEntry}>|Record} snapshotData - New snapshot data to replace existing ones
+ * @returns {void}
+ */
+ replaceSnapshots(snapshotData) {
+ this.#snapshots.clear();
+ if (Array.isArray(snapshotData)) {
+ for (const { hash: hash2, snapshot } of snapshotData) {
+ this.#snapshots.set(hash2, snapshot);
+ }
+ } else if (snapshotData && typeof snapshotData === "object") {
+ this.#snapshots = new Map(Object.entries(snapshotData));
+ }
+ }
+ /**
+ * Starts the auto-flush timer
+ * @returns {void}
+ */
+ #startAutoFlush() {
+ return this.#scheduleFlush();
+ }
+ /**
+ * Stops the auto-flush timer
+ * @returns {void}
+ */
+ #stopAutoFlush() {
+ if (this.#flushTimeout) {
+ clearTimeout2(this.#flushTimeout);
+ this.saveSnapshots().catch(() => {
+ });
+ this.#flushTimeout = null;
+ }
+ }
+ /**
+ * Schedules a flush (debounced to avoid excessive writes)
+ */
+ #scheduleFlush() {
+ this.#flushTimeout = setTimeout2(() => {
+ this.saveSnapshots().catch(() => {
+ });
+ if (this.#autoFlush) {
+ this.#flushTimeout?.refresh();
+ } else {
+ this.#flushTimeout = null;
+ }
+ }, 1e3);
+ }
+ /**
+ * Cleanup method to stop timers
+ * @returns {void}
+ */
+ destroy() {
+ this.#stopAutoFlush();
+ if (this.#flushTimeout) {
+ clearTimeout2(this.#flushTimeout);
+ this.#flushTimeout = null;
+ }
+ }
+ /**
+ * Async close method that saves all recordings and performs cleanup
+ * @returns {Promise}
+ */
+ async close() {
+ if (this.#snapshotPath && this.#snapshots.size !== 0) {
+ await this.saveSnapshots();
+ }
+ this.destroy();
+ }
+ };
+ module2.exports = { SnapshotRecorder, formatRequestKey, createRequestHash, filterHeadersForMatching, filterHeadersForStorage, createHeaderFilters };
+ }
+});
+
+// node_modules/undici/lib/mock/snapshot-agent.js
+var require_snapshot_agent = __commonJS({
+ "node_modules/undici/lib/mock/snapshot-agent.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var Agent2 = require_agent();
+ var MockAgent = require_mock_agent();
+ var { SnapshotRecorder } = require_snapshot_recorder();
+ var WrapHandler = require_wrap_handler();
+ var { InvalidArgumentError, UndiciError } = require_errors();
+ var { validateSnapshotMode } = require_snapshot_utils();
+ var kSnapshotRecorder = /* @__PURE__ */ Symbol("kSnapshotRecorder");
+ var kSnapshotMode = /* @__PURE__ */ Symbol("kSnapshotMode");
+ var kSnapshotPath = /* @__PURE__ */ Symbol("kSnapshotPath");
+ var kSnapshotLoaded = /* @__PURE__ */ Symbol("kSnapshotLoaded");
+ var kRealAgent = /* @__PURE__ */ Symbol("kRealAgent");
+ var warningEmitted = false;
+ var SnapshotAgent = class extends MockAgent {
+ static {
+ __name(this, "SnapshotAgent");
+ }
+ constructor(opts = {}) {
+ if (!warningEmitted) {
+ process.emitWarning(
+ "SnapshotAgent is experimental and subject to change",
+ "ExperimentalWarning"
+ );
+ warningEmitted = true;
+ }
+ const {
+ mode = "record",
+ snapshotPath = null,
+ ...mockAgentOpts
+ } = opts;
+ super(mockAgentOpts);
+ validateSnapshotMode(mode);
+ if ((mode === "playback" || mode === "update") && !snapshotPath) {
+ throw new InvalidArgumentError(`snapshotPath is required when mode is '${mode}'`);
+ }
+ this[kSnapshotMode] = mode;
+ this[kSnapshotPath] = snapshotPath;
+ this[kSnapshotRecorder] = new SnapshotRecorder({
+ snapshotPath: this[kSnapshotPath],
+ mode: this[kSnapshotMode],
+ maxSnapshots: opts.maxSnapshots,
+ autoFlush: opts.autoFlush,
+ flushInterval: opts.flushInterval,
+ matchHeaders: opts.matchHeaders,
+ ignoreHeaders: opts.ignoreHeaders,
+ excludeHeaders: opts.excludeHeaders,
+ matchBody: opts.matchBody,
+ matchQuery: opts.matchQuery,
+ caseSensitive: opts.caseSensitive,
+ shouldRecord: opts.shouldRecord,
+ shouldPlayback: opts.shouldPlayback,
+ excludeUrls: opts.excludeUrls
+ });
+ this[kSnapshotLoaded] = false;
+ if (this[kSnapshotMode] === "record" || this[kSnapshotMode] === "update" || this[kSnapshotMode] === "playback" && opts.excludeUrls && opts.excludeUrls.length > 0) {
+ this[kRealAgent] = new Agent2(opts);
+ }
+ if ((this[kSnapshotMode] === "playback" || this[kSnapshotMode] === "update") && this[kSnapshotPath]) {
+ this.loadSnapshots().catch(() => {
+ });
+ }
+ }
+ dispatch(opts, handler) {
+ handler = WrapHandler.wrap(handler);
+ const mode = this[kSnapshotMode];
+ if (this[kSnapshotRecorder].isUrlExcluded(opts)) {
+ return this[kRealAgent].dispatch(opts, handler);
+ }
+ if (mode === "playback" || mode === "update") {
+ if (!this[kSnapshotLoaded]) {
+ return this.#asyncDispatch(opts, handler);
+ }
+ const snapshot = this[kSnapshotRecorder].findSnapshot(opts);
+ if (snapshot) {
+ return this.#replaySnapshot(snapshot, handler);
+ } else if (mode === "update") {
+ return this.#recordAndReplay(opts, handler);
+ } else {
+ const error51 = new UndiciError(`No snapshot found for ${opts.method || "GET"} ${opts.path}`);
+ if (handler.onError) {
+ handler.onError(error51);
+ return;
+ }
+ throw error51;
+ }
+ } else if (mode === "record") {
+ return this.#recordAndReplay(opts, handler);
+ }
+ }
+ /**
+ * Async version of dispatch for when we need to load snapshots first
+ */
+ async #asyncDispatch(opts, handler) {
+ await this.loadSnapshots();
+ return this.dispatch(opts, handler);
+ }
+ /**
+ * Records a real request and replays the response
+ */
+ #recordAndReplay(opts, handler) {
+ const responseData = {
+ statusCode: null,
+ headers: {},
+ trailers: {},
+ body: []
+ };
+ const self2 = this;
+ const recordingHandler = {
+ onRequestStart(controller, context) {
+ return handler.onRequestStart(controller, { ...context, history: this.history });
+ },
+ onRequestUpgrade(controller, statusCode, headers, socket) {
+ return handler.onRequestUpgrade(controller, statusCode, headers, socket);
+ },
+ onResponseStart(controller, statusCode, headers, statusMessage) {
+ responseData.statusCode = statusCode;
+ responseData.headers = headers;
+ return handler.onResponseStart(controller, statusCode, headers, statusMessage);
+ },
+ onResponseData(controller, chunk) {
+ responseData.body.push(chunk);
+ return handler.onResponseData(controller, chunk);
+ },
+ onResponseEnd(controller, trailers) {
+ responseData.trailers = trailers;
+ const responseBody = Buffer.concat(responseData.body);
+ self2[kSnapshotRecorder].record(opts, {
+ statusCode: responseData.statusCode,
+ headers: responseData.headers,
+ body: responseBody,
+ trailers: responseData.trailers
+ }).then(() => handler.onResponseEnd(controller, trailers)).catch((error51) => handler.onResponseError(controller, error51));
+ }
+ };
+ const agent = this[kRealAgent];
+ return agent.dispatch(opts, recordingHandler);
+ }
+ /**
+ * Replays a recorded response
+ *
+ * @param {Object} snapshot - The recorded snapshot to replay.
+ * @param {Object} handler - The handler to call with the response data.
+ * @returns {void}
+ */
+ #replaySnapshot(snapshot, handler) {
+ try {
+ const { response } = snapshot;
+ const controller = {
+ pause() {
+ },
+ resume() {
+ },
+ abort(reason) {
+ this.aborted = true;
+ this.reason = reason;
+ },
+ aborted: false,
+ paused: false
+ };
+ handler.onRequestStart(controller);
+ handler.onResponseStart(controller, response.statusCode, response.headers);
+ const body = Buffer.from(response.body, "base64");
+ handler.onResponseData(controller, body);
+ handler.onResponseEnd(controller, response.trailers);
+ } catch (error51) {
+ handler.onError?.(error51);
+ }
+ }
+ /**
+ * Loads snapshots from file
+ *
+ * @param {string} [filePath] - Optional file path to load snapshots from.
+ * @returns {Promise} - Resolves when snapshots are loaded.
+ */
+ async loadSnapshots(filePath) {
+ await this[kSnapshotRecorder].loadSnapshots(filePath || this[kSnapshotPath]);
+ this[kSnapshotLoaded] = true;
+ if (this[kSnapshotMode] === "playback") {
+ this.#setupMockInterceptors();
+ }
+ }
+ /**
+ * Saves snapshots to file
+ *
+ * @param {string} [filePath] - Optional file path to save snapshots to.
+ * @returns {Promise} - Resolves when snapshots are saved.
+ */
+ async saveSnapshots(filePath) {
+ return this[kSnapshotRecorder].saveSnapshots(filePath || this[kSnapshotPath]);
+ }
+ /**
+ * Sets up MockAgent interceptors based on recorded snapshots.
+ *
+ * This method creates MockAgent interceptors for each recorded snapshot,
+ * allowing the SnapshotAgent to fall back to MockAgent's standard intercept
+ * mechanism in playback mode. Each interceptor is configured to persist
+ * (remain active for multiple requests) and responds with the recorded
+ * response data.
+ *
+ * Called automatically when loading snapshots in playback mode.
+ *
+ * @returns {void}
+ */
+ #setupMockInterceptors() {
+ for (const snapshot of this[kSnapshotRecorder].getSnapshots()) {
+ const { request, responses, response } = snapshot;
+ const url2 = new URL(request.url);
+ const mockPool = this.get(url2.origin);
+ const responseData = responses ? responses[0] : response;
+ if (!responseData) continue;
+ mockPool.intercept({
+ path: url2.pathname + url2.search,
+ method: request.method,
+ headers: request.headers,
+ body: request.body
+ }).reply(responseData.statusCode, responseData.body, {
+ headers: responseData.headers,
+ trailers: responseData.trailers
+ }).persist();
+ }
+ }
+ /**
+ * Gets the snapshot recorder
+ * @return {SnapshotRecorder} - The snapshot recorder instance
+ */
+ getRecorder() {
+ return this[kSnapshotRecorder];
+ }
+ /**
+ * Gets the current mode
+ * @return {import('./snapshot-utils').SnapshotMode} - The current snapshot mode
+ */
+ getMode() {
+ return this[kSnapshotMode];
+ }
+ /**
+ * Clears all snapshots
+ * @returns {void}
+ */
+ clearSnapshots() {
+ this[kSnapshotRecorder].clear();
+ }
+ /**
+ * Resets call counts for all snapshots (useful for test cleanup)
+ * @returns {void}
+ */
+ resetCallCounts() {
+ this[kSnapshotRecorder].resetCallCounts();
+ }
+ /**
+ * Deletes a specific snapshot by request options
+ * @param {import('./snapshot-recorder').SnapshotRequestOptions} requestOpts - Request options to identify the snapshot
+ * @return {Promise} - Returns true if the snapshot was deleted, false if not found
+ */
+ deleteSnapshot(requestOpts) {
+ return this[kSnapshotRecorder].deleteSnapshot(requestOpts);
+ }
+ /**
+ * Gets information about a specific snapshot
+ * @returns {import('./snapshot-recorder').SnapshotInfo|null} - Snapshot information or null if not found
+ */
+ getSnapshotInfo(requestOpts) {
+ return this[kSnapshotRecorder].getSnapshotInfo(requestOpts);
+ }
+ /**
+ * Replaces all snapshots with new data (full replacement)
+ * @param {Array<{hash: string; snapshot: import('./snapshot-recorder').SnapshotEntryshotEntry}>|Record} snapshotData - New snapshot data to replace existing snapshots
+ * @returns {void}
+ */
+ replaceSnapshots(snapshotData) {
+ this[kSnapshotRecorder].replaceSnapshots(snapshotData);
+ }
+ /**
+ * Closes the agent, saving snapshots and cleaning up resources.
+ *
+ * @returns {Promise}
+ */
+ async close() {
+ await this[kSnapshotRecorder].close();
+ await this[kRealAgent]?.close();
+ await super.close();
+ }
+ };
+ module2.exports = SnapshotAgent;
+ }
+});
+
+// node_modules/undici/lib/global.js
+var require_global2 = __commonJS({
+ "node_modules/undici/lib/global.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var globalDispatcher = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.2");
+ var legacyGlobalDispatcher = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.1");
+ var { InvalidArgumentError } = require_errors();
+ var Agent2 = require_agent();
+ if (getGlobalDispatcher() === void 0) {
+ setGlobalDispatcher(new Agent2());
+ }
+ function setGlobalDispatcher(agent) {
+ if (!agent || typeof agent.dispatch !== "function") {
+ throw new InvalidArgumentError("Argument agent must implement Agent");
+ }
+ Object.defineProperty(globalThis, globalDispatcher, {
+ value: agent,
+ writable: true,
+ enumerable: false,
+ configurable: false
+ });
+ Object.defineProperty(globalThis, legacyGlobalDispatcher, {
+ value: agent,
+ writable: true,
+ enumerable: false,
+ configurable: false
+ });
+ }
+ __name(setGlobalDispatcher, "setGlobalDispatcher");
+ function getGlobalDispatcher() {
+ return globalThis[legacyGlobalDispatcher];
+ }
+ __name(getGlobalDispatcher, "getGlobalDispatcher");
+ var installedExports = (
+ /** @type {const} */
+ [
+ "fetch",
+ "Headers",
+ "Response",
+ "Request",
+ "FormData",
+ "WebSocket",
+ "CloseEvent",
+ "ErrorEvent",
+ "MessageEvent",
+ "EventSource"
+ ]
+ );
+ module2.exports = {
+ setGlobalDispatcher,
+ getGlobalDispatcher,
+ installedExports
+ };
+ }
+});
+
+// node_modules/undici/lib/handler/decorator-handler.js
+var require_decorator_handler = __commonJS({
+ "node_modules/undici/lib/handler/decorator-handler.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var assert2 = __require("node:assert");
+ var WrapHandler = require_wrap_handler();
+ module2.exports = class DecoratorHandler {
+ static {
+ __name(this, "DecoratorHandler");
+ }
+ #handler;
+ #onCompleteCalled = false;
+ #onErrorCalled = false;
+ #onResponseStartCalled = false;
+ constructor(handler) {
+ if (typeof handler !== "object" || handler === null) {
+ throw new TypeError("handler must be an object");
+ }
+ this.#handler = WrapHandler.wrap(handler);
+ }
+ onRequestStart(...args) {
+ this.#handler.onRequestStart?.(...args);
+ }
+ onRequestUpgrade(...args) {
+ assert2(!this.#onCompleteCalled);
+ assert2(!this.#onErrorCalled);
+ return this.#handler.onRequestUpgrade?.(...args);
+ }
+ onResponseStart(...args) {
+ assert2(!this.#onCompleteCalled);
+ assert2(!this.#onErrorCalled);
+ assert2(!this.#onResponseStartCalled);
+ this.#onResponseStartCalled = true;
+ return this.#handler.onResponseStart?.(...args);
+ }
+ onResponseData(...args) {
+ assert2(!this.#onCompleteCalled);
+ assert2(!this.#onErrorCalled);
+ return this.#handler.onResponseData?.(...args);
+ }
+ onResponseEnd(...args) {
+ assert2(!this.#onCompleteCalled);
+ assert2(!this.#onErrorCalled);
+ this.#onCompleteCalled = true;
+ return this.#handler.onResponseEnd?.(...args);
+ }
+ onResponseError(...args) {
+ this.#onErrorCalled = true;
+ return this.#handler.onResponseError?.(...args);
+ }
+ /**
+ * @deprecated
+ */
+ onBodySent() {
+ }
+ };
+ }
+});
+
+// node_modules/undici/lib/handler/redirect-handler.js
+var require_redirect_handler = __commonJS({
+ "node_modules/undici/lib/handler/redirect-handler.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var util = require_util();
+ var { kBodyUsed } = require_symbols();
+ var assert2 = __require("node:assert");
+ var { InvalidArgumentError } = require_errors();
+ var EE = __require("node:events");
+ var redirectableStatusCodes = [300, 301, 302, 303, 307, 308];
+ var kBody = /* @__PURE__ */ Symbol("body");
+ var noop3 = /* @__PURE__ */ __name(() => {
+ }, "noop");
+ var BodyAsyncIterable = class {
+ static {
+ __name(this, "BodyAsyncIterable");
+ }
+ constructor(body) {
+ this[kBody] = body;
+ this[kBodyUsed] = false;
+ }
+ async *[Symbol.asyncIterator]() {
+ assert2(!this[kBodyUsed], "disturbed");
+ this[kBodyUsed] = true;
+ yield* this[kBody];
+ }
+ };
+ var RedirectHandler = class _RedirectHandler {
+ static {
+ __name(this, "RedirectHandler");
+ }
+ static buildDispatch(dispatcher, maxRedirections) {
+ if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
+ throw new InvalidArgumentError("maxRedirections must be a positive number");
+ }
+ const dispatch = dispatcher.dispatch.bind(dispatcher);
+ return (opts, originalHandler) => dispatch(opts, new _RedirectHandler(dispatch, maxRedirections, opts, originalHandler));
+ }
+ constructor(dispatch, maxRedirections, opts, handler) {
+ if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
+ throw new InvalidArgumentError("maxRedirections must be a positive number");
+ }
+ this.dispatch = dispatch;
+ this.location = null;
+ const { maxRedirections: _, ...cleanOpts } = opts;
+ this.opts = cleanOpts;
+ this.maxRedirections = maxRedirections;
+ this.handler = handler;
+ this.history = [];
+ if (util.isStream(this.opts.body)) {
+ if (util.bodyLength(this.opts.body) === 0) {
+ this.opts.body.on("data", function() {
+ assert2(false);
+ });
+ }
+ if (typeof this.opts.body.readableDidRead !== "boolean") {
+ this.opts.body[kBodyUsed] = false;
+ EE.prototype.on.call(this.opts.body, "data", function() {
+ this[kBodyUsed] = true;
+ });
+ }
+ } else if (this.opts.body && typeof this.opts.body.pipeTo === "function") {
+ this.opts.body = new BodyAsyncIterable(this.opts.body);
+ } else if (this.opts.body && typeof this.opts.body !== "string" && !ArrayBuffer.isView(this.opts.body) && util.isIterable(this.opts.body) && !util.isFormDataLike(this.opts.body)) {
+ this.opts.body = new BodyAsyncIterable(this.opts.body);
+ }
+ }
+ onRequestStart(controller, context) {
+ this.handler.onRequestStart?.(controller, { ...context, history: this.history });
+ }
+ onRequestUpgrade(controller, statusCode, headers, socket) {
+ this.handler.onRequestUpgrade?.(controller, statusCode, headers, socket);
+ }
+ onResponseStart(controller, statusCode, headers, statusMessage) {
+ if (this.opts.throwOnMaxRedirect && this.history.length >= this.maxRedirections) {
+ throw new Error("max redirects");
+ }
+ if ((statusCode === 301 || statusCode === 302) && this.opts.method === "POST") {
+ this.opts.method = "GET";
+ if (util.isStream(this.opts.body)) {
+ util.destroy(this.opts.body.on("error", noop3));
+ }
+ this.opts.body = null;
+ }
+ if (statusCode === 303 && this.opts.method !== "HEAD") {
+ this.opts.method = "GET";
+ if (util.isStream(this.opts.body)) {
+ util.destroy(this.opts.body.on("error", noop3));
+ }
+ this.opts.body = null;
+ }
+ this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body) || redirectableStatusCodes.indexOf(statusCode) === -1 ? null : headers.location;
+ if (this.opts.origin) {
+ this.history.push(new URL(this.opts.path, this.opts.origin));
+ }
+ if (!this.location) {
+ this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
+ return;
+ }
+ const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)));
+ const path27 = search ? `${pathname}${search}` : pathname;
+ const redirectUrlString = `${origin}${path27}`;
+ for (const historyUrl of this.history) {
+ if (historyUrl.toString() === redirectUrlString) {
+ throw new InvalidArgumentError(`Redirect loop detected. Cannot redirect to ${origin}. This typically happens when using a Client or Pool with cross-origin redirects. Use an Agent for cross-origin redirects.`);
+ }
+ }
+ this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin);
+ this.opts.path = path27;
+ this.opts.origin = origin;
+ this.opts.query = null;
+ }
+ onResponseData(controller, chunk) {
+ if (this.location) {
+ } else {
+ this.handler.onResponseData?.(controller, chunk);
+ }
+ }
+ onResponseEnd(controller, trailers) {
+ if (this.location) {
+ this.dispatch(this.opts, this);
+ } else {
+ this.handler.onResponseEnd(controller, trailers);
+ }
+ }
+ onResponseError(controller, error51) {
+ this.handler.onResponseError?.(controller, error51);
+ }
+ };
+ function shouldRemoveHeader(header, removeContent, unknownOrigin) {
+ if (header.length === 4) {
+ return util.headerNameToString(header) === "host";
+ }
+ if (removeContent && util.headerNameToString(header).startsWith("content-")) {
+ return true;
+ }
+ if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) {
+ const name = util.headerNameToString(header);
+ return name === "authorization" || name === "cookie" || name === "proxy-authorization";
+ }
+ return false;
+ }
+ __name(shouldRemoveHeader, "shouldRemoveHeader");
+ function cleanRequestHeaders(headers, removeContent, unknownOrigin) {
+ const ret = [];
+ if (Array.isArray(headers)) {
+ for (let i = 0; i < headers.length; i += 2) {
+ if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) {
+ ret.push(headers[i], headers[i + 1]);
+ }
+ }
+ } else if (headers && typeof headers === "object") {
+ const entries = util.hasSafeIterator(headers) ? headers : Object.entries(headers);
+ for (const [key, value] of entries) {
+ if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) {
+ ret.push(key, value);
+ }
+ }
+ } else {
+ assert2(headers == null, "headers must be an object or an array");
+ }
+ return ret;
+ }
+ __name(cleanRequestHeaders, "cleanRequestHeaders");
+ module2.exports = RedirectHandler;
+ }
+});
+
+// node_modules/undici/lib/interceptor/redirect.js
+var require_redirect = __commonJS({
+ "node_modules/undici/lib/interceptor/redirect.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var RedirectHandler = require_redirect_handler();
+ function createRedirectInterceptor({ maxRedirections: defaultMaxRedirections } = {}) {
+ return (dispatch) => {
+ return /* @__PURE__ */ __name(function Intercept(opts, handler) {
+ const { maxRedirections = defaultMaxRedirections, ...rest } = opts;
+ if (maxRedirections == null || maxRedirections === 0) {
+ return dispatch(opts, handler);
+ }
+ const dispatchOpts = { ...rest };
+ const redirectHandler = new RedirectHandler(dispatch, maxRedirections, dispatchOpts, handler);
+ return dispatch(dispatchOpts, redirectHandler);
+ }, "Intercept");
+ };
+ }
+ __name(createRedirectInterceptor, "createRedirectInterceptor");
+ module2.exports = createRedirectInterceptor;
+ }
+});
+
+// node_modules/undici/lib/interceptor/response-error.js
+var require_response_error = __commonJS({
+ "node_modules/undici/lib/interceptor/response-error.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var DecoratorHandler = require_decorator_handler();
+ var { ResponseError } = require_errors();
+ var ResponseErrorHandler = class extends DecoratorHandler {
+ static {
+ __name(this, "ResponseErrorHandler");
+ }
+ #statusCode;
+ #contentType;
+ #decoder;
+ #headers;
+ #body;
+ constructor(_opts, { handler }) {
+ super(handler);
+ }
+ #checkContentType(contentType) {
+ return (this.#contentType ?? "").indexOf(contentType) === 0;
+ }
+ onRequestStart(controller, context) {
+ this.#statusCode = 0;
+ this.#contentType = null;
+ this.#decoder = null;
+ this.#headers = null;
+ this.#body = "";
+ return super.onRequestStart(controller, context);
+ }
+ onResponseStart(controller, statusCode, headers, statusMessage) {
+ this.#statusCode = statusCode;
+ this.#headers = headers;
+ this.#contentType = headers["content-type"];
+ if (this.#statusCode < 400) {
+ return super.onResponseStart(controller, statusCode, headers, statusMessage);
+ }
+ if (this.#checkContentType("application/json") || this.#checkContentType("text/plain")) {
+ this.#decoder = new TextDecoder("utf-8");
+ }
+ }
+ onResponseData(controller, chunk) {
+ if (this.#statusCode < 400) {
+ return super.onResponseData(controller, chunk);
+ }
+ this.#body += this.#decoder?.decode(chunk, { stream: true }) ?? "";
+ }
+ onResponseEnd(controller, trailers) {
+ if (this.#statusCode >= 400) {
+ this.#body += this.#decoder?.decode(void 0, { stream: false }) ?? "";
+ if (this.#checkContentType("application/json")) {
+ try {
+ this.#body = JSON.parse(this.#body);
+ } catch {
+ }
+ }
+ let err;
+ const stackTraceLimit = Error.stackTraceLimit;
+ Error.stackTraceLimit = 0;
+ try {
+ err = new ResponseError("Response Error", this.#statusCode, {
+ body: this.#body,
+ headers: this.#headers
+ });
+ } finally {
+ Error.stackTraceLimit = stackTraceLimit;
+ }
+ super.onResponseError(controller, err);
+ } else {
+ super.onResponseEnd(controller, trailers);
+ }
+ }
+ onResponseError(controller, err) {
+ super.onResponseError(controller, err);
+ }
+ };
+ module2.exports = () => {
+ return (dispatch) => {
+ return /* @__PURE__ */ __name(function Intercept(opts, handler) {
+ return dispatch(opts, new ResponseErrorHandler(opts, { handler }));
+ }, "Intercept");
+ };
+ };
+ }
+});
+
+// node_modules/undici/lib/interceptor/retry.js
+var require_retry = __commonJS({
+ "node_modules/undici/lib/interceptor/retry.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var RetryHandler = require_retry_handler();
+ module2.exports = (globalOpts) => {
+ return (dispatch) => {
+ return /* @__PURE__ */ __name(function retryInterceptor(opts, handler) {
+ return dispatch(
+ opts,
+ new RetryHandler(
+ { ...opts, retryOptions: { ...globalOpts, ...opts.retryOptions } },
+ {
+ handler,
+ dispatch
+ }
+ )
+ );
+ }, "retryInterceptor");
+ };
+ };
+ }
+});
+
+// node_modules/undici/lib/interceptor/dump.js
+var require_dump = __commonJS({
+ "node_modules/undici/lib/interceptor/dump.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { InvalidArgumentError, RequestAbortedError } = require_errors();
+ var DecoratorHandler = require_decorator_handler();
+ var DumpHandler = class extends DecoratorHandler {
+ static {
+ __name(this, "DumpHandler");
+ }
+ #maxSize = 1024 * 1024;
+ #dumped = false;
+ #size = 0;
+ #controller = null;
+ aborted = false;
+ reason = false;
+ constructor({ maxSize, signal }, handler) {
+ if (maxSize != null && (!Number.isFinite(maxSize) || maxSize < 1)) {
+ throw new InvalidArgumentError("maxSize must be a number greater than 0");
+ }
+ super(handler);
+ this.#maxSize = maxSize ?? this.#maxSize;
+ }
+ #abort(reason) {
+ this.aborted = true;
+ this.reason = reason;
+ }
+ onRequestStart(controller, context) {
+ controller.abort = this.#abort.bind(this);
+ this.#controller = controller;
+ return super.onRequestStart(controller, context);
+ }
+ onResponseStart(controller, statusCode, headers, statusMessage) {
+ const contentLength = headers["content-length"];
+ if (contentLength != null && contentLength > this.#maxSize) {
+ throw new RequestAbortedError(
+ `Response size (${contentLength}) larger than maxSize (${this.#maxSize})`
+ );
+ }
+ if (this.aborted === true) {
+ return true;
+ }
+ return super.onResponseStart(controller, statusCode, headers, statusMessage);
+ }
+ onResponseError(controller, err) {
+ if (this.#dumped) {
+ return;
+ }
+ err = this.#controller?.reason ?? err;
+ super.onResponseError(controller, err);
+ }
+ onResponseData(controller, chunk) {
+ this.#size = this.#size + chunk.length;
+ if (this.#size >= this.#maxSize) {
+ this.#dumped = true;
+ if (this.aborted === true) {
+ super.onResponseError(controller, this.reason);
+ } else {
+ super.onResponseEnd(controller, {});
+ }
+ }
+ return true;
+ }
+ onResponseEnd(controller, trailers) {
+ if (this.#dumped) {
+ return;
+ }
+ if (this.#controller.aborted === true) {
+ super.onResponseError(controller, this.reason);
+ return;
+ }
+ super.onResponseEnd(controller, trailers);
+ }
+ };
+ function createDumpInterceptor({ maxSize: defaultMaxSize } = {
+ maxSize: 1024 * 1024
+ }) {
+ return (dispatch) => {
+ return /* @__PURE__ */ __name(function Intercept(opts, handler) {
+ const { dumpMaxSize = defaultMaxSize } = opts;
+ const dumpHandler = new DumpHandler({ maxSize: dumpMaxSize, signal: opts.signal }, handler);
+ return dispatch(opts, dumpHandler);
+ }, "Intercept");
+ };
+ }
+ __name(createDumpInterceptor, "createDumpInterceptor");
+ module2.exports = createDumpInterceptor;
+ }
+});
+
+// node_modules/undici/lib/interceptor/dns.js
+var require_dns = __commonJS({
+ "node_modules/undici/lib/interceptor/dns.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { isIP } = __require("node:net");
+ var { lookup } = __require("node:dns");
+ var DecoratorHandler = require_decorator_handler();
+ var { InvalidArgumentError, InformationalError } = require_errors();
+ var maxInt = Math.pow(2, 31) - 1;
+ function hasSafeIterator(headers) {
+ const prototype = Object.getPrototypeOf(headers);
+ const ownIterator = Object.prototype.hasOwnProperty.call(headers, Symbol.iterator);
+ return ownIterator || prototype != null && prototype !== Object.prototype && typeof headers[Symbol.iterator] === "function";
+ }
+ __name(hasSafeIterator, "hasSafeIterator");
+ function isHostHeader(key) {
+ return typeof key === "string" && key.toLowerCase() === "host";
+ }
+ __name(isHostHeader, "isHostHeader");
+ function normalizeHeaders(headers) {
+ if (headers == null) {
+ return null;
+ }
+ if (Array.isArray(headers)) {
+ if (headers.length === 0 || !Array.isArray(headers[0])) {
+ return headers;
+ }
+ const normalized = [];
+ for (const header of headers) {
+ if (Array.isArray(header) && header.length === 2) {
+ normalized.push(header[0], header[1]);
+ } else {
+ normalized.push(header);
+ }
+ }
+ return normalized;
+ }
+ if (typeof headers === "object" && hasSafeIterator(headers)) {
+ const normalized = [];
+ for (const header of headers) {
+ if (Array.isArray(header) && header.length === 2) {
+ normalized.push(header[0], header[1]);
+ } else {
+ normalized.push(header);
+ }
+ }
+ return normalized;
+ }
+ return headers;
+ }
+ __name(normalizeHeaders, "normalizeHeaders");
+ function hasHostHeader(headers) {
+ if (headers == null) {
+ return false;
+ }
+ if (Array.isArray(headers)) {
+ if (headers.length === 0) {
+ return false;
+ }
+ for (let i = 0; i < headers.length; i += 2) {
+ if (isHostHeader(headers[i])) {
+ return true;
+ }
+ }
+ return false;
+ }
+ if (typeof headers === "object") {
+ for (const key in headers) {
+ if (isHostHeader(key)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+ __name(hasHostHeader, "hasHostHeader");
+ function withHostHeader(host, headers) {
+ const normalizedHeaders = normalizeHeaders(headers);
+ if (hasHostHeader(normalizedHeaders)) {
+ return normalizedHeaders;
+ }
+ if (Array.isArray(normalizedHeaders)) {
+ return ["host", host, ...normalizedHeaders];
+ }
+ if (normalizedHeaders && typeof normalizedHeaders === "object") {
+ return {
+ host,
+ ...normalizedHeaders
+ };
+ }
+ return { host };
+ }
+ __name(withHostHeader, "withHostHeader");
+ var DNSStorage = class {
+ static {
+ __name(this, "DNSStorage");
+ }
+ #maxItems = 0;
+ #records = /* @__PURE__ */ new Map();
+ constructor(opts) {
+ this.#maxItems = opts.maxItems;
+ }
+ get size() {
+ return this.#records.size;
+ }
+ get(hostname4) {
+ return this.#records.get(hostname4) ?? null;
+ }
+ set(hostname4, records) {
+ this.#records.set(hostname4, records);
+ }
+ delete(hostname4) {
+ this.#records.delete(hostname4);
+ }
+ // Delegate to storage decide can we do more lookups or not
+ full() {
+ return this.size >= this.#maxItems;
+ }
+ };
+ var DNSInstance = class {
+ static {
+ __name(this, "DNSInstance");
+ }
+ #maxTTL = 0;
+ #maxItems = 0;
+ dualStack = true;
+ affinity = null;
+ lookup = null;
+ pick = null;
+ storage = null;
+ constructor(opts) {
+ this.#maxTTL = opts.maxTTL;
+ this.#maxItems = opts.maxItems;
+ this.dualStack = opts.dualStack;
+ this.affinity = opts.affinity;
+ this.lookup = opts.lookup ?? this.#defaultLookup;
+ this.pick = opts.pick ?? this.#defaultPick;
+ this.storage = opts.storage ?? new DNSStorage(opts);
+ }
+ runLookup(origin, opts, cb) {
+ const ips = this.storage.get(origin.hostname);
+ if (ips == null && this.storage.full()) {
+ cb(null, origin);
+ return;
+ }
+ const newOpts = {
+ affinity: this.affinity,
+ dualStack: this.dualStack,
+ lookup: this.lookup,
+ pick: this.pick,
+ ...opts.dns,
+ maxTTL: this.#maxTTL,
+ maxItems: this.#maxItems
+ };
+ if (ips == null) {
+ this.lookup(origin, newOpts, (err, addresses) => {
+ if (err || addresses == null || addresses.length === 0) {
+ cb(err ?? new InformationalError("No DNS entries found"));
+ return;
+ }
+ this.setRecords(origin, addresses);
+ const records = this.storage.get(origin.hostname);
+ const ip = this.pick(
+ origin,
+ records,
+ newOpts.affinity
+ );
+ let port;
+ if (typeof ip.port === "number") {
+ port = `:${ip.port}`;
+ } else if (origin.port !== "") {
+ port = `:${origin.port}`;
+ } else {
+ port = "";
+ }
+ cb(
+ null,
+ new URL(`${origin.protocol}//${ip.family === 6 ? `[${ip.address}]` : ip.address}${port}`)
+ );
+ });
+ } else {
+ const ip = this.pick(
+ origin,
+ ips,
+ newOpts.affinity
+ );
+ if (ip == null) {
+ this.storage.delete(origin.hostname);
+ this.runLookup(origin, opts, cb);
+ return;
+ }
+ let port;
+ if (typeof ip.port === "number") {
+ port = `:${ip.port}`;
+ } else if (origin.port !== "") {
+ port = `:${origin.port}`;
+ } else {
+ port = "";
+ }
+ cb(
+ null,
+ new URL(`${origin.protocol}//${ip.family === 6 ? `[${ip.address}]` : ip.address}${port}`)
+ );
+ }
+ }
+ #defaultLookup(origin, opts, cb) {
+ lookup(
+ origin.hostname,
+ {
+ all: true,
+ family: this.dualStack === false ? this.affinity : 0,
+ order: "ipv4first"
+ },
+ (err, addresses) => {
+ if (err) {
+ return cb(err);
+ }
+ const results = /* @__PURE__ */ new Map();
+ for (const addr of addresses) {
+ results.set(`${addr.address}:${addr.family}`, addr);
+ }
+ cb(null, results.values());
+ }
+ );
+ }
+ #defaultPick(origin, hostnameRecords, affinity) {
+ let ip = null;
+ const { records, offset } = hostnameRecords;
+ let family;
+ if (this.dualStack) {
+ if (affinity == null) {
+ if (offset == null || offset === maxInt) {
+ hostnameRecords.offset = 0;
+ affinity = 4;
+ } else {
+ hostnameRecords.offset++;
+ affinity = (hostnameRecords.offset & 1) === 1 ? 6 : 4;
+ }
+ }
+ if (records[affinity] != null && records[affinity].ips.length > 0) {
+ family = records[affinity];
+ } else {
+ family = records[affinity === 4 ? 6 : 4];
+ }
+ } else {
+ family = records[affinity];
+ }
+ if (family == null || family.ips.length === 0) {
+ return ip;
+ }
+ if (family.offset == null || family.offset === maxInt) {
+ family.offset = 0;
+ } else {
+ family.offset++;
+ }
+ const position = family.offset % family.ips.length;
+ ip = family.ips[position] ?? null;
+ if (ip == null) {
+ return ip;
+ }
+ if (Date.now() - ip.timestamp > ip.ttl) {
+ family.ips.splice(position, 1);
+ return this.pick(origin, hostnameRecords, affinity);
+ }
+ return ip;
+ }
+ pickFamily(origin, ipFamily) {
+ const records = this.storage.get(origin.hostname)?.records;
+ if (!records) {
+ return null;
+ }
+ const family = records[ipFamily];
+ if (!family) {
+ return null;
+ }
+ if (family.offset == null || family.offset === maxInt) {
+ family.offset = 0;
+ } else {
+ family.offset++;
+ }
+ const position = family.offset % family.ips.length;
+ const ip = family.ips[position] ?? null;
+ if (ip == null) {
+ return ip;
+ }
+ if (Date.now() - ip.timestamp > ip.ttl) {
+ family.ips.splice(position, 1);
+ }
+ return ip;
+ }
+ setRecords(origin, addresses) {
+ const timestamp = Date.now();
+ const records = { records: { 4: null, 6: null } };
+ let minTTL = this.#maxTTL;
+ for (const record2 of addresses) {
+ record2.timestamp = timestamp;
+ if (typeof record2.ttl === "number") {
+ record2.ttl = Math.min(record2.ttl, this.#maxTTL);
+ minTTL = Math.min(minTTL, record2.ttl);
+ } else {
+ record2.ttl = this.#maxTTL;
+ }
+ const familyRecords = records.records[record2.family] ?? { ips: [] };
+ familyRecords.ips.push(record2);
+ records.records[record2.family] = familyRecords;
+ }
+ this.storage.set(origin.hostname, records, { ttl: minTTL });
+ }
+ deleteRecords(origin) {
+ this.storage.delete(origin.hostname);
+ }
+ getHandler(meta3, opts) {
+ return new DNSDispatchHandler(this, meta3, opts);
+ }
+ };
+ var DNSDispatchHandler = class extends DecoratorHandler {
+ static {
+ __name(this, "DNSDispatchHandler");
+ }
+ #state = null;
+ #opts = null;
+ #dispatch = null;
+ #origin = null;
+ #controller = null;
+ #newOrigin = null;
+ #firstTry = true;
+ constructor(state, { origin, handler, dispatch, newOrigin }, opts) {
+ super(handler);
+ this.#origin = origin;
+ this.#newOrigin = newOrigin;
+ this.#opts = { ...opts };
+ this.#state = state;
+ this.#dispatch = dispatch;
+ }
+ onResponseError(controller, err) {
+ switch (err.code) {
+ case "ETIMEDOUT":
+ case "ECONNREFUSED": {
+ if (this.#state.dualStack) {
+ if (!this.#firstTry) {
+ super.onResponseError(controller, err);
+ return;
+ }
+ this.#firstTry = false;
+ const otherFamily = this.#newOrigin.hostname[0] === "[" ? 4 : 6;
+ const ip = this.#state.pickFamily(this.#origin, otherFamily);
+ if (ip == null) {
+ super.onResponseError(controller, err);
+ return;
+ }
+ let port;
+ if (typeof ip.port === "number") {
+ port = `:${ip.port}`;
+ } else if (this.#origin.port !== "") {
+ port = `:${this.#origin.port}`;
+ } else {
+ port = "";
+ }
+ const dispatchOpts = {
+ ...this.#opts,
+ origin: `${this.#origin.protocol}//${ip.family === 6 ? `[${ip.address}]` : ip.address}${port}`,
+ headers: withHostHeader(this.#origin.host, this.#opts.headers)
+ };
+ this.#dispatch(dispatchOpts, this);
+ return;
+ }
+ super.onResponseError(controller, err);
+ break;
+ }
+ case "ENOTFOUND":
+ this.#state.deleteRecords(this.#origin);
+ super.onResponseError(controller, err);
+ break;
+ default:
+ super.onResponseError(controller, err);
+ break;
+ }
+ }
+ };
+ module2.exports = (interceptorOpts) => {
+ if (interceptorOpts?.maxTTL != null && (typeof interceptorOpts?.maxTTL !== "number" || interceptorOpts?.maxTTL < 0)) {
+ throw new InvalidArgumentError("Invalid maxTTL. Must be a positive number");
+ }
+ if (interceptorOpts?.maxItems != null && (typeof interceptorOpts?.maxItems !== "number" || interceptorOpts?.maxItems < 1)) {
+ throw new InvalidArgumentError(
+ "Invalid maxItems. Must be a positive number and greater than zero"
+ );
+ }
+ if (interceptorOpts?.affinity != null && interceptorOpts?.affinity !== 4 && interceptorOpts?.affinity !== 6) {
+ throw new InvalidArgumentError("Invalid affinity. Must be either 4 or 6");
+ }
+ if (interceptorOpts?.dualStack != null && typeof interceptorOpts?.dualStack !== "boolean") {
+ throw new InvalidArgumentError("Invalid dualStack. Must be a boolean");
+ }
+ if (interceptorOpts?.lookup != null && typeof interceptorOpts?.lookup !== "function") {
+ throw new InvalidArgumentError("Invalid lookup. Must be a function");
+ }
+ if (interceptorOpts?.pick != null && typeof interceptorOpts?.pick !== "function") {
+ throw new InvalidArgumentError("Invalid pick. Must be a function");
+ }
+ if (interceptorOpts?.storage != null && (typeof interceptorOpts?.storage?.get !== "function" || typeof interceptorOpts?.storage?.set !== "function" || typeof interceptorOpts?.storage?.full !== "function" || typeof interceptorOpts?.storage?.delete !== "function")) {
+ throw new InvalidArgumentError("Invalid storage. Must be a object with methods: { get, set, full, delete }");
+ }
+ const dualStack = interceptorOpts?.dualStack ?? true;
+ let affinity;
+ if (dualStack) {
+ affinity = interceptorOpts?.affinity ?? null;
+ } else {
+ affinity = interceptorOpts?.affinity ?? 4;
+ }
+ const opts = {
+ maxTTL: interceptorOpts?.maxTTL ?? 1e4,
+ // Expressed in ms
+ lookup: interceptorOpts?.lookup ?? null,
+ pick: interceptorOpts?.pick ?? null,
+ dualStack,
+ affinity,
+ maxItems: interceptorOpts?.maxItems ?? Infinity,
+ storage: interceptorOpts?.storage
+ };
+ const instance = new DNSInstance(opts);
+ return (dispatch) => {
+ return /* @__PURE__ */ __name(function dnsInterceptor(origDispatchOpts, handler) {
+ const origin = origDispatchOpts.origin.constructor === URL ? origDispatchOpts.origin : new URL(origDispatchOpts.origin);
+ if (isIP(origin.hostname) !== 0) {
+ return dispatch(origDispatchOpts, handler);
+ }
+ instance.runLookup(origin, origDispatchOpts, (err, newOrigin) => {
+ if (err) {
+ return handler.onResponseError(null, err);
+ }
+ const dispatchOpts = {
+ ...origDispatchOpts,
+ servername: origin.hostname,
+ // For SNI on TLS
+ origin: newOrigin.origin,
+ headers: withHostHeader(origin.host, origDispatchOpts.headers)
+ };
+ dispatch(
+ dispatchOpts,
+ instance.getHandler(
+ { origin, dispatch, handler, newOrigin },
+ origDispatchOpts
+ )
+ );
+ });
+ return true;
+ }, "dnsInterceptor");
+ };
+ };
+ }
+});
+
+// node_modules/undici/lib/util/cache.js
+var require_cache = __commonJS({
+ "node_modules/undici/lib/util/cache.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var {
+ safeHTTPMethods,
+ pathHasQueryOrFragment,
+ hasSafeIterator
+ } = require_util();
+ var { serializePathWithQuery } = require_util();
+ function makeCacheKey(opts) {
+ if (!opts.origin) {
+ throw new Error("opts.origin is undefined");
+ }
+ let fullPath = opts.path || "/";
+ if (opts.query && !pathHasQueryOrFragment(fullPath)) {
+ fullPath = serializePathWithQuery(fullPath, opts.query);
+ }
+ return {
+ origin: opts.origin.toString(),
+ method: opts.method,
+ path: fullPath,
+ headers: opts.headers
+ };
+ }
+ __name(makeCacheKey, "makeCacheKey");
+ function normalizeHeaders(opts) {
+ let headers;
+ if (opts.headers == null) {
+ headers = {};
+ } else if (typeof opts.headers === "object") {
+ headers = {};
+ if (hasSafeIterator(opts.headers)) {
+ for (const x of opts.headers) {
+ if (!Array.isArray(x)) {
+ throw new Error("opts.headers is not a valid header map");
+ }
+ const [key, val] = x;
+ if (typeof key !== "string" || typeof val !== "string") {
+ throw new Error("opts.headers is not a valid header map");
+ }
+ headers[key.toLowerCase()] = val;
+ }
+ } else {
+ for (const key of Object.keys(opts.headers)) {
+ headers[key.toLowerCase()] = opts.headers[key];
+ }
+ }
+ } else {
+ throw new Error("opts.headers is not an object");
+ }
+ return headers;
+ }
+ __name(normalizeHeaders, "normalizeHeaders");
+ function assertCacheKey(key) {
+ if (typeof key !== "object") {
+ throw new TypeError(`expected key to be object, got ${typeof key}`);
+ }
+ for (const property of ["origin", "method", "path"]) {
+ if (typeof key[property] !== "string") {
+ throw new TypeError(`expected key.${property} to be string, got ${typeof key[property]}`);
+ }
+ }
+ if (key.headers !== void 0 && typeof key.headers !== "object") {
+ throw new TypeError(`expected headers to be object, got ${typeof key}`);
+ }
+ }
+ __name(assertCacheKey, "assertCacheKey");
+ function assertCacheValue(value) {
+ if (typeof value !== "object") {
+ throw new TypeError(`expected value to be object, got ${typeof value}`);
+ }
+ for (const property of ["statusCode", "cachedAt", "staleAt", "deleteAt"]) {
+ if (typeof value[property] !== "number") {
+ throw new TypeError(`expected value.${property} to be number, got ${typeof value[property]}`);
+ }
+ }
+ if (typeof value.statusMessage !== "string") {
+ throw new TypeError(`expected value.statusMessage to be string, got ${typeof value.statusMessage}`);
+ }
+ if (value.headers != null && typeof value.headers !== "object") {
+ throw new TypeError(`expected value.rawHeaders to be object, got ${typeof value.headers}`);
+ }
+ if (value.vary !== void 0 && typeof value.vary !== "object") {
+ throw new TypeError(`expected value.vary to be object, got ${typeof value.vary}`);
+ }
+ if (value.etag !== void 0 && typeof value.etag !== "string") {
+ throw new TypeError(`expected value.etag to be string, got ${typeof value.etag}`);
+ }
+ }
+ __name(assertCacheValue, "assertCacheValue");
+ function parseCacheControlHeader(header) {
+ const output = {};
+ let directives;
+ if (Array.isArray(header)) {
+ directives = [];
+ for (const directive of header) {
+ directives.push(...directive.split(","));
+ }
+ } else {
+ directives = header.split(",");
+ }
+ for (let i = 0; i < directives.length; i++) {
+ const directive = directives[i].toLowerCase();
+ const keyValueDelimiter = directive.indexOf("=");
+ let key;
+ let value;
+ if (keyValueDelimiter !== -1) {
+ key = directive.substring(0, keyValueDelimiter).trimStart();
+ value = directive.substring(keyValueDelimiter + 1);
+ } else {
+ key = directive.trim();
+ }
+ switch (key) {
+ case "min-fresh":
+ case "max-stale":
+ case "max-age":
+ case "s-maxage":
+ case "stale-while-revalidate":
+ case "stale-if-error": {
+ if (value === void 0 || value[0] === " ") {
+ continue;
+ }
+ if (value.length >= 2 && value[0] === '"' && value[value.length - 1] === '"') {
+ value = value.substring(1, value.length - 1);
+ }
+ const parsedValue = parseInt(value, 10);
+ if (parsedValue !== parsedValue) {
+ continue;
+ }
+ if (key === "max-age" && key in output && output[key] >= parsedValue) {
+ continue;
+ }
+ output[key] = parsedValue;
+ break;
+ }
+ case "private":
+ case "no-cache": {
+ if (value) {
+ if (value[0] === '"') {
+ const headers = [value.substring(1)];
+ let foundEndingQuote = value[value.length - 1] === '"';
+ if (!foundEndingQuote) {
+ for (let j = i + 1; j < directives.length; j++) {
+ const nextPart = directives[j];
+ const nextPartLength = nextPart.length;
+ headers.push(nextPart.trim());
+ if (nextPartLength !== 0 && nextPart[nextPartLength - 1] === '"') {
+ foundEndingQuote = true;
+ break;
+ }
+ }
+ }
+ if (foundEndingQuote) {
+ let lastHeader = headers[headers.length - 1];
+ if (lastHeader[lastHeader.length - 1] === '"') {
+ lastHeader = lastHeader.substring(0, lastHeader.length - 1);
+ headers[headers.length - 1] = lastHeader;
+ }
+ for (let j = 0; j < headers.length; j++) {
+ headers[j] = headers[j].trim();
+ }
+ if (key in output) {
+ output[key] = output[key].concat(headers);
+ } else {
+ output[key] = headers;
+ }
+ }
+ } else {
+ const fieldName = value.trim();
+ if (key in output) {
+ output[key] = output[key].concat(fieldName);
+ } else {
+ output[key] = [fieldName];
+ }
+ }
+ break;
+ }
+ }
+ // eslint-disable-next-line no-fallthrough
+ case "public":
+ case "no-store":
+ case "must-revalidate":
+ case "proxy-revalidate":
+ case "immutable":
+ case "no-transform":
+ case "must-understand":
+ case "only-if-cached":
+ if (value) {
+ continue;
+ }
+ output[key] = true;
+ break;
+ default:
+ continue;
+ }
+ }
+ return output;
+ }
+ __name(parseCacheControlHeader, "parseCacheControlHeader");
+ function parseVaryHeader(varyHeader, headers) {
+ if (typeof varyHeader === "string" && varyHeader.includes("*")) {
+ return headers;
+ }
+ const output = (
+ /** @type {Record} */
+ {}
+ );
+ const varyingHeaders = typeof varyHeader === "string" ? varyHeader.split(",") : varyHeader;
+ for (const header of varyingHeaders) {
+ const trimmedHeader = header.trim().toLowerCase();
+ output[trimmedHeader] = headers[trimmedHeader] ?? null;
+ }
+ return output;
+ }
+ __name(parseVaryHeader, "parseVaryHeader");
+ function isEtagUsable(etag) {
+ if (etag.length <= 2) {
+ return false;
+ }
+ if (etag[0] === '"' && etag[etag.length - 1] === '"') {
+ return !(etag[1] === '"' || etag.startsWith('"W/'));
+ }
+ if (etag.startsWith('W/"') && etag[etag.length - 1] === '"') {
+ return etag.length !== 4;
+ }
+ return false;
+ }
+ __name(isEtagUsable, "isEtagUsable");
+ function assertCacheStore(store, name = "CacheStore") {
+ if (typeof store !== "object" || store === null) {
+ throw new TypeError(`expected type of ${name} to be a CacheStore, got ${store === null ? "null" : typeof store}`);
+ }
+ for (const fn of ["get", "createWriteStream", "delete"]) {
+ if (typeof store[fn] !== "function") {
+ throw new TypeError(`${name} needs to have a \`${fn}()\` function`);
+ }
+ }
+ }
+ __name(assertCacheStore, "assertCacheStore");
+ function assertCacheMethods(methods, name = "CacheMethods") {
+ if (!Array.isArray(methods)) {
+ throw new TypeError(`expected type of ${name} needs to be an array, got ${methods === null ? "null" : typeof methods}`);
+ }
+ if (methods.length === 0) {
+ throw new TypeError(`${name} needs to have at least one method`);
+ }
+ for (const method of methods) {
+ if (!safeHTTPMethods.includes(method)) {
+ throw new TypeError(`element of ${name}-array needs to be one of following values: ${safeHTTPMethods.join(", ")}, got ${method}`);
+ }
+ }
+ }
+ __name(assertCacheMethods, "assertCacheMethods");
+ function makeDeduplicationKey(cacheKey, excludeHeaders) {
+ const headers = {};
+ if (cacheKey.headers) {
+ const sortedHeaders = Object.keys(cacheKey.headers).sort();
+ for (const header of sortedHeaders) {
+ if (excludeHeaders?.has(header.toLowerCase())) {
+ continue;
+ }
+ headers[header] = cacheKey.headers[header];
+ }
+ }
+ return JSON.stringify([cacheKey.origin, cacheKey.method, cacheKey.path, headers]);
+ }
+ __name(makeDeduplicationKey, "makeDeduplicationKey");
+ module2.exports = {
+ makeCacheKey,
+ normalizeHeaders,
+ assertCacheKey,
+ assertCacheValue,
+ parseCacheControlHeader,
+ parseVaryHeader,
+ isEtagUsable,
+ assertCacheMethods,
+ assertCacheStore,
+ makeDeduplicationKey
+ };
+ }
+});
+
+// node_modules/undici/lib/util/date.js
+var require_date = __commonJS({
+ "node_modules/undici/lib/util/date.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ function parseHttpDate(date5) {
+ switch (date5[3]) {
+ case ",":
+ return parseImfDate(date5);
+ case " ":
+ return parseAscTimeDate(date5);
+ default:
+ return parseRfc850Date(date5);
+ }
+ }
+ __name(parseHttpDate, "parseHttpDate");
+ function parseImfDate(date5) {
+ if (date5.length !== 29 || date5[4] !== " " || date5[7] !== " " || date5[11] !== " " || date5[16] !== " " || date5[19] !== ":" || date5[22] !== ":" || date5[25] !== " " || date5[26] !== "G" || date5[27] !== "M" || date5[28] !== "T") {
+ return void 0;
+ }
+ let weekday = -1;
+ if (date5[0] === "S" && date5[1] === "u" && date5[2] === "n") {
+ weekday = 0;
+ } else if (date5[0] === "M" && date5[1] === "o" && date5[2] === "n") {
+ weekday = 1;
+ } else if (date5[0] === "T" && date5[1] === "u" && date5[2] === "e") {
+ weekday = 2;
+ } else if (date5[0] === "W" && date5[1] === "e" && date5[2] === "d") {
+ weekday = 3;
+ } else if (date5[0] === "T" && date5[1] === "h" && date5[2] === "u") {
+ weekday = 4;
+ } else if (date5[0] === "F" && date5[1] === "r" && date5[2] === "i") {
+ weekday = 5;
+ } else if (date5[0] === "S" && date5[1] === "a" && date5[2] === "t") {
+ weekday = 6;
+ } else {
+ return void 0;
+ }
+ let day = 0;
+ if (date5[5] === "0") {
+ const code = date5.charCodeAt(6);
+ if (code < 49 || code > 57) {
+ return void 0;
+ }
+ day = code - 48;
+ } else {
+ const code1 = date5.charCodeAt(5);
+ if (code1 < 49 || code1 > 51) {
+ return void 0;
+ }
+ const code2 = date5.charCodeAt(6);
+ if (code2 < 48 || code2 > 57) {
+ return void 0;
+ }
+ day = (code1 - 48) * 10 + (code2 - 48);
+ }
+ let monthIdx = -1;
+ if (date5[8] === "J" && date5[9] === "a" && date5[10] === "n") {
+ monthIdx = 0;
+ } else if (date5[8] === "F" && date5[9] === "e" && date5[10] === "b") {
+ monthIdx = 1;
+ } else if (date5[8] === "M" && date5[9] === "a") {
+ if (date5[10] === "r") {
+ monthIdx = 2;
+ } else if (date5[10] === "y") {
+ monthIdx = 4;
+ } else {
+ return void 0;
+ }
+ } else if (date5[8] === "J") {
+ if (date5[9] === "a" && date5[10] === "n") {
+ monthIdx = 0;
+ } else if (date5[9] === "u") {
+ if (date5[10] === "n") {
+ monthIdx = 5;
+ } else if (date5[10] === "l") {
+ monthIdx = 6;
+ } else {
+ return void 0;
+ }
+ } else {
+ return void 0;
+ }
+ } else if (date5[8] === "A") {
+ if (date5[9] === "p" && date5[10] === "r") {
+ monthIdx = 3;
+ } else if (date5[9] === "u" && date5[10] === "g") {
+ monthIdx = 7;
+ } else {
+ return void 0;
+ }
+ } else if (date5[8] === "S" && date5[9] === "e" && date5[10] === "p") {
+ monthIdx = 8;
+ } else if (date5[8] === "O" && date5[9] === "c" && date5[10] === "t") {
+ monthIdx = 9;
+ } else if (date5[8] === "N" && date5[9] === "o" && date5[10] === "v") {
+ monthIdx = 10;
+ } else if (date5[8] === "D" && date5[9] === "e" && date5[10] === "c") {
+ monthIdx = 11;
+ } else {
+ return void 0;
+ }
+ const yearDigit1 = date5.charCodeAt(12);
+ if (yearDigit1 < 48 || yearDigit1 > 57) {
+ return void 0;
+ }
+ const yearDigit2 = date5.charCodeAt(13);
+ if (yearDigit2 < 48 || yearDigit2 > 57) {
+ return void 0;
+ }
+ const yearDigit3 = date5.charCodeAt(14);
+ if (yearDigit3 < 48 || yearDigit3 > 57) {
+ return void 0;
+ }
+ const yearDigit4 = date5.charCodeAt(15);
+ if (yearDigit4 < 48 || yearDigit4 > 57) {
+ return void 0;
+ }
+ const year = (yearDigit1 - 48) * 1e3 + (yearDigit2 - 48) * 100 + (yearDigit3 - 48) * 10 + (yearDigit4 - 48);
+ let hour = 0;
+ if (date5[17] === "0") {
+ const code = date5.charCodeAt(18);
+ if (code < 48 || code > 57) {
+ return void 0;
+ }
+ hour = code - 48;
+ } else {
+ const code1 = date5.charCodeAt(17);
+ if (code1 < 48 || code1 > 50) {
+ return void 0;
+ }
+ const code2 = date5.charCodeAt(18);
+ if (code2 < 48 || code2 > 57) {
+ return void 0;
+ }
+ if (code1 === 50 && code2 > 51) {
+ return void 0;
+ }
+ hour = (code1 - 48) * 10 + (code2 - 48);
+ }
+ let minute = 0;
+ if (date5[20] === "0") {
+ const code = date5.charCodeAt(21);
+ if (code < 48 || code > 57) {
+ return void 0;
+ }
+ minute = code - 48;
+ } else {
+ const code1 = date5.charCodeAt(20);
+ if (code1 < 48 || code1 > 53) {
+ return void 0;
+ }
+ const code2 = date5.charCodeAt(21);
+ if (code2 < 48 || code2 > 57) {
+ return void 0;
+ }
+ minute = (code1 - 48) * 10 + (code2 - 48);
+ }
+ let second = 0;
+ if (date5[23] === "0") {
+ const code = date5.charCodeAt(24);
+ if (code < 48 || code > 57) {
+ return void 0;
+ }
+ second = code - 48;
+ } else {
+ const code1 = date5.charCodeAt(23);
+ if (code1 < 48 || code1 > 53) {
+ return void 0;
+ }
+ const code2 = date5.charCodeAt(24);
+ if (code2 < 48 || code2 > 57) {
+ return void 0;
+ }
+ second = (code1 - 48) * 10 + (code2 - 48);
+ }
+ const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
+ return result.getUTCDay() === weekday ? result : void 0;
+ }
+ __name(parseImfDate, "parseImfDate");
+ function parseAscTimeDate(date5) {
+ if (date5.length !== 24 || date5[7] !== " " || date5[10] !== " " || date5[19] !== " ") {
+ return void 0;
+ }
+ let weekday = -1;
+ if (date5[0] === "S" && date5[1] === "u" && date5[2] === "n") {
+ weekday = 0;
+ } else if (date5[0] === "M" && date5[1] === "o" && date5[2] === "n") {
+ weekday = 1;
+ } else if (date5[0] === "T" && date5[1] === "u" && date5[2] === "e") {
+ weekday = 2;
+ } else if (date5[0] === "W" && date5[1] === "e" && date5[2] === "d") {
+ weekday = 3;
+ } else if (date5[0] === "T" && date5[1] === "h" && date5[2] === "u") {
+ weekday = 4;
+ } else if (date5[0] === "F" && date5[1] === "r" && date5[2] === "i") {
+ weekday = 5;
+ } else if (date5[0] === "S" && date5[1] === "a" && date5[2] === "t") {
+ weekday = 6;
+ } else {
+ return void 0;
+ }
+ let monthIdx = -1;
+ if (date5[4] === "J" && date5[5] === "a" && date5[6] === "n") {
+ monthIdx = 0;
+ } else if (date5[4] === "F" && date5[5] === "e" && date5[6] === "b") {
+ monthIdx = 1;
+ } else if (date5[4] === "M" && date5[5] === "a") {
+ if (date5[6] === "r") {
+ monthIdx = 2;
+ } else if (date5[6] === "y") {
+ monthIdx = 4;
+ } else {
+ return void 0;
+ }
+ } else if (date5[4] === "J") {
+ if (date5[5] === "a" && date5[6] === "n") {
+ monthIdx = 0;
+ } else if (date5[5] === "u") {
+ if (date5[6] === "n") {
+ monthIdx = 5;
+ } else if (date5[6] === "l") {
+ monthIdx = 6;
+ } else {
+ return void 0;
+ }
+ } else {
+ return void 0;
+ }
+ } else if (date5[4] === "A") {
+ if (date5[5] === "p" && date5[6] === "r") {
+ monthIdx = 3;
+ } else if (date5[5] === "u" && date5[6] === "g") {
+ monthIdx = 7;
+ } else {
+ return void 0;
+ }
+ } else if (date5[4] === "S" && date5[5] === "e" && date5[6] === "p") {
+ monthIdx = 8;
+ } else if (date5[4] === "O" && date5[5] === "c" && date5[6] === "t") {
+ monthIdx = 9;
+ } else if (date5[4] === "N" && date5[5] === "o" && date5[6] === "v") {
+ monthIdx = 10;
+ } else if (date5[4] === "D" && date5[5] === "e" && date5[6] === "c") {
+ monthIdx = 11;
+ } else {
+ return void 0;
+ }
+ let day = 0;
+ if (date5[8] === " ") {
+ const code = date5.charCodeAt(9);
+ if (code < 49 || code > 57) {
+ return void 0;
+ }
+ day = code - 48;
+ } else {
+ const code1 = date5.charCodeAt(8);
+ if (code1 < 49 || code1 > 51) {
+ return void 0;
+ }
+ const code2 = date5.charCodeAt(9);
+ if (code2 < 48 || code2 > 57) {
+ return void 0;
+ }
+ day = (code1 - 48) * 10 + (code2 - 48);
+ }
+ let hour = 0;
+ if (date5[11] === "0") {
+ const code = date5.charCodeAt(12);
+ if (code < 48 || code > 57) {
+ return void 0;
+ }
+ hour = code - 48;
+ } else {
+ const code1 = date5.charCodeAt(11);
+ if (code1 < 48 || code1 > 50) {
+ return void 0;
+ }
+ const code2 = date5.charCodeAt(12);
+ if (code2 < 48 || code2 > 57) {
+ return void 0;
+ }
+ if (code1 === 50 && code2 > 51) {
+ return void 0;
+ }
+ hour = (code1 - 48) * 10 + (code2 - 48);
+ }
+ let minute = 0;
+ if (date5[14] === "0") {
+ const code = date5.charCodeAt(15);
+ if (code < 48 || code > 57) {
+ return void 0;
+ }
+ minute = code - 48;
+ } else {
+ const code1 = date5.charCodeAt(14);
+ if (code1 < 48 || code1 > 53) {
+ return void 0;
+ }
+ const code2 = date5.charCodeAt(15);
+ if (code2 < 48 || code2 > 57) {
+ return void 0;
+ }
+ minute = (code1 - 48) * 10 + (code2 - 48);
+ }
+ let second = 0;
+ if (date5[17] === "0") {
+ const code = date5.charCodeAt(18);
+ if (code < 48 || code > 57) {
+ return void 0;
+ }
+ second = code - 48;
+ } else {
+ const code1 = date5.charCodeAt(17);
+ if (code1 < 48 || code1 > 53) {
+ return void 0;
+ }
+ const code2 = date5.charCodeAt(18);
+ if (code2 < 48 || code2 > 57) {
+ return void 0;
+ }
+ second = (code1 - 48) * 10 + (code2 - 48);
+ }
+ const yearDigit1 = date5.charCodeAt(20);
+ if (yearDigit1 < 48 || yearDigit1 > 57) {
+ return void 0;
+ }
+ const yearDigit2 = date5.charCodeAt(21);
+ if (yearDigit2 < 48 || yearDigit2 > 57) {
+ return void 0;
+ }
+ const yearDigit3 = date5.charCodeAt(22);
+ if (yearDigit3 < 48 || yearDigit3 > 57) {
+ return void 0;
+ }
+ const yearDigit4 = date5.charCodeAt(23);
+ if (yearDigit4 < 48 || yearDigit4 > 57) {
+ return void 0;
+ }
+ const year = (yearDigit1 - 48) * 1e3 + (yearDigit2 - 48) * 100 + (yearDigit3 - 48) * 10 + (yearDigit4 - 48);
+ const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
+ return result.getUTCDay() === weekday ? result : void 0;
+ }
+ __name(parseAscTimeDate, "parseAscTimeDate");
+ function parseRfc850Date(date5) {
+ let commaIndex = -1;
+ let weekday = -1;
+ if (date5[0] === "S") {
+ if (date5[1] === "u" && date5[2] === "n" && date5[3] === "d" && date5[4] === "a" && date5[5] === "y") {
+ weekday = 0;
+ commaIndex = 6;
+ } else if (date5[1] === "a" && date5[2] === "t" && date5[3] === "u" && date5[4] === "r" && date5[5] === "d" && date5[6] === "a" && date5[7] === "y") {
+ weekday = 6;
+ commaIndex = 8;
+ }
+ } else if (date5[0] === "M" && date5[1] === "o" && date5[2] === "n" && date5[3] === "d" && date5[4] === "a" && date5[5] === "y") {
+ weekday = 1;
+ commaIndex = 6;
+ } else if (date5[0] === "T") {
+ if (date5[1] === "u" && date5[2] === "e" && date5[3] === "s" && date5[4] === "d" && date5[5] === "a" && date5[6] === "y") {
+ weekday = 2;
+ commaIndex = 7;
+ } else if (date5[1] === "h" && date5[2] === "u" && date5[3] === "r" && date5[4] === "s" && date5[5] === "d" && date5[6] === "a" && date5[7] === "y") {
+ weekday = 4;
+ commaIndex = 8;
+ }
+ } else if (date5[0] === "W" && date5[1] === "e" && date5[2] === "d" && date5[3] === "n" && date5[4] === "e" && date5[5] === "s" && date5[6] === "d" && date5[7] === "a" && date5[8] === "y") {
+ weekday = 3;
+ commaIndex = 9;
+ } else if (date5[0] === "F" && date5[1] === "r" && date5[2] === "i" && date5[3] === "d" && date5[4] === "a" && date5[5] === "y") {
+ weekday = 5;
+ commaIndex = 6;
+ } else {
+ return void 0;
+ }
+ if (date5[commaIndex] !== "," || date5.length - commaIndex - 1 !== 23 || date5[commaIndex + 1] !== " " || date5[commaIndex + 4] !== "-" || date5[commaIndex + 8] !== "-" || date5[commaIndex + 11] !== " " || date5[commaIndex + 14] !== ":" || date5[commaIndex + 17] !== ":" || date5[commaIndex + 20] !== " " || date5[commaIndex + 21] !== "G" || date5[commaIndex + 22] !== "M" || date5[commaIndex + 23] !== "T") {
+ return void 0;
+ }
+ let day = 0;
+ if (date5[commaIndex + 2] === "0") {
+ const code = date5.charCodeAt(commaIndex + 3);
+ if (code < 49 || code > 57) {
+ return void 0;
+ }
+ day = code - 48;
+ } else {
+ const code1 = date5.charCodeAt(commaIndex + 2);
+ if (code1 < 49 || code1 > 51) {
+ return void 0;
+ }
+ const code2 = date5.charCodeAt(commaIndex + 3);
+ if (code2 < 48 || code2 > 57) {
+ return void 0;
+ }
+ day = (code1 - 48) * 10 + (code2 - 48);
+ }
+ let monthIdx = -1;
+ if (date5[commaIndex + 5] === "J" && date5[commaIndex + 6] === "a" && date5[commaIndex + 7] === "n") {
+ monthIdx = 0;
+ } else if (date5[commaIndex + 5] === "F" && date5[commaIndex + 6] === "e" && date5[commaIndex + 7] === "b") {
+ monthIdx = 1;
+ } else if (date5[commaIndex + 5] === "M" && date5[commaIndex + 6] === "a" && date5[commaIndex + 7] === "r") {
+ monthIdx = 2;
+ } else if (date5[commaIndex + 5] === "A" && date5[commaIndex + 6] === "p" && date5[commaIndex + 7] === "r") {
+ monthIdx = 3;
+ } else if (date5[commaIndex + 5] === "M" && date5[commaIndex + 6] === "a" && date5[commaIndex + 7] === "y") {
+ monthIdx = 4;
+ } else if (date5[commaIndex + 5] === "J" && date5[commaIndex + 6] === "u" && date5[commaIndex + 7] === "n") {
+ monthIdx = 5;
+ } else if (date5[commaIndex + 5] === "J" && date5[commaIndex + 6] === "u" && date5[commaIndex + 7] === "l") {
+ monthIdx = 6;
+ } else if (date5[commaIndex + 5] === "A" && date5[commaIndex + 6] === "u" && date5[commaIndex + 7] === "g") {
+ monthIdx = 7;
+ } else if (date5[commaIndex + 5] === "S" && date5[commaIndex + 6] === "e" && date5[commaIndex + 7] === "p") {
+ monthIdx = 8;
+ } else if (date5[commaIndex + 5] === "O" && date5[commaIndex + 6] === "c" && date5[commaIndex + 7] === "t") {
+ monthIdx = 9;
+ } else if (date5[commaIndex + 5] === "N" && date5[commaIndex + 6] === "o" && date5[commaIndex + 7] === "v") {
+ monthIdx = 10;
+ } else if (date5[commaIndex + 5] === "D" && date5[commaIndex + 6] === "e" && date5[commaIndex + 7] === "c") {
+ monthIdx = 11;
+ } else {
+ return void 0;
+ }
+ const yearDigit1 = date5.charCodeAt(commaIndex + 9);
+ if (yearDigit1 < 48 || yearDigit1 > 57) {
+ return void 0;
+ }
+ const yearDigit2 = date5.charCodeAt(commaIndex + 10);
+ if (yearDigit2 < 48 || yearDigit2 > 57) {
+ return void 0;
+ }
+ let year = (yearDigit1 - 48) * 10 + (yearDigit2 - 48);
+ year += year < 70 ? 2e3 : 1900;
+ let hour = 0;
+ if (date5[commaIndex + 12] === "0") {
+ const code = date5.charCodeAt(commaIndex + 13);
+ if (code < 48 || code > 57) {
+ return void 0;
+ }
+ hour = code - 48;
+ } else {
+ const code1 = date5.charCodeAt(commaIndex + 12);
+ if (code1 < 48 || code1 > 50) {
+ return void 0;
+ }
+ const code2 = date5.charCodeAt(commaIndex + 13);
+ if (code2 < 48 || code2 > 57) {
+ return void 0;
+ }
+ if (code1 === 50 && code2 > 51) {
+ return void 0;
+ }
+ hour = (code1 - 48) * 10 + (code2 - 48);
+ }
+ let minute = 0;
+ if (date5[commaIndex + 15] === "0") {
+ const code = date5.charCodeAt(commaIndex + 16);
+ if (code < 48 || code > 57) {
+ return void 0;
+ }
+ minute = code - 48;
+ } else {
+ const code1 = date5.charCodeAt(commaIndex + 15);
+ if (code1 < 48 || code1 > 53) {
+ return void 0;
+ }
+ const code2 = date5.charCodeAt(commaIndex + 16);
+ if (code2 < 48 || code2 > 57) {
+ return void 0;
+ }
+ minute = (code1 - 48) * 10 + (code2 - 48);
+ }
+ let second = 0;
+ if (date5[commaIndex + 18] === "0") {
+ const code = date5.charCodeAt(commaIndex + 19);
+ if (code < 48 || code > 57) {
+ return void 0;
+ }
+ second = code - 48;
+ } else {
+ const code1 = date5.charCodeAt(commaIndex + 18);
+ if (code1 < 48 || code1 > 53) {
+ return void 0;
+ }
+ const code2 = date5.charCodeAt(commaIndex + 19);
+ if (code2 < 48 || code2 > 57) {
+ return void 0;
+ }
+ second = (code1 - 48) * 10 + (code2 - 48);
+ }
+ const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
+ return result.getUTCDay() === weekday ? result : void 0;
+ }
+ __name(parseRfc850Date, "parseRfc850Date");
+ module2.exports = {
+ parseHttpDate
+ };
+ }
+});
+
+// node_modules/undici/lib/handler/cache-handler.js
+var require_cache_handler = __commonJS({
+ "node_modules/undici/lib/handler/cache-handler.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var util = require_util();
+ var {
+ parseCacheControlHeader,
+ parseVaryHeader,
+ isEtagUsable
+ } = require_cache();
+ var { parseHttpDate } = require_date();
+ function noop3() {
+ }
+ __name(noop3, "noop");
+ var HEURISTICALLY_CACHEABLE_STATUS_CODES = [
+ 200,
+ 203,
+ 204,
+ 206,
+ 300,
+ 301,
+ 308,
+ 404,
+ 405,
+ 410,
+ 414,
+ 501
+ ];
+ var NOT_UNDERSTOOD_STATUS_CODES = [
+ 206
+ ];
+ var MAX_RESPONSE_AGE = 2147483647e3;
+ var CacheHandler = class {
+ static {
+ __name(this, "CacheHandler");
+ }
+ /**
+ * @type {import('../../types/cache-interceptor.d.ts').default.CacheKey}
+ */
+ #cacheKey;
+ /**
+ * @type {import('../../types/cache-interceptor.d.ts').default.CacheHandlerOptions['type']}
+ */
+ #cacheType;
+ /**
+ * @type {number | undefined}
+ */
+ #cacheByDefault;
+ /**
+ * @type {import('../../types/cache-interceptor.d.ts').default.CacheStore}
+ */
+ #store;
+ /**
+ * @type {import('../../types/dispatcher.d.ts').default.DispatchHandler}
+ */
+ #handler;
+ /**
+ * @type {import('node:stream').Writable | undefined}
+ */
+ #writeStream;
+ /**
+ * @param {import('../../types/cache-interceptor.d.ts').default.CacheHandlerOptions} opts
+ * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} cacheKey
+ * @param {import('../../types/dispatcher.d.ts').default.DispatchHandler} handler
+ */
+ constructor({ store, type: type2, cacheByDefault }, cacheKey, handler) {
+ this.#store = store;
+ this.#cacheType = type2;
+ this.#cacheByDefault = cacheByDefault;
+ this.#cacheKey = cacheKey;
+ this.#handler = handler;
+ }
+ onRequestStart(controller, context) {
+ this.#writeStream?.destroy();
+ this.#writeStream = void 0;
+ this.#handler.onRequestStart?.(controller, context);
+ }
+ onRequestUpgrade(controller, statusCode, headers, socket) {
+ this.#handler.onRequestUpgrade?.(controller, statusCode, headers, socket);
+ }
+ /**
+ * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
+ * @param {number} statusCode
+ * @param {import('../../types/header.d.ts').IncomingHttpHeaders} resHeaders
+ * @param {string} statusMessage
+ */
+ onResponseStart(controller, statusCode, resHeaders, statusMessage) {
+ const downstreamOnHeaders = /* @__PURE__ */ __name(() => this.#handler.onResponseStart?.(
+ controller,
+ statusCode,
+ resHeaders,
+ statusMessage
+ ), "downstreamOnHeaders");
+ const handler = this;
+ if (!util.safeHTTPMethods.includes(this.#cacheKey.method) && statusCode >= 200 && statusCode <= 399) {
+ try {
+ this.#store.delete(this.#cacheKey)?.catch?.(noop3);
+ } catch {
+ }
+ return downstreamOnHeaders();
+ }
+ const cacheControlHeader = resHeaders["cache-control"];
+ const heuristicallyCacheable = resHeaders["last-modified"] && HEURISTICALLY_CACHEABLE_STATUS_CODES.includes(statusCode);
+ if (!cacheControlHeader && !resHeaders["expires"] && !heuristicallyCacheable && !this.#cacheByDefault) {
+ return downstreamOnHeaders();
+ }
+ const cacheControlDirectives = cacheControlHeader ? parseCacheControlHeader(cacheControlHeader) : {};
+ if (!canCacheResponse(this.#cacheType, statusCode, resHeaders, cacheControlDirectives, this.#cacheKey.headers)) {
+ return downstreamOnHeaders();
+ }
+ const now = Date.now();
+ const resAge = resHeaders.age ? getAge(resHeaders.age) : void 0;
+ if (resAge && resAge >= MAX_RESPONSE_AGE) {
+ return downstreamOnHeaders();
+ }
+ const resDate = typeof resHeaders.date === "string" ? parseHttpDate(resHeaders.date) : void 0;
+ const staleAt = determineStaleAt(this.#cacheType, now, resAge, resHeaders, resDate, cacheControlDirectives) ?? this.#cacheByDefault;
+ if (staleAt === void 0 || resAge && resAge > staleAt) {
+ return downstreamOnHeaders();
+ }
+ const baseTime = resDate ? resDate.getTime() : now;
+ const absoluteStaleAt = staleAt + baseTime;
+ if (now >= absoluteStaleAt) {
+ return downstreamOnHeaders();
+ }
+ let varyDirectives;
+ if (this.#cacheKey.headers && resHeaders.vary) {
+ varyDirectives = parseVaryHeader(resHeaders.vary, this.#cacheKey.headers);
+ if (!varyDirectives) {
+ return downstreamOnHeaders();
+ }
+ }
+ const deleteAt = determineDeleteAt(baseTime, cacheControlDirectives, absoluteStaleAt);
+ const strippedHeaders = stripNecessaryHeaders(resHeaders, cacheControlDirectives);
+ const value = {
+ statusCode,
+ statusMessage,
+ headers: strippedHeaders,
+ vary: varyDirectives,
+ cacheControlDirectives,
+ cachedAt: resAge ? now - resAge : now,
+ staleAt: absoluteStaleAt,
+ deleteAt
+ };
+ if (statusCode === 304) {
+ const handle304 = /* @__PURE__ */ __name((cachedValue) => {
+ if (!cachedValue) {
+ return downstreamOnHeaders();
+ }
+ value.statusCode = cachedValue.statusCode;
+ value.statusMessage = cachedValue.statusMessage;
+ value.etag = cachedValue.etag;
+ value.headers = { ...cachedValue.headers, ...strippedHeaders };
+ downstreamOnHeaders();
+ this.#writeStream = this.#store.createWriteStream(this.#cacheKey, value);
+ if (!this.#writeStream || !cachedValue?.body) {
+ return;
+ }
+ if (typeof cachedValue.body.values === "function") {
+ const bodyIterator = cachedValue.body.values();
+ const streamCachedBody = /* @__PURE__ */ __name(() => {
+ for (const chunk of bodyIterator) {
+ const full = this.#writeStream.write(chunk) === false;
+ this.#handler.onResponseData?.(controller, chunk);
+ if (full) {
+ break;
+ }
+ }
+ }, "streamCachedBody");
+ this.#writeStream.on("error", function() {
+ handler.#writeStream = void 0;
+ handler.#store.delete(handler.#cacheKey);
+ }).on("drain", () => {
+ streamCachedBody();
+ }).on("close", function() {
+ if (handler.#writeStream === this) {
+ handler.#writeStream = void 0;
+ }
+ });
+ streamCachedBody();
+ } else if (typeof cachedValue.body.on === "function") {
+ cachedValue.body.on("data", (chunk) => {
+ this.#writeStream.write(chunk);
+ this.#handler.onResponseData?.(controller, chunk);
+ }).on("end", () => {
+ this.#writeStream.end();
+ }).on("error", () => {
+ this.#writeStream = void 0;
+ this.#store.delete(this.#cacheKey);
+ });
+ this.#writeStream.on("error", function() {
+ handler.#writeStream = void 0;
+ handler.#store.delete(handler.#cacheKey);
+ }).on("close", function() {
+ if (handler.#writeStream === this) {
+ handler.#writeStream = void 0;
+ }
+ });
+ }
+ }, "handle304");
+ const result = this.#store.get(this.#cacheKey);
+ if (result && typeof result.then === "function") {
+ result.then(handle304);
+ } else {
+ handle304(result);
+ }
+ } else {
+ if (typeof resHeaders.etag === "string" && isEtagUsable(resHeaders.etag)) {
+ value.etag = resHeaders.etag;
+ }
+ this.#writeStream = this.#store.createWriteStream(this.#cacheKey, value);
+ if (!this.#writeStream) {
+ return downstreamOnHeaders();
+ }
+ this.#writeStream.on("drain", () => controller.resume()).on("error", function() {
+ handler.#writeStream = void 0;
+ handler.#store.delete(handler.#cacheKey);
+ }).on("close", function() {
+ if (handler.#writeStream === this) {
+ handler.#writeStream = void 0;
+ }
+ controller.resume();
+ });
+ downstreamOnHeaders();
+ }
+ }
+ onResponseData(controller, chunk) {
+ if (this.#writeStream?.write(chunk) === false) {
+ controller.pause();
+ }
+ this.#handler.onResponseData?.(controller, chunk);
+ }
+ onResponseEnd(controller, trailers) {
+ this.#writeStream?.end();
+ this.#handler.onResponseEnd?.(controller, trailers);
+ }
+ onResponseError(controller, err) {
+ this.#writeStream?.destroy(err);
+ this.#writeStream = void 0;
+ this.#handler.onResponseError?.(controller, err);
+ }
+ };
+ function canCacheResponse(cacheType, statusCode, resHeaders, cacheControlDirectives, reqHeaders) {
+ if (statusCode < 200 || NOT_UNDERSTOOD_STATUS_CODES.includes(statusCode)) {
+ return false;
+ }
+ if (!HEURISTICALLY_CACHEABLE_STATUS_CODES.includes(statusCode) && !resHeaders["expires"] && !cacheControlDirectives.public && cacheControlDirectives["max-age"] === void 0 && // RFC 9111: a private response directive, if the cache is not shared
+ !(cacheControlDirectives.private && cacheType === "private") && !(cacheControlDirectives["s-maxage"] !== void 0 && cacheType === "shared")) {
+ return false;
+ }
+ if (cacheControlDirectives["no-store"]) {
+ return false;
+ }
+ if (cacheType === "shared" && cacheControlDirectives.private === true) {
+ return false;
+ }
+ if (resHeaders.vary?.includes("*")) {
+ return false;
+ }
+ if (reqHeaders?.authorization) {
+ if (!cacheControlDirectives.public && !cacheControlDirectives["s-maxage"] && !cacheControlDirectives["must-revalidate"]) {
+ return false;
+ }
+ if (typeof reqHeaders.authorization !== "string") {
+ return false;
+ }
+ if (Array.isArray(cacheControlDirectives["no-cache"]) && cacheControlDirectives["no-cache"].includes("authorization")) {
+ return false;
+ }
+ if (Array.isArray(cacheControlDirectives["private"]) && cacheControlDirectives["private"].includes("authorization")) {
+ return false;
+ }
+ }
+ return true;
+ }
+ __name(canCacheResponse, "canCacheResponse");
+ function getAge(ageHeader) {
+ const age = parseInt(Array.isArray(ageHeader) ? ageHeader[0] : ageHeader);
+ return isNaN(age) ? void 0 : age * 1e3;
+ }
+ __name(getAge, "getAge");
+ function determineStaleAt(cacheType, now, age, resHeaders, responseDate, cacheControlDirectives) {
+ if (cacheType === "shared") {
+ const sMaxAge = cacheControlDirectives["s-maxage"];
+ if (sMaxAge !== void 0) {
+ return sMaxAge > 0 ? sMaxAge * 1e3 : void 0;
+ }
+ }
+ const maxAge = cacheControlDirectives["max-age"];
+ if (maxAge !== void 0) {
+ return maxAge > 0 ? maxAge * 1e3 : void 0;
+ }
+ if (typeof resHeaders.expires === "string") {
+ const expiresDate = parseHttpDate(resHeaders.expires);
+ if (expiresDate) {
+ if (now >= expiresDate.getTime()) {
+ return void 0;
+ }
+ if (responseDate) {
+ if (responseDate >= expiresDate) {
+ return void 0;
+ }
+ if (age !== void 0 && age > expiresDate - responseDate) {
+ return void 0;
+ }
+ }
+ return expiresDate.getTime() - now;
+ }
+ }
+ if (typeof resHeaders["last-modified"] === "string") {
+ const lastModified = new Date(resHeaders["last-modified"]);
+ if (isValidDate(lastModified)) {
+ if (lastModified.getTime() >= now) {
+ return void 0;
+ }
+ const responseAge = now - lastModified.getTime();
+ return responseAge * 0.1;
+ }
+ }
+ if (cacheControlDirectives.immutable) {
+ return 31536e3;
+ }
+ return void 0;
+ }
+ __name(determineStaleAt, "determineStaleAt");
+ function determineDeleteAt(now, cacheControlDirectives, staleAt) {
+ let staleWhileRevalidate = -Infinity;
+ let staleIfError = -Infinity;
+ let immutable = -Infinity;
+ if (cacheControlDirectives["stale-while-revalidate"]) {
+ staleWhileRevalidate = staleAt + cacheControlDirectives["stale-while-revalidate"] * 1e3;
+ }
+ if (cacheControlDirectives["stale-if-error"]) {
+ staleIfError = staleAt + cacheControlDirectives["stale-if-error"] * 1e3;
+ }
+ if (cacheControlDirectives.immutable && staleWhileRevalidate === -Infinity && staleIfError === -Infinity) {
+ immutable = now + 31536e6;
+ }
+ if (staleWhileRevalidate === -Infinity && staleIfError === -Infinity && immutable === -Infinity) {
+ const freshnessLifetime = staleAt - now;
+ return staleAt + freshnessLifetime;
+ }
+ return Math.max(staleAt, staleWhileRevalidate, staleIfError, immutable);
+ }
+ __name(determineDeleteAt, "determineDeleteAt");
+ function stripNecessaryHeaders(resHeaders, cacheControlDirectives) {
+ const headersToRemove = [
+ "connection",
+ "proxy-authenticate",
+ "proxy-authentication-info",
+ "proxy-authorization",
+ "proxy-connection",
+ "te",
+ "transfer-encoding",
+ "upgrade",
+ // We'll add age back when serving it
+ "age"
+ ];
+ if (resHeaders["connection"]) {
+ if (Array.isArray(resHeaders["connection"])) {
+ headersToRemove.push(...resHeaders["connection"].map((header) => header.trim()));
+ } else {
+ headersToRemove.push(...resHeaders["connection"].split(",").map((header) => header.trim()));
+ }
+ }
+ if (Array.isArray(cacheControlDirectives["no-cache"])) {
+ headersToRemove.push(...cacheControlDirectives["no-cache"]);
+ }
+ if (Array.isArray(cacheControlDirectives["private"])) {
+ headersToRemove.push(...cacheControlDirectives["private"]);
+ }
+ let strippedHeaders;
+ for (const headerName of headersToRemove) {
+ if (resHeaders[headerName]) {
+ strippedHeaders ??= { ...resHeaders };
+ delete strippedHeaders[headerName];
+ }
+ }
+ return strippedHeaders ?? resHeaders;
+ }
+ __name(stripNecessaryHeaders, "stripNecessaryHeaders");
+ function isValidDate(date5) {
+ return date5 instanceof Date && Number.isFinite(date5.valueOf());
+ }
+ __name(isValidDate, "isValidDate");
+ module2.exports = CacheHandler;
+ }
+});
+
+// node_modules/undici/lib/cache/memory-cache-store.js
+var require_memory_cache_store = __commonJS({
+ "node_modules/undici/lib/cache/memory-cache-store.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { Writable } = __require("node:stream");
+ var { EventEmitter: EventEmitter3 } = __require("node:events");
+ var { assertCacheKey, assertCacheValue } = require_cache();
+ var MemoryCacheStore = class extends EventEmitter3 {
+ static {
+ __name(this, "MemoryCacheStore");
+ }
+ #maxCount = 1024;
+ #maxSize = 104857600;
+ // 100MB
+ #maxEntrySize = 5242880;
+ // 5MB
+ #size = 0;
+ #count = 0;
+ #entries = /* @__PURE__ */ new Map();
+ #hasEmittedMaxSizeEvent = false;
+ /**
+ * @param {import('../../types/cache-interceptor.d.ts').default.MemoryCacheStoreOpts | undefined} [opts]
+ */
+ constructor(opts) {
+ super();
+ if (opts) {
+ if (typeof opts !== "object") {
+ throw new TypeError("MemoryCacheStore options must be an object");
+ }
+ if (opts.maxCount !== void 0) {
+ if (typeof opts.maxCount !== "number" || !Number.isInteger(opts.maxCount) || opts.maxCount < 0) {
+ throw new TypeError("MemoryCacheStore options.maxCount must be a non-negative integer");
+ }
+ this.#maxCount = opts.maxCount;
+ }
+ if (opts.maxSize !== void 0) {
+ if (typeof opts.maxSize !== "number" || !Number.isInteger(opts.maxSize) || opts.maxSize < 0) {
+ throw new TypeError("MemoryCacheStore options.maxSize must be a non-negative integer");
+ }
+ this.#maxSize = opts.maxSize;
+ }
+ if (opts.maxEntrySize !== void 0) {
+ if (typeof opts.maxEntrySize !== "number" || !Number.isInteger(opts.maxEntrySize) || opts.maxEntrySize < 0) {
+ throw new TypeError("MemoryCacheStore options.maxEntrySize must be a non-negative integer");
+ }
+ this.#maxEntrySize = opts.maxEntrySize;
+ }
+ }
+ }
+ /**
+ * Get the current size of the cache in bytes
+ * @returns {number} The current size of the cache in bytes
+ */
+ get size() {
+ return this.#size;
+ }
+ /**
+ * Check if the cache is full (either max size or max count reached)
+ * @returns {boolean} True if the cache is full, false otherwise
+ */
+ isFull() {
+ return this.#size >= this.#maxSize || this.#count >= this.#maxCount;
+ }
+ /**
+ * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} req
+ * @returns {import('../../types/cache-interceptor.d.ts').default.GetResult | undefined}
+ */
+ get(key) {
+ assertCacheKey(key);
+ const topLevelKey = `${key.origin}:${key.path}`;
+ const now = Date.now();
+ const entries = this.#entries.get(topLevelKey);
+ const entry = entries ? findEntry(key, entries, now) : null;
+ return entry == null ? void 0 : {
+ statusMessage: entry.statusMessage,
+ statusCode: entry.statusCode,
+ headers: entry.headers,
+ body: entry.body,
+ vary: entry.vary ? entry.vary : void 0,
+ etag: entry.etag,
+ cacheControlDirectives: entry.cacheControlDirectives,
+ cachedAt: entry.cachedAt,
+ staleAt: entry.staleAt,
+ deleteAt: entry.deleteAt
+ };
+ }
+ /**
+ * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
+ * @param {import('../../types/cache-interceptor.d.ts').default.CacheValue} val
+ * @returns {Writable | undefined}
+ */
+ createWriteStream(key, val) {
+ assertCacheKey(key);
+ assertCacheValue(val);
+ const topLevelKey = `${key.origin}:${key.path}`;
+ const store = this;
+ const entry = { ...key, ...val, body: [], size: 0 };
+ return new Writable({
+ write(chunk, encoding, callback) {
+ if (typeof chunk === "string") {
+ chunk = Buffer.from(chunk, encoding);
+ }
+ entry.size += chunk.byteLength;
+ if (entry.size >= store.#maxEntrySize) {
+ this.destroy();
+ } else {
+ entry.body.push(chunk);
+ }
+ callback(null);
+ },
+ final(callback) {
+ let entries = store.#entries.get(topLevelKey);
+ if (!entries) {
+ entries = [];
+ store.#entries.set(topLevelKey, entries);
+ }
+ const previousEntry = findEntry(key, entries, Date.now());
+ if (previousEntry) {
+ const index = entries.indexOf(previousEntry);
+ entries.splice(index, 1, entry);
+ store.#size -= previousEntry.size;
+ } else {
+ entries.push(entry);
+ store.#count += 1;
+ }
+ store.#size += entry.size;
+ if (store.#size > store.#maxSize || store.#count > store.#maxCount) {
+ if (!store.#hasEmittedMaxSizeEvent) {
+ store.emit("maxSizeExceeded", {
+ size: store.#size,
+ maxSize: store.#maxSize,
+ count: store.#count,
+ maxCount: store.#maxCount
+ });
+ store.#hasEmittedMaxSizeEvent = true;
+ }
+ for (const [key2, entries2] of store.#entries) {
+ for (const entry2 of entries2.splice(0, entries2.length / 2)) {
+ store.#size -= entry2.size;
+ store.#count -= 1;
+ }
+ if (entries2.length === 0) {
+ store.#entries.delete(key2);
+ }
+ }
+ if (store.#size < store.#maxSize && store.#count < store.#maxCount) {
+ store.#hasEmittedMaxSizeEvent = false;
+ }
+ }
+ callback(null);
+ }
+ });
+ }
+ /**
+ * @param {CacheKey} key
+ */
+ delete(key) {
+ if (typeof key !== "object") {
+ throw new TypeError(`expected key to be object, got ${typeof key}`);
+ }
+ const topLevelKey = `${key.origin}:${key.path}`;
+ for (const entry of this.#entries.get(topLevelKey) ?? []) {
+ this.#size -= entry.size;
+ this.#count -= 1;
+ }
+ this.#entries.delete(topLevelKey);
+ }
+ };
+ function findEntry(key, entries, now) {
+ return entries.find((entry) => entry.deleteAt > now && entry.method === key.method && (entry.vary == null || Object.keys(entry.vary).every((headerName) => {
+ if (entry.vary[headerName] === null) {
+ return key.headers[headerName] === void 0;
+ }
+ return entry.vary[headerName] === key.headers[headerName];
+ })));
+ }
+ __name(findEntry, "findEntry");
+ module2.exports = MemoryCacheStore;
+ }
+});
+
+// node_modules/undici/lib/handler/cache-revalidation-handler.js
+var require_cache_revalidation_handler = __commonJS({
+ "node_modules/undici/lib/handler/cache-revalidation-handler.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var assert2 = __require("node:assert");
+ var CacheRevalidationHandler = class {
+ static {
+ __name(this, "CacheRevalidationHandler");
+ }
+ #successful = false;
+ /**
+ * @type {((boolean, any) => void) | null}
+ */
+ #callback;
+ /**
+ * @type {(import('../../types/dispatcher.d.ts').default.DispatchHandler)}
+ */
+ #handler;
+ #context;
+ /**
+ * @type {boolean}
+ */
+ #allowErrorStatusCodes;
+ /**
+ * @param {(boolean) => void} callback Function to call if the cached value is valid
+ * @param {import('../../types/dispatcher.d.ts').default.DispatchHandlers} handler
+ * @param {boolean} allowErrorStatusCodes
+ */
+ constructor(callback, handler, allowErrorStatusCodes) {
+ if (typeof callback !== "function") {
+ throw new TypeError("callback must be a function");
+ }
+ this.#callback = callback;
+ this.#handler = handler;
+ this.#allowErrorStatusCodes = allowErrorStatusCodes;
+ }
+ onRequestStart(_, context) {
+ this.#successful = false;
+ this.#context = context;
+ }
+ onRequestUpgrade(controller, statusCode, headers, socket) {
+ this.#handler.onRequestUpgrade?.(controller, statusCode, headers, socket);
+ }
+ onResponseStart(controller, statusCode, headers, statusMessage) {
+ assert2(this.#callback != null);
+ this.#successful = statusCode === 304 || this.#allowErrorStatusCodes && statusCode >= 500 && statusCode <= 504;
+ this.#callback(this.#successful, this.#context);
+ this.#callback = null;
+ if (this.#successful) {
+ return true;
+ }
+ this.#handler.onRequestStart?.(controller, this.#context);
+ this.#handler.onResponseStart?.(
+ controller,
+ statusCode,
+ headers,
+ statusMessage
+ );
+ }
+ onResponseData(controller, chunk) {
+ if (this.#successful) {
+ return;
+ }
+ return this.#handler.onResponseData?.(controller, chunk);
+ }
+ onResponseEnd(controller, trailers) {
+ if (this.#successful) {
+ return;
+ }
+ this.#handler.onResponseEnd?.(controller, trailers);
+ }
+ onResponseError(controller, err) {
+ if (this.#successful) {
+ return;
+ }
+ if (this.#callback) {
+ this.#callback(false);
+ this.#callback = null;
+ }
+ if (typeof this.#handler.onResponseError === "function") {
+ this.#handler.onResponseError(controller, err);
+ } else {
+ throw err;
+ }
+ }
+ };
+ module2.exports = CacheRevalidationHandler;
+ }
+});
+
+// node_modules/undici/lib/interceptor/cache.js
+var require_cache2 = __commonJS({
+ "node_modules/undici/lib/interceptor/cache.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var assert2 = __require("node:assert");
+ var { Readable } = __require("node:stream");
+ var util = require_util();
+ var CacheHandler = require_cache_handler();
+ var MemoryCacheStore = require_memory_cache_store();
+ var CacheRevalidationHandler = require_cache_revalidation_handler();
+ var { assertCacheStore, assertCacheMethods, makeCacheKey, normalizeHeaders, parseCacheControlHeader } = require_cache();
+ var { AbortError } = require_errors();
+ function assertCacheOrigins(origins, name) {
+ if (origins === void 0) return;
+ if (!Array.isArray(origins)) {
+ throw new TypeError(`expected ${name} to be an array or undefined, got ${typeof origins}`);
+ }
+ for (let i = 0; i < origins.length; i++) {
+ const origin = origins[i];
+ if (typeof origin !== "string" && !(origin instanceof RegExp)) {
+ throw new TypeError(`expected ${name}[${i}] to be a string or RegExp, got ${typeof origin}`);
+ }
+ }
+ }
+ __name(assertCacheOrigins, "assertCacheOrigins");
+ var nop = /* @__PURE__ */ __name(() => {
+ }, "nop");
+ function needsRevalidation(result, cacheControlDirectives, { headers = {} }) {
+ if (cacheControlDirectives?.["no-cache"]) {
+ return true;
+ }
+ if (result.cacheControlDirectives?.["no-cache"] && !Array.isArray(result.cacheControlDirectives["no-cache"])) {
+ return true;
+ }
+ if (headers["if-modified-since"] || headers["if-none-match"]) {
+ return true;
+ }
+ return false;
+ }
+ __name(needsRevalidation, "needsRevalidation");
+ function isStale(result, cacheControlDirectives) {
+ const now = Date.now();
+ if (now > result.staleAt) {
+ if (cacheControlDirectives?.["max-stale"]) {
+ const gracePeriod = result.staleAt + cacheControlDirectives["max-stale"] * 1e3;
+ return now > gracePeriod;
+ }
+ return true;
+ }
+ if (cacheControlDirectives?.["min-fresh"]) {
+ const timeLeftTillStale = result.staleAt - now;
+ const threshold = cacheControlDirectives["min-fresh"] * 1e3;
+ return timeLeftTillStale <= threshold;
+ }
+ return false;
+ }
+ __name(isStale, "isStale");
+ function withinStaleWhileRevalidateWindow(result) {
+ const staleWhileRevalidate = result.cacheControlDirectives?.["stale-while-revalidate"];
+ if (!staleWhileRevalidate) {
+ return false;
+ }
+ const now = Date.now();
+ const staleWhileRevalidateExpiry = result.staleAt + staleWhileRevalidate * 1e3;
+ return now <= staleWhileRevalidateExpiry;
+ }
+ __name(withinStaleWhileRevalidateWindow, "withinStaleWhileRevalidateWindow");
+ function handleUncachedResponse(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl) {
+ if (reqCacheControl?.["only-if-cached"]) {
+ let aborted2 = false;
+ try {
+ if (typeof handler.onConnect === "function") {
+ handler.onConnect(() => {
+ aborted2 = true;
+ });
+ if (aborted2) {
+ return;
+ }
+ }
+ if (typeof handler.onHeaders === "function") {
+ handler.onHeaders(504, [], nop, "Gateway Timeout");
+ if (aborted2) {
+ return;
+ }
+ }
+ if (typeof handler.onComplete === "function") {
+ handler.onComplete([]);
+ }
+ } catch (err) {
+ if (typeof handler.onError === "function") {
+ handler.onError(err);
+ }
+ }
+ return true;
+ }
+ return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
+ }
+ __name(handleUncachedResponse, "handleUncachedResponse");
+ function sendCachedValue(handler, opts, result, age, context, isStale2) {
+ const stream = util.isStream(result.body) ? result.body : Readable.from(result.body ?? []);
+ assert2(!stream.destroyed, "stream should not be destroyed");
+ assert2(!stream.readableDidRead, "stream should not be readableDidRead");
+ const controller = {
+ resume() {
+ stream.resume();
+ },
+ pause() {
+ stream.pause();
+ },
+ get paused() {
+ return stream.isPaused();
+ },
+ get aborted() {
+ return stream.destroyed;
+ },
+ get reason() {
+ return stream.errored;
+ },
+ abort(reason) {
+ stream.destroy(reason ?? new AbortError());
+ }
+ };
+ stream.on("error", function(err) {
+ if (!this.readableEnded) {
+ if (typeof handler.onResponseError === "function") {
+ handler.onResponseError(controller, err);
+ } else {
+ throw err;
+ }
+ }
+ }).on("close", function() {
+ if (!this.errored) {
+ handler.onResponseEnd?.(controller, {});
+ }
+ });
+ handler.onRequestStart?.(controller, context);
+ if (stream.destroyed) {
+ return;
+ }
+ const headers = { ...result.headers, age: String(age) };
+ if (isStale2) {
+ headers.warning = '110 - "response is stale"';
+ }
+ handler.onResponseStart?.(controller, result.statusCode, headers, result.statusMessage);
+ if (opts.method === "HEAD") {
+ stream.destroy();
+ } else {
+ stream.on("data", function(chunk) {
+ handler.onResponseData?.(controller, chunk);
+ });
+ }
+ }
+ __name(sendCachedValue, "sendCachedValue");
+ function handleResult(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl, result) {
+ if (!result) {
+ return handleUncachedResponse(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl);
+ }
+ const now = Date.now();
+ if (now > result.deleteAt) {
+ return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
+ }
+ const age = Math.round((now - result.cachedAt) / 1e3);
+ if (reqCacheControl?.["max-age"] && age >= reqCacheControl["max-age"]) {
+ return dispatch(opts, handler);
+ }
+ const stale = isStale(result, reqCacheControl);
+ const revalidate = needsRevalidation(result, reqCacheControl, opts);
+ if (stale || revalidate) {
+ if (util.isStream(opts.body) && util.bodyLength(opts.body) !== 0) {
+ return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
+ }
+ if (!revalidate && withinStaleWhileRevalidateWindow(result)) {
+ sendCachedValue(handler, opts, result, age, null, true);
+ queueMicrotask(() => {
+ const headers2 = {
+ ...opts.headers,
+ "if-modified-since": new Date(result.cachedAt).toUTCString()
+ };
+ if (result.etag) {
+ headers2["if-none-match"] = result.etag;
+ }
+ if (result.vary) {
+ for (const key in result.vary) {
+ if (result.vary[key] != null) {
+ headers2[key] = result.vary[key];
+ }
+ }
+ }
+ dispatch(
+ {
+ ...opts,
+ headers: headers2
+ },
+ new CacheHandler(globalOpts, cacheKey, {
+ // Silent handler that just updates the cache
+ onRequestStart() {
+ },
+ onRequestUpgrade() {
+ },
+ onResponseStart() {
+ },
+ onResponseData() {
+ },
+ onResponseEnd() {
+ },
+ onResponseError() {
+ }
+ })
+ );
+ });
+ return true;
+ }
+ let withinStaleIfErrorThreshold = false;
+ const staleIfErrorExpiry = result.cacheControlDirectives["stale-if-error"] ?? reqCacheControl?.["stale-if-error"];
+ if (staleIfErrorExpiry) {
+ withinStaleIfErrorThreshold = now < result.staleAt + staleIfErrorExpiry * 1e3;
+ }
+ const headers = {
+ ...opts.headers,
+ "if-modified-since": new Date(result.cachedAt).toUTCString()
+ };
+ if (result.etag) {
+ headers["if-none-match"] = result.etag;
+ }
+ if (result.vary) {
+ for (const key in result.vary) {
+ if (result.vary[key] != null) {
+ headers[key] = result.vary[key];
+ }
+ }
+ }
+ return dispatch(
+ {
+ ...opts,
+ headers
+ },
+ new CacheRevalidationHandler(
+ (success2, context) => {
+ if (success2) {
+ sendCachedValue(handler, opts, result, age, context, stale);
+ } else if (util.isStream(result.body)) {
+ result.body.on("error", nop).destroy();
+ }
+ },
+ new CacheHandler(globalOpts, cacheKey, handler),
+ withinStaleIfErrorThreshold
+ )
+ );
+ }
+ if (util.isStream(opts.body)) {
+ opts.body.on("error", nop).destroy();
+ }
+ sendCachedValue(handler, opts, result, age, null, false);
+ }
+ __name(handleResult, "handleResult");
+ module2.exports = (opts = {}) => {
+ const {
+ store = new MemoryCacheStore(),
+ methods = ["GET"],
+ cacheByDefault = void 0,
+ type: type2 = "shared",
+ origins = void 0
+ } = opts;
+ if (typeof opts !== "object" || opts === null) {
+ throw new TypeError(`expected type of opts to be an Object, got ${opts === null ? "null" : typeof opts}`);
+ }
+ assertCacheStore(store, "opts.store");
+ assertCacheMethods(methods, "opts.methods");
+ assertCacheOrigins(origins, "opts.origins");
+ if (typeof cacheByDefault !== "undefined" && typeof cacheByDefault !== "number") {
+ throw new TypeError(`expected opts.cacheByDefault to be number or undefined, got ${typeof cacheByDefault}`);
+ }
+ if (typeof type2 !== "undefined" && type2 !== "shared" && type2 !== "private") {
+ throw new TypeError(`expected opts.type to be shared, private, or undefined, got ${typeof type2}`);
+ }
+ const globalOpts = {
+ store,
+ methods,
+ cacheByDefault,
+ type: type2
+ };
+ const safeMethodsToNotCache = util.safeHTTPMethods.filter((method) => methods.includes(method) === false);
+ return (dispatch) => {
+ return (opts2, handler) => {
+ if (!opts2.origin || safeMethodsToNotCache.includes(opts2.method)) {
+ return dispatch(opts2, handler);
+ }
+ if (origins !== void 0) {
+ const requestOrigin = opts2.origin.toString().toLowerCase();
+ let isAllowed = false;
+ for (let i = 0; i < origins.length; i++) {
+ const allowed = origins[i];
+ if (typeof allowed === "string") {
+ if (allowed.toLowerCase() === requestOrigin) {
+ isAllowed = true;
+ break;
+ }
+ } else if (allowed.test(requestOrigin)) {
+ isAllowed = true;
+ break;
+ }
+ }
+ if (!isAllowed) {
+ return dispatch(opts2, handler);
+ }
+ }
+ opts2 = {
+ ...opts2,
+ headers: normalizeHeaders(opts2)
+ };
+ const reqCacheControl = opts2.headers?.["cache-control"] ? parseCacheControlHeader(opts2.headers["cache-control"]) : void 0;
+ if (reqCacheControl?.["no-store"]) {
+ return dispatch(opts2, handler);
+ }
+ const cacheKey = makeCacheKey(opts2);
+ const result = store.get(cacheKey);
+ if (result && typeof result.then === "function") {
+ return result.then((result2) => handleResult(
+ dispatch,
+ globalOpts,
+ cacheKey,
+ handler,
+ opts2,
+ reqCacheControl,
+ result2
+ ));
+ } else {
+ return handleResult(
+ dispatch,
+ globalOpts,
+ cacheKey,
+ handler,
+ opts2,
+ reqCacheControl,
+ result
+ );
+ }
+ };
+ };
+ };
+ }
+});
+
+// node_modules/undici/lib/interceptor/decompress.js
+var require_decompress = __commonJS({
+ "node_modules/undici/lib/interceptor/decompress.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { createInflate, createGunzip, createBrotliDecompress, createZstdDecompress } = __require("node:zlib");
+ var { pipeline } = __require("node:stream");
+ var DecoratorHandler = require_decorator_handler();
+ var { runtimeFeatures } = require_runtime_features();
+ var supportedEncodings = {
+ gzip: createGunzip,
+ "x-gzip": createGunzip,
+ br: createBrotliDecompress,
+ deflate: createInflate,
+ compress: createInflate,
+ "x-compress": createInflate,
+ ...runtimeFeatures.has("zstd") ? { zstd: createZstdDecompress } : {}
+ };
+ var defaultSkipStatusCodes = (
+ /** @type {const} */
+ [204, 304]
+ );
+ var warningEmitted = (
+ /** @type {boolean} */
+ false
+ );
+ var DecompressHandler = class extends DecoratorHandler {
+ static {
+ __name(this, "DecompressHandler");
+ }
+ /** @type {Transform[]} */
+ #decompressors = [];
+ /** @type {Readonly} */
+ #skipStatusCodes;
+ /** @type {boolean} */
+ #skipErrorResponses;
+ constructor(handler, { skipStatusCodes = defaultSkipStatusCodes, skipErrorResponses = true } = {}) {
+ super(handler);
+ this.#skipStatusCodes = skipStatusCodes;
+ this.#skipErrorResponses = skipErrorResponses;
+ }
+ /**
+ * Determines if decompression should be skipped based on encoding and status code
+ * @param {string} contentEncoding - Content-Encoding header value
+ * @param {number} statusCode - HTTP status code of the response
+ * @returns {boolean} - True if decompression should be skipped
+ */
+ #shouldSkipDecompression(contentEncoding, statusCode) {
+ if (!contentEncoding || statusCode < 200) return true;
+ if (this.#skipStatusCodes.includes(statusCode)) return true;
+ if (this.#skipErrorResponses && statusCode >= 400) return true;
+ return false;
+ }
+ /**
+ * Creates a chain of decompressors for multiple content encodings
+ *
+ * @param {string} encodings - Comma-separated list of content encodings
+ * @returns {Array} - Array of decompressor streams
+ * @throws {Error} - If the number of content-encodings exceeds the maximum allowed
+ */
+ #createDecompressionChain(encodings) {
+ const parts = encodings.split(",");
+ const maxContentEncodings = 5;
+ if (parts.length > maxContentEncodings) {
+ throw new Error(`too many content-encodings in response: ${parts.length}, maximum allowed is ${maxContentEncodings}`);
+ }
+ const decompressors = [];
+ for (let i = parts.length - 1; i >= 0; i--) {
+ const encoding = parts[i].trim();
+ if (!encoding) continue;
+ if (!supportedEncodings[encoding]) {
+ decompressors.length = 0;
+ return decompressors;
+ }
+ decompressors.push(supportedEncodings[encoding]());
+ }
+ return decompressors;
+ }
+ /**
+ * Sets up event handlers for a decompressor stream using readable events
+ * @param {DecompressorStream} decompressor - The decompressor stream
+ * @param {Controller} controller - The controller to coordinate with
+ * @returns {void}
+ */
+ #setupDecompressorEvents(decompressor, controller) {
+ decompressor.on("readable", () => {
+ let chunk;
+ while ((chunk = decompressor.read()) !== null) {
+ const result = super.onResponseData(controller, chunk);
+ if (result === false) {
+ break;
+ }
+ }
+ });
+ decompressor.on("error", (error51) => {
+ super.onResponseError(controller, error51);
+ });
+ }
+ /**
+ * Sets up event handling for a single decompressor
+ * @param {Controller} controller - The controller to handle events
+ * @returns {void}
+ */
+ #setupSingleDecompressor(controller) {
+ const decompressor = this.#decompressors[0];
+ this.#setupDecompressorEvents(decompressor, controller);
+ decompressor.on("end", () => {
+ super.onResponseEnd(controller, {});
+ });
+ }
+ /**
+ * Sets up event handling for multiple chained decompressors using pipeline
+ * @param {Controller} controller - The controller to handle events
+ * @returns {void}
+ */
+ #setupMultipleDecompressors(controller) {
+ const lastDecompressor = this.#decompressors[this.#decompressors.length - 1];
+ this.#setupDecompressorEvents(lastDecompressor, controller);
+ pipeline(this.#decompressors, (err) => {
+ if (err) {
+ super.onResponseError(controller, err);
+ return;
+ }
+ super.onResponseEnd(controller, {});
+ });
+ }
+ /**
+ * Cleans up decompressor references to prevent memory leaks
+ * @returns {void}
+ */
+ #cleanupDecompressors() {
+ this.#decompressors.length = 0;
+ }
+ /**
+ * @param {Controller} controller
+ * @param {number} statusCode
+ * @param {Record} headers
+ * @param {string} statusMessage
+ * @returns {void}
+ */
+ onResponseStart(controller, statusCode, headers, statusMessage) {
+ const contentEncoding = headers["content-encoding"];
+ if (this.#shouldSkipDecompression(contentEncoding, statusCode)) {
+ return super.onResponseStart(controller, statusCode, headers, statusMessage);
+ }
+ const decompressors = this.#createDecompressionChain(contentEncoding.toLowerCase());
+ if (decompressors.length === 0) {
+ this.#cleanupDecompressors();
+ return super.onResponseStart(controller, statusCode, headers, statusMessage);
+ }
+ this.#decompressors = decompressors;
+ const { "content-encoding": _, "content-length": __, ...newHeaders } = headers;
+ if (this.#decompressors.length === 1) {
+ this.#setupSingleDecompressor(controller);
+ } else {
+ this.#setupMultipleDecompressors(controller);
+ }
+ return super.onResponseStart(controller, statusCode, newHeaders, statusMessage);
+ }
+ /**
+ * @param {Controller} controller
+ * @param {Buffer} chunk
+ * @returns {void}
+ */
+ onResponseData(controller, chunk) {
+ if (this.#decompressors.length > 0) {
+ this.#decompressors[0].write(chunk);
+ return;
+ }
+ super.onResponseData(controller, chunk);
+ }
+ /**
+ * @param {Controller} controller
+ * @param {Record | undefined} trailers
+ * @returns {void}
+ */
+ onResponseEnd(controller, trailers) {
+ if (this.#decompressors.length > 0) {
+ this.#decompressors[0].end();
+ this.#cleanupDecompressors();
+ return;
+ }
+ super.onResponseEnd(controller, trailers);
+ }
+ /**
+ * @param {Controller} controller
+ * @param {Error} err
+ * @returns {void}
+ */
+ onResponseError(controller, err) {
+ if (this.#decompressors.length > 0) {
+ for (const decompressor of this.#decompressors) {
+ decompressor.destroy(err);
+ }
+ this.#cleanupDecompressors();
+ }
+ super.onResponseError(controller, err);
+ }
+ };
+ function createDecompressInterceptor(options2 = {}) {
+ if (!warningEmitted) {
+ process.emitWarning(
+ "DecompressInterceptor is experimental and subject to change",
+ "ExperimentalWarning"
+ );
+ warningEmitted = true;
+ }
+ return (dispatch) => {
+ return (opts, handler) => {
+ const decompressHandler = new DecompressHandler(handler, options2);
+ return dispatch(opts, decompressHandler);
+ };
+ };
+ }
+ __name(createDecompressInterceptor, "createDecompressInterceptor");
+ module2.exports = createDecompressInterceptor;
+ }
+});
+
+// node_modules/undici/lib/handler/deduplication-handler.js
+var require_deduplication_handler = __commonJS({
+ "node_modules/undici/lib/handler/deduplication-handler.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { RequestAbortedError } = require_errors();
+ var DEFAULT_MAX_BUFFER_SIZE = 5 * 1024 * 1024;
+ var DeduplicationHandler = class {
+ static {
+ __name(this, "DeduplicationHandler");
+ }
+ /**
+ * @type {DispatchHandler}
+ */
+ #primaryHandler;
+ /**
+ * @type {WaitingHandler[]}
+ */
+ #waitingHandlers = [];
+ /**
+ * @type {number}
+ */
+ #maxBufferSize = DEFAULT_MAX_BUFFER_SIZE;
+ /**
+ * @type {number}
+ */
+ #statusCode = 0;
+ /**
+ * @type {Record}
+ */
+ #headers = {};
+ /**
+ * @type {string}
+ */
+ #statusMessage = "";
+ /**
+ * @type {boolean}
+ */
+ #aborted = false;
+ /**
+ * @type {boolean}
+ */
+ #responseStarted = false;
+ /**
+ * @type {boolean}
+ */
+ #responseDataStarted = false;
+ /**
+ * @type {boolean}
+ */
+ #completed = false;
+ /**
+ * @type {import('../../types/dispatcher.d.ts').default.DispatchController | null}
+ */
+ #controller = null;
+ /**
+ * @type {(() => void) | null}
+ */
+ #onComplete = null;
+ /**
+ * @param {DispatchHandler} primaryHandler The primary handler
+ * @param {() => void} onComplete Callback when request completes
+ * @param {number} [maxBufferSize] Maximum paused buffer size per waiting handler
+ */
+ constructor(primaryHandler, onComplete, maxBufferSize = DEFAULT_MAX_BUFFER_SIZE) {
+ this.#primaryHandler = primaryHandler;
+ this.#onComplete = onComplete;
+ this.#maxBufferSize = maxBufferSize;
+ }
+ /**
+ * Add a waiting handler that will receive response events.
+ * Returns false if deduplication can no longer safely attach this handler.
+ *
+ * @param {DispatchHandler} handler
+ * @returns {boolean}
+ */
+ addWaitingHandler(handler) {
+ if (this.#completed || this.#responseDataStarted) {
+ return false;
+ }
+ const waitingHandler = this.#createWaitingHandler(handler);
+ const waitingController = waitingHandler.controller;
+ try {
+ handler.onRequestStart?.(waitingController, null);
+ if (waitingController.aborted) {
+ waitingHandler.done = true;
+ return true;
+ }
+ if (this.#responseStarted) {
+ handler.onResponseStart?.(
+ waitingController,
+ this.#statusCode,
+ this.#headers,
+ this.#statusMessage
+ );
+ }
+ } catch {
+ waitingHandler.done = true;
+ return true;
+ }
+ if (!waitingController.aborted) {
+ this.#waitingHandlers.push(waitingHandler);
+ }
+ return true;
+ }
+ /**
+ * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
+ * @param {any} context
+ */
+ onRequestStart(controller, context) {
+ this.#controller = controller;
+ this.#primaryHandler.onRequestStart?.(controller, context);
+ }
+ /**
+ * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
+ * @param {number} statusCode
+ * @param {import('../../types/header.d.ts').IncomingHttpHeaders} headers
+ * @param {Socket} socket
+ */
+ onRequestUpgrade(controller, statusCode, headers, socket) {
+ this.#primaryHandler.onRequestUpgrade?.(controller, statusCode, headers, socket);
+ }
+ /**
+ * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
+ * @param {number} statusCode
+ * @param {Record} headers
+ * @param {string} statusMessage
+ */
+ onResponseStart(controller, statusCode, headers, statusMessage) {
+ this.#responseStarted = true;
+ this.#statusCode = statusCode;
+ this.#headers = headers;
+ this.#statusMessage = statusMessage;
+ this.#primaryHandler.onResponseStart?.(controller, statusCode, headers, statusMessage);
+ for (const waitingHandler of this.#waitingHandlers) {
+ const { handler, controller: waitingController } = waitingHandler;
+ if (waitingHandler.done || waitingController.aborted) {
+ waitingHandler.done = true;
+ continue;
+ }
+ try {
+ handler.onResponseStart?.(
+ waitingController,
+ statusCode,
+ headers,
+ statusMessage
+ );
+ } catch {
+ }
+ if (waitingController.aborted) {
+ waitingHandler.done = true;
+ }
+ }
+ this.#pruneDoneWaitingHandlers();
+ }
+ /**
+ * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
+ * @param {Buffer} chunk
+ */
+ onResponseData(controller, chunk) {
+ if (this.#aborted || this.#completed) {
+ return;
+ }
+ this.#responseDataStarted = true;
+ this.#primaryHandler.onResponseData?.(controller, chunk);
+ for (const waitingHandler of this.#waitingHandlers) {
+ const { handler, controller: waitingController } = waitingHandler;
+ if (waitingHandler.done || waitingController.aborted) {
+ waitingHandler.done = true;
+ continue;
+ }
+ if (waitingController.paused) {
+ this.#bufferWaitingChunk(waitingHandler, chunk);
+ continue;
+ }
+ try {
+ handler.onResponseData?.(waitingController, chunk);
+ } catch {
+ }
+ if (waitingController.aborted) {
+ waitingHandler.done = true;
+ waitingHandler.bufferedChunks = [];
+ waitingHandler.bufferedBytes = 0;
+ }
+ }
+ this.#pruneDoneWaitingHandlers();
+ }
+ /**
+ * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
+ * @param {object} trailers
+ */
+ onResponseEnd(controller, trailers) {
+ if (this.#aborted || this.#completed) {
+ return;
+ }
+ this.#completed = true;
+ this.#primaryHandler.onResponseEnd?.(controller, trailers);
+ for (const waitingHandler of this.#waitingHandlers) {
+ if (waitingHandler.done || waitingHandler.controller.aborted) {
+ waitingHandler.done = true;
+ continue;
+ }
+ this.#flushWaitingHandler(waitingHandler);
+ if (waitingHandler.done || waitingHandler.controller.aborted) {
+ waitingHandler.done = true;
+ continue;
+ }
+ if (waitingHandler.controller.paused && waitingHandler.bufferedChunks.length > 0) {
+ waitingHandler.pendingTrailers = trailers;
+ continue;
+ }
+ try {
+ waitingHandler.handler.onResponseEnd?.(waitingHandler.controller, trailers);
+ } catch {
+ }
+ waitingHandler.done = true;
+ }
+ this.#pruneDoneWaitingHandlers();
+ this.#onComplete?.();
+ }
+ /**
+ * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
+ * @param {Error} err
+ */
+ onResponseError(controller, err) {
+ if (this.#completed) {
+ return;
+ }
+ this.#aborted = true;
+ this.#completed = true;
+ this.#primaryHandler.onResponseError?.(controller, err);
+ for (const waitingHandler of this.#waitingHandlers) {
+ this.#errorWaitingHandler(waitingHandler, err);
+ }
+ this.#waitingHandlers = [];
+ this.#onComplete?.();
+ }
+ /**
+ * @param {DispatchHandler} handler
+ * @returns {WaitingHandler}
+ */
+ #createWaitingHandler(handler) {
+ const waitingHandler = {
+ handler,
+ controller: null,
+ bufferedChunks: [],
+ bufferedBytes: 0,
+ pendingTrailers: null,
+ done: false
+ };
+ const state = {
+ aborted: false,
+ paused: false,
+ reason: null
+ };
+ waitingHandler.controller = {
+ resume: /* @__PURE__ */ __name(() => {
+ if (state.aborted) {
+ return;
+ }
+ state.paused = false;
+ this.#flushWaitingHandler(waitingHandler);
+ if (this.#completed && waitingHandler.pendingTrailers && waitingHandler.bufferedChunks.length === 0 && !state.paused && !state.aborted) {
+ try {
+ waitingHandler.handler.onResponseEnd?.(waitingHandler.controller, waitingHandler.pendingTrailers);
+ } catch {
+ }
+ waitingHandler.pendingTrailers = null;
+ waitingHandler.done = true;
+ }
+ this.#pruneDoneWaitingHandlers();
+ }, "resume"),
+ pause: /* @__PURE__ */ __name(() => {
+ if (!state.aborted) {
+ state.paused = true;
+ }
+ }, "pause"),
+ get paused() {
+ return state.paused;
+ },
+ get aborted() {
+ return state.aborted;
+ },
+ get reason() {
+ return state.reason;
+ },
+ abort: /* @__PURE__ */ __name((reason) => {
+ state.aborted = true;
+ state.reason = reason ?? null;
+ waitingHandler.done = true;
+ waitingHandler.pendingTrailers = null;
+ waitingHandler.bufferedChunks = [];
+ waitingHandler.bufferedBytes = 0;
+ }, "abort")
+ };
+ return waitingHandler;
+ }
+ /**
+ * @param {WaitingHandler} waitingHandler
+ * @param {Buffer} chunk
+ */
+ #bufferWaitingChunk(waitingHandler, chunk) {
+ if (waitingHandler.done || waitingHandler.controller.aborted) {
+ waitingHandler.done = true;
+ waitingHandler.bufferedChunks = [];
+ waitingHandler.bufferedBytes = 0;
+ return;
+ }
+ const bufferedChunk = Buffer.from(chunk);
+ waitingHandler.bufferedChunks.push(bufferedChunk);
+ waitingHandler.bufferedBytes += bufferedChunk.length;
+ if (waitingHandler.bufferedBytes > this.#maxBufferSize) {
+ const err = new RequestAbortedError(`Deduplicated waiting handler exceeded maxBufferSize (${this.#maxBufferSize} bytes) while paused`);
+ this.#errorWaitingHandler(waitingHandler, err);
+ }
+ }
+ /**
+ * @param {WaitingHandler} waitingHandler
+ */
+ #flushWaitingHandler(waitingHandler) {
+ const { handler, controller } = waitingHandler;
+ while (!waitingHandler.done && !controller.aborted && !controller.paused && waitingHandler.bufferedChunks.length > 0) {
+ const bufferedChunk = waitingHandler.bufferedChunks.shift();
+ waitingHandler.bufferedBytes -= bufferedChunk.length;
+ try {
+ handler.onResponseData?.(controller, bufferedChunk);
+ } catch {
+ }
+ if (controller.aborted) {
+ waitingHandler.done = true;
+ waitingHandler.pendingTrailers = null;
+ waitingHandler.bufferedChunks = [];
+ waitingHandler.bufferedBytes = 0;
+ break;
+ }
+ }
+ }
+ /**
+ * @param {WaitingHandler} waitingHandler
+ * @param {Error} err
+ */
+ #errorWaitingHandler(waitingHandler, err) {
+ if (waitingHandler.done) {
+ return;
+ }
+ waitingHandler.done = true;
+ waitingHandler.pendingTrailers = null;
+ waitingHandler.bufferedChunks = [];
+ waitingHandler.bufferedBytes = 0;
+ try {
+ waitingHandler.controller.abort(err);
+ waitingHandler.handler.onResponseError?.(waitingHandler.controller, err);
+ } catch {
+ }
+ }
+ #pruneDoneWaitingHandlers() {
+ this.#waitingHandlers = this.#waitingHandlers.filter((waitingHandler) => waitingHandler.done === false);
+ }
+ };
+ module2.exports = DeduplicationHandler;
+ }
+});
+
+// node_modules/undici/lib/interceptor/deduplicate.js
+var require_deduplicate = __commonJS({
+ "node_modules/undici/lib/interceptor/deduplicate.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var diagnosticsChannel = __require("node:diagnostics_channel");
+ var util = require_util();
+ var DeduplicationHandler = require_deduplication_handler();
+ var { normalizeHeaders, makeCacheKey, makeDeduplicationKey } = require_cache();
+ var pendingRequestsChannel = diagnosticsChannel.channel("undici:request:pending-requests");
+ module2.exports = (opts = {}) => {
+ const {
+ methods = ["GET"],
+ skipHeaderNames = [],
+ excludeHeaderNames = [],
+ maxBufferSize = 5 * 1024 * 1024
+ } = opts;
+ if (typeof opts !== "object" || opts === null) {
+ throw new TypeError(`expected type of opts to be an Object, got ${opts === null ? "null" : typeof opts}`);
+ }
+ if (!Array.isArray(methods)) {
+ throw new TypeError(`expected opts.methods to be an array, got ${typeof methods}`);
+ }
+ for (const method of methods) {
+ if (!util.safeHTTPMethods.includes(method)) {
+ throw new TypeError(`expected opts.methods to only contain safe HTTP methods, got ${method}`);
+ }
+ }
+ if (!Array.isArray(skipHeaderNames)) {
+ throw new TypeError(`expected opts.skipHeaderNames to be an array, got ${typeof skipHeaderNames}`);
+ }
+ if (!Array.isArray(excludeHeaderNames)) {
+ throw new TypeError(`expected opts.excludeHeaderNames to be an array, got ${typeof excludeHeaderNames}`);
+ }
+ if (!Number.isFinite(maxBufferSize) || maxBufferSize <= 0) {
+ throw new TypeError(`expected opts.maxBufferSize to be a positive finite number, got ${maxBufferSize}`);
+ }
+ const skipHeaderNamesSet = new Set(skipHeaderNames.map((name) => name.toLowerCase()));
+ const excludeHeaderNamesSet = new Set(excludeHeaderNames.map((name) => name.toLowerCase()));
+ const pendingRequests = /* @__PURE__ */ new Map();
+ return (dispatch) => {
+ return (opts2, handler) => {
+ if (!opts2.origin || methods.includes(opts2.method) === false) {
+ return dispatch(opts2, handler);
+ }
+ opts2 = {
+ ...opts2,
+ headers: normalizeHeaders(opts2)
+ };
+ if (skipHeaderNamesSet.size > 0) {
+ for (const headerName of Object.keys(opts2.headers)) {
+ if (skipHeaderNamesSet.has(headerName.toLowerCase())) {
+ return dispatch(opts2, handler);
+ }
+ }
+ }
+ const cacheKey = makeCacheKey(opts2);
+ const dedupeKey = makeDeduplicationKey(cacheKey, excludeHeaderNamesSet);
+ const pendingHandler = pendingRequests.get(dedupeKey);
+ if (pendingHandler) {
+ if (pendingHandler.addWaitingHandler(handler)) {
+ return true;
+ }
+ return dispatch(opts2, handler);
+ }
+ const deduplicationHandler = new DeduplicationHandler(
+ handler,
+ () => {
+ pendingRequests.delete(dedupeKey);
+ if (pendingRequestsChannel.hasSubscribers) {
+ pendingRequestsChannel.publish({ size: pendingRequests.size, key: dedupeKey, type: "removed" });
+ }
+ },
+ maxBufferSize
+ );
+ pendingRequests.set(dedupeKey, deduplicationHandler);
+ if (pendingRequestsChannel.hasSubscribers) {
+ pendingRequestsChannel.publish({ size: pendingRequests.size, key: dedupeKey, type: "added" });
+ }
+ return dispatch(opts2, deduplicationHandler);
+ };
+ };
+ };
+ }
+});
+
+// node_modules/undici/lib/cache/sqlite-cache-store.js
+var require_sqlite_cache_store = __commonJS({
+ "node_modules/undici/lib/cache/sqlite-cache-store.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { Writable } = __require("node:stream");
+ var { assertCacheKey, assertCacheValue } = require_cache();
+ var DatabaseSync;
+ var VERSION2 = 3;
+ var MAX_ENTRY_SIZE = 2 * 1e3 * 1e3 * 1e3;
+ module2.exports = class SqliteCacheStore {
+ static {
+ __name(this, "SqliteCacheStore");
+ }
+ #maxEntrySize = MAX_ENTRY_SIZE;
+ #maxCount = Infinity;
+ /**
+ * @type {import('node:sqlite').DatabaseSync}
+ */
+ #db;
+ /**
+ * @type {import('node:sqlite').StatementSync}
+ */
+ #getValuesQuery;
+ /**
+ * @type {import('node:sqlite').StatementSync}
+ */
+ #updateValueQuery;
+ /**
+ * @type {import('node:sqlite').StatementSync}
+ */
+ #insertValueQuery;
+ /**
+ * @type {import('node:sqlite').StatementSync}
+ */
+ #deleteExpiredValuesQuery;
+ /**
+ * @type {import('node:sqlite').StatementSync}
+ */
+ #deleteByUrlQuery;
+ /**
+ * @type {import('node:sqlite').StatementSync}
+ */
+ #countEntriesQuery;
+ /**
+ * @type {import('node:sqlite').StatementSync | null}
+ */
+ #deleteOldValuesQuery;
+ /**
+ * @param {import('../../types/cache-interceptor.d.ts').default.SqliteCacheStoreOpts | undefined} opts
+ */
+ constructor(opts) {
+ if (opts) {
+ if (typeof opts !== "object") {
+ throw new TypeError("SqliteCacheStore options must be an object");
+ }
+ if (opts.maxEntrySize !== void 0) {
+ if (typeof opts.maxEntrySize !== "number" || !Number.isInteger(opts.maxEntrySize) || opts.maxEntrySize < 0) {
+ throw new TypeError("SqliteCacheStore options.maxEntrySize must be a non-negative integer");
+ }
+ if (opts.maxEntrySize > MAX_ENTRY_SIZE) {
+ throw new TypeError("SqliteCacheStore options.maxEntrySize must be less than 2gb");
+ }
+ this.#maxEntrySize = opts.maxEntrySize;
+ }
+ if (opts.maxCount !== void 0) {
+ if (typeof opts.maxCount !== "number" || !Number.isInteger(opts.maxCount) || opts.maxCount < 0) {
+ throw new TypeError("SqliteCacheStore options.maxCount must be a non-negative integer");
+ }
+ this.#maxCount = opts.maxCount;
+ }
+ }
+ if (!DatabaseSync) {
+ DatabaseSync = __require("node:sqlite").DatabaseSync;
+ }
+ this.#db = new DatabaseSync(opts?.location ?? ":memory:");
+ this.#db.exec(`
+ PRAGMA journal_mode = WAL;
+ PRAGMA synchronous = NORMAL;
+ PRAGMA temp_store = memory;
+ PRAGMA optimize;
+
+ CREATE TABLE IF NOT EXISTS cacheInterceptorV${VERSION2} (
+ -- Data specific to us
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ url TEXT NOT NULL,
+ method TEXT NOT NULL,
+
+ -- Data returned to the interceptor
+ body BUF NULL,
+ deleteAt INTEGER NOT NULL,
+ statusCode INTEGER NOT NULL,
+ statusMessage TEXT NOT NULL,
+ headers TEXT NULL,
+ cacheControlDirectives TEXT NULL,
+ etag TEXT NULL,
+ vary TEXT NULL,
+ cachedAt INTEGER NOT NULL,
+ staleAt INTEGER NOT NULL
+ );
+
+ CREATE INDEX IF NOT EXISTS idx_cacheInterceptorV${VERSION2}_getValuesQuery ON cacheInterceptorV${VERSION2}(url, method, deleteAt);
+ CREATE INDEX IF NOT EXISTS idx_cacheInterceptorV${VERSION2}_deleteByUrlQuery ON cacheInterceptorV${VERSION2}(deleteAt);
+ `);
+ this.#getValuesQuery = this.#db.prepare(`
+ SELECT
+ id,
+ body,
+ deleteAt,
+ statusCode,
+ statusMessage,
+ headers,
+ etag,
+ cacheControlDirectives,
+ vary,
+ cachedAt,
+ staleAt
+ FROM cacheInterceptorV${VERSION2}
+ WHERE
+ url = ?
+ AND method = ?
+ ORDER BY
+ deleteAt ASC
+ `);
+ this.#updateValueQuery = this.#db.prepare(`
+ UPDATE cacheInterceptorV${VERSION2} SET
+ body = ?,
+ deleteAt = ?,
+ statusCode = ?,
+ statusMessage = ?,
+ headers = ?,
+ etag = ?,
+ cacheControlDirectives = ?,
+ cachedAt = ?,
+ staleAt = ?
+ WHERE
+ id = ?
+ `);
+ this.#insertValueQuery = this.#db.prepare(`
+ INSERT INTO cacheInterceptorV${VERSION2} (
+ url,
+ method,
+ body,
+ deleteAt,
+ statusCode,
+ statusMessage,
+ headers,
+ etag,
+ cacheControlDirectives,
+ vary,
+ cachedAt,
+ staleAt
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ `);
+ this.#deleteByUrlQuery = this.#db.prepare(
+ `DELETE FROM cacheInterceptorV${VERSION2} WHERE url = ?`
+ );
+ this.#countEntriesQuery = this.#db.prepare(
+ `SELECT COUNT(*) AS total FROM cacheInterceptorV${VERSION2}`
+ );
+ this.#deleteExpiredValuesQuery = this.#db.prepare(
+ `DELETE FROM cacheInterceptorV${VERSION2} WHERE deleteAt <= ?`
+ );
+ this.#deleteOldValuesQuery = this.#maxCount === Infinity ? null : this.#db.prepare(`
+ DELETE FROM cacheInterceptorV${VERSION2}
+ WHERE id IN (
+ SELECT
+ id
+ FROM cacheInterceptorV${VERSION2}
+ ORDER BY cachedAt ASC
+ LIMIT ?
+ )
+ `);
+ }
+ close() {
+ this.#db.close();
+ }
+ /**
+ * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
+ * @returns {(import('../../types/cache-interceptor.d.ts').default.GetResult & { body?: Buffer }) | undefined}
+ */
+ get(key) {
+ assertCacheKey(key);
+ const value = this.#findValue(key);
+ return value ? {
+ body: value.body ? Buffer.from(value.body.buffer, value.body.byteOffset, value.body.byteLength) : void 0,
+ statusCode: value.statusCode,
+ statusMessage: value.statusMessage,
+ headers: value.headers ? JSON.parse(value.headers) : void 0,
+ etag: value.etag ? value.etag : void 0,
+ vary: value.vary ? JSON.parse(value.vary) : void 0,
+ cacheControlDirectives: value.cacheControlDirectives ? JSON.parse(value.cacheControlDirectives) : void 0,
+ cachedAt: value.cachedAt,
+ staleAt: value.staleAt,
+ deleteAt: value.deleteAt
+ } : void 0;
+ }
+ /**
+ * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
+ * @param {import('../../types/cache-interceptor.d.ts').default.CacheValue & { body: null | Buffer | Array}} value
+ */
+ set(key, value) {
+ assertCacheKey(key);
+ const url2 = this.#makeValueUrl(key);
+ const body = Array.isArray(value.body) ? Buffer.concat(value.body) : value.body;
+ const size = body?.byteLength;
+ if (size && size > this.#maxEntrySize) {
+ return;
+ }
+ const existingValue = this.#findValue(key, true);
+ if (existingValue) {
+ this.#updateValueQuery.run(
+ body,
+ value.deleteAt,
+ value.statusCode,
+ value.statusMessage,
+ value.headers ? JSON.stringify(value.headers) : null,
+ value.etag ? value.etag : null,
+ value.cacheControlDirectives ? JSON.stringify(value.cacheControlDirectives) : null,
+ value.cachedAt,
+ value.staleAt,
+ existingValue.id
+ );
+ } else {
+ this.#insertValueQuery.run(
+ url2,
+ key.method,
+ body,
+ value.deleteAt,
+ value.statusCode,
+ value.statusMessage,
+ value.headers ? JSON.stringify(value.headers) : null,
+ value.etag ? value.etag : null,
+ value.cacheControlDirectives ? JSON.stringify(value.cacheControlDirectives) : null,
+ value.vary ? JSON.stringify(value.vary) : null,
+ value.cachedAt,
+ value.staleAt
+ );
+ this.#prune();
+ }
+ }
+ /**
+ * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
+ * @param {import('../../types/cache-interceptor.d.ts').default.CacheValue} value
+ * @returns {Writable | undefined}
+ */
+ createWriteStream(key, value) {
+ assertCacheKey(key);
+ assertCacheValue(value);
+ let size = 0;
+ const body = [];
+ const store = this;
+ return new Writable({
+ decodeStrings: true,
+ write(chunk, encoding, callback) {
+ size += chunk.byteLength;
+ if (size < store.#maxEntrySize) {
+ body.push(chunk);
+ } else {
+ this.destroy();
+ }
+ callback();
+ },
+ final(callback) {
+ store.set(key, { ...value, body });
+ callback();
+ }
+ });
+ }
+ /**
+ * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
+ */
+ delete(key) {
+ if (typeof key !== "object") {
+ throw new TypeError(`expected key to be object, got ${typeof key}`);
+ }
+ this.#deleteByUrlQuery.run(this.#makeValueUrl(key));
+ }
+ #prune() {
+ if (Number.isFinite(this.#maxCount) && this.size <= this.#maxCount) {
+ return 0;
+ }
+ {
+ const removed = this.#deleteExpiredValuesQuery.run(Date.now()).changes;
+ if (removed) {
+ return removed;
+ }
+ }
+ {
+ const removed = this.#deleteOldValuesQuery?.run(Math.max(Math.floor(this.#maxCount * 0.1), 1)).changes;
+ if (removed) {
+ return removed;
+ }
+ }
+ return 0;
+ }
+ /**
+ * Counts the number of rows in the cache
+ * @returns {Number}
+ */
+ get size() {
+ const { total } = this.#countEntriesQuery.get();
+ return total;
+ }
+ /**
+ * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
+ * @returns {string}
+ */
+ #makeValueUrl(key) {
+ return `${key.origin}/${key.path}`;
+ }
+ /**
+ * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
+ * @param {boolean} [canBeExpired=false]
+ * @returns {SqliteStoreValue | undefined}
+ */
+ #findValue(key, canBeExpired = false) {
+ const url2 = this.#makeValueUrl(key);
+ const { headers, method } = key;
+ const values = this.#getValuesQuery.all(url2, method);
+ if (values.length === 0) {
+ return void 0;
+ }
+ const now = Date.now();
+ for (const value of values) {
+ if (now >= value.deleteAt && !canBeExpired) {
+ continue;
+ }
+ let matches = true;
+ if (value.vary) {
+ const vary = JSON.parse(value.vary);
+ for (const header in vary) {
+ if (!headerValueEquals(headers[header], vary[header])) {
+ matches = false;
+ break;
+ }
+ }
+ }
+ if (matches) {
+ return value;
+ }
+ }
+ return void 0;
+ }
+ };
+ function headerValueEquals(lhs, rhs) {
+ if (lhs == null && rhs == null) {
+ return true;
+ }
+ if (lhs == null && rhs != null || lhs != null && rhs == null) {
+ return false;
+ }
+ if (Array.isArray(lhs) && Array.isArray(rhs)) {
+ if (lhs.length !== rhs.length) {
+ return false;
+ }
+ return lhs.every((x, i) => x === rhs[i]);
+ }
+ return lhs === rhs;
+ }
+ __name(headerValueEquals, "headerValueEquals");
+ }
+});
+
+// node_modules/undici/lib/web/fetch/headers.js
+var require_headers = __commonJS({
+ "node_modules/undici/lib/web/fetch/headers.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { kConstruct } = require_symbols();
+ var { kEnumerableProperty } = require_util();
+ var {
+ iteratorMixin,
+ isValidHeaderName,
+ isValidHeaderValue
+ } = require_util2();
+ var { webidl } = require_webidl();
+ var assert2 = __require("node:assert");
+ var util = __require("node:util");
+ function isHTTPWhiteSpaceCharCode(code) {
+ return code === 10 || code === 13 || code === 9 || code === 32;
+ }
+ __name(isHTTPWhiteSpaceCharCode, "isHTTPWhiteSpaceCharCode");
+ function headerValueNormalize(potentialValue) {
+ let i = 0;
+ let j = potentialValue.length;
+ while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j;
+ while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i;
+ return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j);
+ }
+ __name(headerValueNormalize, "headerValueNormalize");
+ function fill(headers, object2) {
+ if (Array.isArray(object2)) {
+ for (let i = 0; i < object2.length; ++i) {
+ const header = object2[i];
+ if (header.length !== 2) {
+ throw webidl.errors.exception({
+ header: "Headers constructor",
+ message: `expected name/value pair to be length 2, found ${header.length}.`
+ });
+ }
+ appendHeader(headers, header[0], header[1]);
+ }
+ } else if (typeof object2 === "object" && object2 !== null) {
+ const keys = Object.keys(object2);
+ for (let i = 0; i < keys.length; ++i) {
+ appendHeader(headers, keys[i], object2[keys[i]]);
+ }
+ } else {
+ throw webidl.errors.conversionFailed({
+ prefix: "Headers constructor",
+ argument: "Argument 1",
+ types: ["sequence>", "record"]
+ });
+ }
+ }
+ __name(fill, "fill");
+ function appendHeader(headers, name, value) {
+ value = headerValueNormalize(value);
+ if (!isValidHeaderName(name)) {
+ throw webidl.errors.invalidArgument({
+ prefix: "Headers.append",
+ value: name,
+ type: "header name"
+ });
+ } else if (!isValidHeaderValue(value)) {
+ throw webidl.errors.invalidArgument({
+ prefix: "Headers.append",
+ value,
+ type: "header value"
+ });
+ }
+ if (getHeadersGuard(headers) === "immutable") {
+ throw new TypeError("immutable");
+ }
+ return getHeadersList(headers).append(name, value, false);
+ }
+ __name(appendHeader, "appendHeader");
+ function headersListSortAndCombine(target) {
+ const headersList = getHeadersList(target);
+ if (!headersList) {
+ return [];
+ }
+ if (headersList.sortedMap) {
+ return headersList.sortedMap;
+ }
+ const headers = [];
+ const names = headersList.toSortedArray();
+ const cookies = headersList.cookies;
+ if (cookies === null || cookies.length === 1) {
+ return headersList.sortedMap = names;
+ }
+ for (let i = 0; i < names.length; ++i) {
+ const { 0: name, 1: value } = names[i];
+ if (name === "set-cookie") {
+ for (let j = 0; j < cookies.length; ++j) {
+ headers.push([name, cookies[j]]);
+ }
+ } else {
+ headers.push([name, value]);
+ }
+ }
+ return headersList.sortedMap = headers;
+ }
+ __name(headersListSortAndCombine, "headersListSortAndCombine");
+ function compareHeaderName(a, b) {
+ return a[0] < b[0] ? -1 : 1;
+ }
+ __name(compareHeaderName, "compareHeaderName");
+ var HeadersList = class _HeadersList {
+ static {
+ __name(this, "HeadersList");
+ }
+ /** @type {[string, string][]|null} */
+ cookies = null;
+ sortedMap;
+ headersMap;
+ constructor(init) {
+ if (init instanceof _HeadersList) {
+ this.headersMap = new Map(init.headersMap);
+ this.sortedMap = init.sortedMap;
+ this.cookies = init.cookies === null ? null : [...init.cookies];
+ } else {
+ this.headersMap = new Map(init);
+ this.sortedMap = null;
+ }
+ }
+ /**
+ * @see https://fetch.spec.whatwg.org/#header-list-contains
+ * @param {string} name
+ * @param {boolean} isLowerCase
+ */
+ contains(name, isLowerCase) {
+ return this.headersMap.has(isLowerCase ? name : name.toLowerCase());
+ }
+ clear() {
+ this.headersMap.clear();
+ this.sortedMap = null;
+ this.cookies = null;
+ }
+ /**
+ * @see https://fetch.spec.whatwg.org/#concept-header-list-append
+ * @param {string} name
+ * @param {string} value
+ * @param {boolean} isLowerCase
+ */
+ append(name, value, isLowerCase) {
+ this.sortedMap = null;
+ const lowercaseName = isLowerCase ? name : name.toLowerCase();
+ const exists = this.headersMap.get(lowercaseName);
+ if (exists) {
+ const delimiter = lowercaseName === "cookie" ? "; " : ", ";
+ this.headersMap.set(lowercaseName, {
+ name: exists.name,
+ value: `${exists.value}${delimiter}${value}`
+ });
+ } else {
+ this.headersMap.set(lowercaseName, { name, value });
+ }
+ if (lowercaseName === "set-cookie") {
+ (this.cookies ??= []).push(value);
+ }
+ }
+ /**
+ * @see https://fetch.spec.whatwg.org/#concept-header-list-set
+ * @param {string} name
+ * @param {string} value
+ * @param {boolean} isLowerCase
+ */
+ set(name, value, isLowerCase) {
+ this.sortedMap = null;
+ const lowercaseName = isLowerCase ? name : name.toLowerCase();
+ if (lowercaseName === "set-cookie") {
+ this.cookies = [value];
+ }
+ this.headersMap.set(lowercaseName, { name, value });
+ }
+ /**
+ * @see https://fetch.spec.whatwg.org/#concept-header-list-delete
+ * @param {string} name
+ * @param {boolean} isLowerCase
+ */
+ delete(name, isLowerCase) {
+ this.sortedMap = null;
+ if (!isLowerCase) name = name.toLowerCase();
+ if (name === "set-cookie") {
+ this.cookies = null;
+ }
+ this.headersMap.delete(name);
+ }
+ /**
+ * @see https://fetch.spec.whatwg.org/#concept-header-list-get
+ * @param {string} name
+ * @param {boolean} isLowerCase
+ * @returns {string | null}
+ */
+ get(name, isLowerCase) {
+ return this.headersMap.get(isLowerCase ? name : name.toLowerCase())?.value ?? null;
+ }
+ *[Symbol.iterator]() {
+ for (const { 0: name, 1: { value } } of this.headersMap) {
+ yield [name, value];
+ }
+ }
+ get entries() {
+ const headers = {};
+ if (this.headersMap.size !== 0) {
+ for (const { name, value } of this.headersMap.values()) {
+ headers[name] = value;
+ }
+ }
+ return headers;
+ }
+ rawValues() {
+ return this.headersMap.values();
+ }
+ get entriesList() {
+ const headers = [];
+ if (this.headersMap.size !== 0) {
+ for (const { 0: lowerName, 1: { name, value } } of this.headersMap) {
+ if (lowerName === "set-cookie") {
+ for (const cookie of this.cookies) {
+ headers.push([name, cookie]);
+ }
+ } else {
+ headers.push([name, value]);
+ }
+ }
+ }
+ return headers;
+ }
+ // https://fetch.spec.whatwg.org/#convert-header-names-to-a-sorted-lowercase-set
+ toSortedArray() {
+ const size = this.headersMap.size;
+ const array2 = new Array(size);
+ if (size <= 32) {
+ if (size === 0) {
+ return array2;
+ }
+ const iterator = this.headersMap[Symbol.iterator]();
+ const firstValue = iterator.next().value;
+ array2[0] = [firstValue[0], firstValue[1].value];
+ assert2(firstValue[1].value !== null);
+ for (let i = 1, j = 0, right2 = 0, left2 = 0, pivot = 0, x, value; i < size; ++i) {
+ value = iterator.next().value;
+ x = array2[i] = [value[0], value[1].value];
+ assert2(x[1] !== null);
+ left2 = 0;
+ right2 = i;
+ while (left2 < right2) {
+ pivot = left2 + (right2 - left2 >> 1);
+ if (array2[pivot][0] <= x[0]) {
+ left2 = pivot + 1;
+ } else {
+ right2 = pivot;
+ }
+ }
+ if (i !== pivot) {
+ j = i;
+ while (j > left2) {
+ array2[j] = array2[--j];
+ }
+ array2[left2] = x;
+ }
+ }
+ if (!iterator.next().done) {
+ throw new TypeError("Unreachable");
+ }
+ return array2;
+ } else {
+ let i = 0;
+ for (const { 0: name, 1: { value } } of this.headersMap) {
+ array2[i++] = [name, value];
+ assert2(value !== null);
+ }
+ return array2.sort(compareHeaderName);
+ }
+ }
+ };
+ var Headers2 = class _Headers {
+ static {
+ __name(this, "Headers");
+ }
+ #guard;
+ /**
+ * @type {HeadersList}
+ */
+ #headersList;
+ /**
+ * @param {HeadersInit|Symbol} [init]
+ * @returns
+ */
+ constructor(init = void 0) {
+ webidl.util.markAsUncloneable(this);
+ if (init === kConstruct) {
+ return;
+ }
+ this.#headersList = new HeadersList();
+ this.#guard = "none";
+ if (init !== void 0) {
+ init = webidl.converters.HeadersInit(init, "Headers constructor", "init");
+ fill(this, init);
+ }
+ }
+ // https://fetch.spec.whatwg.org/#dom-headers-append
+ append(name, value) {
+ webidl.brandCheck(this, _Headers);
+ webidl.argumentLengthCheck(arguments, 2, "Headers.append");
+ const prefix = "Headers.append";
+ name = webidl.converters.ByteString(name, prefix, "name");
+ value = webidl.converters.ByteString(value, prefix, "value");
+ return appendHeader(this, name, value);
+ }
+ // https://fetch.spec.whatwg.org/#dom-headers-delete
+ delete(name) {
+ webidl.brandCheck(this, _Headers);
+ webidl.argumentLengthCheck(arguments, 1, "Headers.delete");
+ const prefix = "Headers.delete";
+ name = webidl.converters.ByteString(name, prefix, "name");
+ if (!isValidHeaderName(name)) {
+ throw webidl.errors.invalidArgument({
+ prefix: "Headers.delete",
+ value: name,
+ type: "header name"
+ });
+ }
+ if (this.#guard === "immutable") {
+ throw new TypeError("immutable");
+ }
+ if (!this.#headersList.contains(name, false)) {
+ return;
+ }
+ this.#headersList.delete(name, false);
+ }
+ // https://fetch.spec.whatwg.org/#dom-headers-get
+ get(name) {
+ webidl.brandCheck(this, _Headers);
+ webidl.argumentLengthCheck(arguments, 1, "Headers.get");
+ const prefix = "Headers.get";
+ name = webidl.converters.ByteString(name, prefix, "name");
+ if (!isValidHeaderName(name)) {
+ throw webidl.errors.invalidArgument({
+ prefix,
+ value: name,
+ type: "header name"
+ });
+ }
+ return this.#headersList.get(name, false);
+ }
+ // https://fetch.spec.whatwg.org/#dom-headers-has
+ has(name) {
+ webidl.brandCheck(this, _Headers);
+ webidl.argumentLengthCheck(arguments, 1, "Headers.has");
+ const prefix = "Headers.has";
+ name = webidl.converters.ByteString(name, prefix, "name");
+ if (!isValidHeaderName(name)) {
+ throw webidl.errors.invalidArgument({
+ prefix,
+ value: name,
+ type: "header name"
+ });
+ }
+ return this.#headersList.contains(name, false);
+ }
+ // https://fetch.spec.whatwg.org/#dom-headers-set
+ set(name, value) {
+ webidl.brandCheck(this, _Headers);
+ webidl.argumentLengthCheck(arguments, 2, "Headers.set");
+ const prefix = "Headers.set";
+ name = webidl.converters.ByteString(name, prefix, "name");
+ value = webidl.converters.ByteString(value, prefix, "value");
+ value = headerValueNormalize(value);
+ if (!isValidHeaderName(name)) {
+ throw webidl.errors.invalidArgument({
+ prefix,
+ value: name,
+ type: "header name"
+ });
+ } else if (!isValidHeaderValue(value)) {
+ throw webidl.errors.invalidArgument({
+ prefix,
+ value,
+ type: "header value"
+ });
+ }
+ if (this.#guard === "immutable") {
+ throw new TypeError("immutable");
+ }
+ this.#headersList.set(name, value, false);
+ }
+ // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie
+ getSetCookie() {
+ webidl.brandCheck(this, _Headers);
+ const list = this.#headersList.cookies;
+ if (list) {
+ return [...list];
+ }
+ return [];
+ }
+ [util.inspect.custom](depth, options2) {
+ options2.depth ??= depth;
+ return `Headers ${util.formatWithOptions(options2, this.#headersList.entries)}`;
+ }
+ static getHeadersGuard(o) {
+ return o.#guard;
+ }
+ static setHeadersGuard(o, guard) {
+ o.#guard = guard;
+ }
+ /**
+ * @param {Headers} o
+ */
+ static getHeadersList(o) {
+ return o.#headersList;
+ }
+ /**
+ * @param {Headers} target
+ * @param {HeadersList} list
+ */
+ static setHeadersList(target, list) {
+ target.#headersList = list;
+ }
+ };
+ var { getHeadersGuard, setHeadersGuard, getHeadersList, setHeadersList } = Headers2;
+ Reflect.deleteProperty(Headers2, "getHeadersGuard");
+ Reflect.deleteProperty(Headers2, "setHeadersGuard");
+ Reflect.deleteProperty(Headers2, "getHeadersList");
+ Reflect.deleteProperty(Headers2, "setHeadersList");
+ iteratorMixin("Headers", Headers2, headersListSortAndCombine, 0, 1);
+ Object.defineProperties(Headers2.prototype, {
+ append: kEnumerableProperty,
+ delete: kEnumerableProperty,
+ get: kEnumerableProperty,
+ has: kEnumerableProperty,
+ set: kEnumerableProperty,
+ getSetCookie: kEnumerableProperty,
+ [Symbol.toStringTag]: {
+ value: "Headers",
+ configurable: true
+ },
+ [util.inspect.custom]: {
+ enumerable: false
+ }
+ });
+ webidl.converters.HeadersInit = function(V, prefix, argument) {
+ if (webidl.util.Type(V) === webidl.util.Types.OBJECT) {
+ const iterator = Reflect.get(V, Symbol.iterator);
+ if (!util.types.isProxy(V) && iterator === Headers2.prototype.entries) {
+ try {
+ return getHeadersList(V).entriesList;
+ } catch {
+ }
+ }
+ if (typeof iterator === "function") {
+ return webidl.converters["sequence>"](V, prefix, argument, iterator.bind(V));
+ }
+ return webidl.converters["record"](V, prefix, argument);
+ }
+ throw webidl.errors.conversionFailed({
+ prefix: "Headers constructor",
+ argument: "Argument 1",
+ types: ["sequence>", "record"]
+ });
+ };
+ module2.exports = {
+ fill,
+ // for test.
+ compareHeaderName,
+ Headers: Headers2,
+ HeadersList,
+ getHeadersGuard,
+ setHeadersGuard,
+ setHeadersList,
+ getHeadersList
+ };
+ }
+});
+
+// node_modules/undici/lib/web/fetch/response.js
+var require_response = __commonJS({
+ "node_modules/undici/lib/web/fetch/response.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { Headers: Headers2, HeadersList, fill, getHeadersGuard, setHeadersGuard, setHeadersList } = require_headers();
+ var { extractBody, cloneBody, mixinBody, streamRegistry, bodyUnusable } = require_body();
+ var util = require_util();
+ var nodeUtil = __require("node:util");
+ var { kEnumerableProperty } = util;
+ var {
+ isValidReasonPhrase,
+ isCancelled,
+ isAborted,
+ isErrorLike,
+ environmentSettingsObject: relevantRealm
+ } = require_util2();
+ var {
+ redirectStatusSet,
+ nullBodyStatus
+ } = require_constants4();
+ var { webidl } = require_webidl();
+ var { URLSerializer } = require_data_url();
+ var { kConstruct } = require_symbols();
+ var assert2 = __require("node:assert");
+ var { isomorphicEncode, serializeJavascriptValueToJSONString } = require_infra();
+ var textEncoder2 = new TextEncoder("utf-8");
+ var Response2 = class _Response {
+ static {
+ __name(this, "Response");
+ }
+ /** @type {Headers} */
+ #headers;
+ #state;
+ // Creates network error Response.
+ static error() {
+ const responseObject = fromInnerResponse(makeNetworkError(), "immutable");
+ return responseObject;
+ }
+ // https://fetch.spec.whatwg.org/#dom-response-json
+ static json(data, init = void 0) {
+ webidl.argumentLengthCheck(arguments, 1, "Response.json");
+ if (init !== null) {
+ init = webidl.converters.ResponseInit(init);
+ }
+ const bytes = textEncoder2.encode(
+ serializeJavascriptValueToJSONString(data)
+ );
+ const body = extractBody(bytes);
+ const responseObject = fromInnerResponse(makeResponse({}), "response");
+ initializeResponse(responseObject, init, { body: body[0], type: "application/json" });
+ return responseObject;
+ }
+ // Creates a redirect Response that redirects to url with status status.
+ static redirect(url2, status = 302) {
+ webidl.argumentLengthCheck(arguments, 1, "Response.redirect");
+ url2 = webidl.converters.USVString(url2);
+ status = webidl.converters["unsigned short"](status);
+ let parsedURL;
+ try {
+ parsedURL = new URL(url2, relevantRealm.settingsObject.baseUrl);
+ } catch (err) {
+ throw new TypeError(`Failed to parse URL from ${url2}`, { cause: err });
+ }
+ if (!redirectStatusSet.has(status)) {
+ throw new RangeError(`Invalid status code ${status}`);
+ }
+ const responseObject = fromInnerResponse(makeResponse({}), "immutable");
+ responseObject.#state.status = status;
+ const value = isomorphicEncode(URLSerializer(parsedURL));
+ responseObject.#state.headersList.append("location", value, true);
+ return responseObject;
+ }
+ // https://fetch.spec.whatwg.org/#dom-response
+ constructor(body = null, init = void 0) {
+ webidl.util.markAsUncloneable(this);
+ if (body === kConstruct) {
+ return;
+ }
+ if (body !== null) {
+ body = webidl.converters.BodyInit(body, "Response", "body");
+ }
+ init = webidl.converters.ResponseInit(init);
+ this.#state = makeResponse({});
+ this.#headers = new Headers2(kConstruct);
+ setHeadersGuard(this.#headers, "response");
+ setHeadersList(this.#headers, this.#state.headersList);
+ let bodyWithType = null;
+ if (body != null) {
+ const [extractedBody, type2] = extractBody(body);
+ bodyWithType = { body: extractedBody, type: type2 };
+ }
+ initializeResponse(this, init, bodyWithType);
+ }
+ // Returns response’s type, e.g., "cors".
+ get type() {
+ webidl.brandCheck(this, _Response);
+ return this.#state.type;
+ }
+ // Returns response’s URL, if it has one; otherwise the empty string.
+ get url() {
+ webidl.brandCheck(this, _Response);
+ const urlList = this.#state.urlList;
+ const url2 = urlList[urlList.length - 1] ?? null;
+ if (url2 === null) {
+ return "";
+ }
+ return URLSerializer(url2, true);
+ }
+ // Returns whether response was obtained through a redirect.
+ get redirected() {
+ webidl.brandCheck(this, _Response);
+ return this.#state.urlList.length > 1;
+ }
+ // Returns response’s status.
+ get status() {
+ webidl.brandCheck(this, _Response);
+ return this.#state.status;
+ }
+ // Returns whether response’s status is an ok status.
+ get ok() {
+ webidl.brandCheck(this, _Response);
+ return this.#state.status >= 200 && this.#state.status <= 299;
+ }
+ // Returns response’s status message.
+ get statusText() {
+ webidl.brandCheck(this, _Response);
+ return this.#state.statusText;
+ }
+ // Returns response’s headers as Headers.
+ get headers() {
+ webidl.brandCheck(this, _Response);
+ return this.#headers;
+ }
+ get body() {
+ webidl.brandCheck(this, _Response);
+ return this.#state.body ? this.#state.body.stream : null;
+ }
+ get bodyUsed() {
+ webidl.brandCheck(this, _Response);
+ return !!this.#state.body && util.isDisturbed(this.#state.body.stream);
+ }
+ // Returns a clone of response.
+ clone() {
+ webidl.brandCheck(this, _Response);
+ if (bodyUnusable(this.#state)) {
+ throw webidl.errors.exception({
+ header: "Response.clone",
+ message: "Body has already been consumed."
+ });
+ }
+ const clonedResponse = cloneResponse(this.#state);
+ if (this.#state.urlList.length !== 0 && this.#state.body?.stream) {
+ streamRegistry.register(this, new WeakRef(this.#state.body.stream));
+ }
+ return fromInnerResponse(clonedResponse, getHeadersGuard(this.#headers));
+ }
+ [nodeUtil.inspect.custom](depth, options2) {
+ if (options2.depth === null) {
+ options2.depth = 2;
+ }
+ options2.colors ??= true;
+ const properties = {
+ status: this.status,
+ statusText: this.statusText,
+ headers: this.headers,
+ body: this.body,
+ bodyUsed: this.bodyUsed,
+ ok: this.ok,
+ redirected: this.redirected,
+ type: this.type,
+ url: this.url
+ };
+ return `Response ${nodeUtil.formatWithOptions(options2, properties)}`;
+ }
+ /**
+ * @param {Response} response
+ */
+ static getResponseHeaders(response) {
+ return response.#headers;
+ }
+ /**
+ * @param {Response} response
+ * @param {Headers} newHeaders
+ */
+ static setResponseHeaders(response, newHeaders) {
+ response.#headers = newHeaders;
+ }
+ /**
+ * @param {Response} response
+ */
+ static getResponseState(response) {
+ return response.#state;
+ }
+ /**
+ * @param {Response} response
+ * @param {any} newState
+ */
+ static setResponseState(response, newState) {
+ response.#state = newState;
+ }
+ };
+ var { getResponseHeaders, setResponseHeaders, getResponseState, setResponseState } = Response2;
+ Reflect.deleteProperty(Response2, "getResponseHeaders");
+ Reflect.deleteProperty(Response2, "setResponseHeaders");
+ Reflect.deleteProperty(Response2, "getResponseState");
+ Reflect.deleteProperty(Response2, "setResponseState");
+ mixinBody(Response2, getResponseState);
+ Object.defineProperties(Response2.prototype, {
+ type: kEnumerableProperty,
+ url: kEnumerableProperty,
+ status: kEnumerableProperty,
+ ok: kEnumerableProperty,
+ redirected: kEnumerableProperty,
+ statusText: kEnumerableProperty,
+ headers: kEnumerableProperty,
+ clone: kEnumerableProperty,
+ body: kEnumerableProperty,
+ bodyUsed: kEnumerableProperty,
+ [Symbol.toStringTag]: {
+ value: "Response",
+ configurable: true
+ }
+ });
+ Object.defineProperties(Response2, {
+ json: kEnumerableProperty,
+ redirect: kEnumerableProperty,
+ error: kEnumerableProperty
+ });
+ function cloneResponse(response) {
+ if (response.internalResponse) {
+ return filterResponse(
+ cloneResponse(response.internalResponse),
+ response.type
+ );
+ }
+ const newResponse = makeResponse({ ...response, body: null });
+ if (response.body != null) {
+ newResponse.body = cloneBody(response.body);
+ }
+ return newResponse;
+ }
+ __name(cloneResponse, "cloneResponse");
+ function makeResponse(init) {
+ return {
+ aborted: false,
+ rangeRequested: false,
+ timingAllowPassed: false,
+ requestIncludesCredentials: false,
+ type: "default",
+ status: 200,
+ timingInfo: null,
+ cacheState: "",
+ statusText: "",
+ ...init,
+ headersList: init?.headersList ? new HeadersList(init?.headersList) : new HeadersList(),
+ urlList: init?.urlList ? [...init.urlList] : []
+ };
+ }
+ __name(makeResponse, "makeResponse");
+ function makeNetworkError(reason) {
+ const isError = isErrorLike(reason);
+ return makeResponse({
+ type: "error",
+ status: 0,
+ error: isError ? reason : new Error(reason ? String(reason) : reason),
+ aborted: reason && reason.name === "AbortError"
+ });
+ }
+ __name(makeNetworkError, "makeNetworkError");
+ function isNetworkError(response) {
+ return (
+ // A network error is a response whose type is "error",
+ response.type === "error" && // status is 0
+ response.status === 0
+ );
+ }
+ __name(isNetworkError, "isNetworkError");
+ function makeFilteredResponse(response, state) {
+ state = {
+ internalResponse: response,
+ ...state
+ };
+ return new Proxy(response, {
+ get(target, p) {
+ return p in state ? state[p] : target[p];
+ },
+ set(target, p, value) {
+ assert2(!(p in state));
+ target[p] = value;
+ return true;
+ }
+ });
+ }
+ __name(makeFilteredResponse, "makeFilteredResponse");
+ function filterResponse(response, type2) {
+ if (type2 === "basic") {
+ return makeFilteredResponse(response, {
+ type: "basic",
+ headersList: response.headersList
+ });
+ } else if (type2 === "cors") {
+ return makeFilteredResponse(response, {
+ type: "cors",
+ headersList: response.headersList
+ });
+ } else if (type2 === "opaque") {
+ return makeFilteredResponse(response, {
+ type: "opaque",
+ urlList: [],
+ status: 0,
+ statusText: "",
+ body: null
+ });
+ } else if (type2 === "opaqueredirect") {
+ return makeFilteredResponse(response, {
+ type: "opaqueredirect",
+ status: 0,
+ statusText: "",
+ headersList: [],
+ body: null
+ });
+ } else {
+ assert2(false);
+ }
+ }
+ __name(filterResponse, "filterResponse");
+ function makeAppropriateNetworkError(fetchParams, err = null) {
+ assert2(isCancelled(fetchParams));
+ return isAborted(fetchParams) ? makeNetworkError(Object.assign(new DOMException("The operation was aborted.", "AbortError"), { cause: err })) : makeNetworkError(Object.assign(new DOMException("Request was cancelled."), { cause: err }));
+ }
+ __name(makeAppropriateNetworkError, "makeAppropriateNetworkError");
+ function initializeResponse(response, init, body) {
+ if (init.status !== null && (init.status < 200 || init.status > 599)) {
+ throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.');
+ }
+ if ("statusText" in init && init.statusText != null) {
+ if (!isValidReasonPhrase(String(init.statusText))) {
+ throw new TypeError("Invalid statusText");
+ }
+ }
+ if ("status" in init && init.status != null) {
+ getResponseState(response).status = init.status;
+ }
+ if ("statusText" in init && init.statusText != null) {
+ getResponseState(response).statusText = init.statusText;
+ }
+ if ("headers" in init && init.headers != null) {
+ fill(getResponseHeaders(response), init.headers);
+ }
+ if (body) {
+ if (nullBodyStatus.includes(response.status)) {
+ throw webidl.errors.exception({
+ header: "Response constructor",
+ message: `Invalid response status code ${response.status}`
+ });
+ }
+ getResponseState(response).body = body.body;
+ if (body.type != null && !getResponseState(response).headersList.contains("content-type", true)) {
+ getResponseState(response).headersList.append("content-type", body.type, true);
+ }
+ }
+ }
+ __name(initializeResponse, "initializeResponse");
+ function fromInnerResponse(innerResponse, guard) {
+ const response = new Response2(kConstruct);
+ setResponseState(response, innerResponse);
+ const headers = new Headers2(kConstruct);
+ setResponseHeaders(response, headers);
+ setHeadersList(headers, innerResponse.headersList);
+ setHeadersGuard(headers, guard);
+ if (innerResponse.urlList.length !== 0 && innerResponse.body?.stream) {
+ streamRegistry.register(response, new WeakRef(innerResponse.body.stream));
+ }
+ return response;
+ }
+ __name(fromInnerResponse, "fromInnerResponse");
+ webidl.converters.XMLHttpRequestBodyInit = function(V, prefix, name) {
+ if (typeof V === "string") {
+ return webidl.converters.USVString(V, prefix, name);
+ }
+ if (webidl.is.Blob(V)) {
+ return V;
+ }
+ if (webidl.is.BufferSource(V)) {
+ return V;
+ }
+ if (webidl.is.FormData(V)) {
+ return V;
+ }
+ if (webidl.is.URLSearchParams(V)) {
+ return V;
+ }
+ return webidl.converters.DOMString(V, prefix, name);
+ };
+ webidl.converters.BodyInit = function(V, prefix, argument) {
+ if (webidl.is.ReadableStream(V)) {
+ return V;
+ }
+ if (V?.[Symbol.asyncIterator]) {
+ return V;
+ }
+ return webidl.converters.XMLHttpRequestBodyInit(V, prefix, argument);
+ };
+ webidl.converters.ResponseInit = webidl.dictionaryConverter([
+ {
+ key: "status",
+ converter: webidl.converters["unsigned short"],
+ defaultValue: /* @__PURE__ */ __name(() => 200, "defaultValue")
+ },
+ {
+ key: "statusText",
+ converter: webidl.converters.ByteString,
+ defaultValue: /* @__PURE__ */ __name(() => "", "defaultValue")
+ },
+ {
+ key: "headers",
+ converter: webidl.converters.HeadersInit
+ }
+ ]);
+ webidl.is.Response = webidl.util.MakeTypeAssertion(Response2);
+ module2.exports = {
+ isNetworkError,
+ makeNetworkError,
+ makeResponse,
+ makeAppropriateNetworkError,
+ filterResponse,
+ Response: Response2,
+ cloneResponse,
+ fromInnerResponse,
+ getResponseState
+ };
+ }
+});
+
+// node_modules/undici/lib/web/fetch/request.js
+var require_request2 = __commonJS({
+ "node_modules/undici/lib/web/fetch/request.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { extractBody, mixinBody, cloneBody, bodyUnusable } = require_body();
+ var { Headers: Headers2, fill: fillHeaders, HeadersList, setHeadersGuard, getHeadersGuard, setHeadersList, getHeadersList } = require_headers();
+ var util = require_util();
+ var nodeUtil = __require("node:util");
+ var {
+ isValidHTTPToken,
+ sameOrigin,
+ environmentSettingsObject
+ } = require_util2();
+ var {
+ forbiddenMethodsSet,
+ corsSafeListedMethodsSet,
+ referrerPolicy,
+ requestRedirect,
+ requestMode,
+ requestCredentials,
+ requestCache,
+ requestDuplex
+ } = require_constants4();
+ var { kEnumerableProperty, normalizedMethodRecordsBase, normalizedMethodRecords } = util;
+ var { webidl } = require_webidl();
+ var { URLSerializer } = require_data_url();
+ var { kConstruct } = require_symbols();
+ var assert2 = __require("node:assert");
+ var { getMaxListeners, setMaxListeners, defaultMaxListeners } = __require("node:events");
+ var kAbortController = /* @__PURE__ */ Symbol("abortController");
+ var requestFinalizer = new FinalizationRegistry(({ signal, abort }) => {
+ signal.removeEventListener("abort", abort);
+ });
+ var dependentControllerMap = /* @__PURE__ */ new WeakMap();
+ var abortSignalHasEventHandlerLeakWarning;
+ try {
+ abortSignalHasEventHandlerLeakWarning = getMaxListeners(new AbortController().signal) > 0;
+ } catch {
+ abortSignalHasEventHandlerLeakWarning = false;
+ }
+ function buildAbort(acRef) {
+ return abort;
+ function abort() {
+ const ac = acRef.deref();
+ if (ac !== void 0) {
+ requestFinalizer.unregister(abort);
+ this.removeEventListener("abort", abort);
+ ac.abort(this.reason);
+ const controllerList = dependentControllerMap.get(ac.signal);
+ if (controllerList !== void 0) {
+ if (controllerList.size !== 0) {
+ for (const ref of controllerList) {
+ const ctrl = ref.deref();
+ if (ctrl !== void 0) {
+ ctrl.abort(this.reason);
+ }
+ }
+ controllerList.clear();
+ }
+ dependentControllerMap.delete(ac.signal);
+ }
+ }
+ }
+ __name(abort, "abort");
+ }
+ __name(buildAbort, "buildAbort");
+ var patchMethodWarning = false;
+ var Request = class _Request {
+ static {
+ __name(this, "Request");
+ }
+ /** @type {AbortSignal} */
+ #signal;
+ /** @type {import('../../dispatcher/dispatcher')} */
+ #dispatcher;
+ /** @type {Headers} */
+ #headers;
+ #state;
+ // https://fetch.spec.whatwg.org/#dom-request
+ constructor(input, init = void 0) {
+ webidl.util.markAsUncloneable(this);
+ if (input === kConstruct) {
+ return;
+ }
+ const prefix = "Request constructor";
+ webidl.argumentLengthCheck(arguments, 1, prefix);
+ input = webidl.converters.RequestInfo(input);
+ init = webidl.converters.RequestInit(init);
+ let request = null;
+ let fallbackMode = null;
+ const baseUrl = environmentSettingsObject.settingsObject.baseUrl;
+ let signal = null;
+ if (typeof input === "string") {
+ this.#dispatcher = init.dispatcher;
+ let parsedURL;
+ try {
+ parsedURL = new URL(input, baseUrl);
+ } catch (err) {
+ throw new TypeError("Failed to parse URL from " + input, { cause: err });
+ }
+ if (parsedURL.username || parsedURL.password) {
+ throw new TypeError(
+ "Request cannot be constructed from a URL that includes credentials: " + input
+ );
+ }
+ request = makeRequest({ urlList: [parsedURL] });
+ fallbackMode = "cors";
+ } else {
+ assert2(webidl.is.Request(input));
+ request = input.#state;
+ signal = input.#signal;
+ this.#dispatcher = init.dispatcher || input.#dispatcher;
+ }
+ const origin = environmentSettingsObject.settingsObject.origin;
+ let window2 = "client";
+ if (request.window?.constructor?.name === "EnvironmentSettingsObject" && sameOrigin(request.window, origin)) {
+ window2 = request.window;
+ }
+ if (init.window != null) {
+ throw new TypeError(`'window' option '${window2}' must be null`);
+ }
+ if ("window" in init) {
+ window2 = "no-window";
+ }
+ request = makeRequest({
+ // URL request’s URL.
+ // undici implementation note: this is set as the first item in request's urlList in makeRequest
+ // method request’s method.
+ method: request.method,
+ // header list A copy of request’s header list.
+ // undici implementation note: headersList is cloned in makeRequest
+ headersList: request.headersList,
+ // unsafe-request flag Set.
+ unsafeRequest: request.unsafeRequest,
+ // client This’s relevant settings object.
+ client: environmentSettingsObject.settingsObject,
+ // window window.
+ window: window2,
+ // priority request’s priority.
+ priority: request.priority,
+ // origin request’s origin. The propagation of the origin is only significant for navigation requests
+ // being handled by a service worker. In this scenario a request can have an origin that is different
+ // from the current client.
+ origin: request.origin,
+ // referrer request’s referrer.
+ referrer: request.referrer,
+ // referrer policy request’s referrer policy.
+ referrerPolicy: request.referrerPolicy,
+ // mode request’s mode.
+ mode: request.mode,
+ // credentials mode request’s credentials mode.
+ credentials: request.credentials,
+ // cache mode request’s cache mode.
+ cache: request.cache,
+ // redirect mode request’s redirect mode.
+ redirect: request.redirect,
+ // integrity metadata request’s integrity metadata.
+ integrity: request.integrity,
+ // keepalive request’s keepalive.
+ keepalive: request.keepalive,
+ // reload-navigation flag request’s reload-navigation flag.
+ reloadNavigation: request.reloadNavigation,
+ // history-navigation flag request’s history-navigation flag.
+ historyNavigation: request.historyNavigation,
+ // URL list A clone of request’s URL list.
+ urlList: [...request.urlList]
+ });
+ const initHasKey = Object.keys(init).length !== 0;
+ if (initHasKey) {
+ if (request.mode === "navigate") {
+ request.mode = "same-origin";
+ }
+ request.reloadNavigation = false;
+ request.historyNavigation = false;
+ request.origin = "client";
+ request.referrer = "client";
+ request.referrerPolicy = "";
+ request.url = request.urlList[request.urlList.length - 1];
+ request.urlList = [request.url];
+ }
+ if (init.referrer !== void 0) {
+ const referrer = init.referrer;
+ if (referrer === "") {
+ request.referrer = "no-referrer";
+ } else {
+ let parsedReferrer;
+ try {
+ parsedReferrer = new URL(referrer, baseUrl);
+ } catch (err) {
+ throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err });
+ }
+ if (parsedReferrer.protocol === "about:" && parsedReferrer.hostname === "client" || origin && !sameOrigin(parsedReferrer, environmentSettingsObject.settingsObject.baseUrl)) {
+ request.referrer = "client";
+ } else {
+ request.referrer = parsedReferrer;
+ }
+ }
+ }
+ if (init.referrerPolicy !== void 0) {
+ request.referrerPolicy = init.referrerPolicy;
+ }
+ let mode;
+ if (init.mode !== void 0) {
+ mode = init.mode;
+ } else {
+ mode = fallbackMode;
+ }
+ if (mode === "navigate") {
+ throw webidl.errors.exception({
+ header: "Request constructor",
+ message: "invalid request mode navigate."
+ });
+ }
+ if (mode != null) {
+ request.mode = mode;
+ }
+ if (init.credentials !== void 0) {
+ request.credentials = init.credentials;
+ }
+ if (init.cache !== void 0) {
+ request.cache = init.cache;
+ }
+ if (request.cache === "only-if-cached" && request.mode !== "same-origin") {
+ throw new TypeError(
+ "'only-if-cached' can be set only with 'same-origin' mode"
+ );
+ }
+ if (init.redirect !== void 0) {
+ request.redirect = init.redirect;
+ }
+ if (init.integrity != null) {
+ request.integrity = String(init.integrity);
+ }
+ if (init.keepalive !== void 0) {
+ request.keepalive = Boolean(init.keepalive);
+ }
+ if (init.method !== void 0) {
+ let method = init.method;
+ const mayBeNormalized = normalizedMethodRecords[method];
+ if (mayBeNormalized !== void 0) {
+ request.method = mayBeNormalized;
+ } else {
+ if (!isValidHTTPToken(method)) {
+ throw new TypeError(`'${method}' is not a valid HTTP method.`);
+ }
+ const upperCase = method.toUpperCase();
+ if (forbiddenMethodsSet.has(upperCase)) {
+ throw new TypeError(`'${method}' HTTP method is unsupported.`);
+ }
+ method = normalizedMethodRecordsBase[upperCase] ?? method;
+ request.method = method;
+ }
+ if (!patchMethodWarning && request.method === "patch") {
+ process.emitWarning("Using `patch` is highly likely to result in a `405 Method Not Allowed`. `PATCH` is much more likely to succeed.", {
+ code: "UNDICI-FETCH-patch"
+ });
+ patchMethodWarning = true;
+ }
+ }
+ if (init.signal !== void 0) {
+ signal = init.signal;
+ }
+ this.#state = request;
+ const ac = new AbortController();
+ this.#signal = ac.signal;
+ if (signal != null) {
+ if (signal.aborted) {
+ ac.abort(signal.reason);
+ } else {
+ this[kAbortController] = ac;
+ const acRef = new WeakRef(ac);
+ const abort = buildAbort(acRef);
+ if (abortSignalHasEventHandlerLeakWarning && getMaxListeners(signal) === defaultMaxListeners) {
+ setMaxListeners(1500, signal);
+ }
+ util.addAbortListener(signal, abort);
+ requestFinalizer.register(ac, { signal, abort }, abort);
+ }
+ }
+ this.#headers = new Headers2(kConstruct);
+ setHeadersList(this.#headers, request.headersList);
+ setHeadersGuard(this.#headers, "request");
+ if (mode === "no-cors") {
+ if (!corsSafeListedMethodsSet.has(request.method)) {
+ throw new TypeError(
+ `'${request.method} is unsupported in no-cors mode.`
+ );
+ }
+ setHeadersGuard(this.#headers, "request-no-cors");
+ }
+ if (initHasKey) {
+ const headersList = getHeadersList(this.#headers);
+ const headers = init.headers !== void 0 ? init.headers : new HeadersList(headersList);
+ headersList.clear();
+ if (headers instanceof HeadersList) {
+ for (const { name, value } of headers.rawValues()) {
+ headersList.append(name, value, false);
+ }
+ headersList.cookies = headers.cookies;
+ } else {
+ fillHeaders(this.#headers, headers);
+ }
+ }
+ const inputBody = webidl.is.Request(input) ? input.#state.body : null;
+ if ((init.body != null || inputBody != null) && (request.method === "GET" || request.method === "HEAD")) {
+ throw new TypeError("Request with GET/HEAD method cannot have body.");
+ }
+ let initBody = null;
+ if (init.body != null) {
+ const [extractedBody, contentType] = extractBody(
+ init.body,
+ request.keepalive
+ );
+ initBody = extractedBody;
+ if (contentType && !getHeadersList(this.#headers).contains("content-type", true)) {
+ this.#headers.append("content-type", contentType, true);
+ }
+ }
+ const inputOrInitBody = initBody ?? inputBody;
+ if (inputOrInitBody != null && inputOrInitBody.source == null) {
+ if (initBody != null && init.duplex == null) {
+ throw new TypeError("RequestInit: duplex option is required when sending a body.");
+ }
+ if (request.mode !== "same-origin" && request.mode !== "cors") {
+ throw new TypeError(
+ 'If request is made from ReadableStream, mode should be "same-origin" or "cors"'
+ );
+ }
+ request.useCORSPreflightFlag = true;
+ }
+ let finalBody = inputOrInitBody;
+ if (initBody == null && inputBody != null) {
+ if (bodyUnusable(input.#state)) {
+ throw new TypeError(
+ "Cannot construct a Request with a Request object that has already been used."
+ );
+ }
+ const identityTransform = new TransformStream();
+ inputBody.stream.pipeThrough(identityTransform);
+ finalBody = {
+ source: inputBody.source,
+ length: inputBody.length,
+ stream: identityTransform.readable
+ };
+ }
+ this.#state.body = finalBody;
+ }
+ // Returns request’s HTTP method, which is "GET" by default.
+ get method() {
+ webidl.brandCheck(this, _Request);
+ return this.#state.method;
+ }
+ // Returns the URL of request as a string.
+ get url() {
+ webidl.brandCheck(this, _Request);
+ return URLSerializer(this.#state.url);
+ }
+ // Returns a Headers object consisting of the headers associated with request.
+ // Note that headers added in the network layer by the user agent will not
+ // be accounted for in this object, e.g., the "Host" header.
+ get headers() {
+ webidl.brandCheck(this, _Request);
+ return this.#headers;
+ }
+ // Returns the kind of resource requested by request, e.g., "document"
+ // or "script".
+ get destination() {
+ webidl.brandCheck(this, _Request);
+ return this.#state.destination;
+ }
+ // Returns the referrer of request. Its value can be a same-origin URL if
+ // explicitly set in init, the empty string to indicate no referrer, and
+ // "about:client" when defaulting to the global’s default. This is used
+ // during fetching to determine the value of the `Referer` header of the
+ // request being made.
+ get referrer() {
+ webidl.brandCheck(this, _Request);
+ if (this.#state.referrer === "no-referrer") {
+ return "";
+ }
+ if (this.#state.referrer === "client") {
+ return "about:client";
+ }
+ return this.#state.referrer.toString();
+ }
+ // Returns the referrer policy associated with request.
+ // This is used during fetching to compute the value of the request’s
+ // referrer.
+ get referrerPolicy() {
+ webidl.brandCheck(this, _Request);
+ return this.#state.referrerPolicy;
+ }
+ // Returns the mode associated with request, which is a string indicating
+ // whether the request will use CORS, or will be restricted to same-origin
+ // URLs.
+ get mode() {
+ webidl.brandCheck(this, _Request);
+ return this.#state.mode;
+ }
+ // Returns the credentials mode associated with request,
+ // which is a string indicating whether credentials will be sent with the
+ // request always, never, or only when sent to a same-origin URL.
+ get credentials() {
+ webidl.brandCheck(this, _Request);
+ return this.#state.credentials;
+ }
+ // Returns the cache mode associated with request,
+ // which is a string indicating how the request will
+ // interact with the browser’s cache when fetching.
+ get cache() {
+ webidl.brandCheck(this, _Request);
+ return this.#state.cache;
+ }
+ // Returns the redirect mode associated with request,
+ // which is a string indicating how redirects for the
+ // request will be handled during fetching. A request
+ // will follow redirects by default.
+ get redirect() {
+ webidl.brandCheck(this, _Request);
+ return this.#state.redirect;
+ }
+ // Returns request’s subresource integrity metadata, which is a
+ // cryptographic hash of the resource being fetched. Its value
+ // consists of multiple hashes separated by whitespace. [SRI]
+ get integrity() {
+ webidl.brandCheck(this, _Request);
+ return this.#state.integrity;
+ }
+ // Returns a boolean indicating whether or not request can outlive the
+ // global in which it was created.
+ get keepalive() {
+ webidl.brandCheck(this, _Request);
+ return this.#state.keepalive;
+ }
+ // Returns a boolean indicating whether or not request is for a reload
+ // navigation.
+ get isReloadNavigation() {
+ webidl.brandCheck(this, _Request);
+ return this.#state.reloadNavigation;
+ }
+ // Returns a boolean indicating whether or not request is for a history
+ // navigation (a.k.a. back-forward navigation).
+ get isHistoryNavigation() {
+ webidl.brandCheck(this, _Request);
+ return this.#state.historyNavigation;
+ }
+ // Returns the signal associated with request, which is an AbortSignal
+ // object indicating whether or not request has been aborted, and its
+ // abort event handler.
+ get signal() {
+ webidl.brandCheck(this, _Request);
+ return this.#signal;
+ }
+ get body() {
+ webidl.brandCheck(this, _Request);
+ return this.#state.body ? this.#state.body.stream : null;
+ }
+ get bodyUsed() {
+ webidl.brandCheck(this, _Request);
+ return !!this.#state.body && util.isDisturbed(this.#state.body.stream);
+ }
+ get duplex() {
+ webidl.brandCheck(this, _Request);
+ return "half";
+ }
+ // Returns a clone of request.
+ clone() {
+ webidl.brandCheck(this, _Request);
+ if (bodyUnusable(this.#state)) {
+ throw new TypeError("unusable");
+ }
+ const clonedRequest = cloneRequest(this.#state);
+ const ac = new AbortController();
+ if (this.signal.aborted) {
+ ac.abort(this.signal.reason);
+ } else {
+ let list = dependentControllerMap.get(this.signal);
+ if (list === void 0) {
+ list = /* @__PURE__ */ new Set();
+ dependentControllerMap.set(this.signal, list);
+ }
+ const acRef = new WeakRef(ac);
+ list.add(acRef);
+ util.addAbortListener(
+ ac.signal,
+ buildAbort(acRef)
+ );
+ }
+ return fromInnerRequest(clonedRequest, this.#dispatcher, ac.signal, getHeadersGuard(this.#headers));
+ }
+ [nodeUtil.inspect.custom](depth, options2) {
+ if (options2.depth === null) {
+ options2.depth = 2;
+ }
+ options2.colors ??= true;
+ const properties = {
+ method: this.method,
+ url: this.url,
+ headers: this.headers,
+ destination: this.destination,
+ referrer: this.referrer,
+ referrerPolicy: this.referrerPolicy,
+ mode: this.mode,
+ credentials: this.credentials,
+ cache: this.cache,
+ redirect: this.redirect,
+ integrity: this.integrity,
+ keepalive: this.keepalive,
+ isReloadNavigation: this.isReloadNavigation,
+ isHistoryNavigation: this.isHistoryNavigation,
+ signal: this.signal
+ };
+ return `Request ${nodeUtil.formatWithOptions(options2, properties)}`;
+ }
+ /**
+ * @param {Request} request
+ * @param {AbortSignal} newSignal
+ */
+ static setRequestSignal(request, newSignal) {
+ request.#signal = newSignal;
+ return request;
+ }
+ /**
+ * @param {Request} request
+ */
+ static getRequestDispatcher(request) {
+ return request.#dispatcher;
+ }
+ /**
+ * @param {Request} request
+ * @param {import('../../dispatcher/dispatcher')} newDispatcher
+ */
+ static setRequestDispatcher(request, newDispatcher) {
+ request.#dispatcher = newDispatcher;
+ }
+ /**
+ * @param {Request} request
+ * @param {Headers} newHeaders
+ */
+ static setRequestHeaders(request, newHeaders) {
+ request.#headers = newHeaders;
+ }
+ /**
+ * @param {Request} request
+ */
+ static getRequestState(request) {
+ return request.#state;
+ }
+ /**
+ * @param {Request} request
+ * @param {any} newState
+ */
+ static setRequestState(request, newState) {
+ request.#state = newState;
+ }
+ };
+ var { setRequestSignal, getRequestDispatcher, setRequestDispatcher, setRequestHeaders, getRequestState, setRequestState } = Request;
+ Reflect.deleteProperty(Request, "setRequestSignal");
+ Reflect.deleteProperty(Request, "getRequestDispatcher");
+ Reflect.deleteProperty(Request, "setRequestDispatcher");
+ Reflect.deleteProperty(Request, "setRequestHeaders");
+ Reflect.deleteProperty(Request, "getRequestState");
+ Reflect.deleteProperty(Request, "setRequestState");
+ mixinBody(Request, getRequestState);
+ function makeRequest(init) {
+ return {
+ method: init.method ?? "GET",
+ localURLsOnly: init.localURLsOnly ?? false,
+ unsafeRequest: init.unsafeRequest ?? false,
+ body: init.body ?? null,
+ client: init.client ?? null,
+ reservedClient: init.reservedClient ?? null,
+ replacesClientId: init.replacesClientId ?? "",
+ window: init.window ?? "client",
+ keepalive: init.keepalive ?? false,
+ serviceWorkers: init.serviceWorkers ?? "all",
+ initiator: init.initiator ?? "",
+ destination: init.destination ?? "",
+ priority: init.priority ?? null,
+ origin: init.origin ?? "client",
+ policyContainer: init.policyContainer ?? "client",
+ referrer: init.referrer ?? "client",
+ referrerPolicy: init.referrerPolicy ?? "",
+ mode: init.mode ?? "no-cors",
+ useCORSPreflightFlag: init.useCORSPreflightFlag ?? false,
+ credentials: init.credentials ?? "same-origin",
+ useCredentials: init.useCredentials ?? false,
+ cache: init.cache ?? "default",
+ redirect: init.redirect ?? "follow",
+ integrity: init.integrity ?? "",
+ cryptoGraphicsNonceMetadata: init.cryptoGraphicsNonceMetadata ?? "",
+ parserMetadata: init.parserMetadata ?? "",
+ reloadNavigation: init.reloadNavigation ?? false,
+ historyNavigation: init.historyNavigation ?? false,
+ userActivation: init.userActivation ?? false,
+ taintedOrigin: init.taintedOrigin ?? false,
+ redirectCount: init.redirectCount ?? 0,
+ responseTainting: init.responseTainting ?? "basic",
+ preventNoCacheCacheControlHeaderModification: init.preventNoCacheCacheControlHeaderModification ?? false,
+ done: init.done ?? false,
+ timingAllowFailed: init.timingAllowFailed ?? false,
+ useURLCredentials: init.useURLCredentials ?? void 0,
+ traversableForUserPrompts: init.traversableForUserPrompts ?? "client",
+ urlList: init.urlList,
+ url: init.urlList[0],
+ headersList: init.headersList ? new HeadersList(init.headersList) : new HeadersList()
+ };
+ }
+ __name(makeRequest, "makeRequest");
+ function cloneRequest(request) {
+ const newRequest = makeRequest({ ...request, body: null });
+ if (request.body != null) {
+ newRequest.body = cloneBody(request.body);
+ }
+ return newRequest;
+ }
+ __name(cloneRequest, "cloneRequest");
+ function fromInnerRequest(innerRequest, dispatcher, signal, guard) {
+ const request = new Request(kConstruct);
+ setRequestState(request, innerRequest);
+ setRequestDispatcher(request, dispatcher);
+ setRequestSignal(request, signal);
+ const headers = new Headers2(kConstruct);
+ setRequestHeaders(request, headers);
+ setHeadersList(headers, innerRequest.headersList);
+ setHeadersGuard(headers, guard);
+ return request;
+ }
+ __name(fromInnerRequest, "fromInnerRequest");
+ Object.defineProperties(Request.prototype, {
+ method: kEnumerableProperty,
+ url: kEnumerableProperty,
+ headers: kEnumerableProperty,
+ redirect: kEnumerableProperty,
+ clone: kEnumerableProperty,
+ signal: kEnumerableProperty,
+ duplex: kEnumerableProperty,
+ destination: kEnumerableProperty,
+ body: kEnumerableProperty,
+ bodyUsed: kEnumerableProperty,
+ isHistoryNavigation: kEnumerableProperty,
+ isReloadNavigation: kEnumerableProperty,
+ keepalive: kEnumerableProperty,
+ integrity: kEnumerableProperty,
+ cache: kEnumerableProperty,
+ credentials: kEnumerableProperty,
+ attribute: kEnumerableProperty,
+ referrerPolicy: kEnumerableProperty,
+ referrer: kEnumerableProperty,
+ mode: kEnumerableProperty,
+ [Symbol.toStringTag]: {
+ value: "Request",
+ configurable: true
+ }
+ });
+ webidl.is.Request = webidl.util.MakeTypeAssertion(Request);
+ webidl.converters.RequestInfo = function(V) {
+ if (typeof V === "string") {
+ return webidl.converters.USVString(V);
+ }
+ if (webidl.is.Request(V)) {
+ return V;
+ }
+ return webidl.converters.USVString(V);
+ };
+ webidl.converters.RequestInit = webidl.dictionaryConverter([
+ {
+ key: "method",
+ converter: webidl.converters.ByteString
+ },
+ {
+ key: "headers",
+ converter: webidl.converters.HeadersInit
+ },
+ {
+ key: "body",
+ converter: webidl.nullableConverter(
+ webidl.converters.BodyInit
+ )
+ },
+ {
+ key: "referrer",
+ converter: webidl.converters.USVString
+ },
+ {
+ key: "referrerPolicy",
+ converter: webidl.converters.DOMString,
+ // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy
+ allowedValues: referrerPolicy
+ },
+ {
+ key: "mode",
+ converter: webidl.converters.DOMString,
+ // https://fetch.spec.whatwg.org/#concept-request-mode
+ allowedValues: requestMode
+ },
+ {
+ key: "credentials",
+ converter: webidl.converters.DOMString,
+ // https://fetch.spec.whatwg.org/#requestcredentials
+ allowedValues: requestCredentials
+ },
+ {
+ key: "cache",
+ converter: webidl.converters.DOMString,
+ // https://fetch.spec.whatwg.org/#requestcache
+ allowedValues: requestCache
+ },
+ {
+ key: "redirect",
+ converter: webidl.converters.DOMString,
+ // https://fetch.spec.whatwg.org/#requestredirect
+ allowedValues: requestRedirect
+ },
+ {
+ key: "integrity",
+ converter: webidl.converters.DOMString
+ },
+ {
+ key: "keepalive",
+ converter: webidl.converters.boolean
+ },
+ {
+ key: "signal",
+ converter: webidl.nullableConverter(
+ (signal) => webidl.converters.AbortSignal(
+ signal,
+ "RequestInit",
+ "signal"
+ )
+ )
+ },
+ {
+ key: "window",
+ converter: webidl.converters.any
+ },
+ {
+ key: "duplex",
+ converter: webidl.converters.DOMString,
+ allowedValues: requestDuplex
+ },
+ {
+ key: "dispatcher",
+ // undici specific option
+ converter: webidl.converters.any
+ },
+ {
+ key: "priority",
+ converter: webidl.converters.DOMString,
+ allowedValues: ["high", "low", "auto"],
+ defaultValue: /* @__PURE__ */ __name(() => "auto", "defaultValue")
+ }
+ ]);
+ module2.exports = {
+ Request,
+ makeRequest,
+ fromInnerRequest,
+ cloneRequest,
+ getRequestDispatcher,
+ getRequestState
+ };
+ }
+});
+
+// node_modules/undici/lib/web/subresource-integrity/subresource-integrity.js
+var require_subresource_integrity = __commonJS({
+ "node_modules/undici/lib/web/subresource-integrity/subresource-integrity.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var assert2 = __require("node:assert");
+ var { runtimeFeatures } = require_runtime_features();
+ var validSRIHashAlgorithmTokenSet = /* @__PURE__ */ new Map([["sha256", 0], ["sha384", 1], ["sha512", 2]]);
+ var crypto4;
+ if (runtimeFeatures.has("crypto")) {
+ crypto4 = __require("node:crypto");
+ const cryptoHashes = crypto4.getHashes();
+ if (cryptoHashes.length === 0) {
+ validSRIHashAlgorithmTokenSet.clear();
+ }
+ for (const algorithm of validSRIHashAlgorithmTokenSet.keys()) {
+ if (cryptoHashes.includes(algorithm) === false) {
+ validSRIHashAlgorithmTokenSet.delete(algorithm);
+ }
+ }
+ } else {
+ validSRIHashAlgorithmTokenSet.clear();
+ }
+ var getSRIHashAlgorithmIndex = (
+ /** @type {GetSRIHashAlgorithmIndex} */
+ Map.prototype.get.bind(
+ validSRIHashAlgorithmTokenSet
+ )
+ );
+ var isValidSRIHashAlgorithm = (
+ /** @type {IsValidSRIHashAlgorithm} */
+ Map.prototype.has.bind(validSRIHashAlgorithmTokenSet)
+ );
+ var bytesMatch = runtimeFeatures.has("crypto") === false || validSRIHashAlgorithmTokenSet.size === 0 ? () => true : (bytes, metadataList) => {
+ const parsedMetadata = parseMetadata(metadataList);
+ if (parsedMetadata.length === 0) {
+ return true;
+ }
+ const metadata = getStrongestMetadata(parsedMetadata);
+ for (const item of metadata) {
+ const algorithm = item.alg;
+ const expectedValue = item.val;
+ const actualValue = applyAlgorithmToBytes(algorithm, bytes);
+ if (caseSensitiveMatch(actualValue, expectedValue)) {
+ return true;
+ }
+ }
+ return false;
+ };
+ function getStrongestMetadata(metadataList) {
+ const result = [];
+ let strongest = null;
+ for (const item of metadataList) {
+ assert2(isValidSRIHashAlgorithm(item.alg), "Invalid SRI hash algorithm token");
+ if (result.length === 0) {
+ result.push(item);
+ strongest = item;
+ continue;
+ }
+ const currentAlgorithm = (
+ /** @type {Metadata} */
+ strongest.alg
+ );
+ const currentAlgorithmIndex = getSRIHashAlgorithmIndex(currentAlgorithm);
+ const newAlgorithm = item.alg;
+ const newAlgorithmIndex = getSRIHashAlgorithmIndex(newAlgorithm);
+ if (newAlgorithmIndex < currentAlgorithmIndex) {
+ continue;
+ } else if (newAlgorithmIndex > currentAlgorithmIndex) {
+ strongest = item;
+ result[0] = item;
+ result.length = 1;
+ } else {
+ result.push(item);
+ }
+ }
+ return result;
+ }
+ __name(getStrongestMetadata, "getStrongestMetadata");
+ function parseMetadata(metadata) {
+ const result = [];
+ for (const item of metadata.split(" ")) {
+ const expressionAndOptions = item.split("?", 1);
+ const algorithmExpression = expressionAndOptions[0];
+ let base64Value = "";
+ const algorithmAndValue = [algorithmExpression.slice(0, 6), algorithmExpression.slice(7)];
+ const algorithm = algorithmAndValue[0];
+ if (!isValidSRIHashAlgorithm(algorithm)) {
+ continue;
+ }
+ if (algorithmAndValue[1]) {
+ base64Value = algorithmAndValue[1];
+ }
+ const metadata2 = {
+ alg: algorithm,
+ val: base64Value
+ };
+ result.push(metadata2);
+ }
+ return result;
+ }
+ __name(parseMetadata, "parseMetadata");
+ var applyAlgorithmToBytes = /* @__PURE__ */ __name((algorithm, bytes) => {
+ return crypto4.hash(algorithm, bytes, "base64");
+ }, "applyAlgorithmToBytes");
+ function caseSensitiveMatch(actualValue, expectedValue) {
+ let actualValueLength = actualValue.length;
+ if (actualValueLength !== 0 && actualValue[actualValueLength - 1] === "=") {
+ actualValueLength -= 1;
+ }
+ if (actualValueLength !== 0 && actualValue[actualValueLength - 1] === "=") {
+ actualValueLength -= 1;
+ }
+ let expectedValueLength = expectedValue.length;
+ if (expectedValueLength !== 0 && expectedValue[expectedValueLength - 1] === "=") {
+ expectedValueLength -= 1;
+ }
+ if (expectedValueLength !== 0 && expectedValue[expectedValueLength - 1] === "=") {
+ expectedValueLength -= 1;
+ }
+ if (actualValueLength !== expectedValueLength) {
+ return false;
+ }
+ for (let i = 0; i < actualValueLength; ++i) {
+ if (actualValue[i] === expectedValue[i] || actualValue[i] === "+" && expectedValue[i] === "-" || actualValue[i] === "/" && expectedValue[i] === "_") {
+ continue;
+ }
+ return false;
+ }
+ return true;
+ }
+ __name(caseSensitiveMatch, "caseSensitiveMatch");
+ module2.exports = {
+ applyAlgorithmToBytes,
+ bytesMatch,
+ caseSensitiveMatch,
+ isValidSRIHashAlgorithm,
+ getStrongestMetadata,
+ parseMetadata
+ };
+ }
+});
+
+// node_modules/undici/lib/web/fetch/index.js
+var require_fetch = __commonJS({
+ "node_modules/undici/lib/web/fetch/index.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var {
+ makeNetworkError,
+ makeAppropriateNetworkError,
+ filterResponse,
+ makeResponse,
+ fromInnerResponse,
+ getResponseState
+ } = require_response();
+ var { HeadersList } = require_headers();
+ var { Request, cloneRequest, getRequestDispatcher, getRequestState } = require_request2();
+ var zlib = __require("node:zlib");
+ var {
+ makePolicyContainer,
+ clonePolicyContainer,
+ requestBadPort,
+ TAOCheck,
+ appendRequestOriginHeader,
+ responseLocationURL,
+ requestCurrentURL,
+ setRequestReferrerPolicyOnRedirect,
+ tryUpgradeRequestToAPotentiallyTrustworthyURL,
+ createOpaqueTimingInfo,
+ appendFetchMetadata,
+ corsCheck,
+ crossOriginResourcePolicyCheck,
+ determineRequestsReferrer,
+ coarsenedSharedCurrentTime,
+ sameOrigin,
+ isCancelled,
+ isAborted,
+ isErrorLike,
+ fullyReadBody,
+ readableStreamClose,
+ urlIsLocal,
+ urlIsHttpHttpsScheme,
+ urlHasHttpsScheme,
+ clampAndCoarsenConnectionTimingInfo,
+ simpleRangeHeaderValue,
+ buildContentRange,
+ createInflate,
+ extractMimeType,
+ hasAuthenticationEntry,
+ includesCredentials,
+ isTraversableNavigable
+ } = require_util2();
+ var assert2 = __require("node:assert");
+ var { safelyExtractBody, extractBody } = require_body();
+ var {
+ redirectStatusSet,
+ nullBodyStatus,
+ safeMethodsSet,
+ requestBodyHeader,
+ subresourceSet
+ } = require_constants4();
+ var EE = __require("node:events");
+ var { Readable, pipeline, finished, isErrored, isReadable } = __require("node:stream");
+ var { addAbortListener, bufferToLowerCasedHeaderName } = require_util();
+ var { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = require_data_url();
+ var { getGlobalDispatcher } = require_global2();
+ var { webidl } = require_webidl();
+ var { STATUS_CODES } = __require("node:http");
+ var { bytesMatch } = require_subresource_integrity();
+ var { createDeferredPromise } = require_promise();
+ var { isomorphicEncode } = require_infra();
+ var { runtimeFeatures } = require_runtime_features();
+ var hasZstd = runtimeFeatures.has("zstd");
+ var GET_OR_HEAD = ["GET", "HEAD"];
+ var defaultUserAgent = typeof __UNDICI_IS_NODE__ !== "undefined" || typeof esbuildDetection !== "undefined" ? "node" : "undici";
+ var resolveObjectURL;
+ var Fetch = class extends EE {
+ static {
+ __name(this, "Fetch");
+ }
+ constructor(dispatcher) {
+ super();
+ this.dispatcher = dispatcher;
+ this.connection = null;
+ this.dump = false;
+ this.state = "ongoing";
+ }
+ terminate(reason) {
+ if (this.state !== "ongoing") {
+ return;
+ }
+ this.state = "terminated";
+ this.connection?.destroy(reason);
+ this.emit("terminated", reason);
+ }
+ // https://fetch.spec.whatwg.org/#fetch-controller-abort
+ abort(error51) {
+ if (this.state !== "ongoing") {
+ return;
+ }
+ this.state = "aborted";
+ if (!error51) {
+ error51 = new DOMException("The operation was aborted.", "AbortError");
+ }
+ this.serializedAbortReason = error51;
+ this.connection?.destroy(error51);
+ this.emit("terminated", error51);
+ }
+ };
+ function handleFetchDone(response) {
+ finalizeAndReportTiming(response, "fetch");
+ }
+ __name(handleFetchDone, "handleFetchDone");
+ function fetch2(input, init = void 0) {
+ webidl.argumentLengthCheck(arguments, 1, "globalThis.fetch");
+ let p = createDeferredPromise();
+ let requestObject;
+ try {
+ requestObject = new Request(input, init);
+ } catch (e) {
+ p.reject(e);
+ return p.promise;
+ }
+ const request = getRequestState(requestObject);
+ if (requestObject.signal.aborted) {
+ abortFetch(p, request, null, requestObject.signal.reason, null);
+ return p.promise;
+ }
+ const globalObject = request.client.globalObject;
+ if (globalObject?.constructor?.name === "ServiceWorkerGlobalScope") {
+ request.serviceWorkers = "none";
+ }
+ let responseObject = null;
+ let locallyAborted = false;
+ let controller = null;
+ addAbortListener(
+ requestObject.signal,
+ () => {
+ locallyAborted = true;
+ assert2(controller != null);
+ controller.abort(requestObject.signal.reason);
+ const realResponse = responseObject?.deref();
+ abortFetch(p, request, realResponse, requestObject.signal.reason, controller.controller);
+ }
+ );
+ const processResponse = /* @__PURE__ */ __name((response) => {
+ if (locallyAborted) {
+ return;
+ }
+ if (response.aborted) {
+ abortFetch(p, request, responseObject, controller.serializedAbortReason, controller.controller);
+ return;
+ }
+ if (response.type === "error") {
+ p.reject(new TypeError("fetch failed", { cause: response.error }));
+ return;
+ }
+ responseObject = new WeakRef(fromInnerResponse(response, "immutable"));
+ p.resolve(responseObject.deref());
+ p = null;
+ }, "processResponse");
+ controller = fetching({
+ request,
+ processResponseEndOfBody: handleFetchDone,
+ processResponse,
+ dispatcher: getRequestDispatcher(requestObject),
+ // undici
+ // Keep requestObject alive to prevent its AbortController from being GC'd
+ // See https://github.com/nodejs/undici/issues/4627
+ requestObject
+ });
+ return p.promise;
+ }
+ __name(fetch2, "fetch");
+ function finalizeAndReportTiming(response, initiatorType = "other") {
+ if (response.type === "error" && response.aborted) {
+ return;
+ }
+ if (!response.urlList?.length) {
+ return;
+ }
+ const originalURL = response.urlList[0];
+ let timingInfo = response.timingInfo;
+ let cacheState = response.cacheState;
+ if (!urlIsHttpHttpsScheme(originalURL)) {
+ return;
+ }
+ if (timingInfo === null) {
+ return;
+ }
+ if (!response.timingAllowPassed) {
+ timingInfo = createOpaqueTimingInfo({
+ startTime: timingInfo.startTime
+ });
+ cacheState = "";
+ }
+ timingInfo.endTime = coarsenedSharedCurrentTime();
+ response.timingInfo = timingInfo;
+ markResourceTiming(
+ timingInfo,
+ originalURL.href,
+ initiatorType,
+ globalThis,
+ cacheState,
+ "",
+ // bodyType
+ response.status
+ );
+ }
+ __name(finalizeAndReportTiming, "finalizeAndReportTiming");
+ var markResourceTiming = performance.markResourceTiming;
+ function abortFetch(p, request, responseObject, error51, controller) {
+ if (p) {
+ p.reject(error51);
+ }
+ if (request.body?.stream != null && isReadable(request.body.stream)) {
+ request.body.stream.cancel(error51).catch((err) => {
+ if (err.code === "ERR_INVALID_STATE") {
+ return;
+ }
+ throw err;
+ });
+ }
+ if (responseObject == null) {
+ return;
+ }
+ const response = getResponseState(responseObject);
+ if (response.body?.stream != null && isReadable(response.body.stream)) {
+ controller.error(error51);
+ }
+ }
+ __name(abortFetch, "abortFetch");
+ function fetching({
+ request,
+ processRequestBodyChunkLength,
+ processRequestEndOfBody,
+ processResponse,
+ processResponseEndOfBody,
+ processResponseConsumeBody,
+ useParallelQueue = false,
+ dispatcher = getGlobalDispatcher(),
+ // undici
+ requestObject = null
+ // Keep alive to prevent AbortController GC, see #4627
+ }) {
+ assert2(dispatcher);
+ let taskDestination = null;
+ let crossOriginIsolatedCapability = false;
+ if (request.client != null) {
+ taskDestination = request.client.globalObject;
+ crossOriginIsolatedCapability = request.client.crossOriginIsolatedCapability;
+ }
+ const currentTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability);
+ const timingInfo = createOpaqueTimingInfo({
+ startTime: currentTime
+ });
+ const fetchParams = {
+ controller: new Fetch(dispatcher),
+ request,
+ timingInfo,
+ processRequestBodyChunkLength,
+ processRequestEndOfBody,
+ processResponse,
+ processResponseConsumeBody,
+ processResponseEndOfBody,
+ taskDestination,
+ crossOriginIsolatedCapability,
+ // Keep requestObject alive to prevent its AbortController from being GC'd
+ requestObject
+ };
+ assert2(!request.body || request.body.stream);
+ if (request.window === "client") {
+ request.window = request.client?.globalObject?.constructor?.name === "Window" ? request.client : "no-window";
+ }
+ if (request.origin === "client") {
+ request.origin = request.client.origin;
+ }
+ if (request.policyContainer === "client") {
+ if (request.client != null) {
+ request.policyContainer = clonePolicyContainer(
+ request.client.policyContainer
+ );
+ } else {
+ request.policyContainer = makePolicyContainer();
+ }
+ }
+ if (!request.headersList.contains("accept", true)) {
+ const value = "*/*";
+ request.headersList.append("accept", value, true);
+ }
+ if (!request.headersList.contains("accept-language", true)) {
+ request.headersList.append("accept-language", "*", true);
+ }
+ if (request.priority === null) {
+ }
+ if (subresourceSet.has(request.destination)) {
+ }
+ mainFetch(fetchParams, false);
+ return fetchParams.controller;
+ }
+ __name(fetching, "fetching");
+ async function mainFetch(fetchParams, recursive) {
+ try {
+ const request = fetchParams.request;
+ let response = null;
+ if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) {
+ response = makeNetworkError("local URLs only");
+ }
+ tryUpgradeRequestToAPotentiallyTrustworthyURL(request);
+ if (requestBadPort(request) === "blocked") {
+ response = makeNetworkError("bad port");
+ }
+ if (request.referrerPolicy === "") {
+ request.referrerPolicy = request.policyContainer.referrerPolicy;
+ }
+ if (request.referrer !== "no-referrer") {
+ request.referrer = determineRequestsReferrer(request);
+ }
+ if (response === null) {
+ const currentURL = requestCurrentURL(request);
+ if (
+ // - request’s current URL’s origin is same origin with request’s origin,
+ // and request’s response tainting is "basic"
+ sameOrigin(currentURL, request.url) && request.responseTainting === "basic" || // request’s current URL’s scheme is "data"
+ currentURL.protocol === "data:" || // - request’s mode is "navigate" or "websocket"
+ (request.mode === "navigate" || request.mode === "websocket")
+ ) {
+ request.responseTainting = "basic";
+ response = await schemeFetch(fetchParams);
+ } else if (request.mode === "same-origin") {
+ response = makeNetworkError('request mode cannot be "same-origin"');
+ } else if (request.mode === "no-cors") {
+ if (request.redirect !== "follow") {
+ response = makeNetworkError(
+ 'redirect mode cannot be "follow" for "no-cors" request'
+ );
+ } else {
+ request.responseTainting = "opaque";
+ response = await schemeFetch(fetchParams);
+ }
+ } else if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) {
+ response = makeNetworkError("URL scheme must be a HTTP(S) scheme");
+ } else {
+ request.responseTainting = "cors";
+ response = await httpFetch(fetchParams);
+ }
+ }
+ if (recursive) {
+ return response;
+ }
+ if (response.status !== 0 && !response.internalResponse) {
+ if (request.responseTainting === "cors") {
+ }
+ if (request.responseTainting === "basic") {
+ response = filterResponse(response, "basic");
+ } else if (request.responseTainting === "cors") {
+ response = filterResponse(response, "cors");
+ } else if (request.responseTainting === "opaque") {
+ response = filterResponse(response, "opaque");
+ } else {
+ assert2(false);
+ }
+ }
+ let internalResponse = response.status === 0 ? response : response.internalResponse;
+ if (internalResponse.urlList.length === 0) {
+ internalResponse.urlList.push(...request.urlList);
+ }
+ if (!request.timingAllowFailed) {
+ response.timingAllowPassed = true;
+ }
+ if (response.type === "opaque" && internalResponse.status === 206 && internalResponse.rangeRequested && !request.headers.contains("range", true)) {
+ response = internalResponse = makeNetworkError();
+ }
+ if (response.status !== 0 && (request.method === "HEAD" || request.method === "CONNECT" || nullBodyStatus.includes(internalResponse.status))) {
+ internalResponse.body = null;
+ fetchParams.controller.dump = true;
+ }
+ if (request.integrity) {
+ const processBodyError = /* @__PURE__ */ __name((reason) => fetchFinale(fetchParams, makeNetworkError(reason)), "processBodyError");
+ if (request.responseTainting === "opaque" || response.body == null) {
+ processBodyError(response.error);
+ return;
+ }
+ const processBody = /* @__PURE__ */ __name((bytes) => {
+ if (!bytesMatch(bytes, request.integrity)) {
+ processBodyError("integrity mismatch");
+ return;
+ }
+ response.body = safelyExtractBody(bytes)[0];
+ fetchFinale(fetchParams, response);
+ }, "processBody");
+ fullyReadBody(response.body, processBody, processBodyError);
+ } else {
+ fetchFinale(fetchParams, response);
+ }
+ } catch (err) {
+ fetchParams.controller.terminate(err);
+ }
+ }
+ __name(mainFetch, "mainFetch");
+ function schemeFetch(fetchParams) {
+ if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) {
+ return Promise.resolve(makeAppropriateNetworkError(fetchParams));
+ }
+ const { request } = fetchParams;
+ const { protocol: scheme } = requestCurrentURL(request);
+ switch (scheme) {
+ case "about:": {
+ return Promise.resolve(makeNetworkError("about scheme is not supported"));
+ }
+ case "blob:": {
+ if (!resolveObjectURL) {
+ resolveObjectURL = __require("node:buffer").resolveObjectURL;
+ }
+ const blobURLEntry = requestCurrentURL(request);
+ if (blobURLEntry.search.length !== 0) {
+ return Promise.resolve(makeNetworkError("NetworkError when attempting to fetch resource."));
+ }
+ const blob = resolveObjectURL(blobURLEntry.toString());
+ if (request.method !== "GET" || !webidl.is.Blob(blob)) {
+ return Promise.resolve(makeNetworkError("invalid method"));
+ }
+ const response = makeResponse();
+ const fullLength = blob.size;
+ const serializedFullLength = isomorphicEncode(`${fullLength}`);
+ const type2 = blob.type;
+ if (!request.headersList.contains("range", true)) {
+ const bodyWithType = extractBody(blob);
+ response.statusText = "OK";
+ response.body = bodyWithType[0];
+ response.headersList.set("content-length", serializedFullLength, true);
+ response.headersList.set("content-type", type2, true);
+ } else {
+ response.rangeRequested = true;
+ const rangeHeader = request.headersList.get("range", true);
+ const rangeValue = simpleRangeHeaderValue(rangeHeader, true);
+ if (rangeValue === "failure") {
+ return Promise.resolve(makeNetworkError("failed to fetch the data URL"));
+ }
+ let { rangeStartValue: rangeStart, rangeEndValue: rangeEnd } = rangeValue;
+ if (rangeStart === null) {
+ rangeStart = fullLength - rangeEnd;
+ rangeEnd = rangeStart + rangeEnd - 1;
+ } else {
+ if (rangeStart >= fullLength) {
+ return Promise.resolve(makeNetworkError("Range start is greater than the blob's size."));
+ }
+ if (rangeEnd === null || rangeEnd >= fullLength) {
+ rangeEnd = fullLength - 1;
+ }
+ }
+ const slicedBlob = blob.slice(rangeStart, rangeEnd + 1, type2);
+ const slicedBodyWithType = extractBody(slicedBlob);
+ response.body = slicedBodyWithType[0];
+ const serializedSlicedLength = isomorphicEncode(`${slicedBlob.size}`);
+ const contentRange = buildContentRange(rangeStart, rangeEnd, fullLength);
+ response.status = 206;
+ response.statusText = "Partial Content";
+ response.headersList.set("content-length", serializedSlicedLength, true);
+ response.headersList.set("content-type", type2, true);
+ response.headersList.set("content-range", contentRange, true);
+ }
+ return Promise.resolve(response);
+ }
+ case "data:": {
+ const currentURL = requestCurrentURL(request);
+ const dataURLStruct = dataURLProcessor(currentURL);
+ if (dataURLStruct === "failure") {
+ return Promise.resolve(makeNetworkError("failed to fetch the data URL"));
+ }
+ const mimeType = serializeAMimeType(dataURLStruct.mimeType);
+ return Promise.resolve(makeResponse({
+ statusText: "OK",
+ headersList: [
+ ["content-type", { name: "Content-Type", value: mimeType }]
+ ],
+ body: safelyExtractBody(dataURLStruct.body)[0]
+ }));
+ }
+ case "file:": {
+ return Promise.resolve(makeNetworkError("not implemented... yet..."));
+ }
+ case "http:":
+ case "https:": {
+ return httpFetch(fetchParams).catch((err) => makeNetworkError(err));
+ }
+ default: {
+ return Promise.resolve(makeNetworkError("unknown scheme"));
+ }
+ }
+ }
+ __name(schemeFetch, "schemeFetch");
+ function finalizeResponse2(fetchParams, response) {
+ fetchParams.request.done = true;
+ if (fetchParams.processResponseDone != null) {
+ queueMicrotask(() => fetchParams.processResponseDone(response));
+ }
+ }
+ __name(finalizeResponse2, "finalizeResponse");
+ function fetchFinale(fetchParams, response) {
+ let timingInfo = fetchParams.timingInfo;
+ const processResponseEndOfBody = /* @__PURE__ */ __name(() => {
+ const unsafeEndTime = Date.now();
+ if (fetchParams.request.destination === "document") {
+ fetchParams.controller.fullTimingInfo = timingInfo;
+ }
+ fetchParams.controller.reportTimingSteps = () => {
+ if (!urlIsHttpHttpsScheme(fetchParams.request.url)) {
+ return;
+ }
+ timingInfo.endTime = unsafeEndTime;
+ let cacheState = response.cacheState;
+ const bodyInfo = response.bodyInfo;
+ if (!response.timingAllowPassed) {
+ timingInfo = createOpaqueTimingInfo(timingInfo);
+ cacheState = "";
+ }
+ let responseStatus = 0;
+ if (fetchParams.request.mode !== "navigate" || !response.hasCrossOriginRedirects) {
+ responseStatus = response.status;
+ const mimeType = extractMimeType(response.headersList);
+ if (mimeType !== "failure") {
+ bodyInfo.contentType = minimizeSupportedMimeType(mimeType);
+ }
+ }
+ if (fetchParams.request.initiatorType != null) {
+ markResourceTiming(timingInfo, fetchParams.request.url.href, fetchParams.request.initiatorType, globalThis, cacheState, bodyInfo, responseStatus);
+ }
+ };
+ const processResponseEndOfBodyTask = /* @__PURE__ */ __name(() => {
+ fetchParams.request.done = true;
+ if (fetchParams.processResponseEndOfBody != null) {
+ queueMicrotask(() => fetchParams.processResponseEndOfBody(response));
+ }
+ if (fetchParams.request.initiatorType != null) {
+ fetchParams.controller.reportTimingSteps();
+ }
+ }, "processResponseEndOfBodyTask");
+ queueMicrotask(() => processResponseEndOfBodyTask());
+ }, "processResponseEndOfBody");
+ if (fetchParams.processResponse != null) {
+ queueMicrotask(() => {
+ fetchParams.processResponse(response);
+ fetchParams.processResponse = null;
+ });
+ }
+ const internalResponse = response.type === "error" ? response : response.internalResponse ?? response;
+ if (internalResponse.body == null) {
+ processResponseEndOfBody();
+ } else {
+ finished(internalResponse.body.stream, () => {
+ processResponseEndOfBody();
+ });
+ }
+ }
+ __name(fetchFinale, "fetchFinale");
+ async function httpFetch(fetchParams) {
+ const request = fetchParams.request;
+ let response = null;
+ let actualResponse = null;
+ const timingInfo = fetchParams.timingInfo;
+ if (request.serviceWorkers === "all") {
+ }
+ if (response === null) {
+ if (request.redirect === "follow") {
+ request.serviceWorkers = "none";
+ }
+ actualResponse = response = await httpNetworkOrCacheFetch(fetchParams);
+ if (request.responseTainting === "cors" && corsCheck(request, response) === "failure") {
+ return makeNetworkError("cors failure");
+ }
+ if (TAOCheck(request, response) === "failure") {
+ request.timingAllowFailed = true;
+ }
+ }
+ if ((request.responseTainting === "opaque" || response.type === "opaque") && crossOriginResourcePolicyCheck(
+ request.origin,
+ request.client,
+ request.destination,
+ actualResponse
+ ) === "blocked") {
+ return makeNetworkError("blocked");
+ }
+ if (redirectStatusSet.has(actualResponse.status)) {
+ if (request.redirect !== "manual") {
+ fetchParams.controller.connection.destroy(void 0, false);
+ }
+ if (request.redirect === "error") {
+ response = makeNetworkError("unexpected redirect");
+ } else if (request.redirect === "manual") {
+ response = actualResponse;
+ } else if (request.redirect === "follow") {
+ response = await httpRedirectFetch(fetchParams, response);
+ } else {
+ assert2(false);
+ }
+ }
+ response.timingInfo = timingInfo;
+ return response;
+ }
+ __name(httpFetch, "httpFetch");
+ function httpRedirectFetch(fetchParams, response) {
+ const request = fetchParams.request;
+ const actualResponse = response.internalResponse ? response.internalResponse : response;
+ let locationURL;
+ try {
+ locationURL = responseLocationURL(
+ actualResponse,
+ requestCurrentURL(request).hash
+ );
+ if (locationURL == null) {
+ return response;
+ }
+ } catch (err) {
+ return Promise.resolve(makeNetworkError(err));
+ }
+ if (!urlIsHttpHttpsScheme(locationURL)) {
+ return Promise.resolve(makeNetworkError("URL scheme must be a HTTP(S) scheme"));
+ }
+ if (request.redirectCount === 20) {
+ return Promise.resolve(makeNetworkError("redirect count exceeded"));
+ }
+ request.redirectCount += 1;
+ if (request.mode === "cors" && (locationURL.username || locationURL.password) && !sameOrigin(request, locationURL)) {
+ return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"'));
+ }
+ if (request.responseTainting === "cors" && (locationURL.username || locationURL.password)) {
+ return Promise.resolve(makeNetworkError(
+ 'URL cannot contain credentials for request mode "cors"'
+ ));
+ }
+ if (actualResponse.status !== 303 && request.body != null && request.body.source == null) {
+ return Promise.resolve(makeNetworkError());
+ }
+ if ([301, 302].includes(actualResponse.status) && request.method === "POST" || actualResponse.status === 303 && !GET_OR_HEAD.includes(request.method)) {
+ request.method = "GET";
+ request.body = null;
+ for (const headerName of requestBodyHeader) {
+ request.headersList.delete(headerName);
+ }
+ }
+ if (!sameOrigin(requestCurrentURL(request), locationURL)) {
+ request.headersList.delete("authorization", true);
+ request.headersList.delete("proxy-authorization", true);
+ request.headersList.delete("cookie", true);
+ request.headersList.delete("host", true);
+ }
+ if (request.body != null) {
+ assert2(request.body.source != null);
+ request.body = safelyExtractBody(request.body.source)[0];
+ }
+ const timingInfo = fetchParams.timingInfo;
+ timingInfo.redirectEndTime = timingInfo.postRedirectStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability);
+ if (timingInfo.redirectStartTime === 0) {
+ timingInfo.redirectStartTime = timingInfo.startTime;
+ }
+ request.urlList.push(locationURL);
+ setRequestReferrerPolicyOnRedirect(request, actualResponse);
+ return mainFetch(fetchParams, true);
+ }
+ __name(httpRedirectFetch, "httpRedirectFetch");
+ async function httpNetworkOrCacheFetch(fetchParams, isAuthenticationFetch = false, isNewConnectionFetch = false) {
+ const request = fetchParams.request;
+ let httpFetchParams = null;
+ let httpRequest = null;
+ let response = null;
+ const httpCache = null;
+ const revalidatingFlag = false;
+ if (request.window === "no-window" && request.redirect === "error") {
+ httpFetchParams = fetchParams;
+ httpRequest = request;
+ } else {
+ httpRequest = cloneRequest(request);
+ httpFetchParams = { ...fetchParams };
+ httpFetchParams.request = httpRequest;
+ }
+ const includeCredentials = request.credentials === "include" || request.credentials === "same-origin" && request.responseTainting === "basic";
+ const contentLength = httpRequest.body ? httpRequest.body.length : null;
+ let contentLengthHeaderValue = null;
+ if (httpRequest.body == null && ["POST", "PUT"].includes(httpRequest.method)) {
+ contentLengthHeaderValue = "0";
+ }
+ if (contentLength != null) {
+ contentLengthHeaderValue = isomorphicEncode(`${contentLength}`);
+ }
+ if (contentLengthHeaderValue != null && !httpRequest.headersList.contains("content-length", true)) {
+ httpRequest.headersList.append("content-length", contentLengthHeaderValue, true);
+ }
+ if (contentLength != null && httpRequest.keepalive) {
+ }
+ if (webidl.is.URL(httpRequest.referrer)) {
+ httpRequest.headersList.append("referer", isomorphicEncode(httpRequest.referrer.href), true);
+ }
+ appendRequestOriginHeader(httpRequest);
+ appendFetchMetadata(httpRequest);
+ if (!httpRequest.headersList.contains("user-agent", true)) {
+ httpRequest.headersList.append("user-agent", defaultUserAgent, true);
+ }
+ if (httpRequest.cache === "default" && (httpRequest.headersList.contains("if-modified-since", true) || httpRequest.headersList.contains("if-none-match", true) || httpRequest.headersList.contains("if-unmodified-since", true) || httpRequest.headersList.contains("if-match", true) || httpRequest.headersList.contains("if-range", true))) {
+ httpRequest.cache = "no-store";
+ }
+ if (httpRequest.cache === "no-cache" && !httpRequest.preventNoCacheCacheControlHeaderModification && !httpRequest.headersList.contains("cache-control", true)) {
+ httpRequest.headersList.append("cache-control", "max-age=0", true);
+ }
+ if (httpRequest.cache === "no-store" || httpRequest.cache === "reload") {
+ if (!httpRequest.headersList.contains("pragma", true)) {
+ httpRequest.headersList.append("pragma", "no-cache", true);
+ }
+ if (!httpRequest.headersList.contains("cache-control", true)) {
+ httpRequest.headersList.append("cache-control", "no-cache", true);
+ }
+ }
+ if (httpRequest.headersList.contains("range", true)) {
+ httpRequest.headersList.append("accept-encoding", "identity", true);
+ }
+ if (!httpRequest.headersList.contains("accept-encoding", true)) {
+ if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) {
+ httpRequest.headersList.append("accept-encoding", "br, gzip, deflate", true);
+ } else {
+ httpRequest.headersList.append("accept-encoding", "gzip, deflate", true);
+ }
+ }
+ httpRequest.headersList.delete("host", true);
+ if (includeCredentials) {
+ if (!httpRequest.headersList.contains("authorization", true)) {
+ let authorizationValue = null;
+ if (hasAuthenticationEntry(httpRequest) && (httpRequest.useURLCredentials === void 0 || !includesCredentials(requestCurrentURL(httpRequest)))) {
+ } else if (includesCredentials(requestCurrentURL(httpRequest)) && isAuthenticationFetch) {
+ const { username, password } = requestCurrentURL(httpRequest);
+ authorizationValue = `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`;
+ }
+ if (authorizationValue !== null) {
+ httpRequest.headersList.append("Authorization", authorizationValue, false);
+ }
+ }
+ }
+ if (httpCache == null) {
+ httpRequest.cache = "no-store";
+ }
+ if (httpRequest.cache !== "no-store" && httpRequest.cache !== "reload") {
+ }
+ if (response == null) {
+ if (httpRequest.cache === "only-if-cached") {
+ return makeNetworkError("only if cached");
+ }
+ const forwardResponse = await httpNetworkFetch(
+ httpFetchParams,
+ includeCredentials,
+ isNewConnectionFetch
+ );
+ if (!safeMethodsSet.has(httpRequest.method) && forwardResponse.status >= 200 && forwardResponse.status <= 399) {
+ }
+ if (revalidatingFlag && forwardResponse.status === 304) {
+ }
+ if (response == null) {
+ response = forwardResponse;
+ }
+ }
+ response.urlList = [...httpRequest.urlList];
+ if (httpRequest.headersList.contains("range", true)) {
+ response.rangeRequested = true;
+ }
+ response.requestIncludesCredentials = includeCredentials;
+ if (response.status === 401 && httpRequest.responseTainting !== "cors" && includeCredentials && (request.useURLCredentials !== void 0 || isTraversableNavigable(request.traversableForUserPrompts))) {
+ if (request.body != null) {
+ if (request.body.source == null) {
+ return response;
+ }
+ request.body = safelyExtractBody(request.body.source)[0];
+ }
+ if (request.useURLCredentials === void 0 || isAuthenticationFetch) {
+ if (isCancelled(fetchParams)) {
+ return makeAppropriateNetworkError(fetchParams);
+ }
+ return response;
+ }
+ fetchParams.controller.connection.destroy();
+ response = await httpNetworkOrCacheFetch(fetchParams, true);
+ }
+ if (response.status === 407) {
+ if (request.window === "no-window") {
+ return makeNetworkError();
+ }
+ if (isCancelled(fetchParams)) {
+ return makeAppropriateNetworkError(fetchParams);
+ }
+ return makeNetworkError("proxy authentication required");
+ }
+ if (
+ // response’s status is 421
+ response.status === 421 && // isNewConnectionFetch is false
+ !isNewConnectionFetch && // request’s body is null, or request’s body is non-null and request’s body’s source is non-null
+ (request.body == null || request.body.source != null)
+ ) {
+ if (isCancelled(fetchParams)) {
+ return makeAppropriateNetworkError(fetchParams);
+ }
+ fetchParams.controller.connection.destroy();
+ response = await httpNetworkOrCacheFetch(
+ fetchParams,
+ isAuthenticationFetch,
+ true
+ );
+ }
+ if (isAuthenticationFetch) {
+ }
+ return response;
+ }
+ __name(httpNetworkOrCacheFetch, "httpNetworkOrCacheFetch");
+ async function httpNetworkFetch(fetchParams, includeCredentials = false, forceNewConnection = false) {
+ assert2(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed);
+ fetchParams.controller.connection = {
+ abort: null,
+ destroyed: false,
+ destroy(err, abort = true) {
+ if (!this.destroyed) {
+ this.destroyed = true;
+ if (abort) {
+ this.abort?.(err ?? new DOMException("The operation was aborted.", "AbortError"));
+ }
+ }
+ }
+ };
+ const request = fetchParams.request;
+ let response = null;
+ const timingInfo = fetchParams.timingInfo;
+ const httpCache = null;
+ if (httpCache == null) {
+ request.cache = "no-store";
+ }
+ const newConnection = forceNewConnection ? "yes" : "no";
+ if (request.mode === "websocket") {
+ } else {
+ }
+ let requestBody = null;
+ if (request.body == null && fetchParams.processRequestEndOfBody) {
+ queueMicrotask(() => fetchParams.processRequestEndOfBody());
+ } else if (request.body != null) {
+ const processBodyChunk = /* @__PURE__ */ __name(async function* (bytes) {
+ if (isCancelled(fetchParams)) {
+ return;
+ }
+ yield bytes;
+ fetchParams.processRequestBodyChunkLength?.(bytes.byteLength);
+ }, "processBodyChunk");
+ const processEndOfBody = /* @__PURE__ */ __name(() => {
+ if (isCancelled(fetchParams)) {
+ return;
+ }
+ if (fetchParams.processRequestEndOfBody) {
+ fetchParams.processRequestEndOfBody();
+ }
+ }, "processEndOfBody");
+ const processBodyError = /* @__PURE__ */ __name((e) => {
+ if (isCancelled(fetchParams)) {
+ return;
+ }
+ if (e.name === "AbortError") {
+ fetchParams.controller.abort();
+ } else {
+ fetchParams.controller.terminate(e);
+ }
+ }, "processBodyError");
+ requestBody = (async function* () {
+ try {
+ for await (const bytes of request.body.stream) {
+ yield* processBodyChunk(bytes);
+ }
+ processEndOfBody();
+ } catch (err) {
+ processBodyError(err);
+ }
+ })();
+ }
+ try {
+ const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody });
+ if (socket) {
+ response = makeResponse({ status, statusText, headersList, socket });
+ } else {
+ const iterator = body[Symbol.asyncIterator]();
+ fetchParams.controller.next = () => iterator.next();
+ response = makeResponse({ status, statusText, headersList });
+ }
+ } catch (err) {
+ if (err.name === "AbortError") {
+ fetchParams.controller.connection.destroy();
+ return makeAppropriateNetworkError(fetchParams, err);
+ }
+ return makeNetworkError(err);
+ }
+ const pullAlgorithm = /* @__PURE__ */ __name(() => {
+ return fetchParams.controller.resume();
+ }, "pullAlgorithm");
+ const cancelAlgorithm = /* @__PURE__ */ __name((reason) => {
+ if (!isCancelled(fetchParams)) {
+ fetchParams.controller.abort(reason);
+ }
+ }, "cancelAlgorithm");
+ const stream = new ReadableStream(
+ {
+ start(controller) {
+ fetchParams.controller.controller = controller;
+ },
+ pull: pullAlgorithm,
+ cancel: cancelAlgorithm,
+ type: "bytes"
+ }
+ );
+ response.body = { stream, source: null, length: null };
+ if (!fetchParams.controller.resume) {
+ fetchParams.controller.on("terminated", onAborted);
+ }
+ fetchParams.controller.resume = async () => {
+ while (true) {
+ let bytes;
+ let isFailure;
+ try {
+ const { done, value } = await fetchParams.controller.next();
+ if (isAborted(fetchParams)) {
+ break;
+ }
+ bytes = done ? void 0 : value;
+ } catch (err) {
+ if (fetchParams.controller.ended && !timingInfo.encodedBodySize) {
+ bytes = void 0;
+ } else {
+ bytes = err;
+ isFailure = true;
+ }
+ }
+ if (bytes === void 0) {
+ readableStreamClose(fetchParams.controller.controller);
+ finalizeResponse2(fetchParams, response);
+ return;
+ }
+ timingInfo.decodedBodySize += bytes?.byteLength ?? 0;
+ if (isFailure) {
+ fetchParams.controller.terminate(bytes);
+ return;
+ }
+ const buffer = new Uint8Array(bytes);
+ if (buffer.byteLength) {
+ fetchParams.controller.controller.enqueue(buffer);
+ }
+ if (isErrored(stream)) {
+ fetchParams.controller.terminate();
+ return;
+ }
+ if (fetchParams.controller.controller.desiredSize <= 0) {
+ return;
+ }
+ }
+ };
+ function onAborted(reason) {
+ if (isAborted(fetchParams)) {
+ response.aborted = true;
+ if (isReadable(stream)) {
+ fetchParams.controller.controller.error(
+ fetchParams.controller.serializedAbortReason
+ );
+ }
+ } else {
+ if (isReadable(stream)) {
+ fetchParams.controller.controller.error(new TypeError("terminated", {
+ cause: isErrorLike(reason) ? reason : void 0
+ }));
+ }
+ }
+ fetchParams.controller.connection.destroy();
+ }
+ __name(onAborted, "onAborted");
+ return response;
+ function dispatch({ body }) {
+ const url2 = requestCurrentURL(request);
+ const agent = fetchParams.controller.dispatcher;
+ const path27 = url2.pathname + url2.search;
+ const hasTrailingQuestionMark = url2.search.length === 0 && url2.href[url2.href.length - url2.hash.length - 1] === "?";
+ return new Promise((resolve16, reject) => agent.dispatch(
+ {
+ path: hasTrailingQuestionMark ? `${path27}?` : path27,
+ origin: url2.origin,
+ method: request.method,
+ body: agent.isMockActive ? request.body && (request.body.source || request.body.stream) : body,
+ headers: request.headersList.entries,
+ maxRedirections: 0,
+ upgrade: request.mode === "websocket" ? "websocket" : void 0
+ },
+ {
+ body: null,
+ abort: null,
+ onConnect(abort) {
+ const { connection } = fetchParams.controller;
+ timingInfo.finalConnectionTimingInfo = clampAndCoarsenConnectionTimingInfo(void 0, timingInfo.postRedirectStartTime, fetchParams.crossOriginIsolatedCapability);
+ if (connection.destroyed) {
+ abort(new DOMException("The operation was aborted.", "AbortError"));
+ } else {
+ fetchParams.controller.on("terminated", abort);
+ this.abort = connection.abort = abort;
+ }
+ timingInfo.finalNetworkRequestStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability);
+ },
+ onResponseStarted() {
+ timingInfo.finalNetworkResponseStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability);
+ },
+ onHeaders(status, rawHeaders, resume, statusText) {
+ if (status < 200) {
+ return false;
+ }
+ const headersList = new HeadersList();
+ for (let i = 0; i < rawHeaders.length; i += 2) {
+ const nameStr = bufferToLowerCasedHeaderName(rawHeaders[i]);
+ const value = rawHeaders[i + 1];
+ if (Array.isArray(value) && !Buffer.isBuffer(rawHeaders[i + 1])) {
+ for (const val of value) {
+ headersList.append(nameStr, val.toString("latin1"), true);
+ }
+ } else {
+ headersList.append(nameStr, value.toString("latin1"), true);
+ }
+ }
+ const location = headersList.get("location", true);
+ this.body = new Readable({ read: resume });
+ const willFollow = location && request.redirect === "follow" && redirectStatusSet.has(status);
+ const decoders = [];
+ if (request.method !== "HEAD" && request.method !== "CONNECT" && !nullBodyStatus.includes(status) && !willFollow) {
+ const contentEncoding = headersList.get("content-encoding", true);
+ const codings = contentEncoding ? contentEncoding.toLowerCase().split(",") : [];
+ const maxContentEncodings = 5;
+ if (codings.length > maxContentEncodings) {
+ reject(new Error(`too many content-encodings in response: ${codings.length}, maximum allowed is ${maxContentEncodings}`));
+ return true;
+ }
+ for (let i = codings.length - 1; i >= 0; --i) {
+ const coding = codings[i].trim();
+ if (coding === "x-gzip" || coding === "gzip") {
+ decoders.push(zlib.createGunzip({
+ // Be less strict when decoding compressed responses, since sometimes
+ // servers send slightly invalid responses that are still accepted
+ // by common browsers.
+ // Always using Z_SYNC_FLUSH is what cURL does.
+ flush: zlib.constants.Z_SYNC_FLUSH,
+ finishFlush: zlib.constants.Z_SYNC_FLUSH
+ }));
+ } else if (coding === "deflate") {
+ decoders.push(createInflate({
+ flush: zlib.constants.Z_SYNC_FLUSH,
+ finishFlush: zlib.constants.Z_SYNC_FLUSH
+ }));
+ } else if (coding === "br") {
+ decoders.push(zlib.createBrotliDecompress({
+ flush: zlib.constants.BROTLI_OPERATION_FLUSH,
+ finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH
+ }));
+ } else if (coding === "zstd" && hasZstd) {
+ decoders.push(zlib.createZstdDecompress({
+ flush: zlib.constants.ZSTD_e_continue,
+ finishFlush: zlib.constants.ZSTD_e_end
+ }));
+ } else {
+ decoders.length = 0;
+ break;
+ }
+ }
+ }
+ const onError = this.onError.bind(this);
+ resolve16({
+ status,
+ statusText,
+ headersList,
+ body: decoders.length ? pipeline(this.body, ...decoders, (err) => {
+ if (err) {
+ this.onError(err);
+ }
+ }).on("error", onError) : this.body.on("error", onError)
+ });
+ return true;
+ },
+ onData(chunk) {
+ if (fetchParams.controller.dump) {
+ return;
+ }
+ const bytes = chunk;
+ timingInfo.encodedBodySize += bytes.byteLength;
+ return this.body.push(bytes);
+ },
+ onComplete() {
+ if (this.abort) {
+ fetchParams.controller.off("terminated", this.abort);
+ }
+ fetchParams.controller.ended = true;
+ this.body.push(null);
+ },
+ onError(error51) {
+ if (this.abort) {
+ fetchParams.controller.off("terminated", this.abort);
+ }
+ this.body?.destroy(error51);
+ fetchParams.controller.terminate(error51);
+ reject(error51);
+ },
+ onRequestUpgrade(_controller, status, headers, socket) {
+ if (socket.session != null && status !== 200 || socket.session == null && status !== 101) {
+ return false;
+ }
+ const headersList = new HeadersList();
+ for (const [name, value] of Object.entries(headers)) {
+ if (value == null) {
+ continue;
+ }
+ const headerName = name.toLowerCase();
+ if (Array.isArray(value)) {
+ for (const entry of value) {
+ headersList.append(headerName, String(entry), true);
+ }
+ } else {
+ headersList.append(headerName, String(value), true);
+ }
+ }
+ resolve16({
+ status,
+ statusText: STATUS_CODES[status],
+ headersList,
+ socket
+ });
+ return true;
+ },
+ onUpgrade(status, rawHeaders, socket) {
+ if (socket.session != null && status !== 200 || socket.session == null && status !== 101) {
+ return false;
+ }
+ const headersList = new HeadersList();
+ for (let i = 0; i < rawHeaders.length; i += 2) {
+ const nameStr = bufferToLowerCasedHeaderName(rawHeaders[i]);
+ const value = rawHeaders[i + 1];
+ if (Array.isArray(value) && !Buffer.isBuffer(rawHeaders[i + 1])) {
+ for (const val of value) {
+ headersList.append(nameStr, val.toString("latin1"), true);
+ }
+ } else {
+ headersList.append(nameStr, value.toString("latin1"), true);
+ }
+ }
+ resolve16({
+ status,
+ statusText: STATUS_CODES[status],
+ headersList,
+ socket
+ });
+ return true;
+ }
+ }
+ ));
+ }
+ __name(dispatch, "dispatch");
+ }
+ __name(httpNetworkFetch, "httpNetworkFetch");
+ module2.exports = {
+ fetch: fetch2,
+ Fetch,
+ fetching,
+ finalizeAndReportTiming
+ };
+ }
+});
+
+// node_modules/undici/lib/web/cache/util.js
+var require_util3 = __commonJS({
+ "node_modules/undici/lib/web/cache/util.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var assert2 = __require("node:assert");
+ var { URLSerializer } = require_data_url();
+ var { isValidHeaderName } = require_util2();
+ function urlEquals(A, B, excludeFragment = false) {
+ const serializedA = URLSerializer(A, excludeFragment);
+ const serializedB = URLSerializer(B, excludeFragment);
+ return serializedA === serializedB;
+ }
+ __name(urlEquals, "urlEquals");
+ function getFieldValues(header) {
+ assert2(header !== null);
+ const values = [];
+ for (let value of header.split(",")) {
+ value = value.trim();
+ if (isValidHeaderName(value)) {
+ values.push(value);
+ }
+ }
+ return values;
+ }
+ __name(getFieldValues, "getFieldValues");
+ module2.exports = {
+ urlEquals,
+ getFieldValues
+ };
+ }
+});
+
+// node_modules/undici/lib/web/cache/cache.js
+var require_cache3 = __commonJS({
+ "node_modules/undici/lib/web/cache/cache.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var assert2 = __require("node:assert");
+ var { kConstruct } = require_symbols();
+ var { urlEquals, getFieldValues } = require_util3();
+ var { kEnumerableProperty, isDisturbed } = require_util();
+ var { webidl } = require_webidl();
+ var { cloneResponse, fromInnerResponse, getResponseState } = require_response();
+ var { Request, fromInnerRequest, getRequestState } = require_request2();
+ var { fetching } = require_fetch();
+ var { urlIsHttpHttpsScheme, readAllBytes } = require_util2();
+ var { createDeferredPromise } = require_promise();
+ var Cache = class _Cache {
+ static {
+ __name(this, "Cache");
+ }
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list
+ * @type {requestResponseList}
+ */
+ #relevantRequestResponseList;
+ constructor() {
+ if (arguments[0] !== kConstruct) {
+ webidl.illegalConstructor();
+ }
+ webidl.util.markAsUncloneable(this);
+ this.#relevantRequestResponseList = arguments[1];
+ }
+ async match(request, options2 = {}) {
+ webidl.brandCheck(this, _Cache);
+ const prefix = "Cache.match";
+ webidl.argumentLengthCheck(arguments, 1, prefix);
+ request = webidl.converters.RequestInfo(request);
+ options2 = webidl.converters.CacheQueryOptions(options2, prefix, "options");
+ const p = this.#internalMatchAll(request, options2, 1);
+ if (p.length === 0) {
+ return;
+ }
+ return p[0];
+ }
+ async matchAll(request = void 0, options2 = {}) {
+ webidl.brandCheck(this, _Cache);
+ const prefix = "Cache.matchAll";
+ if (request !== void 0) request = webidl.converters.RequestInfo(request);
+ options2 = webidl.converters.CacheQueryOptions(options2, prefix, "options");
+ return this.#internalMatchAll(request, options2);
+ }
+ async add(request) {
+ webidl.brandCheck(this, _Cache);
+ const prefix = "Cache.add";
+ webidl.argumentLengthCheck(arguments, 1, prefix);
+ request = webidl.converters.RequestInfo(request);
+ const requests = [request];
+ const responseArrayPromise = this.addAll(requests);
+ return await responseArrayPromise;
+ }
+ async addAll(requests) {
+ webidl.brandCheck(this, _Cache);
+ const prefix = "Cache.addAll";
+ webidl.argumentLengthCheck(arguments, 1, prefix);
+ const responsePromises = [];
+ const requestList = [];
+ for (let request of requests) {
+ if (request === void 0) {
+ throw webidl.errors.conversionFailed({
+ prefix,
+ argument: "Argument 1",
+ types: ["undefined is not allowed"]
+ });
+ }
+ request = webidl.converters.RequestInfo(request);
+ if (typeof request === "string") {
+ continue;
+ }
+ const r = getRequestState(request);
+ if (!urlIsHttpHttpsScheme(r.url) || r.method !== "GET") {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: "Expected http/s scheme when method is not GET."
+ });
+ }
+ }
+ const fetchControllers = [];
+ for (const request of requests) {
+ const r = getRequestState(new Request(request));
+ if (!urlIsHttpHttpsScheme(r.url)) {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: "Expected http/s scheme."
+ });
+ }
+ r.initiator = "fetch";
+ r.destination = "subresource";
+ requestList.push(r);
+ const responsePromise = createDeferredPromise();
+ fetchControllers.push(fetching({
+ request: r,
+ processResponse(response) {
+ if (response.type === "error" || response.status === 206 || response.status < 200 || response.status > 299) {
+ responsePromise.reject(webidl.errors.exception({
+ header: "Cache.addAll",
+ message: "Received an invalid status code or the request failed."
+ }));
+ } else if (response.headersList.contains("vary")) {
+ const fieldValues = getFieldValues(response.headersList.get("vary"));
+ for (const fieldValue of fieldValues) {
+ if (fieldValue === "*") {
+ responsePromise.reject(webidl.errors.exception({
+ header: "Cache.addAll",
+ message: "invalid vary field value"
+ }));
+ for (const controller of fetchControllers) {
+ controller.abort();
+ }
+ return;
+ }
+ }
+ }
+ },
+ processResponseEndOfBody(response) {
+ if (response.aborted) {
+ responsePromise.reject(new DOMException("aborted", "AbortError"));
+ return;
+ }
+ responsePromise.resolve(response);
+ }
+ }));
+ responsePromises.push(responsePromise.promise);
+ }
+ const p = Promise.all(responsePromises);
+ const responses = await p;
+ const operations = [];
+ let index = 0;
+ for (const response of responses) {
+ const operation = {
+ type: "put",
+ // 7.3.2
+ request: requestList[index],
+ // 7.3.3
+ response
+ // 7.3.4
+ };
+ operations.push(operation);
+ index++;
+ }
+ const cacheJobPromise = createDeferredPromise();
+ let errorData = null;
+ try {
+ this.#batchCacheOperations(operations);
+ } catch (e) {
+ errorData = e;
+ }
+ queueMicrotask(() => {
+ if (errorData === null) {
+ cacheJobPromise.resolve(void 0);
+ } else {
+ cacheJobPromise.reject(errorData);
+ }
+ });
+ return cacheJobPromise.promise;
+ }
+ async put(request, response) {
+ webidl.brandCheck(this, _Cache);
+ const prefix = "Cache.put";
+ webidl.argumentLengthCheck(arguments, 2, prefix);
+ request = webidl.converters.RequestInfo(request);
+ response = webidl.converters.Response(response, prefix, "response");
+ let innerRequest = null;
+ if (webidl.is.Request(request)) {
+ innerRequest = getRequestState(request);
+ } else {
+ innerRequest = getRequestState(new Request(request));
+ }
+ if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== "GET") {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: "Expected an http/s scheme when method is not GET"
+ });
+ }
+ const innerResponse = getResponseState(response);
+ if (innerResponse.status === 206) {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: "Got 206 status"
+ });
+ }
+ if (innerResponse.headersList.contains("vary")) {
+ const fieldValues = getFieldValues(innerResponse.headersList.get("vary"));
+ for (const fieldValue of fieldValues) {
+ if (fieldValue === "*") {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: "Got * vary field value"
+ });
+ }
+ }
+ }
+ if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) {
+ throw webidl.errors.exception({
+ header: prefix,
+ message: "Response body is locked or disturbed"
+ });
+ }
+ const clonedResponse = cloneResponse(innerResponse);
+ const bodyReadPromise = createDeferredPromise();
+ if (innerResponse.body != null) {
+ const stream = innerResponse.body.stream;
+ const reader = stream.getReader();
+ readAllBytes(reader, bodyReadPromise.resolve, bodyReadPromise.reject);
+ } else {
+ bodyReadPromise.resolve(void 0);
+ }
+ const operations = [];
+ const operation = {
+ type: "put",
+ // 14.
+ request: innerRequest,
+ // 15.
+ response: clonedResponse
+ // 16.
+ };
+ operations.push(operation);
+ const bytes = await bodyReadPromise.promise;
+ if (clonedResponse.body != null) {
+ clonedResponse.body.source = bytes;
+ }
+ const cacheJobPromise = createDeferredPromise();
+ let errorData = null;
+ try {
+ this.#batchCacheOperations(operations);
+ } catch (e) {
+ errorData = e;
+ }
+ queueMicrotask(() => {
+ if (errorData === null) {
+ cacheJobPromise.resolve();
+ } else {
+ cacheJobPromise.reject(errorData);
+ }
+ });
+ return cacheJobPromise.promise;
+ }
+ async delete(request, options2 = {}) {
+ webidl.brandCheck(this, _Cache);
+ const prefix = "Cache.delete";
+ webidl.argumentLengthCheck(arguments, 1, prefix);
+ request = webidl.converters.RequestInfo(request);
+ options2 = webidl.converters.CacheQueryOptions(options2, prefix, "options");
+ let r = null;
+ if (webidl.is.Request(request)) {
+ r = getRequestState(request);
+ if (r.method !== "GET" && !options2.ignoreMethod) {
+ return false;
+ }
+ } else {
+ assert2(typeof request === "string");
+ r = getRequestState(new Request(request));
+ }
+ const operations = [];
+ const operation = {
+ type: "delete",
+ request: r,
+ options: options2
+ };
+ operations.push(operation);
+ const cacheJobPromise = createDeferredPromise();
+ let errorData = null;
+ let requestResponses;
+ try {
+ requestResponses = this.#batchCacheOperations(operations);
+ } catch (e) {
+ errorData = e;
+ }
+ queueMicrotask(() => {
+ if (errorData === null) {
+ cacheJobPromise.resolve(!!requestResponses?.length);
+ } else {
+ cacheJobPromise.reject(errorData);
+ }
+ });
+ return cacheJobPromise.promise;
+ }
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys
+ * @param {any} request
+ * @param {import('../../../types/cache').CacheQueryOptions} options
+ * @returns {Promise}
+ */
+ async keys(request = void 0, options2 = {}) {
+ webidl.brandCheck(this, _Cache);
+ const prefix = "Cache.keys";
+ if (request !== void 0) request = webidl.converters.RequestInfo(request);
+ options2 = webidl.converters.CacheQueryOptions(options2, prefix, "options");
+ let r = null;
+ if (request !== void 0) {
+ if (webidl.is.Request(request)) {
+ r = getRequestState(request);
+ if (r.method !== "GET" && !options2.ignoreMethod) {
+ return [];
+ }
+ } else if (typeof request === "string") {
+ r = getRequestState(new Request(request));
+ }
+ }
+ const promise2 = createDeferredPromise();
+ const requests = [];
+ if (request === void 0) {
+ for (const requestResponse of this.#relevantRequestResponseList) {
+ requests.push(requestResponse[0]);
+ }
+ } else {
+ const requestResponses = this.#queryCache(r, options2);
+ for (const requestResponse of requestResponses) {
+ requests.push(requestResponse[0]);
+ }
+ }
+ queueMicrotask(() => {
+ const requestList = [];
+ for (const request2 of requests) {
+ const requestObject = fromInnerRequest(
+ request2,
+ void 0,
+ new AbortController().signal,
+ "immutable"
+ );
+ requestList.push(requestObject);
+ }
+ promise2.resolve(Object.freeze(requestList));
+ });
+ return promise2.promise;
+ }
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm
+ * @param {CacheBatchOperation[]} operations
+ * @returns {requestResponseList}
+ */
+ #batchCacheOperations(operations) {
+ const cache3 = this.#relevantRequestResponseList;
+ const backupCache = [...cache3];
+ const addedItems = [];
+ const resultList = [];
+ try {
+ for (const operation of operations) {
+ if (operation.type !== "delete" && operation.type !== "put") {
+ throw webidl.errors.exception({
+ header: "Cache.#batchCacheOperations",
+ message: 'operation type does not match "delete" or "put"'
+ });
+ }
+ if (operation.type === "delete" && operation.response != null) {
+ throw webidl.errors.exception({
+ header: "Cache.#batchCacheOperations",
+ message: "delete operation should not have an associated response"
+ });
+ }
+ if (this.#queryCache(operation.request, operation.options, addedItems).length) {
+ throw new DOMException("???", "InvalidStateError");
+ }
+ let requestResponses;
+ if (operation.type === "delete") {
+ requestResponses = this.#queryCache(operation.request, operation.options);
+ if (requestResponses.length === 0) {
+ return [];
+ }
+ for (const requestResponse of requestResponses) {
+ const idx = cache3.indexOf(requestResponse);
+ assert2(idx !== -1);
+ cache3.splice(idx, 1);
+ }
+ } else if (operation.type === "put") {
+ if (operation.response == null) {
+ throw webidl.errors.exception({
+ header: "Cache.#batchCacheOperations",
+ message: "put operation should have an associated response"
+ });
+ }
+ const r = operation.request;
+ if (!urlIsHttpHttpsScheme(r.url)) {
+ throw webidl.errors.exception({
+ header: "Cache.#batchCacheOperations",
+ message: "expected http or https scheme"
+ });
+ }
+ if (r.method !== "GET") {
+ throw webidl.errors.exception({
+ header: "Cache.#batchCacheOperations",
+ message: "not get method"
+ });
+ }
+ if (operation.options != null) {
+ throw webidl.errors.exception({
+ header: "Cache.#batchCacheOperations",
+ message: "options must not be defined"
+ });
+ }
+ requestResponses = this.#queryCache(operation.request);
+ for (const requestResponse of requestResponses) {
+ const idx = cache3.indexOf(requestResponse);
+ assert2(idx !== -1);
+ cache3.splice(idx, 1);
+ }
+ cache3.push([operation.request, operation.response]);
+ addedItems.push([operation.request, operation.response]);
+ }
+ resultList.push([operation.request, operation.response]);
+ }
+ return resultList;
+ } catch (e) {
+ this.#relevantRequestResponseList.length = 0;
+ this.#relevantRequestResponseList = backupCache;
+ throw e;
+ }
+ }
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#query-cache
+ * @param {any} requestQuery
+ * @param {import('../../../types/cache').CacheQueryOptions} options
+ * @param {requestResponseList} targetStorage
+ * @returns {requestResponseList}
+ */
+ #queryCache(requestQuery, options2, targetStorage) {
+ const resultList = [];
+ const storage = targetStorage ?? this.#relevantRequestResponseList;
+ for (const requestResponse of storage) {
+ const [cachedRequest, cachedResponse] = requestResponse;
+ if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options2)) {
+ resultList.push(requestResponse);
+ }
+ }
+ return resultList;
+ }
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm
+ * @param {any} requestQuery
+ * @param {any} request
+ * @param {any | null} response
+ * @param {import('../../../types/cache').CacheQueryOptions | undefined} options
+ * @returns {boolean}
+ */
+ #requestMatchesCachedItem(requestQuery, request, response = null, options2) {
+ const queryURL = new URL(requestQuery.url);
+ const cachedURL = new URL(request.url);
+ if (options2?.ignoreSearch) {
+ cachedURL.search = "";
+ queryURL.search = "";
+ }
+ if (!urlEquals(queryURL, cachedURL, true)) {
+ return false;
+ }
+ if (response == null || options2?.ignoreVary || !response.headersList.contains("vary")) {
+ return true;
+ }
+ const fieldValues = getFieldValues(response.headersList.get("vary"));
+ for (const fieldValue of fieldValues) {
+ if (fieldValue === "*") {
+ return false;
+ }
+ const requestValue = request.headersList.get(fieldValue);
+ const queryValue = requestQuery.headersList.get(fieldValue);
+ if (requestValue !== queryValue) {
+ return false;
+ }
+ }
+ return true;
+ }
+ #internalMatchAll(request, options2, maxResponses = Infinity) {
+ let r = null;
+ if (request !== void 0) {
+ if (webidl.is.Request(request)) {
+ r = getRequestState(request);
+ if (r.method !== "GET" && !options2.ignoreMethod) {
+ return [];
+ }
+ } else if (typeof request === "string") {
+ r = getRequestState(new Request(request));
+ }
+ }
+ const responses = [];
+ if (request === void 0) {
+ for (const requestResponse of this.#relevantRequestResponseList) {
+ responses.push(requestResponse[1]);
+ }
+ } else {
+ const requestResponses = this.#queryCache(r, options2);
+ for (const requestResponse of requestResponses) {
+ responses.push(requestResponse[1]);
+ }
+ }
+ const responseList = [];
+ for (const response of responses) {
+ const responseObject = fromInnerResponse(cloneResponse(response), "immutable");
+ responseList.push(responseObject);
+ if (responseList.length >= maxResponses) {
+ break;
+ }
+ }
+ return Object.freeze(responseList);
+ }
+ };
+ Object.defineProperties(Cache.prototype, {
+ [Symbol.toStringTag]: {
+ value: "Cache",
+ configurable: true
+ },
+ match: kEnumerableProperty,
+ matchAll: kEnumerableProperty,
+ add: kEnumerableProperty,
+ addAll: kEnumerableProperty,
+ put: kEnumerableProperty,
+ delete: kEnumerableProperty,
+ keys: kEnumerableProperty
+ });
+ var cacheQueryOptionConverters = [
+ {
+ key: "ignoreSearch",
+ converter: webidl.converters.boolean,
+ defaultValue: /* @__PURE__ */ __name(() => false, "defaultValue")
+ },
+ {
+ key: "ignoreMethod",
+ converter: webidl.converters.boolean,
+ defaultValue: /* @__PURE__ */ __name(() => false, "defaultValue")
+ },
+ {
+ key: "ignoreVary",
+ converter: webidl.converters.boolean,
+ defaultValue: /* @__PURE__ */ __name(() => false, "defaultValue")
+ }
+ ];
+ webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters);
+ webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([
+ ...cacheQueryOptionConverters,
+ {
+ key: "cacheName",
+ converter: webidl.converters.DOMString
+ }
+ ]);
+ webidl.converters.Response = webidl.interfaceConverter(
+ webidl.is.Response,
+ "Response"
+ );
+ webidl.converters["sequence"] = webidl.sequenceConverter(
+ webidl.converters.RequestInfo
+ );
+ module2.exports = {
+ Cache
+ };
+ }
+});
+
+// node_modules/undici/lib/web/cache/cachestorage.js
+var require_cachestorage = __commonJS({
+ "node_modules/undici/lib/web/cache/cachestorage.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { Cache } = require_cache3();
+ var { webidl } = require_webidl();
+ var { kEnumerableProperty } = require_util();
+ var { kConstruct } = require_symbols();
+ var CacheStorage = class _CacheStorage {
+ static {
+ __name(this, "CacheStorage");
+ }
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map
+ * @type {Map}
+ */
+ async has(cacheName) {
+ webidl.brandCheck(this, _CacheStorage);
+ const prefix = "CacheStorage.has";
+ webidl.argumentLengthCheck(arguments, 1, prefix);
+ cacheName = webidl.converters.DOMString(cacheName, prefix, "cacheName");
+ return this.#caches.has(cacheName);
+ }
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open
+ * @param {string} cacheName
+ * @returns {Promise}
+ */
+ async open(cacheName) {
+ webidl.brandCheck(this, _CacheStorage);
+ const prefix = "CacheStorage.open";
+ webidl.argumentLengthCheck(arguments, 1, prefix);
+ cacheName = webidl.converters.DOMString(cacheName, prefix, "cacheName");
+ if (this.#caches.has(cacheName)) {
+ const cache4 = this.#caches.get(cacheName);
+ return new Cache(kConstruct, cache4);
+ }
+ const cache3 = [];
+ this.#caches.set(cacheName, cache3);
+ return new Cache(kConstruct, cache3);
+ }
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete
+ * @param {string} cacheName
+ * @returns {Promise}
+ */
+ async delete(cacheName) {
+ webidl.brandCheck(this, _CacheStorage);
+ const prefix = "CacheStorage.delete";
+ webidl.argumentLengthCheck(arguments, 1, prefix);
+ cacheName = webidl.converters.DOMString(cacheName, prefix, "cacheName");
+ return this.#caches.delete(cacheName);
+ }
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys
+ * @returns {Promise}
+ */
+ async keys() {
+ webidl.brandCheck(this, _CacheStorage);
+ const keys = this.#caches.keys();
+ return [...keys];
+ }
+ };
+ Object.defineProperties(CacheStorage.prototype, {
+ [Symbol.toStringTag]: {
+ value: "CacheStorage",
+ configurable: true
+ },
+ match: kEnumerableProperty,
+ has: kEnumerableProperty,
+ open: kEnumerableProperty,
+ delete: kEnumerableProperty,
+ keys: kEnumerableProperty
+ });
+ module2.exports = {
+ CacheStorage
+ };
+ }
+});
+
+// node_modules/undici/lib/web/cookies/constants.js
+var require_constants5 = __commonJS({
+ "node_modules/undici/lib/web/cookies/constants.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var maxAttributeValueSize = 1024;
+ var maxNameValuePairSize = 4096;
+ module2.exports = {
+ maxAttributeValueSize,
+ maxNameValuePairSize
+ };
+ }
+});
+
+// node_modules/undici/lib/web/cookies/util.js
+var require_util4 = __commonJS({
+ "node_modules/undici/lib/web/cookies/util.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ function isCTLExcludingHtab(value) {
+ for (let i = 0; i < value.length; ++i) {
+ const code = value.charCodeAt(i);
+ if (code >= 0 && code <= 8 || code >= 10 && code <= 31 || code === 127) {
+ return true;
+ }
+ }
+ return false;
+ }
+ __name(isCTLExcludingHtab, "isCTLExcludingHtab");
+ function validateCookieName(name) {
+ for (let i = 0; i < name.length; ++i) {
+ const code = name.charCodeAt(i);
+ if (code < 33 || // exclude CTLs (0-31), SP and HT
+ code > 126 || // exclude non-ascii and DEL
+ code === 34 || // "
+ code === 40 || // (
+ code === 41 || // )
+ code === 60 || // <
+ code === 62 || // >
+ code === 64 || // @
+ code === 44 || // ,
+ code === 59 || // ;
+ code === 58 || // :
+ code === 92 || // \
+ code === 47 || // /
+ code === 91 || // [
+ code === 93 || // ]
+ code === 63 || // ?
+ code === 61 || // =
+ code === 123 || // {
+ code === 125) {
+ throw new Error("Invalid cookie name");
+ }
+ }
+ }
+ __name(validateCookieName, "validateCookieName");
+ function validateCookieValue(value) {
+ let len = value.length;
+ let i = 0;
+ if (value[0] === '"') {
+ if (len === 1 || value[len - 1] !== '"') {
+ throw new Error("Invalid cookie value");
+ }
+ --len;
+ ++i;
+ }
+ while (i < len) {
+ const code = value.charCodeAt(i++);
+ if (code < 33 || // exclude CTLs (0-31)
+ code > 126 || // non-ascii and DEL (127)
+ code === 34 || // "
+ code === 44 || // ,
+ code === 59 || // ;
+ code === 92) {
+ throw new Error("Invalid cookie value");
+ }
+ }
+ }
+ __name(validateCookieValue, "validateCookieValue");
+ function validateCookiePath(path27) {
+ for (let i = 0; i < path27.length; ++i) {
+ const code = path27.charCodeAt(i);
+ if (code < 32 || // exclude CTLs (0-31)
+ code === 127 || // DEL
+ code === 59) {
+ throw new Error("Invalid cookie path");
+ }
+ }
+ }
+ __name(validateCookiePath, "validateCookiePath");
+ function validateCookieDomain(domain2) {
+ if (domain2.startsWith("-") || domain2.endsWith(".") || domain2.endsWith("-")) {
+ throw new Error("Invalid cookie domain");
+ }
+ }
+ __name(validateCookieDomain, "validateCookieDomain");
+ var IMFDays = [
+ "Sun",
+ "Mon",
+ "Tue",
+ "Wed",
+ "Thu",
+ "Fri",
+ "Sat"
+ ];
+ var IMFMonths = [
+ "Jan",
+ "Feb",
+ "Mar",
+ "Apr",
+ "May",
+ "Jun",
+ "Jul",
+ "Aug",
+ "Sep",
+ "Oct",
+ "Nov",
+ "Dec"
+ ];
+ var IMFPaddedNumbers = Array(61).fill(0).map((_, i) => i.toString().padStart(2, "0"));
+ function toIMFDate(date5) {
+ if (typeof date5 === "number") {
+ date5 = new Date(date5);
+ }
+ return `${IMFDays[date5.getUTCDay()]}, ${IMFPaddedNumbers[date5.getUTCDate()]} ${IMFMonths[date5.getUTCMonth()]} ${date5.getUTCFullYear()} ${IMFPaddedNumbers[date5.getUTCHours()]}:${IMFPaddedNumbers[date5.getUTCMinutes()]}:${IMFPaddedNumbers[date5.getUTCSeconds()]} GMT`;
+ }
+ __name(toIMFDate, "toIMFDate");
+ function validateCookieMaxAge(maxAge) {
+ if (maxAge < 0) {
+ throw new Error("Invalid cookie max-age");
+ }
+ }
+ __name(validateCookieMaxAge, "validateCookieMaxAge");
+ function stringify2(cookie) {
+ if (cookie.name.length === 0) {
+ return null;
+ }
+ validateCookieName(cookie.name);
+ validateCookieValue(cookie.value);
+ const out = [`${cookie.name}=${cookie.value}`];
+ if (cookie.name.startsWith("__Secure-")) {
+ cookie.secure = true;
+ }
+ if (cookie.name.startsWith("__Host-")) {
+ cookie.secure = true;
+ cookie.domain = null;
+ cookie.path = "/";
+ }
+ if (cookie.secure) {
+ out.push("Secure");
+ }
+ if (cookie.httpOnly) {
+ out.push("HttpOnly");
+ }
+ if (typeof cookie.maxAge === "number") {
+ validateCookieMaxAge(cookie.maxAge);
+ out.push(`Max-Age=${cookie.maxAge}`);
+ }
+ if (cookie.domain) {
+ validateCookieDomain(cookie.domain);
+ out.push(`Domain=${cookie.domain}`);
+ }
+ if (cookie.path) {
+ validateCookiePath(cookie.path);
+ out.push(`Path=${cookie.path}`);
+ }
+ if (cookie.expires && cookie.expires.toString() !== "Invalid Date") {
+ out.push(`Expires=${toIMFDate(cookie.expires)}`);
+ }
+ if (cookie.sameSite) {
+ out.push(`SameSite=${cookie.sameSite}`);
+ }
+ for (const part of cookie.unparsed) {
+ if (!part.includes("=")) {
+ throw new Error("Invalid unparsed");
+ }
+ const [key, ...value] = part.split("=");
+ out.push(`${key.trim()}=${value.join("=")}`);
+ }
+ return out.join("; ");
+ }
+ __name(stringify2, "stringify");
+ module2.exports = {
+ isCTLExcludingHtab,
+ validateCookieName,
+ validateCookiePath,
+ validateCookieValue,
+ toIMFDate,
+ stringify: stringify2
+ };
+ }
+});
+
+// node_modules/undici/lib/web/cookies/parse.js
+var require_parse2 = __commonJS({
+ "node_modules/undici/lib/web/cookies/parse.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { collectASequenceOfCodePointsFast } = require_infra();
+ var { maxNameValuePairSize, maxAttributeValueSize } = require_constants5();
+ var { isCTLExcludingHtab } = require_util4();
+ var assert2 = __require("node:assert");
+ function parseSetCookie(header) {
+ if (isCTLExcludingHtab(header)) {
+ return null;
+ }
+ let nameValuePair = "";
+ let unparsedAttributes = "";
+ let name = "";
+ let value = "";
+ if (header.includes(";")) {
+ const position = { position: 0 };
+ nameValuePair = collectASequenceOfCodePointsFast(";", header, position);
+ unparsedAttributes = header.slice(position.position);
+ } else {
+ nameValuePair = header;
+ }
+ if (!nameValuePair.includes("=")) {
+ value = nameValuePair;
+ } else {
+ const position = { position: 0 };
+ name = collectASequenceOfCodePointsFast(
+ "=",
+ nameValuePair,
+ position
+ );
+ value = nameValuePair.slice(position.position + 1);
+ }
+ name = name.trim();
+ value = value.trim();
+ if (name.length + value.length > maxNameValuePairSize) {
+ return null;
+ }
+ return {
+ name,
+ value,
+ ...parseUnparsedAttributes(unparsedAttributes)
+ };
+ }
+ __name(parseSetCookie, "parseSetCookie");
+ function parseUnparsedAttributes(unparsedAttributes, cookieAttributeList = {}) {
+ if (unparsedAttributes.length === 0) {
+ return cookieAttributeList;
+ }
+ assert2(unparsedAttributes[0] === ";");
+ unparsedAttributes = unparsedAttributes.slice(1);
+ let cookieAv = "";
+ if (unparsedAttributes.includes(";")) {
+ cookieAv = collectASequenceOfCodePointsFast(
+ ";",
+ unparsedAttributes,
+ { position: 0 }
+ );
+ unparsedAttributes = unparsedAttributes.slice(cookieAv.length);
+ } else {
+ cookieAv = unparsedAttributes;
+ unparsedAttributes = "";
+ }
+ let attributeName = "";
+ let attributeValue = "";
+ if (cookieAv.includes("=")) {
+ const position = { position: 0 };
+ attributeName = collectASequenceOfCodePointsFast(
+ "=",
+ cookieAv,
+ position
+ );
+ attributeValue = cookieAv.slice(position.position + 1);
+ } else {
+ attributeName = cookieAv;
+ }
+ attributeName = attributeName.trim();
+ attributeValue = attributeValue.trim();
+ if (attributeValue.length > maxAttributeValueSize) {
+ return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList);
+ }
+ const attributeNameLowercase = attributeName.toLowerCase();
+ if (attributeNameLowercase === "expires") {
+ const expiryTime = new Date(attributeValue);
+ cookieAttributeList.expires = expiryTime;
+ } else if (attributeNameLowercase === "max-age") {
+ const charCode = attributeValue.charCodeAt(0);
+ if ((charCode < 48 || charCode > 57) && attributeValue[0] !== "-") {
+ return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList);
+ }
+ if (!/^\d+$/.test(attributeValue)) {
+ return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList);
+ }
+ const deltaSeconds = Number(attributeValue);
+ cookieAttributeList.maxAge = deltaSeconds;
+ } else if (attributeNameLowercase === "domain") {
+ let cookieDomain = attributeValue;
+ if (cookieDomain[0] === ".") {
+ cookieDomain = cookieDomain.slice(1);
+ }
+ cookieDomain = cookieDomain.toLowerCase();
+ cookieAttributeList.domain = cookieDomain;
+ } else if (attributeNameLowercase === "path") {
+ let cookiePath = "";
+ if (attributeValue.length === 0 || attributeValue[0] !== "/") {
+ cookiePath = "/";
+ } else {
+ cookiePath = attributeValue;
+ }
+ cookieAttributeList.path = cookiePath;
+ } else if (attributeNameLowercase === "secure") {
+ cookieAttributeList.secure = true;
+ } else if (attributeNameLowercase === "httponly") {
+ cookieAttributeList.httpOnly = true;
+ } else if (attributeNameLowercase === "samesite") {
+ const attributeValueLowercase = attributeValue.toLowerCase();
+ if (attributeValueLowercase === "none") {
+ cookieAttributeList.sameSite = "None";
+ } else if (attributeValueLowercase === "strict") {
+ cookieAttributeList.sameSite = "Strict";
+ } else if (attributeValueLowercase === "lax") {
+ cookieAttributeList.sameSite = "Lax";
+ }
+ } else {
+ cookieAttributeList.unparsed ??= [];
+ cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`);
+ }
+ return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList);
+ }
+ __name(parseUnparsedAttributes, "parseUnparsedAttributes");
+ module2.exports = {
+ parseSetCookie,
+ parseUnparsedAttributes
+ };
+ }
+});
+
+// node_modules/undici/lib/web/cookies/index.js
+var require_cookies = __commonJS({
+ "node_modules/undici/lib/web/cookies/index.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { parseSetCookie } = require_parse2();
+ var { stringify: stringify2 } = require_util4();
+ var { webidl } = require_webidl();
+ var { Headers: Headers2 } = require_headers();
+ var brandChecks = webidl.brandCheckMultiple([Headers2, globalThis.Headers].filter(Boolean));
+ function getCookies(headers) {
+ webidl.argumentLengthCheck(arguments, 1, "getCookies");
+ brandChecks(headers);
+ const cookie = headers.get("cookie");
+ const out = {};
+ if (!cookie) {
+ return out;
+ }
+ for (const piece of cookie.split(";")) {
+ const [name, ...value] = piece.split("=");
+ out[name.trim()] = value.join("=");
+ }
+ return out;
+ }
+ __name(getCookies, "getCookies");
+ function deleteCookie(headers, name, attributes) {
+ brandChecks(headers);
+ const prefix = "deleteCookie";
+ webidl.argumentLengthCheck(arguments, 2, prefix);
+ name = webidl.converters.DOMString(name, prefix, "name");
+ attributes = webidl.converters.DeleteCookieAttributes(attributes);
+ setCookie(headers, {
+ name,
+ value: "",
+ expires: /* @__PURE__ */ new Date(0),
+ ...attributes
+ });
+ }
+ __name(deleteCookie, "deleteCookie");
+ function getSetCookies(headers) {
+ webidl.argumentLengthCheck(arguments, 1, "getSetCookies");
+ brandChecks(headers);
+ const cookies = headers.getSetCookie();
+ if (!cookies) {
+ return [];
+ }
+ return cookies.map((pair) => parseSetCookie(pair));
+ }
+ __name(getSetCookies, "getSetCookies");
+ function parseCookie(cookie) {
+ cookie = webidl.converters.DOMString(cookie);
+ return parseSetCookie(cookie);
+ }
+ __name(parseCookie, "parseCookie");
+ function setCookie(headers, cookie) {
+ webidl.argumentLengthCheck(arguments, 2, "setCookie");
+ brandChecks(headers);
+ cookie = webidl.converters.Cookie(cookie);
+ const str3 = stringify2(cookie);
+ if (str3) {
+ headers.append("set-cookie", str3, true);
+ }
+ }
+ __name(setCookie, "setCookie");
+ webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([
+ {
+ converter: webidl.nullableConverter(webidl.converters.DOMString),
+ key: "path",
+ defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
+ },
+ {
+ converter: webidl.nullableConverter(webidl.converters.DOMString),
+ key: "domain",
+ defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
+ }
+ ]);
+ webidl.converters.Cookie = webidl.dictionaryConverter([
+ {
+ converter: webidl.converters.DOMString,
+ key: "name"
+ },
+ {
+ converter: webidl.converters.DOMString,
+ key: "value"
+ },
+ {
+ converter: webidl.nullableConverter((value) => {
+ if (typeof value === "number") {
+ return webidl.converters["unsigned long long"](value);
+ }
+ return new Date(value);
+ }),
+ key: "expires",
+ defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
+ },
+ {
+ converter: webidl.nullableConverter(webidl.converters["long long"]),
+ key: "maxAge",
+ defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
+ },
+ {
+ converter: webidl.nullableConverter(webidl.converters.DOMString),
+ key: "domain",
+ defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
+ },
+ {
+ converter: webidl.nullableConverter(webidl.converters.DOMString),
+ key: "path",
+ defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
+ },
+ {
+ converter: webidl.nullableConverter(webidl.converters.boolean),
+ key: "secure",
+ defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
+ },
+ {
+ converter: webidl.nullableConverter(webidl.converters.boolean),
+ key: "httpOnly",
+ defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
+ },
+ {
+ converter: webidl.converters.USVString,
+ key: "sameSite",
+ allowedValues: ["Strict", "Lax", "None"]
+ },
+ {
+ converter: webidl.sequenceConverter(webidl.converters.DOMString),
+ key: "unparsed",
+ defaultValue: /* @__PURE__ */ __name(() => [], "defaultValue")
+ }
+ ]);
+ module2.exports = {
+ getCookies,
+ deleteCookie,
+ getSetCookies,
+ setCookie,
+ parseCookie
+ };
+ }
+});
+
+// node_modules/undici/lib/web/websocket/events.js
+var require_events = __commonJS({
+ "node_modules/undici/lib/web/websocket/events.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { webidl } = require_webidl();
+ var { kEnumerableProperty } = require_util();
+ var { kConstruct } = require_symbols();
+ var MessageEvent = class _MessageEvent extends Event {
+ static {
+ __name(this, "MessageEvent");
+ }
+ #eventInit;
+ constructor(type2, eventInitDict = {}) {
+ if (type2 === kConstruct) {
+ super(arguments[1], arguments[2]);
+ webidl.util.markAsUncloneable(this);
+ return;
+ }
+ const prefix = "MessageEvent constructor";
+ webidl.argumentLengthCheck(arguments, 1, prefix);
+ type2 = webidl.converters.DOMString(type2, prefix, "type");
+ eventInitDict = webidl.converters.MessageEventInit(eventInitDict, prefix, "eventInitDict");
+ super(type2, eventInitDict);
+ this.#eventInit = eventInitDict;
+ webidl.util.markAsUncloneable(this);
+ }
+ get data() {
+ webidl.brandCheck(this, _MessageEvent);
+ return this.#eventInit.data;
+ }
+ get origin() {
+ webidl.brandCheck(this, _MessageEvent);
+ return this.#eventInit.origin;
+ }
+ get lastEventId() {
+ webidl.brandCheck(this, _MessageEvent);
+ return this.#eventInit.lastEventId;
+ }
+ get source() {
+ webidl.brandCheck(this, _MessageEvent);
+ return this.#eventInit.source;
+ }
+ get ports() {
+ webidl.brandCheck(this, _MessageEvent);
+ if (!Object.isFrozen(this.#eventInit.ports)) {
+ Object.freeze(this.#eventInit.ports);
+ }
+ return this.#eventInit.ports;
+ }
+ initMessageEvent(type2, bubbles = false, cancelable = false, data = null, origin = "", lastEventId = "", source = null, ports = []) {
+ webidl.brandCheck(this, _MessageEvent);
+ webidl.argumentLengthCheck(arguments, 1, "MessageEvent.initMessageEvent");
+ return new _MessageEvent(type2, {
+ bubbles,
+ cancelable,
+ data,
+ origin,
+ lastEventId,
+ source,
+ ports
+ });
+ }
+ static createFastMessageEvent(type2, init) {
+ const messageEvent = new _MessageEvent(kConstruct, type2, init);
+ messageEvent.#eventInit = init;
+ messageEvent.#eventInit.data ??= null;
+ messageEvent.#eventInit.origin ??= "";
+ messageEvent.#eventInit.lastEventId ??= "";
+ messageEvent.#eventInit.source ??= null;
+ messageEvent.#eventInit.ports ??= [];
+ return messageEvent;
+ }
+ };
+ var { createFastMessageEvent } = MessageEvent;
+ delete MessageEvent.createFastMessageEvent;
+ var CloseEvent = class _CloseEvent extends Event {
+ static {
+ __name(this, "CloseEvent");
+ }
+ #eventInit;
+ constructor(type2, eventInitDict = {}) {
+ const prefix = "CloseEvent constructor";
+ webidl.argumentLengthCheck(arguments, 1, prefix);
+ type2 = webidl.converters.DOMString(type2, prefix, "type");
+ eventInitDict = webidl.converters.CloseEventInit(eventInitDict);
+ super(type2, eventInitDict);
+ this.#eventInit = eventInitDict;
+ webidl.util.markAsUncloneable(this);
+ }
+ get wasClean() {
+ webidl.brandCheck(this, _CloseEvent);
+ return this.#eventInit.wasClean;
+ }
+ get code() {
+ webidl.brandCheck(this, _CloseEvent);
+ return this.#eventInit.code;
+ }
+ get reason() {
+ webidl.brandCheck(this, _CloseEvent);
+ return this.#eventInit.reason;
+ }
+ };
+ var ErrorEvent = class _ErrorEvent extends Event {
+ static {
+ __name(this, "ErrorEvent");
+ }
+ #eventInit;
+ constructor(type2, eventInitDict) {
+ const prefix = "ErrorEvent constructor";
+ webidl.argumentLengthCheck(arguments, 1, prefix);
+ super(type2, eventInitDict);
+ webidl.util.markAsUncloneable(this);
+ type2 = webidl.converters.DOMString(type2, prefix, "type");
+ eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {});
+ this.#eventInit = eventInitDict;
+ }
+ get message() {
+ webidl.brandCheck(this, _ErrorEvent);
+ return this.#eventInit.message;
+ }
+ get filename() {
+ webidl.brandCheck(this, _ErrorEvent);
+ return this.#eventInit.filename;
+ }
+ get lineno() {
+ webidl.brandCheck(this, _ErrorEvent);
+ return this.#eventInit.lineno;
+ }
+ get colno() {
+ webidl.brandCheck(this, _ErrorEvent);
+ return this.#eventInit.colno;
+ }
+ get error() {
+ webidl.brandCheck(this, _ErrorEvent);
+ return this.#eventInit.error;
+ }
+ };
+ Object.defineProperties(MessageEvent.prototype, {
+ [Symbol.toStringTag]: {
+ value: "MessageEvent",
+ configurable: true
+ },
+ data: kEnumerableProperty,
+ origin: kEnumerableProperty,
+ lastEventId: kEnumerableProperty,
+ source: kEnumerableProperty,
+ ports: kEnumerableProperty,
+ initMessageEvent: kEnumerableProperty
+ });
+ Object.defineProperties(CloseEvent.prototype, {
+ [Symbol.toStringTag]: {
+ value: "CloseEvent",
+ configurable: true
+ },
+ reason: kEnumerableProperty,
+ code: kEnumerableProperty,
+ wasClean: kEnumerableProperty
+ });
+ Object.defineProperties(ErrorEvent.prototype, {
+ [Symbol.toStringTag]: {
+ value: "ErrorEvent",
+ configurable: true
+ },
+ message: kEnumerableProperty,
+ filename: kEnumerableProperty,
+ lineno: kEnumerableProperty,
+ colno: kEnumerableProperty,
+ error: kEnumerableProperty
+ });
+ webidl.converters.MessagePort = webidl.interfaceConverter(
+ webidl.is.MessagePort,
+ "MessagePort"
+ );
+ webidl.converters["sequence"] = webidl.sequenceConverter(
+ webidl.converters.MessagePort
+ );
+ var eventInit = [
+ {
+ key: "bubbles",
+ converter: webidl.converters.boolean,
+ defaultValue: /* @__PURE__ */ __name(() => false, "defaultValue")
+ },
+ {
+ key: "cancelable",
+ converter: webidl.converters.boolean,
+ defaultValue: /* @__PURE__ */ __name(() => false, "defaultValue")
+ },
+ {
+ key: "composed",
+ converter: webidl.converters.boolean,
+ defaultValue: /* @__PURE__ */ __name(() => false, "defaultValue")
+ }
+ ];
+ webidl.converters.MessageEventInit = webidl.dictionaryConverter([
+ ...eventInit,
+ {
+ key: "data",
+ converter: webidl.converters.any,
+ defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
+ },
+ {
+ key: "origin",
+ converter: webidl.converters.USVString,
+ defaultValue: /* @__PURE__ */ __name(() => "", "defaultValue")
+ },
+ {
+ key: "lastEventId",
+ converter: webidl.converters.DOMString,
+ defaultValue: /* @__PURE__ */ __name(() => "", "defaultValue")
+ },
+ {
+ key: "source",
+ // Node doesn't implement WindowProxy or ServiceWorker, so the only
+ // valid value for source is a MessagePort.
+ converter: webidl.nullableConverter(webidl.converters.MessagePort),
+ defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
+ },
+ {
+ key: "ports",
+ converter: webidl.converters["sequence"],
+ defaultValue: /* @__PURE__ */ __name(() => [], "defaultValue")
+ }
+ ]);
+ webidl.converters.CloseEventInit = webidl.dictionaryConverter([
+ ...eventInit,
+ {
+ key: "wasClean",
+ converter: webidl.converters.boolean,
+ defaultValue: /* @__PURE__ */ __name(() => false, "defaultValue")
+ },
+ {
+ key: "code",
+ converter: webidl.converters["unsigned short"],
+ defaultValue: /* @__PURE__ */ __name(() => 0, "defaultValue")
+ },
+ {
+ key: "reason",
+ converter: webidl.converters.USVString,
+ defaultValue: /* @__PURE__ */ __name(() => "", "defaultValue")
+ }
+ ]);
+ webidl.converters.ErrorEventInit = webidl.dictionaryConverter([
+ ...eventInit,
+ {
+ key: "message",
+ converter: webidl.converters.DOMString,
+ defaultValue: /* @__PURE__ */ __name(() => "", "defaultValue")
+ },
+ {
+ key: "filename",
+ converter: webidl.converters.USVString,
+ defaultValue: /* @__PURE__ */ __name(() => "", "defaultValue")
+ },
+ {
+ key: "lineno",
+ converter: webidl.converters["unsigned long"],
+ defaultValue: /* @__PURE__ */ __name(() => 0, "defaultValue")
+ },
+ {
+ key: "colno",
+ converter: webidl.converters["unsigned long"],
+ defaultValue: /* @__PURE__ */ __name(() => 0, "defaultValue")
+ },
+ {
+ key: "error",
+ converter: webidl.converters.any
+ }
+ ]);
+ module2.exports = {
+ MessageEvent,
+ CloseEvent,
+ ErrorEvent,
+ createFastMessageEvent
+ };
+ }
+});
+
+// node_modules/undici/lib/web/websocket/constants.js
+var require_constants6 = __commonJS({
+ "node_modules/undici/lib/web/websocket/constants.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var uid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
+ var staticPropertyDescriptors = {
+ enumerable: true,
+ writable: false,
+ configurable: false
+ };
+ var states = {
+ CONNECTING: 0,
+ OPEN: 1,
+ CLOSING: 2,
+ CLOSED: 3
+ };
+ var sentCloseFrameState = {
+ SENT: 1,
+ RECEIVED: 2
+ };
+ var opcodes = {
+ CONTINUATION: 0,
+ TEXT: 1,
+ BINARY: 2,
+ CLOSE: 8,
+ PING: 9,
+ PONG: 10
+ };
+ var maxUnsigned16Bit = 65535;
+ var parserStates = {
+ INFO: 0,
+ PAYLOADLENGTH_16: 2,
+ PAYLOADLENGTH_64: 3,
+ READ_DATA: 4
+ };
+ var emptyBuffer = Buffer.allocUnsafe(0);
+ var sendHints = {
+ text: 1,
+ typedArray: 2,
+ arrayBuffer: 3,
+ blob: 4
+ };
+ module2.exports = {
+ uid,
+ sentCloseFrameState,
+ staticPropertyDescriptors,
+ states,
+ opcodes,
+ maxUnsigned16Bit,
+ parserStates,
+ emptyBuffer,
+ sendHints
+ };
+ }
+});
+
+// node_modules/undici/lib/web/websocket/util.js
+var require_util5 = __commonJS({
+ "node_modules/undici/lib/web/websocket/util.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { states, opcodes } = require_constants6();
+ var { isUtf8 } = __require("node:buffer");
+ var { removeHTTPWhitespace } = require_data_url();
+ var { collectASequenceOfCodePointsFast } = require_infra();
+ function isConnecting(readyState) {
+ return readyState === states.CONNECTING;
+ }
+ __name(isConnecting, "isConnecting");
+ function isEstablished(readyState) {
+ return readyState === states.OPEN;
+ }
+ __name(isEstablished, "isEstablished");
+ function isClosing(readyState) {
+ return readyState === states.CLOSING;
+ }
+ __name(isClosing, "isClosing");
+ function isClosed(readyState) {
+ return readyState === states.CLOSED;
+ }
+ __name(isClosed, "isClosed");
+ function fireEvent(e, target, eventFactory = (type2, init) => new Event(type2, init), eventInitDict = {}) {
+ const event = eventFactory(e, eventInitDict);
+ target.dispatchEvent(event);
+ }
+ __name(fireEvent, "fireEvent");
+ function websocketMessageReceived(handler, type2, data) {
+ handler.onMessage(type2, data);
+ }
+ __name(websocketMessageReceived, "websocketMessageReceived");
+ function toArrayBuffer(buffer) {
+ if (buffer.byteLength === buffer.buffer.byteLength) {
+ return buffer.buffer;
+ }
+ return new Uint8Array(buffer).buffer;
+ }
+ __name(toArrayBuffer, "toArrayBuffer");
+ function isValidSubprotocol(protocol) {
+ if (protocol.length === 0) {
+ return false;
+ }
+ for (let i = 0; i < protocol.length; ++i) {
+ const code = protocol.charCodeAt(i);
+ if (code < 33 || // CTL, contains SP (0x20) and HT (0x09)
+ code > 126 || code === 34 || // "
+ code === 40 || // (
+ code === 41 || // )
+ code === 44 || // ,
+ code === 47 || // /
+ code === 58 || // :
+ code === 59 || // ;
+ code === 60 || // <
+ code === 61 || // =
+ code === 62 || // >
+ code === 63 || // ?
+ code === 64 || // @
+ code === 91 || // [
+ code === 92 || // \
+ code === 93 || // ]
+ code === 123 || // {
+ code === 125) {
+ return false;
+ }
+ }
+ return true;
+ }
+ __name(isValidSubprotocol, "isValidSubprotocol");
+ function isValidStatusCode(code) {
+ if (code >= 1e3 && code < 1015) {
+ return code !== 1004 && // reserved
+ code !== 1005 && // "MUST NOT be set as a status code"
+ code !== 1006;
+ }
+ return code >= 3e3 && code <= 4999;
+ }
+ __name(isValidStatusCode, "isValidStatusCode");
+ function isControlFrame(opcode) {
+ return opcode === opcodes.CLOSE || opcode === opcodes.PING || opcode === opcodes.PONG;
+ }
+ __name(isControlFrame, "isControlFrame");
+ function isContinuationFrame(opcode) {
+ return opcode === opcodes.CONTINUATION;
+ }
+ __name(isContinuationFrame, "isContinuationFrame");
+ function isTextBinaryFrame(opcode) {
+ return opcode === opcodes.TEXT || opcode === opcodes.BINARY;
+ }
+ __name(isTextBinaryFrame, "isTextBinaryFrame");
+ function isValidOpcode(opcode) {
+ return isTextBinaryFrame(opcode) || isContinuationFrame(opcode) || isControlFrame(opcode);
+ }
+ __name(isValidOpcode, "isValidOpcode");
+ function parseExtensions(extensions) {
+ const position = { position: 0 };
+ const extensionList = /* @__PURE__ */ new Map();
+ while (position.position < extensions.length) {
+ const pair = collectASequenceOfCodePointsFast(";", extensions, position);
+ const [name, value = ""] = pair.split("=", 2);
+ extensionList.set(
+ removeHTTPWhitespace(name, true, false),
+ removeHTTPWhitespace(value, false, true)
+ );
+ position.position++;
+ }
+ return extensionList;
+ }
+ __name(parseExtensions, "parseExtensions");
+ function isValidClientWindowBits(value) {
+ if (value.length === 0) {
+ return false;
+ }
+ for (let i = 0; i < value.length; i++) {
+ const byte = value.charCodeAt(i);
+ if (byte < 48 || byte > 57) {
+ return false;
+ }
+ }
+ const num = Number.parseInt(value, 10);
+ return num >= 8 && num <= 15;
+ }
+ __name(isValidClientWindowBits, "isValidClientWindowBits");
+ function getURLRecord(url2, baseURL) {
+ let urlRecord;
+ try {
+ urlRecord = new URL(url2, baseURL);
+ } catch (e) {
+ throw new DOMException(e, "SyntaxError");
+ }
+ if (urlRecord.protocol === "http:") {
+ urlRecord.protocol = "ws:";
+ } else if (urlRecord.protocol === "https:") {
+ urlRecord.protocol = "wss:";
+ }
+ if (urlRecord.protocol !== "ws:" && urlRecord.protocol !== "wss:") {
+ throw new DOMException("expected a ws: or wss: url", "SyntaxError");
+ }
+ if (urlRecord.hash.length || urlRecord.href.endsWith("#")) {
+ throw new DOMException("hash", "SyntaxError");
+ }
+ return urlRecord;
+ }
+ __name(getURLRecord, "getURLRecord");
+ function validateCloseCodeAndReason(code, reason) {
+ if (code !== null) {
+ if (code !== 1e3 && (code < 3e3 || code > 4999)) {
+ throw new DOMException("invalid code", "InvalidAccessError");
+ }
+ }
+ if (reason !== null) {
+ const reasonBytesLength = Buffer.byteLength(reason);
+ if (reasonBytesLength > 123) {
+ throw new DOMException(`Reason must be less than 123 bytes; received ${reasonBytesLength}`, "SyntaxError");
+ }
+ }
+ }
+ __name(validateCloseCodeAndReason, "validateCloseCodeAndReason");
+ var utf8Decode = (() => {
+ if (typeof process.versions.icu === "string") {
+ const fatalDecoder = new TextDecoder("utf-8", { fatal: true });
+ return fatalDecoder.decode.bind(fatalDecoder);
+ }
+ return function(buffer) {
+ if (isUtf8(buffer)) {
+ return buffer.toString("utf-8");
+ }
+ throw new TypeError("Invalid utf-8 received.");
+ };
+ })();
+ module2.exports = {
+ isConnecting,
+ isEstablished,
+ isClosing,
+ isClosed,
+ fireEvent,
+ isValidSubprotocol,
+ isValidStatusCode,
+ websocketMessageReceived,
+ utf8Decode,
+ isControlFrame,
+ isContinuationFrame,
+ isTextBinaryFrame,
+ isValidOpcode,
+ parseExtensions,
+ isValidClientWindowBits,
+ toArrayBuffer,
+ getURLRecord,
+ validateCloseCodeAndReason
+ };
+ }
+});
+
+// node_modules/undici/lib/web/websocket/frame.js
+var require_frame = __commonJS({
+ "node_modules/undici/lib/web/websocket/frame.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { runtimeFeatures } = require_runtime_features();
+ var { maxUnsigned16Bit, opcodes } = require_constants6();
+ var BUFFER_SIZE = 8 * 1024;
+ var buffer = null;
+ var bufIdx = BUFFER_SIZE;
+ var randomFillSync = runtimeFeatures.has("crypto") ? __require("node:crypto").randomFillSync : /* @__PURE__ */ __name(function randomFillSync2(buffer2, _offset, _size2) {
+ for (let i = 0; i < buffer2.length; ++i) {
+ buffer2[i] = Math.random() * 255 | 0;
+ }
+ return buffer2;
+ }, "randomFillSync");
+ function generateMask() {
+ if (bufIdx === BUFFER_SIZE) {
+ bufIdx = 0;
+ randomFillSync(buffer ??= Buffer.allocUnsafeSlow(BUFFER_SIZE), 0, BUFFER_SIZE);
+ }
+ return [buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++]];
+ }
+ __name(generateMask, "generateMask");
+ var WebsocketFrameSend = class {
+ static {
+ __name(this, "WebsocketFrameSend");
+ }
+ /**
+ * @param {Buffer|undefined} data
+ */
+ constructor(data) {
+ this.frameData = data;
+ }
+ createFrame(opcode) {
+ const frameData = this.frameData;
+ const maskKey = generateMask();
+ const bodyLength = frameData?.byteLength ?? 0;
+ let payloadLength = bodyLength;
+ let offset = 6;
+ if (bodyLength > maxUnsigned16Bit) {
+ offset += 8;
+ payloadLength = 127;
+ } else if (bodyLength > 125) {
+ offset += 2;
+ payloadLength = 126;
+ }
+ const buffer2 = Buffer.allocUnsafe(bodyLength + offset);
+ buffer2[0] = buffer2[1] = 0;
+ buffer2[0] |= 128;
+ buffer2[0] = (buffer2[0] & 240) + opcode;
+ buffer2[offset - 4] = maskKey[0];
+ buffer2[offset - 3] = maskKey[1];
+ buffer2[offset - 2] = maskKey[2];
+ buffer2[offset - 1] = maskKey[3];
+ buffer2[1] = payloadLength;
+ if (payloadLength === 126) {
+ buffer2.writeUInt16BE(bodyLength, 2);
+ } else if (payloadLength === 127) {
+ buffer2[2] = buffer2[3] = 0;
+ buffer2.writeUIntBE(bodyLength, 4, 6);
+ }
+ buffer2[1] |= 128;
+ for (let i = 0; i < bodyLength; ++i) {
+ buffer2[offset + i] = frameData[i] ^ maskKey[i & 3];
+ }
+ return buffer2;
+ }
+ /**
+ * @param {Uint8Array} buffer
+ */
+ static createFastTextFrame(buffer2) {
+ const maskKey = generateMask();
+ const bodyLength = buffer2.length;
+ for (let i = 0; i < bodyLength; ++i) {
+ buffer2[i] ^= maskKey[i & 3];
+ }
+ let payloadLength = bodyLength;
+ let offset = 6;
+ if (bodyLength > maxUnsigned16Bit) {
+ offset += 8;
+ payloadLength = 127;
+ } else if (bodyLength > 125) {
+ offset += 2;
+ payloadLength = 126;
+ }
+ const head = Buffer.allocUnsafeSlow(offset);
+ head[0] = 128 | opcodes.TEXT;
+ head[1] = payloadLength | 128;
+ head[offset - 4] = maskKey[0];
+ head[offset - 3] = maskKey[1];
+ head[offset - 2] = maskKey[2];
+ head[offset - 1] = maskKey[3];
+ if (payloadLength === 126) {
+ head.writeUInt16BE(bodyLength, 2);
+ } else if (payloadLength === 127) {
+ head[2] = head[3] = 0;
+ head.writeUIntBE(bodyLength, 4, 6);
+ }
+ return [head, buffer2];
+ }
+ };
+ module2.exports = {
+ WebsocketFrameSend,
+ generateMask
+ // for benchmark
+ };
+ }
+});
+
+// node_modules/undici/lib/web/websocket/connection.js
+var require_connection = __commonJS({
+ "node_modules/undici/lib/web/websocket/connection.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { uid, states, sentCloseFrameState, emptyBuffer, opcodes } = require_constants6();
+ var { parseExtensions, isClosed, isClosing, isEstablished, isConnecting, validateCloseCodeAndReason } = require_util5();
+ var { makeRequest } = require_request2();
+ var { fetching } = require_fetch();
+ var { Headers: Headers2, getHeadersList } = require_headers();
+ var { getDecodeSplit } = require_util2();
+ var { WebsocketFrameSend } = require_frame();
+ var assert2 = __require("node:assert");
+ var { runtimeFeatures } = require_runtime_features();
+ var crypto4 = runtimeFeatures.has("crypto") ? __require("node:crypto") : null;
+ var warningEmitted = false;
+ function establishWebSocketConnection(url2, protocols, client, handler, options2) {
+ const requestURL = url2;
+ requestURL.protocol = url2.protocol === "ws:" ? "http:" : "https:";
+ const request = makeRequest({
+ urlList: [requestURL],
+ client,
+ serviceWorkers: "none",
+ referrer: "no-referrer",
+ mode: "websocket",
+ credentials: "include",
+ cache: "no-store",
+ redirect: "error",
+ useURLCredentials: true
+ });
+ if (options2.headers) {
+ const headersList = getHeadersList(new Headers2(options2.headers));
+ request.headersList = headersList;
+ }
+ const keyValue = crypto4.randomBytes(16).toString("base64");
+ request.headersList.append("sec-websocket-key", keyValue, true);
+ request.headersList.append("sec-websocket-version", "13", true);
+ for (const protocol of protocols) {
+ request.headersList.append("sec-websocket-protocol", protocol, true);
+ }
+ const permessageDeflate = "permessage-deflate; client_max_window_bits";
+ request.headersList.append("sec-websocket-extensions", permessageDeflate, true);
+ const controller = fetching({
+ request,
+ useParallelQueue: true,
+ dispatcher: options2.dispatcher,
+ processResponse(response) {
+ if (response.type === "error" || response.status !== 101) {
+ if (response.socket?.session == null) {
+ failWebsocketConnection(handler, 1002, "Received network error or non-101 status code.", response.error);
+ return;
+ }
+ if (response.status !== 200) {
+ failWebsocketConnection(handler, 1002, "Received network error or non-200 status code.", response.error);
+ return;
+ }
+ }
+ if (warningEmitted === false && response.socket?.session != null) {
+ process.emitWarning("WebSocket over HTTP2 is experimental, and subject to change.", "ExperimentalWarning");
+ warningEmitted = true;
+ }
+ if (protocols.length !== 0 && !response.headersList.get("Sec-WebSocket-Protocol")) {
+ failWebsocketConnection(handler, 1002, "Server did not respond with sent protocols.");
+ return;
+ }
+ if (response.socket.session == null && response.headersList.get("Upgrade")?.toLowerCase() !== "websocket") {
+ failWebsocketConnection(handler, 1002, 'Server did not set Upgrade header to "websocket".');
+ return;
+ }
+ if (response.socket.session == null && response.headersList.get("Connection")?.toLowerCase() !== "upgrade") {
+ failWebsocketConnection(handler, 1002, 'Server did not set Connection header to "upgrade".');
+ return;
+ }
+ const secWSAccept = response.headersList.get("Sec-WebSocket-Accept");
+ const digest = crypto4.hash("sha1", keyValue + uid, "base64");
+ if (secWSAccept !== digest) {
+ failWebsocketConnection(handler, 1002, "Incorrect hash received in Sec-WebSocket-Accept header.");
+ return;
+ }
+ const secExtension = response.headersList.get("Sec-WebSocket-Extensions");
+ let extensions;
+ if (secExtension !== null) {
+ extensions = parseExtensions(secExtension);
+ if (!extensions.has("permessage-deflate")) {
+ failWebsocketConnection(handler, 1002, "Sec-WebSocket-Extensions header does not match.");
+ return;
+ }
+ }
+ const secProtocol = response.headersList.get("Sec-WebSocket-Protocol");
+ if (secProtocol !== null) {
+ const requestProtocols = getDecodeSplit("sec-websocket-protocol", request.headersList);
+ if (!requestProtocols.includes(secProtocol)) {
+ failWebsocketConnection(handler, 1002, "Protocol was not set in the opening handshake.");
+ return;
+ }
+ }
+ response.socket.on("data", handler.onSocketData);
+ response.socket.on("close", handler.onSocketClose);
+ response.socket.on("error", handler.onSocketError);
+ handler.wasEverConnected = true;
+ handler.onConnectionEstablished(response, extensions);
+ }
+ });
+ return controller;
+ }
+ __name(establishWebSocketConnection, "establishWebSocketConnection");
+ function closeWebSocketConnection(object2, code, reason, validate2 = false) {
+ code ??= null;
+ reason ??= "";
+ if (validate2) validateCloseCodeAndReason(code, reason);
+ if (isClosed(object2.readyState) || isClosing(object2.readyState)) {
+ } else if (!isEstablished(object2.readyState)) {
+ failWebsocketConnection(object2);
+ object2.readyState = states.CLOSING;
+ } else if (!object2.closeState.has(sentCloseFrameState.SENT) && !object2.closeState.has(sentCloseFrameState.RECEIVED)) {
+ const frame = new WebsocketFrameSend();
+ if (reason.length !== 0 && code === null) {
+ code = 1e3;
+ }
+ assert2(code === null || Number.isInteger(code));
+ if (code === null && reason.length === 0) {
+ frame.frameData = emptyBuffer;
+ } else if (code !== null && reason === null) {
+ frame.frameData = Buffer.allocUnsafe(2);
+ frame.frameData.writeUInt16BE(code, 0);
+ } else if (code !== null && reason !== null) {
+ frame.frameData = Buffer.allocUnsafe(2 + Buffer.byteLength(reason));
+ frame.frameData.writeUInt16BE(code, 0);
+ frame.frameData.write(reason, 2, "utf-8");
+ } else {
+ frame.frameData = emptyBuffer;
+ }
+ object2.socket.write(frame.createFrame(opcodes.CLOSE));
+ object2.closeState.add(sentCloseFrameState.SENT);
+ object2.readyState = states.CLOSING;
+ } else {
+ object2.readyState = states.CLOSING;
+ }
+ }
+ __name(closeWebSocketConnection, "closeWebSocketConnection");
+ function failWebsocketConnection(handler, code, reason, cause) {
+ if (isEstablished(handler.readyState)) {
+ closeWebSocketConnection(handler, code, reason, false);
+ }
+ handler.controller.abort();
+ if (isConnecting(handler.readyState)) {
+ handler.onSocketClose();
+ } else if (handler.socket?.destroyed === false) {
+ handler.socket.destroy();
+ }
+ }
+ __name(failWebsocketConnection, "failWebsocketConnection");
+ module2.exports = {
+ establishWebSocketConnection,
+ failWebsocketConnection,
+ closeWebSocketConnection
+ };
+ }
+});
+
+// node_modules/undici/lib/web/websocket/permessage-deflate.js
+var require_permessage_deflate = __commonJS({
+ "node_modules/undici/lib/web/websocket/permessage-deflate.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { createInflateRaw, Z_DEFAULT_WINDOWBITS } = __require("node:zlib");
+ var { isValidClientWindowBits } = require_util5();
+ var { MessageSizeExceededError } = require_errors();
+ var tail = Buffer.from([0, 0, 255, 255]);
+ var kBuffer = /* @__PURE__ */ Symbol("kBuffer");
+ var kLength = /* @__PURE__ */ Symbol("kLength");
+ var PerMessageDeflate = class {
+ static {
+ __name(this, "PerMessageDeflate");
+ }
+ /** @type {import('node:zlib').InflateRaw} */
+ #inflate;
+ #options = {};
+ #maxPayloadSize = 0;
+ /**
+ * @param {Map} extensions
+ */
+ constructor(extensions, options2) {
+ this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover");
+ this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits");
+ this.#maxPayloadSize = options2.maxPayloadSize;
+ }
+ /**
+ * Decompress a compressed payload.
+ * @param {Buffer} chunk Compressed data
+ * @param {boolean} fin Final fragment flag
+ * @param {Function} callback Callback function
+ */
+ decompress(chunk, fin, callback) {
+ if (!this.#inflate) {
+ let windowBits = Z_DEFAULT_WINDOWBITS;
+ if (this.#options.serverMaxWindowBits) {
+ if (!isValidClientWindowBits(this.#options.serverMaxWindowBits)) {
+ callback(new Error("Invalid server_max_window_bits"));
+ return;
+ }
+ windowBits = Number.parseInt(this.#options.serverMaxWindowBits);
+ }
+ try {
+ this.#inflate = createInflateRaw({ windowBits });
+ } catch (err) {
+ callback(err);
+ return;
+ }
+ this.#inflate[kBuffer] = [];
+ this.#inflate[kLength] = 0;
+ this.#inflate.on("data", (data) => {
+ this.#inflate[kLength] += data.length;
+ if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) {
+ callback(new MessageSizeExceededError());
+ this.#inflate.removeAllListeners();
+ this.#inflate = null;
+ return;
+ }
+ this.#inflate[kBuffer].push(data);
+ });
+ this.#inflate.on("error", (err) => {
+ this.#inflate = null;
+ callback(err);
+ });
+ }
+ this.#inflate.write(chunk);
+ if (fin) {
+ this.#inflate.write(tail);
+ }
+ this.#inflate.flush(() => {
+ if (!this.#inflate) {
+ return;
+ }
+ const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]);
+ this.#inflate[kBuffer].length = 0;
+ this.#inflate[kLength] = 0;
+ callback(null, full);
+ });
+ }
+ };
+ module2.exports = { PerMessageDeflate };
+ }
+});
+
+// node_modules/undici/lib/web/websocket/receiver.js
+var require_receiver = __commonJS({
+ "node_modules/undici/lib/web/websocket/receiver.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { Writable } = __require("node:stream");
+ var assert2 = __require("node:assert");
+ var { parserStates, opcodes, states, emptyBuffer, sentCloseFrameState } = require_constants6();
+ var {
+ isValidStatusCode,
+ isValidOpcode,
+ websocketMessageReceived,
+ utf8Decode,
+ isControlFrame,
+ isTextBinaryFrame,
+ isContinuationFrame
+ } = require_util5();
+ var { failWebsocketConnection } = require_connection();
+ var { WebsocketFrameSend } = require_frame();
+ var { PerMessageDeflate } = require_permessage_deflate();
+ var { MessageSizeExceededError } = require_errors();
+ var ByteParser = class extends Writable {
+ static {
+ __name(this, "ByteParser");
+ }
+ #buffers = [];
+ #fragmentsBytes = 0;
+ #byteOffset = 0;
+ #loop = false;
+ #state = parserStates.INFO;
+ #info = {};
+ #fragments = [];
+ /** @type {Map} */
+ #extensions;
+ /** @type {import('./websocket').Handler} */
+ #handler;
+ /** @type {number} */
+ #maxFragments;
+ /** @type {number} */
+ #maxPayloadSize;
+ /**
+ * @param {import('./websocket').Handler} handler
+ * @param {Map|null} extensions
+ * @param {{ maxFragments?: number, maxPayloadSize?: number }} [options]
+ */
+ constructor(handler, extensions, options2 = {}) {
+ super();
+ this.#handler = handler;
+ this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions;
+ this.#maxFragments = options2.maxFragments ?? 0;
+ this.#maxPayloadSize = options2.maxPayloadSize ?? 0;
+ if (this.#extensions.has("permessage-deflate")) {
+ this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions, options2));
+ }
+ }
+ /**
+ * @param {Buffer} chunk
+ * @param {() => void} callback
+ */
+ _write(chunk, _, callback) {
+ this.#buffers.push(chunk);
+ this.#byteOffset += chunk.length;
+ this.#loop = true;
+ this.run(callback);
+ }
+ #validatePayloadLength() {
+ if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength + this.#fragmentsBytes > this.#maxPayloadSize) {
+ failWebsocketConnection(this.#handler, 1009, "Payload size exceeds maximum allowed size");
+ return false;
+ }
+ return true;
+ }
+ /**
+ * Runs whenever a new chunk is received.
+ * Callback is called whenever there are no more chunks buffering,
+ * or not enough bytes are buffered to parse.
+ */
+ run(callback) {
+ while (this.#loop) {
+ if (this.#state === parserStates.INFO) {
+ if (this.#byteOffset < 2) {
+ return callback();
+ }
+ const buffer = this.consume(2);
+ const fin = (buffer[0] & 128) !== 0;
+ const opcode = buffer[0] & 15;
+ const masked = (buffer[1] & 128) === 128;
+ const fragmented = !fin && opcode !== opcodes.CONTINUATION;
+ const payloadLength = buffer[1] & 127;
+ const rsv1 = buffer[0] & 64;
+ const rsv2 = buffer[0] & 32;
+ const rsv3 = buffer[0] & 16;
+ if (!isValidOpcode(opcode)) {
+ failWebsocketConnection(this.#handler, 1002, "Invalid opcode received");
+ return callback();
+ }
+ if (masked) {
+ failWebsocketConnection(this.#handler, 1002, "Frame cannot be masked");
+ return callback();
+ }
+ if (rsv1 !== 0 && !this.#extensions.has("permessage-deflate")) {
+ failWebsocketConnection(this.#handler, 1002, "Expected RSV1 to be clear.");
+ return;
+ }
+ if (rsv2 !== 0 || rsv3 !== 0) {
+ failWebsocketConnection(this.#handler, 1002, "RSV1, RSV2, RSV3 must be clear");
+ return;
+ }
+ if (fragmented && !isTextBinaryFrame(opcode)) {
+ failWebsocketConnection(this.#handler, 1002, "Invalid frame type was fragmented.");
+ return;
+ }
+ if (isTextBinaryFrame(opcode) && this.#fragments.length > 0) {
+ failWebsocketConnection(this.#handler, 1002, "Expected continuation frame");
+ return;
+ }
+ if (this.#info.fragmented && fragmented) {
+ failWebsocketConnection(this.#handler, 1002, "Fragmented frame exceeded 125 bytes.");
+ return;
+ }
+ if ((payloadLength > 125 || fragmented) && isControlFrame(opcode)) {
+ failWebsocketConnection(this.#handler, 1002, "Control frame either too large or fragmented");
+ return;
+ }
+ if (isContinuationFrame(opcode) && this.#fragments.length === 0 && !this.#info.compressed) {
+ failWebsocketConnection(this.#handler, 1002, "Unexpected continuation frame");
+ return;
+ }
+ if (payloadLength <= 125) {
+ this.#info.payloadLength = payloadLength;
+ this.#state = parserStates.READ_DATA;
+ if (!this.#validatePayloadLength()) {
+ return;
+ }
+ } else if (payloadLength === 126) {
+ this.#state = parserStates.PAYLOADLENGTH_16;
+ } else if (payloadLength === 127) {
+ this.#state = parserStates.PAYLOADLENGTH_64;
+ }
+ if (isTextBinaryFrame(opcode)) {
+ this.#info.binaryType = opcode;
+ this.#info.compressed = rsv1 !== 0;
+ }
+ this.#info.opcode = opcode;
+ this.#info.masked = masked;
+ this.#info.fin = fin;
+ this.#info.fragmented = fragmented;
+ } else if (this.#state === parserStates.PAYLOADLENGTH_16) {
+ if (this.#byteOffset < 2) {
+ return callback();
+ }
+ const buffer = this.consume(2);
+ this.#info.payloadLength = buffer.readUInt16BE(0);
+ this.#state = parserStates.READ_DATA;
+ if (!this.#validatePayloadLength()) {
+ return;
+ }
+ } else if (this.#state === parserStates.PAYLOADLENGTH_64) {
+ if (this.#byteOffset < 8) {
+ return callback();
+ }
+ const buffer = this.consume(8);
+ const upper = buffer.readUInt32BE(0);
+ const lower = buffer.readUInt32BE(4);
+ if (upper !== 0 || lower > 2 ** 31 - 1) {
+ failWebsocketConnection(this.#handler, 1009, "Received payload length > 2^31 bytes.");
+ return;
+ }
+ this.#info.payloadLength = lower;
+ this.#state = parserStates.READ_DATA;
+ if (!this.#validatePayloadLength()) {
+ return;
+ }
+ } else if (this.#state === parserStates.READ_DATA) {
+ if (this.#byteOffset < this.#info.payloadLength) {
+ return callback();
+ }
+ const body = this.consume(this.#info.payloadLength);
+ if (isControlFrame(this.#info.opcode)) {
+ this.#loop = this.parseControlFrame(body);
+ this.#state = parserStates.INFO;
+ } else {
+ if (!this.#info.compressed) {
+ if (!this.writeFragments(body)) {
+ return;
+ }
+ if (!this.#info.fragmented && this.#info.fin) {
+ websocketMessageReceived(this.#handler, this.#info.binaryType, this.consumeFragments());
+ }
+ this.#state = parserStates.INFO;
+ } else {
+ this.#extensions.get("permessage-deflate").decompress(
+ body,
+ this.#info.fin,
+ (error51, data) => {
+ if (error51) {
+ const code = error51 instanceof MessageSizeExceededError ? 1009 : 1007;
+ failWebsocketConnection(this.#handler, code, error51.message);
+ return;
+ }
+ if (!this.writeFragments(data)) {
+ return;
+ }
+ if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) {
+ failWebsocketConnection(this.#handler, 1009, new MessageSizeExceededError().message);
+ return;
+ }
+ if (!this.#info.fin) {
+ this.#state = parserStates.INFO;
+ this.#loop = true;
+ this.run(callback);
+ return;
+ }
+ websocketMessageReceived(this.#handler, this.#info.binaryType, this.consumeFragments());
+ this.#loop = true;
+ this.#state = parserStates.INFO;
+ this.run(callback);
+ },
+ this.#fragmentsBytes
+ );
+ this.#loop = false;
+ break;
+ }
+ }
+ }
+ }
+ }
+ /**
+ * Take n bytes from the buffered Buffers
+ * @param {number} n
+ * @returns {Buffer}
+ */
+ consume(n) {
+ if (n > this.#byteOffset) {
+ throw new Error("Called consume() before buffers satiated.");
+ } else if (n === 0) {
+ return emptyBuffer;
+ }
+ this.#byteOffset -= n;
+ const first = this.#buffers[0];
+ if (first.length > n) {
+ this.#buffers[0] = first.subarray(n, first.length);
+ return first.subarray(0, n);
+ } else if (first.length === n) {
+ return this.#buffers.shift();
+ } else {
+ let offset = 0;
+ const buffer = Buffer.allocUnsafeSlow(n);
+ while (offset !== n) {
+ const next = this.#buffers[0];
+ const length = next.length;
+ if (length + offset === n) {
+ buffer.set(this.#buffers.shift(), offset);
+ break;
+ } else if (length + offset > n) {
+ buffer.set(next.subarray(0, n - offset), offset);
+ this.#buffers[0] = next.subarray(n - offset);
+ break;
+ } else {
+ buffer.set(this.#buffers.shift(), offset);
+ offset += length;
+ }
+ }
+ return buffer;
+ }
+ }
+ writeFragments(fragment) {
+ if (this.#maxFragments > 0 && this.#fragments.length === this.#maxFragments) {
+ failWebsocketConnection(this.#handler, 1008, "Too many message fragments");
+ return false;
+ }
+ this.#fragmentsBytes += fragment.length;
+ this.#fragments.push(fragment);
+ return true;
+ }
+ consumeFragments() {
+ const fragments = this.#fragments;
+ if (fragments.length === 1) {
+ this.#fragmentsBytes = 0;
+ return fragments.shift();
+ }
+ let offset = 0;
+ const output = Buffer.allocUnsafeSlow(this.#fragmentsBytes);
+ for (let i = 0; i < fragments.length; ++i) {
+ const buffer = fragments[i];
+ output.set(buffer, offset);
+ offset += buffer.length;
+ }
+ this.#fragments = [];
+ this.#fragmentsBytes = 0;
+ return output;
+ }
+ parseCloseBody(data) {
+ assert2(data.length !== 1);
+ let code;
+ if (data.length >= 2) {
+ code = data.readUInt16BE(0);
+ }
+ if (code !== void 0 && !isValidStatusCode(code)) {
+ return { code: 1002, reason: "Invalid status code", error: true };
+ }
+ let reason = data.subarray(2);
+ if (reason[0] === 239 && reason[1] === 187 && reason[2] === 191) {
+ reason = reason.subarray(3);
+ }
+ try {
+ reason = utf8Decode(reason);
+ } catch {
+ return { code: 1007, reason: "Invalid UTF-8", error: true };
+ }
+ return { code, reason, error: false };
+ }
+ /**
+ * Parses control frames.
+ * @param {Buffer} body
+ */
+ parseControlFrame(body) {
+ const { opcode, payloadLength } = this.#info;
+ if (opcode === opcodes.CLOSE) {
+ if (payloadLength === 1) {
+ failWebsocketConnection(this.#handler, 1002, "Received close frame with a 1-byte body.");
+ return false;
+ }
+ this.#info.closeInfo = this.parseCloseBody(body);
+ if (this.#info.closeInfo.error) {
+ const { code, reason } = this.#info.closeInfo;
+ failWebsocketConnection(this.#handler, code, reason);
+ return false;
+ }
+ if (!this.#handler.closeState.has(sentCloseFrameState.SENT) && !this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) {
+ let body2 = emptyBuffer;
+ if (this.#info.closeInfo.code) {
+ body2 = Buffer.allocUnsafe(2);
+ body2.writeUInt16BE(this.#info.closeInfo.code, 0);
+ }
+ const closeFrame = new WebsocketFrameSend(body2);
+ this.#handler.socket.write(closeFrame.createFrame(opcodes.CLOSE));
+ this.#handler.closeState.add(sentCloseFrameState.SENT);
+ }
+ this.#handler.readyState = states.CLOSING;
+ this.#handler.closeState.add(sentCloseFrameState.RECEIVED);
+ return false;
+ } else if (opcode === opcodes.PING) {
+ if (!this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) {
+ const frame = new WebsocketFrameSend(body);
+ this.#handler.socket.write(frame.createFrame(opcodes.PONG));
+ this.#handler.onPing(body);
+ }
+ } else if (opcode === opcodes.PONG) {
+ this.#handler.onPong(body);
+ }
+ return true;
+ }
+ get closingInfo() {
+ return this.#info.closeInfo;
+ }
+ };
+ module2.exports = {
+ ByteParser
+ };
+ }
+});
+
+// node_modules/undici/lib/web/websocket/sender.js
+var require_sender = __commonJS({
+ "node_modules/undici/lib/web/websocket/sender.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { WebsocketFrameSend } = require_frame();
+ var { opcodes, sendHints } = require_constants6();
+ var FixedQueue = require_fixed_queue();
+ var SendQueue = class {
+ static {
+ __name(this, "SendQueue");
+ }
+ /**
+ * @type {FixedQueue}
+ */
+ #queue = new FixedQueue();
+ /**
+ * @type {boolean}
+ */
+ #running = false;
+ /** @type {import('node:net').Socket} */
+ #socket;
+ constructor(socket) {
+ this.#socket = socket;
+ }
+ add(item, cb, hint) {
+ if (hint !== sendHints.blob) {
+ if (!this.#running) {
+ if (hint === sendHints.text) {
+ const { 0: head, 1: body } = WebsocketFrameSend.createFastTextFrame(item);
+ this.#socket.cork();
+ this.#socket.write(head);
+ this.#socket.write(body, cb);
+ this.#socket.uncork();
+ } else {
+ this.#socket.write(createFrame(item, hint), cb);
+ }
+ } else {
+ const node2 = {
+ promise: null,
+ callback: cb,
+ frame: createFrame(item, hint)
+ };
+ this.#queue.push(node2);
+ }
+ return;
+ }
+ const node = {
+ promise: item.arrayBuffer().then((ab) => {
+ node.promise = null;
+ node.frame = createFrame(ab, hint);
+ }),
+ callback: cb,
+ frame: null
+ };
+ this.#queue.push(node);
+ if (!this.#running) {
+ this.#run();
+ }
+ }
+ async #run() {
+ this.#running = true;
+ const queue = this.#queue;
+ while (!queue.isEmpty()) {
+ const node = queue.shift();
+ if (node.promise !== null) {
+ await node.promise;
+ }
+ this.#socket.write(node.frame, node.callback);
+ node.callback = node.frame = null;
+ }
+ this.#running = false;
+ }
+ };
+ function createFrame(data, hint) {
+ return new WebsocketFrameSend(toBuffer(data, hint)).createFrame(hint === sendHints.text ? opcodes.TEXT : opcodes.BINARY);
+ }
+ __name(createFrame, "createFrame");
+ function toBuffer(data, hint) {
+ switch (hint) {
+ case sendHints.text:
+ case sendHints.typedArray:
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
+ case sendHints.arrayBuffer:
+ case sendHints.blob:
+ return new Uint8Array(data);
+ }
+ }
+ __name(toBuffer, "toBuffer");
+ module2.exports = { SendQueue };
+ }
+});
+
+// node_modules/undici/lib/web/websocket/websocket.js
+var require_websocket = __commonJS({
+ "node_modules/undici/lib/web/websocket/websocket.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { isArrayBuffer } = __require("node:util/types");
+ var { webidl } = require_webidl();
+ var { URLSerializer } = require_data_url();
+ var { environmentSettingsObject } = require_util2();
+ var { staticPropertyDescriptors, states, sentCloseFrameState, sendHints, opcodes } = require_constants6();
+ var {
+ isConnecting,
+ isEstablished,
+ isClosing,
+ isClosed,
+ isValidSubprotocol,
+ fireEvent,
+ utf8Decode,
+ toArrayBuffer,
+ getURLRecord
+ } = require_util5();
+ var { establishWebSocketConnection, closeWebSocketConnection, failWebsocketConnection } = require_connection();
+ var { ByteParser } = require_receiver();
+ var { kEnumerableProperty } = require_util();
+ var { getGlobalDispatcher } = require_global2();
+ var { ErrorEvent, CloseEvent, createFastMessageEvent } = require_events();
+ var { SendQueue } = require_sender();
+ var { WebsocketFrameSend } = require_frame();
+ var { channels } = require_diagnostics();
+ function getSocketAddress(socket) {
+ if (typeof socket?.address === "function") {
+ return socket.address();
+ }
+ if (typeof socket?.session?.socket?.address === "function") {
+ return socket.session.socket.address();
+ }
+ return null;
+ }
+ __name(getSocketAddress, "getSocketAddress");
+ var WebSocket = class _WebSocket extends EventTarget {
+ static {
+ __name(this, "WebSocket");
+ }
+ #events = {
+ open: null,
+ error: null,
+ close: null,
+ message: null
+ };
+ #bufferedAmount = 0;
+ #protocol = "";
+ #extensions = "";
+ /** @type {SendQueue} */
+ #sendQueue;
+ /** @type {Handler} */
+ #handler = {
+ onConnectionEstablished: /* @__PURE__ */ __name((response, extensions) => this.#onConnectionEstablished(response, extensions), "onConnectionEstablished"),
+ onMessage: /* @__PURE__ */ __name((opcode, data) => this.#onMessage(opcode, data), "onMessage"),
+ onParserError: /* @__PURE__ */ __name((err) => failWebsocketConnection(this.#handler, null, err.message), "onParserError"),
+ onParserDrain: /* @__PURE__ */ __name(() => this.#onParserDrain(), "onParserDrain"),
+ onSocketData: /* @__PURE__ */ __name((chunk) => {
+ if (!this.#parser.write(chunk)) {
+ this.#handler.socket.pause();
+ }
+ }, "onSocketData"),
+ onSocketError: /* @__PURE__ */ __name((err) => {
+ this.#handler.readyState = states.CLOSING;
+ if (channels.socketError.hasSubscribers) {
+ channels.socketError.publish(err);
+ }
+ this.#handler.socket.destroy();
+ }, "onSocketError"),
+ onSocketClose: /* @__PURE__ */ __name(() => this.#onSocketClose(), "onSocketClose"),
+ onPing: /* @__PURE__ */ __name((body) => {
+ if (channels.ping.hasSubscribers) {
+ channels.ping.publish({
+ payload: body,
+ websocket: this
+ });
+ }
+ }, "onPing"),
+ onPong: /* @__PURE__ */ __name((body) => {
+ if (channels.pong.hasSubscribers) {
+ channels.pong.publish({
+ payload: body,
+ websocket: this
+ });
+ }
+ }, "onPong"),
+ readyState: states.CONNECTING,
+ socket: null,
+ closeState: /* @__PURE__ */ new Set(),
+ controller: null,
+ wasEverConnected: false
+ };
+ #url;
+ #binaryType;
+ /** @type {import('./receiver').ByteParser} */
+ #parser;
+ /**
+ * @param {string} url
+ * @param {string|string[]} protocols
+ */
+ constructor(url2, protocols = []) {
+ super();
+ webidl.util.markAsUncloneable(this);
+ const prefix = "WebSocket constructor";
+ webidl.argumentLengthCheck(arguments, 1, prefix);
+ const options2 = webidl.converters["DOMString or sequence or WebSocketInit"](protocols, prefix, "options");
+ url2 = webidl.converters.USVString(url2);
+ protocols = options2.protocols;
+ const baseURL = environmentSettingsObject.settingsObject.baseUrl;
+ const urlRecord = getURLRecord(url2, baseURL);
+ if (typeof protocols === "string") {
+ protocols = [protocols];
+ }
+ if (protocols.length !== new Set(protocols.map((p) => p.toLowerCase())).size) {
+ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError");
+ }
+ if (protocols.length > 0 && !protocols.every((p) => isValidSubprotocol(p))) {
+ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError");
+ }
+ this.#url = new URL(urlRecord.href);
+ const client = environmentSettingsObject.settingsObject;
+ this.#handler.controller = establishWebSocketConnection(
+ urlRecord,
+ protocols,
+ client,
+ this.#handler,
+ options2
+ );
+ this.#handler.readyState = _WebSocket.CONNECTING;
+ this.#binaryType = "blob";
+ }
+ /**
+ * @see https://websockets.spec.whatwg.org/#dom-websocket-close
+ * @param {number|undefined} code
+ * @param {string|undefined} reason
+ */
+ close(code = void 0, reason = void 0) {
+ webidl.brandCheck(this, _WebSocket);
+ const prefix = "WebSocket.close";
+ if (code !== void 0) {
+ code = webidl.converters["unsigned short"](code, prefix, "code", webidl.attributes.Clamp);
+ }
+ if (reason !== void 0) {
+ reason = webidl.converters.USVString(reason);
+ }
+ code ??= null;
+ reason ??= "";
+ closeWebSocketConnection(this.#handler, code, reason, true);
+ }
+ /**
+ * @see https://websockets.spec.whatwg.org/#dom-websocket-send
+ * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data
+ */
+ send(data) {
+ webidl.brandCheck(this, _WebSocket);
+ const prefix = "WebSocket.send";
+ webidl.argumentLengthCheck(arguments, 1, prefix);
+ data = webidl.converters.WebSocketSendData(data, prefix, "data");
+ if (isConnecting(this.#handler.readyState)) {
+ throw new DOMException("Sent before connected.", "InvalidStateError");
+ }
+ if (!isEstablished(this.#handler.readyState) || isClosing(this.#handler.readyState)) {
+ return;
+ }
+ if (typeof data === "string") {
+ const buffer = Buffer.from(data);
+ this.#bufferedAmount += buffer.byteLength;
+ this.#sendQueue.add(buffer, () => {
+ this.#bufferedAmount -= buffer.byteLength;
+ }, sendHints.text);
+ } else if (isArrayBuffer(data)) {
+ this.#bufferedAmount += data.byteLength;
+ this.#sendQueue.add(data, () => {
+ this.#bufferedAmount -= data.byteLength;
+ }, sendHints.arrayBuffer);
+ } else if (ArrayBuffer.isView(data)) {
+ this.#bufferedAmount += data.byteLength;
+ this.#sendQueue.add(data, () => {
+ this.#bufferedAmount -= data.byteLength;
+ }, sendHints.typedArray);
+ } else if (webidl.is.Blob(data)) {
+ this.#bufferedAmount += data.size;
+ this.#sendQueue.add(data, () => {
+ this.#bufferedAmount -= data.size;
+ }, sendHints.blob);
+ }
+ }
+ get readyState() {
+ webidl.brandCheck(this, _WebSocket);
+ return this.#handler.readyState;
+ }
+ get bufferedAmount() {
+ webidl.brandCheck(this, _WebSocket);
+ return this.#bufferedAmount;
+ }
+ get url() {
+ webidl.brandCheck(this, _WebSocket);
+ return URLSerializer(this.#url);
+ }
+ get extensions() {
+ webidl.brandCheck(this, _WebSocket);
+ return this.#extensions;
+ }
+ get protocol() {
+ webidl.brandCheck(this, _WebSocket);
+ return this.#protocol;
+ }
+ get onopen() {
+ webidl.brandCheck(this, _WebSocket);
+ return this.#events.open;
+ }
+ set onopen(fn) {
+ webidl.brandCheck(this, _WebSocket);
+ if (this.#events.open) {
+ this.removeEventListener("open", this.#events.open);
+ }
+ const listener = webidl.converters.EventHandlerNonNull(fn);
+ if (listener !== null) {
+ this.addEventListener("open", listener);
+ this.#events.open = fn;
+ } else {
+ this.#events.open = null;
+ }
+ }
+ get onerror() {
+ webidl.brandCheck(this, _WebSocket);
+ return this.#events.error;
+ }
+ set onerror(fn) {
+ webidl.brandCheck(this, _WebSocket);
+ if (this.#events.error) {
+ this.removeEventListener("error", this.#events.error);
+ }
+ const listener = webidl.converters.EventHandlerNonNull(fn);
+ if (listener !== null) {
+ this.addEventListener("error", listener);
+ this.#events.error = fn;
+ } else {
+ this.#events.error = null;
+ }
+ }
+ get onclose() {
+ webidl.brandCheck(this, _WebSocket);
+ return this.#events.close;
+ }
+ set onclose(fn) {
+ webidl.brandCheck(this, _WebSocket);
+ if (this.#events.close) {
+ this.removeEventListener("close", this.#events.close);
+ }
+ const listener = webidl.converters.EventHandlerNonNull(fn);
+ if (listener !== null) {
+ this.addEventListener("close", listener);
+ this.#events.close = fn;
+ } else {
+ this.#events.close = null;
+ }
+ }
+ get onmessage() {
+ webidl.brandCheck(this, _WebSocket);
+ return this.#events.message;
+ }
+ set onmessage(fn) {
+ webidl.brandCheck(this, _WebSocket);
+ if (this.#events.message) {
+ this.removeEventListener("message", this.#events.message);
+ }
+ const listener = webidl.converters.EventHandlerNonNull(fn);
+ if (listener !== null) {
+ this.addEventListener("message", listener);
+ this.#events.message = fn;
+ } else {
+ this.#events.message = null;
+ }
+ }
+ get binaryType() {
+ webidl.brandCheck(this, _WebSocket);
+ return this.#binaryType;
+ }
+ set binaryType(type2) {
+ webidl.brandCheck(this, _WebSocket);
+ if (type2 !== "blob" && type2 !== "arraybuffer") {
+ this.#binaryType = "blob";
+ } else {
+ this.#binaryType = type2;
+ }
+ }
+ /**
+ * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
+ */
+ #onConnectionEstablished(response, parsedExtensions) {
+ this.#handler.socket = response.socket;
+ const webSocketOptions = this.#handler.controller.dispatcher?.webSocketOptions;
+ const maxFragments = webSocketOptions?.maxFragments;
+ const maxPayloadSize = webSocketOptions?.maxPayloadSize;
+ const parser2 = new ByteParser(this.#handler, parsedExtensions, {
+ maxFragments,
+ maxPayloadSize
+ });
+ parser2.on("drain", () => this.#handler.onParserDrain());
+ parser2.on("error", (err) => this.#handler.onParserError(err));
+ this.#parser = parser2;
+ this.#sendQueue = new SendQueue(response.socket);
+ this.#handler.readyState = states.OPEN;
+ const extensions = response.headersList.get("sec-websocket-extensions");
+ if (extensions !== null) {
+ this.#extensions = extensions;
+ }
+ const protocol = response.headersList.get("sec-websocket-protocol");
+ if (protocol !== null) {
+ this.#protocol = protocol;
+ }
+ fireEvent("open", this);
+ if (channels.open.hasSubscribers) {
+ const headers = response.headersList.entries;
+ channels.open.publish({
+ address: getSocketAddress(response.socket),
+ protocol: this.#protocol,
+ extensions: this.#extensions,
+ websocket: this,
+ handshakeResponse: {
+ status: response.status,
+ statusText: response.statusText,
+ headers
+ }
+ });
+ }
+ }
+ #onMessage(type2, data) {
+ if (this.#handler.readyState !== states.OPEN) {
+ return;
+ }
+ let dataForEvent;
+ if (type2 === opcodes.TEXT) {
+ try {
+ dataForEvent = utf8Decode(data);
+ } catch {
+ failWebsocketConnection(this.#handler, 1007, "Received invalid UTF-8 in text frame.");
+ return;
+ }
+ } else if (type2 === opcodes.BINARY) {
+ if (this.#binaryType === "blob") {
+ dataForEvent = new Blob([data]);
+ } else {
+ dataForEvent = toArrayBuffer(data);
+ }
+ }
+ fireEvent("message", this, createFastMessageEvent, {
+ origin: this.#url.origin,
+ data: dataForEvent
+ });
+ }
+ #onParserDrain() {
+ this.#handler.socket.resume();
+ }
+ /**
+ * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
+ * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4
+ */
+ #onSocketClose() {
+ const wasClean = this.#handler.closeState.has(sentCloseFrameState.SENT) && this.#handler.closeState.has(sentCloseFrameState.RECEIVED);
+ let code = 1005;
+ let reason = "";
+ const result = this.#parser?.closingInfo;
+ if (result && !result.error) {
+ code = result.code ?? 1005;
+ reason = result.reason;
+ }
+ this.#handler.readyState = states.CLOSED;
+ if (!this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) {
+ code = 1006;
+ fireEvent("error", this, (type2, init) => new ErrorEvent(type2, init), {
+ error: new TypeError(reason)
+ });
+ }
+ fireEvent("close", this, (type2, init) => new CloseEvent(type2, init), {
+ wasClean,
+ code,
+ reason
+ });
+ if (channels.close.hasSubscribers) {
+ channels.close.publish({
+ websocket: this,
+ code,
+ reason
+ });
+ }
+ }
+ /**
+ * @param {WebSocket} ws
+ * @param {Buffer|undefined} buffer
+ */
+ static ping(ws, buffer) {
+ if (Buffer.isBuffer(buffer)) {
+ if (buffer.length > 125) {
+ throw new TypeError("A PING frame cannot have a body larger than 125 bytes.");
+ }
+ } else if (buffer !== void 0) {
+ throw new TypeError("Expected buffer payload");
+ }
+ const readyState = ws.#handler.readyState;
+ if (isEstablished(readyState) && !isClosing(readyState) && !isClosed(readyState)) {
+ const frame = new WebsocketFrameSend(buffer);
+ ws.#handler.socket.write(frame.createFrame(opcodes.PING));
+ }
+ }
+ };
+ var { ping } = WebSocket;
+ Reflect.deleteProperty(WebSocket, "ping");
+ WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING;
+ WebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN;
+ WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING;
+ WebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED;
+ Object.defineProperties(WebSocket.prototype, {
+ CONNECTING: staticPropertyDescriptors,
+ OPEN: staticPropertyDescriptors,
+ CLOSING: staticPropertyDescriptors,
+ CLOSED: staticPropertyDescriptors,
+ url: kEnumerableProperty,
+ readyState: kEnumerableProperty,
+ bufferedAmount: kEnumerableProperty,
+ onopen: kEnumerableProperty,
+ onerror: kEnumerableProperty,
+ onclose: kEnumerableProperty,
+ close: kEnumerableProperty,
+ onmessage: kEnumerableProperty,
+ binaryType: kEnumerableProperty,
+ send: kEnumerableProperty,
+ extensions: kEnumerableProperty,
+ protocol: kEnumerableProperty,
+ [Symbol.toStringTag]: {
+ value: "WebSocket",
+ writable: false,
+ enumerable: false,
+ configurable: true
+ }
+ });
+ Object.defineProperties(WebSocket, {
+ CONNECTING: staticPropertyDescriptors,
+ OPEN: staticPropertyDescriptors,
+ CLOSING: staticPropertyDescriptors,
+ CLOSED: staticPropertyDescriptors
+ });
+ webidl.converters["sequence"] = webidl.sequenceConverter(
+ webidl.converters.DOMString
+ );
+ webidl.converters["DOMString or sequence"] = function(V, prefix, argument) {
+ if (webidl.util.Type(V) === webidl.util.Types.OBJECT && Symbol.iterator in V) {
+ return webidl.converters["sequence"](V);
+ }
+ return webidl.converters.DOMString(V, prefix, argument);
+ };
+ webidl.converters.WebSocketInit = webidl.dictionaryConverter([
+ {
+ key: "protocols",
+ converter: webidl.converters["DOMString or sequence"],
+ defaultValue: /* @__PURE__ */ __name(() => [], "defaultValue")
+ },
+ {
+ key: "dispatcher",
+ converter: webidl.converters.any,
+ defaultValue: /* @__PURE__ */ __name(() => getGlobalDispatcher(), "defaultValue")
+ },
+ {
+ key: "headers",
+ converter: webidl.nullableConverter(webidl.converters.HeadersInit)
+ }
+ ]);
+ webidl.converters["DOMString or sequence or WebSocketInit"] = function(V) {
+ if (webidl.util.Type(V) === webidl.util.Types.OBJECT && !(Symbol.iterator in V)) {
+ return webidl.converters.WebSocketInit(V);
+ }
+ return { protocols: webidl.converters["DOMString or sequence"](V) };
+ };
+ webidl.converters.WebSocketSendData = function(V) {
+ if (webidl.util.Type(V) === webidl.util.Types.OBJECT) {
+ if (webidl.is.Blob(V)) {
+ return V;
+ }
+ if (webidl.is.BufferSource(V)) {
+ return V;
+ }
+ }
+ return webidl.converters.USVString(V);
+ };
+ module2.exports = {
+ WebSocket,
+ ping
+ };
+ }
+});
+
+// node_modules/undici/lib/web/websocket/stream/websocketerror.js
+var require_websocketerror = __commonJS({
+ "node_modules/undici/lib/web/websocket/stream/websocketerror.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { webidl } = require_webidl();
+ var { validateCloseCodeAndReason } = require_util5();
+ var { kConstruct } = require_symbols();
+ var { kEnumerableProperty } = require_util();
+ function createInheritableDOMException() {
+ class Test extends DOMException {
+ static {
+ __name(this, "Test");
+ }
+ get reason() {
+ return "";
+ }
+ }
+ if (new Test().reason !== void 0) {
+ return DOMException;
+ }
+ return new Proxy(DOMException, {
+ construct(target, args, newTarget) {
+ const instance = Reflect.construct(target, args, target);
+ Object.setPrototypeOf(instance, newTarget.prototype);
+ return instance;
+ }
+ });
+ }
+ __name(createInheritableDOMException, "createInheritableDOMException");
+ var WebSocketError = class _WebSocketError extends createInheritableDOMException() {
+ static {
+ __name(this, "WebSocketError");
+ }
+ #closeCode;
+ #reason;
+ constructor(message = "", init = void 0) {
+ message = webidl.converters.DOMString(message, "WebSocketError", "message");
+ super(message, "WebSocketError");
+ if (init === kConstruct) {
+ return;
+ } else if (init !== null) {
+ init = webidl.converters.WebSocketCloseInfo(init);
+ }
+ let code = init.closeCode ?? null;
+ const reason = init.reason ?? "";
+ validateCloseCodeAndReason(code, reason);
+ if (reason.length !== 0 && code === null) {
+ code = 1e3;
+ }
+ this.#closeCode = code;
+ this.#reason = reason;
+ }
+ get closeCode() {
+ return this.#closeCode;
+ }
+ get reason() {
+ return this.#reason;
+ }
+ /**
+ * @param {string} message
+ * @param {number|null} code
+ * @param {string} reason
+ */
+ static createUnvalidatedWebSocketError(message, code, reason) {
+ const error51 = new _WebSocketError(message, kConstruct);
+ error51.#closeCode = code;
+ error51.#reason = reason;
+ return error51;
+ }
+ };
+ var { createUnvalidatedWebSocketError } = WebSocketError;
+ delete WebSocketError.createUnvalidatedWebSocketError;
+ Object.defineProperties(WebSocketError.prototype, {
+ closeCode: kEnumerableProperty,
+ reason: kEnumerableProperty,
+ [Symbol.toStringTag]: {
+ value: "WebSocketError",
+ writable: false,
+ enumerable: false,
+ configurable: true
+ }
+ });
+ webidl.is.WebSocketError = webidl.util.MakeTypeAssertion(WebSocketError);
+ module2.exports = { WebSocketError, createUnvalidatedWebSocketError };
+ }
+});
+
+// node_modules/undici/lib/web/websocket/stream/websocketstream.js
+var require_websocketstream = __commonJS({
+ "node_modules/undici/lib/web/websocket/stream/websocketstream.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { createDeferredPromise } = require_promise();
+ var { environmentSettingsObject } = require_util2();
+ var { states, opcodes, sentCloseFrameState } = require_constants6();
+ var { webidl } = require_webidl();
+ var { getURLRecord, isValidSubprotocol, isEstablished, utf8Decode } = require_util5();
+ var { establishWebSocketConnection, failWebsocketConnection, closeWebSocketConnection } = require_connection();
+ var { channels } = require_diagnostics();
+ var { WebsocketFrameSend } = require_frame();
+ var { ByteParser } = require_receiver();
+ var { WebSocketError, createUnvalidatedWebSocketError } = require_websocketerror();
+ var { kEnumerableProperty } = require_util();
+ var { utf8DecodeBytes } = require_encoding();
+ var emittedExperimentalWarning = false;
+ var WebSocketStream = class {
+ static {
+ __name(this, "WebSocketStream");
+ }
+ // Each WebSocketStream object has an associated url , which is a URL record .
+ /** @type {URL} */
+ #url;
+ // Each WebSocketStream object has an associated opened promise , which is a promise.
+ /** @type {import('../../../util/promise').DeferredPromise} */
+ #openedPromise;
+ // Each WebSocketStream object has an associated closed promise , which is a promise.
+ /** @type {import('../../../util/promise').DeferredPromise} */
+ #closedPromise;
+ // Each WebSocketStream object has an associated readable stream , which is a ReadableStream .
+ /** @type {ReadableStream} */
+ #readableStream;
+ /** @type {ReadableStreamDefaultController} */
+ #readableStreamController;
+ // Each WebSocketStream object has an associated writable stream , which is a WritableStream .
+ /** @type {WritableStream} */
+ #writableStream;
+ // Each WebSocketStream object has an associated boolean handshake aborted , which is initially false.
+ #handshakeAborted = false;
+ /** @type {import('../websocket').Handler} */
+ #handler = {
+ // https://whatpr.org/websockets/48/7b748d3...d5570f3.html#feedback-to-websocket-stream-from-the-protocol
+ onConnectionEstablished: /* @__PURE__ */ __name((response, extensions) => this.#onConnectionEstablished(response, extensions), "onConnectionEstablished"),
+ onMessage: /* @__PURE__ */ __name((opcode, data) => this.#onMessage(opcode, data), "onMessage"),
+ onParserError: /* @__PURE__ */ __name((err) => failWebsocketConnection(this.#handler, null, err.message), "onParserError"),
+ onParserDrain: /* @__PURE__ */ __name(() => this.#handler.socket.resume(), "onParserDrain"),
+ onSocketData: /* @__PURE__ */ __name((chunk) => {
+ if (!this.#parser.write(chunk)) {
+ this.#handler.socket.pause();
+ }
+ }, "onSocketData"),
+ onSocketError: /* @__PURE__ */ __name((err) => {
+ this.#handler.readyState = states.CLOSING;
+ if (channels.socketError.hasSubscribers) {
+ channels.socketError.publish(err);
+ }
+ this.#handler.socket.destroy();
+ }, "onSocketError"),
+ onSocketClose: /* @__PURE__ */ __name(() => this.#onSocketClose(), "onSocketClose"),
+ onPing: /* @__PURE__ */ __name(() => {
+ }, "onPing"),
+ onPong: /* @__PURE__ */ __name(() => {
+ }, "onPong"),
+ readyState: states.CONNECTING,
+ socket: null,
+ closeState: /* @__PURE__ */ new Set(),
+ controller: null,
+ wasEverConnected: false
+ };
+ /** @type {import('../receiver').ByteParser} */
+ #parser;
+ constructor(url2, options2 = void 0) {
+ if (!emittedExperimentalWarning) {
+ process.emitWarning("WebSocketStream is experimental! Expect it to change at any time.", {
+ code: "UNDICI-WSS"
+ });
+ emittedExperimentalWarning = true;
+ }
+ webidl.argumentLengthCheck(arguments, 1, "WebSocket");
+ url2 = webidl.converters.USVString(url2);
+ if (options2 !== null) {
+ options2 = webidl.converters.WebSocketStreamOptions(options2);
+ }
+ const baseURL = environmentSettingsObject.settingsObject.baseUrl;
+ const urlRecord = getURLRecord(url2, baseURL);
+ const protocols = options2.protocols;
+ if (protocols.length !== new Set(protocols.map((p) => p.toLowerCase())).size) {
+ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError");
+ }
+ if (protocols.length > 0 && !protocols.every((p) => isValidSubprotocol(p))) {
+ throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError");
+ }
+ this.#url = urlRecord.toString();
+ this.#openedPromise = createDeferredPromise();
+ this.#closedPromise = createDeferredPromise();
+ if (options2.signal != null) {
+ const signal = options2.signal;
+ if (signal.aborted) {
+ this.#openedPromise.reject(signal.reason);
+ this.#closedPromise.reject(signal.reason);
+ return;
+ }
+ signal.addEventListener("abort", () => {
+ if (!isEstablished(this.#handler.readyState)) {
+ failWebsocketConnection(this.#handler);
+ this.#handler.readyState = states.CLOSING;
+ this.#openedPromise.reject(signal.reason);
+ this.#closedPromise.reject(signal.reason);
+ this.#handshakeAborted = true;
+ }
+ }, { once: true });
+ }
+ const client = environmentSettingsObject.settingsObject;
+ this.#handler.controller = establishWebSocketConnection(
+ urlRecord,
+ protocols,
+ client,
+ this.#handler,
+ options2
+ );
+ }
+ // The url getter steps are to return this 's url , serialized .
+ get url() {
+ return this.#url.toString();
+ }
+ // The opened getter steps are to return this 's opened promise .
+ get opened() {
+ return this.#openedPromise.promise;
+ }
+ // The closed getter steps are to return this 's closed promise .
+ get closed() {
+ return this.#closedPromise.promise;
+ }
+ // The close( closeInfo ) method steps are:
+ close(closeInfo = void 0) {
+ if (closeInfo !== null) {
+ closeInfo = webidl.converters.WebSocketCloseInfo(closeInfo);
+ }
+ const code = closeInfo.closeCode ?? null;
+ const reason = closeInfo.reason;
+ closeWebSocketConnection(this.#handler, code, reason, true);
+ }
+ #write(chunk) {
+ chunk = webidl.converters.WebSocketStreamWrite(chunk);
+ const promise2 = createDeferredPromise();
+ let data = null;
+ let opcode = null;
+ if (webidl.is.BufferSource(chunk)) {
+ data = new Uint8Array(ArrayBuffer.isView(chunk) ? new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength) : chunk.slice());
+ opcode = opcodes.BINARY;
+ } else {
+ let string4;
+ try {
+ string4 = webidl.converters.DOMString(chunk);
+ } catch (e) {
+ promise2.reject(e);
+ return promise2.promise;
+ }
+ data = new TextEncoder().encode(string4);
+ opcode = opcodes.TEXT;
+ }
+ if (!this.#handler.closeState.has(sentCloseFrameState.SENT) && !this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) {
+ const frame = new WebsocketFrameSend(data);
+ this.#handler.socket.write(frame.createFrame(opcode), () => {
+ promise2.resolve(void 0);
+ });
+ }
+ return promise2.promise;
+ }
+ /** @type {import('../websocket').Handler['onConnectionEstablished']} */
+ #onConnectionEstablished(response, parsedExtensions) {
+ this.#handler.socket = response.socket;
+ const maxFragments = this.#handler.controller.dispatcher?.webSocketOptions?.maxFragments;
+ const maxPayloadSize = this.#handler.controller.dispatcher?.webSocketOptions?.maxPayloadSize;
+ const parser2 = new ByteParser(this.#handler, parsedExtensions, {
+ maxFragments,
+ maxPayloadSize
+ });
+ parser2.on("drain", () => this.#handler.onParserDrain());
+ parser2.on("error", (err) => this.#handler.onParserError(err));
+ this.#parser = parser2;
+ this.#handler.readyState = states.OPEN;
+ const extensions = parsedExtensions ?? "";
+ const protocol = response.headersList.get("sec-websocket-protocol") ?? "";
+ const readable = new ReadableStream({
+ start: /* @__PURE__ */ __name((controller) => {
+ this.#readableStreamController = controller;
+ }, "start"),
+ cancel: /* @__PURE__ */ __name((reason) => this.#cancel(reason), "cancel")
+ });
+ const writable = new WritableStream({
+ write: /* @__PURE__ */ __name((chunk) => this.#write(chunk), "write"),
+ close: /* @__PURE__ */ __name(() => closeWebSocketConnection(this.#handler, null, null), "close"),
+ abort: /* @__PURE__ */ __name((reason) => this.#closeUsingReason(reason), "abort")
+ });
+ this.#readableStream = readable;
+ this.#writableStream = writable;
+ this.#openedPromise.resolve({
+ extensions,
+ protocol,
+ readable,
+ writable
+ });
+ }
+ /** @type {import('../websocket').Handler['onMessage']} */
+ #onMessage(type2, data) {
+ if (this.#handler.readyState !== states.OPEN) {
+ return;
+ }
+ let chunk;
+ if (type2 === opcodes.TEXT) {
+ try {
+ chunk = utf8Decode(data);
+ } catch {
+ failWebsocketConnection(this.#handler, 1007, "Received invalid UTF-8 in text frame.");
+ return;
+ }
+ } else if (type2 === opcodes.BINARY) {
+ chunk = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
+ }
+ this.#readableStreamController.enqueue(chunk);
+ }
+ /** @type {import('../websocket').Handler['onSocketClose']} */
+ #onSocketClose() {
+ const wasClean = this.#handler.closeState.has(sentCloseFrameState.SENT) && this.#handler.closeState.has(sentCloseFrameState.RECEIVED);
+ this.#handler.readyState = states.CLOSED;
+ if (this.#handshakeAborted) {
+ return;
+ }
+ if (!this.#handler.wasEverConnected) {
+ this.#openedPromise.reject(new WebSocketError("Socket never opened"));
+ }
+ const result = this.#parser?.closingInfo;
+ let code = result?.code ?? 1005;
+ if (!this.#handler.closeState.has(sentCloseFrameState.SENT) && !this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) {
+ code = 1006;
+ }
+ const reason = result?.reason == null ? "" : utf8DecodeBytes(Buffer.from(result.reason));
+ if (wasClean) {
+ this.#readableStreamController.close();
+ if (!this.#writableStream.locked) {
+ this.#writableStream.abort(new DOMException("A closed WebSocketStream cannot be written to", "InvalidStateError"));
+ }
+ this.#closedPromise.resolve({
+ closeCode: code,
+ reason
+ });
+ } else {
+ const error51 = createUnvalidatedWebSocketError("unclean close", code, reason);
+ this.#readableStreamController?.error(error51);
+ this.#writableStream?.abort(error51);
+ this.#closedPromise.reject(error51);
+ }
+ }
+ #closeUsingReason(reason) {
+ let code = null;
+ let reasonString = "";
+ if (webidl.is.WebSocketError(reason)) {
+ code = reason.closeCode;
+ reasonString = reason.reason;
+ }
+ closeWebSocketConnection(this.#handler, code, reasonString);
+ }
+ // To cancel a WebSocketStream stream given reason , close using reason giving stream and reason .
+ #cancel(reason) {
+ this.#closeUsingReason(reason);
+ }
+ };
+ Object.defineProperties(WebSocketStream.prototype, {
+ url: kEnumerableProperty,
+ opened: kEnumerableProperty,
+ closed: kEnumerableProperty,
+ close: kEnumerableProperty,
+ [Symbol.toStringTag]: {
+ value: "WebSocketStream",
+ writable: false,
+ enumerable: false,
+ configurable: true
+ }
+ });
+ webidl.converters.WebSocketStreamOptions = webidl.dictionaryConverter([
+ {
+ key: "protocols",
+ converter: webidl.sequenceConverter(webidl.converters.USVString),
+ defaultValue: /* @__PURE__ */ __name(() => [], "defaultValue")
+ },
+ {
+ key: "signal",
+ converter: webidl.nullableConverter(webidl.converters.AbortSignal),
+ defaultValue: /* @__PURE__ */ __name(() => null, "defaultValue")
+ }
+ ]);
+ webidl.converters.WebSocketCloseInfo = webidl.dictionaryConverter([
+ {
+ key: "closeCode",
+ converter: /* @__PURE__ */ __name((V) => webidl.converters["unsigned short"](V, webidl.attributes.EnforceRange), "converter")
+ },
+ {
+ key: "reason",
+ converter: webidl.converters.USVString,
+ defaultValue: /* @__PURE__ */ __name(() => "", "defaultValue")
+ }
+ ]);
+ webidl.converters.WebSocketStreamWrite = function(V) {
+ if (typeof V === "string") {
+ return webidl.converters.USVString(V);
+ }
+ return webidl.converters.BufferSource(V);
+ };
+ module2.exports = { WebSocketStream };
+ }
+});
+
+// node_modules/undici/lib/web/eventsource/util.js
+var require_util6 = __commonJS({
+ "node_modules/undici/lib/web/eventsource/util.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ function isValidLastEventId(value) {
+ return value.indexOf("\0") === -1;
+ }
+ __name(isValidLastEventId, "isValidLastEventId");
+ function isASCIINumber(value) {
+ if (value.length === 0) return false;
+ for (let i = 0; i < value.length; i++) {
+ if (value.charCodeAt(i) < 48 || value.charCodeAt(i) > 57) return false;
+ }
+ return true;
+ }
+ __name(isASCIINumber, "isASCIINumber");
+ module2.exports = {
+ isValidLastEventId,
+ isASCIINumber
+ };
+ }
+});
+
+// node_modules/undici/lib/web/eventsource/eventsource-stream.js
+var require_eventsource_stream = __commonJS({
+ "node_modules/undici/lib/web/eventsource/eventsource-stream.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { Transform: Transform2 } = __require("node:stream");
+ var { isASCIINumber, isValidLastEventId } = require_util6();
+ var BOM = [239, 187, 191];
+ var LF = 10;
+ var CR = 13;
+ var COLON = 58;
+ var SPACE = 32;
+ var EventSourceStream = class extends Transform2 {
+ static {
+ __name(this, "EventSourceStream");
+ }
+ /**
+ * @type {eventSourceSettings}
+ */
+ state;
+ /**
+ * Leading byte-order-mark check.
+ * @type {boolean}
+ */
+ checkBOM = true;
+ /**
+ * @type {boolean}
+ */
+ crlfCheck = false;
+ /**
+ * @type {boolean}
+ */
+ eventEndCheck = false;
+ /**
+ * @type {Buffer|null}
+ */
+ buffer = null;
+ pos = 0;
+ event = {
+ data: void 0,
+ event: void 0,
+ id: void 0,
+ retry: void 0
+ };
+ /**
+ * @param {object} options
+ * @param {boolean} [options.readableObjectMode]
+ * @param {eventSourceSettings} [options.eventSourceSettings]
+ * @param {(chunk: any, encoding?: BufferEncoding | undefined) => boolean} [options.push]
+ */
+ constructor(options2 = {}) {
+ options2.readableObjectMode = true;
+ super(options2);
+ this.state = options2.eventSourceSettings || {};
+ if (options2.push) {
+ this.push = options2.push;
+ }
+ }
+ /**
+ * @param {Buffer} chunk
+ * @param {string} _encoding
+ * @param {Function} callback
+ * @returns {void}
+ */
+ _transform(chunk, _encoding, callback) {
+ if (chunk.length === 0) {
+ callback();
+ return;
+ }
+ if (this.buffer) {
+ this.buffer = Buffer.concat([this.buffer, chunk]);
+ } else {
+ this.buffer = chunk;
+ }
+ if (this.checkBOM) {
+ switch (this.buffer.length) {
+ case 1:
+ if (this.buffer[0] === BOM[0]) {
+ callback();
+ return;
+ }
+ this.checkBOM = false;
+ callback();
+ return;
+ case 2:
+ if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1]) {
+ callback();
+ return;
+ }
+ this.checkBOM = false;
+ break;
+ case 3:
+ if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) {
+ this.buffer = Buffer.alloc(0);
+ this.checkBOM = false;
+ callback();
+ return;
+ }
+ this.checkBOM = false;
+ break;
+ default:
+ if (this.buffer[0] === BOM[0] && this.buffer[1] === BOM[1] && this.buffer[2] === BOM[2]) {
+ this.buffer = this.buffer.subarray(3);
+ }
+ this.checkBOM = false;
+ break;
+ }
+ }
+ while (this.pos < this.buffer.length) {
+ if (this.eventEndCheck) {
+ if (this.crlfCheck) {
+ if (this.buffer[this.pos] === LF) {
+ this.buffer = this.buffer.subarray(this.pos + 1);
+ this.pos = 0;
+ this.crlfCheck = false;
+ continue;
+ }
+ this.crlfCheck = false;
+ }
+ if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {
+ if (this.buffer[this.pos] === CR) {
+ this.crlfCheck = true;
+ }
+ this.buffer = this.buffer.subarray(this.pos + 1);
+ this.pos = 0;
+ if (this.event.data !== void 0 || this.event.event || this.event.id !== void 0 || this.event.retry) {
+ this.processEvent(this.event);
+ }
+ this.clearEvent();
+ continue;
+ }
+ this.eventEndCheck = false;
+ continue;
+ }
+ if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {
+ if (this.buffer[this.pos] === CR) {
+ this.crlfCheck = true;
+ }
+ this.parseLine(this.buffer.subarray(0, this.pos), this.event);
+ this.buffer = this.buffer.subarray(this.pos + 1);
+ this.pos = 0;
+ this.eventEndCheck = true;
+ continue;
+ }
+ this.pos++;
+ }
+ callback();
+ }
+ /**
+ * @param {Buffer} line
+ * @param {EventSourceStreamEvent} event
+ */
+ parseLine(line, event) {
+ if (line.length === 0) {
+ return;
+ }
+ const colonPosition = line.indexOf(COLON);
+ if (colonPosition === 0) {
+ return;
+ }
+ let field = "";
+ let value = "";
+ if (colonPosition !== -1) {
+ field = line.subarray(0, colonPosition).toString("utf8");
+ let valueStart = colonPosition + 1;
+ if (line[valueStart] === SPACE) {
+ ++valueStart;
+ }
+ value = line.subarray(valueStart).toString("utf8");
+ } else {
+ field = line.toString("utf8");
+ value = "";
+ }
+ switch (field) {
+ case "data":
+ if (event[field] === void 0) {
+ event[field] = value;
+ } else {
+ event[field] += `
+${value}`;
+ }
+ break;
+ case "retry":
+ if (isASCIINumber(value)) {
+ event[field] = value;
+ }
+ break;
+ case "id":
+ if (isValidLastEventId(value)) {
+ event[field] = value;
+ }
+ break;
+ case "event":
+ if (value.length > 0) {
+ event[field] = value;
+ }
+ break;
+ }
+ }
+ /**
+ * @param {EventSourceStreamEvent} event
+ */
+ processEvent(event) {
+ if (event.retry && isASCIINumber(event.retry)) {
+ this.state.reconnectionTime = parseInt(event.retry, 10);
+ }
+ if (event.id !== void 0 && isValidLastEventId(event.id)) {
+ this.state.lastEventId = event.id;
+ }
+ if (event.data !== void 0) {
+ this.push({
+ type: event.event || "message",
+ options: {
+ data: event.data,
+ lastEventId: this.state.lastEventId,
+ origin: this.state.origin
+ }
+ });
+ }
+ }
+ clearEvent() {
+ this.event = {
+ data: void 0,
+ event: void 0,
+ id: void 0,
+ retry: void 0
+ };
+ }
+ };
+ module2.exports = {
+ EventSourceStream
+ };
+ }
+});
+
+// node_modules/undici/lib/web/eventsource/eventsource.js
+var require_eventsource = __commonJS({
+ "node_modules/undici/lib/web/eventsource/eventsource.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { pipeline } = __require("node:stream");
+ var { fetching } = require_fetch();
+ var { makeRequest } = require_request2();
+ var { webidl } = require_webidl();
+ var { EventSourceStream } = require_eventsource_stream();
+ var { parseMIMEType } = require_data_url();
+ var { createFastMessageEvent } = require_events();
+ var { isNetworkError } = require_response();
+ var { kEnumerableProperty } = require_util();
+ var { environmentSettingsObject } = require_util2();
+ var experimentalWarned = false;
+ var defaultReconnectionTime = 3e3;
+ var CONNECTING = 0;
+ var OPEN = 1;
+ var CLOSED = 2;
+ var ANONYMOUS = "anonymous";
+ var USE_CREDENTIALS = "use-credentials";
+ var EventSource = class _EventSource extends EventTarget {
+ static {
+ __name(this, "EventSource");
+ }
+ #events = {
+ open: null,
+ error: null,
+ message: null
+ };
+ #url;
+ #withCredentials = false;
+ /**
+ * @type {ReadyState}
+ */
+ #readyState = CONNECTING;
+ #request = null;
+ #controller = null;
+ #dispatcher;
+ /**
+ * @type {import('./eventsource-stream').eventSourceSettings}
+ */
+ #state;
+ /**
+ * Creates a new EventSource object.
+ * @param {string} url
+ * @param {EventSourceInit} [eventSourceInitDict={}]
+ * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#the-eventsource-interface
+ */
+ constructor(url2, eventSourceInitDict = {}) {
+ super();
+ webidl.util.markAsUncloneable(this);
+ const prefix = "EventSource constructor";
+ webidl.argumentLengthCheck(arguments, 1, prefix);
+ if (!experimentalWarned) {
+ experimentalWarned = true;
+ process.emitWarning("EventSource is experimental, expect them to change at any time.", {
+ code: "UNDICI-ES"
+ });
+ }
+ url2 = webidl.converters.USVString(url2);
+ eventSourceInitDict = webidl.converters.EventSourceInitDict(eventSourceInitDict, prefix, "eventSourceInitDict");
+ this.#dispatcher = eventSourceInitDict.node.dispatcher || eventSourceInitDict.dispatcher;
+ this.#state = {
+ lastEventId: "",
+ reconnectionTime: eventSourceInitDict.node.reconnectionTime
+ };
+ const settings = environmentSettingsObject;
+ let urlRecord;
+ try {
+ urlRecord = new URL(url2, settings.settingsObject.baseUrl);
+ this.#state.origin = urlRecord.origin;
+ } catch (e) {
+ throw new DOMException(e, "SyntaxError");
+ }
+ this.#url = urlRecord.href;
+ let corsAttributeState = ANONYMOUS;
+ if (eventSourceInitDict.withCredentials === true) {
+ corsAttributeState = USE_CREDENTIALS;
+ this.#withCredentials = true;
+ }
+ const initRequest = {
+ redirect: "follow",
+ keepalive: true,
+ // @see https://html.spec.whatwg.org/multipage/urls-and-fetching.html#cors-settings-attributes
+ mode: "cors",
+ credentials: corsAttributeState === "anonymous" ? "same-origin" : "omit",
+ referrer: "no-referrer"
+ };
+ initRequest.client = environmentSettingsObject.settingsObject;
+ initRequest.headersList = [["accept", { name: "accept", value: "text/event-stream" }]];
+ initRequest.cache = "no-store";
+ initRequest.initiator = "other";
+ initRequest.urlList = [new URL(this.#url)];
+ this.#request = makeRequest(initRequest);
+ this.#connect();
+ }
+ /**
+ * Returns the state of this EventSource object's connection. It can have the
+ * values described below.
+ * @returns {ReadyState}
+ * @readonly
+ */
+ get readyState() {
+ return this.#readyState;
+ }
+ /**
+ * Returns the URL providing the event stream.
+ * @readonly
+ * @returns {string}
+ */
+ get url() {
+ return this.#url;
+ }
+ /**
+ * Returns a boolean indicating whether the EventSource object was
+ * instantiated with CORS credentials set (true), or not (false, the default).
+ */
+ get withCredentials() {
+ return this.#withCredentials;
+ }
+ #connect() {
+ if (this.#readyState === CLOSED) return;
+ this.#readyState = CONNECTING;
+ const fetchParams = {
+ request: this.#request,
+ dispatcher: this.#dispatcher
+ };
+ const processEventSourceEndOfBody = /* @__PURE__ */ __name((response) => {
+ if (!isNetworkError(response)) {
+ return this.#reconnect();
+ }
+ }, "processEventSourceEndOfBody");
+ fetchParams.processResponseEndOfBody = processEventSourceEndOfBody;
+ fetchParams.processResponse = (response) => {
+ if (isNetworkError(response)) {
+ if (response.aborted) {
+ this.close();
+ this.dispatchEvent(new Event("error"));
+ return;
+ } else {
+ this.#reconnect();
+ return;
+ }
+ }
+ const contentType = response.headersList.get("content-type", true);
+ const mimeType = contentType !== null ? parseMIMEType(contentType) : "failure";
+ const contentTypeValid = mimeType !== "failure" && mimeType.essence === "text/event-stream";
+ if (response.status !== 200 || contentTypeValid === false) {
+ this.close();
+ this.dispatchEvent(new Event("error"));
+ return;
+ }
+ this.#readyState = OPEN;
+ this.dispatchEvent(new Event("open"));
+ this.#state.origin = response.urlList[response.urlList.length - 1].origin;
+ const eventSourceStream = new EventSourceStream({
+ eventSourceSettings: this.#state,
+ push: /* @__PURE__ */ __name((event) => {
+ this.dispatchEvent(createFastMessageEvent(
+ event.type,
+ event.options
+ ));
+ }, "push")
+ });
+ pipeline(
+ response.body.stream,
+ eventSourceStream,
+ (error51) => {
+ if (error51?.aborted === false) {
+ this.close();
+ this.dispatchEvent(new Event("error"));
+ }
+ }
+ );
+ };
+ this.#controller = fetching(fetchParams);
+ }
+ /**
+ * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model
+ * @returns {void}
+ */
+ #reconnect() {
+ if (this.#readyState === CLOSED) return;
+ this.#readyState = CONNECTING;
+ this.dispatchEvent(new Event("error"));
+ setTimeout(() => {
+ if (this.#readyState !== CONNECTING) return;
+ if (this.#state.lastEventId.length) {
+ this.#request.headersList.set("last-event-id", this.#state.lastEventId, true);
+ }
+ this.#connect();
+ }, this.#state.reconnectionTime)?.unref();
+ }
+ /**
+ * Closes the connection, if any, and sets the readyState attribute to
+ * CLOSED.
+ */
+ close() {
+ webidl.brandCheck(this, _EventSource);
+ if (this.#readyState === CLOSED) return;
+ this.#readyState = CLOSED;
+ this.#controller.abort();
+ this.#request = null;
+ }
+ get onopen() {
+ return this.#events.open;
+ }
+ set onopen(fn) {
+ if (this.#events.open) {
+ this.removeEventListener("open", this.#events.open);
+ }
+ const listener = webidl.converters.EventHandlerNonNull(fn);
+ if (listener !== null) {
+ this.addEventListener("open", listener);
+ this.#events.open = fn;
+ } else {
+ this.#events.open = null;
+ }
+ }
+ get onmessage() {
+ return this.#events.message;
+ }
+ set onmessage(fn) {
+ if (this.#events.message) {
+ this.removeEventListener("message", this.#events.message);
+ }
+ const listener = webidl.converters.EventHandlerNonNull(fn);
+ if (listener !== null) {
+ this.addEventListener("message", listener);
+ this.#events.message = fn;
+ } else {
+ this.#events.message = null;
+ }
+ }
+ get onerror() {
+ return this.#events.error;
+ }
+ set onerror(fn) {
+ if (this.#events.error) {
+ this.removeEventListener("error", this.#events.error);
+ }
+ const listener = webidl.converters.EventHandlerNonNull(fn);
+ if (listener !== null) {
+ this.addEventListener("error", listener);
+ this.#events.error = fn;
+ } else {
+ this.#events.error = null;
+ }
+ }
+ };
+ var constantsPropertyDescriptors = {
+ CONNECTING: {
+ __proto__: null,
+ configurable: false,
+ enumerable: true,
+ value: CONNECTING,
+ writable: false
+ },
+ OPEN: {
+ __proto__: null,
+ configurable: false,
+ enumerable: true,
+ value: OPEN,
+ writable: false
+ },
+ CLOSED: {
+ __proto__: null,
+ configurable: false,
+ enumerable: true,
+ value: CLOSED,
+ writable: false
+ }
+ };
+ Object.defineProperties(EventSource, constantsPropertyDescriptors);
+ Object.defineProperties(EventSource.prototype, constantsPropertyDescriptors);
+ Object.defineProperties(EventSource.prototype, {
+ close: kEnumerableProperty,
+ onerror: kEnumerableProperty,
+ onmessage: kEnumerableProperty,
+ onopen: kEnumerableProperty,
+ readyState: kEnumerableProperty,
+ url: kEnumerableProperty,
+ withCredentials: kEnumerableProperty
+ });
+ webidl.converters.EventSourceInitDict = webidl.dictionaryConverter([
+ {
+ key: "withCredentials",
+ converter: webidl.converters.boolean,
+ defaultValue: /* @__PURE__ */ __name(() => false, "defaultValue")
+ },
+ {
+ key: "dispatcher",
+ // undici only
+ converter: webidl.converters.any
+ },
+ {
+ key: "node",
+ // undici only
+ converter: webidl.dictionaryConverter([
+ {
+ key: "reconnectionTime",
+ converter: webidl.converters["unsigned long"],
+ defaultValue: /* @__PURE__ */ __name(() => defaultReconnectionTime, "defaultValue")
+ },
+ {
+ key: "dispatcher",
+ converter: webidl.converters.any
+ }
+ ]),
+ defaultValue: /* @__PURE__ */ __name(() => ({}), "defaultValue")
+ }
+ ]);
+ module2.exports = {
+ EventSource,
+ defaultReconnectionTime
+ };
+ }
+});
+
+// node_modules/undici/index.js
+var require_undici = __commonJS({
+ "node_modules/undici/index.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var Client = require_client();
+ var Dispatcher = require_dispatcher();
+ var Pool = require_pool();
+ var BalancedPool = require_balanced_pool();
+ var RoundRobinPool = require_round_robin_pool();
+ var Agent2 = require_agent();
+ var ProxyAgent = require_proxy_agent();
+ var Socks5ProxyAgent = require_socks5_proxy_agent();
+ var EnvHttpProxyAgent = require_env_http_proxy_agent();
+ var RetryAgent = require_retry_agent();
+ var H2CClient = require_h2c_client();
+ var errors = require_errors();
+ var util = require_util();
+ var { InvalidArgumentError } = errors;
+ var api = require_api();
+ var buildConnector = require_connect();
+ var MockClient = require_mock_client();
+ var { MockCallHistory, MockCallHistoryLog } = require_mock_call_history();
+ var MockAgent = require_mock_agent();
+ var MockPool = require_mock_pool();
+ var SnapshotAgent = require_snapshot_agent();
+ var mockErrors = require_mock_errors();
+ var RetryHandler = require_retry_handler();
+ var { getGlobalDispatcher, setGlobalDispatcher } = require_global2();
+ var DecoratorHandler = require_decorator_handler();
+ var RedirectHandler = require_redirect_handler();
+ Object.assign(Dispatcher.prototype, api);
+ module2.exports.Dispatcher = Dispatcher;
+ module2.exports.Client = Client;
+ module2.exports.Pool = Pool;
+ module2.exports.BalancedPool = BalancedPool;
+ module2.exports.RoundRobinPool = RoundRobinPool;
+ module2.exports.Agent = Agent2;
+ module2.exports.ProxyAgent = ProxyAgent;
+ module2.exports.Socks5ProxyAgent = Socks5ProxyAgent;
+ module2.exports.EnvHttpProxyAgent = EnvHttpProxyAgent;
+ module2.exports.RetryAgent = RetryAgent;
+ module2.exports.H2CClient = H2CClient;
+ module2.exports.RetryHandler = RetryHandler;
+ module2.exports.DecoratorHandler = DecoratorHandler;
+ module2.exports.RedirectHandler = RedirectHandler;
+ module2.exports.interceptors = {
+ redirect: require_redirect(),
+ responseError: require_response_error(),
+ retry: require_retry(),
+ dump: require_dump(),
+ dns: require_dns(),
+ cache: require_cache2(),
+ decompress: require_decompress(),
+ deduplicate: require_deduplicate()
+ };
+ module2.exports.cacheStores = {
+ MemoryCacheStore: require_memory_cache_store()
+ };
+ var SqliteCacheStore = require_sqlite_cache_store();
+ module2.exports.cacheStores.SqliteCacheStore = SqliteCacheStore;
+ module2.exports.buildConnector = buildConnector;
+ module2.exports.errors = errors;
+ module2.exports.util = {
+ parseHeaders: util.parseHeaders,
+ headerNameToString: util.headerNameToString
+ };
+ function makeDispatcher(fn) {
+ return (url2, opts, handler) => {
+ if (typeof opts === "function") {
+ handler = opts;
+ opts = null;
+ }
+ if (!url2 || typeof url2 !== "string" && typeof url2 !== "object" && !(url2 instanceof URL)) {
+ throw new InvalidArgumentError("invalid url");
+ }
+ if (opts != null && typeof opts !== "object") {
+ throw new InvalidArgumentError("invalid opts");
+ }
+ if (opts && opts.path != null) {
+ if (typeof opts.path !== "string") {
+ throw new InvalidArgumentError("invalid opts.path");
+ }
+ let path27 = opts.path;
+ if (!opts.path.startsWith("/")) {
+ path27 = `/${path27}`;
+ }
+ url2 = new URL(util.parseOrigin(url2).origin + path27);
+ } else {
+ if (!opts) {
+ opts = typeof url2 === "object" ? url2 : {};
+ }
+ url2 = util.parseURL(url2);
+ }
+ const { agent, dispatcher = getGlobalDispatcher() } = opts;
+ if (agent) {
+ throw new InvalidArgumentError("unsupported opts.agent. Did you mean opts.client?");
+ }
+ return fn.call(dispatcher, {
+ ...opts,
+ origin: url2.origin,
+ path: url2.search ? `${url2.pathname}${url2.search}` : url2.pathname,
+ method: opts.method || (opts.body ? "PUT" : "GET")
+ }, handler);
+ };
+ }
+ __name(makeDispatcher, "makeDispatcher");
+ module2.exports.setGlobalDispatcher = setGlobalDispatcher;
+ module2.exports.getGlobalDispatcher = getGlobalDispatcher;
+ var fetchImpl = require_fetch().fetch;
+ var currentFilename = typeof __filename !== "undefined" ? __filename : void 0;
+ function appendFetchStackTrace(err, filename) {
+ if (!err || typeof err !== "object") {
+ return;
+ }
+ const stack = typeof err.stack === "string" ? err.stack : "";
+ const normalizedFilename = filename.replace(/\\/g, "/");
+ if (stack && (stack.includes(filename) || stack.includes(normalizedFilename))) {
+ return;
+ }
+ const capture = {};
+ Error.captureStackTrace(capture, appendFetchStackTrace);
+ if (!capture.stack) {
+ return;
+ }
+ const captureLines = capture.stack.split("\n").slice(1).join("\n");
+ err.stack = stack ? `${stack}
+${captureLines}` : capture.stack;
+ }
+ __name(appendFetchStackTrace, "appendFetchStackTrace");
+ module2.exports.fetch = /* @__PURE__ */ __name(function fetch2(init, options2 = void 0) {
+ return fetchImpl(init, options2).catch((err) => {
+ if (currentFilename) {
+ appendFetchStackTrace(err, currentFilename);
+ } else if (err && typeof err === "object") {
+ Error.captureStackTrace(err, module2.exports.fetch);
+ }
+ throw err;
+ });
+ }, "fetch");
+ module2.exports.Headers = require_headers().Headers;
+ module2.exports.Response = require_response().Response;
+ module2.exports.Request = require_request2().Request;
+ module2.exports.FormData = require_formdata().FormData;
+ var { setGlobalOrigin, getGlobalOrigin } = require_global();
+ module2.exports.setGlobalOrigin = setGlobalOrigin;
+ module2.exports.getGlobalOrigin = getGlobalOrigin;
+ var { CacheStorage } = require_cachestorage();
+ var { kConstruct } = require_symbols();
+ module2.exports.caches = new CacheStorage(kConstruct);
+ var { deleteCookie, getCookies, getSetCookies, setCookie, parseCookie } = require_cookies();
+ module2.exports.deleteCookie = deleteCookie;
+ module2.exports.getCookies = getCookies;
+ module2.exports.getSetCookies = getSetCookies;
+ module2.exports.setCookie = setCookie;
+ module2.exports.parseCookie = parseCookie;
+ var { parseMIMEType, serializeAMimeType } = require_data_url();
+ module2.exports.parseMIMEType = parseMIMEType;
+ module2.exports.serializeAMimeType = serializeAMimeType;
+ var { CloseEvent, ErrorEvent, MessageEvent } = require_events();
+ var { WebSocket, ping } = require_websocket();
+ module2.exports.WebSocket = WebSocket;
+ module2.exports.CloseEvent = CloseEvent;
+ module2.exports.ErrorEvent = ErrorEvent;
+ module2.exports.MessageEvent = MessageEvent;
+ module2.exports.ping = ping;
+ module2.exports.WebSocketStream = require_websocketstream().WebSocketStream;
+ module2.exports.WebSocketError = require_websocketerror().WebSocketError;
+ module2.exports.request = makeDispatcher(api.request);
+ module2.exports.stream = makeDispatcher(api.stream);
+ module2.exports.pipeline = makeDispatcher(api.pipeline);
+ module2.exports.connect = makeDispatcher(api.connect);
+ module2.exports.upgrade = makeDispatcher(api.upgrade);
+ module2.exports.MockClient = MockClient;
+ module2.exports.MockCallHistory = MockCallHistory;
+ module2.exports.MockCallHistoryLog = MockCallHistoryLog;
+ module2.exports.MockPool = MockPool;
+ module2.exports.MockAgent = MockAgent;
+ module2.exports.SnapshotAgent = SnapshotAgent;
+ module2.exports.mockErrors = mockErrors;
+ var { EventSource } = require_eventsource();
+ module2.exports.EventSource = EventSource;
+ function install() {
+ globalThis.fetch = module2.exports.fetch;
+ globalThis.Headers = module2.exports.Headers;
+ globalThis.Response = module2.exports.Response;
+ globalThis.Request = module2.exports.Request;
+ globalThis.FormData = module2.exports.FormData;
+ globalThis.WebSocket = module2.exports.WebSocket;
+ globalThis.CloseEvent = module2.exports.CloseEvent;
+ globalThis.ErrorEvent = module2.exports.ErrorEvent;
+ globalThis.MessageEvent = module2.exports.MessageEvent;
+ globalThis.EventSource = module2.exports.EventSource;
+ }
+ __name(install, "install");
+ module2.exports.install = install;
+ }
+});
+
+// node_modules/react/cjs/react-jsx-runtime.production.js
+var require_react_jsx_runtime_production = __commonJS({
+ "node_modules/react/cjs/react-jsx-runtime.production.js"(exports2) {
+ "use strict";
+ init_esbuild_shims();
+ var REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element");
+ var REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment");
+ function jsxProd(type2, config2, maybeKey) {
+ var key = null;
+ void 0 !== maybeKey && (key = "" + maybeKey);
+ void 0 !== config2.key && (key = "" + config2.key);
+ if ("key" in config2) {
+ maybeKey = {};
+ for (var propName in config2)
+ "key" !== propName && (maybeKey[propName] = config2[propName]);
+ } else maybeKey = config2;
+ config2 = maybeKey.ref;
+ return {
+ $$typeof: REACT_ELEMENT_TYPE,
+ type: type2,
+ key,
+ ref: void 0 !== config2 ? config2 : null,
+ props: maybeKey
+ };
+ }
+ __name(jsxProd, "jsxProd");
+ exports2.Fragment = REACT_FRAGMENT_TYPE;
+ exports2.jsx = jsxProd;
+ exports2.jsxs = jsxProd;
+ }
+});
+
+// node_modules/react/jsx-runtime.js
+var require_jsx_runtime = __commonJS({
+ "node_modules/react/jsx-runtime.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ if (true) {
+ module2.exports = require_react_jsx_runtime_production();
+ } else {
+ module2.exports = null;
+ }
+ }
+});
+
+// packages/cli/node_modules/ignore/index.js
+var require_ignore2 = __commonJS({
+ "packages/cli/node_modules/ignore/index.js"(exports2, module2) {
+ init_esbuild_shims();
+ function makeArray(subject) {
+ return Array.isArray(subject) ? subject : [subject];
+ }
+ __name(makeArray, "makeArray");
+ var UNDEFINED = void 0;
+ var EMPTY2 = "";
+ var SPACE = " ";
+ var ESCAPE2 = "\\";
+ var REGEX_TEST_BLANK_LINE = /^\s+$/;
+ var REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/;
+ var REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
+ var REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
+ var REGEX_SPLITALL_CRLF = /\r?\n/g;
+ var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
+ var REGEX_TEST_TRAILING_SLASH = /\/$/;
+ var SLASH = "/";
+ var TMP_KEY_IGNORE = "node-ignore";
+ if (typeof Symbol !== "undefined") {
+ TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
+ }
+ var KEY_IGNORE = TMP_KEY_IGNORE;
+ var define2 = /* @__PURE__ */ __name((object2, key, value) => {
+ Object.defineProperty(object2, key, { value });
+ return value;
+ }, "define");
+ var REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g;
+ var RETURN_FALSE = /* @__PURE__ */ __name(() => false, "RETURN_FALSE");
+ var sanitizeRange = /* @__PURE__ */ __name((range) => range.replace(
+ REGEX_REGEXP_RANGE,
+ (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) ? match : EMPTY2
+ ), "sanitizeRange");
+ var cleanRangeBackSlash = /* @__PURE__ */ __name((slashes) => {
+ const { length } = slashes;
+ return slashes.slice(0, length - length % 2);
+ }, "cleanRangeBackSlash");
+ var REPLACERS = [
+ [
+ // Remove BOM
+ // TODO:
+ // Other similar zero-width characters?
+ /^\uFEFF/,
+ () => EMPTY2
+ ],
+ // > Trailing spaces are ignored unless they are quoted with backslash ("\")
+ [
+ // (a\ ) -> (a )
+ // (a ) -> (a)
+ // (a ) -> (a)
+ // (a \ ) -> (a )
+ /((?:\\\\)*?)(\\?\s+)$/,
+ (_, m1, m2) => m1 + (m2.indexOf("\\") === 0 ? SPACE : EMPTY2)
+ ],
+ // Replace (\ ) with ' '
+ // (\ ) -> ' '
+ // (\\ ) -> '\\ '
+ // (\\\ ) -> '\\ '
+ [
+ /(\\+?)\s/g,
+ (_, m1) => {
+ const { length } = m1;
+ return m1.slice(0, length - length % 2) + SPACE;
+ }
+ ],
+ // Escape metacharacters
+ // which is written down by users but means special for regular expressions.
+ // > There are 12 characters with special meanings:
+ // > - the backslash \,
+ // > - the caret ^,
+ // > - the dollar sign $,
+ // > - the period or dot .,
+ // > - the vertical bar or pipe symbol |,
+ // > - the question mark ?,
+ // > - the asterisk or star *,
+ // > - the plus sign +,
+ // > - the opening parenthesis (,
+ // > - the closing parenthesis ),
+ // > - and the opening square bracket [,
+ // > - the opening curly brace {,
+ // > These special characters are often called "metacharacters".
+ [
+ /[\\$.|*+(){^]/g,
+ (match) => `\\${match}`
+ ],
+ [
+ // > a question mark (?) matches a single character
+ /(?!\\)\?/g,
+ () => "[^/]"
+ ],
+ // leading slash
+ [
+ // > A leading slash matches the beginning of the pathname.
+ // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
+ // A leading slash matches the beginning of the pathname
+ /^\//,
+ () => "^"
+ ],
+ // replace special metacharacter slash after the leading slash
+ [
+ /\//g,
+ () => "\\/"
+ ],
+ [
+ // > A leading "**" followed by a slash means match in all directories.
+ // > For example, "**/foo" matches file or directory "foo" anywhere,
+ // > the same as pattern "foo".
+ // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
+ // > under directory "foo".
+ // Notice that the '*'s have been replaced as '\\*'
+ /^\^*\\\*\\\*\\\//,
+ // '**/foo' <-> 'foo'
+ () => "^(?:.*\\/)?"
+ ],
+ // starting
+ [
+ // there will be no leading '/'
+ // (which has been replaced by section "leading slash")
+ // If starts with '**', adding a '^' to the regular expression also works
+ /^(?=[^^])/,
+ /* @__PURE__ */ __name(function startingReplacer() {
+ return !/\/(?!$)/.test(this) ? "(?:^|\\/)" : "^";
+ }, "startingReplacer")
+ ],
+ // two globstars
+ [
+ // Use lookahead assertions so that we could match more than one `'/**'`
+ /\\\/\\\*\\\*(?=\\\/|$)/g,
+ // Zero, one or several directories
+ // should not use '*', or it will be replaced by the next replacer
+ // Check if it is not the last `'/**'`
+ (_, index, str3) => index + 6 < str3.length ? "(?:\\/[^\\/]+)*" : "\\/.+"
+ ],
+ // normal intermediate wildcards
+ [
+ // Never replace escaped '*'
+ // ignore rule '\*' will match the path '*'
+ // 'abc.*/' -> go
+ // 'abc.*' -> skip this rule,
+ // coz trailing single wildcard will be handed by [trailing wildcard]
+ /(^|[^\\]+)(\\\*)+(?=.+)/g,
+ // '*.js' matches '.js'
+ // '*.js' doesn't match 'abc'
+ (_, p1, p2) => {
+ const unescaped = p2.replace(/\\\*/g, "[^\\/]*");
+ return p1 + unescaped;
+ }
+ ],
+ [
+ // unescape, revert step 3 except for back slash
+ // For example, if a user escape a '\\*',
+ // after step 3, the result will be '\\\\\\*'
+ /\\\\\\(?=[$.|*+(){^])/g,
+ () => ESCAPE2
+ ],
+ [
+ // '\\\\' -> '\\'
+ /\\\\/g,
+ () => ESCAPE2
+ ],
+ [
+ // > The range notation, e.g. [a-zA-Z],
+ // > can be used to match one of the characters in a range.
+ // `\` is escaped by step 3
+ /(\\)?\[([^\]/]*?)(\\*)($|\])/g,
+ (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE2 ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` : close === "]" ? endEscape.length % 2 === 0 ? `[${sanitizeRange(range)}${endEscape}]` : "[]" : "[]"
+ ],
+ // ending
+ [
+ // 'js' will not match 'js.'
+ // 'ab' will not match 'abc'
+ /(?:[^*])$/,
+ // WTF!
+ // https://git-scm.com/docs/gitignore
+ // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)
+ // which re-fixes #24, #38
+ // > If there is a separator at the end of the pattern then the pattern
+ // > will only match directories, otherwise the pattern can match both
+ // > files and directories.
+ // 'js*' will not match 'a.js'
+ // 'js/' will not match 'a.js'
+ // 'js' will match 'a.js' and 'a.js/'
+ (match) => /\/$/.test(match) ? `${match}$` : `${match}(?=$|\\/$)`
+ ]
+ ];
+ var REGEX_REPLACE_TRAILING_WILDCARD = /(^|\\\/)?\\\*$/;
+ var MODE_IGNORE = "regex";
+ var MODE_CHECK_IGNORE = "checkRegex";
+ var UNDERSCORE = "_";
+ var TRAILING_WILD_CARD_REPLACERS = {
+ [MODE_IGNORE](_, p1) {
+ const prefix = p1 ? `${p1}[^/]+` : "[^/]*";
+ return `${prefix}(?=$|\\/$)`;
+ },
+ [MODE_CHECK_IGNORE](_, p1) {
+ const prefix = p1 ? `${p1}[^/]*` : "[^/]*";
+ return `${prefix}(?=$|\\/$)`;
+ }
+ };
+ var makeRegexPrefix = /* @__PURE__ */ __name((pattern) => REPLACERS.reduce(
+ (prev, [matcher, replacer]) => prev.replace(matcher, replacer.bind(pattern)),
+ pattern
+ ), "makeRegexPrefix");
+ var isString = /* @__PURE__ */ __name((subject) => typeof subject === "string", "isString");
+ var checkPattern = /* @__PURE__ */ __name((pattern) => pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) && pattern.indexOf("#") !== 0, "checkPattern");
+ var splitPattern = /* @__PURE__ */ __name((pattern) => pattern.split(REGEX_SPLITALL_CRLF).filter(Boolean), "splitPattern");
+ var IgnoreRule = class {
+ static {
+ __name(this, "IgnoreRule");
+ }
+ constructor(pattern, mark, body, ignoreCase, negative, prefix) {
+ this.pattern = pattern;
+ this.mark = mark;
+ this.negative = negative;
+ define2(this, "body", body);
+ define2(this, "ignoreCase", ignoreCase);
+ define2(this, "regexPrefix", prefix);
+ }
+ get regex() {
+ const key = UNDERSCORE + MODE_IGNORE;
+ if (this[key]) {
+ return this[key];
+ }
+ return this._make(MODE_IGNORE, key);
+ }
+ get checkRegex() {
+ const key = UNDERSCORE + MODE_CHECK_IGNORE;
+ if (this[key]) {
+ return this[key];
+ }
+ return this._make(MODE_CHECK_IGNORE, key);
+ }
+ _make(mode, key) {
+ const str3 = this.regexPrefix.replace(
+ REGEX_REPLACE_TRAILING_WILDCARD,
+ // It does not need to bind pattern
+ TRAILING_WILD_CARD_REPLACERS[mode]
+ );
+ const regex2 = this.ignoreCase ? new RegExp(str3, "i") : new RegExp(str3);
+ return define2(this, key, regex2);
+ }
+ };
+ var createRule = /* @__PURE__ */ __name(({
+ pattern,
+ mark
+ }, ignoreCase) => {
+ let negative = false;
+ let body = pattern;
+ if (body.indexOf("!") === 0) {
+ negative = true;
+ body = body.substr(1);
+ }
+ body = body.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, "!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, "#");
+ const regexPrefix = makeRegexPrefix(body);
+ return new IgnoreRule(
+ pattern,
+ mark,
+ body,
+ ignoreCase,
+ negative,
+ regexPrefix
+ );
+ }, "createRule");
+ var RuleManager = class {
+ static {
+ __name(this, "RuleManager");
+ }
+ constructor(ignoreCase) {
+ this._ignoreCase = ignoreCase;
+ this._rules = [];
+ }
+ _add(pattern) {
+ if (pattern && pattern[KEY_IGNORE]) {
+ this._rules = this._rules.concat(pattern._rules._rules);
+ this._added = true;
+ return;
+ }
+ if (isString(pattern)) {
+ pattern = {
+ pattern
+ };
+ }
+ if (checkPattern(pattern.pattern)) {
+ const rule = createRule(pattern, this._ignoreCase);
+ this._added = true;
+ this._rules.push(rule);
+ }
+ }
+ // @param {Array | string | Ignore} pattern
+ add(pattern) {
+ this._added = false;
+ makeArray(
+ isString(pattern) ? splitPattern(pattern) : pattern
+ ).forEach(this._add, this);
+ return this._added;
+ }
+ // Test one single path without recursively checking parent directories
+ //
+ // - checkUnignored `boolean` whether should check if the path is unignored,
+ // setting `checkUnignored` to `false` could reduce additional
+ // path matching.
+ // - check `string` either `MODE_IGNORE` or `MODE_CHECK_IGNORE`
+ // @returns {TestResult} true if a file is ignored
+ test(path27, checkUnignored, mode) {
+ let ignored = false;
+ let unignored = false;
+ let matchedRule;
+ this._rules.forEach((rule) => {
+ const { negative } = rule;
+ if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) {
+ return;
+ }
+ const matched = rule[mode].test(path27);
+ if (!matched) {
+ return;
+ }
+ ignored = !negative;
+ unignored = negative;
+ matchedRule = negative ? UNDEFINED : rule;
+ });
+ const ret = {
+ ignored,
+ unignored
+ };
+ if (matchedRule) {
+ ret.rule = matchedRule;
+ }
+ return ret;
+ }
+ };
+ var throwError = /* @__PURE__ */ __name((message, Ctor) => {
+ throw new Ctor(message);
+ }, "throwError");
+ var checkPath = /* @__PURE__ */ __name((path27, originalPath, doThrow) => {
+ if (!isString(path27)) {
+ return doThrow(
+ `path must be a string, but got \`${originalPath}\``,
+ TypeError
+ );
+ }
+ if (!path27) {
+ return doThrow(`path must not be empty`, TypeError);
+ }
+ if (checkPath.isNotRelative(path27)) {
+ const r = "`path.relative()`d";
+ return doThrow(
+ `path should be a ${r} string, but got "${originalPath}"`,
+ RangeError
+ );
+ }
+ return true;
+ }, "checkPath");
+ var isNotRelative = /* @__PURE__ */ __name((path27) => REGEX_TEST_INVALID_PATH.test(path27), "isNotRelative");
+ checkPath.isNotRelative = isNotRelative;
+ checkPath.convert = (p) => p;
+ var Ignore = class {
+ static {
+ __name(this, "Ignore");
+ }
+ constructor({
+ ignorecase = true,
+ ignoreCase = ignorecase,
+ allowRelativePaths = false
+ } = {}) {
+ define2(this, KEY_IGNORE, true);
+ this._rules = new RuleManager(ignoreCase);
+ this._strictPathCheck = !allowRelativePaths;
+ this._initCache();
+ }
+ _initCache() {
+ this._ignoreCache = /* @__PURE__ */ Object.create(null);
+ this._testCache = /* @__PURE__ */ Object.create(null);
+ }
+ add(pattern) {
+ if (this._rules.add(pattern)) {
+ this._initCache();
+ }
+ return this;
+ }
+ // legacy
+ addPattern(pattern) {
+ return this.add(pattern);
+ }
+ // @returns {TestResult}
+ _test(originalPath, cache3, checkUnignored, slices) {
+ const path27 = originalPath && checkPath.convert(originalPath);
+ checkPath(
+ path27,
+ originalPath,
+ this._strictPathCheck ? throwError : RETURN_FALSE
+ );
+ return this._t(path27, cache3, checkUnignored, slices);
+ }
+ checkIgnore(path27) {
+ if (!REGEX_TEST_TRAILING_SLASH.test(path27)) {
+ return this.test(path27);
+ }
+ const slices = path27.split(SLASH).filter(Boolean);
+ slices.pop();
+ if (slices.length) {
+ const parent = this._t(
+ slices.join(SLASH) + SLASH,
+ this._testCache,
+ true,
+ slices
+ );
+ if (parent.ignored) {
+ return parent;
+ }
+ }
+ return this._rules.test(path27, false, MODE_CHECK_IGNORE);
+ }
+ _t(path27, cache3, checkUnignored, slices) {
+ if (path27 in cache3) {
+ return cache3[path27];
+ }
+ if (!slices) {
+ slices = path27.split(SLASH).filter(Boolean);
+ }
+ slices.pop();
+ if (!slices.length) {
+ return cache3[path27] = this._rules.test(path27, checkUnignored, MODE_IGNORE);
+ }
+ const parent = this._t(
+ slices.join(SLASH) + SLASH,
+ cache3,
+ checkUnignored,
+ slices
+ );
+ return cache3[path27] = parent.ignored ? parent : this._rules.test(path27, checkUnignored, MODE_IGNORE);
+ }
+ ignores(path27) {
+ return this._test(path27, this._ignoreCache, false).ignored;
+ }
+ createFilter() {
+ return (path27) => !this.ignores(path27);
+ }
+ filter(paths) {
+ return makeArray(paths).filter(this.createFilter());
+ }
+ // @returns {TestResult}
+ test(path27) {
+ return this._test(path27, this._testCache, true);
+ }
+ };
+ var factory = /* @__PURE__ */ __name((options2) => new Ignore(options2), "factory");
+ var isPathValid = /* @__PURE__ */ __name((path27) => checkPath(path27 && checkPath.convert(path27), path27, RETURN_FALSE), "isPathValid");
+ var setupWindows = /* @__PURE__ */ __name(() => {
+ const makePosix = /* @__PURE__ */ __name((str3) => /^\\\\\?\\/.test(str3) || /["<>|\u0000-\u001F]+/u.test(str3) ? str3 : str3.replace(/\\/g, "/"), "makePosix");
+ checkPath.convert = makePosix;
+ const REGEX_TEST_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
+ checkPath.isNotRelative = (path27) => REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path27) || isNotRelative(path27);
+ }, "setupWindows");
+ if (
+ // Detect `process` so that it can run in browsers.
+ typeof process !== "undefined" && process.platform === "win32"
+ ) {
+ setupWindows();
+ }
+ module2.exports = factory;
+ factory.default = factory;
+ module2.exports.isPathValid = isPathValid;
+ define2(module2.exports, /* @__PURE__ */ Symbol.for("setupWindows"), setupWindows);
+ }
+});
+
+// node_modules/tinycolor2/cjs/tinycolor.js
+var require_tinycolor = __commonJS({
+ "node_modules/tinycolor2/cjs/tinycolor.js"(exports2, module2) {
+ init_esbuild_shims();
+ (function(global2, factory) {
+ typeof exports2 === "object" && typeof module2 !== "undefined" ? module2.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, global2.tinycolor = factory());
+ })(exports2, (function() {
+ "use strict";
+ function _typeof(obj) {
+ "@babel/helpers - typeof";
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj2) {
+ return typeof obj2;
+ } : function(obj2) {
+ return obj2 && "function" == typeof Symbol && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
+ }, _typeof(obj);
+ }
+ __name(_typeof, "_typeof");
+ var trimLeft = /^\s+/;
+ var trimRight = /\s+$/;
+ function tinycolor(color, opts) {
+ color = color ? color : "";
+ opts = opts || {};
+ if (color instanceof tinycolor) {
+ return color;
+ }
+ if (!(this instanceof tinycolor)) {
+ return new tinycolor(color, opts);
+ }
+ var rgb = inputToRGB(color);
+ this._originalInput = color, this._r = rgb.r, this._g = rgb.g, this._b = rgb.b, this._a = rgb.a, this._roundA = Math.round(100 * this._a) / 100, this._format = opts.format || rgb.format;
+ this._gradientType = opts.gradientType;
+ if (this._r < 1) this._r = Math.round(this._r);
+ if (this._g < 1) this._g = Math.round(this._g);
+ if (this._b < 1) this._b = Math.round(this._b);
+ this._ok = rgb.ok;
+ }
+ __name(tinycolor, "tinycolor");
+ tinycolor.prototype = {
+ isDark: /* @__PURE__ */ __name(function isDark() {
+ return this.getBrightness() < 128;
+ }, "isDark"),
+ isLight: /* @__PURE__ */ __name(function isLight() {
+ return !this.isDark();
+ }, "isLight"),
+ isValid: /* @__PURE__ */ __name(function isValid() {
+ return this._ok;
+ }, "isValid"),
+ getOriginalInput: /* @__PURE__ */ __name(function getOriginalInput() {
+ return this._originalInput;
+ }, "getOriginalInput"),
+ getFormat: /* @__PURE__ */ __name(function getFormat() {
+ return this._format;
+ }, "getFormat"),
+ getAlpha: /* @__PURE__ */ __name(function getAlpha() {
+ return this._a;
+ }, "getAlpha"),
+ getBrightness: /* @__PURE__ */ __name(function getBrightness() {
+ var rgb = this.toRgb();
+ return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1e3;
+ }, "getBrightness"),
+ getLuminance: /* @__PURE__ */ __name(function getLuminance() {
+ var rgb = this.toRgb();
+ var RsRGB, GsRGB, BsRGB, R, G, B;
+ RsRGB = rgb.r / 255;
+ GsRGB = rgb.g / 255;
+ BsRGB = rgb.b / 255;
+ if (RsRGB <= 0.03928) R = RsRGB / 12.92;
+ else R = Math.pow((RsRGB + 0.055) / 1.055, 2.4);
+ if (GsRGB <= 0.03928) G = GsRGB / 12.92;
+ else G = Math.pow((GsRGB + 0.055) / 1.055, 2.4);
+ if (BsRGB <= 0.03928) B = BsRGB / 12.92;
+ else B = Math.pow((BsRGB + 0.055) / 1.055, 2.4);
+ return 0.2126 * R + 0.7152 * G + 0.0722 * B;
+ }, "getLuminance"),
+ setAlpha: /* @__PURE__ */ __name(function setAlpha(value) {
+ this._a = boundAlpha(value);
+ this._roundA = Math.round(100 * this._a) / 100;
+ return this;
+ }, "setAlpha"),
+ toHsv: /* @__PURE__ */ __name(function toHsv() {
+ var hsv = rgbToHsv(this._r, this._g, this._b);
+ return {
+ h: hsv.h * 360,
+ s: hsv.s,
+ v: hsv.v,
+ a: this._a
+ };
+ }, "toHsv"),
+ toHsvString: /* @__PURE__ */ __name(function toHsvString() {
+ var hsv = rgbToHsv(this._r, this._g, this._b);
+ var h = Math.round(hsv.h * 360), s = Math.round(hsv.s * 100), v = Math.round(hsv.v * 100);
+ return this._a == 1 ? "hsv(" + h + ", " + s + "%, " + v + "%)" : "hsva(" + h + ", " + s + "%, " + v + "%, " + this._roundA + ")";
+ }, "toHsvString"),
+ toHsl: /* @__PURE__ */ __name(function toHsl() {
+ var hsl = rgbToHsl(this._r, this._g, this._b);
+ return {
+ h: hsl.h * 360,
+ s: hsl.s,
+ l: hsl.l,
+ a: this._a
+ };
+ }, "toHsl"),
+ toHslString: /* @__PURE__ */ __name(function toHslString() {
+ var hsl = rgbToHsl(this._r, this._g, this._b);
+ var h = Math.round(hsl.h * 360), s = Math.round(hsl.s * 100), l = Math.round(hsl.l * 100);
+ return this._a == 1 ? "hsl(" + h + ", " + s + "%, " + l + "%)" : "hsla(" + h + ", " + s + "%, " + l + "%, " + this._roundA + ")";
+ }, "toHslString"),
+ toHex: /* @__PURE__ */ __name(function toHex(allow3Char) {
+ return rgbToHex(this._r, this._g, this._b, allow3Char);
+ }, "toHex"),
+ toHexString: /* @__PURE__ */ __name(function toHexString(allow3Char) {
+ return "#" + this.toHex(allow3Char);
+ }, "toHexString"),
+ toHex8: /* @__PURE__ */ __name(function toHex8(allow4Char) {
+ return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char);
+ }, "toHex8"),
+ toHex8String: /* @__PURE__ */ __name(function toHex8String(allow4Char) {
+ return "#" + this.toHex8(allow4Char);
+ }, "toHex8String"),
+ toRgb: /* @__PURE__ */ __name(function toRgb() {
+ return {
+ r: Math.round(this._r),
+ g: Math.round(this._g),
+ b: Math.round(this._b),
+ a: this._a
+ };
+ }, "toRgb"),
+ toRgbString: /* @__PURE__ */ __name(function toRgbString() {
+ return this._a == 1 ? "rgb(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ")" : "rgba(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ", " + this._roundA + ")";
+ }, "toRgbString"),
+ toPercentageRgb: /* @__PURE__ */ __name(function toPercentageRgb() {
+ return {
+ r: Math.round(bound01(this._r, 255) * 100) + "%",
+ g: Math.round(bound01(this._g, 255) * 100) + "%",
+ b: Math.round(bound01(this._b, 255) * 100) + "%",
+ a: this._a
+ };
+ }, "toPercentageRgb"),
+ toPercentageRgbString: /* @__PURE__ */ __name(function toPercentageRgbString() {
+ return this._a == 1 ? "rgb(" + Math.round(bound01(this._r, 255) * 100) + "%, " + Math.round(bound01(this._g, 255) * 100) + "%, " + Math.round(bound01(this._b, 255) * 100) + "%)" : "rgba(" + Math.round(bound01(this._r, 255) * 100) + "%, " + Math.round(bound01(this._g, 255) * 100) + "%, " + Math.round(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")";
+ }, "toPercentageRgbString"),
+ toName: /* @__PURE__ */ __name(function toName() {
+ if (this._a === 0) {
+ return "transparent";
+ }
+ if (this._a < 1) {
+ return false;
+ }
+ return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false;
+ }, "toName"),
+ toFilter: /* @__PURE__ */ __name(function toFilter(secondColor) {
+ var hex8String = "#" + rgbaToArgbHex(this._r, this._g, this._b, this._a);
+ var secondHex8String = hex8String;
+ var gradientType = this._gradientType ? "GradientType = 1, " : "";
+ if (secondColor) {
+ var s = tinycolor(secondColor);
+ secondHex8String = "#" + rgbaToArgbHex(s._r, s._g, s._b, s._a);
+ }
+ return "progid:DXImageTransform.Microsoft.gradient(" + gradientType + "startColorstr=" + hex8String + ",endColorstr=" + secondHex8String + ")";
+ }, "toFilter"),
+ toString: /* @__PURE__ */ __name(function toString(format3) {
+ var formatSet = !!format3;
+ format3 = format3 || this._format;
+ var formattedString = false;
+ var hasAlpha = this._a < 1 && this._a >= 0;
+ var needsAlphaFormat = !formatSet && hasAlpha && (format3 === "hex" || format3 === "hex6" || format3 === "hex3" || format3 === "hex4" || format3 === "hex8" || format3 === "name");
+ if (needsAlphaFormat) {
+ if (format3 === "name" && this._a === 0) {
+ return this.toName();
+ }
+ return this.toRgbString();
+ }
+ if (format3 === "rgb") {
+ formattedString = this.toRgbString();
+ }
+ if (format3 === "prgb") {
+ formattedString = this.toPercentageRgbString();
+ }
+ if (format3 === "hex" || format3 === "hex6") {
+ formattedString = this.toHexString();
+ }
+ if (format3 === "hex3") {
+ formattedString = this.toHexString(true);
+ }
+ if (format3 === "hex4") {
+ formattedString = this.toHex8String(true);
+ }
+ if (format3 === "hex8") {
+ formattedString = this.toHex8String();
+ }
+ if (format3 === "name") {
+ formattedString = this.toName();
+ }
+ if (format3 === "hsl") {
+ formattedString = this.toHslString();
+ }
+ if (format3 === "hsv") {
+ formattedString = this.toHsvString();
+ }
+ return formattedString || this.toHexString();
+ }, "toString"),
+ clone: /* @__PURE__ */ __name(function clone2() {
+ return tinycolor(this.toString());
+ }, "clone"),
+ _applyModification: /* @__PURE__ */ __name(function _applyModification(fn, args) {
+ var color = fn.apply(null, [this].concat([].slice.call(args)));
+ this._r = color._r;
+ this._g = color._g;
+ this._b = color._b;
+ this.setAlpha(color._a);
+ return this;
+ }, "_applyModification"),
+ lighten: /* @__PURE__ */ __name(function lighten() {
+ return this._applyModification(_lighten, arguments);
+ }, "lighten"),
+ brighten: /* @__PURE__ */ __name(function brighten() {
+ return this._applyModification(_brighten, arguments);
+ }, "brighten"),
+ darken: /* @__PURE__ */ __name(function darken() {
+ return this._applyModification(_darken, arguments);
+ }, "darken"),
+ desaturate: /* @__PURE__ */ __name(function desaturate() {
+ return this._applyModification(_desaturate, arguments);
+ }, "desaturate"),
+ saturate: /* @__PURE__ */ __name(function saturate() {
+ return this._applyModification(_saturate, arguments);
+ }, "saturate"),
+ greyscale: /* @__PURE__ */ __name(function greyscale() {
+ return this._applyModification(_greyscale, arguments);
+ }, "greyscale"),
+ spin: /* @__PURE__ */ __name(function spin() {
+ return this._applyModification(_spin, arguments);
+ }, "spin"),
+ _applyCombination: /* @__PURE__ */ __name(function _applyCombination(fn, args) {
+ return fn.apply(null, [this].concat([].slice.call(args)));
+ }, "_applyCombination"),
+ analogous: /* @__PURE__ */ __name(function analogous() {
+ return this._applyCombination(_analogous, arguments);
+ }, "analogous"),
+ complement: /* @__PURE__ */ __name(function complement() {
+ return this._applyCombination(_complement, arguments);
+ }, "complement"),
+ monochromatic: /* @__PURE__ */ __name(function monochromatic() {
+ return this._applyCombination(_monochromatic, arguments);
+ }, "monochromatic"),
+ splitcomplement: /* @__PURE__ */ __name(function splitcomplement() {
+ return this._applyCombination(_splitcomplement, arguments);
+ }, "splitcomplement"),
+ // Disabled until https://github.com/bgrins/TinyColor/issues/254
+ // polyad: function (number) {
+ // return this._applyCombination(polyad, [number]);
+ // },
+ triad: /* @__PURE__ */ __name(function triad() {
+ return this._applyCombination(polyad, [3]);
+ }, "triad"),
+ tetrad: /* @__PURE__ */ __name(function tetrad() {
+ return this._applyCombination(polyad, [4]);
+ }, "tetrad")
+ };
+ tinycolor.fromRatio = function(color, opts) {
+ if (_typeof(color) == "object") {
+ var newColor = {};
+ for (var i in color) {
+ if (color.hasOwnProperty(i)) {
+ if (i === "a") {
+ newColor[i] = color[i];
+ } else {
+ newColor[i] = convertToPercentage(color[i]);
+ }
+ }
+ }
+ color = newColor;
+ }
+ return tinycolor(color, opts);
+ };
+ function inputToRGB(color) {
+ var rgb = {
+ r: 0,
+ g: 0,
+ b: 0
+ };
+ var a = 1;
+ var s = null;
+ var v = null;
+ var l = null;
+ var ok = false;
+ var format3 = false;
+ if (typeof color == "string") {
+ color = stringInputToObject(color);
+ }
+ if (_typeof(color) == "object") {
+ if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) {
+ rgb = rgbToRgb(color.r, color.g, color.b);
+ ok = true;
+ format3 = String(color.r).substr(-1) === "%" ? "prgb" : "rgb";
+ } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) {
+ s = convertToPercentage(color.s);
+ v = convertToPercentage(color.v);
+ rgb = hsvToRgb(color.h, s, v);
+ ok = true;
+ format3 = "hsv";
+ } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) {
+ s = convertToPercentage(color.s);
+ l = convertToPercentage(color.l);
+ rgb = hslToRgb(color.h, s, l);
+ ok = true;
+ format3 = "hsl";
+ }
+ if (color.hasOwnProperty("a")) {
+ a = color.a;
+ }
+ }
+ a = boundAlpha(a);
+ return {
+ ok,
+ format: color.format || format3,
+ r: Math.min(255, Math.max(rgb.r, 0)),
+ g: Math.min(255, Math.max(rgb.g, 0)),
+ b: Math.min(255, Math.max(rgb.b, 0)),
+ a
+ };
+ }
+ __name(inputToRGB, "inputToRGB");
+ function rgbToRgb(r, g, b) {
+ return {
+ r: bound01(r, 255) * 255,
+ g: bound01(g, 255) * 255,
+ b: bound01(b, 255) * 255
+ };
+ }
+ __name(rgbToRgb, "rgbToRgb");
+ function rgbToHsl(r, g, b) {
+ r = bound01(r, 255);
+ g = bound01(g, 255);
+ b = bound01(b, 255);
+ var max = Math.max(r, g, b), min = Math.min(r, g, b);
+ var h, s, l = (max + min) / 2;
+ if (max == min) {
+ h = s = 0;
+ } else {
+ var d = max - min;
+ s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
+ switch (max) {
+ case r:
+ h = (g - b) / d + (g < b ? 6 : 0);
+ break;
+ case g:
+ h = (b - r) / d + 2;
+ break;
+ case b:
+ h = (r - g) / d + 4;
+ break;
+ }
+ h /= 6;
+ }
+ return {
+ h,
+ s,
+ l
+ };
+ }
+ __name(rgbToHsl, "rgbToHsl");
+ function hslToRgb(h, s, l) {
+ var r, g, b;
+ h = bound01(h, 360);
+ s = bound01(s, 100);
+ l = bound01(l, 100);
+ function hue2rgb(p2, q2, t) {
+ if (t < 0) t += 1;
+ if (t > 1) t -= 1;
+ if (t < 1 / 6) return p2 + (q2 - p2) * 6 * t;
+ if (t < 1 / 2) return q2;
+ if (t < 2 / 3) return p2 + (q2 - p2) * (2 / 3 - t) * 6;
+ return p2;
+ }
+ __name(hue2rgb, "hue2rgb");
+ if (s === 0) {
+ r = g = b = l;
+ } else {
+ var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
+ var p = 2 * l - q;
+ r = hue2rgb(p, q, h + 1 / 3);
+ g = hue2rgb(p, q, h);
+ b = hue2rgb(p, q, h - 1 / 3);
+ }
+ return {
+ r: r * 255,
+ g: g * 255,
+ b: b * 255
+ };
+ }
+ __name(hslToRgb, "hslToRgb");
+ function rgbToHsv(r, g, b) {
+ r = bound01(r, 255);
+ g = bound01(g, 255);
+ b = bound01(b, 255);
+ var max = Math.max(r, g, b), min = Math.min(r, g, b);
+ var h, s, v = max;
+ var d = max - min;
+ s = max === 0 ? 0 : d / max;
+ if (max == min) {
+ h = 0;
+ } else {
+ switch (max) {
+ case r:
+ h = (g - b) / d + (g < b ? 6 : 0);
+ break;
+ case g:
+ h = (b - r) / d + 2;
+ break;
+ case b:
+ h = (r - g) / d + 4;
+ break;
+ }
+ h /= 6;
+ }
+ return {
+ h,
+ s,
+ v
+ };
+ }
+ __name(rgbToHsv, "rgbToHsv");
+ function hsvToRgb(h, s, v) {
+ h = bound01(h, 360) * 6;
+ s = bound01(s, 100);
+ v = bound01(v, 100);
+ var i = Math.floor(h), f = h - i, p = v * (1 - s), q = v * (1 - f * s), t = v * (1 - (1 - f) * s), mod = i % 6, r = [v, q, p, p, t, v][mod], g = [t, v, v, q, p, p][mod], b = [p, p, t, v, v, q][mod];
+ return {
+ r: r * 255,
+ g: g * 255,
+ b: b * 255
+ };
+ }
+ __name(hsvToRgb, "hsvToRgb");
+ function rgbToHex(r, g, b, allow3Char) {
+ var hex3 = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))];
+ if (allow3Char && hex3[0].charAt(0) == hex3[0].charAt(1) && hex3[1].charAt(0) == hex3[1].charAt(1) && hex3[2].charAt(0) == hex3[2].charAt(1)) {
+ return hex3[0].charAt(0) + hex3[1].charAt(0) + hex3[2].charAt(0);
+ }
+ return hex3.join("");
+ }
+ __name(rgbToHex, "rgbToHex");
+ function rgbaToHex(r, g, b, a, allow4Char) {
+ var hex3 = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16)), pad2(convertDecimalToHex(a))];
+ if (allow4Char && hex3[0].charAt(0) == hex3[0].charAt(1) && hex3[1].charAt(0) == hex3[1].charAt(1) && hex3[2].charAt(0) == hex3[2].charAt(1) && hex3[3].charAt(0) == hex3[3].charAt(1)) {
+ return hex3[0].charAt(0) + hex3[1].charAt(0) + hex3[2].charAt(0) + hex3[3].charAt(0);
+ }
+ return hex3.join("");
+ }
+ __name(rgbaToHex, "rgbaToHex");
+ function rgbaToArgbHex(r, g, b, a) {
+ var hex3 = [pad2(convertDecimalToHex(a)), pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))];
+ return hex3.join("");
+ }
+ __name(rgbaToArgbHex, "rgbaToArgbHex");
+ tinycolor.equals = function(color1, color2) {
+ if (!color1 || !color2) return false;
+ return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString();
+ };
+ tinycolor.random = function() {
+ return tinycolor.fromRatio({
+ r: Math.random(),
+ g: Math.random(),
+ b: Math.random()
+ });
+ };
+ function _desaturate(color, amount) {
+ amount = amount === 0 ? 0 : amount || 10;
+ var hsl = tinycolor(color).toHsl();
+ hsl.s -= amount / 100;
+ hsl.s = clamp01(hsl.s);
+ return tinycolor(hsl);
+ }
+ __name(_desaturate, "_desaturate");
+ function _saturate(color, amount) {
+ amount = amount === 0 ? 0 : amount || 10;
+ var hsl = tinycolor(color).toHsl();
+ hsl.s += amount / 100;
+ hsl.s = clamp01(hsl.s);
+ return tinycolor(hsl);
+ }
+ __name(_saturate, "_saturate");
+ function _greyscale(color) {
+ return tinycolor(color).desaturate(100);
+ }
+ __name(_greyscale, "_greyscale");
+ function _lighten(color, amount) {
+ amount = amount === 0 ? 0 : amount || 10;
+ var hsl = tinycolor(color).toHsl();
+ hsl.l += amount / 100;
+ hsl.l = clamp01(hsl.l);
+ return tinycolor(hsl);
+ }
+ __name(_lighten, "_lighten");
+ function _brighten(color, amount) {
+ amount = amount === 0 ? 0 : amount || 10;
+ var rgb = tinycolor(color).toRgb();
+ rgb.r = Math.max(0, Math.min(255, rgb.r - Math.round(255 * -(amount / 100))));
+ rgb.g = Math.max(0, Math.min(255, rgb.g - Math.round(255 * -(amount / 100))));
+ rgb.b = Math.max(0, Math.min(255, rgb.b - Math.round(255 * -(amount / 100))));
+ return tinycolor(rgb);
+ }
+ __name(_brighten, "_brighten");
+ function _darken(color, amount) {
+ amount = amount === 0 ? 0 : amount || 10;
+ var hsl = tinycolor(color).toHsl();
+ hsl.l -= amount / 100;
+ hsl.l = clamp01(hsl.l);
+ return tinycolor(hsl);
+ }
+ __name(_darken, "_darken");
+ function _spin(color, amount) {
+ var hsl = tinycolor(color).toHsl();
+ var hue = (hsl.h + amount) % 360;
+ hsl.h = hue < 0 ? 360 + hue : hue;
+ return tinycolor(hsl);
+ }
+ __name(_spin, "_spin");
+ function _complement(color) {
+ var hsl = tinycolor(color).toHsl();
+ hsl.h = (hsl.h + 180) % 360;
+ return tinycolor(hsl);
+ }
+ __name(_complement, "_complement");
+ function polyad(color, number4) {
+ if (isNaN(number4) || number4 <= 0) {
+ throw new Error("Argument to polyad must be a positive number");
+ }
+ var hsl = tinycolor(color).toHsl();
+ var result = [tinycolor(color)];
+ var step = 360 / number4;
+ for (var i = 1; i < number4; i++) {
+ result.push(tinycolor({
+ h: (hsl.h + i * step) % 360,
+ s: hsl.s,
+ l: hsl.l
+ }));
+ }
+ return result;
+ }
+ __name(polyad, "polyad");
+ function _splitcomplement(color) {
+ var hsl = tinycolor(color).toHsl();
+ var h = hsl.h;
+ return [tinycolor(color), tinycolor({
+ h: (h + 72) % 360,
+ s: hsl.s,
+ l: hsl.l
+ }), tinycolor({
+ h: (h + 216) % 360,
+ s: hsl.s,
+ l: hsl.l
+ })];
+ }
+ __name(_splitcomplement, "_splitcomplement");
+ function _analogous(color, results, slices) {
+ results = results || 6;
+ slices = slices || 30;
+ var hsl = tinycolor(color).toHsl();
+ var part = 360 / slices;
+ var ret = [tinycolor(color)];
+ for (hsl.h = (hsl.h - (part * results >> 1) + 720) % 360; --results; ) {
+ hsl.h = (hsl.h + part) % 360;
+ ret.push(tinycolor(hsl));
+ }
+ return ret;
+ }
+ __name(_analogous, "_analogous");
+ function _monochromatic(color, results) {
+ results = results || 6;
+ var hsv = tinycolor(color).toHsv();
+ var h = hsv.h, s = hsv.s, v = hsv.v;
+ var ret = [];
+ var modification = 1 / results;
+ while (results--) {
+ ret.push(tinycolor({
+ h,
+ s,
+ v
+ }));
+ v = (v + modification) % 1;
+ }
+ return ret;
+ }
+ __name(_monochromatic, "_monochromatic");
+ tinycolor.mix = function(color1, color2, amount) {
+ amount = amount === 0 ? 0 : amount || 50;
+ var rgb1 = tinycolor(color1).toRgb();
+ var rgb2 = tinycolor(color2).toRgb();
+ var p = amount / 100;
+ var rgba = {
+ r: (rgb2.r - rgb1.r) * p + rgb1.r,
+ g: (rgb2.g - rgb1.g) * p + rgb1.g,
+ b: (rgb2.b - rgb1.b) * p + rgb1.b,
+ a: (rgb2.a - rgb1.a) * p + rgb1.a
+ };
+ return tinycolor(rgba);
+ };
+ tinycolor.readability = function(color1, color2) {
+ var c1 = tinycolor(color1);
+ var c2 = tinycolor(color2);
+ return (Math.max(c1.getLuminance(), c2.getLuminance()) + 0.05) / (Math.min(c1.getLuminance(), c2.getLuminance()) + 0.05);
+ };
+ tinycolor.isReadable = function(color1, color2, wcag2) {
+ var readability = tinycolor.readability(color1, color2);
+ var wcag2Parms, out;
+ out = false;
+ wcag2Parms = validateWCAG2Parms(wcag2);
+ switch (wcag2Parms.level + wcag2Parms.size) {
+ case "AAsmall":
+ case "AAAlarge":
+ out = readability >= 4.5;
+ break;
+ case "AAlarge":
+ out = readability >= 3;
+ break;
+ case "AAAsmall":
+ out = readability >= 7;
+ break;
+ }
+ return out;
+ };
+ tinycolor.mostReadable = function(baseColor, colorList, args) {
+ var bestColor = null;
+ var bestScore = 0;
+ var readability;
+ var includeFallbackColors, level, size;
+ args = args || {};
+ includeFallbackColors = args.includeFallbackColors;
+ level = args.level;
+ size = args.size;
+ for (var i = 0; i < colorList.length; i++) {
+ readability = tinycolor.readability(baseColor, colorList[i]);
+ if (readability > bestScore) {
+ bestScore = readability;
+ bestColor = tinycolor(colorList[i]);
+ }
+ }
+ if (tinycolor.isReadable(baseColor, bestColor, {
+ level,
+ size
+ }) || !includeFallbackColors) {
+ return bestColor;
+ } else {
+ args.includeFallbackColors = false;
+ return tinycolor.mostReadable(baseColor, ["#fff", "#000"], args);
+ }
+ };
+ var names = tinycolor.names = {
+ aliceblue: "f0f8ff",
+ antiquewhite: "faebd7",
+ aqua: "0ff",
+ aquamarine: "7fffd4",
+ azure: "f0ffff",
+ beige: "f5f5dc",
+ bisque: "ffe4c4",
+ black: "000",
+ blanchedalmond: "ffebcd",
+ blue: "00f",
+ blueviolet: "8a2be2",
+ brown: "a52a2a",
+ burlywood: "deb887",
+ burntsienna: "ea7e5d",
+ cadetblue: "5f9ea0",
+ chartreuse: "7fff00",
+ chocolate: "d2691e",
+ coral: "ff7f50",
+ cornflowerblue: "6495ed",
+ cornsilk: "fff8dc",
+ crimson: "dc143c",
+ cyan: "0ff",
+ darkblue: "00008b",
+ darkcyan: "008b8b",
+ darkgoldenrod: "b8860b",
+ darkgray: "a9a9a9",
+ darkgreen: "006400",
+ darkgrey: "a9a9a9",
+ darkkhaki: "bdb76b",
+ darkmagenta: "8b008b",
+ darkolivegreen: "556b2f",
+ darkorange: "ff8c00",
+ darkorchid: "9932cc",
+ darkred: "8b0000",
+ darksalmon: "e9967a",
+ darkseagreen: "8fbc8f",
+ darkslateblue: "483d8b",
+ darkslategray: "2f4f4f",
+ darkslategrey: "2f4f4f",
+ darkturquoise: "00ced1",
+ darkviolet: "9400d3",
+ deeppink: "ff1493",
+ deepskyblue: "00bfff",
+ dimgray: "696969",
+ dimgrey: "696969",
+ dodgerblue: "1e90ff",
+ firebrick: "b22222",
+ floralwhite: "fffaf0",
+ forestgreen: "228b22",
+ fuchsia: "f0f",
+ gainsboro: "dcdcdc",
+ ghostwhite: "f8f8ff",
+ gold: "ffd700",
+ goldenrod: "daa520",
+ gray: "808080",
+ green: "008000",
+ greenyellow: "adff2f",
+ grey: "808080",
+ honeydew: "f0fff0",
+ hotpink: "ff69b4",
+ indianred: "cd5c5c",
+ indigo: "4b0082",
+ ivory: "fffff0",
+ khaki: "f0e68c",
+ lavender: "e6e6fa",
+ lavenderblush: "fff0f5",
+ lawngreen: "7cfc00",
+ lemonchiffon: "fffacd",
+ lightblue: "add8e6",
+ lightcoral: "f08080",
+ lightcyan: "e0ffff",
+ lightgoldenrodyellow: "fafad2",
+ lightgray: "d3d3d3",
+ lightgreen: "90ee90",
+ lightgrey: "d3d3d3",
+ lightpink: "ffb6c1",
+ lightsalmon: "ffa07a",
+ lightseagreen: "20b2aa",
+ lightskyblue: "87cefa",
+ lightslategray: "789",
+ lightslategrey: "789",
+ lightsteelblue: "b0c4de",
+ lightyellow: "ffffe0",
+ lime: "0f0",
+ limegreen: "32cd32",
+ linen: "faf0e6",
+ magenta: "f0f",
+ maroon: "800000",
+ mediumaquamarine: "66cdaa",
+ mediumblue: "0000cd",
+ mediumorchid: "ba55d3",
+ mediumpurple: "9370db",
+ mediumseagreen: "3cb371",
+ mediumslateblue: "7b68ee",
+ mediumspringgreen: "00fa9a",
+ mediumturquoise: "48d1cc",
+ mediumvioletred: "c71585",
+ midnightblue: "191970",
+ mintcream: "f5fffa",
+ mistyrose: "ffe4e1",
+ moccasin: "ffe4b5",
+ navajowhite: "ffdead",
+ navy: "000080",
+ oldlace: "fdf5e6",
+ olive: "808000",
+ olivedrab: "6b8e23",
+ orange: "ffa500",
+ orangered: "ff4500",
+ orchid: "da70d6",
+ palegoldenrod: "eee8aa",
+ palegreen: "98fb98",
+ paleturquoise: "afeeee",
+ palevioletred: "db7093",
+ papayawhip: "ffefd5",
+ peachpuff: "ffdab9",
+ peru: "cd853f",
+ pink: "ffc0cb",
+ plum: "dda0dd",
+ powderblue: "b0e0e6",
+ purple: "800080",
+ rebeccapurple: "663399",
+ red: "f00",
+ rosybrown: "bc8f8f",
+ royalblue: "4169e1",
+ saddlebrown: "8b4513",
+ salmon: "fa8072",
+ sandybrown: "f4a460",
+ seagreen: "2e8b57",
+ seashell: "fff5ee",
+ sienna: "a0522d",
+ silver: "c0c0c0",
+ skyblue: "87ceeb",
+ slateblue: "6a5acd",
+ slategray: "708090",
+ slategrey: "708090",
+ snow: "fffafa",
+ springgreen: "00ff7f",
+ steelblue: "4682b4",
+ tan: "d2b48c",
+ teal: "008080",
+ thistle: "d8bfd8",
+ tomato: "ff6347",
+ turquoise: "40e0d0",
+ violet: "ee82ee",
+ wheat: "f5deb3",
+ white: "fff",
+ whitesmoke: "f5f5f5",
+ yellow: "ff0",
+ yellowgreen: "9acd32"
+ };
+ var hexNames = tinycolor.hexNames = flip(names);
+ function flip(o) {
+ var flipped = {};
+ for (var i in o) {
+ if (o.hasOwnProperty(i)) {
+ flipped[o[i]] = i;
+ }
+ }
+ return flipped;
+ }
+ __name(flip, "flip");
+ function boundAlpha(a) {
+ a = parseFloat(a);
+ if (isNaN(a) || a < 0 || a > 1) {
+ a = 1;
+ }
+ return a;
+ }
+ __name(boundAlpha, "boundAlpha");
+ function bound01(n, max) {
+ if (isOnePointZero(n)) n = "100%";
+ var processPercent = isPercentage(n);
+ n = Math.min(max, Math.max(0, parseFloat(n)));
+ if (processPercent) {
+ n = parseInt(n * max, 10) / 100;
+ }
+ if (Math.abs(n - max) < 1e-6) {
+ return 1;
+ }
+ return n % max / parseFloat(max);
+ }
+ __name(bound01, "bound01");
+ function clamp01(val) {
+ return Math.min(1, Math.max(0, val));
+ }
+ __name(clamp01, "clamp01");
+ function parseIntFromHex(val) {
+ return parseInt(val, 16);
+ }
+ __name(parseIntFromHex, "parseIntFromHex");
+ function isOnePointZero(n) {
+ return typeof n == "string" && n.indexOf(".") != -1 && parseFloat(n) === 1;
+ }
+ __name(isOnePointZero, "isOnePointZero");
+ function isPercentage(n) {
+ return typeof n === "string" && n.indexOf("%") != -1;
+ }
+ __name(isPercentage, "isPercentage");
+ function pad2(c) {
+ return c.length == 1 ? "0" + c : "" + c;
+ }
+ __name(pad2, "pad2");
+ function convertToPercentage(n) {
+ if (n <= 1) {
+ n = n * 100 + "%";
+ }
+ return n;
+ }
+ __name(convertToPercentage, "convertToPercentage");
+ function convertDecimalToHex(d) {
+ return Math.round(parseFloat(d) * 255).toString(16);
+ }
+ __name(convertDecimalToHex, "convertDecimalToHex");
+ function convertHexToDecimal(h) {
+ return parseIntFromHex(h) / 255;
+ }
+ __name(convertHexToDecimal, "convertHexToDecimal");
+ var matchers = (function() {
+ var CSS_INTEGER = "[-\\+]?\\d+%?";
+ var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?";
+ var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")";
+ var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
+ var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
+ return {
+ CSS_UNIT: new RegExp(CSS_UNIT),
+ rgb: new RegExp("rgb" + PERMISSIVE_MATCH3),
+ rgba: new RegExp("rgba" + PERMISSIVE_MATCH4),
+ hsl: new RegExp("hsl" + PERMISSIVE_MATCH3),
+ hsla: new RegExp("hsla" + PERMISSIVE_MATCH4),
+ hsv: new RegExp("hsv" + PERMISSIVE_MATCH3),
+ hsva: new RegExp("hsva" + PERMISSIVE_MATCH4),
+ hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
+ hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
+ hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
+ hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/
+ };
+ })();
+ function isValidCSSUnit(color) {
+ return !!matchers.CSS_UNIT.exec(color);
+ }
+ __name(isValidCSSUnit, "isValidCSSUnit");
+ function stringInputToObject(color) {
+ color = color.replace(trimLeft, "").replace(trimRight, "").toLowerCase();
+ var named = false;
+ if (names[color]) {
+ color = names[color];
+ named = true;
+ } else if (color == "transparent") {
+ return {
+ r: 0,
+ g: 0,
+ b: 0,
+ a: 0,
+ format: "name"
+ };
+ }
+ var match;
+ if (match = matchers.rgb.exec(color)) {
+ return {
+ r: match[1],
+ g: match[2],
+ b: match[3]
+ };
+ }
+ if (match = matchers.rgba.exec(color)) {
+ return {
+ r: match[1],
+ g: match[2],
+ b: match[3],
+ a: match[4]
+ };
+ }
+ if (match = matchers.hsl.exec(color)) {
+ return {
+ h: match[1],
+ s: match[2],
+ l: match[3]
+ };
+ }
+ if (match = matchers.hsla.exec(color)) {
+ return {
+ h: match[1],
+ s: match[2],
+ l: match[3],
+ a: match[4]
+ };
+ }
+ if (match = matchers.hsv.exec(color)) {
+ return {
+ h: match[1],
+ s: match[2],
+ v: match[3]
+ };
+ }
+ if (match = matchers.hsva.exec(color)) {
+ return {
+ h: match[1],
+ s: match[2],
+ v: match[3],
+ a: match[4]
+ };
+ }
+ if (match = matchers.hex8.exec(color)) {
+ return {
+ r: parseIntFromHex(match[1]),
+ g: parseIntFromHex(match[2]),
+ b: parseIntFromHex(match[3]),
+ a: convertHexToDecimal(match[4]),
+ format: named ? "name" : "hex8"
+ };
+ }
+ if (match = matchers.hex6.exec(color)) {
+ return {
+ r: parseIntFromHex(match[1]),
+ g: parseIntFromHex(match[2]),
+ b: parseIntFromHex(match[3]),
+ format: named ? "name" : "hex"
+ };
+ }
+ if (match = matchers.hex4.exec(color)) {
+ return {
+ r: parseIntFromHex(match[1] + "" + match[1]),
+ g: parseIntFromHex(match[2] + "" + match[2]),
+ b: parseIntFromHex(match[3] + "" + match[3]),
+ a: convertHexToDecimal(match[4] + "" + match[4]),
+ format: named ? "name" : "hex8"
+ };
+ }
+ if (match = matchers.hex3.exec(color)) {
+ return {
+ r: parseIntFromHex(match[1] + "" + match[1]),
+ g: parseIntFromHex(match[2] + "" + match[2]),
+ b: parseIntFromHex(match[3] + "" + match[3]),
+ format: named ? "name" : "hex"
+ };
+ }
+ return false;
+ }
+ __name(stringInputToObject, "stringInputToObject");
+ function validateWCAG2Parms(parms) {
+ var level, size;
+ parms = parms || {
+ level: "AA",
+ size: "small"
+ };
+ level = (parms.level || "AA").toUpperCase();
+ size = (parms.size || "small").toLowerCase();
+ if (level !== "AA" && level !== "AAA") {
+ level = "AA";
+ }
+ if (size !== "small" && size !== "large") {
+ size = "small";
+ }
+ return {
+ level,
+ size
+ };
+ }
+ __name(validateWCAG2Parms, "validateWCAG2Parms");
+ return tinycolor;
+ }));
+ }
+});
+
+// node_modules/tinygradient/index.js
+var require_tinygradient = __commonJS({
+ "node_modules/tinygradient/index.js"(exports2, module2) {
+ init_esbuild_shims();
+ var tinycolor = require_tinycolor();
+ var RGBA_MAX = { r: 256, g: 256, b: 256, a: 1 };
+ var HSVA_MAX = { h: 360, s: 1, v: 1, a: 1 };
+ function stepize(start, end, steps) {
+ let step = {};
+ for (let k in start) {
+ if (start.hasOwnProperty(k)) {
+ step[k] = steps === 0 ? 0 : (end[k] - start[k]) / steps;
+ }
+ }
+ return step;
+ }
+ __name(stepize, "stepize");
+ function interpolate(step, start, i, max) {
+ let color = {};
+ for (let k in start) {
+ if (start.hasOwnProperty(k)) {
+ color[k] = step[k] * i + start[k];
+ color[k] = color[k] < 0 ? color[k] + max[k] : max[k] !== 1 ? color[k] % max[k] : color[k];
+ }
+ }
+ return color;
+ }
+ __name(interpolate, "interpolate");
+ function interpolateRgb(stop1, stop2, steps) {
+ const start = stop1.color.toRgb();
+ const end = stop2.color.toRgb();
+ const step = stepize(start, end, steps);
+ let gradient2 = [stop1.color];
+ for (let i = 1; i < steps; i++) {
+ const color = interpolate(step, start, i, RGBA_MAX);
+ gradient2.push(tinycolor(color));
+ }
+ return gradient2;
+ }
+ __name(interpolateRgb, "interpolateRgb");
+ function interpolateHsv(stop1, stop2, steps, mode) {
+ const start = stop1.color.toHsv();
+ const end = stop2.color.toHsv();
+ if (start.s === 0 || end.s === 0) {
+ return interpolateRgb(stop1, stop2, steps);
+ }
+ let trigonometric;
+ if (typeof mode === "boolean") {
+ trigonometric = mode;
+ } else {
+ const trigShortest = start.h < end.h && end.h - start.h < 180 || start.h > end.h && start.h - end.h > 180;
+ trigonometric = mode === "long" && trigShortest || mode === "short" && !trigShortest;
+ }
+ const step = stepize(start, end, steps);
+ let gradient2 = [stop1.color];
+ let diff2;
+ if (start.h <= end.h && !trigonometric || start.h >= end.h && trigonometric) {
+ diff2 = end.h - start.h;
+ } else if (trigonometric) {
+ diff2 = 360 - end.h + start.h;
+ } else {
+ diff2 = 360 - start.h + end.h;
+ }
+ step.h = Math.pow(-1, trigonometric ? 1 : 0) * Math.abs(diff2) / steps;
+ for (let i = 1; i < steps; i++) {
+ const color = interpolate(step, start, i, HSVA_MAX);
+ gradient2.push(tinycolor(color));
+ }
+ return gradient2;
+ }
+ __name(interpolateHsv, "interpolateHsv");
+ function computeSubsteps(stops, steps) {
+ const l = stops.length;
+ steps = parseInt(steps, 10);
+ if (isNaN(steps) || steps < 2) {
+ throw new Error("Invalid number of steps (< 2)");
+ }
+ if (steps < l) {
+ throw new Error("Number of steps cannot be inferior to number of stops");
+ }
+ let substeps = [];
+ for (let i = 1; i < l; i++) {
+ const step = (steps - 1) * (stops[i].pos - stops[i - 1].pos);
+ substeps.push(Math.max(1, Math.round(step)));
+ }
+ let totalSubsteps = 1;
+ for (let n = l - 1; n--; ) totalSubsteps += substeps[n];
+ while (totalSubsteps !== steps) {
+ if (totalSubsteps < steps) {
+ const min = Math.min.apply(null, substeps);
+ substeps[substeps.indexOf(min)]++;
+ totalSubsteps++;
+ } else {
+ const max = Math.max.apply(null, substeps);
+ substeps[substeps.indexOf(max)]--;
+ totalSubsteps--;
+ }
+ }
+ return substeps;
+ }
+ __name(computeSubsteps, "computeSubsteps");
+ function computeAt(stops, pos, method, max) {
+ if (pos < 0 || pos > 1) {
+ throw new Error("Position must be between 0 and 1");
+ }
+ let start, end;
+ for (let i = 0, l = stops.length; i < l - 1; i++) {
+ if (pos >= stops[i].pos && pos < stops[i + 1].pos) {
+ start = stops[i];
+ end = stops[i + 1];
+ break;
+ }
+ }
+ if (!start) {
+ start = end = stops[stops.length - 1];
+ }
+ const step = stepize(start.color[method](), end.color[method](), (end.pos - start.pos) * 100);
+ const color = interpolate(step, start.color[method](), (pos - start.pos) * 100, max);
+ return tinycolor(color);
+ }
+ __name(computeAt, "computeAt");
+ var TinyGradient = class _TinyGradient {
+ static {
+ __name(this, "TinyGradient");
+ }
+ /**
+ * @param {StopInput[]|ColorInput[]} stops
+ * @returns {TinyGradient}
+ */
+ constructor(stops) {
+ if (stops.length < 2) {
+ throw new Error("Invalid number of stops (< 2)");
+ }
+ const havingPositions = stops[0].pos !== void 0;
+ let l = stops.length;
+ let p = -1;
+ let lastColorLess = false;
+ this.stops = stops.map((stop, i) => {
+ const hasPosition = stop.pos !== void 0;
+ if (havingPositions ^ hasPosition) {
+ throw new Error("Cannot mix positionned and not posionned color stops");
+ }
+ if (hasPosition) {
+ const hasColor = stop.color !== void 0;
+ if (!hasColor && (lastColorLess || i === 0 || i === l - 1)) {
+ throw new Error("Cannot define two consecutive position-only stops");
+ }
+ lastColorLess = !hasColor;
+ stop = {
+ color: hasColor ? tinycolor(stop.color) : null,
+ colorLess: !hasColor,
+ pos: stop.pos
+ };
+ if (stop.pos < 0 || stop.pos > 1) {
+ throw new Error("Color stops positions must be between 0 and 1");
+ } else if (stop.pos < p) {
+ throw new Error("Color stops positions are not ordered");
+ }
+ p = stop.pos;
+ } else {
+ stop = {
+ color: tinycolor(stop.color !== void 0 ? stop.color : stop),
+ pos: i / (l - 1)
+ };
+ }
+ return stop;
+ });
+ if (this.stops[0].pos !== 0) {
+ this.stops.unshift({
+ color: this.stops[0].color,
+ pos: 0
+ });
+ l++;
+ }
+ if (this.stops[l - 1].pos !== 1) {
+ this.stops.push({
+ color: this.stops[l - 1].color,
+ pos: 1
+ });
+ }
+ }
+ /**
+ * Return new instance with reversed stops
+ * @return {TinyGradient}
+ */
+ reverse() {
+ let stops = [];
+ this.stops.forEach(function(stop) {
+ stops.push({
+ color: stop.color,
+ pos: 1 - stop.pos
+ });
+ });
+ return new _TinyGradient(stops.reverse());
+ }
+ /**
+ * Return new instance with looped stops
+ * @return {TinyGradient}
+ */
+ loop() {
+ let stops1 = [];
+ let stops2 = [];
+ this.stops.forEach((stop) => {
+ stops1.push({
+ color: stop.color,
+ pos: stop.pos / 2
+ });
+ });
+ this.stops.slice(0, -1).forEach((stop) => {
+ stops2.push({
+ color: stop.color,
+ pos: 1 - stop.pos / 2
+ });
+ });
+ return new _TinyGradient(stops1.concat(stops2.reverse()));
+ }
+ /**
+ * Generate gradient with RGBa interpolation
+ * @param {number} steps
+ * @return {tinycolor[]}
+ */
+ rgb(steps) {
+ const substeps = computeSubsteps(this.stops, steps);
+ let gradient2 = [];
+ this.stops.forEach((stop, i) => {
+ if (stop.colorLess) {
+ stop.color = interpolateRgb(this.stops[i - 1], this.stops[i + 1], 2)[1];
+ }
+ });
+ for (let i = 0, l = this.stops.length; i < l - 1; i++) {
+ const rgb = interpolateRgb(this.stops[i], this.stops[i + 1], substeps[i]);
+ gradient2.splice(gradient2.length, 0, ...rgb);
+ }
+ gradient2.push(this.stops[this.stops.length - 1].color);
+ return gradient2;
+ }
+ /**
+ * Generate gradient with HSVa interpolation
+ * @param {number} steps
+ * @param {boolean|'long'|'short'} [mode=false]
+ * - false to step in clockwise
+ * - true to step in trigonometric order
+ * - 'short' to use the shortest way
+ * - 'long' to use the longest way
+ * @return {tinycolor[]}
+ */
+ hsv(steps, mode) {
+ const substeps = computeSubsteps(this.stops, steps);
+ let gradient2 = [];
+ this.stops.forEach((stop, i) => {
+ if (stop.colorLess) {
+ stop.color = interpolateHsv(this.stops[i - 1], this.stops[i + 1], 2, mode)[1];
+ }
+ });
+ for (let i = 0, l = this.stops.length; i < l - 1; i++) {
+ const hsv = interpolateHsv(this.stops[i], this.stops[i + 1], substeps[i], mode);
+ gradient2.splice(gradient2.length, 0, ...hsv);
+ }
+ gradient2.push(this.stops[this.stops.length - 1].color);
+ return gradient2;
+ }
+ /**
+ * Generate CSS3 command (no prefix) for this gradient
+ * @param {String} [mode=linear] - 'linear' or 'radial'
+ * @param {String} [direction] - default is 'to right' or 'ellipse at center'
+ * @return {String}
+ */
+ css(mode, direction) {
+ mode = mode || "linear";
+ direction = direction || (mode === "linear" ? "to right" : "ellipse at center");
+ let css = mode + "-gradient(" + direction;
+ this.stops.forEach(function(stop) {
+ css += ", " + (stop.colorLess ? "" : stop.color.toRgbString() + " ") + stop.pos * 100 + "%";
+ });
+ css += ")";
+ return css;
+ }
+ /**
+ * Returns the color at specific position with RGBa interpolation
+ * @param {number} pos, between 0 and 1
+ * @return {tinycolor}
+ */
+ rgbAt(pos) {
+ return computeAt(this.stops, pos, "toRgb", RGBA_MAX);
+ }
+ /**
+ * Returns the color at specific position with HSVa interpolation
+ * @param {number} pos, between 0 and 1
+ * @return {tinycolor}
+ */
+ hsvAt(pos) {
+ return computeAt(this.stops, pos, "toHsv", HSVA_MAX);
+ }
+ };
+ module2.exports = function(stops) {
+ if (arguments.length === 1) {
+ if (!Array.isArray(arguments[0])) {
+ throw new Error('"stops" is not an array');
+ }
+ stops = arguments[0];
+ } else {
+ stops = Array.prototype.slice.call(arguments);
+ }
+ return new TinyGradient(stops);
+ };
+ }
+});
+
+// node_modules/emoji-regex/index.js
+var require_emoji_regex = __commonJS({
+ "node_modules/emoji-regex/index.js"(exports2, module2) {
+ init_esbuild_shims();
+ module2.exports = () => {
+ return /[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E-\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED8\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])))?))?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3C-\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE8A\uDE8E-\uDEC2\uDEC6\uDEC8\uDECD-\uDEDC\uDEDF-\uDEEA\uDEEF]|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g;
+ };
+ }
+});
+
+// node_modules/get-caller-file/index.js
+var require_get_caller_file = __commonJS({
+ "node_modules/get-caller-file/index.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ module2.exports = /* @__PURE__ */ __name(function getCallerFile2(position) {
+ if (position === void 0) {
+ position = 2;
+ }
+ if (position >= Error.stackTraceLimit) {
+ throw new TypeError("getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `" + position + "` and Error.stackTraceLimit was: `" + Error.stackTraceLimit + "`");
+ }
+ var oldPrepareStackTrace = Error.prepareStackTrace;
+ Error.prepareStackTrace = function(_, stack2) {
+ return stack2;
+ };
+ var stack = new Error().stack;
+ Error.prepareStackTrace = oldPrepareStackTrace;
+ if (stack !== null && typeof stack === "object") {
+ return stack[position] ? stack[position].getFileName() : void 0;
+ }
+ }, "getCallerFile");
+ }
+});
+
+// node_modules/picocolors/picocolors.js
+var require_picocolors = __commonJS({
+ "node_modules/picocolors/picocolors.js"(exports2, module2) {
+ init_esbuild_shims();
+ var p = process || {};
+ var argv = p.argv || [];
+ var env6 = p.env || {};
+ var isColorSupported = !(!!env6.NO_COLOR || argv.includes("--no-color")) && (!!env6.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env6.TERM !== "dumb" || !!env6.CI);
+ var formatter = /* @__PURE__ */ __name((open, close, replace = open) => (input) => {
+ let string4 = "" + input, index = string4.indexOf(close, open.length);
+ return ~index ? open + replaceClose(string4, close, replace, index) + close : open + string4 + close;
+ }, "formatter");
+ var replaceClose = /* @__PURE__ */ __name((string4, close, replace, index) => {
+ let result = "", cursor = 0;
+ do {
+ result += string4.substring(cursor, index) + replace;
+ cursor = index + close.length;
+ index = string4.indexOf(close, cursor);
+ } while (~index);
+ return result + string4.substring(cursor);
+ }, "replaceClose");
+ var createColors = /* @__PURE__ */ __name((enabled = isColorSupported) => {
+ let f = enabled ? formatter : () => String;
+ return {
+ isColorSupported: enabled,
+ reset: f("\x1B[0m", "\x1B[0m"),
+ bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
+ dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
+ italic: f("\x1B[3m", "\x1B[23m"),
+ underline: f("\x1B[4m", "\x1B[24m"),
+ inverse: f("\x1B[7m", "\x1B[27m"),
+ hidden: f("\x1B[8m", "\x1B[28m"),
+ strikethrough: f("\x1B[9m", "\x1B[29m"),
+ black: f("\x1B[30m", "\x1B[39m"),
+ red: f("\x1B[31m", "\x1B[39m"),
+ green: f("\x1B[32m", "\x1B[39m"),
+ yellow: f("\x1B[33m", "\x1B[39m"),
+ blue: f("\x1B[34m", "\x1B[39m"),
+ magenta: f("\x1B[35m", "\x1B[39m"),
+ cyan: f("\x1B[36m", "\x1B[39m"),
+ white: f("\x1B[37m", "\x1B[39m"),
+ gray: f("\x1B[90m", "\x1B[39m"),
+ bgBlack: f("\x1B[40m", "\x1B[49m"),
+ bgRed: f("\x1B[41m", "\x1B[49m"),
+ bgGreen: f("\x1B[42m", "\x1B[49m"),
+ bgYellow: f("\x1B[43m", "\x1B[49m"),
+ bgBlue: f("\x1B[44m", "\x1B[49m"),
+ bgMagenta: f("\x1B[45m", "\x1B[49m"),
+ bgCyan: f("\x1B[46m", "\x1B[49m"),
+ bgWhite: f("\x1B[47m", "\x1B[49m"),
+ blackBright: f("\x1B[90m", "\x1B[39m"),
+ redBright: f("\x1B[91m", "\x1B[39m"),
+ greenBright: f("\x1B[92m", "\x1B[39m"),
+ yellowBright: f("\x1B[93m", "\x1B[39m"),
+ blueBright: f("\x1B[94m", "\x1B[39m"),
+ magentaBright: f("\x1B[95m", "\x1B[39m"),
+ cyanBright: f("\x1B[96m", "\x1B[39m"),
+ whiteBright: f("\x1B[97m", "\x1B[39m"),
+ bgBlackBright: f("\x1B[100m", "\x1B[49m"),
+ bgRedBright: f("\x1B[101m", "\x1B[49m"),
+ bgGreenBright: f("\x1B[102m", "\x1B[49m"),
+ bgYellowBright: f("\x1B[103m", "\x1B[49m"),
+ bgBlueBright: f("\x1B[104m", "\x1B[49m"),
+ bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
+ bgCyanBright: f("\x1B[106m", "\x1B[49m"),
+ bgWhiteBright: f("\x1B[107m", "\x1B[49m")
+ };
+ }, "createColors");
+ module2.exports = createColors();
+ module2.exports.createColors = createColors;
+ }
+});
+
+// node_modules/js-tokens/index.js
+var require_js_tokens = __commonJS({
+ "node_modules/js-tokens/index.js"(exports2) {
+ init_esbuild_shims();
+ Object.defineProperty(exports2, "__esModule", {
+ value: true
+ });
+ exports2.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyus]{1,6}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g;
+ exports2.matchToToken = function(match) {
+ var token = { type: "invalid", value: match[0], closed: void 0 };
+ if (match[1]) token.type = "string", token.closed = !!(match[3] || match[4]);
+ else if (match[5]) token.type = "comment";
+ else if (match[6]) token.type = "comment", token.closed = !!match[7];
+ else if (match[8]) token.type = "regex";
+ else if (match[9]) token.type = "number";
+ else if (match[10]) token.type = "name";
+ else if (match[11]) token.type = "punctuator";
+ else if (match[12]) token.type = "whitespace";
+ return token;
+ };
+ }
+});
+
+// node_modules/@babel/helper-validator-identifier/lib/identifier.js
+var require_identifier = __commonJS({
+ "node_modules/@babel/helper-validator-identifier/lib/identifier.js"(exports2) {
+ "use strict";
+ init_esbuild_shims();
+ Object.defineProperty(exports2, "__esModule", {
+ value: true
+ });
+ exports2.isIdentifierChar = isIdentifierChar;
+ exports2.isIdentifierName = isIdentifierName;
+ exports2.isIdentifierStart = isIdentifierStart;
+ var nonASCIIidentifierStartChars = "\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088F\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5C\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDC-\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7DC\uA7F1-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC";
+ var nonASCIIidentifierChars = "\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0897-\u089F\u08CA-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C04\u0C3C\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0CF3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u180F-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1ABF-\u1ADD\u1AE0-\u1AEB\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DFF\u200C\u200D\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\u30FB\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA8FF-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F\uFF65";
+ var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
+ var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
+ nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
+ var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 4, 51, 13, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 7, 25, 39, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 39, 27, 10, 22, 251, 41, 7, 1, 17, 5, 57, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 31, 9, 2, 0, 3, 0, 2, 37, 2, 0, 26, 0, 2, 0, 45, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 200, 32, 32, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 24, 43, 261, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 26, 3994, 6, 582, 6842, 29, 1763, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 433, 44, 212, 63, 33, 24, 3, 24, 45, 74, 6, 0, 67, 12, 65, 1, 2, 0, 15, 4, 10, 7381, 42, 31, 98, 114, 8702, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 229, 29, 3, 0, 208, 30, 2, 2, 2, 1, 2, 6, 3, 4, 10, 1, 225, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4381, 3, 5773, 3, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 8489];
+ var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 7, 9, 32, 4, 318, 1, 78, 5, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 199, 7, 137, 9, 54, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 55, 9, 266, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 245, 1, 2, 9, 233, 0, 3, 0, 8, 1, 6, 0, 475, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
+ function isInAstralSet(code, set2) {
+ let pos = 65536;
+ for (let i = 0, length = set2.length; i < length; i += 2) {
+ pos += set2[i];
+ if (pos > code) return false;
+ pos += set2[i + 1];
+ if (pos >= code) return true;
+ }
+ return false;
+ }
+ __name(isInAstralSet, "isInAstralSet");
+ function isIdentifierStart(code) {
+ if (code < 65) return code === 36;
+ if (code <= 90) return true;
+ if (code < 97) return code === 95;
+ if (code <= 122) return true;
+ if (code <= 65535) {
+ return code >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code));
+ }
+ return isInAstralSet(code, astralIdentifierStartCodes);
+ }
+ __name(isIdentifierStart, "isIdentifierStart");
+ function isIdentifierChar(code) {
+ if (code < 48) return code === 36;
+ if (code < 58) return true;
+ if (code < 65) return false;
+ if (code <= 90) return true;
+ if (code < 97) return code === 95;
+ if (code <= 122) return true;
+ if (code <= 65535) {
+ return code >= 170 && nonASCIIidentifier.test(String.fromCharCode(code));
+ }
+ return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
+ }
+ __name(isIdentifierChar, "isIdentifierChar");
+ function isIdentifierName(name) {
+ let isFirst = true;
+ for (let i = 0; i < name.length; i++) {
+ let cp = name.charCodeAt(i);
+ if ((cp & 64512) === 55296 && i + 1 < name.length) {
+ const trail = name.charCodeAt(++i);
+ if ((trail & 64512) === 56320) {
+ cp = 65536 + ((cp & 1023) << 10) + (trail & 1023);
+ }
+ }
+ if (isFirst) {
+ isFirst = false;
+ if (!isIdentifierStart(cp)) {
+ return false;
+ }
+ } else if (!isIdentifierChar(cp)) {
+ return false;
+ }
+ }
+ return !isFirst;
+ }
+ __name(isIdentifierName, "isIdentifierName");
+ }
+});
+
+// node_modules/@babel/helper-validator-identifier/lib/keyword.js
+var require_keyword = __commonJS({
+ "node_modules/@babel/helper-validator-identifier/lib/keyword.js"(exports2) {
+ "use strict";
+ init_esbuild_shims();
+ Object.defineProperty(exports2, "__esModule", {
+ value: true
+ });
+ exports2.isKeyword = isKeyword;
+ exports2.isReservedWord = isReservedWord;
+ exports2.isStrictBindOnlyReservedWord = isStrictBindOnlyReservedWord;
+ exports2.isStrictBindReservedWord = isStrictBindReservedWord;
+ exports2.isStrictReservedWord = isStrictReservedWord;
+ var reservedWords = {
+ keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"],
+ strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
+ strictBind: ["eval", "arguments"]
+ };
+ var keywords = new Set(reservedWords.keyword);
+ var reservedWordsStrictSet = new Set(reservedWords.strict);
+ var reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
+ function isReservedWord(word, inModule) {
+ return inModule && word === "await" || word === "enum";
+ }
+ __name(isReservedWord, "isReservedWord");
+ function isStrictReservedWord(word, inModule) {
+ return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
+ }
+ __name(isStrictReservedWord, "isStrictReservedWord");
+ function isStrictBindOnlyReservedWord(word) {
+ return reservedWordsStrictBindSet.has(word);
+ }
+ __name(isStrictBindOnlyReservedWord, "isStrictBindOnlyReservedWord");
+ function isStrictBindReservedWord(word, inModule) {
+ return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
+ }
+ __name(isStrictBindReservedWord, "isStrictBindReservedWord");
+ function isKeyword(word) {
+ return keywords.has(word);
+ }
+ __name(isKeyword, "isKeyword");
+ }
+});
+
+// node_modules/@babel/helper-validator-identifier/lib/index.js
+var require_lib = __commonJS({
+ "node_modules/@babel/helper-validator-identifier/lib/index.js"(exports2) {
+ "use strict";
+ init_esbuild_shims();
+ Object.defineProperty(exports2, "__esModule", {
+ value: true
+ });
+ Object.defineProperty(exports2, "isIdentifierChar", {
+ enumerable: true,
+ get: /* @__PURE__ */ __name(function() {
+ return _identifier.isIdentifierChar;
+ }, "get")
+ });
+ Object.defineProperty(exports2, "isIdentifierName", {
+ enumerable: true,
+ get: /* @__PURE__ */ __name(function() {
+ return _identifier.isIdentifierName;
+ }, "get")
+ });
+ Object.defineProperty(exports2, "isIdentifierStart", {
+ enumerable: true,
+ get: /* @__PURE__ */ __name(function() {
+ return _identifier.isIdentifierStart;
+ }, "get")
+ });
+ Object.defineProperty(exports2, "isKeyword", {
+ enumerable: true,
+ get: /* @__PURE__ */ __name(function() {
+ return _keyword.isKeyword;
+ }, "get")
+ });
+ Object.defineProperty(exports2, "isReservedWord", {
+ enumerable: true,
+ get: /* @__PURE__ */ __name(function() {
+ return _keyword.isReservedWord;
+ }, "get")
+ });
+ Object.defineProperty(exports2, "isStrictBindOnlyReservedWord", {
+ enumerable: true,
+ get: /* @__PURE__ */ __name(function() {
+ return _keyword.isStrictBindOnlyReservedWord;
+ }, "get")
+ });
+ Object.defineProperty(exports2, "isStrictBindReservedWord", {
+ enumerable: true,
+ get: /* @__PURE__ */ __name(function() {
+ return _keyword.isStrictBindReservedWord;
+ }, "get")
+ });
+ Object.defineProperty(exports2, "isStrictReservedWord", {
+ enumerable: true,
+ get: /* @__PURE__ */ __name(function() {
+ return _keyword.isStrictReservedWord;
+ }, "get")
+ });
+ var _identifier = require_identifier();
+ var _keyword = require_keyword();
+ }
+});
+
+// node_modules/@babel/code-frame/lib/index.js
+var require_lib2 = __commonJS({
+ "node_modules/@babel/code-frame/lib/index.js"(exports2) {
+ "use strict";
+ init_esbuild_shims();
+ Object.defineProperty(exports2, "__esModule", { value: true });
+ var picocolors = require_picocolors();
+ var jsTokens = require_js_tokens();
+ var helperValidatorIdentifier = require_lib();
+ function isColorSupported() {
+ return typeof process === "object" && (process.env.FORCE_COLOR === "0" || process.env.FORCE_COLOR === "false") ? false : picocolors.isColorSupported;
+ }
+ __name(isColorSupported, "isColorSupported");
+ var compose = /* @__PURE__ */ __name((f, g) => (v) => f(g(v)), "compose");
+ function buildDefs(colors) {
+ return {
+ keyword: colors.cyan,
+ capitalized: colors.yellow,
+ jsxIdentifier: colors.yellow,
+ punctuator: colors.yellow,
+ number: colors.magenta,
+ string: colors.green,
+ regex: colors.magenta,
+ comment: colors.gray,
+ invalid: compose(compose(colors.white, colors.bgRed), colors.bold),
+ gutter: colors.gray,
+ marker: compose(colors.red, colors.bold),
+ message: compose(colors.red, colors.bold),
+ reset: colors.reset
+ };
+ }
+ __name(buildDefs, "buildDefs");
+ var defsOn = buildDefs(picocolors.createColors(true));
+ var defsOff = buildDefs(picocolors.createColors(false));
+ function getDefs(enabled) {
+ return enabled ? defsOn : defsOff;
+ }
+ __name(getDefs, "getDefs");
+ var sometimesKeywords = /* @__PURE__ */ new Set(["as", "async", "from", "get", "of", "set"]);
+ var NEWLINE$1 = /\r\n|[\n\r\u2028\u2029]/;
+ var BRACKET = /^[()[\]{}]$/;
+ var tokenize2;
+ var JSX_TAG = /^[a-z][\w-]*$/i;
+ var getTokenType = /* @__PURE__ */ __name(function(token, offset, text) {
+ if (token.type === "name") {
+ const tokenValue = token.value;
+ if (helperValidatorIdentifier.isKeyword(tokenValue) || helperValidatorIdentifier.isStrictReservedWord(tokenValue, true) || sometimesKeywords.has(tokenValue)) {
+ return "keyword";
+ }
+ if (JSX_TAG.test(tokenValue) && (text[offset - 1] === "<" || text.slice(offset - 2, offset) === "")) {
+ return "jsxIdentifier";
+ }
+ const firstChar = String.fromCodePoint(tokenValue.codePointAt(0));
+ if (firstChar !== firstChar.toLowerCase()) {
+ return "capitalized";
+ }
+ }
+ if (token.type === "punctuator" && BRACKET.test(token.value)) {
+ return "bracket";
+ }
+ if (token.type === "invalid" && (token.value === "@" || token.value === "#")) {
+ return "punctuator";
+ }
+ return token.type;
+ }, "getTokenType");
+ tokenize2 = /* @__PURE__ */ __name(function* (text) {
+ let match;
+ while (match = jsTokens.default.exec(text)) {
+ const token = jsTokens.matchToToken(match);
+ yield {
+ type: getTokenType(token, match.index, text),
+ value: token.value
+ };
+ }
+ }, "tokenize");
+ function highlight(text) {
+ if (text === "") return "";
+ const defs = getDefs(true);
+ let highlighted = "";
+ for (const {
+ type: type2,
+ value
+ } of tokenize2(text)) {
+ if (type2 in defs) {
+ highlighted += value.split(NEWLINE$1).map((str3) => defs[type2](str3)).join("\n");
+ } else {
+ highlighted += value;
+ }
+ }
+ return highlighted;
+ }
+ __name(highlight, "highlight");
+ var deprecationWarningShown = false;
+ var NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
+ function getMarkerLines(loc, source, opts, startLineBaseZero) {
+ const startLoc = Object.assign({
+ column: 0,
+ line: -1
+ }, loc.start);
+ const endLoc = Object.assign({}, startLoc, loc.end);
+ const {
+ linesAbove = 2,
+ linesBelow = 3
+ } = opts || {};
+ const startLine = startLoc.line - startLineBaseZero;
+ const startColumn = startLoc.column;
+ const endLine = endLoc.line - startLineBaseZero;
+ const endColumn = endLoc.column;
+ let start = Math.max(startLine - (linesAbove + 1), 0);
+ let end = Math.min(source.length, endLine + linesBelow);
+ if (startLine === -1) {
+ start = 0;
+ }
+ if (endLine === -1) {
+ end = source.length;
+ }
+ const lineDiff = endLine - startLine;
+ const markerLines = {};
+ if (lineDiff) {
+ for (let i = 0; i <= lineDiff; i++) {
+ const lineNumber = i + startLine;
+ if (!startColumn) {
+ markerLines[lineNumber] = true;
+ } else if (i === 0) {
+ const sourceLength = source[lineNumber - 1].length;
+ markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
+ } else if (i === lineDiff) {
+ markerLines[lineNumber] = [0, endColumn];
+ } else {
+ const sourceLength = source[lineNumber - i].length;
+ markerLines[lineNumber] = [0, sourceLength];
+ }
+ }
+ } else {
+ if (startColumn === endColumn) {
+ if (startColumn) {
+ markerLines[startLine] = [startColumn, 0];
+ } else {
+ markerLines[startLine] = true;
+ }
+ } else {
+ markerLines[startLine] = [startColumn, endColumn - startColumn];
+ }
+ }
+ return {
+ start,
+ end,
+ markerLines
+ };
+ }
+ __name(getMarkerLines, "getMarkerLines");
+ function codeFrameColumns2(rawLines, loc, opts = {}) {
+ const shouldHighlight = opts.forceColor || isColorSupported() && opts.highlightCode;
+ const startLineBaseZero = (opts.startLine || 1) - 1;
+ const defs = getDefs(shouldHighlight);
+ const lines = rawLines.split(NEWLINE);
+ const {
+ start,
+ end,
+ markerLines
+ } = getMarkerLines(loc, lines, opts, startLineBaseZero);
+ const hasColumns = loc.start && typeof loc.start.column === "number";
+ const numberMaxWidth = String(end + startLineBaseZero).length;
+ const highlightedLines = shouldHighlight ? highlight(rawLines) : rawLines;
+ let frame = highlightedLines.split(NEWLINE, end).slice(start, end).map((line, index2) => {
+ const number4 = start + 1 + index2;
+ const paddedNumber = ` ${number4 + startLineBaseZero}`.slice(-numberMaxWidth);
+ const gutter = ` ${paddedNumber} |`;
+ const hasMarker = markerLines[number4];
+ const lastMarkerLine = !markerLines[number4 + 1];
+ if (hasMarker) {
+ let markerLine = "";
+ if (Array.isArray(hasMarker)) {
+ const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " ");
+ const numberOfMarkers = hasMarker[1] || 1;
+ markerLine = ["\n ", defs.gutter(gutter.replace(/\d/g, " ")), " ", markerSpacing, defs.marker("^").repeat(numberOfMarkers)].join("");
+ if (lastMarkerLine && opts.message) {
+ markerLine += " " + defs.message(opts.message);
+ }
+ }
+ return [defs.marker(">"), defs.gutter(gutter), line.length > 0 ? ` ${line}` : "", markerLine].join("");
+ } else {
+ return ` ${defs.gutter(gutter)}${line.length > 0 ? ` ${line}` : ""}`;
+ }
+ }).join("\n");
+ if (opts.message && !hasColumns) {
+ frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}
+${frame}`;
+ }
+ if (shouldHighlight) {
+ return defs.reset(frame);
+ } else {
+ return frame;
+ }
+ }
+ __name(codeFrameColumns2, "codeFrameColumns");
+ function index(rawLines, lineNumber, colNumber, opts = {}) {
+ if (!deprecationWarningShown) {
+ deprecationWarningShown = true;
+ const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.";
+ if (process.emitWarning) {
+ process.emitWarning(message, "DeprecationWarning");
+ } else {
+ const deprecationError = new Error(message);
+ deprecationError.name = "DeprecationWarning";
+ console.warn(new Error(message));
+ }
+ }
+ colNumber = Math.max(colNumber, 0);
+ const location = {
+ start: {
+ column: colNumber,
+ line: lineNumber
+ }
+ };
+ return codeFrameColumns2(rawLines, location, opts);
+ }
+ __name(index, "index");
+ exports2.codeFrameColumns = codeFrameColumns2;
+ exports2.default = index;
+ exports2.highlight = highlight;
+ }
+});
+
+// node_modules/read-package-up/node_modules/semver/internal/debug.js
+var require_debug = __commonJS({
+ "node_modules/read-package-up/node_modules/semver/internal/debug.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var debug = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => {
+ };
+ module2.exports = debug;
+ }
+});
+
+// node_modules/read-package-up/node_modules/semver/internal/constants.js
+var require_constants7 = __commonJS({
+ "node_modules/read-package-up/node_modules/semver/internal/constants.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var SEMVER_SPEC_VERSION = "2.0.0";
+ var MAX_LENGTH = 256;
+ var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */
+ 9007199254740991;
+ var MAX_SAFE_COMPONENT_LENGTH = 16;
+ var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6;
+ var RELEASE_TYPES = [
+ "major",
+ "premajor",
+ "minor",
+ "preminor",
+ "patch",
+ "prepatch",
+ "prerelease"
+ ];
+ module2.exports = {
+ MAX_LENGTH,
+ MAX_SAFE_COMPONENT_LENGTH,
+ MAX_SAFE_BUILD_LENGTH,
+ MAX_SAFE_INTEGER,
+ RELEASE_TYPES,
+ SEMVER_SPEC_VERSION,
+ FLAG_INCLUDE_PRERELEASE: 1,
+ FLAG_LOOSE: 2
+ };
+ }
+});
+
+// node_modules/read-package-up/node_modules/semver/internal/re.js
+var require_re = __commonJS({
+ "node_modules/read-package-up/node_modules/semver/internal/re.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var {
+ MAX_SAFE_COMPONENT_LENGTH,
+ MAX_SAFE_BUILD_LENGTH,
+ MAX_LENGTH
+ } = require_constants7();
+ var debug = require_debug();
+ exports2 = module2.exports = {};
+ var re = exports2.re = [];
+ var safeRe = exports2.safeRe = [];
+ var src = exports2.src = [];
+ var safeSrc = exports2.safeSrc = [];
+ var t = exports2.t = {};
+ var R = 0;
+ var LETTERDASHNUMBER = "[a-zA-Z0-9-]";
+ var safeRegexReplacements = [
+ ["\\s", 1],
+ ["\\d", MAX_LENGTH],
+ [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH]
+ ];
+ var makeSafeRegex = /* @__PURE__ */ __name((value) => {
+ for (const [token, max] of safeRegexReplacements) {
+ value = value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`);
+ }
+ return value;
+ }, "makeSafeRegex");
+ var createToken = /* @__PURE__ */ __name((name, value, isGlobal) => {
+ const safe = makeSafeRegex(value);
+ const index = R++;
+ debug(name, index, value);
+ t[name] = index;
+ src[index] = value;
+ safeSrc[index] = safe;
+ re[index] = new RegExp(value, isGlobal ? "g" : void 0);
+ safeRe[index] = new RegExp(safe, isGlobal ? "g" : void 0);
+ }, "createToken");
+ createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*");
+ createToken("NUMERICIDENTIFIERLOOSE", "\\d+");
+ createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`);
+ createToken("MAINVERSION", `(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})\\.(${src[t.NUMERICIDENTIFIER]})`);
+ createToken("MAINVERSIONLOOSE", `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})\\.(${src[t.NUMERICIDENTIFIERLOOSE]})`);
+ createToken("PRERELEASEIDENTIFIER", `(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIER]})`);
+ createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t.NONNUMERICIDENTIFIER]}|${src[t.NUMERICIDENTIFIERLOOSE]})`);
+ createToken("PRERELEASE", `(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`);
+ createToken("PRERELEASELOOSE", `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`);
+ createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`);
+ createToken("BUILD", `(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`);
+ createToken("FULLPLAIN", `v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`);
+ createToken("FULL", `^${src[t.FULLPLAIN]}$`);
+ createToken("LOOSEPLAIN", `[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`);
+ createToken("LOOSE", `^${src[t.LOOSEPLAIN]}$`);
+ createToken("GTLT", "((?:<|>)?=?)");
+ createToken("XRANGEIDENTIFIERLOOSE", `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
+ createToken("XRANGEIDENTIFIER", `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`);
+ createToken("XRANGEPLAIN", `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:\\.(${src[t.XRANGEIDENTIFIER]})(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?)?)?`);
+ createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?)?)?`);
+ createToken("XRANGE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`);
+ createToken("XRANGELOOSE", `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`);
+ createToken("COERCEPLAIN", `${"(^|[^\\d])(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`);
+ createToken("COERCE", `${src[t.COERCEPLAIN]}(?:$|[^\\d])`);
+ createToken("COERCEFULL", src[t.COERCEPLAIN] + `(?:${src[t.PRERELEASE]})?(?:${src[t.BUILD]})?(?:$|[^\\d])`);
+ createToken("COERCERTL", src[t.COERCE], true);
+ createToken("COERCERTLFULL", src[t.COERCEFULL], true);
+ createToken("LONETILDE", "(?:~>?)");
+ createToken("TILDETRIM", `(\\s*)${src[t.LONETILDE]}\\s+`, true);
+ exports2.tildeTrimReplace = "$1~";
+ createToken("TILDE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`);
+ createToken("TILDELOOSE", `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`);
+ createToken("LONECARET", "(?:\\^)");
+ createToken("CARETTRIM", `(\\s*)${src[t.LONECARET]}\\s+`, true);
+ exports2.caretTrimReplace = "$1^";
+ createToken("CARET", `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`);
+ createToken("CARETLOOSE", `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`);
+ createToken("COMPARATORLOOSE", `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`);
+ createToken("COMPARATOR", `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`);
+ createToken("COMPARATORTRIM", `(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true);
+ exports2.comparatorTrimReplace = "$1$2$3";
+ createToken("HYPHENRANGE", `^\\s*(${src[t.XRANGEPLAIN]})\\s+-\\s+(${src[t.XRANGEPLAIN]})\\s*$`);
+ createToken("HYPHENRANGELOOSE", `^\\s*(${src[t.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t.XRANGEPLAINLOOSE]})\\s*$`);
+ createToken("STAR", "(<|>)?=?\\s*\\*");
+ createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$");
+ createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$");
+ }
+});
+
+// node_modules/read-package-up/node_modules/semver/internal/parse-options.js
+var require_parse_options = __commonJS({
+ "node_modules/read-package-up/node_modules/semver/internal/parse-options.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var looseOption = Object.freeze({ loose: true });
+ var emptyOpts = Object.freeze({});
+ var parseOptions = /* @__PURE__ */ __name((options2) => {
+ if (!options2) {
+ return emptyOpts;
+ }
+ if (typeof options2 !== "object") {
+ return looseOption;
+ }
+ return options2;
+ }, "parseOptions");
+ module2.exports = parseOptions;
+ }
+});
+
+// node_modules/read-package-up/node_modules/semver/internal/identifiers.js
+var require_identifiers = __commonJS({
+ "node_modules/read-package-up/node_modules/semver/internal/identifiers.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var numeric = /^[0-9]+$/;
+ var compareIdentifiers = /* @__PURE__ */ __name((a, b) => {
+ if (typeof a === "number" && typeof b === "number") {
+ return a === b ? 0 : a < b ? -1 : 1;
+ }
+ const anum = numeric.test(a);
+ const bnum = numeric.test(b);
+ if (anum && bnum) {
+ a = +a;
+ b = +b;
+ }
+ return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;
+ }, "compareIdentifiers");
+ var rcompareIdentifiers = /* @__PURE__ */ __name((a, b) => compareIdentifiers(b, a), "rcompareIdentifiers");
+ module2.exports = {
+ compareIdentifiers,
+ rcompareIdentifiers
+ };
+ }
+});
+
+// node_modules/read-package-up/node_modules/semver/classes/semver.js
+var require_semver = __commonJS({
+ "node_modules/read-package-up/node_modules/semver/classes/semver.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var debug = require_debug();
+ var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants7();
+ var { safeRe: re, t } = require_re();
+ var parseOptions = require_parse_options();
+ var { compareIdentifiers } = require_identifiers();
+ var isPrereleaseIdentifier = /* @__PURE__ */ __name((prerelease, identifier) => {
+ const identifiers = identifier.split(".");
+ if (identifiers.length > prerelease.length) {
+ return false;
+ }
+ for (let i = 0; i < identifiers.length; i++) {
+ if (compareIdentifiers(prerelease[i], identifiers[i]) !== 0) {
+ return false;
+ }
+ }
+ return true;
+ }, "isPrereleaseIdentifier");
+ var SemVer = class _SemVer {
+ static {
+ __name(this, "SemVer");
+ }
+ constructor(version2, options2) {
+ options2 = parseOptions(options2);
+ if (version2 instanceof _SemVer) {
+ if (version2.loose === !!options2.loose && version2.includePrerelease === !!options2.includePrerelease) {
+ return version2;
+ } else {
+ version2 = version2.version;
+ }
+ } else if (typeof version2 !== "string") {
+ throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version2}".`);
+ }
+ if (version2.length > MAX_LENGTH) {
+ throw new TypeError(
+ `version is longer than ${MAX_LENGTH} characters`
+ );
+ }
+ debug("SemVer", version2, options2);
+ this.options = options2;
+ this.loose = !!options2.loose;
+ this.includePrerelease = !!options2.includePrerelease;
+ const m = version2.trim().match(options2.loose ? re[t.LOOSE] : re[t.FULL]);
+ if (!m) {
+ throw new TypeError(`Invalid Version: ${version2}`);
+ }
+ this.raw = version2;
+ this.major = +m[1];
+ this.minor = +m[2];
+ this.patch = +m[3];
+ if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
+ throw new TypeError("Invalid major version");
+ }
+ if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
+ throw new TypeError("Invalid minor version");
+ }
+ if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
+ throw new TypeError("Invalid patch version");
+ }
+ if (!m[4]) {
+ this.prerelease = [];
+ } else {
+ this.prerelease = m[4].split(".").map((id) => {
+ if (/^[0-9]+$/.test(id)) {
+ const num = +id;
+ if (num >= 0 && num < MAX_SAFE_INTEGER) {
+ return num;
+ }
+ }
+ return id;
+ });
+ }
+ this.build = m[5] ? m[5].split(".") : [];
+ this.format();
+ }
+ format() {
+ this.version = `${this.major}.${this.minor}.${this.patch}`;
+ if (this.prerelease.length) {
+ this.version += `-${this.prerelease.join(".")}`;
+ }
+ return this.version;
+ }
+ toString() {
+ return this.version;
+ }
+ compare(other) {
+ debug("SemVer.compare", this.version, this.options, other);
+ if (!(other instanceof _SemVer)) {
+ if (typeof other === "string" && other === this.version) {
+ return 0;
+ }
+ other = new _SemVer(other, this.options);
+ }
+ if (other.version === this.version) {
+ return 0;
+ }
+ return this.compareMain(other) || this.comparePre(other);
+ }
+ compareMain(other) {
+ if (!(other instanceof _SemVer)) {
+ other = new _SemVer(other, this.options);
+ }
+ if (this.major < other.major) {
+ return -1;
+ }
+ if (this.major > other.major) {
+ return 1;
+ }
+ if (this.minor < other.minor) {
+ return -1;
+ }
+ if (this.minor > other.minor) {
+ return 1;
+ }
+ if (this.patch < other.patch) {
+ return -1;
+ }
+ if (this.patch > other.patch) {
+ return 1;
+ }
+ return 0;
+ }
+ comparePre(other) {
+ if (!(other instanceof _SemVer)) {
+ other = new _SemVer(other, this.options);
+ }
+ if (this.prerelease.length && !other.prerelease.length) {
+ return -1;
+ } else if (!this.prerelease.length && other.prerelease.length) {
+ return 1;
+ } else if (!this.prerelease.length && !other.prerelease.length) {
+ return 0;
+ }
+ let i = 0;
+ do {
+ const a = this.prerelease[i];
+ const b = other.prerelease[i];
+ debug("prerelease compare", i, a, b);
+ if (a === void 0 && b === void 0) {
+ return 0;
+ } else if (b === void 0) {
+ return 1;
+ } else if (a === void 0) {
+ return -1;
+ } else if (a === b) {
+ continue;
+ } else {
+ return compareIdentifiers(a, b);
+ }
+ } while (++i);
+ }
+ compareBuild(other) {
+ if (!(other instanceof _SemVer)) {
+ other = new _SemVer(other, this.options);
+ }
+ let i = 0;
+ do {
+ const a = this.build[i];
+ const b = other.build[i];
+ debug("build compare", i, a, b);
+ if (a === void 0 && b === void 0) {
+ return 0;
+ } else if (b === void 0) {
+ return 1;
+ } else if (a === void 0) {
+ return -1;
+ } else if (a === b) {
+ continue;
+ } else {
+ return compareIdentifiers(a, b);
+ }
+ } while (++i);
+ }
+ // preminor will bump the version up to the next minor release, and immediately
+ // down to pre-release. premajor and prepatch work the same way.
+ inc(release2, identifier, identifierBase) {
+ if (release2.startsWith("pre")) {
+ if (!identifier && identifierBase === false) {
+ throw new Error("invalid increment argument: identifier is empty");
+ }
+ if (identifier) {
+ const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE]);
+ if (!match || match[1] !== identifier) {
+ throw new Error(`invalid identifier: ${identifier}`);
+ }
+ }
+ }
+ switch (release2) {
+ case "premajor":
+ this.prerelease.length = 0;
+ this.patch = 0;
+ this.minor = 0;
+ this.major++;
+ this.inc("pre", identifier, identifierBase);
+ break;
+ case "preminor":
+ this.prerelease.length = 0;
+ this.patch = 0;
+ this.minor++;
+ this.inc("pre", identifier, identifierBase);
+ break;
+ case "prepatch":
+ this.prerelease.length = 0;
+ this.inc("patch", identifier, identifierBase);
+ this.inc("pre", identifier, identifierBase);
+ break;
+ // If the input is a non-prerelease version, this acts the same as
+ // prepatch.
+ case "prerelease":
+ if (this.prerelease.length === 0) {
+ this.inc("patch", identifier, identifierBase);
+ }
+ this.inc("pre", identifier, identifierBase);
+ break;
+ case "release":
+ if (this.prerelease.length === 0) {
+ throw new Error(`version ${this.raw} is not a prerelease`);
+ }
+ this.prerelease.length = 0;
+ break;
+ case "major":
+ if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
+ this.major++;
+ }
+ this.minor = 0;
+ this.patch = 0;
+ this.prerelease = [];
+ break;
+ case "minor":
+ if (this.patch !== 0 || this.prerelease.length === 0) {
+ this.minor++;
+ }
+ this.patch = 0;
+ this.prerelease = [];
+ break;
+ case "patch":
+ if (this.prerelease.length === 0) {
+ this.patch++;
+ }
+ this.prerelease = [];
+ break;
+ // This probably shouldn't be used publicly.
+ // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
+ case "pre": {
+ const base = Number(identifierBase) ? 1 : 0;
+ if (this.prerelease.length === 0) {
+ this.prerelease = [base];
+ } else {
+ let i = this.prerelease.length;
+ while (--i >= 0) {
+ if (typeof this.prerelease[i] === "number") {
+ this.prerelease[i]++;
+ i = -2;
+ }
+ }
+ if (i === -1) {
+ if (identifier === this.prerelease.join(".") && identifierBase === false) {
+ throw new Error("invalid increment argument: identifier already exists");
+ }
+ this.prerelease.push(base);
+ }
+ }
+ if (identifier) {
+ let prerelease = [identifier, base];
+ if (identifierBase === false) {
+ prerelease = [identifier];
+ }
+ if (isPrereleaseIdentifier(this.prerelease, identifier)) {
+ const prereleaseBase = this.prerelease[identifier.split(".").length];
+ if (isNaN(prereleaseBase)) {
+ this.prerelease = prerelease;
+ }
+ } else {
+ this.prerelease = prerelease;
+ }
+ }
+ break;
+ }
+ default:
+ throw new Error(`invalid increment argument: ${release2}`);
+ }
+ this.raw = this.format();
+ if (this.build.length) {
+ this.raw += `+${this.build.join(".")}`;
+ }
+ return this;
+ }
+ };
+ module2.exports = SemVer;
+ }
+});
+
+// node_modules/read-package-up/node_modules/semver/functions/parse.js
+var require_parse3 = __commonJS({
+ "node_modules/read-package-up/node_modules/semver/functions/parse.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var SemVer = require_semver();
+ var parse4 = /* @__PURE__ */ __name((version2, options2, throwErrors = false) => {
+ if (version2 instanceof SemVer) {
+ return version2;
+ }
+ try {
+ return new SemVer(version2, options2);
+ } catch (er) {
+ if (!throwErrors) {
+ return null;
+ }
+ throw er;
+ }
+ }, "parse");
+ module2.exports = parse4;
+ }
+});
+
+// node_modules/read-package-up/node_modules/semver/functions/valid.js
+var require_valid = __commonJS({
+ "node_modules/read-package-up/node_modules/semver/functions/valid.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var parse4 = require_parse3();
+ var valid = /* @__PURE__ */ __name((version2, options2) => {
+ const v = parse4(version2, options2);
+ return v ? v.version : null;
+ }, "valid");
+ module2.exports = valid;
+ }
+});
+
+// node_modules/read-package-up/node_modules/semver/functions/clean.js
+var require_clean = __commonJS({
+ "node_modules/read-package-up/node_modules/semver/functions/clean.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var parse4 = require_parse3();
+ var clean = /* @__PURE__ */ __name((version2, options2) => {
+ const s = parse4(version2.trim().replace(/^[=v]+/, ""), options2);
+ return s ? s.version : null;
+ }, "clean");
+ module2.exports = clean;
+ }
+});
+
+// node_modules/spdx-license-ids/index.json
+var require_spdx_license_ids = __commonJS({
+ "node_modules/spdx-license-ids/index.json"(exports2, module2) {
+ module2.exports = [
+ "0BSD",
+ "3D-Slicer-1.0",
+ "AAL",
+ "ADSL",
+ "AFL-1.1",
+ "AFL-1.2",
+ "AFL-2.0",
+ "AFL-2.1",
+ "AFL-3.0",
+ "AGPL-1.0-only",
+ "AGPL-1.0-or-later",
+ "AGPL-3.0-only",
+ "AGPL-3.0-or-later",
+ "ALGLIB-Documentation",
+ "AMD-newlib",
+ "AMDPLPA",
+ "AML",
+ "AML-glslang",
+ "AMPAS",
+ "ANTLR-PD",
+ "ANTLR-PD-fallback",
+ "APAFML",
+ "APL-1.0",
+ "APSL-1.0",
+ "APSL-1.1",
+ "APSL-1.2",
+ "APSL-2.0",
+ "ASWF-Digital-Assets-1.0",
+ "ASWF-Digital-Assets-1.1",
+ "Abstyles",
+ "AdaCore-doc",
+ "Adobe-2006",
+ "Adobe-Display-PostScript",
+ "Adobe-Glyph",
+ "Adobe-Utopia",
+ "Advanced-Cryptics-Dictionary",
+ "Afmparse",
+ "Aladdin",
+ "Apache-1.0",
+ "Apache-1.1",
+ "Apache-2.0",
+ "App-s2p",
+ "Arphic-1999",
+ "Artistic-1.0",
+ "Artistic-1.0-Perl",
+ "Artistic-1.0-cl8",
+ "Artistic-2.0",
+ "Artistic-dist",
+ "Aspell-RU",
+ "BOLA-1.1",
+ "BSD-1-Clause",
+ "BSD-2-Clause",
+ "BSD-2-Clause-Darwin",
+ "BSD-2-Clause-Patent",
+ "BSD-2-Clause-Views",
+ "BSD-2-Clause-first-lines",
+ "BSD-2-Clause-pkgconf-disclaimer",
+ "BSD-3-Clause",
+ "BSD-3-Clause-Attribution",
+ "BSD-3-Clause-Clear",
+ "BSD-3-Clause-HP",
+ "BSD-3-Clause-LBNL",
+ "BSD-3-Clause-Modification",
+ "BSD-3-Clause-No-Military-License",
+ "BSD-3-Clause-No-Nuclear-License",
+ "BSD-3-Clause-No-Nuclear-License-2014",
+ "BSD-3-Clause-No-Nuclear-Warranty",
+ "BSD-3-Clause-Open-MPI",
+ "BSD-3-Clause-Sun",
+ "BSD-3-Clause-Tso",
+ "BSD-3-Clause-acpica",
+ "BSD-3-Clause-flex",
+ "BSD-4-Clause",
+ "BSD-4-Clause-Shortened",
+ "BSD-4-Clause-UC",
+ "BSD-4.3RENO",
+ "BSD-4.3TAHOE",
+ "BSD-Advertising-Acknowledgement",
+ "BSD-Attribution-HPND-disclaimer",
+ "BSD-Inferno-Nettverk",
+ "BSD-Mark-Modifications",
+ "BSD-Protection",
+ "BSD-Source-Code",
+ "BSD-Source-beginning-file",
+ "BSD-Systemics",
+ "BSD-Systemics-W3Works",
+ "BSL-1.0",
+ "BUSL-1.1",
+ "Baekmuk",
+ "Bahyph",
+ "Barr",
+ "Beerware",
+ "BitTorrent-1.0",
+ "BitTorrent-1.1",
+ "Bitstream-Charter",
+ "Bitstream-Vera",
+ "BlueOak-1.0.0",
+ "Boehm-GC",
+ "Boehm-GC-without-fee",
+ "Borceux",
+ "Brian-Gladman-2-Clause",
+ "Brian-Gladman-3-Clause",
+ "Buddy",
+ "C-UDA-1.0",
+ "CAL-1.0",
+ "CAL-1.0-Combined-Work-Exception",
+ "CAPEC-tou",
+ "CATOSL-1.1",
+ "CC-BY-1.0",
+ "CC-BY-2.0",
+ "CC-BY-2.5",
+ "CC-BY-2.5-AU",
+ "CC-BY-3.0",
+ "CC-BY-3.0-AT",
+ "CC-BY-3.0-AU",
+ "CC-BY-3.0-DE",
+ "CC-BY-3.0-IGO",
+ "CC-BY-3.0-NL",
+ "CC-BY-3.0-US",
+ "CC-BY-4.0",
+ "CC-BY-NC-1.0",
+ "CC-BY-NC-2.0",
+ "CC-BY-NC-2.5",
+ "CC-BY-NC-3.0",
+ "CC-BY-NC-3.0-DE",
+ "CC-BY-NC-4.0",
+ "CC-BY-NC-ND-1.0",
+ "CC-BY-NC-ND-2.0",
+ "CC-BY-NC-ND-2.5",
+ "CC-BY-NC-ND-3.0",
+ "CC-BY-NC-ND-3.0-DE",
+ "CC-BY-NC-ND-3.0-IGO",
+ "CC-BY-NC-ND-4.0",
+ "CC-BY-NC-SA-1.0",
+ "CC-BY-NC-SA-2.0",
+ "CC-BY-NC-SA-2.0-DE",
+ "CC-BY-NC-SA-2.0-FR",
+ "CC-BY-NC-SA-2.0-UK",
+ "CC-BY-NC-SA-2.5",
+ "CC-BY-NC-SA-3.0",
+ "CC-BY-NC-SA-3.0-DE",
+ "CC-BY-NC-SA-3.0-IGO",
+ "CC-BY-NC-SA-4.0",
+ "CC-BY-ND-1.0",
+ "CC-BY-ND-2.0",
+ "CC-BY-ND-2.5",
+ "CC-BY-ND-3.0",
+ "CC-BY-ND-3.0-DE",
+ "CC-BY-ND-4.0",
+ "CC-BY-SA-1.0",
+ "CC-BY-SA-2.0",
+ "CC-BY-SA-2.0-UK",
+ "CC-BY-SA-2.1-JP",
+ "CC-BY-SA-2.5",
+ "CC-BY-SA-3.0",
+ "CC-BY-SA-3.0-AT",
+ "CC-BY-SA-3.0-DE",
+ "CC-BY-SA-3.0-IGO",
+ "CC-BY-SA-4.0",
+ "CC-PDDC",
+ "CC-PDM-1.0",
+ "CC-SA-1.0",
+ "CC0-1.0",
+ "CDDL-1.0",
+ "CDDL-1.1",
+ "CDL-1.0",
+ "CDLA-Permissive-1.0",
+ "CDLA-Permissive-2.0",
+ "CDLA-Sharing-1.0",
+ "CECILL-1.0",
+ "CECILL-1.1",
+ "CECILL-2.0",
+ "CECILL-2.1",
+ "CECILL-B",
+ "CECILL-C",
+ "CERN-OHL-1.1",
+ "CERN-OHL-1.2",
+ "CERN-OHL-P-2.0",
+ "CERN-OHL-S-2.0",
+ "CERN-OHL-W-2.0",
+ "CFITSIO",
+ "CMU-Mach",
+ "CMU-Mach-nodoc",
+ "CNRI-Jython",
+ "CNRI-Python",
+ "CNRI-Python-GPL-Compatible",
+ "COIL-1.0",
+ "CPAL-1.0",
+ "CPL-1.0",
+ "CPOL-1.02",
+ "CUA-OPL-1.0",
+ "Caldera",
+ "Caldera-no-preamble",
+ "Catharon",
+ "ClArtistic",
+ "Clips",
+ "Community-Spec-1.0",
+ "Condor-1.1",
+ "Cornell-Lossless-JPEG",
+ "Cronyx",
+ "Crossword",
+ "CryptoSwift",
+ "CrystalStacker",
+ "Cube",
+ "D-FSL-1.0",
+ "DEC-3-Clause",
+ "DL-DE-BY-2.0",
+ "DL-DE-ZERO-2.0",
+ "DOC",
+ "DRL-1.0",
+ "DRL-1.1",
+ "DSDP",
+ "DocBook-DTD",
+ "DocBook-Schema",
+ "DocBook-Stylesheet",
+ "DocBook-XML",
+ "Dotseqn",
+ "ECL-1.0",
+ "ECL-2.0",
+ "EFL-1.0",
+ "EFL-2.0",
+ "EPICS",
+ "EPL-1.0",
+ "EPL-2.0",
+ "ESA-PL-permissive-2.4",
+ "ESA-PL-strong-copyleft-2.4",
+ "ESA-PL-weak-copyleft-2.4",
+ "EUDatagrid",
+ "EUPL-1.0",
+ "EUPL-1.1",
+ "EUPL-1.2",
+ "Elastic-2.0",
+ "Entessa",
+ "ErlPL-1.1",
+ "Eurosym",
+ "FBM",
+ "FDK-AAC",
+ "FSFAP",
+ "FSFAP-no-warranty-disclaimer",
+ "FSFUL",
+ "FSFULLR",
+ "FSFULLRSD",
+ "FSFULLRWD",
+ "FSL-1.1-ALv2",
+ "FSL-1.1-MIT",
+ "FTL",
+ "Fair",
+ "Ferguson-Twofish",
+ "Frameworx-1.0",
+ "FreeBSD-DOC",
+ "FreeImage",
+ "Furuseth",
+ "GCR-docs",
+ "GD",
+ "GFDL-1.1-invariants-only",
+ "GFDL-1.1-invariants-or-later",
+ "GFDL-1.1-no-invariants-only",
+ "GFDL-1.1-no-invariants-or-later",
+ "GFDL-1.1-only",
+ "GFDL-1.1-or-later",
+ "GFDL-1.2-invariants-only",
+ "GFDL-1.2-invariants-or-later",
+ "GFDL-1.2-no-invariants-only",
+ "GFDL-1.2-no-invariants-or-later",
+ "GFDL-1.2-only",
+ "GFDL-1.2-or-later",
+ "GFDL-1.3-invariants-only",
+ "GFDL-1.3-invariants-or-later",
+ "GFDL-1.3-no-invariants-only",
+ "GFDL-1.3-no-invariants-or-later",
+ "GFDL-1.3-only",
+ "GFDL-1.3-or-later",
+ "GL2PS",
+ "GLWTPL",
+ "GPL-1.0-only",
+ "GPL-1.0-or-later",
+ "GPL-2.0-only",
+ "GPL-2.0-or-later",
+ "GPL-3.0-only",
+ "GPL-3.0-or-later",
+ "Game-Programming-Gems",
+ "Giftware",
+ "Glide",
+ "Glulxe",
+ "Graphics-Gems",
+ "Gutmann",
+ "HDF5",
+ "HIDAPI",
+ "HP-1986",
+ "HP-1989",
+ "HPND",
+ "HPND-DEC",
+ "HPND-Fenneberg-Livingston",
+ "HPND-INRIA-IMAG",
+ "HPND-Intel",
+ "HPND-Kevlin-Henney",
+ "HPND-MIT-disclaimer",
+ "HPND-Markus-Kuhn",
+ "HPND-Netrek",
+ "HPND-Pbmplus",
+ "HPND-SMC",
+ "HPND-UC",
+ "HPND-UC-export-US",
+ "HPND-doc",
+ "HPND-doc-sell",
+ "HPND-export-US",
+ "HPND-export-US-acknowledgement",
+ "HPND-export-US-modify",
+ "HPND-export2-US",
+ "HPND-merchantability-variant",
+ "HPND-sell-MIT-disclaimer-xserver",
+ "HPND-sell-regexpr",
+ "HPND-sell-variant",
+ "HPND-sell-variant-MIT-disclaimer",
+ "HPND-sell-variant-MIT-disclaimer-rev",
+ "HPND-sell-variant-critical-systems",
+ "HTMLTIDY",
+ "HaskellReport",
+ "Hippocratic-2.1",
+ "IBM-pibs",
+ "ICU",
+ "IEC-Code-Components-EULA",
+ "IJG",
+ "IJG-short",
+ "IPA",
+ "IPL-1.0",
+ "ISC",
+ "ISC-Veillard",
+ "ISO-permission",
+ "ImageMagick",
+ "Imlib2",
+ "Info-ZIP",
+ "Inner-Net-2.0",
+ "InnoSetup",
+ "Intel",
+ "Intel-ACPI",
+ "Interbase-1.0",
+ "JPL-image",
+ "JPNIC",
+ "JSON",
+ "Jam",
+ "JasPer-2.0",
+ "Kastrup",
+ "Kazlib",
+ "Knuth-CTAN",
+ "LAL-1.2",
+ "LAL-1.3",
+ "LGPL-2.0-only",
+ "LGPL-2.0-or-later",
+ "LGPL-2.1-only",
+ "LGPL-2.1-or-later",
+ "LGPL-3.0-only",
+ "LGPL-3.0-or-later",
+ "LGPLLR",
+ "LOOP",
+ "LPD-document",
+ "LPL-1.0",
+ "LPL-1.02",
+ "LPPL-1.0",
+ "LPPL-1.1",
+ "LPPL-1.2",
+ "LPPL-1.3a",
+ "LPPL-1.3c",
+ "LZMA-SDK-9.11-to-9.20",
+ "LZMA-SDK-9.22",
+ "Latex2e",
+ "Latex2e-translated-notice",
+ "Leptonica",
+ "LiLiQ-P-1.1",
+ "LiLiQ-R-1.1",
+ "LiLiQ-Rplus-1.1",
+ "Libpng",
+ "Linux-OpenIB",
+ "Linux-man-pages-1-para",
+ "Linux-man-pages-copyleft",
+ "Linux-man-pages-copyleft-2-para",
+ "Linux-man-pages-copyleft-var",
+ "Lucida-Bitmap-Fonts",
+ "MIPS",
+ "MIT",
+ "MIT-0",
+ "MIT-CMU",
+ "MIT-Click",
+ "MIT-Festival",
+ "MIT-Khronos-old",
+ "MIT-Modern-Variant",
+ "MIT-STK",
+ "MIT-Wu",
+ "MIT-advertising",
+ "MIT-enna",
+ "MIT-feh",
+ "MIT-open-group",
+ "MIT-testregex",
+ "MITNFA",
+ "MMIXware",
+ "MMPL-1.0.1",
+ "MPEG-SSG",
+ "MPL-1.0",
+ "MPL-1.1",
+ "MPL-2.0",
+ "MPL-2.0-no-copyleft-exception",
+ "MS-LPL",
+ "MS-PL",
+ "MS-RL",
+ "MTLL",
+ "Mackerras-3-Clause",
+ "Mackerras-3-Clause-acknowledgment",
+ "MakeIndex",
+ "Martin-Birgmeier",
+ "McPhee-slideshow",
+ "Minpack",
+ "MirOS",
+ "Motosoto",
+ "MulanPSL-1.0",
+ "MulanPSL-2.0",
+ "Multics",
+ "Mup",
+ "NAIST-2003",
+ "NASA-1.3",
+ "NBPL-1.0",
+ "NCBI-PD",
+ "NCGL-UK-2.0",
+ "NCL",
+ "NCSA",
+ "NGPL",
+ "NICTA-1.0",
+ "NIST-PD",
+ "NIST-PD-TNT",
+ "NIST-PD-fallback",
+ "NIST-Software",
+ "NLOD-1.0",
+ "NLOD-2.0",
+ "NLPL",
+ "NOSL",
+ "NPL-1.0",
+ "NPL-1.1",
+ "NPOSL-3.0",
+ "NRL",
+ "NTIA-PD",
+ "NTP",
+ "NTP-0",
+ "Naumen",
+ "NetCDF",
+ "Newsletr",
+ "Nokia",
+ "Noweb",
+ "O-UDA-1.0",
+ "OAR",
+ "OCCT-PL",
+ "OCLC-2.0",
+ "ODC-By-1.0",
+ "ODbL-1.0",
+ "OFFIS",
+ "OFL-1.0",
+ "OFL-1.0-RFN",
+ "OFL-1.0-no-RFN",
+ "OFL-1.1",
+ "OFL-1.1-RFN",
+ "OFL-1.1-no-RFN",
+ "OGC-1.0",
+ "OGDL-Taiwan-1.0",
+ "OGL-Canada-2.0",
+ "OGL-UK-1.0",
+ "OGL-UK-2.0",
+ "OGL-UK-3.0",
+ "OGTSL",
+ "OLDAP-1.1",
+ "OLDAP-1.2",
+ "OLDAP-1.3",
+ "OLDAP-1.4",
+ "OLDAP-2.0",
+ "OLDAP-2.0.1",
+ "OLDAP-2.1",
+ "OLDAP-2.2",
+ "OLDAP-2.2.1",
+ "OLDAP-2.2.2",
+ "OLDAP-2.3",
+ "OLDAP-2.4",
+ "OLDAP-2.5",
+ "OLDAP-2.6",
+ "OLDAP-2.7",
+ "OLDAP-2.8",
+ "OLFL-1.3",
+ "OML",
+ "OPL-1.0",
+ "OPL-UK-3.0",
+ "OPUBL-1.0",
+ "OSC-1.0",
+ "OSET-PL-2.1",
+ "OSL-1.0",
+ "OSL-1.1",
+ "OSL-2.0",
+ "OSL-2.1",
+ "OSL-3.0",
+ "OSSP",
+ "OpenMDW-1.0",
+ "OpenPBS-2.3",
+ "OpenSSL",
+ "OpenSSL-standalone",
+ "OpenVision",
+ "PADL",
+ "PDDL-1.0",
+ "PHP-3.0",
+ "PHP-3.01",
+ "PPL",
+ "PSF-2.0",
+ "ParaType-Free-Font-1.3",
+ "Parity-6.0.0",
+ "Parity-7.0.0",
+ "Pixar",
+ "Plexus",
+ "PolyForm-Noncommercial-1.0.0",
+ "PolyForm-Small-Business-1.0.0",
+ "PostgreSQL",
+ "Python-2.0",
+ "Python-2.0.1",
+ "QPL-1.0",
+ "QPL-1.0-INRIA-2004",
+ "Qhull",
+ "RHeCos-1.1",
+ "RPL-1.1",
+ "RPL-1.5",
+ "RPSL-1.0",
+ "RSA-MD",
+ "RSCPL",
+ "Rdisc",
+ "Ruby",
+ "Ruby-pty",
+ "SAX-PD",
+ "SAX-PD-2.0",
+ "SCEA",
+ "SGI-B-1.0",
+ "SGI-B-1.1",
+ "SGI-B-2.0",
+ "SGI-OpenGL",
+ "SGMLUG-PM",
+ "SGP4",
+ "SHL-0.5",
+ "SHL-0.51",
+ "SISSL",
+ "SISSL-1.2",
+ "SL",
+ "SMAIL-GPL",
+ "SMLNJ",
+ "SMPPL",
+ "SNIA",
+ "SOFA",
+ "SPL-1.0",
+ "SSH-OpenSSH",
+ "SSH-short",
+ "SSLeay-standalone",
+ "SSPL-1.0",
+ "SUL-1.0",
+ "SWL",
+ "Saxpath",
+ "SchemeReport",
+ "Sendmail",
+ "Sendmail-8.23",
+ "Sendmail-Open-Source-1.1",
+ "SimPL-2.0",
+ "Sleepycat",
+ "Soundex",
+ "Spencer-86",
+ "Spencer-94",
+ "Spencer-99",
+ "SugarCRM-1.1.3",
+ "Sun-PPP",
+ "Sun-PPP-2000",
+ "SunPro",
+ "Symlinks",
+ "TAPR-OHL-1.0",
+ "TCL",
+ "TCP-wrappers",
+ "TGPPL-1.0",
+ "TMate",
+ "TORQUE-1.1",
+ "TOSL",
+ "TPDL",
+ "TPL-1.0",
+ "TTWL",
+ "TTYP0",
+ "TU-Berlin-1.0",
+ "TU-Berlin-2.0",
+ "TekHVC",
+ "TermReadKey",
+ "ThirdEye",
+ "TrustedQSL",
+ "UCAR",
+ "UCL-1.0",
+ "UMich-Merit",
+ "UPL-1.0",
+ "URT-RLE",
+ "Ubuntu-font-1.0",
+ "UnRAR",
+ "Unicode-3.0",
+ "Unicode-DFS-2015",
+ "Unicode-DFS-2016",
+ "Unicode-TOU",
+ "UnixCrypt",
+ "Unlicense",
+ "Unlicense-libtelnet",
+ "Unlicense-libwhirlpool",
+ "VOSTROM",
+ "VSL-1.0",
+ "Vim",
+ "Vixie-Cron",
+ "W3C",
+ "W3C-19980720",
+ "W3C-20150513",
+ "WTFNMFPL",
+ "WTFPL",
+ "Watcom-1.0",
+ "Widget-Workshop",
+ "WordNet",
+ "Wsuipa",
+ "X11",
+ "X11-distribute-modifications-variant",
+ "X11-no-permit-persons",
+ "X11-swapped",
+ "XFree86-1.1",
+ "XSkat",
+ "Xdebug-1.03",
+ "Xerox",
+ "Xfig",
+ "Xnet",
+ "YPL-1.0",
+ "YPL-1.1",
+ "ZPL-1.1",
+ "ZPL-2.0",
+ "ZPL-2.1",
+ "Zed",
+ "Zeeff",
+ "Zend-2.0",
+ "Zimbra-1.3",
+ "Zimbra-1.4",
+ "Zlib",
+ "any-OSI",
+ "any-OSI-perl-modules",
+ "bcrypt-Solar-Designer",
+ "blessing",
+ "bzip2-1.0.6",
+ "check-cvs",
+ "checkmk",
+ "copyleft-next-0.3.0",
+ "copyleft-next-0.3.1",
+ "curl",
+ "cve-tou",
+ "diffmark",
+ "dtoa",
+ "dvipdfm",
+ "eGenix",
+ "etalab-2.0",
+ "fwlw",
+ "gSOAP-1.3b",
+ "generic-xts",
+ "gnuplot",
+ "gtkbook",
+ "hdparm",
+ "hyphen-bulgarian",
+ "iMatix",
+ "jove",
+ "libpng-1.6.35",
+ "libpng-2.0",
+ "libselinux-1.0",
+ "libtiff",
+ "libutil-David-Nugent",
+ "lsof",
+ "magaz",
+ "mailprio",
+ "man2html",
+ "metamail",
+ "mpi-permissive",
+ "mpich2",
+ "mplus",
+ "ngrep",
+ "pkgconf",
+ "pnmstitch",
+ "psfrag",
+ "psutils",
+ "python-ldap",
+ "radvd",
+ "snprintf",
+ "softSurfer",
+ "ssh-keyscan",
+ "swrule",
+ "threeparttable",
+ "ulem",
+ "w3m",
+ "wwl",
+ "xinetd",
+ "xkeyboard-config-Zinoviev",
+ "xlock",
+ "xpp",
+ "xzoom",
+ "zlib-acknowledgement"
+ ];
+ }
+});
+
+// node_modules/spdx-license-ids/deprecated.json
+var require_deprecated = __commonJS({
+ "node_modules/spdx-license-ids/deprecated.json"(exports2, module2) {
+ module2.exports = [
+ "AGPL-1.0",
+ "AGPL-3.0",
+ "BSD-2-Clause-FreeBSD",
+ "BSD-2-Clause-NetBSD",
+ "GFDL-1.1",
+ "GFDL-1.2",
+ "GFDL-1.3",
+ "GPL-1.0",
+ "GPL-2.0",
+ "GPL-2.0-with-GCC-exception",
+ "GPL-2.0-with-autoconf-exception",
+ "GPL-2.0-with-bison-exception",
+ "GPL-2.0-with-classpath-exception",
+ "GPL-2.0-with-font-exception",
+ "GPL-3.0",
+ "GPL-3.0-with-GCC-exception",
+ "GPL-3.0-with-autoconf-exception",
+ "LGPL-2.0",
+ "LGPL-2.1",
+ "LGPL-3.0",
+ "Net-SNMP",
+ "Nunit",
+ "StandardML-NJ",
+ "bzip2-1.0.5",
+ "eCos-2.0",
+ "wxWindows"
+ ];
+ }
+});
+
+// node_modules/spdx-exceptions/index.json
+var require_spdx_exceptions = __commonJS({
+ "node_modules/spdx-exceptions/index.json"(exports2, module2) {
+ module2.exports = [
+ "389-exception",
+ "Asterisk-exception",
+ "Autoconf-exception-2.0",
+ "Autoconf-exception-3.0",
+ "Autoconf-exception-generic",
+ "Autoconf-exception-generic-3.0",
+ "Autoconf-exception-macro",
+ "Bison-exception-1.24",
+ "Bison-exception-2.2",
+ "Bootloader-exception",
+ "Classpath-exception-2.0",
+ "CLISP-exception-2.0",
+ "cryptsetup-OpenSSL-exception",
+ "DigiRule-FOSS-exception",
+ "eCos-exception-2.0",
+ "Fawkes-Runtime-exception",
+ "FLTK-exception",
+ "fmt-exception",
+ "Font-exception-2.0",
+ "freertos-exception-2.0",
+ "GCC-exception-2.0",
+ "GCC-exception-2.0-note",
+ "GCC-exception-3.1",
+ "Gmsh-exception",
+ "GNAT-exception",
+ "GNOME-examples-exception",
+ "GNU-compiler-exception",
+ "gnu-javamail-exception",
+ "GPL-3.0-interface-exception",
+ "GPL-3.0-linking-exception",
+ "GPL-3.0-linking-source-exception",
+ "GPL-CC-1.0",
+ "GStreamer-exception-2005",
+ "GStreamer-exception-2008",
+ "i2p-gpl-java-exception",
+ "KiCad-libraries-exception",
+ "LGPL-3.0-linking-exception",
+ "libpri-OpenH323-exception",
+ "Libtool-exception",
+ "Linux-syscall-note",
+ "LLGPL",
+ "LLVM-exception",
+ "LZMA-exception",
+ "mif-exception",
+ "OCaml-LGPL-linking-exception",
+ "OCCT-exception-1.0",
+ "OpenJDK-assembly-exception-1.0",
+ "openvpn-openssl-exception",
+ "PS-or-PDF-font-exception-20170817",
+ "QPL-1.0-INRIA-2004-exception",
+ "Qt-GPL-exception-1.0",
+ "Qt-LGPL-exception-1.1",
+ "Qwt-exception-1.0",
+ "SANE-exception",
+ "SHL-2.0",
+ "SHL-2.1",
+ "stunnel-exception",
+ "SWI-exception",
+ "Swift-exception",
+ "Texinfo-exception",
+ "u-boot-exception-2.0",
+ "UBDL-exception",
+ "Universal-FOSS-exception-1.0",
+ "vsftpd-openssl-exception",
+ "WxWindows-exception-3.1",
+ "x11vnc-openssl-exception"
+ ];
+ }
+});
+
+// node_modules/spdx-expression-parse/scan.js
+var require_scan = __commonJS({
+ "node_modules/spdx-expression-parse/scan.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var licenses = [].concat(require_spdx_license_ids()).concat(require_deprecated());
+ var exceptions = require_spdx_exceptions();
+ module2.exports = function(source) {
+ var index = 0;
+ function hasMore() {
+ return index < source.length;
+ }
+ __name(hasMore, "hasMore");
+ function read(value) {
+ if (value instanceof RegExp) {
+ var chars = source.slice(index);
+ var match = chars.match(value);
+ if (match) {
+ index += match[0].length;
+ return match[0];
+ }
+ } else {
+ if (source.indexOf(value, index) === index) {
+ index += value.length;
+ return value;
+ }
+ }
+ }
+ __name(read, "read");
+ function skipWhitespace() {
+ read(/[ ]*/);
+ }
+ __name(skipWhitespace, "skipWhitespace");
+ function operator() {
+ var string4;
+ var possibilities = ["WITH", "AND", "OR", "(", ")", ":", "+"];
+ for (var i = 0; i < possibilities.length; i++) {
+ string4 = read(possibilities[i]);
+ if (string4) {
+ break;
+ }
+ }
+ if (string4 === "+" && index > 1 && source[index - 2] === " ") {
+ throw new Error("Space before `+`");
+ }
+ return string4 && {
+ type: "OPERATOR",
+ string: string4
+ };
+ }
+ __name(operator, "operator");
+ function idstring() {
+ return read(/[A-Za-z0-9-.]+/);
+ }
+ __name(idstring, "idstring");
+ function expectIdstring() {
+ var string4 = idstring();
+ if (!string4) {
+ throw new Error("Expected idstring at offset " + index);
+ }
+ return string4;
+ }
+ __name(expectIdstring, "expectIdstring");
+ function documentRef() {
+ if (read("DocumentRef-")) {
+ var string4 = expectIdstring();
+ return { type: "DOCUMENTREF", string: string4 };
+ }
+ }
+ __name(documentRef, "documentRef");
+ function licenseRef() {
+ if (read("LicenseRef-")) {
+ var string4 = expectIdstring();
+ return { type: "LICENSEREF", string: string4 };
+ }
+ }
+ __name(licenseRef, "licenseRef");
+ function identifier() {
+ var begin = index;
+ var string4 = idstring();
+ if (licenses.indexOf(string4) !== -1) {
+ return {
+ type: "LICENSE",
+ string: string4
+ };
+ } else if (exceptions.indexOf(string4) !== -1) {
+ return {
+ type: "EXCEPTION",
+ string: string4
+ };
+ }
+ index = begin;
+ }
+ __name(identifier, "identifier");
+ function parseToken() {
+ return operator() || documentRef() || licenseRef() || identifier();
+ }
+ __name(parseToken, "parseToken");
+ var tokens = [];
+ while (hasMore()) {
+ skipWhitespace();
+ if (!hasMore()) {
+ break;
+ }
+ var token = parseToken();
+ if (!token) {
+ throw new Error("Unexpected `" + source[index] + "` at offset " + index);
+ }
+ tokens.push(token);
+ }
+ return tokens;
+ };
+ }
+});
+
+// node_modules/spdx-expression-parse/parse.js
+var require_parse4 = __commonJS({
+ "node_modules/spdx-expression-parse/parse.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ module2.exports = function(tokens) {
+ var index = 0;
+ function hasMore() {
+ return index < tokens.length;
+ }
+ __name(hasMore, "hasMore");
+ function token() {
+ return hasMore() ? tokens[index] : null;
+ }
+ __name(token, "token");
+ function next() {
+ if (!hasMore()) {
+ throw new Error();
+ }
+ index++;
+ }
+ __name(next, "next");
+ function parseOperator(operator) {
+ var t = token();
+ if (t && t.type === "OPERATOR" && operator === t.string) {
+ next();
+ return t.string;
+ }
+ }
+ __name(parseOperator, "parseOperator");
+ function parseWith() {
+ if (parseOperator("WITH")) {
+ var t = token();
+ if (t && t.type === "EXCEPTION") {
+ next();
+ return t.string;
+ }
+ throw new Error("Expected exception after `WITH`");
+ }
+ }
+ __name(parseWith, "parseWith");
+ function parseLicenseRef() {
+ var begin = index;
+ var string4 = "";
+ var t = token();
+ if (t.type === "DOCUMENTREF") {
+ next();
+ string4 += "DocumentRef-" + t.string + ":";
+ if (!parseOperator(":")) {
+ throw new Error("Expected `:` after `DocumentRef-...`");
+ }
+ }
+ t = token();
+ if (t.type === "LICENSEREF") {
+ next();
+ string4 += "LicenseRef-" + t.string;
+ return { license: string4 };
+ }
+ index = begin;
+ }
+ __name(parseLicenseRef, "parseLicenseRef");
+ function parseLicense() {
+ var t = token();
+ if (t && t.type === "LICENSE") {
+ next();
+ var node2 = { license: t.string };
+ if (parseOperator("+")) {
+ node2.plus = true;
+ }
+ var exception = parseWith();
+ if (exception) {
+ node2.exception = exception;
+ }
+ return node2;
+ }
+ }
+ __name(parseLicense, "parseLicense");
+ function parseParenthesizedExpression() {
+ var left2 = parseOperator("(");
+ if (!left2) {
+ return;
+ }
+ var expr = parseExpression();
+ if (!parseOperator(")")) {
+ throw new Error("Expected `)`");
+ }
+ return expr;
+ }
+ __name(parseParenthesizedExpression, "parseParenthesizedExpression");
+ function parseAtom() {
+ return parseParenthesizedExpression() || parseLicenseRef() || parseLicense();
+ }
+ __name(parseAtom, "parseAtom");
+ function makeBinaryOpParser(operator, nextParser) {
+ return /* @__PURE__ */ __name(function parseBinaryOp() {
+ var left2 = nextParser();
+ if (!left2) {
+ return;
+ }
+ if (!parseOperator(operator)) {
+ return left2;
+ }
+ var right2 = parseBinaryOp();
+ if (!right2) {
+ throw new Error("Expected expression");
+ }
+ return {
+ left: left2,
+ conjunction: operator.toLowerCase(),
+ right: right2
+ };
+ }, "parseBinaryOp");
+ }
+ __name(makeBinaryOpParser, "makeBinaryOpParser");
+ var parseAnd = makeBinaryOpParser("AND", parseAtom);
+ var parseExpression = makeBinaryOpParser("OR", parseAnd);
+ var node = parseExpression();
+ if (!node || hasMore()) {
+ throw new Error("Syntax error");
+ }
+ return node;
+ };
+ }
+});
+
+// node_modules/spdx-expression-parse/index.js
+var require_spdx_expression_parse = __commonJS({
+ "node_modules/spdx-expression-parse/index.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var scan = require_scan();
+ var parse4 = require_parse4();
+ module2.exports = function(source) {
+ return parse4(scan(source));
+ };
+ }
+});
+
+// node_modules/spdx-correct/index.js
+var require_spdx_correct = __commonJS({
+ "node_modules/spdx-correct/index.js"(exports2, module2) {
+ init_esbuild_shims();
+ var parse4 = require_spdx_expression_parse();
+ var spdxLicenseIds = require_spdx_license_ids();
+ function valid(string4) {
+ try {
+ parse4(string4);
+ return true;
+ } catch (error51) {
+ return false;
+ }
+ }
+ __name(valid, "valid");
+ function sortTranspositions(a, b) {
+ var length = b[0].length - a[0].length;
+ if (length !== 0) return length;
+ return a[0].toUpperCase().localeCompare(b[0].toUpperCase());
+ }
+ __name(sortTranspositions, "sortTranspositions");
+ var transpositions = [
+ ["APGL", "AGPL"],
+ ["Gpl", "GPL"],
+ ["GLP", "GPL"],
+ ["APL", "Apache"],
+ ["ISD", "ISC"],
+ ["GLP", "GPL"],
+ ["IST", "ISC"],
+ ["Claude", "Clause"],
+ [" or later", "+"],
+ [" International", ""],
+ ["GNU", "GPL"],
+ ["GUN", "GPL"],
+ ["+", ""],
+ ["GNU GPL", "GPL"],
+ ["GNU LGPL", "LGPL"],
+ ["GNU/GPL", "GPL"],
+ ["GNU GLP", "GPL"],
+ ["GNU LESSER GENERAL PUBLIC LICENSE", "LGPL"],
+ ["GNU Lesser General Public License", "LGPL"],
+ ["GNU LESSER GENERAL PUBLIC LICENSE", "LGPL-2.1"],
+ ["GNU Lesser General Public License", "LGPL-2.1"],
+ ["LESSER GENERAL PUBLIC LICENSE", "LGPL"],
+ ["Lesser General Public License", "LGPL"],
+ ["LESSER GENERAL PUBLIC LICENSE", "LGPL-2.1"],
+ ["Lesser General Public License", "LGPL-2.1"],
+ ["GNU General Public License", "GPL"],
+ ["Gnu public license", "GPL"],
+ ["GNU Public License", "GPL"],
+ ["GNU GENERAL PUBLIC LICENSE", "GPL"],
+ ["MTI", "MIT"],
+ ["Mozilla Public License", "MPL"],
+ ["Universal Permissive License", "UPL"],
+ ["WTH", "WTF"],
+ ["WTFGPL", "WTFPL"],
+ ["-License", ""]
+ ].sort(sortTranspositions);
+ var TRANSPOSED = 0;
+ var CORRECT = 1;
+ var transforms = [
+ // e.g. 'mit'
+ function(argument) {
+ return argument.toUpperCase();
+ },
+ // e.g. 'MIT '
+ function(argument) {
+ return argument.trim();
+ },
+ // e.g. 'M.I.T.'
+ function(argument) {
+ return argument.replace(/\./g, "");
+ },
+ // e.g. 'Apache- 2.0'
+ function(argument) {
+ return argument.replace(/\s+/g, "");
+ },
+ // e.g. 'CC BY 4.0''
+ function(argument) {
+ return argument.replace(/\s+/g, "-");
+ },
+ // e.g. 'LGPLv2.1'
+ function(argument) {
+ return argument.replace("v", "-");
+ },
+ // e.g. 'Apache 2.0'
+ function(argument) {
+ return argument.replace(/,?\s*(\d)/, "-$1");
+ },
+ // e.g. 'GPL 2'
+ function(argument) {
+ return argument.replace(/,?\s*(\d)/, "-$1.0");
+ },
+ // e.g. 'Apache Version 2.0'
+ function(argument) {
+ return argument.replace(/,?\s*(V\.|v\.|V|v|Version|version)\s*(\d)/, "-$2");
+ },
+ // e.g. 'Apache Version 2'
+ function(argument) {
+ return argument.replace(/,?\s*(V\.|v\.|V|v|Version|version)\s*(\d)/, "-$2.0");
+ },
+ // e.g. 'ZLIB'
+ function(argument) {
+ return argument[0].toUpperCase() + argument.slice(1);
+ },
+ // e.g. 'MPL/2.0'
+ function(argument) {
+ return argument.replace("/", "-");
+ },
+ // e.g. 'Apache 2'
+ function(argument) {
+ return argument.replace(/\s*V\s*(\d)/, "-$1").replace(/(\d)$/, "$1.0");
+ },
+ // e.g. 'GPL-2.0', 'GPL-3.0'
+ function(argument) {
+ if (argument.indexOf("3.0") !== -1) {
+ return argument + "-or-later";
+ } else {
+ return argument + "-only";
+ }
+ },
+ // e.g. 'GPL-2.0-'
+ function(argument) {
+ return argument + "only";
+ },
+ // e.g. 'GPL2'
+ function(argument) {
+ return argument.replace(/(\d)$/, "-$1.0");
+ },
+ // e.g. 'BSD 3'
+ function(argument) {
+ return argument.replace(/(-| )?(\d)$/, "-$2-Clause");
+ },
+ // e.g. 'BSD clause 3'
+ function(argument) {
+ return argument.replace(/(-| )clause(-| )(\d)/, "-$3-Clause");
+ },
+ // e.g. 'New BSD license'
+ function(argument) {
+ return argument.replace(/\b(Modified|New|Revised)(-| )?BSD((-| )License)?/i, "BSD-3-Clause");
+ },
+ // e.g. 'Simplified BSD license'
+ function(argument) {
+ return argument.replace(/\bSimplified(-| )?BSD((-| )License)?/i, "BSD-2-Clause");
+ },
+ // e.g. 'Free BSD license'
+ function(argument) {
+ return argument.replace(/\b(Free|Net)(-| )?BSD((-| )License)?/i, "BSD-2-Clause-$1BSD");
+ },
+ // e.g. 'Clear BSD license'
+ function(argument) {
+ return argument.replace(/\bClear(-| )?BSD((-| )License)?/i, "BSD-3-Clause-Clear");
+ },
+ // e.g. 'Old BSD License'
+ function(argument) {
+ return argument.replace(/\b(Old|Original)(-| )?BSD((-| )License)?/i, "BSD-4-Clause");
+ },
+ // e.g. 'BY-NC-4.0'
+ function(argument) {
+ return "CC-" + argument;
+ },
+ // e.g. 'BY-NC'
+ function(argument) {
+ return "CC-" + argument + "-4.0";
+ },
+ // e.g. 'Attribution-NonCommercial'
+ function(argument) {
+ return argument.replace("Attribution", "BY").replace("NonCommercial", "NC").replace("NoDerivatives", "ND").replace(/ (\d)/, "-$1").replace(/ ?International/, "");
+ },
+ // e.g. 'Attribution-NonCommercial'
+ function(argument) {
+ return "CC-" + argument.replace("Attribution", "BY").replace("NonCommercial", "NC").replace("NoDerivatives", "ND").replace(/ (\d)/, "-$1").replace(/ ?International/, "") + "-4.0";
+ }
+ ];
+ var licensesWithVersions = spdxLicenseIds.map(function(id) {
+ var match = /^(.*)-\d+\.\d+$/.exec(id);
+ return match ? [match[0], match[1]] : [id, null];
+ }).reduce(function(objectMap, item) {
+ var key = item[1];
+ objectMap[key] = objectMap[key] || [];
+ objectMap[key].push(item[0]);
+ return objectMap;
+ }, {});
+ var licensesWithOneVersion = Object.keys(licensesWithVersions).map(/* @__PURE__ */ __name(function makeEntries(key) {
+ return [key, licensesWithVersions[key]];
+ }, "makeEntries")).filter(/* @__PURE__ */ __name(function identifySoleVersions(item) {
+ return (
+ // Licenses has just one valid version suffix.
+ item[1].length === 1 && item[0] !== null && // APL will be considered Apache, rather than APL-1.0
+ item[0] !== "APL"
+ );
+ }, "identifySoleVersions")).map(/* @__PURE__ */ __name(function createLastResorts(item) {
+ return [item[0], item[1][0]];
+ }, "createLastResorts"));
+ licensesWithVersions = void 0;
+ var lastResorts = [
+ ["UNLI", "Unlicense"],
+ ["WTF", "WTFPL"],
+ ["2 CLAUSE", "BSD-2-Clause"],
+ ["2-CLAUSE", "BSD-2-Clause"],
+ ["3 CLAUSE", "BSD-3-Clause"],
+ ["3-CLAUSE", "BSD-3-Clause"],
+ ["AFFERO", "AGPL-3.0-or-later"],
+ ["AGPL", "AGPL-3.0-or-later"],
+ ["APACHE", "Apache-2.0"],
+ ["ARTISTIC", "Artistic-2.0"],
+ ["Affero", "AGPL-3.0-or-later"],
+ ["BEER", "Beerware"],
+ ["BOOST", "BSL-1.0"],
+ ["BSD", "BSD-2-Clause"],
+ ["CDDL", "CDDL-1.1"],
+ ["ECLIPSE", "EPL-1.0"],
+ ["FUCK", "WTFPL"],
+ ["GNU", "GPL-3.0-or-later"],
+ ["LGPL", "LGPL-3.0-or-later"],
+ ["GPLV1", "GPL-1.0-only"],
+ ["GPL-1", "GPL-1.0-only"],
+ ["GPLV2", "GPL-2.0-only"],
+ ["GPL-2", "GPL-2.0-only"],
+ ["GPL", "GPL-3.0-or-later"],
+ ["MIT +NO-FALSE-ATTRIBS", "MITNFA"],
+ ["MIT", "MIT"],
+ ["MPL", "MPL-2.0"],
+ ["X11", "X11"],
+ ["ZLIB", "Zlib"]
+ ].concat(licensesWithOneVersion).sort(sortTranspositions);
+ var SUBSTRING = 0;
+ var IDENTIFIER = 1;
+ var validTransformation = /* @__PURE__ */ __name(function(identifier) {
+ for (var i = 0; i < transforms.length; i++) {
+ var transformed = transforms[i](identifier).trim();
+ if (transformed !== identifier && valid(transformed)) {
+ return transformed;
+ }
+ }
+ return null;
+ }, "validTransformation");
+ var validLastResort = /* @__PURE__ */ __name(function(identifier) {
+ var upperCased = identifier.toUpperCase();
+ for (var i = 0; i < lastResorts.length; i++) {
+ var lastResort = lastResorts[i];
+ if (upperCased.indexOf(lastResort[SUBSTRING]) > -1) {
+ return lastResort[IDENTIFIER];
+ }
+ }
+ return null;
+ }, "validLastResort");
+ var anyCorrection = /* @__PURE__ */ __name(function(identifier, check3) {
+ for (var i = 0; i < transpositions.length; i++) {
+ var transposition = transpositions[i];
+ var transposed = transposition[TRANSPOSED];
+ if (identifier.indexOf(transposed) > -1) {
+ var corrected = identifier.replace(
+ transposed,
+ transposition[CORRECT]
+ );
+ var checked = check3(corrected);
+ if (checked !== null) {
+ return checked;
+ }
+ }
+ }
+ return null;
+ }, "anyCorrection");
+ module2.exports = function(identifier, options2) {
+ options2 = options2 || {};
+ var upgrade = options2.upgrade === void 0 ? true : !!options2.upgrade;
+ function postprocess(value) {
+ return upgrade ? upgradeGPLs(value) : value;
+ }
+ __name(postprocess, "postprocess");
+ var validArugment = typeof identifier === "string" && identifier.trim().length !== 0;
+ if (!validArugment) {
+ throw Error("Invalid argument. Expected non-empty string.");
+ }
+ identifier = identifier.trim();
+ if (valid(identifier)) {
+ return postprocess(identifier);
+ }
+ var noPlus = identifier.replace(/\+$/, "").trim();
+ if (valid(noPlus)) {
+ return postprocess(noPlus);
+ }
+ var transformed = validTransformation(identifier);
+ if (transformed !== null) {
+ return postprocess(transformed);
+ }
+ transformed = anyCorrection(identifier, function(argument) {
+ if (valid(argument)) {
+ return argument;
+ }
+ return validTransformation(argument);
+ });
+ if (transformed !== null) {
+ return postprocess(transformed);
+ }
+ transformed = validLastResort(identifier);
+ if (transformed !== null) {
+ return postprocess(transformed);
+ }
+ transformed = anyCorrection(identifier, validLastResort);
+ if (transformed !== null) {
+ return postprocess(transformed);
+ }
+ return null;
+ };
+ function upgradeGPLs(value) {
+ if ([
+ "GPL-1.0",
+ "LGPL-1.0",
+ "AGPL-1.0",
+ "GPL-2.0",
+ "LGPL-2.0",
+ "AGPL-2.0",
+ "LGPL-2.1"
+ ].indexOf(value) !== -1) {
+ return value + "-only";
+ } else if ([
+ "GPL-1.0+",
+ "GPL-2.0+",
+ "GPL-3.0+",
+ "LGPL-2.0+",
+ "LGPL-2.1+",
+ "LGPL-3.0+",
+ "AGPL-1.0+",
+ "AGPL-3.0+"
+ ].indexOf(value) !== -1) {
+ return value.replace(/\+$/, "-or-later");
+ } else if (["GPL-3.0", "LGPL-3.0", "AGPL-3.0"].indexOf(value) !== -1) {
+ return value + "-or-later";
+ } else {
+ return value;
+ }
+ }
+ __name(upgradeGPLs, "upgradeGPLs");
+ }
+});
+
+// node_modules/validate-npm-package-license/index.js
+var require_validate_npm_package_license = __commonJS({
+ "node_modules/validate-npm-package-license/index.js"(exports2, module2) {
+ init_esbuild_shims();
+ var parse4 = require_spdx_expression_parse();
+ var correct = require_spdx_correct();
+ var genericWarning = 'license should be a valid SPDX license expression (without "LicenseRef"), "UNLICENSED", or "SEE LICENSE IN "';
+ var fileReferenceRE = /^SEE LICEN[CS]E IN (.+)$/;
+ function startsWith(prefix, string4) {
+ return string4.slice(0, prefix.length) === prefix;
+ }
+ __name(startsWith, "startsWith");
+ function usesLicenseRef(ast) {
+ if (ast.hasOwnProperty("license")) {
+ var license = ast.license;
+ return startsWith("LicenseRef", license) || startsWith("DocumentRef", license);
+ } else {
+ return usesLicenseRef(ast.left) || usesLicenseRef(ast.right);
+ }
+ }
+ __name(usesLicenseRef, "usesLicenseRef");
+ module2.exports = function(argument) {
+ var ast;
+ try {
+ ast = parse4(argument);
+ } catch (e) {
+ var match;
+ if (argument === "UNLICENSED" || argument === "UNLICENCED") {
+ return {
+ validForOldPackages: true,
+ validForNewPackages: true,
+ unlicensed: true
+ };
+ } else if (match = fileReferenceRE.exec(argument)) {
+ return {
+ validForOldPackages: true,
+ validForNewPackages: true,
+ inFile: match[1]
+ };
+ } else {
+ var result = {
+ validForOldPackages: false,
+ validForNewPackages: false,
+ warnings: [genericWarning]
+ };
+ if (argument.trim().length !== 0) {
+ var corrected = correct(argument);
+ if (corrected) {
+ result.warnings.push(
+ 'license is similar to the valid expression "' + corrected + '"'
+ );
+ }
+ }
+ return result;
+ }
+ }
+ if (usesLicenseRef(ast)) {
+ return {
+ validForNewPackages: false,
+ validForOldPackages: false,
+ spdx: true,
+ warnings: [genericWarning]
+ };
+ } else {
+ return {
+ validForNewPackages: true,
+ validForOldPackages: true,
+ spdx: true
+ };
+ }
+ };
+ }
+});
+
+// node_modules/read-package-up/node_modules/lru-cache/dist/commonjs/node/index.min.js
+var require_index_min = __commonJS({
+ "node_modules/read-package-up/node_modules/lru-cache/dist/commonjs/node/index.min.js"(exports2) {
+ "use strict";
+ init_esbuild_shims();
+ var j = /* @__PURE__ */ __name((c, t) => () => (t || c((t = { exports: {} }).exports, t), t.exports), "j");
+ var I = j((O) => {
+ "use strict";
+ Object.defineProperty(O, "__esModule", { value: true });
+ O.tracing = O.metrics = void 0;
+ var U = __require("node:diagnostics_channel");
+ O.metrics = (0, U.channel)("lru-cache:metrics");
+ O.tracing = (0, U.tracingChannel)("lru-cache");
+ });
+ var P = j((D) => {
+ "use strict";
+ Object.defineProperty(D, "__esModule", { value: true });
+ D.defaultPerf = void 0;
+ D.defaultPerf = typeof performance == "object" && performance && typeof performance.now == "function" ? performance : Date;
+ });
+ Object.defineProperty(exports2, "__esModule", { value: true });
+ exports2.LRUCache = void 0;
+ var g = I();
+ var N = P();
+ var C = /* @__PURE__ */ __name(() => g.metrics.hasSubscribers || g.tracing.hasSubscribers, "C");
+ var k = /* @__PURE__ */ new Set();
+ var G = typeof process == "object" && process ? process : {};
+ var V = /* @__PURE__ */ __name((c, t, e, i) => {
+ typeof G.emitWarning == "function" ? G.emitWarning(c, t, e, i) : console.error(`[${e}] ${t}: ${c}`);
+ }, "V");
+ var q = /* @__PURE__ */ __name((c) => !k.has(c), "q");
+ var T = /* @__PURE__ */ __name((c) => !!c && c === Math.floor(c) && c > 0 && isFinite(c), "T");
+ var H = /* @__PURE__ */ __name((c) => T(c) ? c <= Math.pow(2, 8) ? Uint8Array : c <= Math.pow(2, 16) ? Uint16Array : c <= Math.pow(2, 32) ? Uint32Array : c <= Number.MAX_SAFE_INTEGER ? W : null : null, "H");
+ var W = class extends Array {
+ static {
+ __name(this, "W");
+ }
+ constructor(t) {
+ super(t), this.fill(0);
+ }
+ };
+ var x = class c {
+ static {
+ __name(this, "c");
+ }
+ heap;
+ length;
+ static #o = false;
+ static create(t) {
+ let e = H(t);
+ if (!e) return [];
+ c.#o = true;
+ let i = new c(t, e);
+ return c.#o = false, i;
+ }
+ constructor(t, e) {
+ if (!c.#o) throw new TypeError("instantiate Stack using Stack.create(n)");
+ this.heap = new e(t), this.length = 0;
+ }
+ push(t) {
+ this.heap[this.length++] = t;
+ }
+ pop() {
+ return this.heap[--this.length];
+ }
+ };
+ var L = class c {
+ static {
+ __name(this, "c");
+ }
+ #o;
+ #c;
+ #m;
+ #W;
+ #S;
+ #M;
+ #j;
+ #w;
+ get perf() {
+ return this.#w;
+ }
+ ttl;
+ ttlResolution;
+ ttlAutopurge;
+ updateAgeOnGet;
+ updateAgeOnHas;
+ allowStale;
+ noDisposeOnSet;
+ noUpdateTTL;
+ maxEntrySize;
+ sizeCalculation;
+ noDeleteOnFetchRejection;
+ noDeleteOnStaleGet;
+ allowStaleOnFetchAbort;
+ allowStaleOnFetchRejection;
+ ignoreFetchAbort;
+ backgroundFetchSize;
+ #n;
+ #b;
+ #s;
+ #i;
+ #t;
+ #l;
+ #u;
+ #a;
+ #h;
+ #_;
+ #r;
+ #y;
+ #F;
+ #d;
+ #g;
+ #T;
+ #U;
+ #f;
+ #D;
+ static unsafeExposeInternals(t) {
+ return { starts: t.#F, ttls: t.#d, autopurgeTimers: t.#g, sizes: t.#y, keyMap: t.#s, keyList: t.#i, valList: t.#t, next: t.#l, prev: t.#u, get head() {
+ return t.#a;
+ }, get tail() {
+ return t.#h;
+ }, free: t.#_, isBackgroundFetch: /* @__PURE__ */ __name((e) => t.#e(e), "isBackgroundFetch"), backgroundFetch: /* @__PURE__ */ __name((e, i, s, n) => t.#G(e, i, s, n), "backgroundFetch"), moveToTail: /* @__PURE__ */ __name((e) => t.#L(e), "moveToTail"), indexes: /* @__PURE__ */ __name((e) => t.#A(e), "indexes"), rindexes: /* @__PURE__ */ __name((e) => t.#z(e), "rindexes"), isStale: /* @__PURE__ */ __name((e) => t.#p(e), "isStale") };
+ }
+ get max() {
+ return this.#o;
+ }
+ get maxSize() {
+ return this.#c;
+ }
+ get calculatedSize() {
+ return this.#b;
+ }
+ get size() {
+ return this.#n;
+ }
+ get fetchMethod() {
+ return this.#M;
+ }
+ get memoMethod() {
+ return this.#j;
+ }
+ get dispose() {
+ return this.#m;
+ }
+ get onInsert() {
+ return this.#W;
+ }
+ get disposeAfter() {
+ return this.#S;
+ }
+ constructor(t) {
+ let { max: e = 0, ttl: i, ttlResolution: s = 1, ttlAutopurge: n, updateAgeOnGet: r, updateAgeOnHas: h, allowStale: a, dispose: o, onInsert: d, disposeAfter: _, noDisposeOnSet: y, noUpdateTTL: u, maxSize: p = 0, maxEntrySize: f = 0, sizeCalculation: b, fetchMethod: l, memoMethod: S, noDeleteOnFetchRejection: F, noDeleteOnStaleGet: w, allowStaleOnFetchRejection: m, allowStaleOnFetchAbort: A, ignoreFetchAbort: z2, backgroundFetchSize: M = 1, perf: v } = t;
+ if (this.backgroundFetchSize = M, v !== void 0 && typeof v?.now != "function") throw new TypeError("perf option must have a now() method if specified");
+ if (this.#w = v ?? N.defaultPerf, e !== 0 && !T(e)) throw new TypeError("max option must be a nonnegative integer");
+ let E = e ? H(e) : Array;
+ if (!E) throw new Error("invalid max value: " + e);
+ if (this.#o = e, this.#c = p, this.maxEntrySize = f || this.#c, this.sizeCalculation = b, this.sizeCalculation) {
+ if (!this.#c && !this.maxEntrySize) throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");
+ if (typeof this.sizeCalculation != "function") throw new TypeError("sizeCalculation set to non-function");
+ }
+ if (S !== void 0 && typeof S != "function") throw new TypeError("memoMethod must be a function if defined");
+ if (this.#j = S, l !== void 0 && typeof l != "function") throw new TypeError("fetchMethod must be a function if specified");
+ if (this.#M = l, this.#U = !!l, this.#s = /* @__PURE__ */ new Map(), this.#i = Array.from({ length: e }).fill(void 0), this.#t = Array.from({ length: e }).fill(void 0), this.#l = new E(e), this.#u = new E(e), this.#a = 0, this.#h = 0, this.#_ = x.create(e), this.#n = 0, this.#b = 0, typeof o == "function" && (this.#m = o), typeof d == "function" && (this.#W = d), typeof _ == "function" ? (this.#S = _, this.#r = []) : (this.#S = void 0, this.#r = void 0), this.#T = !!this.#m, this.#D = !!this.#W, this.#f = !!this.#S, this.noDisposeOnSet = !!y, this.noUpdateTTL = !!u, this.noDeleteOnFetchRejection = !!F, this.allowStaleOnFetchRejection = !!m, this.allowStaleOnFetchAbort = !!A, this.ignoreFetchAbort = !!z2, this.maxEntrySize !== 0) {
+ if (this.#c !== 0 && !T(this.#c)) throw new TypeError("maxSize must be a positive integer if specified");
+ if (!T(this.maxEntrySize)) throw new TypeError("maxEntrySize must be a positive integer if specified");
+ this.#X();
+ }
+ if (this.allowStale = !!a, this.noDeleteOnStaleGet = !!w, this.updateAgeOnGet = !!r, this.updateAgeOnHas = !!h, this.ttlResolution = T(s) || s === 0 ? s : 1, this.ttlAutopurge = !!n, this.ttl = i || 0, this.ttl) {
+ if (!T(this.ttl)) throw new TypeError("ttl must be a positive integer if specified");
+ this.#k();
+ }
+ if (this.#o === 0 && this.ttl === 0 && this.#c === 0) throw new TypeError("At least one of max, maxSize, or ttl is required");
+ if (!this.ttlAutopurge && !this.#o && !this.#c) {
+ let R = "LRU_CACHE_UNBOUNDED";
+ q(R) && (k.add(R), V("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.", "UnboundedCacheWarning", R, c));
+ }
+ }
+ getRemainingTTL(t) {
+ return this.#s.has(t) ? 1 / 0 : 0;
+ }
+ #k() {
+ let t = new W(this.#o), e = new W(this.#o);
+ this.#d = t, this.#F = e;
+ let i = this.ttlAutopurge ? Array.from({ length: this.#o }) : void 0;
+ this.#g = i, this.#H = (h, a, o = this.#w.now()) => {
+ e[h] = a !== 0 ? o : 0, t[h] = a, s(h, a);
+ }, this.#R = (h) => {
+ e[h] = t[h] !== 0 ? this.#w.now() : 0, s(h, t[h]);
+ };
+ let s = this.ttlAutopurge ? (h, a) => {
+ if (i?.[h] && (clearTimeout(i[h]), i[h] = void 0), a && a !== 0 && i) {
+ let o = setTimeout(() => {
+ this.#p(h) && this.#v(this.#i[h], "expire");
+ }, a + 1);
+ o.unref && o.unref(), i[h] = o;
+ }
+ } : () => {
+ };
+ this.#E = (h, a) => {
+ if (t[a]) {
+ let o = t[a], d = e[a];
+ if (!o || !d) return;
+ h.ttl = o, h.start = d, h.now = n || r();
+ let _ = h.now - d;
+ h.remainingTTL = o - _;
+ }
+ };
+ let n = 0, r = /* @__PURE__ */ __name(() => {
+ let h = this.#w.now();
+ if (this.ttlResolution > 0) {
+ n = h;
+ let a = setTimeout(() => n = 0, this.ttlResolution);
+ a.unref && a.unref();
+ }
+ return h;
+ }, "r");
+ this.getRemainingTTL = (h) => {
+ let a = this.#s.get(h);
+ if (a === void 0) return 0;
+ let o = t[a], d = e[a];
+ if (!o || !d) return 1 / 0;
+ let _ = (n || r()) - d;
+ return o - _;
+ }, this.#p = (h) => {
+ let a = e[h], o = t[h];
+ return !!o && !!a && (n || r()) - a > o;
+ };
+ }
+ #R = /* @__PURE__ */ __name(() => {
+ }, "#R");
+ #E = /* @__PURE__ */ __name(() => {
+ }, "#E");
+ #H = /* @__PURE__ */ __name(() => {
+ }, "#H");
+ #p = /* @__PURE__ */ __name(() => false, "#p");
+ #X() {
+ let t = new W(this.#o);
+ this.#b = 0, this.#y = t, this.#C = (e) => {
+ this.#b -= t[e], t[e] = 0;
+ }, this.#N = (e, i, s, n) => {
+ if (!T(s)) {
+ if (this.#e(i)) return this.backgroundFetchSize;
+ if (n) {
+ if (typeof n != "function") throw new TypeError("sizeCalculation must be a function");
+ if (s = n(i, e), !T(s)) throw new TypeError("sizeCalculation return invalid (expect positive integer)");
+ } else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");
+ }
+ return s;
+ }, this.#I = (e, i, s) => {
+ if (t[e] = i, this.#c) {
+ let n = this.#c - t[e];
+ for (; this.#b > n; ) this.#P(true);
+ }
+ this.#b += t[e], s && (s.entrySize = i, s.totalCalculatedSize = this.#b);
+ };
+ }
+ #C = /* @__PURE__ */ __name((t) => {
+ }, "#C");
+ #I = /* @__PURE__ */ __name((t, e, i) => {
+ }, "#I");
+ #N = /* @__PURE__ */ __name((t, e, i, s) => {
+ if (i || s) throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");
+ return 0;
+ }, "#N");
+ *#A({ allowStale: t = this.allowStale } = {}) {
+ if (this.#n) for (let e = this.#h; this.#V(e) && ((t || !this.#p(e)) && (yield e), e !== this.#a); ) e = this.#u[e];
+ }
+ *#z({ allowStale: t = this.allowStale } = {}) {
+ if (this.#n) for (let e = this.#a; this.#V(e) && ((t || !this.#p(e)) && (yield e), e !== this.#h); ) e = this.#l[e];
+ }
+ #V(t) {
+ return t !== void 0 && this.#s.get(this.#i[t]) === t;
+ }
+ *entries() {
+ for (let t of this.#A()) this.#t[t] !== void 0 && this.#i[t] !== void 0 && !this.#e(this.#t[t]) && (yield [this.#i[t], this.#t[t]]);
+ }
+ *rentries() {
+ for (let t of this.#z()) this.#t[t] !== void 0 && this.#i[t] !== void 0 && !this.#e(this.#t[t]) && (yield [this.#i[t], this.#t[t]]);
+ }
+ *keys() {
+ for (let t of this.#A()) {
+ let e = this.#i[t];
+ e !== void 0 && !this.#e(this.#t[t]) && (yield e);
+ }
+ }
+ *rkeys() {
+ for (let t of this.#z()) {
+ let e = this.#i[t];
+ e !== void 0 && !this.#e(this.#t[t]) && (yield e);
+ }
+ }
+ *values() {
+ for (let t of this.#A()) this.#t[t] !== void 0 && !this.#e(this.#t[t]) && (yield this.#t[t]);
+ }
+ *rvalues() {
+ for (let t of this.#z()) this.#t[t] !== void 0 && !this.#e(this.#t[t]) && (yield this.#t[t]);
+ }
+ [Symbol.iterator]() {
+ return this.entries();
+ }
+ [Symbol.toStringTag] = "LRUCache";
+ find(t, e = {}) {
+ for (let i of this.#A()) {
+ let s = this.#t[i], n = this.#e(s) ? s.__staleWhileFetching : s;
+ if (n !== void 0 && t(n, this.#i[i], this)) return this.#x(this.#i[i], e);
+ }
+ }
+ forEach(t, e = this) {
+ for (let i of this.#A()) {
+ let s = this.#t[i], n = this.#e(s) ? s.__staleWhileFetching : s;
+ n !== void 0 && t.call(e, n, this.#i[i], this);
+ }
+ }
+ rforEach(t, e = this) {
+ for (let i of this.#z()) {
+ let s = this.#t[i], n = this.#e(s) ? s.__staleWhileFetching : s;
+ n !== void 0 && t.call(e, n, this.#i[i], this);
+ }
+ }
+ purgeStale() {
+ let t = false;
+ for (let e of this.#z({ allowStale: true })) this.#p(e) && (this.#v(this.#i[e], "expire"), t = true);
+ return t;
+ }
+ info(t) {
+ let e = this.#s.get(t);
+ if (e === void 0) return;
+ let i = this.#t[e], s = this.#e(i) ? i.__staleWhileFetching : i;
+ if (s === void 0) return;
+ let n = { value: s };
+ if (this.#d && this.#F) {
+ let r = this.#d[e], h = this.#F[e];
+ if (r && h) {
+ let a = r - (this.#w.now() - h);
+ n.ttl = a, n.start = Date.now();
+ }
+ }
+ return this.#y && (n.size = this.#y[e]), n;
+ }
+ dump() {
+ let t = [];
+ for (let e of this.#A({ allowStale: true })) {
+ let i = this.#i[e], s = this.#t[e], n = this.#e(s) ? s.__staleWhileFetching : s;
+ if (n === void 0 || i === void 0) continue;
+ let r = { value: n };
+ if (this.#d && this.#F) {
+ r.ttl = this.#d[e];
+ let h = this.#w.now() - this.#F[e];
+ r.start = Math.floor(Date.now() - h);
+ }
+ this.#y && (r.size = this.#y[e]), t.unshift([i, r]);
+ }
+ return t;
+ }
+ load(t) {
+ this.clear();
+ for (let [e, i] of t) {
+ if (i.start) {
+ let s = Date.now() - i.start;
+ i.start = this.#w.now() - s;
+ }
+ this.#O(e, i.value, i);
+ }
+ }
+ set(t, e, i = {}) {
+ let { status: s = g.metrics.hasSubscribers ? {} : void 0 } = i;
+ i.status = s, s && (s.op = "set", s.key = t, e !== void 0 && (s.value = e), s.cache = this);
+ let n = this.#O(t, e, i);
+ return s && g.metrics.hasSubscribers && g.metrics.publish(s), n;
+ }
+ #O(t, e, i, s) {
+ let { ttl: n = this.ttl, start: r, noDisposeOnSet: h = this.noDisposeOnSet, sizeCalculation: a = this.sizeCalculation, status: o } = i, d = this.#e(e);
+ if (e === void 0) return o && (o.set = "deleted"), this.delete(t), this;
+ let { noUpdateTTL: _ = this.noUpdateTTL } = i;
+ o && !d && (o.value = e);
+ let y = this.#N(t, e, i.size || 0, a, o);
+ if (this.maxEntrySize && y > this.maxEntrySize) return this.#v(t, "set"), o && (o.set = "miss", o.maxEntrySizeExceeded = true), this;
+ let u = this.#n === 0 ? void 0 : this.#s.get(t);
+ if (u === void 0) u = this.#n === 0 ? this.#h : this.#_.length !== 0 ? this.#_.pop() : this.#n === this.#o ? this.#P(false) : this.#n, this.#i[u] = t, this.#t[u] = e, this.#s.set(t, u), this.#l[this.#h] = u, this.#u[u] = this.#h, this.#h = u, this.#n++, this.#I(u, y, o), o && (o.set = "add"), _ = false, this.#D && !d && this.#W?.(e, t, "add");
+ else {
+ this.#L(u);
+ let p = this.#t[u];
+ if (e !== p) {
+ if (!h) if (this.#e(p)) {
+ p !== s && p.__abortController.abort(new Error("replaced"));
+ let { __staleWhileFetching: f } = p;
+ f !== void 0 && f !== e && (this.#T && this.#m?.(f, t, "set"), this.#f && this.#r?.push([f, t, "set"]));
+ } else this.#T && this.#m?.(p, t, "set"), this.#f && this.#r?.push([p, t, "set"]);
+ if (this.#C(u), this.#I(u, y, o), this.#t[u] = e, !d) {
+ let f = p && this.#e(p) ? p.__staleWhileFetching : p, b = f === void 0 ? "add" : e !== f ? "replace" : "update";
+ o && (o.set = b, f !== void 0 && (o.oldValue = f)), this.#D && this.onInsert?.(e, t, b);
+ }
+ } else d || (o && (o.set = "update"), this.#D && this.onInsert?.(e, t, "update"));
+ }
+ if (n !== 0 && !this.#d && this.#k(), this.#d && (_ || this.#H(u, n, r), o && this.#E(o, u)), !h && this.#f && this.#r) {
+ let p = this.#r, f;
+ for (; f = p?.shift(); ) this.#S?.(...f);
+ }
+ return this;
+ }
+ pop() {
+ try {
+ for (; this.#n; ) {
+ let t = this.#t[this.#a];
+ if (this.#P(true), this.#e(t)) {
+ if (t.__staleWhileFetching) return t.__staleWhileFetching;
+ } else if (t !== void 0) return t;
+ }
+ } finally {
+ if (this.#f && this.#r) {
+ let t = this.#r, e;
+ for (; e = t?.shift(); ) this.#S?.(...e);
+ }
+ }
+ }
+ #P(t) {
+ let e = this.#a, i = this.#i[e], s = this.#t[e], n = this.#e(s);
+ n && s.__abortController.abort(new Error("evicted"));
+ let r = n ? s.__staleWhileFetching : s;
+ return (this.#T || this.#f) && r !== void 0 && (this.#T && this.#m?.(r, i, "evict"), this.#f && this.#r?.push([r, i, "evict"])), this.#C(e), this.#g?.[e] && (clearTimeout(this.#g[e]), this.#g[e] = void 0), t && (this.#i[e] = void 0, this.#t[e] = void 0, this.#_.push(e)), this.#n === 1 ? (this.#a = this.#h = 0, this.#_.length = 0) : this.#a = this.#l[e], this.#s.delete(i), this.#n--, e;
+ }
+ has(t, e = {}) {
+ let { status: i = g.metrics.hasSubscribers ? {} : void 0 } = e;
+ e.status = i, i && (i.op = "has", i.key = t, i.cache = this);
+ let s = this.#Y(t, e);
+ return g.metrics.hasSubscribers && g.metrics.publish(i), s;
+ }
+ #Y(t, e = {}) {
+ let { updateAgeOnHas: i = this.updateAgeOnHas, status: s } = e, n = this.#s.get(t);
+ if (n !== void 0) {
+ let r = this.#t[n];
+ if (this.#e(r) && r.__staleWhileFetching === void 0) return false;
+ if (this.#p(n)) s && (s.has = "stale", this.#E(s, n));
+ else return i && this.#R(n), s && (s.has = "hit", this.#E(s, n)), true;
+ } else s && (s.has = "miss");
+ return false;
+ }
+ peek(t, e = {}) {
+ let { status: i = C() ? {} : void 0 } = e;
+ i && (i.op = "peek", i.key = t, i.cache = this), e.status = i;
+ let s = this.#J(t, e);
+ return g.metrics.hasSubscribers && g.metrics.publish(i), s;
+ }
+ #J(t, e) {
+ let { status: i, allowStale: s = this.allowStale } = e, n = this.#s.get(t);
+ if (n === void 0 || !s && this.#p(n)) {
+ i && (i.peek = n === void 0 ? "miss" : "stale");
+ return;
+ }
+ let r = this.#t[n], h = this.#e(r) ? r.__staleWhileFetching : r;
+ return i && (h !== void 0 ? (i.peek = "hit", i.value = h) : i.peek = "miss"), h;
+ }
+ #G(t, e, i, s) {
+ let n = e === void 0 ? void 0 : this.#t[e];
+ if (this.#e(n)) return n;
+ let r = new AbortController(), { signal: h } = i;
+ h?.addEventListener("abort", () => r.abort(h.reason), { signal: r.signal });
+ let a = { signal: r.signal, options: i, context: s }, o = /* @__PURE__ */ __name((f, b = false) => {
+ let { aborted: l } = r.signal, S = i.ignoreFetchAbort && f !== void 0, F = i.ignoreFetchAbort || !!(i.allowStaleOnFetchAbort && f !== void 0);
+ if (i.status && (l && !b ? (i.status.fetchAborted = true, i.status.fetchError = r.signal.reason, S && (i.status.fetchAbortIgnored = true)) : i.status.fetchResolved = true), l && !S && !b) return _(r.signal.reason, F);
+ let w = u, m = this.#t[e];
+ return (m === u || m === void 0 && S && b) && (f === void 0 ? w.__staleWhileFetching !== void 0 ? this.#t[e] = w.__staleWhileFetching : this.#v(t, "fetch") : (i.status && (i.status.fetchUpdated = true), this.#O(t, f, a.options, w))), f;
+ }, "o"), d = /* @__PURE__ */ __name((f) => (i.status && (i.status.fetchRejected = true, i.status.fetchError = f), _(f, false)), "d"), _ = /* @__PURE__ */ __name((f, b) => {
+ let { aborted: l } = r.signal, S = l && i.allowStaleOnFetchAbort, F = S || i.allowStaleOnFetchRejection, w = F || i.noDeleteOnFetchRejection, m = u;
+ if (this.#t[e] === u && (!w || !b && m.__staleWhileFetching === void 0 ? this.#v(t, "fetch") : S || (this.#t[e] = m.__staleWhileFetching)), F) return i.status && m.__staleWhileFetching !== void 0 && (i.status.returnedStale = true), m.__staleWhileFetching;
+ if (m.__returned === m) throw f;
+ }, "_"), y = /* @__PURE__ */ __name((f, b) => {
+ let l = this.#M?.(t, n, a);
+ r.signal.addEventListener("abort", () => {
+ (!i.ignoreFetchAbort || i.allowStaleOnFetchAbort) && (f(void 0), i.allowStaleOnFetchAbort && (f = /* @__PURE__ */ __name((S) => o(S, true), "f")));
+ }), l && l instanceof Promise ? l.then((S) => f(S === void 0 ? void 0 : S), b) : l !== void 0 && f(l);
+ }, "y");
+ i.status && (i.status.fetchDispatched = true);
+ let u = new Promise(y).then(o, d), p = Object.assign(u, { __abortController: r, __staleWhileFetching: n, __returned: void 0 });
+ return e === void 0 ? (this.#O(t, p, { ...a.options, status: void 0 }), e = this.#s.get(t)) : this.#t[e] = p, p;
+ }
+ #e(t) {
+ if (!this.#U) return false;
+ let e = t;
+ return !!e && e instanceof Promise && e.hasOwnProperty("__staleWhileFetching") && e.__abortController instanceof AbortController;
+ }
+ fetch(t, e = {}) {
+ let i = g.tracing.hasSubscribers, { status: s = C() ? {} : void 0 } = e;
+ e.status = s, s && e.context && (s.context = e.context);
+ let n = this.#q(t, e);
+ return s && i && (s.trace = true, g.tracing.tracePromise(() => n, s).catch(() => {
+ })), n;
+ }
+ async #q(t, e = {}) {
+ let { allowStale: i = this.allowStale, updateAgeOnGet: s = this.updateAgeOnGet, noDeleteOnStaleGet: n = this.noDeleteOnStaleGet, ttl: r = this.ttl, noDisposeOnSet: h = this.noDisposeOnSet, size: a = 0, sizeCalculation: o = this.sizeCalculation, noUpdateTTL: d = this.noUpdateTTL, noDeleteOnFetchRejection: _ = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection: y = this.allowStaleOnFetchRejection, ignoreFetchAbort: u = this.ignoreFetchAbort, allowStaleOnFetchAbort: p = this.allowStaleOnFetchAbort, context: f, forceRefresh: b = false, status: l, signal: S } = e;
+ if (l && (l.op = "fetch", l.key = t, b && (l.forceRefresh = true), l.cache = this), !this.#U) return l && (l.fetch = "get"), this.#x(t, { allowStale: i, updateAgeOnGet: s, noDeleteOnStaleGet: n, status: l });
+ let F = { allowStale: i, updateAgeOnGet: s, noDeleteOnStaleGet: n, ttl: r, noDisposeOnSet: h, size: a, sizeCalculation: o, noUpdateTTL: d, noDeleteOnFetchRejection: _, allowStaleOnFetchRejection: y, allowStaleOnFetchAbort: p, ignoreFetchAbort: u, status: l, signal: S }, w = this.#s.get(t);
+ if (w === void 0) {
+ l && (l.fetch = "miss");
+ let m = this.#G(t, w, F, f);
+ return m.__returned = m;
+ } else {
+ let m = this.#t[w];
+ if (this.#e(m)) {
+ let E = i && m.__staleWhileFetching !== void 0;
+ return l && (l.fetch = "inflight", E && (l.returnedStale = true)), E ? m.__staleWhileFetching : m.__returned = m;
+ }
+ let A = this.#p(w);
+ if (!b && !A) return l && (l.fetch = "hit"), this.#L(w), s && this.#R(w), l && this.#E(l, w), m;
+ let z2 = this.#G(t, w, F, f), v = z2.__staleWhileFetching !== void 0 && i;
+ return l && (l.fetch = A ? "stale" : "refresh", v && A && (l.returnedStale = true)), v ? z2.__staleWhileFetching : z2.__returned = z2;
+ }
+ }
+ forceFetch(t, e = {}) {
+ let i = g.tracing.hasSubscribers, { status: s = C() ? {} : void 0 } = e;
+ e.status = s, s && e.context && (s.context = e.context);
+ let n = this.#K(t, e);
+ return s && i && (s.trace = true, g.tracing.tracePromise(() => n, s).catch(() => {
+ })), n;
+ }
+ async #K(t, e = {}) {
+ let i = await this.#q(t, e);
+ if (i === void 0) throw new Error("fetch() returned undefined");
+ return i;
+ }
+ memo(t, e = {}) {
+ let { status: i = g.metrics.hasSubscribers ? {} : void 0 } = e;
+ e.status = i, i && (i.op = "memo", i.key = t, e.context && (i.context = e.context), i.cache = this);
+ let s = this.#Q(t, e);
+ return i && (i.value = s), g.metrics.hasSubscribers && g.metrics.publish(i), s;
+ }
+ #Q(t, e = {}) {
+ let i = this.#j;
+ if (!i) throw new Error("no memoMethod provided to constructor");
+ let { context: s, status: n, forceRefresh: r, ...h } = e;
+ n && r && (n.forceRefresh = true);
+ let a = this.#x(t, h), o = r || a === void 0;
+ if (n && (n.memo = o ? "miss" : "hit", o || (n.value = a)), !o) return a;
+ let d = i(t, a, { options: h, context: s });
+ return n && (n.value = d), this.#O(t, d, h), d;
+ }
+ get(t, e = {}) {
+ let { status: i = g.metrics.hasSubscribers ? {} : void 0 } = e;
+ e.status = i, i && (i.op = "get", i.key = t, i.cache = this);
+ let s = this.#x(t, e);
+ return i && (s !== void 0 && (i.value = s), g.metrics.hasSubscribers && g.metrics.publish(i)), s;
+ }
+ #x(t, e = {}) {
+ let { allowStale: i = this.allowStale, updateAgeOnGet: s = this.updateAgeOnGet, noDeleteOnStaleGet: n = this.noDeleteOnStaleGet, status: r } = e, h = this.#s.get(t);
+ if (h === void 0) {
+ r && (r.get = "miss");
+ return;
+ }
+ let a = this.#t[h], o = this.#e(a);
+ return r && this.#E(r, h), this.#p(h) ? o ? (r && (r.get = "stale-fetching"), i && a.__staleWhileFetching !== void 0 ? (r && (r.returnedStale = true), a.__staleWhileFetching) : void 0) : (n || this.#v(t, "expire"), r && (r.get = "stale"), i ? (r && (r.returnedStale = true), a) : void 0) : (r && (r.get = o ? "fetching" : "hit"), this.#L(h), s && this.#R(h), o ? a.__staleWhileFetching : a);
+ }
+ #B(t, e) {
+ this.#u[e] = t, this.#l[t] = e;
+ }
+ #L(t) {
+ t !== this.#h && (t === this.#a ? this.#a = this.#l[t] : this.#B(this.#u[t], this.#l[t]), this.#B(this.#h, t), this.#h = t);
+ }
+ delete(t) {
+ return this.#v(t, "delete");
+ }
+ #v(t, e) {
+ g.metrics.hasSubscribers && g.metrics.publish({ op: "delete", delete: e, key: t, cache: this });
+ let i = false;
+ if (this.#n !== 0) {
+ let s = this.#s.get(t);
+ if (s !== void 0) if (this.#g?.[s] && (clearTimeout(this.#g?.[s]), this.#g[s] = void 0), i = true, this.#n === 1) this.#$(e);
+ else {
+ this.#C(s);
+ let n = this.#t[s];
+ if (this.#e(n) ? n.__abortController.abort(new Error("deleted")) : (this.#T || this.#f) && (this.#T && this.#m?.(n, t, e), this.#f && this.#r?.push([n, t, e])), this.#s.delete(t), this.#i[s] = void 0, this.#t[s] = void 0, s === this.#h) this.#h = this.#u[s];
+ else if (s === this.#a) this.#a = this.#l[s];
+ else {
+ let r = this.#u[s];
+ this.#l[r] = this.#l[s];
+ let h = this.#l[s];
+ this.#u[h] = this.#u[s];
+ }
+ this.#n--, this.#_.push(s);
+ }
+ }
+ if (this.#f && this.#r?.length) {
+ let s = this.#r, n;
+ for (; n = s?.shift(); ) this.#S?.(...n);
+ }
+ return i;
+ }
+ clear() {
+ return this.#$("delete");
+ }
+ #$(t) {
+ for (let e of this.#z({ allowStale: true })) {
+ let i = this.#t[e];
+ if (this.#e(i)) i.__abortController.abort(new Error("deleted"));
+ else {
+ let s = this.#i[e];
+ this.#T && this.#m?.(i, s, t), this.#f && this.#r?.push([i, s, t]);
+ }
+ }
+ if (this.#s.clear(), this.#t.fill(void 0), this.#i.fill(void 0), this.#d && this.#F) {
+ this.#d.fill(0), this.#F.fill(0);
+ for (let e of this.#g ?? []) e !== void 0 && clearTimeout(e);
+ this.#g?.fill(void 0);
+ }
+ if (this.#y && this.#y.fill(0), this.#a = 0, this.#h = 0, this.#_.length = 0, this.#b = 0, this.#n = 0, this.#f && this.#r) {
+ let e = this.#r, i;
+ for (; i = e?.shift(); ) this.#S?.(...i);
+ }
+ }
+ };
+ exports2.LRUCache = L;
+ }
+});
+
+// node_modules/read-package-up/node_modules/hosted-git-info/lib/hosts.js
+var require_hosts = __commonJS({
+ "node_modules/read-package-up/node_modules/hosted-git-info/lib/hosts.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var maybeJoin = /* @__PURE__ */ __name((...args) => args.every((arg) => arg) ? args.join("") : "", "maybeJoin");
+ var maybeEncode = /* @__PURE__ */ __name((arg) => arg ? encodeURIComponent(arg) : "", "maybeEncode");
+ var formatHashFragment = /* @__PURE__ */ __name((f) => f.toLowerCase().replace(/^\W+/g, "").replace(/(? `git@${domain2}:${user}/${project}.git${maybeJoin("#", committish)}`, "sshtemplate"),
+ sshurltemplate: /* @__PURE__ */ __name(({ domain: domain2, user, project, committish }) => `git+ssh://git@${domain2}/${user}/${project}.git${maybeJoin("#", committish)}`, "sshurltemplate"),
+ edittemplate: /* @__PURE__ */ __name(({ domain: domain2, user, project, committish, editpath, path: path27 }) => `https://${domain2}/${user}/${project}${maybeJoin("/", editpath, "/", maybeEncode(committish || "HEAD"), "/", path27)}`, "edittemplate"),
+ browsetemplate: /* @__PURE__ */ __name(({ domain: domain2, user, project, committish, treepath }) => `https://${domain2}/${user}/${project}${maybeJoin("/", treepath, "/", maybeEncode(committish))}`, "browsetemplate"),
+ browsetreetemplate: /* @__PURE__ */ __name(({ domain: domain2, user, project, committish, treepath, path: path27, fragment, hashformat }) => `https://${domain2}/${user}/${project}/${treepath}/${maybeEncode(committish || "HEAD")}/${path27}${maybeJoin("#", hashformat(fragment || ""))}`, "browsetreetemplate"),
+ browseblobtemplate: /* @__PURE__ */ __name(({ domain: domain2, user, project, committish, blobpath, path: path27, fragment, hashformat }) => `https://${domain2}/${user}/${project}/${blobpath}/${maybeEncode(committish || "HEAD")}/${path27}${maybeJoin("#", hashformat(fragment || ""))}`, "browseblobtemplate"),
+ docstemplate: /* @__PURE__ */ __name(({ domain: domain2, user, project, treepath, committish }) => `https://${domain2}/${user}/${project}${maybeJoin("/", treepath, "/", maybeEncode(committish))}#readme`, "docstemplate"),
+ httpstemplate: /* @__PURE__ */ __name(({ auth, domain: domain2, user, project, committish }) => `git+https://${maybeJoin(auth, "@")}${domain2}/${user}/${project}.git${maybeJoin("#", committish)}`, "httpstemplate"),
+ filetemplate: /* @__PURE__ */ __name(({ domain: domain2, user, project, committish, path: path27 }) => `https://${domain2}/${user}/${project}/raw/${maybeEncode(committish || "HEAD")}/${path27}`, "filetemplate"),
+ shortcuttemplate: /* @__PURE__ */ __name(({ type: type2, user, project, committish }) => `${type2}:${user}/${project}${maybeJoin("#", committish)}`, "shortcuttemplate"),
+ pathtemplate: /* @__PURE__ */ __name(({ user, project, committish }) => `${user}/${project}${maybeJoin("#", committish)}`, "pathtemplate"),
+ bugstemplate: /* @__PURE__ */ __name(({ domain: domain2, user, project }) => `https://${domain2}/${user}/${project}/issues`, "bugstemplate"),
+ hashformat: formatHashFragment
+ };
+ var hosts = {};
+ hosts.github = {
+ // First two are insecure and generally shouldn't be used any more, but
+ // they are still supported.
+ protocols: ["git:", "http:", "git+ssh:", "git+https:", "ssh:", "https:"],
+ domain: "github.com",
+ treepath: "tree",
+ blobpath: "blob",
+ editpath: "edit",
+ filetemplate: /* @__PURE__ */ __name(({ auth, user, project, committish, path: path27 }) => `https://${maybeJoin(auth, "@")}raw.githubusercontent.com/${user}/${project}/${maybeEncode(committish || "HEAD")}/${path27}`, "filetemplate"),
+ gittemplate: /* @__PURE__ */ __name(({ auth, domain: domain2, user, project, committish }) => `git://${maybeJoin(auth, "@")}${domain2}/${user}/${project}.git${maybeJoin("#", committish)}`, "gittemplate"),
+ tarballtemplate: /* @__PURE__ */ __name(({ domain: domain2, user, project, committish }) => `https://codeload.${domain2}/${user}/${project}/tar.gz/${maybeEncode(committish || "HEAD")}`, "tarballtemplate"),
+ extract: /* @__PURE__ */ __name((url2) => {
+ let [, user, project, type2, committish] = url2.pathname.split("/", 5);
+ if (type2 && type2 !== "tree") {
+ return;
+ }
+ if (!type2) {
+ committish = url2.hash.slice(1);
+ }
+ if (project && project.endsWith(".git")) {
+ project = project.slice(0, -4);
+ }
+ if (!user || !project) {
+ return;
+ }
+ return { user, project, committish };
+ }, "extract")
+ };
+ hosts.bitbucket = {
+ protocols: ["git+ssh:", "git+https:", "ssh:", "https:"],
+ domain: "bitbucket.org",
+ treepath: "src",
+ blobpath: "src",
+ editpath: "?mode=edit",
+ edittemplate: /* @__PURE__ */ __name(({ domain: domain2, user, project, committish, treepath, path: path27, editpath }) => `https://${domain2}/${user}/${project}${maybeJoin("/", treepath, "/", maybeEncode(committish || "HEAD"), "/", path27, editpath)}`, "edittemplate"),
+ tarballtemplate: /* @__PURE__ */ __name(({ domain: domain2, user, project, committish }) => `https://${domain2}/${user}/${project}/get/${maybeEncode(committish || "HEAD")}.tar.gz`, "tarballtemplate"),
+ extract: /* @__PURE__ */ __name((url2) => {
+ let [, user, project, aux] = url2.pathname.split("/", 4);
+ if (["get"].includes(aux)) {
+ return;
+ }
+ if (project && project.endsWith(".git")) {
+ project = project.slice(0, -4);
+ }
+ if (!user || !project) {
+ return;
+ }
+ return { user, project, committish: url2.hash.slice(1) };
+ }, "extract")
+ };
+ hosts.gitlab = {
+ protocols: ["git+ssh:", "git+https:", "ssh:", "https:"],
+ domain: "gitlab.com",
+ treepath: "tree",
+ blobpath: "tree",
+ editpath: "-/edit",
+ tarballtemplate: /* @__PURE__ */ __name(({ domain: domain2, user, project, committish }) => `https://${domain2}/api/v4/projects/${maybeEncode(user + "/" + project)}/repository/archive.tar.gz?sha=${maybeEncode(committish || "HEAD")}`, "tarballtemplate"),
+ extract: /* @__PURE__ */ __name((url2) => {
+ const path27 = url2.pathname.slice(1);
+ if (path27.includes("/-/") || path27.includes("/archive.tar.gz")) {
+ return;
+ }
+ const segments = path27.split("/");
+ let project = segments.pop();
+ if (project.endsWith(".git")) {
+ project = project.slice(0, -4);
+ }
+ const user = segments.join("/");
+ if (!user || !project) {
+ return;
+ }
+ return { user, project, committish: url2.hash.slice(1) };
+ }, "extract")
+ };
+ hosts.gist = {
+ protocols: ["git:", "git+ssh:", "git+https:", "ssh:", "https:"],
+ domain: "gist.github.com",
+ editpath: "edit",
+ sshtemplate: /* @__PURE__ */ __name(({ domain: domain2, project, committish }) => `git@${domain2}:${project}.git${maybeJoin("#", committish)}`, "sshtemplate"),
+ sshurltemplate: /* @__PURE__ */ __name(({ domain: domain2, project, committish }) => `git+ssh://git@${domain2}/${project}.git${maybeJoin("#", committish)}`, "sshurltemplate"),
+ edittemplate: /* @__PURE__ */ __name(({ domain: domain2, user, project, committish, editpath }) => `https://${domain2}/${user}/${project}${maybeJoin("/", maybeEncode(committish))}/${editpath}`, "edittemplate"),
+ browsetemplate: /* @__PURE__ */ __name(({ domain: domain2, project, committish }) => `https://${domain2}/${project}${maybeJoin("/", maybeEncode(committish))}`, "browsetemplate"),
+ browsetreetemplate: /* @__PURE__ */ __name(({ domain: domain2, project, committish, path: path27, hashformat }) => `https://${domain2}/${project}${maybeJoin("/", maybeEncode(committish))}${maybeJoin("#", hashformat(path27))}`, "browsetreetemplate"),
+ browseblobtemplate: /* @__PURE__ */ __name(({ domain: domain2, project, committish, path: path27, hashformat }) => `https://${domain2}/${project}${maybeJoin("/", maybeEncode(committish))}${maybeJoin("#", hashformat(path27))}`, "browseblobtemplate"),
+ docstemplate: /* @__PURE__ */ __name(({ domain: domain2, project, committish }) => `https://${domain2}/${project}${maybeJoin("/", maybeEncode(committish))}`, "docstemplate"),
+ httpstemplate: /* @__PURE__ */ __name(({ domain: domain2, project, committish }) => `git+https://${domain2}/${project}.git${maybeJoin("#", committish)}`, "httpstemplate"),
+ filetemplate: /* @__PURE__ */ __name(({ user, project, committish, path: path27 }) => `https://gist.githubusercontent.com/${user}/${project}/raw${maybeJoin("/", maybeEncode(committish))}/${path27}`, "filetemplate"),
+ shortcuttemplate: /* @__PURE__ */ __name(({ type: type2, project, committish }) => `${type2}:${project}${maybeJoin("#", committish)}`, "shortcuttemplate"),
+ pathtemplate: /* @__PURE__ */ __name(({ project, committish }) => `${project}${maybeJoin("#", committish)}`, "pathtemplate"),
+ bugstemplate: /* @__PURE__ */ __name(({ domain: domain2, project }) => `https://${domain2}/${project}`, "bugstemplate"),
+ gittemplate: /* @__PURE__ */ __name(({ domain: domain2, project, committish }) => `git://${domain2}/${project}.git${maybeJoin("#", committish)}`, "gittemplate"),
+ tarballtemplate: /* @__PURE__ */ __name(({ project, committish }) => `https://codeload.github.com/gist/${project}/tar.gz/${maybeEncode(committish || "HEAD")}`, "tarballtemplate"),
+ extract: /* @__PURE__ */ __name((url2) => {
+ let [, user, project, aux] = url2.pathname.split("/", 4);
+ if (aux === "raw") {
+ return;
+ }
+ if (!project) {
+ if (!user) {
+ return;
+ }
+ project = user;
+ user = null;
+ }
+ if (project.endsWith(".git")) {
+ project = project.slice(0, -4);
+ }
+ return { user, project, committish: url2.hash.slice(1) };
+ }, "extract"),
+ hashformat: /* @__PURE__ */ __name(function(fragment) {
+ return fragment && "file-" + formatHashFragment(fragment);
+ }, "hashformat")
+ };
+ hosts.sourcehut = {
+ protocols: ["git+ssh:", "https:"],
+ domain: "git.sr.ht",
+ treepath: "tree",
+ blobpath: "tree",
+ filetemplate: /* @__PURE__ */ __name(({ domain: domain2, user, project, committish, path: path27 }) => `https://${domain2}/${user}/${project}/blob/${maybeEncode(committish) || "HEAD"}/${path27}`, "filetemplate"),
+ httpstemplate: /* @__PURE__ */ __name(({ domain: domain2, user, project, committish }) => `https://${domain2}/${user}/${project}${maybeJoin("#", committish)}`, "httpstemplate"),
+ tarballtemplate: /* @__PURE__ */ __name(({ domain: domain2, user, project, committish }) => `https://${domain2}/${user}/${project}/archive/${maybeEncode(committish) || "HEAD"}.tar.gz`, "tarballtemplate"),
+ bugstemplate: /* @__PURE__ */ __name(() => null, "bugstemplate"),
+ extract: /* @__PURE__ */ __name((url2) => {
+ let [, user, project, aux] = url2.pathname.split("/", 4);
+ if (["archive"].includes(aux)) {
+ return;
+ }
+ if (project && project.endsWith(".git")) {
+ project = project.slice(0, -4);
+ }
+ if (!user || !project) {
+ return;
+ }
+ return { user, project, committish: url2.hash.slice(1) };
+ }, "extract")
+ };
+ for (const [name, host] of Object.entries(hosts)) {
+ hosts[name] = Object.assign({}, defaults2, host);
+ }
+ module2.exports = hosts;
+ }
+});
+
+// node_modules/read-package-up/node_modules/hosted-git-info/lib/parse-url.js
+var require_parse_url = __commonJS({
+ "node_modules/read-package-up/node_modules/hosted-git-info/lib/parse-url.js"(exports2, module2) {
+ init_esbuild_shims();
+ var url2 = __require("url");
+ var lastIndexOfBefore = /* @__PURE__ */ __name((str3, char, beforeChar) => {
+ const startPosition = str3.indexOf(beforeChar);
+ return str3.lastIndexOf(char, startPosition > -1 ? startPosition : Infinity);
+ }, "lastIndexOfBefore");
+ var safeUrl = /* @__PURE__ */ __name((u) => {
+ try {
+ return new url2.URL(u);
+ } catch {
+ }
+ }, "safeUrl");
+ var correctProtocol = /* @__PURE__ */ __name((arg, protocols) => {
+ const firstColon = arg.indexOf(":");
+ const proto4 = arg.slice(0, firstColon + 1);
+ if (Object.prototype.hasOwnProperty.call(protocols, proto4)) {
+ return arg;
+ }
+ if (arg.substr(firstColon, 3) === "://") {
+ return arg;
+ }
+ const firstAt = arg.indexOf("@");
+ if (firstAt > -1) {
+ if (firstAt > firstColon) {
+ return `git+ssh://${arg}`;
+ } else {
+ return arg;
+ }
+ }
+ return `${arg.slice(0, firstColon + 1)}//${arg.slice(firstColon + 1)}`;
+ }, "correctProtocol");
+ var correctUrl = /* @__PURE__ */ __name((giturl) => {
+ const firstAt = lastIndexOfBefore(giturl, "@", "#");
+ const lastColonBeforeHash = lastIndexOfBefore(giturl, ":", "#");
+ if (lastColonBeforeHash > firstAt) {
+ giturl = giturl.slice(0, lastColonBeforeHash) + "/" + giturl.slice(lastColonBeforeHash + 1);
+ }
+ if (lastIndexOfBefore(giturl, ":", "#") === -1 && giturl.indexOf("//") === -1) {
+ giturl = `git+ssh://${giturl}`;
+ }
+ return giturl;
+ }, "correctUrl");
+ module2.exports = (giturl, protocols) => {
+ const withProtocol = protocols ? correctProtocol(giturl, protocols) : giturl;
+ return safeUrl(withProtocol) || safeUrl(correctUrl(withProtocol));
+ };
+ }
+});
+
+// node_modules/read-package-up/node_modules/hosted-git-info/lib/from-url.js
+var require_from_url = __commonJS({
+ "node_modules/read-package-up/node_modules/hosted-git-info/lib/from-url.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var parseUrl = require_parse_url();
+ var isGitHubShorthand = /* @__PURE__ */ __name((arg) => {
+ const firstHash = arg.indexOf("#");
+ const firstSlash = arg.indexOf("/");
+ const secondSlash = arg.indexOf("/", firstSlash + 1);
+ const firstColon = arg.indexOf(":");
+ const firstSpace = /\s/.exec(arg);
+ const firstAt = arg.indexOf("@");
+ const spaceOnlyAfterHash = !firstSpace || firstHash > -1 && firstSpace.index > firstHash;
+ const atOnlyAfterHash = firstAt === -1 || firstHash > -1 && firstAt > firstHash;
+ const colonOnlyAfterHash = firstColon === -1 || firstHash > -1 && firstColon > firstHash;
+ const secondSlashOnlyAfterHash = secondSlash === -1 || firstHash > -1 && secondSlash > firstHash;
+ const hasSlash = firstSlash > 0;
+ const doesNotEndWithSlash = firstHash > -1 ? arg[firstHash - 1] !== "/" : !arg.endsWith("/");
+ const doesNotStartWithDot = !arg.startsWith(".");
+ return spaceOnlyAfterHash && hasSlash && doesNotEndWithSlash && doesNotStartWithDot && atOnlyAfterHash && colonOnlyAfterHash && secondSlashOnlyAfterHash;
+ }, "isGitHubShorthand");
+ module2.exports = (giturl, opts, { gitHosts, protocols }) => {
+ if (!giturl) {
+ return;
+ }
+ const correctedUrl = isGitHubShorthand(giturl) ? `github:${giturl}` : giturl;
+ const parsed = parseUrl(correctedUrl, protocols);
+ if (!parsed) {
+ return;
+ }
+ const gitHostShortcut = gitHosts.byShortcut[parsed.protocol];
+ const gitHostDomain = gitHosts.byDomain[parsed.hostname.startsWith("www.") ? parsed.hostname.slice(4) : parsed.hostname];
+ const gitHostName = gitHostShortcut || gitHostDomain;
+ if (!gitHostName) {
+ return;
+ }
+ const gitHostInfo = gitHosts[gitHostShortcut || gitHostDomain];
+ let auth = null;
+ if (protocols[parsed.protocol]?.auth && (parsed.username || parsed.password)) {
+ auth = `${parsed.username}${parsed.password ? ":" + parsed.password : ""}`;
+ }
+ let committish = null;
+ let user = null;
+ let project = null;
+ let defaultRepresentation = null;
+ try {
+ if (gitHostShortcut) {
+ let pathname = parsed.pathname.startsWith("/") ? parsed.pathname.slice(1) : parsed.pathname;
+ const firstAt = pathname.indexOf("@");
+ if (firstAt > -1) {
+ pathname = pathname.slice(firstAt + 1);
+ }
+ const lastSlash = pathname.lastIndexOf("/");
+ if (lastSlash > -1) {
+ user = decodeURIComponent(pathname.slice(0, lastSlash));
+ if (!user) {
+ user = null;
+ }
+ project = decodeURIComponent(pathname.slice(lastSlash + 1));
+ } else {
+ project = decodeURIComponent(pathname);
+ }
+ if (project.endsWith(".git")) {
+ project = project.slice(0, -4);
+ }
+ if (parsed.hash) {
+ committish = decodeURIComponent(parsed.hash.slice(1));
+ }
+ defaultRepresentation = "shortcut";
+ } else {
+ if (!gitHostInfo.protocols.includes(parsed.protocol)) {
+ return;
+ }
+ const segments = gitHostInfo.extract(parsed);
+ if (!segments) {
+ return;
+ }
+ user = segments.user && decodeURIComponent(segments.user);
+ project = decodeURIComponent(segments.project);
+ committish = decodeURIComponent(segments.committish);
+ defaultRepresentation = protocols[parsed.protocol]?.name || parsed.protocol.slice(0, -1);
+ }
+ } catch (err) {
+ if (err instanceof URIError) {
+ return;
+ } else {
+ throw err;
+ }
+ }
+ return [gitHostName, user, auth, project, committish, defaultRepresentation, opts];
+ };
+ }
+});
+
+// node_modules/read-package-up/node_modules/hosted-git-info/lib/index.js
+var require_lib3 = __commonJS({
+ "node_modules/read-package-up/node_modules/hosted-git-info/lib/index.js"(exports2, module2) {
+ "use strict";
+ init_esbuild_shims();
+ var { LRUCache } = require_index_min();
+ var hosts = require_hosts();
+ var fromUrl = require_from_url();
+ var parseUrl = require_parse_url();
+ var cache3 = new LRUCache({ max: 1e3 });
+ function unknownHostedUrl(url2) {
+ try {
+ const {
+ protocol,
+ hostname: hostname4,
+ pathname
+ } = new URL(url2);
+ if (!hostname4) {
+ return null;
+ }
+ const proto4 = /(?:git\+)http:$/.test(protocol) ? "http:" : "https:";
+ const path27 = pathname.replace(/\.git$/, "");
+ return `${proto4}//${hostname4}${path27}`;
+ } catch {
+ return null;
+ }
+ }
+ __name(unknownHostedUrl, "unknownHostedUrl");
+ var GitHost = class _GitHost {
+ static {
+ __name(this, "GitHost");
+ }
+ constructor(type2, user, auth, project, committish, defaultRepresentation, opts = {}) {
+ Object.assign(this, _GitHost.#gitHosts[type2], {
+ type: type2,
+ user,
+ auth,
+ project,
+ committish,
+ default: defaultRepresentation,
+ opts
+ });
+ }
+ static #gitHosts = { byShortcut: {}, byDomain: {} };
+ static #protocols = {
+ "git+ssh:": { name: "sshurl" },
+ "ssh:": { name: "sshurl" },
+ "git+https:": { name: "https", auth: true },
+ "git:": { auth: true },
+ "http:": { auth: true },
+ "https:": { auth: true },
+ "git+http:": { auth: true }
+ };
+ static addHost(name, host) {
+ _GitHost.#gitHosts[name] = host;
+ _GitHost.#gitHosts.byDomain[host.domain] = name;
+ _GitHost.#gitHosts.byShortcut[`${name}:`] = name;
+ _GitHost.#protocols[`${name}:`] = { name };
+ }
+ static fromUrl(giturl, opts) {
+ if (typeof giturl !== "string") {
+ return;
+ }
+ const key = giturl + JSON.stringify(opts || {});
+ if (!cache3.has(key)) {
+ const hostArgs = fromUrl(giturl, opts, {
+ gitHosts: _GitHost.#gitHosts,
+ protocols: _GitHost.#protocols
+ });
+ cache3.set(key, hostArgs ? new _GitHost(...hostArgs) : void 0);
+ }
+ return cache3.get(key);
+ }
+ static fromManifest(manifest, opts = {}) {
+ if (!manifest || typeof manifest !== "object") {
+ return;
+ }
+ const r = manifest.repository;
+ const rurl = r && (typeof r === "string" ? r : typeof r === "object" && typeof r.url === "string" ? r.url : null);
+ if (!rurl) {
+ throw new Error("no repository");
+ }
+ const info = rurl && _GitHost.fromUrl(rurl.replace(/^git\+/, ""), opts) || null;
+ if (info) {
+ return info;
+ }
+ const unk = unknownHostedUrl(rurl);
+ return _GitHost.fromUrl(unk, opts) || unk;
+ }
+ static parseUrl(url2) {
+ return parseUrl(url2);
+ }
+ #fill(template, opts) {
+ if (typeof template !== "function") {
+ return null;
+ }
+ const options2 = { ...this, ...this.opts, ...opts };
+ if (!options2.path) {
+ options2.path = "";
+ }
+ if (options2.path.startsWith("/")) {
+ options2.path = options2.path.slice(1);
+ }
+ if (options2.noCommittish) {
+ options2.committish = null;
+ }
+ const result = template(options2);
+ return options2.noGitPlus && result.startsWith("git+") ? result.slice(4) : result;
+ }
+ hash() {
+ return this.committish ? `#${this.committish}` : "";
+ }
+ ssh(opts) {
+ return this.#fill(this.sshtemplate, opts);
+ }
+ sshurl(opts) {
+ return this.#fill(this.sshurltemplate, opts);
+ }
+ browse(path27, ...args) {
+ if (typeof path27 !== "string") {
+ return this.#fill(this.browsetemplate, path27);
+ }
+ if (typeof args[0] !== "string") {
+ return this.#fill(this.browsetreetemplate, { ...args[0], path: path27 });
+ }
+ return this.#fill(this.browsetreetemplate, { ...args[1], fragment: args[0], path: path27 });
+ }
+ // If the path is known to be a file, then browseFile should be used. For some hosts
+ // the url is the same as browse, but for others like GitHub a file can use both `/tree/`
+ // and `/blob/` in the path. When using a default committish of `HEAD` then the `/tree/`
+ // path will redirect to a specific commit. Using the `/blob/` path avoids this and
+ // does not redirect to a different commit.
+ browseFile(path27, ...args) {
+ if (typeof args[0] !== "string") {
+ return this.#fill(this.browseblobtemplate, { ...args[0], path: path27 });
+ }
+ return this.#fill(this.browseblobtemplate, { ...args[1], fragment: args[0], path: path27 });
+ }
+ docs(opts) {
+ return this.#fill(this.docstemplate, opts);
+ }
+ bugs(opts) {
+ return this.#fill(this.bugstemplate, opts);
+ }
+ https(opts) {
+ return this.#fill(this.httpstemplate, opts);
+ }
+ git(opts) {
+ return this.#fill(this.gittemplate, opts);
+ }
+ shortcut(opts) {
+ return this.#fill(this.shortcuttemplate, opts);
+ }
+ path(opts) {
+ return this.#fill(this.pathtemplate, opts);
+ }
+ tarball(opts) {
+ return this.#fill(this.tarballtemplate, { ...opts, noCommittish: false });
+ }
+ file(path27, opts) {
+ return this.#fill(this.filetemplate, { ...opts, path: path27 });
+ }
+ edit(path27, opts) {
+ return this.#fill(this.edittemplate, { ...opts, path: path27 });
+ }
+ getDefaultRepresentation() {
+ return this.default;
+ }
+ toString(opts) {
+ if (this.default && typeof this[this.default] === "function") {
+ return this[this.default](opts);
+ }
+ return this.sshurl(opts);
+ }
+ };
+ for (const [name, host] of Object.entries(hosts)) {
+ GitHost.addHost(name, host);
+ }
+ module2.exports = GitHost;
+ }
+});
+
+// node_modules/read-package-up/node_modules/normalize-package-data/lib/extract_description.js
+var require_extract_description = __commonJS({
+ "node_modules/read-package-up/node_modules/normalize-package-data/lib/extract_description.js"(exports2, module2) {
+ init_esbuild_shims();
+ module2.exports = extractDescription;
+ function extractDescription(d) {
+ if (!d) {
+ return;
+ }
+ if (d === "ERROR: No README data found!") {
+ return;
+ }
+ d = d.trim().split("\n");
+ let s = 0;
+ while (d[s] && d[s].trim().match(/^(#|$)/)) {
+ s++;
+ }
+ const l = d.length;
+ let e = s + 1;
+ while (e < l && d[e].trim()) {
+ e++;
+ }
+ return d.slice(s, e).join(" ").trim();
+ }
+ __name(extractDescription, "extractDescription");
+ }
+});
+
+// node_modules/read-package-up/node_modules/normalize-package-data/lib/typos.json
+var require_typos = __commonJS({
+ "node_modules/read-package-up/node_modules/normalize-package-data/lib/typos.json"(exports2, module2) {
+ module2.exports = {
+ topLevel: {
+ dependancies: "dependencies",
+ dependecies: "dependencies",
+ depdenencies: "dependencies",
+ devEependencies: "devDependencies",
+ depends: "dependencies",
+ "dev-dependencies": "devDependencies",
+ devDependences: "devDependencies",
+ devDepenencies: "devDependencies",
+ devdependencies: "devDependencies",
+ repostitory: "repository",
+ repo: "repository",
+ prefereGlobal: "preferGlobal",
+ hompage: "homepage",
+ hampage: "homepage",
+ autohr: "author",
+ autor: "author",
+ contributers: "contributors",
+ publicationConfig: "publishConfig",
+ script: "scripts"
+ },
+ bugs: { web: "url", name: "url" },
+ script: { server: "start", tests: "test" }
+ };
+ }
+});
+
+// node_modules/read-package-up/node_modules/normalize-package-data/lib/fixer.js
+var require_fixer = __commonJS({
+ "node_modules/read-package-up/node_modules/normalize-package-data/lib/fixer.js"(exports2, module2) {
+ init_esbuild_shims();
+ var { URL: URL2 } = __require("node:url");
+ var isValidSemver = require_valid();
+ var cleanSemver = require_clean();
+ var validateLicense = require_validate_npm_package_license();
+ var hostedGitInfo = require_lib3();
+ var { isBuiltin } = __require("node:module");
+ var depTypes = ["dependencies", "devDependencies", "optionalDependencies"];
+ var extractDescription = require_extract_description();
+ var typos = require_typos();
+ var isEmail = /* @__PURE__ */ __name((str3) => str3.includes("@") && str3.indexOf("@") < str3.lastIndexOf("."), "isEmail");
+ module2.exports = {
+ // default warning function
+ warn: /* @__PURE__ */ __name(function() {
+ }, "warn"),
+ fixRepositoryField: /* @__PURE__ */ __name(function(data) {
+ if (data.repositories) {
+ this.warn("repositories");
+ data.repository = data.repositories[0];
+ }
+ if (!data.repository) {
+ return this.warn("missingRepository");
+ }
+ if (typeof data.repository === "string") {
+ data.repository = {
+ type: "git",
+ url: data.repository
+ };
+ }
+ var r = data.repository.url || "";
+ if (r) {
+ var hosted = hostedGitInfo.fromUrl(r);
+ if (hosted) {
+ r = data.repository.url = hosted.getDefaultRepresentation() === "shortcut" ? hosted.https() : hosted.toString();
+ }
+ }
+ if (r.match(/github.com\/[^/]+\/[^/]+\.git\.git$/)) {
+ this.warn("brokenGitUrl", r);
+ }
+ }, "fixRepositoryField"),
+ fixTypos: /* @__PURE__ */ __name(function(data) {
+ Object.keys(typos.topLevel).forEach(function(d) {
+ if (Object.prototype.hasOwnProperty.call(data, d)) {
+ this.warn("typo", d, typos.topLevel[d]);
+ }
+ }, this);
+ }, "fixTypos"),
+ fixScriptsField: /* @__PURE__ */ __name(function(data) {
+ if (!data.scripts) {
+ return;
+ }
+ if (typeof data.scripts !== "object") {
+ this.warn("nonObjectScripts");
+ delete data.scripts;
+ return;
+ }
+ Object.keys(data.scripts).forEach(function(k) {
+ if (typeof data.scripts[k] !== "string") {
+ this.warn("nonStringScript");
+ delete data.scripts[k];
+ } else if (typos.script[k] && !data.scripts[typos.script[k]]) {
+ this.warn("typo", k, typos.script[k], "scripts");
+ }
+ }, this);
+ }, "fixScriptsField"),
+ fixFilesField: /* @__PURE__ */ __name(function(data) {
+ var files = data.files;
+ if (files && !Array.isArray(files)) {
+ this.warn("nonArrayFiles");
+ delete data.files;
+ } else if (data.files) {
+ data.files = data.files.filter(function(file2) {
+ if (!file2 || typeof file2 !== "string") {
+ this.warn("invalidFilename", file2);
+ return false;
+ } else {
+ return true;
+ }
+ }, this);
+ }
+ }, "fixFilesField"),
+ fixBinField: /* @__PURE__ */ __name(function(data) {
+ if (!data.bin) {
+ return;
+ }
+ if (typeof data.bin === "string") {
+ var b = {};
+ var match;
+ if (match = data.name.match(/^@[^/]+[/](.*)$/)) {
+ b[match[1]] = data.bin;
+ } else {
+ b[data.name] = data.bin;
+ }
+ data.bin = b;
+ }
+ }, "fixBinField"),
+ fixManField: /* @__PURE__ */ __name(function(data) {
+ if (!data.man) {
+ return;
+ }
+ if (typeof data.man === "string") {
+ data.man = [data.man];
+ }
+ }, "fixManField"),
+ fixBundleDependenciesField: /* @__PURE__ */ __name(function(data) {
+ var bdd = "bundledDependencies";
+ var bd = "bundleDependencies";
+ if (data[bdd] && !data[bd]) {
+ data[bd] = data[bdd];
+ delete data[bdd];
+ }
+ if (data[bd] && !Array.isArray(data[bd])) {
+ this.warn("nonArrayBundleDependencies");
+ delete data[bd];
+ } else if (data[bd]) {
+ data[bd] = data[bd].filter(function(filtered) {
+ if (!filtered || typeof filtered !== "string") {
+ this.warn("nonStringBundleDependency", filtered);
+ return false;
+ } else {
+ if (!data.dependencies) {
+ data.dependencies = {};
+ }
+ if (!Object.prototype.hasOwnProperty.call(data.dependencies, filtered)) {
+ this.warn("nonDependencyBundleDependency", filtered);
+ data.dependencies[filtered] = "*";
+ }
+ return true;
+ }
+ }, this);
+ }
+ }, "fixBundleDependenciesField"),
+ fixDependencies: /* @__PURE__ */ __name(function(data) {
+ objectifyDeps(data, this.warn);
+ addOptionalDepsToDeps(data, this.warn);
+ this.fixBundleDependenciesField(data);
+ ["dependencies", "devDependencies"].forEach(function(deps) {
+ if (!(deps in data)) {
+ return;
+ }
+ if (!data[deps] || typeof data[deps] !== "object") {
+ this.warn("nonObjectDependencies", deps);
+ delete data[deps];
+ return;
+ }
+ Object.keys(data[deps]).forEach(function(d) {
+ var r = data[deps][d];
+ if (typeof r !== "string") {
+ this.warn("nonStringDependency", d, JSON.stringify(r));
+ delete data[deps][d];
+ }
+ var hosted = hostedGitInfo.fromUrl(data[deps][d]);
+ if (hosted) {
+ data[deps][d] = hosted.toString();
+ }
+ }, this);
+ }, this);
+ }, "fixDependencies"),
+ fixModulesField: /* @__PURE__ */ __name(function(data) {
+ if (data.modules) {
+ this.warn("deprecatedModules");
+ delete data.modules;
+ }
+ }, "fixModulesField"),
+ fixKeywordsField: /* @__PURE__ */ __name(function(data) {
+ if (typeof data.keywords === "string") {
+ data.keywords = data.keywords.split(/,\s+/);
+ }
+ if (data.keywords && !Array.isArray(data.keywords)) {
+ delete data.keywords;
+ this.warn("nonArrayKeywords");
+ } else if (data.keywords) {
+ data.keywords = data.keywords.filter(function(kw) {
+ if (typeof kw !== "string" || !kw) {
+ this.warn("nonStringKeyword");
+ return false;
+ } else {
+ return true;
+ }
+ }, this);
+ }
+ }, "fixKeywordsField"),
+ fixVersionField: /* @__PURE__ */ __name(function(data, strict) {
+ var loose = !strict;
+ if (!data.version) {
+ data.version = "";
+ return true;
+ }
+ if (!isValidSemver(data.version, loose)) {
+ throw new Error('Invalid version: "' + data.version + '"');
+ }
+ data.version = cleanSemver(data.version, loose);
+ return true;
+ }, "fixVersionField"),
+ fixPeople: /* @__PURE__ */ __name(function(data) {
+ modifyPeople(data, unParsePerson);
+ modifyPeople(data, parsePerson);
+ }, "fixPeople"),
+ fixNameField: /* @__PURE__ */ __name(function(data, options2) {
+ if (typeof options2 === "boolean") {
+ options2 = { strict: options2 };
+ } else if (typeof options2 === "undefined") {
+ options2 = {};
+ }
+ var strict = options2.strict;
+ if (!data.name && !strict) {
+ data.name = "";
+ return;
+ }
+ if (typeof data.name !== "string") {
+ throw new Error("name field must be a string.");
+ }
+ if (!strict) {
+ data.name = data.name.trim();
+ }
+ ensureValidName(data.name, strict, options2.allowLegacyCase);
+ if (isBuiltin(data.name)) {
+ this.warn("conflictingName", data.name);
+ }
+ }, "fixNameField"),
+ fixDescriptionField: /* @__PURE__ */ __name(function(data) {
+ if (data.description && typeof data.description !== "string") {
+ this.warn("nonStringDescription");
+ delete data.description;
+ }
+ if (data.readme && !data.description) {
+ data.description = extractDescription(data.readme);
+ }
+ if (data.description === void 0) {
+ delete data.description;
+ }
+ if (!data.description) {
+ this.warn("missingDescription");
+ }
+ }, "fixDescriptionField"),
+ fixReadmeField: /* @__PURE__ */ __name(function(data) {
+ if (!data.readme) {
+ this.warn("missingReadme");
+ data.readme = "ERROR: No README data found!";
+ }
+ }, "fixReadmeField"),
+ fixBugsField: /* @__PURE__ */ __name(function(data) {
+ if (!data.bugs && data.repository && data.repository.url) {
+ var hosted = hostedGitInfo.fromUrl(data.repository.url);
+ if (hosted && hosted.bugs()) {
+ data.bugs = { url: hosted.bugs() };
+ }
+ } else if (data.bugs) {
+ if (typeof data.bugs === "string") {
+ if (isEmail(data.bugs)) {
+ data.bugs = { email: data.bugs };
+ } else if (URL2.canParse(data.bugs)) {
+ data.bugs = { url: data.bugs };
+ } else {
+ this.warn("nonEmailUrlBugsString");
+ }
+ } else {
+ bugsTypos(data.bugs, this.warn);
+ var oldBugs = data.bugs;
+ data.bugs = {};
+ if (oldBugs.url) {
+ if (URL2.canParse(oldBugs.url)) {
+ data.bugs.url = oldBugs.url;
+ } else {
+ this.warn("nonUrlBugsUrlField");
+ }
+ }
+ if (oldBugs.email) {
+ if (typeof oldBugs.email === "string" && isEmail(oldBugs.email)) {
+ data.bugs.email = oldBugs.email;
+ } else {
+ this.warn("nonEmailBugsEmailField");
+ }
+ }
+ }
+ if (!data.bugs.email && !data.bugs.url) {
+ delete data.bugs;
+ this.warn("emptyNormalizedBugs");
+ }
+ }
+ }, "fixBugsField"),
+ fixHomepageField: /* @__PURE__ */ __name(function(data) {
+ if (!data.homepage && data.repository && data.repository.url) {
+ var hosted = hostedGitInfo.fromUrl(data.repository.url);
+ if (hosted && hosted.docs()) {
+ data.homepage = hosted.docs();
+ }
+ }
+ if (!data.homepage) {
+ return;
+ }
+ if (typeof data.homepage !== "string") {
+ this.warn("nonUrlHomepage");
+ return delete data.homepage;
+ }
+ if (!URL2.canParse(data.homepage)) {
+ data.homepage = "http://" + data.homepage;
+ }
+ }, "fixHomepageField"),
+ fixLicenseField: /* @__PURE__ */ __name(function(data) {
+ const license = data.license || data.licence;
+ if (!license) {
+ return this.warn("missingLicense");
+ }
+ if (typeof license !== "string" || license.length < 1 || license.trim() === "") {
+ return this.warn("invalidLicense");
+ }
+ if (!validateLicense(license).validForNewPackages) {
+ return this.warn("invalidLicense");
+ }
+ }, "fixLicenseField")
+ };
+ function isValidScopedPackageName(spec) {
+ if (spec.charAt(0) !== "@") {
+ return false;
+ }
+ var rest = spec.slice(1).split("/");
+ if (rest.length !== 2) {
+ return false;
+ }
+ return rest[0] && rest[1] && rest[0] === encodeURIComponent(rest[0]) && rest[1] === encodeURIComponent(rest[1]);
+ }
+ __name(isValidScopedPackageName, "isValidScopedPackageName");
+ function isCorrectlyEncodedName(spec) {
+ return !spec.match(/[/@\s+%:]/) && spec === encodeURIComponent(spec);
+ }
+ __name(isCorrectlyEncodedName, "isCorrectlyEncodedName");
+ function ensureValidName(name, strict, allowLegacyCase) {
+ if (name.charAt(0) === "." || !(isValidScopedPackageName(name) || isCorrectlyEncodedName(name)) || strict && !allowLegacyCase && name !== name.toLowerCase() || name.toLowerCase() === "node_modules" || name.toLowerCase() === "favicon.ico") {
+ throw new Error("Invalid name: " + JSON.stringify(name));
+ }
+ }
+ __name(ensureValidName, "ensureValidName");
+ function modifyPeople(data, fn) {
+ if (data.author) {
+ data.author = fn(data.author);
+ }
+ ["maintainers", "contributors"].forEach(function(set2) {
+ if (!Array.isArray(data[set2])) {
+ return;
+ }
+ data[set2] = data[set2].map(fn);
+ });
+ return data;
+ }
+ __name(modifyPeople, "modifyPeople");
+ function unParsePerson(person) {
+ if (typeof person === "string") {
+ return person;
+ }
+ var name = person.name || "";
+ var u = person.url || person.web;
+ var wrappedUrl = u ? " (" + u + ")" : "";
+ var e = person.email || person.mail;
+ var wrappedEmail = e ? " <" + e + ">" : "";
+ return name + wrappedEmail + wrappedUrl;
+ }
+ __name(unParsePerson, "unParsePerson");
+ function parsePerson(person) {
+ if (typeof person !== "string") {
+ return person;
+ }
+ var matchedName = person.match(/^([^(<]+)/);
+ var matchedUrl = person.match(/\(([^()]+)\)/);
+ var matchedEmail = person.match(/<([^<>]+)>/);
+ var obj = {};
+ if (matchedName && matchedName[0].trim()) {
+ obj.name = matchedName[0].trim();
+ }
+ if (matchedEmail) {
+ obj.email = matchedEmail[1];
+ }
+ if (matchedUrl) {
+ obj.url = matchedUrl[1];
+ }
+ return obj;
+ }
+ __name(parsePerson, "parsePerson");
+ function addOptionalDepsToDeps(data) {
+ var o = data.optionalDependencies;
+ if (!o) {
+ return;
+ }
+ var d = data.dependencies || {};
+ Object.keys(o).forEach(function(k) {
+ d[k] = o[k];
+ });
+ data.dependencies = d;
+ }
+ __name(addOptionalDepsToDeps, "addOptionalDepsToDeps");
+ function depObjectify(deps, type2, warn) {
+ if (!deps) {
+ return {};
+ }
+ if (typeof deps === "string") {
+ deps = deps.trim().split(/[\n\r\s\t ,]+/);
+ }
+ if (!Array.isArray(deps)) {
+ return deps;
+ }
+ warn("deprecatedArrayDependencies", type2);
+ var o = {};
+ deps.filter(function(d) {
+ return typeof d === "string";
+ }).forEach(function(d) {
+ d = d.trim().split(/(:?[@\s><=])/);
+ var dn = d.shift();
+ var dv = d.join("");
+ dv = dv.trim();
+ dv = dv.replace(/^@/, "");
+ o[dn] = dv;
+ });
+ return o;
+ }
+ __name(depObjectify, "depObjectify");
+ function objectifyDeps(data, warn) {
+ depTypes.forEach(function(type2) {
+ if (!data[type2]) {
+ return;
+ }
+ data[type2] = depObjectify(data[type2], type2, warn);
+ });
+ }
+ __name(objectifyDeps, "objectifyDeps");
+ function bugsTypos(bugs, warn) {
+ if (!bugs) {
+ return;
+ }
+ Object.keys(bugs).forEach(function(k) {
+ if (typos.bugs[k]) {
+ warn("typo", k, typos.bugs[k], "bugs");
+ bugs[typos.bugs[k]] = bugs[k];
+ delete bugs[k];
+ }
+ });
+ }
+ __name(bugsTypos, "bugsTypos");
+ }
+});
+
+// node_modules/read-package-up/node_modules/normalize-package-data/lib/warning_messages.json
+var require_warning_messages = __commonJS({
+ "node_modules/read-package-up/node_modules/normalize-package-data/lib/warning_messages.json"(exports2, module2) {
+ module2.exports = {
+ repositories: "'repositories' (plural) Not supported. Please pick one as the 'repository' field",
+ missingRepository: "No repository field.",
+ brokenGitUrl: "Probably broken git url: %s",
+ nonObjectScripts: "scripts must be an object",
+ nonStringScript: "script values must be string commands",
+ nonArrayFiles: "Invalid 'files' member",
+ invalidFilename: "Invalid filename in 'files' list: %s",
+ nonArrayBundleDependencies: "Invalid 'bundleDependencies' list. Must be array of package names",
+ nonStringBundleDependency: "Invalid bundleDependencies member: %s",
+ nonDependencyBundleDependency: "Non-dependency in bundleDependencies: %s",
+ nonObjectDependencies: "%s field must be an object",
+ nonStringDependency: "Invalid dependency: %s %s",
+ deprecatedArrayDependencies: "specifying %s as array is deprecated",
+ deprecatedModules: "modules field is deprecated",
+ nonArrayKeywords: "keywords should be an array of strings",
+ nonStringKeyword: "keywords should be an array of strings",
+ conflictingName: "%s is also the name of a node core module.",
+ nonStringDescription: "'description' field should be a string",
+ missingDescription: "No description",
+ missingReadme: "No README data",
+ missingLicense: "No license field.",
+ nonEmailUrlBugsString: "Bug string field must be url, email, or {email,url}",
+ nonUrlBugsUrlField: "bugs.url field must be a string url. Deleted.",
+ nonEmailBugsEmailField: "bugs.email field must be a string email. Deleted.",
+ emptyNormalizedBugs: "Normalized value of bugs field is an empty object. Deleted.",
+ nonUrlHomepage: "homepage field must be a string url. Deleted.",
+ invalidLicense: "license should be a valid SPDX license expression",
+ typo: "%s should probably be %s."
+ };
+ }
+});
+
+// node_modules/read-package-up/node_modules/normalize-package-data/lib/make_warning.js
+var require_make_warning = __commonJS({
+ "node_modules/read-package-up/node_modules/normalize-package-data/lib/make_warning.js"(exports2, module2) {
+ init_esbuild_shims();
+ var util = __require("util");
+ var messages = require_warning_messages();
+ module2.exports = function() {
+ var args = Array.prototype.slice.call(arguments, 0);
+ var warningName = args.shift();
+ if (warningName === "typo") {
+ return makeTypoWarning.apply(null, args);
+ } else {
+ var msgTemplate = messages[warningName] ? messages[warningName] : warningName + ": '%s'";
+ args.unshift(msgTemplate);
+ return util.format.apply(null, args);
+ }
+ };
+ function makeTypoWarning(providedName, probableName, field) {
+ if (field) {
+ providedName = field + "['" + providedName + "']";
+ probableName = field + "['" + probableName + "']";
+ }
+ return util.format(messages.typo, providedName, probableName);
+ }
+ __name(makeTypoWarning, "makeTypoWarning");
+ }
+});
+
+// node_modules/read-package-up/node_modules/normalize-package-data/lib/normalize.js
+var require_normalize = __commonJS({
+ "node_modules/read-package-up/node_modules/normalize-package-data/lib/normalize.js"(exports2, module2) {
+ init_esbuild_shims();
+ module2.exports = normalize5;
+ var fixer = require_fixer();
+ normalize5.fixer = fixer;
+ var makeWarning = require_make_warning();
+ var fieldsToFix = [
+ "name",
+ "version",
+ "description",
+ "repository",
+ "modules",
+ "scripts",
+ "files",
+ "bin",
+ "man",
+ "bugs",
+ "keywords",
+ "readme",
+ "homepage",
+ "license"
+ ];
+ var otherThingsToFix = ["dependencies", "people", "typos"];
+ var thingsToFix = fieldsToFix.map(function(fieldName) {
+ return ucFirst(fieldName) + "Field";
+ });
+ thingsToFix = thingsToFix.concat(otherThingsToFix);
+ function normalize5(data, warn, strict) {
+ if (warn === true) {
+ warn = null;
+ strict = true;
+ }
+ if (!strict) {
+ strict = false;
+ }
+ if (!warn || data.private) {
+ warn = /* @__PURE__ */ __name(function() {
+ }, "warn");
+ }
+ if (data.scripts && data.scripts.install === "node-gyp rebuild" && !data.scripts.preinstall) {
+ data.gypfile = true;
+ }
+ fixer.warn = function() {
+ warn(makeWarning.apply(null, arguments));
+ };
+ thingsToFix.forEach(function(thingName) {
+ fixer["fix" + ucFirst(thingName)](data, strict);
+ });
+ data._id = data.name + "@" + data.version;
+ }
+ __name(normalize5, "normalize");
+ function ucFirst(string4) {
+ return string4.charAt(0).toUpperCase() + string4.slice(1);
+ }
+ __name(ucFirst, "ucFirst");
+ }
+});
+
+// packages/cli/src/cli.tsx
+init_esbuild_shims();
+
+// node_modules/ink/build/index.js
+init_esbuild_shims();
+
+// node_modules/ink/build/render.js
+init_esbuild_shims();
+import { Stream } from "node:stream";
+import process13 from "node:process";
+
+// node_modules/ink/build/ink.js
+init_esbuild_shims();
+var import_react16 = __toESM(require_react(), 1);
+import process12 from "node:process";
+
+// node_modules/es-toolkit/dist/compat/index.mjs
+init_esbuild_shims();
+
+// node_modules/es-toolkit/dist/compat/function/debounce.mjs
+init_esbuild_shims();
+
+// node_modules/es-toolkit/dist/function/debounce.mjs
+init_esbuild_shims();
+function debounce(func, debounceMs, { signal, edges } = {}) {
+ let pendingThis = void 0;
+ let pendingArgs = null;
+ const leading = edges != null && edges.includes("leading");
+ const trailing = edges == null || edges.includes("trailing");
+ const invoke = /* @__PURE__ */ __name(() => {
+ if (pendingArgs !== null) {
+ func.apply(pendingThis, pendingArgs);
+ pendingThis = void 0;
+ pendingArgs = null;
+ }
+ }, "invoke");
+ const onTimerEnd = /* @__PURE__ */ __name(() => {
+ if (trailing) invoke();
+ cancel();
+ }, "onTimerEnd");
+ let timeoutId = null;
+ const schedule = /* @__PURE__ */ __name(() => {
+ if (timeoutId != null) clearTimeout(timeoutId);
+ timeoutId = setTimeout(() => {
+ timeoutId = null;
+ onTimerEnd();
+ }, debounceMs);
+ }, "schedule");
+ const cancelTimer = /* @__PURE__ */ __name(() => {
+ if (timeoutId !== null) {
+ clearTimeout(timeoutId);
+ timeoutId = null;
+ }
+ }, "cancelTimer");
+ const cancel = /* @__PURE__ */ __name(() => {
+ cancelTimer();
+ pendingThis = void 0;
+ pendingArgs = null;
+ }, "cancel");
+ const flush = /* @__PURE__ */ __name(() => {
+ invoke();
+ }, "flush");
+ const debounced = /* @__PURE__ */ __name(function(...args) {
+ if (signal?.aborted) return;
+ pendingThis = this;
+ pendingArgs = args;
+ const isFirstCall = timeoutId == null;
+ schedule();
+ if (leading && isFirstCall) invoke();
+ }, "debounced");
+ debounced.schedule = schedule;
+ debounced.cancel = cancel;
+ debounced.flush = flush;
+ signal?.addEventListener("abort", cancel, { once: true });
+ return debounced;
+}
+__name(debounce, "debounce");
+
+// node_modules/es-toolkit/dist/compat/function/debounce.mjs
+function debounce2(func, debounceMs = 0, options2 = {}) {
+ if (typeof options2 !== "object") options2 = {};
+ const { leading = false, trailing = true, maxWait } = options2;
+ const edges = Array(2);
+ if (leading) edges[0] = "leading";
+ if (trailing) edges[1] = "trailing";
+ let result = void 0;
+ let pendingAt = null;
+ const _debounced = debounce(function(...args) {
+ result = func.apply(this, args);
+ pendingAt = null;
+ }, debounceMs, { edges });
+ const debounced = /* @__PURE__ */ __name(function(...args) {
+ if (maxWait != null) {
+ if (pendingAt === null) pendingAt = Date.now();
+ if (Date.now() - pendingAt >= maxWait) {
+ result = func.apply(this, args);
+ pendingAt = Date.now();
+ _debounced.cancel();
+ _debounced.schedule();
+ return result;
+ }
+ }
+ _debounced.apply(this, args);
+ return result;
+ }, "debounced");
+ const flush = /* @__PURE__ */ __name(() => {
+ _debounced.flush();
+ return result;
+ }, "flush");
+ debounced.cancel = _debounced.cancel;
+ debounced.flush = flush;
+ return debounced;
+}
+__name(debounce2, "debounce");
+
+// node_modules/es-toolkit/dist/compat/function/throttle.mjs
+init_esbuild_shims();
+function throttle(func, throttleMs = 0, options2 = {}) {
+ const { leading = true, trailing = true } = options2;
+ return debounce2(func, throttleMs, {
+ leading,
+ maxWait: throttleMs,
+ trailing
+ });
+}
+__name(throttle, "throttle");
+
+// node_modules/ansi-escapes/index.js
+init_esbuild_shims();
+
+// node_modules/ansi-escapes/base.js
+var base_exports = {};
+__export(base_exports, {
+ ConEmu: () => ConEmu,
+ beep: () => beep,
+ beginSynchronizedOutput: () => beginSynchronizedOutput,
+ clearScreen: () => clearScreen,
+ clearTerminal: () => clearTerminal,
+ clearViewport: () => clearViewport,
+ cursorBackward: () => cursorBackward,
+ cursorDown: () => cursorDown,
+ cursorForward: () => cursorForward,
+ cursorGetPosition: () => cursorGetPosition,
+ cursorHide: () => cursorHide,
+ cursorLeft: () => cursorLeft,
+ cursorMove: () => cursorMove,
+ cursorNextLine: () => cursorNextLine,
+ cursorPrevLine: () => cursorPrevLine,
+ cursorRestorePosition: () => cursorRestorePosition,
+ cursorSavePosition: () => cursorSavePosition,
+ cursorShow: () => cursorShow,
+ cursorTo: () => cursorTo,
+ cursorUp: () => cursorUp,
+ endSynchronizedOutput: () => endSynchronizedOutput,
+ enterAlternativeScreen: () => enterAlternativeScreen,
+ eraseDown: () => eraseDown,
+ eraseEndLine: () => eraseEndLine,
+ eraseLine: () => eraseLine,
+ eraseLines: () => eraseLines,
+ eraseScreen: () => eraseScreen,
+ eraseStartLine: () => eraseStartLine,
+ eraseUp: () => eraseUp,
+ exitAlternativeScreen: () => exitAlternativeScreen,
+ iTerm: () => iTerm,
+ image: () => image,
+ link: () => link,
+ scrollDown: () => scrollDown,
+ scrollUp: () => scrollUp,
+ setCwd: () => setCwd,
+ synchronizedOutput: () => synchronizedOutput
+});
+init_esbuild_shims();
+import process2 from "node:process";
+import os from "node:os";
+
+// node_modules/environment/index.js
+init_esbuild_shims();
+var isBrowser = globalThis.window?.document !== void 0;
+var isNode = globalThis.process?.versions?.node !== void 0;
+var isBun = globalThis.process?.versions?.bun !== void 0;
+var isDeno = globalThis.Deno?.version?.deno !== void 0;
+var isElectron = globalThis.process?.versions?.electron !== void 0;
+var isJsDom = globalThis.navigator?.userAgent?.includes("jsdom") === true;
+var isWebWorker = typeof WorkerGlobalScope !== "undefined" && globalThis instanceof WorkerGlobalScope;
+var isDedicatedWorker = typeof DedicatedWorkerGlobalScope !== "undefined" && globalThis instanceof DedicatedWorkerGlobalScope;
+var isSharedWorker = typeof SharedWorkerGlobalScope !== "undefined" && globalThis instanceof SharedWorkerGlobalScope;
+var isServiceWorker = typeof ServiceWorkerGlobalScope !== "undefined" && globalThis instanceof ServiceWorkerGlobalScope;
+var platform = globalThis.navigator?.userAgentData?.platform;
+var isMacOs = platform === "macOS" || globalThis.navigator?.platform === "MacIntel" || globalThis.navigator?.userAgent?.includes(" Mac ") === true || globalThis.process?.platform === "darwin";
+var isWindows = platform === "Windows" || globalThis.navigator?.platform === "Win32" || globalThis.process?.platform === "win32";
+var isLinux = platform === "Linux" || globalThis.navigator?.platform?.startsWith("Linux") === true || globalThis.navigator?.userAgent?.includes(" Linux ") === true || globalThis.process?.platform === "linux";
+var isIos = platform === "iOS" || globalThis.navigator?.platform === "MacIntel" && globalThis.navigator?.maxTouchPoints > 1 || /iPad|iPhone|iPod/.test(globalThis.navigator?.platform);
+var isAndroid = platform === "Android" || globalThis.navigator?.platform === "Android" || globalThis.navigator?.userAgent?.includes(" Android ") === true || globalThis.process?.platform === "android";
+
+// node_modules/ansi-escapes/base.js
+var ESC = "\x1B[";
+var OSC = "\x1B]";
+var BEL = "\x07";
+var SEP = ";";
+var isTerminalApp = !isBrowser && process2.env.TERM_PROGRAM === "Apple_Terminal";
+var isWindows2 = !isBrowser && process2.platform === "win32";
+var isTmux = !isBrowser && (process2.env.TERM?.startsWith("screen") || process2.env.TERM?.startsWith("tmux") || process2.env.TMUX !== void 0);
+var cwdFunction = isBrowser ? () => {
+ throw new Error("`process.cwd()` only works in Node.js, not the browser.");
+} : process2.cwd;
+var wrapOsc = /* @__PURE__ */ __name((sequence) => {
+ if (isTmux) {
+ return "\x1BPtmux;" + sequence.replaceAll("\x1B", "\x1B\x1B") + "\x1B\\";
+ }
+ return sequence;
+}, "wrapOsc");
+var cursorTo = /* @__PURE__ */ __name((x, y) => {
+ if (typeof x !== "number") {
+ throw new TypeError("The `x` argument is required");
+ }
+ if (typeof y !== "number") {
+ return ESC + (x + 1) + "G";
+ }
+ return ESC + (y + 1) + SEP + (x + 1) + "H";
+}, "cursorTo");
+var cursorMove = /* @__PURE__ */ __name((x, y) => {
+ if (typeof x !== "number") {
+ throw new TypeError("The `x` argument is required");
+ }
+ let returnValue = "";
+ if (x < 0) {
+ returnValue += ESC + -x + "D";
+ } else if (x > 0) {
+ returnValue += ESC + x + "C";
+ }
+ if (y < 0) {
+ returnValue += ESC + -y + "A";
+ } else if (y > 0) {
+ returnValue += ESC + y + "B";
+ }
+ return returnValue;
+}, "cursorMove");
+var cursorUp = /* @__PURE__ */ __name((count = 1) => ESC + count + "A", "cursorUp");
+var cursorDown = /* @__PURE__ */ __name((count = 1) => ESC + count + "B", "cursorDown");
+var cursorForward = /* @__PURE__ */ __name((count = 1) => ESC + count + "C", "cursorForward");
+var cursorBackward = /* @__PURE__ */ __name((count = 1) => ESC + count + "D", "cursorBackward");
+var cursorLeft = ESC + "G";
+var cursorSavePosition = isTerminalApp ? "\x1B7" : ESC + "s";
+var cursorRestorePosition = isTerminalApp ? "\x1B8" : ESC + "u";
+var cursorGetPosition = ESC + "6n";
+var cursorNextLine = ESC + "E";
+var cursorPrevLine = ESC + "F";
+var cursorHide = ESC + "?25l";
+var cursorShow = ESC + "?25h";
+var eraseLines = /* @__PURE__ */ __name((count) => {
+ let clear = "";
+ for (let i = 0; i < count; i++) {
+ clear += eraseLine + (i < count - 1 ? cursorUp() : "");
+ }
+ if (count) {
+ clear += cursorLeft;
+ }
+ return clear;
+}, "eraseLines");
+var eraseEndLine = ESC + "K";
+var eraseStartLine = ESC + "1K";
+var eraseLine = ESC + "2K";
+var eraseDown = ESC + "J";
+var eraseUp = ESC + "1J";
+var eraseScreen = ESC + "2J";
+var scrollUp = ESC + "S";
+var scrollDown = ESC + "T";
+var clearScreen = "\x1Bc";
+var clearViewport = `${eraseScreen}${ESC}H`;
+var isOldWindows = /* @__PURE__ */ __name(() => {
+ if (isBrowser || !isWindows2) {
+ return false;
+ }
+ const parts = os.release().split(".");
+ const major = Number(parts[0]);
+ const build = Number(parts[2] ?? 0);
+ if (major < 10) {
+ return true;
+ }
+ if (major === 10 && build < 10586) {
+ return true;
+ }
+ return false;
+}, "isOldWindows");
+var clearTerminal = isOldWindows() ? `${eraseScreen}${ESC}0f` : `${eraseScreen}${ESC}3J${ESC}H`;
+var enterAlternativeScreen = ESC + "?1049h";
+var exitAlternativeScreen = ESC + "?1049l";
+var beginSynchronizedOutput = ESC + "?2026h";
+var endSynchronizedOutput = ESC + "?2026l";
+var synchronizedOutput = /* @__PURE__ */ __name((text) => beginSynchronizedOutput + text + endSynchronizedOutput, "synchronizedOutput");
+var beep = BEL;
+var link = /* @__PURE__ */ __name((text, url2) => {
+ const openLink = wrapOsc(`${OSC}8${SEP}${SEP}${url2}${BEL}`);
+ const closeLink = wrapOsc(`${OSC}8${SEP}${SEP}${BEL}`);
+ return openLink + text + closeLink;
+}, "link");
+var image = /* @__PURE__ */ __name((data, options2 = {}) => {
+ let returnValue = `${OSC}1337;File=inline=1`;
+ if (options2.width) {
+ returnValue += `;width=${options2.width}`;
+ }
+ if (options2.height) {
+ returnValue += `;height=${options2.height}`;
+ }
+ if (options2.preserveAspectRatio === false) {
+ returnValue += ";preserveAspectRatio=0";
+ }
+ const imageBuffer = Buffer.from(data);
+ return wrapOsc(returnValue + `;size=${imageBuffer.byteLength}:` + imageBuffer.toString("base64") + BEL);
+}, "image");
+var iTerm = {
+ setCwd: /* @__PURE__ */ __name((cwd2 = cwdFunction()) => wrapOsc(`${OSC}50;CurrentDir=${cwd2}${BEL}`), "setCwd"),
+ annotation(message, options2 = {}) {
+ let returnValue = `${OSC}1337;`;
+ const hasX = options2.x !== void 0;
+ const hasY = options2.y !== void 0;
+ if ((hasX || hasY) && !(hasX && hasY && options2.length !== void 0)) {
+ throw new Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");
+ }
+ message = message.replaceAll("|", "");
+ returnValue += options2.isHidden ? "AddHiddenAnnotation=" : "AddAnnotation=";
+ if (options2.length > 0) {
+ returnValue += (hasX ? [message, options2.length, options2.x, options2.y] : [options2.length, message]).join("|");
+ } else {
+ returnValue += message;
+ }
+ return wrapOsc(returnValue + BEL);
+ }
+};
+var ConEmu = {
+ setCwd: /* @__PURE__ */ __name((cwd2 = cwdFunction()) => wrapOsc(`${OSC}9;9;${cwd2}${BEL}`), "setCwd")
+};
+var setCwd = /* @__PURE__ */ __name((cwd2 = cwdFunction()) => iTerm.setCwd(cwd2) + ConEmu.setCwd(cwd2), "setCwd");
+
+// node_modules/is-in-ci/index.js
+init_esbuild_shims();
+import { env } from "node:process";
+var check = /* @__PURE__ */ __name((key) => key in env && env[key] !== "0" && env[key] !== "false", "check");
+var isInCi = check("CI") || check("CONTINUOUS_INTEGRATION");
+var is_in_ci_default = isInCi;
+
+// node_modules/auto-bind/index.js
+init_esbuild_shims();
+var getAllProperties = /* @__PURE__ */ __name((object2) => {
+ const properties = /* @__PURE__ */ new Set();
+ do {
+ for (const key of Reflect.ownKeys(object2)) {
+ properties.add([object2, key]);
+ }
+ } while ((object2 = Reflect.getPrototypeOf(object2)) && object2 !== Object.prototype);
+ return properties;
+}, "getAllProperties");
+function autoBind(self2, { include, exclude } = {}) {
+ const filter = /* @__PURE__ */ __name((key) => {
+ const match = /* @__PURE__ */ __name((pattern) => typeof pattern === "string" ? key === pattern : pattern.test(key), "match");
+ if (include) {
+ return include.some(match);
+ }
+ if (exclude) {
+ return !exclude.some(match);
+ }
+ return true;
+ }, "filter");
+ for (const [object2, key] of getAllProperties(self2.constructor.prototype)) {
+ if (key === "constructor" || !filter(key)) {
+ continue;
+ }
+ const descriptor = Reflect.getOwnPropertyDescriptor(object2, key);
+ if (descriptor && typeof descriptor.value === "function") {
+ self2[key] = self2[key].bind(self2);
+ }
+ }
+ return self2;
+}
+__name(autoBind, "autoBind");
+
+// node_modules/ink/build/ink.js
+var import_signal_exit2 = __toESM(require_signal_exit(), 1);
+
+// node_modules/patch-console/dist/index.js
+init_esbuild_shims();
+import { PassThrough } from "node:stream";
+var consoleMethods = [
+ "assert",
+ "count",
+ "countReset",
+ "debug",
+ "dir",
+ "dirxml",
+ "error",
+ "group",
+ "groupCollapsed",
+ "groupEnd",
+ "info",
+ "log",
+ "table",
+ "time",
+ "timeEnd",
+ "timeLog",
+ "trace",
+ "warn"
+];
+var originalMethods = {};
+var patchConsole = /* @__PURE__ */ __name((callback) => {
+ const stdout = new PassThrough();
+ const stderr = new PassThrough();
+ stdout.write = (data) => {
+ callback("stdout", data);
+ };
+ stderr.write = (data) => {
+ callback("stderr", data);
+ };
+ const internalConsole = new console.Console(stdout, stderr);
+ for (const method of consoleMethods) {
+ originalMethods[method] = console[method];
+ console[method] = internalConsole[method];
+ }
+ return () => {
+ for (const method of consoleMethods) {
+ console[method] = originalMethods[method];
+ }
+ originalMethods = {};
+ };
+}, "patchConsole");
+var dist_default = patchConsole;
+
+// node_modules/ink/build/ink.js
+var import_constants2 = __toESM(require_constants(), 1);
+
+// node_modules/yoga-layout/dist/src/index.js
+init_esbuild_shims();
+
+// node_modules/yoga-layout/dist/binaries/yoga-wasm-base64-esm.js
+init_esbuild_shims();
+var loadYoga = (() => {
+ var _scriptDir = import.meta.url;
+ return (function(loadYoga2) {
+ loadYoga2 = loadYoga2 || {};
+ var h;
+ h || (h = typeof loadYoga2 !== "undefined" ? loadYoga2 : {});
+ var aa, ca;
+ h.ready = new Promise(function(a, b) {
+ aa = a;
+ ca = b;
+ });
+ var da = Object.assign({}, h), q = "";
+ "undefined" != typeof document && document.currentScript && (q = document.currentScript.src);
+ _scriptDir && (q = _scriptDir);
+ 0 !== q.indexOf("blob:") ? q = q.substr(0, q.replace(/[?#].*/, "").lastIndexOf("/") + 1) : q = "";
+ var ea = h.print || console.log.bind(console), v = h.printErr || console.warn.bind(console);
+ Object.assign(h, da);
+ da = null;
+ var w;
+ h.wasmBinary && (w = h.wasmBinary);
+ var noExitRuntime = h.noExitRuntime || true;
+ "object" != typeof WebAssembly && x("no native wasm support detected");
+ var fa, ha = false;
+ function z2(a, b, c) {
+ c = b + c;
+ for (var d = ""; !(b >= c); ) {
+ var e = a[b++];
+ if (!e) break;
+ if (e & 128) {
+ var f = a[b++] & 63;
+ if (192 == (e & 224)) d += String.fromCharCode((e & 31) << 6 | f);
+ else {
+ var g = a[b++] & 63;
+ e = 224 == (e & 240) ? (e & 15) << 12 | f << 6 | g : (e & 7) << 18 | f << 12 | g << 6 | a[b++] & 63;
+ 65536 > e ? d += String.fromCharCode(e) : (e -= 65536, d += String.fromCharCode(55296 | e >> 10, 56320 | e & 1023));
+ }
+ } else d += String.fromCharCode(e);
+ }
+ return d;
+ }
+ __name(z2, "z");
+ var ia, ja, A, C, ka, D, E, la, ma;
+ function na() {
+ var a = fa.buffer;
+ ia = a;
+ h.HEAP8 = ja = new Int8Array(a);
+ h.HEAP16 = C = new Int16Array(a);
+ h.HEAP32 = D = new Int32Array(a);
+ h.HEAPU8 = A = new Uint8Array(a);
+ h.HEAPU16 = ka = new Uint16Array(a);
+ h.HEAPU32 = E = new Uint32Array(a);
+ h.HEAPF32 = la = new Float32Array(a);
+ h.HEAPF64 = ma = new Float64Array(a);
+ }
+ __name(na, "na");
+ var oa, pa = [], qa = [], ra = [];
+ function sa() {
+ var a = h.preRun.shift();
+ pa.unshift(a);
+ }
+ __name(sa, "sa");
+ var F = 0, ta = null, G = null;
+ function x(a) {
+ if (h.onAbort) h.onAbort(a);
+ a = "Aborted(" + a + ")";
+ v(a);
+ ha = true;
+ a = new WebAssembly.RuntimeError(a + ". Build with -sASSERTIONS for more info.");
+ ca(a);
+ throw a;
+ }
+ __name(x, "x");
+ function ua(a) {
+ return a.startsWith("data:application/octet-stream;base64,");
+ }
+ __name(ua, "ua");
+ var H;
+ H = "data:application/octet-stream;base64,AGFzbQEAAAABugM3YAF/AGACf38AYAF/AX9gA39/fwBgAn98AGACf38Bf2ADf39/AX9gBH9/f30BfWADf398AGAAAGAEf39/fwBgAX8BfGACf38BfGAFf39/f38Bf2AAAX9gA39/fwF9YAZ/f31/fX8AYAV/f39/fwBgAn9/AX1gBX9/f319AX1gAX8BfWADf35/AX5gB39/f39/f38AYAZ/f39/f38AYAR/f39/AX9gBn9/f319fQF9YAR/f31/AGADf399AX1gBn98f39/fwF/YAR/fHx/AGACf30AYAh/f39/f39/fwBgDX9/f39/f39/f39/f38AYAp/f39/f39/f39/AGAFf39/f38BfGAEfHx/fwF9YA1/fX1/f399fX9/f39/AX9gB39/f319f38AYAJ+fwF/YAN/fX0BfWABfAF8YAN/fHwAYAR/f319AGAHf39/fX19fQF9YA1/fX99f31/fX19fX1/AX9gC39/f39/f399fX19AX9gCH9/f39/f319AGAEf39+fgBgB39/f39/f38Bf2ACfH8BfGAFf398fH8AYAN/f38BfGAEf39/fABgA39/fQBgBn9/fX99fwF/ArUBHgFhAWEAHwFhAWIAAwFhAWMACQFhAWQAFgFhAWUAEQFhAWYAIAFhAWcAAAFhAWgAIQFhAWkAAwFhAWoAAAFhAWsAFwFhAWwACgFhAW0ABQFhAW4AAwFhAW8AAQFhAXAAFwFhAXEABgFhAXIAAAFhAXMAIgFhAXQACgFhAXUADQFhAXYAFgFhAXcAAgFhAXgAAwFhAXkAGAFhAXoAAgFhAUEAAQFhAUIAEQFhAUMAAQFhAUQAAAOiAqACAgMSBwcACRkDAAoRBgYKEwAPDxMBBiMTCgcHGgMUASQFJRQHAwMKCgMmAQYYDxobFAAKBw8KBwMDAgkCAAAFGwACBwIHBgIDAQMIDAABKAkHBQURACkZASoAAAIrLAIALQcHBy4HLwkFCgMCMA0xAgMJAgACAQYKAQIBBQEACQIFAQEABQAODQ0GFQIBHBUGAgkCEAAAAAUyDzMMBQYINAUCAwUODg41AgMCAgIDBgICNgIBDAwMAQsLCwsLCx0CAAIAAAABABABBQICAQMCEgMMCwEBAQEBAQsLAQICAwICAgICAgIDAgIICAEICAgEBAQEBAQEBAQABAQABAQEBAAE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GiABQQA2AvADIAFCADcC6AMgAigC7AMiAyACKALoAyIERwRAIAMgBGsiBEEASA0FIAEgBBAeIgM2AuwDIAEgAzYC6AMgASADIARqNgLwAyACKALoAyIEIAIoAuwDIghHBEADQCADIAQoAgA2AgAgA0EEaiEDIARBBGoiBCAIRw0ACwsgASADNgLsAwsgASACKQL0AzcC9AMgASACKAKEBDYChAQgASACKQL8AzcC/AMgAUEANgLkAwsgBSABNgIAIAEgADYC5AMLIAZBAWohBiAFQQRqIgUgB0cNAAsLDwsQAgALUAACQAJAAkACQAJAIAIOBAQAAQIDCyAAIAEgAUEwahBDDwsgACABIAFBMGogAxBEDwsgACABIAFBMGoQQg8LECQACyAAIAEgAUEwaiADEEULcAIBfwF9IwBBEGsiBCQAIARBCGogACABQQJ0QdwlaigCACACEDZDAADAfyEFAkACQAJAIAQtAAxBAWsOAgABAgsgBCoCCCEFDAELIAQqAgggA5RDCtcjPJQhBQsgBEEQaiQAIAVDAAAAACAFIAVbGwt5AgF/AX0jAEEQayIDJAAgA0EIaiAAIAFBAnRB7CVqKAIAIAIQU0MAAMB/IQQCQAJAAkAgAy0ADEEBaw4CAAECCyADKgIIIQQMAQsgAyoCCEMAAAAAlEMK1yM8lCEECyADQRBqJAAgBEMAAAAAl0MAAAAAIAQgBFsbC1QAAkACQAJAAkACQCACDgQEAAECAwsgACABIAFBwgBqEEMPCyAAIAEgAUHCAGogAxBEDwsgACABIAFBwgBqEEIPCxAkAAsgACABIAFBwgBqIAMQRQsvACAAIAJFQQF0IgIgASADEGAgACACIAEQS5IgACACIAEgAxB/IAAgAiABEFKSkgvOAQIDfwJ9IwBBEGsiAyQAQQEhBCADQQhqIABB/ABqIgUgACABQQF0akH2AGoiAS8BABAfAkACQCADKgIIIgcgAioCACIGXARAIAcgB1sEQCACLQAEIQIMAgsgBiAGXCEECyACLQAEIQIgBEUNACADLQAMIAJB/wFxRg0BCyAFIAEgBiACEDkDQCAALQAAIgFBBHENASAAIAFBBHI6AAAgACgCECIBBEAgACABEQAACyAAQYCAgP4HNgKcASAAKALkAyIADQALCyADQRBqJAALzgECA38CfSMAQRBrIgMk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AWsOAgABAgsgBCoCCCEFDAELIAQqAgggA5RDCtcjPJQhBQsgBEEQaiQAIAVDAAAAACAFIAVbGwscACAAIAFBCCACpyACQiCIpyADpyADQiCIpxAVCwUAEFgACzkAIABFBEBBAA8LAn8gAUGAf3FBgL8DRiABQf8ATXJFBEBB/DtBGTYCAEF/DAELIAAgAToAAEEBCwvEAgACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCABQQlrDhIACgsMCgsCAwQFDAsMDAoLBwgJCyACIAIoAgAiAUEEajYCACAAIAEoAgA2AgAPCwALIAIgAigCACIBQQRqNgIAIAAgATIBADcDAA8LIAIgAigCACIBQQRqNgIAIAAgATMBADcDAA8LIAIgAigCACIBQQRqNgIAIAAgATAAADcDAA8LIAIgAigCACIBQQRqNgIAIAAgATEAADcDAA8LAAsgAiACKAIAQQdqQXhxIgFBCGo2AgAgACABKwMAOQMADwsgACACIAMRAQALDwsgAiACKAIAIgFBBGo2AgAgACABNAIANwMADwsgAiACKAIAIgFBBGo2AgAgACABNQIANwMADwsgAiACKAIAQQdqQXhxIgFBCGo2AgAgACABKQMANwMAC84BAgN/An0jAEEQayIDJABBASEEIANBCGogAEH8AGoiBSAAIAFBAXRqQegAaiIBLwEAEB8CQAJAIAMqAggiByACKgIAIgZcBEAgByAHWwRAIAItAAQhAgwCCyAGIAZcIQQLIAItAAQhAiAERQ0AIAMtAAwgAkH/AXFGDQELIAUgASAGIAIQOQNAIAAtAAAiAUEEcQ0BIAAgAUEEcjoAACAAKAIQIgEEQCAAIAERAAALIABBgICA/gc2ApwBIAAoAuQDIgANAAsLIANBEGokAAtdAQR/IAAoAgAhAgNAIAIsAAAiAxBXBEBBfyEEIAAgAkEBaiICNgIAIAFBzJmz5gBNBH9BfyADQTBrIgMgAUEKbCIEaiADIARB/////wdzShsFIAQLIQEMAQsLIAELrhQCEn8BfiMAQdAAayIIJAAgCCABNgJMIAhBN2ohFyAIQThqIRQCQAJAAkACQANAIAEhDSAHIA5B/////wdzSg0BIAcgDmohDgJAAkACQCANIgctAAAiCQRAA0ACQAJAIAlB/wFxIgFFBEAgByEBDAELIAFBJUcNASAH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IQEgAEIANwIEIAAgATYCACABIAA2AgQgAkEQaiQAIAALGwEBfyAABEAgACgCACIBBEAgARAjCyAAECMLC0kBAn9BBBAeIQFBIBAeIgBBADYCHCAAQoCAgICAgIDAPzcCFCAAQgA3AgwgAEEAOgAIIABBAzYCBCAAQQA2AgAgASAANgIAIAELIAAgAkEFR0EAIAIbRQRAQbgwIAMgBBBJDwsgAyAEEHALIgEBfiABIAKtIAOtQiCGhCAEIAARFQAiBUIgiKckASAFpwuoAQEFfyAAKAJUIgMoAgAhBSADKAIEIgQgACgCFCAAKAIcIgdrIgYgBCAGSRsiBgRAIAUgByAGECsaIAMgAygCACAGaiIFNgIAIAMgAygCBCAGayIENgIECyAEIAIgAiAESxsiBARAIAUgASAEECsaIAMgAygCACAEaiIFNgIAIAMgAygCBCAEazYCBAsgBUEAOgAAIAAgACgCLCIBNgIcIAAgATYCFCACCwQAQgALBABBAAuKBQIGfgJ/IAEgASgCAEEHakF4cSIBQRBqNgIAIAAhCSABKQMAIQMgASkDCCEGIwBBIGsiCCQAAkAgBkL///////////8AgyIEQoCAgICAgMCAPH0gBEKAgICAgIDA/8MAfVQEQCAGQgSGIANCPIiEIQQgA0L//////////w+DIgNCgYCAgICAgIAIWgRAIARCgYCAgICAgIDAAHwhAgwCCyAEQoCAgICAgICAQH0hAiADQoCAgICAgICACFINASACIARCAYN8IQIMAQsgA1AgBEKAgICAgIDA//8AVCAEQoCAgICAgMD//wBRG0UEQCAGQgSGIANCPIiEQv////////8Dg0KAgICAgICA/P8AhCECDAELQoCAgICAgID4/wAhAiAEQv///////7//wwBWDQBCACECIARCMIinIgBBkfcASQ0AIAMhAiAGQv///////z+DQoCAgICAgMAAhCIFIQcCQCAAQYH3AGsiAUHAAHEEQCACIAFBQGqthiEHQgAhAgwBCyABRQ0AIAcgAa0iBIYgAkHAACABa62IhCEHIAIgBIYhAgsgCCACNwMQIAggBzcDGAJAQYH4ACAAayIAQcAAcQRAIAUgAEFAaq2IIQNCACEFDAELIABFDQAgBUHAACAAa62GIAMgAK0iAoiEIQMgBSACiCEFCyAIIAM3AwAgCCAF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ASAAKAIAIQAgASACQQFxBH8gASgCACAAaigCAAUgAAsRCwALYQECfyMAQRBrIgIkACABIAAoAgQiA0EBdWohASAAKAIAIQAgAiABIANBAXEEfyABKAIAIABqKAIABSAACxEBAEEQEB4iACACKQMINwMIIAAgAikDADcDACACQRBqJAAgAAtjAQJ/IwBBEGsiAyQAIAEgACgCBCIEQQF1aiEBIAAoAgAhACADIAEgAiAEQQFxBH8gASgCACAAaigCAAUgAAsRAwBBEBAeIgAgAykDCDcDCCAAIAMpAwA3AwAgA0EQaiQAIAALNwEBfyABIAAoAgQiA0EBdWohASAAKAIAIQAgASACIANBAXEEfyABKAIAIABqKAIABSAACxEEAAs5AQF/IAEgACgCBCIEQQF1aiEBIAAoAgAhACABIAIgAyAEQQFxBH8gASgCACAAaigCAAUgAAsRCAALCQAgASAAEQIACwUAQcM7Cw8AIAEgACgCAGogAjYCAAsNACABIAAoAgBqKAIACxgBAX9BEBAeIgBCADcDCCAAQQA2AgAgAAsYAQF/QRAQHiIAQgA3AwAgAEIANwMIIAALDABBMBAeQQBBMBAqCzcBAX8gASAAKAIEIgNBAXVqIQEgACgCACEAIAEgAiADQQFxBH8gASgCACAAaigCAAUgAAsRHgALBQBBvjsLIQAgACABKAIAIAEgASwAC0EASBtBuzsgAigCABAQNgIACyoBAX9BDBAeIgFBADoABCABIAAoAgA2AgggAEEANgIAIAFB2Cc2AgAgAQsFAEG7OwsFAEG4OwshACAAIAEoAgAgASABLAALQQBIG0GkOyACKAIAEBA2AgAL2AEBBH8jAEEgayIDJAAgASgCACIEQfD///8HSQRAAkACQCAEQQtPBEAgBEEPckEBaiIFEB4hBiADIAVBgICAgHhyNgIQIAMgBjYCCCADIAQ2AgwgBCAGaiEFDAELIAMgBDoAEyADQQhqIgYgBGohBSAERQ0BCyAGIAFBBGogBBArGgsgBUEAOgAAIAMgAjYCACADQRhqIANBCGogAyAAEQMAIAMoAhgQHSADKAIYIgAQBiADKAIAEAYgAywAE0EASARAIAMoAggQIwsgA0EgaiQAIAAPCxACAAsqAQF/QQwQHiIBQQA6AAQgASAAKAIANgIIIABBADYCACABQeAmNgIAIAELBQBBpDsLaQECfyMAQRBrIgYkACABIAAoAgQiB0EBdWohASAAKAIAIQAgBiABIAIgAyAEIAUgB0EBcQR/IAEoAgAgAGooAgAFIAALERAAQRAQHiIAIAYpAwg3AwggACAGKQMANwMAIAZBEGokACAACwUAQaA7Cx0AIAAoAgAiACAALQAAQfcBcUEIQQAgARtyOgAAC6oBAgJ/AX0jAEEQayICJAAgACgCACEAIAFB/wFxIgNBBkkEQAJ/AkACQAJAIANBBGsOAgABAgsgAEHUA2ogAC0AiANBA3FBAkYNAhogAEHMA2oMAgsgAEHMA2ogAC0AiANBA3FBAkYNARogAEHUA2oMAQsgACABQf8BcUECdGpBzANqCyoCACEEIAJBEGokACAEuw8LIAJB7hA2AgAgAEEFQdglIAIQLBAkAAuqAQICfwF9IwBBEGsiAiQAIAAoAgAhACABQf8BcSIDQQZJBEACfwJAAkACQCADQQRrDgIAAQILIABBxANqIAAtAIgDQQNxQQJGDQIaIABBvANqDAILIABBvANqIAAtAIgDQQNxQQJGDQEaIABBxANqDAELIAAgAUH/AXFBAnRqQbwDagsqAgAhBCACQRBqJAAgBLsPCyACQe4QNgIAIABBBUHYJSACECwQJAALqgECAn8BfSMAQRBrIgIkACAAKAIAIQAgAUH/AXEiA0EGSQRAAn8CQAJAAkAgA0EEaw4CAAECCyAAQbQDaiAALQCIA0EDcUECRg0CGiAAQawDagwCCyAAQawDaiAALQCIA0EDcUECRg0BGiAAQbQDagwBCyAAIAFB/wFxQQJ0akGsA2oLKgIAIQQgAkEQaiQAIAS7DwsgAkHuEDYCACAAQQVB2CUgAhAsECQAC08AIAAgASgCACIBKgKcA7s5AwAgACABKgKkA7s5AwggACABKgKgA7s5AxAgACABKgKoA7s5AxggACABKgKMA7s5AyAgACABKgKQA7s5AygLDAAgACgCACoCkAO7CwwAIAAoAgAqAowDuwsMACAAKAIAKgKoA7sLDAAgACgCACoCoAO7CwwAIAAoAgAqAqQDuwsMACAAKAIAKgKcA7sL6AMCBH0FfyMAQUBqIgokACAAKAIAIQAgCkEIakEAQTgQKhpB8DpB8DooAgBBAWo2AgAgABB4IAAtABRBA3EiCCADQQEgA0H/AXEbIAgbIQkgAEEUaiEIIAG2IQQgACoC+AMhBQJ9AkACQAJAIAAtAPwDQQFrDgIBAAILIAUgBJRDCtcjPJQhBQsgBUMAAAAAYEUNACAAIAlB/wFxQQAgBCAEEDEgCEECQQEgBBAiIAhBAkEBIAQQIZKSDAELIAggCUH/AXFBACAEIAQQLSIFIAVbBEBBAiELIAggCUH/AXFBACAEIAQQLQwBCyAEIARcIQsgBAshByACtiEFIAAqAoAEIQYgACAHAn0CQAJAAkAgAC0AhARBAWsOAgEAAgsgBiAFlEMK1yM8lCEGCyAGQwAAAABgRQ0AIAAgCUH/AXFBASAFIAQQMSAIQQBBASAEECIgCEEAQQEgBBAhkpIMAQsgCCAJQf8BcSIJQQEgBSAEEC0iBiAGWwRAQQIhDCAIIAlBASAFIAQQLQwBCyAFIAVcIQwgBQsgA0H/AXEgCyAMIAQgBUEBQQAgCkEIakEAQfA6KAIAED0EQCAAIAAtAIgDQQNxIAQgBRB2IABEAAAAAAAAAABEAAAAAAAAAAAQcwsgCkFAayQACw0AIAAoAgAtAABBAXELFQAgACgCACIAIAAtAABB/gFxOgAACxAAIAAoAgAtAABBBHFBAnYLegECfyMAQRBrIgEkACAAKAIAIgAoAggEQANAIAAtAAAiAkEEcUUEQCAAIAJBBHI6AAAgACgCECICBEAgACACEQAACyAAQYCAgP4HNgKcASAAKALkAyIADQELCyABQRBqJAAPCyABQYAINgIAIABBBUHYJSABECwQJAALLgEBfyAAKAIIIQEgAEEANgIIIAEEQCABIAEoAgAoAgQRAAALIAAoAgBBADYCEAsXACAAKAIEKAIIIgAgACgCACgCCBEAAAsuAQF/IAAoAgghAiAAIAE2AgggAgRAIAIgAigCACgCBBEAAAsgACgCAEEFNgIQCz4BAX8gACgCBCEBIABBADYCBCABBEAgASABKAIAKAIEEQAACyAAKAIAIgBBADYCCCAAIAAtAABB7wFxOgAAC0kBAX8jAEEQayIGJAAgBiABKAIEKAIEIgEgAiADIAQgBSABKAIAKAIIERAAIAAgBisDALY4AgAgACAGKwMItjgCBCAGQRBqJAALcwECfyMAQRBrIgIkACAAKAIEIQMgACABNgIEIAMEQCADIAMoAgAoAgQRAAALIAAoAgAiACgC6AMgACgC7ANHBEAgAkH5IzYCACAAQQVB2CUgAhAsECQACyAAQQQ2AgggACAALQAAQRByOgAAIAJBEGokAAs8AQF/AkAgACgCACIAKALsAyAAKALoAyIAa0ECdSABTQ0AIAAgAUECdGooAgAiAEUNACAAKAIEIQILIAILGQAgACgCACgC5AMiAEUEQEEADwsgACgCBAsXACAAKAIAIgAoAuwDIAAoAugDa0ECdQuOAwEDfyMAQdACayICJAACQCAAKAIAIgAoAuwDIAAoAugDRg0AIAEoAgAiAygC5AMhASAAIAMQb0UNACAAIAFGBEAgAkEIakEAQcQCECoaIAJBADoAGCACQgA3AxAgAkGAgID+BzYCDCACQRxqQQBBxAEQKhogAkHgAWohBCACQSBqIQEDQCABQoCAgPyLgIDAv383AhAgAUKBgICAEDcCCCABQoCAgPyLgIDAv383AgAgAUEYaiIBIARHDQALIAJCgICA/IuAgMC/fzcD8AEgAkKBgICAEDcD6AEgAkKAgID8i4CAwL9/NwPgASACQoCAgP6HgIDg/wA3AoQCIAJCgICA/oeAgOD/ADcC/AEgAiACLQD4AUH4AXE6APgBIAJBjAJqQQBBwAAQKhogA0GYAWogAkEIakHEAhArGiADQQA2AuQDCwNAIAAtAAAiAUEEcQ0BIAAgAUEEcjoAACAAKAIQIgEEQCAAIAERAAALIABBgICA/gc2ApwBIAAoAuQDIgANAAsLIAJB0AJqJAAL4AcBCH8jAEHQAGsiByQAIAAoAgAhAAJAAkAgASgCACIIKALkA0UEQCAAKAIIDQEgCC0AF0EQdEGAgDBxQYCAIEYEQCAAIAAoAuADQQFqNgLgAwsgACgC6AMiASACQQJ0aiEGAkAgACgC7AMiBCAAQfADaiIDKAIAIgVJBEAgBCAGRgRAIAYgCDYCACAAIAZBBGo2AuwDDAILIAQgBCICQQRrIgFLBEADQCACIAEoAgA2AgAgAkEEaiECIAFBBGoiASAESQ0ACwsgACACNgLsAyAGQQRqIgEgBEcEQCAEIAQgAWsiAUF8cWsgBiABEDMaCyAGIAg2AgAMAQsgBCABa0ECdUEBaiIEQYCAgIAETw0DAkAgB0EgakH/////AyAFIAFrIgFBAXUiBSAEIAQgBUkbIAFB/P///wdPGyACIAMQSiIDKAIIIgIgAygCDEcNACADKAIEIgEgAygCACIESwRAIAMgASABIARrQQJ1QQFqQX5tQQJ0IgRqIAEgAiABayIBEDMgAWoiAjYCCCADIAMoAgQgBGo2AgQMAQsgB0E4akEBIAIgBGtBAXUgAiAERhsiASABQQJ2IAMoAhAQSiIFKAIIIQQCfyADKAIIIgIgAygCBCIBRgRAIAQhAiABDAELIAQgAiABa2ohAgNAIAQgASgCADYCACABQQRqIQEgBEEEaiIEIAJHDQALIAMoAgghASADKAIECyEEIAMoAgAhCSADIAUoAgA2AgAgBSAJNgIAIAMgBSgCBDYCBCAFIAQ2AgQgAyACNgIIIAUgATYCCCADKAIMIQogAyAFKAIMNgIMIAUgCjYCDCABIARHBEAgBSABIAQgAWtBA2pBfHFqNgIICyAJRQ0AIAkQIyADKAIIIQILIAIgCDYCACADIAMoAghBBGo2AgggAyADKAIEIAYgACgC6AMiAWsiAmsgASACEDM2AgQgAygCCCAGIAAoAuwDIAZrIgQQMyEGIAAoAugDIQEgACADKAIENgLoAyADIAE2AgQgACgC7AMhAiAAIAQgBmo2AuwDIAMgAjYCCCAAKALwAyEEIAAgAygCDDYC8AMgAyABNgIAIAMgBDYCDCABIAJHBEAgAyACIAEgAmtBA2pBfHFqNgIICyABRQ0AIAEQIwsgCCAANgLkAwNAIAAtAAAiAUEEcUUEQCAAIAFBBHI6AAAgACgCECIBBEAgACABEQAACyAAQYCAgP4HNgKcASAAKALkAyIADQELCyAHQdAAaiQADwsgB0HEIzYCECAAQQVB2CUgB0EQahAsECQACyAHQckkNgIAIABBBUHYJSAHECwQJAALEAIACxAAIAAoAgAtAABBAnFBAXYLWQIBfwF9IwBBEGsiAiQAIAJBCGogACgCACIAQfwAaiAAIAFB/wFxQQF0ai8BaBAfQwAAwH8hAwJAAkAgAi0ADA4EAQAAAQALIAIqAgghAwsgAkEQaiQAIAMLTgEBfyMAQRBrIgMkACADQQhqIAEoAgAiAUH8AGogASACQf8BcUEBdGovAUQQHyADLQAMIQEgACADKgIIuzkDCCAAIAE2AgAgA0EQaiQAC14CAX8BfCMAQRBrIgIkACACQQhqIAAoAgAiAEH8AGogACABQf8BcUEBdGovAVYQH0QAAAAAAAD4fyEDAkACQCACLQAMDgQBAAABAAsgAioCCLshAwsgAkEQaiQAIAMLJAEBfUMAAMB/IAAoAgAiAEH8AGogAC8BehAgIgEgASABXBu7C0QBAX8jAEEQayICJAAgAkEIaiABKAIAIgFB/ABqIAEvAXgQHyACLQAMIQEgACACKgIIuzkDCCAAIAE2AgAgAkEQaiQAC0QBAX8jAEEQayICJAAgAkEIaiABKAIAIgFB/ABqIAEvAXYQHyACLQAMIQEgACACKgIIuzkDCCAAIAE2AgAgAkEQaiQAC0QBAX8jAEEQayICJAAgAkEIaiABKAIAIgFB/ABqIAEvAXQQHyACLQAMIQEgACACKgIIuzkDCCAAIAE2AgAgAkEQaiQAC0QBAX8jAEEQayICJAAgAkEIaiABKAIAIgFB/ABqIAEvAXIQHyACLQAMIQEgACACKgIIuzkDCCAAIAE2AgAgAkEQaiQAC0QBAX8jAEEQayICJAAgAkEIaiABKAIAIgFB/ABqIAEvAXAQHyACLQAMIQEgACACKgIIuzkDCCAAIAE2AgAgAkEQaiQAC0QBAX8jAEEQayICJAAgAkEIaiABKAIAIgFB/ABqIAEvAW4QHyACLQAMIQEgACACKgIIuzkDCCAAIAE2AgAgAkEQaiQAC0gCAX8BfQJ9IAAoAgAiAEH8AGoiASAALwEcECAiAiACXARAQwAAgD9DAAAAACAAKAL0Ay0ACEEBcRsMAQsgASAALwEcECALuws2AgF/AX0gACgCACIAQfwAaiIBIAAvARoQICICIAJcBEBEAAAAAAAAAAAPCyABIAAvARoQILsLRAEBfyMAQRBrIgIkACACQQhqIAEoAgAiAUH8AGogAS8BHhAfIAItAAwhASAAIAIqAgi7OQMIIAAgATYCACACQRBqJAALEAAgACgCAC0AF0ECdkEDcQsNACAAKAIALQAXQQNxC04BAX8jAEEQayIDJAAgA0EIaiABKAIAIgFB/ABqIAEgAkH/AXFBAXRqLwEgEB8gAy0ADCEBIAAgAyoCCLs5AwggACABNgIAIANBEGokAAsQACAAKAIALQAUQQR2QQdxCw0AIAAoAgAvABVBDnYLDQAgACgCAC0AFEEDcQsQACAAKAIALQAUQQJ2QQNxCw0AIAAoAgAvABZBD3ELEAAgACgCAC8AFUEEdkEPcQsNACAAKAIALwAVQQ9xC04BAX8jAEEQayIDJAAgA0EIaiABKAIAIgFB/ABqIAEgAkH/AXFBAXRqLwEyEB8gAy0ADCEBIAAgAyoCCLs5AwggACABNgIAIANBEGokAAsQACAAKAIALwAVQQx2QQNxCxAAIAAoAgAtABdBBHZBAXELgQECA38BfSMAQRBrIgMkACAAKAIAIQQCfSACtiIGIAZcBEBBACEAQwAAwH8MAQtBAEECIAZDAACAf1sgBkMAAID/W3IiBRshAEMAAMB/IAYgBRsLIQYgAyAAOgAMIAMgBjgCCCADIAMpAwg3AwAgBCABQf8BcSADEIgBIANBEGokAAt5AgF9An8jAEEQayIEJAAgACgCACEFIAQCfyACtiIDIANcBEBDAADAfyEDQQAMAQtDAADAfyADIANDAACAf1sgA0MAAID/W3IiABshAyAARQs6AAwgBCADOAIIIAQgBCkDCDcDACAFIAFB/wFxIAQQiAEgBEEQaiQAC3EBAX8CQCAAKAIAIgAtAAAiAkECcUEBdiABRg0AIAAgAkH9AXFBAkEAIAEbcjoAAANAIAAtAAAiAUEEcQ0BIAAgAUEEcjoAACAAKAIQIgEEQCAAIAERAAALIABBgICA/gc2ApwBIAAoAuQDIgANAAsLC4EBAgN/AX0jAEEQayIDJAAgACgCACEEAn0gArYiBiAGXARAQQAhAEMAAMB/DAELQQBBAiAGQwAAgH9bIAZDAACA/1tyIgUbIQBDAADAfyAGIAUbCyEGIAMgADoADCADIAY4AgggAyADKQMINwMAIAQgAUH/AXEgAxCOASADQRBqJAALeQIBfQJ/IwBBEGsiBCQAIAAoAgAhBSAEAn8gArYiAyADXARAQwAAwH8hA0EADAELQwAAwH8gAyADQwAAgH9bIANDAACA/1tyIgAbIQMgAEULOgAMIAQgAzgCCCAEIAQpAwg3AwAgBSABQf8BcSAEEI4BIARBEGokAAv5AQICfQR/IwBBEGsiBSQAIAAoAgAhAAJ/IAK2IgMgA1wEQEMAAMB/IQNBAAwBC0MAAMB/IAMgA0MAAIB/WyADQwAAgP9bciIGGyEDIAZFCyEGQQEhByAFQQhqIABB/ABqIgggACABQf8BcUEBdGpB1gBqIgEvAQAQHwJAAkAgAyAFKgIIIgRcBH8gBCAEWw0BIAMgA1wFIAcLRQ0AIAUtAAwgBkYNAQsgCCABIAMgBhA5A0AgAC0AACIBQQRxDQEgACABQQRyOgAAIAAoAhAiAQRAIAAgAREAAAsgAEGAgID+BzYCnAEgACgC5AMiAA0ACwsgBUEQaiQAC7UBAgN/An0CQCAAKAIAIgBB/ABqIgMgAEH6AGoiAi8BABAgIgYgAbYiBVsNACAFIAVbIgRFIAYgBlxxDQACQCAEIAVDAAAAAFsgBYtDAACAf1tyRXFFBEAgAiACLwEAQfj/A3E7AQAMAQsgAyACIAVBAxBMCwNAIAAtAAAiAkEEcQ0BIAAgAkEEcjoAACAAKAIQIgIEQCAAIAIRAAALIABBgICA/gc2ApwBIAAoAuQDIgANAAsLC3wCA38BfSMAQRBrIgIkACAAKAIAIQMCfSABtiIFIAVcBEBBACEAQwAAwH8MAQtBAEECIAVDAACAf1sgBUMAAID/W3IiBBshAEMAAMB/IAUgBBsLIQUgAiAAOgAMIAIgBTgCCCACIAIpAwg3AwAgA0EBIAIQVSACQRBqJAALdAIBfQJ/IwBBEGsiAyQAIAAoAgAhBCADAn8gAbYiAiACXARAQwAAwH8hAkEADAELQwAAwH8gAiACQwAAgH9bIAJDAACA/1tyIgAbIQIgAEULOgAMIAMgAjgCCCADIAMpAwg3AwAgBEEBIAMQVSADQRBqJAALfAIDfwF9IwBBEGsiAiQAIAAoAgAhAwJ9IAG2IgUgBVwEQEEAIQBDAADAfwwBC0EAQQIgBUMAAIB/WyAFQwAAgP9bciIEGyEAQwAAwH8gBSAEGwshBSACIAA6AAwgAiAFOAIIIAIgAikDCDcDACADQQAgAhBVIAJBEGokAAt0AgF9An8jAEEQayIDJAAgACgCACEEIAMCfyABtiICIAJcBEBDAADAfyECQQAMAQtDAADAfyACIAJDAACAf1sgAkMAAID/W3IiABshAiAARQs6AAwgAyACOAIIIAMgAykDCDcDACAEQQAgAxBVIANBEGokAAt8AgN/AX0jAEEQayICJAAgACgCACEDAn0gAbYiBSAFXARAQQAhAEMAAMB/DAELQQBBAiAFQwAAgH9bIAVDAACA/1tyIgQbIQBDAADAfyAFIAQbCyEFIAIgADoADCACIAU4AgggAiACKQMINwMAIANBASACEFYgAkEQaiQAC3QCAX0CfyMAQRBrIgMkACAAKAIAIQQgAwJ/IAG2IgIgAlwEQEMAAMB/IQJBAAwBC0MAAMB/IAIgAkMAAIB/WyACQwAAgP9bciIAGyECIABFCzoADCADIAI4AgggAyADKQMINwMAIARBASADEFYgA0EQaiQAC3wCA38BfSMAQRBrIgIkACAAKAIAIQMCfSABtiIFIAVcBEBBACEAQwAAwH8MAQtBAEECIAVDAACAf1sgBUMAAID/W3IiBBshAEMAAMB/IAUgBBsLIQUgAiAAOgAMIAIgBTgCCCACIAIpAwg3AwAgA0EAIAIQViACQRBqJAALdAIBfQJ/IwBBEGsiAyQAIAAoAgAhBCADAn8gAbYiAiACXARAQwAAwH8hAkEADAELQwAAwH8gAiACQwAAgH9bIAJDAACA/1tyIgAbIQIgAEULOgAMIAMgAjgCCCADIAMpAwg3AwAgBEEAIAMQViADQRBqJAALPwEBfyMAQRBrIgEkACAAKAIAIQAgAUEDOgAMIAFBgICA/gc2AgggASABKQMINwMAIABBASABEEYgAUEQaiQAC3wCA38BfSMAQRBrIgIkACAAKAIAIQMCfSABtiIFIAVcBEBBACEAQwAAwH8MAQtBAEECIAVDAACAf1sgBUMAAID/W3IiBBshAEMAAMB/IAUgBBsLIQUgAiAAOgAMIAIgBTgCCCACIAIpAwg3AwAgA0EBIAIQRiACQRBqJAALdAIBfQJ/IwBBEGsiAyQAIAAoAgAhBCADAn8gAbYiAiACXARAQwAAwH8hAkEADAELQwAAwH8gAiACQwAAgH9bIAJDAACA/1tyIgAbIQIgAEULOgAMIAMgAjgCCCADIAMpAwg3AwAgBEEBIAMQRiADQRBqJAALPwEBfyMAQRBrIgEkACAAKAIAIQAgAUEDOgAMIAFBgICA/gc2AgggASABKQMINwMAIABBACABEEYgAUEQaiQAC3wCA38BfSMAQRBrIgIkACAAKAIAIQMCfSABtiIFIAVcBEBBACEAQwAAwH8MAQtBAEECIAVDAACAf1sgBUMAAID/W3IiBBshAEMAAMB/IAUgBBsLIQUgAiAAOgAMIAIgBTgCCCACIAIpAwg3AwAgA0EAIAIQRiACQRBqJAALdAIBfQJ/IwBBEGsiAyQAIAAoAgAhBCADAn8gAbYiAiACXARAQwAAwH8hAkEADAELQwAAwH8gAiACQwAAgH9bIAJDAACA/1tyIgAbIQIgAEULOgAMIAMgAjgCCCADIAMpAwg3AwAgBEEAIAMQRiADQRBqJAALoAECA38CfQJAIAAoAgAiAEH8AGoiAyAAQRxqIgIvAQAQICIGIAG2IgVbDQAgBSAFWyIERSAGIAZccQ0AAkAgBEUEQCACIAIvAQBB+P8DcTsBAAwBCyADIAIgBUEDEEwLA0AgAC0AACICQQRxDQEgACACQQRyOgAAIAAoAhAiAgRAIAAgAhEAAAsgAEGAgID+BzYCnAEgACgC5AMiAA0ACwsLoAECA38CfQJAIAAoAgAiAEH8AGoiAyAAQRpqIgIvAQAQICIGIAG2IgVbDQAgBSAFWyIERSAGIAZccQ0AAkAgBEUEQCACIAIvAQBB+P8DcTsBAAwBCyADIAIgBUEDEEwLA0AgAC0AACICQQRxDQEgACACQQRyOgAAIAAoAhAiAgRAIAAgAhEAAAsgAEGAgID+BzYCnAEgACgC5AMiAA0ACwsLPQEBfyMAQRBrIgEkACAAKAIAIQAgAUEDOgAMIAFBgICA/gc2AgggASABKQMINwMAIAAgARBrIAFBEGokAAt6AgN/AX0jAEEQayICJAAgACgCACEDAn0gAbYiBSAFXARAQQAhAEMAAMB/DAELQQBBAiAFQwAAgH9bIAVDAACA/1tyIgQbIQBDAADAfyAFIAQbCyEFIAIgADoADCACIAU4AgggAiACKQMINwMAIAMgAhBrIAJBEGokAAtyAgF9An8jAEEQayIDJAAgACgCACEEIAMCfyABtiICIAJcBEBDAADAfyECQQAMAQtDAADAfyACIAJDAACAf1sgAkMAAID/W3IiABshAiAARQs6AAwgAyACOAIIIAMgAykDCDcDACAEIAMQayADQRBqJAALoAECA38CfQJAIAAoAgAiAEH8AGoiAyAAQRhqIgIvAQAQICIGIAG2IgVbDQAgBSAFWyIERSAGIAZccQ0AAkAgBEUEQCACIAIvAQBB+P8DcTsBAAwBCyADIAIgBUEDEEwLA0AgAC0AACICQQRxDQEgACACQQRyOgAAIAAoAhAiAgRAIAAgAhEAAAsgAEGAgID+BzYCnAEgACgC5AMiAA0ACwsLkAEBAX8CQCAAKAIAIgBBF2otAAAiAkECdkEDcSABQf8BcUYNACAAIAAvABUgAkEQdHIiAjsAFSAAIAJB///PB3EgAUEDcUESdHJBEHY6ABcDQCAALQAAIgFBBHENASAAIAFBBHI6AAAgACgCECIBBEAgACABEQAACyAAQYCAgP4HNgKcASAAKALkAyIADQALCwuNAQEBfwJAIAAoAgAiAEEXai0AACICQQNxIAFB/wFxRg0AIAAgAC8AFSACQRB0ciICOwAVIAAgAkH///MHcSABQQNxQRB0ckEQdjoAFwNAIAAtAAAiAUEEcQ0BIAAgAUEEcjoAACAAKAIQIgEEQCAAIAERAAALIABBgICA/gc2ApwBIAAoAuQDIgANAAsLC0MBAX8jAEEQayICJAAgACgCACEAIAJBAzoADCACQYCAgP4HNgIIIAIgAikDCDcDACAAIAFB/wFxIAIQZSACQRBqJAALgAECA38BfSMAQRBrIgMkACAAKAIAIQQCfSACtiIGIAZcBEBBACEAQwAAwH8MAQtBAEECIAZDAACAf1sgBkMAAID/W3IiBRshAEMAAMB/IAYgBRsLIQYgAyAAOgAMIAMgBjgCCCADIAMpAwg3AwAgBCABQf8BcSADEGUgA0EQaiQAC3gCAX0CfyMAQRBrIgQkACAAKAIAIQUgBAJ/IAK2IgMgA1wEQEMAAMB/IQNBAAwBC0MAAMB/IAMgA0MAAIB/WyADQwAAgP9bciIAGyEDIABFCzoADCAEIAM4AgggBCAEKQMINwMAIAUgAUH/AXEgBBBlIARBEGokAAt3AQF/AkAgACgCACIALQAUIgJBBHZBB3EgAUH/AXFGDQAgACACQY8BcSABQQR0QfAAcXI6ABQDQCAALQAAIgFBBHENASAAIAFBBHI6AAAgACgCECIBBEAgACABEQAACyAAQYCAgP4HNgKcASAAKALkAyIADQALCwuJAQEBfwJAIAFB/wFxIAAoAgAiAC8AFSICQQ52Rg0AIABBF2ogAiAALQAXQRB0ciICQRB2OgAAIAAgAkH//wBxIAFBDnRyOwAVA0AgAC0AACIBQQRxDQEgACABQQRyOgAAIAAoAhAiAQRAIAAgAREAAAsgAEGAgID+BzYCnAEgACgC5AMiAA0ACwsLcAEBfwJAIAAoAgAiAC0AFCICQQNxIAFB/wFxRg0AIAAgAkH8AXEgAUEDcXI6ABQDQCAALQAAIgFBBHENASAAIAFBBHI6AAAgACgCECIBBEAgACABEQAACyAAQYCAgP4HNgKcASAAKALkAyIADQALCwt2AQF/AkAgACgCACIALQAUIgJBAnZBA3EgAUH/AXFGDQAgACACQfMBcSABQQJ0QQxxcjoAFANAIAAtAAAiAUEEcQ0BIAAgAUEEcjoAACAAKAIQIgEEQCAAIAERAAALIABBgICA/gc2ApwBIAAoAuQDIgANAAsLC48BAQF/AkAgACgCACIALwAVIgJBCHZBD3EgAUH/AXFGDQAgAEEXaiACIAAtABdBEHRyIgJBEHY6AAAgACACQf/hA3EgAUEPcUEIdHI7ABUDQCAALQAAIgFBBHENASAAIAFBBHI6AAAgACgCECIBBEAgACABEQAACyAAQYCAgP4HNgKcASAAKALkAyIADQALCwuPAQEBfwJAIAFB/wFxIAAoAgAiAC8AFSAAQRdqLQAAQRB0ciICQfABcUEEdkYNACAAIAJBEHY6ABcgACACQY/+A3EgAUEEdEHwAXFyOwAVA0AgAC0AACIBQQRxDQEgACABQQRyOgAAIAAoAhAiAQRAIAAgAREAAAsgAEGAgID+BzYCnAEgACgC5AMiAA0ACwsLhwEBAX8CQCAAKAIAIgAvABUgAEEXai0AAEEQdHIiAkEPcSABQf8BcUYNACAAIAJBEHY6ABcgACACQfD/A3EgAUEPcXI7ABUDQCAALQAAIgFBBHENASAAIAFBBHI6AAAgACgCECIBBEAgACABEQAACyAAQYCAgP4HNgKcASAAKALkAyIADQALCwtDAQF/IwBBEGsiAiQAIAAoAgAhACACQQM6AAwgAkGAgID+BzYCCCACIAIpAwg3AwAgACABQf8BcSACEGcgAkEQaiQAC4ABAgN/AX0jAEEQayIDJAAgACgCACEEAn0gArYiBiAGXARAQQAhAEMAAMB/DAELQQBBAiAGQwAAgH9bIAZDAACA/1tyIgUbIQBDAADAfyAGIAUbCyEGIAMgADoADCADIAY4AgggAyADKQMINwMAIAQgAUH/AXEgAxBnIANBEGokAAt4AgF9An8jAEEQayIEJAAgACgCACEFIAQCfyACtiIDIANcBEBDAADAfyEDQQAMAQtDAADAfyADIANDAACAf1sgA0MAAID/W3IiABshAyAARQs6AAwgBCADOAIIIAQgBCkDCDcDACAFIAFB/wFxIAQQZyAEQRBqJAALjwEBAX8CQCAAKAIAIgAvABUiAkEMdkEDcSABQf8BcUYNACAAQRdqIAIgAC0AF0EQdHIiAkEQdjoAACAAIAJB/58DcSABQQNxQQx0cjsAFQNAIAAtAAAiAUEEcQ0BIAAgAUEEcjoAACAAKAIQIgEEQCAAIAERAAALIABBgICA/gc2ApwBIAAoAuQDIgANAAsLC5ABAQF/AkAgACgCACIAQRdqLQAAIgJBBHZBAXEgAUH/AXFGDQAgACAALwAVIAJBEHRyIgI7ABUgACACQf//vwdxIAFBAXFBFHRyQRB2OgAXA0AgAC0AACIBQQRxDQEgACABQQRyOgAAIAAoAhAiAQRAIAAgAREAAAsgAEGAgID+BzYCnAEgACgC5AMiAA0ACwsL9g0CCH8CfSMAQRBrIgIkAAJAAkAgASgCACIFLQAUIAAoAgAiAS0AFHNB/wBxDQAgBS8AFSAFLQAXQRB0ciABLwAVIAEtABdBEHRyc0H//z9xDQAgBUH8AGohByABQfwAaiEIAkAgAS8AGCIAQQdxRQRAIAUtABhBB3FFDQELIAggABAgIgogByAFLwAYECAiC1sNACAKIApbIAsgC1tyDQELAkAgAS8AGiIAQQdxRQRAIAUtABpBB3FFDQELIAggABAgIgogByAFLwAaECAiC1sNACAKIApbIAsgC1tyDQELAkAgAS8AHCIAQQdxRQRAIAUtABxBB3FFDQELIAggABAgIgogByAFLwAcECAiC1sNACAKIApbIAsgC1tyDQELAkAgAS8AHiIAQQdxRQRAIAUtAB5BB3FFDQELIAJBCGogCCAAEB8gAiAHIAUvAB4QH0EBIQAgAioCCCIKIAIqAgAiC1wEfyAKIApbDQIgCyALXAUgAAtFDQEgAi0ADCACLQAERw0BCyAFQSBqIQAgAUEgaiEGA0ACQCAGIANBAXRqLwAAIgRBB3FFBEAgAC0AAEEHcUUNAQsgAkEIaiAIIAQQHyACIAcgAC8AABAfQQEhBCACKgIIIgogAioCACILXAR/IAogClsNAyALIAtcBSAEC0UNAiACLQAMIAItAARHDQILIABBAmohACADQQFqIgNBCUcNAAsgBUEyaiEAIAFBMmohBkEAIQMDQAJAIAYgA0EBdGovAAAiBEEHcUUEQCAALQAAQQdxRQ0BCyACQQhqIAggBBAfIAIgByAALwAAEB9BASEEIAIqAggiCiACKgIAIgtcBH8gCiAKWw0DIAsgC1wFIAQLRQ0CIAItAAwgAi0ABEcNAgsgAEECaiEAIANBAWoiA0EJRw0ACyAFQcQAaiEAIAFBxABqIQZBACEDA0ACQCAGIANBAXRqLwAAIgRBB3FFBEAgAC0AAEEHcUUNAQsgAkEIaiAIIAQQHyACIAcgAC8AABAfQQEhBCACKgIIIgogAioCACILXAR/IAogClsNAyALIAtcBSAEC0UNAiACLQAMIAItAARHDQILIABBAmohACADQQFqIgNBCUcNAAsgBUHWAGohACABQdYAaiEGQQAhAwNAAkAgBiADQQF0ai8AACIEQQdxRQRAIAAtAABBB3FFDQELIAJBCGogCCAEEB8gAiAHIAAvAAAQH0EBIQQgAioCCCIKIAIqAgAiC1wEfyAKIApbDQMgCyALXAUgBAtFDQIgAi0ADCACLQAERw0CCyAAQQJqIQAgA0EBaiIDQQlHDQALIAVB6ABqIQAgAUHoAGohBkEAIQMDQAJAIAYgA0EBdGovAAAiBEEHcUUEQCAALQAAQQdxRQ0BCyACQQhqIAggBBAfIAIgByAALwAAEB9BASEEIAIqAggiCiACKgIAIgtcBH8gCiAKWw0DIAsgC1wFIAQLRQ0CIAItAAwgAi0ABEcNAgsgAEECaiEAIANBAWoiA0EDRw0ACyAFQe4AaiEAIAFB7gBqIQlBACEEQQAhAwNAAkAgCSADQQF0ai8AACIGQQdxRQRAIAAtAABBB3FFDQELIAJBCGogCCAGEB8gAiAHIAAvAAAQH0EBIQMgAioCCCIKIAIqAgAiC1wEfyAKIApbDQMgCyALXAUgAwtFDQIgAi0ADCACLQAERw0CCyAAQQJqIQBBASEDIAQhBkEBIQQgBkUNAAsgBUHyAGohACABQfIAaiEJQQAhBEEAIQMDQAJAIAkgA0EBdGovAAAiBkEHcUUEQCAALQAAQQdxRQ0BCyACQQhqIAggBhAfIAIgByAALwAAEB9BASEDIAIqAggiCiACKgIAIgtcBH8gCiAKWw0DIAsgC1wFIAMLRQ0CIAItAAwgAi0ABEcNAgsgAEECaiEAQQEhAyAEIQZBASEEIAZFDQALIAVB9gBqIQAgAUH2AGohCUEAIQRBACEDA0ACQCAJIANBAXRqLwAAIgZBB3FFBEAgAC0AAEEHcUUNAQsgAkEIaiAIIAYQHyACIAcgAC8AABAfQQEhAyACKgIIIgogAioCACILXAR/IAogClsNAyALIAtcBSADC0UNAiACLQAMIAItAARHDQILIABBAmohAEEBIQMgBCEGQQEhBCAGRQ0ACyABLwB6IgBBB3FFBEAgBS0AekEHcUUNAgsgCCAAECAiCiAHIAUvAHoQICILWw0BIAogClsNACALIAtcDQELIAFBFGogBUEUakHoABArGiABQfwAaiAFQfwAahCgAQNAIAEtAAAiAEEEcQ0BIAEgAEEEcjoAACABKAIQIgAEQCABIAARAAALIAFBgICA/gc2ApwBIAEoAuQDIgENAAsLIAJBEGokAAvGAwEEfyMAQaAEayICJAAgACgCBCEBIABBADYCBCABBEAgASABKAIAKAIEEQAACyAAKAIIIQEgAEEANgIIIAEEQCABIAEoAgAoAgQRAAALAkAgACgCACIAKALoAyAAKALsA0YEQCAAKALkAw0BIAAgAkEYaiAAKAL0AxBcIgEpAgA3AgAgACABKAIQNgIQIAAgASkCCDcCCCAAQRRqIAFBFGpB6AAQKxogACABKQKMATcCjAEgACABKQKEATcChAEgACABKQJ8NwJ8IAEoApQBIQQgAUEANgKUASAAKAKUASEDIAAgBDYClAEgAwRAIAMQWwsgAEGYAWogAUGYAWpB0AIQKxogACgC6AMiAwRAIAAgAzYC7AMgAxAjCyAAIAEoAugDNgLoAyAAIAEoAuwDNgLsAyAAIAEoAvADNgLwAyABQQA2AvADIAFCADcC6AMgACABKQL8AzcC/AMgACABKQL0AzcC9AMgACABKAKEBDYChAQgASgClAEhACABQQA2ApQBIAAEQCAAEFsLIAJBoARqJAAPCyACQfAcNgIQIABBBUHYJSACQRBqECwQJAALIAJB5hE2AgAgAEEFQdglIAIQLBAkAAsLAEEMEB4gABCiAQsLAEEMEB5BABCiAQsNACAAKAIALQAIQQFxCwoAIAAoAgAoAhQLGQAgAUH/AXEEQBACAAsgACgCACgCEEEBcQsYACAAKAIAIgAgAC0ACEH+AXEgAXI6AAgLJgAgASAAKAIAIgAoAhRHBEAgACABNgIUIAAgACgCDEEBajYCDAsLkgEBAn8jAEEQayICJAAgACgCACEAIAFDAAAAAGAEQCABIAAqAhhcBEAgACABOAIYIAAgACgCDEEBajYCDAsgAkEQaiQADwsgAkGIFDYCACMAQRBrIgMkACADIAI2AgwCQCAARQRAQbgwQdglIAIQSRoMAQsgAEEAQQVB2CUgAiAAKAIEEQ0AGgsgA0EQaiQAECQACz8AIAFB/wFxRQRAIAIgACgCACIAKAIQIgFBAXFHBEAgACABQX5xIAJyNgIQIAAgACgCDEEBajYCDAsPCxACAAsL4CYjAEGACAuBHk9ubHkgbGVhZiBub2RlcyB3aXRoIGN1c3RvbSBtZWFzdXJlIGZ1bmN0aW9ucyBzaG91bGQgbWFudWFsbHkgbWFyayB0aGVtc2VsdmVzIGFzIGRpcnR5AGlzRGlydHkAbWFya0RpcnR5AGRlc3Ryb3kAc2V0RGlzcGxheQBnZXREaXNwbGF5AHNldEZsZXgALSsgICAwWDB4AC0wWCswWCAwWC0weCsweCAweABzZXRGbGV4R3JvdwBnZXRGbGV4R3JvdwBzZXRPdmVyZmxvdwBnZXRPdmVyZmxvdwBoYXNOZXdMYXlvdXQAY2FsY3VsYXRlTGF5b3V0AGdldENvbXB1dGVkTGF5b3V0AHVuc2lnbmVkIHNob3J0AGdldENoaWxkQ291bnQAdW5zaWduZWQgaW50AHNldEp1c3RpZnlDb250ZW50AGdldEp1c3RpZnlDb250ZW50AGF2YWlsYWJsZUhlaWdodCBpcyBpbmRlZmluaXRlIHNvIGhlaWdodFNpemluZ01vZGUgbXVzdCBiZSBTaXppbmdNb2RlOjpNYXhDb250ZW50AGF2YWlsYWJsZVdpZHRoIGlzIGluZGVmaW5pdGUgc28gd2lkdGhTaXppbmdNb2RlIG11c3QgYmUgU2l6aW5nTW9kZTo6TWF4Q29udGVudABzZXRBbGlnbkNvbnRlbnQAZ2V0QWxpZ25Db250ZW50AGdldFBhcmVudABpbXBsZW1lbnQAc2V0TWF4SGVpZ2h0UGVyY2VudABzZXRIZWlnaHRQZXJjZW50AHNldE1pbkhlaWdodFBlcmNlbnQAc2V0RmxleEJhc2lzUGVyY2VudABzZXRHYXBQZXJjZW50AHNldFBvc2l0aW9uUGVyY2VudABzZXRNYXJnaW5QZXJjZW50AHNldE1heFdpZHRoUGVyY2VudABzZXRXaWR0aFBlcmNlbnQAc2V0TWluV2lkdGhQZXJjZW50AHNldFBhZGRpbmdQZXJjZW50AGhhbmRsZS50eXBlKCkgPT0gU3R5bGVWYWx1ZUhhbmRsZTo6VHlwZTo6UG9pbnQgfHwgaGFuZGxlLnR5cGUoKSA9PSBTdHlsZVZhbHVlSGFuZGxlOjpUeXBlOjpQZXJjZW50AGNyZWF0ZURlZmF1bHQAdW5pdAByaWdodABoZWlnaHQAc2V0TWF4SGVpZ2h0AGdldE1heEhlaWdodABzZXRIZWlnaHQAZ2V0SGVpZ2h0AHNldE1pbkhlaWdodABnZXRNaW5IZWlnaHQAZ2V0Q29tcHV0ZWRIZWlnaHQAZ2V0Q29tcHV0ZWRSaWdodABsZWZ0AGdldENvbXB1dGVkTGVmdAByZXNldABfX2Rlc3RydWN0AGZsb2F0AHVpbnQ2NF90AHVzZVdlYkRlZmF1bHRzAHNldFVzZVdlYkRlZmF1bHRzAHNldEFsaWduSXRlbXMAZ2V0QWxpZ25JdGVtcwBzZXRGbGV4QmFzaXMAZ2V0RmxleEJhc2lzAENhbm5vdCBnZXQgbGF5b3V0IHByb3BlcnRpZXMgb2YgbXVsdGktZWRnZSBzaG9ydGhhbmRzAHNldFBvaW50U2NhbGVGYWN0b3IATWVhc3VyZUNhbGxiYWNrV3JhcHBlcgBEaXJ0aWVkQ2FsbGJhY2tXcmFwcGVyAENhbm5vdCByZXNldCBhIG5vZGUgc3RpbGwgYXR0YWNoZWQgdG8gYSBvd25lcgBzZXRCb3JkZXIAZ2V0Qm9yZGVyAGdldENvbXB1dGVkQm9yZGVyAGdldE51bWJlcgBoYW5kbGUudHlwZSgpID09IFN0eWxlVmFsdWVIYW5kbGU6OlR5cGU6Ok51bWJlcgB1bnNpZ25lZCBjaGFyAHRvcABnZXRDb21wdXRlZFRvcABzZXRGbGV4V3JhcABnZXRGbGV4V3JhcABzZXRHYXAAZ2V0R2FwACVwAHNldEhlaWdodEF1dG8Ac2V0RmxleEJhc2lzQXV0bwBzZXRQb3NpdGlvbkF1dG8Ac2V0TWFyZ2luQXV0bwBzZXRXaWR0aEF1dG8AU2NhbGUgZmFjdG9yIHNob3VsZCBub3QgYmUgbGVzcyB0aGFuIHplcm8Ac2V0QXNwZWN0UmF0aW8AZ2V0QXNwZWN0UmF0aW8Ac2V0UG9zaXRpb24AZ2V0UG9zaXRpb24Abm90aWZ5T25EZXN0cnVjdGlvbgBzZXRGbGV4RGlyZWN0aW9uAGdldEZsZXhEaXJlY3Rpb24Ac2V0RGlyZWN0aW9uAGdldERpcmVjdGlvbgBzZXRNYXJnaW4AZ2V0TWFyZ2luAGdldENvbXB1dGVkTWFyZ2luAG1hcmtMYXlvdXRTZWVuAG5hbgBib3R0b20AZ2V0Q29tcHV0ZWRCb3R0b20AYm9vbABlbXNjcmlwdGVuOjp2YWwAc2V0RmxleFNocmluawBnZXRGbGV4U2hyaW5rAHNldEFsd2F5c0Zvcm1zQ29udGFpbmluZ0Jsb2NrAE1lYXN1cmVDYWxsYmFjawBEaXJ0aWVkQ2FsbGJhY2sAZ2V0TGVuZ3RoAHdpZHRoAHNldE1heFdpZHRoAGdldE1heFdpZHRoAHNldFdpZHRoAGdldFdpZHRoAHNldE1pbldpZHRoAGdldE1pbldpZHRoAGdldENvbXB1dGVkV2lkdGgAcHVzaAAvaG9tZS9ydW5uZXIvd29yay95b2dhL3lvZ2EvamF2YXNjcmlwdC8uLi95b2dhL3N0eWxlL1NtYWxsVmFsdWVCdWZmZXIuaAAvaG9tZS9ydW5uZXIvd29yay95b2dhL3lvZ2EvamF2YXNjcmlwdC8uLi95b2dhL3N0eWxlL1N0eWxlVmFsdWVQb29sLmgAdW5zaWduZWQgbG9uZwBzZXRCb3hTaXppbmcAZ2V0Qm94U2l6aW5nAHN0ZDo6d3N0cmluZwBzdGQ6OnN0cmluZwBzdGQ6OnUxNnN0cmluZwBzdGQ6OnUzMnN0cmluZwBzZXRQYWRkaW5nAGdldFBhZGRpbmcAZ2V0Q29tcHV0ZWRQYWRkaW5nAFRyaWVkIHRvIGNvbnN0cnVjdCBZR05vZGUgd2l0aCBudWxsIGNvbmZpZwBBdHRlbXB0aW5nIHRvIGNvbnN0cnVjdCBOb2RlIHdpdGggbnVsbCBjb25maWcAY3JlYXRlV2l0aENvbmZpZwBpbmYAc2V0QWxpZ25TZWxmAGdldEFsaWduU2VsZgBTaXplAHZhbHVlAFZhbHVlAGNyZWF0ZQBtZWFzdXJlAHNldFBvc2l0aW9uVHlwZQBnZXRQb3NpdGlvblR5cGUAaXNSZWZlcmVuY2VCYXNlbGluZQBzZXRJc1JlZmVyZW5jZUJhc2VsaW5lAGNvcHlTdHlsZQBkb3VibGUATm9kZQBleHRlbmQAaW5zZXJ0Q2hpbGQAZ2V0Q2hpbGQAcmVtb3ZlQ2hpbGQAdm9pZABzZXRFeHBlcmltZW50YWxGZWF0dXJlRW5hYmxlZABpc0V4cGVyaW1lbnRhbEZlYXR1cmVFbmFibGVkAGRpcnRpZWQAQ2Fubm90IHJlc2V0IGEgbm9kZSB3aGljaCBzdGlsbCBoYXMgY2hpbGRyZW4gYXR0YWNoZWQAdW5zZXRNZWFzdXJlRnVuYwB1bnNldERpcnRpZWRGdW5jAHNldEVycmF0YQBnZXRFcnJhdGEATWVhc3VyZSBmdW5jdGlvbiByZXR1cm5lZCBhbiBpbnZhbGlkIGRpbWVuc2lvbiB0byBZb2dhOiBbd2lkdGg9JWYsIGhlaWdodD0lZl0ARXhwZWN0IGN1c3RvbSBiYXNlbGluZSBmdW5jdGlvbiB0byBub3QgcmV0dXJuIE5hTgBOQU4ASU5GAGVtc2NyaXB0ZW46Om1lbW9yeV92aWV3PHNob3J0PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzx1bnNpZ25lZCBzaG9ydD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8aW50PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzx1bnNpZ25lZCBpbnQ+AGVtc2NyaXB0ZW46Om1lbW9yeV92aWV3PGZsb2F0PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzx1aW50OF90PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxpbnQ4X3Q+AGVtc2NyaXB0ZW46Om1lbW9yeV92aWV3PHVpbnQxNl90PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxpbnQxNl90PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzx1aW50MzJfdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8aW50MzJfdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8Y2hhcj4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dW5zaWduZWQgY2hhcj4Ac3RkOjpiYXNpY19zdHJpbmc8dW5zaWduZWQgY2hhcj4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8c2lnbmVk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";
+ if (!ua(H)) {
+ var va = H;
+ H = h.locateFile ? h.locateFile(va, q) : q + va;
+ }
+ function wa() {
+ var a = H;
+ try {
+ if (a == H && w) return new Uint8Array(w);
+ if (ua(a)) try {
+ var b = xa(a.slice(37)), c = new Uint8Array(b.length);
+ for (a = 0; a < b.length; ++a) c[a] = b.charCodeAt(a);
+ var d = c;
+ } catch (f) {
+ throw Error("Converting base64 string to bytes failed.");
+ }
+ else d = void 0;
+ var e = d;
+ if (e) return e;
+ throw "both async and sync fetching of the wasm failed";
+ } catch (f) {
+ x(f);
+ }
+ }
+ __name(wa, "wa");
+ function ya() {
+ return w || "function" != typeof fetch ? Promise.resolve().then(function() {
+ return wa();
+ }) : fetch(H, { credentials: "same-origin" }).then(function(a) {
+ if (!a.ok) throw "failed to load wasm binary file at '" + H + "'";
+ return a.arrayBuffer();
+ }).catch(function() {
+ return wa();
+ });
+ }
+ __name(ya, "ya");
+ function za(a) {
+ for (; 0 < a.length; ) a.shift()(h);
+ }
+ __name(za, "za");
+ function Aa(a) {
+ if (void 0 === a) return "_unknown";
+ a = a.replace(/[^a-zA-Z0-9_]/g, "$");
+ var b = a.charCodeAt(0);
+ return 48 <= b && 57 >= b ? "_" + a : a;
+ }
+ __name(Aa, "Aa");
+ function Ba(a, b) {
+ a = Aa(a);
+ return function() {
+ return b.apply(this, arguments);
+ };
+ }
+ __name(Ba, "Ba");
+ var J = [{}, { value: void 0 }, { value: null }, { value: true }, { value: false }], Ca = [];
+ function Da(a) {
+ var b = Error, c = Ba(a, function(d) {
+ this.name = a;
+ this.message = d;
+ d = Error(d).stack;
+ void 0 !== d && (this.stack = this.toString() + "\n" + d.replace(/^Error(:[^\n]*)?\n/, ""));
+ });
+ c.prototype = Object.create(b.prototype);
+ c.prototype.constructor = c;
+ c.prototype.toString = function() {
+ return void 0 === this.message ? this.name : this.name + ": " + this.message;
+ };
+ return c;
+ }
+ __name(Da, "Da");
+ var K = void 0;
+ function L(a) {
+ throw new K(a);
+ }
+ __name(L, "L");
+ var M = /* @__PURE__ */ __name((a) => {
+ a || L("Cannot use deleted val. handle = " + a);
+ return J[a].value;
+ }, "M"), Ea = /* @__PURE__ */ __name((a) => {
+ switch (a) {
+ case void 0:
+ return 1;
+ case null:
+ return 2;
+ case true:
+ return 3;
+ case false:
+ return 4;
+ default:
+ var b = Ca.length ? Ca.pop() : J.length;
+ J[b] = { ga: 1, value: a };
+ return b;
+ }
+ }, "Ea"), Fa = void 0, Ga = void 0;
+ function N(a) {
+ for (var b = ""; A[a]; ) b += Ga[A[a++]];
+ return b;
+ }
+ __name(N, "N");
+ var O = [];
+ function Ha() {
+ for (; O.length; ) {
+ var a = O.pop();
+ a.M.$ = false;
+ a["delete"]();
+ }
+ }
+ __name(Ha, "Ha");
+ var P = void 0, Q = {};
+ function Ia(a, b) {
+ for (void 0 === b && L("ptr should not be undefined"); a.R; ) b = a.ba(b), a = a.R;
+ return b;
+ }
+ __name(Ia, "Ia");
+ var R = {};
+ function Ja(a) {
+ a = Ka(a);
+ var b = N(a);
+ S(a);
+ return b;
+ }
+ __name(Ja, "Ja");
+ function La(a, b) {
+ var c = R[a];
+ void 0 === c && L(b + " has unknown type " + Ja(a));
+ return c;
+ }
+ __name(La, "La");
+ function Ma() {
+ }
+ __name(Ma, "Ma");
+ var Na = false;
+ function Oa(a) {
+ --a.count.value;
+ 0 === a.count.value && (a.T ? a.U.W(a.T) : a.P.N.W(a.O));
+ }
+ __name(Oa, "Oa");
+ function Pa(a, b, c) {
+ if (b === c) return a;
+ if (void 0 === c.R) return null;
+ a = Pa(a, b, c.R);
+ return null === a ? null : c.na(a);
+ }
+ __name(Pa, "Pa");
+ var Qa = {};
+ function Ra(a, b) {
+ b = Ia(a, b);
+ return Q[b];
+ }
+ __name(Ra, "Ra");
+ var Sa = void 0;
+ function Ta(a) {
+ throw new Sa(a);
+ }
+ __name(Ta, "Ta");
+ function Ua(a, b) {
+ b.P && b.O || Ta("makeClassHandle requires ptr and ptrType");
+ !!b.U !== !!b.T && Ta("Both smartPtrType and smartPtr must be specified");
+ b.count = { value: 1 };
+ return T(Object.create(a, { M: { value: b } }));
+ }
+ __name(Ua, "Ua");
+ function T(a) {
+ if ("undefined" === typeof FinalizationRegistry) return T = /* @__PURE__ */ __name((b) => b, "T"), a;
+ Na = new FinalizationRegistry((b) => {
+ Oa(b.M);
+ });
+ T = /* @__PURE__ */ __name((b) => {
+ var c = b.M;
+ c.T && Na.register(b, { M: c }, b);
+ return b;
+ }, "T");
+ Ma = /* @__PURE__ */ __name((b) => {
+ Na.unregister(b);
+ }, "Ma");
+ return T(a);
+ }
+ __name(T, "T");
+ var Va = {};
+ function Wa(a) {
+ for (; a.length; ) {
+ var b = a.pop();
+ a.pop()(b);
+ }
+ }
+ __name(Wa, "Wa");
+ function Xa(a) {
+ return this.fromWireType(D[a >> 2]);
+ }
+ __name(Xa, "Xa");
+ var U = {}, Ya = {};
+ function V(a, b, c) {
+ function d(k) {
+ k = c(k);
+ k.length !== a.length && Ta("Mismatched type converter count");
+ for (var m = 0; m < a.length; ++m) W(a[m], k[m]);
+ }
+ __name(d, "d");
+ a.forEach(function(k) {
+ Ya[k] = b;
+ });
+ var e = Array(b.length), f = [], g = 0;
+ b.forEach((k, m) => {
+ R.hasOwnProperty(k) ? e[m] = R[k] : (f.push(k), U.hasOwnProperty(k) || (U[k] = []), U[k].push(() => {
+ e[m] = R[k];
+ ++g;
+ g === f.length && d(e);
+ }));
+ });
+ 0 === f.length && d(e);
+ }
+ __name(V, "V");
+ function Za(a) {
+ switch (a) {
+ case 1:
+ return 0;
+ case 2:
+ return 1;
+ case 4:
+ return 2;
+ case 8:
+ return 3;
+ default:
+ throw new TypeError("Unknown type size: " + a);
+ }
+ }
+ __name(Za, "Za");
+ function W(a, b, c = {}) {
+ if (!("argPackAdvance" in b)) throw new TypeError("registerType registeredInstance requires argPackAdvance");
+ var d = b.name;
+ a || L('type "' + d + '" must have a positive integer typeid pointer');
+ if (R.hasOwnProperty(a)) {
+ if (c.ua) return;
+ L("Cannot register type '" + d + "' twice");
+ }
+ R[a] = b;
+ delete Ya[a];
+ U.hasOwnProperty(a) && (b = U[a], delete U[a], b.forEach((e) => e()));
+ }
+ __name(W, "W");
+ function $a(a) {
+ L(a.M.P.N.name + " instance already deleted");
+ }
+ __name($a, "$a");
+ function X() {
+ }
+ __name(X, "X");
+ function ab(a, b, c) {
+ if (void 0 === a[b].S) {
+ var d = a[b];
+ a[b] = function() {
+ a[b].S.hasOwnProperty(arguments.length) || L("Function '" + c + "' called with an invalid number of arguments (" + arguments.length + ") - expects one of (" + a[b].S + ")!");
+ return a[b].S[arguments.length].apply(this, arguments);
+ };
+ a[b].S = [];
+ a[b].S[d.Z] = d;
+ }
+ }
+ __name(ab, "ab");
+ function bb(a, b) {
+ h.hasOwnProperty(a) ? (L("Cannot register public name '" + a + "' twice"), ab(h, a, a), h.hasOwnProperty(void 0) && L("Cannot register multiple overloads of a function with the same number of arguments (undefined)!"), h[a].S[void 0] = b) : h[a] = b;
+ }
+ __name(bb, "bb");
+ function cb(a, b, c, d, e, f, g, k) {
+ this.name = a;
+ this.constructor = b;
+ this.X = c;
+ this.W = d;
+ this.R = e;
+ this.pa = f;
+ this.ba = g;
+ this.na = k;
+ this.ja = [];
+ }
+ __name(cb, "cb");
+ function db(a, b, c) {
+ for (; b !== c; ) b.ba || L("Expected null or instance of " + c.name + ", got an instance of " + b.name), a = b.ba(a), b = b.R;
+ return a;
+ }
+ __name(db, "db");
+ function eb(a, b) {
+ if (null === b) return this.ea && L("null is not a valid " + this.name), 0;
+ b.M || L('Cannot pass "' + fb(b) + '" as a ' + this.name);
+ b.M.O || L("Cannot pass deleted object as a pointer of type " + this.name);
+ return db(b.M.O, b.M.P.N, this.N);
+ }
+ __name(eb, "eb");
+ function gb(a, b) {
+ if (null === b) {
+ this.ea && L("null is not a valid " + this.name);
+ if (this.da) {
+ var c = this.fa();
+ null !== a && a.push(this.W, c);
+ return c;
+ }
+ return 0;
+ }
+ b.M || L('Cannot pass "' + fb(b) + '" as a ' + this.name);
+ b.M.O || L("Cannot pass deleted object as a pointer of type " + this.name);
+ !this.ca && b.M.P.ca && L("Cannot convert argument of type " + (b.M.U ? b.M.U.name : b.M.P.name) + " to parameter type " + this.name);
+ c = db(b.M.O, b.M.P.N, this.N);
+ if (this.da) switch (void 0 === b.M.T && L("Passing raw pointer to smart pointer is illegal"), this.Ba) {
+ case 0:
+ b.M.U === this ? c = b.M.T : L("Cannot convert argument of type " + (b.M.U ? b.M.U.name : b.M.P.name) + " to parameter type " + this.name);
+ break;
+ case 1:
+ c = b.M.T;
+ break;
+ case 2:
+ if (b.M.U === this) c = b.M.T;
+ else {
+ var d = b.clone();
+ c = this.xa(c, Ea(function() {
+ d["delete"]();
+ }));
+ null !== a && a.push(this.W, c);
+ }
+ break;
+ default:
+ L("Unsupporting sharing policy");
+ }
+ return c;
+ }
+ __name(gb, "gb");
+ function hb(a, b) {
+ if (null === b) return this.ea && L("null is not a valid " + this.name), 0;
+ b.M || L('Cannot pass "' + fb(b) + '" as a ' + this.name);
+ b.M.O || L("Cannot pass deleted object as a pointer of type " + this.name);
+ b.M.P.ca && L("Cannot convert argument of type " + b.M.P.name + " to parameter type " + this.name);
+ return db(b.M.O, b.M.P.N, this.N);
+ }
+ __name(hb, "hb");
+ function Y(a, b, c, d) {
+ this.name = a;
+ this.N = b;
+ this.ea = c;
+ this.ca = d;
+ this.da = false;
+ this.W = this.xa = this.fa = this.ka = this.Ba = this.wa = void 0;
+ void 0 !== b.R ? this.toWireType = gb : (this.toWireType = d ? eb : hb, this.V = null);
+ }
+ __name(Y, "Y");
+ function ib(a, b) {
+ h.hasOwnProperty(a) || Ta("Replacing nonexistant public symbol");
+ h[a] = b;
+ h[a].Z = void 0;
+ }
+ __name(ib, "ib");
+ function jb(a, b) {
+ var c = [];
+ return function() {
+ c.length = 0;
+ Object.assign(c, arguments);
+ if (a.includes("j")) {
+ var d = h["dynCall_" + a];
+ d = c && c.length ? d.apply(null, [b].concat(c)) : d.call(null, b);
+ } else d = oa.get(b).apply(null, c);
+ return d;
+ };
+ }
+ __name(jb, "jb");
+ function Z(a, b) {
+ a = N(a);
+ var c = a.includes("j") ? jb(a, b) : oa.get(b);
+ "function" != typeof c && L("unknown function pointer with signature " + a + ": " + b);
+ return c;
+ }
+ __name(Z, "Z");
+ var mb = void 0;
+ function nb(a, b) {
+ function c(f) {
+ e[f] || R[f] || (Ya[f] ? Ya[f].forEach(c) : (d.push(f), e[f] = true));
+ }
+ __name(c, "c");
+ var d = [], e = {};
+ b.forEach(c);
+ throw new mb(a + ": " + d.map(Ja).join([", "]));
+ }
+ __name(nb, "nb");
+ function ob(a, b, c, d, e) {
+ var f = b.length;
+ 2 > f && L("argTypes array size mismatch! Must at least get return value and 'this' types!");
+ var g = null !== b[1] && null !== c, k = false;
+ for (c = 1; c < b.length; ++c) if (null !== b[c] && void 0 === b[c].V) {
+ k = true;
+ break;
+ }
+ var m = "void" !== b[0].name, l = f - 2, n = Array(l), p = [], r = [];
+ return function() {
+ arguments.length !== l && L("function " + a + " called with " + arguments.length + " arguments, expected " + l + " args!");
+ r.length = 0;
+ p.length = g ? 2 : 1;
+ p[0] = e;
+ if (g) {
+ var u = b[1].toWireType(r, this);
+ p[1] = u;
+ }
+ for (var t = 0; t < l; ++t) n[t] = b[t + 2].toWireType(r, arguments[t]), p.push(n[t]);
+ t = d.apply(null, p);
+ if (k) Wa(r);
+ else for (var y = g ? 1 : 2; y < b.length; y++) {
+ var B = 1 === y ? u : n[y - 2];
+ null !== b[y].V && b[y].V(B);
+ }
+ u = m ? b[0].fromWireType(t) : void 0;
+ return u;
+ };
+ }
+ __name(ob, "ob");
+ function pb(a, b) {
+ for (var c = [], d = 0; d < a; d++) c.push(E[b + 4 * d >> 2]);
+ return c;
+ }
+ __name(pb, "pb");
+ function qb(a) {
+ 4 < a && 0 === --J[a].ga && (J[a] = void 0, Ca.push(a));
+ }
+ __name(qb, "qb");
+ function fb(a) {
+ if (null === a) return "null";
+ var b = typeof a;
+ return "object" === b || "array" === b || "function" === b ? a.toString() : "" + a;
+ }
+ __name(fb, "fb");
+ function rb(a, b) {
+ switch (b) {
+ case 2:
+ return function(c) {
+ return this.fromWireType(la[c >> 2]);
+ };
+ case 3:
+ return function(c) {
+ return this.fromWireType(ma[c >> 3]);
+ };
+ default:
+ throw new TypeError("Unknown float type: " + a);
+ }
+ }
+ __name(rb, "rb");
+ function sb(a, b, c) {
+ switch (b) {
+ case 0:
+ return c ? function(d) {
+ return ja[d];
+ } : function(d) {
+ return A[d];
+ };
+ case 1:
+ return c ? function(d) {
+ return C[d >> 1];
+ } : function(d) {
+ return ka[d >> 1];
+ };
+ case 2:
+ return c ? function(d) {
+ return D[d >> 2];
+ } : function(d) {
+ return E[d >> 2];
+ };
+ default:
+ throw new TypeError("Unknown integer type: " + a);
+ }
+ }
+ __name(sb, "sb");
+ function tb(a, b) {
+ for (var c = "", d = 0; !(d >= b / 2); ++d) {
+ var e = C[a + 2 * d >> 1];
+ if (0 == e) break;
+ c += String.fromCharCode(e);
+ }
+ return c;
+ }
+ __name(tb, "tb");
+ function ub(a, b, c) {
+ void 0 === c && (c = 2147483647);
+ if (2 > c) return 0;
+ c -= 2;
+ var d = b;
+ c = c < 2 * a.length ? c / 2 : a.length;
+ for (var e = 0; e < c; ++e) C[b >> 1] = a.charCodeAt(e), b += 2;
+ C[b >> 1] = 0;
+ return b - d;
+ }
+ __name(ub, "ub");
+ function vb(a) {
+ return 2 * a.length;
+ }
+ __name(vb, "vb");
+ function wb(a, b) {
+ for (var c = 0, d = ""; !(c >= b / 4); ) {
+ var e = D[a + 4 * c >> 2];
+ if (0 == e) break;
+ ++c;
+ 65536 <= e ? (e -= 65536, d += String.fromCharCode(55296 | e >> 10, 56320 | e & 1023)) : d += String.fromCharCode(e);
+ }
+ return d;
+ }
+ __name(wb, "wb");
+ function xb(a, b, c) {
+ void 0 === c && (c = 2147483647);
+ if (4 > c) return 0;
+ var d = b;
+ c = d + c - 4;
+ for (var e = 0; e < a.length; ++e) {
+ var f = a.charCodeAt(e);
+ if (55296 <= f && 57343 >= f) {
+ var g = a.charCodeAt(++e);
+ f = 65536 + ((f & 1023) << 10) | g & 1023;
+ }
+ D[b >> 2] = f;
+ b += 4;
+ if (b + 4 > c) break;
+ }
+ D[b >> 2] = 0;
+ return b - d;
+ }
+ __name(xb, "xb");
+ function yb(a) {
+ for (var b = 0, c = 0; c < a.length; ++c) {
+ var d = a.charCodeAt(c);
+ 55296 <= d && 57343 >= d && ++c;
+ b += 4;
+ }
+ return b;
+ }
+ __name(yb, "yb");
+ var zb = {};
+ function Ab(a) {
+ var b = zb[a];
+ return void 0 === b ? N(a) : b;
+ }
+ __name(Ab, "Ab");
+ var Bb = [];
+ function Cb(a) {
+ var b = Bb.length;
+ Bb.push(a);
+ return b;
+ }
+ __name(Cb, "Cb");
+ function Db(a, b) {
+ for (var c = Array(a), d = 0; d < a; ++d) c[d] = La(E[b + 4 * d >> 2], "parameter " + d);
+ return c;
+ }
+ __name(Db, "Db");
+ var Eb = [], Fb = [null, [], []];
+ K = h.BindingError = Da("BindingError");
+ h.count_emval_handles = function() {
+ for (var a = 0, b = 5; b < J.length; ++b) void 0 !== J[b] && ++a;
+ return a;
+ };
+ h.get_first_emval = function() {
+ for (var a = 5; a < J.length; ++a) if (void 0 !== J[a]) return J[a];
+ return null;
+ };
+ Fa = h.PureVirtualError = Da("PureVirtualError");
+ for (var Gb = Array(256), Hb = 0; 256 > Hb; ++Hb) Gb[Hb] = String.fromCharCode(Hb);
+ Ga = Gb;
+ h.getInheritedInstanceCount = function() {
+ return Object.keys(Q).length;
+ };
+ h.getLiveInheritedInstances = function() {
+ var a = [], b;
+ for (b in Q) Q.hasOwnProperty(b) && a.push(Q[b]);
+ return a;
+ };
+ h.flushPendingDeletes = Ha;
+ h.setDelayFunction = function(a) {
+ P = a;
+ O.length && P && P(Ha);
+ };
+ Sa = h.InternalError = Da("InternalError");
+ X.prototype.isAliasOf = function(a) {
+ if (!(this instanceof X && a instanceof X)) return false;
+ var b = this.M.P.N, c = this.M.O, d = a.M.P.N;
+ for (a = a.M.O; b.R; ) c = b.ba(c), b = b.R;
+ for (; d.R; ) a = d.ba(a), d = d.R;
+ return b === d && c === a;
+ };
+ X.prototype.clone = function() {
+ this.M.O || $a(this);
+ if (this.M.aa) return this.M.count.value += 1, this;
+ var a = T, b = Object, c = b.create, d = Object.getPrototypeOf(this), e = this.M;
+ a = a(c.call(b, d, { M: { value: { count: e.count, $: e.$, aa: e.aa, O: e.O, P: e.P, T: e.T, U: e.U } } }));
+ a.M.count.value += 1;
+ a.M.$ = false;
+ return a;
+ };
+ X.prototype["delete"] = function() {
+ this.M.O || $a(this);
+ this.M.$ && !this.M.aa && L("Object already scheduled for deletion");
+ Ma(this);
+ Oa(this.M);
+ this.M.aa || (this.M.T = void 0, this.M.O = void 0);
+ };
+ X.prototype.isDeleted = function() {
+ return !this.M.O;
+ };
+ X.prototype.deleteLater = function() {
+ this.M.O || $a(this);
+ this.M.$ && !this.M.aa && L("Object already scheduled for deletion");
+ O.push(this);
+ 1 === O.length && P && P(Ha);
+ this.M.$ = true;
+ return this;
+ };
+ Y.prototype.qa = function(a) {
+ this.ka && (a = this.ka(a));
+ return a;
+ };
+ Y.prototype.ha = function(a) {
+ this.W && this.W(a);
+ };
+ Y.prototype.argPackAdvance = 8;
+ Y.prototype.readValueFromPointer = Xa;
+ Y.prototype.deleteObject = function(a) {
+ if (null !== a) a["delete"]();
+ };
+ Y.prototype.fromWireType = function(a) {
+ function b() {
+ return this.da ? Ua(this.N.X, { P: this.wa, O: c, U: this, T: a }) : Ua(this.N.X, { P: this, O: a });
+ }
+ __name(b, "b");
+ var c = this.qa(a);
+ if (!c) return this.ha(a), null;
+ var d = Ra(this.N, c);
+ if (void 0 !== d) {
+ if (0 === d.M.count.value) return d.M.O = c, d.M.T = a, d.clone();
+ d = d.clone();
+ this.ha(a);
+ return d;
+ }
+ d = this.N.pa(c);
+ d = Qa[d];
+ if (!d) return b.call(this);
+ d = this.ca ? d.la : d.pointerType;
+ var e = Pa(c, this.N, d.N);
+ return null === e ? b.call(this) : this.da ? Ua(d.N.X, { P: d, O: e, U: this, T: a }) : Ua(d.N.X, { P: d, O: e });
+ };
+ mb = h.UnboundTypeError = Da("UnboundTypeError");
+ var xa = "function" == typeof atob ? atob : function(a) {
+ var b = "", c = 0;
+ a = a.replace(/[^A-Za-z0-9\+\/=]/g, "");
+ do {
+ var d = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a.charAt(c++));
+ var e = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a.charAt(c++));
+ var f = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a.charAt(c++));
+ var g = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a.charAt(c++));
+ d = d << 2 | e >> 4;
+ e = (e & 15) << 4 | f >> 2;
+ var k = (f & 3) << 6 | g;
+ b += String.fromCharCode(d);
+ 64 !== f && (b += String.fromCharCode(e));
+ 64 !== g && (b += String.fromCharCode(k));
+ } while (c < a.length);
+ return b;
+ }, Jb = {
+ l: /* @__PURE__ */ __name(function(a, b, c, d) {
+ x("Assertion failed: " + (a ? z2(A, a) : "") + ", at: " + [b ? b ? z2(A, b) : "" : "unknown filename", c, d ? d ? z2(A, d) : "" : "unknown function"]);
+ }, "l"),
+ q: /* @__PURE__ */ __name(function(a, b, c) {
+ a = N(a);
+ b = La(b, "wrapper");
+ c = M(c);
+ var d = [].slice, e = b.N, f = e.X, g = e.R.X, k = e.R.constructor;
+ a = Ba(a, function() {
+ e.R.ja.forEach(function(l) {
+ if (this[l] === g[l]) throw new Fa("Pure virtual function " + l + " must be implemented in JavaScript");
+ }.bind(this));
+ Object.defineProperty(this, "__parent", { value: f });
+ this.__construct.apply(this, d.call(arguments));
+ });
+ f.__construct = function() {
+ this === f && L("Pass correct 'this' to __construct");
+ var l = k.implement.apply(void 0, [this].concat(d.call(arguments)));
+ Ma(l);
+ var n = l.M;
+ l.notifyOnDestruction();
+ n.aa = true;
+ Object.defineProperties(this, { M: { value: n } });
+ T(this);
+ l = n.O;
+ l = Ia(e, l);
+ Q.hasOwnProperty(l) ? L("Tried to register registered instance: " + l) : Q[l] = this;
+ };
+ f.__destruct = function() {
+ this === f && L("Pass correct 'this' to __destruct");
+ Ma(this);
+ var l = this.M.O;
+ l = Ia(e, l);
+ Q.hasOwnProperty(l) ? delete Q[l] : L("Tried to unregister unregistered instance: " + l);
+ };
+ a.prototype = Object.create(f);
+ for (var m in c) a.prototype[m] = c[m];
+ return Ea(a);
+ }, "q"),
+ j: /* @__PURE__ */ __name(function(a) {
+ var b = Va[a];
+ delete Va[a];
+ var c = b.fa, d = b.W, e = b.ia, f = e.map((g) => g.ta).concat(e.map((g) => g.za));
+ V([a], f, (g) => {
+ var k = {};
+ e.forEach((m, l) => {
+ var n = g[l], p = m.ra, r = m.sa, u = g[l + e.length], t = m.ya, y = m.Aa;
+ k[m.oa] = { read: /* @__PURE__ */ __name((B) => n.fromWireType(p(r, B)), "read"), write: /* @__PURE__ */ __name((B, ba) => {
+ var I = [];
+ t(
+ y,
+ B,
+ u.toWireType(I, ba)
+ );
+ Wa(I);
+ }, "write") };
+ });
+ return [{ name: b.name, fromWireType: /* @__PURE__ */ __name(function(m) {
+ var l = {}, n;
+ for (n in k) l[n] = k[n].read(m);
+ d(m);
+ return l;
+ }, "fromWireType"), toWireType: /* @__PURE__ */ __name(function(m, l) {
+ for (var n in k) if (!(n in l)) throw new TypeError('Missing field: "' + n + '"');
+ var p = c();
+ for (n in k) k[n].write(p, l[n]);
+ null !== m && m.push(d, p);
+ return p;
+ }, "toWireType"), argPackAdvance: 8, readValueFromPointer: Xa, V: d }];
+ });
+ }, "j"),
+ v: /* @__PURE__ */ __name(function() {
+ }, "v"),
+ B: /* @__PURE__ */ __name(function(a, b, c, d, e) {
+ var f = Za(c);
+ b = N(b);
+ W(a, {
+ name: b,
+ fromWireType: /* @__PURE__ */ __name(function(g) {
+ return !!g;
+ }, "fromWireType"),
+ toWireType: /* @__PURE__ */ __name(function(g, k) {
+ return k ? d : e;
+ }, "toWireType"),
+ argPackAdvance: 8,
+ readValueFromPointer: /* @__PURE__ */ __name(function(g) {
+ if (1 === c) var k = ja;
+ else if (2 === c) k = C;
+ else if (4 === c) k = D;
+ else throw new TypeError("Unknown boolean type size: " + b);
+ return this.fromWireType(k[g >> f]);
+ }, "readValueFromPointer"),
+ V: null
+ });
+ }, "B"),
+ f: /* @__PURE__ */ __name(function(a, b, c, d, e, f, g, k, m, l, n, p, r) {
+ n = N(n);
+ f = Z(e, f);
+ k && (k = Z(g, k));
+ l && (l = Z(m, l));
+ r = Z(p, r);
+ var u = Aa(n);
+ bb(u, function() {
+ nb("Cannot construct " + n + " due to unbound types", [d]);
+ });
+ V([a, b, c], d ? [d] : [], function(t) {
+ t = t[0];
+ if (d) {
+ var y = t.N;
+ var B = y.X;
+ } else B = X.prototype;
+ t = Ba(u, function() {
+ if (Object.getPrototypeOf(this) !== ba) throw new K("Use 'new' to construct " + n);
+ if (void 0 === I.Y) throw new K(n + " has no accessible constructor");
+ var kb = I.Y[arguments.length];
+ if (void 0 === kb) throw new K("Tried to invoke ctor of " + n + " with invalid number of parameters (" + arguments.length + ") - expected (" + Object.keys(I.Y).toString() + ") parameters instead!");
+ return kb.apply(this, arguments);
+ });
+ var ba = Object.create(B, { constructor: { value: t } });
+ t.prototype = ba;
+ var I = new cb(n, t, ba, r, y, f, k, l);
+ y = new Y(n, I, true, false);
+ B = new Y(n + "*", I, false, false);
+ var lb = new Y(n + " const*", I, false, true);
+ Qa[a] = {
+ pointerType: B,
+ la: lb
+ };
+ ib(u, t);
+ return [y, B, lb];
+ });
+ }, "f"),
+ d: /* @__PURE__ */ __name(function(a, b, c, d, e, f, g) {
+ var k = pb(c, d);
+ b = N(b);
+ f = Z(e, f);
+ V([], [a], function(m) {
+ function l() {
+ nb("Cannot call " + n + " due to unbound types", k);
+ }
+ __name(l, "l");
+ m = m[0];
+ var n = m.name + "." + b;
+ b.startsWith("@@") && (b = Symbol[b.substring(2)]);
+ var p = m.N.constructor;
+ void 0 === p[b] ? (l.Z = c - 1, p[b] = l) : (ab(p, b, n), p[b].S[c - 1] = l);
+ V([], k, function(r) {
+ r = ob(n, [r[0], null].concat(r.slice(1)), null, f, g);
+ void 0 === p[b].S ? (r.Z = c - 1, p[b] = r) : p[b].S[c - 1] = r;
+ return [];
+ });
+ return [];
+ });
+ }, "d"),
+ p: /* @__PURE__ */ __name(function(a, b, c, d, e, f) {
+ 0 < b || x();
+ var g = pb(
+ b,
+ c
+ );
+ e = Z(d, e);
+ V([], [a], function(k) {
+ k = k[0];
+ var m = "constructor " + k.name;
+ void 0 === k.N.Y && (k.N.Y = []);
+ if (void 0 !== k.N.Y[b - 1]) throw new K("Cannot register multiple constructors with identical number of parameters (" + (b - 1) + ") for class '" + k.name + "'! Overload resolution is currently only performed using the parameter count, not actual type info!");
+ k.N.Y[b - 1] = () => {
+ nb("Cannot construct " + k.name + " due to unbound types", g);
+ };
+ V([], g, function(l) {
+ l.splice(1, 0, null);
+ k.N.Y[b - 1] = ob(m, l, null, e, f);
+ return [];
+ });
+ return [];
+ });
+ }, "p"),
+ a: /* @__PURE__ */ __name(function(a, b, c, d, e, f, g, k) {
+ var m = pb(c, d);
+ b = N(b);
+ f = Z(e, f);
+ V([], [a], function(l) {
+ function n() {
+ nb("Cannot call " + p + " due to unbound types", m);
+ }
+ __name(n, "n");
+ l = l[0];
+ var p = l.name + "." + b;
+ b.startsWith("@@") && (b = Symbol[b.substring(2)]);
+ k && l.N.ja.push(b);
+ var r = l.N.X, u = r[b];
+ void 0 === u || void 0 === u.S && u.className !== l.name && u.Z === c - 2 ? (n.Z = c - 2, n.className = l.name, r[b] = n) : (ab(r, b, p), r[b].S[c - 2] = n);
+ V([], m, function(t) {
+ t = ob(p, t, l, f, g);
+ void 0 === r[b].S ? (t.Z = c - 2, r[b] = t) : r[b].S[c - 2] = t;
+ return [];
+ });
+ return [];
+ });
+ }, "a"),
+ A: /* @__PURE__ */ __name(function(a, b) {
+ b = N(b);
+ W(
+ a,
+ { name: b, fromWireType: /* @__PURE__ */ __name(function(c) {
+ var d = M(c);
+ qb(c);
+ return d;
+ }, "fromWireType"), toWireType: /* @__PURE__ */ __name(function(c, d) {
+ return Ea(d);
+ }, "toWireType"), argPackAdvance: 8, readValueFromPointer: Xa, V: null }
+ );
+ }, "A"),
+ n: /* @__PURE__ */ __name(function(a, b, c) {
+ c = Za(c);
+ b = N(b);
+ W(a, { name: b, fromWireType: /* @__PURE__ */ __name(function(d) {
+ return d;
+ }, "fromWireType"), toWireType: /* @__PURE__ */ __name(function(d, e) {
+ return e;
+ }, "toWireType"), argPackAdvance: 8, readValueFromPointer: rb(b, c), V: null });
+ }, "n"),
+ e: /* @__PURE__ */ __name(function(a, b, c, d, e) {
+ b = N(b);
+ -1 === e && (e = 4294967295);
+ e = Za(c);
+ var f = /* @__PURE__ */ __name((k) => k, "f");
+ if (0 === d) {
+ var g = 32 - 8 * c;
+ f = /* @__PURE__ */ __name((k) => k << g >>> g, "f");
+ }
+ c = b.includes("unsigned") ? function(k, m) {
+ return m >>> 0;
+ } : function(k, m) {
+ return m;
+ };
+ W(a, { name: b, fromWireType: f, toWireType: c, argPackAdvance: 8, readValueFromPointer: sb(b, e, 0 !== d), V: null });
+ }, "e"),
+ b: /* @__PURE__ */ __name(function(a, b, c) {
+ function d(f) {
+ f >>= 2;
+ var g = E;
+ return new e(ia, g[f + 1], g[f]);
+ }
+ __name(d, "d");
+ var e = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array][b];
+ c = N(c);
+ W(a, { name: c, fromWireType: d, argPackAdvance: 8, readValueFromPointer: d }, { ua: true });
+ }, "b"),
+ o: /* @__PURE__ */ __name(function(a, b) {
+ b = N(b);
+ var c = "std::string" === b;
+ W(a, { name: b, fromWireType: /* @__PURE__ */ __name(function(d) {
+ var e = E[d >> 2], f = d + 4;
+ if (c) for (var g = f, k = 0; k <= e; ++k) {
+ var m = f + k;
+ if (k == e || 0 == A[m]) {
+ g = g ? z2(A, g, m - g) : "";
+ if (void 0 === l) var l = g;
+ else l += String.fromCharCode(0), l += g;
+ g = m + 1;
+ }
+ }
+ else {
+ l = Array(e);
+ for (k = 0; k < e; ++k) l[k] = String.fromCharCode(A[f + k]);
+ l = l.join("");
+ }
+ S(d);
+ return l;
+ }, "fromWireType"), toWireType: /* @__PURE__ */ __name(function(d, e) {
+ e instanceof ArrayBuffer && (e = new Uint8Array(e));
+ var f, g = "string" == typeof e;
+ g || e instanceof Uint8Array || e instanceof Uint8ClampedArray || e instanceof Int8Array || L("Cannot pass non-string to std::string");
+ if (c && g) {
+ var k = 0;
+ for (f = 0; f < e.length; ++f) {
+ var m = e.charCodeAt(f);
+ 127 >= m ? k++ : 2047 >= m ? k += 2 : 55296 <= m && 57343 >= m ? (k += 4, ++f) : k += 3;
+ }
+ f = k;
+ } else f = e.length;
+ k = Ib(4 + f + 1);
+ m = k + 4;
+ E[k >> 2] = f;
+ if (c && g) {
+ if (g = m, m = f + 1, f = A, 0 < m) {
+ m = g + m - 1;
+ for (var l = 0; l < e.length; ++l) {
+ var n = e.charCodeAt(l);
+ if (55296 <= n && 57343 >= n) {
+ var p = e.charCodeAt(++l);
+ n = 65536 + ((n & 1023) << 10) | p & 1023;
+ }
+ if (127 >= n) {
+ if (g >= m) break;
+ f[g++] = n;
+ } else {
+ if (2047 >= n) {
+ if (g + 1 >= m) break;
+ f[g++] = 192 | n >> 6;
+ } else {
+ if (65535 >= n) {
+ if (g + 2 >= m) break;
+ f[g++] = 224 | n >> 12;
+ } else {
+ if (g + 3 >= m) break;
+ f[g++] = 240 | n >> 18;
+ f[g++] = 128 | n >> 12 & 63;
+ }
+ f[g++] = 128 | n >> 6 & 63;
+ }
+ f[g++] = 128 | n & 63;
+ }
+ }
+ f[g] = 0;
+ }
+ } else if (g) for (g = 0; g < f; ++g) l = e.charCodeAt(g), 255 < l && (S(m), L("String has UTF-16 code units that do not fit in 8 bits")), A[m + g] = l;
+ else for (g = 0; g < f; ++g) A[m + g] = e[g];
+ null !== d && d.push(S, k);
+ return k;
+ }, "toWireType"), argPackAdvance: 8, readValueFromPointer: Xa, V: /* @__PURE__ */ __name(function(d) {
+ S(d);
+ }, "V") });
+ }, "o"),
+ i: /* @__PURE__ */ __name(function(a, b, c) {
+ c = N(c);
+ if (2 === b) {
+ var d = tb;
+ var e = ub;
+ var f = vb;
+ var g = /* @__PURE__ */ __name(() => ka, "g");
+ var k = 1;
+ } else 4 === b && (d = wb, e = xb, f = yb, g = /* @__PURE__ */ __name(() => E, "g"), k = 2);
+ W(a, { name: c, fromWireType: /* @__PURE__ */ __name(function(m) {
+ for (var l = E[m >> 2], n = g(), p, r = m + 4, u = 0; u <= l; ++u) {
+ var t = m + 4 + u * b;
+ if (u == l || 0 == n[t >> k]) r = d(r, t - r), void 0 === p ? p = r : (p += String.fromCharCode(0), p += r), r = t + b;
+ }
+ S(m);
+ return p;
+ }, "fromWireType"), toWireType: /* @__PURE__ */ __name(function(m, l) {
+ "string" != typeof l && L("Cannot pass non-string to C++ string type " + c);
+ var n = f(l), p = Ib(4 + n + b);
+ E[p >> 2] = n >> k;
+ e(l, p + 4, n + b);
+ null !== m && m.push(S, p);
+ return p;
+ }, "toWireType"), argPackAdvance: 8, readValueFromPointer: Xa, V: /* @__PURE__ */ __name(function(m) {
+ S(m);
+ }, "V") });
+ }, "i"),
+ k: /* @__PURE__ */ __name(function(a, b, c, d, e, f) {
+ Va[a] = { name: N(b), fa: Z(c, d), W: Z(e, f), ia: [] };
+ }, "k"),
+ h: /* @__PURE__ */ __name(function(a, b, c, d, e, f, g, k, m, l) {
+ Va[a].ia.push({ oa: N(b), ta: c, ra: Z(d, e), sa: f, za: g, ya: Z(k, m), Aa: l });
+ }, "h"),
+ C: /* @__PURE__ */ __name(function(a, b) {
+ b = N(b);
+ W(a, {
+ va: true,
+ name: b,
+ argPackAdvance: 0,
+ fromWireType: /* @__PURE__ */ __name(function() {
+ }, "fromWireType"),
+ toWireType: /* @__PURE__ */ __name(function() {
+ }, "toWireType")
+ });
+ }, "C"),
+ s: /* @__PURE__ */ __name(function(a, b, c, d, e) {
+ a = Bb[a];
+ b = M(b);
+ c = Ab(c);
+ var f = [];
+ E[d >> 2] = Ea(f);
+ return a(b, c, f, e);
+ }, "s"),
+ t: /* @__PURE__ */ __name(function(a, b, c, d) {
+ a = Bb[a];
+ b = M(b);
+ c = Ab(c);
+ a(b, c, null, d);
+ }, "t"),
+ g: qb,
+ m: /* @__PURE__ */ __name(function(a, b) {
+ var c = Db(a, b), d = c[0];
+ b = d.name + "_$" + c.slice(1).map(function(g) {
+ return g.name;
+ }).join("_") + "$";
+ var e = Eb[b];
+ if (void 0 !== e) return e;
+ var f = Array(a - 1);
+ e = Cb((g, k, m, l) => {
+ for (var n = 0, p = 0; p < a - 1; ++p) f[p] = c[p + 1].readValueFromPointer(l + n), n += c[p + 1].argPackAdvance;
+ g = g[k].apply(
+ g,
+ f
+ );
+ for (p = 0; p < a - 1; ++p) c[p + 1].ma && c[p + 1].ma(f[p]);
+ if (!d.va) return d.toWireType(m, g);
+ });
+ return Eb[b] = e;
+ }, "m"),
+ D: /* @__PURE__ */ __name(function(a) {
+ 4 < a && (J[a].ga += 1);
+ }, "D"),
+ r: /* @__PURE__ */ __name(function(a) {
+ var b = M(a);
+ Wa(b);
+ qb(a);
+ }, "r"),
+ c: /* @__PURE__ */ __name(function() {
+ x("");
+ }, "c"),
+ x: /* @__PURE__ */ __name(function(a, b, c) {
+ A.copyWithin(a, b, b + c);
+ }, "x"),
+ w: /* @__PURE__ */ __name(function(a) {
+ var b = A.length;
+ a >>>= 0;
+ if (2147483648 < a) return false;
+ for (var c = 1; 4 >= c; c *= 2) {
+ var d = b * (1 + 0.2 / c);
+ d = Math.min(d, a + 100663296);
+ var e = Math;
+ d = Math.max(a, d);
+ e = e.min.call(e, 2147483648, d + (65536 - d % 65536) % 65536);
+ a: {
+ try {
+ fa.grow(e - ia.byteLength + 65535 >>> 16);
+ na();
+ var f = 1;
+ break a;
+ } catch (g) {
+ }
+ f = void 0;
+ }
+ if (f) return true;
+ }
+ return false;
+ }, "w"),
+ z: /* @__PURE__ */ __name(function() {
+ return 52;
+ }, "z"),
+ u: /* @__PURE__ */ __name(function() {
+ return 70;
+ }, "u"),
+ y: /* @__PURE__ */ __name(function(a, b, c, d) {
+ for (var e = 0, f = 0; f < c; f++) {
+ var g = E[b >> 2], k = E[b + 4 >> 2];
+ b += 8;
+ for (var m = 0; m < k; m++) {
+ var l = A[g + m], n = Fb[a];
+ 0 === l || 10 === l ? ((1 === a ? ea : v)(z2(n, 0)), n.length = 0) : n.push(l);
+ }
+ e += k;
+ }
+ E[d >> 2] = e;
+ return 0;
+ }, "y")
+ };
+ (function() {
+ function a(e) {
+ h.asm = e.exports;
+ fa = h.asm.E;
+ na();
+ oa = h.asm.J;
+ qa.unshift(h.asm.F);
+ F--;
+ h.monitorRunDependencies && h.monitorRunDependencies(F);
+ 0 == F && (null !== ta && (clearInterval(ta), ta = null), G && (e = G, G = null, e()));
+ }
+ __name(a, "a");
+ function b(e) {
+ a(e.instance);
+ }
+ __name(b, "b");
+ function c(e) {
+ return ya().then(function(f) {
+ return WebAssembly.instantiate(f, d);
+ }).then(function(f) {
+ return f;
+ }).then(e, function(f) {
+ v("failed to asynchronously prepare wasm: " + f);
+ x(f);
+ });
+ }
+ __name(c, "c");
+ var d = { a: Jb };
+ F++;
+ h.monitorRunDependencies && h.monitorRunDependencies(F);
+ if (h.instantiateWasm) try {
+ return h.instantiateWasm(
+ d,
+ a
+ );
+ } catch (e) {
+ v("Module.instantiateWasm callback failed with error: " + e), ca(e);
+ }
+ (function() {
+ return w || "function" != typeof WebAssembly.instantiateStreaming || ua(H) || "function" != typeof fetch ? c(b) : fetch(H, { credentials: "same-origin" }).then(function(e) {
+ return WebAssembly.instantiateStreaming(e, d).then(b, function(f) {
+ v("wasm streaming compile failed: " + f);
+ v("falling back to ArrayBuffer instantiation");
+ return c(b);
+ });
+ });
+ })().catch(ca);
+ return {};
+ })();
+ h.___wasm_call_ctors = function() {
+ return (h.___wasm_call_ctors = h.asm.F).apply(null, arguments);
+ };
+ var Ka = h.___getTypeName = function() {
+ return (Ka = h.___getTypeName = h.asm.G).apply(null, arguments);
+ };
+ h.__embind_initialize_bindings = function() {
+ return (h.__embind_initialize_bindings = h.asm.H).apply(null, arguments);
+ };
+ var Ib = h._malloc = function() {
+ return (Ib = h._malloc = h.asm.I).apply(null, arguments);
+ }, S = h._free = function() {
+ return (S = h._free = h.asm.K).apply(null, arguments);
+ };
+ h.dynCall_jiji = function() {
+ return (h.dynCall_jiji = h.asm.L).apply(null, arguments);
+ };
+ var Kb;
+ G = /* @__PURE__ */ __name(function Lb() {
+ Kb || Mb();
+ Kb || (G = Lb);
+ }, "Lb");
+ function Mb() {
+ function a() {
+ if (!Kb && (Kb = true, h.calledRun = true, !ha)) {
+ za(qa);
+ aa(h);
+ if (h.onRuntimeInitialized) h.onRuntimeInitialized();
+ if (h.postRun) for ("function" == typeof h.postRun && (h.postRun = [h.postRun]); h.postRun.length; ) {
+ var b = h.postRun.shift();
+ ra.unshift(b);
+ }
+ za(ra);
+ }
+ }
+ __name(a, "a");
+ if (!(0 < F)) {
+ if (h.preRun) for ("function" == typeof h.preRun && (h.preRun = [h.preRun]); h.preRun.length; ) sa();
+ za(pa);
+ 0 < F || (h.setStatus ? (h.setStatus("Running..."), setTimeout(function() {
+ setTimeout(function() {
+ h.setStatus("");
+ }, 1);
+ a();
+ }, 1)) : a());
+ }
+ }
+ __name(Mb, "Mb");
+ if (h.preInit) for ("function" == typeof h.preInit && (h.preInit = [h.preInit]); 0 < h.preInit.length; ) h.preInit.pop()();
+ Mb();
+ return loadYoga2.ready;
+ });
+})();
+var yoga_wasm_base64_esm_default = loadYoga;
+
+// node_modules/yoga-layout/dist/src/wrapAssembly.js
+init_esbuild_shims();
+
+// node_modules/yoga-layout/dist/src/generated/YGEnums.js
+init_esbuild_shims();
+var Align = /* @__PURE__ */ (function(Align2) {
+ Align2[Align2["Auto"] = 0] = "Auto";
+ Align2[Align2["FlexStart"] = 1] = "FlexStart";
+ Align2[Align2["Center"] = 2] = "Center";
+ Align2[Align2["FlexEnd"] = 3] = "FlexEnd";
+ Align2[Align2["Stretch"] = 4] = "Stretch";
+ Align2[Align2["Baseline"] = 5] = "Baseline";
+ Align2[Align2["SpaceBetween"] = 6] = "SpaceBetween";
+ Align2[Align2["SpaceAround"] = 7] = "SpaceAround";
+ Align2[Align2["SpaceEvenly"] = 8] = "SpaceEvenly";
+ return Align2;
+})({});
+var BoxSizing = /* @__PURE__ */ (function(BoxSizing2) {
+ BoxSizing2[BoxSizing2["BorderBox"] = 0] = "BorderBox";
+ BoxSizing2[BoxSizing2["ContentBox"] = 1] = "ContentBox";
+ return BoxSizing2;
+})({});
+var Dimension = /* @__PURE__ */ (function(Dimension2) {
+ Dimension2[Dimension2["Width"] = 0] = "Width";
+ Dimension2[Dimension2["Height"] = 1] = "Height";
+ return Dimension2;
+})({});
+var Direction = /* @__PURE__ */ (function(Direction2) {
+ Direction2[Direction2["Inherit"] = 0] = "Inherit";
+ Direction2[Direction2["LTR"] = 1] = "LTR";
+ Direction2[Direction2["RTL"] = 2] = "RTL";
+ return Direction2;
+})({});
+var Display = /* @__PURE__ */ (function(Display2) {
+ Display2[Display2["Flex"] = 0] = "Flex";
+ Display2[Display2["None"] = 1] = "None";
+ Display2[Display2["Contents"] = 2] = "Contents";
+ return Display2;
+})({});
+var Edge = /* @__PURE__ */ (function(Edge2) {
+ Edge2[Edge2["Left"] = 0] = "Left";
+ Edge2[Edge2["Top"] = 1] = "Top";
+ Edge2[Edge2["Right"] = 2] = "Right";
+ Edge2[Edge2["Bottom"] = 3] = "Bottom";
+ Edge2[Edge2["Start"] = 4] = "Start";
+ Edge2[Edge2["End"] = 5] = "End";
+ Edge2[Edge2["Horizontal"] = 6] = "Horizontal";
+ Edge2[Edge2["Vertical"] = 7] = "Vertical";
+ Edge2[Edge2["All"] = 8] = "All";
+ return Edge2;
+})({});
+var Errata = /* @__PURE__ */ (function(Errata2) {
+ Errata2[Errata2["None"] = 0] = "None";
+ Errata2[Errata2["StretchFlexBasis"] = 1] = "StretchFlexBasis";
+ Errata2[Errata2["AbsolutePositionWithoutInsetsExcludesPadding"] = 2] = "AbsolutePositionWithoutInsetsExcludesPadding";
+ Errata2[Errata2["AbsolutePercentAgainstInnerSize"] = 4] = "AbsolutePercentAgainstInnerSize";
+ Errata2[Errata2["All"] = 2147483647] = "All";
+ Errata2[Errata2["Classic"] = 2147483646] = "Classic";
+ return Errata2;
+})({});
+var ExperimentalFeature = /* @__PURE__ */ (function(ExperimentalFeature2) {
+ ExperimentalFeature2[ExperimentalFeature2["WebFlexBasis"] = 0] = "WebFlexBasis";
+ return ExperimentalFeature2;
+})({});
+var FlexDirection = /* @__PURE__ */ (function(FlexDirection2) {
+ FlexDirection2[FlexDirection2["Column"] = 0] = "Column";
+ FlexDirection2[FlexDirection2["ColumnReverse"] = 1] = "ColumnReverse";
+ FlexDirection2[FlexDirection2["Row"] = 2] = "Row";
+ FlexDirection2[FlexDirection2["RowReverse"] = 3] = "RowReverse";
+ return FlexDirection2;
+})({});
+var Gutter = /* @__PURE__ */ (function(Gutter2) {
+ Gutter2[Gutter2["Column"] = 0] = "Column";
+ Gutter2[Gutter2["Row"] = 1] = "Row";
+ Gutter2[Gutter2["All"] = 2] = "All";
+ return Gutter2;
+})({});
+var Justify = /* @__PURE__ */ (function(Justify2) {
+ Justify2[Justify2["FlexStart"] = 0] = "FlexStart";
+ Justify2[Justify2["Center"] = 1] = "Center";
+ Justify2[Justify2["FlexEnd"] = 2] = "FlexEnd";
+ Justify2[Justify2["SpaceBetween"] = 3] = "SpaceBetween";
+ Justify2[Justify2["SpaceAround"] = 4] = "SpaceAround";
+ Justify2[Justify2["SpaceEvenly"] = 5] = "SpaceEvenly";
+ return Justify2;
+})({});
+var LogLevel = /* @__PURE__ */ (function(LogLevel2) {
+ LogLevel2[LogLevel2["Error"] = 0] = "Error";
+ LogLevel2[LogLevel2["Warn"] = 1] = "Warn";
+ LogLevel2[LogLevel2["Info"] = 2] = "Info";
+ LogLevel2[LogLevel2["Debug"] = 3] = "Debug";
+ LogLevel2[LogLevel2["Verbose"] = 4] = "Verbose";
+ LogLevel2[LogLevel2["Fatal"] = 5] = "Fatal";
+ return LogLevel2;
+})({});
+var MeasureMode = /* @__PURE__ */ (function(MeasureMode2) {
+ MeasureMode2[MeasureMode2["Undefined"] = 0] = "Undefined";
+ MeasureMode2[MeasureMode2["Exactly"] = 1] = "Exactly";
+ MeasureMode2[MeasureMode2["AtMost"] = 2] = "AtMost";
+ return MeasureMode2;
+})({});
+var NodeType = /* @__PURE__ */ (function(NodeType2) {
+ NodeType2[NodeType2["Default"] = 0] = "Default";
+ NodeType2[NodeType2["Text"] = 1] = "Text";
+ return NodeType2;
+})({});
+var Overflow = /* @__PURE__ */ (function(Overflow2) {
+ Overflow2[Overflow2["Visible"] = 0] = "Visible";
+ Overflow2[Overflow2["Hidden"] = 1] = "Hidden";
+ Overflow2[Overflow2["Scroll"] = 2] = "Scroll";
+ return Overflow2;
+})({});
+var PositionType = /* @__PURE__ */ (function(PositionType2) {
+ PositionType2[PositionType2["Static"] = 0] = "Static";
+ PositionType2[PositionType2["Relative"] = 1] = "Relative";
+ PositionType2[PositionType2["Absolute"] = 2] = "Absolute";
+ return PositionType2;
+})({});
+var Unit = /* @__PURE__ */ (function(Unit2) {
+ Unit2[Unit2["Undefined"] = 0] = "Undefined";
+ Unit2[Unit2["Point"] = 1] = "Point";
+ Unit2[Unit2["Percent"] = 2] = "Percent";
+ Unit2[Unit2["Auto"] = 3] = "Auto";
+ return Unit2;
+})({});
+var Wrap = /* @__PURE__ */ (function(Wrap2) {
+ Wrap2[Wrap2["NoWrap"] = 0] = "NoWrap";
+ Wrap2[Wrap2["Wrap"] = 1] = "Wrap";
+ Wrap2[Wrap2["WrapReverse"] = 2] = "WrapReverse";
+ return Wrap2;
+})({});
+var constants = {
+ ALIGN_AUTO: Align.Auto,
+ ALIGN_FLEX_START: Align.FlexStart,
+ ALIGN_CENTER: Align.Center,
+ ALIGN_FLEX_END: Align.FlexEnd,
+ ALIGN_STRETCH: Align.Stretch,
+ ALIGN_BASELINE: Align.Baseline,
+ ALIGN_SPACE_BETWEEN: Align.SpaceBetween,
+ ALIGN_SPACE_AROUND: Align.SpaceAround,
+ ALIGN_SPACE_EVENLY: Align.SpaceEvenly,
+ BOX_SIZING_BORDER_BOX: BoxSizing.BorderBox,
+ BOX_SIZING_CONTENT_BOX: BoxSizing.ContentBox,
+ DIMENSION_WIDTH: Dimension.Width,
+ DIMENSION_HEIGHT: Dimension.Height,
+ DIRECTION_INHERIT: Direction.Inherit,
+ DIRECTION_LTR: Direction.LTR,
+ DIRECTION_RTL: Direction.RTL,
+ DISPLAY_FLEX: Display.Flex,
+ DISPLAY_NONE: Display.None,
+ DISPLAY_CONTENTS: Display.Contents,
+ EDGE_LEFT: Edge.Left,
+ EDGE_TOP: Edge.Top,
+ EDGE_RIGHT: Edge.Right,
+ EDGE_BOTTOM: Edge.Bottom,
+ EDGE_START: Edge.Start,
+ EDGE_END: Edge.End,
+ EDGE_HORIZONTAL: Edge.Horizontal,
+ EDGE_VERTICAL: Edge.Vertical,
+ EDGE_ALL: Edge.All,
+ ERRATA_NONE: Errata.None,
+ ERRATA_STRETCH_FLEX_BASIS: Errata.StretchFlexBasis,
+ ERRATA_ABSOLUTE_POSITION_WITHOUT_INSETS_EXCLUDES_PADDING: Errata.AbsolutePositionWithoutInsetsExcludesPadding,
+ ERRATA_ABSOLUTE_PERCENT_AGAINST_INNER_SIZE: Errata.AbsolutePercentAgainstInnerSize,
+ ERRATA_ALL: Errata.All,
+ ERRATA_CLASSIC: Errata.Classic,
+ EXPERIMENTAL_FEATURE_WEB_FLEX_BASIS: ExperimentalFeature.WebFlexBasis,
+ FLEX_DIRECTION_COLUMN: FlexDirection.Column,
+ FLEX_DIRECTION_COLUMN_REVERSE: FlexDirection.ColumnReverse,
+ FLEX_DIRECTION_ROW: FlexDirection.Row,
+ FLEX_DIRECTION_ROW_REVERSE: FlexDirection.RowReverse,
+ GUTTER_COLUMN: Gutter.Column,
+ GUTTER_ROW: Gutter.Row,
+ GUTTER_ALL: Gutter.All,
+ JUSTIFY_FLEX_START: Justify.FlexStart,
+ JUSTIFY_CENTER: Justify.Center,
+ JUSTIFY_FLEX_END: Justify.FlexEnd,
+ JUSTIFY_SPACE_BETWEEN: Justify.SpaceBetween,
+ JUSTIFY_SPACE_AROUND: Justify.SpaceAround,
+ JUSTIFY_SPACE_EVENLY: Justify.SpaceEvenly,
+ LOG_LEVEL_ERROR: LogLevel.Error,
+ LOG_LEVEL_WARN: LogLevel.Warn,
+ LOG_LEVEL_INFO: LogLevel.Info,
+ LOG_LEVEL_DEBUG: LogLevel.Debug,
+ LOG_LEVEL_VERBOSE: LogLevel.Verbose,
+ LOG_LEVEL_FATAL: LogLevel.Fatal,
+ MEASURE_MODE_UNDEFINED: MeasureMode.Undefined,
+ MEASURE_MODE_EXACTLY: MeasureMode.Exactly,
+ MEASURE_MODE_AT_MOST: MeasureMode.AtMost,
+ NODE_TYPE_DEFAULT: NodeType.Default,
+ NODE_TYPE_TEXT: NodeType.Text,
+ OVERFLOW_VISIBLE: Overflow.Visible,
+ OVERFLOW_HIDDEN: Overflow.Hidden,
+ OVERFLOW_SCROLL: Overflow.Scroll,
+ POSITION_TYPE_STATIC: PositionType.Static,
+ POSITION_TYPE_RELATIVE: PositionType.Relative,
+ POSITION_TYPE_ABSOLUTE: PositionType.Absolute,
+ UNIT_UNDEFINED: Unit.Undefined,
+ UNIT_POINT: Unit.Point,
+ UNIT_PERCENT: Unit.Percent,
+ UNIT_AUTO: Unit.Auto,
+ WRAP_NO_WRAP: Wrap.NoWrap,
+ WRAP_WRAP: Wrap.Wrap,
+ WRAP_WRAP_REVERSE: Wrap.WrapReverse
+};
+var YGEnums_default = constants;
+
+// node_modules/yoga-layout/dist/src/wrapAssembly.js
+function wrapAssembly(lib) {
+ function patch(prototype, name, fn) {
+ const original = prototype[name];
+ prototype[name] = function() {
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
+ args[_key] = arguments[_key];
+ }
+ return fn.call(this, original, ...args);
+ };
+ }
+ __name(patch, "patch");
+ for (const fnName of ["setPosition", "setMargin", "setFlexBasis", "setWidth", "setHeight", "setMinWidth", "setMinHeight", "setMaxWidth", "setMaxHeight", "setPadding", "setGap"]) {
+ const methods = {
+ [Unit.Point]: lib.Node.prototype[fnName],
+ [Unit.Percent]: lib.Node.prototype[`${fnName}Percent`],
+ [Unit.Auto]: lib.Node.prototype[`${fnName}Auto`]
+ };
+ patch(lib.Node.prototype, fnName, function(original) {
+ for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
+ args[_key2 - 1] = arguments[_key2];
+ }
+ const value = args.pop();
+ let unit, asNumber;
+ if (value === "auto") {
+ unit = Unit.Auto;
+ asNumber = void 0;
+ } else if (typeof value === "object") {
+ unit = value.unit;
+ asNumber = value.valueOf();
+ } else {
+ unit = typeof value === "string" && value.endsWith("%") ? Unit.Percent : Unit.Point;
+ asNumber = parseFloat(value);
+ if (value !== void 0 && !Number.isNaN(value) && Number.isNaN(asNumber)) {
+ throw new Error(`Invalid value ${value} for ${fnName}`);
+ }
+ }
+ if (!methods[unit]) throw new Error(`Failed to execute "${fnName}": Unsupported unit '${value}'`);
+ if (asNumber !== void 0) {
+ return methods[unit].call(this, ...args, asNumber);
+ } else {
+ return methods[unit].call(this, ...args);
+ }
+ });
+ }
+ function wrapMeasureFunction(measureFunction) {
+ return lib.MeasureCallback.implement({
+ measure: /* @__PURE__ */ __name(function() {
+ const {
+ width,
+ height
+ } = measureFunction(...arguments);
+ return {
+ width: width ?? NaN,
+ height: height ?? NaN
+ };
+ }, "measure")
+ });
+ }
+ __name(wrapMeasureFunction, "wrapMeasureFunction");
+ patch(lib.Node.prototype, "setMeasureFunc", function(original, measureFunc) {
+ if (measureFunc) {
+ return original.call(this, wrapMeasureFunction(measureFunc));
+ } else {
+ return this.unsetMeasureFunc();
+ }
+ });
+ function wrapDirtiedFunc(dirtiedFunction) {
+ return lib.DirtiedCallback.implement({
+ dirtied: dirtiedFunction
+ });
+ }
+ __name(wrapDirtiedFunc, "wrapDirtiedFunc");
+ patch(lib.Node.prototype, "setDirtiedFunc", function(original, dirtiedFunc) {
+ original.call(this, wrapDirtiedFunc(dirtiedFunc));
+ });
+ patch(lib.Config.prototype, "free", function() {
+ lib.Config.destroy(this);
+ });
+ patch(lib.Node, "create", (_, config2) => {
+ return config2 ? lib.Node.createWithConfig(config2) : lib.Node.createDefault();
+ });
+ patch(lib.Node.prototype, "free", function() {
+ lib.Node.destroy(this);
+ });
+ patch(lib.Node.prototype, "freeRecursive", function() {
+ for (let t = 0, T = this.getChildCount(); t < T; ++t) {
+ this.getChild(0).freeRecursive();
+ }
+ this.free();
+ });
+ patch(lib.Node.prototype, "calculateLayout", function(original) {
+ let width = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : NaN;
+ let height = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : NaN;
+ let direction = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : Direction.LTR;
+ return original.call(this, width, height, direction);
+ });
+ return {
+ Config: lib.Config,
+ Node: lib.Node,
+ ...YGEnums_default
+ };
+}
+__name(wrapAssembly, "wrapAssembly");
+
+// node_modules/yoga-layout/dist/src/index.js
+var Yoga = wrapAssembly(await yoga_wasm_base64_esm_default());
+var src_default = Yoga;
+
+// node_modules/wrap-ansi/index.js
+init_esbuild_shims();
+
+// node_modules/string-width/index.js
+init_esbuild_shims();
+
+// node_modules/strip-ansi/index.js
+init_esbuild_shims();
+
+// node_modules/ansi-regex/index.js
+init_esbuild_shims();
+function ansiRegex({ onlyFirst = false } = {}) {
+ const ST = "(?:\\u0007|\\u001B\\u005C|\\u009C)";
+ const osc = `(?:\\u001B\\][\\s\\S]*?${ST})`;
+ const csi = "[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";
+ const pattern = `${osc}|${csi}`;
+ return new RegExp(pattern, onlyFirst ? void 0 : "g");
+}
+__name(ansiRegex, "ansiRegex");
+
+// node_modules/strip-ansi/index.js
+var regex = ansiRegex();
+function stripAnsi(string4) {
+ if (typeof string4 !== "string") {
+ throw new TypeError(`Expected a \`string\`, got \`${typeof string4}\``);
+ }
+ if (!string4.includes("\x1B") && !string4.includes("\x9B")) {
+ return string4;
+ }
+ return string4.replace(regex, "");
+}
+__name(stripAnsi, "stripAnsi");
+
+// node_modules/get-east-asian-width/index.js
+init_esbuild_shims();
+
+// node_modules/get-east-asian-width/lookup.js
+init_esbuild_shims();
+
+// node_modules/get-east-asian-width/lookup-data.js
+init_esbuild_shims();
+var ambiguousMinimalCodePoint = 161;
+var ambiguousMaximumCodePoint = 1114109;
+var ambiguousRanges = [161, 161, 164, 164, 167, 168, 170, 170, 173, 174, 176, 180, 182, 186, 188, 191, 198, 198, 208, 208, 215, 216, 222, 225, 230, 230, 232, 234, 236, 237, 240, 240, 242, 243, 247, 250, 252, 252, 254, 254, 257, 257, 273, 273, 275, 275, 283, 283, 294, 295, 299, 299, 305, 307, 312, 312, 319, 322, 324, 324, 328, 331, 333, 333, 338, 339, 358, 359, 363, 363, 462, 462, 464, 464, 466, 466, 468, 468, 470, 470, 472, 472, 474, 474, 476, 476, 593, 593, 609, 609, 708, 708, 711, 711, 713, 715, 717, 717, 720, 720, 728, 731, 733, 733, 735, 735, 768, 879, 913, 929, 931, 937, 945, 961, 963, 969, 1025, 1025, 1040, 1103, 1105, 1105, 8208, 8208, 8211, 8214, 8216, 8217, 8220, 8221, 8224, 8226, 8228, 8231, 8240, 8240, 8242, 8243, 8245, 8245, 8251, 8251, 8254, 8254, 8308, 8308, 8319, 8319, 8321, 8324, 8364, 8364, 8451, 8451, 8453, 8453, 8457, 8457, 8467, 8467, 8470, 8470, 8481, 8482, 8486, 8486, 8491, 8491, 8531, 8532, 8539, 8542, 8544, 8555, 8560, 8569, 8585, 8585, 8592, 8601, 8632, 8633, 8658, 8658, 8660, 8660, 8679, 8679, 8704, 8704, 8706, 8707, 8711, 8712, 8715, 8715, 8719, 8719, 8721, 8721, 8725, 8725, 8730, 8730, 8733, 8736, 8739, 8739, 8741, 8741, 8743, 8748, 8750, 8750, 8756, 8759, 8764, 8765, 8776, 8776, 8780, 8780, 8786, 8786, 8800, 8801, 8804, 8807, 8810, 8811, 8814, 8815, 8834, 8835, 8838, 8839, 8853, 8853, 8857, 8857, 8869, 8869, 8895, 8895, 8978, 8978, 9312, 9449, 9451, 9547, 9552, 9587, 9600, 9615, 9618, 9621, 9632, 9633, 9635, 9641, 9650, 9651, 9654, 9655, 9660, 9661, 9664, 9665, 9670, 9672, 9675, 9675, 9678, 9681, 9698, 9701, 9711, 9711, 9733, 9734, 9737, 9737, 9742, 9743, 9756, 9756, 9758, 9758, 9792, 9792, 9794, 9794, 9824, 9825, 9827, 9829, 9831, 9834, 9836, 9837, 9839, 9839, 9886, 9887, 9919, 9919, 9926, 9933, 9935, 9939, 9941, 9953, 9955, 9955, 9960, 9961, 9963, 9969, 9972, 9972, 9974, 9977, 9979, 9980, 9982, 9983, 10045, 10045, 10102, 10111, 11094, 11097, 12872, 12879, 57344, 63743, 65024, 65039, 65533, 65533, 127232, 127242, 127248, 127277, 127280, 127337, 127344, 127373, 127375, 127376, 127387, 127404, 917760, 917999, 983040, 1048573, 1048576, 1114109];
+var fullwidthMinimalCodePoint = 12288;
+var fullwidthMaximumCodePoint = 65510;
+var fullwidthRanges = [12288, 12288, 65281, 65376, 65504, 65510];
+var wideMinimalCodePoint = 4352;
+var wideMaximumCodePoint = 262141;
+var wideRanges = [4352, 4447, 8986, 8987, 9001, 9002, 9193, 9196, 9200, 9200, 9203, 9203, 9725, 9726, 9748, 9749, 9776, 9783, 9800, 9811, 9855, 9855, 9866, 9871, 9875, 9875, 9889, 9889, 9898, 9899, 9917, 9918, 9924, 9925, 9934, 9934, 9940, 9940, 9962, 9962, 9970, 9971, 9973, 9973, 9978, 9978, 9981, 9981, 9989, 9989, 9994, 9995, 10024, 10024, 10060, 10060, 10062, 10062, 10067, 10069, 10071, 10071, 10133, 10135, 10160, 10160, 10175, 10175, 11035, 11036, 11088, 11088, 11093, 11093, 11904, 11929, 11931, 12019, 12032, 12245, 12272, 12287, 12289, 12350, 12353, 12438, 12441, 12543, 12549, 12591, 12593, 12686, 12688, 12773, 12783, 12830, 12832, 12871, 12880, 42124, 42128, 42182, 43360, 43388, 44032, 55203, 63744, 64255, 65040, 65049, 65072, 65106, 65108, 65126, 65128, 65131, 94176, 94180, 94192, 94198, 94208, 101589, 101631, 101662, 101760, 101874, 110576, 110579, 110581, 110587, 110589, 110590, 110592, 110882, 110898, 110898, 110928, 110930, 110933, 110933, 110948, 110951, 110960, 111355, 119552, 119638, 119648, 119670, 126980, 126980, 127183, 127183, 127374, 127374, 127377, 127386, 127488, 127490, 127504, 127547, 127552, 127560, 127568, 127569, 127584, 127589, 127744, 127776, 127789, 127797, 127799, 127868, 127870, 127891, 127904, 127946, 127951, 127955, 127968, 127984, 127988, 127988, 127992, 128062, 128064, 128064, 128066, 128252, 128255, 128317, 128331, 128334, 128336, 128359, 128378, 128378, 128405, 128406, 128420, 128420, 128507, 128591, 128640, 128709, 128716, 128716, 128720, 128722, 128725, 128728, 128732, 128735, 128747, 128748, 128756, 128764, 128992, 129003, 129008, 129008, 129292, 129338, 129340, 129349, 129351, 129535, 129648, 129660, 129664, 129674, 129678, 129734, 129736, 129736, 129741, 129756, 129759, 129770, 129775, 129784, 131072, 196605, 196608, 262141];
+
+// node_modules/get-east-asian-width/utilities.js
+init_esbuild_shims();
+var isInRange = /* @__PURE__ */ __name((ranges, codePoint) => {
+ let low = 0;
+ let high = Math.floor(ranges.length / 2) - 1;
+ while (low <= high) {
+ const mid = Math.floor((low + high) / 2);
+ const i = mid * 2;
+ if (codePoint < ranges[i]) {
+ high = mid - 1;
+ } else if (codePoint > ranges[i + 1]) {
+ low = mid + 1;
+ } else {
+ return true;
+ }
+ }
+ return false;
+}, "isInRange");
+
+// node_modules/get-east-asian-width/lookup.js
+var commonCjkCodePoint = 19968;
+var [wideFastPathStart, wideFastPathEnd] = /* @__PURE__ */ findWideFastPathRange(wideRanges);
+function findWideFastPathRange(ranges) {
+ let fastPathStart = ranges[0];
+ let fastPathEnd = ranges[1];
+ for (let index = 0; index < ranges.length; index += 2) {
+ const start = ranges[index];
+ const end = ranges[index + 1];
+ if (commonCjkCodePoint >= start && commonCjkCodePoint <= end) {
+ return [start, end];
+ }
+ if (end - start > fastPathEnd - fastPathStart) {
+ fastPathStart = start;
+ fastPathEnd = end;
+ }
+ }
+ return [fastPathStart, fastPathEnd];
+}
+__name(findWideFastPathRange, "findWideFastPathRange");
+var isAmbiguous = /* @__PURE__ */ __name((codePoint) => {
+ if (codePoint < ambiguousMinimalCodePoint || codePoint > ambiguousMaximumCodePoint) {
+ return false;
+ }
+ return isInRange(ambiguousRanges, codePoint);
+}, "isAmbiguous");
+var isFullWidth = /* @__PURE__ */ __name((codePoint) => {
+ if (codePoint < fullwidthMinimalCodePoint || codePoint > fullwidthMaximumCodePoint) {
+ return false;
+ }
+ return isInRange(fullwidthRanges, codePoint);
+}, "isFullWidth");
+var isWide = /* @__PURE__ */ __name((codePoint) => {
+ if (codePoint >= wideFastPathStart && codePoint <= wideFastPathEnd) {
+ return true;
+ }
+ if (codePoint < wideMinimalCodePoint || codePoint > wideMaximumCodePoint) {
+ return false;
+ }
+ return isInRange(wideRanges, codePoint);
+}, "isWide");
+
+// node_modules/get-east-asian-width/index.js
+function validate(codePoint) {
+ if (!Number.isSafeInteger(codePoint)) {
+ throw new TypeError(`Expected a code point, got \`${typeof codePoint}\`.`);
+ }
+}
+__name(validate, "validate");
+function eastAsianWidth(codePoint, { ambiguousAsWide = false } = {}) {
+ validate(codePoint);
+ if (isFullWidth(codePoint) || isWide(codePoint) || ambiguousAsWide && isAmbiguous(codePoint)) {
+ return 2;
+ }
+ return 1;
+}
+__name(eastAsianWidth, "eastAsianWidth");
+
+// node_modules/string-width/index.js
+var segmenter = new Intl.Segmenter();
+var zeroWidthClusterRegex = new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Format}|\\p{Mark}|\\p{Surrogate})+$", "v");
+var leadingNonPrintingRegex = new RegExp("^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+", "v");
+var rgiEmojiRegex = new RegExp("^\\p{RGI_Emoji}$", "v");
+var unqualifiedKeycapRegex = /^[\d#*]\u20E3$/;
+var extendedPictographicRegex = new RegExp("\\p{Extended_Pictographic}", "gu");
+function isDoubleWidthNonRgiEmojiSequence(segment) {
+ if (segment.length > 50) {
+ return false;
+ }
+ if (unqualifiedKeycapRegex.test(segment)) {
+ return true;
+ }
+ if (segment.includes("\u200D")) {
+ const pictographics = segment.match(extendedPictographicRegex);
+ return pictographics !== null && pictographics.length >= 2;
+ }
+ return false;
+}
+__name(isDoubleWidthNonRgiEmojiSequence, "isDoubleWidthNonRgiEmojiSequence");
+function baseVisible(segment) {
+ return segment.replace(leadingNonPrintingRegex, "");
+}
+__name(baseVisible, "baseVisible");
+function isZeroWidthCluster(segment) {
+ return zeroWidthClusterRegex.test(segment);
+}
+__name(isZeroWidthCluster, "isZeroWidthCluster");
+function isHangulLeadingJamo(codePoint) {
+ return codePoint >= 4352 && codePoint <= 4447 || codePoint >= 43360 && codePoint <= 43388;
+}
+__name(isHangulLeadingJamo, "isHangulLeadingJamo");
+function isHangulVowelJamo(codePoint) {
+ return codePoint >= 4448 && codePoint <= 4519 || codePoint >= 55216 && codePoint <= 55238;
+}
+__name(isHangulVowelJamo, "isHangulVowelJamo");
+function isHangulTrailingJamo(codePoint) {
+ return codePoint >= 4520 && codePoint <= 4607 || codePoint >= 55243 && codePoint <= 55291;
+}
+__name(isHangulTrailingJamo, "isHangulTrailingJamo");
+function isHangulJamo(codePoint) {
+ return isHangulLeadingJamo(codePoint) || isHangulVowelJamo(codePoint) || isHangulTrailingJamo(codePoint);
+}
+__name(isHangulJamo, "isHangulJamo");
+function hangulClusterWidth(visibleSegment, eastAsianWidthOptions) {
+ const codePoints = [];
+ for (const character of visibleSegment) {
+ if (zeroWidthClusterRegex.test(character)) {
+ continue;
+ }
+ codePoints.push(character.codePointAt(0));
+ }
+ if (codePoints.length === 0) {
+ return void 0;
+ }
+ let width = 0;
+ for (let index = 0; index < codePoints.length; index++) {
+ const codePoint = codePoints[index];
+ if (!isHangulJamo(codePoint)) {
+ if (width === 0) {
+ return void 0;
+ }
+ for (let remaining = index; remaining < codePoints.length; remaining++) {
+ width += eastAsianWidth(codePoints[remaining], eastAsianWidthOptions);
+ }
+ return width;
+ }
+ if (isHangulLeadingJamo(codePoint) && isHangulVowelJamo(codePoints[index + 1])) {
+ width += 2;
+ index += isHangulTrailingJamo(codePoints[index + 2]) ? 2 : 1;
+ continue;
+ }
+ width += eastAsianWidth(codePoint, eastAsianWidthOptions);
+ }
+ return width;
+}
+__name(hangulClusterWidth, "hangulClusterWidth");
+function trailingHalfwidthWidth(visibleSegment, eastAsianWidthOptions) {
+ let extra = 0;
+ let first = true;
+ for (const character of visibleSegment) {
+ if (first) {
+ first = false;
+ continue;
+ }
+ if (character >= "\uFF00" && character <= "\uFFEF") {
+ extra += eastAsianWidth(character.codePointAt(0), eastAsianWidthOptions);
+ }
+ }
+ return extra;
+}
+__name(trailingHalfwidthWidth, "trailingHalfwidthWidth");
+function stringWidth(input, options2 = {}) {
+ if (typeof input !== "string" || input.length === 0) {
+ return 0;
+ }
+ const {
+ ambiguousIsNarrow = true,
+ countAnsiEscapeCodes = false
+ } = options2;
+ let string4 = input;
+ if (!countAnsiEscapeCodes && (string4.includes("\x1B") || string4.includes("\x9B"))) {
+ string4 = stripAnsi(string4);
+ }
+ if (string4.length === 0) {
+ return 0;
+ }
+ if (/^[\u0020-\u007E]*$/.test(string4)) {
+ return string4.length;
+ }
+ let width = 0;
+ const eastAsianWidthOptions = { ambiguousAsWide: !ambiguousIsNarrow };
+ for (const { segment } of segmenter.segment(string4)) {
+ if (isZeroWidthCluster(segment)) {
+ continue;
+ }
+ if (rgiEmojiRegex.test(segment) || isDoubleWidthNonRgiEmojiSequence(segment)) {
+ width += 2;
+ continue;
+ }
+ const visibleSegment = baseVisible(segment);
+ const hangulWidth = hangulClusterWidth(visibleSegment, eastAsianWidthOptions);
+ if (hangulWidth !== void 0) {
+ width += hangulWidth;
+ continue;
+ }
+ const codePoint = visibleSegment.codePointAt(0);
+ width += eastAsianWidth(codePoint, eastAsianWidthOptions);
+ width += trailingHalfwidthWidth(visibleSegment, eastAsianWidthOptions);
+ }
+ return width;
+}
+__name(stringWidth, "stringWidth");
+
+// node_modules/wrap-ansi/node_modules/ansi-styles/index.js
+init_esbuild_shims();
+var ANSI_BACKGROUND_OFFSET = 10;
+var wrapAnsi16 = /* @__PURE__ */ __name((offset = 0) => (code) => `\x1B[${code + offset}m`, "wrapAnsi16");
+var wrapAnsi256 = /* @__PURE__ */ __name((offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`, "wrapAnsi256");
+var wrapAnsi16m = /* @__PURE__ */ __name((offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`, "wrapAnsi16m");
+var 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],
+ overline: [53, 55],
+ 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],
+ gray: [90, 39],
+ // Alias of `blackBright`
+ grey: [90, 39],
+ // Alias of `blackBright`
+ 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],
+ bgGray: [100, 49],
+ // Alias of `bgBlackBright`
+ bgGrey: [100, 49],
+ // Alias of `bgBlackBright`
+ bgRedBright: [101, 49],
+ bgGreenBright: [102, 49],
+ bgYellowBright: [103, 49],
+ bgBlueBright: [104, 49],
+ bgMagentaBright: [105, 49],
+ bgCyanBright: [106, 49],
+ bgWhiteBright: [107, 49]
+ }
+};
+var modifierNames = Object.keys(styles.modifier);
+var foregroundColorNames = Object.keys(styles.color);
+var backgroundColorNames = Object.keys(styles.bgColor);
+var colorNames = [...foregroundColorNames, ...backgroundColorNames];
+function assembleStyles() {
+ const codes = /* @__PURE__ */ new Map();
+ for (const [groupName, group] of Object.entries(styles)) {
+ for (const [styleName, style] of Object.entries(group)) {
+ styles[styleName] = {
+ open: `\x1B[${style[0]}m`,
+ close: `\x1B[${style[1]}m`
+ };
+ group[styleName] = styles[styleName];
+ codes.set(style[0], style[1]);
+ }
+ Object.defineProperty(styles, groupName, {
+ value: group,
+ enumerable: false
+ });
+ }
+ Object.defineProperty(styles, "codes", {
+ value: codes,
+ enumerable: false
+ });
+ styles.color.close = "\x1B[39m";
+ styles.bgColor.close = "\x1B[49m";
+ styles.color.ansi = wrapAnsi16();
+ styles.color.ansi256 = wrapAnsi256();
+ styles.color.ansi16m = wrapAnsi16m();
+ styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
+ styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
+ styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
+ Object.defineProperties(styles, {
+ rgbToAnsi256: {
+ value(red, green, blue) {
+ if (red === green && green === blue) {
+ if (red < 8) {
+ return 16;
+ }
+ if (red > 248) {
+ return 231;
+ }
+ return Math.round((red - 8) / 247 * 24) + 232;
+ }
+ return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
+ },
+ enumerable: false
+ },
+ hexToRgb: {
+ value(hex3) {
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex3.toString(16));
+ if (!matches) {
+ return [0, 0, 0];
+ }
+ let [colorString] = matches;
+ if (colorString.length === 3) {
+ colorString = [...colorString].map((character) => character + character).join("");
+ }
+ const integer2 = Number.parseInt(colorString, 16);
+ return [
+ /* eslint-disable no-bitwise */
+ integer2 >> 16 & 255,
+ integer2 >> 8 & 255,
+ integer2 & 255
+ /* eslint-enable no-bitwise */
+ ];
+ },
+ enumerable: false
+ },
+ hexToAnsi256: {
+ value: /* @__PURE__ */ __name((hex3) => styles.rgbToAnsi256(...styles.hexToRgb(hex3)), "value"),
+ enumerable: false
+ },
+ ansi256ToAnsi: {
+ value(code) {
+ if (code < 8) {
+ return 30 + code;
+ }
+ if (code < 16) {
+ return 90 + (code - 8);
+ }
+ let red;
+ let green;
+ let blue;
+ if (code >= 232) {
+ red = ((code - 232) * 10 + 8) / 255;
+ green = red;
+ blue = red;
+ } else {
+ code -= 16;
+ const remainder = code % 36;
+ red = Math.floor(code / 36) / 5;
+ green = Math.floor(remainder / 6) / 5;
+ blue = remainder % 6 / 5;
+ }
+ const value = Math.max(red, green, blue) * 2;
+ if (value === 0) {
+ return 30;
+ }
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
+ if (value === 2) {
+ result += 60;
+ }
+ return result;
+ },
+ enumerable: false
+ },
+ rgbToAnsi: {
+ value: /* @__PURE__ */ __name((red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)), "value"),
+ enumerable: false
+ },
+ hexToAnsi: {
+ value: /* @__PURE__ */ __name((hex3) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex3)), "value"),
+ enumerable: false
+ }
+ });
+ return styles;
+}
+__name(assembleStyles, "assembleStyles");
+var ansiStyles = assembleStyles();
+var ansi_styles_default = ansiStyles;
+
+// node_modules/wrap-ansi/index.js
+var ANSI_ESCAPE = "\x1B";
+var ANSI_ESCAPE_CSI = "\x9B";
+var ESCAPES = /* @__PURE__ */ new Set([
+ ANSI_ESCAPE,
+ ANSI_ESCAPE_CSI
+]);
+var ANSI_ESCAPE_BELL = "\x07";
+var ANSI_CSI = "[";
+var ANSI_OSC = "]";
+var ANSI_SGR_TERMINATOR = "m";
+var ANSI_SGR_RESET = 0;
+var ANSI_SGR_RESET_FOREGROUND = 39;
+var ANSI_SGR_RESET_BACKGROUND = 49;
+var ANSI_SGR_RESET_UNDERLINE_COLOR = 59;
+var ANSI_SGR_FOREGROUND_EXTENDED = 38;
+var ANSI_SGR_BACKGROUND_EXTENDED = 48;
+var ANSI_SGR_UNDERLINE_COLOR_EXTENDED = 58;
+var ANSI_SGR_COLOR_MODE_256 = 5;
+var ANSI_SGR_COLOR_MODE_RGB = 2;
+var ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;
+var ANSI_ESCAPE_REGEX = new RegExp(`^\\u001B(?:\\${ANSI_CSI}(?[0-9;]*)${ANSI_SGR_TERMINATOR}|${ANSI_ESCAPE_LINK}(?[^\\u0007\\u001B]*)(?:\\u0007|\\u001B\\\\))`);
+var ANSI_ESCAPE_CSI_REGEX = new RegExp(`^\\u009B(?[0-9;]*)${ANSI_SGR_TERMINATOR}`);
+var ANSI_SGR_MODIFIER_CLOSE_CODES = new Set(ansi_styles_default.codes.values());
+ANSI_SGR_MODIFIER_CLOSE_CODES.delete(ANSI_SGR_RESET);
+var segmenter2 = new Intl.Segmenter();
+var getGraphemes = /* @__PURE__ */ __name((string4) => Array.from(segmenter2.segment(string4), ({ segment }) => segment), "getGraphemes");
+var TAB_SIZE = 8;
+var wrapAnsiCode = /* @__PURE__ */ __name((code) => `${ANSI_ESCAPE}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`, "wrapAnsiCode");
+var wrapAnsiHyperlink = /* @__PURE__ */ __name((url2) => `${ANSI_ESCAPE}${ANSI_ESCAPE_LINK}${url2}${ANSI_ESCAPE_BELL}`, "wrapAnsiHyperlink");
+var getSgrTokens = /* @__PURE__ */ __name((sgrParameters) => {
+ const codes = sgrParameters.split(";").map((sgrParameter) => sgrParameter === "" ? ANSI_SGR_RESET : Number.parseInt(sgrParameter, 10));
+ const sgrTokens = [];
+ for (let index = 0; index < codes.length; index++) {
+ const code = codes[index];
+ if (!Number.isFinite(code)) {
+ continue;
+ }
+ if (code === ANSI_SGR_FOREGROUND_EXTENDED || code === ANSI_SGR_BACKGROUND_EXTENDED || code === ANSI_SGR_UNDERLINE_COLOR_EXTENDED) {
+ if (index + 1 >= codes.length) {
+ break;
+ }
+ const mode = codes[index + 1];
+ if (mode === ANSI_SGR_COLOR_MODE_256 && Number.isFinite(codes[index + 2])) {
+ sgrTokens.push([code, mode, codes[index + 2]]);
+ index += 2;
+ continue;
+ }
+ const red = codes[index + 2];
+ const green = codes[index + 3];
+ const blue = codes[index + 4];
+ if (mode === ANSI_SGR_COLOR_MODE_RGB && Number.isFinite(red) && Number.isFinite(green) && Number.isFinite(blue)) {
+ sgrTokens.push([code, mode, red, green, blue]);
+ index += 4;
+ continue;
+ }
+ break;
+ }
+ sgrTokens.push([code]);
+ }
+ return sgrTokens;
+}, "getSgrTokens");
+var removeActiveStyle = /* @__PURE__ */ __name((activeStyles, family) => {
+ const activeStyleIndex = activeStyles.findIndex((activeStyle) => activeStyle.family === family);
+ if (activeStyleIndex !== -1) {
+ activeStyles.splice(activeStyleIndex, 1);
+ }
+}, "removeActiveStyle");
+var upsertActiveStyle = /* @__PURE__ */ __name((activeStyles, nextActiveStyle) => {
+ removeActiveStyle(activeStyles, nextActiveStyle.family);
+ activeStyles.push(nextActiveStyle);
+}, "upsertActiveStyle");
+var removeModifierStylesByClose = /* @__PURE__ */ __name((activeStyles, closeCode) => {
+ for (let index = activeStyles.length - 1; index >= 0; index--) {
+ const activeStyle = activeStyles[index];
+ if (activeStyle.family.startsWith("modifier-") && activeStyle.close === closeCode) {
+ activeStyles.splice(index, 1);
+ }
+ }
+}, "removeModifierStylesByClose");
+var getColorStyle = /* @__PURE__ */ __name((code, sgrToken) => {
+ if (code >= 30 && code <= 37 || code >= 90 && code <= 97 || code === ANSI_SGR_FOREGROUND_EXTENDED && sgrToken.length > 1) {
+ return {
+ family: "foreground",
+ open: sgrToken.join(";"),
+ close: ANSI_SGR_RESET_FOREGROUND
+ };
+ }
+ if (code >= 40 && code <= 47 || code >= 100 && code <= 107 || code === ANSI_SGR_BACKGROUND_EXTENDED && sgrToken.length > 1) {
+ return {
+ family: "background",
+ open: sgrToken.join(";"),
+ close: ANSI_SGR_RESET_BACKGROUND
+ };
+ }
+ if (code === ANSI_SGR_UNDERLINE_COLOR_EXTENDED && sgrToken.length > 1) {
+ return {
+ family: "underlineColor",
+ open: sgrToken.join(";"),
+ close: ANSI_SGR_RESET_UNDERLINE_COLOR
+ };
+ }
+}, "getColorStyle");
+var applySgrResetCode = /* @__PURE__ */ __name((code, activeStyles) => {
+ if (code === ANSI_SGR_RESET) {
+ activeStyles.length = 0;
+ return true;
+ }
+ if (code === ANSI_SGR_RESET_FOREGROUND) {
+ removeActiveStyle(activeStyles, "foreground");
+ return true;
+ }
+ if (code === ANSI_SGR_RESET_BACKGROUND) {
+ removeActiveStyle(activeStyles, "background");
+ return true;
+ }
+ if (code === ANSI_SGR_RESET_UNDERLINE_COLOR) {
+ removeActiveStyle(activeStyles, "underlineColor");
+ return true;
+ }
+ if (ANSI_SGR_MODIFIER_CLOSE_CODES.has(code)) {
+ removeModifierStylesByClose(activeStyles, code);
+ return true;
+ }
+ return false;
+}, "applySgrResetCode");
+var applySgrToken = /* @__PURE__ */ __name((sgrToken, activeStyles) => {
+ const [code] = sgrToken;
+ if (applySgrResetCode(code, activeStyles)) {
+ return;
+ }
+ const colorStyle = getColorStyle(code, sgrToken);
+ if (colorStyle) {
+ upsertActiveStyle(activeStyles, colorStyle);
+ return;
+ }
+ const close = ansi_styles_default.codes.get(code);
+ if (close !== void 0 && close !== ANSI_SGR_RESET) {
+ upsertActiveStyle(activeStyles, {
+ family: `modifier-${code}`,
+ open: sgrToken.join(";"),
+ close
+ });
+ }
+}, "applySgrToken");
+var applySgrParameters = /* @__PURE__ */ __name((sgrParameters, activeStyles) => {
+ for (const sgrToken of getSgrTokens(sgrParameters)) {
+ applySgrToken(sgrToken, activeStyles);
+ }
+}, "applySgrParameters");
+var applySgrResets = /* @__PURE__ */ __name((sgrParameters, activeStyles) => {
+ for (const sgrToken of getSgrTokens(sgrParameters)) {
+ const [code] = sgrToken;
+ applySgrResetCode(code, activeStyles);
+ }
+}, "applySgrResets");
+var applyLeadingSgrResets = /* @__PURE__ */ __name((string4, activeStyles) => {
+ let remainder = string4;
+ while (remainder.length > 0) {
+ if (remainder.startsWith(ANSI_ESCAPE) && remainder[1] !== "\\") {
+ const match = ANSI_ESCAPE_REGEX.exec(remainder);
+ if (!match) {
+ break;
+ }
+ if (match.groups.sgr !== void 0) {
+ applySgrResets(match.groups.sgr, activeStyles);
+ }
+ remainder = remainder.slice(match[0].length);
+ continue;
+ }
+ if (remainder.startsWith(ANSI_ESCAPE_CSI)) {
+ const match = ANSI_ESCAPE_CSI_REGEX.exec(remainder);
+ if (!match || match.groups.sgr === void 0) {
+ break;
+ }
+ applySgrResets(match.groups.sgr, activeStyles);
+ remainder = remainder.slice(match[0].length);
+ continue;
+ }
+ break;
+ }
+}, "applyLeadingSgrResets");
+var getClosingSgrSequence = /* @__PURE__ */ __name((activeStyles) => [...activeStyles].reverse().map((activeStyle) => wrapAnsiCode(activeStyle.close)).join(""), "getClosingSgrSequence");
+var getOpeningSgrSequence = /* @__PURE__ */ __name((activeStyles) => activeStyles.map((activeStyle) => wrapAnsiCode(activeStyle.open)).join(""), "getOpeningSgrSequence");
+var wordLengths = /* @__PURE__ */ __name((string4) => string4.split(" ").map((word) => stringWidth(word)), "wordLengths");
+var wrapWord = /* @__PURE__ */ __name((rows, word, columns) => {
+ const characters = getGraphemes(word);
+ let isInsideEscape = false;
+ let isInsideLinkEscape = false;
+ let visible = stringWidth(stripAnsi(rows.at(-1)));
+ for (const [index, character] of characters.entries()) {
+ const characterLength = stringWidth(character);
+ if (visible + characterLength <= columns) {
+ rows[rows.length - 1] += character;
+ } else {
+ rows.push(character);
+ visible = 0;
+ }
+ if (ESCAPES.has(character) && !(isInsideLinkEscape && character === ANSI_ESCAPE && characters[index + 1] === "\\")) {
+ isInsideEscape = true;
+ const ansiEscapeLinkCandidate = characters.slice(index + 1, index + 1 + ANSI_ESCAPE_LINK.length).join("");
+ isInsideLinkEscape = ansiEscapeLinkCandidate === ANSI_ESCAPE_LINK;
+ }
+ if (isInsideEscape) {
+ if (isInsideLinkEscape) {
+ if (character === ANSI_ESCAPE_BELL || character === "\\" && index > 0 && characters[index - 1] === ANSI_ESCAPE) {
+ isInsideEscape = false;
+ isInsideLinkEscape = false;
+ }
+ } else if (character === ANSI_SGR_TERMINATOR) {
+ isInsideEscape = false;
+ }
+ continue;
+ }
+ visible += characterLength;
+ if (visible === columns && index < characters.length - 1) {
+ rows.push("");
+ visible = 0;
+ }
+ }
+ if (!visible && rows.at(-1).length > 0 && rows.length > 1) {
+ rows[rows.length - 2] += rows.pop();
+ }
+}, "wrapWord");
+var stringVisibleTrimSpacesRight = /* @__PURE__ */ __name((string4) => {
+ const words = string4.split(" ");
+ let last = words.length;
+ while (last > 0) {
+ if (stringWidth(words[last - 1]) > 0) {
+ break;
+ }
+ last--;
+ }
+ if (last === words.length) {
+ return string4;
+ }
+ return words.slice(0, last).join(" ") + words.slice(last).join("");
+}, "stringVisibleTrimSpacesRight");
+var expandTabs = /* @__PURE__ */ __name((line) => {
+ if (!line.includes(" ")) {
+ return line;
+ }
+ const segments = line.split(" ");
+ let visible = 0;
+ let expandedLine = "";
+ for (const [index, segment] of segments.entries()) {
+ expandedLine += segment;
+ visible += stringWidth(segment);
+ if (index < segments.length - 1) {
+ const spaces = TAB_SIZE - visible % TAB_SIZE;
+ expandedLine += " ".repeat(spaces);
+ visible += spaces;
+ }
+ }
+ return expandedLine;
+}, "expandTabs");
+var exec = /* @__PURE__ */ __name((string4, columns, options2 = {}) => {
+ if (options2.trim !== false && string4.trim() === "") {
+ return "";
+ }
+ let returnValue = "";
+ let escapeUrl;
+ const activeStyles = [];
+ const lengths = wordLengths(string4);
+ let rows = [""];
+ for (const [index, word] of string4.split(" ").entries()) {
+ if (options2.trim !== false) {
+ rows[rows.length - 1] = rows.at(-1).trimStart();
+ }
+ let rowLength = stringWidth(rows.at(-1));
+ if (index !== 0) {
+ if (rowLength >= columns && (options2.wordWrap === false || options2.trim === false)) {
+ rows.push("");
+ rowLength = 0;
+ }
+ if (rowLength > 0 || options2.trim === false) {
+ rows[rows.length - 1] += " ";
+ rowLength++;
+ }
+ }
+ if (options2.hard && options2.wordWrap !== false && lengths[index] > columns) {
+ const remainingColumns = columns - rowLength;
+ const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns);
+ const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns);
+ if (breaksStartingNextLine < breaksStartingThisLine) {
+ rows.push("");
+ }
+ wrapWord(rows, word, columns);
+ continue;
+ }
+ if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) {
+ if (options2.wordWrap === false && rowLength < columns) {
+ wrapWord(rows, word, columns);
+ continue;
+ }
+ rows.push("");
+ }
+ if (rowLength + lengths[index] > columns && options2.wordWrap === false) {
+ wrapWord(rows, word, columns);
+ continue;
+ }
+ rows[rows.length - 1] += word;
+ }
+ if (options2.trim !== false) {
+ rows = rows.map((row) => stringVisibleTrimSpacesRight(row));
+ }
+ const preString = rows.join("\n");
+ const pre = getGraphemes(preString);
+ let preStringIndex = 0;
+ for (const [index, character] of pre.entries()) {
+ returnValue += character;
+ if (character === ANSI_ESCAPE && pre[index + 1] !== "\\") {
+ const { groups } = ANSI_ESCAPE_REGEX.exec(preString.slice(preStringIndex)) || { groups: {} };
+ if (groups.sgr !== void 0) {
+ applySgrParameters(groups.sgr, activeStyles);
+ } else if (groups.uri !== void 0) {
+ escapeUrl = groups.uri.length === 0 ? void 0 : groups.uri;
+ }
+ } else if (character === ANSI_ESCAPE_CSI) {
+ const { groups } = ANSI_ESCAPE_CSI_REGEX.exec(preString.slice(preStringIndex)) || { groups: {} };
+ if (groups.sgr !== void 0) {
+ applySgrParameters(groups.sgr, activeStyles);
+ }
+ }
+ if (pre[index + 1] === "\n") {
+ if (escapeUrl) {
+ returnValue += wrapAnsiHyperlink("");
+ }
+ returnValue += getClosingSgrSequence(activeStyles);
+ } else if (character === "\n") {
+ const openingStyles = [...activeStyles];
+ applyLeadingSgrResets(preString.slice(preStringIndex + 1), openingStyles);
+ returnValue += getOpeningSgrSequence(openingStyles);
+ if (escapeUrl) {
+ returnValue += wrapAnsiHyperlink(escapeUrl);
+ }
+ }
+ preStringIndex += character.length;
+ }
+ return returnValue;
+}, "exec");
+function wrapAnsi(string4, columns, options2) {
+ return String(string4).normalize().replaceAll("\r\n", "\n").split("\n").map((line) => exec(expandTabs(line), columns, options2)).join("\n");
+}
+__name(wrapAnsi, "wrapAnsi");
+
+// node_modules/ink/build/utils.js
+init_esbuild_shims();
+
+// node_modules/terminal-size/index.js
+init_esbuild_shims();
+import process3 from "node:process";
+import { execFileSync } from "node:child_process";
+import fs from "node:fs";
+import tty from "node:tty";
+var defaultColumns = 80;
+var defaultRows = 24;
+var exec2 = /* @__PURE__ */ __name((command2, arguments_, { shell, env: env6 } = {}) => execFileSync(command2, arguments_, {
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "ignore"],
+ timeout: 500,
+ shell,
+ env: env6
+}).trim(), "exec");
+var create = /* @__PURE__ */ __name((columns, rows) => ({
+ columns: Number.parseInt(columns, 10),
+ rows: Number.parseInt(rows, 10)
+}), "create");
+var createIfNotDefault = /* @__PURE__ */ __name((maybeColumns, maybeRows) => {
+ const { columns, rows } = create(maybeColumns, maybeRows);
+ if (Number.isNaN(columns) || Number.isNaN(rows)) {
+ return;
+ }
+ if (columns === defaultColumns && rows === defaultRows) {
+ return;
+ }
+ return { columns, rows };
+}, "createIfNotDefault");
+var isForegroundProcess = /* @__PURE__ */ __name(() => {
+ if (process3.platform !== "linux") {
+ return true;
+ }
+ try {
+ const statContents = fs.readFileSync("/proc/self/stat", "utf8");
+ const closingParenthesisIndex = statContents.lastIndexOf(") ");
+ if (closingParenthesisIndex === -1) {
+ return false;
+ }
+ const statFields = statContents.slice(closingParenthesisIndex + 2).trim().split(/\s+/);
+ const processGroupId = Number.parseInt(statFields[2], 10);
+ const foregroundProcessGroupId = Number.parseInt(statFields[5], 10);
+ if (Number.isNaN(processGroupId) || Number.isNaN(foregroundProcessGroupId)) {
+ return false;
+ }
+ if (foregroundProcessGroupId <= 0) {
+ return false;
+ }
+ return processGroupId === foregroundProcessGroupId;
+ } catch {
+ return false;
+ }
+}, "isForegroundProcess");
+function terminalSize() {
+ const { env: env6, stdout, stderr } = process3;
+ if (stdout?.columns && stdout?.rows) {
+ return create(stdout.columns, stdout.rows);
+ }
+ if (stderr?.columns && stderr?.rows) {
+ return create(stderr.columns, stderr.rows);
+ }
+ if (env6.COLUMNS && env6.LINES) {
+ return create(env6.COLUMNS, env6.LINES);
+ }
+ const fallback = {
+ columns: defaultColumns,
+ rows: defaultRows
+ };
+ if (process3.platform === "win32") {
+ return tput() ?? fallback;
+ }
+ if (process3.platform === "darwin") {
+ return devTty() ?? tput() ?? fallback;
+ }
+ return devTty() ?? tput() ?? resize() ?? fallback;
+}
+__name(terminalSize, "terminalSize");
+var devTty = /* @__PURE__ */ __name(() => {
+ try {
+ const flags = process3.platform === "darwin" ? fs.constants.O_EVTONLY | fs.constants.O_NONBLOCK : fs.constants.O_NONBLOCK;
+ const { columns, rows } = tty.WriteStream(fs.openSync("/dev/tty", flags));
+ return { columns, rows };
+ } catch {
+ }
+}, "devTty");
+var tput = /* @__PURE__ */ __name(() => {
+ try {
+ const columns = exec2("tput", ["cols"], { env: { TERM: "dumb", ...process3.env } });
+ const rows = exec2("tput", ["lines"], { env: { TERM: "dumb", ...process3.env } });
+ if (columns && rows) {
+ return createIfNotDefault(columns, rows);
+ }
+ } catch {
+ }
+}, "tput");
+var resize = /* @__PURE__ */ __name(() => {
+ try {
+ if (!isForegroundProcess()) {
+ return;
+ }
+ const size = exec2("resize", ["-u"]).match(/\d+/g);
+ if (size.length === 2) {
+ return createIfNotDefault(size[0], size[1]);
+ }
+ } catch {
+ }
+}, "resize");
+
+// node_modules/ink/build/utils.js
+var getWindowSize = /* @__PURE__ */ __name((stdout) => {
+ const { columns, rows } = stdout;
+ if (columns && rows) {
+ return { columns, rows };
+ }
+ const fallbackSize = terminalSize();
+ return {
+ columns: columns || fallbackSize.columns || 80,
+ rows: rows || fallbackSize.rows || 24
+ };
+}, "getWindowSize");
+
+// node_modules/ink/build/reconciler.js
+init_esbuild_shims();
+var import_react_reconciler = __toESM(require_react_reconciler(), 1);
+var import_constants = __toESM(require_constants(), 1);
+var Scheduler = __toESM(require_scheduler(), 1);
+import process4 from "node:process";
+var import_react = __toESM(require_react(), 1);
+
+// node_modules/ink/build/dom.js
+init_esbuild_shims();
+
+// node_modules/ink/build/measure-text.js
+init_esbuild_shims();
+
+// node_modules/widest-line/index.js
+init_esbuild_shims();
+function widestLine(string4) {
+ let lineWidth = 0;
+ for (const line of string4.split("\n")) {
+ lineWidth = Math.max(lineWidth, stringWidth(line));
+ }
+ return lineWidth;
+}
+__name(widestLine, "widestLine");
+
+// node_modules/ink/build/measure-text.js
+var cache = /* @__PURE__ */ new Map();
+var measureText = /* @__PURE__ */ __name((text) => {
+ if (text.length === 0) {
+ return {
+ width: 0,
+ height: 0
+ };
+ }
+ const cachedDimensions = cache.get(text);
+ if (cachedDimensions) {
+ return cachedDimensions;
+ }
+ const width = widestLine(text);
+ const height = text.split("\n").length;
+ const dimensions = { width, height };
+ cache.set(text, dimensions);
+ return dimensions;
+}, "measureText");
+var measure_text_default = measureText;
+
+// node_modules/ink/build/wrap-text.js
+init_esbuild_shims();
+
+// node_modules/cli-truncate/index.js
+init_esbuild_shims();
+
+// node_modules/slice-ansi/index.js
+init_esbuild_shims();
+
+// node_modules/slice-ansi/tokenize-ansi.js
+init_esbuild_shims();
+
+// node_modules/slice-ansi/node_modules/ansi-styles/index.js
+init_esbuild_shims();
+var ANSI_BACKGROUND_OFFSET2 = 10;
+var wrapAnsi162 = /* @__PURE__ */ __name((offset = 0) => (code) => `\x1B[${code + offset}m`, "wrapAnsi16");
+var wrapAnsi2562 = /* @__PURE__ */ __name((offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`, "wrapAnsi256");
+var wrapAnsi16m2 = /* @__PURE__ */ __name((offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`, "wrapAnsi16m");
+var styles2 = {
+ 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],
+ overline: [53, 55],
+ 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],
+ gray: [90, 39],
+ // Alias of `blackBright`
+ grey: [90, 39],
+ // Alias of `blackBright`
+ 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],
+ bgGray: [100, 49],
+ // Alias of `bgBlackBright`
+ bgGrey: [100, 49],
+ // Alias of `bgBlackBright`
+ bgRedBright: [101, 49],
+ bgGreenBright: [102, 49],
+ bgYellowBright: [103, 49],
+ bgBlueBright: [104, 49],
+ bgMagentaBright: [105, 49],
+ bgCyanBright: [106, 49],
+ bgWhiteBright: [107, 49]
+ }
+};
+var modifierNames2 = Object.keys(styles2.modifier);
+var foregroundColorNames2 = Object.keys(styles2.color);
+var backgroundColorNames2 = Object.keys(styles2.bgColor);
+var colorNames2 = [...foregroundColorNames2, ...backgroundColorNames2];
+function assembleStyles2() {
+ const codes = /* @__PURE__ */ new Map();
+ for (const [groupName, group] of Object.entries(styles2)) {
+ for (const [styleName, style] of Object.entries(group)) {
+ styles2[styleName] = {
+ open: `\x1B[${style[0]}m`,
+ close: `\x1B[${style[1]}m`
+ };
+ group[styleName] = styles2[styleName];
+ codes.set(style[0], style[1]);
+ }
+ Object.defineProperty(styles2, groupName, {
+ value: group,
+ enumerable: false
+ });
+ }
+ Object.defineProperty(styles2, "codes", {
+ value: codes,
+ enumerable: false
+ });
+ styles2.color.close = "\x1B[39m";
+ styles2.bgColor.close = "\x1B[49m";
+ styles2.color.ansi = wrapAnsi162();
+ styles2.color.ansi256 = wrapAnsi2562();
+ styles2.color.ansi16m = wrapAnsi16m2();
+ styles2.bgColor.ansi = wrapAnsi162(ANSI_BACKGROUND_OFFSET2);
+ styles2.bgColor.ansi256 = wrapAnsi2562(ANSI_BACKGROUND_OFFSET2);
+ styles2.bgColor.ansi16m = wrapAnsi16m2(ANSI_BACKGROUND_OFFSET2);
+ Object.defineProperties(styles2, {
+ rgbToAnsi256: {
+ value(red, green, blue) {
+ if (red === green && green === blue) {
+ if (red < 8) {
+ return 16;
+ }
+ if (red > 248) {
+ return 231;
+ }
+ return Math.round((red - 8) / 247 * 24) + 232;
+ }
+ return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
+ },
+ enumerable: false
+ },
+ hexToRgb: {
+ value(hex3) {
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex3.toString(16));
+ if (!matches) {
+ return [0, 0, 0];
+ }
+ let [colorString] = matches;
+ if (colorString.length === 3) {
+ colorString = [...colorString].map((character) => character + character).join("");
+ }
+ const integer2 = Number.parseInt(colorString, 16);
+ return [
+ /* eslint-disable no-bitwise */
+ integer2 >> 16 & 255,
+ integer2 >> 8 & 255,
+ integer2 & 255
+ /* eslint-enable no-bitwise */
+ ];
+ },
+ enumerable: false
+ },
+ hexToAnsi256: {
+ value: /* @__PURE__ */ __name((hex3) => styles2.rgbToAnsi256(...styles2.hexToRgb(hex3)), "value"),
+ enumerable: false
+ },
+ ansi256ToAnsi: {
+ value(code) {
+ if (code < 8) {
+ return 30 + code;
+ }
+ if (code < 16) {
+ return 90 + (code - 8);
+ }
+ let red;
+ let green;
+ let blue;
+ if (code >= 232) {
+ red = ((code - 232) * 10 + 8) / 255;
+ green = red;
+ blue = red;
+ } else {
+ code -= 16;
+ const remainder = code % 36;
+ red = Math.floor(code / 36) / 5;
+ green = Math.floor(remainder / 6) / 5;
+ blue = remainder % 6 / 5;
+ }
+ const value = Math.max(red, green, blue) * 2;
+ if (value === 0) {
+ return 30;
+ }
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
+ if (value === 2) {
+ result += 60;
+ }
+ return result;
+ },
+ enumerable: false
+ },
+ rgbToAnsi: {
+ value: /* @__PURE__ */ __name((red, green, blue) => styles2.ansi256ToAnsi(styles2.rgbToAnsi256(red, green, blue)), "value"),
+ enumerable: false
+ },
+ hexToAnsi: {
+ value: /* @__PURE__ */ __name((hex3) => styles2.ansi256ToAnsi(styles2.hexToAnsi256(hex3)), "value"),
+ enumerable: false
+ }
+ });
+ return styles2;
+}
+__name(assembleStyles2, "assembleStyles");
+var ansiStyles2 = assembleStyles2();
+var ansi_styles_default2 = ansiStyles2;
+
+// node_modules/is-fullwidth-code-point/index.js
+init_esbuild_shims();
+function isFullwidthCodePoint(codePoint) {
+ if (!Number.isInteger(codePoint)) {
+ return false;
+ }
+ return isFullWidth(codePoint) || isWide(codePoint);
+}
+__name(isFullwidthCodePoint, "isFullwidthCodePoint");
+
+// node_modules/slice-ansi/tokenize-ansi.js
+var ESCAPE_CODE_POINT = 27;
+var C1_DCS_CODE_POINT = 144;
+var C1_SOS_CODE_POINT = 152;
+var C1_CSI_CODE_POINT = 155;
+var C1_ST_CODE_POINT = 156;
+var C1_OSC_CODE_POINT = 157;
+var C1_PM_CODE_POINT = 158;
+var C1_APC_CODE_POINT = 159;
+var ESCAPES2 = /* @__PURE__ */ new Set([
+ ESCAPE_CODE_POINT,
+ C1_DCS_CODE_POINT,
+ C1_SOS_CODE_POINT,
+ C1_CSI_CODE_POINT,
+ C1_ST_CODE_POINT,
+ C1_OSC_CODE_POINT,
+ C1_PM_CODE_POINT,
+ C1_APC_CODE_POINT
+]);
+var ESCAPE = "\x1B";
+var ANSI_BELL = "\x07";
+var ANSI_CSI2 = "[";
+var ANSI_OSC2 = "]";
+var ANSI_DCS = "P";
+var ANSI_SOS = "X";
+var ANSI_PM = "^";
+var ANSI_APC = "_";
+var ANSI_SGR_TERMINATOR2 = "m";
+var ANSI_OSC_TERMINATOR = "\\";
+var ANSI_STRING_TERMINATOR = `${ESCAPE}${ANSI_OSC_TERMINATOR}`;
+var C1_OSC = "\x9D";
+var C1_STRING_TERMINATOR = "\x9C";
+var ANSI_HYPERLINK_ESC_PREFIX = `${ESCAPE}${ANSI_OSC2}8;`;
+var ANSI_HYPERLINK_C1_PREFIX = `${C1_OSC}8;`;
+var ANSI_HYPERLINK_ESC_CLOSE = `${ANSI_HYPERLINK_ESC_PREFIX};`;
+var ANSI_HYPERLINK_C1_CLOSE = `${ANSI_HYPERLINK_C1_PREFIX};`;
+var CODE_POINT_0 = "0".codePointAt(0);
+var CODE_POINT_9 = "9".codePointAt(0);
+var CODE_POINT_SEMICOLON = ";".codePointAt(0);
+var CODE_POINT_COLON = ":".codePointAt(0);
+var CODE_POINT_CSI_PARAMETER_START = "0".codePointAt(0);
+var CODE_POINT_CSI_PARAMETER_END = "?".codePointAt(0);
+var CODE_POINT_CSI_INTERMEDIATE_START = " ".codePointAt(0);
+var CODE_POINT_CSI_INTERMEDIATE_END = "/".codePointAt(0);
+var CODE_POINT_CSI_FINAL_START = "@".codePointAt(0);
+var CODE_POINT_CSI_FINAL_END = "~".codePointAt(0);
+var REGIONAL_INDICATOR_SYMBOL_LETTER_A = 127462;
+var REGIONAL_INDICATOR_SYMBOL_LETTER_Z = 127487;
+var SGR_RESET_CODE = 0;
+var SGR_EXTENDED_FOREGROUND_CODE = 38;
+var SGR_DEFAULT_FOREGROUND_CODE = 39;
+var SGR_EXTENDED_BACKGROUND_CODE = 48;
+var SGR_DEFAULT_BACKGROUND_CODE = 49;
+var SGR_COLOR_TYPE_ANSI_256 = 5;
+var SGR_COLOR_TYPE_TRUECOLOR = 2;
+var SGR_ANSI_256_FRAGMENT_LENGTH = 3;
+var SGR_TRUECOLOR_FRAGMENT_LENGTH = 5;
+var SGR_ANSI_256_LAST_PARAMETER_OFFSET = 2;
+var SGR_TRUECOLOR_LAST_PARAMETER_OFFSET = 4;
+var VARIATION_SELECTOR_16_CODE_POINT = 65039;
+var COMBINING_ENCLOSING_KEYCAP_CODE_POINT = 8419;
+var EMOJI_PRESENTATION_GRAPHEME_REGEX = new RegExp("\\p{Emoji_Presentation}", "v");
+var GRAPHEME_SEGMENTER = new Intl.Segmenter(void 0, { granularity: "grapheme" });
+var endCodeNumbers = /* @__PURE__ */ new Set();
+for (const [, end] of ansi_styles_default2.codes) {
+ endCodeNumbers.add(end);
+}
+function isSgrParameterCharacter(codePoint) {
+ return codePoint >= CODE_POINT_0 && codePoint <= CODE_POINT_9 || codePoint === CODE_POINT_SEMICOLON || codePoint === CODE_POINT_COLON;
+}
+__name(isSgrParameterCharacter, "isSgrParameterCharacter");
+function isCsiParameterCharacter(codePoint) {
+ return codePoint >= CODE_POINT_CSI_PARAMETER_START && codePoint <= CODE_POINT_CSI_PARAMETER_END;
+}
+__name(isCsiParameterCharacter, "isCsiParameterCharacter");
+function isCsiIntermediateCharacter(codePoint) {
+ return codePoint >= CODE_POINT_CSI_INTERMEDIATE_START && codePoint <= CODE_POINT_CSI_INTERMEDIATE_END;
+}
+__name(isCsiIntermediateCharacter, "isCsiIntermediateCharacter");
+function isCsiFinalCharacter(codePoint) {
+ return codePoint >= CODE_POINT_CSI_FINAL_START && codePoint <= CODE_POINT_CSI_FINAL_END;
+}
+__name(isCsiFinalCharacter, "isCsiFinalCharacter");
+function isRegionalIndicatorCodePoint(codePoint) {
+ return codePoint >= REGIONAL_INDICATOR_SYMBOL_LETTER_A && codePoint <= REGIONAL_INDICATOR_SYMBOL_LETTER_Z;
+}
+__name(isRegionalIndicatorCodePoint, "isRegionalIndicatorCodePoint");
+function createControlParseResult(code, endIndex) {
+ return {
+ token: {
+ type: "control",
+ code
+ },
+ endIndex
+ };
+}
+__name(createControlParseResult, "createControlParseResult");
+function isEmojiStyleGrapheme(grapheme) {
+ if (EMOJI_PRESENTATION_GRAPHEME_REGEX.test(grapheme)) {
+ return true;
+ }
+ for (const character of grapheme) {
+ const codePoint = character.codePointAt(0);
+ if (codePoint === VARIATION_SELECTOR_16_CODE_POINT || codePoint === COMBINING_ENCLOSING_KEYCAP_CODE_POINT) {
+ return true;
+ }
+ }
+ return false;
+}
+__name(isEmojiStyleGrapheme, "isEmojiStyleGrapheme");
+function getGraphemeWidth(grapheme) {
+ let regionalIndicatorCount = 0;
+ for (const character of grapheme) {
+ const codePoint = character.codePointAt(0);
+ if (isFullwidthCodePoint(codePoint)) {
+ return 2;
+ }
+ if (isRegionalIndicatorCodePoint(codePoint)) {
+ regionalIndicatorCount++;
+ }
+ }
+ if (regionalIndicatorCount >= 1) {
+ return 2;
+ }
+ if (isEmojiStyleGrapheme(grapheme)) {
+ return 2;
+ }
+ return 1;
+}
+__name(getGraphemeWidth, "getGraphemeWidth");
+function getSgrPrefix(code) {
+ if (code.startsWith("\x9B")) {
+ return "\x9B";
+ }
+ return `${ESCAPE}${ANSI_CSI2}`;
+}
+__name(getSgrPrefix, "getSgrPrefix");
+function createSgrCode(prefix, values) {
+ return `${prefix}${values.join(";")}${ANSI_SGR_TERMINATOR2}`;
+}
+__name(createSgrCode, "createSgrCode");
+function getSgrFragments(code) {
+ const fragments = [];
+ const sgrPrefix = getSgrPrefix(code);
+ let parameterString;
+ if (code.startsWith(`${ESCAPE}${ANSI_CSI2}`)) {
+ parameterString = code.slice(2, -1);
+ } else if (code.startsWith("\x9B")) {
+ parameterString = code.slice(1, -1);
+ } else {
+ return fragments;
+ }
+ const rawCodes = parameterString.length === 0 ? [String(SGR_RESET_CODE)] : parameterString.split(";");
+ let index = 0;
+ while (index < rawCodes.length) {
+ const codeNumber = Number.parseInt(rawCodes[index], 10);
+ if (Number.isNaN(codeNumber)) {
+ index++;
+ continue;
+ }
+ if (codeNumber === SGR_RESET_CODE) {
+ fragments.push({ type: "reset" });
+ index++;
+ continue;
+ }
+ if (codeNumber === SGR_EXTENDED_FOREGROUND_CODE || codeNumber === SGR_EXTENDED_BACKGROUND_CODE) {
+ const colorType = Number.parseInt(rawCodes[index + 1], 10);
+ if (colorType === SGR_COLOR_TYPE_ANSI_256 && index + SGR_ANSI_256_LAST_PARAMETER_OFFSET < rawCodes.length) {
+ const openCode3 = createSgrCode(sgrPrefix, rawCodes.slice(index, index + SGR_ANSI_256_FRAGMENT_LENGTH));
+ fragments.push({
+ type: "start",
+ code: openCode3,
+ endCode: ansi_styles_default2.color.ansi(codeNumber === SGR_EXTENDED_FOREGROUND_CODE ? SGR_DEFAULT_FOREGROUND_CODE : SGR_DEFAULT_BACKGROUND_CODE)
+ });
+ index += SGR_ANSI_256_FRAGMENT_LENGTH;
+ continue;
+ }
+ if (colorType === SGR_COLOR_TYPE_TRUECOLOR && index + SGR_TRUECOLOR_LAST_PARAMETER_OFFSET < rawCodes.length) {
+ const openCode3 = createSgrCode(sgrPrefix, rawCodes.slice(index, index + SGR_TRUECOLOR_FRAGMENT_LENGTH));
+ fragments.push({
+ type: "start",
+ code: openCode3,
+ endCode: ansi_styles_default2.color.ansi(codeNumber === SGR_EXTENDED_FOREGROUND_CODE ? SGR_DEFAULT_FOREGROUND_CODE : SGR_DEFAULT_BACKGROUND_CODE)
+ });
+ index += SGR_TRUECOLOR_FRAGMENT_LENGTH;
+ continue;
+ }
+ const openCode2 = createSgrCode(sgrPrefix, [rawCodes[index]]);
+ fragments.push({
+ type: "start",
+ code: openCode2,
+ endCode: ansi_styles_default2.color.ansi(codeNumber === SGR_EXTENDED_FOREGROUND_CODE ? SGR_DEFAULT_FOREGROUND_CODE : SGR_DEFAULT_BACKGROUND_CODE)
+ });
+ index++;
+ continue;
+ }
+ if (endCodeNumbers.has(codeNumber)) {
+ fragments.push({
+ type: "end",
+ endCode: ansi_styles_default2.color.ansi(codeNumber)
+ });
+ index++;
+ continue;
+ }
+ const mappedEndCode = ansi_styles_default2.codes.get(codeNumber);
+ if (mappedEndCode !== void 0) {
+ const openCode2 = createSgrCode(sgrPrefix, [rawCodes[index]]);
+ fragments.push({
+ type: "start",
+ code: openCode2,
+ endCode: ansi_styles_default2.color.ansi(mappedEndCode)
+ });
+ index++;
+ continue;
+ }
+ const openCode = createSgrCode(sgrPrefix, [rawCodes[index]]);
+ fragments.push({
+ type: "start",
+ code: openCode,
+ endCode: ansi_styles_default2.reset.open
+ });
+ index++;
+ }
+ if (fragments.length === 0) {
+ fragments.push({ type: "reset" });
+ }
+ return fragments;
+}
+__name(getSgrFragments, "getSgrFragments");
+function parseCsiCode(string4, index) {
+ const escapeCodePoint = string4.codePointAt(index);
+ let sequenceStartIndex;
+ if (escapeCodePoint === ESCAPE_CODE_POINT) {
+ if (string4[index + 1] !== ANSI_CSI2) {
+ return;
+ }
+ sequenceStartIndex = index + 2;
+ } else if (escapeCodePoint === C1_CSI_CODE_POINT) {
+ sequenceStartIndex = index + 1;
+ } else {
+ return;
+ }
+ let hasCanonicalSgrParameters = true;
+ for (let sequenceIndex = sequenceStartIndex; sequenceIndex < string4.length; sequenceIndex++) {
+ const codePoint = string4.codePointAt(sequenceIndex);
+ if (isCsiFinalCharacter(codePoint)) {
+ const code = string4.slice(index, sequenceIndex + 1);
+ if (string4[sequenceIndex] !== ANSI_SGR_TERMINATOR2 || !hasCanonicalSgrParameters) {
+ return createControlParseResult(code, sequenceIndex + 1);
+ }
+ return {
+ token: {
+ type: "sgr",
+ code,
+ fragments: getSgrFragments(code)
+ },
+ endIndex: sequenceIndex + 1
+ };
+ }
+ if (isCsiParameterCharacter(codePoint)) {
+ if (!isSgrParameterCharacter(codePoint)) {
+ hasCanonicalSgrParameters = false;
+ }
+ continue;
+ }
+ if (isCsiIntermediateCharacter(codePoint)) {
+ hasCanonicalSgrParameters = false;
+ continue;
+ }
+ const endIndex = sequenceIndex;
+ return createControlParseResult(string4.slice(index, endIndex), endIndex);
+ }
+ return createControlParseResult(string4.slice(index), string4.length);
+}
+__name(parseCsiCode, "parseCsiCode");
+function parseHyperlinkCode(string4, index) {
+ let hyperlinkPrefix;
+ let hyperlinkClose;
+ const codePoint = string4.codePointAt(index);
+ if (codePoint === ESCAPE_CODE_POINT && string4.startsWith(ANSI_HYPERLINK_ESC_PREFIX, index)) {
+ hyperlinkPrefix = ANSI_HYPERLINK_ESC_PREFIX;
+ hyperlinkClose = ANSI_HYPERLINK_ESC_CLOSE;
+ } else if (codePoint === C1_OSC_CODE_POINT && string4.startsWith(ANSI_HYPERLINK_C1_PREFIX, index)) {
+ hyperlinkPrefix = ANSI_HYPERLINK_C1_PREFIX;
+ hyperlinkClose = ANSI_HYPERLINK_C1_CLOSE;
+ } else {
+ return;
+ }
+ const uriStart = string4.indexOf(";", index + hyperlinkPrefix.length);
+ if (uriStart === -1) {
+ return createControlParseResult(string4.slice(index), string4.length);
+ }
+ for (let sequenceIndex = uriStart + 1; sequenceIndex < string4.length; sequenceIndex++) {
+ const character = string4[sequenceIndex];
+ if (character === ANSI_BELL) {
+ const code = string4.slice(index, sequenceIndex + 1);
+ const action = sequenceIndex === uriStart + 1 ? "close" : "open";
+ return {
+ token: {
+ type: "hyperlink",
+ code,
+ action,
+ closePrefix: hyperlinkClose,
+ terminator: ANSI_BELL
+ },
+ endIndex: sequenceIndex + 1
+ };
+ }
+ if (character === ESCAPE && string4[sequenceIndex + 1] === ANSI_OSC_TERMINATOR) {
+ const code = string4.slice(index, sequenceIndex + 2);
+ const action = sequenceIndex === uriStart + 1 ? "close" : "open";
+ return {
+ token: {
+ type: "hyperlink",
+ code,
+ action,
+ closePrefix: hyperlinkClose,
+ terminator: ANSI_STRING_TERMINATOR
+ },
+ endIndex: sequenceIndex + 2
+ };
+ }
+ if (character === C1_STRING_TERMINATOR) {
+ const code = string4.slice(index, sequenceIndex + 1);
+ const action = sequenceIndex === uriStart + 1 ? "close" : "open";
+ return {
+ token: {
+ type: "hyperlink",
+ code,
+ action,
+ closePrefix: hyperlinkClose,
+ terminator: C1_STRING_TERMINATOR
+ },
+ endIndex: sequenceIndex + 1
+ };
+ }
+ }
+ return createControlParseResult(string4.slice(index), string4.length);
+}
+__name(parseHyperlinkCode, "parseHyperlinkCode");
+function parseControlStringCode(string4, index) {
+ const codePoint = string4.codePointAt(index);
+ let sequenceStartIndex;
+ let supportsBellTerminator = false;
+ switch (codePoint) {
+ case ESCAPE_CODE_POINT: {
+ const command2 = string4[index + 1];
+ switch (command2) {
+ case ANSI_OSC2: {
+ sequenceStartIndex = index + 2;
+ supportsBellTerminator = true;
+ break;
+ }
+ case ANSI_DCS:
+ case ANSI_SOS:
+ case ANSI_PM:
+ case ANSI_APC: {
+ sequenceStartIndex = index + 2;
+ break;
+ }
+ case ANSI_OSC_TERMINATOR: {
+ return createControlParseResult(ANSI_STRING_TERMINATOR, index + 2);
+ }
+ default: {
+ return;
+ }
+ }
+ break;
+ }
+ case C1_OSC_CODE_POINT: {
+ sequenceStartIndex = index + 1;
+ supportsBellTerminator = true;
+ break;
+ }
+ case C1_DCS_CODE_POINT:
+ case C1_SOS_CODE_POINT:
+ case C1_PM_CODE_POINT:
+ case C1_APC_CODE_POINT: {
+ sequenceStartIndex = index + 1;
+ break;
+ }
+ case C1_ST_CODE_POINT: {
+ return createControlParseResult(C1_STRING_TERMINATOR, index + 1);
+ }
+ default: {
+ return;
+ }
+ }
+ for (let sequenceIndex = sequenceStartIndex; sequenceIndex < string4.length; sequenceIndex++) {
+ if (supportsBellTerminator && string4[sequenceIndex] === ANSI_BELL) {
+ return createControlParseResult(string4.slice(index, sequenceIndex + 1), sequenceIndex + 1);
+ }
+ if (string4[sequenceIndex] === ESCAPE && string4[sequenceIndex + 1] === ANSI_OSC_TERMINATOR) {
+ return createControlParseResult(string4.slice(index, sequenceIndex + 2), sequenceIndex + 2);
+ }
+ if (string4[sequenceIndex] === C1_STRING_TERMINATOR) {
+ return createControlParseResult(string4.slice(index, sequenceIndex + 1), sequenceIndex + 1);
+ }
+ }
+ return createControlParseResult(string4.slice(index), string4.length);
+}
+__name(parseControlStringCode, "parseControlStringCode");
+function parseAnsiCode(string4, index) {
+ const codePoint = string4.codePointAt(index);
+ if (codePoint === ESCAPE_CODE_POINT || codePoint === C1_OSC_CODE_POINT) {
+ const hyperlinkCode = parseHyperlinkCode(string4, index);
+ if (hyperlinkCode) {
+ return hyperlinkCode;
+ }
+ }
+ const controlStringCode = parseControlStringCode(string4, index);
+ if (controlStringCode) {
+ return controlStringCode;
+ }
+ return parseCsiCode(string4, index);
+}
+__name(parseAnsiCode, "parseAnsiCode");
+function appendTrailingAnsiTokens(string4, index, tokens) {
+ while (index < string4.length) {
+ const nextCodePoint = string4.codePointAt(index);
+ if (!ESCAPES2.has(nextCodePoint)) {
+ break;
+ }
+ const escapeCode = parseAnsiCode(string4, index);
+ if (!escapeCode) {
+ break;
+ }
+ tokens.push(escapeCode.token);
+ index = escapeCode.endIndex;
+ }
+ return index;
+}
+__name(appendTrailingAnsiTokens, "appendTrailingAnsiTokens");
+function parseCharacterTokenWithRawSegmentation(string4, index, graphemeSegments) {
+ const segment = graphemeSegments.containing(index);
+ if (!segment || segment.index !== index) {
+ return;
+ }
+ return {
+ token: {
+ type: "character",
+ // Intentionally preserve UAX29 behavior (GB3): CRLF is one grapheme cluster.
+ value: segment.segment,
+ visibleWidth: getGraphemeWidth(segment.segment),
+ isGraphemeContinuation: false
+ },
+ endIndex: index + segment.segment.length
+ };
+}
+__name(parseCharacterTokenWithRawSegmentation, "parseCharacterTokenWithRawSegmentation");
+function collectVisibleCharacters(string4) {
+ const visibleCharacters = [];
+ let index = 0;
+ while (index < string4.length) {
+ const codePoint = string4.codePointAt(index);
+ if (ESCAPES2.has(codePoint)) {
+ const code = parseAnsiCode(string4, index);
+ if (code) {
+ index = code.endIndex;
+ continue;
+ }
+ }
+ const value = String.fromCodePoint(codePoint);
+ visibleCharacters.push({
+ value,
+ visibleWidth: 1,
+ isGraphemeContinuation: false
+ });
+ index += value.length;
+ }
+ return visibleCharacters;
+}
+__name(collectVisibleCharacters, "collectVisibleCharacters");
+function applyGraphemeMetadata(visibleCharacters) {
+ if (visibleCharacters.length === 0) {
+ return;
+ }
+ const visibleString = visibleCharacters.map(({ value }) => value).join("");
+ const scalarOffsets = [];
+ let scalarOffset = 0;
+ for (const visibleCharacter of visibleCharacters) {
+ scalarOffsets.push(scalarOffset);
+ scalarOffset += visibleCharacter.value.length;
+ }
+ let scalarIndex = 0;
+ for (const segment of GRAPHEME_SEGMENTER.segment(visibleString)) {
+ while (scalarIndex < visibleCharacters.length && scalarOffsets[scalarIndex] < segment.index) {
+ scalarIndex++;
+ }
+ let graphemeIndex = scalarIndex;
+ let isFirstInGrapheme = true;
+ while (graphemeIndex < visibleCharacters.length && scalarOffsets[graphemeIndex] < segment.index + segment.segment.length) {
+ visibleCharacters[graphemeIndex].visibleWidth = isFirstInGrapheme ? getGraphemeWidth(segment.segment) : 0;
+ visibleCharacters[graphemeIndex].isGraphemeContinuation = !isFirstInGrapheme;
+ isFirstInGrapheme = false;
+ graphemeIndex++;
+ }
+ scalarIndex = graphemeIndex;
+ }
+}
+__name(applyGraphemeMetadata, "applyGraphemeMetadata");
+function tokenizeAnsiWithVisibleSegmentation(string4, { endCharacter = Number.POSITIVE_INFINITY } = {}) {
+ const tokens = [];
+ const visibleCharacters = collectVisibleCharacters(string4);
+ applyGraphemeMetadata(visibleCharacters);
+ let index = 0;
+ let visibleCharacterIndex = 0;
+ let visibleCount = 0;
+ while (index < string4.length) {
+ const codePoint = string4.codePointAt(index);
+ if (ESCAPES2.has(codePoint)) {
+ const code = parseAnsiCode(string4, index);
+ if (code) {
+ tokens.push(code.token);
+ index = code.endIndex;
+ continue;
+ }
+ }
+ const value = String.fromCodePoint(codePoint);
+ const visibleCharacter = visibleCharacters[visibleCharacterIndex];
+ let visibleWidth = isFullwidthCodePoint(codePoint) ? 2 : value.length;
+ if (visibleCharacter) {
+ visibleWidth = visibleCharacter.visibleWidth;
+ }
+ const token = {
+ type: "character",
+ value,
+ visibleWidth,
+ isGraphemeContinuation: visibleCharacter ? visibleCharacter.isGraphemeContinuation : false
+ };
+ tokens.push(token);
+ index += value.length;
+ visibleCharacterIndex++;
+ visibleCount += token.visibleWidth;
+ if (visibleCount >= endCharacter) {
+ const nextVisibleCharacter = visibleCharacters[visibleCharacterIndex];
+ if (!nextVisibleCharacter || !nextVisibleCharacter.isGraphemeContinuation) {
+ index = appendTrailingAnsiTokens(string4, index, tokens);
+ break;
+ }
+ }
+ }
+ return tokens;
+}
+__name(tokenizeAnsiWithVisibleSegmentation, "tokenizeAnsiWithVisibleSegmentation");
+function areValuesInSameGrapheme(leftValue, rightValue) {
+ const pair = `${leftValue}${rightValue}`;
+ const splitIndex = leftValue.length;
+ for (const segment of GRAPHEME_SEGMENTER.segment(pair)) {
+ if (segment.index === splitIndex) {
+ return false;
+ }
+ if (segment.index > splitIndex) {
+ return true;
+ }
+ }
+ return true;
+}
+__name(areValuesInSameGrapheme, "areValuesInSameGrapheme");
+function hasAnsiSplitContinuationAhead(string4, startIndex, previousVisibleValue, graphemeSegments) {
+ if (!previousVisibleValue) {
+ return false;
+ }
+ let index = startIndex;
+ let hasAnsiCode = false;
+ while (index < string4.length) {
+ const codePoint = string4.codePointAt(index);
+ if (ESCAPES2.has(codePoint)) {
+ const code = parseAnsiCode(string4, index);
+ if (code) {
+ hasAnsiCode = true;
+ index = code.endIndex;
+ continue;
+ }
+ }
+ if (!hasAnsiCode) {
+ return false;
+ }
+ const characterToken = parseCharacterTokenWithRawSegmentation(string4, index, graphemeSegments);
+ if (!characterToken) {
+ return true;
+ }
+ return areValuesInSameGrapheme(previousVisibleValue, characterToken.token.value);
+ }
+ return false;
+}
+__name(hasAnsiSplitContinuationAhead, "hasAnsiSplitContinuationAhead");
+function tokenizeAnsi(string4, { endCharacter = Number.POSITIVE_INFINITY } = {}) {
+ const tokens = [];
+ const graphemeSegments = GRAPHEME_SEGMENTER.segment(string4);
+ let index = 0;
+ let visibleCount = 0;
+ let previousVisibleValue;
+ let hasAnsiSinceLastVisible = false;
+ while (index < string4.length) {
+ const codePoint = string4.codePointAt(index);
+ if (ESCAPES2.has(codePoint)) {
+ const code = parseAnsiCode(string4, index);
+ if (code) {
+ tokens.push(code.token);
+ index = code.endIndex;
+ hasAnsiSinceLastVisible = true;
+ continue;
+ }
+ }
+ const characterToken = parseCharacterTokenWithRawSegmentation(string4, index, graphemeSegments);
+ if (!characterToken) {
+ return tokenizeAnsiWithVisibleSegmentation(string4, { endCharacter });
+ }
+ if (hasAnsiSinceLastVisible && previousVisibleValue && areValuesInSameGrapheme(previousVisibleValue, characterToken.token.value)) {
+ return tokenizeAnsiWithVisibleSegmentation(string4, { endCharacter });
+ }
+ tokens.push(characterToken.token);
+ index = characterToken.endIndex;
+ visibleCount += characterToken.token.visibleWidth;
+ hasAnsiSinceLastVisible = false;
+ previousVisibleValue = characterToken.token.value;
+ if (visibleCount >= endCharacter) {
+ if (hasAnsiSplitContinuationAhead(string4, index, previousVisibleValue, graphemeSegments)) {
+ return tokenizeAnsiWithVisibleSegmentation(string4, { endCharacter });
+ }
+ index = appendTrailingAnsiTokens(string4, index, tokens);
+ break;
+ }
+ }
+ return tokens;
+}
+__name(tokenizeAnsi, "tokenizeAnsi");
+
+// node_modules/slice-ansi/index.js
+function applySgrFragments(activeStyles, fragments) {
+ for (const fragment of fragments) {
+ switch (fragment.type) {
+ case "reset": {
+ activeStyles.clear();
+ break;
+ }
+ case "end": {
+ activeStyles.delete(fragment.endCode);
+ break;
+ }
+ case "start": {
+ activeStyles.delete(fragment.endCode);
+ activeStyles.set(fragment.endCode, fragment.code);
+ break;
+ }
+ default: {
+ break;
+ }
+ }
+ }
+ return activeStyles;
+}
+__name(applySgrFragments, "applySgrFragments");
+function undoAnsiCodes(activeStyles) {
+ return [...activeStyles.keys()].toReversed().join("");
+}
+__name(undoAnsiCodes, "undoAnsiCodes");
+function closeHyperlink(hyperlinkToken) {
+ return `${hyperlinkToken.closePrefix}${hyperlinkToken.terminator}`;
+}
+__name(closeHyperlink, "closeHyperlink");
+function shouldIncludeSgrAfterEnd(token, activeStyles) {
+ let hasStartFragment = false;
+ let hasClosingEffect = false;
+ for (const fragment of token.fragments) {
+ if (fragment.type === "start") {
+ hasStartFragment = true;
+ continue;
+ }
+ if (fragment.type === "reset" && activeStyles.size > 0) {
+ hasClosingEffect = true;
+ continue;
+ }
+ if (fragment.type === "end" && activeStyles.has(fragment.endCode)) {
+ hasClosingEffect = true;
+ }
+ }
+ return hasClosingEffect && !hasStartFragment;
+}
+__name(shouldIncludeSgrAfterEnd, "shouldIncludeSgrAfterEnd");
+function hasSgrStartFragment(token) {
+ return token.fragments.some((fragment) => fragment.type === "start");
+}
+__name(hasSgrStartFragment, "hasSgrStartFragment");
+function discardPendingHyperlink(parameters) {
+ if (parameters.activeHyperlink && !parameters.activeHyperlinkHasVisibleText && parameters.activeHyperlinkOutputIndex !== void 0) {
+ const openCodeLength = parameters.activeHyperlink.code.length;
+ parameters.returnValue = parameters.returnValue.slice(0, parameters.activeHyperlinkOutputIndex) + parameters.returnValue.slice(parameters.activeHyperlinkOutputIndex + openCodeLength);
+ if (parameters.pendingSgrOutputIndex !== void 0 && parameters.pendingSgrOutputIndex > parameters.activeHyperlinkOutputIndex) {
+ parameters.pendingSgrOutputIndex -= openCodeLength;
+ }
+ }
+ parameters.activeHyperlink = void 0;
+ parameters.activeHyperlinkHasVisibleText = false;
+ parameters.activeHyperlinkOutputIndex = void 0;
+}
+__name(discardPendingHyperlink, "discardPendingHyperlink");
+function applySgrToken2(parameters) {
+ if (parameters.isPastEnd && !shouldIncludeSgrAfterEnd(parameters.token, parameters.activeStyles)) {
+ return parameters;
+ }
+ if (parameters.include && hasSgrStartFragment(parameters.token) && parameters.pendingSgrOutputIndex === void 0) {
+ parameters.pendingSgrOutputIndex = parameters.returnValue.length;
+ parameters.pendingSgrActiveStyles = new Map(parameters.activeStyles);
+ }
+ parameters.activeStyles = applySgrFragments(parameters.activeStyles, parameters.token.fragments);
+ if (parameters.include) {
+ parameters.returnValue += parameters.token.code;
+ }
+ return parameters;
+}
+__name(applySgrToken2, "applySgrToken");
+function applyHyperlinkToken(parameters) {
+ if (parameters.isPastEnd && (parameters.token.action !== "close" || !parameters.activeHyperlink)) {
+ return parameters;
+ }
+ if (parameters.token.action === "open") {
+ parameters.activeHyperlink = parameters.token;
+ parameters.activeHyperlinkHasVisibleText = false;
+ parameters.activeHyperlinkOutputIndex = void 0;
+ if (parameters.include) {
+ parameters.activeHyperlinkOutputIndex = parameters.returnValue.length;
+ }
+ } else if (parameters.token.action === "close") {
+ if (parameters.include && parameters.activeHyperlink && !parameters.activeHyperlinkHasVisibleText) {
+ discardPendingHyperlink(parameters);
+ return parameters;
+ }
+ parameters.activeHyperlink = void 0;
+ parameters.activeHyperlinkHasVisibleText = false;
+ parameters.activeHyperlinkOutputIndex = void 0;
+ }
+ if (parameters.include) {
+ parameters.returnValue += parameters.token.code;
+ }
+ return parameters;
+}
+__name(applyHyperlinkToken, "applyHyperlinkToken");
+function applyControlToken(parameters) {
+ if (!parameters.isPastEnd && parameters.include) {
+ parameters.returnValue += parameters.token.code;
+ }
+ return parameters;
+}
+__name(applyControlToken, "applyControlToken");
+function applyCharacterToken(parameters) {
+ if (!parameters.include && parameters.position >= parameters.start && !parameters.token.isGraphemeContinuation) {
+ parameters.include = true;
+ parameters.returnValue = [...parameters.activeStyles.values()].join("");
+ if (parameters.activeHyperlink) {
+ parameters.activeHyperlinkOutputIndex = parameters.returnValue.length;
+ parameters.returnValue += parameters.activeHyperlink.code;
+ }
+ }
+ if (parameters.include) {
+ parameters.returnValue += parameters.token.value;
+ parameters.pendingSgrOutputIndex = void 0;
+ parameters.pendingSgrActiveStyles = void 0;
+ if (parameters.activeHyperlink) {
+ parameters.activeHyperlinkHasVisibleText = true;
+ }
+ }
+ parameters.position += parameters.token.visibleWidth;
+ return parameters;
+}
+__name(applyCharacterToken, "applyCharacterToken");
+var tokenHandlers = {
+ sgr: applySgrToken2,
+ hyperlink: applyHyperlinkToken,
+ control: applyControlToken,
+ character: applyCharacterToken
+};
+function applyToken(parameters) {
+ const tokenHandler = tokenHandlers[parameters.token.type];
+ if (!tokenHandler) {
+ return parameters;
+ }
+ return tokenHandler(parameters);
+}
+__name(applyToken, "applyToken");
+function createHasContinuationAheadMap(tokens) {
+ const hasContinuationAhead = Array.from({ length: tokens.length }, () => false);
+ let nextCharacterIsContinuation = false;
+ for (let tokenIndex = tokens.length - 1; tokenIndex >= 0; tokenIndex--) {
+ const token = tokens[tokenIndex];
+ hasContinuationAhead[tokenIndex] = nextCharacterIsContinuation;
+ if (token.type === "character") {
+ nextCharacterIsContinuation = Boolean(token.isGraphemeContinuation);
+ }
+ }
+ return hasContinuationAhead;
+}
+__name(createHasContinuationAheadMap, "createHasContinuationAheadMap");
+function isPastEndBoundary(token, position, end) {
+ if (end === void 0) {
+ return false;
+ }
+ if (position >= end) {
+ return true;
+ }
+ return token.type === "character" && !token.isGraphemeContinuation && position + token.visibleWidth > end;
+}
+__name(isPastEndBoundary, "isPastEndBoundary");
+function sliceAnsi(string4, start, end) {
+ const tokens = tokenizeAnsi(string4, { endCharacter: end });
+ const hasContinuationAhead = createHasContinuationAheadMap(tokens);
+ let activeStyles = /* @__PURE__ */ new Map();
+ let activeHyperlink;
+ let activeHyperlinkHasVisibleText = false;
+ let activeHyperlinkOutputIndex;
+ let pendingSgrOutputIndex;
+ let pendingSgrActiveStyles;
+ let position = 0;
+ let returnValue = "";
+ let include = false;
+ for (const [tokenIndex, token] of tokens.entries()) {
+ let isPastEnd = isPastEndBoundary(token, position, end);
+ if (isPastEnd && token.type !== "character" && hasContinuationAhead[tokenIndex]) {
+ isPastEnd = false;
+ }
+ if (isPastEnd && token.type === "character" && !token.isGraphemeContinuation) {
+ if (activeHyperlink && !activeHyperlinkHasVisibleText) {
+ const hyperlinkState = {
+ activeHyperlink,
+ activeHyperlinkHasVisibleText,
+ activeHyperlinkOutputIndex,
+ pendingSgrOutputIndex,
+ returnValue
+ };
+ discardPendingHyperlink(hyperlinkState);
+ ({
+ activeHyperlink,
+ activeHyperlinkHasVisibleText,
+ activeHyperlinkOutputIndex,
+ pendingSgrOutputIndex,
+ returnValue
+ } = hyperlinkState);
+ }
+ if (pendingSgrOutputIndex !== void 0) {
+ returnValue = returnValue.slice(0, pendingSgrOutputIndex);
+ activeStyles = pendingSgrActiveStyles;
+ pendingSgrOutputIndex = void 0;
+ pendingSgrActiveStyles = void 0;
+ }
+ break;
+ }
+ ({ activeStyles, activeHyperlink, activeHyperlinkHasVisibleText, activeHyperlinkOutputIndex, pendingSgrOutputIndex, pendingSgrActiveStyles, position, returnValue, include } = applyToken({
+ token,
+ isPastEnd,
+ start,
+ activeStyles,
+ activeHyperlink,
+ activeHyperlinkHasVisibleText,
+ activeHyperlinkOutputIndex,
+ pendingSgrOutputIndex,
+ pendingSgrActiveStyles,
+ position,
+ returnValue,
+ include
+ }));
+ }
+ if (!include) {
+ return "";
+ }
+ if (activeHyperlink) {
+ returnValue += closeHyperlink(activeHyperlink);
+ }
+ returnValue += undoAnsiCodes(activeStyles);
+ return returnValue;
+}
+__name(sliceAnsi, "sliceAnsi");
+
+// node_modules/cli-truncate/index.js
+function getIndexOfNearestSpace(string4, wantedIndex, shouldSearchRight) {
+ if (string4.charAt(wantedIndex) === " ") {
+ return wantedIndex;
+ }
+ const direction = shouldSearchRight ? 1 : -1;
+ for (let index = 0; index <= 3; index++) {
+ const finalIndex = wantedIndex + index * direction;
+ if (string4.charAt(finalIndex) === " ") {
+ return finalIndex;
+ }
+ }
+ return wantedIndex;
+}
+__name(getIndexOfNearestSpace, "getIndexOfNearestSpace");
+function cliTruncate(text, columns, options2 = {}) {
+ const {
+ position = "end",
+ space = false,
+ preferTruncationOnSpace = false
+ } = options2;
+ let { truncationCharacter = "\u2026" } = options2;
+ if (typeof text !== "string") {
+ throw new TypeError(`Expected \`input\` to be a string, got ${typeof text}`);
+ }
+ if (typeof columns !== "number") {
+ throw new TypeError(`Expected \`columns\` to be a number, got ${typeof columns}`);
+ }
+ if (columns < 1) {
+ return "";
+ }
+ const length = stringWidth(text);
+ if (length <= columns) {
+ return text;
+ }
+ if (columns === 1) {
+ return truncationCharacter;
+ }
+ const ANSI = {
+ ESC: 27,
+ LEFT_BRACKET: 91,
+ LETTER_M: 109
+ };
+ const isSgrParameter = /* @__PURE__ */ __name((code) => code >= 48 && code <= 57 || code === 59, "isSgrParameter");
+ function leadingSgrSpanEndIndex(string4) {
+ let index = 0;
+ while (index + 2 < string4.length && string4.codePointAt(index) === ANSI.ESC && string4.codePointAt(index + 1) === ANSI.LEFT_BRACKET) {
+ let j = index + 2;
+ while (j < string4.length && isSgrParameter(string4.codePointAt(j))) {
+ j++;
+ }
+ if (j < string4.length && string4.codePointAt(j) === ANSI.LETTER_M) {
+ index = j + 1;
+ continue;
+ }
+ break;
+ }
+ return index;
+ }
+ __name(leadingSgrSpanEndIndex, "leadingSgrSpanEndIndex");
+ function trailingSgrSpanStartIndex(string4) {
+ let start = string4.length;
+ while (start > 1 && string4.codePointAt(start - 1) === ANSI.LETTER_M) {
+ let j = start - 2;
+ while (j >= 0 && isSgrParameter(string4.codePointAt(j))) {
+ j--;
+ }
+ if (j >= 1 && string4.codePointAt(j - 1) === ANSI.ESC && string4.codePointAt(j) === ANSI.LEFT_BRACKET) {
+ start = j - 1;
+ continue;
+ }
+ break;
+ }
+ return start;
+ }
+ __name(trailingSgrSpanStartIndex, "trailingSgrSpanStartIndex");
+ function appendWithInheritedStyleFromEnd(visible, suffix) {
+ const start = trailingSgrSpanStartIndex(visible);
+ if (start === visible.length) {
+ return visible + suffix;
+ }
+ return visible.slice(0, start) + suffix + visible.slice(start);
+ }
+ __name(appendWithInheritedStyleFromEnd, "appendWithInheritedStyleFromEnd");
+ function prependWithInheritedStyleFromStart(prefix, visible) {
+ const end = leadingSgrSpanEndIndex(visible);
+ if (end === 0) {
+ return prefix + visible;
+ }
+ return visible.slice(0, end) + prefix + visible.slice(end);
+ }
+ __name(prependWithInheritedStyleFromStart, "prependWithInheritedStyleFromStart");
+ if (position === "start") {
+ if (preferTruncationOnSpace) {
+ const nearestSpace = getIndexOfNearestSpace(text, length - columns + 1, true);
+ const right3 = sliceAnsi(text, nearestSpace, length).trim();
+ return prependWithInheritedStyleFromStart(truncationCharacter, right3);
+ }
+ if (space) {
+ truncationCharacter += " ";
+ }
+ const right2 = sliceAnsi(text, length - columns + stringWidth(truncationCharacter), length);
+ return prependWithInheritedStyleFromStart(truncationCharacter, right2);
+ }
+ if (position === "middle") {
+ if (space) {
+ truncationCharacter = ` ${truncationCharacter} `;
+ }
+ const half = Math.floor(columns / 2);
+ if (preferTruncationOnSpace) {
+ const spaceNearFirstBreakPoint = getIndexOfNearestSpace(text, half);
+ const spaceNearSecondBreakPoint = getIndexOfNearestSpace(text, length - (columns - half) + 1, true);
+ return sliceAnsi(text, 0, spaceNearFirstBreakPoint) + truncationCharacter + sliceAnsi(text, spaceNearSecondBreakPoint, length).trim();
+ }
+ return sliceAnsi(text, 0, half) + truncationCharacter + sliceAnsi(text, length - (columns - half) + stringWidth(truncationCharacter), length);
+ }
+ if (position === "end") {
+ if (preferTruncationOnSpace) {
+ const nearestSpace = getIndexOfNearestSpace(text, columns - 1);
+ const left3 = sliceAnsi(text, 0, nearestSpace);
+ return appendWithInheritedStyleFromEnd(left3, truncationCharacter);
+ }
+ if (space) {
+ truncationCharacter = ` ${truncationCharacter}`;
+ }
+ const left2 = sliceAnsi(text, 0, columns - stringWidth(truncationCharacter));
+ return appendWithInheritedStyleFromEnd(left2, truncationCharacter);
+ }
+ throw new Error(`Expected \`options.position\` to be either \`start\`, \`middle\` or \`end\`, got ${position}`);
+}
+__name(cliTruncate, "cliTruncate");
+
+// node_modules/ink/build/wrap-text.js
+var cache2 = {};
+var wrapText = /* @__PURE__ */ __name((text, maxWidth, wrapType) => {
+ const cacheKey = text + String(maxWidth) + String(wrapType);
+ const cachedText = cache2[cacheKey];
+ if (cachedText) {
+ return cachedText;
+ }
+ let wrappedText = text;
+ if (wrapType === "wrap") {
+ wrappedText = wrapAnsi(text, maxWidth, {
+ trim: false,
+ hard: true
+ });
+ }
+ if (wrapType === "hard") {
+ wrappedText = wrapAnsi(text, maxWidth, {
+ trim: false,
+ hard: true,
+ wordWrap: false
+ });
+ }
+ if (wrapType.startsWith("truncate")) {
+ let position = "end";
+ if (wrapType === "truncate-middle") {
+ position = "middle";
+ }
+ if (wrapType === "truncate-start") {
+ position = "start";
+ }
+ wrappedText = cliTruncate(text, maxWidth, { position });
+ }
+ cache2[cacheKey] = wrappedText;
+ return wrappedText;
+}, "wrapText");
+var wrap_text_default = wrapText;
+
+// node_modules/ink/build/squash-text-nodes.js
+init_esbuild_shims();
+
+// node_modules/ink/build/sanitize-ansi.js
+init_esbuild_shims();
+
+// node_modules/ink/build/ansi-tokenizer.js
+init_esbuild_shims();
+var bellCharacter = "\x07";
+var escapeCharacter = "\x1B";
+var stringTerminatorCharacter = "\x9C";
+var csiCharacter = "\x9B";
+var oscCharacter = "\x9D";
+var dcsCharacter = "\x90";
+var pmCharacter = "\x9E";
+var apcCharacter = "\x9F";
+var sosCharacter = "\x98";
+var isCsiParameterCharacter2 = /* @__PURE__ */ __name((character) => {
+ const codePoint = character.codePointAt(0);
+ return codePoint !== void 0 && codePoint >= 48 && codePoint <= 63;
+}, "isCsiParameterCharacter");
+var isCsiIntermediateCharacter2 = /* @__PURE__ */ __name((character) => {
+ const codePoint = character.codePointAt(0);
+ return codePoint !== void 0 && codePoint >= 32 && codePoint <= 47;
+}, "isCsiIntermediateCharacter");
+var isCsiFinalCharacter2 = /* @__PURE__ */ __name((character) => {
+ const codePoint = character.codePointAt(0);
+ return codePoint !== void 0 && codePoint >= 64 && codePoint <= 126;
+}, "isCsiFinalCharacter");
+var isEscapeIntermediateCharacter = /* @__PURE__ */ __name((character) => {
+ const codePoint = character.codePointAt(0);
+ return codePoint !== void 0 && codePoint >= 32 && codePoint <= 47;
+}, "isEscapeIntermediateCharacter");
+var isEscapeFinalCharacter = /* @__PURE__ */ __name((character) => {
+ const codePoint = character.codePointAt(0);
+ return codePoint !== void 0 && codePoint >= 48 && codePoint <= 126;
+}, "isEscapeFinalCharacter");
+var isC1ControlCharacter = /* @__PURE__ */ __name((character) => {
+ const codePoint = character.codePointAt(0);
+ return codePoint !== void 0 && codePoint >= 128 && codePoint <= 159;
+}, "isC1ControlCharacter");
+var readCsiSequence = /* @__PURE__ */ __name((text, fromIndex) => {
+ let index = fromIndex;
+ while (index < text.length) {
+ const character = text[index];
+ if (!isCsiParameterCharacter2(character)) {
+ break;
+ }
+ index++;
+ }
+ const parameterString = text.slice(fromIndex, index);
+ const intermediateStartIndex = index;
+ while (index < text.length) {
+ const character = text[index];
+ if (!isCsiIntermediateCharacter2(character)) {
+ break;
+ }
+ index++;
+ }
+ const intermediateString = text.slice(intermediateStartIndex, index);
+ const finalCharacter = text[index];
+ if (finalCharacter === void 0 || !isCsiFinalCharacter2(finalCharacter)) {
+ return void 0;
+ }
+ return {
+ endIndex: index + 1,
+ parameterString,
+ intermediateString,
+ finalCharacter
+ };
+}, "readCsiSequence");
+var findControlStringTerminatorIndex = /* @__PURE__ */ __name((text, fromIndex, allowBellTerminator) => {
+ for (let index = fromIndex; index < text.length; index++) {
+ const character = text[index];
+ if (allowBellTerminator && character === bellCharacter) {
+ return index + 1;
+ }
+ if (character === stringTerminatorCharacter) {
+ return index + 1;
+ }
+ if (character === escapeCharacter) {
+ const followingCharacter = text[index + 1];
+ if (followingCharacter === escapeCharacter) {
+ index++;
+ continue;
+ }
+ if (followingCharacter === "\\") {
+ return index + 2;
+ }
+ }
+ }
+ return void 0;
+}, "findControlStringTerminatorIndex");
+var readEscapeSequence = /* @__PURE__ */ __name((text, fromIndex) => {
+ let index = fromIndex;
+ while (index < text.length) {
+ const character = text[index];
+ if (!isEscapeIntermediateCharacter(character)) {
+ break;
+ }
+ index++;
+ }
+ const intermediateString = text.slice(fromIndex, index);
+ const finalCharacter = text[index];
+ if (finalCharacter === void 0 || !isEscapeFinalCharacter(finalCharacter)) {
+ return void 0;
+ }
+ return {
+ endIndex: index + 1,
+ intermediateString,
+ finalCharacter
+ };
+}, "readEscapeSequence");
+var getControlStringFromEscapeIntroducer = /* @__PURE__ */ __name((character) => {
+ switch (character) {
+ case "]": {
+ return { type: "osc", allowBellTerminator: true };
+ }
+ case "P": {
+ return { type: "dcs", allowBellTerminator: false };
+ }
+ case "^": {
+ return { type: "pm", allowBellTerminator: false };
+ }
+ case "_": {
+ return { type: "apc", allowBellTerminator: false };
+ }
+ case "X": {
+ return { type: "sos", allowBellTerminator: false };
+ }
+ default: {
+ return void 0;
+ }
+ }
+}, "getControlStringFromEscapeIntroducer");
+var getControlStringFromC1Introducer = /* @__PURE__ */ __name((character) => {
+ switch (character) {
+ case oscCharacter: {
+ return { type: "osc", allowBellTerminator: true };
+ }
+ case dcsCharacter: {
+ return { type: "dcs", allowBellTerminator: false };
+ }
+ case pmCharacter: {
+ return { type: "pm", allowBellTerminator: false };
+ }
+ case apcCharacter: {
+ return { type: "apc", allowBellTerminator: false };
+ }
+ case sosCharacter: {
+ return { type: "sos", allowBellTerminator: false };
+ }
+ default: {
+ return void 0;
+ }
+ }
+}, "getControlStringFromC1Introducer");
+var hasAnsiControlCharacters = /* @__PURE__ */ __name((text) => {
+ if (text.includes(escapeCharacter)) {
+ return true;
+ }
+ for (const character of text) {
+ if (isC1ControlCharacter(character)) {
+ return true;
+ }
+ }
+ return false;
+}, "hasAnsiControlCharacters");
+var malformedFromIndex = /* @__PURE__ */ __name((tokens, text, textStartIndex, fromIndex) => {
+ if (fromIndex > textStartIndex) {
+ tokens.push({ type: "text", value: text.slice(textStartIndex, fromIndex) });
+ }
+ tokens.push({ type: "invalid", value: text.slice(fromIndex) });
+ return tokens;
+}, "malformedFromIndex");
+var tokenizeAnsi2 = /* @__PURE__ */ __name((text) => {
+ if (!hasAnsiControlCharacters(text)) {
+ return [{ type: "text", value: text }];
+ }
+ const tokens = [];
+ let textStartIndex = 0;
+ for (let index = 0; index < text.length; ) {
+ const character = text[index];
+ if (character === void 0) {
+ break;
+ }
+ if (character === escapeCharacter) {
+ const followingCharacter = text[index + 1];
+ if (followingCharacter === void 0) {
+ return malformedFromIndex(tokens, text, textStartIndex, index);
+ }
+ if (followingCharacter === "[") {
+ const csiSequence = readCsiSequence(text, index + 2);
+ if (csiSequence === void 0) {
+ return malformedFromIndex(tokens, text, textStartIndex, index);
+ }
+ if (index > textStartIndex) {
+ tokens.push({ type: "text", value: text.slice(textStartIndex, index) });
+ }
+ tokens.push({
+ type: "csi",
+ value: text.slice(index, csiSequence.endIndex),
+ parameterString: csiSequence.parameterString,
+ intermediateString: csiSequence.intermediateString,
+ finalCharacter: csiSequence.finalCharacter
+ });
+ index = csiSequence.endIndex;
+ textStartIndex = index;
+ continue;
+ }
+ const escapeControlString = getControlStringFromEscapeIntroducer(followingCharacter);
+ if (escapeControlString !== void 0) {
+ const controlStringTerminatorIndex = findControlStringTerminatorIndex(text, index + 2, escapeControlString.allowBellTerminator);
+ if (controlStringTerminatorIndex === void 0) {
+ return malformedFromIndex(tokens, text, textStartIndex, index);
+ }
+ if (index > textStartIndex) {
+ tokens.push({ type: "text", value: text.slice(textStartIndex, index) });
+ }
+ tokens.push({
+ type: escapeControlString.type,
+ value: text.slice(index, controlStringTerminatorIndex)
+ });
+ index = controlStringTerminatorIndex;
+ textStartIndex = index;
+ continue;
+ }
+ const escapeSequence = readEscapeSequence(text, index + 1);
+ if (escapeSequence === void 0) {
+ if (isEscapeIntermediateCharacter(followingCharacter)) {
+ return malformedFromIndex(tokens, text, textStartIndex, index);
+ }
+ if (index > textStartIndex) {
+ tokens.push({ type: "text", value: text.slice(textStartIndex, index) });
+ }
+ index++;
+ textStartIndex = index;
+ continue;
+ }
+ if (index > textStartIndex) {
+ tokens.push({ type: "text", value: text.slice(textStartIndex, index) });
+ }
+ tokens.push({
+ type: "esc",
+ value: text.slice(index, escapeSequence.endIndex),
+ intermediateString: escapeSequence.intermediateString,
+ finalCharacter: escapeSequence.finalCharacter
+ });
+ index = escapeSequence.endIndex;
+ textStartIndex = index;
+ continue;
+ }
+ if (character === csiCharacter) {
+ const csiSequence = readCsiSequence(text, index + 1);
+ if (csiSequence === void 0) {
+ return malformedFromIndex(tokens, text, textStartIndex, index);
+ }
+ if (index > textStartIndex) {
+ tokens.push({ type: "text", value: text.slice(textStartIndex, index) });
+ }
+ tokens.push({
+ type: "csi",
+ value: text.slice(index, csiSequence.endIndex),
+ parameterString: csiSequence.parameterString,
+ intermediateString: csiSequence.intermediateString,
+ finalCharacter: csiSequence.finalCharacter
+ });
+ index = csiSequence.endIndex;
+ textStartIndex = index;
+ continue;
+ }
+ const c1ControlString = getControlStringFromC1Introducer(character);
+ if (c1ControlString !== void 0) {
+ const controlStringTerminatorIndex = findControlStringTerminatorIndex(text, index + 1, c1ControlString.allowBellTerminator);
+ if (controlStringTerminatorIndex === void 0) {
+ return malformedFromIndex(tokens, text, textStartIndex, index);
+ }
+ if (index > textStartIndex) {
+ tokens.push({ type: "text", value: text.slice(textStartIndex, index) });
+ }
+ tokens.push({
+ type: c1ControlString.type,
+ value: text.slice(index, controlStringTerminatorIndex)
+ });
+ index = controlStringTerminatorIndex;
+ textStartIndex = index;
+ continue;
+ }
+ if (character === stringTerminatorCharacter) {
+ if (index > textStartIndex) {
+ tokens.push({ type: "text", value: text.slice(textStartIndex, index) });
+ }
+ tokens.push({ type: "st", value: character });
+ index++;
+ textStartIndex = index;
+ continue;
+ }
+ if (isC1ControlCharacter(character)) {
+ if (index > textStartIndex) {
+ tokens.push({ type: "text", value: text.slice(textStartIndex, index) });
+ }
+ tokens.push({ type: "c1", value: character });
+ index++;
+ textStartIndex = index;
+ continue;
+ }
+ index++;
+ }
+ if (textStartIndex < text.length) {
+ tokens.push({ type: "text", value: text.slice(textStartIndex) });
+ }
+ return tokens;
+}, "tokenizeAnsi");
+
+// node_modules/ink/build/sanitize-ansi.js
+var sgrParametersRegex = /^[\d:;]*$/;
+var sanitizeAnsi = /* @__PURE__ */ __name((text) => {
+ if (!hasAnsiControlCharacters(text)) {
+ return text;
+ }
+ let output = "";
+ for (const token of tokenizeAnsi2(text)) {
+ if (token.type === "text" || token.type === "osc") {
+ output += token.value;
+ continue;
+ }
+ if (token.type === "csi" && token.finalCharacter === "m" && token.intermediateString === "" && sgrParametersRegex.test(token.parameterString)) {
+ output += token.value;
+ }
+ }
+ return output;
+}, "sanitizeAnsi");
+var sanitize_ansi_default = sanitizeAnsi;
+
+// node_modules/ink/build/squash-text-nodes.js
+var squashTextNodes = /* @__PURE__ */ __name((node) => {
+ let text = "";
+ for (let index = 0; index < node.childNodes.length; index++) {
+ const childNode = node.childNodes[index];
+ if (childNode === void 0) {
+ continue;
+ }
+ let nodeText = "";
+ if (childNode.nodeName === "#text") {
+ nodeText = childNode.nodeValue;
+ } else {
+ if (childNode.nodeName === "ink-text" || childNode.nodeName === "ink-virtual-text") {
+ nodeText = squashTextNodes(childNode);
+ }
+ if (nodeText.length > 0 && typeof childNode.internal_transform === "function") {
+ nodeText = childNode.internal_transform(nodeText, index);
+ }
+ }
+ text += nodeText;
+ }
+ return sanitize_ansi_default(text);
+}, "squashTextNodes");
+var squash_text_nodes_default = squashTextNodes;
+
+// node_modules/ink/build/dom.js
+var createNode = /* @__PURE__ */ __name((nodeName) => {
+ const node = {
+ nodeName,
+ style: {},
+ attributes: {},
+ childNodes: [],
+ parentNode: void 0,
+ yogaNode: nodeName === "ink-virtual-text" ? void 0 : src_default.Node.create(),
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ internal_accessibility: {}
+ };
+ if (nodeName === "ink-text") {
+ node.yogaNode?.setMeasureFunc(measureTextNode.bind(null, node));
+ }
+ return node;
+}, "createNode");
+var appendChildNode = /* @__PURE__ */ __name((node, childNode) => {
+ if (childNode.parentNode) {
+ removeChildNode(childNode.parentNode, childNode);
+ }
+ childNode.parentNode = node;
+ node.childNodes.push(childNode);
+ if (childNode.yogaNode) {
+ node.yogaNode?.insertChild(childNode.yogaNode, node.yogaNode.getChildCount());
+ }
+ if (node.nodeName === "ink-text" || node.nodeName === "ink-virtual-text") {
+ markNodeAsDirty(node);
+ }
+}, "appendChildNode");
+var insertBeforeNode = /* @__PURE__ */ __name((node, newChildNode, beforeChildNode) => {
+ if (newChildNode.parentNode) {
+ removeChildNode(newChildNode.parentNode, newChildNode);
+ }
+ newChildNode.parentNode = node;
+ const index = node.childNodes.indexOf(beforeChildNode);
+ if (index >= 0) {
+ node.childNodes.splice(index, 0, newChildNode);
+ if (newChildNode.yogaNode) {
+ node.yogaNode?.insertChild(newChildNode.yogaNode, index);
+ }
+ } else {
+ node.childNodes.push(newChildNode);
+ if (newChildNode.yogaNode) {
+ node.yogaNode?.insertChild(newChildNode.yogaNode, node.yogaNode.getChildCount());
+ }
+ }
+ if (node.nodeName === "ink-text" || node.nodeName === "ink-virtual-text") {
+ markNodeAsDirty(node);
+ }
+}, "insertBeforeNode");
+var removeChildNode = /* @__PURE__ */ __name((node, removeNode) => {
+ if (removeNode.yogaNode) {
+ removeNode.parentNode?.yogaNode?.removeChild(removeNode.yogaNode);
+ }
+ removeNode.parentNode = void 0;
+ const index = node.childNodes.indexOf(removeNode);
+ if (index >= 0) {
+ node.childNodes.splice(index, 1);
+ }
+ if (node.nodeName === "ink-text" || node.nodeName === "ink-virtual-text") {
+ markNodeAsDirty(node);
+ }
+}, "removeChildNode");
+var setAttribute = /* @__PURE__ */ __name((node, key, value) => {
+ if (key === "internal_accessibility") {
+ node.internal_accessibility = value;
+ return;
+ }
+ node.attributes[key] = value;
+}, "setAttribute");
+var setStyle = /* @__PURE__ */ __name((node, style) => {
+ node.style = style ?? {};
+}, "setStyle");
+var createTextNode = /* @__PURE__ */ __name((text) => {
+ const node = {
+ nodeName: "#text",
+ nodeValue: text,
+ yogaNode: void 0,
+ parentNode: void 0,
+ style: {}
+ };
+ setTextNodeValue(node, text);
+ return node;
+}, "createTextNode");
+var measureTextNode = /* @__PURE__ */ __name(function(node, width) {
+ const text = node.nodeName === "#text" ? node.nodeValue : squash_text_nodes_default(node);
+ const dimensions = measure_text_default(text);
+ if (dimensions.width <= width) {
+ return dimensions;
+ }
+ if (dimensions.width >= 1 && width > 0 && width < 1) {
+ return dimensions;
+ }
+ const textWrap = node.style?.textWrap ?? "wrap";
+ const wrappedText = wrap_text_default(text, width, textWrap);
+ return measure_text_default(wrappedText);
+}, "measureTextNode");
+var findClosestYogaNode = /* @__PURE__ */ __name((node) => {
+ if (!node?.parentNode) {
+ return void 0;
+ }
+ return node.yogaNode ?? findClosestYogaNode(node.parentNode);
+}, "findClosestYogaNode");
+var markNodeAsDirty = /* @__PURE__ */ __name((node) => {
+ const yogaNode = findClosestYogaNode(node);
+ yogaNode?.markDirty();
+}, "markNodeAsDirty");
+var setTextNodeValue = /* @__PURE__ */ __name((node, text) => {
+ if (typeof text !== "string") {
+ text = String(text);
+ }
+ node.nodeValue = text;
+ markNodeAsDirty(node);
+}, "setTextNodeValue");
+var addLayoutListener = /* @__PURE__ */ __name((rootNode, listener) => {
+ if (rootNode.nodeName !== "ink-root") {
+ return () => {
+ };
+ }
+ rootNode.internal_layoutListeners ??= /* @__PURE__ */ new Set();
+ rootNode.internal_layoutListeners.add(listener);
+ return () => {
+ rootNode.internal_layoutListeners?.delete(listener);
+ };
+}, "addLayoutListener");
+var emitLayoutListeners = /* @__PURE__ */ __name((rootNode) => {
+ if (rootNode.nodeName !== "ink-root" || !rootNode.internal_layoutListeners) {
+ return;
+ }
+ for (const listener of rootNode.internal_layoutListeners) {
+ listener();
+ }
+}, "emitLayoutListeners");
+
+// node_modules/ink/build/styles.js
+init_esbuild_shims();
+var positionEdges = [
+ ["top", src_default.EDGE_TOP],
+ ["right", src_default.EDGE_RIGHT],
+ ["bottom", src_default.EDGE_BOTTOM],
+ ["left", src_default.EDGE_LEFT]
+];
+var applyPositionStyles = /* @__PURE__ */ __name((node, style) => {
+ if ("position" in style) {
+ let positionType = src_default.POSITION_TYPE_RELATIVE;
+ if (style.position === "absolute") {
+ positionType = src_default.POSITION_TYPE_ABSOLUTE;
+ } else if (style.position === "static") {
+ positionType = src_default.POSITION_TYPE_STATIC;
+ }
+ node.setPositionType(positionType);
+ }
+ for (const [property, edge] of positionEdges) {
+ if (!(property in style)) {
+ continue;
+ }
+ const value = style[property];
+ if (typeof value === "string") {
+ node.setPositionPercent(edge, Number.parseFloat(value));
+ continue;
+ }
+ node.setPosition(edge, value);
+ }
+}, "applyPositionStyles");
+var applyMarginStyles = /* @__PURE__ */ __name((node, style) => {
+ if ("margin" in style) {
+ node.setMargin(src_default.EDGE_ALL, style.margin ?? 0);
+ }
+ if ("marginX" in style) {
+ node.setMargin(src_default.EDGE_HORIZONTAL, style.marginX ?? 0);
+ }
+ if ("marginY" in style) {
+ node.setMargin(src_default.EDGE_VERTICAL, style.marginY ?? 0);
+ }
+ if ("marginLeft" in style) {
+ node.setMargin(src_default.EDGE_START, style.marginLeft ?? 0);
+ }
+ if ("marginRight" in style) {
+ node.setMargin(src_default.EDGE_END, style.marginRight ?? 0);
+ }
+ if ("marginTop" in style) {
+ node.setMargin(src_default.EDGE_TOP, style.marginTop ?? 0);
+ }
+ if ("marginBottom" in style) {
+ node.setMargin(src_default.EDGE_BOTTOM, style.marginBottom ?? 0);
+ }
+}, "applyMarginStyles");
+var applyPaddingStyles = /* @__PURE__ */ __name((node, style) => {
+ if ("padding" in style) {
+ node.setPadding(src_default.EDGE_ALL, style.padding ?? 0);
+ }
+ if ("paddingX" in style) {
+ node.setPadding(src_default.EDGE_HORIZONTAL, style.paddingX ?? 0);
+ }
+ if ("paddingY" in style) {
+ node.setPadding(src_default.EDGE_VERTICAL, style.paddingY ?? 0);
+ }
+ if ("paddingLeft" in style) {
+ node.setPadding(src_default.EDGE_LEFT, style.paddingLeft ?? 0);
+ }
+ if ("paddingRight" in style) {
+ node.setPadding(src_default.EDGE_RIGHT, style.paddingRight ?? 0);
+ }
+ if ("paddingTop" in style) {
+ node.setPadding(src_default.EDGE_TOP, style.paddingTop ?? 0);
+ }
+ if ("paddingBottom" in style) {
+ node.setPadding(src_default.EDGE_BOTTOM, style.paddingBottom ?? 0);
+ }
+}, "applyPaddingStyles");
+var applyFlexStyles = /* @__PURE__ */ __name((node, style) => {
+ if ("flexGrow" in style) {
+ node.setFlexGrow(style.flexGrow ?? 0);
+ }
+ if ("flexShrink" in style) {
+ node.setFlexShrink(typeof style.flexShrink === "number" ? style.flexShrink : 1);
+ }
+ if ("flexWrap" in style) {
+ if (style.flexWrap === "nowrap") {
+ node.setFlexWrap(src_default.WRAP_NO_WRAP);
+ }
+ if (style.flexWrap === "wrap") {
+ node.setFlexWrap(src_default.WRAP_WRAP);
+ }
+ if (style.flexWrap === "wrap-reverse") {
+ node.setFlexWrap(src_default.WRAP_WRAP_REVERSE);
+ }
+ }
+ if ("flexDirection" in style) {
+ if (style.flexDirection === "row") {
+ node.setFlexDirection(src_default.FLEX_DIRECTION_ROW);
+ }
+ if (style.flexDirection === "row-reverse") {
+ node.setFlexDirection(src_default.FLEX_DIRECTION_ROW_REVERSE);
+ }
+ if (style.flexDirection === "column") {
+ node.setFlexDirection(src_default.FLEX_DIRECTION_COLUMN);
+ }
+ if (style.flexDirection === "column-reverse") {
+ node.setFlexDirection(src_default.FLEX_DIRECTION_COLUMN_REVERSE);
+ }
+ }
+ if ("flexBasis" in style) {
+ if (typeof style.flexBasis === "number") {
+ node.setFlexBasis(style.flexBasis);
+ } else if (typeof style.flexBasis === "string") {
+ node.setFlexBasisPercent(Number.parseInt(style.flexBasis, 10));
+ } else {
+ node.setFlexBasisAuto();
+ }
+ }
+ if ("alignItems" in style) {
+ if (style.alignItems === "stretch" || !style.alignItems) {
+ node.setAlignItems(src_default.ALIGN_STRETCH);
+ }
+ if (style.alignItems === "flex-start") {
+ node.setAlignItems(src_default.ALIGN_FLEX_START);
+ }
+ if (style.alignItems === "center") {
+ node.setAlignItems(src_default.ALIGN_CENTER);
+ }
+ if (style.alignItems === "flex-end") {
+ node.setAlignItems(src_default.ALIGN_FLEX_END);
+ }
+ if (style.alignItems === "baseline") {
+ node.setAlignItems(src_default.ALIGN_BASELINE);
+ }
+ }
+ if ("alignSelf" in style) {
+ if (style.alignSelf === "auto" || !style.alignSelf) {
+ node.setAlignSelf(src_default.ALIGN_AUTO);
+ }
+ if (style.alignSelf === "flex-start") {
+ node.setAlignSelf(src_default.ALIGN_FLEX_START);
+ }
+ if (style.alignSelf === "center") {
+ node.setAlignSelf(src_default.ALIGN_CENTER);
+ }
+ if (style.alignSelf === "flex-end") {
+ node.setAlignSelf(src_default.ALIGN_FLEX_END);
+ }
+ if (style.alignSelf === "stretch") {
+ node.setAlignSelf(src_default.ALIGN_STRETCH);
+ }
+ if (style.alignSelf === "baseline") {
+ node.setAlignSelf(src_default.ALIGN_BASELINE);
+ }
+ }
+ if ("alignContent" in style) {
+ if (style.alignContent === "flex-start" || !style.alignContent) {
+ node.setAlignContent(src_default.ALIGN_FLEX_START);
+ }
+ if (style.alignContent === "center") {
+ node.setAlignContent(src_default.ALIGN_CENTER);
+ }
+ if (style.alignContent === "flex-end") {
+ node.setAlignContent(src_default.ALIGN_FLEX_END);
+ }
+ if (style.alignContent === "space-between") {
+ node.setAlignContent(src_default.ALIGN_SPACE_BETWEEN);
+ }
+ if (style.alignContent === "space-around") {
+ node.setAlignContent(src_default.ALIGN_SPACE_AROUND);
+ }
+ if (style.alignContent === "space-evenly") {
+ node.setAlignContent(src_default.ALIGN_SPACE_EVENLY);
+ }
+ if (style.alignContent === "stretch") {
+ node.setAlignContent(src_default.ALIGN_STRETCH);
+ }
+ }
+ if ("justifyContent" in style) {
+ if (style.justifyContent === "flex-start" || !style.justifyContent) {
+ node.setJustifyContent(src_default.JUSTIFY_FLEX_START);
+ }
+ if (style.justifyContent === "center") {
+ node.setJustifyContent(src_default.JUSTIFY_CENTER);
+ }
+ if (style.justifyContent === "flex-end") {
+ node.setJustifyContent(src_default.JUSTIFY_FLEX_END);
+ }
+ if (style.justifyContent === "space-between") {
+ node.setJustifyContent(src_default.JUSTIFY_SPACE_BETWEEN);
+ }
+ if (style.justifyContent === "space-around") {
+ node.setJustifyContent(src_default.JUSTIFY_SPACE_AROUND);
+ }
+ if (style.justifyContent === "space-evenly") {
+ node.setJustifyContent(src_default.JUSTIFY_SPACE_EVENLY);
+ }
+ }
+}, "applyFlexStyles");
+var applyDimensionStyles = /* @__PURE__ */ __name((node, style) => {
+ if ("width" in style) {
+ if (typeof style.width === "number") {
+ node.setWidth(style.width);
+ } else if (typeof style.width === "string") {
+ node.setWidthPercent(Number.parseInt(style.width, 10));
+ } else {
+ node.setWidthAuto();
+ }
+ }
+ if ("height" in style) {
+ if (typeof style.height === "number") {
+ node.setHeight(style.height);
+ } else if (typeof style.height === "string") {
+ node.setHeightPercent(Number.parseInt(style.height, 10));
+ } else {
+ node.setHeightAuto();
+ }
+ }
+ if ("minWidth" in style) {
+ if (typeof style.minWidth === "string") {
+ node.setMinWidthPercent(Number.parseInt(style.minWidth, 10));
+ } else {
+ node.setMinWidth(style.minWidth ?? 0);
+ }
+ }
+ if ("minHeight" in style) {
+ if (typeof style.minHeight === "string") {
+ node.setMinHeightPercent(Number.parseInt(style.minHeight, 10));
+ } else {
+ node.setMinHeight(style.minHeight ?? 0);
+ }
+ }
+ if ("maxWidth" in style) {
+ if (typeof style.maxWidth === "string") {
+ node.setMaxWidthPercent(Number.parseInt(style.maxWidth, 10));
+ } else {
+ node.setMaxWidth(style.maxWidth);
+ }
+ }
+ if ("maxHeight" in style) {
+ if (typeof style.maxHeight === "string") {
+ node.setMaxHeightPercent(Number.parseInt(style.maxHeight, 10));
+ } else {
+ node.setMaxHeight(style.maxHeight);
+ }
+ }
+ if ("aspectRatio" in style) {
+ node.setAspectRatio(style.aspectRatio);
+ }
+}, "applyDimensionStyles");
+var applyDisplayStyles = /* @__PURE__ */ __name((node, style) => {
+ if ("display" in style) {
+ node.setDisplay(style.display === "flex" ? src_default.DISPLAY_FLEX : src_default.DISPLAY_NONE);
+ }
+}, "applyDisplayStyles");
+var applyBorderStyles = /* @__PURE__ */ __name((node, style, currentStyle) => {
+ const hasBorderChanges = "borderStyle" in style || "borderTop" in style || "borderBottom" in style || "borderLeft" in style || "borderRight" in style;
+ if (!hasBorderChanges) {
+ return;
+ }
+ const borderWidth = currentStyle.borderStyle ? 1 : 0;
+ node.setBorder(src_default.EDGE_TOP, currentStyle.borderTop === false ? 0 : borderWidth);
+ node.setBorder(src_default.EDGE_BOTTOM, currentStyle.borderBottom === false ? 0 : borderWidth);
+ node.setBorder(src_default.EDGE_LEFT, currentStyle.borderLeft === false ? 0 : borderWidth);
+ node.setBorder(src_default.EDGE_RIGHT, currentStyle.borderRight === false ? 0 : borderWidth);
+}, "applyBorderStyles");
+var applyGapStyles = /* @__PURE__ */ __name((node, style) => {
+ if ("gap" in style) {
+ node.setGap(src_default.GUTTER_ALL, style.gap ?? 0);
+ }
+ if ("columnGap" in style) {
+ node.setGap(src_default.GUTTER_COLUMN, style.columnGap ?? 0);
+ }
+ if ("rowGap" in style) {
+ node.setGap(src_default.GUTTER_ROW, style.rowGap ?? 0);
+ }
+}, "applyGapStyles");
+var styles3 = /* @__PURE__ */ __name((node, style = {}, currentStyle = style) => {
+ applyPositionStyles(node, style);
+ applyMarginStyles(node, style);
+ applyPaddingStyles(node, style);
+ applyFlexStyles(node, style);
+ applyDimensionStyles(node, style);
+ applyDisplayStyles(node, style);
+ applyBorderStyles(node, style, currentStyle);
+ applyGapStyles(node, style);
+}, "styles");
+var styles_default = styles3;
+
+// node_modules/ink/build/reconciler.js
+if (process4.env["DEV"] === "true") {
+ let isDevtoolsInstalled = false;
+ try {
+ import.meta.resolve("react-devtools-core");
+ isDevtoolsInstalled = true;
+ } catch {
+ }
+ if (isDevtoolsInstalled) {
+ await import("./chunks/devtools-V5WI5QLO.js");
+ }
+}
+var diff = /* @__PURE__ */ __name((before, after) => {
+ if (before === after) {
+ return;
+ }
+ if (!before) {
+ return after;
+ }
+ const changed = {};
+ let isChanged = false;
+ for (const key of Object.keys(before)) {
+ const isDeleted = after ? !Object.hasOwn(after, key) : true;
+ if (isDeleted) {
+ changed[key] = void 0;
+ isChanged = true;
+ }
+ }
+ if (after) {
+ for (const key of Object.keys(after)) {
+ if (after[key] !== before[key]) {
+ changed[key] = after[key];
+ isChanged = true;
+ }
+ }
+ }
+ return isChanged ? changed : void 0;
+}, "diff");
+var cleanupYogaNode = /* @__PURE__ */ __name((node) => {
+ node?.unsetMeasureFunc();
+ node?.freeRecursive();
+}, "cleanupYogaNode");
+var currentUpdatePriority = import_constants.NoEventPriority;
+var currentRootNode;
+async function loadPackageJson() {
+ const fs22 = await import("node:fs");
+ const content = fs22.readFileSync(new URL("../package.json", import.meta.url), "utf8");
+ const parsedContent = JSON.parse(content);
+ return {
+ name: parsedContent?.name,
+ version: parsedContent?.version
+ };
+}
+__name(loadPackageJson, "loadPackageJson");
+var packageInfo = {
+ name: "ink",
+ version: import_react.version
+};
+if (process4.env["DEV"] === "true") {
+ try {
+ const loaded = await loadPackageJson();
+ packageInfo = {
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
+ name: loaded.name || packageInfo.name,
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
+ version: loaded.version || packageInfo.version
+ };
+ } catch (error51) {
+ console.warn("Failed to load package.json in development mode. Falling back to default renderer metadata.", error51);
+ }
+}
+var reconciler_default = (0, import_react_reconciler.default)({
+ getRootHostContext: /* @__PURE__ */ __name(() => ({
+ isInsideText: false
+ }), "getRootHostContext"),
+ prepareForCommit: /* @__PURE__ */ __name(() => null, "prepareForCommit"),
+ preparePortalMount: /* @__PURE__ */ __name(() => null, "preparePortalMount"),
+ clearContainer: /* @__PURE__ */ __name(() => false, "clearContainer"),
+ resetAfterCommit(rootNode) {
+ if (typeof rootNode.onComputeLayout === "function") {
+ rootNode.onComputeLayout();
+ }
+ emitLayoutListeners(rootNode);
+ if (rootNode.staticNode !== rootNode.previousStaticNode) {
+ rootNode.previousStaticNode = rootNode.staticNode;
+ if (typeof rootNode.onStaticChange === "function") {
+ rootNode.onStaticChange();
+ }
+ }
+ if (rootNode.isStaticDirty) {
+ rootNode.isStaticDirty = false;
+ if (typeof rootNode.onImmediateRender === "function") {
+ rootNode.onImmediateRender();
+ }
+ return;
+ }
+ if (typeof rootNode.onRender === "function") {
+ rootNode.onRender();
+ }
+ },
+ getChildHostContext(parentHostContext, type2) {
+ const previousIsInsideText = parentHostContext.isInsideText;
+ const isInsideText = type2 === "ink-text" || type2 === "ink-virtual-text";
+ if (previousIsInsideText === isInsideText) {
+ return parentHostContext;
+ }
+ return { isInsideText };
+ },
+ shouldSetTextContent: /* @__PURE__ */ __name(() => false, "shouldSetTextContent"),
+ createInstance(originalType, newProps, rootNode, hostContext) {
+ if (hostContext.isInsideText && originalType === "ink-box") {
+ throw new Error(` can\u2019t be nested inside component`);
+ }
+ const type2 = originalType === "ink-text" && hostContext.isInsideText ? "ink-virtual-text" : originalType;
+ const node = createNode(type2);
+ for (const [key, value] of Object.entries(newProps)) {
+ if (key === "children") {
+ continue;
+ }
+ if (key === "style") {
+ setStyle(node, value);
+ if (node.yogaNode) {
+ styles_default(node.yogaNode, value);
+ }
+ continue;
+ }
+ if (key === "internal_transform") {
+ node.internal_transform = value;
+ continue;
+ }
+ if (key === "internal_static") {
+ currentRootNode = rootNode;
+ node.internal_static = true;
+ rootNode.isStaticDirty = true;
+ rootNode.staticNode = node;
+ continue;
+ }
+ setAttribute(node, key, value);
+ }
+ return node;
+ },
+ createTextInstance(text, _root, hostContext) {
+ if (!hostContext.isInsideText) {
+ throw new Error(`Text string "${text}" must be rendered inside component`);
+ }
+ return createTextNode(text);
+ },
+ resetTextContent() {
+ },
+ hideTextInstance(node) {
+ setTextNodeValue(node, "");
+ },
+ unhideTextInstance(node, text) {
+ setTextNodeValue(node, text);
+ },
+ getPublicInstance: /* @__PURE__ */ __name((instance) => instance, "getPublicInstance"),
+ hideInstance(node) {
+ node.yogaNode?.setDisplay(src_default.DISPLAY_NONE);
+ },
+ unhideInstance(node) {
+ node.yogaNode?.setDisplay(src_default.DISPLAY_FLEX);
+ },
+ appendInitialChild: appendChildNode,
+ appendChild: appendChildNode,
+ insertBefore: insertBeforeNode,
+ finalizeInitialChildren() {
+ return false;
+ },
+ isPrimaryRenderer: true,
+ supportsMutation: true,
+ supportsPersistence: false,
+ supportsHydration: false,
+ // Scheduler integration for concurrent mode
+ supportsMicrotasks: true,
+ scheduleMicrotask: queueMicrotask,
+ // @ts-expect-error @types/react-reconciler is outdated and doesn't include scheduleCallback
+ scheduleCallback: Scheduler.unstable_scheduleCallback,
+ cancelCallback: Scheduler.unstable_cancelCallback,
+ shouldYield: Scheduler.unstable_shouldYield,
+ now: Scheduler.unstable_now,
+ scheduleTimeout: setTimeout,
+ cancelTimeout: clearTimeout,
+ noTimeout: -1,
+ beforeActiveInstanceBlur() {
+ },
+ afterActiveInstanceBlur() {
+ },
+ detachDeletedInstance() {
+ },
+ getInstanceFromNode: /* @__PURE__ */ __name(() => null, "getInstanceFromNode"),
+ prepareScopeUpdate() {
+ },
+ getInstanceFromScope: /* @__PURE__ */ __name(() => null, "getInstanceFromScope"),
+ appendChildToContainer: appendChildNode,
+ insertInContainerBefore: insertBeforeNode,
+ removeChildFromContainer(node, removeNode) {
+ removeChildNode(node, removeNode);
+ cleanupYogaNode(removeNode.yogaNode);
+ if (removeNode.internal_static && currentRootNode?.staticNode === removeNode) {
+ currentRootNode.staticNode = void 0;
+ }
+ },
+ commitUpdate(node, _type, oldProps, newProps) {
+ if (currentRootNode && node.internal_static) {
+ currentRootNode.isStaticDirty = true;
+ }
+ const props = diff(oldProps, newProps);
+ const style = diff(oldProps["style"], newProps["style"]);
+ if (!props && !style) {
+ return;
+ }
+ if (props) {
+ for (const [key, value] of Object.entries(props)) {
+ if (key === "style") {
+ setStyle(node, value);
+ continue;
+ }
+ if (key === "internal_transform") {
+ node.internal_transform = value;
+ continue;
+ }
+ if (key === "internal_static") {
+ node.internal_static = true;
+ continue;
+ }
+ setAttribute(node, key, value);
+ }
+ }
+ if (style && node.yogaNode) {
+ styles_default(node.yogaNode, style, newProps["style"] ?? {});
+ }
+ },
+ commitTextUpdate(node, _oldText, newText) {
+ setTextNodeValue(node, newText);
+ },
+ removeChild(node, removeNode) {
+ removeChildNode(node, removeNode);
+ cleanupYogaNode(removeNode.yogaNode);
+ if (removeNode.internal_static && currentRootNode?.staticNode === removeNode) {
+ currentRootNode.staticNode = void 0;
+ }
+ },
+ setCurrentUpdatePriority(newPriority) {
+ currentUpdatePriority = newPriority;
+ },
+ getCurrentUpdatePriority: /* @__PURE__ */ __name(() => currentUpdatePriority, "getCurrentUpdatePriority"),
+ resolveUpdatePriority() {
+ if (currentUpdatePriority !== import_constants.NoEventPriority) {
+ return currentUpdatePriority;
+ }
+ return import_constants.DefaultEventPriority;
+ },
+ maySuspendCommit() {
+ return true;
+ },
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ NotPendingTransition: void 0,
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ HostTransitionContext: (0, import_react.createContext)(null),
+ resetFormInstance() {
+ },
+ requestPostPaintCallback() {
+ },
+ shouldAttemptEagerTransition() {
+ return false;
+ },
+ trackSchedulerEvent() {
+ },
+ resolveEventType() {
+ return null;
+ },
+ resolveEventTimeStamp() {
+ return -1.1;
+ },
+ preloadInstance() {
+ return true;
+ },
+ startSuspendingCommit() {
+ },
+ suspendInstance() {
+ },
+ waitForCommitToBeReady() {
+ return null;
+ },
+ rendererPackageName: packageInfo.name,
+ rendererVersion: packageInfo.version
+});
+
+// node_modules/ink/build/renderer.js
+init_esbuild_shims();
+
+// node_modules/ink/build/render-node-to-output.js
+init_esbuild_shims();
+
+// node_modules/indent-string/index.js
+init_esbuild_shims();
+function indentString(string4, count = 1, options2 = {}) {
+ const {
+ indent = " ",
+ includeEmptyLines = false
+ } = options2;
+ if (typeof string4 !== "string") {
+ throw new TypeError(
+ `Expected \`input\` to be a \`string\`, got \`${typeof string4}\``
+ );
+ }
+ if (typeof count !== "number") {
+ throw new TypeError(
+ `Expected \`count\` to be a \`number\`, got \`${typeof count}\``
+ );
+ }
+ if (count < 0) {
+ throw new RangeError(
+ `Expected \`count\` to be at least 0, got \`${count}\``
+ );
+ }
+ if (typeof indent !== "string") {
+ throw new TypeError(
+ `Expected \`options.indent\` to be a \`string\`, got \`${typeof indent}\``
+ );
+ }
+ if (count === 0) {
+ return string4;
+ }
+ const regex2 = includeEmptyLines ? /^/gm : /^(?!\s*$)/gm;
+ return string4.replace(regex2, indent.repeat(count));
+}
+__name(indentString, "indentString");
+
+// node_modules/ink/build/get-max-width.js
+init_esbuild_shims();
+var getMaxWidth = /* @__PURE__ */ __name((yogaNode) => {
+ return yogaNode.getComputedWidth() - yogaNode.getComputedPadding(src_default.EDGE_LEFT) - yogaNode.getComputedPadding(src_default.EDGE_RIGHT) - yogaNode.getComputedBorder(src_default.EDGE_LEFT) - yogaNode.getComputedBorder(src_default.EDGE_RIGHT);
+}, "getMaxWidth");
+var get_max_width_default = getMaxWidth;
+
+// node_modules/ink/build/render-border.js
+init_esbuild_shims();
+
+// node_modules/cli-boxes/index.js
+init_esbuild_shims();
+
+// node_modules/cli-boxes/boxes.json
+var boxes_default = {
+ single: {
+ topLeft: "\u250C",
+ top: "\u2500",
+ topRight: "\u2510",
+ right: "\u2502",
+ bottomRight: "\u2518",
+ bottom: "\u2500",
+ bottomLeft: "\u2514",
+ left: "\u2502"
+ },
+ double: {
+ topLeft: "\u2554",
+ top: "\u2550",
+ topRight: "\u2557",
+ right: "\u2551",
+ bottomRight: "\u255D",
+ bottom: "\u2550",
+ bottomLeft: "\u255A",
+ left: "\u2551"
+ },
+ round: {
+ topLeft: "\u256D",
+ top: "\u2500",
+ topRight: "\u256E",
+ right: "\u2502",
+ bottomRight: "\u256F",
+ bottom: "\u2500",
+ bottomLeft: "\u2570",
+ left: "\u2502"
+ },
+ bold: {
+ topLeft: "\u250F",
+ top: "\u2501",
+ topRight: "\u2513",
+ right: "\u2503",
+ bottomRight: "\u251B",
+ bottom: "\u2501",
+ bottomLeft: "\u2517",
+ left: "\u2503"
+ },
+ singleDouble: {
+ topLeft: "\u2553",
+ top: "\u2500",
+ topRight: "\u2556",
+ right: "\u2551",
+ bottomRight: "\u255C",
+ bottom: "\u2500",
+ bottomLeft: "\u2559",
+ left: "\u2551"
+ },
+ doubleSingle: {
+ topLeft: "\u2552",
+ top: "\u2550",
+ topRight: "\u2555",
+ right: "\u2502",
+ bottomRight: "\u255B",
+ bottom: "\u2550",
+ bottomLeft: "\u2558",
+ left: "\u2502"
+ },
+ classic: {
+ topLeft: "+",
+ top: "-",
+ topRight: "+",
+ right: "|",
+ bottomRight: "+",
+ bottom: "-",
+ bottomLeft: "+",
+ left: "|"
+ },
+ arrow: {
+ topLeft: "\u2198",
+ top: "\u2193",
+ topRight: "\u2199",
+ right: "\u2190",
+ bottomRight: "\u2196",
+ bottom: "\u2191",
+ bottomLeft: "\u2197",
+ left: "\u2192"
+ }
+};
+
+// node_modules/cli-boxes/index.js
+var cli_boxes_default = boxes_default;
+
+// node_modules/ink/node_modules/chalk/source/index.js
+init_esbuild_shims();
+
+// node_modules/ink/node_modules/chalk/source/vendor/ansi-styles/index.js
+init_esbuild_shims();
+var ANSI_BACKGROUND_OFFSET3 = 10;
+var wrapAnsi163 = /* @__PURE__ */ __name((offset = 0) => (code) => `\x1B[${code + offset}m`, "wrapAnsi16");
+var wrapAnsi2563 = /* @__PURE__ */ __name((offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`, "wrapAnsi256");
+var wrapAnsi16m3 = /* @__PURE__ */ __name((offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`, "wrapAnsi16m");
+var styles4 = {
+ 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],
+ overline: [53, 55],
+ 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],
+ gray: [90, 39],
+ // Alias of `blackBright`
+ grey: [90, 39],
+ // Alias of `blackBright`
+ 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],
+ bgGray: [100, 49],
+ // Alias of `bgBlackBright`
+ bgGrey: [100, 49],
+ // Alias of `bgBlackBright`
+ bgRedBright: [101, 49],
+ bgGreenBright: [102, 49],
+ bgYellowBright: [103, 49],
+ bgBlueBright: [104, 49],
+ bgMagentaBright: [105, 49],
+ bgCyanBright: [106, 49],
+ bgWhiteBright: [107, 49]
+ }
+};
+var modifierNames3 = Object.keys(styles4.modifier);
+var foregroundColorNames3 = Object.keys(styles4.color);
+var backgroundColorNames3 = Object.keys(styles4.bgColor);
+var colorNames3 = [...foregroundColorNames3, ...backgroundColorNames3];
+function assembleStyles3() {
+ const codes = /* @__PURE__ */ new Map();
+ for (const [groupName, group] of Object.entries(styles4)) {
+ for (const [styleName, style] of Object.entries(group)) {
+ styles4[styleName] = {
+ open: `\x1B[${style[0]}m`,
+ close: `\x1B[${style[1]}m`
+ };
+ group[styleName] = styles4[styleName];
+ codes.set(style[0], style[1]);
+ }
+ Object.defineProperty(styles4, groupName, {
+ value: group,
+ enumerable: false
+ });
+ }
+ Object.defineProperty(styles4, "codes", {
+ value: codes,
+ enumerable: false
+ });
+ styles4.color.close = "\x1B[39m";
+ styles4.bgColor.close = "\x1B[49m";
+ styles4.color.ansi = wrapAnsi163();
+ styles4.color.ansi256 = wrapAnsi2563();
+ styles4.color.ansi16m = wrapAnsi16m3();
+ styles4.bgColor.ansi = wrapAnsi163(ANSI_BACKGROUND_OFFSET3);
+ styles4.bgColor.ansi256 = wrapAnsi2563(ANSI_BACKGROUND_OFFSET3);
+ styles4.bgColor.ansi16m = wrapAnsi16m3(ANSI_BACKGROUND_OFFSET3);
+ Object.defineProperties(styles4, {
+ rgbToAnsi256: {
+ value(red, green, blue) {
+ if (red === green && green === blue) {
+ if (red < 8) {
+ return 16;
+ }
+ if (red > 248) {
+ return 231;
+ }
+ return Math.round((red - 8) / 247 * 24) + 232;
+ }
+ return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
+ },
+ enumerable: false
+ },
+ hexToRgb: {
+ value(hex3) {
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex3.toString(16));
+ if (!matches) {
+ return [0, 0, 0];
+ }
+ let [colorString] = matches;
+ if (colorString.length === 3) {
+ colorString = [...colorString].map((character) => character + character).join("");
+ }
+ const integer2 = Number.parseInt(colorString, 16);
+ return [
+ /* eslint-disable no-bitwise */
+ integer2 >> 16 & 255,
+ integer2 >> 8 & 255,
+ integer2 & 255
+ /* eslint-enable no-bitwise */
+ ];
+ },
+ enumerable: false
+ },
+ hexToAnsi256: {
+ value: /* @__PURE__ */ __name((hex3) => styles4.rgbToAnsi256(...styles4.hexToRgb(hex3)), "value"),
+ enumerable: false
+ },
+ ansi256ToAnsi: {
+ value(code) {
+ if (code < 8) {
+ return 30 + code;
+ }
+ if (code < 16) {
+ return 90 + (code - 8);
+ }
+ let red;
+ let green;
+ let blue;
+ if (code >= 232) {
+ red = ((code - 232) * 10 + 8) / 255;
+ green = red;
+ blue = red;
+ } else {
+ code -= 16;
+ const remainder = code % 36;
+ red = Math.floor(code / 36) / 5;
+ green = Math.floor(remainder / 6) / 5;
+ blue = remainder % 6 / 5;
+ }
+ const value = Math.max(red, green, blue) * 2;
+ if (value === 0) {
+ return 30;
+ }
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
+ if (value === 2) {
+ result += 60;
+ }
+ return result;
+ },
+ enumerable: false
+ },
+ rgbToAnsi: {
+ value: /* @__PURE__ */ __name((red, green, blue) => styles4.ansi256ToAnsi(styles4.rgbToAnsi256(red, green, blue)), "value"),
+ enumerable: false
+ },
+ hexToAnsi: {
+ value: /* @__PURE__ */ __name((hex3) => styles4.ansi256ToAnsi(styles4.hexToAnsi256(hex3)), "value"),
+ enumerable: false
+ }
+ });
+ return styles4;
+}
+__name(assembleStyles3, "assembleStyles");
+var ansiStyles3 = assembleStyles3();
+var ansi_styles_default3 = ansiStyles3;
+
+// node_modules/ink/node_modules/chalk/source/vendor/supports-color/index.js
+init_esbuild_shims();
+import process5 from "node:process";
+import os2 from "node:os";
+import tty2 from "node:tty";
+function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process5.argv) {
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
+ const position = argv.indexOf(prefix + flag);
+ const terminatorPosition = argv.indexOf("--");
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
+}
+__name(hasFlag, "hasFlag");
+var { env: env2 } = process5;
+var flagForceColor;
+if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
+ flagForceColor = 0;
+} else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
+ flagForceColor = 1;
+}
+function envForceColor() {
+ if ("FORCE_COLOR" in env2) {
+ if (env2.FORCE_COLOR === "true") {
+ return 1;
+ }
+ if (env2.FORCE_COLOR === "false") {
+ return 0;
+ }
+ return env2.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env2.FORCE_COLOR, 10), 3);
+ }
+}
+__name(envForceColor, "envForceColor");
+function translateLevel(level) {
+ if (level === 0) {
+ return false;
+ }
+ return {
+ level,
+ hasBasic: true,
+ has256: level >= 2,
+ has16m: level >= 3
+ };
+}
+__name(translateLevel, "translateLevel");
+function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
+ const noFlagForceColor = envForceColor();
+ if (noFlagForceColor !== void 0) {
+ flagForceColor = noFlagForceColor;
+ }
+ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
+ if (forceColor === 0) {
+ return 0;
+ }
+ if (sniffFlags) {
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
+ return 3;
+ }
+ if (hasFlag("color=256")) {
+ return 2;
+ }
+ }
+ if ("TF_BUILD" in env2 && "AGENT_NAME" in env2) {
+ return 1;
+ }
+ if (haveStream && !streamIsTTY && forceColor === void 0) {
+ return 0;
+ }
+ const min = forceColor || 0;
+ if (env2.TERM === "dumb") {
+ return min;
+ }
+ if (process5.platform === "win32") {
+ const osRelease = os2.release().split(".");
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
+ }
+ return 1;
+ }
+ if ("CI" in env2) {
+ if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => key in env2)) {
+ return 3;
+ }
+ if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env2) || env2.CI_NAME === "codeship") {
+ return 1;
+ }
+ return min;
+ }
+ if ("TEAMCITY_VERSION" in env2) {
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env2.TEAMCITY_VERSION) ? 1 : 0;
+ }
+ if (env2.COLORTERM === "truecolor") {
+ return 3;
+ }
+ if (env2.TERM === "xterm-kitty") {
+ return 3;
+ }
+ if (env2.TERM === "xterm-ghostty") {
+ return 3;
+ }
+ if (env2.TERM === "wezterm") {
+ return 3;
+ }
+ if ("TERM_PROGRAM" in env2) {
+ const version2 = Number.parseInt((env2.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
+ switch (env2.TERM_PROGRAM) {
+ case "iTerm.app": {
+ return version2 >= 3 ? 3 : 2;
+ }
+ case "Apple_Terminal": {
+ return 2;
+ }
+ }
+ }
+ if (/-256(color)?$/i.test(env2.TERM)) {
+ return 2;
+ }
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env2.TERM)) {
+ return 1;
+ }
+ if ("COLORTERM" in env2) {
+ return 1;
+ }
+ return min;
+}
+__name(_supportsColor, "_supportsColor");
+function createSupportsColor(stream, options2 = {}) {
+ const level = _supportsColor(stream, {
+ streamIsTTY: stream && stream.isTTY,
+ ...options2
+ });
+ return translateLevel(level);
+}
+__name(createSupportsColor, "createSupportsColor");
+var supportsColor = {
+ stdout: createSupportsColor({ isTTY: tty2.isatty(1) }),
+ stderr: createSupportsColor({ isTTY: tty2.isatty(2) })
+};
+var supports_color_default = supportsColor;
+
+// node_modules/ink/node_modules/chalk/source/utilities.js
+init_esbuild_shims();
+function stringReplaceAll(string4, substring, replacer) {
+ let index = string4.indexOf(substring);
+ if (index === -1) {
+ return string4;
+ }
+ const substringLength = substring.length;
+ let endIndex = 0;
+ let returnValue = "";
+ do {
+ returnValue += string4.slice(endIndex, index) + substring + replacer;
+ endIndex = index + substringLength;
+ index = string4.indexOf(substring, endIndex);
+ } while (index !== -1);
+ returnValue += string4.slice(endIndex);
+ return returnValue;
+}
+__name(stringReplaceAll, "stringReplaceAll");
+function stringEncaseCRLFWithFirstIndex(string4, prefix, postfix, index) {
+ let endIndex = 0;
+ let returnValue = "";
+ do {
+ const gotCR = string4[index - 1] === "\r";
+ returnValue += string4.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
+ endIndex = index + 1;
+ index = string4.indexOf("\n", endIndex);
+ } while (index !== -1);
+ returnValue += string4.slice(endIndex);
+ return returnValue;
+}
+__name(stringEncaseCRLFWithFirstIndex, "stringEncaseCRLFWithFirstIndex");
+
+// node_modules/ink/node_modules/chalk/source/index.js
+var { stdout: stdoutColor, stderr: stderrColor } = supports_color_default;
+var GENERATOR = /* @__PURE__ */ Symbol("GENERATOR");
+var STYLER = /* @__PURE__ */ Symbol("STYLER");
+var IS_EMPTY = /* @__PURE__ */ Symbol("IS_EMPTY");
+var levelMapping = [
+ "ansi",
+ "ansi",
+ "ansi256",
+ "ansi16m"
+];
+var styles5 = /* @__PURE__ */ Object.create(null);
+var applyOptions = /* @__PURE__ */ __name((object2, options2 = {}) => {
+ if (options2.level && !(Number.isInteger(options2.level) && options2.level >= 0 && options2.level <= 3)) {
+ throw new Error("The `level` option should be an integer from 0 to 3");
+ }
+ const colorLevel = stdoutColor ? stdoutColor.level : 0;
+ object2.level = options2.level === void 0 ? colorLevel : options2.level;
+}, "applyOptions");
+var chalkFactory = /* @__PURE__ */ __name((options2) => {
+ const chalk4 = /* @__PURE__ */ __name((...strings) => strings.join(" "), "chalk");
+ applyOptions(chalk4, options2);
+ Object.setPrototypeOf(chalk4, createChalk.prototype);
+ return chalk4;
+}, "chalkFactory");
+function createChalk(options2) {
+ return chalkFactory(options2);
+}
+__name(createChalk, "createChalk");
+Object.setPrototypeOf(createChalk.prototype, Function.prototype);
+for (const [styleName, style] of Object.entries(ansi_styles_default3)) {
+ styles5[styleName] = {
+ get() {
+ const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
+ Object.defineProperty(this, styleName, { value: builder });
+ return builder;
+ }
+ };
+}
+styles5.visible = {
+ get() {
+ const builder = createBuilder(this, this[STYLER], true);
+ Object.defineProperty(this, "visible", { value: builder });
+ return builder;
+ }
+};
+var getModelAnsi = /* @__PURE__ */ __name((model, level, type2, ...arguments_) => {
+ if (model === "rgb") {
+ if (level === "ansi16m") {
+ return ansi_styles_default3[type2].ansi16m(...arguments_);
+ }
+ if (level === "ansi256") {
+ return ansi_styles_default3[type2].ansi256(ansi_styles_default3.rgbToAnsi256(...arguments_));
+ }
+ return ansi_styles_default3[type2].ansi(ansi_styles_default3.rgbToAnsi(...arguments_));
+ }
+ if (model === "hex") {
+ return getModelAnsi("rgb", level, type2, ...ansi_styles_default3.hexToRgb(...arguments_));
+ }
+ return ansi_styles_default3[type2][model](...arguments_);
+}, "getModelAnsi");
+var usedModels = ["rgb", "hex", "ansi256"];
+for (const model of usedModels) {
+ styles5[model] = {
+ get() {
+ const { level } = this;
+ return function(...arguments_) {
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default3.color.close, this[STYLER]);
+ return createBuilder(this, styler, this[IS_EMPTY]);
+ };
+ }
+ };
+ const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
+ styles5[bgModel] = {
+ get() {
+ const { level } = this;
+ return function(...arguments_) {
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default3.bgColor.close, this[STYLER]);
+ return createBuilder(this, styler, this[IS_EMPTY]);
+ };
+ }
+ };
+}
+var proto = Object.defineProperties(() => {
+}, {
+ ...styles5,
+ level: {
+ enumerable: true,
+ get() {
+ return this[GENERATOR].level;
+ },
+ set(level) {
+ this[GENERATOR].level = level;
+ }
+ }
+});
+var createStyler = /* @__PURE__ */ __name((open, close, parent) => {
+ let openAll;
+ let closeAll;
+ if (parent === void 0) {
+ openAll = open;
+ closeAll = close;
+ } else {
+ openAll = parent.openAll + open;
+ closeAll = close + parent.closeAll;
+ }
+ return {
+ open,
+ close,
+ openAll,
+ closeAll,
+ parent
+ };
+}, "createStyler");
+var createBuilder = /* @__PURE__ */ __name((self2, _styler, _isEmpty) => {
+ const builder = /* @__PURE__ */ __name((...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" ")), "builder");
+ Object.setPrototypeOf(builder, proto);
+ builder[GENERATOR] = self2;
+ builder[STYLER] = _styler;
+ builder[IS_EMPTY] = _isEmpty;
+ return builder;
+}, "createBuilder");
+var applyStyle = /* @__PURE__ */ __name((self2, string4) => {
+ if (self2.level <= 0 || !string4) {
+ return self2[IS_EMPTY] ? "" : string4;
+ }
+ let styler = self2[STYLER];
+ if (styler === void 0) {
+ return string4;
+ }
+ const { openAll, closeAll } = styler;
+ if (string4.includes("\x1B")) {
+ while (styler !== void 0) {
+ string4 = stringReplaceAll(string4, styler.close, styler.open);
+ styler = styler.parent;
+ }
+ }
+ const lfIndex = string4.indexOf("\n");
+ if (lfIndex !== -1) {
+ string4 = stringEncaseCRLFWithFirstIndex(string4, closeAll, openAll, lfIndex);
+ }
+ return openAll + string4 + closeAll;
+}, "applyStyle");
+Object.defineProperties(createChalk.prototype, styles5);
+var chalk = createChalk();
+var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
+var source_default = chalk;
+
+// node_modules/ink/build/colorize.js
+init_esbuild_shims();
+var rgbRegex = /^rgb\(\s?(\d+),\s?(\d+),\s?(\d+)\s?\)$/;
+var ansiRegex2 = /^ansi256\(\s?(\d+)\s?\)$/;
+var isNamedColor = /* @__PURE__ */ __name((color) => {
+ return color in source_default;
+}, "isNamedColor");
+var colorize = /* @__PURE__ */ __name((str3, color, type2) => {
+ if (!color) {
+ return str3;
+ }
+ if (isNamedColor(color)) {
+ if (type2 === "foreground") {
+ return source_default[color](str3);
+ }
+ const methodName = `bg${color[0].toUpperCase() + color.slice(1)}`;
+ return source_default[methodName](str3);
+ }
+ if (color.startsWith("#")) {
+ return type2 === "foreground" ? source_default.hex(color)(str3) : source_default.bgHex(color)(str3);
+ }
+ if (color.startsWith("ansi256")) {
+ const matches = ansiRegex2.exec(color);
+ if (!matches) {
+ return str3;
+ }
+ const value = Number(matches[1]);
+ return type2 === "foreground" ? source_default.ansi256(value)(str3) : source_default.bgAnsi256(value)(str3);
+ }
+ if (color.startsWith("rgb")) {
+ const matches = rgbRegex.exec(color);
+ if (!matches) {
+ return str3;
+ }
+ const firstValue = Number(matches[1]);
+ const secondValue = Number(matches[2]);
+ const thirdValue = Number(matches[3]);
+ return type2 === "foreground" ? source_default.rgb(firstValue, secondValue, thirdValue)(str3) : source_default.bgRgb(firstValue, secondValue, thirdValue)(str3);
+ }
+ return str3;
+}, "colorize");
+var colorize_default = colorize;
+
+// node_modules/ink/build/render-border.js
+var stylePiece = /* @__PURE__ */ __name((segment, fg, bg, dim) => {
+ let styled = colorize_default(segment, fg, "foreground");
+ styled = colorize_default(styled, bg, "background");
+ if (dim) {
+ styled = source_default.dim(styled);
+ }
+ return styled;
+}, "stylePiece");
+var renderBorder = /* @__PURE__ */ __name((x, y, node, output) => {
+ if (node.style.borderStyle) {
+ const width = node.yogaNode.getComputedWidth();
+ const height = node.yogaNode.getComputedHeight();
+ const box = typeof node.style.borderStyle === "string" ? cli_boxes_default[node.style.borderStyle] : node.style.borderStyle;
+ const topBorderColor = node.style.borderTopColor ?? node.style.borderColor;
+ const bottomBorderColor = node.style.borderBottomColor ?? node.style.borderColor;
+ const leftBorderColor = node.style.borderLeftColor ?? node.style.borderColor;
+ const rightBorderColor = node.style.borderRightColor ?? node.style.borderColor;
+ const topBorderBackgroundColor = node.style.borderTopBackgroundColor ?? node.style.borderBackgroundColor;
+ const bottomBorderBackgroundColor = node.style.borderBottomBackgroundColor ?? node.style.borderBackgroundColor;
+ const leftBorderBackgroundColor = node.style.borderLeftBackgroundColor ?? node.style.borderBackgroundColor;
+ const rightBorderBackgroundColor = node.style.borderRightBackgroundColor ?? node.style.borderBackgroundColor;
+ const dimTopBorderColor = node.style.borderTopDimColor ?? node.style.borderDimColor;
+ const dimBottomBorderColor = node.style.borderBottomDimColor ?? node.style.borderDimColor;
+ const dimLeftBorderColor = node.style.borderLeftDimColor ?? node.style.borderDimColor;
+ const dimRightBorderColor = node.style.borderRightDimColor ?? node.style.borderDimColor;
+ const showTopBorder = node.style.borderTop !== false;
+ const showBottomBorder = node.style.borderBottom !== false;
+ const showLeftBorder = node.style.borderLeft !== false;
+ const showRightBorder = node.style.borderRight !== false;
+ const contentWidth = width - (showLeftBorder ? 1 : 0) - (showRightBorder ? 1 : 0);
+ let topBorder = showTopBorder ? (showLeftBorder ? box.topLeft : "") + box.top.repeat(contentWidth) + (showRightBorder ? box.topRight : "") : void 0;
+ topBorder &&= stylePiece(topBorder, topBorderColor, topBorderBackgroundColor, dimTopBorderColor);
+ let verticalBorderHeight = height;
+ if (showTopBorder) {
+ verticalBorderHeight -= 1;
+ }
+ if (showBottomBorder) {
+ verticalBorderHeight -= 1;
+ }
+ let leftBorder = "";
+ if (showLeftBorder) {
+ const one = stylePiece(box.left, leftBorderColor, leftBorderBackgroundColor, dimLeftBorderColor);
+ leftBorder = (one + "\n").repeat(verticalBorderHeight);
+ }
+ let rightBorder = "";
+ if (showRightBorder) {
+ const one = stylePiece(box.right, rightBorderColor, rightBorderBackgroundColor, dimRightBorderColor);
+ rightBorder = (one + "\n").repeat(verticalBorderHeight);
+ }
+ let bottomBorder = showBottomBorder ? (showLeftBorder ? box.bottomLeft : "") + box.bottom.repeat(contentWidth) + (showRightBorder ? box.bottomRight : "") : void 0;
+ bottomBorder &&= stylePiece(bottomBorder, bottomBorderColor, bottomBorderBackgroundColor, dimBottomBorderColor);
+ const offsetY = showTopBorder ? 1 : 0;
+ if (topBorder) {
+ output.write(x, y, topBorder, { transformers: [] });
+ }
+ if (leftBorder) {
+ output.write(x, y + offsetY, leftBorder, { transformers: [] });
+ }
+ if (rightBorder) {
+ output.write(x + width - 1, y + offsetY, rightBorder, {
+ transformers: []
+ });
+ }
+ if (bottomBorder) {
+ output.write(x, y + height - 1, bottomBorder, { transformers: [] });
+ }
+ }
+}, "renderBorder");
+var render_border_default = renderBorder;
+
+// node_modules/ink/build/render-background.js
+init_esbuild_shims();
+var renderBackground = /* @__PURE__ */ __name((x, y, node, output) => {
+ if (!node.style.backgroundColor) {
+ return;
+ }
+ const width = node.yogaNode.getComputedWidth();
+ const height = node.yogaNode.getComputedHeight();
+ const leftBorderWidth = node.style.borderStyle && node.style.borderLeft !== false ? 1 : 0;
+ const rightBorderWidth = node.style.borderStyle && node.style.borderRight !== false ? 1 : 0;
+ const topBorderHeight = node.style.borderStyle && node.style.borderTop !== false ? 1 : 0;
+ const bottomBorderHeight = node.style.borderStyle && node.style.borderBottom !== false ? 1 : 0;
+ const contentWidth = width - leftBorderWidth - rightBorderWidth;
+ const contentHeight = height - topBorderHeight - bottomBorderHeight;
+ if (!(contentWidth > 0 && contentHeight > 0)) {
+ return;
+ }
+ const backgroundLine = colorize_default(" ".repeat(contentWidth), node.style.backgroundColor, "background");
+ for (let row = 0; row < contentHeight; row++) {
+ output.write(x + leftBorderWidth, y + topBorderHeight + row, backgroundLine, { transformers: [] });
+ }
+}, "renderBackground");
+var render_background_default = renderBackground;
+
+// node_modules/ink/build/render-node-to-output.js
+var applyPaddingToText = /* @__PURE__ */ __name((node, text) => {
+ const yogaNode = node.childNodes[0]?.yogaNode;
+ if (yogaNode) {
+ const offsetX = yogaNode.getComputedLeft();
+ const offsetY = yogaNode.getComputedTop();
+ text = "\n".repeat(offsetY) + indentString(text, offsetX);
+ }
+ return text;
+}, "applyPaddingToText");
+var renderNodeToScreenReaderOutput = /* @__PURE__ */ __name((node, options2 = {}) => {
+ if (options2.skipStaticElements && node.internal_static) {
+ return "";
+ }
+ if (node.yogaNode?.getDisplay() === src_default.DISPLAY_NONE) {
+ return "";
+ }
+ let output = "";
+ if (node.nodeName === "ink-text") {
+ output = squash_text_nodes_default(node);
+ } else if (node.nodeName === "ink-box" || node.nodeName === "ink-root") {
+ const separator = node.style.flexDirection === "row" || node.style.flexDirection === "row-reverse" ? " " : "\n";
+ const childNodes = node.style.flexDirection === "row-reverse" || node.style.flexDirection === "column-reverse" ? [...node.childNodes].reverse() : [...node.childNodes];
+ output = childNodes.map((childNode) => {
+ const screenReaderOutput = renderNodeToScreenReaderOutput(childNode, {
+ parentRole: node.internal_accessibility?.role,
+ skipStaticElements: options2.skipStaticElements
+ });
+ return screenReaderOutput;
+ }).filter(Boolean).join(separator);
+ }
+ if (node.internal_accessibility) {
+ const { role, state } = node.internal_accessibility;
+ if (state) {
+ const stateKeys = Object.keys(state);
+ const stateDescription = stateKeys.filter((key) => state[key]).join(", ");
+ if (stateDescription) {
+ output = `(${stateDescription}) ${output}`;
+ }
+ }
+ if (role && role !== options2.parentRole) {
+ output = `${role}: ${output}`;
+ }
+ }
+ return output;
+}, "renderNodeToScreenReaderOutput");
+var renderNodeToOutput = /* @__PURE__ */ __name((node, output, options2) => {
+ const { offsetX = 0, offsetY = 0, transformers = [], skipStaticElements } = options2;
+ if (skipStaticElements && node.internal_static) {
+ return;
+ }
+ const { yogaNode } = node;
+ if (yogaNode) {
+ if (yogaNode.getDisplay() === src_default.DISPLAY_NONE) {
+ return;
+ }
+ const x = offsetX + yogaNode.getComputedLeft();
+ const y = offsetY + yogaNode.getComputedTop();
+ let newTransformers = transformers;
+ if (typeof node.internal_transform === "function") {
+ newTransformers = [node.internal_transform, ...transformers];
+ }
+ if (node.nodeName === "ink-text") {
+ let text = squash_text_nodes_default(node);
+ if (text.length > 0) {
+ const currentWidth = widestLine(text);
+ const maxWidth = get_max_width_default(yogaNode);
+ if (currentWidth > maxWidth) {
+ const textWrap = node.style.textWrap ?? "wrap";
+ text = wrap_text_default(text, maxWidth, textWrap);
+ }
+ text = applyPaddingToText(node, text);
+ output.write(x, y, text, { transformers: newTransformers });
+ }
+ return;
+ }
+ let clipped = false;
+ if (node.nodeName === "ink-box") {
+ render_background_default(x, y, node, output);
+ render_border_default(x, y, node, output);
+ const clipHorizontally = node.style.overflowX === "hidden" || node.style.overflow === "hidden";
+ const clipVertically = node.style.overflowY === "hidden" || node.style.overflow === "hidden";
+ if (clipHorizontally || clipVertically) {
+ const x1 = clipHorizontally ? x + yogaNode.getComputedBorder(src_default.EDGE_LEFT) : void 0;
+ const x2 = clipHorizontally ? x + yogaNode.getComputedWidth() - yogaNode.getComputedBorder(src_default.EDGE_RIGHT) : void 0;
+ const y1 = clipVertically ? y + yogaNode.getComputedBorder(src_default.EDGE_TOP) : void 0;
+ const y2 = clipVertically ? y + yogaNode.getComputedHeight() - yogaNode.getComputedBorder(src_default.EDGE_BOTTOM) : void 0;
+ output.clip({ x1, x2, y1, y2 });
+ clipped = true;
+ }
+ }
+ if (node.nodeName === "ink-root" || node.nodeName === "ink-box") {
+ for (const childNode of node.childNodes) {
+ renderNodeToOutput(childNode, output, {
+ offsetX: x,
+ offsetY: y,
+ transformers: newTransformers,
+ skipStaticElements
+ });
+ }
+ if (clipped) {
+ output.unclip();
+ }
+ }
+ }
+}, "renderNodeToOutput");
+var render_node_to_output_default = renderNodeToOutput;
+
+// node_modules/ink/build/output.js
+init_esbuild_shims();
+
+// node_modules/@alcalzone/ansi-tokenize/build/index.js
+init_esbuild_shims();
+
+// node_modules/@alcalzone/ansi-tokenize/build/ansiCodes.js
+init_esbuild_shims();
+
+// node_modules/@alcalzone/ansi-tokenize/node_modules/ansi-styles/index.js
+init_esbuild_shims();
+var ANSI_BACKGROUND_OFFSET4 = 10;
+var wrapAnsi164 = /* @__PURE__ */ __name((offset = 0) => (code) => `\x1B[${code + offset}m`, "wrapAnsi16");
+var wrapAnsi2564 = /* @__PURE__ */ __name((offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`, "wrapAnsi256");
+var wrapAnsi16m4 = /* @__PURE__ */ __name((offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`, "wrapAnsi16m");
+var styles6 = {
+ 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],
+ overline: [53, 55],
+ 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],
+ gray: [90, 39],
+ // Alias of `blackBright`
+ grey: [90, 39],
+ // Alias of `blackBright`
+ 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],
+ bgGray: [100, 49],
+ // Alias of `bgBlackBright`
+ bgGrey: [100, 49],
+ // Alias of `bgBlackBright`
+ bgRedBright: [101, 49],
+ bgGreenBright: [102, 49],
+ bgYellowBright: [103, 49],
+ bgBlueBright: [104, 49],
+ bgMagentaBright: [105, 49],
+ bgCyanBright: [106, 49],
+ bgWhiteBright: [107, 49]
+ }
+};
+var modifierNames4 = Object.keys(styles6.modifier);
+var foregroundColorNames4 = Object.keys(styles6.color);
+var backgroundColorNames4 = Object.keys(styles6.bgColor);
+var colorNames4 = [...foregroundColorNames4, ...backgroundColorNames4];
+function assembleStyles4() {
+ const codes = /* @__PURE__ */ new Map();
+ for (const [groupName, group] of Object.entries(styles6)) {
+ for (const [styleName, style] of Object.entries(group)) {
+ styles6[styleName] = {
+ open: `\x1B[${style[0]}m`,
+ close: `\x1B[${style[1]}m`
+ };
+ group[styleName] = styles6[styleName];
+ codes.set(style[0], style[1]);
+ }
+ Object.defineProperty(styles6, groupName, {
+ value: group,
+ enumerable: false
+ });
+ }
+ Object.defineProperty(styles6, "codes", {
+ value: codes,
+ enumerable: false
+ });
+ styles6.color.close = "\x1B[39m";
+ styles6.bgColor.close = "\x1B[49m";
+ styles6.color.ansi = wrapAnsi164();
+ styles6.color.ansi256 = wrapAnsi2564();
+ styles6.color.ansi16m = wrapAnsi16m4();
+ styles6.bgColor.ansi = wrapAnsi164(ANSI_BACKGROUND_OFFSET4);
+ styles6.bgColor.ansi256 = wrapAnsi2564(ANSI_BACKGROUND_OFFSET4);
+ styles6.bgColor.ansi16m = wrapAnsi16m4(ANSI_BACKGROUND_OFFSET4);
+ Object.defineProperties(styles6, {
+ rgbToAnsi256: {
+ value(red, green, blue) {
+ if (red === green && green === blue) {
+ if (red < 8) {
+ return 16;
+ }
+ if (red > 248) {
+ return 231;
+ }
+ return Math.round((red - 8) / 247 * 24) + 232;
+ }
+ return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
+ },
+ enumerable: false
+ },
+ hexToRgb: {
+ value(hex3) {
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex3.toString(16));
+ if (!matches) {
+ return [0, 0, 0];
+ }
+ let [colorString] = matches;
+ if (colorString.length === 3) {
+ colorString = [...colorString].map((character) => character + character).join("");
+ }
+ const integer2 = Number.parseInt(colorString, 16);
+ return [
+ /* eslint-disable no-bitwise */
+ integer2 >> 16 & 255,
+ integer2 >> 8 & 255,
+ integer2 & 255
+ /* eslint-enable no-bitwise */
+ ];
+ },
+ enumerable: false
+ },
+ hexToAnsi256: {
+ value: /* @__PURE__ */ __name((hex3) => styles6.rgbToAnsi256(...styles6.hexToRgb(hex3)), "value"),
+ enumerable: false
+ },
+ ansi256ToAnsi: {
+ value(code) {
+ if (code < 8) {
+ return 30 + code;
+ }
+ if (code < 16) {
+ return 90 + (code - 8);
+ }
+ let red;
+ let green;
+ let blue;
+ if (code >= 232) {
+ red = ((code - 232) * 10 + 8) / 255;
+ green = red;
+ blue = red;
+ } else {
+ code -= 16;
+ const remainder = code % 36;
+ red = Math.floor(code / 36) / 5;
+ green = Math.floor(remainder / 6) / 5;
+ blue = remainder % 6 / 5;
+ }
+ const value = Math.max(red, green, blue) * 2;
+ if (value === 0) {
+ return 30;
+ }
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
+ if (value === 2) {
+ result += 60;
+ }
+ return result;
+ },
+ enumerable: false
+ },
+ rgbToAnsi: {
+ value: /* @__PURE__ */ __name((red, green, blue) => styles6.ansi256ToAnsi(styles6.rgbToAnsi256(red, green, blue)), "value"),
+ enumerable: false
+ },
+ hexToAnsi: {
+ value: /* @__PURE__ */ __name((hex3) => styles6.ansi256ToAnsi(styles6.hexToAnsi256(hex3)), "value"),
+ enumerable: false
+ }
+ });
+ return styles6;
+}
+__name(assembleStyles4, "assembleStyles");
+var ansiStyles4 = assembleStyles4();
+var ansi_styles_default4 = ansiStyles4;
+
+// node_modules/@alcalzone/ansi-tokenize/build/consts.js
+init_esbuild_shims();
+var BEL2 = "\x07";
+var ESC2 = "\x1B";
+var BACKSLASH = "\\";
+var CSI = "[";
+var OSC2 = "]";
+var C1_ST = "\x9C";
+var CC_BEL = BEL2.charCodeAt(0);
+var CC_ESC = ESC2.charCodeAt(0);
+var CC_BACKSLASH = BACKSLASH.charCodeAt(0);
+var CC_CSI = CSI.charCodeAt(0);
+var CC_OSC = OSC2.charCodeAt(0);
+var CC_C1_ST = C1_ST.charCodeAt(0);
+var CC_0 = "0".charCodeAt(0);
+var CC_9 = "9".charCodeAt(0);
+var CC_SEMI = ";".charCodeAt(0);
+var CC_M = "m".charCodeAt(0);
+var ESCAPES3 = /* @__PURE__ */ new Set([CC_ESC, 155]);
+var linkCodePrefix = `${ESC2}${OSC2}8;`;
+var linkCodePrefixCharCodes = linkCodePrefix.split("").map((char) => char.charCodeAt(0));
+var linkEndCode = `${ESC2}${OSC2}8;;${BEL2}`;
+var linkEndCodeST = `${ESC2}${OSC2}8;;${ESC2}${BACKSLASH}`;
+var linkEndCodeC1ST = `${ESC2}${OSC2}8;;${C1_ST}`;
+
+// node_modules/@alcalzone/ansi-tokenize/build/ansiCodes.js
+var endCodesSet = /* @__PURE__ */ new Set();
+var endCodesMap = /* @__PURE__ */ new Map();
+for (const [start, end] of ansi_styles_default4.codes) {
+ endCodesSet.add(ansi_styles_default4.color.ansi(end));
+ endCodesMap.set(ansi_styles_default4.color.ansi(start), ansi_styles_default4.color.ansi(end));
+}
+function getEndCode(code) {
+ if (endCodesSet.has(code))
+ return code;
+ if (endCodesMap.has(code))
+ return endCodesMap.get(code);
+ if (code.startsWith(linkCodePrefix)) {
+ if (code.endsWith("\x1B\\"))
+ return linkEndCodeST;
+ if (code.endsWith("\x9C"))
+ return linkEndCodeC1ST;
+ return linkEndCode;
+ }
+ code = code.slice(2);
+ if (code.startsWith("38")) {
+ return ansi_styles_default4.color.close;
+ } else if (code.startsWith("48")) {
+ return ansi_styles_default4.bgColor.close;
+ }
+ const ret = ansi_styles_default4.codes.get(parseInt(code, 10));
+ if (ret) {
+ return ansi_styles_default4.color.ansi(ret);
+ } else {
+ return ansi_styles_default4.reset.open;
+ }
+}
+__name(getEndCode, "getEndCode");
+function ansiCodesToString(codes) {
+ const deduplicated = new Set(codes.map((code) => code.code));
+ return [...deduplicated].join("");
+}
+__name(ansiCodesToString, "ansiCodesToString");
+function isIntensityCode(code) {
+ return code.code === ansi_styles_default4.bold.open || code.code === ansi_styles_default4.dim.open;
+}
+__name(isIntensityCode, "isIntensityCode");
+
+// node_modules/@alcalzone/ansi-tokenize/build/diff.js
+init_esbuild_shims();
+
+// node_modules/@alcalzone/ansi-tokenize/build/undo.js
+init_esbuild_shims();
+
+// node_modules/@alcalzone/ansi-tokenize/build/reduce.js
+init_esbuild_shims();
+function reduceAnsiCodes(codes) {
+ return reduceAnsiCodesIncremental([], codes);
+}
+__name(reduceAnsiCodes, "reduceAnsiCodes");
+function reduceAnsiCodesIncremental(codes, newCodes) {
+ let ret = [...codes];
+ for (const code of newCodes) {
+ if (code.code === ansi_styles_default4.reset.open) {
+ ret = [];
+ } else if (endCodesSet.has(code.code)) {
+ ret = ret.filter((retCode) => retCode.endCode !== code.code);
+ } else {
+ if (isIntensityCode(code)) {
+ if (!ret.find((retCode) => retCode.code === code.code && retCode.endCode === code.endCode)) {
+ ret.push(code);
+ }
+ } else {
+ ret = ret.filter((retCode) => retCode.endCode !== code.endCode);
+ ret.push(code);
+ }
+ }
+ }
+ return ret;
+}
+__name(reduceAnsiCodesIncremental, "reduceAnsiCodesIncremental");
+
+// node_modules/@alcalzone/ansi-tokenize/build/undo.js
+function undoAnsiCodes2(codes) {
+ return reduceAnsiCodes(codes).reverse().map((code) => ({
+ ...code,
+ code: code.endCode
+ }));
+}
+__name(undoAnsiCodes2, "undoAnsiCodes");
+
+// node_modules/@alcalzone/ansi-tokenize/build/diff.js
+function diffAnsiCodes(from, to) {
+ const endCodesInTo = new Set(to.map((code) => code.endCode));
+ const startCodesInTo = new Set(to.map((code) => code.code));
+ const startCodesInFrom = new Set(from.map((code) => code.code));
+ return [
+ // Ignore all styles in `from` that are not overwritten or removed by `to`
+ // Disable all styles in `from` that are removed in `to`
+ ...undoAnsiCodes2(from.filter((code) => {
+ if (isIntensityCode(code)) {
+ return !startCodesInTo.has(code.code);
+ }
+ return !endCodesInTo.has(code.endCode);
+ })),
+ // Add all styles in `to` that don't exist in `from`
+ ...to.filter((code) => !startCodesInFrom.has(code.code))
+ ];
+}
+__name(diffAnsiCodes, "diffAnsiCodes");
+
+// node_modules/@alcalzone/ansi-tokenize/build/styledChars.js
+init_esbuild_shims();
+function styledCharsFromTokens(tokens) {
+ let codes = [];
+ const ret = [];
+ for (const token of tokens) {
+ if (token.type === "ansi") {
+ codes = reduceAnsiCodesIncremental(codes, [token]);
+ } else if (token.type === "char") {
+ ret.push({
+ ...token,
+ styles: [...codes]
+ });
+ }
+ }
+ return ret;
+}
+__name(styledCharsFromTokens, "styledCharsFromTokens");
+function styledCharsToString(chars) {
+ let ret = "";
+ for (let i = 0; i < chars.length; i++) {
+ const char = chars[i];
+ if (i === 0) {
+ ret += ansiCodesToString(char.styles);
+ } else {
+ ret += ansiCodesToString(diffAnsiCodes(chars[i - 1].styles, char.styles));
+ }
+ ret += char.value;
+ if (i === chars.length - 1) {
+ ret += ansiCodesToString(diffAnsiCodes(char.styles, []));
+ }
+ }
+ return ret;
+}
+__name(styledCharsToString, "styledCharsToString");
+
+// node_modules/@alcalzone/ansi-tokenize/build/tokenize.js
+init_esbuild_shims();
+var segmenter3 = new Intl.Segmenter(void 0, { granularity: "grapheme" });
+function isFullwidthGrapheme(grapheme, baseCodePoint) {
+ if (isFullwidthCodePoint(baseCodePoint))
+ return true;
+ if (grapheme.includes("\uFE0F"))
+ return true;
+ if (baseCodePoint >= 127462 && baseCodePoint <= 127487)
+ return true;
+ return false;
+}
+__name(isFullwidthGrapheme, "isFullwidthGrapheme");
+function parseLinkCode(string4, offset) {
+ string4 = string4.slice(offset);
+ for (let index = 1; index < linkCodePrefixCharCodes.length; index++) {
+ if (string4.charCodeAt(index) !== linkCodePrefixCharCodes[index]) {
+ return void 0;
+ }
+ }
+ const paramsEndIndex = string4.indexOf(";", linkCodePrefix.length);
+ if (paramsEndIndex === -1)
+ return void 0;
+ const endIndex = findOSCTerminatorIndex(string4, paramsEndIndex + 1);
+ if (endIndex === -1)
+ return void 0;
+ return string4.slice(0, endIndex + 1);
+}
+__name(parseLinkCode, "parseLinkCode");
+function parseOSCSequence(string4, offset) {
+ string4 = string4.slice(offset);
+ const endIndex = findOSCTerminatorIndex(string4, 2);
+ if (endIndex === -1)
+ return void 0;
+ return string4.slice(0, endIndex + 1);
+}
+__name(parseOSCSequence, "parseOSCSequence");
+function findOSCTerminatorIndex(string4, startIndex) {
+ for (let i = startIndex; i < string4.length; i++) {
+ const ch = string4.charCodeAt(i);
+ if (ch === CC_BEL)
+ return i;
+ if (ch === CC_C1_ST)
+ return i;
+ if (ch === CC_ESC && i + 1 < string4.length && string4.charCodeAt(i + 1) === CC_BACKSLASH) {
+ return i + 1;
+ }
+ }
+ return -1;
+}
+__name(findOSCTerminatorIndex, "findOSCTerminatorIndex");
+function findSGRSequenceEndIndex(str3) {
+ for (let index = 2; index < str3.length; index++) {
+ const charCode = str3.charCodeAt(index);
+ if (charCode === CC_M)
+ return index;
+ if (charCode === CC_SEMI)
+ continue;
+ if (charCode >= CC_0 && charCode <= CC_9)
+ continue;
+ break;
+ }
+ return -1;
+}
+__name(findSGRSequenceEndIndex, "findSGRSequenceEndIndex");
+function parseSGRSequence(string4, offset) {
+ string4 = string4.slice(offset);
+ const endIndex = findSGRSequenceEndIndex(string4);
+ if (endIndex === -1)
+ return;
+ return string4.slice(0, endIndex + 1);
+}
+__name(parseSGRSequence, "parseSGRSequence");
+function splitCompoundSGRSequences(code) {
+ if (!code.includes(";")) {
+ return [code];
+ }
+ const codeParts = code.slice(2, -1).split(";");
+ const ret = [];
+ for (let i = 0; i < codeParts.length; i++) {
+ const rawCode = codeParts[i];
+ if (rawCode === "38" || rawCode === "48") {
+ if (i + 2 < codeParts.length && codeParts[i + 1] === "5") {
+ ret.push(codeParts.slice(i, i + 3).join(";"));
+ i += 2;
+ continue;
+ } else if (i + 4 < codeParts.length && codeParts[i + 1] === "2") {
+ ret.push(codeParts.slice(i, i + 5).join(";"));
+ i += 4;
+ continue;
+ }
+ }
+ ret.push(rawCode);
+ }
+ return ret.map((part) => `\x1B[${part}m`);
+}
+__name(splitCompoundSGRSequences, "splitCompoundSGRSequences");
+function tokenize(str3, endChar = Number.POSITIVE_INFINITY) {
+ const ret = [];
+ let visible = 0;
+ let codeEndIndex = 0;
+ for (const { segment, index } of segmenter3.segment(str3)) {
+ if (index < codeEndIndex)
+ continue;
+ const codePoint = segment.codePointAt(0);
+ if (ESCAPES3.has(codePoint)) {
+ let code;
+ const nextCodePoint = str3.codePointAt(index + 1);
+ if (nextCodePoint === CC_OSC) {
+ code = parseLinkCode(str3, index);
+ if (code) {
+ ret.push({
+ type: "ansi",
+ code,
+ endCode: getEndCode(code)
+ });
+ } else {
+ code = parseOSCSequence(str3, index);
+ if (code) {
+ ret.push({
+ type: "control",
+ code
+ });
+ }
+ }
+ } else if (nextCodePoint === CC_CSI) {
+ code = parseSGRSequence(str3, index);
+ if (code) {
+ const codes = splitCompoundSGRSequences(code);
+ for (const individualCode of codes) {
+ ret.push({
+ type: "ansi",
+ code: individualCode,
+ endCode: getEndCode(individualCode)
+ });
+ }
+ }
+ }
+ if (code) {
+ codeEndIndex = index + code.length;
+ continue;
+ }
+ }
+ const fullWidth = isFullwidthGrapheme(segment, codePoint);
+ ret.push({
+ type: "char",
+ value: segment,
+ fullWidth
+ });
+ visible += fullWidth ? 2 : 1;
+ if (visible >= endChar) {
+ break;
+ }
+ }
+ return ret;
+}
+__name(tokenize, "tokenize");
+
+// node_modules/ink/build/output.js
+var OutputCaches = class {
+ static {
+ __name(this, "OutputCaches");
+ }
+ widths = /* @__PURE__ */ new Map();
+ blockWidths = /* @__PURE__ */ new Map();
+ styledChars = /* @__PURE__ */ new Map();
+ getStyledChars(line) {
+ let cached2 = this.styledChars.get(line);
+ if (cached2 === void 0) {
+ cached2 = styledCharsFromTokens(tokenize(line));
+ this.styledChars.set(line, cached2);
+ }
+ return cached2;
+ }
+ getStringWidth(text) {
+ let cached2 = this.widths.get(text);
+ if (cached2 === void 0) {
+ cached2 = stringWidth(text);
+ this.widths.set(text, cached2);
+ }
+ return cached2;
+ }
+ getWidestLine(text) {
+ let cached2 = this.blockWidths.get(text);
+ if (cached2 === void 0) {
+ let lineWidth = 0;
+ for (const line of text.split("\n")) {
+ lineWidth = Math.max(lineWidth, this.getStringWidth(line));
+ }
+ cached2 = lineWidth;
+ this.blockWidths.set(text, cached2);
+ }
+ return cached2;
+ }
+};
+var Output = class {
+ static {
+ __name(this, "Output");
+ }
+ width;
+ height;
+ operations = [];
+ caches = new OutputCaches();
+ constructor(options2) {
+ const { width, height } = options2;
+ this.width = width;
+ this.height = height;
+ }
+ write(x, y, text, options2) {
+ const { transformers } = options2;
+ if (!text) {
+ return;
+ }
+ this.operations.push({
+ type: "write",
+ x,
+ y,
+ text,
+ transformers
+ });
+ }
+ clip(clip) {
+ this.operations.push({
+ type: "clip",
+ clip
+ });
+ }
+ unclip() {
+ this.operations.push({
+ type: "unclip"
+ });
+ }
+ get() {
+ const output = [];
+ for (let y = 0; y < this.height; y++) {
+ const row = [];
+ for (let x = 0; x < this.width; x++) {
+ row.push({
+ type: "char",
+ value: " ",
+ fullWidth: false,
+ styles: []
+ });
+ }
+ output.push(row);
+ }
+ const clips = [];
+ for (const operation of this.operations) {
+ if (operation.type === "clip") {
+ clips.push(operation.clip);
+ }
+ if (operation.type === "unclip") {
+ clips.pop();
+ }
+ if (operation.type === "write") {
+ const { text, transformers } = operation;
+ let { x, y } = operation;
+ let lines = text.split("\n");
+ const clip = clips.at(-1);
+ if (clip) {
+ const clipHorizontally = typeof clip?.x1 === "number" && typeof clip?.x2 === "number";
+ const clipVertically = typeof clip?.y1 === "number" && typeof clip?.y2 === "number";
+ if (clipHorizontally) {
+ const width = this.caches.getWidestLine(text);
+ if (x + width < clip.x1 || x > clip.x2) {
+ continue;
+ }
+ }
+ if (clipVertically) {
+ const height = lines.length;
+ if (y + height < clip.y1 || y > clip.y2) {
+ continue;
+ }
+ }
+ if (clipHorizontally) {
+ lines = lines.map((line) => {
+ const from = x < clip.x1 ? clip.x1 - x : 0;
+ const width = this.caches.getStringWidth(line);
+ const to = x + width > clip.x2 ? clip.x2 - x : width;
+ return sliceAnsi(line, from, to);
+ });
+ if (x < clip.x1) {
+ x = clip.x1;
+ }
+ }
+ if (clipVertically) {
+ const from = y < clip.y1 ? clip.y1 - y : 0;
+ const height = lines.length;
+ const to = y + height > clip.y2 ? clip.y2 - y : height;
+ lines = lines.slice(from, to);
+ if (y < clip.y1) {
+ y = clip.y1;
+ }
+ }
+ }
+ let offsetY = 0;
+ for (let [index, line] of lines.entries()) {
+ const currentLine = output[y + offsetY];
+ if (!currentLine) {
+ continue;
+ }
+ for (const transformer of transformers) {
+ line = transformer(line, index);
+ }
+ const characters = this.caches.getStyledChars(line);
+ let offsetX = x;
+ if (characters.length === 0) {
+ offsetY++;
+ continue;
+ }
+ const spaceCell = {
+ type: "char",
+ value: " ",
+ fullWidth: false,
+ styles: []
+ };
+ if (currentLine[offsetX]?.value === "" && offsetX > 0 && this.caches.getStringWidth(currentLine[offsetX - 1]?.value ?? "") > 1) {
+ currentLine[offsetX - 1] = spaceCell;
+ }
+ for (const character of characters) {
+ currentLine[offsetX] = character;
+ const characterWidth2 = Math.max(1, this.caches.getStringWidth(character.value));
+ if (characterWidth2 > 1) {
+ for (let index2 = 1; index2 < characterWidth2; index2++) {
+ currentLine[offsetX + index2] = {
+ type: "char",
+ value: "",
+ fullWidth: false,
+ styles: character.styles
+ };
+ }
+ }
+ offsetX += characterWidth2;
+ }
+ if (currentLine[offsetX]?.value === "") {
+ currentLine[offsetX] = spaceCell;
+ }
+ offsetY++;
+ }
+ }
+ }
+ const generatedOutput = output.map((line) => {
+ const lineWithoutEmptyItems = line.filter((item) => item !== void 0);
+ return styledCharsToString(lineWithoutEmptyItems).trimEnd();
+ }).join("\n");
+ return {
+ output: generatedOutput,
+ height: output.length
+ };
+ }
+};
+
+// node_modules/ink/build/renderer.js
+var renderer = /* @__PURE__ */ __name((node, isScreenReaderEnabled) => {
+ if (node.yogaNode) {
+ if (isScreenReaderEnabled) {
+ const output2 = renderNodeToScreenReaderOutput(node, {
+ skipStaticElements: true
+ });
+ const outputHeight2 = output2 === "" ? 0 : output2.split("\n").length;
+ let staticOutput2 = "";
+ if (node.staticNode) {
+ staticOutput2 = renderNodeToScreenReaderOutput(node.staticNode, {
+ skipStaticElements: false
+ });
+ }
+ return {
+ output: output2,
+ outputHeight: outputHeight2,
+ staticOutput: staticOutput2 ? `${staticOutput2}
+` : ""
+ };
+ }
+ const output = new Output({
+ width: node.yogaNode.getComputedWidth(),
+ height: node.yogaNode.getComputedHeight()
+ });
+ render_node_to_output_default(node, output, {
+ skipStaticElements: true
+ });
+ let staticOutput;
+ if (node.staticNode?.yogaNode) {
+ staticOutput = new Output({
+ width: node.staticNode.yogaNode.getComputedWidth(),
+ height: node.staticNode.yogaNode.getComputedHeight()
+ });
+ render_node_to_output_default(node.staticNode, staticOutput, {
+ skipStaticElements: false
+ });
+ }
+ const { output: generatedOutput, height: outputHeight } = output.get();
+ return {
+ output: generatedOutput,
+ outputHeight,
+ // Newline at the end is needed, because static output doesn't have one, so
+ // interactive output will override last line of static output
+ staticOutput: staticOutput ? `${staticOutput.get().output}
+` : ""
+ };
+ }
+ return {
+ output: "",
+ outputHeight: 0,
+ staticOutput: ""
+ };
+}, "renderer");
+var renderer_default = renderer;
+
+// node_modules/ink/build/cursor-helpers.js
+init_esbuild_shims();
+var showCursorEscape = "\x1B[?25h";
+var hideCursorEscape = "\x1B[?25l";
+var cursorPositionChanged = /* @__PURE__ */ __name((a, b) => a?.x !== b?.x || a?.y !== b?.y, "cursorPositionChanged");
+var buildCursorSuffix = /* @__PURE__ */ __name((visibleLineCount2, cursorPosition) => {
+ if (!cursorPosition) {
+ return "";
+ }
+ const moveUp2 = visibleLineCount2 - cursorPosition.y;
+ return (moveUp2 > 0 ? base_exports.cursorUp(moveUp2) : "") + base_exports.cursorTo(cursorPosition.x) + showCursorEscape;
+}, "buildCursorSuffix");
+var buildReturnToBottom = /* @__PURE__ */ __name((previousLineCount, previousCursorPosition) => {
+ if (!previousCursorPosition) {
+ return "";
+ }
+ const down = previousLineCount - 1 - previousCursorPosition.y;
+ return (down > 0 ? base_exports.cursorDown(down) : "") + base_exports.cursorTo(0);
+}, "buildReturnToBottom");
+var buildCursorOnlySequence = /* @__PURE__ */ __name((input) => {
+ const hidePrefix = input.cursorWasShown ? hideCursorEscape : "";
+ const returnToBottom = buildReturnToBottom(input.previousLineCount, input.previousCursorPosition);
+ const cursorSuffix = buildCursorSuffix(input.visibleLineCount, input.cursorPosition);
+ return hidePrefix + returnToBottom + cursorSuffix;
+}, "buildCursorOnlySequence");
+var buildReturnToBottomPrefix = /* @__PURE__ */ __name((cursorWasShown, previousLineCount, previousCursorPosition) => {
+ if (!cursorWasShown) {
+ return "";
+ }
+ return hideCursorEscape + buildReturnToBottom(previousLineCount, previousCursorPosition);
+}, "buildReturnToBottomPrefix");
+
+// node_modules/ink/build/log-update.js
+init_esbuild_shims();
+
+// node_modules/cli-cursor/index.js
+init_esbuild_shims();
+import process7 from "node:process";
+
+// node_modules/restore-cursor/index.js
+init_esbuild_shims();
+var import_onetime = __toESM(require_onetime(), 1);
+var import_signal_exit = __toESM(require_signal_exit(), 1);
+import process6 from "node:process";
+var restoreCursor = (0, import_onetime.default)(() => {
+ (0, import_signal_exit.default)(() => {
+ process6.stderr.write("\x1B[?25h");
+ }, { alwaysLast: true });
+});
+var restore_cursor_default = restoreCursor;
+
+// node_modules/cli-cursor/index.js
+var isHidden = false;
+var cliCursor = {};
+cliCursor.show = (writableStream = process7.stderr) => {
+ if (!writableStream.isTTY) {
+ return;
+ }
+ isHidden = false;
+ writableStream.write("\x1B[?25h");
+};
+cliCursor.hide = (writableStream = process7.stderr) => {
+ if (!writableStream.isTTY) {
+ return;
+ }
+ restore_cursor_default();
+ isHidden = true;
+ writableStream.write("\x1B[?25l");
+};
+cliCursor.toggle = (force, writableStream) => {
+ if (force !== void 0) {
+ isHidden = force;
+ }
+ if (isHidden) {
+ cliCursor.show(writableStream);
+ } else {
+ cliCursor.hide(writableStream);
+ }
+};
+var cli_cursor_default = cliCursor;
+
+// node_modules/ink/build/log-update.js
+var visibleLineCount = /* @__PURE__ */ __name((lines, str3) => str3.endsWith("\n") ? lines.length - 1 : lines.length, "visibleLineCount");
+var createStandard = /* @__PURE__ */ __name((stream, { showCursor: showCursor2 = false } = {}) => {
+ let previousLineCount = 0;
+ let previousOutput = "";
+ let hasHiddenCursor = false;
+ let cursorPosition;
+ let cursorDirty = false;
+ let previousCursorPosition;
+ let cursorWasShown = false;
+ const getActiveCursor = /* @__PURE__ */ __name(() => cursorDirty ? cursorPosition : void 0, "getActiveCursor");
+ const hasChanges = /* @__PURE__ */ __name((str3, activeCursor) => {
+ const cursorChanged = cursorPositionChanged(activeCursor, previousCursorPosition);
+ return str3 !== previousOutput || cursorChanged;
+ }, "hasChanges");
+ const render2 = /* @__PURE__ */ __name((str3) => {
+ if (!showCursor2 && !hasHiddenCursor) {
+ cli_cursor_default.hide(stream);
+ hasHiddenCursor = true;
+ }
+ const activeCursor = getActiveCursor();
+ cursorDirty = false;
+ const cursorChanged = cursorPositionChanged(activeCursor, previousCursorPosition);
+ if (!hasChanges(str3, activeCursor)) {
+ return false;
+ }
+ const lines = str3.split("\n");
+ const visibleCount = visibleLineCount(lines, str3);
+ const cursorSuffix = buildCursorSuffix(visibleCount, activeCursor);
+ if (str3 === previousOutput && cursorChanged) {
+ stream.write(buildCursorOnlySequence({
+ cursorWasShown,
+ previousLineCount,
+ previousCursorPosition,
+ visibleLineCount: visibleCount,
+ cursorPosition: activeCursor
+ }));
+ } else {
+ previousOutput = str3;
+ const returnPrefix = buildReturnToBottomPrefix(cursorWasShown, previousLineCount, previousCursorPosition);
+ stream.write(returnPrefix + base_exports.eraseLines(previousLineCount) + str3 + cursorSuffix);
+ previousLineCount = lines.length;
+ }
+ previousCursorPosition = activeCursor ? { ...activeCursor } : void 0;
+ cursorWasShown = activeCursor !== void 0;
+ return true;
+ }, "render");
+ render2.clear = () => {
+ const prefix = buildReturnToBottomPrefix(cursorWasShown, previousLineCount, previousCursorPosition);
+ stream.write(prefix + base_exports.eraseLines(previousLineCount));
+ previousOutput = "";
+ previousLineCount = 0;
+ previousCursorPosition = void 0;
+ cursorWasShown = false;
+ };
+ render2.done = () => {
+ previousOutput = "";
+ previousLineCount = 0;
+ previousCursorPosition = void 0;
+ cursorWasShown = false;
+ if (!showCursor2) {
+ cli_cursor_default.show(stream);
+ hasHiddenCursor = false;
+ }
+ };
+ render2.reset = () => {
+ previousOutput = "";
+ previousLineCount = 0;
+ previousCursorPosition = void 0;
+ cursorWasShown = false;
+ };
+ render2.sync = (str3) => {
+ const activeCursor = cursorDirty ? cursorPosition : void 0;
+ cursorDirty = false;
+ const lines = str3.split("\n");
+ previousOutput = str3;
+ previousLineCount = lines.length;
+ if (!activeCursor && cursorWasShown) {
+ stream.write(hideCursorEscape);
+ }
+ if (activeCursor) {
+ stream.write(buildCursorSuffix(visibleLineCount(lines, str3), activeCursor));
+ }
+ previousCursorPosition = activeCursor ? { ...activeCursor } : void 0;
+ cursorWasShown = activeCursor !== void 0;
+ };
+ render2.setCursorPosition = (position) => {
+ cursorPosition = position;
+ cursorDirty = true;
+ };
+ render2.isCursorDirty = () => cursorDirty;
+ render2.willRender = (str3) => hasChanges(str3, getActiveCursor());
+ return render2;
+}, "createStandard");
+var createIncremental = /* @__PURE__ */ __name((stream, { showCursor: showCursor2 = false } = {}) => {
+ let previousLines = [];
+ let previousOutput = "";
+ let hasHiddenCursor = false;
+ let cursorPosition;
+ let cursorDirty = false;
+ let previousCursorPosition;
+ let cursorWasShown = false;
+ const getActiveCursor = /* @__PURE__ */ __name(() => cursorDirty ? cursorPosition : void 0, "getActiveCursor");
+ const hasChanges = /* @__PURE__ */ __name((str3, activeCursor) => {
+ const cursorChanged = cursorPositionChanged(activeCursor, previousCursorPosition);
+ return str3 !== previousOutput || cursorChanged;
+ }, "hasChanges");
+ const render2 = /* @__PURE__ */ __name((str3) => {
+ if (!showCursor2 && !hasHiddenCursor) {
+ cli_cursor_default.hide(stream);
+ hasHiddenCursor = true;
+ }
+ const activeCursor = getActiveCursor();
+ cursorDirty = false;
+ const cursorChanged = cursorPositionChanged(activeCursor, previousCursorPosition);
+ if (!hasChanges(str3, activeCursor)) {
+ return false;
+ }
+ const nextLines = str3.split("\n");
+ const visibleCount = visibleLineCount(nextLines, str3);
+ const previousVisible = visibleLineCount(previousLines, previousOutput);
+ if (str3 === previousOutput && cursorChanged) {
+ stream.write(buildCursorOnlySequence({
+ cursorWasShown,
+ previousLineCount: previousLines.length,
+ previousCursorPosition,
+ visibleLineCount: visibleCount,
+ cursorPosition: activeCursor
+ }));
+ previousCursorPosition = activeCursor ? { ...activeCursor } : void 0;
+ cursorWasShown = activeCursor !== void 0;
+ return true;
+ }
+ const returnPrefix = buildReturnToBottomPrefix(cursorWasShown, previousLines.length, previousCursorPosition);
+ if (str3 === "\n" || previousOutput.length === 0) {
+ const cursorSuffix2 = buildCursorSuffix(visibleCount, activeCursor);
+ stream.write(returnPrefix + base_exports.eraseLines(previousLines.length) + str3 + cursorSuffix2);
+ cursorWasShown = activeCursor !== void 0;
+ previousCursorPosition = activeCursor ? { ...activeCursor } : void 0;
+ previousOutput = str3;
+ previousLines = nextLines;
+ return true;
+ }
+ const hasTrailingNewline = str3.endsWith("\n");
+ const buffer = [];
+ buffer.push(returnPrefix);
+ if (visibleCount < previousVisible) {
+ const previousHadTrailingNewline = previousOutput.endsWith("\n");
+ const extraSlot = previousHadTrailingNewline ? 1 : 0;
+ buffer.push(base_exports.eraseLines(previousVisible - visibleCount + extraSlot), base_exports.cursorUp(visibleCount));
+ } else {
+ buffer.push(base_exports.cursorUp(previousLines.length - 1));
+ }
+ for (let i = 0; i < visibleCount; i++) {
+ const isLastLine = i === visibleCount - 1;
+ if (nextLines[i] === previousLines[i]) {
+ if (!isLastLine || hasTrailingNewline) {
+ buffer.push(base_exports.cursorNextLine);
+ }
+ continue;
+ }
+ buffer.push(base_exports.cursorTo(0) + nextLines[i] + base_exports.eraseEndLine + // Don't append newline after the last line when the input
+ // has no trailing newline (fullscreen mode).
+ (isLastLine && !hasTrailingNewline ? "" : "\n"));
+ }
+ const cursorSuffix = buildCursorSuffix(visibleCount, activeCursor);
+ buffer.push(cursorSuffix);
+ stream.write(buffer.join(""));
+ cursorWasShown = activeCursor !== void 0;
+ previousCursorPosition = activeCursor ? { ...activeCursor } : void 0;
+ previousOutput = str3;
+ previousLines = nextLines;
+ return true;
+ }, "render");
+ render2.clear = () => {
+ const prefix = buildReturnToBottomPrefix(cursorWasShown, previousLines.length, previousCursorPosition);
+ stream.write(prefix + base_exports.eraseLines(previousLines.length));
+ previousOutput = "";
+ previousLines = [];
+ previousCursorPosition = void 0;
+ cursorWasShown = false;
+ };
+ render2.done = () => {
+ previousOutput = "";
+ previousLines = [];
+ previousCursorPosition = void 0;
+ cursorWasShown = false;
+ if (!showCursor2) {
+ cli_cursor_default.show(stream);
+ hasHiddenCursor = false;
+ }
+ };
+ render2.reset = () => {
+ previousOutput = "";
+ previousLines = [];
+ previousCursorPosition = void 0;
+ cursorWasShown = false;
+ };
+ render2.sync = (str3) => {
+ const activeCursor = cursorDirty ? cursorPosition : void 0;
+ cursorDirty = false;
+ const lines = str3.split("\n");
+ previousOutput = str3;
+ previousLines = lines;
+ if (!activeCursor && cursorWasShown) {
+ stream.write(hideCursorEscape);
+ }
+ if (activeCursor) {
+ stream.write(buildCursorSuffix(visibleLineCount(lines, str3), activeCursor));
+ }
+ previousCursorPosition = activeCursor ? { ...activeCursor } : void 0;
+ cursorWasShown = activeCursor !== void 0;
+ };
+ render2.setCursorPosition = (position) => {
+ cursorPosition = position;
+ cursorDirty = true;
+ };
+ render2.isCursorDirty = () => cursorDirty;
+ render2.willRender = (str3) => hasChanges(str3, getActiveCursor());
+ return render2;
+}, "createIncremental");
+var create2 = /* @__PURE__ */ __name((stream, { showCursor: showCursor2 = false, incremental = false } = {}) => {
+ if (incremental) {
+ return createIncremental(stream, { showCursor: showCursor2 });
+ }
+ return createStandard(stream, { showCursor: showCursor2 });
+}, "create");
+var logUpdate = { create: create2 };
+var log_update_default = logUpdate;
+
+// node_modules/ink/build/write-synchronized.js
+init_esbuild_shims();
+var bsu = "\x1B[?2026h";
+var esu = "\x1B[?2026l";
+function shouldSynchronize(stream, interactive) {
+ return "isTTY" in stream && stream.isTTY && (interactive ?? !is_in_ci_default);
+}
+__name(shouldSynchronize, "shouldSynchronize");
+
+// node_modules/ink/build/instances.js
+init_esbuild_shims();
+var instances = /* @__PURE__ */ new WeakMap();
+var instances_default = instances;
+
+// node_modules/ink/build/components/App.js
+init_esbuild_shims();
+var import_react15 = __toESM(require_react(), 1);
+import { EventEmitter as EventEmitter2 } from "node:events";
+import process11 from "node:process";
+
+// node_modules/ink/build/input-parser.js
+init_esbuild_shims();
+var escape2 = "\x1B";
+var pasteStart = "\x1B[200~";
+var pasteEnd = "\x1B[201~";
+var isCsiParameterByte = /* @__PURE__ */ __name((byte) => {
+ return byte >= 48 && byte <= 63;
+}, "isCsiParameterByte");
+var isCsiIntermediateByte = /* @__PURE__ */ __name((byte) => {
+ return byte >= 32 && byte <= 47;
+}, "isCsiIntermediateByte");
+var isCsiFinalByte = /* @__PURE__ */ __name((byte) => {
+ return byte >= 64 && byte <= 126;
+}, "isCsiFinalByte");
+var parseCsiSequence = /* @__PURE__ */ __name((input, startIndex, prefixLength) => {
+ const csiPayloadStart = startIndex + prefixLength + 1;
+ let index = csiPayloadStart;
+ for (; index < input.length; index++) {
+ const byte = input.codePointAt(index);
+ if (byte === void 0) {
+ return "pending";
+ }
+ if (isCsiParameterByte(byte) || isCsiIntermediateByte(byte)) {
+ continue;
+ }
+ if (byte === 91 && index === csiPayloadStart) {
+ continue;
+ }
+ if (isCsiFinalByte(byte)) {
+ return {
+ sequence: input.slice(startIndex, index + 1),
+ nextIndex: index + 1
+ };
+ }
+ return void 0;
+ }
+ return "pending";
+}, "parseCsiSequence");
+var parseSs3Sequence = /* @__PURE__ */ __name((input, startIndex, prefixLength) => {
+ const nextIndex = startIndex + prefixLength + 2;
+ if (nextIndex > input.length) {
+ return "pending";
+ }
+ const finalByte = input.codePointAt(nextIndex - 1);
+ if (finalByte === void 0 || !isCsiFinalByte(finalByte)) {
+ return void 0;
+ }
+ return {
+ sequence: input.slice(startIndex, nextIndex),
+ nextIndex
+ };
+}, "parseSs3Sequence");
+var parseControlSequence = /* @__PURE__ */ __name((input, startIndex, prefixLength) => {
+ const sequenceType = input[startIndex + prefixLength];
+ if (sequenceType === void 0) {
+ return "pending";
+ }
+ if (sequenceType === "[") {
+ return parseCsiSequence(input, startIndex, prefixLength);
+ }
+ if (sequenceType === "O") {
+ return parseSs3Sequence(input, startIndex, prefixLength);
+ }
+ return void 0;
+}, "parseControlSequence");
+var parseEscapedCodePoint = /* @__PURE__ */ __name((input, escapeIndex) => {
+ const nextCodePoint = input.codePointAt(escapeIndex + 1);
+ const nextCodePointLength = nextCodePoint !== void 0 && nextCodePoint > 65535 ? 2 : 1;
+ const nextIndex = escapeIndex + 1 + nextCodePointLength;
+ return {
+ sequence: input.slice(escapeIndex, nextIndex),
+ nextIndex
+ };
+}, "parseEscapedCodePoint");
+var parseEscapeSequence = /* @__PURE__ */ __name((input, escapeIndex) => {
+ if (escapeIndex === input.length - 1) {
+ return "pending";
+ }
+ const next = input[escapeIndex + 1];
+ if (next === escape2) {
+ if (escapeIndex + 2 >= input.length) {
+ return "pending";
+ }
+ const doubleEscapeSequence = parseControlSequence(input, escapeIndex, 2);
+ if (doubleEscapeSequence === "pending") {
+ return "pending";
+ }
+ if (doubleEscapeSequence) {
+ return doubleEscapeSequence;
+ }
+ return {
+ sequence: input.slice(escapeIndex, escapeIndex + 2),
+ nextIndex: escapeIndex + 2
+ };
+ }
+ const controlSequence = parseControlSequence(input, escapeIndex, 1);
+ if (controlSequence === "pending") {
+ return "pending";
+ }
+ if (controlSequence) {
+ return controlSequence;
+ }
+ return parseEscapedCodePoint(input, escapeIndex);
+}, "parseEscapeSequence");
+var splitBackspaceBytes = /* @__PURE__ */ __name((text, events) => {
+ let textSegmentStart = 0;
+ for (let index = 0; index < text.length; index++) {
+ const character = text[index];
+ if (character === "\x7F" || character === "\b") {
+ if (index > textSegmentStart) {
+ events.push(text.slice(textSegmentStart, index));
+ }
+ events.push(character);
+ textSegmentStart = index + 1;
+ }
+ }
+ if (textSegmentStart < text.length) {
+ events.push(text.slice(textSegmentStart));
+ }
+}, "splitBackspaceBytes");
+var parseKeypresses = /* @__PURE__ */ __name((input) => {
+ const events = [];
+ let index = 0;
+ const pendingFrom = /* @__PURE__ */ __name((pendingStartIndex) => ({
+ events,
+ pending: input.slice(pendingStartIndex)
+ }), "pendingFrom");
+ while (index < input.length) {
+ const escapeIndex = input.indexOf(escape2, index);
+ if (escapeIndex === -1) {
+ splitBackspaceBytes(input.slice(index), events);
+ return {
+ events,
+ pending: ""
+ };
+ }
+ if (escapeIndex > index) {
+ splitBackspaceBytes(input.slice(index, escapeIndex), events);
+ }
+ const parsedEscapeSequence = parseEscapeSequence(input, escapeIndex);
+ if (parsedEscapeSequence === "pending") {
+ return pendingFrom(escapeIndex);
+ }
+ if (parsedEscapeSequence.sequence === pasteStart) {
+ const afterStart = parsedEscapeSequence.nextIndex;
+ const endIndex = input.indexOf(pasteEnd, afterStart);
+ if (endIndex === -1) {
+ return pendingFrom(escapeIndex);
+ }
+ events.push({ paste: input.slice(afterStart, endIndex) });
+ index = endIndex + pasteEnd.length;
+ continue;
+ }
+ events.push(parsedEscapeSequence.sequence);
+ index = parsedEscapeSequence.nextIndex;
+ }
+ return {
+ events,
+ pending: ""
+ };
+}, "parseKeypresses");
+var createInputParser = /* @__PURE__ */ __name(() => {
+ let pending = "";
+ return {
+ push(chunk) {
+ const parsedInput = parseKeypresses(pending + chunk);
+ pending = parsedInput.pending;
+ return parsedInput.events;
+ },
+ hasPendingEscape() {
+ return pending.startsWith(escape2) && !pending.startsWith(pasteStart) && pending !== "\x1B[200";
+ },
+ flushPendingEscape() {
+ if (!pending.startsWith(escape2)) {
+ return void 0;
+ }
+ const pendingEscape = pending;
+ pending = "";
+ return pendingEscape;
+ },
+ reset() {
+ pending = "";
+ }
+ };
+}, "createInputParser");
+
+// node_modules/ink/build/components/AppContext.js
+init_esbuild_shims();
+var import_react2 = __toESM(require_react(), 1);
+var noopSuspension = {
+ async resume() {
+ },
+ async [Symbol.asyncDispose]() {
+ }
+};
+var defaultValue = {
+ exit(_errorOrResult) {
+ },
+ async waitUntilRenderFlush() {
+ },
+ suspendTerminal: /* @__PURE__ */ __name((async (callback) => {
+ if (callback) {
+ await callback();
+ return void 0;
+ }
+ return noopSuspension;
+ }), "suspendTerminal")
+};
+var AppContext = (0, import_react2.createContext)(defaultValue);
+AppContext.displayName = "InternalAppContext";
+var AppContext_default = AppContext;
+
+// node_modules/ink/build/components/StdinContext.js
+init_esbuild_shims();
+var import_react3 = __toESM(require_react(), 1);
+import { EventEmitter } from "node:events";
+import process8 from "node:process";
+var StdinContext = (0, import_react3.createContext)({
+ stdin: process8.stdin,
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ internal_eventEmitter: new EventEmitter(),
+ setRawMode() {
+ },
+ setBracketedPasteMode() {
+ },
+ isRawModeSupported: false,
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ internal_exitOnCtrlC: true
+});
+StdinContext.displayName = "InternalStdinContext";
+var StdinContext_default = StdinContext;
+
+// node_modules/ink/build/components/StdoutContext.js
+init_esbuild_shims();
+var import_react4 = __toESM(require_react(), 1);
+import process9 from "node:process";
+var StdoutContext = (0, import_react4.createContext)({
+ stdout: process9.stdout,
+ write() {
+ }
+});
+StdoutContext.displayName = "InternalStdoutContext";
+var StdoutContext_default = StdoutContext;
+
+// node_modules/ink/build/components/StderrContext.js
+init_esbuild_shims();
+var import_react5 = __toESM(require_react(), 1);
+import process10 from "node:process";
+var StderrContext = (0, import_react5.createContext)({
+ stderr: process10.stderr,
+ write() {
+ }
+});
+StderrContext.displayName = "InternalStderrContext";
+var StderrContext_default = StderrContext;
+
+// node_modules/ink/build/components/FocusContext.js
+init_esbuild_shims();
+var import_react6 = __toESM(require_react(), 1);
+var FocusContext = (0, import_react6.createContext)({
+ activeId: void 0,
+ add() {
+ },
+ remove() {
+ },
+ activate() {
+ },
+ deactivate() {
+ },
+ enableFocus() {
+ },
+ disableFocus() {
+ },
+ focusNext() {
+ },
+ focusPrevious() {
+ },
+ focus() {
+ }
+});
+FocusContext.displayName = "InternalFocusContext";
+var FocusContext_default = FocusContext;
+
+// node_modules/ink/build/components/AnimationContext.js
+init_esbuild_shims();
+var import_react7 = __toESM(require_react(), 1);
+var animationContext = (0, import_react7.createContext)({
+ renderThrottleMs: 0,
+ subscribe() {
+ return {
+ startTime: 0,
+ unsubscribe() {
+ }
+ };
+ }
+});
+animationContext.displayName = "InternalAnimationContext";
+var AnimationContext_default = animationContext;
+
+// node_modules/ink/build/components/CursorContext.js
+init_esbuild_shims();
+var import_react8 = __toESM(require_react(), 1);
+var CursorContext = (0, import_react8.createContext)({
+ setCursorPosition() {
+ }
+});
+CursorContext.displayName = "InternalCursorContext";
+var CursorContext_default = CursorContext;
+
+// node_modules/ink/build/components/ErrorBoundary.js
+init_esbuild_shims();
+var import_react14 = __toESM(require_react(), 1);
+
+// node_modules/ink/build/components/ErrorOverview.js
+init_esbuild_shims();
+var import_react13 = __toESM(require_react(), 1);
+var import_stack_utils = __toESM(require_stack_utils(), 1);
+import * as fs2 from "node:fs";
+import { cwd } from "node:process";
+
+// node_modules/code-excerpt/dist/index.js
+init_esbuild_shims();
+
+// node_modules/convert-to-spaces/dist/index.js
+init_esbuild_shims();
+var convertToSpaces = /* @__PURE__ */ __name((input, spaces = 2) => {
+ return input.replace(/^\t+/gm, ($1) => " ".repeat($1.length * spaces));
+}, "convertToSpaces");
+var dist_default2 = convertToSpaces;
+
+// node_modules/code-excerpt/dist/index.js
+var generateLineNumbers = /* @__PURE__ */ __name((line, around) => {
+ const lineNumbers = [];
+ const min = line - around;
+ const max = line + around;
+ for (let lineNumber = min; lineNumber <= max; lineNumber++) {
+ lineNumbers.push(lineNumber);
+ }
+ return lineNumbers;
+}, "generateLineNumbers");
+var codeExcerpt = /* @__PURE__ */ __name((source, line, options2 = {}) => {
+ var _a6;
+ if (typeof source !== "string") {
+ throw new TypeError("Source code is missing.");
+ }
+ if (!line || line < 1) {
+ throw new TypeError("Line number must start from `1`.");
+ }
+ const lines = dist_default2(source).split(/\r?\n/);
+ if (line > lines.length) {
+ return;
+ }
+ return generateLineNumbers(line, (_a6 = options2.around) !== null && _a6 !== void 0 ? _a6 : 3).filter((line2) => lines[line2 - 1] !== void 0).map((line2) => ({ line: line2, value: lines[line2 - 1] }));
+}, "codeExcerpt");
+var dist_default3 = codeExcerpt;
+
+// node_modules/ink/build/components/Box.js
+init_esbuild_shims();
+var import_react11 = __toESM(require_react(), 1);
+
+// node_modules/ink/build/components/AccessibilityContext.js
+init_esbuild_shims();
+var import_react9 = __toESM(require_react(), 1);
+var accessibilityContext = (0, import_react9.createContext)({
+ isScreenReaderEnabled: false
+});
+
+// node_modules/ink/build/components/BackgroundContext.js
+init_esbuild_shims();
+var import_react10 = __toESM(require_react(), 1);
+var backgroundContext = (0, import_react10.createContext)(void 0);
+
+// node_modules/ink/build/components/Box.js
+var Box = (0, import_react11.forwardRef)(({ children, backgroundColor, "aria-label": ariaLabel, "aria-hidden": ariaHidden, "aria-role": role, "aria-state": ariaState, ...style }, ref) => {
+ const { isScreenReaderEnabled } = (0, import_react11.useContext)(accessibilityContext);
+ const label = ariaLabel ? import_react11.default.createElement("ink-text", null, ariaLabel) : void 0;
+ if (isScreenReaderEnabled && ariaHidden) {
+ return null;
+ }
+ const boxElement = import_react11.default.createElement("ink-box", { ref, style: {
+ flexWrap: "nowrap",
+ flexDirection: "row",
+ flexGrow: 0,
+ flexShrink: 1,
+ ...style,
+ backgroundColor,
+ overflowX: style.overflowX ?? style.overflow ?? "visible",
+ overflowY: style.overflowY ?? style.overflow ?? "visible"
+ }, internal_accessibility: {
+ role,
+ state: ariaState
+ } }, isScreenReaderEnabled && label ? label : children);
+ if (backgroundColor) {
+ return import_react11.default.createElement(backgroundContext.Provider, { value: backgroundColor }, boxElement);
+ }
+ return boxElement;
+});
+Box.displayName = "Box";
+var Box_default = Box;
+
+// node_modules/ink/build/components/Text.js
+init_esbuild_shims();
+var import_react12 = __toESM(require_react(), 1);
+function Text({ color, backgroundColor, dimColor = false, bold = false, italic = false, underline = false, strikethrough = false, inverse = false, wrap: wrap2 = "wrap", children, "aria-label": ariaLabel, "aria-hidden": ariaHidden = false }) {
+ const { isScreenReaderEnabled } = (0, import_react12.useContext)(accessibilityContext);
+ const inheritedBackgroundColor = (0, import_react12.useContext)(backgroundContext);
+ const childrenOrAriaLabel = isScreenReaderEnabled && ariaLabel ? ariaLabel : children;
+ if (childrenOrAriaLabel === void 0 || childrenOrAriaLabel === null) {
+ return null;
+ }
+ const transform2 = /* @__PURE__ */ __name((children2) => {
+ if (dimColor) {
+ children2 = source_default.dim(children2);
+ }
+ if (color) {
+ children2 = colorize_default(children2, color, "foreground");
+ }
+ const effectiveBackgroundColor = backgroundColor ?? inheritedBackgroundColor;
+ if (effectiveBackgroundColor) {
+ children2 = colorize_default(children2, effectiveBackgroundColor, "background");
+ }
+ if (bold) {
+ children2 = source_default.bold(children2);
+ }
+ if (italic) {
+ children2 = source_default.italic(children2);
+ }
+ if (underline) {
+ children2 = source_default.underline(children2);
+ }
+ if (strikethrough) {
+ children2 = source_default.strikethrough(children2);
+ }
+ if (inverse) {
+ children2 = source_default.inverse(children2);
+ }
+ return children2;
+ }, "transform");
+ if (isScreenReaderEnabled && ariaHidden) {
+ return null;
+ }
+ return import_react12.default.createElement("ink-text", { style: { flexGrow: 0, flexShrink: 1, flexDirection: "row", textWrap: wrap2 }, internal_transform: transform2 }, childrenOrAriaLabel);
+}
+__name(Text, "Text");
+
+// node_modules/ink/build/components/ErrorOverview.js
+var cleanupPath = /* @__PURE__ */ __name((path27) => {
+ return path27?.replace(`file://${cwd()}/`, "");
+}, "cleanupPath");
+var stackUtils = new import_stack_utils.default({
+ cwd: cwd(),
+ internals: import_stack_utils.default.nodeInternals()
+});
+function ErrorOverview({ error: error51 }) {
+ const stack = error51.stack ? error51.stack.split("\n").slice(1) : void 0;
+ const origin = stack ? stackUtils.parseLine(stack[0]) : void 0;
+ const filePath = cleanupPath(origin?.file);
+ let excerpt;
+ let lineWidth = 0;
+ const stackLineCounts = /* @__PURE__ */ new Map();
+ if (filePath && origin?.line && fs2.existsSync(filePath)) {
+ const sourceCode = fs2.readFileSync(filePath, "utf8");
+ excerpt = dist_default3(sourceCode, origin.line);
+ if (excerpt) {
+ for (const { line } of excerpt) {
+ lineWidth = Math.max(lineWidth, String(line).length);
+ }
+ }
+ }
+ return import_react13.default.createElement(
+ Box_default,
+ { flexDirection: "column", padding: 1 },
+ import_react13.default.createElement(
+ Box_default,
+ null,
+ import_react13.default.createElement(
+ Text,
+ { backgroundColor: "red", color: "white" },
+ " ",
+ "ERROR",
+ " "
+ ),
+ import_react13.default.createElement(
+ Text,
+ null,
+ " ",
+ error51.message
+ )
+ ),
+ origin && filePath ? import_react13.default.createElement(
+ Box_default,
+ { marginTop: 1 },
+ import_react13.default.createElement(
+ Text,
+ { dimColor: true },
+ filePath,
+ ":",
+ origin.line,
+ ":",
+ origin.column
+ )
+ ) : null,
+ origin && excerpt ? import_react13.default.createElement(Box_default, { marginTop: 1, flexDirection: "column" }, excerpt.map(({ line, value }) => import_react13.default.createElement(
+ Box_default,
+ { key: line },
+ import_react13.default.createElement(
+ Box_default,
+ { width: lineWidth + 1 },
+ import_react13.default.createElement(
+ Text,
+ { dimColor: line !== origin.line, backgroundColor: line === origin.line ? "red" : void 0, color: line === origin.line ? "white" : void 0, "aria-label": line === origin.line ? `Line ${line}, error` : `Line ${line}` },
+ String(line).padStart(lineWidth, " "),
+ ":"
+ )
+ ),
+ import_react13.default.createElement(Text, { key: line, backgroundColor: line === origin.line ? "red" : void 0, color: line === origin.line ? "white" : void 0 }, " " + value)
+ ))) : null,
+ error51.stack ? import_react13.default.createElement(Box_default, { marginTop: 1, flexDirection: "column" }, error51.stack.split("\n").slice(1).map((line) => {
+ const parsedLine = stackUtils.parseLine(line);
+ const lineCount = stackLineCounts.get(line) ?? 0;
+ stackLineCounts.set(line, lineCount + 1);
+ const key = `${line}-${lineCount}`;
+ if (!parsedLine?.file || !parsedLine.line || !parsedLine.column) {
+ return import_react13.default.createElement(
+ Box_default,
+ { key },
+ import_react13.default.createElement(Text, { dimColor: true }, "- "),
+ import_react13.default.createElement(
+ Text,
+ { dimColor: true, bold: true },
+ line,
+ "\\t",
+ " "
+ )
+ );
+ }
+ return import_react13.default.createElement(
+ Box_default,
+ { key },
+ import_react13.default.createElement(Text, { dimColor: true }, "- "),
+ import_react13.default.createElement(Text, { dimColor: true, bold: true }, parsedLine.function),
+ import_react13.default.createElement(
+ Text,
+ { dimColor: true, color: "gray", "aria-label": `at ${cleanupPath(parsedLine.file) ?? ""} line ${parsedLine.line} column ${parsedLine.column}` },
+ " ",
+ "(",
+ cleanupPath(parsedLine.file) ?? "",
+ ":",
+ parsedLine.line,
+ ":",
+ parsedLine.column,
+ ")"
+ )
+ );
+ })) : null
+ );
+}
+__name(ErrorOverview, "ErrorOverview");
+
+// node_modules/ink/build/components/ErrorBoundary.js
+var ErrorBoundary = class extends import_react14.PureComponent {
+ static {
+ __name(this, "ErrorBoundary");
+ }
+ static displayName = "InternalErrorBoundary";
+ static getDerivedStateFromError(error51) {
+ return { error: error51 };
+ }
+ state = {
+ error: void 0
+ };
+ componentDidCatch(error51) {
+ this.props.onError(error51);
+ }
+ render() {
+ if (this.state.error) {
+ return import_react14.default.createElement(ErrorOverview, { error: this.state.error });
+ }
+ return this.props.children;
+ }
+};
+
+// node_modules/ink/build/components/App.js
+var tab = " ";
+var shiftTab = "\x1B[Z";
+var escape3 = "\x1B";
+function App({ children, stdin, stdout, stderr, writeToStdout, writeToStderr, exitOnCtrlC, onExit, onWaitUntilRenderFlush, onSuspendTerminal, onRegisterInputControl, setCursorPosition, interactive, renderThrottleMs }) {
+ const [isFocusEnabled, setIsFocusEnabled] = (0, import_react15.useState)(true);
+ const [activeFocusId, setActiveFocusId] = (0, import_react15.useState)(void 0);
+ const [, setFocusables] = (0, import_react15.useState)([]);
+ const focusablesCountRef = (0, import_react15.useRef)(0);
+ const animationSubscribersRef = (0, import_react15.useRef)(/* @__PURE__ */ new Map());
+ const animationTimerRef = (0, import_react15.useRef)(void 0);
+ const rawModeEnabledCount = (0, import_react15.useRef)(0);
+ const pendingDisableRawModeRef = (0, import_react15.useRef)(false);
+ const bracketedPasteModeEnabledCount = (0, import_react15.useRef)(0);
+ const internal_eventEmitter = (0, import_react15.useRef)(new EventEmitter2());
+ internal_eventEmitter.current.setMaxListeners(Infinity);
+ const readableListenerRef = (0, import_react15.useRef)(void 0);
+ const inputParserRef = (0, import_react15.useRef)(createInputParser());
+ const pendingInputFlushRef = (0, import_react15.useRef)(void 0);
+ const pendingInputFlushDelayMilliseconds = 20;
+ const clearPendingInputFlush = (0, import_react15.useCallback)(() => {
+ if (!pendingInputFlushRef.current) {
+ return;
+ }
+ clearTimeout(pendingInputFlushRef.current);
+ pendingInputFlushRef.current = void 0;
+ }, []);
+ const clearAnimationTimer = (0, import_react15.useCallback)(() => {
+ if (!animationTimerRef.current) {
+ return;
+ }
+ clearTimeout(animationTimerRef.current);
+ animationTimerRef.current = void 0;
+ }, []);
+ const scheduleAnimationTick = (0, import_react15.useCallback)(() => {
+ clearAnimationTimer();
+ if (animationSubscribersRef.current.size === 0) {
+ return;
+ }
+ let nextDueTime = Number.POSITIVE_INFINITY;
+ for (const subscriber of animationSubscribersRef.current.values()) {
+ nextDueTime = Math.min(nextDueTime, subscriber.nextDueTime);
+ }
+ const delay = Math.max(0, nextDueTime - performance.now());
+ animationTimerRef.current = setTimeout(() => {
+ animationTimerRef.current = void 0;
+ const currentTime = performance.now();
+ for (const subscriber of animationSubscribersRef.current.values()) {
+ if (currentTime < subscriber.nextDueTime) {
+ continue;
+ }
+ subscriber.callback(currentTime);
+ const elapsedTime = currentTime - subscriber.startTime;
+ const elapsedFrames = Math.floor(elapsedTime / subscriber.interval) + 1;
+ subscriber.nextDueTime = subscriber.startTime + elapsedFrames * subscriber.interval;
+ }
+ scheduleAnimationTick();
+ }, delay);
+ }, [clearAnimationTimer]);
+ const animationSubscribe = (0, import_react15.useCallback)((callback, interval) => {
+ const startTime = performance.now();
+ animationSubscribersRef.current.set(callback, {
+ callback,
+ interval,
+ startTime,
+ nextDueTime: startTime + interval
+ });
+ scheduleAnimationTick();
+ return {
+ startTime,
+ unsubscribe() {
+ animationSubscribersRef.current.delete(callback);
+ if (animationSubscribersRef.current.size === 0) {
+ clearAnimationTimer();
+ return;
+ }
+ scheduleAnimationTick();
+ }
+ };
+ }, [clearAnimationTimer, scheduleAnimationTick]);
+ (0, import_react15.useEffect)(() => {
+ return () => {
+ clearAnimationTimer();
+ };
+ }, [clearAnimationTimer]);
+ const isRawModeSupported = stdin.isTTY;
+ const detachReadableListener = (0, import_react15.useCallback)(() => {
+ if (!readableListenerRef.current) {
+ return;
+ }
+ stdin.removeListener("readable", readableListenerRef.current);
+ readableListenerRef.current = void 0;
+ }, [stdin]);
+ const clearInputState = (0, import_react15.useCallback)(() => {
+ inputParserRef.current.reset();
+ clearPendingInputFlush();
+ detachReadableListener();
+ }, [clearPendingInputFlush, detachReadableListener]);
+ const disableRawMode = (0, import_react15.useCallback)(() => {
+ pendingDisableRawModeRef.current = false;
+ stdin.setRawMode(false);
+ stdin.unref();
+ rawModeEnabledCount.current = 0;
+ clearInputState();
+ }, [stdin, clearInputState]);
+ const handleExit = (0, import_react15.useCallback)((errorOrResult) => {
+ if (isRawModeSupported && (rawModeEnabledCount.current > 0 || pendingDisableRawModeRef.current)) {
+ disableRawMode();
+ }
+ onExit(errorOrResult);
+ }, [isRawModeSupported, disableRawMode, onExit]);
+ const handleInput = (0, import_react15.useCallback)((input) => {
+ if (input === "" && exitOnCtrlC) {
+ handleExit();
+ return;
+ }
+ if (input === escape3 && isFocusEnabled) {
+ setActiveFocusId(void 0);
+ }
+ }, [exitOnCtrlC, handleExit, isFocusEnabled]);
+ const emitInput = (0, import_react15.useCallback)((input) => {
+ handleInput(input);
+ internal_eventEmitter.current.emit("input", input);
+ }, [handleInput]);
+ const schedulePendingInputFlush = (0, import_react15.useCallback)(() => {
+ clearPendingInputFlush();
+ pendingInputFlushRef.current = setTimeout(() => {
+ pendingInputFlushRef.current = void 0;
+ const pendingEscape = inputParserRef.current.flushPendingEscape();
+ if (!pendingEscape) {
+ return;
+ }
+ emitInput(pendingEscape);
+ }, pendingInputFlushDelayMilliseconds);
+ }, [clearPendingInputFlush, emitInput]);
+ const handleReadable = (0, import_react15.useCallback)(() => {
+ clearPendingInputFlush();
+ let chunk;
+ while ((chunk = stdin.read()) !== null) {
+ const inputEvents = inputParserRef.current.push(chunk);
+ for (const event of inputEvents) {
+ if (typeof event === "string") {
+ emitInput(event);
+ } else {
+ if (internal_eventEmitter.current.listenerCount("paste") === 0) {
+ emitInput(event.paste);
+ continue;
+ }
+ internal_eventEmitter.current.emit("paste", event.paste);
+ }
+ }
+ }
+ if (inputParserRef.current.hasPendingEscape()) {
+ schedulePendingInputFlush();
+ }
+ }, [stdin, emitInput, clearPendingInputFlush, schedulePendingInputFlush]);
+ const attachReadableListener = (0, import_react15.useCallback)(() => {
+ if (readableListenerRef.current) {
+ return;
+ }
+ readableListenerRef.current = handleReadable;
+ stdin.addListener("readable", handleReadable);
+ }, [stdin, handleReadable]);
+ const handleSetRawMode = (0, import_react15.useCallback)((isEnabled) => {
+ if (!isRawModeSupported) {
+ if (stdin === process11.stdin) {
+ throw new Error("Raw mode is not supported on the current process.stdin, which Ink uses as input stream by default.\nRead about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported");
+ } else {
+ throw new Error("Raw mode is not supported on the stdin provided to Ink.\nRead about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported");
+ }
+ }
+ stdin.setEncoding("utf8");
+ if (isEnabled) {
+ if (rawModeEnabledCount.current === 0) {
+ const isRawModeAlreadyEnabled = pendingDisableRawModeRef.current;
+ pendingDisableRawModeRef.current = false;
+ if (!isRawModeAlreadyEnabled) {
+ stdin.ref();
+ stdin.setRawMode(true);
+ }
+ attachReadableListener();
+ }
+ rawModeEnabledCount.current++;
+ return;
+ }
+ if (rawModeEnabledCount.current === 0) {
+ return;
+ }
+ if (--rawModeEnabledCount.current === 0) {
+ clearInputState();
+ pendingDisableRawModeRef.current = true;
+ queueMicrotask(() => {
+ if (!pendingDisableRawModeRef.current) {
+ return;
+ }
+ disableRawMode();
+ });
+ }
+ }, [
+ isRawModeSupported,
+ stdin,
+ attachReadableListener,
+ clearInputState,
+ disableRawMode
+ ]);
+ const handleSetBracketedPasteMode = (0, import_react15.useCallback)((isEnabled) => {
+ if (!stdout.isTTY) {
+ return;
+ }
+ if (isEnabled) {
+ if (bracketedPasteModeEnabledCount.current === 0) {
+ stdout.write("\x1B[?2004h");
+ }
+ bracketedPasteModeEnabledCount.current++;
+ return;
+ }
+ if (bracketedPasteModeEnabledCount.current === 0) {
+ return;
+ }
+ if (--bracketedPasteModeEnabledCount.current === 0) {
+ stdout.write("\x1B[?2004l");
+ }
+ }, [stdout]);
+ const suspendedInputStateRef = (0, import_react15.useRef)({
+ rawMode: false,
+ bracketedPaste: false
+ });
+ const pauseInput = (0, import_react15.useCallback)(() => {
+ const wasRawMode = isRawModeSupported && rawModeEnabledCount.current > 0;
+ const wasBracketedPaste = bracketedPasteModeEnabledCount.current > 0;
+ suspendedInputStateRef.current = {
+ rawMode: wasRawMode,
+ bracketedPaste: wasBracketedPaste
+ };
+ if (wasBracketedPaste && stdout.isTTY) {
+ try {
+ stdout.write("\x1B[?2004l");
+ } catch {
+ }
+ }
+ if (wasRawMode) {
+ stdin.setRawMode(false);
+ stdin.unref();
+ clearInputState();
+ }
+ }, [isRawModeSupported, stdin, stdout, clearInputState]);
+ const resumeInput = (0, import_react15.useCallback)(() => {
+ const { rawMode, bracketedPaste } = suspendedInputStateRef.current;
+ if (rawMode) {
+ stdin.setEncoding("utf8");
+ stdin.ref();
+ stdin.setRawMode(true);
+ attachReadableListener();
+ }
+ if (bracketedPaste && stdout.isTTY) {
+ try {
+ stdout.write("\x1B[?2004h");
+ } catch {
+ }
+ }
+ }, [stdin, stdout, attachReadableListener]);
+ (0, import_react15.useInsertionEffect)(() => {
+ onRegisterInputControl(pauseInput, resumeInput);
+ }, [onRegisterInputControl, pauseInput, resumeInput]);
+ const findNextFocusable = (0, import_react15.useCallback)((currentFocusables, currentActiveFocusId) => {
+ const activeIndex = currentFocusables.findIndex((focusable) => {
+ return focusable.id === currentActiveFocusId;
+ });
+ for (let index = activeIndex + 1; index < currentFocusables.length; index++) {
+ const focusable = currentFocusables[index];
+ if (focusable?.isActive) {
+ return focusable.id;
+ }
+ }
+ return void 0;
+ }, []);
+ const findPreviousFocusable = (0, import_react15.useCallback)((currentFocusables, currentActiveFocusId) => {
+ const activeIndex = currentFocusables.findIndex((focusable) => {
+ return focusable.id === currentActiveFocusId;
+ });
+ for (let index = activeIndex - 1; index >= 0; index--) {
+ const focusable = currentFocusables[index];
+ if (focusable?.isActive) {
+ return focusable.id;
+ }
+ }
+ return void 0;
+ }, []);
+ const focusNext = (0, import_react15.useCallback)(() => {
+ setFocusables((currentFocusables) => {
+ setActiveFocusId((currentActiveFocusId) => {
+ const firstFocusableId = currentFocusables.find((focusable) => focusable.isActive)?.id;
+ const nextFocusableId = findNextFocusable(currentFocusables, currentActiveFocusId);
+ return nextFocusableId ?? firstFocusableId;
+ });
+ return currentFocusables;
+ });
+ }, [findNextFocusable]);
+ const focusPrevious = (0, import_react15.useCallback)(() => {
+ setFocusables((currentFocusables) => {
+ setActiveFocusId((currentActiveFocusId) => {
+ const lastFocusableId = currentFocusables.findLast((focusable) => focusable.isActive)?.id;
+ const previousFocusableId = findPreviousFocusable(currentFocusables, currentActiveFocusId);
+ return previousFocusableId ?? lastFocusableId;
+ });
+ return currentFocusables;
+ });
+ }, [findPreviousFocusable]);
+ (0, import_react15.useEffect)(() => {
+ const handleTabNavigation = /* @__PURE__ */ __name((input) => {
+ if (!isFocusEnabled || focusablesCountRef.current === 0)
+ return;
+ if (input === tab) {
+ focusNext();
+ }
+ if (input === shiftTab) {
+ focusPrevious();
+ }
+ }, "handleTabNavigation");
+ internal_eventEmitter.current.on("input", handleTabNavigation);
+ const emitter = internal_eventEmitter.current;
+ return () => {
+ emitter.off("input", handleTabNavigation);
+ };
+ }, [isFocusEnabled, focusNext, focusPrevious]);
+ const enableFocus = (0, import_react15.useCallback)(() => {
+ setIsFocusEnabled(true);
+ }, []);
+ const disableFocus = (0, import_react15.useCallback)(() => {
+ setIsFocusEnabled(false);
+ }, []);
+ const focus = (0, import_react15.useCallback)((id) => {
+ setFocusables((currentFocusables) => {
+ const hasFocusableId = currentFocusables.some((focusable) => focusable?.id === id);
+ if (hasFocusableId) {
+ setActiveFocusId(id);
+ }
+ return currentFocusables;
+ });
+ }, []);
+ const addFocusable = (0, import_react15.useCallback)((id, { autoFocus }) => {
+ setFocusables((currentFocusables) => {
+ focusablesCountRef.current = currentFocusables.length + 1;
+ return [
+ ...currentFocusables,
+ {
+ id,
+ isActive: true
+ }
+ ];
+ });
+ if (autoFocus) {
+ setActiveFocusId((currentActiveFocusId) => {
+ if (!currentActiveFocusId) {
+ return id;
+ }
+ return currentActiveFocusId;
+ });
+ }
+ }, []);
+ const removeFocusable = (0, import_react15.useCallback)((id) => {
+ setActiveFocusId((currentActiveFocusId) => {
+ if (currentActiveFocusId === id) {
+ return void 0;
+ }
+ return currentActiveFocusId;
+ });
+ setFocusables((currentFocusables) => {
+ const filtered = currentFocusables.filter((focusable) => {
+ return focusable.id !== id;
+ });
+ focusablesCountRef.current = filtered.length;
+ return filtered;
+ });
+ }, []);
+ const activateFocusable = (0, import_react15.useCallback)((id) => {
+ setFocusables((currentFocusables) => currentFocusables.map((focusable) => {
+ if (focusable.id !== id) {
+ return focusable;
+ }
+ return {
+ id,
+ isActive: true
+ };
+ }));
+ }, []);
+ const deactivateFocusable = (0, import_react15.useCallback)((id) => {
+ setActiveFocusId((currentActiveFocusId) => {
+ if (currentActiveFocusId === id) {
+ return void 0;
+ }
+ return currentActiveFocusId;
+ });
+ setFocusables((currentFocusables) => currentFocusables.map((focusable) => {
+ if (focusable.id !== id) {
+ return focusable;
+ }
+ return {
+ id,
+ isActive: false
+ };
+ }));
+ }, []);
+ (0, import_react15.useEffect)(() => {
+ return () => {
+ const canWriteToStdout = !stdout.destroyed && !stdout.writableEnded;
+ if (interactive && canWriteToStdout) {
+ cli_cursor_default.show(stdout);
+ }
+ if (isRawModeSupported && (rawModeEnabledCount.current > 0 || pendingDisableRawModeRef.current)) {
+ disableRawMode();
+ }
+ if (bracketedPasteModeEnabledCount.current > 0) {
+ if (stdout.isTTY && canWriteToStdout) {
+ stdout.write("\x1B[?2004l");
+ }
+ bracketedPasteModeEnabledCount.current = 0;
+ }
+ };
+ }, [stdout, isRawModeSupported, disableRawMode, interactive]);
+ const appContextValue = (0, import_react15.useMemo)(() => ({
+ exit: handleExit,
+ waitUntilRenderFlush: onWaitUntilRenderFlush,
+ suspendTerminal: onSuspendTerminal
+ }), [handleExit, onWaitUntilRenderFlush, onSuspendTerminal]);
+ const stdinContextValue = (0, import_react15.useMemo)(() => ({
+ stdin,
+ setRawMode: handleSetRawMode,
+ setBracketedPasteMode: handleSetBracketedPasteMode,
+ isRawModeSupported,
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ internal_exitOnCtrlC: exitOnCtrlC,
+ // eslint-disable-next-line @typescript-eslint/naming-convention
+ internal_eventEmitter: internal_eventEmitter.current
+ }), [
+ stdin,
+ handleSetRawMode,
+ handleSetBracketedPasteMode,
+ isRawModeSupported,
+ exitOnCtrlC
+ ]);
+ const stdoutContextValue = (0, import_react15.useMemo)(() => ({
+ stdout,
+ write: writeToStdout
+ }), [stdout, writeToStdout]);
+ const stderrContextValue = (0, import_react15.useMemo)(() => ({
+ stderr,
+ write: writeToStderr
+ }), [stderr, writeToStderr]);
+ const cursorContextValue = (0, import_react15.useMemo)(() => ({
+ setCursorPosition
+ }), [setCursorPosition]);
+ const focusContextValue = (0, import_react15.useMemo)(() => ({
+ activeId: activeFocusId,
+ add: addFocusable,
+ remove: removeFocusable,
+ activate: activateFocusable,
+ deactivate: deactivateFocusable,
+ enableFocus,
+ disableFocus,
+ focusNext,
+ focusPrevious,
+ focus
+ }), [
+ activeFocusId,
+ addFocusable,
+ removeFocusable,
+ activateFocusable,
+ deactivateFocusable,
+ enableFocus,
+ disableFocus,
+ focusNext,
+ focusPrevious,
+ focus
+ ]);
+ const animationContextValue = (0, import_react15.useMemo)(() => ({
+ renderThrottleMs,
+ subscribe: animationSubscribe
+ }), [animationSubscribe, renderThrottleMs]);
+ return import_react15.default.createElement(
+ AppContext_default.Provider,
+ { value: appContextValue },
+ import_react15.default.createElement(
+ StdinContext_default.Provider,
+ { value: stdinContextValue },
+ import_react15.default.createElement(
+ StdoutContext_default.Provider,
+ { value: stdoutContextValue },
+ import_react15.default.createElement(
+ StderrContext_default.Provider,
+ { value: stderrContextValue },
+ import_react15.default.createElement(
+ FocusContext_default.Provider,
+ { value: focusContextValue },
+ import_react15.default.createElement(
+ AnimationContext_default.Provider,
+ { value: animationContextValue },
+ import_react15.default.createElement(
+ CursorContext_default.Provider,
+ { value: cursorContextValue },
+ import_react15.default.createElement(ErrorBoundary, { onError: handleExit }, children)
+ )
+ )
+ )
+ )
+ )
+ )
+ );
+}
+__name(App, "App");
+App.displayName = "InternalApp";
+var App_default = App;
+
+// node_modules/ink/build/kitty-keyboard.js
+init_esbuild_shims();
+var kittyFlags = {
+ disambiguateEscapeCodes: 1,
+ reportEventTypes: 2,
+ reportAlternateKeys: 4,
+ reportAllKeysAsEscapeCodes: 8,
+ reportAssociatedText: 16
+};
+function resolveFlags(flags) {
+ let result = 0;
+ for (const flag of flags) {
+ result |= kittyFlags[flag];
+ }
+ return result;
+}
+__name(resolveFlags, "resolveFlags");
+var kittyModifiers = {
+ shift: 1,
+ alt: 2,
+ ctrl: 4,
+ super: 8,
+ hyper: 16,
+ meta: 32,
+ capsLock: 64,
+ numLock: 128
+};
+
+// node_modules/ink/build/ink.js
+var noop = /* @__PURE__ */ __name(() => {
+}, "noop");
+var textEncoder = new TextEncoder();
+var yieldImmediate = /* @__PURE__ */ __name(async () => new Promise((resolve16) => {
+ setImmediate(resolve16);
+}), "yieldImmediate");
+var kittyQueryEscapeByte = 27;
+var kittyQueryOpenBracketByte = 91;
+var kittyQueryQuestionMarkByte = 63;
+var kittyQueryLetterByte = 117;
+var zeroByte = 48;
+var nineByte = 57;
+var isDigitByte = /* @__PURE__ */ __name((byte) => byte >= zeroByte && byte <= nineByte, "isDigitByte");
+var matchKittyQueryResponse = /* @__PURE__ */ __name((buffer, startIndex) => {
+ if (buffer[startIndex] !== kittyQueryEscapeByte || buffer[startIndex + 1] !== kittyQueryOpenBracketByte || buffer[startIndex + 2] !== kittyQueryQuestionMarkByte) {
+ return void 0;
+ }
+ let index = startIndex + 3;
+ const digitsStartIndex = index;
+ while (index < buffer.length && isDigitByte(buffer[index])) {
+ index++;
+ }
+ if (index === digitsStartIndex) {
+ return void 0;
+ }
+ if (index === buffer.length) {
+ return { state: "partial" };
+ }
+ if (buffer[index] === kittyQueryLetterByte) {
+ return { state: "complete", endIndex: index };
+ }
+ return void 0;
+}, "matchKittyQueryResponse");
+var hasCompleteKittyQueryResponse = /* @__PURE__ */ __name((buffer) => {
+ for (let index = 0; index < buffer.length; index++) {
+ const match = matchKittyQueryResponse(buffer, index);
+ if (match?.state === "complete") {
+ return true;
+ }
+ }
+ return false;
+}, "hasCompleteKittyQueryResponse");
+var stripKittyQueryResponsesAndTrailingPartial = /* @__PURE__ */ __name((buffer) => {
+ const keptBytes = [];
+ let index = 0;
+ while (index < buffer.length) {
+ const match = matchKittyQueryResponse(buffer, index);
+ if (match?.state === "complete") {
+ index = match.endIndex + 1;
+ continue;
+ }
+ if (match?.state === "partial") {
+ break;
+ }
+ keptBytes.push(buffer[index]);
+ index++;
+ }
+ return keptBytes;
+}, "stripKittyQueryResponsesAndTrailingPartial");
+var isWindowsConsole = process12.platform === "win32";
+var shouldClearTerminalForFrame = /* @__PURE__ */ __name(({ isTty, viewportRows, previousOutputHeight, nextOutputHeight, isUnmounting }) => {
+ if (!isTty) {
+ return false;
+ }
+ const hadPreviousFrame = previousOutputHeight > 0;
+ const wasFullscreen = previousOutputHeight >= viewportRows;
+ const wasOverflowing = previousOutputHeight > viewportRows;
+ const isOverflowing = nextOutputHeight > viewportRows;
+ const isFullscreen = nextOutputHeight >= viewportRows;
+ const isLeavingFullscreen = wasFullscreen && nextOutputHeight < viewportRows;
+ const shouldClearOnUnmount = isUnmounting && wasFullscreen;
+ if (isWindowsConsole && (wasFullscreen || isFullscreen)) {
+ return true;
+ }
+ return (
+ // Overflowing frames still need full clear fallback.
+ wasOverflowing || isOverflowing && hadPreviousFrame || // Clear when shrinking from fullscreen to non-fullscreen output.
+ isLeavingFullscreen || // Preserve legacy unmount behavior for fullscreen frames: final teardown
+ // render should clear once to avoid leaving a scrolled viewport state.
+ shouldClearOnUnmount
+ );
+}, "shouldClearTerminalForFrame");
+var isErrorInput = /* @__PURE__ */ __name((value) => {
+ return value instanceof Error || Object.prototype.toString.call(value) === "[object Error]";
+}, "isErrorInput");
+var getWritableStreamState = /* @__PURE__ */ __name((stdout) => {
+ const canWriteToStdout = !stdout.destroyed && !stdout.writableEnded && (stdout.writable ?? true);
+ const hasWritableState = stdout._writableState !== void 0 || stdout.writableLength !== void 0;
+ return {
+ canWriteToStdout,
+ hasWritableState
+ };
+}, "getWritableStreamState");
+var settleThrottle = /* @__PURE__ */ __name((throttled, canWriteToStdout) => {
+ if (!throttled || typeof throttled.flush !== "function") {
+ return;
+ }
+ const throttledValue = throttled;
+ if (canWriteToStdout) {
+ throttledValue.flush();
+ } else if (typeof throttledValue.cancel === "function") {
+ throttledValue.cancel();
+ }
+}, "settleThrottle");
+var Ink = class {
+ static {
+ __name(this, "Ink");
+ }
+ /**
+ Whether this instance is using concurrent rendering mode.
+ */
+ isConcurrent;
+ options;
+ log;
+ cursorPosition;
+ throttledLog;
+ isScreenReaderEnabled;
+ interactive;
+ renderThrottleMs;
+ alternateScreen;
+ // Ignore last render after unmounting a tree to prevent empty output before exit
+ isUnmounted;
+ isUnmounting;
+ lastOutput;
+ lastOutputToRender;
+ lastOutputHeight;
+ lastTerminalWidth;
+ container;
+ rootNode;
+ // This variable is used only in debug mode to store full static output
+ // so that it's rerendered every time, not just new static parts, like in non-debug mode
+ fullStaticOutput;
+ exitPromise;
+ exitResult;
+ beforeExitHandler;
+ restoreConsole;
+ unsubscribeResize;
+ throttledOnRender;
+ hasPendingThrottledRender = false;
+ kittyProtocolEnabled = false;
+ kittyFlags;
+ cancelKittyDetection;
+ nextRenderCommit;
+ // Set while suspendTerminal() has handed the terminal to a child process.
+ isSuspended = false;
+ // Input pause/resume hooks registered by the App component, which owns raw
+ // mode and bracketed paste state.
+ pauseInput;
+ resumeInput;
+ constructor(options2) {
+ autoBind(this);
+ this.options = options2;
+ this.rootNode = createNode("ink-root");
+ this.rootNode.onComputeLayout = this.calculateLayout;
+ this.isScreenReaderEnabled = options2.isScreenReaderEnabled ?? process12.env["INK_SCREEN_READER"] === "true";
+ this.interactive = this.resolveInteractiveOption(options2.interactive);
+ this.alternateScreen = false;
+ const unthrottled = options2.debug || this.isScreenReaderEnabled;
+ const maxFps = options2.maxFps ?? 30;
+ const renderThrottleMs = maxFps > 0 ? Math.max(1, Math.ceil(1e3 / maxFps)) : 0;
+ this.renderThrottleMs = unthrottled ? 0 : renderThrottleMs;
+ if (unthrottled) {
+ this.rootNode.onRender = this.onRender;
+ this.throttledOnRender = void 0;
+ } else {
+ const throttled = throttle(this.onRender, renderThrottleMs, {
+ leading: true,
+ trailing: true
+ });
+ this.rootNode.onRender = () => {
+ this.hasPendingThrottledRender = true;
+ throttled();
+ };
+ this.throttledOnRender = throttled;
+ }
+ this.rootNode.onImmediateRender = this.onRender;
+ this.rootNode.onStaticChange = this.handleStaticChange;
+ this.log = log_update_default.create(options2.stdout, {
+ incremental: options2.incrementalRendering
+ });
+ this.cursorPosition = void 0;
+ this.throttledLog = unthrottled ? this.log : throttle((output) => {
+ const shouldWrite = this.log.willRender(output);
+ const sync = this.shouldSync();
+ if (sync && shouldWrite) {
+ this.options.stdout.write(bsu);
+ }
+ this.log(output);
+ if (sync && shouldWrite) {
+ this.options.stdout.write(esu);
+ }
+ }, void 0, {
+ leading: true,
+ trailing: true
+ });
+ this.isUnmounted = false;
+ this.isUnmounting = false;
+ this.isConcurrent = options2.concurrent ?? false;
+ this.lastOutput = "";
+ this.lastOutputToRender = "";
+ this.lastOutputHeight = 0;
+ this.lastTerminalWidth = getWindowSize(this.options.stdout).columns;
+ this.fullStaticOutput = "";
+ const rootTag = options2.concurrent ? import_constants2.ConcurrentRoot : import_constants2.LegacyRoot;
+ this.container = reconciler_default.createContainer(this.rootNode, rootTag, null, false, null, "id", () => {
+ }, () => {
+ }, () => {
+ }, () => {
+ });
+ this.unsubscribeExit = (0, import_signal_exit2.default)(this.unmount, { alwaysLast: false });
+ this.setAlternateScreen(Boolean(options2.alternateScreen));
+ if (process12.env["DEV"] === "true") {
+ reconciler_default.injectIntoDevTools();
+ }
+ if (options2.patchConsole) {
+ this.patchConsole();
+ }
+ if (this.interactive) {
+ options2.stdout.on("resize", this.resized);
+ this.unsubscribeResize = () => {
+ options2.stdout.off("resize", this.resized);
+ };
+ }
+ this.initKittyKeyboard();
+ this.exitPromise = new Promise((resolve16, reject) => {
+ this.resolveExitPromise = resolve16;
+ this.rejectExitPromise = reject;
+ });
+ void this.exitPromise.catch(noop);
+ }
+ resized = /* @__PURE__ */ __name(() => {
+ const currentWidth = getWindowSize(this.options.stdout).columns;
+ if (currentWidth < this.lastTerminalWidth) {
+ this.log.clear();
+ this.lastOutput = "";
+ this.lastOutputToRender = "";
+ }
+ this.calculateLayout();
+ emitLayoutListeners(this.rootNode);
+ this.onRender();
+ this.lastTerminalWidth = currentWidth;
+ }, "resized");
+ resolveExitPromise = /* @__PURE__ */ __name(() => {
+ }, "resolveExitPromise");
+ rejectExitPromise = /* @__PURE__ */ __name(() => {
+ }, "rejectExitPromise");
+ unsubscribeExit = /* @__PURE__ */ __name(() => {
+ }, "unsubscribeExit");
+ handleAppExit = /* @__PURE__ */ __name((errorOrResult) => {
+ if (this.isUnmounted || this.isUnmounting) {
+ return;
+ }
+ if (isErrorInput(errorOrResult)) {
+ this.unmount(errorOrResult);
+ return;
+ }
+ this.exitResult = errorOrResult;
+ this.unmount();
+ }, "handleAppExit");
+ setCursorPosition = /* @__PURE__ */ __name((position) => {
+ this.cursorPosition = position;
+ this.log.setCursorPosition(position);
+ }, "setCursorPosition");
+ restoreLastOutput = /* @__PURE__ */ __name(() => {
+ if (!this.interactive) {
+ return;
+ }
+ this.log.setCursorPosition(this.cursorPosition);
+ this.log(this.lastOutputToRender || this.lastOutput + "\n");
+ }, "restoreLastOutput");
+ calculateLayout = /* @__PURE__ */ __name(() => {
+ const terminalWidth = getWindowSize(this.options.stdout).columns;
+ this.rootNode.yogaNode.setWidth(terminalWidth);
+ this.rootNode.yogaNode.calculateLayout(void 0, void 0, src_default.DIRECTION_LTR);
+ }, "calculateLayout");
+ // Resets `fullStaticOutput` when the identity changes so stale items from a previous instance are not replayed on future rewrites.
+ handleStaticChange = /* @__PURE__ */ __name(() => {
+ this.fullStaticOutput = "";
+ }, "handleStaticChange");
+ onRender = /* @__PURE__ */ __name(() => {
+ this.hasPendingThrottledRender = false;
+ if (this.isUnmounted) {
+ return;
+ }
+ if (this.isSuspended) {
+ if (this.nextRenderCommit) {
+ this.nextRenderCommit.resolve();
+ this.nextRenderCommit = void 0;
+ }
+ return;
+ }
+ if (this.nextRenderCommit) {
+ this.nextRenderCommit.resolve();
+ this.nextRenderCommit = void 0;
+ }
+ const startTime = performance.now();
+ const { output, outputHeight, staticOutput } = renderer_default(this.rootNode, this.isScreenReaderEnabled);
+ this.options.onRender?.({ renderTime: performance.now() - startTime });
+ const hasStaticOutput = staticOutput && staticOutput !== "\n";
+ if (this.options.debug) {
+ if (hasStaticOutput) {
+ this.fullStaticOutput += staticOutput;
+ }
+ this.lastOutput = output;
+ this.lastOutputToRender = output;
+ this.lastOutputHeight = outputHeight;
+ this.options.stdout.write(this.fullStaticOutput + output);
+ return;
+ }
+ if (!this.interactive) {
+ if (hasStaticOutput) {
+ this.options.stdout.write(staticOutput);
+ }
+ this.lastOutput = output;
+ this.lastOutputToRender = output + "\n";
+ this.lastOutputHeight = outputHeight;
+ return;
+ }
+ if (this.isScreenReaderEnabled) {
+ const sync = this.shouldSync();
+ if (sync) {
+ this.options.stdout.write(bsu);
+ }
+ if (hasStaticOutput) {
+ const erase = this.lastOutputHeight > 0 ? base_exports.eraseLines(this.lastOutputHeight) : "";
+ this.options.stdout.write(erase + staticOutput);
+ this.lastOutputHeight = 0;
+ }
+ if (output === this.lastOutput && !hasStaticOutput) {
+ if (sync) {
+ this.options.stdout.write(esu);
+ }
+ return;
+ }
+ const terminalWidth = getWindowSize(this.options.stdout).columns;
+ const wrappedOutput = wrapAnsi(output, terminalWidth, {
+ trim: false,
+ hard: true
+ });
+ if (hasStaticOutput) {
+ this.options.stdout.write(wrappedOutput);
+ } else {
+ const erase = this.lastOutputHeight > 0 ? base_exports.eraseLines(this.lastOutputHeight) : "";
+ this.options.stdout.write(erase + wrappedOutput);
+ }
+ this.lastOutput = output;
+ this.lastOutputToRender = wrappedOutput;
+ this.lastOutputHeight = wrappedOutput === "" ? 0 : wrappedOutput.split("\n").length;
+ if (sync) {
+ this.options.stdout.write(esu);
+ }
+ return;
+ }
+ if (hasStaticOutput) {
+ this.fullStaticOutput += staticOutput;
+ }
+ this.renderInteractiveFrame(output, outputHeight, hasStaticOutput ? staticOutput : "");
+ }, "onRender");
+ render(node) {
+ const tree = import_react16.default.createElement(
+ accessibilityContext.Provider,
+ { value: { isScreenReaderEnabled: this.isScreenReaderEnabled } },
+ import_react16.default.createElement(App_default, { stdin: this.options.stdin, stdout: this.options.stdout, stderr: this.options.stderr, exitOnCtrlC: this.options.exitOnCtrlC, interactive: this.interactive, renderThrottleMs: this.renderThrottleMs, writeToStdout: this.writeToStdout, writeToStderr: this.writeToStderr, setCursorPosition: this.setCursorPosition, onExit: this.handleAppExit, onWaitUntilRenderFlush: this.waitUntilRenderFlush, onSuspendTerminal: this.suspendTerminal, onRegisterInputControl: this.registerInputControl }, node)
+ );
+ if (this.options.concurrent) {
+ reconciler_default.updateContainer(tree, this.container, null, noop);
+ } else {
+ reconciler_default.updateContainerSync(tree, this.container, null, noop);
+ reconciler_default.flushSyncWork();
+ }
+ }
+ writeToStdout(data) {
+ if (this.isUnmounted) {
+ return;
+ }
+ if (this.isSuspended) {
+ return;
+ }
+ if (this.options.debug) {
+ this.options.stdout.write(data + this.fullStaticOutput + this.lastOutput);
+ return;
+ }
+ if (!this.interactive) {
+ this.options.stdout.write(data);
+ return;
+ }
+ const sync = this.shouldSync();
+ if (sync) {
+ this.options.stdout.write(bsu);
+ }
+ this.log.clear();
+ this.options.stdout.write(data);
+ this.restoreLastOutput();
+ if (sync) {
+ this.options.stdout.write(esu);
+ }
+ }
+ writeToStderr(data) {
+ if (this.isUnmounted) {
+ return;
+ }
+ if (this.isSuspended) {
+ return;
+ }
+ if (this.options.debug) {
+ this.options.stderr.write(data);
+ this.options.stdout.write(this.fullStaticOutput + this.lastOutput);
+ return;
+ }
+ if (!this.interactive) {
+ this.options.stderr.write(data);
+ return;
+ }
+ const sync = this.shouldSync();
+ if (sync) {
+ this.options.stdout.write(bsu);
+ }
+ this.log.clear();
+ this.options.stderr.write(data);
+ this.restoreLastOutput();
+ if (sync) {
+ this.options.stdout.write(esu);
+ }
+ }
+ // eslint-disable-next-line @typescript-eslint/no-restricted-types
+ unmount(error51) {
+ if (this.isUnmounted || this.isUnmounting) {
+ return;
+ }
+ this.isUnmounting = true;
+ if (this.beforeExitHandler) {
+ process12.off("beforeExit", this.beforeExitHandler);
+ this.beforeExitHandler = void 0;
+ }
+ const stdout = this.options.stdout;
+ const { canWriteToStdout, hasWritableState } = getWritableStreamState(stdout);
+ settleThrottle(this.throttledOnRender, canWriteToStdout);
+ if (canWriteToStdout) {
+ const shouldRenderFinalFrame = !this.throttledOnRender || !this.hasPendingThrottledRender && this.fullStaticOutput === "";
+ if (shouldRenderFinalFrame) {
+ this.calculateLayout();
+ this.onRender();
+ }
+ }
+ this.isUnmounted = true;
+ this.unsubscribeExit();
+ settleThrottle(this.throttledLog, canWriteToStdout);
+ if (typeof this.restoreConsole === "function") {
+ this.restoreConsole();
+ }
+ const finishUnmount = /* @__PURE__ */ __name(() => {
+ if (typeof this.unsubscribeResize === "function") {
+ this.unsubscribeResize();
+ }
+ if (this.cancelKittyDetection) {
+ this.cancelKittyDetection();
+ }
+ if (canWriteToStdout) {
+ if (this.kittyProtocolEnabled) {
+ this.writeBestEffort(this.options.stdout, "\x1B[ {
+ if (isErrorInput(error51)) {
+ this.rejectExitPromise(error51);
+ } else {
+ this.resolveExitPromise(exitResult);
+ }
+ }, "resolveOrReject");
+ const isProcessExiting = error51 !== void 0 && !isErrorInput(error51);
+ if (isProcessExiting) {
+ resolveOrReject();
+ } else if (canWriteToStdout && hasWritableState) {
+ this.options.stdout.write("", resolveOrReject);
+ } else {
+ setImmediate(resolveOrReject);
+ }
+ }, "finishUnmount");
+ const concurrentReconciler = reconciler_default;
+ if (this.options.concurrent) {
+ reconciler_default.updateContainerSync(null, this.container, null, noop);
+ reconciler_default.flushSyncWork();
+ concurrentReconciler.flushPassiveEffects?.();
+ finishUnmount();
+ } else {
+ reconciler_default.updateContainerSync(null, this.container, null, noop);
+ reconciler_default.flushSyncWork();
+ finishUnmount();
+ }
+ }
+ async waitUntilExit() {
+ if (!this.beforeExitHandler) {
+ this.beforeExitHandler = () => {
+ this.unmount();
+ };
+ process12.once("beforeExit", this.beforeExitHandler);
+ }
+ return this.exitPromise;
+ }
+ async waitUntilRenderFlush() {
+ if (this.isUnmounted || this.isUnmounting) {
+ await this.awaitExit();
+ return;
+ }
+ await yieldImmediate();
+ if (this.isUnmounted || this.isUnmounting) {
+ await this.awaitExit();
+ return;
+ }
+ if (this.isConcurrent && this.hasPendingConcurrentWork()) {
+ await Promise.race([this.awaitNextRender(), this.awaitExit()]);
+ if (this.isUnmounted || this.isUnmounting) {
+ this.nextRenderCommit = void 0;
+ await this.awaitExit();
+ return;
+ }
+ }
+ reconciler_default.flushSyncWork();
+ const stdout = this.options.stdout;
+ const { canWriteToStdout, hasWritableState } = getWritableStreamState(stdout);
+ settleThrottle(this.throttledOnRender, canWriteToStdout);
+ settleThrottle(this.throttledLog, canWriteToStdout);
+ if (canWriteToStdout && hasWritableState) {
+ await new Promise((resolve16) => {
+ this.options.stdout.write("", () => {
+ resolve16();
+ });
+ });
+ return;
+ }
+ await yieldImmediate();
+ }
+ clear() {
+ if (this.interactive && !this.options.debug) {
+ this.log.clear();
+ this.log.sync(this.lastOutputToRender || this.lastOutput + "\n");
+ }
+ }
+ patchConsole() {
+ if (this.options.debug) {
+ return;
+ }
+ this.restoreConsole = dist_default((stream, data) => {
+ if (stream === "stdout") {
+ this.writeToStdout(data);
+ }
+ if (stream === "stderr") {
+ const isReactMessage = data.startsWith("The above error occurred");
+ if (!isReactMessage) {
+ this.writeToStderr(data);
+ }
+ }
+ });
+ }
+ registerInputControl(pauseInput, resumeInput) {
+ this.pauseInput = pauseInput;
+ this.resumeInput = resumeInput;
+ }
+ async suspendTerminal(callback) {
+ this.beginSuspend();
+ if (callback) {
+ try {
+ await callback();
+ } finally {
+ await this.endSuspend();
+ }
+ return void 0;
+ }
+ const resume = /* @__PURE__ */ __name(async () => {
+ await this.endSuspend();
+ }, "resume");
+ return { resume, [Symbol.asyncDispose]: resume };
+ }
+ setAlternateScreen(enabled) {
+ this.alternateScreen = this.resolveAlternateScreenOption(enabled, this.interactive);
+ if (this.alternateScreen) {
+ this.writeBestEffort(this.options.stdout, base_exports.enterAlternativeScreen);
+ this.writeBestEffort(this.options.stdout, hideCursorEscape);
+ }
+ }
+ resolveInteractiveOption(interactive) {
+ return interactive ?? (!is_in_ci_default && Boolean(this.options.stdout.isTTY));
+ }
+ resolveAlternateScreenOption(alternateScreen, interactive) {
+ return Boolean(alternateScreen) && interactive && Boolean(this.options.stdout.isTTY);
+ }
+ shouldSync() {
+ return shouldSynchronize(this.options.stdout, this.interactive);
+ }
+ // Best-effort write: streams may already be destroyed during shutdown.
+ writeBestEffort(stream, data) {
+ try {
+ stream.write(data);
+ } catch {
+ }
+ }
+ // Waits for the exit promise to settle, suppressing any rejection.
+ // Errors are surfaced via waitUntilExit() instead.
+ async awaitExit() {
+ try {
+ await this.exitPromise;
+ } catch {
+ }
+ }
+ hasPendingConcurrentWork() {
+ const concurrentContainer = this.container;
+ return (concurrentContainer.pendingLanes ?? 0) !== 0 && concurrentContainer.callbackNode !== void 0 && concurrentContainer.callbackNode !== null;
+ }
+ async awaitNextRender() {
+ if (!this.nextRenderCommit) {
+ let resolveRender;
+ const promise2 = new Promise((resolve16) => {
+ resolveRender = resolve16;
+ });
+ this.nextRenderCommit = { promise: promise2, resolve: resolveRender };
+ }
+ return this.nextRenderCommit.promise;
+ }
+ renderInteractiveFrame(output, outputHeight, staticOutput) {
+ const hasStaticOutput = staticOutput !== "";
+ const isTty = this.options.stdout.isTTY;
+ const viewportRows = isTty ? getWindowSize(this.options.stdout).rows : 24;
+ const isFullscreen = isTty && outputHeight >= viewportRows;
+ const outputToRender = isFullscreen ? output : output + "\n";
+ const shouldClearTerminal = shouldClearTerminalForFrame({
+ isTty,
+ viewportRows,
+ previousOutputHeight: this.lastOutputHeight,
+ nextOutputHeight: outputHeight,
+ isUnmounting: this.isUnmounting
+ });
+ if (shouldClearTerminal) {
+ const sync = this.shouldSync();
+ if (sync) {
+ this.options.stdout.write(bsu);
+ }
+ this.options.stdout.write(base_exports.clearTerminal + this.fullStaticOutput + output);
+ this.lastOutput = output;
+ this.lastOutputToRender = outputToRender;
+ this.lastOutputHeight = outputHeight;
+ this.log.sync(outputToRender);
+ if (sync) {
+ this.options.stdout.write(esu);
+ }
+ return;
+ }
+ if (hasStaticOutput) {
+ const sync = this.shouldSync();
+ if (sync) {
+ this.options.stdout.write(bsu);
+ }
+ this.log.clear();
+ this.options.stdout.write(staticOutput);
+ this.log(outputToRender);
+ if (sync) {
+ this.options.stdout.write(esu);
+ }
+ } else if (output !== this.lastOutput || this.log.isCursorDirty()) {
+ this.throttledLog(outputToRender);
+ }
+ this.lastOutput = output;
+ this.lastOutputToRender = outputToRender;
+ this.lastOutputHeight = outputHeight;
+ }
+ initKittyKeyboard() {
+ if (!this.options.kittyKeyboard) {
+ return;
+ }
+ const opts = this.options.kittyKeyboard;
+ const mode = opts.mode ?? "auto";
+ if (mode === "disabled") {
+ return;
+ }
+ const flags = opts.flags ?? ["disambiguateEscapeCodes"];
+ if (mode === "enabled") {
+ if (this.options.stdin.isTTY && this.options.stdout.isTTY) {
+ this.enableKittyProtocol(flags);
+ }
+ return;
+ }
+ if (!this.interactive || !this.options.stdin.isTTY || !this.options.stdout.isTTY) {
+ return;
+ }
+ this.confirmKittySupport(flags);
+ }
+ confirmKittySupport(flags) {
+ const { stdin, stdout } = this.options;
+ let responseBuffer = [];
+ const cleanup = /* @__PURE__ */ __name(() => {
+ this.cancelKittyDetection = void 0;
+ clearTimeout(timer);
+ stdin.removeListener("data", onData);
+ const remaining = stripKittyQueryResponsesAndTrailingPartial(responseBuffer);
+ responseBuffer = [];
+ if (remaining.length > 0) {
+ stdin.unshift(Uint8Array.from(remaining));
+ }
+ }, "cleanup");
+ const onData = /* @__PURE__ */ __name((data) => {
+ const chunk = typeof data === "string" ? textEncoder.encode(data) : data;
+ for (const byte of chunk) {
+ responseBuffer.push(byte);
+ }
+ if (hasCompleteKittyQueryResponse(responseBuffer)) {
+ cleanup();
+ if (!this.isUnmounted) {
+ this.enableKittyProtocol(flags);
+ }
+ }
+ }, "onData");
+ stdin.on("data", onData);
+ const timer = setTimeout(cleanup, 200);
+ this.cancelKittyDetection = cleanup;
+ stdout.write("\x1B[?u");
+ }
+ enableKittyProtocol(flags) {
+ this.options.stdout.write(`\x1B[>${resolveFlags(flags)}u`);
+ this.kittyProtocolEnabled = true;
+ this.kittyFlags = flags;
+ }
+ beginSuspend() {
+ if (this.isSuspended) {
+ throw new Error("The terminal is already suspended. Resume the current suspension before suspending again.");
+ }
+ this.isSuspended = true;
+ if (!this.interactive || this.isUnmounted || this.isUnmounting) {
+ return;
+ }
+ try {
+ const stdout = this.options.stdout;
+ const { canWriteToStdout } = getWritableStreamState(stdout);
+ settleThrottle(this.throttledOnRender, canWriteToStdout);
+ settleThrottle(this.throttledLog, canWriteToStdout);
+ if (canWriteToStdout) {
+ this.log.clear();
+ this.log.done();
+ if (this.kittyProtocolEnabled) {
+ this.writeBestEffort(this.options.stdout, "\x1B[${resolveFlags(this.kittyFlags)}u`);
+ }
+ }
+ this.lastOutput = "";
+ this.lastOutputToRender = "";
+ this.lastOutputHeight = 0;
+ this.log.reset();
+ try {
+ this.calculateLayout();
+ this.onRender();
+ await this.waitUntilRenderFlush();
+ } catch {
+ }
+ }
+};
+
+// node_modules/ink/build/render.js
+var render = /* @__PURE__ */ __name((node, options2) => {
+ const inkOptions = {
+ stdout: process13.stdout,
+ stdin: process13.stdin,
+ stderr: process13.stderr,
+ debug: false,
+ exitOnCtrlC: true,
+ patchConsole: true,
+ maxFps: 30,
+ incrementalRendering: false,
+ concurrent: false,
+ alternateScreen: false,
+ ...getOptions(options2)
+ };
+ const instance = getInstance(inkOptions.stdout, () => new Ink(inkOptions));
+ instance.render(node);
+ return {
+ rerender: instance.render,
+ unmount() {
+ instance.unmount();
+ },
+ waitUntilExit: instance.waitUntilExit,
+ waitUntilRenderFlush: instance.waitUntilRenderFlush,
+ cleanup() {
+ instance.unmount();
+ },
+ clear: instance.clear
+ };
+}, "render");
+var render_default = render;
+var getOptions = /* @__PURE__ */ __name((stdout = {}) => {
+ if (stdout instanceof Stream) {
+ return {
+ stdout,
+ stdin: process13.stdin
+ };
+ }
+ return stdout;
+}, "getOptions");
+var getInstance = /* @__PURE__ */ __name((stdout, createInstance) => {
+ const instance = instances_default.get(stdout);
+ if (instance === void 0) {
+ const newInstance = createInstance();
+ instances_default.set(stdout, newInstance);
+ return newInstance;
+ }
+ process13.stderr.write("Warning: render() was called again for the same stdout before the previous Ink instance was unmounted. Reusing stdout across multiple render() calls is unsupported. Call unmount() first.\n");
+ return instance;
+}, "getInstance");
+
+// node_modules/ink/build/render-to-string.js
+init_esbuild_shims();
+var import_constants3 = __toESM(require_constants(), 1);
+
+// node_modules/ink/build/components/Static.js
+init_esbuild_shims();
+var import_react17 = __toESM(require_react(), 1);
+function Static(props) {
+ const { items, children: render2, style: customStyle } = props;
+ const [index, setIndex] = (0, import_react17.useState)(0);
+ const itemsToRender = (0, import_react17.useMemo)(() => {
+ return items.slice(index);
+ }, [items, index]);
+ (0, import_react17.useLayoutEffect)(() => {
+ setIndex(items.length);
+ }, [items.length]);
+ const children = itemsToRender.map((item, itemIndex) => {
+ return render2(item, index + itemIndex);
+ });
+ const style = (0, import_react17.useMemo)(() => ({
+ position: "absolute",
+ flexDirection: "column",
+ ...customStyle
+ }), [customStyle]);
+ return import_react17.default.createElement("ink-box", { internal_static: true, style }, children);
+}
+__name(Static, "Static");
+
+// node_modules/ink/build/components/Transform.js
+init_esbuild_shims();
+var import_react18 = __toESM(require_react(), 1);
+function Transform({ children, transform: transform2, accessibilityLabel }) {
+ const { isScreenReaderEnabled } = (0, import_react18.useContext)(accessibilityContext);
+ if (children === void 0 || children === null) {
+ return null;
+ }
+ return import_react18.default.createElement("ink-text", { style: { flexGrow: 0, flexShrink: 1, flexDirection: "row" }, internal_transform: transform2 }, isScreenReaderEnabled && accessibilityLabel ? accessibilityLabel : children);
+}
+__name(Transform, "Transform");
+
+// node_modules/ink/build/components/Newline.js
+init_esbuild_shims();
+var import_react19 = __toESM(require_react(), 1);
+
+// node_modules/ink/build/components/Spacer.js
+init_esbuild_shims();
+var import_react20 = __toESM(require_react(), 1);
+
+// node_modules/ink/build/hooks/use-input.js
+init_esbuild_shims();
+var import_react22 = __toESM(require_react(), 1);
+
+// node_modules/ink/build/parse-keypress.js
+init_esbuild_shims();
+var textDecoder = new TextDecoder();
+var metaKeyCodeRe = /^(?:\x1b)([a-zA-Z0-9])$/;
+var fnKeyRe = /^(?:\x1b+)(O|N|\[|\[\[)(?:(\d+)(?:;(\d+))?([~^$])|(?:1;)?(\d+)?([a-zA-Z]))/;
+var keyName = {
+ /* xterm/gnome ESC O letter */
+ OP: "f1",
+ OQ: "f2",
+ OR: "f3",
+ OS: "f4",
+ /* vt220-style ESC [ letter (e.g. Ctrl+F1 sends ESC [ 1 ; 5 P) */
+ "[P": "f1",
+ "[Q": "f2",
+ "[R": "f3",
+ "[S": "f4",
+ /* xterm/rxvt ESC [ number ~ */
+ "[11~": "f1",
+ "[12~": "f2",
+ "[13~": "f3",
+ "[14~": "f4",
+ /* from Cygwin and used in libuv */
+ "[[A": "f1",
+ "[[B": "f2",
+ "[[C": "f3",
+ "[[D": "f4",
+ "[[E": "f5",
+ /* common */
+ "[15~": "f5",
+ "[17~": "f6",
+ "[18~": "f7",
+ "[19~": "f8",
+ "[20~": "f9",
+ "[21~": "f10",
+ "[23~": "f11",
+ "[24~": "f12",
+ /* xterm ESC [ letter */
+ "[A": "up",
+ "[B": "down",
+ "[C": "right",
+ "[D": "left",
+ "[E": "clear",
+ "[F": "end",
+ "[H": "home",
+ /* xterm/gnome ESC O letter */
+ OA: "up",
+ OB: "down",
+ OC: "right",
+ OD: "left",
+ OE: "clear",
+ OF: "end",
+ OH: "home",
+ /* xterm/rxvt ESC [ number ~ */
+ "[1~": "home",
+ "[2~": "insert",
+ "[3~": "delete",
+ "[4~": "end",
+ "[5~": "pageup",
+ "[6~": "pagedown",
+ /* putty */
+ "[[5~": "pageup",
+ "[[6~": "pagedown",
+ /* rxvt */
+ "[7~": "home",
+ "[8~": "end",
+ /* rxvt keys with modifiers */
+ "[a": "up",
+ "[b": "down",
+ "[c": "right",
+ "[d": "left",
+ "[e": "clear",
+ "[2$": "insert",
+ "[3$": "delete",
+ "[5$": "pageup",
+ "[6$": "pagedown",
+ "[7$": "home",
+ "[8$": "end",
+ Oa: "up",
+ Ob: "down",
+ Oc: "right",
+ Od: "left",
+ Oe: "clear",
+ "[2^": "insert",
+ "[3^": "delete",
+ "[5^": "pageup",
+ "[6^": "pagedown",
+ "[7^": "home",
+ "[8^": "end",
+ /* misc. */
+ "[Z": "tab"
+};
+var nonAlphanumericKeys = [...Object.values(keyName), "backspace"];
+var isShiftKey = /* @__PURE__ */ __name((code) => {
+ return [
+ "[a",
+ "[b",
+ "[c",
+ "[d",
+ "[e",
+ "[2$",
+ "[3$",
+ "[5$",
+ "[6$",
+ "[7$",
+ "[8$",
+ "[Z"
+ ].includes(code);
+}, "isShiftKey");
+var isCtrlKey = /* @__PURE__ */ __name((code) => {
+ return [
+ "Oa",
+ "Ob",
+ "Oc",
+ "Od",
+ "Oe",
+ "[2^",
+ "[3^",
+ "[5^",
+ "[6^",
+ "[7^",
+ "[8^"
+ ].includes(code);
+}, "isCtrlKey");
+var kittyKeyRe = /^\x1b\[(\d+)(?:;(\d+)(?::(\d+))?(?:;([\d:]+))?)?u$/;
+var kittySpecialKeyRe = /^\x1b\[(\d+);(\d+):(\d+)([A-Za-z~])$/;
+var kittySpecialLetterKeys = {
+ A: "up",
+ B: "down",
+ C: "right",
+ D: "left",
+ E: "clear",
+ F: "end",
+ H: "home",
+ P: "f1",
+ Q: "f2",
+ R: "f3",
+ S: "f4"
+};
+var kittySpecialNumberKeys = {
+ 2: "insert",
+ 3: "delete",
+ 5: "pageup",
+ 6: "pagedown",
+ 7: "home",
+ 8: "end",
+ 11: "f1",
+ 12: "f2",
+ 13: "f3",
+ 14: "f4",
+ 15: "f5",
+ 17: "f6",
+ 18: "f7",
+ 19: "f8",
+ 20: "f9",
+ 21: "f10",
+ 23: "f11",
+ 24: "f12"
+};
+var kittyCodepointNames = {
+ 27: "escape",
+ // 13 (return) and 32 (space) are handled before this lookup
+ // in parseKittyKeypress so they can be marked as printable.
+ 9: "tab",
+ 127: "backspace",
+ 8: "backspace",
+ 57358: "capslock",
+ 57359: "scrolllock",
+ 57360: "numlock",
+ 57361: "printscreen",
+ 57362: "pause",
+ 57363: "menu",
+ 57376: "f13",
+ 57377: "f14",
+ 57378: "f15",
+ 57379: "f16",
+ 57380: "f17",
+ 57381: "f18",
+ 57382: "f19",
+ 57383: "f20",
+ 57384: "f21",
+ 57385: "f22",
+ 57386: "f23",
+ 57387: "f24",
+ 57388: "f25",
+ 57389: "f26",
+ 57390: "f27",
+ 57391: "f28",
+ 57392: "f29",
+ 57393: "f30",
+ 57394: "f31",
+ 57395: "f32",
+ 57396: "f33",
+ 57397: "f34",
+ 57398: "f35",
+ 57399: "kp0",
+ 57400: "kp1",
+ 57401: "kp2",
+ 57402: "kp3",
+ 57403: "kp4",
+ 57404: "kp5",
+ 57405: "kp6",
+ 57406: "kp7",
+ 57407: "kp8",
+ 57408: "kp9",
+ 57409: "kpdecimal",
+ 57410: "kpdivide",
+ 57411: "kpmultiply",
+ 57412: "kpsubtract",
+ 57413: "kpadd",
+ 57414: "kpenter",
+ 57415: "kpequal",
+ 57416: "kpseparator",
+ 57417: "kpleft",
+ 57418: "kpright",
+ 57419: "kpup",
+ 57420: "kpdown",
+ 57421: "kppageup",
+ 57422: "kppagedown",
+ 57423: "kphome",
+ 57424: "kpend",
+ 57425: "kpinsert",
+ 57426: "kpdelete",
+ 57427: "kpbegin",
+ 57428: "mediaplay",
+ 57429: "mediapause",
+ 57430: "mediaplaypause",
+ 57431: "mediareverse",
+ 57432: "mediastop",
+ 57433: "mediafastforward",
+ 57434: "mediarewind",
+ 57435: "mediatracknext",
+ 57436: "mediatrackprevious",
+ 57437: "mediarecord",
+ 57438: "lowervolume",
+ 57439: "raisevolume",
+ 57440: "mutevolume",
+ 57441: "leftshift",
+ 57442: "leftcontrol",
+ 57443: "leftalt",
+ 57444: "leftsuper",
+ 57445: "lefthyper",
+ 57446: "leftmeta",
+ 57447: "rightshift",
+ 57448: "rightcontrol",
+ 57449: "rightalt",
+ 57450: "rightsuper",
+ 57451: "righthyper",
+ 57452: "rightmeta",
+ 57453: "isoLevel3Shift",
+ 57454: "isoLevel5Shift"
+};
+var isValidCodepoint = /* @__PURE__ */ __name((cp) => cp >= 0 && cp <= 1114111 && !(cp >= 55296 && cp <= 57343), "isValidCodepoint");
+var safeFromCodePoint = /* @__PURE__ */ __name((cp) => isValidCodepoint(cp) ? String.fromCodePoint(cp) : "?", "safeFromCodePoint");
+function resolveEventType(value) {
+ if (value === 3)
+ return "release";
+ if (value === 2)
+ return "repeat";
+ return "press";
+}
+__name(resolveEventType, "resolveEventType");
+function parseKittyModifiers(modifiers) {
+ return {
+ ctrl: !!(modifiers & kittyModifiers.ctrl),
+ shift: !!(modifiers & kittyModifiers.shift),
+ meta: !!(modifiers & (kittyModifiers.meta | kittyModifiers.alt)),
+ super: !!(modifiers & kittyModifiers.super),
+ hyper: !!(modifiers & kittyModifiers.hyper),
+ capsLock: !!(modifiers & kittyModifiers.capsLock),
+ numLock: !!(modifiers & kittyModifiers.numLock)
+ };
+}
+__name(parseKittyModifiers, "parseKittyModifiers");
+var parseKittyKeypress = /* @__PURE__ */ __name((s) => {
+ const match = kittyKeyRe.exec(s);
+ if (!match)
+ return null;
+ const codepoint = parseInt(match[1], 10);
+ const modifiers = match[2] ? Math.max(0, parseInt(match[2], 10) - 1) : 0;
+ const eventType = match[3] ? parseInt(match[3], 10) : 1;
+ const textField = match[4];
+ if (!isValidCodepoint(codepoint)) {
+ return null;
+ }
+ let text;
+ if (textField) {
+ text = textField.split(":").map((cp) => safeFromCodePoint(parseInt(cp, 10))).join("");
+ }
+ let name;
+ let isPrintable;
+ if (codepoint === 32) {
+ name = "space";
+ isPrintable = true;
+ } else if (codepoint === 13) {
+ name = "return";
+ isPrintable = true;
+ } else if (kittyCodepointNames[codepoint]) {
+ name = kittyCodepointNames[codepoint];
+ isPrintable = false;
+ } else if (codepoint >= 1 && codepoint <= 26) {
+ name = String.fromCodePoint(codepoint + 96);
+ isPrintable = false;
+ } else {
+ name = safeFromCodePoint(codepoint).toLowerCase();
+ isPrintable = true;
+ }
+ if (isPrintable && !text) {
+ text = safeFromCodePoint(codepoint);
+ }
+ return {
+ name,
+ ...parseKittyModifiers(modifiers),
+ eventType: resolveEventType(eventType),
+ sequence: s,
+ raw: s,
+ isKittyProtocol: true,
+ isPrintable,
+ text
+ };
+}, "parseKittyKeypress");
+var parseKittySpecialKey = /* @__PURE__ */ __name((s) => {
+ const match = kittySpecialKeyRe.exec(s);
+ if (!match)
+ return null;
+ const number4 = parseInt(match[1], 10);
+ const modifiers = Math.max(0, parseInt(match[2], 10) - 1);
+ const eventType = parseInt(match[3], 10);
+ const terminator = match[4];
+ const name = terminator === "~" ? kittySpecialNumberKeys[number4] : kittySpecialLetterKeys[terminator];
+ if (!name)
+ return null;
+ return {
+ name,
+ ...parseKittyModifiers(modifiers),
+ eventType: resolveEventType(eventType),
+ sequence: s,
+ raw: s,
+ isKittyProtocol: true,
+ isPrintable: false
+ };
+}, "parseKittySpecialKey");
+var parseKeypress = /* @__PURE__ */ __name((s = "") => {
+ let parts;
+ if (s instanceof Uint8Array) {
+ if (s[0] > 127 && s[1] === void 0) {
+ s[0] -= 128;
+ s = "\x1B" + textDecoder.decode(s);
+ } else {
+ s = textDecoder.decode(s);
+ }
+ } else if (s !== void 0 && typeof s !== "string") {
+ s = String(s);
+ } else if (!s) {
+ s = "";
+ }
+ const kittyResult = parseKittyKeypress(s);
+ if (kittyResult)
+ return kittyResult;
+ const kittySpecialResult = parseKittySpecialKey(s);
+ if (kittySpecialResult)
+ return kittySpecialResult;
+ if (kittyKeyRe.test(s)) {
+ return {
+ name: "",
+ ctrl: false,
+ meta: false,
+ shift: false,
+ sequence: s,
+ raw: s,
+ isKittyProtocol: true,
+ isPrintable: false
+ };
+ }
+ const key = {
+ name: "",
+ ctrl: false,
+ meta: false,
+ shift: false,
+ sequence: s,
+ raw: s
+ };
+ key.sequence = key.sequence || s || key.name;
+ if (s === "\r" || s === "\x1B\r") {
+ key.raw = void 0;
+ key.name = "return";
+ key.meta = s.length === 2;
+ } else if (s === "\n") {
+ key.name = "enter";
+ } else if (s === " ") {
+ key.name = "tab";
+ } else if (s === "\b" || s === "\x1B\b") {
+ key.name = "backspace";
+ key.meta = s.charAt(0) === "\x1B";
+ } else if (s === "\x7F" || s === "\x1B\x7F") {
+ key.name = "backspace";
+ key.meta = s.charAt(0) === "\x1B";
+ } else if (s === "\x1B" || s === "\x1B\x1B") {
+ key.name = "escape";
+ key.meta = s.length === 2;
+ } else if (s === " " || s === "\x1B ") {
+ key.name = "space";
+ key.meta = s.length === 2;
+ } else if (s.length === 1 && s <= "") {
+ key.name = String.fromCharCode(s.charCodeAt(0) + "a".charCodeAt(0) - 1);
+ key.ctrl = true;
+ } else if (s.length === 1 && s >= "0" && s <= "9") {
+ key.name = "number";
+ } else if (s.length === 1 && s >= "a" && s <= "z") {
+ key.name = s;
+ } else if (s.length === 1 && s >= "A" && s <= "Z") {
+ key.name = s.toLowerCase();
+ key.shift = true;
+ } else if (parts = metaKeyCodeRe.exec(s)) {
+ key.name = parts[1].toLowerCase();
+ key.meta = true;
+ key.shift = /^[A-Z]$/.test(parts[1]);
+ } else if (parts = fnKeyRe.exec(s)) {
+ const segs = [...s];
+ if (segs[0] === "\x1B" && segs[1] === "\x1B") {
+ key.meta = true;
+ }
+ const code = [parts[1], parts[2], parts[4], parts[6]].filter(Boolean).join("");
+ const modifier = (parts[3] || parts[5] || 1) - 1;
+ key.ctrl = !!(modifier & 4);
+ key.meta = key.meta || !!(modifier & 10);
+ key.shift = !!(modifier & 1);
+ key.code = code;
+ key.name = keyName[code] ?? "";
+ key.shift = isShiftKey(code) || key.shift;
+ key.ctrl = isCtrlKey(code) || key.ctrl;
+ }
+ return key;
+}, "parseKeypress");
+var parse_keypress_default = parseKeypress;
+
+// node_modules/ink/build/hooks/use-stdin.js
+init_esbuild_shims();
+var import_react21 = __toESM(require_react(), 1);
+var useStdin = /* @__PURE__ */ __name(() => (0, import_react21.useContext)(StdinContext_default), "useStdin");
+var useStdinContext = /* @__PURE__ */ __name(() => (0, import_react21.useContext)(StdinContext_default), "useStdinContext");
+var use_stdin_default = useStdin;
+
+// node_modules/ink/build/hooks/use-input.js
+var useInput = /* @__PURE__ */ __name((inputHandler, options2 = {}) => {
+ const { setRawMode, internal_exitOnCtrlC, internal_eventEmitter } = useStdinContext();
+ (0, import_react22.useEffect)(() => {
+ if (options2.isActive === false) {
+ return;
+ }
+ setRawMode(true);
+ return () => {
+ setRawMode(false);
+ };
+ }, [options2.isActive, setRawMode]);
+ const handleData = (0, import_react22.useEffectEvent)((data) => {
+ const keypress = parse_keypress_default(data);
+ const key = {
+ upArrow: keypress.name === "up",
+ downArrow: keypress.name === "down",
+ leftArrow: keypress.name === "left",
+ rightArrow: keypress.name === "right",
+ pageDown: keypress.name === "pagedown",
+ pageUp: keypress.name === "pageup",
+ home: keypress.name === "home",
+ end: keypress.name === "end",
+ return: keypress.name === "return",
+ escape: keypress.name === "escape",
+ ctrl: keypress.ctrl,
+ shift: keypress.shift,
+ tab: keypress.name === "tab",
+ backspace: keypress.name === "backspace",
+ delete: keypress.name === "delete",
+ meta: keypress.meta,
+ // Kitty keyboard protocol modifiers
+ super: keypress.super ?? false,
+ hyper: keypress.hyper ?? false,
+ capsLock: keypress.capsLock ?? false,
+ numLock: keypress.numLock ?? false,
+ eventType: keypress.eventType
+ };
+ let input;
+ if (keypress.isKittyProtocol) {
+ if (keypress.isPrintable) {
+ input = keypress.text ?? keypress.name;
+ } else if (keypress.ctrl && keypress.name.length === 1) {
+ input = keypress.name;
+ } else {
+ input = "";
+ }
+ } else if (keypress.ctrl) {
+ input = keypress.name ?? "";
+ } else {
+ input = keypress.sequence;
+ }
+ if (!keypress.isKittyProtocol && nonAlphanumericKeys.includes(keypress.name)) {
+ input = "";
+ }
+ if (input.startsWith("\x1B")) {
+ input = input.slice(1);
+ }
+ if (input.length === 1 && /[A-Z]/.test(input)) {
+ key.shift = true;
+ }
+ if (input === "c" && key.ctrl && internal_exitOnCtrlC) {
+ return;
+ }
+ reconciler_default.discreteUpdates(() => {
+ inputHandler(input, key);
+ });
+ });
+ (0, import_react22.useEffect)(() => {
+ if (options2.isActive === false) {
+ return;
+ }
+ internal_eventEmitter.on("input", handleData);
+ return () => {
+ internal_eventEmitter.removeListener("input", handleData);
+ };
+ }, [options2.isActive, internal_eventEmitter]);
+}, "useInput");
+var use_input_default = useInput;
+
+// node_modules/ink/build/hooks/use-paste.js
+init_esbuild_shims();
+var import_react23 = __toESM(require_react(), 1);
+
+// node_modules/ink/build/hooks/use-app.js
+init_esbuild_shims();
+var import_react24 = __toESM(require_react(), 1);
+var useApp = /* @__PURE__ */ __name(() => (0, import_react24.useContext)(AppContext_default), "useApp");
+var use_app_default = useApp;
+
+// node_modules/ink/build/hooks/use-stdout.js
+init_esbuild_shims();
+var import_react25 = __toESM(require_react(), 1);
+var useStdout = /* @__PURE__ */ __name(() => (0, import_react25.useContext)(StdoutContext_default), "useStdout");
+var use_stdout_default = useStdout;
+
+// node_modules/ink/build/hooks/use-stderr.js
+init_esbuild_shims();
+var import_react26 = __toESM(require_react(), 1);
+
+// node_modules/ink/build/hooks/use-focus.js
+init_esbuild_shims();
+var import_react27 = __toESM(require_react(), 1);
+
+// node_modules/ink/build/hooks/use-focus-manager.js
+init_esbuild_shims();
+var import_react28 = __toESM(require_react(), 1);
+
+// node_modules/ink/build/hooks/use-is-screen-reader-enabled.js
+init_esbuild_shims();
+var import_react29 = __toESM(require_react(), 1);
+
+// node_modules/ink/build/hooks/use-cursor.js
+init_esbuild_shims();
+var import_react30 = __toESM(require_react(), 1);
+var useCursor = /* @__PURE__ */ __name(() => {
+ const context = (0, import_react30.useContext)(CursorContext_default);
+ const positionRef = (0, import_react30.useRef)(void 0);
+ const setCursorPosition = (0, import_react30.useCallback)((position) => {
+ positionRef.current = position;
+ }, []);
+ (0, import_react30.useInsertionEffect)(() => {
+ context.setCursorPosition(positionRef.current);
+ return () => {
+ context.setCursorPosition(void 0);
+ };
+ });
+ return { setCursorPosition };
+}, "useCursor");
+var use_cursor_default = useCursor;
+
+// node_modules/ink/build/hooks/use-animation.js
+init_esbuild_shims();
+var import_react31 = __toESM(require_react(), 1);
+
+// node_modules/ink/build/hooks/use-window-size.js
+init_esbuild_shims();
+var import_react32 = __toESM(require_react(), 1);
+var useWindowSize = /* @__PURE__ */ __name(() => {
+ const { stdout } = use_stdout_default();
+ const [size, setSize] = (0, import_react32.useState)(() => getWindowSize(stdout));
+ (0, import_react32.useEffect)(() => {
+ const onResize = /* @__PURE__ */ __name(() => {
+ setSize(getWindowSize(stdout));
+ }, "onResize");
+ stdout.on("resize", onResize);
+ return () => {
+ stdout.off("resize", onResize);
+ };
+ }, [stdout]);
+ return size;
+}, "useWindowSize");
+var use_window_size_default = useWindowSize;
+
+// node_modules/ink/build/hooks/use-box-metrics.js
+init_esbuild_shims();
+var import_react33 = __toESM(require_react(), 1);
+var emptyMetrics = {
+ width: 0,
+ height: 0,
+ left: 0,
+ top: 0
+};
+var findRootNode = /* @__PURE__ */ __name((node) => {
+ if (!node) {
+ return void 0;
+ }
+ if (!node.parentNode) {
+ return node.nodeName === "ink-root" ? node : void 0;
+ }
+ return findRootNode(node.parentNode);
+}, "findRootNode");
+var useBoxMetrics = /* @__PURE__ */ __name((ref) => {
+ const [metrics, setMetrics] = (0, import_react33.useState)(emptyMetrics);
+ const [hasMeasured, setHasMeasured] = (0, import_react33.useState)(false);
+ const updateMetrics = (0, import_react33.useCallback)(() => {
+ const layout = ref.current?.yogaNode?.getComputedLayout() ?? emptyMetrics;
+ setMetrics((previousMetrics) => {
+ const hasChanged = previousMetrics.width !== layout.width || previousMetrics.height !== layout.height || previousMetrics.left !== layout.left || previousMetrics.top !== layout.top;
+ return hasChanged ? layout : previousMetrics;
+ });
+ setHasMeasured(Boolean(ref.current));
+ }, [ref]);
+ (0, import_react33.useEffect)(updateMetrics);
+ (0, import_react33.useEffect)(() => {
+ const rootNode = findRootNode(ref.current);
+ if (!rootNode) {
+ return;
+ }
+ return addLayoutListener(rootNode, updateMetrics);
+ });
+ return (0, import_react33.useMemo)(() => ({
+ ...metrics,
+ hasMeasured
+ }), [metrics, hasMeasured]);
+}, "useBoxMetrics");
+var use_box_metrics_default = useBoxMetrics;
+
+// node_modules/ink/build/measure-element.js
+init_esbuild_shims();
+
+// packages/cli/src/cli.tsx
+import { readFileSync as readFileSync16 } from "node:fs";
+import { join as join15 } from "node:path";
+import { homedir as homedir9 } from "node:os";
+
+// packages/core/src/index.ts
+init_esbuild_shims();
+
+// packages/core/src/settings.ts
+init_esbuild_shims();
+
+// packages/core/src/common/model-capabilities.ts
+init_esbuild_shims();
+var DEEPSEEK_V4_MODELS = /* @__PURE__ */ new Set(["deepseek-v4-flash", "deepseek-v4-pro"]);
+var NON_MULTIMODAL_MODELS = /* @__PURE__ */ new Set([
+ "deepseek-v4-pro",
+ "deepseek-v4-flash",
+ "deepseek-chat",
+ "deepseek-reasoner"
+]);
+function defaultsToThinkingMode(model) {
+ return DEEPSEEK_V4_MODELS.has(model);
+}
+__name(defaultsToThinkingMode, "defaultsToThinkingMode");
+function supportsMultimodal(model) {
+ return !NON_MULTIMODAL_MODELS.has(model.trim());
+}
+__name(supportsMultimodal, "supportsMultimodal");
+
+// packages/core/src/settings.ts
+import * as fs3 from "fs";
+import * as os3 from "os";
+import * as path from "path";
+function resolveReasoningEffort(value) {
+ return value === "high" || value === "max" ? value : void 0;
+}
+__name(resolveReasoningEffort, "resolveReasoningEffort");
+function parseBoolean(value) {
+ if (typeof value === "boolean") {
+ return value;
+ }
+ if (typeof value !== "string") {
+ return void 0;
+ }
+ const normalized = value.trim().toLowerCase();
+ if (["1", "true", "enabled", "yes", "on"].includes(normalized)) {
+ return true;
+ }
+ if (["0", "false", "disabled", "no", "off"].includes(normalized)) {
+ return false;
+ }
+ return void 0;
+}
+__name(parseBoolean, "parseBoolean");
+function parseTemperature(value) {
+ const raw = typeof value === "number" ? value : typeof value === "string" && value.trim() ? Number(value) : NaN;
+ if (!Number.isFinite(raw) || raw < 0 || raw > 2) {
+ return void 0;
+ }
+ return raw;
+}
+__name(parseTemperature, "parseTemperature");
+function trimString(value) {
+ return typeof value === "string" ? value.trim() : "";
+}
+__name(trimString, "trimString");
+var VALID_PERMISSION_SCOPES = /* @__PURE__ */ new Set([
+ "read-in-cwd",
+ "read-out-cwd",
+ "write-in-cwd",
+ "write-out-cwd",
+ "delete-in-cwd",
+ "delete-out-cwd",
+ "query-git-log",
+ "mutate-git-log",
+ "network",
+ "mcp"
+]);
+function normalizePermissionList(value) {
+ if (!Array.isArray(value)) {
+ return [];
+ }
+ const result = [];
+ for (const item of value) {
+ if (typeof item !== "string" || !VALID_PERMISSION_SCOPES.has(item)) {
+ continue;
+ }
+ const scope = item;
+ if (!result.includes(scope)) {
+ result.push(scope);
+ }
+ }
+ return result;
+}
+__name(normalizePermissionList, "normalizePermissionList");
+function mergePermissionLists(...lists) {
+ const result = [];
+ for (const list of lists) {
+ for (const scope of list ?? []) {
+ if (!result.includes(scope)) {
+ result.push(scope);
+ }
+ }
+ }
+ return result;
+}
+__name(mergePermissionLists, "mergePermissionLists");
+function normalizePermissionDefaultMode(value) {
+ return value === "allowAll" || value === "askAll" ? value : void 0;
+}
+__name(normalizePermissionDefaultMode, "normalizePermissionDefaultMode");
+function normalizePermissions(settings) {
+ return {
+ allow: normalizePermissionList(settings?.allow),
+ deny: normalizePermissionList(settings?.deny),
+ ask: normalizePermissionList(settings?.ask),
+ defaultMode: normalizePermissionDefaultMode(settings?.defaultMode) ?? "allowAll"
+ };
+}
+__name(normalizePermissions, "normalizePermissions");
+function mergePermissions(userSettings, projectSettings) {
+ const userPermissions = normalizePermissions(userSettings?.permissions);
+ const projectPermissions = normalizePermissions(projectSettings?.permissions);
+ return {
+ allow: mergePermissionLists(userPermissions.allow, projectPermissions.allow),
+ deny: mergePermissionLists(userPermissions.deny, projectPermissions.deny),
+ ask: mergePermissionLists(userPermissions.ask, projectPermissions.ask),
+ defaultMode: projectSettings?.permissions ? projectPermissions.defaultMode : userSettings?.permissions ? userPermissions.defaultMode : "allowAll"
+ };
+}
+__name(mergePermissions, "mergePermissions");
+function normalizeEnabledSkills(value) {
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
+ return {};
+ }
+ const result = {};
+ for (const [name, enabled] of Object.entries(value)) {
+ if (!name || typeof enabled !== "boolean") {
+ continue;
+ }
+ result[name] = enabled;
+ }
+ return result;
+}
+__name(normalizeEnabledSkills, "normalizeEnabledSkills");
+function mergeEnabledSkills(userSettings, projectSettings) {
+ return {
+ ...normalizeEnabledSkills(userSettings?.enabledSkills),
+ ...normalizeEnabledSkills(projectSettings?.enabledSkills)
+ };
+}
+__name(mergeEnabledSkills, "mergeEnabledSkills");
+var DEFAULT_STATUSLINE_REFRESH_MS = 2e3;
+var MIN_STATUSLINE_REFRESH_MS = 500;
+var DEFAULT_STATUSLINE_SEPARATOR = " \xB7 ";
+function isPlainObject(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+__name(isPlainObject, "isPlainObject");
+function normalizeStatusLineProvider(value) {
+ if (!isPlainObject(value)) {
+ return null;
+ }
+ const type2 = value["type"];
+ const idRaw = trimString(value["id"]);
+ const id = idRaw || void 0;
+ const timeoutRaw = value["timeoutMs"];
+ const timeoutMs = typeof timeoutRaw === "number" && Number.isFinite(timeoutRaw) && timeoutRaw > 0 ? Math.floor(timeoutRaw) : void 0;
+ const colorRaw = trimString(value["color"]);
+ const color = colorRaw || void 0;
+ const maxLengthRaw = value["maxLength"];
+ const maxLength = typeof maxLengthRaw === "number" && Number.isFinite(maxLengthRaw) && maxLengthRaw > 0 ? Math.floor(maxLengthRaw) : void 0;
+ const newLine = value["newLine"] === true ? true : void 0;
+ if (type2 === "command") {
+ const command2 = trimString(value["command"]);
+ if (!command2) {
+ return null;
+ }
+ const cwdRaw = trimString(value["cwd"]);
+ return {
+ type: "command",
+ id,
+ command: command2,
+ cwd: cwdRaw || void 0,
+ timeoutMs,
+ color,
+ newLine,
+ maxLength
+ };
+ }
+ if (type2 === "module") {
+ const modulePath = trimString(value["path"]);
+ if (!modulePath) {
+ return null;
+ }
+ return {
+ type: "module",
+ id,
+ path: modulePath,
+ timeoutMs,
+ color,
+ newLine,
+ maxLength
+ };
+ }
+ return null;
+}
+__name(normalizeStatusLineProvider, "normalizeStatusLineProvider");
+function normalizeStatusLine(value) {
+ if (!isPlainObject(value)) {
+ return null;
+ }
+ const result = {};
+ const enabled = parseBoolean(value["enabled"]);
+ if (enabled !== void 0) {
+ result.enabled = enabled;
+ }
+ const refreshRaw = value["refreshMs"];
+ if (typeof refreshRaw === "number" && Number.isFinite(refreshRaw) && refreshRaw >= MIN_STATUSLINE_REFRESH_MS) {
+ result.refreshMs = Math.floor(refreshRaw);
+ }
+ const separator = value["separator"];
+ if (typeof separator === "string") {
+ result.separator = separator;
+ }
+ const providers = value["providers"];
+ if (Array.isArray(providers)) {
+ const normalized = [];
+ for (const entry of providers) {
+ const provider = normalizeStatusLineProvider(entry);
+ if (provider) {
+ normalized.push(provider);
+ }
+ }
+ result.providers = normalized;
+ }
+ return result;
+}
+__name(normalizeStatusLine, "normalizeStatusLine");
+function mergeStatusLine(userSettings, projectSettings) {
+ const userConfig = normalizeStatusLine(userSettings?.statusline) ?? {};
+ const projectConfig = normalizeStatusLine(projectSettings?.statusline) ?? {};
+ const userProviders = userConfig.providers ?? [];
+ const projectProviders = projectConfig.providers ?? [];
+ const projectIds = new Set(projectProviders.map((p) => p.id));
+ const providers = [...userProviders.filter((p) => !projectIds.has(p.id)), ...projectProviders];
+ const enabled = projectConfig.enabled ?? userConfig.enabled ?? providers.length > 0;
+ const refreshMs = projectConfig.refreshMs ?? userConfig.refreshMs ?? DEFAULT_STATUSLINE_REFRESH_MS;
+ const separator = projectConfig.separator ?? userConfig.separator ?? DEFAULT_STATUSLINE_SEPARATOR;
+ return {
+ enabled,
+ refreshMs,
+ separator,
+ providers
+ };
+}
+__name(mergeStatusLine, "mergeStatusLine");
+function normalizeEnv(env6) {
+ const result = {};
+ if (!env6) {
+ return result;
+ }
+ for (const [key, value] of Object.entries(env6)) {
+ if (typeof value === "string") {
+ result[key] = value;
+ }
+ }
+ return result;
+}
+__name(normalizeEnv, "normalizeEnv");
+function collectDeepcodeEnv(processEnv = process.env) {
+ const result = {};
+ for (const [key, value] of Object.entries(processEnv)) {
+ if (!key.startsWith("DEEPCODE_") || typeof value !== "string") {
+ continue;
+ }
+ const strippedKey = key.slice("DEEPCODE_".length);
+ if (strippedKey) {
+ result[strippedKey] = value;
+ }
+ }
+ return result;
+}
+__name(collectDeepcodeEnv, "collectDeepcodeEnv");
+function extractMcpEnv(env6) {
+ const result = {};
+ for (const [key, value] of Object.entries(env6)) {
+ if (!key.startsWith("MCP_")) {
+ continue;
+ }
+ const strippedKey = key.slice("MCP_".length);
+ if (strippedKey) {
+ result[strippedKey] = value;
+ }
+ }
+ return result;
+}
+__name(extractMcpEnv, "extractMcpEnv");
+function mergeMcpServers(userSettings, projectSettings, userEnv, projectEnv, systemEnv) {
+ const userServers = userSettings?.mcpServers ?? {};
+ const projectServers = projectSettings?.mcpServers ?? {};
+ const serverNames = /* @__PURE__ */ new Set([...Object.keys(userServers), ...Object.keys(projectServers)]);
+ if (serverNames.size === 0) {
+ return void 0;
+ }
+ const userMcpEnv = extractMcpEnv(userEnv);
+ const projectMcpEnv = extractMcpEnv(projectEnv);
+ const systemMcpEnv = extractMcpEnv(systemEnv);
+ const merged = {};
+ for (const name of serverNames) {
+ const userConfig = userServers[name];
+ const projectConfig = projectServers[name];
+ const command2 = projectConfig?.command ?? userConfig?.command;
+ if (!command2) {
+ continue;
+ }
+ const env6 = {
+ ...userEnv,
+ ...userConfig?.env ?? {},
+ ...userMcpEnv,
+ ...projectEnv,
+ ...projectConfig?.env ?? {},
+ ...projectMcpEnv,
+ ...systemEnv,
+ ...systemMcpEnv
+ };
+ const config2 = {
+ command: command2,
+ args: projectConfig?.args ?? userConfig?.args
+ };
+ if (Object.keys(env6).length > 0) {
+ config2.env = env6;
+ }
+ merged[name] = config2;
+ }
+ return Object.keys(merged).length > 0 ? merged : void 0;
+}
+__name(mergeMcpServers, "mergeMcpServers");
+function resolveSettingsSources(userSettings, projectSettings, defaults2, processEnv = process.env) {
+ const userEnv = normalizeEnv(userSettings?.env);
+ const projectEnv = normalizeEnv(projectSettings?.env);
+ const systemEnv = collectDeepcodeEnv(processEnv);
+ const env6 = {
+ ...userEnv,
+ ...projectEnv,
+ ...systemEnv
+ };
+ const model = trimString(systemEnv.MODEL) || trimString(projectSettings?.model) || trimString(projectEnv.MODEL) || trimString(userSettings?.model) || trimString(userEnv.MODEL) || defaults2.model;
+ const thinkingEnabled = parseBoolean(systemEnv.THINKING_ENABLED) ?? parseBoolean(projectSettings?.thinkingEnabled) ?? parseBoolean(projectEnv.THINKING_ENABLED) ?? parseBoolean(userSettings?.thinkingEnabled) ?? parseBoolean(userEnv.THINKING_ENABLED) ?? defaultsToThinkingMode(model);
+ const reasoningEffort = resolveReasoningEffort(systemEnv.REASONING_EFFORT) ?? resolveReasoningEffort(projectSettings?.reasoningEffort) ?? resolveReasoningEffort(projectEnv.REASONING_EFFORT) ?? resolveReasoningEffort(userSettings?.reasoningEffort) ?? resolveReasoningEffort(userEnv.REASONING_EFFORT) ?? "max";
+ const temperature = parseTemperature(systemEnv.TEMPERATURE) ?? parseTemperature(projectSettings?.temperature) ?? parseTemperature(projectEnv.TEMPERATURE) ?? parseTemperature(userSettings?.temperature) ?? parseTemperature(userEnv.TEMPERATURE);
+ const debugLogEnabled = parseBoolean(systemEnv.DEBUG_LOG_ENABLED) ?? parseBoolean(projectSettings?.debugLogEnabled) ?? parseBoolean(projectEnv.DEBUG_LOG_ENABLED) ?? parseBoolean(userSettings?.debugLogEnabled) ?? parseBoolean(userEnv.DEBUG_LOG_ENABLED) ?? false;
+ const telemetryEnabled = parseBoolean(systemEnv.TELEMETRY_ENABLED) ?? parseBoolean(projectSettings?.telemetryEnabled) ?? parseBoolean(projectEnv.TELEMETRY_ENABLED) ?? parseBoolean(userSettings?.telemetryEnabled) ?? parseBoolean(userEnv.TELEMETRY_ENABLED) ?? true;
+ const notify = trimString(systemEnv.NOTIFY) || trimString(projectSettings?.notify) || trimString(userSettings?.notify) || "";
+ const webSearchTool = trimString(systemEnv.WEB_SEARCH_TOOL) || trimString(projectSettings?.webSearchTool) || trimString(userSettings?.webSearchTool) || "";
+ return {
+ env: env6,
+ apiKey: trimString(env6.API_KEY) || void 0,
+ baseURL: trimString(env6.BASE_URL) || defaults2.baseURL,
+ model,
+ temperature,
+ thinkingEnabled,
+ reasoningEffort,
+ debugLogEnabled,
+ telemetryEnabled,
+ notify: notify || void 0,
+ webSearchTool: webSearchTool || void 0,
+ mcpServers: mergeMcpServers(userSettings, projectSettings, userEnv, projectEnv, systemEnv),
+ permissions: mergePermissions(userSettings, projectSettings),
+ enabledSkills: mergeEnabledSkills(userSettings, projectSettings),
+ statusline: mergeStatusLine(userSettings, projectSettings)
+ };
+}
+__name(resolveSettingsSources, "resolveSettingsSources");
+function modelConfigKey(config2) {
+ return config2.thinkingEnabled ? `thinking:${config2.reasoningEffort}` : "thinking:none";
+}
+__name(modelConfigKey, "modelConfigKey");
+function applyModelConfigSelection(settings, current, selected) {
+ const changed = selected.model !== current.model || modelConfigKey(selected) !== modelConfigKey(current);
+ const next = { ...settings ?? {} };
+ if (!changed) {
+ return { settings: next, changed: false };
+ }
+ if (selected.model !== current.model || Object.prototype.hasOwnProperty.call(next, "model")) {
+ next.model = selected.model;
+ } else {
+ delete next.model;
+ }
+ next.thinkingEnabled = selected.thinkingEnabled;
+ if (selected.thinkingEnabled) {
+ next.reasoningEffort = selected.reasoningEffort;
+ }
+ return { settings: next, changed: true };
+}
+__name(applyModelConfigSelection, "applyModelConfigSelection");
+var DEFAULT_MODEL = "deepseek-v4-pro";
+var DEFAULT_BASE_URL = "https://api.deepseek.com";
+function getUserSettingsPath() {
+ return path.join(os3.homedir(), ".deepcode", "settings.json");
+}
+__name(getUserSettingsPath, "getUserSettingsPath");
+function getProjectSettingsPath(projectRoot) {
+ return path.join(projectRoot, ".deepcode", "settings.json");
+}
+__name(getProjectSettingsPath, "getProjectSettingsPath");
+function readSettingsFile(settingsPath) {
+ try {
+ if (!fs3.existsSync(settingsPath)) {
+ return null;
+ }
+ const raw = fs3.readFileSync(settingsPath, "utf8");
+ return JSON.parse(raw);
+ } catch {
+ return null;
+ }
+}
+__name(readSettingsFile, "readSettingsFile");
+function readSettings() {
+ return readSettingsFile(getUserSettingsPath());
+}
+__name(readSettings, "readSettings");
+function readProjectSettings(projectRoot = process.cwd()) {
+ return readSettingsFile(getProjectSettingsPath(projectRoot));
+}
+__name(readProjectSettings, "readProjectSettings");
+function writeSettingsFile(settingsPath, settings) {
+ fs3.mkdirSync(path.dirname(settingsPath), { recursive: true });
+ fs3.writeFileSync(settingsPath, `${JSON.stringify(settings, null, 2)}
+`, "utf8");
+}
+__name(writeSettingsFile, "writeSettingsFile");
+function writeSettings(settings) {
+ const settingsPath = getUserSettingsPath();
+ writeSettingsFile(settingsPath, settings);
+}
+__name(writeSettings, "writeSettings");
+function writeProjectSettings(settings, projectRoot = process.cwd()) {
+ const settingsPath = getProjectSettingsPath(projectRoot);
+ writeSettingsFile(settingsPath, settings);
+}
+__name(writeProjectSettings, "writeProjectSettings");
+function writeModelConfigSelection(selection, current = resolveCurrentSettings(), projectRoot = process.cwd()) {
+ const projectSettingsPath = getProjectSettingsPath(projectRoot);
+ const shouldWriteProjectSettings = fs3.existsSync(projectSettingsPath);
+ const rawSettings = shouldWriteProjectSettings ? readProjectSettings(projectRoot) : readSettings();
+ const result = applyModelConfigSelection(rawSettings, current, selection);
+ if (result.changed) {
+ if (shouldWriteProjectSettings) {
+ writeProjectSettings(result.settings, projectRoot);
+ } else {
+ writeSettings(result.settings);
+ }
+ }
+ return result;
+}
+__name(writeModelConfigSelection, "writeModelConfigSelection");
+function resolveCurrentSettings(projectRoot = process.cwd()) {
+ const userPath = path.resolve(getUserSettingsPath());
+ const projectPath = path.resolve(getProjectSettingsPath(projectRoot));
+ const sameFile = userPath === projectPath;
+ return resolveSettingsSources(
+ readSettings(),
+ sameFile ? null : readProjectSettings(projectRoot),
+ {
+ model: DEFAULT_MODEL,
+ baseURL: DEFAULT_BASE_URL
+ },
+ process.env
+ );
+}
+__name(resolveCurrentSettings, "resolveCurrentSettings");
+
+// packages/core/src/session.ts
+init_esbuild_shims();
+var import_gray_matter2 = __toESM(require_gray_matter(), 1);
+import * as fs17 from "fs";
+import * as path14 from "path";
+import * as os9 from "os";
+import * as crypto3 from "crypto";
+
+// node_modules/ejs/lib/esm/ejs.js
+init_esbuild_shims();
+import fs4 from "node:fs";
+import path2 from "node:path";
+
+// node_modules/ejs/lib/esm/utils.js
+init_esbuild_shims();
+var utils = {};
+var regExpChars = /[|\\{}()[\]^$+*?.]/g;
+var hasOwnProperty = Object.prototype.hasOwnProperty;
+var hasOwn = /* @__PURE__ */ __name(function(obj, key) {
+ return hasOwnProperty.apply(obj, [key]);
+}, "hasOwn");
+utils.hasOwn = hasOwn;
+utils.escapeRegExpChars = function(string4) {
+ if (!string4) {
+ return "";
+ }
+ return String(string4).replace(regExpChars, "\\$&");
+};
+var _ENCODE_HTML_RULES = {
+ "&": "&",
+ "<": "<",
+ ">": ">",
+ '"': """,
+ "'": "'"
+};
+var _MATCH_HTML = /[&<>'"]/g;
+function encode_char(c) {
+ return _ENCODE_HTML_RULES[c] || c;
+}
+__name(encode_char, "encode_char");
+var escapeFuncStr = `var _ENCODE_HTML_RULES = {
+ "&": "&"
+ , "<": "<"
+ , ">": ">"
+ , '"': """
+ , "'": "'"
+ }
+ , _MATCH_HTML = /[&<>'"]/g;
+function encode_char(c) {
+ return _ENCODE_HTML_RULES[c] || c;
+};
+`;
+utils.escapeXML = function(markup) {
+ return markup == void 0 ? "" : String(markup).replace(_MATCH_HTML, encode_char);
+};
+function escapeXMLToString() {
+ return Function.prototype.toString.call(this) + ";\n" + escapeFuncStr;
+}
+__name(escapeXMLToString, "escapeXMLToString");
+try {
+ if (typeof Object.defineProperty === "function") {
+ Object.defineProperty(utils.escapeXML, "toString", { value: escapeXMLToString });
+ } else {
+ utils.escapeXML.toString = escapeXMLToString;
+ }
+} catch (err) {
+ console.warn("Unable to set escapeXML.toString (is the Function prototype frozen?)");
+}
+utils.shallowCopy = function(to, from) {
+ from = from || {};
+ if (to !== null && to !== void 0) {
+ for (var p in from) {
+ if (!hasOwn(from, p)) {
+ continue;
+ }
+ if (p === "__proto__" || p === "constructor") {
+ continue;
+ }
+ to[p] = from[p];
+ }
+ }
+ return to;
+};
+utils.shallowCopyFromList = function(to, from, list) {
+ list = list || [];
+ from = from || {};
+ if (to !== null && to !== void 0) {
+ for (var i = 0; i < list.length; i++) {
+ var p = list[i];
+ if (typeof from[p] != "undefined") {
+ if (!hasOwn(from, p)) {
+ continue;
+ }
+ if (p === "__proto__" || p === "constructor") {
+ continue;
+ }
+ to[p] = from[p];
+ }
+ }
+ }
+ return to;
+};
+utils.cache = {
+ _data: {},
+ set: /* @__PURE__ */ __name(function(key, val) {
+ this._data[key] = val;
+ }, "set"),
+ get: /* @__PURE__ */ __name(function(key) {
+ return this._data[key];
+ }, "get"),
+ remove: /* @__PURE__ */ __name(function(key) {
+ delete this._data[key];
+ }, "remove"),
+ reset: /* @__PURE__ */ __name(function() {
+ this._data = {};
+ }, "reset")
+};
+utils.hyphenToCamel = function(str3) {
+ return str3.replace(/-[a-z]/g, function(match) {
+ return match[1].toUpperCase();
+ });
+};
+utils.createNullProtoObjWherePossible = (function() {
+ if (typeof Object.create == "function") {
+ return function() {
+ return /* @__PURE__ */ Object.create(null);
+ };
+ }
+ if (!({ __proto__: null } instanceof Object)) {
+ return function() {
+ return { __proto__: null };
+ };
+ }
+ return function() {
+ return {};
+ };
+})();
+utils.hasOwnOnlyObject = function(obj) {
+ var o = utils.createNullProtoObjWherePossible();
+ for (var p in obj) {
+ if (hasOwn(obj, p)) {
+ o[p] = obj[p];
+ }
+ }
+ return o;
+};
+if (typeof exports != "undefined") {
+ module.exports = utils;
+}
+var utils_default = utils;
+
+// node_modules/ejs/lib/esm/ejs.js
+var DECLARATION_KEYWORD = "let";
+var ejs = {};
+var _DEFAULT_OPEN_DELIMITER = "<";
+var _DEFAULT_CLOSE_DELIMITER = ">";
+var _DEFAULT_DELIMITER = "%";
+var _DEFAULT_LOCALS_NAME = "locals";
+var _REGEX_STRING = "(<%%|%%>|<%=|<%-|<%_|<%#|<%|%>|-%>|_%>)";
+var _OPTS_PASSABLE_WITH_DATA = [
+ "delimiter",
+ "scope",
+ "context",
+ "debug",
+ "compileDebug",
+ "_with",
+ "rmWhitespace",
+ "strict",
+ "filename",
+ "async"
+];
+var _OPTS_PASSABLE_WITH_DATA_EXPRESS = _OPTS_PASSABLE_WITH_DATA.concat("cache");
+var _BOM = /^\uFEFF/;
+var _JS_IDENTIFIER = /^[a-zA-Z_$][0-9a-zA-Z_$]*$/;
+ejs.cache = utils_default.cache;
+ejs.fileLoader = fs4.readFileSync;
+ejs.localsName = _DEFAULT_LOCALS_NAME;
+ejs.promiseImpl = new Function("return this;")().Promise;
+ejs.resolveInclude = function(name, filename, isDir) {
+ let dirname13 = path2.dirname;
+ let extname4 = path2.extname;
+ let resolve16 = path2.resolve;
+ let includePath = resolve16(isDir ? filename : dirname13(filename), name);
+ let ext = extname4(name);
+ if (!ext) {
+ includePath += ".ejs";
+ }
+ return includePath;
+};
+function resolvePaths(name, paths) {
+ let filePath;
+ if (paths.some(function(v) {
+ filePath = ejs.resolveInclude(name, v, true);
+ return fs4.existsSync(filePath);
+ })) {
+ return filePath;
+ }
+}
+__name(resolvePaths, "resolvePaths");
+function getIncludePath(path27, options2) {
+ let includePath;
+ let filePath;
+ let views = options2.views;
+ let match = /^[A-Za-z]+:\\|^\//.exec(path27);
+ if (match && match.length) {
+ path27 = path27.replace(/^\/*/, "");
+ if (Array.isArray(options2.root)) {
+ includePath = resolvePaths(path27, options2.root);
+ } else {
+ includePath = ejs.resolveInclude(path27, options2.root || "/", true);
+ }
+ } else {
+ if (options2.filename) {
+ filePath = ejs.resolveInclude(path27, options2.filename);
+ if (fs4.existsSync(filePath)) {
+ includePath = filePath;
+ }
+ }
+ if (!includePath && Array.isArray(views)) {
+ includePath = resolvePaths(path27, views);
+ }
+ if (!includePath && typeof options2.includer !== "function") {
+ throw new Error('Could not find the include file "' + options2.escapeFunction(path27) + '"');
+ }
+ }
+ return includePath;
+}
+__name(getIncludePath, "getIncludePath");
+function handleCache(options2, template) {
+ let func;
+ let filename = options2.filename;
+ let hasTemplate = arguments.length > 1;
+ if (options2.cache) {
+ if (!filename) {
+ throw new Error("cache option requires a filename");
+ }
+ func = ejs.cache.get(filename);
+ if (func) {
+ return func;
+ }
+ if (!hasTemplate) {
+ template = fileLoader(filename).toString().replace(_BOM, "");
+ }
+ } else if (!hasTemplate) {
+ if (!filename) {
+ throw new Error("Internal EJS error: no file name or template provided");
+ }
+ template = fileLoader(filename).toString().replace(_BOM, "");
+ }
+ func = ejs.compile(template, options2);
+ if (options2.cache) {
+ ejs.cache.set(filename, func);
+ }
+ return func;
+}
+__name(handleCache, "handleCache");
+function tryHandleCache(options2, data, cb) {
+ let result;
+ if (!cb) {
+ if (typeof ejs.promiseImpl == "function") {
+ return new ejs.promiseImpl(function(resolve16, reject) {
+ try {
+ result = handleCache(options2)(data);
+ resolve16(result);
+ } catch (err) {
+ reject(err);
+ }
+ });
+ } else {
+ throw new Error("Please provide a callback function");
+ }
+ } else {
+ try {
+ result = handleCache(options2)(data);
+ } catch (err) {
+ return cb(err);
+ }
+ cb(null, result);
+ }
+}
+__name(tryHandleCache, "tryHandleCache");
+function fileLoader(filePath) {
+ return ejs.fileLoader(filePath);
+}
+__name(fileLoader, "fileLoader");
+function includeFile(path27, options2) {
+ let opts = utils_default.shallowCopy(utils_default.createNullProtoObjWherePossible(), options2);
+ opts.filename = getIncludePath(path27, opts);
+ if (typeof options2.includer === "function") {
+ let includerResult = options2.includer(path27, opts.filename);
+ if (includerResult) {
+ if (includerResult.filename) {
+ opts.filename = includerResult.filename;
+ }
+ if (includerResult.template) {
+ return handleCache(opts, includerResult.template);
+ }
+ }
+ }
+ return handleCache(opts);
+}
+__name(includeFile, "includeFile");
+function rethrow(err, str3, flnm, lineno, esc2) {
+ let lines = str3.split("\n");
+ let start = Math.max(lineno - 3, 0);
+ let end = Math.min(lines.length, lineno + 3);
+ let filename = esc2(flnm);
+ let context = lines.slice(start, end).map(function(line, i) {
+ let curr = i + start + 1;
+ return (curr == lineno ? " >> " : " ") + curr + "| " + line;
+ }).join("\n");
+ err.path = filename;
+ err.message = (filename || "ejs") + ":" + lineno + "\n" + context + "\n\n" + err.message;
+ throw err;
+}
+__name(rethrow, "rethrow");
+function stripSemi(str3) {
+ return str3.replace(/;(\s*$)/, "$1");
+}
+__name(stripSemi, "stripSemi");
+ejs.compile = /* @__PURE__ */ __name(function compile(template, opts) {
+ let templ;
+ if (opts && opts.scope) {
+ console.warn("`scope` option is deprecated and will be removed in future EJS");
+ if (!opts.context) {
+ opts.context = opts.scope;
+ }
+ delete opts.scope;
+ }
+ templ = new Template(template, opts);
+ return templ.compile();
+}, "compile");
+ejs.render = function(template, d, o) {
+ let data = d || utils_default.createNullProtoObjWherePossible();
+ let opts = o || utils_default.createNullProtoObjWherePossible();
+ if (arguments.length == 2) {
+ utils_default.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA);
+ }
+ return handleCache(opts, template)(data);
+};
+ejs.renderFile = function() {
+ let args = Array.prototype.slice.call(arguments);
+ let filename = args.shift();
+ let cb;
+ let opts = { filename };
+ let data;
+ let viewOpts;
+ if (typeof arguments[arguments.length - 1] == "function") {
+ cb = args.pop();
+ }
+ if (args.length) {
+ data = args.shift();
+ if (args.length) {
+ utils_default.shallowCopy(opts, args.pop());
+ } else {
+ if (utils_default.hasOwn(data, "settings") && data.settings) {
+ if (data.settings.views) {
+ opts.views = data.settings.views;
+ }
+ if (data.settings["view cache"]) {
+ opts.cache = true;
+ }
+ viewOpts = data.settings["view options"];
+ if (viewOpts) {
+ utils_default.shallowCopy(opts, viewOpts);
+ }
+ }
+ utils_default.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA_EXPRESS);
+ }
+ opts.filename = filename;
+ } else {
+ data = utils_default.createNullProtoObjWherePossible();
+ }
+ return tryHandleCache(opts, data, cb);
+};
+ejs.Template = Template;
+ejs.clearCache = function() {
+ ejs.cache.reset();
+};
+function Template(text, optsParam) {
+ let opts = utils_default.hasOwnOnlyObject(optsParam);
+ let options2 = utils_default.createNullProtoObjWherePossible();
+ this.templateText = text;
+ this.mode = null;
+ this.truncate = false;
+ this.currentLine = 1;
+ this.source = "";
+ options2.escapeFunction = opts.escape || opts.escapeFunction || utils_default.escapeXML;
+ options2.compileDebug = opts.compileDebug !== false;
+ options2.debug = !!opts.debug;
+ options2.filename = opts.filename;
+ options2.openDelimiter = opts.openDelimiter || ejs.openDelimiter || _DEFAULT_OPEN_DELIMITER;
+ options2.closeDelimiter = opts.closeDelimiter || ejs.closeDelimiter || _DEFAULT_CLOSE_DELIMITER;
+ options2.delimiter = opts.delimiter || ejs.delimiter || _DEFAULT_DELIMITER;
+ options2.strict = opts.strict || false;
+ options2.context = opts.context;
+ options2.cache = opts.cache || false;
+ options2.rmWhitespace = opts.rmWhitespace;
+ options2.root = opts.root;
+ options2.includer = opts.includer;
+ options2.outputFunctionName = opts.outputFunctionName;
+ options2.localsName = opts.localsName || ejs.localsName || _DEFAULT_LOCALS_NAME;
+ options2.views = opts.views;
+ options2.async = opts.async;
+ options2.destructuredLocals = opts.destructuredLocals;
+ options2.legacyInclude = typeof opts.legacyInclude != "undefined" ? !!opts.legacyInclude : true;
+ if (options2.strict) {
+ options2._with = false;
+ } else {
+ options2._with = typeof opts._with != "undefined" ? opts._with : true;
+ }
+ this.opts = options2;
+ this.regex = this.createRegex();
+}
+__name(Template, "Template");
+Template.modes = {
+ EVAL: "eval",
+ ESCAPED: "escaped",
+ RAW: "raw",
+ COMMENT: "comment",
+ LITERAL: "literal"
+};
+Template.prototype = {
+ createRegex: /* @__PURE__ */ __name(function() {
+ let str3 = _REGEX_STRING;
+ let delim = utils_default.escapeRegExpChars(this.opts.delimiter);
+ let open = utils_default.escapeRegExpChars(this.opts.openDelimiter);
+ let close = utils_default.escapeRegExpChars(this.opts.closeDelimiter);
+ str3 = str3.replace(/%/g, delim).replace(//g, close);
+ return new RegExp(str3);
+ }, "createRegex"),
+ compile: /* @__PURE__ */ __name(function() {
+ let src;
+ let fn;
+ let opts = this.opts;
+ let prepended = "";
+ let appended = "";
+ let escapeFn = opts.escapeFunction;
+ let ctor;
+ let sanitizedFilename = opts.filename ? JSON.stringify(opts.filename) : "undefined";
+ if (!this.source) {
+ this.generateSource();
+ prepended += ` ${DECLARATION_KEYWORD} __output = "";
+ function __append(s) { if (s !== undefined && s !== null) __output += s }
+`;
+ if (opts.outputFunctionName) {
+ if (!_JS_IDENTIFIER.test(opts.outputFunctionName)) {
+ throw new Error("outputFunctionName is not a valid JS identifier.");
+ }
+ prepended += ` ${DECLARATION_KEYWORD} ` + opts.outputFunctionName + " = __append;\n";
+ }
+ if (opts.localsName && !_JS_IDENTIFIER.test(opts.localsName)) {
+ throw new Error("localsName is not a valid JS identifier.");
+ }
+ if (opts.destructuredLocals && opts.destructuredLocals.length) {
+ let destructuring = ` ${DECLARATION_KEYWORD} __locals = (` + opts.localsName + " || {}),\n";
+ for (let i = 0; i < opts.destructuredLocals.length; i++) {
+ let name = opts.destructuredLocals[i];
+ if (!_JS_IDENTIFIER.test(name)) {
+ throw new Error("destructuredLocals[" + i + "] is not a valid JS identifier.");
+ }
+ if (i > 0) {
+ destructuring += ",\n ";
+ }
+ destructuring += name + " = __locals." + name;
+ }
+ prepended += destructuring + ";\n";
+ }
+ if (opts._with !== false) {
+ prepended += " with (" + opts.localsName + " || {}) {\n";
+ appended += " }\n";
+ }
+ appended += " return __output;\n";
+ this.source = prepended + this.source + appended;
+ }
+ if (opts.compileDebug) {
+ src = `${DECLARATION_KEYWORD} __line = 1
+ , __lines = ` + JSON.stringify(this.templateText) + "\n , __filename = " + sanitizedFilename + ";\ntry {\n" + this.source + "} catch (e) {\n rethrow(e, __lines, __filename, __line, escapeFn);\n}\n";
+ } else {
+ src = this.source;
+ }
+ if (opts.strict) {
+ src = '"use strict";\n' + src;
+ }
+ if (opts.debug) {
+ console.log(src);
+ }
+ if (opts.compileDebug && opts.filename) {
+ src = src + "\n//# sourceURL=" + sanitizedFilename + "\n";
+ }
+ try {
+ if (opts.async) {
+ try {
+ ctor = new Function("return (async function(){}).constructor;")();
+ } catch (e) {
+ if (e instanceof SyntaxError) {
+ throw new Error("This environment does not support async/await");
+ } else {
+ throw e;
+ }
+ }
+ } else {
+ ctor = Function;
+ }
+ fn = new ctor(opts.localsName + ", escapeFn, include, rethrow", src);
+ } catch (e) {
+ if (e instanceof SyntaxError) {
+ if (opts.filename) {
+ e.message += " in " + opts.filename;
+ }
+ e.message += " while compiling ejs\n\n";
+ e.message += "If the above error is not helpful, you may want to try EJS-Lint:\n";
+ e.message += "https://github.com/RyanZim/EJS-Lint";
+ if (!opts.async) {
+ e.message += "\n";
+ e.message += "Or, if you meant to create an async function, pass `async: true` as an option.";
+ }
+ }
+ throw e;
+ }
+ let returnedFn = /* @__PURE__ */ __name(function anonymous(data) {
+ let include = /* @__PURE__ */ __name(function(path27, includeData) {
+ let d = utils_default.shallowCopy(utils_default.createNullProtoObjWherePossible(), data);
+ if (includeData) {
+ d = utils_default.shallowCopy(d, includeData);
+ }
+ return includeFile(path27, opts)(d);
+ }, "include");
+ return fn.apply(
+ opts.context,
+ [data || utils_default.createNullProtoObjWherePossible(), escapeFn, include, rethrow]
+ );
+ }, "anonymous");
+ if (opts.filename && typeof Object.defineProperty === "function") {
+ let filename = opts.filename;
+ let basename6 = path2.basename(filename, path2.extname(filename));
+ try {
+ Object.defineProperty(returnedFn, "name", {
+ value: basename6,
+ writable: false,
+ enumerable: false,
+ configurable: true
+ });
+ } catch (e) {
+ }
+ }
+ return returnedFn;
+ }, "compile"),
+ generateSource: /* @__PURE__ */ __name(function() {
+ let opts = this.opts;
+ if (opts.rmWhitespace) {
+ this.templateText = this.templateText.replace(/[\r\n]+/g, "\n").replace(/^\s+|\s+$/gm, "");
+ }
+ let self2 = this;
+ let d = this.opts.delimiter;
+ let o = this.opts.openDelimiter;
+ let c = this.opts.closeDelimiter;
+ let openWhitespaceSlurpTag = utils_default.escapeRegExpChars(o + d + "_");
+ let closeWhitespaceSlurpTag = utils_default.escapeRegExpChars("_" + d + c);
+ let openWhitespaceSlurpReplacement = o + d + "_";
+ let closeWhitespaceSlurpReplacement = "_" + d + c;
+ this.templateText = this.templateText.replace(new RegExp("[ \\t]*" + openWhitespaceSlurpTag, "gm"), openWhitespaceSlurpReplacement).replace(new RegExp(closeWhitespaceSlurpTag + "[ \\t]*", "gm"), closeWhitespaceSlurpReplacement);
+ let matches = this.parseTemplateText();
+ if (matches && matches.length) {
+ matches.forEach(function(line, index) {
+ let closing;
+ if (line.indexOf(o + d) === 0 && line.indexOf(o + d + d) !== 0) {
+ closing = matches[index + 2];
+ if (!(closing == d + c || closing == "-" + d + c || closing == "_" + d + c)) {
+ throw new Error('Could not find matching close tag for "' + line + '".');
+ }
+ }
+ self2.scanLine(line);
+ });
+ }
+ }, "generateSource"),
+ parseTemplateText: /* @__PURE__ */ __name(function() {
+ let str3 = this.templateText;
+ let pat = this.regex;
+ let result = pat.exec(str3);
+ let arr = [];
+ let firstPos;
+ while (result) {
+ firstPos = result.index;
+ if (firstPos !== 0) {
+ arr.push(str3.substring(0, firstPos));
+ str3 = str3.slice(firstPos);
+ }
+ arr.push(result[0]);
+ str3 = str3.slice(result[0].length);
+ result = pat.exec(str3);
+ }
+ if (str3) {
+ arr.push(str3);
+ }
+ return arr;
+ }, "parseTemplateText"),
+ _addOutput: /* @__PURE__ */ __name(function(line) {
+ if (this.truncate) {
+ line = line.replace(/^(?:\r\n|\r|\n)/, "");
+ this.truncate = false;
+ }
+ if (!line) {
+ return line;
+ }
+ line = line.replace(/\\/g, "\\\\");
+ line = line.replace(/\n/g, "\\n");
+ line = line.replace(/\r/g, "\\r");
+ line = line.replace(/"/g, '\\"');
+ this.source += ' ; __append("' + line + '")\n';
+ }, "_addOutput"),
+ scanLine: /* @__PURE__ */ __name(function(line) {
+ let self2 = this;
+ let d = this.opts.delimiter;
+ let o = this.opts.openDelimiter;
+ let c = this.opts.closeDelimiter;
+ let newLineCount = 0;
+ newLineCount = line.split("\n").length - 1;
+ switch (line) {
+ case o + d:
+ case o + d + "_":
+ this.mode = Template.modes.EVAL;
+ break;
+ case o + d + "=":
+ this.mode = Template.modes.ESCAPED;
+ break;
+ case o + d + "-":
+ this.mode = Template.modes.RAW;
+ break;
+ case o + d + "#":
+ this.mode = Template.modes.COMMENT;
+ break;
+ case o + d + d:
+ this.mode = Template.modes.LITERAL;
+ this.source += ' ; __append("' + line.replace(o + d + d, o + d) + '")\n';
+ break;
+ case d + d + c:
+ this.mode = Template.modes.LITERAL;
+ this.source += ' ; __append("' + line.replace(d + d + c, d + c) + '")\n';
+ break;
+ case d + c:
+ case "-" + d + c:
+ case "_" + d + c:
+ if (this.mode == Template.modes.LITERAL) {
+ this._addOutput(line);
+ }
+ this.mode = null;
+ this.truncate = line.indexOf("-") === 0 || line.indexOf("_") === 0;
+ break;
+ default:
+ if (this.mode) {
+ switch (this.mode) {
+ case Template.modes.EVAL:
+ case Template.modes.ESCAPED:
+ case Template.modes.RAW:
+ if (line.lastIndexOf("//") > line.lastIndexOf("\n")) {
+ line += "\n";
+ }
+ }
+ switch (this.mode) {
+ // Just executing code
+ case Template.modes.EVAL:
+ this.source += " ; " + line + "\n";
+ break;
+ // Exec, esc, and output
+ case Template.modes.ESCAPED:
+ this.source += " ; __append(escapeFn(" + stripSemi(line) + "))\n";
+ break;
+ // Exec and output
+ case Template.modes.RAW:
+ this.source += " ; __append(" + stripSemi(line) + ")\n";
+ break;
+ case Template.modes.COMMENT:
+ break;
+ // Literal <%% mode, append as raw output
+ case Template.modes.LITERAL:
+ this._addOutput(line);
+ break;
+ }
+ } else {
+ this._addOutput(line);
+ }
+ }
+ if (self2.opts.compileDebug && newLineCount) {
+ this.currentLine += newLineCount;
+ this.source += " ; __line = " + this.currentLine + "\n";
+ }
+ }, "scanLine")
+};
+ejs.escapeXML = utils_default.escapeXML;
+ejs.__express = ejs.renderFile;
+if (typeof window != "undefined") {
+ window.ejs = ejs;
+}
+if (typeof module != "undefined") {
+ module.exports = ejs;
+}
+var ejs_default = ejs;
+
+// packages/core/src/common/notify.ts
+init_esbuild_shims();
+import { spawn } from "child_process";
+function formatDurationSeconds(durationMs) {
+ const safeMs = Number.isFinite(durationMs) ? Math.max(0, durationMs) : 0;
+ return String(Math.floor(safeMs / 1e3));
+}
+__name(formatDurationSeconds, "formatDurationSeconds");
+function buildNotifyEnv(durationMs, baseEnv = process.env, context = {}) {
+ const env6 = {
+ ...baseEnv,
+ DURATION: formatDurationSeconds(durationMs)
+ };
+ delete env6.STATUS;
+ delete env6.FAIL_REASON;
+ delete env6.BODY;
+ delete env6.TITLE;
+ if (context.status) {
+ env6.STATUS = context.status;
+ }
+ if (context.failReason) {
+ env6.FAIL_REASON = context.failReason;
+ }
+ if (context.body) {
+ env6.BODY = context.body;
+ }
+ if (context.title) {
+ env6.TITLE = context.title;
+ }
+ return env6;
+}
+__name(buildNotifyEnv, "buildNotifyEnv");
+function launchNotifyScript(notifyPath, durationMs, workingDirectory, spawnProcess = spawn, configuredEnv = {}, context = {}) {
+ const commandPath = notifyPath?.trim();
+ if (!commandPath) {
+ return;
+ }
+ const options2 = {
+ cwd: workingDirectory,
+ detached: process.platform !== "win32",
+ env: buildNotifyEnv(durationMs, { ...process.env, ...configuredEnv }, context),
+ stdio: "ignore"
+ };
+ try {
+ const child = spawnProcess(commandPath, [], options2);
+ child.once("error", (error51) => {
+ if (process.platform === "win32") {
+ return;
+ }
+ if (error51.code !== "EACCES" && error51.code !== "ENOEXEC") {
+ return;
+ }
+ try {
+ const fallbackChild = spawnProcess("/bin/sh", [commandPath], options2);
+ fallbackChild.once("error", () => void 0);
+ fallbackChild.unref();
+ } catch {
+ }
+ });
+ child.unref();
+ } catch {
+ }
+}
+__name(launchNotifyScript, "launchNotifyScript");
+
+// packages/core/src/common/openai-thinking.ts
+init_esbuild_shims();
+function buildThinkingRequestOptions(thinkingEnabled, _baseURL, reasoningEffort = "max") {
+ const thinking = { type: thinkingEnabled ? "enabled" : "disabled" };
+ return {
+ thinking,
+ ...thinkingEnabled ? { extra_body: { reasoning_effort: reasoningEffort } } : {}
+ };
+}
+__name(buildThinkingRequestOptions, "buildThinkingRequestOptions");
+
+// packages/core/src/common/file-utils.ts
+init_esbuild_shims();
+import * as fs5 from "fs";
+import * as path3 from "path";
+function normalizeContent(value) {
+ return value.replace(/\r\n/g, "\n");
+}
+__name(normalizeContent, "normalizeContent");
+function detectLineEndings(value) {
+ return value.includes("\r\n") ? "CRLF" : "LF";
+}
+__name(detectLineEndings, "detectLineEndings");
+function detectEncoding(buffer) {
+ if (buffer.length >= 2 && buffer[0] === 255 && buffer[1] === 254) {
+ return "utf16le";
+ }
+ return "utf8";
+}
+__name(detectEncoding, "detectEncoding");
+function readTextFileWithMetadata(filePath) {
+ const buffer = fs5.readFileSync(filePath);
+ const stat = fs5.statSync(filePath);
+ const encoding = detectEncoding(buffer);
+ const raw = buffer.toString(encoding);
+ return {
+ content: normalizeContent(raw),
+ encoding,
+ lineEndings: detectLineEndings(raw),
+ timestamp: Math.floor(stat.mtimeMs)
+ };
+}
+__name(readTextFileWithMetadata, "readTextFileWithMetadata");
+function writeTextFile(filePath, content, encoding, lineEndings) {
+ const normalized = normalizeContent(content);
+ const toWrite = lineEndings === "CRLF" ? normalized.replace(/\n/g, "\r\n") : normalized;
+ fs5.writeFileSync(filePath, toWrite, { encoding });
+ return Buffer.byteLength(toWrite, encoding === "utf16le" ? "utf16le" : "utf8");
+}
+__name(writeTextFile, "writeTextFile");
+function ensureParentDirectory(filePath) {
+ fs5.mkdirSync(path3.dirname(filePath), { recursive: true });
+}
+__name(ensureParentDirectory, "ensureParentDirectory");
+function hasFileChangedSinceState(filePath, state) {
+ const current = readTextFileWithMetadata(filePath);
+ if (current.timestamp <= state.timestamp) {
+ return false;
+ }
+ const isFullRead = !state.isPartialView && typeof state.offset === "undefined" && typeof state.limit === "undefined";
+ return !(isFullRead && current.content === state.content);
+}
+__name(hasFileChangedSinceState, "hasFileChangedSinceState");
+function buildDiffPreview(filePath, originalContent, updatedContent, maxLines = 40) {
+ const original = originalContent === null ? null : normalizeContent(originalContent);
+ const updated = normalizeContent(updatedContent);
+ if (original !== null && original === updated) {
+ return null;
+ }
+ const oldLines = toDiffLines(original);
+ const newLines = toDiffLines(updated);
+ let prefix = 0;
+ while (prefix < oldLines.length && prefix < newLines.length && oldLines[prefix] === newLines[prefix]) {
+ prefix += 1;
+ }
+ let suffix = 0;
+ while (suffix < oldLines.length - prefix && suffix < newLines.length - prefix && oldLines[oldLines.length - 1 - suffix] === newLines[newLines.length - 1 - suffix]) {
+ suffix += 1;
+ }
+ const oldChanged = oldLines.slice(prefix, oldLines.length - suffix);
+ const newChanged = newLines.slice(prefix, newLines.length - suffix);
+ const oldStart = original === null ? 0 : prefix + 1;
+ const newStart = prefix + 1;
+ const previewLines = [
+ `--- ${original === null ? "/dev/null" : `a/${filePath}`}`,
+ `+++ b/${filePath}`,
+ `@@ -${oldStart},${oldChanged.length} +${newStart},${newChanged.length} @@`
+ ];
+ if (prefix > 0) {
+ previewLines.push(` ${oldLines[prefix - 1]}`);
+ }
+ for (const line of oldChanged) {
+ previewLines.push(`-${line}`);
+ }
+ for (const line of newChanged) {
+ previewLines.push(`+${line}`);
+ }
+ if (suffix > 0) {
+ previewLines.push(` ${oldLines[oldLines.length - suffix]}`);
+ }
+ if (previewLines.length > maxLines) {
+ return `${previewLines.slice(0, maxLines).join("\n")}
+...`;
+ }
+ return previewLines.join("\n");
+}
+__name(buildDiffPreview, "buildDiffPreview");
+function toDiffLines(content) {
+ if (!content) {
+ return [];
+ }
+ const lines = content.split("\n");
+ if (lines[lines.length - 1] === "") {
+ lines.pop();
+ }
+ return lines;
+}
+__name(toDiffLines, "toDiffLines");
+
+// packages/core/src/prompt.ts
+init_esbuild_shims();
+import { execFileSync as execFileSync3, execSync } from "child_process";
+import * as fs7 from "fs";
+import * as os5 from "os";
+import * as path5 from "path";
+var import_gray_matter = __toESM(require_gray_matter(), 1);
+import { fileURLToPath } from "url";
+
+// packages/core/src/common/shell-utils.ts
+init_esbuild_shims();
+import { execFileSync as execFileSync2 } from "child_process";
+import * as fs6 from "fs";
+import * as os4 from "os";
+import * as path4 from "path";
+import * as pathWin32 from "path/win32";
+var WINDOWS_GIT_LOCATIONS = ["C:\\Program Files\\Git\\cmd\\git.exe", "C:\\Program Files (x86)\\Git\\cmd\\git.exe"];
+var WINDOWS_BASH_LOCATIONS = ["C:\\Program Files\\Git\\bin\\bash.exe", "C:\\Program Files (x86)\\Git\\bin\\bash.exe"];
+var NUL_REDIRECT_REGEX = /(\d?&?>+\s*)[Nn][Uu][Ll](?=\s|$|[|&;)\n])/g;
+var cachedGitBashPath = null;
+function setShellIfWindows() {
+ if (process.platform !== "win32") {
+ return;
+ }
+ process.env.SHELL = findGitBashPath();
+}
+__name(setShellIfWindows, "setShellIfWindows");
+function findGitBashPath() {
+ if (cachedGitBashPath) {
+ return cachedGitBashPath;
+ }
+ const bashPath = resolveWindowsGitBashPath({
+ findExecutableCandidates: findAllWindowsExecutableCandidates,
+ findGitExecPath,
+ existsSync: fs6.existsSync
+ });
+ if (bashPath) {
+ cachedGitBashPath = bashPath;
+ return bashPath;
+ }
+ throw new Error(
+ "Deep Code on Windows requires Git Bash. Install Git for Windows, or ensure Git's bash.exe is available in PATH."
+ );
+}
+__name(findGitBashPath, "findGitBashPath");
+function resolveWindowsGitBashPath(lookup) {
+ return firstExistingWindowsPath(
+ [
+ ...lookup.findExecutableCandidates("bash"),
+ ...WINDOWS_BASH_LOCATIONS,
+ ...gitExecPathToBashCandidates(lookup.findGitExecPath()),
+ ...lookup.findExecutableCandidates("git").flatMap(gitExecutableToBashCandidates)
+ ],
+ lookup.existsSync
+ );
+}
+__name(resolveWindowsGitBashPath, "resolveWindowsGitBashPath");
+function resolveShellPath() {
+ if (process.platform === "win32") {
+ return findGitBashPath();
+ }
+ const envShell = process.env.SHELL;
+ if (envShell && getShellKind(envShell) !== "unknown") {
+ return envShell;
+ }
+ return "/bin/bash";
+}
+__name(resolveShellPath, "resolveShellPath");
+function getShellKind(shellPath) {
+ const executable = shellPath.replace(/\\/g, "/").split("/").pop()?.toLowerCase() ?? "";
+ if (executable === "bash" || executable === "bash.exe") {
+ return "bash";
+ }
+ if (executable === "zsh" || executable === "zsh.exe") {
+ return "zsh";
+ }
+ return "unknown";
+}
+__name(getShellKind, "getShellKind");
+function buildShellInitCommand(shellPath) {
+ switch (getShellKind(shellPath)) {
+ case "zsh":
+ return ['ZSHRC="${ZDOTDIR:-$HOME}/.zshrc"', 'if [ -f "$ZSHRC" ]; then { . "$ZSHRC"; } >/dev/null 2>&1; fi'].join(
+ "; "
+ );
+ case "bash":
+ return [
+ 'BASHRC="${BASH_ENV:-$HOME/.bashrc}"',
+ 'if [ -f "$BASHRC" ]; then { . "$BASHRC"; } >/dev/null 2>&1; fi'
+ ].join("; ");
+ default:
+ return null;
+ }
+}
+__name(buildShellInitCommand, "buildShellInitCommand");
+function buildDisableExtglobCommand(shellPath) {
+ switch (getShellKind(shellPath)) {
+ case "bash":
+ return "shopt -u extglob 2>/dev/null || true";
+ case "zsh":
+ return "setopt NO_EXTENDED_GLOB 2>/dev/null || true";
+ default:
+ return null;
+ }
+}
+__name(buildDisableExtglobCommand, "buildDisableExtglobCommand");
+function rewriteWindowsNullRedirect(command2) {
+ return command2.replace(NUL_REDIRECT_REGEX, "$1/dev/null");
+}
+__name(rewriteWindowsNullRedirect, "rewriteWindowsNullRedirect");
+function windowsPathToPosixPath(windowsPath) {
+ if (windowsPath.startsWith("\\\\")) {
+ return windowsPath.replace(/\\/g, "/");
+ }
+ const driveMatch = windowsPath.match(/^([A-Za-z]):[/\\]/);
+ if (driveMatch) {
+ const driveLetter = driveMatch[1].toLowerCase();
+ return `/${driveLetter}${windowsPath.slice(2).replace(/\\/g, "/")}`;
+ }
+ return windowsPath.replace(/\\/g, "/");
+}
+__name(windowsPathToPosixPath, "windowsPathToPosixPath");
+function posixPathToWindowsPath(posixPath) {
+ if (posixPath.startsWith("//")) {
+ return posixPath.replace(/\//g, "\\");
+ }
+ const cygdriveMatch = posixPath.match(/^\/cygdrive\/([A-Za-z])(\/|$)/);
+ if (cygdriveMatch) {
+ const driveLetter = cygdriveMatch[1].toUpperCase();
+ const rest = posixPath.slice(`/cygdrive/${cygdriveMatch[1]}`.length);
+ return `${driveLetter}:${(rest || "\\").replace(/\//g, "\\")}`;
+ }
+ const driveMatch = posixPath.match(/^\/([A-Za-z])(\/|$)/);
+ if (driveMatch) {
+ const driveLetter = driveMatch[1].toUpperCase();
+ const rest = posixPath.slice(2);
+ return `${driveLetter}:${(rest || "\\").replace(/\//g, "\\")}`;
+ }
+ return posixPath.replace(/\//g, "\\");
+}
+__name(posixPathToWindowsPath, "posixPathToWindowsPath");
+function toNativeCwd(shellCwd) {
+ if (process.platform !== "win32") {
+ return shellCwd;
+ }
+ return posixPathToWindowsPath(shellCwd);
+}
+__name(toNativeCwd, "toNativeCwd");
+function buildShellEnv(shellPath, extraEnv = {}) {
+ const env6 = {
+ ...process.env,
+ ...extraEnv,
+ SHELL: shellPath,
+ GIT_EDITOR: "true"
+ };
+ if (process.platform === "win32") {
+ const tmpdir4 = windowsPathToPosixPath(os4.tmpdir());
+ env6.TMPDIR = tmpdir4;
+ env6.TMPPREFIX = path4.posix.join(tmpdir4, "zsh");
+ }
+ return env6;
+}
+__name(buildShellEnv, "buildShellEnv");
+function findAllWindowsExecutableCandidates(executable) {
+ const extraCandidates = executable === "git" ? WINDOWS_GIT_LOCATIONS : executable === "bash" ? WINDOWS_BASH_LOCATIONS : [];
+ try {
+ const output = execFileSync2("where.exe", [executable], {
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "ignore"],
+ windowsHide: true
+ });
+ let whereResults = output.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
+ if (executable === "bash") {
+ whereResults = whereResults.filter((candidate) => !/system32[\\/]bash\.exe$/i.test(candidate));
+ }
+ return filterWindowsExecutableCandidates([...whereResults, ...extraCandidates]);
+ } catch {
+ return filterWindowsExecutableCandidates(extraCandidates);
+ }
+}
+__name(findAllWindowsExecutableCandidates, "findAllWindowsExecutableCandidates");
+function findGitExecPath() {
+ try {
+ const output = execFileSync2("git", ["--exec-path"], {
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "ignore"],
+ windowsHide: true
+ }).trim();
+ return output || null;
+ } catch {
+ return null;
+ }
+}
+__name(findGitExecPath, "findGitExecPath");
+function gitExecPathToBashCandidates(execPath) {
+ if (!execPath) {
+ return [];
+ }
+ const normalized = execPath.replace(/\//g, "\\");
+ return [
+ pathWin32.join(normalized, "..", "..", "..", "bin", "bash.exe"),
+ pathWin32.join(normalized, "..", "..", "bin", "bash.exe")
+ ];
+}
+__name(gitExecPathToBashCandidates, "gitExecPathToBashCandidates");
+function gitExecutableToBashCandidates(gitPath) {
+ return [pathWin32.join(gitPath, "..", "..", "bin", "bash.exe"), pathWin32.join(gitPath, "..", "bin", "bash.exe")];
+}
+__name(gitExecutableToBashCandidates, "gitExecutableToBashCandidates");
+function firstExistingWindowsPath(candidates, existsSync16) {
+ const seen = /* @__PURE__ */ new Set();
+ for (const candidate of candidates) {
+ const normalized = pathWin32.resolve(candidate);
+ const key = normalized.toLowerCase();
+ if (seen.has(key)) {
+ continue;
+ }
+ seen.add(key);
+ if (getShellKind(normalized) === "bash" && existsSync16(normalized)) {
+ return normalized;
+ }
+ }
+ return null;
+}
+__name(firstExistingWindowsPath, "firstExistingWindowsPath");
+function filterWindowsExecutableCandidates(candidates) {
+ const cwd2 = process.cwd().toLowerCase();
+ const seen = /* @__PURE__ */ new Set();
+ const results = [];
+ for (const candidate of candidates) {
+ const normalized = path4.resolve(candidate).toLowerCase();
+ const candidateDir = path4.dirname(normalized).toLowerCase();
+ if (candidateDir === cwd2 || normalized.startsWith(`${cwd2}${path4.sep}`)) {
+ continue;
+ }
+ if (!seen.has(normalized) && fs6.existsSync(candidate)) {
+ seen.add(normalized);
+ results.push(candidate);
+ }
+ }
+ return results;
+}
+__name(filterWindowsExecutableCandidates, "filterWindowsExecutableCandidates");
+
+// packages/core/src/prompt.ts
+var COMPACT_PROMPT_BASE = `Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
+This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.
+
+Before providing your final summary, wrap your analysis in tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:
+
+1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:
+ - The user's explicit requests and intents
+ - Your approach to addressing the user's requests
+ - Key decisions, technical concepts and code patterns
+ - Specific details like:
+ - file names
+ - full code snippets
+ - function signatures
+ - file edits
+ - Errors that you ran into and how you fixed them
+ - Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
+2. Double-check for technical accuracy and completeness, addressing each required element thoroughly.
+
+Your summary should include the following sections:
+
+1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
+2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.
+3. Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable and include a summary of why this file read or edit is important.
+4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
+5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.
+6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.
+6. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.
+7. Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable.
+8. Optional Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's most recent explicit requests, and the task you were working on immediately before this summary request. If your last task was concluded, then only list next steps if they are explicitly in line with the users request. Do not start on tangential requests or really old requests that were already completed without confirming with the user first.
+ If there is a next step, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no drift in task interpretation.
+
+Here's an example of how your output should be structured:
+
+
+
+[Your thought process, ensuring all points are covered thoroughly and accurately]
+
+
+
+1. Primary Request and Intent:
+ [Detailed description]
+
+2. Key Technical Concepts:
+ - [Concept 1]
+ - [Concept 2]
+ - [...]
+
+3. Files and Code Sections:
+ - [File Name 1]
+ - [Summary of why this file is important]
+ - [Summary of the changes made to this file, if any]
+ - [Important Code Snippet]
+ - [File Name 2]
+ - [Important Code Snippet]
+ - [...]
+
+4. Errors and fixes:
+ - [Detailed description of error 1]:
+ - [How you fixed the error]
+ - [User feedback on the error if any]
+ - [...]
+
+5. Problem Solving:
+ [Description of solved problems and ongoing troubleshooting]
+
+6. All user messages:
+ - [Detailed non tool use user message]
+ - [...]
+
+7. Pending Tasks:
+ - [Task 1]
+ - [Task 2]
+ - [...]
+
+8. Current Work:
+ [Precise description of current work]
+
+9. Optional Next Step:
+ [Optional Next step to take]
+
+`;
+var AGENTIC_BEHAVIOR_PROMPT = `
+## Agentic Behavior: Plan \u2192 Execute \u2192 Verify \u2192 Auto-Fix
+
+For any non-trivial task (coding, debugging, refactoring, configuration), follow this disciplined cycle:
+
+### 1. Plan First
+- Before executing any changes, use \`UpdatePlan\` to break the task into small, verifiable steps
+- Each step should have a clear success criterion (e.g., "file compiles", "test passes", "output matches expected")
+- Keep the plan visible throughout the task
+
+### 2. Execute Step-by-Step
+- Work through the plan one step at a time
+- Use the most appropriate tool for each step (Read, Edit, Write, Bash)
+- After each modification, use Bash to verify syntax/compilation if applicable
+
+### 3. Verify After Each Step
+- After a command runs, check the exit code and output
+- If exit code \u2260 0, do NOT move on \u2014 treat this as a bug to fix immediately
+- For code changes: run the relevant build/test/lint command to verify correctness
+- Only mark a step as [x] in UpdatePlan when verification passes
+
+### 4. Auto Error Recovery (Critical)
+When ANY tool call fails (bash exit code \u2260 0, edit mismatch, write error):
+1. **Analyze** \u2014 Read the error output carefully. Extract the specific error message, line number, and file path.
+2. **Diagnose** \u2014 Identify the root cause (syntax error, missing import, wrong API, permission issue, etc.)
+3. **Fix** \u2014 Apply the minimal fix needed:
+ - For compile errors: fix the exact line/syntax
+ - For test failures: fix the implementation or test
+ - For runtime errors: fix the logic
+4. **Verify** \u2014 Re-run the original command that failed to confirm the fix works
+5. **Retry** \u2014 If the fix doesn't resolve the issue, try a different approach
+6. **Escalate** \u2014 After 3 failed attempts, explain the problem to the user with the error details
+
+IMPORTANT: Never proceed to the next task step while a verification failure is unresolved. Fix first, then move on.
+
+### 5. Completion Checklist
+Before declaring a task complete:
+- [ ] All steps in the plan are marked [x]
+- [ ] The code compiles/builds without errors
+- [ ] Relevant tests pass
+- [ ] The output matches what was requested
+`;
+var SYSTEM_PROMPT_BASE = `\u4F60\u662F\u540D\u53EBDeep Code\u7684\u4EA4\u4E92\u5F0FCLI\u5DE5\u5177\uFF0C\u5E2E\u52A9\u7528\u6237\u5B8C\u6210\u8F6F\u4EF6\u5DE5\u7A0B\u4EFB\u52A1\u3002 Use the instructions below and the tools available to you to assist the user.
+
+\u91CD\u8981\uFF1A\u4E25\u7981\u7F16\u9020\u4EFB\u4F55\u975E\u7F16\u7A0B\u76F8\u5173\u7684 URL\u3002\u5BF9\u4E8E\u7F16\u7A0B\u94FE\u63A5\uFF0C\u4EC5\u9650\u4F7F\u7528\uFF1A1) \u7528\u6237\u63D0\u4F9B\u7684\u4E0A\u4E0B\u6587\uFF1B2) \u4F60\u786E\u5B9A\u7684\u5B98\u65B9\u6587\u6863\u4E3B\u57DF\u540D\u3002\u5728\u8F93\u51FA\u524D\uFF0C\u5FC5\u987B\u81EA\u67E5\u8BE5\u94FE\u63A5\u662F\u5426\u5B58\u5728\u4E8E\u4F60\u7684\u4E0A\u4E0B\u6587\u8BB0\u5FC6\u4E2D\uFF1B\u82E5\u4E0D\u5B58\u5728\uFF0C\u8BF7\u660E\u786E\u8BF4\u660E\u65E0\u6CD5\u63D0\u4F9B\u3002
+
+${AGENTIC_BEHAVIOR_PROMPT}`;
+var DEFAULT_SKILL_TEMPLATES = ["karpathy-guidelines.md"];
+var DEFAULT_SKILL_RESOURCE_FILE_LIMIT = 50;
+var SKILL_RESOURCE_EXCLUDED_DIRS = /* @__PURE__ */ new Set([
+ ".cache",
+ ".git",
+ ".next",
+ ".turbo",
+ "build",
+ "coverage",
+ "dist",
+ "node_modules",
+ "out"
+]);
+function readToolDocs(extensionRoot, options2 = {}) {
+ const toolsDir = path5.join(extensionRoot, "templates", "tools");
+ if (!fs7.existsSync(toolsDir)) {
+ return "";
+ }
+ const entries = fs7.readdirSync(toolsDir);
+ const docs = entries.filter((entry) => entry.endsWith(".md") || entry.endsWith(".md.ejs")).sort().map((entry) => {
+ const fullPath = path5.join(toolsDir, entry);
+ try {
+ const template = fs7.readFileSync(fullPath, "utf8");
+ const content = entry.endsWith(".ejs") ? ejs_default.render(template, { supportsMultimodal: supportsMultimodal(options2.model ?? "") }) : template;
+ return content.trim();
+ } catch {
+ return "";
+ }
+ }).filter((content) => content.length > 0);
+ return docs.join("\n\n");
+}
+__name(readToolDocs, "readToolDocs");
+function readDefaultSkillDocs(extensionRoot, enabledSkills = {}) {
+ const skillsDir = path5.join(extensionRoot, "templates", "skills");
+ return DEFAULT_SKILL_TEMPLATES.map((entry) => {
+ const fullPath = path5.join(skillsDir, entry);
+ const name = path5.basename(entry, ".md");
+ if (enabledSkills[name] === false) {
+ return null;
+ }
+ try {
+ return {
+ name,
+ content: fs7.readFileSync(fullPath, "utf8").trim()
+ };
+ } catch {
+ return null;
+ }
+ }).filter((skill) => Boolean(skill?.content));
+}
+__name(readDefaultSkillDocs, "readDefaultSkillDocs");
+function getDefaultSkillPrompt(options2 = {}) {
+ const skillDocs = readDefaultSkillDocs(getExtensionRoot(), options2.enabledSkills);
+ if (skillDocs.length === 0) {
+ return "";
+ }
+ return buildSkillDocumentsPrompt(skillDocs);
+}
+__name(getDefaultSkillPrompt, "getDefaultSkillPrompt");
+function buildSkillDocumentsPrompt(skills) {
+ const blocks = skills.map((skill) => renderSkillDocumentBlock(skill));
+ return `Use the skill documents below to assist the user:
+${blocks.join("\n\n")}`;
+}
+__name(buildSkillDocumentsPrompt, "buildSkillDocumentsPrompt");
+function renderSkillDocumentBlock(skill) {
+ const pathAttribute = skill.path ? ` path="${escapeXml(skill.path)}"` : "";
+ const resources = renderSkillResources(skill.skillFilePath);
+ const content = stripSkillPromptMetadata(skill.content);
+ return `<${skill.name}-skill${pathAttribute}>
+${content}${resources}
+${skill.name}-skill>`;
+}
+__name(renderSkillDocumentBlock, "renderSkillDocumentBlock");
+function stripSkillPromptMetadata(content) {
+ try {
+ const parsed = (0, import_gray_matter.default)(content);
+ if (!Object.prototype.hasOwnProperty.call(parsed.data, "metadata")) {
+ return content;
+ }
+ const frontmatter = { ...parsed.data };
+ delete frontmatter.metadata;
+ return import_gray_matter.default.stringify(parsed.content, frontmatter);
+ } catch {
+ return content;
+ }
+}
+__name(stripSkillPromptMetadata, "stripSkillPromptMetadata");
+function renderSkillResources(skillFilePath) {
+ if (!skillFilePath) {
+ return "";
+ }
+ const listing = listSkillResourceFiles(skillFilePath, DEFAULT_SKILL_RESOURCE_FILE_LIMIT);
+ if (listing.files.length === 0 && !listing.truncated) {
+ return "";
+ }
+ const fileLines = listing.files.map((file2) => ` ${escapeXml(file2)}`);
+ const noteLine = listing.truncated ? [` Listing capped at ${DEFAULT_SKILL_RESOURCE_FILE_LIMIT} files and may be incomplete.`] : [];
+ return `
+
+
+${[...fileLines, ...noteLine].join("\n")}
+`;
+}
+__name(renderSkillResources, "renderSkillResources");
+function listSkillResourceFiles(skillFilePath, limit2) {
+ const skillDir = path5.dirname(skillFilePath);
+ const files = [];
+ let truncated = false;
+ const visit = /* @__PURE__ */ __name((dir, relativeDir = "") => {
+ if (files.length > limit2) {
+ truncated = true;
+ return;
+ }
+ let entries;
+ try {
+ entries = fs7.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ if (entry.name.startsWith(".")) {
+ continue;
+ }
+ const relativePath = relativeDir ? path5.join(relativeDir, entry.name) : entry.name;
+ const fullPath = path5.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ if (SKILL_RESOURCE_EXCLUDED_DIRS.has(entry.name)) {
+ continue;
+ }
+ visit(fullPath, relativePath);
+ if (truncated) {
+ return;
+ }
+ continue;
+ }
+ if (!entry.isFile() || entry.name === "SKILL.md") {
+ continue;
+ }
+ files.push(toPosixPath(relativePath));
+ if (files.length > limit2) {
+ truncated = true;
+ return;
+ }
+ }
+ }, "visit");
+ visit(skillDir);
+ return { files: files.slice(0, limit2), truncated };
+}
+__name(listSkillResourceFiles, "listSkillResourceFiles");
+function toPosixPath(filePath) {
+ return filePath.split(path5.sep).join("/");
+}
+__name(toPosixPath, "toPosixPath");
+function escapeXml(value) {
+ return value.replace(/&/g, "&").replace(/"/g, """).replace(//g, ">");
+}
+__name(escapeXml, "escapeXml");
+function getCurrentDateAndModelPrompt(model) {
+ const date5 = /* @__PURE__ */ new Date();
+ let prompt = `\u4ECA\u5929\u662F${date5.getFullYear()}\u5E74${date5.getMonth() + 1}\u6708${date5.getDate()}\u65E5\u3002\u968F\u7740\u5BF9\u8BDD\u7684\u8FDB\u884C\uFF0C\u65F6\u95F4\u5728\u6D41\u901D\u3002`;
+ prompt += model ? `
+\u5F53\u524DLLM\u6A21\u578B\u4E3A${model}\uFF0C\u5BF9\u8BDD\u4E2D\u53EF\u901A\u8FC7/model\u547D\u4EE4\u5207\u6362\u6A21\u578B\u3002` : "";
+ return prompt;
+}
+__name(getCurrentDateAndModelPrompt, "getCurrentDateAndModelPrompt");
+function getSystemPrompt(_projectRoot, options2 = {}) {
+ const toolDocs = readToolDocs(getExtensionRoot(), options2);
+ return toolDocs ? `${SYSTEM_PROMPT_BASE}
+
+# Available Tools
+
+${toolDocs}` : SYSTEM_PROMPT_BASE;
+}
+__name(getSystemPrompt, "getSystemPrompt");
+function getCompactPrompt(sessionMessages) {
+ const jsonl = sessionMessages.map(
+ (message) => JSON.stringify({
+ id: message.id,
+ role: message.role,
+ content: message.content,
+ contentParams: message.contentParams,
+ messageParams: message.messageParams,
+ createTime: message.createTime
+ })
+ ).join("\n");
+ return `${COMPACT_PROMPT_BASE}
+
+conversation below:
+
+\`\`\`jsonl
+${jsonl}
+\`\`\``;
+}
+__name(getCompactPrompt, "getCompactPrompt");
+function getRuntimeContext(projectRoot, model) {
+ const uname = getUnameInfo();
+ const shellPath = getShellPathInfo();
+ const shellModeOpts = process.platform === "win32" ? { "shell mode": "git-bash" } : {};
+ const runtimeVersions = getRuntimeVersionInfo();
+ const env6 = {
+ "root path": projectRoot,
+ pwd: projectRoot,
+ homedir: os5.homedir(),
+ "system info": uname,
+ "shell path": shellPath,
+ ...shellModeOpts,
+ ...runtimeVersions,
+ "command installed": {
+ ripgrep: checkToolInstalled("rg"),
+ jq: checkToolInstalled("jq")
+ }
+ };
+ return `${getCurrentDateAndModelPrompt(model)}
+
+# Local Workspace Environment
+
+\`\`\`json
+${JSON.stringify(env6, null, 2)}
+\`\`\``;
+}
+__name(getRuntimeContext, "getRuntimeContext");
+function checkToolInstalled(tool) {
+ try {
+ if (process.platform === "win32") {
+ const bashPath = findGitBashPath();
+ execFileSync3(bashPath, ["-lc", `command -v ${shellSingleQuote(tool)}`], {
+ encoding: "utf8",
+ stdio: "ignore",
+ windowsHide: true
+ });
+ return true;
+ }
+ execSync(`command -v ${tool}`, { encoding: "utf8", stdio: "ignore" });
+ return true;
+ } catch {
+ return false;
+ }
+}
+__name(checkToolInstalled, "checkToolInstalled");
+function getShellPathInfo() {
+ try {
+ return resolveShellPath();
+ } catch (error51) {
+ return error51 instanceof Error ? error51.message : String(error51);
+ }
+}
+__name(getShellPathInfo, "getShellPathInfo");
+function shellSingleQuote(value) {
+ return `'${value.replace(/'/g, `'"'"'`)}'`;
+}
+__name(shellSingleQuote, "shellSingleQuote");
+function getRuntimeVersionInfo() {
+ const versions = {};
+ const pythonVersion = getCommandVersion("python3", ["--version"]);
+ const nodeVersion2 = getCommandVersion("node", ["--version"]);
+ if (pythonVersion) {
+ versions["python3 version"] = pythonVersion.replace(/^Python\s+/i, "");
+ }
+ if (nodeVersion2) {
+ versions["node version"] = nodeVersion2;
+ }
+ return versions;
+}
+__name(getRuntimeVersionInfo, "getRuntimeVersionInfo");
+function getCommandVersion(command2, args) {
+ try {
+ const commandText = [command2, ...args].map(shellSingleQuote).join(" ");
+ if (process.platform === "win32") {
+ return execFileSync3(findGitBashPath(), ["-lc", `${commandText} 2>&1`], {
+ encoding: "utf8",
+ windowsHide: true
+ }).trim();
+ }
+ return execSync(`${commandText} 2>&1`, { encoding: "utf8" }).trim();
+ } catch {
+ return null;
+ }
+}
+__name(getCommandVersion, "getCommandVersion");
+function getUnameInfo() {
+ try {
+ if (process.platform === "win32") {
+ return execFileSync3(findGitBashPath(), ["-lc", "uname -a"], {
+ encoding: "utf8",
+ windowsHide: true
+ }).trim();
+ }
+ return execSync("uname -a", { encoding: "utf8" }).trim();
+ } catch {
+ return `${os5.type()} ${os5.release()} ${os5.arch()}`;
+ }
+}
+__name(getUnameInfo, "getUnameInfo");
+function getExtensionRoot() {
+ if (typeof __dirname !== "undefined") {
+ return path5.resolve(__dirname, "..");
+ }
+ const currentFilePath = fileURLToPath(import.meta.url);
+ return path5.resolve(path5.dirname(currentFilePath), "..");
+}
+__name(getExtensionRoot, "getExtensionRoot");
+function getTools(_options = {}, externalTools = []) {
+ const tools = [
+ {
+ type: "function",
+ function: {
+ name: "bash",
+ description: "Execute shell commands in a persistent bash session.",
+ parameters: {
+ type: "object",
+ properties: {
+ command: {
+ type: "string",
+ description: "The shell command to execute"
+ },
+ description: {
+ type: "string",
+ description: 'Clear, concise description of what this command does in active voice. Never use words like "complex" or "risk" in the description - just describe what it does.'
+ },
+ sideEffects: {
+ description: 'Permission scopes required by this bash command. Use [] only for commands that do not read, write, delete, or access the network. Use ["unknown"] when the effects cannot be classified safely.',
+ type: "array",
+ items: {
+ type: "string",
+ enum: [
+ "read-in-cwd",
+ "read-out-cwd",
+ "write-in-cwd",
+ "write-out-cwd",
+ "delete-in-cwd",
+ "delete-out-cwd",
+ "query-git-log",
+ "mutate-git-log",
+ "network",
+ "unknown"
+ ]
+ },
+ uniqueItems: true
+ },
+ run_in_background: {
+ type: "boolean",
+ description: "Set to true to run the command in the background. Use this only when you need to perform a blocking task and do not need the result immediately."
+ }
+ },
+ required: ["command", "sideEffects"],
+ additionalProperties: false
+ }
+ }
+ },
+ {
+ type: "function",
+ function: {
+ name: "AskUserQuestion",
+ description: "When the task has ambiguities or multiple implementation approaches, use this tool to pause execution and ask the user a question to get clarification or make a decision.",
+ parameters: {
+ type: "object",
+ properties: {
+ questions: {
+ type: "array",
+ description: "Questions to present to the user. Usually only one question is needed at a time.",
+ items: {
+ type: "object",
+ properties: {
+ question: {
+ type: "string",
+ description: "The question to ask the user."
+ },
+ multiSelect: {
+ type: "boolean",
+ description: "Whether the user may choose multiple options."
+ },
+ options: {
+ type: "array",
+ description: "A list of predefined options for the user to choose from.",
+ items: {
+ type: "object",
+ properties: {
+ label: {
+ type: "string",
+ description: "The display text for the option."
+ },
+ description: {
+ type: "string",
+ description: "A detailed explanation or hint about this option to help the user understand what happens if they choose it."
+ }
+ },
+ required: ["label"]
+ }
+ }
+ },
+ required: ["question", "options"]
+ }
+ }
+ },
+ required: ["questions"],
+ additionalProperties: false
+ }
+ }
+ },
+ {
+ type: "function",
+ function: {
+ name: "UpdatePlan",
+ description: "Update the current task plan. The plan argument must be the complete markdown task list to show as the latest progress state.",
+ parameters: {
+ type: "object",
+ properties: {
+ plan: {
+ type: "string",
+ description: "The complete markdown task list, including task status markers such as [ ], [>], [x], and optional notes."
+ },
+ explanation: {
+ type: "string",
+ description: "Optional short reason for changing the plan."
+ }
+ },
+ required: ["plan"],
+ additionalProperties: false
+ }
+ }
+ },
+ {
+ type: "function",
+ function: {
+ name: "read",
+ description: "Read files from the filesystem (text, images, PDFs, notebooks).",
+ parameters: {
+ type: "object",
+ properties: {
+ file_path: {
+ type: "string",
+ description: "UNIX-style path to file"
+ },
+ offset: {
+ type: "number",
+ description: "Line number to start reading from"
+ },
+ limit: {
+ type: "number",
+ description: "Number of lines to read"
+ },
+ pages: {
+ type: "string",
+ description: 'Page range for PDF files (e.g., "1-5", "3", "10-20"). Only applicable to PDF files.'
+ }
+ },
+ required: ["file_path"],
+ additionalProperties: false
+ }
+ }
+ },
+ {
+ type: "function",
+ function: {
+ name: "write",
+ description: "Create files or overwrite them with a complete string payload. Prefer edit for existing files.",
+ parameters: {
+ type: "object",
+ properties: {
+ file_path: {
+ type: "string",
+ description: "Absolute path to file"
+ },
+ content: {
+ type: "string",
+ description: "Complete file content as a single string. Serialize JSON documents before writing."
+ }
+ },
+ required: ["file_path", "content"],
+ additionalProperties: false
+ }
+ }
+ },
+ {
+ type: "function",
+ function: {
+ name: "edit",
+ description: "Perform scoped string replacements in files.",
+ parameters: {
+ type: "object",
+ properties: {
+ snippet_id: {
+ type: "string",
+ description: "Required Read/Edit snippet_id."
+ },
+ file_path: {
+ type: "string",
+ description: "Optional absolute path guard; must match snippet_id's file."
+ },
+ old_string: {
+ type: "string",
+ description: "Exact text to replace inside snippet_id's scope"
+ },
+ new_string: {
+ type: "string",
+ description: "Replacement text (must differ from old_string)"
+ },
+ replace_all: {
+ type: "boolean",
+ description: "Replace all occurences of old_string (default false)",
+ default: false
+ },
+ expected_occurrences: {
+ type: "number",
+ description: "Expected number of matches, especially useful as a safety check with replace_all"
+ }
+ },
+ required: ["snippet_id", "old_string", "new_string"],
+ additionalProperties: false
+ }
+ }
+ }
+ ];
+ tools.push({
+ type: "function",
+ function: {
+ name: "WebSearch",
+ description: "Perform web searching using a natural language query.",
+ parameters: {
+ type: "object",
+ properties: {
+ query: {
+ type: "string",
+ description: "A search query phrased as a clear, specific natural language question or statement that includes key context."
+ }
+ },
+ required: ["query"],
+ additionalProperties: false
+ }
+ }
+ });
+ for (const tool of externalTools) {
+ tools.push(tool);
+ }
+ return tools;
+}
+__name(getTools, "getTools");
+
+// packages/core/src/tools/executor.ts
+init_esbuild_shims();
+
+// packages/core/src/tools/ask-user-question-handler.ts
+init_esbuild_shims();
+async function handleAskUserQuestionTool(args, _context) {
+ const questions = parseQuestions(args.questions);
+ if (!questions.ok) {
+ return {
+ ok: false,
+ name: "AskUserQuestion",
+ error: questions.error
+ };
+ }
+ const metadata = {
+ kind: "ask_user_question",
+ questions: questions.value
+ };
+ return {
+ ok: true,
+ name: "AskUserQuestion",
+ output: buildQuestionSummary(questions.value),
+ metadata,
+ awaitUserResponse: true
+ };
+}
+__name(handleAskUserQuestionTool, "handleAskUserQuestionTool");
+function parseQuestions(raw) {
+ if (!Array.isArray(raw) || raw.length === 0) {
+ return {
+ ok: false,
+ error: '"questions" must be a non-empty array.'
+ };
+ }
+ const questions = [];
+ for (let index = 0; index < raw.length; index += 1) {
+ const item = raw[index];
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
+ return {
+ ok: false,
+ error: `Question at index ${index} must be an object.`
+ };
+ }
+ const question = typeof item.question === "string" ? item.question.trim() : "";
+ if (!question) {
+ return {
+ ok: false,
+ error: `Question at index ${index} is missing a non-empty "question" string.`
+ };
+ }
+ const rawOptions = item.options;
+ if (!Array.isArray(rawOptions) || rawOptions.length === 0) {
+ return {
+ ok: false,
+ error: `Question at index ${index} must include a non-empty "options" array.`
+ };
+ }
+ const options2 = [];
+ for (let optionIndex = 0; optionIndex < rawOptions.length; optionIndex += 1) {
+ const option = rawOptions[optionIndex];
+ if (!option || typeof option !== "object" || Array.isArray(option)) {
+ return {
+ ok: false,
+ error: `Option ${optionIndex} for question ${index} must be an object.`
+ };
+ }
+ const label = typeof option.label === "string" ? option.label.trim() : "";
+ if (!label) {
+ return {
+ ok: false,
+ error: `Option ${optionIndex} for question ${index} is missing a non-empty "label" string.`
+ };
+ }
+ const description = typeof option.description === "string" ? option.description.trim() : void 0;
+ options2.push({
+ label,
+ description: description || void 0
+ });
+ }
+ const multiSelect = typeof item.multiSelect === "boolean" ? item.multiSelect : void 0;
+ questions.push({
+ question,
+ multiSelect,
+ options: options2
+ });
+ }
+ return {
+ ok: true,
+ value: questions
+ };
+}
+__name(parseQuestions, "parseQuestions");
+function buildQuestionSummary(questions) {
+ const lines = ["Waiting for user input."];
+ questions.forEach((item, index) => {
+ lines.push("");
+ lines.push(`${index + 1}. ${item.question}`);
+ lines.push(` Mode: ${item.multiSelect ? "multi-select" : "single-select"}`);
+ item.options.forEach((option) => {
+ lines.push(` - ${option.label}`);
+ if (option.description) {
+ lines.push(` ${option.description}`);
+ }
+ });
+ lines.push(" - Other");
+ });
+ return lines.join("\n");
+}
+__name(buildQuestionSummary, "buildQuestionSummary");
+
+// packages/core/src/tools/bash-handler.ts
+init_esbuild_shims();
+import { spawn as spawn2 } from "child_process";
+import { randomUUID } from "crypto";
+import * as fs8 from "fs";
+import * as os6 from "os";
+import * as path6 from "path";
+
+// packages/core/src/common/bash-timeout.ts
+init_esbuild_shims();
+var DEFAULT_BASH_TIMEOUT_MS = 10 * 60 * 1e3;
+var MIN_BASH_TIMEOUT_MS = 60 * 1e3;
+var BASH_TIMEOUT_INCREMENT_MS = 5 * 60 * 1e3;
+var BASH_TIMEOUT_DECREMENT_MS = 60 * 1e3;
+function clampBashTimeoutMs(timeoutMs, minTimeoutMs = MIN_BASH_TIMEOUT_MS) {
+ if (!Number.isFinite(timeoutMs)) {
+ return DEFAULT_BASH_TIMEOUT_MS;
+ }
+ const minimum = Number.isFinite(minTimeoutMs) ? Math.max(1, Math.round(minTimeoutMs)) : MIN_BASH_TIMEOUT_MS;
+ return Math.max(minimum, Math.round(timeoutMs));
+}
+__name(clampBashTimeoutMs, "clampBashTimeoutMs");
+
+// packages/core/src/common/process-tree.ts
+init_esbuild_shims();
+import { spawnSync } from "child_process";
+function killProcessTree(pid, signal = "SIGKILL", deps = {}) {
+ if (!Number.isInteger(pid) || pid <= 0) {
+ return false;
+ }
+ const platform2 = deps.platform ?? process.platform;
+ const killPid = deps.killPid ?? ((targetPid, targetSignal) => process.kill(targetPid, targetSignal));
+ if (platform2 === "win32") {
+ const runTaskkill = deps.runTaskkill ?? runWindowsTaskkill;
+ if (runTaskkill(pid)) {
+ return true;
+ }
+ return killDirectProcess(pid, signal, killPid);
+ }
+ if (deps.killGroupOnNonWindows !== false && killDirectProcess(-pid, signal, killPid)) {
+ return true;
+ }
+ return killDirectProcess(pid, signal, killPid);
+}
+__name(killProcessTree, "killProcessTree");
+function runWindowsTaskkill(pid, spawnSyncImpl = spawnSync) {
+ const result = spawnSyncImpl("taskkill", ["/PID", String(pid), "/T", "/F"], {
+ stdio: "ignore",
+ windowsHide: true
+ });
+ return !result.error && result.status === 0;
+}
+__name(runWindowsTaskkill, "runWindowsTaskkill");
+function killDirectProcess(pid, signal, killPid) {
+ try {
+ killPid(pid, signal);
+ return true;
+ } catch {
+ return false;
+ }
+}
+__name(killDirectProcess, "killDirectProcess");
+
+// packages/core/src/tools/bash-handler.ts
+var MAX_OUTPUT_CHARS = 3e4;
+var MAX_CAPTURE_CHARS = 10 * 1024 * 1024;
+var BACKGROUND_OUTPUT_DIR = path6.join(os6.tmpdir(), "deepcode-background");
+var TRAILING_BACKGROUND_OPERATOR_PATTERN = /(^|[^\\&])\s*&\s*$/;
+var sessionWorkingDirs = /* @__PURE__ */ new Map();
+function clearSessionWorkingDir(sessionId) {
+ if (!sessionId) {
+ return;
+ }
+ sessionWorkingDirs.delete(sessionId);
+}
+__name(clearSessionWorkingDir, "clearSessionWorkingDir");
+async function handleBashTool(args, context) {
+ const rawCommand = typeof args.command === "string" ? args.command : "";
+ const runInBackground = isTrue(args.run_in_background);
+ const command2 = runInBackground ? stripTrailingBackgroundOperator(rawCommand) : rawCommand;
+ if (!command2.trim()) {
+ return {
+ ok: false,
+ name: "bash",
+ error: 'Missing required "command" string.'
+ };
+ }
+ const startCwd = getSessionCwd(context.sessionId, context.projectRoot);
+ const { shellPath, shellArgs, marker } = buildShellCommand(command2);
+ if (runInBackground) {
+ return startBackgroundShellCommand(shellPath, shellArgs, startCwd, command2, marker, context);
+ }
+ const execution = await executeShellCommand(shellPath, shellArgs, startCwd, command2, context);
+ const result = buildToolCommandResultWithAnalysis(
+ execution.stdout,
+ execution.stderr,
+ marker,
+ execution.exitCode,
+ execution.signal,
+ shellPath,
+ startCwd,
+ execution.timedOut,
+ execution.timeoutMs,
+ execution.deadlineAtMs
+ );
+ updateSessionCwd(context.sessionId, startCwd, result.cwd);
+ if (execution.error || result.exitCode !== 0 || result.signal !== null) {
+ const errorMessage = buildErrorMessage(result.exitCode, result.signal, execution.error, execution.timedOut);
+ return formatResult({ ...result, ok: false }, "bash", errorMessage);
+ }
+ return formatResult(result, "bash");
+}
+__name(handleBashTool, "handleBashTool");
+function extractErrorAnalysis(output, exitCode) {
+ if (!output || exitCode === 0) {
+ return void 0;
+ }
+ const lines = output.split(/\r?\n/);
+ const errorLines = [];
+ let lineCount = 0;
+ for (const line of lines) {
+ const lower = line.toLowerCase();
+ if (/error|exception|traceback|failed|failure|not found|syntax\s*error|cannot\s+find|undefined|ts\d+|ts error/i.test(
+ lower
+ )) {
+ errorLines.push(line.trim());
+ lineCount++;
+ if (lineCount >= 10) break;
+ }
+ }
+ if (errorLines.length === 0) return void 0;
+ return errorLines.join("\n");
+}
+__name(extractErrorAnalysis, "extractErrorAnalysis");
+function buildToolCommandResultWithAnalysis(stdout, stderr, marker, exitCode, signal, shellPath, startCwd, timedOut = false, timeoutMs, deadlineAtMs) {
+ const result = buildToolCommandResult(
+ stdout,
+ stderr,
+ marker,
+ exitCode,
+ signal,
+ shellPath,
+ startCwd,
+ timedOut,
+ timeoutMs,
+ deadlineAtMs
+ );
+ if (exitCode !== 0 && signal === null && !timedOut) {
+ const analysis = extractErrorAnalysis(result.output, exitCode);
+ if (analysis) {
+ result.output = `
+${analysis}
+
+
+${result.output}`;
+ }
+ }
+ return result;
+}
+__name(buildToolCommandResultWithAnalysis, "buildToolCommandResultWithAnalysis");
+function isTrue(value) {
+ return value === true || value === "true";
+}
+__name(isTrue, "isTrue");
+function stripTrailingBackgroundOperator(command2) {
+ return command2.replace(TRAILING_BACKGROUND_OPERATOR_PATTERN, "$1").trimEnd();
+}
+__name(stripTrailingBackgroundOperator, "stripTrailingBackgroundOperator");
+function getSessionCwd(sessionId, fallback) {
+ return sessionWorkingDirs.get(sessionId) ?? fallback;
+}
+__name(getSessionCwd, "getSessionCwd");
+function updateSessionCwd(sessionId, fallback, cwd2) {
+ const nextCwd = cwd2 ?? fallback;
+ sessionWorkingDirs.set(sessionId, nextCwd);
+}
+__name(updateSessionCwd, "updateSessionCwd");
+function buildShellCommand(command2) {
+ const shellPath = resolveShellPath();
+ const marker = buildMarker();
+ const initCommand = buildShellInitCommand(shellPath);
+ const disableExtglobCommand = buildDisableExtglobCommand(shellPath);
+ const normalizedCommand = rewriteWindowsNullRedirect(command2);
+ const wrappedParts = [];
+ if (initCommand) {
+ wrappedParts.push(initCommand);
+ }
+ if (disableExtglobCommand) {
+ wrappedParts.push(disableExtglobCommand);
+ }
+ wrappedParts.push(
+ normalizedCommand,
+ "__DEEPCODE_STATUS__=$?",
+ `printf '%s%s\\n' "${marker}" "$PWD"`,
+ "exit $__DEEPCODE_STATUS__"
+ );
+ const wrappedCommand = `{ ${wrappedParts.join("; ")}; } < /dev/null`;
+ return { shellPath, shellArgs: ["-c", wrappedCommand], marker };
+}
+__name(buildShellCommand, "buildShellCommand");
+async function executeShellCommand(shellPath, shellArgs, cwd2, command2, context) {
+ return new Promise((resolve16) => {
+ const detached = process.platform !== "win32";
+ const configuredEnv = context.createOpenAIClient?.().env ?? {};
+ const minTimeoutMs = context.bashMinTimeoutMs;
+ const initialTimeoutMs = clampBashTimeoutMs(context.bashTimeoutMs ?? DEFAULT_BASH_TIMEOUT_MS, minTimeoutMs);
+ const startedAtMs = Date.now();
+ let timeoutMs = initialTimeoutMs;
+ let deadlineAtMs = startedAtMs + timeoutMs;
+ let timedOut = false;
+ let settled = false;
+ let timeoutTimer = null;
+ const child = spawn2(shellPath, shellArgs, {
+ cwd: cwd2,
+ env: buildShellEnv(shellPath, configuredEnv),
+ detached,
+ windowsHide: true,
+ stdio: ["ignore", "pipe", "pipe"]
+ });
+ const pid = child.pid;
+ const getTimeoutInfo = /* @__PURE__ */ __name(() => ({
+ timeoutMs,
+ startedAtMs,
+ deadlineAtMs,
+ timedOut
+ }), "getTimeoutInfo");
+ const stopTimeoutTimer = /* @__PURE__ */ __name(() => {
+ if (timeoutTimer) {
+ clearTimeout(timeoutTimer);
+ timeoutTimer = null;
+ }
+ }, "stopTimeoutTimer");
+ const triggerTimeout = /* @__PURE__ */ __name(() => {
+ if (settled || timedOut || typeof pid !== "number") {
+ return;
+ }
+ timedOut = true;
+ stopTimeoutTimer();
+ killProcessTree(pid, "SIGKILL");
+ }, "triggerTimeout");
+ const scheduleTimeout = /* @__PURE__ */ __name(() => {
+ stopTimeoutTimer();
+ if (settled) {
+ return;
+ }
+ const remainingMs = Math.max(0, deadlineAtMs - Date.now());
+ timeoutTimer = setTimeout(triggerTimeout, remainingMs);
+ }, "scheduleTimeout");
+ const timeoutControl = {
+ getInfo: getTimeoutInfo,
+ setTimeoutMs: /* @__PURE__ */ __name((nextTimeoutMs) => {
+ timeoutMs = clampBashTimeoutMs(nextTimeoutMs, minTimeoutMs);
+ deadlineAtMs = startedAtMs + timeoutMs;
+ if (deadlineAtMs <= Date.now()) {
+ triggerTimeout();
+ } else {
+ scheduleTimeout();
+ }
+ return getTimeoutInfo();
+ }, "setTimeoutMs")
+ };
+ if (typeof pid === "number") {
+ context.onProcessStart?.(pid, command2);
+ context.onProcessTimeoutControl?.(pid, timeoutControl);
+ scheduleTimeout();
+ }
+ let stdout = "";
+ let stderr = "";
+ let error51;
+ child.stdout?.on("data", (chunk) => {
+ stdout = appendChunk(stdout, chunk);
+ const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
+ context.onProcessStdout?.(pid, text);
+ });
+ child.stderr?.on("data", (chunk) => {
+ stderr = appendChunk(stderr, chunk);
+ const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
+ context.onProcessStdout?.(pid, text);
+ });
+ child.on("error", (spawnError) => {
+ error51 = spawnError.message;
+ });
+ child.on("close", (code, signal) => {
+ settled = true;
+ stopTimeoutTimer();
+ if (typeof pid === "number") {
+ context.onProcessTimeoutControl?.(pid, null);
+ context.onProcessExit?.(pid);
+ }
+ resolve16({
+ stdout,
+ stderr,
+ exitCode: typeof code === "number" ? code : null,
+ signal: signal ?? null,
+ error: error51,
+ timedOut,
+ timeoutMs,
+ deadlineAtMs
+ });
+ });
+ });
+}
+__name(executeShellCommand, "executeShellCommand");
+function startBackgroundShellCommand(shellPath, shellArgs, cwd2, command2, marker, context) {
+ fs8.mkdirSync(BACKGROUND_OUTPUT_DIR, { recursive: true });
+ const taskId = `bash-${randomUUID()}`;
+ const outputPath = path6.join(BACKGROUND_OUTPUT_DIR, `${taskId}.log`);
+ const startedAtMs = Date.now();
+ const detached = process.platform !== "win32";
+ const configuredEnv = context.createOpenAIClient?.().env ?? {};
+ const child = spawn2(shellPath, shellArgs, {
+ cwd: cwd2,
+ env: buildShellEnv(shellPath, configuredEnv),
+ detached,
+ windowsHide: true,
+ stdio: ["ignore", "pipe", "pipe"]
+ });
+ const pid = child.pid;
+ const processId = typeof pid === "number" ? pid : -1;
+ const stopCommand = typeof pid === "number" ? buildStopBackgroundProcessCommand(pid) : null;
+ let stdout = "";
+ let stderr = "";
+ let error51;
+ const appendOutputFile = /* @__PURE__ */ __name((chunk) => {
+ try {
+ fs8.appendFileSync(outputPath, chunk);
+ } catch {
+ }
+ }, "appendOutputFile");
+ if (typeof pid === "number") {
+ context.onProcessStart?.(pid, command2);
+ }
+ child.stdout?.on("data", (chunk) => {
+ stdout = appendChunk(stdout, chunk);
+ appendOutputFile(chunk);
+ const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
+ if (typeof pid === "number") {
+ context.onProcessStdout?.(pid, text);
+ }
+ });
+ child.stderr?.on("data", (chunk) => {
+ stderr = appendChunk(stderr, chunk);
+ appendOutputFile(chunk);
+ const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
+ if (typeof pid === "number") {
+ context.onProcessStdout?.(pid, text);
+ }
+ });
+ child.on("error", (spawnError) => {
+ error51 = spawnError.message;
+ });
+ child.on("close", (code, signal) => {
+ const markerResult = stripMarker(stdout, marker);
+ const finalOutput = joinOutput(markerResult.output, stderr);
+ const result = buildToolCommandResult(
+ stdout,
+ stderr,
+ marker,
+ typeof code === "number" ? code : null,
+ signal ?? null,
+ shellPath,
+ cwd2
+ );
+ updateSessionCwd(context.sessionId, cwd2, result.cwd);
+ writeFinalBackgroundOutput(outputPath, finalOutput);
+ if (typeof pid === "number") {
+ context.onProcessExit?.(pid);
+ }
+ const ok = !error51 && result.exitCode === 0 && result.signal === null;
+ context.onBackgroundProcessComplete?.({
+ taskId,
+ processId,
+ command: command2,
+ outputPath,
+ ok,
+ exitCode: result.exitCode,
+ signal: result.signal,
+ error: ok ? void 0 : buildErrorMessage(result.exitCode, result.signal, error51),
+ cwd: result.cwd,
+ shellPath,
+ startedAtMs,
+ completedAtMs: Date.now()
+ });
+ });
+ return {
+ ok: true,
+ name: "bash",
+ output: buildBackgroundStartMessage(taskId, outputPath, stopCommand),
+ metadata: {
+ backgroundTaskId: taskId,
+ processId: typeof pid === "number" ? pid : null,
+ outputPath,
+ stopCommand,
+ cwd: cwd2,
+ shellPath,
+ startCwd: cwd2,
+ runInBackground: true
+ }
+ };
+}
+__name(startBackgroundShellCommand, "startBackgroundShellCommand");
+function buildBackgroundStartMessage(taskId, outputPath, stopCommand) {
+ const parts = [`Command running in background with ID: ${taskId}.`];
+ if (stopCommand) {
+ parts.push(`Stop it with: ${stopCommand}`);
+ }
+ parts.push(`Output is being written to: ${outputPath}`);
+ return parts.join(" ");
+}
+__name(buildBackgroundStartMessage, "buildBackgroundStartMessage");
+function buildStopBackgroundProcessCommand(processId) {
+ if (process.platform === "win32") {
+ return `cmd.exe /c "taskkill /PID ${processId} /T /F"`;
+ }
+ return `kill -- -${processId}`;
+}
+__name(buildStopBackgroundProcessCommand, "buildStopBackgroundProcessCommand");
+function writeFinalBackgroundOutput(outputPath, output) {
+ try {
+ fs8.writeFileSync(outputPath, output ?? "", "utf8");
+ } catch {
+ }
+}
+__name(writeFinalBackgroundOutput, "writeFinalBackgroundOutput");
+function appendChunk(existing, chunk) {
+ if (existing.length >= MAX_CAPTURE_CHARS) {
+ return existing;
+ }
+ const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
+ const remaining = MAX_CAPTURE_CHARS - existing.length;
+ return `${existing}${text.slice(0, remaining)}`;
+}
+__name(appendChunk, "appendChunk");
+function buildMarker() {
+ const token = Math.random().toString(36).slice(2);
+ return `__DEEPCODE_PWD__${token}__`;
+}
+__name(buildMarker, "buildMarker");
+function buildToolCommandResult(stdout, stderr, marker, exitCode, signal, shellPath, startCwd, timedOut = false, timeoutMs, deadlineAtMs) {
+ const { output: cleanedStdout, cwd: cwd2 } = stripMarker(stdout, marker);
+ const combined = joinOutput(cleanedStdout, stderr);
+ const { text, truncated } = truncateOutput(combined);
+ return {
+ ok: exitCode === 0 && signal === null,
+ output: text,
+ cwd: cwd2,
+ exitCode,
+ signal,
+ truncated,
+ shellPath,
+ startCwd,
+ timedOut,
+ timeoutMs,
+ deadlineAt: typeof deadlineAtMs === "number" ? new Date(deadlineAtMs).toISOString() : void 0
+ };
+}
+__name(buildToolCommandResult, "buildToolCommandResult");
+function stripMarker(stdout, marker) {
+ if (!stdout) {
+ return { output: "", cwd: null };
+ }
+ const lines = stdout.split(/\r?\n/);
+ let markerIndex = -1;
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
+ if (lines[i].startsWith(marker)) {
+ markerIndex = i;
+ break;
+ }
+ }
+ if (markerIndex === -1) {
+ return { output: stdout, cwd: null };
+ }
+ const markerLine = lines[markerIndex];
+ const shellCwd = markerLine.slice(marker.length).trim();
+ const cwd2 = shellCwd ? toNativeCwd(shellCwd) : null;
+ lines.splice(markerIndex, 1);
+ return { output: lines.join("\n"), cwd: cwd2 };
+}
+__name(stripMarker, "stripMarker");
+function joinOutput(stdout, stderr) {
+ const trimmedStdout = stdout ?? "";
+ const trimmedStderr = stderr ?? "";
+ if (trimmedStdout && trimmedStderr) {
+ return `${trimmedStdout}
+${trimmedStderr}`;
+ }
+ return trimmedStdout || trimmedStderr;
+}
+__name(joinOutput, "joinOutput");
+function truncateOutput(output) {
+ if (output.length <= MAX_OUTPUT_CHARS) {
+ return { text: output, truncated: false };
+ }
+ return { text: output.slice(0, MAX_OUTPUT_CHARS), truncated: true };
+}
+__name(truncateOutput, "truncateOutput");
+function buildErrorMessage(exitCode, signal, error51, timedOut = false) {
+ if (error51) {
+ return error51;
+ }
+ if (timedOut) {
+ return "Command timed out.";
+ }
+ if (signal) {
+ return `Command terminated by signal ${signal}.`;
+ }
+ if (exitCode !== null) {
+ return `Command failed with exit code ${exitCode}.`;
+ }
+ return "Command failed.";
+}
+__name(buildErrorMessage, "buildErrorMessage");
+function formatResult(result, name, errorMessage) {
+ const metadata = {
+ exitCode: result.exitCode,
+ signal: result.signal,
+ cwd: result.cwd,
+ truncated: result.truncated,
+ shellPath: result.shellPath,
+ startCwd: result.startCwd
+ };
+ if (typeof result.timedOut === "boolean") {
+ metadata.timedOut = result.timedOut;
+ }
+ if (typeof result.timeoutMs === "number") {
+ metadata.timeoutMs = result.timeoutMs;
+ }
+ if (result.deadlineAt) {
+ metadata.deadlineAt = result.deadlineAt;
+ }
+ const outputValue = result.output ? result.output : void 0;
+ return {
+ ok: result.ok,
+ name,
+ output: outputValue,
+ error: errorMessage,
+ metadata
+ };
+}
+__name(formatResult, "formatResult");
+
+// packages/core/src/tools/edit-handler.ts
+init_esbuild_shims();
+import * as fs10 from "fs";
+
+// node_modules/zod/index.js
+init_esbuild_shims();
+
+// node_modules/zod/v4/classic/external.js
+var external_exports = {};
+__export(external_exports, {
+ $brand: () => $brand,
+ $input: () => $input,
+ $output: () => $output,
+ NEVER: () => NEVER,
+ TimePrecision: () => TimePrecision,
+ ZodAny: () => ZodAny,
+ ZodArray: () => ZodArray,
+ ZodBase64: () => ZodBase64,
+ ZodBase64URL: () => ZodBase64URL,
+ ZodBigInt: () => ZodBigInt,
+ ZodBigIntFormat: () => ZodBigIntFormat,
+ ZodBoolean: () => ZodBoolean,
+ ZodCIDRv4: () => ZodCIDRv4,
+ ZodCIDRv6: () => ZodCIDRv6,
+ ZodCUID: () => ZodCUID,
+ ZodCUID2: () => ZodCUID2,
+ ZodCatch: () => ZodCatch,
+ ZodCodec: () => ZodCodec,
+ ZodCustom: () => ZodCustom,
+ ZodCustomStringFormat: () => ZodCustomStringFormat,
+ ZodDate: () => ZodDate,
+ ZodDefault: () => ZodDefault,
+ ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
+ ZodE164: () => ZodE164,
+ ZodEmail: () => ZodEmail,
+ ZodEmoji: () => ZodEmoji,
+ ZodEnum: () => ZodEnum,
+ ZodError: () => ZodError,
+ ZodExactOptional: () => ZodExactOptional,
+ ZodFile: () => ZodFile,
+ ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
+ ZodFunction: () => ZodFunction,
+ ZodGUID: () => ZodGUID,
+ ZodIPv4: () => ZodIPv4,
+ ZodIPv6: () => ZodIPv6,
+ ZodISODate: () => ZodISODate,
+ ZodISODateTime: () => ZodISODateTime,
+ ZodISODuration: () => ZodISODuration,
+ ZodISOTime: () => ZodISOTime,
+ ZodIntersection: () => ZodIntersection,
+ ZodIssueCode: () => ZodIssueCode,
+ ZodJWT: () => ZodJWT,
+ ZodKSUID: () => ZodKSUID,
+ ZodLazy: () => ZodLazy,
+ ZodLiteral: () => ZodLiteral,
+ ZodMAC: () => ZodMAC,
+ ZodMap: () => ZodMap,
+ ZodNaN: () => ZodNaN,
+ ZodNanoID: () => ZodNanoID,
+ ZodNever: () => ZodNever,
+ ZodNonOptional: () => ZodNonOptional,
+ ZodNull: () => ZodNull,
+ ZodNullable: () => ZodNullable,
+ ZodNumber: () => ZodNumber,
+ ZodNumberFormat: () => ZodNumberFormat,
+ ZodObject: () => ZodObject,
+ ZodOptional: () => ZodOptional,
+ ZodPipe: () => ZodPipe,
+ ZodPrefault: () => ZodPrefault,
+ ZodPreprocess: () => ZodPreprocess,
+ ZodPromise: () => ZodPromise,
+ ZodReadonly: () => ZodReadonly,
+ ZodRealError: () => ZodRealError,
+ ZodRecord: () => ZodRecord,
+ ZodSet: () => ZodSet,
+ ZodString: () => ZodString,
+ ZodStringFormat: () => ZodStringFormat,
+ ZodSuccess: () => ZodSuccess,
+ ZodSymbol: () => ZodSymbol,
+ ZodTemplateLiteral: () => ZodTemplateLiteral,
+ ZodTransform: () => ZodTransform,
+ ZodTuple: () => ZodTuple,
+ ZodType: () => ZodType,
+ ZodULID: () => ZodULID,
+ ZodURL: () => ZodURL,
+ ZodUUID: () => ZodUUID,
+ ZodUndefined: () => ZodUndefined,
+ ZodUnion: () => ZodUnion,
+ ZodUnknown: () => ZodUnknown,
+ ZodVoid: () => ZodVoid,
+ ZodXID: () => ZodXID,
+ ZodXor: () => ZodXor,
+ _ZodString: () => _ZodString,
+ _default: () => _default2,
+ _function: () => _function,
+ any: () => any,
+ array: () => array,
+ base64: () => base642,
+ base64url: () => base64url2,
+ bigint: () => bigint2,
+ boolean: () => boolean2,
+ catch: () => _catch2,
+ check: () => check2,
+ cidrv4: () => cidrv42,
+ cidrv6: () => cidrv62,
+ clone: () => clone,
+ codec: () => codec,
+ coerce: () => coerce_exports,
+ config: () => config,
+ core: () => core_exports2,
+ cuid: () => cuid3,
+ cuid2: () => cuid22,
+ custom: () => custom,
+ date: () => date3,
+ decode: () => decode2,
+ decodeAsync: () => decodeAsync2,
+ describe: () => describe2,
+ discriminatedUnion: () => discriminatedUnion,
+ e164: () => e1642,
+ email: () => email2,
+ emoji: () => emoji2,
+ encode: () => encode2,
+ encodeAsync: () => encodeAsync2,
+ endsWith: () => _endsWith,
+ enum: () => _enum2,
+ exactOptional: () => exactOptional,
+ file: () => file,
+ flattenError: () => flattenError,
+ float32: () => float32,
+ float64: () => float64,
+ formatError: () => formatError,
+ fromJSONSchema: () => fromJSONSchema,
+ function: () => _function,
+ getErrorMap: () => getErrorMap,
+ globalRegistry: () => globalRegistry,
+ gt: () => _gt,
+ gte: () => _gte,
+ guid: () => guid2,
+ hash: () => hash,
+ hex: () => hex2,
+ hostname: () => hostname2,
+ httpUrl: () => httpUrl,
+ includes: () => _includes,
+ instanceof: () => _instanceof,
+ int: () => int,
+ int32: () => int32,
+ int64: () => int64,
+ intersection: () => intersection,
+ invertCodec: () => invertCodec,
+ ipv4: () => ipv42,
+ ipv6: () => ipv62,
+ iso: () => iso_exports,
+ json: () => json,
+ jwt: () => jwt,
+ keyof: () => keyof,
+ ksuid: () => ksuid2,
+ lazy: () => lazy,
+ length: () => _length,
+ literal: () => literal,
+ locales: () => locales_exports,
+ looseObject: () => looseObject,
+ looseRecord: () => looseRecord,
+ lowercase: () => _lowercase,
+ lt: () => _lt,
+ lte: () => _lte,
+ mac: () => mac2,
+ map: () => map,
+ maxLength: () => _maxLength,
+ maxSize: () => _maxSize,
+ meta: () => meta2,
+ mime: () => _mime,
+ minLength: () => _minLength,
+ minSize: () => _minSize,
+ multipleOf: () => _multipleOf,
+ nan: () => nan,
+ nanoid: () => nanoid2,
+ nativeEnum: () => nativeEnum,
+ negative: () => _negative,
+ never: () => never,
+ nonnegative: () => _nonnegative,
+ nonoptional: () => nonoptional,
+ nonpositive: () => _nonpositive,
+ normalize: () => _normalize,
+ null: () => _null3,
+ nullable: () => nullable,
+ nullish: () => nullish2,
+ number: () => number2,
+ object: () => object,
+ optional: () => optional,
+ overwrite: () => _overwrite,
+ parse: () => parse3,
+ parseAsync: () => parseAsync2,
+ partialRecord: () => partialRecord,
+ pipe: () => pipe,
+ positive: () => _positive,
+ prefault: () => prefault,
+ preprocess: () => preprocess,
+ prettifyError: () => prettifyError,
+ promise: () => promise,
+ property: () => _property,
+ readonly: () => readonly,
+ record: () => record,
+ refine: () => refine,
+ regex: () => _regex,
+ regexes: () => regexes_exports,
+ registry: () => registry,
+ safeDecode: () => safeDecode2,
+ safeDecodeAsync: () => safeDecodeAsync2,
+ safeEncode: () => safeEncode2,
+ safeEncodeAsync: () => safeEncodeAsync2,
+ safeParse: () => safeParse2,
+ safeParseAsync: () => safeParseAsync2,
+ set: () => set,
+ setErrorMap: () => setErrorMap,
+ size: () => _size,
+ slugify: () => _slugify,
+ startsWith: () => _startsWith,
+ strictObject: () => strictObject,
+ string: () => string2,
+ stringFormat: () => stringFormat,
+ stringbool: () => stringbool,
+ success: () => success,
+ superRefine: () => superRefine,
+ symbol: () => symbol,
+ templateLiteral: () => templateLiteral,
+ toJSONSchema: () => toJSONSchema,
+ toLowerCase: () => _toLowerCase,
+ toUpperCase: () => _toUpperCase,
+ transform: () => transform,
+ treeifyError: () => treeifyError,
+ trim: () => _trim,
+ tuple: () => tuple,
+ uint32: () => uint32,
+ uint64: () => uint64,
+ ulid: () => ulid2,
+ undefined: () => _undefined3,
+ union: () => union,
+ unknown: () => unknown,
+ uppercase: () => _uppercase,
+ url: () => url,
+ util: () => util_exports,
+ uuid: () => uuid2,
+ uuidv4: () => uuidv4,
+ uuidv6: () => uuidv6,
+ uuidv7: () => uuidv7,
+ void: () => _void2,
+ xid: () => xid2,
+ xor: () => xor
+});
+init_esbuild_shims();
+
+// node_modules/zod/v4/core/index.js
+var core_exports2 = {};
+__export(core_exports2, {
+ $ZodAny: () => $ZodAny,
+ $ZodArray: () => $ZodArray,
+ $ZodAsyncError: () => $ZodAsyncError,
+ $ZodBase64: () => $ZodBase64,
+ $ZodBase64URL: () => $ZodBase64URL,
+ $ZodBigInt: () => $ZodBigInt,
+ $ZodBigIntFormat: () => $ZodBigIntFormat,
+ $ZodBoolean: () => $ZodBoolean,
+ $ZodCIDRv4: () => $ZodCIDRv4,
+ $ZodCIDRv6: () => $ZodCIDRv6,
+ $ZodCUID: () => $ZodCUID,
+ $ZodCUID2: () => $ZodCUID2,
+ $ZodCatch: () => $ZodCatch,
+ $ZodCheck: () => $ZodCheck,
+ $ZodCheckBigIntFormat: () => $ZodCheckBigIntFormat,
+ $ZodCheckEndsWith: () => $ZodCheckEndsWith,
+ $ZodCheckGreaterThan: () => $ZodCheckGreaterThan,
+ $ZodCheckIncludes: () => $ZodCheckIncludes,
+ $ZodCheckLengthEquals: () => $ZodCheckLengthEquals,
+ $ZodCheckLessThan: () => $ZodCheckLessThan,
+ $ZodCheckLowerCase: () => $ZodCheckLowerCase,
+ $ZodCheckMaxLength: () => $ZodCheckMaxLength,
+ $ZodCheckMaxSize: () => $ZodCheckMaxSize,
+ $ZodCheckMimeType: () => $ZodCheckMimeType,
+ $ZodCheckMinLength: () => $ZodCheckMinLength,
+ $ZodCheckMinSize: () => $ZodCheckMinSize,
+ $ZodCheckMultipleOf: () => $ZodCheckMultipleOf,
+ $ZodCheckNumberFormat: () => $ZodCheckNumberFormat,
+ $ZodCheckOverwrite: () => $ZodCheckOverwrite,
+ $ZodCheckProperty: () => $ZodCheckProperty,
+ $ZodCheckRegex: () => $ZodCheckRegex,
+ $ZodCheckSizeEquals: () => $ZodCheckSizeEquals,
+ $ZodCheckStartsWith: () => $ZodCheckStartsWith,
+ $ZodCheckStringFormat: () => $ZodCheckStringFormat,
+ $ZodCheckUpperCase: () => $ZodCheckUpperCase,
+ $ZodCodec: () => $ZodCodec,
+ $ZodCustom: () => $ZodCustom,
+ $ZodCustomStringFormat: () => $ZodCustomStringFormat,
+ $ZodDate: () => $ZodDate,
+ $ZodDefault: () => $ZodDefault,
+ $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion,
+ $ZodE164: () => $ZodE164,
+ $ZodEmail: () => $ZodEmail,
+ $ZodEmoji: () => $ZodEmoji,
+ $ZodEncodeError: () => $ZodEncodeError,
+ $ZodEnum: () => $ZodEnum,
+ $ZodError: () => $ZodError,
+ $ZodExactOptional: () => $ZodExactOptional,
+ $ZodFile: () => $ZodFile,
+ $ZodFunction: () => $ZodFunction,
+ $ZodGUID: () => $ZodGUID,
+ $ZodIPv4: () => $ZodIPv4,
+ $ZodIPv6: () => $ZodIPv6,
+ $ZodISODate: () => $ZodISODate,
+ $ZodISODateTime: () => $ZodISODateTime,
+ $ZodISODuration: () => $ZodISODuration,
+ $ZodISOTime: () => $ZodISOTime,
+ $ZodIntersection: () => $ZodIntersection,
+ $ZodJWT: () => $ZodJWT,
+ $ZodKSUID: () => $ZodKSUID,
+ $ZodLazy: () => $ZodLazy,
+ $ZodLiteral: () => $ZodLiteral,
+ $ZodMAC: () => $ZodMAC,
+ $ZodMap: () => $ZodMap,
+ $ZodNaN: () => $ZodNaN,
+ $ZodNanoID: () => $ZodNanoID,
+ $ZodNever: () => $ZodNever,
+ $ZodNonOptional: () => $ZodNonOptional,
+ $ZodNull: () => $ZodNull,
+ $ZodNullable: () => $ZodNullable,
+ $ZodNumber: () => $ZodNumber,
+ $ZodNumberFormat: () => $ZodNumberFormat,
+ $ZodObject: () => $ZodObject,
+ $ZodObjectJIT: () => $ZodObjectJIT,
+ $ZodOptional: () => $ZodOptional,
+ $ZodPipe: () => $ZodPipe,
+ $ZodPrefault: () => $ZodPrefault,
+ $ZodPreprocess: () => $ZodPreprocess,
+ $ZodPromise: () => $ZodPromise,
+ $ZodReadonly: () => $ZodReadonly,
+ $ZodRealError: () => $ZodRealError,
+ $ZodRecord: () => $ZodRecord,
+ $ZodRegistry: () => $ZodRegistry,
+ $ZodSet: () => $ZodSet,
+ $ZodString: () => $ZodString,
+ $ZodStringFormat: () => $ZodStringFormat,
+ $ZodSuccess: () => $ZodSuccess,
+ $ZodSymbol: () => $ZodSymbol,
+ $ZodTemplateLiteral: () => $ZodTemplateLiteral,
+ $ZodTransform: () => $ZodTransform,
+ $ZodTuple: () => $ZodTuple,
+ $ZodType: () => $ZodType,
+ $ZodULID: () => $ZodULID,
+ $ZodURL: () => $ZodURL,
+ $ZodUUID: () => $ZodUUID,
+ $ZodUndefined: () => $ZodUndefined,
+ $ZodUnion: () => $ZodUnion,
+ $ZodUnknown: () => $ZodUnknown,
+ $ZodVoid: () => $ZodVoid,
+ $ZodXID: () => $ZodXID,
+ $ZodXor: () => $ZodXor,
+ $brand: () => $brand,
+ $constructor: () => $constructor,
+ $input: () => $input,
+ $output: () => $output,
+ Doc: () => Doc,
+ JSONSchema: () => json_schema_exports,
+ JSONSchemaGenerator: () => JSONSchemaGenerator,
+ NEVER: () => NEVER,
+ TimePrecision: () => TimePrecision,
+ _any: () => _any,
+ _array: () => _array,
+ _base64: () => _base64,
+ _base64url: () => _base64url,
+ _bigint: () => _bigint,
+ _boolean: () => _boolean,
+ _catch: () => _catch,
+ _check: () => _check,
+ _cidrv4: () => _cidrv4,
+ _cidrv6: () => _cidrv6,
+ _coercedBigint: () => _coercedBigint,
+ _coercedBoolean: () => _coercedBoolean,
+ _coercedDate: () => _coercedDate,
+ _coercedNumber: () => _coercedNumber,
+ _coercedString: () => _coercedString,
+ _cuid: () => _cuid,
+ _cuid2: () => _cuid2,
+ _custom: () => _custom,
+ _date: () => _date,
+ _decode: () => _decode,
+ _decodeAsync: () => _decodeAsync,
+ _default: () => _default,
+ _discriminatedUnion: () => _discriminatedUnion,
+ _e164: () => _e164,
+ _email: () => _email,
+ _emoji: () => _emoji2,
+ _encode: () => _encode,
+ _encodeAsync: () => _encodeAsync,
+ _endsWith: () => _endsWith,
+ _enum: () => _enum,
+ _file: () => _file,
+ _float32: () => _float32,
+ _float64: () => _float64,
+ _gt: () => _gt,
+ _gte: () => _gte,
+ _guid: () => _guid,
+ _includes: () => _includes,
+ _int: () => _int,
+ _int32: () => _int32,
+ _int64: () => _int64,
+ _intersection: () => _intersection,
+ _ipv4: () => _ipv4,
+ _ipv6: () => _ipv6,
+ _isoDate: () => _isoDate,
+ _isoDateTime: () => _isoDateTime,
+ _isoDuration: () => _isoDuration,
+ _isoTime: () => _isoTime,
+ _jwt: () => _jwt,
+ _ksuid: () => _ksuid,
+ _lazy: () => _lazy,
+ _length: () => _length,
+ _literal: () => _literal,
+ _lowercase: () => _lowercase,
+ _lt: () => _lt,
+ _lte: () => _lte,
+ _mac: () => _mac,
+ _map: () => _map,
+ _max: () => _lte,
+ _maxLength: () => _maxLength,
+ _maxSize: () => _maxSize,
+ _mime: () => _mime,
+ _min: () => _gte,
+ _minLength: () => _minLength,
+ _minSize: () => _minSize,
+ _multipleOf: () => _multipleOf,
+ _nan: () => _nan,
+ _nanoid: () => _nanoid,
+ _nativeEnum: () => _nativeEnum,
+ _negative: () => _negative,
+ _never: () => _never,
+ _nonnegative: () => _nonnegative,
+ _nonoptional: () => _nonoptional,
+ _nonpositive: () => _nonpositive,
+ _normalize: () => _normalize,
+ _null: () => _null2,
+ _nullable: () => _nullable,
+ _number: () => _number,
+ _optional: () => _optional,
+ _overwrite: () => _overwrite,
+ _parse: () => _parse,
+ _parseAsync: () => _parseAsync,
+ _pipe: () => _pipe,
+ _positive: () => _positive,
+ _promise: () => _promise,
+ _property: () => _property,
+ _readonly: () => _readonly,
+ _record: () => _record,
+ _refine: () => _refine,
+ _regex: () => _regex,
+ _safeDecode: () => _safeDecode,
+ _safeDecodeAsync: () => _safeDecodeAsync,
+ _safeEncode: () => _safeEncode,
+ _safeEncodeAsync: () => _safeEncodeAsync,
+ _safeParse: () => _safeParse,
+ _safeParseAsync: () => _safeParseAsync,
+ _set: () => _set,
+ _size: () => _size,
+ _slugify: () => _slugify,
+ _startsWith: () => _startsWith,
+ _string: () => _string,
+ _stringFormat: () => _stringFormat,
+ _stringbool: () => _stringbool,
+ _success: () => _success,
+ _superRefine: () => _superRefine,
+ _symbol: () => _symbol,
+ _templateLiteral: () => _templateLiteral,
+ _toLowerCase: () => _toLowerCase,
+ _toUpperCase: () => _toUpperCase,
+ _transform: () => _transform,
+ _trim: () => _trim,
+ _tuple: () => _tuple,
+ _uint32: () => _uint32,
+ _uint64: () => _uint64,
+ _ulid: () => _ulid,
+ _undefined: () => _undefined2,
+ _union: () => _union,
+ _unknown: () => _unknown,
+ _uppercase: () => _uppercase,
+ _url: () => _url,
+ _uuid: () => _uuid,
+ _uuidv4: () => _uuidv4,
+ _uuidv6: () => _uuidv6,
+ _uuidv7: () => _uuidv7,
+ _void: () => _void,
+ _xid: () => _xid,
+ _xor: () => _xor,
+ clone: () => clone,
+ config: () => config,
+ createStandardJSONSchemaMethod: () => createStandardJSONSchemaMethod,
+ createToJSONSchemaMethod: () => createToJSONSchemaMethod,
+ decode: () => decode,
+ decodeAsync: () => decodeAsync,
+ describe: () => describe,
+ encode: () => encode,
+ encodeAsync: () => encodeAsync,
+ extractDefs: () => extractDefs,
+ finalize: () => finalize,
+ flattenError: () => flattenError,
+ formatError: () => formatError,
+ globalConfig: () => globalConfig,
+ globalRegistry: () => globalRegistry,
+ initializeContext: () => initializeContext,
+ isValidBase64: () => isValidBase64,
+ isValidBase64URL: () => isValidBase64URL,
+ isValidJWT: () => isValidJWT,
+ locales: () => locales_exports,
+ meta: () => meta,
+ parse: () => parse2,
+ parseAsync: () => parseAsync,
+ prettifyError: () => prettifyError,
+ process: () => process14,
+ regexes: () => regexes_exports,
+ registry: () => registry,
+ safeDecode: () => safeDecode,
+ safeDecodeAsync: () => safeDecodeAsync,
+ safeEncode: () => safeEncode,
+ safeEncodeAsync: () => safeEncodeAsync,
+ safeParse: () => safeParse,
+ safeParseAsync: () => safeParseAsync,
+ toDotPath: () => toDotPath,
+ toJSONSchema: () => toJSONSchema,
+ treeifyError: () => treeifyError,
+ util: () => util_exports,
+ version: () => version
+});
+init_esbuild_shims();
+
+// node_modules/zod/v4/core/core.js
+init_esbuild_shims();
+var _a;
+var NEVER = /* @__PURE__ */ Object.freeze({
+ status: "aborted"
+});
+// @__NO_SIDE_EFFECTS__
+function $constructor(name, initializer3, params) {
+ function init(inst, def) {
+ if (!inst._zod) {
+ Object.defineProperty(inst, "_zod", {
+ value: {
+ def,
+ constr: _,
+ traits: /* @__PURE__ */ new Set()
+ },
+ enumerable: false
+ });
+ }
+ if (inst._zod.traits.has(name)) {
+ return;
+ }
+ inst._zod.traits.add(name);
+ initializer3(inst, def);
+ const proto4 = _.prototype;
+ const keys = Object.keys(proto4);
+ for (let i = 0; i < keys.length; i++) {
+ const k = keys[i];
+ if (!(k in inst)) {
+ inst[k] = proto4[k].bind(inst);
+ }
+ }
+ }
+ __name(init, "init");
+ const Parent = params?.Parent ?? Object;
+ class Definition extends Parent {
+ static {
+ __name(this, "Definition");
+ }
+ }
+ Object.defineProperty(Definition, "name", { value: name });
+ function _(def) {
+ var _a6;
+ const inst = params?.Parent ? new Definition() : this;
+ init(inst, def);
+ (_a6 = inst._zod).deferred ?? (_a6.deferred = []);
+ for (const fn of inst._zod.deferred) {
+ fn();
+ }
+ return inst;
+ }
+ __name(_, "_");
+ Object.defineProperty(_, "init", { value: init });
+ Object.defineProperty(_, Symbol.hasInstance, {
+ value: /* @__PURE__ */ __name((inst) => {
+ if (params?.Parent && inst instanceof params.Parent)
+ return true;
+ return inst?._zod?.traits?.has(name);
+ }, "value")
+ });
+ Object.defineProperty(_, "name", { value: name });
+ return _;
+}
+__name($constructor, "$constructor");
+var $brand = /* @__PURE__ */ Symbol("zod_brand");
+var $ZodAsyncError = class extends Error {
+ static {
+ __name(this, "$ZodAsyncError");
+ }
+ constructor() {
+ super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
+ }
+};
+var $ZodEncodeError = class extends Error {
+ static {
+ __name(this, "$ZodEncodeError");
+ }
+ constructor(name) {
+ super(`Encountered unidirectional transform during encode: ${name}`);
+ this.name = "ZodEncodeError";
+ }
+};
+(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});
+var globalConfig = globalThis.__zod_globalConfig;
+function config(newConfig) {
+ if (newConfig)
+ Object.assign(globalConfig, newConfig);
+ return globalConfig;
+}
+__name(config, "config");
+
+// node_modules/zod/v4/core/parse.js
+init_esbuild_shims();
+
+// node_modules/zod/v4/core/errors.js
+init_esbuild_shims();
+
+// node_modules/zod/v4/core/util.js
+var util_exports = {};
+__export(util_exports, {
+ BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES,
+ Class: () => Class,
+ NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES,
+ aborted: () => aborted,
+ allowsEval: () => allowsEval,
+ assert: () => assert,
+ assertEqual: () => assertEqual,
+ assertIs: () => assertIs,
+ assertNever: () => assertNever,
+ assertNotEqual: () => assertNotEqual,
+ assignProp: () => assignProp,
+ base64ToUint8Array: () => base64ToUint8Array,
+ base64urlToUint8Array: () => base64urlToUint8Array,
+ cached: () => cached,
+ captureStackTrace: () => captureStackTrace,
+ cleanEnum: () => cleanEnum,
+ cleanRegex: () => cleanRegex,
+ clone: () => clone,
+ cloneDef: () => cloneDef,
+ createTransparentProxy: () => createTransparentProxy,
+ defineLazy: () => defineLazy,
+ esc: () => esc,
+ escapeRegex: () => escapeRegex,
+ explicitlyAborted: () => explicitlyAborted,
+ extend: () => extend,
+ finalizeIssue: () => finalizeIssue,
+ floatSafeRemainder: () => floatSafeRemainder,
+ getElementAtPath: () => getElementAtPath,
+ getEnumValues: () => getEnumValues,
+ getLengthableOrigin: () => getLengthableOrigin,
+ getParsedType: () => getParsedType,
+ getSizableOrigin: () => getSizableOrigin,
+ hexToUint8Array: () => hexToUint8Array,
+ isObject: () => isObject,
+ isPlainObject: () => isPlainObject2,
+ issue: () => issue,
+ joinValues: () => joinValues,
+ jsonStringifyReplacer: () => jsonStringifyReplacer,
+ merge: () => merge,
+ mergeDefs: () => mergeDefs,
+ normalizeParams: () => normalizeParams,
+ nullish: () => nullish,
+ numKeys: () => numKeys,
+ objectClone: () => objectClone,
+ omit: () => omit,
+ optionalKeys: () => optionalKeys,
+ parsedType: () => parsedType,
+ partial: () => partial,
+ pick: () => pick,
+ prefixIssues: () => prefixIssues,
+ primitiveTypes: () => primitiveTypes,
+ promiseAllObject: () => promiseAllObject,
+ propertyKeyTypes: () => propertyKeyTypes,
+ randomString: () => randomString,
+ required: () => required,
+ safeExtend: () => safeExtend,
+ shallowClone: () => shallowClone,
+ slugify: () => slugify,
+ stringifyPrimitive: () => stringifyPrimitive,
+ uint8ArrayToBase64: () => uint8ArrayToBase64,
+ uint8ArrayToBase64url: () => uint8ArrayToBase64url,
+ uint8ArrayToHex: () => uint8ArrayToHex,
+ unwrapMessage: () => unwrapMessage
+});
+init_esbuild_shims();
+function assertEqual(val) {
+ return val;
+}
+__name(assertEqual, "assertEqual");
+function assertNotEqual(val) {
+ return val;
+}
+__name(assertNotEqual, "assertNotEqual");
+function assertIs(_arg) {
+}
+__name(assertIs, "assertIs");
+function assertNever(_x) {
+ throw new Error("Unexpected value in exhaustive check");
+}
+__name(assertNever, "assertNever");
+function assert(_) {
+}
+__name(assert, "assert");
+function getEnumValues(entries) {
+ const numericValues = Object.values(entries).filter((v) => typeof v === "number");
+ const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
+ return values;
+}
+__name(getEnumValues, "getEnumValues");
+function joinValues(array2, separator = "|") {
+ return array2.map((val) => stringifyPrimitive(val)).join(separator);
+}
+__name(joinValues, "joinValues");
+function jsonStringifyReplacer(_, value) {
+ if (typeof value === "bigint")
+ return value.toString();
+ return value;
+}
+__name(jsonStringifyReplacer, "jsonStringifyReplacer");
+function cached(getter) {
+ const set2 = false;
+ return {
+ get value() {
+ if (!set2) {
+ const value = getter();
+ Object.defineProperty(this, "value", { value });
+ return value;
+ }
+ throw new Error("cached value already set");
+ }
+ };
+}
+__name(cached, "cached");
+function nullish(input) {
+ return input === null || input === void 0;
+}
+__name(nullish, "nullish");
+function cleanRegex(source) {
+ const start = source.startsWith("^") ? 1 : 0;
+ const end = source.endsWith("$") ? source.length - 1 : source.length;
+ return source.slice(start, end);
+}
+__name(cleanRegex, "cleanRegex");
+function floatSafeRemainder(val, step) {
+ const ratio = val / step;
+ const roundedRatio = Math.round(ratio);
+ const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1);
+ if (Math.abs(ratio - roundedRatio) < tolerance)
+ return 0;
+ return ratio - roundedRatio;
+}
+__name(floatSafeRemainder, "floatSafeRemainder");
+var EVALUATING = /* @__PURE__ */ Symbol("evaluating");
+function defineLazy(object2, key, getter) {
+ let value = void 0;
+ Object.defineProperty(object2, key, {
+ get() {
+ if (value === EVALUATING) {
+ return void 0;
+ }
+ if (value === void 0) {
+ value = EVALUATING;
+ value = getter();
+ }
+ return value;
+ },
+ set(v) {
+ Object.defineProperty(object2, key, {
+ value: v
+ // configurable: true,
+ });
+ },
+ configurable: true
+ });
+}
+__name(defineLazy, "defineLazy");
+function objectClone(obj) {
+ return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));
+}
+__name(objectClone, "objectClone");
+function assignProp(target, prop, value) {
+ Object.defineProperty(target, prop, {
+ value,
+ writable: true,
+ enumerable: true,
+ configurable: true
+ });
+}
+__name(assignProp, "assignProp");
+function mergeDefs(...defs) {
+ const mergedDescriptors = {};
+ for (const def of defs) {
+ const descriptors = Object.getOwnPropertyDescriptors(def);
+ Object.assign(mergedDescriptors, descriptors);
+ }
+ return Object.defineProperties({}, mergedDescriptors);
+}
+__name(mergeDefs, "mergeDefs");
+function cloneDef(schema) {
+ return mergeDefs(schema._zod.def);
+}
+__name(cloneDef, "cloneDef");
+function getElementAtPath(obj, path27) {
+ if (!path27)
+ return obj;
+ return path27.reduce((acc, key) => acc?.[key], obj);
+}
+__name(getElementAtPath, "getElementAtPath");
+function promiseAllObject(promisesObj) {
+ const keys = Object.keys(promisesObj);
+ const promises = keys.map((key) => promisesObj[key]);
+ return Promise.all(promises).then((results) => {
+ const resolvedObj = {};
+ for (let i = 0; i < keys.length; i++) {
+ resolvedObj[keys[i]] = results[i];
+ }
+ return resolvedObj;
+ });
+}
+__name(promiseAllObject, "promiseAllObject");
+function randomString(length = 10) {
+ const chars = "abcdefghijklmnopqrstuvwxyz";
+ let str3 = "";
+ for (let i = 0; i < length; i++) {
+ str3 += chars[Math.floor(Math.random() * chars.length)];
+ }
+ return str3;
+}
+__name(randomString, "randomString");
+function esc(str3) {
+ return JSON.stringify(str3);
+}
+__name(esc, "esc");
+function slugify(input) {
+ return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
+}
+__name(slugify, "slugify");
+var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {
+};
+function isObject(data) {
+ return typeof data === "object" && data !== null && !Array.isArray(data);
+}
+__name(isObject, "isObject");
+var allowsEval = /* @__PURE__ */ cached(() => {
+ if (globalConfig.jitless) {
+ return false;
+ }
+ if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) {
+ return false;
+ }
+ try {
+ const F = Function;
+ new F("");
+ return true;
+ } catch (_) {
+ return false;
+ }
+});
+function isPlainObject2(o) {
+ if (isObject(o) === false)
+ return false;
+ const ctor = o.constructor;
+ if (ctor === void 0)
+ return true;
+ if (typeof ctor !== "function")
+ return true;
+ const prot = ctor.prototype;
+ if (isObject(prot) === false)
+ return false;
+ if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
+ return false;
+ }
+ return true;
+}
+__name(isPlainObject2, "isPlainObject");
+function shallowClone(o) {
+ if (isPlainObject2(o))
+ return { ...o };
+ if (Array.isArray(o))
+ return [...o];
+ if (o instanceof Map)
+ return new Map(o);
+ if (o instanceof Set)
+ return new Set(o);
+ return o;
+}
+__name(shallowClone, "shallowClone");
+function numKeys(data) {
+ let keyCount = 0;
+ for (const key in data) {
+ if (Object.prototype.hasOwnProperty.call(data, key)) {
+ keyCount++;
+ }
+ }
+ return keyCount;
+}
+__name(numKeys, "numKeys");
+var getParsedType = /* @__PURE__ */ __name((data) => {
+ const t = typeof data;
+ switch (t) {
+ case "undefined":
+ return "undefined";
+ case "string":
+ return "string";
+ case "number":
+ return Number.isNaN(data) ? "nan" : "number";
+ case "boolean":
+ return "boolean";
+ case "function":
+ return "function";
+ case "bigint":
+ return "bigint";
+ case "symbol":
+ return "symbol";
+ case "object":
+ if (Array.isArray(data)) {
+ return "array";
+ }
+ if (data === null) {
+ return "null";
+ }
+ if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
+ return "promise";
+ }
+ if (typeof Map !== "undefined" && data instanceof Map) {
+ return "map";
+ }
+ if (typeof Set !== "undefined" && data instanceof Set) {
+ return "set";
+ }
+ if (typeof Date !== "undefined" && data instanceof Date) {
+ return "date";
+ }
+ if (typeof File !== "undefined" && data instanceof File) {
+ return "file";
+ }
+ return "object";
+ default:
+ throw new Error(`Unknown data type: ${t}`);
+ }
+}, "getParsedType");
+var propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]);
+var primitiveTypes = /* @__PURE__ */ new Set([
+ "string",
+ "number",
+ "bigint",
+ "boolean",
+ "symbol",
+ "undefined"
+]);
+function escapeRegex(str3) {
+ return str3.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
+__name(escapeRegex, "escapeRegex");
+function clone(inst, def, params) {
+ const cl = new inst._zod.constr(def ?? inst._zod.def);
+ if (!def || params?.parent)
+ cl._zod.parent = inst;
+ return cl;
+}
+__name(clone, "clone");
+function normalizeParams(_params) {
+ const params = _params;
+ if (!params)
+ return {};
+ if (typeof params === "string")
+ return { error: /* @__PURE__ */ __name(() => params, "error") };
+ if (params?.message !== void 0) {
+ if (params?.error !== void 0)
+ throw new Error("Cannot specify both `message` and `error` params");
+ params.error = params.message;
+ }
+ delete params.message;
+ if (typeof params.error === "string")
+ return { ...params, error: /* @__PURE__ */ __name(() => params.error, "error") };
+ return params;
+}
+__name(normalizeParams, "normalizeParams");
+function createTransparentProxy(getter) {
+ let target;
+ return new Proxy({}, {
+ get(_, prop, receiver) {
+ target ?? (target = getter());
+ return Reflect.get(target, prop, receiver);
+ },
+ set(_, prop, value, receiver) {
+ target ?? (target = getter());
+ return Reflect.set(target, prop, value, receiver);
+ },
+ has(_, prop) {
+ target ?? (target = getter());
+ return Reflect.has(target, prop);
+ },
+ deleteProperty(_, prop) {
+ target ?? (target = getter());
+ return Reflect.deleteProperty(target, prop);
+ },
+ ownKeys(_) {
+ target ?? (target = getter());
+ return Reflect.ownKeys(target);
+ },
+ getOwnPropertyDescriptor(_, prop) {
+ target ?? (target = getter());
+ return Reflect.getOwnPropertyDescriptor(target, prop);
+ },
+ defineProperty(_, prop, descriptor) {
+ target ?? (target = getter());
+ return Reflect.defineProperty(target, prop, descriptor);
+ }
+ });
+}
+__name(createTransparentProxy, "createTransparentProxy");
+function stringifyPrimitive(value) {
+ if (typeof value === "bigint")
+ return value.toString() + "n";
+ if (typeof value === "string")
+ return `"${value}"`;
+ return `${value}`;
+}
+__name(stringifyPrimitive, "stringifyPrimitive");
+function optionalKeys(shape) {
+ return Object.keys(shape).filter((k) => {
+ return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
+ });
+}
+__name(optionalKeys, "optionalKeys");
+var NUMBER_FORMAT_RANGES = {
+ safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
+ int32: [-2147483648, 2147483647],
+ uint32: [0, 4294967295],
+ float32: [-34028234663852886e22, 34028234663852886e22],
+ float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
+};
+var BIGINT_FORMAT_RANGES = {
+ int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")],
+ uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")]
+};
+function pick(schema, mask) {
+ const currDef = schema._zod.def;
+ const checks = currDef.checks;
+ const hasChecks = checks && checks.length > 0;
+ if (hasChecks) {
+ throw new Error(".pick() cannot be used on object schemas containing refinements");
+ }
+ const def = mergeDefs(schema._zod.def, {
+ get shape() {
+ const newShape = {};
+ for (const key in mask) {
+ if (!(key in currDef.shape)) {
+ throw new Error(`Unrecognized key: "${key}"`);
+ }
+ if (!mask[key])
+ continue;
+ newShape[key] = currDef.shape[key];
+ }
+ assignProp(this, "shape", newShape);
+ return newShape;
+ },
+ checks: []
+ });
+ return clone(schema, def);
+}
+__name(pick, "pick");
+function omit(schema, mask) {
+ const currDef = schema._zod.def;
+ const checks = currDef.checks;
+ const hasChecks = checks && checks.length > 0;
+ if (hasChecks) {
+ throw new Error(".omit() cannot be used on object schemas containing refinements");
+ }
+ const def = mergeDefs(schema._zod.def, {
+ get shape() {
+ const newShape = { ...schema._zod.def.shape };
+ for (const key in mask) {
+ if (!(key in currDef.shape)) {
+ throw new Error(`Unrecognized key: "${key}"`);
+ }
+ if (!mask[key])
+ continue;
+ delete newShape[key];
+ }
+ assignProp(this, "shape", newShape);
+ return newShape;
+ },
+ checks: []
+ });
+ return clone(schema, def);
+}
+__name(omit, "omit");
+function extend(schema, shape) {
+ if (!isPlainObject2(shape)) {
+ throw new Error("Invalid input to extend: expected a plain object");
+ }
+ const checks = schema._zod.def.checks;
+ const hasChecks = checks && checks.length > 0;
+ if (hasChecks) {
+ const existingShape = schema._zod.def.shape;
+ for (const key in shape) {
+ if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) {
+ throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.");
+ }
+ }
+ }
+ const def = mergeDefs(schema._zod.def, {
+ get shape() {
+ const _shape = { ...schema._zod.def.shape, ...shape };
+ assignProp(this, "shape", _shape);
+ return _shape;
+ }
+ });
+ return clone(schema, def);
+}
+__name(extend, "extend");
+function safeExtend(schema, shape) {
+ if (!isPlainObject2(shape)) {
+ throw new Error("Invalid input to safeExtend: expected a plain object");
+ }
+ const def = mergeDefs(schema._zod.def, {
+ get shape() {
+ const _shape = { ...schema._zod.def.shape, ...shape };
+ assignProp(this, "shape", _shape);
+ return _shape;
+ }
+ });
+ return clone(schema, def);
+}
+__name(safeExtend, "safeExtend");
+function merge(a, b) {
+ if (a._zod.def.checks?.length) {
+ throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");
+ }
+ const def = mergeDefs(a._zod.def, {
+ get shape() {
+ const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };
+ assignProp(this, "shape", _shape);
+ return _shape;
+ },
+ get catchall() {
+ return b._zod.def.catchall;
+ },
+ checks: b._zod.def.checks ?? []
+ });
+ return clone(a, def);
+}
+__name(merge, "merge");
+function partial(Class2, schema, mask) {
+ const currDef = schema._zod.def;
+ const checks = currDef.checks;
+ const hasChecks = checks && checks.length > 0;
+ if (hasChecks) {
+ throw new Error(".partial() cannot be used on object schemas containing refinements");
+ }
+ const def = mergeDefs(schema._zod.def, {
+ get shape() {
+ const oldShape = schema._zod.def.shape;
+ const shape = { ...oldShape };
+ if (mask) {
+ for (const key in mask) {
+ if (!(key in oldShape)) {
+ throw new Error(`Unrecognized key: "${key}"`);
+ }
+ if (!mask[key])
+ continue;
+ shape[key] = Class2 ? new Class2({
+ type: "optional",
+ innerType: oldShape[key]
+ }) : oldShape[key];
+ }
+ } else {
+ for (const key in oldShape) {
+ shape[key] = Class2 ? new Class2({
+ type: "optional",
+ innerType: oldShape[key]
+ }) : oldShape[key];
+ }
+ }
+ assignProp(this, "shape", shape);
+ return shape;
+ },
+ checks: []
+ });
+ return clone(schema, def);
+}
+__name(partial, "partial");
+function required(Class2, schema, mask) {
+ const def = mergeDefs(schema._zod.def, {
+ get shape() {
+ const oldShape = schema._zod.def.shape;
+ const shape = { ...oldShape };
+ if (mask) {
+ for (const key in mask) {
+ if (!(key in shape)) {
+ throw new Error(`Unrecognized key: "${key}"`);
+ }
+ if (!mask[key])
+ continue;
+ shape[key] = new Class2({
+ type: "nonoptional",
+ innerType: oldShape[key]
+ });
+ }
+ } else {
+ for (const key in oldShape) {
+ shape[key] = new Class2({
+ type: "nonoptional",
+ innerType: oldShape[key]
+ });
+ }
+ }
+ assignProp(this, "shape", shape);
+ return shape;
+ }
+ });
+ return clone(schema, def);
+}
+__name(required, "required");
+function aborted(x, startIndex = 0) {
+ if (x.aborted === true)
+ return true;
+ for (let i = startIndex; i < x.issues.length; i++) {
+ if (x.issues[i]?.continue !== true) {
+ return true;
+ }
+ }
+ return false;
+}
+__name(aborted, "aborted");
+function explicitlyAborted(x, startIndex = 0) {
+ if (x.aborted === true)
+ return true;
+ for (let i = startIndex; i < x.issues.length; i++) {
+ if (x.issues[i]?.continue === false) {
+ return true;
+ }
+ }
+ return false;
+}
+__name(explicitlyAborted, "explicitlyAborted");
+function prefixIssues(path27, issues) {
+ return issues.map((iss) => {
+ var _a6;
+ (_a6 = iss).path ?? (_a6.path = []);
+ iss.path.unshift(path27);
+ return iss;
+ });
+}
+__name(prefixIssues, "prefixIssues");
+function unwrapMessage(message) {
+ return typeof message === "string" ? message : message?.message;
+}
+__name(unwrapMessage, "unwrapMessage");
+function finalizeIssue(iss, ctx, config2) {
+ const message = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input";
+ const { inst: _inst, continue: _continue, input: _input, ...rest } = iss;
+ rest.path ?? (rest.path = []);
+ rest.message = message;
+ if (ctx?.reportInput) {
+ rest.input = _input;
+ }
+ return rest;
+}
+__name(finalizeIssue, "finalizeIssue");
+function getSizableOrigin(input) {
+ if (input instanceof Set)
+ return "set";
+ if (input instanceof Map)
+ return "map";
+ if (input instanceof File)
+ return "file";
+ return "unknown";
+}
+__name(getSizableOrigin, "getSizableOrigin");
+function getLengthableOrigin(input) {
+ if (Array.isArray(input))
+ return "array";
+ if (typeof input === "string")
+ return "string";
+ return "unknown";
+}
+__name(getLengthableOrigin, "getLengthableOrigin");
+function parsedType(data) {
+ const t = typeof data;
+ switch (t) {
+ case "number": {
+ return Number.isNaN(data) ? "nan" : "number";
+ }
+ case "object": {
+ if (data === null) {
+ return "null";
+ }
+ if (Array.isArray(data)) {
+ return "array";
+ }
+ const obj = data;
+ if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) {
+ return obj.constructor.name;
+ }
+ }
+ }
+ return t;
+}
+__name(parsedType, "parsedType");
+function issue(...args) {
+ const [iss, input, inst] = args;
+ if (typeof iss === "string") {
+ return {
+ message: iss,
+ code: "custom",
+ input,
+ inst
+ };
+ }
+ return { ...iss };
+}
+__name(issue, "issue");
+function cleanEnum(obj) {
+ return Object.entries(obj).filter(([k, _]) => {
+ return Number.isNaN(Number.parseInt(k, 10));
+ }).map((el) => el[1]);
+}
+__name(cleanEnum, "cleanEnum");
+function base64ToUint8Array(base643) {
+ const binaryString = atob(base643);
+ const bytes = new Uint8Array(binaryString.length);
+ for (let i = 0; i < binaryString.length; i++) {
+ bytes[i] = binaryString.charCodeAt(i);
+ }
+ return bytes;
+}
+__name(base64ToUint8Array, "base64ToUint8Array");
+function uint8ArrayToBase64(bytes) {
+ let binaryString = "";
+ for (let i = 0; i < bytes.length; i++) {
+ binaryString += String.fromCharCode(bytes[i]);
+ }
+ return btoa(binaryString);
+}
+__name(uint8ArrayToBase64, "uint8ArrayToBase64");
+function base64urlToUint8Array(base64url3) {
+ const base643 = base64url3.replace(/-/g, "+").replace(/_/g, "/");
+ const padding = "=".repeat((4 - base643.length % 4) % 4);
+ return base64ToUint8Array(base643 + padding);
+}
+__name(base64urlToUint8Array, "base64urlToUint8Array");
+function uint8ArrayToBase64url(bytes) {
+ return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
+}
+__name(uint8ArrayToBase64url, "uint8ArrayToBase64url");
+function hexToUint8Array(hex3) {
+ const cleanHex = hex3.replace(/^0x/, "");
+ if (cleanHex.length % 2 !== 0) {
+ throw new Error("Invalid hex string length");
+ }
+ const bytes = new Uint8Array(cleanHex.length / 2);
+ for (let i = 0; i < cleanHex.length; i += 2) {
+ bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);
+ }
+ return bytes;
+}
+__name(hexToUint8Array, "hexToUint8Array");
+function uint8ArrayToHex(bytes) {
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
+}
+__name(uint8ArrayToHex, "uint8ArrayToHex");
+var Class = class {
+ static {
+ __name(this, "Class");
+ }
+ constructor(..._args) {
+ }
+};
+
+// node_modules/zod/v4/core/errors.js
+var initializer = /* @__PURE__ */ __name((inst, def) => {
+ inst.name = "$ZodError";
+ Object.defineProperty(inst, "_zod", {
+ value: inst._zod,
+ enumerable: false
+ });
+ Object.defineProperty(inst, "issues", {
+ value: def,
+ enumerable: false
+ });
+ inst.message = JSON.stringify(def, jsonStringifyReplacer, 2);
+ Object.defineProperty(inst, "toString", {
+ value: /* @__PURE__ */ __name(() => inst.message, "value"),
+ enumerable: false
+ });
+}, "initializer");
+var $ZodError = $constructor("$ZodError", initializer);
+var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error });
+function flattenError(error51, mapper = (issue2) => issue2.message) {
+ const fieldErrors = {};
+ const formErrors = [];
+ for (const sub of error51.issues) {
+ if (sub.path.length > 0) {
+ fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
+ fieldErrors[sub.path[0]].push(mapper(sub));
+ } else {
+ formErrors.push(mapper(sub));
+ }
+ }
+ return { formErrors, fieldErrors };
+}
+__name(flattenError, "flattenError");
+function formatError(error51, mapper = (issue2) => issue2.message) {
+ const fieldErrors = { _errors: [] };
+ const processError = /* @__PURE__ */ __name((error52, path27 = []) => {
+ for (const issue2 of error52.issues) {
+ if (issue2.code === "invalid_union" && issue2.errors.length) {
+ issue2.errors.map((issues) => processError({ issues }, [...path27, ...issue2.path]));
+ } else if (issue2.code === "invalid_key") {
+ processError({ issues: issue2.issues }, [...path27, ...issue2.path]);
+ } else if (issue2.code === "invalid_element") {
+ processError({ issues: issue2.issues }, [...path27, ...issue2.path]);
+ } else {
+ const fullpath = [...path27, ...issue2.path];
+ if (fullpath.length === 0) {
+ fieldErrors._errors.push(mapper(issue2));
+ } else {
+ let curr = fieldErrors;
+ let i = 0;
+ while (i < fullpath.length) {
+ const el = fullpath[i];
+ const terminal = i === fullpath.length - 1;
+ if (!terminal) {
+ curr[el] = curr[el] || { _errors: [] };
+ } else {
+ curr[el] = curr[el] || { _errors: [] };
+ curr[el]._errors.push(mapper(issue2));
+ }
+ curr = curr[el];
+ i++;
+ }
+ }
+ }
+ }
+ }, "processError");
+ processError(error51);
+ return fieldErrors;
+}
+__name(formatError, "formatError");
+function treeifyError(error51, mapper = (issue2) => issue2.message) {
+ const result = { errors: [] };
+ const processError = /* @__PURE__ */ __name((error52, path27 = []) => {
+ var _a6, _b2;
+ for (const issue2 of error52.issues) {
+ if (issue2.code === "invalid_union" && issue2.errors.length) {
+ issue2.errors.map((issues) => processError({ issues }, [...path27, ...issue2.path]));
+ } else if (issue2.code === "invalid_key") {
+ processError({ issues: issue2.issues }, [...path27, ...issue2.path]);
+ } else if (issue2.code === "invalid_element") {
+ processError({ issues: issue2.issues }, [...path27, ...issue2.path]);
+ } else {
+ const fullpath = [...path27, ...issue2.path];
+ if (fullpath.length === 0) {
+ result.errors.push(mapper(issue2));
+ continue;
+ }
+ let curr = result;
+ let i = 0;
+ while (i < fullpath.length) {
+ const el = fullpath[i];
+ const terminal = i === fullpath.length - 1;
+ if (typeof el === "string") {
+ curr.properties ?? (curr.properties = {});
+ (_a6 = curr.properties)[el] ?? (_a6[el] = { errors: [] });
+ curr = curr.properties[el];
+ } else {
+ curr.items ?? (curr.items = []);
+ (_b2 = curr.items)[el] ?? (_b2[el] = { errors: [] });
+ curr = curr.items[el];
+ }
+ if (terminal) {
+ curr.errors.push(mapper(issue2));
+ }
+ i++;
+ }
+ }
+ }
+ }, "processError");
+ processError(error51);
+ return result;
+}
+__name(treeifyError, "treeifyError");
+function toDotPath(_path) {
+ const segs = [];
+ const path27 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
+ for (const seg of path27) {
+ if (typeof seg === "number")
+ segs.push(`[${seg}]`);
+ else if (typeof seg === "symbol")
+ segs.push(`[${JSON.stringify(String(seg))}]`);
+ else if (/[^\w$]/.test(seg))
+ segs.push(`[${JSON.stringify(seg)}]`);
+ else {
+ if (segs.length)
+ segs.push(".");
+ segs.push(seg);
+ }
+ }
+ return segs.join("");
+}
+__name(toDotPath, "toDotPath");
+function prettifyError(error51) {
+ const lines = [];
+ const issues = [...error51.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);
+ for (const issue2 of issues) {
+ lines.push(`\u2716 ${issue2.message}`);
+ if (issue2.path?.length)
+ lines.push(` \u2192 at ${toDotPath(issue2.path)}`);
+ }
+ return lines.join("\n");
+}
+__name(prettifyError, "prettifyError");
+
+// node_modules/zod/v4/core/parse.js
+var _parse = /* @__PURE__ */ __name((_Err) => (schema, value, _ctx, _params) => {
+ const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
+ const result = schema._zod.run({ value, issues: [] }, ctx);
+ if (result instanceof Promise) {
+ throw new $ZodAsyncError();
+ }
+ if (result.issues.length) {
+ const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
+ captureStackTrace(e, _params?.callee);
+ throw e;
+ }
+ return result.value;
+}, "_parse");
+var parse2 = /* @__PURE__ */ _parse($ZodRealError);
+var _parseAsync = /* @__PURE__ */ __name((_Err) => async (schema, value, _ctx, params) => {
+ const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
+ let result = schema._zod.run({ value, issues: [] }, ctx);
+ if (result instanceof Promise)
+ result = await result;
+ if (result.issues.length) {
+ const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
+ captureStackTrace(e, params?.callee);
+ throw e;
+ }
+ return result.value;
+}, "_parseAsync");
+var parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError);
+var _safeParse = /* @__PURE__ */ __name((_Err) => (schema, value, _ctx) => {
+ const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
+ const result = schema._zod.run({ value, issues: [] }, ctx);
+ if (result instanceof Promise) {
+ throw new $ZodAsyncError();
+ }
+ return result.issues.length ? {
+ success: false,
+ error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
+ } : { success: true, data: result.value };
+}, "_safeParse");
+var safeParse = /* @__PURE__ */ _safeParse($ZodRealError);
+var _safeParseAsync = /* @__PURE__ */ __name((_Err) => async (schema, value, _ctx) => {
+ const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
+ let result = schema._zod.run({ value, issues: [] }, ctx);
+ if (result instanceof Promise)
+ result = await result;
+ return result.issues.length ? {
+ success: false,
+ error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
+ } : { success: true, data: result.value };
+}, "_safeParseAsync");
+var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError);
+var _encode = /* @__PURE__ */ __name((_Err) => (schema, value, _ctx) => {
+ const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
+ return _parse(_Err)(schema, value, ctx);
+}, "_encode");
+var encode = /* @__PURE__ */ _encode($ZodRealError);
+var _decode = /* @__PURE__ */ __name((_Err) => (schema, value, _ctx) => {
+ return _parse(_Err)(schema, value, _ctx);
+}, "_decode");
+var decode = /* @__PURE__ */ _decode($ZodRealError);
+var _encodeAsync = /* @__PURE__ */ __name((_Err) => async (schema, value, _ctx) => {
+ const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
+ return _parseAsync(_Err)(schema, value, ctx);
+}, "_encodeAsync");
+var encodeAsync = /* @__PURE__ */ _encodeAsync($ZodRealError);
+var _decodeAsync = /* @__PURE__ */ __name((_Err) => async (schema, value, _ctx) => {
+ return _parseAsync(_Err)(schema, value, _ctx);
+}, "_decodeAsync");
+var decodeAsync = /* @__PURE__ */ _decodeAsync($ZodRealError);
+var _safeEncode = /* @__PURE__ */ __name((_Err) => (schema, value, _ctx) => {
+ const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
+ return _safeParse(_Err)(schema, value, ctx);
+}, "_safeEncode");
+var safeEncode = /* @__PURE__ */ _safeEncode($ZodRealError);
+var _safeDecode = /* @__PURE__ */ __name((_Err) => (schema, value, _ctx) => {
+ return _safeParse(_Err)(schema, value, _ctx);
+}, "_safeDecode");
+var safeDecode = /* @__PURE__ */ _safeDecode($ZodRealError);
+var _safeEncodeAsync = /* @__PURE__ */ __name((_Err) => async (schema, value, _ctx) => {
+ const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
+ return _safeParseAsync(_Err)(schema, value, ctx);
+}, "_safeEncodeAsync");
+var safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync($ZodRealError);
+var _safeDecodeAsync = /* @__PURE__ */ __name((_Err) => async (schema, value, _ctx) => {
+ return _safeParseAsync(_Err)(schema, value, _ctx);
+}, "_safeDecodeAsync");
+var safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync($ZodRealError);
+
+// node_modules/zod/v4/core/schemas.js
+init_esbuild_shims();
+
+// node_modules/zod/v4/core/checks.js
+init_esbuild_shims();
+
+// node_modules/zod/v4/core/regexes.js
+var regexes_exports = {};
+__export(regexes_exports, {
+ base64: () => base64,
+ base64url: () => base64url,
+ bigint: () => bigint,
+ boolean: () => boolean,
+ browserEmail: () => browserEmail,
+ cidrv4: () => cidrv4,
+ cidrv6: () => cidrv6,
+ cuid: () => cuid,
+ cuid2: () => cuid2,
+ date: () => date,
+ datetime: () => datetime,
+ domain: () => domain,
+ duration: () => duration,
+ e164: () => e164,
+ email: () => email,
+ emoji: () => emoji,
+ extendedDuration: () => extendedDuration,
+ guid: () => guid,
+ hex: () => hex,
+ hostname: () => hostname,
+ html5Email: () => html5Email,
+ httpProtocol: () => httpProtocol,
+ idnEmail: () => idnEmail,
+ integer: () => integer,
+ ipv4: () => ipv4,
+ ipv6: () => ipv6,
+ ksuid: () => ksuid,
+ lowercase: () => lowercase,
+ mac: () => mac,
+ md5_base64: () => md5_base64,
+ md5_base64url: () => md5_base64url,
+ md5_hex: () => md5_hex,
+ nanoid: () => nanoid,
+ null: () => _null,
+ number: () => number,
+ rfc5322Email: () => rfc5322Email,
+ sha1_base64: () => sha1_base64,
+ sha1_base64url: () => sha1_base64url,
+ sha1_hex: () => sha1_hex,
+ sha256_base64: () => sha256_base64,
+ sha256_base64url: () => sha256_base64url,
+ sha256_hex: () => sha256_hex,
+ sha384_base64: () => sha384_base64,
+ sha384_base64url: () => sha384_base64url,
+ sha384_hex: () => sha384_hex,
+ sha512_base64: () => sha512_base64,
+ sha512_base64url: () => sha512_base64url,
+ sha512_hex: () => sha512_hex,
+ string: () => string,
+ time: () => time,
+ ulid: () => ulid,
+ undefined: () => _undefined,
+ unicodeEmail: () => unicodeEmail,
+ uppercase: () => uppercase,
+ uuid: () => uuid,
+ uuid4: () => uuid4,
+ uuid6: () => uuid6,
+ uuid7: () => uuid7,
+ xid: () => xid
+});
+init_esbuild_shims();
+var cuid = /^[cC][0-9a-z]{6,}$/;
+var cuid2 = /^[0-9a-z]+$/;
+var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
+var xid = /^[0-9a-vA-V]{20}$/;
+var ksuid = /^[A-Za-z0-9]{27}$/;
+var nanoid = /^[a-zA-Z0-9_-]{21}$/;
+var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
+var 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)?)??$/;
+var 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})$/;
+var uuid = /* @__PURE__ */ __name((version2) => {
+ if (!version2)
+ 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}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
+}, "uuid");
+var uuid4 = /* @__PURE__ */ uuid(4);
+var uuid6 = /* @__PURE__ */ uuid(6);
+var uuid7 = /* @__PURE__ */ uuid(7);
+var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
+var 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])?)*$/;
+var 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,}))$/;
+var unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u;
+var idnEmail = unicodeEmail;
+var browserEmail = /^[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])?)*$/;
+var _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
+function emoji() {
+ return new RegExp(_emoji, "u");
+}
+__name(emoji, "emoji");
+var ipv4 = /^(?:(?: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])$/;
+var ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
+var mac = /* @__PURE__ */ __name((delimiter) => {
+ const escapedDelim = escapeRegex(delimiter ?? ":");
+ return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);
+}, "mac");
+var 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])$/;
+var 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])$/;
+var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
+var base64url = /^[A-Za-z0-9_-]*$/;
+var 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])?)*\.?$/;
+var domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
+var httpProtocol = /^https?$/;
+var e164 = /^\+[1-9]\d{6,14}$/;
+var 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])))`;
+var date = /* @__PURE__ */ new RegExp(`^${dateSource}$`);
+function timeSource(args) {
+ const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
+ const regex2 = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
+ return regex2;
+}
+__name(timeSource, "timeSource");
+function time(args) {
+ return new RegExp(`^${timeSource(args)}$`);
+}
+__name(time, "time");
+function datetime(args) {
+ const time3 = timeSource({ precision: args.precision });
+ const opts = ["Z"];
+ if (args.local)
+ opts.push("");
+ if (args.offset)
+ opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
+ const timeRegex = `${time3}(?:${opts.join("|")})`;
+ return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
+}
+__name(datetime, "datetime");
+var string = /* @__PURE__ */ __name((params) => {
+ const regex2 = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
+ return new RegExp(`^${regex2}$`);
+}, "string");
+var bigint = /^-?\d+n?$/;
+var integer = /^-?\d+$/;
+var number = /^-?\d+(?:\.\d+)?$/;
+var boolean = /^(?:true|false)$/i;
+var _null = /^null$/i;
+var _undefined = /^undefined$/i;
+var lowercase = /^[^A-Z]*$/;
+var uppercase = /^[^a-z]*$/;
+var hex = /^[0-9a-fA-F]*$/;
+function fixedBase64(bodyLength, padding) {
+ return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);
+}
+__name(fixedBase64, "fixedBase64");
+function fixedBase64url(length) {
+ return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);
+}
+__name(fixedBase64url, "fixedBase64url");
+var md5_hex = /^[0-9a-fA-F]{32}$/;
+var md5_base64 = /* @__PURE__ */ fixedBase64(22, "==");
+var md5_base64url = /* @__PURE__ */ fixedBase64url(22);
+var sha1_hex = /^[0-9a-fA-F]{40}$/;
+var sha1_base64 = /* @__PURE__ */ fixedBase64(27, "=");
+var sha1_base64url = /* @__PURE__ */ fixedBase64url(27);
+var sha256_hex = /^[0-9a-fA-F]{64}$/;
+var sha256_base64 = /* @__PURE__ */ fixedBase64(43, "=");
+var sha256_base64url = /* @__PURE__ */ fixedBase64url(43);
+var sha384_hex = /^[0-9a-fA-F]{96}$/;
+var sha384_base64 = /* @__PURE__ */ fixedBase64(64, "");
+var sha384_base64url = /* @__PURE__ */ fixedBase64url(64);
+var sha512_hex = /^[0-9a-fA-F]{128}$/;
+var sha512_base64 = /* @__PURE__ */ fixedBase64(86, "==");
+var sha512_base64url = /* @__PURE__ */ fixedBase64url(86);
+
+// node_modules/zod/v4/core/checks.js
+var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
+ var _a6;
+ inst._zod ?? (inst._zod = {});
+ inst._zod.def = def;
+ (_a6 = inst._zod).onattach ?? (_a6.onattach = []);
+});
+var numericOriginMap = {
+ number: "number",
+ bigint: "bigint",
+ object: "date"
+};
+var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => {
+ $ZodCheck.init(inst, def);
+ const origin = numericOriginMap[typeof def.value];
+ inst._zod.onattach.push((inst2) => {
+ const bag = inst2._zod.bag;
+ const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
+ if (def.value < curr) {
+ if (def.inclusive)
+ bag.maximum = def.value;
+ else
+ bag.exclusiveMaximum = def.value;
+ }
+ });
+ inst._zod.check = (payload) => {
+ if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {
+ return;
+ }
+ payload.issues.push({
+ origin,
+ code: "too_big",
+ maximum: typeof def.value === "object" ? def.value.getTime() : def.value,
+ input: payload.value,
+ inclusive: def.inclusive,
+ inst,
+ continue: !def.abort
+ });
+ };
+});
+var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => {
+ $ZodCheck.init(inst, def);
+ const origin = numericOriginMap[typeof def.value];
+ inst._zod.onattach.push((inst2) => {
+ const bag = inst2._zod.bag;
+ const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
+ if (def.value > curr) {
+ if (def.inclusive)
+ bag.minimum = def.value;
+ else
+ bag.exclusiveMinimum = def.value;
+ }
+ });
+ inst._zod.check = (payload) => {
+ if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {
+ return;
+ }
+ payload.issues.push({
+ origin,
+ code: "too_small",
+ minimum: typeof def.value === "object" ? def.value.getTime() : def.value,
+ input: payload.value,
+ inclusive: def.inclusive,
+ inst,
+ continue: !def.abort
+ });
+ };
+});
+var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => {
+ $ZodCheck.init(inst, def);
+ inst._zod.onattach.push((inst2) => {
+ var _a6;
+ (_a6 = inst2._zod.bag).multipleOf ?? (_a6.multipleOf = def.value);
+ });
+ inst._zod.check = (payload) => {
+ if (typeof payload.value !== typeof def.value)
+ throw new Error("Cannot mix number and bigint in multiple_of check.");
+ const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0;
+ if (isMultiple)
+ return;
+ payload.issues.push({
+ origin: typeof payload.value,
+ code: "not_multiple_of",
+ divisor: def.value,
+ input: payload.value,
+ inst,
+ continue: !def.abort
+ });
+ };
+});
+var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => {
+ $ZodCheck.init(inst, def);
+ def.format = def.format || "float64";
+ const isInt = def.format?.includes("int");
+ const origin = isInt ? "int" : "number";
+ const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];
+ inst._zod.onattach.push((inst2) => {
+ const bag = inst2._zod.bag;
+ bag.format = def.format;
+ bag.minimum = minimum;
+ bag.maximum = maximum;
+ if (isInt)
+ bag.pattern = integer;
+ });
+ inst._zod.check = (payload) => {
+ const input = payload.value;
+ if (isInt) {
+ if (!Number.isInteger(input)) {
+ payload.issues.push({
+ expected: origin,
+ format: def.format,
+ code: "invalid_type",
+ continue: false,
+ input,
+ inst
+ });
+ return;
+ }
+ if (!Number.isSafeInteger(input)) {
+ if (input > 0) {
+ payload.issues.push({
+ input,
+ code: "too_big",
+ maximum: Number.MAX_SAFE_INTEGER,
+ note: "Integers must be within the safe integer range.",
+ inst,
+ origin,
+ inclusive: true,
+ continue: !def.abort
+ });
+ } else {
+ payload.issues.push({
+ input,
+ code: "too_small",
+ minimum: Number.MIN_SAFE_INTEGER,
+ note: "Integers must be within the safe integer range.",
+ inst,
+ origin,
+ inclusive: true,
+ continue: !def.abort
+ });
+ }
+ return;
+ }
+ }
+ if (input < minimum) {
+ payload.issues.push({
+ origin: "number",
+ input,
+ code: "too_small",
+ minimum,
+ inclusive: true,
+ inst,
+ continue: !def.abort
+ });
+ }
+ if (input > maximum) {
+ payload.issues.push({
+ origin: "number",
+ input,
+ code: "too_big",
+ maximum,
+ inclusive: true,
+ inst,
+ continue: !def.abort
+ });
+ }
+ };
+});
+var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => {
+ $ZodCheck.init(inst, def);
+ const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format];
+ inst._zod.onattach.push((inst2) => {
+ const bag = inst2._zod.bag;
+ bag.format = def.format;
+ bag.minimum = minimum;
+ bag.maximum = maximum;
+ });
+ inst._zod.check = (payload) => {
+ const input = payload.value;
+ if (input < minimum) {
+ payload.issues.push({
+ origin: "bigint",
+ input,
+ code: "too_small",
+ minimum,
+ inclusive: true,
+ inst,
+ continue: !def.abort
+ });
+ }
+ if (input > maximum) {
+ payload.issues.push({
+ origin: "bigint",
+ input,
+ code: "too_big",
+ maximum,
+ inclusive: true,
+ inst,
+ continue: !def.abort
+ });
+ }
+ };
+});
+var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => {
+ var _a6;
+ $ZodCheck.init(inst, def);
+ (_a6 = inst._zod.def).when ?? (_a6.when = (payload) => {
+ const val = payload.value;
+ return !nullish(val) && val.size !== void 0;
+ });
+ inst._zod.onattach.push((inst2) => {
+ const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
+ if (def.maximum < curr)
+ inst2._zod.bag.maximum = def.maximum;
+ });
+ inst._zod.check = (payload) => {
+ const input = payload.value;
+ const size = input.size;
+ if (size <= def.maximum)
+ return;
+ payload.issues.push({
+ origin: getSizableOrigin(input),
+ code: "too_big",
+ maximum: def.maximum,
+ inclusive: true,
+ input,
+ inst,
+ continue: !def.abort
+ });
+ };
+});
+var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => {
+ var _a6;
+ $ZodCheck.init(inst, def);
+ (_a6 = inst._zod.def).when ?? (_a6.when = (payload) => {
+ const val = payload.value;
+ return !nullish(val) && val.size !== void 0;
+ });
+ inst._zod.onattach.push((inst2) => {
+ const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
+ if (def.minimum > curr)
+ inst2._zod.bag.minimum = def.minimum;
+ });
+ inst._zod.check = (payload) => {
+ const input = payload.value;
+ const size = input.size;
+ if (size >= def.minimum)
+ return;
+ payload.issues.push({
+ origin: getSizableOrigin(input),
+ code: "too_small",
+ minimum: def.minimum,
+ inclusive: true,
+ input,
+ inst,
+ continue: !def.abort
+ });
+ };
+});
+var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => {
+ var _a6;
+ $ZodCheck.init(inst, def);
+ (_a6 = inst._zod.def).when ?? (_a6.when = (payload) => {
+ const val = payload.value;
+ return !nullish(val) && val.size !== void 0;
+ });
+ inst._zod.onattach.push((inst2) => {
+ const bag = inst2._zod.bag;
+ bag.minimum = def.size;
+ bag.maximum = def.size;
+ bag.size = def.size;
+ });
+ inst._zod.check = (payload) => {
+ const input = payload.value;
+ const size = input.size;
+ if (size === def.size)
+ return;
+ const tooBig = size > def.size;
+ payload.issues.push({
+ origin: getSizableOrigin(input),
+ ...tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size },
+ inclusive: true,
+ exact: true,
+ input: payload.value,
+ inst,
+ continue: !def.abort
+ });
+ };
+});
+var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => {
+ var _a6;
+ $ZodCheck.init(inst, def);
+ (_a6 = inst._zod.def).when ?? (_a6.when = (payload) => {
+ const val = payload.value;
+ return !nullish(val) && val.length !== void 0;
+ });
+ inst._zod.onattach.push((inst2) => {
+ const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
+ if (def.maximum < curr)
+ inst2._zod.bag.maximum = def.maximum;
+ });
+ inst._zod.check = (payload) => {
+ const input = payload.value;
+ const length = input.length;
+ if (length <= def.maximum)
+ return;
+ const origin = getLengthableOrigin(input);
+ payload.issues.push({
+ origin,
+ code: "too_big",
+ maximum: def.maximum,
+ inclusive: true,
+ input,
+ inst,
+ continue: !def.abort
+ });
+ };
+});
+var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => {
+ var _a6;
+ $ZodCheck.init(inst, def);
+ (_a6 = inst._zod.def).when ?? (_a6.when = (payload) => {
+ const val = payload.value;
+ return !nullish(val) && val.length !== void 0;
+ });
+ inst._zod.onattach.push((inst2) => {
+ const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
+ if (def.minimum > curr)
+ inst2._zod.bag.minimum = def.minimum;
+ });
+ inst._zod.check = (payload) => {
+ const input = payload.value;
+ const length = input.length;
+ if (length >= def.minimum)
+ return;
+ const origin = getLengthableOrigin(input);
+ payload.issues.push({
+ origin,
+ code: "too_small",
+ minimum: def.minimum,
+ inclusive: true,
+ input,
+ inst,
+ continue: !def.abort
+ });
+ };
+});
+var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => {
+ var _a6;
+ $ZodCheck.init(inst, def);
+ (_a6 = inst._zod.def).when ?? (_a6.when = (payload) => {
+ const val = payload.value;
+ return !nullish(val) && val.length !== void 0;
+ });
+ inst._zod.onattach.push((inst2) => {
+ const bag = inst2._zod.bag;
+ bag.minimum = def.length;
+ bag.maximum = def.length;
+ bag.length = def.length;
+ });
+ inst._zod.check = (payload) => {
+ const input = payload.value;
+ const length = input.length;
+ if (length === def.length)
+ return;
+ const origin = getLengthableOrigin(input);
+ const tooBig = length > def.length;
+ payload.issues.push({
+ origin,
+ ...tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length },
+ inclusive: true,
+ exact: true,
+ input: payload.value,
+ inst,
+ continue: !def.abort
+ });
+ };
+});
+var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => {
+ var _a6, _b2;
+ $ZodCheck.init(inst, def);
+ inst._zod.onattach.push((inst2) => {
+ const bag = inst2._zod.bag;
+ bag.format = def.format;
+ if (def.pattern) {
+ bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
+ bag.patterns.add(def.pattern);
+ }
+ });
+ if (def.pattern)
+ (_a6 = inst._zod).check ?? (_a6.check = (payload) => {
+ def.pattern.lastIndex = 0;
+ if (def.pattern.test(payload.value))
+ return;
+ payload.issues.push({
+ origin: "string",
+ code: "invalid_format",
+ format: def.format,
+ input: payload.value,
+ ...def.pattern ? { pattern: def.pattern.toString() } : {},
+ inst,
+ continue: !def.abort
+ });
+ });
+ else
+ (_b2 = inst._zod).check ?? (_b2.check = () => {
+ });
+});
+var $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def) => {
+ $ZodCheckStringFormat.init(inst, def);
+ inst._zod.check = (payload) => {
+ def.pattern.lastIndex = 0;
+ if (def.pattern.test(payload.value))
+ return;
+ payload.issues.push({
+ origin: "string",
+ code: "invalid_format",
+ format: "regex",
+ input: payload.value,
+ pattern: def.pattern.toString(),
+ inst,
+ continue: !def.abort
+ });
+ };
+});
+var $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => {
+ def.pattern ?? (def.pattern = lowercase);
+ $ZodCheckStringFormat.init(inst, def);
+});
+var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => {
+ def.pattern ?? (def.pattern = uppercase);
+ $ZodCheckStringFormat.init(inst, def);
+});
+var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => {
+ $ZodCheck.init(inst, def);
+ const escapedRegex = escapeRegex(def.includes);
+ const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
+ def.pattern = pattern;
+ inst._zod.onattach.push((inst2) => {
+ const bag = inst2._zod.bag;
+ bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
+ bag.patterns.add(pattern);
+ });
+ inst._zod.check = (payload) => {
+ if (payload.value.includes(def.includes, def.position))
+ return;
+ payload.issues.push({
+ origin: "string",
+ code: "invalid_format",
+ format: "includes",
+ includes: def.includes,
+ input: payload.value,
+ inst,
+ continue: !def.abort
+ });
+ };
+});
+var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => {
+ $ZodCheck.init(inst, def);
+ const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
+ def.pattern ?? (def.pattern = pattern);
+ inst._zod.onattach.push((inst2) => {
+ const bag = inst2._zod.bag;
+ bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
+ bag.patterns.add(pattern);
+ });
+ inst._zod.check = (payload) => {
+ if (payload.value.startsWith(def.prefix))
+ return;
+ payload.issues.push({
+ origin: "string",
+ code: "invalid_format",
+ format: "starts_with",
+ prefix: def.prefix,
+ input: payload.value,
+ inst,
+ continue: !def.abort
+ });
+ };
+});
+var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => {
+ $ZodCheck.init(inst, def);
+ const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
+ def.pattern ?? (def.pattern = pattern);
+ inst._zod.onattach.push((inst2) => {
+ const bag = inst2._zod.bag;
+ bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
+ bag.patterns.add(pattern);
+ });
+ inst._zod.check = (payload) => {
+ if (payload.value.endsWith(def.suffix))
+ return;
+ payload.issues.push({
+ origin: "string",
+ code: "invalid_format",
+ format: "ends_with",
+ suffix: def.suffix,
+ input: payload.value,
+ inst,
+ continue: !def.abort
+ });
+ };
+});
+function handleCheckPropertyResult(result, payload, property) {
+ if (result.issues.length) {
+ payload.issues.push(...prefixIssues(property, result.issues));
+ }
+}
+__name(handleCheckPropertyResult, "handleCheckPropertyResult");
+var $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, def) => {
+ $ZodCheck.init(inst, def);
+ inst._zod.check = (payload) => {
+ const result = def.schema._zod.run({
+ value: payload.value[def.property],
+ issues: []
+ }, {});
+ if (result instanceof Promise) {
+ return result.then((result2) => handleCheckPropertyResult(result2, payload, def.property));
+ }
+ handleCheckPropertyResult(result, payload, def.property);
+ return;
+ };
+});
+var $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def) => {
+ $ZodCheck.init(inst, def);
+ const mimeSet = new Set(def.mime);
+ inst._zod.onattach.push((inst2) => {
+ inst2._zod.bag.mime = def.mime;
+ });
+ inst._zod.check = (payload) => {
+ if (mimeSet.has(payload.value.type))
+ return;
+ payload.issues.push({
+ code: "invalid_value",
+ values: def.mime,
+ input: payload.value.type,
+ inst,
+ continue: !def.abort
+ });
+ };
+});
+var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => {
+ $ZodCheck.init(inst, def);
+ inst._zod.check = (payload) => {
+ payload.value = def.tx(payload.value);
+ };
+});
+
+// node_modules/zod/v4/core/doc.js
+init_esbuild_shims();
+var Doc = class {
+ static {
+ __name(this, "Doc");
+ }
+ constructor(args = []) {
+ this.content = [];
+ this.indent = 0;
+ if (this)
+ this.args = args;
+ }
+ indented(fn) {
+ this.indent += 1;
+ fn(this);
+ this.indent -= 1;
+ }
+ write(arg) {
+ if (typeof arg === "function") {
+ arg(this, { execution: "sync" });
+ arg(this, { execution: "async" });
+ return;
+ }
+ const content = arg;
+ const lines = content.split("\n").filter((x) => x);
+ const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));
+ const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x);
+ for (const line of dedented) {
+ this.content.push(line);
+ }
+ }
+ compile() {
+ const F = Function;
+ const args = this?.args;
+ const content = this?.content ?? [``];
+ const lines = [...content.map((x) => ` ${x}`)];
+ return new F(...args, lines.join("\n"));
+ }
+};
+
+// node_modules/zod/v4/core/versions.js
+init_esbuild_shims();
+var version = {
+ major: 4,
+ minor: 4,
+ patch: 3
+};
+
+// node_modules/zod/v4/core/schemas.js
+var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
+ var _a6;
+ inst ?? (inst = {});
+ inst._zod.def = def;
+ inst._zod.bag = inst._zod.bag || {};
+ inst._zod.version = version;
+ const checks = [...inst._zod.def.checks ?? []];
+ if (inst._zod.traits.has("$ZodCheck")) {
+ checks.unshift(inst);
+ }
+ for (const ch of checks) {
+ for (const fn of ch._zod.onattach) {
+ fn(inst);
+ }
+ }
+ if (checks.length === 0) {
+ (_a6 = inst._zod).deferred ?? (_a6.deferred = []);
+ inst._zod.deferred?.push(() => {
+ inst._zod.run = inst._zod.parse;
+ });
+ } else {
+ const runChecks = /* @__PURE__ */ __name((payload, checks2, ctx) => {
+ let isAborted = aborted(payload);
+ let asyncResult;
+ for (const ch of checks2) {
+ if (ch._zod.def.when) {
+ if (explicitlyAborted(payload))
+ continue;
+ const shouldRun = ch._zod.def.when(payload);
+ if (!shouldRun)
+ continue;
+ } else if (isAborted) {
+ continue;
+ }
+ const currLen = payload.issues.length;
+ const _ = ch._zod.check(payload);
+ if (_ instanceof Promise && ctx?.async === false) {
+ throw new $ZodAsyncError();
+ }
+ if (asyncResult || _ instanceof Promise) {
+ asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
+ await _;
+ const nextLen = payload.issues.length;
+ if (nextLen === currLen)
+ return;
+ if (!isAborted)
+ isAborted = aborted(payload, currLen);
+ });
+ } else {
+ const nextLen = payload.issues.length;
+ if (nextLen === currLen)
+ continue;
+ if (!isAborted)
+ isAborted = aborted(payload, currLen);
+ }
+ }
+ if (asyncResult) {
+ return asyncResult.then(() => {
+ return payload;
+ });
+ }
+ return payload;
+ }, "runChecks");
+ const handleCanaryResult = /* @__PURE__ */ __name((canary, payload, ctx) => {
+ if (aborted(canary)) {
+ canary.aborted = true;
+ return canary;
+ }
+ const checkResult = runChecks(payload, checks, ctx);
+ if (checkResult instanceof Promise) {
+ if (ctx.async === false)
+ throw new $ZodAsyncError();
+ return checkResult.then((checkResult2) => inst._zod.parse(checkResult2, ctx));
+ }
+ return inst._zod.parse(checkResult, ctx);
+ }, "handleCanaryResult");
+ inst._zod.run = (payload, ctx) => {
+ if (ctx.skipChecks) {
+ return inst._zod.parse(payload, ctx);
+ }
+ if (ctx.direction === "backward") {
+ const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });
+ if (canary instanceof Promise) {
+ return canary.then((canary2) => {
+ return handleCanaryResult(canary2, payload, ctx);
+ });
+ }
+ return handleCanaryResult(canary, payload, ctx);
+ }
+ const result = inst._zod.parse(payload, ctx);
+ if (result instanceof Promise) {
+ if (ctx.async === false)
+ throw new $ZodAsyncError();
+ return result.then((result2) => runChecks(result2, checks, ctx));
+ }
+ return runChecks(result, checks, ctx);
+ };
+ }
+ defineLazy(inst, "~standard", () => ({
+ validate: /* @__PURE__ */ __name((value) => {
+ try {
+ const r = safeParse(inst, value);
+ return r.success ? { value: r.data } : { issues: r.error?.issues };
+ } catch (_) {
+ return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues });
+ }
+ }, "validate"),
+ vendor: "zod",
+ version: 1
+ }));
+});
+var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => {
+ $ZodType.init(inst, def);
+ inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag);
+ inst._zod.parse = (payload, _) => {
+ if (def.coerce)
+ try {
+ payload.value = String(payload.value);
+ } catch (_2) {
+ }
+ if (typeof payload.value === "string")
+ return payload;
+ payload.issues.push({
+ expected: "string",
+ code: "invalid_type",
+ input: payload.value,
+ inst
+ });
+ return payload;
+ };
+});
+var $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => {
+ $ZodCheckStringFormat.init(inst, def);
+ $ZodString.init(inst, def);
+});
+var $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => {
+ def.pattern ?? (def.pattern = guid);
+ $ZodStringFormat.init(inst, def);
+});
+var $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => {
+ if (def.version) {
+ const versionMap = {
+ v1: 1,
+ v2: 2,
+ v3: 3,
+ v4: 4,
+ v5: 5,
+ v6: 6,
+ v7: 7,
+ v8: 8
+ };
+ const v = versionMap[def.version];
+ if (v === void 0)
+ throw new Error(`Invalid UUID version: "${def.version}"`);
+ def.pattern ?? (def.pattern = uuid(v));
+ } else
+ def.pattern ?? (def.pattern = uuid());
+ $ZodStringFormat.init(inst, def);
+});
+var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => {
+ def.pattern ?? (def.pattern = email);
+ $ZodStringFormat.init(inst, def);
+});
+var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {
+ $ZodStringFormat.init(inst, def);
+ inst._zod.check = (payload) => {
+ try {
+ const trimmed = payload.value.trim();
+ if (!def.normalize && def.protocol?.source === httpProtocol.source) {
+ if (!/^https?:\/\//i.test(trimmed)) {
+ payload.issues.push({
+ code: "invalid_format",
+ format: "url",
+ note: "Invalid URL format",
+ input: payload.value,
+ inst,
+ continue: !def.abort
+ });
+ return;
+ }
+ }
+ const url2 = new URL(trimmed);
+ if (def.hostname) {
+ def.hostname.lastIndex = 0;
+ if (!def.hostname.test(url2.hostname)) {
+ payload.issues.push({
+ code: "invalid_format",
+ format: "url",
+ note: "Invalid hostname",
+ pattern: def.hostname.source,
+ input: payload.value,
+ inst,
+ continue: !def.abort
+ });
+ }
+ }
+ if (def.protocol) {
+ def.protocol.lastIndex = 0;
+ if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) {
+ payload.issues.push({
+ code: "invalid_format",
+ format: "url",
+ note: "Invalid protocol",
+ pattern: def.protocol.source,
+ input: payload.value,
+ inst,
+ continue: !def.abort
+ });
+ }
+ }
+ if (def.normalize) {
+ payload.value = url2.href;
+ } else {
+ payload.value = trimmed;
+ }
+ return;
+ } catch (_) {
+ payload.issues.push({
+ code: "invalid_format",
+ format: "url",
+ input: payload.value,
+ inst,
+ continue: !def.abort
+ });
+ }
+ };
+});
+var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => {
+ def.pattern ?? (def.pattern = emoji());
+ $ZodStringFormat.init(inst, def);
+});
+var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => {
+ def.pattern ?? (def.pattern = nanoid);
+ $ZodStringFormat.init(inst, def);
+});
+var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => {
+ def.pattern ?? (def.pattern = cuid);
+ $ZodStringFormat.init(inst, def);
+});
+var $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => {
+ def.pattern ?? (def.pattern = cuid2);
+ $ZodStringFormat.init(inst, def);
+});
+var $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => {
+ def.pattern ?? (def.pattern = ulid);
+ $ZodStringFormat.init(inst, def);
+});
+var $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => {
+ def.pattern ?? (def.pattern = xid);
+ $ZodStringFormat.init(inst, def);
+});
+var $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => {
+ def.pattern ?? (def.pattern = ksuid);
+ $ZodStringFormat.init(inst, def);
+});
+var $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => {
+ def.pattern ?? (def.pattern = datetime(def));
+ $ZodStringFormat.init(inst, def);
+});
+var $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => {
+ def.pattern ?? (def.pattern = date);
+ $ZodStringFormat.init(inst, def);
+});
+var $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => {
+ def.pattern ?? (def.pattern = time(def));
+ $ZodStringFormat.init(inst, def);
+});
+var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => {
+ def.pattern ?? (def.pattern = duration);
+ $ZodStringFormat.init(inst, def);
+});
+var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => {
+ def.pattern ?? (def.pattern = ipv4);
+ $ZodStringFormat.init(inst, def);
+ inst._zod.bag.format = `ipv4`;
+});
+var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => {
+ def.pattern ?? (def.pattern = ipv6);
+ $ZodStringFormat.init(inst, def);
+ inst._zod.bag.format = `ipv6`;
+ inst._zod.check = (payload) => {
+ try {
+ new URL(`http://[${payload.value}]`);
+ } catch {
+ payload.issues.push({
+ code: "invalid_format",
+ format: "ipv6",
+ input: payload.value,
+ inst,
+ continue: !def.abort
+ });
+ }
+ };
+});
+var $ZodMAC = /* @__PURE__ */ $constructor("$ZodMAC", (inst, def) => {
+ def.pattern ?? (def.pattern = mac(def.delimiter));
+ $ZodStringFormat.init(inst, def);
+ inst._zod.bag.format = `mac`;
+});
+var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => {
+ def.pattern ?? (def.pattern = cidrv4);
+ $ZodStringFormat.init(inst, def);
+});
+var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => {
+ def.pattern ?? (def.pattern = cidrv6);
+ $ZodStringFormat.init(inst, def);
+ inst._zod.check = (payload) => {
+ const parts = payload.value.split("/");
+ try {
+ if (parts.length !== 2)
+ throw new Error();
+ const [address, prefix] = parts;
+ if (!prefix)
+ throw new Error();
+ const prefixNum = Number(prefix);
+ if (`${prefixNum}` !== prefix)
+ throw new Error();
+ if (prefixNum < 0 || prefixNum > 128)
+ throw new Error();
+ new URL(`http://[${address}]`);
+ } catch {
+ payload.issues.push({
+ code: "invalid_format",
+ format: "cidrv6",
+ input: payload.value,
+ inst,
+ continue: !def.abort
+ });
+ }
+ };
+});
+function isValidBase64(data) {
+ if (data === "")
+ return true;
+ if (/\s/.test(data))
+ return false;
+ if (data.length % 4 !== 0)
+ return false;
+ try {
+ atob(data);
+ return true;
+ } catch {
+ return false;
+ }
+}
+__name(isValidBase64, "isValidBase64");
+var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
+ def.pattern ?? (def.pattern = base64);
+ $ZodStringFormat.init(inst, def);
+ inst._zod.bag.contentEncoding = "base64";
+ inst._zod.check = (payload) => {
+ if (isValidBase64(payload.value))
+ return;
+ payload.issues.push({
+ code: "invalid_format",
+ format: "base64",
+ input: payload.value,
+ inst,
+ continue: !def.abort
+ });
+ };
+});
+function isValidBase64URL(data) {
+ if (!base64url.test(data))
+ return false;
+ const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
+ const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "=");
+ return isValidBase64(padded);
+}
+__name(isValidBase64URL, "isValidBase64URL");
+var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
+ def.pattern ?? (def.pattern = base64url);
+ $ZodStringFormat.init(inst, def);
+ inst._zod.bag.contentEncoding = "base64url";
+ inst._zod.check = (payload) => {
+ if (isValidBase64URL(payload.value))
+ return;
+ payload.issues.push({
+ code: "invalid_format",
+ format: "base64url",
+ input: payload.value,
+ inst,
+ continue: !def.abort
+ });
+ };
+});
+var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => {
+ def.pattern ?? (def.pattern = e164);
+ $ZodStringFormat.init(inst, def);
+});
+function isValidJWT(token, algorithm = null) {
+ try {
+ const tokensParts = token.split(".");
+ if (tokensParts.length !== 3)
+ return false;
+ const [header] = tokensParts;
+ if (!header)
+ return false;
+ const parsedHeader = JSON.parse(atob(header));
+ if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT")
+ return false;
+ if (!parsedHeader.alg)
+ return false;
+ if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm))
+ return false;
+ return true;
+ } catch {
+ return false;
+ }
+}
+__name(isValidJWT, "isValidJWT");
+var $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => {
+ $ZodStringFormat.init(inst, def);
+ inst._zod.check = (payload) => {
+ if (isValidJWT(payload.value, def.alg))
+ return;
+ payload.issues.push({
+ code: "invalid_format",
+ format: "jwt",
+ input: payload.value,
+ inst,
+ continue: !def.abort
+ });
+ };
+});
+var $ZodCustomStringFormat = /* @__PURE__ */ $constructor("$ZodCustomStringFormat", (inst, def) => {
+ $ZodStringFormat.init(inst, def);
+ inst._zod.check = (payload) => {
+ if (def.fn(payload.value))
+ return;
+ payload.issues.push({
+ code: "invalid_format",
+ format: def.format,
+ input: payload.value,
+ inst,
+ continue: !def.abort
+ });
+ };
+});
+var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
+ $ZodType.init(inst, def);
+ inst._zod.pattern = inst._zod.bag.pattern ?? number;
+ inst._zod.parse = (payload, _ctx) => {
+ if (def.coerce)
+ try {
+ payload.value = Number(payload.value);
+ } catch (_) {
+ }
+ const input = payload.value;
+ if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) {
+ return payload;
+ }
+ const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0;
+ payload.issues.push({
+ expected: "number",
+ code: "invalid_type",
+ input,
+ inst,
+ ...received ? { received } : {}
+ });
+ return payload;
+ };
+});
+var $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumberFormat", (inst, def) => {
+ $ZodCheckNumberFormat.init(inst, def);
+ $ZodNumber.init(inst, def);
+});
+var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => {
+ $ZodType.init(inst, def);
+ inst._zod.pattern = boolean;
+ inst._zod.parse = (payload, _ctx) => {
+ if (def.coerce)
+ try {
+ payload.value = Boolean(payload.value);
+ } catch (_) {
+ }
+ const input = payload.value;
+ if (typeof input === "boolean")
+ return payload;
+ payload.issues.push({
+ expected: "boolean",
+ code: "invalid_type",
+ input,
+ inst
+ });
+ return payload;
+ };
+});
+var $ZodBigInt = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def) => {
+ $ZodType.init(inst, def);
+ inst._zod.pattern = bigint;
+ inst._zod.parse = (payload, _ctx) => {
+ if (def.coerce)
+ try {
+ payload.value = BigInt(payload.value);
+ } catch (_) {
+ }
+ if (typeof payload.value === "bigint")
+ return payload;
+ payload.issues.push({
+ expected: "bigint",
+ code: "invalid_type",
+ input: payload.value,
+ inst
+ });
+ return payload;
+ };
+});
+var $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigIntFormat", (inst, def) => {
+ $ZodCheckBigIntFormat.init(inst, def);
+ $ZodBigInt.init(inst, def);
+});
+var $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def) => {
+ $ZodType.init(inst, def);
+ inst._zod.parse = (payload, _ctx) => {
+ const input = payload.value;
+ if (typeof input === "symbol")
+ return payload;
+ payload.issues.push({
+ expected: "symbol",
+ code: "invalid_type",
+ input,
+ inst
+ });
+ return payload;
+ };
+});
+var $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => {
+ $ZodType.init(inst, def);
+ inst._zod.pattern = _undefined;
+ inst._zod.values = /* @__PURE__ */ new Set([void 0]);
+ inst._zod.parse = (payload, _ctx) => {
+ const input = payload.value;
+ if (typeof input === "undefined")
+ return payload;
+ payload.issues.push({
+ expected: "undefined",
+ code: "invalid_type",
+ input,
+ inst
+ });
+ return payload;
+ };
+});
+var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => {
+ $ZodType.init(inst, def);
+ inst._zod.pattern = _null;
+ inst._zod.values = /* @__PURE__ */ new Set([null]);
+ inst._zod.parse = (payload, _ctx) => {
+ const input = payload.value;
+ if (input === null)
+ return payload;
+ payload.issues.push({
+ expected: "null",
+ code: "invalid_type",
+ input,
+ inst
+ });
+ return payload;
+ };
+});
+var $ZodAny = /* @__PURE__ */ $constructor("$ZodAny", (inst, def) => {
+ $ZodType.init(inst, def);
+ inst._zod.parse = (payload) => payload;
+});
+var $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => {
+ $ZodType.init(inst, def);
+ inst._zod.parse = (payload) => payload;
+});
+var $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => {
+ $ZodType.init(inst, def);
+ inst._zod.parse = (payload, _ctx) => {
+ payload.issues.push({
+ expected: "never",
+ code: "invalid_type",
+ input: payload.value,
+ inst
+ });
+ return payload;
+ };
+});
+var $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def) => {
+ $ZodType.init(inst, def);
+ inst._zod.parse = (payload, _ctx) => {
+ const input = payload.value;
+ if (typeof input === "undefined")
+ return payload;
+ payload.issues.push({
+ expected: "void",
+ code: "invalid_type",
+ input,
+ inst
+ });
+ return payload;
+ };
+});
+var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => {
+ $ZodType.init(inst, def);
+ inst._zod.parse = (payload, _ctx) => {
+ if (def.coerce) {
+ try {
+ payload.value = new Date(payload.value);
+ } catch (_err) {
+ }
+ }
+ const input = payload.value;
+ const isDate = input instanceof Date;
+ const isValidDate = isDate && !Number.isNaN(input.getTime());
+ if (isValidDate)
+ return payload;
+ payload.issues.push({
+ expected: "date",
+ code: "invalid_type",
+ input,
+ ...isDate ? { received: "Invalid Date" } : {},
+ inst
+ });
+ return payload;
+ };
+});
+function handleArrayResult(result, final, index) {
+ if (result.issues.length) {
+ final.issues.push(...prefixIssues(index, result.issues));
+ }
+ final.value[index] = result.value;
+}
+__name(handleArrayResult, "handleArrayResult");
+var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
+ $ZodType.init(inst, def);
+ inst._zod.parse = (payload, ctx) => {
+ const input = payload.value;
+ if (!Array.isArray(input)) {
+ payload.issues.push({
+ expected: "array",
+ code: "invalid_type",
+ input,
+ inst
+ });
+ return payload;
+ }
+ payload.value = Array(input.length);
+ const proms = [];
+ for (let i = 0; i < input.length; i++) {
+ const item = input[i];
+ const result = def.element._zod.run({
+ value: item,
+ issues: []
+ }, ctx);
+ if (result instanceof Promise) {
+ proms.push(result.then((result2) => handleArrayResult(result2, payload, i)));
+ } else {
+ handleArrayResult(result, payload, i);
+ }
+ }
+ if (proms.length) {
+ return Promise.all(proms).then(() => payload);
+ }
+ return payload;
+ };
+});
+function handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) {
+ const isPresent = key in input;
+ if (result.issues.length) {
+ if (isOptionalIn && isOptionalOut && !isPresent) {
+ return;
+ }
+ final.issues.push(...prefixIssues(key, result.issues));
+ }
+ if (!isPresent && !isOptionalIn) {
+ if (!result.issues.length) {
+ final.issues.push({
+ code: "invalid_type",
+ expected: "nonoptional",
+ input: void 0,
+ path: [key]
+ });
+ }
+ return;
+ }
+ if (result.value === void 0) {
+ if (isPresent) {
+ final.value[key] = void 0;
+ }
+ } else {
+ final.value[key] = result.value;
+ }
+}
+__name(handlePropertyResult, "handlePropertyResult");
+function normalizeDef(def) {
+ const keys = Object.keys(def.shape);
+ for (const k of keys) {
+ if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) {
+ throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
+ }
+ }
+ const okeys = optionalKeys(def.shape);
+ return {
+ ...def,
+ keys,
+ keySet: new Set(keys),
+ numKeys: keys.length,
+ optionalKeys: new Set(okeys)
+ };
+}
+__name(normalizeDef, "normalizeDef");
+function handleCatchall(proms, input, payload, ctx, def, inst) {
+ const unrecognized = [];
+ const keySet = def.keySet;
+ const _catchall = def.catchall._zod;
+ const t = _catchall.def.type;
+ const isOptionalIn = _catchall.optin === "optional";
+ const isOptionalOut = _catchall.optout === "optional";
+ for (const key in input) {
+ if (key === "__proto__")
+ continue;
+ if (keySet.has(key))
+ continue;
+ if (t === "never") {
+ unrecognized.push(key);
+ continue;
+ }
+ const r = _catchall.run({ value: input[key], issues: [] }, ctx);
+ if (r instanceof Promise) {
+ proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut)));
+ } else {
+ handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);
+ }
+ }
+ if (unrecognized.length) {
+ payload.issues.push({
+ code: "unrecognized_keys",
+ keys: unrecognized,
+ input,
+ inst
+ });
+ }
+ if (!proms.length)
+ return payload;
+ return Promise.all(proms).then(() => {
+ return payload;
+ });
+}
+__name(handleCatchall, "handleCatchall");
+var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
+ $ZodType.init(inst, def);
+ const desc = Object.getOwnPropertyDescriptor(def, "shape");
+ if (!desc?.get) {
+ const sh = def.shape;
+ Object.defineProperty(def, "shape", {
+ get: /* @__PURE__ */ __name(() => {
+ const newSh = { ...sh };
+ Object.defineProperty(def, "shape", {
+ value: newSh
+ });
+ return newSh;
+ }, "get")
+ });
+ }
+ const _normalized = cached(() => normalizeDef(def));
+ defineLazy(inst._zod, "propValues", () => {
+ const shape = def.shape;
+ const propValues = {};
+ for (const key in shape) {
+ const field = shape[key]._zod;
+ if (field.values) {
+ propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set());
+ for (const v of field.values)
+ propValues[key].add(v);
+ }
+ }
+ return propValues;
+ });
+ const isObject2 = isObject;
+ const catchall = def.catchall;
+ let value;
+ inst._zod.parse = (payload, ctx) => {
+ value ?? (value = _normalized.value);
+ const input = payload.value;
+ if (!isObject2(input)) {
+ payload.issues.push({
+ expected: "object",
+ code: "invalid_type",
+ input,
+ inst
+ });
+ return payload;
+ }
+ payload.value = {};
+ const proms = [];
+ const shape = value.shape;
+ for (const key of value.keys) {
+ const el = shape[key];
+ const isOptionalIn = el._zod.optin === "optional";
+ const isOptionalOut = el._zod.optout === "optional";
+ const r = el._zod.run({ value: input[key], issues: [] }, ctx);
+ if (r instanceof Promise) {
+ proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut)));
+ } else {
+ handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);
+ }
+ }
+ if (!catchall) {
+ return proms.length ? Promise.all(proms).then(() => payload) : payload;
+ }
+ return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);
+ };
+});
+var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => {
+ $ZodObject.init(inst, def);
+ const superParse = inst._zod.parse;
+ const _normalized = cached(() => normalizeDef(def));
+ const generateFastpass = /* @__PURE__ */ __name((shape) => {
+ const doc = new Doc(["shape", "payload", "ctx"]);
+ const normalized = _normalized.value;
+ const parseStr = /* @__PURE__ */ __name((key) => {
+ const k = esc(key);
+ return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
+ }, "parseStr");
+ doc.write(`const input = payload.value;`);
+ const ids = /* @__PURE__ */ Object.create(null);
+ let counter = 0;
+ for (const key of normalized.keys) {
+ ids[key] = `key_${counter++}`;
+ }
+ doc.write(`const newResult = {};`);
+ for (const key of normalized.keys) {
+ const id = ids[key];
+ const k = esc(key);
+ const schema = shape[key];
+ const isOptionalIn = schema?._zod?.optin === "optional";
+ const isOptionalOut = schema?._zod?.optout === "optional";
+ doc.write(`const ${id} = ${parseStr(key)};`);
+ if (isOptionalIn && isOptionalOut) {
+ doc.write(`
+ if (${id}.issues.length) {
+ if (${k} in input) {
+ payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
+ ...iss,
+ path: iss.path ? [${k}, ...iss.path] : [${k}]
+ })));
+ }
+ }
+
+ if (${id}.value === undefined) {
+ if (${k} in input) {
+ newResult[${k}] = undefined;
+ }
+ } else {
+ newResult[${k}] = ${id}.value;
+ }
+
+ `);
+ } else if (!isOptionalIn) {
+ doc.write(`
+ const ${id}_present = ${k} in input;
+ if (${id}.issues.length) {
+ payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
+ ...iss,
+ path: iss.path ? [${k}, ...iss.path] : [${k}]
+ })));
+ }
+ if (!${id}_present && !${id}.issues.length) {
+ payload.issues.push({
+ code: "invalid_type",
+ expected: "nonoptional",
+ input: undefined,
+ path: [${k}]
+ });
+ }
+
+ if (${id}_present) {
+ if (${id}.value === undefined) {
+ newResult[${k}] = undefined;
+ } else {
+ newResult[${k}] = ${id}.value;
+ }
+ }
+
+ `);
+ } else {
+ doc.write(`
+ if (${id}.issues.length) {
+ payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
+ ...iss,
+ path: iss.path ? [${k}, ...iss.path] : [${k}]
+ })));
+ }
+
+ if (${id}.value === undefined) {
+ if (${k} in input) {
+ newResult[${k}] = undefined;
+ }
+ } else {
+ newResult[${k}] = ${id}.value;
+ }
+
+ `);
+ }
+ }
+ doc.write(`payload.value = newResult;`);
+ doc.write(`return payload;`);
+ const fn = doc.compile();
+ return (payload, ctx) => fn(shape, payload, ctx);
+ }, "generateFastpass");
+ let fastpass;
+ const isObject2 = isObject;
+ const jit = !globalConfig.jitless;
+ const allowsEval2 = allowsEval;
+ const fastEnabled = jit && allowsEval2.value;
+ const catchall = def.catchall;
+ let value;
+ inst._zod.parse = (payload, ctx) => {
+ value ?? (value = _normalized.value);
+ const input = payload.value;
+ if (!isObject2(input)) {
+ payload.issues.push({
+ expected: "object",
+ code: "invalid_type",
+ input,
+ inst
+ });
+ return payload;
+ }
+ if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
+ if (!fastpass)
+ fastpass = generateFastpass(def.shape);
+ payload = fastpass(payload, ctx);
+ if (!catchall)
+ return payload;
+ return handleCatchall([], input, payload, ctx, value, inst);
+ }
+ return superParse(payload, ctx);
+ };
+});
+function handleUnionResults(results, final, inst, ctx) {
+ for (const result of results) {
+ if (result.issues.length === 0) {
+ final.value = result.value;
+ return final;
+ }
+ }
+ const nonaborted = results.filter((r) => !aborted(r));
+ if (nonaborted.length === 1) {
+ final.value = nonaborted[0].value;
+ return nonaborted[0];
+ }
+ final.issues.push({
+ code: "invalid_union",
+ input: final.value,
+ inst,
+ errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
+ });
+ return final;
+}
+__name(handleUnionResults, "handleUnionResults");
+var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {
+ $ZodType.init(inst, def);
+ defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0);
+ defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0);
+ defineLazy(inst._zod, "values", () => {
+ if (def.options.every((o) => o._zod.values)) {
+ return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));
+ }
+ return void 0;
+ });
+ defineLazy(inst._zod, "pattern", () => {
+ if (def.options.every((o) => o._zod.pattern)) {
+ const patterns = def.options.map((o) => o._zod.pattern);
+ return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
+ }
+ return void 0;
+ });
+ const first = def.options.length === 1 ? def.options[0]._zod.run : null;
+ inst._zod.parse = (payload, ctx) => {
+ if (first) {
+ return first(payload, ctx);
+ }
+ let async = false;
+ const results = [];
+ for (const option of def.options) {
+ const result = option._zod.run({
+ value: payload.value,
+ issues: []
+ }, ctx);
+ if (result instanceof Promise) {
+ results.push(result);
+ async = true;
+ } else {
+ if (result.issues.length === 0)
+ return result;
+ results.push(result);
+ }
+ }
+ if (!async)
+ return handleUnionResults(results, payload, inst, ctx);
+ return Promise.all(results).then((results2) => {
+ return handleUnionResults(results2, payload, inst, ctx);
+ });
+ };
+});
+function handleExclusiveUnionResults(results, final, inst, ctx) {
+ const successes = results.filter((r) => r.issues.length === 0);
+ if (successes.length === 1) {
+ final.value = successes[0].value;
+ return final;
+ }
+ if (successes.length === 0) {
+ final.issues.push({
+ code: "invalid_union",
+ input: final.value,
+ inst,
+ errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
+ });
+ } else {
+ final.issues.push({
+ code: "invalid_union",
+ input: final.value,
+ inst,
+ errors: [],
+ inclusive: false
+ });
+ }
+ return final;
+}
+__name(handleExclusiveUnionResults, "handleExclusiveUnionResults");
+var $ZodXor = /* @__PURE__ */ $constructor("$ZodXor", (inst, def) => {
+ $ZodUnion.init(inst, def);
+ def.inclusive = false;
+ const first = def.options.length === 1 ? def.options[0]._zod.run : null;
+ inst._zod.parse = (payload, ctx) => {
+ if (first) {
+ return first(payload, ctx);
+ }
+ let async = false;
+ const results = [];
+ for (const option of def.options) {
+ const result = option._zod.run({
+ value: payload.value,
+ issues: []
+ }, ctx);
+ if (result instanceof Promise) {
+ results.push(result);
+ async = true;
+ } else {
+ results.push(result);
+ }
+ }
+ if (!async)
+ return handleExclusiveUnionResults(results, payload, inst, ctx);
+ return Promise.all(results).then((results2) => {
+ return handleExclusiveUnionResults(results2, payload, inst, ctx);
+ });
+ };
+});
+var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => {
+ def.inclusive = false;
+ $ZodUnion.init(inst, def);
+ const _super = inst._zod.parse;
+ defineLazy(inst._zod, "propValues", () => {
+ const propValues = {};
+ for (const option of def.options) {
+ const pv = option._zod.propValues;
+ if (!pv || Object.keys(pv).length === 0)
+ throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);
+ for (const [k, v] of Object.entries(pv)) {
+ if (!propValues[k])
+ propValues[k] = /* @__PURE__ */ new Set();
+ for (const val of v) {
+ propValues[k].add(val);
+ }
+ }
+ }
+ return propValues;
+ });
+ const disc = cached(() => {
+ const opts = def.options;
+ const map2 = /* @__PURE__ */ new Map();
+ for (const o of opts) {
+ const values = o._zod.propValues?.[def.discriminator];
+ if (!values || values.size === 0)
+ throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`);
+ for (const v of values) {
+ if (map2.has(v)) {
+ throw new Error(`Duplicate discriminator value "${String(v)}"`);
+ }
+ map2.set(v, o);
+ }
+ }
+ return map2;
+ });
+ inst._zod.parse = (payload, ctx) => {
+ const input = payload.value;
+ if (!isObject(input)) {
+ payload.issues.push({
+ code: "invalid_type",
+ expected: "object",
+ input,
+ inst
+ });
+ return payload;
+ }
+ const opt = disc.value.get(input?.[def.discriminator]);
+ if (opt) {
+ return opt._zod.run(payload, ctx);
+ }
+ if (def.unionFallback || ctx.direction === "backward") {
+ return _super(payload, ctx);
+ }
+ payload.issues.push({
+ code: "invalid_union",
+ errors: [],
+ note: "No matching discriminator",
+ discriminator: def.discriminator,
+ options: Array.from(disc.value.keys()),
+ input,
+ path: [def.discriminator],
+ inst
+ });
+ return payload;
+ };
+});
+var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => {
+ $ZodType.init(inst, def);
+ inst._zod.parse = (payload, ctx) => {
+ const input = payload.value;
+ const left2 = def.left._zod.run({ value: input, issues: [] }, ctx);
+ const right2 = def.right._zod.run({ value: input, issues: [] }, ctx);
+ const async = left2 instanceof Promise || right2 instanceof Promise;
+ if (async) {
+ return Promise.all([left2, right2]).then(([left3, right3]) => {
+ return handleIntersectionResults(payload, left3, right3);
+ });
+ }
+ return handleIntersectionResults(payload, left2, right2);
+ };
+});
+function mergeValues(a, b) {
+ if (a === b) {
+ return { valid: true, data: a };
+ }
+ if (a instanceof Date && b instanceof Date && +a === +b) {
+ return { valid: true, data: a };
+ }
+ if (isPlainObject2(a) && isPlainObject2(b)) {
+ const bKeys = Object.keys(b);
+ const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
+ const newObj = { ...a, ...b };
+ for (const key of sharedKeys) {
+ const sharedValue = mergeValues(a[key], b[key]);
+ if (!sharedValue.valid) {
+ return {
+ valid: false,
+ mergeErrorPath: [key, ...sharedValue.mergeErrorPath]
+ };
+ }
+ newObj[key] = sharedValue.data;
+ }
+ return { valid: true, data: newObj };
+ }
+ if (Array.isArray(a) && Array.isArray(b)) {
+ if (a.length !== b.length) {
+ return { valid: false, mergeErrorPath: [] };
+ }
+ const newArray = [];
+ for (let index = 0; index < a.length; index++) {
+ const itemA = a[index];
+ const itemB = b[index];
+ const sharedValue = mergeValues(itemA, itemB);
+ if (!sharedValue.valid) {
+ return {
+ valid: false,
+ mergeErrorPath: [index, ...sharedValue.mergeErrorPath]
+ };
+ }
+ newArray.push(sharedValue.data);
+ }
+ return { valid: true, data: newArray };
+ }
+ return { valid: false, mergeErrorPath: [] };
+}
+__name(mergeValues, "mergeValues");
+function handleIntersectionResults(result, left2, right2) {
+ const unrecKeys = /* @__PURE__ */ new Map();
+ let unrecIssue;
+ for (const iss of left2.issues) {
+ if (iss.code === "unrecognized_keys") {
+ unrecIssue ?? (unrecIssue = iss);
+ for (const k of iss.keys) {
+ if (!unrecKeys.has(k))
+ unrecKeys.set(k, {});
+ unrecKeys.get(k).l = true;
+ }
+ } else {
+ result.issues.push(iss);
+ }
+ }
+ for (const iss of right2.issues) {
+ if (iss.code === "unrecognized_keys") {
+ for (const k of iss.keys) {
+ if (!unrecKeys.has(k))
+ unrecKeys.set(k, {});
+ unrecKeys.get(k).r = true;
+ }
+ } else {
+ result.issues.push(iss);
+ }
+ }
+ const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);
+ if (bothKeys.length && unrecIssue) {
+ result.issues.push({ ...unrecIssue, keys: bothKeys });
+ }
+ if (aborted(result))
+ return result;
+ const merged = mergeValues(left2.value, right2.value);
+ if (!merged.valid) {
+ throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);
+ }
+ result.value = merged.data;
+ return result;
+}
+__name(handleIntersectionResults, "handleIntersectionResults");
+var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => {
+ $ZodType.init(inst, def);
+ const items = def.items;
+ inst._zod.parse = (payload, ctx) => {
+ const input = payload.value;
+ if (!Array.isArray(input)) {
+ payload.issues.push({
+ input,
+ inst,
+ expected: "tuple",
+ code: "invalid_type"
+ });
+ return payload;
+ }
+ payload.value = [];
+ const proms = [];
+ const optinStart = getTupleOptStart(items, "optin");
+ const optoutStart = getTupleOptStart(items, "optout");
+ if (!def.rest) {
+ if (input.length < optinStart) {
+ payload.issues.push({
+ code: "too_small",
+ minimum: optinStart,
+ inclusive: true,
+ input,
+ inst,
+ origin: "array"
+ });
+ return payload;
+ }
+ if (input.length > items.length) {
+ payload.issues.push({
+ code: "too_big",
+ maximum: items.length,
+ inclusive: true,
+ input,
+ inst,
+ origin: "array"
+ });
+ }
+ }
+ const itemResults = new Array(items.length);
+ for (let i = 0; i < items.length; i++) {
+ const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx);
+ if (r instanceof Promise) {
+ proms.push(r.then((rr) => {
+ itemResults[i] = rr;
+ }));
+ } else {
+ itemResults[i] = r;
+ }
+ }
+ if (def.rest) {
+ let i = items.length - 1;
+ const rest = input.slice(items.length);
+ for (const el of rest) {
+ i++;
+ const result = def.rest._zod.run({ value: el, issues: [] }, ctx);
+ if (result instanceof Promise) {
+ proms.push(result.then((r) => handleTupleResult(r, payload, i)));
+ } else {
+ handleTupleResult(result, payload, i);
+ }
+ }
+ }
+ if (proms.length) {
+ return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));
+ }
+ return handleTupleResults(itemResults, payload, items, input, optoutStart);
+ };
+});
+function getTupleOptStart(items, key) {
+ for (let i = items.length - 1; i >= 0; i--) {
+ if (items[i]._zod[key] !== "optional")
+ return i + 1;
+ }
+ return 0;
+}
+__name(getTupleOptStart, "getTupleOptStart");
+function handleTupleResult(result, final, index) {
+ if (result.issues.length) {
+ final.issues.push(...prefixIssues(index, result.issues));
+ }
+ final.value[index] = result.value;
+}
+__name(handleTupleResult, "handleTupleResult");
+function handleTupleResults(itemResults, final, items, input, optoutStart) {
+ for (let i = 0; i < items.length; i++) {
+ const r = itemResults[i];
+ const isPresent = i < input.length;
+ if (r.issues.length) {
+ if (!isPresent && i >= optoutStart) {
+ final.value.length = i;
+ break;
+ }
+ final.issues.push(...prefixIssues(i, r.issues));
+ }
+ final.value[i] = r.value;
+ }
+ for (let i = final.value.length - 1; i >= input.length; i--) {
+ if (items[i]._zod.optout === "optional" && final.value[i] === void 0) {
+ final.value.length = i;
+ } else {
+ break;
+ }
+ }
+ return final;
+}
+__name(handleTupleResults, "handleTupleResults");
+var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
+ $ZodType.init(inst, def);
+ inst._zod.parse = (payload, ctx) => {
+ const input = payload.value;
+ if (!isPlainObject2(input)) {
+ payload.issues.push({
+ expected: "record",
+ code: "invalid_type",
+ input,
+ inst
+ });
+ return payload;
+ }
+ const proms = [];
+ const values = def.keyType._zod.values;
+ if (values) {
+ payload.value = {};
+ const recordKeys = /* @__PURE__ */ new Set();
+ for (const key of values) {
+ if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
+ recordKeys.add(typeof key === "number" ? key.toString() : key);
+ const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
+ if (keyResult instanceof Promise) {
+ throw new Error("Async schemas not supported in object keys currently");
+ }
+ if (keyResult.issues.length) {
+ payload.issues.push({
+ code: "invalid_key",
+ origin: "record",
+ issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
+ input: key,
+ path: [key],
+ inst
+ });
+ continue;
+ }
+ const outKey = keyResult.value;
+ const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
+ if (result instanceof Promise) {
+ proms.push(result.then((result2) => {
+ if (result2.issues.length) {
+ payload.issues.push(...prefixIssues(key, result2.issues));
+ }
+ payload.value[outKey] = result2.value;
+ }));
+ } else {
+ if (result.issues.length) {
+ payload.issues.push(...prefixIssues(key, result.issues));
+ }
+ payload.value[outKey] = result.value;
+ }
+ }
+ }
+ let unrecognized;
+ for (const key in input) {
+ if (!recordKeys.has(key)) {
+ unrecognized = unrecognized ?? [];
+ unrecognized.push(key);
+ }
+ }
+ if (unrecognized && unrecognized.length > 0) {
+ payload.issues.push({
+ code: "unrecognized_keys",
+ input,
+ inst,
+ keys: unrecognized
+ });
+ }
+ } else {
+ payload.value = {};
+ for (const key of Reflect.ownKeys(input)) {
+ if (key === "__proto__")
+ continue;
+ if (!Object.prototype.propertyIsEnumerable.call(input, key))
+ continue;
+ let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
+ 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;
+ if (checkNumericKey) {
+ const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);
+ if (retryResult instanceof Promise) {
+ throw new Error("Async schemas not supported in object keys currently");
+ }
+ if (retryResult.issues.length === 0) {
+ keyResult = retryResult;
+ }
+ }
+ if (keyResult.issues.length) {
+ if (def.mode === "loose") {
+ payload.value[key] = input[key];
+ } else {
+ payload.issues.push({
+ code: "invalid_key",
+ origin: "record",
+ issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
+ input: key,
+ path: [key],
+ inst
+ });
+ }
+ continue;
+ }
+ const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
+ if (result instanceof Promise) {
+ proms.push(result.then((result2) => {
+ if (result2.issues.length) {
+ payload.issues.push(...prefixIssues(key, result2.issues));
+ }
+ payload.value[keyResult.value] = result2.value;
+ }));
+ } else {
+ if (result.issues.length) {
+ payload.issues.push(...prefixIssues(key, result.issues));
+ }
+ payload.value[keyResult.value] = result.value;
+ }
+ }
+ }
+ if (proms.length) {
+ return Promise.all(proms).then(() => payload);
+ }
+ return payload;
+ };
+});
+var $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => {
+ $ZodType.init(inst, def);
+ inst._zod.parse = (payload, ctx) => {
+ const input = payload.value;
+ if (!(input instanceof Map)) {
+ payload.issues.push({
+ expected: "map",
+ code: "invalid_type",
+ input,
+ inst
+ });
+ return payload;
+ }
+ const proms = [];
+ payload.value = /* @__PURE__ */ new Map();
+ for (const [key, value] of input) {
+ const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
+ const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx);
+ if (keyResult instanceof Promise || valueResult instanceof Promise) {
+ proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => {
+ handleMapResult(keyResult2, valueResult2, payload, key, input, inst, ctx);
+ }));
+ } else {
+ handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);
+ }
+ }
+ if (proms.length)
+ return Promise.all(proms).then(() => payload);
+ return payload;
+ };
+});
+function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {
+ if (keyResult.issues.length) {
+ if (propertyKeyTypes.has(typeof key)) {
+ final.issues.push(...prefixIssues(key, keyResult.issues));
+ } else {
+ final.issues.push({
+ code: "invalid_key",
+ origin: "map",
+ input,
+ inst,
+ issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config()))
+ });
+ }
+ }
+ if (valueResult.issues.length) {
+ if (propertyKeyTypes.has(typeof key)) {
+ final.issues.push(...prefixIssues(key, valueResult.issues));
+ } else {
+ final.issues.push({
+ origin: "map",
+ code: "invalid_element",
+ input,
+ inst,
+ key,
+ issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config()))
+ });
+ }
+ }
+ final.value.set(keyResult.value, valueResult.value);
+}
+__name(handleMapResult, "handleMapResult");
+var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => {
+ $ZodType.init(inst, def);
+ inst._zod.parse = (payload, ctx) => {
+ const input = payload.value;
+ if (!(input instanceof Set)) {
+ payload.issues.push({
+ input,
+ inst,
+ expected: "set",
+ code: "invalid_type"
+ });
+ return payload;
+ }
+ const proms = [];
+ payload.value = /* @__PURE__ */ new Set();
+ for (const item of input) {
+ const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);
+ if (result instanceof Promise) {
+ proms.push(result.then((result2) => handleSetResult(result2, payload)));
+ } else
+ handleSetResult(result, payload);
+ }
+ if (proms.length)
+ return Promise.all(proms).then(() => payload);
+ return payload;
+ };
+});
+function handleSetResult(result, final) {
+ if (result.issues.length) {
+ final.issues.push(...result.issues);
+ }
+ final.value.add(result.value);
+}
+__name(handleSetResult, "handleSetResult");
+var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
+ $ZodType.init(inst, def);
+ const values = getEnumValues(def.entries);
+ const valuesSet = new Set(values);
+ inst._zod.values = valuesSet;
+ inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`);
+ inst._zod.parse = (payload, _ctx) => {
+ const input = payload.value;
+ if (valuesSet.has(input)) {
+ return payload;
+ }
+ payload.issues.push({
+ code: "invalid_value",
+ values,
+ input,
+ inst
+ });
+ return payload;
+ };
+});
+var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
+ $ZodType.init(inst, def);
+ if (def.values.length === 0) {
+ throw new Error("Cannot create literal schema with no valid values");
+ }
+ const values = new Set(def.values);
+ inst._zod.values = values;
+ inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`);
+ inst._zod.parse = (payload, _ctx) => {
+ const input = payload.value;
+ if (values.has(input)) {
+ return payload;
+ }
+ payload.issues.push({
+ code: "invalid_value",
+ values: def.values,
+ input,
+ inst
+ });
+ return payload;
+ };
+});
+var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => {
+ $ZodType.init(inst, def);
+ inst._zod.parse = (payload, _ctx) => {
+ const input = payload.value;
+ if (input instanceof File)
+ return payload;
+ payload.issues.push({
+ expected: "file",
+ code: "invalid_type",
+ input,
+ inst
+ });
+ return payload;
+ };
+});
+var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => {
+ $ZodType.init(inst, def);
+ inst._zod.optin = "optional";
+ inst._zod.parse = (payload, ctx) => {
+ if (ctx.direction === "backward") {
+ throw new $ZodEncodeError(inst.constructor.name);
+ }
+ const _out = def.transform(payload.value, payload);
+ if (ctx.async) {
+ const output = _out instanceof Promise ? _out : Promise.resolve(_out);
+ return output.then((output2) => {
+ payload.value = output2;
+ payload.fallback = true;
+ return payload;
+ });
+ }
+ if (_out instanceof Promise) {
+ throw new $ZodAsyncError();
+ }
+ payload.value = _out;
+ payload.fallback = true;
+ return payload;
+ };
+});
+function handleOptionalResult(result, input) {
+ if (input === void 0 && (result.issues.length || result.fallback)) {
+ return { issues: [], value: void 0 };
+ }
+ return result;
+}
+__name(handleOptionalResult, "handleOptionalResult");
+var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => {
+ $ZodType.init(inst, def);
+ inst._zod.optin = "optional";
+ inst._zod.optout = "optional";
+ defineLazy(inst._zod, "values", () => {
+ return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0;
+ });
+ defineLazy(inst._zod, "pattern", () => {
+ const pattern = def.innerType._zod.pattern;
+ return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0;
+ });
+ inst._zod.parse = (payload, ctx) => {
+ if (def.innerType._zod.optin === "optional") {
+ const input = payload.value;
+ const result = def.innerType._zod.run(payload, ctx);
+ if (result instanceof Promise)
+ return result.then((r) => handleOptionalResult(r, input));
+ return handleOptionalResult(result, input);
+ }
+ if (payload.value === void 0) {
+ return payload;
+ }
+ return def.innerType._zod.run(payload, ctx);
+ };
+});
+var $ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => {
+ $ZodOptional.init(inst, def);
+ defineLazy(inst._zod, "values", () => def.innerType._zod.values);
+ defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern);
+ inst._zod.parse = (payload, ctx) => {
+ return def.innerType._zod.run(payload, ctx);
+ };
+});
+var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => {
+ $ZodType.init(inst, def);
+ defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
+ defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
+ defineLazy(inst._zod, "pattern", () => {
+ const pattern = def.innerType._zod.pattern;
+ return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0;
+ });
+ defineLazy(inst._zod, "values", () => {
+ return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0;
+ });
+ inst._zod.parse = (payload, ctx) => {
+ if (payload.value === null)
+ return payload;
+ return def.innerType._zod.run(payload, ctx);
+ };
+});
+var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => {
+ $ZodType.init(inst, def);
+ inst._zod.optin = "optional";
+ defineLazy(inst._zod, "values", () => def.innerType._zod.values);
+ inst._zod.parse = (payload, ctx) => {
+ if (ctx.direction === "backward") {
+ return def.innerType._zod.run(payload, ctx);
+ }
+ if (payload.value === void 0) {
+ payload.value = def.defaultValue;
+ return payload;
+ }
+ const result = def.innerType._zod.run(payload, ctx);
+ if (result instanceof Promise) {
+ return result.then((result2) => handleDefaultResult(result2, def));
+ }
+ return handleDefaultResult(result, def);
+ };
+});
+function handleDefaultResult(payload, def) {
+ if (payload.value === void 0) {
+ payload.value = def.defaultValue;
+ }
+ return payload;
+}
+__name(handleDefaultResult, "handleDefaultResult");
+var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => {
+ $ZodType.init(inst, def);
+ inst._zod.optin = "optional";
+ defineLazy(inst._zod, "values", () => def.innerType._zod.values);
+ inst._zod.parse = (payload, ctx) => {
+ if (ctx.direction === "backward") {
+ return def.innerType._zod.run(payload, ctx);
+ }
+ if (payload.value === void 0) {
+ payload.value = def.defaultValue;
+ }
+ return def.innerType._zod.run(payload, ctx);
+ };
+});
+var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => {
+ $ZodType.init(inst, def);
+ defineLazy(inst._zod, "values", () => {
+ const v = def.innerType._zod.values;
+ return v ? new Set([...v].filter((x) => x !== void 0)) : void 0;
+ });
+ inst._zod.parse = (payload, ctx) => {
+ const result = def.innerType._zod.run(payload, ctx);
+ if (result instanceof Promise) {
+ return result.then((result2) => handleNonOptionalResult(result2, inst));
+ }
+ return handleNonOptionalResult(result, inst);
+ };
+});
+function handleNonOptionalResult(payload, inst) {
+ if (!payload.issues.length && payload.value === void 0) {
+ payload.issues.push({
+ code: "invalid_type",
+ expected: "nonoptional",
+ input: payload.value,
+ inst
+ });
+ }
+ return payload;
+}
+__name(handleNonOptionalResult, "handleNonOptionalResult");
+var $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => {
+ $ZodType.init(inst, def);
+ inst._zod.parse = (payload, ctx) => {
+ if (ctx.direction === "backward") {
+ throw new $ZodEncodeError("ZodSuccess");
+ }
+ const result = def.innerType._zod.run(payload, ctx);
+ if (result instanceof Promise) {
+ return result.then((result2) => {
+ payload.value = result2.issues.length === 0;
+ return payload;
+ });
+ }
+ payload.value = result.issues.length === 0;
+ return payload;
+ };
+});
+var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => {
+ $ZodType.init(inst, def);
+ inst._zod.optin = "optional";
+ defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
+ defineLazy(inst._zod, "values", () => def.innerType._zod.values);
+ inst._zod.parse = (payload, ctx) => {
+ if (ctx.direction === "backward") {
+ return def.innerType._zod.run(payload, ctx);
+ }
+ const result = def.innerType._zod.run(payload, ctx);
+ if (result instanceof Promise) {
+ return result.then((result2) => {
+ payload.value = result2.value;
+ if (result2.issues.length) {
+ payload.value = def.catchValue({
+ ...payload,
+ error: {
+ issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config()))
+ },
+ input: payload.value
+ });
+ payload.issues = [];
+ payload.fallback = true;
+ }
+ return payload;
+ });
+ }
+ payload.value = result.value;
+ if (result.issues.length) {
+ payload.value = def.catchValue({
+ ...payload,
+ error: {
+ issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config()))
+ },
+ input: payload.value
+ });
+ payload.issues = [];
+ payload.fallback = true;
+ }
+ return payload;
+ };
+});
+var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => {
+ $ZodType.init(inst, def);
+ inst._zod.parse = (payload, _ctx) => {
+ if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) {
+ payload.issues.push({
+ input: payload.value,
+ inst,
+ expected: "nan",
+ code: "invalid_type"
+ });
+ return payload;
+ }
+ return payload;
+ };
+});
+var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => {
+ $ZodType.init(inst, def);
+ defineLazy(inst._zod, "values", () => def.in._zod.values);
+ defineLazy(inst._zod, "optin", () => def.in._zod.optin);
+ defineLazy(inst._zod, "optout", () => def.out._zod.optout);
+ defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
+ inst._zod.parse = (payload, ctx) => {
+ if (ctx.direction === "backward") {
+ const right2 = def.out._zod.run(payload, ctx);
+ if (right2 instanceof Promise) {
+ return right2.then((right3) => handlePipeResult(right3, def.in, ctx));
+ }
+ return handlePipeResult(right2, def.in, ctx);
+ }
+ const left2 = def.in._zod.run(payload, ctx);
+ if (left2 instanceof Promise) {
+ return left2.then((left3) => handlePipeResult(left3, def.out, ctx));
+ }
+ return handlePipeResult(left2, def.out, ctx);
+ };
+});
+function handlePipeResult(left2, next, ctx) {
+ if (left2.issues.length) {
+ left2.aborted = true;
+ return left2;
+ }
+ return next._zod.run({ value: left2.value, issues: left2.issues, fallback: left2.fallback }, ctx);
+}
+__name(handlePipeResult, "handlePipeResult");
+var $ZodCodec = /* @__PURE__ */ $constructor("$ZodCodec", (inst, def) => {
+ $ZodType.init(inst, def);
+ defineLazy(inst._zod, "values", () => def.in._zod.values);
+ defineLazy(inst._zod, "optin", () => def.in._zod.optin);
+ defineLazy(inst._zod, "optout", () => def.out._zod.optout);
+ defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
+ inst._zod.parse = (payload, ctx) => {
+ const direction = ctx.direction || "forward";
+ if (direction === "forward") {
+ const left2 = def.in._zod.run(payload, ctx);
+ if (left2 instanceof Promise) {
+ return left2.then((left3) => handleCodecAResult(left3, def, ctx));
+ }
+ return handleCodecAResult(left2, def, ctx);
+ } else {
+ const right2 = def.out._zod.run(payload, ctx);
+ if (right2 instanceof Promise) {
+ return right2.then((right3) => handleCodecAResult(right3, def, ctx));
+ }
+ return handleCodecAResult(right2, def, ctx);
+ }
+ };
+});
+function handleCodecAResult(result, def, ctx) {
+ if (result.issues.length) {
+ result.aborted = true;
+ return result;
+ }
+ const direction = ctx.direction || "forward";
+ if (direction === "forward") {
+ const transformed = def.transform(result.value, result);
+ if (transformed instanceof Promise) {
+ return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));
+ }
+ return handleCodecTxResult(result, transformed, def.out, ctx);
+ } else {
+ const transformed = def.reverseTransform(result.value, result);
+ if (transformed instanceof Promise) {
+ return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));
+ }
+ return handleCodecTxResult(result, transformed, def.in, ctx);
+ }
+}
+__name(handleCodecAResult, "handleCodecAResult");
+function handleCodecTxResult(left2, value, nextSchema, ctx) {
+ if (left2.issues.length) {
+ left2.aborted = true;
+ return left2;
+ }
+ return nextSchema._zod.run({ value, issues: left2.issues }, ctx);
+}
+__name(handleCodecTxResult, "handleCodecTxResult");
+var $ZodPreprocess = /* @__PURE__ */ $constructor("$ZodPreprocess", (inst, def) => {
+ $ZodPipe.init(inst, def);
+});
+var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => {
+ $ZodType.init(inst, def);
+ defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
+ defineLazy(inst._zod, "values", () => def.innerType._zod.values);
+ defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin);
+ defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout);
+ inst._zod.parse = (payload, ctx) => {
+ if (ctx.direction === "backward") {
+ return def.innerType._zod.run(payload, ctx);
+ }
+ const result = def.innerType._zod.run(payload, ctx);
+ if (result instanceof Promise) {
+ return result.then(handleReadonlyResult);
+ }
+ return handleReadonlyResult(result);
+ };
+});
+function handleReadonlyResult(payload) {
+ payload.value = Object.freeze(payload.value);
+ return payload;
+}
+__name(handleReadonlyResult, "handleReadonlyResult");
+var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => {
+ $ZodType.init(inst, def);
+ const regexParts = [];
+ for (const part of def.parts) {
+ if (typeof part === "object" && part !== null) {
+ if (!part._zod.pattern) {
+ throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);
+ }
+ const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;
+ if (!source)
+ throw new Error(`Invalid template literal part: ${part._zod.traits}`);
+ const start = source.startsWith("^") ? 1 : 0;
+ const end = source.endsWith("$") ? source.length - 1 : source.length;
+ regexParts.push(source.slice(start, end));
+ } else if (part === null || primitiveTypes.has(typeof part)) {
+ regexParts.push(escapeRegex(`${part}`));
+ } else {
+ throw new Error(`Invalid template literal part: ${part}`);
+ }
+ }
+ inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`);
+ inst._zod.parse = (payload, _ctx) => {
+ if (typeof payload.value !== "string") {
+ payload.issues.push({
+ input: payload.value,
+ inst,
+ expected: "string",
+ code: "invalid_type"
+ });
+ return payload;
+ }
+ inst._zod.pattern.lastIndex = 0;
+ if (!inst._zod.pattern.test(payload.value)) {
+ payload.issues.push({
+ input: payload.value,
+ inst,
+ code: "invalid_format",
+ format: def.format ?? "template_literal",
+ pattern: inst._zod.pattern.source
+ });
+ return payload;
+ }
+ return payload;
+ };
+});
+var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => {
+ $ZodType.init(inst, def);
+ inst._def = def;
+ inst._zod.def = def;
+ inst.implement = (func) => {
+ if (typeof func !== "function") {
+ throw new Error("implement() must be called with a function");
+ }
+ return function(...args) {
+ const parsedArgs = inst._def.input ? parse2(inst._def.input, args) : args;
+ const result = Reflect.apply(func, this, parsedArgs);
+ if (inst._def.output) {
+ return parse2(inst._def.output, result);
+ }
+ return result;
+ };
+ };
+ inst.implementAsync = (func) => {
+ if (typeof func !== "function") {
+ throw new Error("implementAsync() must be called with a function");
+ }
+ return async function(...args) {
+ const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;
+ const result = await Reflect.apply(func, this, parsedArgs);
+ if (inst._def.output) {
+ return await parseAsync(inst._def.output, result);
+ }
+ return result;
+ };
+ };
+ inst._zod.parse = (payload, _ctx) => {
+ if (typeof payload.value !== "function") {
+ payload.issues.push({
+ code: "invalid_type",
+ expected: "function",
+ input: payload.value,
+ inst
+ });
+ return payload;
+ }
+ const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise";
+ if (hasPromiseOutput) {
+ payload.value = inst.implementAsync(payload.value);
+ } else {
+ payload.value = inst.implement(payload.value);
+ }
+ return payload;
+ };
+ inst.input = (...args) => {
+ const F = inst.constructor;
+ if (Array.isArray(args[0])) {
+ return new F({
+ type: "function",
+ input: new $ZodTuple({
+ type: "tuple",
+ items: args[0],
+ rest: args[1]
+ }),
+ output: inst._def.output
+ });
+ }
+ return new F({
+ type: "function",
+ input: args[0],
+ output: inst._def.output
+ });
+ };
+ inst.output = (output) => {
+ const F = inst.constructor;
+ return new F({
+ type: "function",
+ input: inst._def.input,
+ output
+ });
+ };
+ return inst;
+});
+var $ZodPromise = /* @__PURE__ */ $constructor("$ZodPromise", (inst, def) => {
+ $ZodType.init(inst, def);
+ inst._zod.parse = (payload, ctx) => {
+ return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));
+ };
+});
+var $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => {
+ $ZodType.init(inst, def);
+ defineLazy(inst._zod, "innerType", () => {
+ const d = def;
+ if (!d._cachedInner)
+ d._cachedInner = def.getter();
+ return d._cachedInner;
+ });
+ defineLazy(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern);
+ defineLazy(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues);
+ defineLazy(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? void 0);
+ defineLazy(inst._zod, "optout", () => inst._zod.innerType?._zod?.optout ?? void 0);
+ inst._zod.parse = (payload, ctx) => {
+ const inner = inst._zod.innerType;
+ return inner._zod.run(payload, ctx);
+ };
+});
+var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => {
+ $ZodCheck.init(inst, def);
+ $ZodType.init(inst, def);
+ inst._zod.parse = (payload, _) => {
+ return payload;
+ };
+ inst._zod.check = (payload) => {
+ const input = payload.value;
+ const r = def.fn(input);
+ if (r instanceof Promise) {
+ return r.then((r2) => handleRefineResult(r2, payload, input, inst));
+ }
+ handleRefineResult(r, payload, input, inst);
+ return;
+ };
+});
+function handleRefineResult(result, payload, input, inst) {
+ if (!result) {
+ const _iss = {
+ code: "custom",
+ input,
+ inst,
+ // incorporates params.error into issue reporting
+ path: [...inst._zod.def.path ?? []],
+ // incorporates params.error into issue reporting
+ continue: !inst._zod.def.abort
+ // params: inst._zod.def.params,
+ };
+ if (inst._zod.def.params)
+ _iss.params = inst._zod.def.params;
+ payload.issues.push(issue(_iss));
+ }
+}
+__name(handleRefineResult, "handleRefineResult");
+
+// node_modules/zod/v4/locales/index.js
+var locales_exports = {};
+__export(locales_exports, {
+ ar: () => ar_default,
+ az: () => az_default,
+ be: () => be_default,
+ bg: () => bg_default,
+ ca: () => ca_default,
+ cs: () => cs_default,
+ da: () => da_default,
+ de: () => de_default,
+ el: () => el_default,
+ en: () => en_default,
+ eo: () => eo_default,
+ es: () => es_default,
+ fa: () => fa_default,
+ fi: () => fi_default,
+ fr: () => fr_default,
+ frCA: () => fr_CA_default,
+ he: () => he_default,
+ hr: () => hr_default,
+ hu: () => hu_default,
+ hy: () => hy_default,
+ id: () => id_default,
+ is: () => is_default,
+ it: () => it_default,
+ ja: () => ja_default,
+ ka: () => ka_default,
+ kh: () => kh_default,
+ km: () => km_default,
+ ko: () => ko_default,
+ lt: () => lt_default,
+ mk: () => mk_default,
+ ms: () => ms_default,
+ nl: () => nl_default,
+ no: () => no_default,
+ ota: () => ota_default,
+ pl: () => pl_default,
+ ps: () => ps_default,
+ pt: () => pt_default,
+ ro: () => ro_default,
+ ru: () => ru_default,
+ sl: () => sl_default,
+ sv: () => sv_default,
+ ta: () => ta_default,
+ th: () => th_default,
+ tr: () => tr_default,
+ ua: () => ua_default,
+ uk: () => uk_default,
+ ur: () => ur_default,
+ uz: () => uz_default,
+ vi: () => vi_default,
+ yo: () => yo_default,
+ zhCN: () => zh_CN_default,
+ zhTW: () => zh_TW_default
+});
+init_esbuild_shims();
+
+// node_modules/zod/v4/locales/ar.js
+init_esbuild_shims();
+var error = /* @__PURE__ */ __name(() => {
+ 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" },
+ array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" },
+ set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "\u0645\u062F\u062E\u0644",
+ email: "\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A",
+ url: "\u0631\u0627\u0628\u0637",
+ emoji: "\u0625\u064A\u0645\u0648\u062C\u064A",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",
+ date: "\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO",
+ time: "\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",
+ duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO",
+ ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4",
+ ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6",
+ cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4",
+ cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6",
+ base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded",
+ base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded",
+ json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON",
+ e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164",
+ jwt: "JWT",
+ template_literal: "\u0645\u062F\u062E\u0644"
+ };
+ const TypeDictionary = {
+ nan: "NaN"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 instanceof ${issue2.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`;
+ }
+ return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${stringifyPrimitive(issue2.values[0])}`;
+ return `\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return ` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"}`;
+ return `\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
+ }
+ return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with")
+ return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${issue2.prefix}"`;
+ if (_issue.format === "ends_with")
+ return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${_issue.pattern}`;
+ return `${FormatDictionary[_issue.format] ?? issue2.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`;
+ }
+ case "not_multiple_of":
+ return `\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${issue2.divisor}`;
+ case "unrecognized_keys":
+ return `\u0645\u0639\u0631\u0641${issue2.keys.length > 1 ? "\u0627\u062A" : ""} \u063A\u0631\u064A\u0628${issue2.keys.length > 1 ? "\u0629" : ""}: ${joinValues(issue2.keys, "\u060C ")}`;
+ case "invalid_key":
+ return `\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`;
+ case "invalid_union":
+ return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";
+ case "invalid_element":
+ return `\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`;
+ default:
+ return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";
+ }
+ };
+}, "error");
+function ar_default() {
+ return {
+ localeError: error()
+ };
+}
+__name(ar_default, "default");
+
+// node_modules/zod/v4/locales/az.js
+init_esbuild_shims();
+var error2 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "simvol", verb: "olmal\u0131d\u0131r" },
+ file: { unit: "bayt", verb: "olmal\u0131d\u0131r" },
+ array: { unit: "element", verb: "olmal\u0131d\u0131r" },
+ set: { unit: "element", verb: "olmal\u0131d\u0131r" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "input",
+ email: "email address",
+ url: "URL",
+ emoji: "emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "ISO datetime",
+ date: "ISO date",
+ time: "ISO time",
+ duration: "ISO duration",
+ ipv4: "IPv4 address",
+ ipv6: "IPv6 address",
+ cidrv4: "IPv4 range",
+ cidrv6: "IPv6 range",
+ base64: "base64-encoded string",
+ base64url: "base64url-encoded string",
+ json_string: "JSON string",
+ e164: "E.164 number",
+ jwt: "JWT",
+ template_literal: "input"
+ };
+ const TypeDictionary = {
+ nan: "NaN"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n instanceof ${issue2.expected}, daxil olan ${received}`;
+ }
+ return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${expected}, daxil olan ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${stringifyPrimitive(issue2.values[0])}`;
+ return `Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`;
+ return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
+ return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with")
+ return `Yanl\u0131\u015F m\u0259tn: "${_issue.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`;
+ if (_issue.format === "ends_with")
+ return `Yanl\u0131\u015F m\u0259tn: "${_issue.suffix}" il\u0259 bitm\u0259lidir`;
+ if (_issue.format === "includes")
+ return `Yanl\u0131\u015F m\u0259tn: "${_issue.includes}" daxil olmal\u0131d\u0131r`;
+ if (_issue.format === "regex")
+ return `Yanl\u0131\u015F m\u0259tn: ${_issue.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`;
+ return `Yanl\u0131\u015F ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `Yanl\u0131\u015F \u0259d\u0259d: ${issue2.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;
+ case "unrecognized_keys":
+ return `Tan\u0131nmayan a\xE7ar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;
+ case "invalid_union":
+ return "Yanl\u0131\u015F d\u0259y\u0259r";
+ case "invalid_element":
+ return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;
+ default:
+ return `Yanl\u0131\u015F d\u0259y\u0259r`;
+ }
+ };
+}, "error");
+function az_default() {
+ return {
+ localeError: error2()
+ };
+}
+__name(az_default, "default");
+
+// node_modules/zod/v4/locales/be.js
+init_esbuild_shims();
+function getBelarusianPlural(count, one, few, many) {
+ const absCount = Math.abs(count);
+ const lastDigit = absCount % 10;
+ const lastTwoDigits = absCount % 100;
+ if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
+ return many;
+ }
+ if (lastDigit === 1) {
+ return one;
+ }
+ if (lastDigit >= 2 && lastDigit <= 4) {
+ return few;
+ }
+ return many;
+}
+__name(getBelarusianPlural, "getBelarusianPlural");
+var error3 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: {
+ unit: {
+ one: "\u0441\u0456\u043C\u0432\u0430\u043B",
+ few: "\u0441\u0456\u043C\u0432\u0430\u043B\u044B",
+ many: "\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E"
+ },
+ verb: "\u043C\u0435\u0446\u044C"
+ },
+ array: {
+ unit: {
+ one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442",
+ few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",
+ many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"
+ },
+ verb: "\u043C\u0435\u0446\u044C"
+ },
+ set: {
+ unit: {
+ one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442",
+ few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",
+ many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"
+ },
+ verb: "\u043C\u0435\u0446\u044C"
+ },
+ file: {
+ unit: {
+ one: "\u0431\u0430\u0439\u0442",
+ few: "\u0431\u0430\u0439\u0442\u044B",
+ many: "\u0431\u0430\u0439\u0442\u0430\u045E"
+ },
+ verb: "\u043C\u0435\u0446\u044C"
+ }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "\u0443\u0432\u043E\u0434",
+ email: "email \u0430\u0434\u0440\u0430\u0441",
+ url: "URL",
+ emoji: "\u044D\u043C\u043E\u0434\u0437\u0456",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441",
+ date: "ISO \u0434\u0430\u0442\u0430",
+ time: "ISO \u0447\u0430\u0441",
+ duration: "ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C",
+ ipv4: "IPv4 \u0430\u0434\u0440\u0430\u0441",
+ ipv6: "IPv6 \u0430\u0434\u0440\u0430\u0441",
+ cidrv4: "IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",
+ cidrv6: "IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",
+ base64: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64",
+ base64url: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url",
+ json_string: "JSON \u0440\u0430\u0434\u043E\u043A",
+ e164: "\u043D\u0443\u043C\u0430\u0440 E.164",
+ jwt: "JWT",
+ template_literal: "\u0443\u0432\u043E\u0434"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "\u043B\u0456\u043A",
+ array: "\u043C\u0430\u0441\u0456\u045E"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F instanceof ${issue2.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`;
+ }
+ return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`;
+ return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ const maxValue = Number(issue2.maximum);
+ const unit = getBelarusianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
+ return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.maximum.toString()} ${unit}`;
+ }
+ return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ const minValue = Number(issue2.minimum);
+ const unit = getBelarusianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
+ return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.minimum.toString()} ${unit}`;
+ }
+ return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with")
+ return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${_issue.prefix}"`;
+ if (_issue.format === "ends_with")
+ return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`;
+ return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`;
+ case "unrecognized_keys":
+ return `\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${issue2.keys.length > 1 ? "\u043A\u043B\u044E\u0447\u044B" : "\u043A\u043B\u044E\u0447"}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`;
+ case "invalid_union":
+ return "\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434";
+ case "invalid_element":
+ return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${issue2.origin}`;
+ default:
+ return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434`;
+ }
+ };
+}, "error");
+function be_default() {
+ return {
+ localeError: error3()
+ };
+}
+__name(be_default, "default");
+
+// node_modules/zod/v4/locales/bg.js
+init_esbuild_shims();
+var error4 = /* @__PURE__ */ __name(() => {
+ 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" },
+ array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" },
+ set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "\u0432\u0445\u043E\u0434",
+ email: "\u0438\u043C\u0435\u0439\u043B \u0430\u0434\u0440\u0435\u0441",
+ url: "URL",
+ emoji: "\u0435\u043C\u043E\u0434\u0436\u0438",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "ISO \u0432\u0440\u0435\u043C\u0435",
+ date: "ISO \u0434\u0430\u0442\u0430",
+ time: "ISO \u0432\u0440\u0435\u043C\u0435",
+ duration: "ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442",
+ ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441",
+ ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441",
+ cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",
+ cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",
+ base64: "base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",
+ base64url: "base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",
+ json_string: "JSON \u043D\u0438\u0437",
+ e164: "E.164 \u043D\u043E\u043C\u0435\u0440",
+ jwt: "JWT",
+ template_literal: "\u0432\u0445\u043E\u0434"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "\u0447\u0438\u0441\u043B\u043E",
+ array: "\u043C\u0430\u0441\u0438\u0432"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`;
+ }
+ return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${stringifyPrimitive(issue2.values[0])}`;
+ return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u043E\u043F\u0446\u0438\u044F: \u043E\u0447\u0430\u043A\u0432\u0430\u043D\u043E \u0435\u0434\u043D\u043E \u043E\u0442 ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin ?? "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430"}`;
+ return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin ?? "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
+ }
+ return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with") {
+ return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u0432\u0430 \u0441 "${_issue.prefix}"`;
+ }
+ if (_issue.format === "ends_with")
+ return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u0432\u044A\u0440\u0448\u0432\u0430 \u0441 "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0432\u043A\u043B\u044E\u0447\u0432\u0430 "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0441\u044A\u0432\u043F\u0430\u0434\u0430 \u0441 ${_issue.pattern}`;
+ let invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D";
+ if (_issue.format === "emoji")
+ invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";
+ if (_issue.format === "datetime")
+ invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";
+ if (_issue.format === "date")
+ invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430";
+ if (_issue.format === "time")
+ invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";
+ if (_issue.format === "duration")
+ invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430";
+ return `${invalid_adj} ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E \u0447\u0438\u0441\u043B\u043E: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0431\u044A\u0434\u0435 \u043A\u0440\u0430\u0442\u043D\u043E \u043D\u0430 ${issue2.divisor}`;
+ case "unrecognized_keys":
+ return `\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${issue2.keys.length > 1 ? "\u0438" : ""} \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u043E\u0432\u0435" : ""}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`;
+ case "invalid_union":
+ return "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434";
+ case "invalid_element":
+ return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442 \u0432 ${issue2.origin}`;
+ default:
+ return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434`;
+ }
+ };
+}, "error");
+function bg_default() {
+ return {
+ localeError: error4()
+ };
+}
+__name(bg_default, "default");
+
+// node_modules/zod/v4/locales/ca.js
+init_esbuild_shims();
+var error5 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "car\xE0cters", verb: "contenir" },
+ file: { unit: "bytes", verb: "contenir" },
+ array: { unit: "elements", verb: "contenir" },
+ set: { unit: "elements", verb: "contenir" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "entrada",
+ email: "adre\xE7a electr\xF2nica",
+ url: "URL",
+ emoji: "emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "data i hora ISO",
+ date: "data ISO",
+ time: "hora ISO",
+ duration: "durada ISO",
+ ipv4: "adre\xE7a IPv4",
+ ipv6: "adre\xE7a IPv6",
+ cidrv4: "rang IPv4",
+ cidrv6: "rang IPv6",
+ base64: "cadena codificada en base64",
+ base64url: "cadena codificada en base64url",
+ json_string: "cadena JSON",
+ e164: "n\xFAmero E.164",
+ jwt: "JWT",
+ template_literal: "entrada"
+ };
+ const TypeDictionary = {
+ nan: "NaN"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `Tipus inv\xE0lid: s'esperava instanceof ${issue2.expected}, s'ha rebut ${received}`;
+ }
+ return `Tipus inv\xE0lid: s'esperava ${expected}, s'ha rebut ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `Valor inv\xE0lid: s'esperava ${stringifyPrimitive(issue2.values[0])}`;
+ return `Opci\xF3 inv\xE0lida: s'esperava una de ${joinValues(issue2.values, " o ")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "com a m\xE0xim" : "menys de";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} contingu\xE9s ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`;
+ return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} fos ${adj} ${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? "com a m\xEDnim" : "m\xE9s de";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `Massa petit: s'esperava que ${issue2.origin} contingu\xE9s ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
+ }
+ return `Massa petit: s'esperava que ${issue2.origin} fos ${adj} ${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with") {
+ return `Format inv\xE0lid: ha de comen\xE7ar amb "${_issue.prefix}"`;
+ }
+ if (_issue.format === "ends_with")
+ return `Format inv\xE0lid: ha d'acabar amb "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `Format inv\xE0lid: ha d'incloure "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${_issue.pattern}`;
+ return `Format inv\xE0lid per a ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${issue2.divisor}`;
+ case "unrecognized_keys":
+ return `Clau${issue2.keys.length > 1 ? "s" : ""} no reconeguda${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `Clau inv\xE0lida a ${issue2.origin}`;
+ case "invalid_union":
+ return "Entrada inv\xE0lida";
+ // Could also be "Tipus d'unió invàlid" but "Entrada invàlida" is more general
+ case "invalid_element":
+ return `Element inv\xE0lid a ${issue2.origin}`;
+ default:
+ return `Entrada inv\xE0lida`;
+ }
+ };
+}, "error");
+function ca_default() {
+ return {
+ localeError: error5()
+ };
+}
+__name(ca_default, "default");
+
+// node_modules/zod/v4/locales/cs.js
+init_esbuild_shims();
+var error6 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "znak\u016F", verb: "m\xEDt" },
+ file: { unit: "bajt\u016F", verb: "m\xEDt" },
+ array: { unit: "prvk\u016F", verb: "m\xEDt" },
+ set: { unit: "prvk\u016F", verb: "m\xEDt" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "regul\xE1rn\xED v\xFDraz",
+ email: "e-mailov\xE1 adresa",
+ url: "URL",
+ emoji: "emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "datum a \u010Das ve form\xE1tu ISO",
+ date: "datum ve form\xE1tu ISO",
+ time: "\u010Das ve form\xE1tu ISO",
+ duration: "doba trv\xE1n\xED ISO",
+ ipv4: "IPv4 adresa",
+ ipv6: "IPv6 adresa",
+ cidrv4: "rozsah IPv4",
+ cidrv6: "rozsah IPv6",
+ base64: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64",
+ base64url: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url",
+ json_string: "\u0159et\u011Bzec ve form\xE1tu JSON",
+ e164: "\u010D\xEDslo E.164",
+ jwt: "JWT",
+ template_literal: "vstup"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "\u010D\xEDslo",
+ string: "\u0159et\u011Bzec",
+ function: "funkce",
+ array: "pole"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no instanceof ${issue2.expected}, obdr\u017Eeno ${received}`;
+ }
+ return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${expected}, obdr\u017Eeno ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${stringifyPrimitive(issue2.values[0])}`;
+ return `Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "prvk\u016F"}`;
+ }
+ return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "prvk\u016F"}`;
+ }
+ return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with")
+ return `Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${_issue.prefix}"`;
+ if (_issue.format === "ends_with")
+ return `Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${_issue.pattern}`;
+ return `Neplatn\xFD form\xE1t ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${issue2.divisor}`;
+ case "unrecognized_keys":
+ return `Nezn\xE1m\xE9 kl\xED\u010De: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `Neplatn\xFD kl\xED\u010D v ${issue2.origin}`;
+ case "invalid_union":
+ return "Neplatn\xFD vstup";
+ case "invalid_element":
+ return `Neplatn\xE1 hodnota v ${issue2.origin}`;
+ default:
+ return `Neplatn\xFD vstup`;
+ }
+ };
+}, "error");
+function cs_default() {
+ return {
+ localeError: error6()
+ };
+}
+__name(cs_default, "default");
+
+// node_modules/zod/v4/locales/da.js
+init_esbuild_shims();
+var error7 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "tegn", verb: "havde" },
+ file: { unit: "bytes", verb: "havde" },
+ array: { unit: "elementer", verb: "indeholdt" },
+ set: { unit: "elementer", verb: "indeholdt" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "input",
+ email: "e-mailadresse",
+ url: "URL",
+ emoji: "emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "ISO dato- og klokkesl\xE6t",
+ date: "ISO-dato",
+ time: "ISO-klokkesl\xE6t",
+ duration: "ISO-varighed",
+ ipv4: "IPv4-omr\xE5de",
+ ipv6: "IPv6-omr\xE5de",
+ cidrv4: "IPv4-spektrum",
+ cidrv6: "IPv6-spektrum",
+ base64: "base64-kodet streng",
+ base64url: "base64url-kodet streng",
+ json_string: "JSON-streng",
+ e164: "E.164-nummer",
+ jwt: "JWT",
+ template_literal: "input"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ string: "streng",
+ number: "tal",
+ boolean: "boolean",
+ array: "liste",
+ object: "objekt",
+ set: "s\xE6t",
+ file: "fil"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `Ugyldigt input: forventede instanceof ${issue2.expected}, fik ${received}`;
+ }
+ return `Ugyldigt input: forventede ${expected}, fik ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `Ugyldig v\xE6rdi: forventede ${stringifyPrimitive(issue2.values[0])}`;
+ return `Ugyldigt valg: forventede en af f\xF8lgende ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
+ if (sizing)
+ return `For stor: forventede ${origin ?? "value"} ${sizing.verb} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elementer"}`;
+ return `For stor: forventede ${origin ?? "value"} havde ${adj} ${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
+ if (sizing) {
+ return `For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
+ }
+ return `For lille: forventede ${origin} havde ${adj} ${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with")
+ return `Ugyldig streng: skal starte med "${_issue.prefix}"`;
+ if (_issue.format === "ends_with")
+ return `Ugyldig streng: skal ende med "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `Ugyldig streng: skal indeholde "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `Ugyldig streng: skal matche m\xF8nsteret ${_issue.pattern}`;
+ return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `Ugyldigt tal: skal v\xE6re deleligt med ${issue2.divisor}`;
+ case "unrecognized_keys":
+ return `${issue2.keys.length > 1 ? "Ukendte n\xF8gler" : "Ukendt n\xF8gle"}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `Ugyldig n\xF8gle i ${issue2.origin}`;
+ case "invalid_union":
+ return "Ugyldigt input: matcher ingen af de tilladte typer";
+ case "invalid_element":
+ return `Ugyldig v\xE6rdi i ${issue2.origin}`;
+ default:
+ return `Ugyldigt input`;
+ }
+ };
+}, "error");
+function da_default() {
+ return {
+ localeError: error7()
+ };
+}
+__name(da_default, "default");
+
+// node_modules/zod/v4/locales/de.js
+init_esbuild_shims();
+var error8 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "Zeichen", verb: "zu haben" },
+ file: { unit: "Bytes", verb: "zu haben" },
+ array: { unit: "Elemente", verb: "zu haben" },
+ set: { unit: "Elemente", verb: "zu haben" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "Eingabe",
+ email: "E-Mail-Adresse",
+ url: "URL",
+ emoji: "Emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "ISO-Datum und -Uhrzeit",
+ date: "ISO-Datum",
+ time: "ISO-Uhrzeit",
+ duration: "ISO-Dauer",
+ ipv4: "IPv4-Adresse",
+ ipv6: "IPv6-Adresse",
+ cidrv4: "IPv4-Bereich",
+ cidrv6: "IPv6-Bereich",
+ base64: "Base64-codierter String",
+ base64url: "Base64-URL-codierter String",
+ json_string: "JSON-String",
+ e164: "E.164-Nummer",
+ jwt: "JWT",
+ template_literal: "Eingabe"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "Zahl",
+ array: "Array"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `Ung\xFCltige Eingabe: erwartet instanceof ${issue2.expected}, erhalten ${received}`;
+ }
+ return `Ung\xFCltige Eingabe: erwartet ${expected}, erhalten ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `Ung\xFCltige Eingabe: erwartet ${stringifyPrimitive(issue2.values[0])}`;
+ return `Ung\xFCltige Option: erwartet eine von ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `Zu gro\xDF: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "Elemente"} hat`;
+ return `Zu gro\xDF: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ist`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} hat`;
+ }
+ return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ist`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with")
+ return `Ung\xFCltiger String: muss mit "${_issue.prefix}" beginnen`;
+ if (_issue.format === "ends_with")
+ return `Ung\xFCltiger String: muss mit "${_issue.suffix}" enden`;
+ if (_issue.format === "includes")
+ return `Ung\xFCltiger String: muss "${_issue.includes}" enthalten`;
+ if (_issue.format === "regex")
+ return `Ung\xFCltiger String: muss dem Muster ${_issue.pattern} entsprechen`;
+ return `Ung\xFCltig: ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `Ung\xFCltige Zahl: muss ein Vielfaches von ${issue2.divisor} sein`;
+ case "unrecognized_keys":
+ return `${issue2.keys.length > 1 ? "Unbekannte Schl\xFCssel" : "Unbekannter Schl\xFCssel"}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `Ung\xFCltiger Schl\xFCssel in ${issue2.origin}`;
+ case "invalid_union":
+ return "Ung\xFCltige Eingabe";
+ case "invalid_element":
+ return `Ung\xFCltiger Wert in ${issue2.origin}`;
+ default:
+ return `Ung\xFCltige Eingabe`;
+ }
+ };
+}, "error");
+function de_default() {
+ return {
+ localeError: error8()
+ };
+}
+__name(de_default, "default");
+
+// node_modules/zod/v4/locales/el.js
+init_esbuild_shims();
+var error9 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "\u03C7\u03B1\u03C1\u03B1\u03BA\u03C4\u03AE\u03C1\u03B5\u03C2", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" },
+ file: { unit: "bytes", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" },
+ array: { unit: "\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" },
+ set: { unit: "\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" },
+ map: { unit: "\u03BA\u03B1\u03C4\u03B1\u03C7\u03C9\u03C1\u03AE\u03C3\u03B5\u03B9\u03C2", verb: "\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2",
+ email: "\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 email",
+ url: "URL",
+ emoji: "emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1 \u03BA\u03B1\u03B9 \u03CE\u03C1\u03B1",
+ date: "ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1",
+ time: "ISO \u03CE\u03C1\u03B1",
+ duration: "ISO \u03B4\u03B9\u03AC\u03C1\u03BA\u03B5\u03B9\u03B1",
+ ipv4: "\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv4",
+ ipv6: "\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv6",
+ mac: "\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 MAC",
+ cidrv4: "\u03B5\u03CD\u03C1\u03BF\u03C2 IPv4",
+ cidrv6: "\u03B5\u03CD\u03C1\u03BF\u03C2 IPv6",
+ base64: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64",
+ base64url: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64url",
+ json_string: "\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC JSON",
+ e164: "\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 E.164",
+ jwt: "JWT",
+ template_literal: "\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2"
+ };
+ const TypeDictionary = {
+ nan: "NaN"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (typeof issue2.expected === "string" && /^[A-Z]/.test(issue2.expected)) {
+ return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD instanceof ${issue2.expected}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${received}`;
+ }
+ return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${expected}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${stringifyPrimitive(issue2.values[0])}`;
+ return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03C0\u03B9\u03BB\u03BF\u03B3\u03AE: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD \u03AD\u03BD\u03B1 \u03B1\u03C0\u03CC ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin ?? "\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1"}`;
+ return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin ?? "\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
+ }
+ return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue2.origin} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with") {
+ return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03BE\u03B5\u03BA\u03B9\u03BD\u03AC \u03BC\u03B5 "${_issue.prefix}"`;
+ }
+ if (_issue.format === "ends_with")
+ return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B5\u03BB\u03B5\u03B9\u03CE\u03BD\u03B5\u03B9 \u03BC\u03B5 "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C0\u03B5\u03C1\u03B9\u03AD\u03C7\u03B5\u03B9 "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B1\u03B9\u03C1\u03B9\u03AC\u03B6\u03B5\u03B9 \u03BC\u03B5 \u03C4\u03BF \u03BC\u03BF\u03C4\u03AF\u03B2\u03BF ${_issue.pattern}`;
+ return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF: ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF\u03C2 \u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 \u03C0\u03BF\u03BB\u03BB\u03B1\u03C0\u03BB\u03AC\u03C3\u03B9\u03BF \u03C4\u03BF\u03C5 ${issue2.divisor}`;
+ case "unrecognized_keys":
+ return `\u0386\u03B3\u03BD\u03C9\u03C3\u03C4${issue2.keys.length > 1 ? "\u03B1" : "\u03BF"} \u03BA\u03BB\u03B5\u03B9\u03B4${issue2.keys.length > 1 ? "\u03B9\u03AC" : "\u03AF"}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF \u03BA\u03BB\u03B5\u03B9\u03B4\u03AF \u03C3\u03C4\u03BF ${issue2.origin}`;
+ case "invalid_union":
+ return "\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2";
+ case "invalid_element":
+ return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C4\u03B9\u03BC\u03AE \u03C3\u03C4\u03BF ${issue2.origin}`;
+ default:
+ return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2`;
+ }
+ };
+}, "error");
+function el_default() {
+ return {
+ localeError: error9()
+ };
+}
+__name(el_default, "default");
+
+// node_modules/zod/v4/locales/en.js
+init_esbuild_shims();
+var error10 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "characters", verb: "to have" },
+ file: { unit: "bytes", verb: "to have" },
+ array: { unit: "items", verb: "to have" },
+ set: { unit: "items", verb: "to have" },
+ map: { unit: "entries", verb: "to have" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "input",
+ email: "email address",
+ url: "URL",
+ emoji: "emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "ISO datetime",
+ date: "ISO date",
+ time: "ISO time",
+ duration: "ISO duration",
+ ipv4: "IPv4 address",
+ ipv6: "IPv6 address",
+ mac: "MAC address",
+ cidrv4: "IPv4 range",
+ cidrv6: "IPv6 range",
+ base64: "base64-encoded string",
+ base64url: "base64url-encoded string",
+ json_string: "JSON string",
+ e164: "E.164 number",
+ jwt: "JWT",
+ template_literal: "input"
+ };
+ const TypeDictionary = {
+ // Compatibility: "nan" -> "NaN" for display
+ nan: "NaN"
+ // All other type names omitted - they fall back to raw values via ?? operator
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ return `Invalid input: expected ${expected}, received ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`;
+ return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`;
+ return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
+ }
+ return `Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with") {
+ return `Invalid string: must start with "${_issue.prefix}"`;
+ }
+ if (_issue.format === "ends_with")
+ return `Invalid string: must end with "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `Invalid string: must include "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `Invalid string: must match pattern ${_issue.pattern}`;
+ return `Invalid ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `Invalid number: must be a multiple of ${issue2.divisor}`;
+ case "unrecognized_keys":
+ return `Unrecognized key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `Invalid key in ${issue2.origin}`;
+ case "invalid_union":
+ if (issue2.options && Array.isArray(issue2.options) && issue2.options.length > 0) {
+ const opts = issue2.options.map((o) => `'${o}'`).join(" | ");
+ return `Invalid discriminator value. Expected ${opts}`;
+ }
+ return "Invalid input";
+ case "invalid_element":
+ return `Invalid value in ${issue2.origin}`;
+ default:
+ return `Invalid input`;
+ }
+ };
+}, "error");
+function en_default() {
+ return {
+ localeError: error10()
+ };
+}
+__name(en_default, "default");
+
+// node_modules/zod/v4/locales/eo.js
+init_esbuild_shims();
+var error11 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "karaktrojn", verb: "havi" },
+ file: { unit: "bajtojn", verb: "havi" },
+ array: { unit: "elementojn", verb: "havi" },
+ set: { unit: "elementojn", verb: "havi" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "enigo",
+ email: "retadreso",
+ url: "URL",
+ emoji: "emo\u011Dio",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "ISO-datotempo",
+ date: "ISO-dato",
+ time: "ISO-tempo",
+ duration: "ISO-da\u016Dro",
+ ipv4: "IPv4-adreso",
+ ipv6: "IPv6-adreso",
+ cidrv4: "IPv4-rango",
+ cidrv6: "IPv6-rango",
+ base64: "64-ume kodita karaktraro",
+ base64url: "URL-64-ume kodita karaktraro",
+ json_string: "JSON-karaktraro",
+ e164: "E.164-nombro",
+ jwt: "JWT",
+ template_literal: "enigo"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "nombro",
+ array: "tabelo",
+ null: "senvalora"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `Nevalida enigo: atendi\u011Dis instanceof ${issue2.expected}, ricevi\u011Dis ${received}`;
+ }
+ return `Nevalida enigo: atendi\u011Dis ${expected}, ricevi\u011Dis ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `Nevalida enigo: atendi\u011Dis ${stringifyPrimitive(issue2.values[0])}`;
+ return `Nevalida opcio: atendi\u011Dis unu el ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementojn"}`;
+ return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} havu ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
+ }
+ return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} estu ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with")
+ return `Nevalida karaktraro: devas komenci\u011Di per "${_issue.prefix}"`;
+ if (_issue.format === "ends_with")
+ return `Nevalida karaktraro: devas fini\u011Di per "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`;
+ return `Nevalida ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `Nevalida nombro: devas esti oblo de ${issue2.divisor}`;
+ case "unrecognized_keys":
+ return `Nekonata${issue2.keys.length > 1 ? "j" : ""} \u015Dlosilo${issue2.keys.length > 1 ? "j" : ""}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `Nevalida \u015Dlosilo en ${issue2.origin}`;
+ case "invalid_union":
+ return "Nevalida enigo";
+ case "invalid_element":
+ return `Nevalida valoro en ${issue2.origin}`;
+ default:
+ return `Nevalida enigo`;
+ }
+ };
+}, "error");
+function eo_default() {
+ return {
+ localeError: error11()
+ };
+}
+__name(eo_default, "default");
+
+// node_modules/zod/v4/locales/es.js
+init_esbuild_shims();
+var error12 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "caracteres", verb: "tener" },
+ file: { unit: "bytes", verb: "tener" },
+ array: { unit: "elementos", verb: "tener" },
+ set: { unit: "elementos", verb: "tener" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "entrada",
+ email: "direcci\xF3n de correo electr\xF3nico",
+ url: "URL",
+ emoji: "emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "fecha y hora ISO",
+ date: "fecha ISO",
+ time: "hora ISO",
+ duration: "duraci\xF3n ISO",
+ ipv4: "direcci\xF3n IPv4",
+ ipv6: "direcci\xF3n IPv6",
+ cidrv4: "rango IPv4",
+ cidrv6: "rango IPv6",
+ base64: "cadena codificada en base64",
+ base64url: "URL codificada en base64",
+ json_string: "cadena JSON",
+ e164: "n\xFAmero E.164",
+ jwt: "JWT",
+ template_literal: "entrada"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ string: "texto",
+ number: "n\xFAmero",
+ boolean: "booleano",
+ array: "arreglo",
+ object: "objeto",
+ set: "conjunto",
+ file: "archivo",
+ date: "fecha",
+ bigint: "n\xFAmero grande",
+ symbol: "s\xEDmbolo",
+ undefined: "indefinido",
+ null: "nulo",
+ function: "funci\xF3n",
+ map: "mapa",
+ record: "registro",
+ tuple: "tupla",
+ enum: "enumeraci\xF3n",
+ union: "uni\xF3n",
+ literal: "literal",
+ promise: "promesa",
+ void: "vac\xEDo",
+ never: "nunca",
+ unknown: "desconocido",
+ any: "cualquiera"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `Entrada inv\xE1lida: se esperaba instanceof ${issue2.expected}, recibido ${received}`;
+ }
+ return `Entrada inv\xE1lida: se esperaba ${expected}, recibido ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `Entrada inv\xE1lida: se esperaba ${stringifyPrimitive(issue2.values[0])}`;
+ return `Opci\xF3n inv\xE1lida: se esperaba una de ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
+ if (sizing)
+ return `Demasiado grande: se esperaba que ${origin ?? "valor"} tuviera ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`;
+ return `Demasiado grande: se esperaba que ${origin ?? "valor"} fuera ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
+ if (sizing) {
+ return `Demasiado peque\xF1o: se esperaba que ${origin} tuviera ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
+ }
+ return `Demasiado peque\xF1o: se esperaba que ${origin} fuera ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with")
+ return `Cadena inv\xE1lida: debe comenzar con "${_issue.prefix}"`;
+ if (_issue.format === "ends_with")
+ return `Cadena inv\xE1lida: debe terminar en "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `Cadena inv\xE1lida: debe incluir "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${_issue.pattern}`;
+ return `Inv\xE1lido ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${issue2.divisor}`;
+ case "unrecognized_keys":
+ return `Llave${issue2.keys.length > 1 ? "s" : ""} desconocida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `Llave inv\xE1lida en ${TypeDictionary[issue2.origin] ?? issue2.origin}`;
+ case "invalid_union":
+ return "Entrada inv\xE1lida";
+ case "invalid_element":
+ return `Valor inv\xE1lido en ${TypeDictionary[issue2.origin] ?? issue2.origin}`;
+ default:
+ return `Entrada inv\xE1lida`;
+ }
+ };
+}, "error");
+function es_default() {
+ return {
+ localeError: error12()
+ };
+}
+__name(es_default, "default");
+
+// node_modules/zod/v4/locales/fa.js
+init_esbuild_shims();
+var error13 = /* @__PURE__ */ __name(() => {
+ 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" },
+ array: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" },
+ set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "\u0648\u0631\u0648\u062F\u06CC",
+ email: "\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644",
+ url: "URL",
+ emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",
+ date: "\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648",
+ time: "\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",
+ duration: "\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",
+ ipv4: "IPv4 \u0622\u062F\u0631\u0633",
+ ipv6: "IPv6 \u0622\u062F\u0631\u0633",
+ cidrv4: "IPv4 \u062F\u0627\u0645\u0646\u0647",
+ cidrv6: "IPv6 \u062F\u0627\u0645\u0646\u0647",
+ base64: "base64-encoded \u0631\u0634\u062A\u0647",
+ base64url: "base64url-encoded \u0631\u0634\u062A\u0647",
+ json_string: "JSON \u0631\u0634\u062A\u0647",
+ e164: "E.164 \u0639\u062F\u062F",
+ jwt: "JWT",
+ template_literal: "\u0648\u0631\u0648\u062F\u06CC"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "\u0639\u062F\u062F",
+ array: "\u0622\u0631\u0627\u06CC\u0647"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${issue2.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`;
+ }
+ return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1) {
+ return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${stringifyPrimitive(issue2.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`;
+ }
+ return `\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${joinValues(issue2.values, "|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`;
+ }
+ return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0628\u0627\u0634\u062F`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0628\u0627\u0634\u062F`;
+ }
+ return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0628\u0627\u0634\u062F`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with") {
+ return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`;
+ }
+ if (_issue.format === "ends_with") {
+ return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`;
+ }
+ if (_issue.format === "includes") {
+ return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${_issue.includes}" \u0628\u0627\u0634\u062F`;
+ }
+ if (_issue.format === "regex") {
+ return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${_issue.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`;
+ }
+ return `${FormatDictionary[_issue.format] ?? issue2.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`;
+ }
+ case "not_multiple_of":
+ return `\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${issue2.divisor} \u0628\u0627\u0634\u062F`;
+ case "unrecognized_keys":
+ return `\u06A9\u0644\u06CC\u062F${issue2.keys.length > 1 ? "\u0647\u0627\u06CC" : ""} \u0646\u0627\u0634\u0646\u0627\u0633: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${issue2.origin}`;
+ case "invalid_union":
+ return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`;
+ case "invalid_element":
+ return `\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${issue2.origin}`;
+ default:
+ return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`;
+ }
+ };
+}, "error");
+function fa_default() {
+ return {
+ localeError: error13()
+ };
+}
+__name(fa_default, "default");
+
+// node_modules/zod/v4/locales/fi.js
+init_esbuild_shims();
+var error14 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "merkki\xE4", subject: "merkkijonon" },
+ file: { unit: "tavua", subject: "tiedoston" },
+ array: { unit: "alkiota", subject: "listan" },
+ set: { unit: "alkiota", subject: "joukon" },
+ number: { unit: "", subject: "luvun" },
+ bigint: { unit: "", subject: "suuren kokonaisluvun" },
+ int: { unit: "", subject: "kokonaisluvun" },
+ date: { unit: "", subject: "p\xE4iv\xE4m\xE4\xE4r\xE4n" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "s\xE4\xE4nn\xF6llinen lauseke",
+ email: "s\xE4hk\xF6postiosoite",
+ url: "URL-osoite",
+ emoji: "emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "ISO-aikaleima",
+ date: "ISO-p\xE4iv\xE4m\xE4\xE4r\xE4",
+ time: "ISO-aika",
+ duration: "ISO-kesto",
+ ipv4: "IPv4-osoite",
+ ipv6: "IPv6-osoite",
+ cidrv4: "IPv4-alue",
+ cidrv6: "IPv6-alue",
+ base64: "base64-koodattu merkkijono",
+ base64url: "base64url-koodattu merkkijono",
+ json_string: "JSON-merkkijono",
+ e164: "E.164-luku",
+ jwt: "JWT",
+ template_literal: "templaattimerkkijono"
+ };
+ const TypeDictionary = {
+ nan: "NaN"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `Virheellinen tyyppi: odotettiin instanceof ${issue2.expected}, oli ${received}`;
+ }
+ return `Virheellinen tyyppi: odotettiin ${expected}, oli ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `Virheellinen sy\xF6te: t\xE4ytyy olla ${stringifyPrimitive(issue2.values[0])}`;
+ return `Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `Liian suuri: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.maximum.toString()} ${sizing.unit}`.trim();
+ }
+ return `Liian suuri: arvon t\xE4ytyy olla ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `Liian pieni: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.minimum.toString()} ${sizing.unit}`.trim();
+ }
+ return `Liian pieni: arvon t\xE4ytyy olla ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with")
+ return `Virheellinen sy\xF6te: t\xE4ytyy alkaa "${_issue.prefix}"`;
+ if (_issue.format === "ends_with")
+ return `Virheellinen sy\xF6te: t\xE4ytyy loppua "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${_issue.includes}"`;
+ if (_issue.format === "regex") {
+ return `Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${_issue.pattern}`;
+ }
+ return `Virheellinen ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `Virheellinen luku: t\xE4ytyy olla luvun ${issue2.divisor} monikerta`;
+ case "unrecognized_keys":
+ return `${issue2.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return "Virheellinen avain tietueessa";
+ case "invalid_union":
+ return "Virheellinen unioni";
+ case "invalid_element":
+ return "Virheellinen arvo joukossa";
+ default:
+ return `Virheellinen sy\xF6te`;
+ }
+ };
+}, "error");
+function fi_default() {
+ return {
+ localeError: error14()
+ };
+}
+__name(fi_default, "default");
+
+// node_modules/zod/v4/locales/fr.js
+init_esbuild_shims();
+var error15 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "caract\xE8res", verb: "avoir" },
+ file: { unit: "octets", verb: "avoir" },
+ array: { unit: "\xE9l\xE9ments", verb: "avoir" },
+ set: { unit: "\xE9l\xE9ments", verb: "avoir" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "entr\xE9e",
+ email: "adresse e-mail",
+ url: "URL",
+ emoji: "emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "date et heure ISO",
+ date: "date ISO",
+ time: "heure ISO",
+ duration: "dur\xE9e ISO",
+ ipv4: "adresse IPv4",
+ ipv6: "adresse IPv6",
+ cidrv4: "plage IPv4",
+ cidrv6: "plage IPv6",
+ base64: "cha\xEEne encod\xE9e en base64",
+ base64url: "cha\xEEne encod\xE9e en base64url",
+ json_string: "cha\xEEne JSON",
+ e164: "num\xE9ro E.164",
+ jwt: "JWT",
+ template_literal: "entr\xE9e"
+ };
+ const TypeDictionary = {
+ string: "cha\xEEne",
+ number: "nombre",
+ int: "entier",
+ boolean: "bool\xE9en",
+ bigint: "grand entier",
+ symbol: "symbole",
+ undefined: "ind\xE9fini",
+ null: "null",
+ never: "jamais",
+ void: "vide",
+ date: "date",
+ array: "tableau",
+ object: "objet",
+ tuple: "tuple",
+ record: "enregistrement",
+ map: "carte",
+ set: "ensemble",
+ file: "fichier",
+ nonoptional: "non-optionnel",
+ nan: "NaN",
+ function: "fonction"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `Entr\xE9e invalide : instanceof ${issue2.expected} attendu, ${received} re\xE7u`;
+ }
+ return `Entr\xE9e invalide : ${expected} attendu, ${received} re\xE7u`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `Entr\xE9e invalide : ${stringifyPrimitive(issue2.values[0])} attendu`;
+ return `Option invalide : une valeur parmi ${joinValues(issue2.values, "|")} attendue`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `Trop grand : ${TypeDictionary[issue2.origin] ?? "valeur"} doit ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\xE9l\xE9ment(s)"}`;
+ return `Trop grand : ${TypeDictionary[issue2.origin] ?? "valeur"} doit \xEAtre ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `Trop petit : ${TypeDictionary[issue2.origin] ?? "valeur"} doit ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
+ return `Trop petit : ${TypeDictionary[issue2.origin] ?? "valeur"} doit \xEAtre ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with")
+ return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`;
+ if (_issue.format === "ends_with")
+ return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`;
+ return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`;
+ }
+ case "not_multiple_of":
+ return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`;
+ case "unrecognized_keys":
+ return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `Cl\xE9 invalide dans ${issue2.origin}`;
+ case "invalid_union":
+ return "Entr\xE9e invalide";
+ case "invalid_element":
+ return `Valeur invalide dans ${issue2.origin}`;
+ default:
+ return `Entr\xE9e invalide`;
+ }
+ };
+}, "error");
+function fr_default() {
+ return {
+ localeError: error15()
+ };
+}
+__name(fr_default, "default");
+
+// node_modules/zod/v4/locales/fr-CA.js
+init_esbuild_shims();
+var error16 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "caract\xE8res", verb: "avoir" },
+ file: { unit: "octets", verb: "avoir" },
+ array: { unit: "\xE9l\xE9ments", verb: "avoir" },
+ set: { unit: "\xE9l\xE9ments", verb: "avoir" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "entr\xE9e",
+ email: "adresse courriel",
+ url: "URL",
+ emoji: "emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "date-heure ISO",
+ date: "date ISO",
+ time: "heure ISO",
+ duration: "dur\xE9e ISO",
+ ipv4: "adresse IPv4",
+ ipv6: "adresse IPv6",
+ cidrv4: "plage IPv4",
+ cidrv6: "plage IPv6",
+ base64: "cha\xEEne encod\xE9e en base64",
+ base64url: "cha\xEEne encod\xE9e en base64url",
+ json_string: "cha\xEEne JSON",
+ e164: "num\xE9ro E.164",
+ jwt: "JWT",
+ template_literal: "entr\xE9e"
+ };
+ const TypeDictionary = {
+ nan: "NaN"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `Entr\xE9e invalide : attendu instanceof ${issue2.expected}, re\xE7u ${received}`;
+ }
+ return `Entr\xE9e invalide : attendu ${expected}, re\xE7u ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `Entr\xE9e invalide : attendu ${stringifyPrimitive(issue2.values[0])}`;
+ return `Option invalide : attendu l'une des valeurs suivantes ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "\u2264" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} ait ${adj}${issue2.maximum.toString()} ${sizing.unit}`;
+ return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} soit ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? "\u2265" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `Trop petit : attendu que ${issue2.origin} ait ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
+ }
+ return `Trop petit : attendu que ${issue2.origin} soit ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with") {
+ return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`;
+ }
+ if (_issue.format === "ends_with")
+ return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `Cha\xEEne invalide : doit correspondre au motif ${_issue.pattern}`;
+ return `${FormatDictionary[_issue.format] ?? issue2.format} invalide`;
+ }
+ case "not_multiple_of":
+ return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`;
+ case "unrecognized_keys":
+ return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `Cl\xE9 invalide dans ${issue2.origin}`;
+ case "invalid_union":
+ return "Entr\xE9e invalide";
+ case "invalid_element":
+ return `Valeur invalide dans ${issue2.origin}`;
+ default:
+ return `Entr\xE9e invalide`;
+ }
+ };
+}, "error");
+function fr_CA_default() {
+ return {
+ localeError: error16()
+ };
+}
+__name(fr_CA_default, "default");
+
+// node_modules/zod/v4/locales/he.js
+init_esbuild_shims();
+var error17 = /* @__PURE__ */ __name(() => {
+ const TypeNames = {
+ string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA", gender: "f" },
+ number: { label: "\u05DE\u05E1\u05E4\u05E8", gender: "m" },
+ boolean: { label: "\u05E2\u05E8\u05DA \u05D1\u05D5\u05DC\u05D9\u05D0\u05E0\u05D9", gender: "m" },
+ bigint: { label: "BigInt", gender: "m" },
+ date: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA", gender: "m" },
+ array: { label: "\u05DE\u05E2\u05E8\u05DA", gender: "m" },
+ object: { label: "\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8", gender: "m" },
+ null: { label: "\u05E2\u05E8\u05DA \u05E8\u05D9\u05E7 (null)", gender: "m" },
+ undefined: { label: "\u05E2\u05E8\u05DA \u05DC\u05D0 \u05DE\u05D5\u05D2\u05D3\u05E8 (undefined)", gender: "m" },
+ symbol: { label: "\u05E1\u05D9\u05DE\u05D1\u05D5\u05DC (Symbol)", gender: "m" },
+ function: { label: "\u05E4\u05D5\u05E0\u05E7\u05E6\u05D9\u05D4", gender: "f" },
+ map: { label: "\u05DE\u05E4\u05D4 (Map)", gender: "f" },
+ set: { label: "\u05E7\u05D1\u05D5\u05E6\u05D4 (Set)", gender: "f" },
+ file: { label: "\u05E7\u05D5\u05D1\u05E5", gender: "m" },
+ promise: { label: "Promise", gender: "m" },
+ NaN: { label: "NaN", gender: "m" },
+ unknown: { label: "\u05E2\u05E8\u05DA \u05DC\u05D0 \u05D9\u05D3\u05D5\u05E2", gender: "m" },
+ value: { label: "\u05E2\u05E8\u05DA", gender: "m" }
+ };
+ const Sizable = {
+ string: { unit: "\u05EA\u05D5\u05D5\u05D9\u05DD", shortLabel: "\u05E7\u05E6\u05E8", longLabel: "\u05D0\u05E8\u05D5\u05DA" },
+ file: { unit: "\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" },
+ array: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" },
+ set: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" },
+ number: { unit: "", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }
+ // no unit
+ };
+ const typeEntry = /* @__PURE__ */ __name((t) => t ? TypeNames[t] : void 0, "typeEntry");
+ const typeLabel = /* @__PURE__ */ __name((t) => {
+ const e = typeEntry(t);
+ if (e)
+ return e.label;
+ return t ?? TypeNames.unknown.label;
+ }, "typeLabel");
+ const withDefinite = /* @__PURE__ */ __name((t) => `\u05D4${typeLabel(t)}`, "withDefinite");
+ const verbFor = /* @__PURE__ */ __name((t) => {
+ const e = typeEntry(t);
+ const gender = e?.gender ?? "m";
+ return gender === "f" ? "\u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05D9\u05D5\u05EA" : "\u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA";
+ }, "verbFor");
+ const getSizing = /* @__PURE__ */ __name((origin) => {
+ if (!origin)
+ return null;
+ return Sizable[origin] ?? null;
+ }, "getSizing");
+ const FormatDictionary = {
+ regex: { label: "\u05E7\u05DC\u05D8", gender: "m" },
+ email: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC", gender: "f" },
+ url: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA", gender: "f" },
+ emoji: { label: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9", gender: "m" },
+ uuid: { label: "UUID", gender: "m" },
+ nanoid: { label: "nanoid", gender: "m" },
+ guid: { label: "GUID", gender: "m" },
+ cuid: { label: "cuid", gender: "m" },
+ cuid2: { label: "cuid2", gender: "m" },
+ ulid: { label: "ULID", gender: "m" },
+ xid: { label: "XID", gender: "m" },
+ ksuid: { label: "KSUID", gender: "m" },
+ datetime: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO", gender: "m" },
+ date: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA ISO", gender: "m" },
+ time: { label: "\u05D6\u05DE\u05DF ISO", gender: "m" },
+ duration: { label: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO", gender: "m" },
+ ipv4: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4", gender: "f" },
+ ipv6: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6", gender: "f" },
+ cidrv4: { label: "\u05D8\u05D5\u05D5\u05D7 IPv4", gender: "m" },
+ cidrv6: { label: "\u05D8\u05D5\u05D5\u05D7 IPv6", gender: "m" },
+ base64: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64", gender: "f" },
+ base64url: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA", gender: "f" },
+ json_string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON", gender: "f" },
+ e164: { label: "\u05DE\u05E1\u05E4\u05E8 E.164", gender: "m" },
+ jwt: { label: "JWT", gender: "m" },
+ ends_with: { label: "\u05E7\u05DC\u05D8", gender: "m" },
+ includes: { label: "\u05E7\u05DC\u05D8", gender: "m" },
+ lowercase: { label: "\u05E7\u05DC\u05D8", gender: "m" },
+ starts_with: { label: "\u05E7\u05DC\u05D8", gender: "m" },
+ uppercase: { label: "\u05E7\u05DC\u05D8", gender: "m" }
+ };
+ const TypeDictionary = {
+ nan: "NaN"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expectedKey = issue2.expected;
+ const expected = TypeDictionary[expectedKey ?? ""] ?? typeLabel(expectedKey);
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? TypeNames[receivedType]?.label ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${issue2.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`;
+ }
+ return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`;
+ }
+ case "invalid_value": {
+ if (issue2.values.length === 1) {
+ return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05E2\u05E8\u05DA \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA ${stringifyPrimitive(issue2.values[0])}`;
+ }
+ const stringified = issue2.values.map((v) => stringifyPrimitive(v));
+ if (issue2.values.length === 2) {
+ return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${stringified[0]} \u05D0\u05D5 ${stringified[1]}`;
+ }
+ const lastValue = stringified[stringified.length - 1];
+ const restValues = stringified.slice(0, -1).join(", ");
+ return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${restValues} \u05D0\u05D5 ${lastValue}`;
+ }
+ case "too_big": {
+ const sizing = getSizing(issue2.origin);
+ const subject = withDefinite(issue2.origin ?? "value");
+ if (issue2.origin === "string") {
+ return `${sizing?.longLabel ?? "\u05D0\u05E8\u05D5\u05DA"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue2.maximum.toString()} ${sizing?.unit ?? ""} ${issue2.inclusive ? "\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA" : "\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8"}`.trim();
+ }
+ if (issue2.origin === "number") {
+ const comparison = issue2.inclusive ? `\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue2.maximum}` : `\u05E7\u05D8\u05DF \u05DE-${issue2.maximum}`;
+ return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`;
+ }
+ if (issue2.origin === "array" || issue2.origin === "set") {
+ const verb = issue2.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA";
+ const comparison = issue2.inclusive ? `${issue2.maximum} ${sizing?.unit ?? ""} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA` : `\u05E4\u05D7\u05D5\u05EA \u05DE-${issue2.maximum} ${sizing?.unit ?? ""}`;
+ return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim();
+ }
+ const adj = issue2.inclusive ? "<=" : "<";
+ const be = verbFor(issue2.origin ?? "value");
+ if (sizing?.unit) {
+ return `${sizing.longLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.maximum.toString()} ${sizing.unit}`;
+ }
+ return `${sizing?.longLabel ?? "\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const sizing = getSizing(issue2.origin);
+ const subject = withDefinite(issue2.origin ?? "value");
+ if (issue2.origin === "string") {
+ return `${sizing?.shortLabel ?? "\u05E7\u05E6\u05E8"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue2.minimum.toString()} ${sizing?.unit ?? ""} ${issue2.inclusive ? "\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8" : "\u05DC\u05E4\u05D7\u05D5\u05EA"}`.trim();
+ }
+ if (issue2.origin === "number") {
+ const comparison = issue2.inclusive ? `\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue2.minimum}` : `\u05D2\u05D3\u05D5\u05DC \u05DE-${issue2.minimum}`;
+ return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`;
+ }
+ if (issue2.origin === "array" || issue2.origin === "set") {
+ const verb = issue2.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA";
+ if (issue2.minimum === 1 && issue2.inclusive) {
+ const singularPhrase = issue2.origin === "set" ? "\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3" : "\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3";
+ return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${singularPhrase}`;
+ }
+ const comparison = issue2.inclusive ? `${issue2.minimum} ${sizing?.unit ?? ""} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8` : `\u05D9\u05D5\u05EA\u05E8 \u05DE-${issue2.minimum} ${sizing?.unit ?? ""}`;
+ return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim();
+ }
+ const adj = issue2.inclusive ? ">=" : ">";
+ const be = verbFor(issue2.origin ?? "value");
+ if (sizing?.unit) {
+ return `${sizing.shortLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
+ }
+ return `${sizing?.shortLabel ?? "\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with")
+ return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1 "${_issue.prefix}"`;
+ if (_issue.format === "ends_with")
+ return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${_issue.pattern}`;
+ const nounEntry = FormatDictionary[_issue.format];
+ const noun = nounEntry?.label ?? _issue.format;
+ const gender = nounEntry?.gender ?? "m";
+ const adjective = gender === "f" ? "\u05EA\u05E7\u05D9\u05E0\u05D4" : "\u05EA\u05E7\u05D9\u05DF";
+ return `${noun} \u05DC\u05D0 ${adjective}`;
+ }
+ case "not_multiple_of":
+ return `\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${issue2.divisor}`;
+ case "unrecognized_keys":
+ return `\u05DE\u05E4\u05EA\u05D7${issue2.keys.length > 1 ? "\u05D5\u05EA" : ""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${issue2.keys.length > 1 ? "\u05D9\u05DD" : "\u05D4"}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key": {
+ return `\u05E9\u05D3\u05D4 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8`;
+ }
+ case "invalid_union":
+ return "\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF";
+ case "invalid_element": {
+ const place = withDefinite(issue2.origin ?? "array");
+ return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${place}`;
+ }
+ default:
+ return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`;
+ }
+ };
+}, "error");
+function he_default() {
+ return {
+ localeError: error17()
+ };
+}
+__name(he_default, "default");
+
+// node_modules/zod/v4/locales/hr.js
+init_esbuild_shims();
+var error18 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "znakova", verb: "imati" },
+ file: { unit: "bajtova", verb: "imati" },
+ array: { unit: "stavki", verb: "imati" },
+ set: { unit: "stavki", verb: "imati" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "unos",
+ email: "email adresa",
+ url: "URL",
+ emoji: "emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "ISO datum i vrijeme",
+ date: "ISO datum",
+ time: "ISO vrijeme",
+ duration: "ISO trajanje",
+ ipv4: "IPv4 adresa",
+ ipv6: "IPv6 adresa",
+ cidrv4: "IPv4 raspon",
+ cidrv6: "IPv6 raspon",
+ base64: "base64 kodirani tekst",
+ base64url: "base64url kodirani tekst",
+ json_string: "JSON tekst",
+ e164: "E.164 broj",
+ jwt: "JWT",
+ template_literal: "unos"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ string: "tekst",
+ number: "broj",
+ boolean: "boolean",
+ array: "niz",
+ object: "objekt",
+ set: "skup",
+ file: "datoteka",
+ date: "datum",
+ bigint: "bigint",
+ symbol: "simbol",
+ undefined: "undefined",
+ null: "null",
+ function: "funkcija",
+ map: "mapa"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `Neispravan unos: o\u010Dekuje se instanceof ${issue2.expected}, a primljeno je ${received}`;
+ }
+ return `Neispravan unos: o\u010Dekuje se ${expected}, a primljeno je ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `Neispravna vrijednost: o\u010Dekivano ${stringifyPrimitive(issue2.values[0])}`;
+ return `Neispravna opcija: o\u010Dekivano jedno od ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
+ if (sizing)
+ return `Preveliko: o\u010Dekivano da ${origin ?? "vrijednost"} ima ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemenata"}`;
+ return `Preveliko: o\u010Dekivano da ${origin ?? "vrijednost"} bude ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
+ if (sizing) {
+ return `Premalo: o\u010Dekivano da ${origin} ima ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
+ }
+ return `Premalo: o\u010Dekivano da ${origin} bude ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with")
+ return `Neispravan tekst: mora zapo\u010Dinjati s "${_issue.prefix}"`;
+ if (_issue.format === "ends_with")
+ return `Neispravan tekst: mora zavr\u0161avati s "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `Neispravan tekst: mora sadr\u017Eavati "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `Neispravan tekst: mora odgovarati uzorku ${_issue.pattern}`;
+ return `Neispravna ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `Neispravan broj: mora biti vi\u0161ekratnik od ${issue2.divisor}`;
+ case "unrecognized_keys":
+ return `Neprepoznat${issue2.keys.length > 1 ? "i klju\u010Devi" : " klju\u010D"}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `Neispravan klju\u010D u ${TypeDictionary[issue2.origin] ?? issue2.origin}`;
+ case "invalid_union":
+ return "Neispravan unos";
+ case "invalid_element":
+ return `Neispravna vrijednost u ${TypeDictionary[issue2.origin] ?? issue2.origin}`;
+ default:
+ return `Neispravan unos`;
+ }
+ };
+}, "error");
+function hr_default() {
+ return {
+ localeError: error18()
+ };
+}
+__name(hr_default, "default");
+
+// node_modules/zod/v4/locales/hu.js
+init_esbuild_shims();
+var error19 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "karakter", verb: "legyen" },
+ file: { unit: "byte", verb: "legyen" },
+ array: { unit: "elem", verb: "legyen" },
+ set: { unit: "elem", verb: "legyen" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "bemenet",
+ email: "email c\xEDm",
+ url: "URL",
+ emoji: "emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "ISO id\u0151b\xE9lyeg",
+ date: "ISO d\xE1tum",
+ time: "ISO id\u0151",
+ duration: "ISO id\u0151intervallum",
+ ipv4: "IPv4 c\xEDm",
+ ipv6: "IPv6 c\xEDm",
+ cidrv4: "IPv4 tartom\xE1ny",
+ cidrv6: "IPv6 tartom\xE1ny",
+ base64: "base64-k\xF3dolt string",
+ base64url: "base64url-k\xF3dolt string",
+ json_string: "JSON string",
+ e164: "E.164 sz\xE1m",
+ jwt: "JWT",
+ template_literal: "bemenet"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "sz\xE1m",
+ array: "t\xF6mb"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k instanceof ${issue2.expected}, a kapott \xE9rt\xE9k ${received}`;
+ }
+ return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${expected}, a kapott \xE9rt\xE9k ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${stringifyPrimitive(issue2.values[0])}`;
+ return `\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `T\xFAl nagy: ${issue2.origin ?? "\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elem"}`;
+ return `T\xFAl nagy: a bemeneti \xE9rt\xE9k ${issue2.origin ?? "\xE9rt\xE9k"} t\xFAl nagy: ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} m\xE9rete t\xFAl kicsi ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
+ }
+ return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} t\xFAl kicsi ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with")
+ return `\xC9rv\xE9nytelen string: "${_issue.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`;
+ if (_issue.format === "ends_with")
+ return `\xC9rv\xE9nytelen string: "${_issue.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`;
+ if (_issue.format === "includes")
+ return `\xC9rv\xE9nytelen string: "${_issue.includes}" \xE9rt\xE9ket kell tartalmaznia`;
+ if (_issue.format === "regex")
+ return `\xC9rv\xE9nytelen string: ${_issue.pattern} mint\xE1nak kell megfelelnie`;
+ return `\xC9rv\xE9nytelen ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `\xC9rv\xE9nytelen sz\xE1m: ${issue2.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;
+ case "unrecognized_keys":
+ return `Ismeretlen kulcs${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `\xC9rv\xE9nytelen kulcs ${issue2.origin}`;
+ case "invalid_union":
+ return "\xC9rv\xE9nytelen bemenet";
+ case "invalid_element":
+ return `\xC9rv\xE9nytelen \xE9rt\xE9k: ${issue2.origin}`;
+ default:
+ return `\xC9rv\xE9nytelen bemenet`;
+ }
+ };
+}, "error");
+function hu_default() {
+ return {
+ localeError: error19()
+ };
+}
+__name(hu_default, "default");
+
+// node_modules/zod/v4/locales/hy.js
+init_esbuild_shims();
+function getArmenianPlural(count, one, many) {
+ return Math.abs(count) === 1 ? one : many;
+}
+__name(getArmenianPlural, "getArmenianPlural");
+function withDefiniteArticle(word) {
+ if (!word)
+ return "";
+ const vowels = ["\u0561", "\u0565", "\u0568", "\u056B", "\u0578", "\u0578\u0582", "\u0585"];
+ const lastChar = word[word.length - 1];
+ return word + (vowels.includes(lastChar) ? "\u0576" : "\u0568");
+}
+__name(withDefiniteArticle, "withDefiniteArticle");
+var error20 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: {
+ unit: {
+ one: "\u0576\u0577\u0561\u0576",
+ many: "\u0576\u0577\u0561\u0576\u0576\u0565\u0580"
+ },
+ verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C"
+ },
+ file: {
+ unit: {
+ one: "\u0562\u0561\u0575\u0569",
+ many: "\u0562\u0561\u0575\u0569\u0565\u0580"
+ },
+ verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C"
+ },
+ array: {
+ unit: {
+ one: "\u057F\u0561\u0580\u0580",
+ many: "\u057F\u0561\u0580\u0580\u0565\u0580"
+ },
+ verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C"
+ },
+ set: {
+ unit: {
+ one: "\u057F\u0561\u0580\u0580",
+ many: "\u057F\u0561\u0580\u0580\u0565\u0580"
+ },
+ verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C"
+ }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "\u0574\u0578\u0582\u057F\u0584",
+ email: "\u0567\u056C. \u0570\u0561\u057D\u0581\u0565",
+ url: "URL",
+ emoji: "\u0567\u0574\u0578\u057B\u056B",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E \u0587 \u056A\u0561\u0574",
+ date: "ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E",
+ time: "ISO \u056A\u0561\u0574",
+ duration: "ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576",
+ ipv4: "IPv4 \u0570\u0561\u057D\u0581\u0565",
+ ipv6: "IPv6 \u0570\u0561\u057D\u0581\u0565",
+ cidrv4: "IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",
+ cidrv6: "IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",
+ base64: "base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",
+ base64url: "base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",
+ json_string: "JSON \u057F\u0578\u0572",
+ e164: "E.164 \u0570\u0561\u0574\u0561\u0580",
+ jwt: "JWT",
+ template_literal: "\u0574\u0578\u0582\u057F\u0584"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "\u0569\u056B\u057E",
+ array: "\u0566\u0561\u0576\u0563\u057E\u0561\u056E"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 instanceof ${issue2.expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`;
+ }
+ return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${stringifyPrimitive(issue2.values[1])}`;
+ return `\u054D\u056D\u0561\u056C \u057F\u0561\u0580\u0562\u0565\u0580\u0561\u056F\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 \u0570\u0565\u057F\u0587\u0575\u0561\u056C\u0576\u0565\u0580\u056B\u0581 \u0574\u0565\u056F\u0568\u055D ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ const maxValue = Number(issue2.maximum);
+ const unit = getArmenianPlural(maxValue, sizing.unit.one, sizing.unit.many);
+ return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin ?? "\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue2.maximum.toString()} ${unit}`;
+ }
+ return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin ?? "\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ const minValue = Number(issue2.minimum);
+ const unit = getArmenianPlural(minValue, sizing.unit.one, sizing.unit.many);
+ return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue2.minimum.toString()} ${unit}`;
+ }
+ return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin)} \u056C\u056B\u0576\u056B ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with")
+ return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B "${_issue.prefix}"-\u0578\u057E`;
+ if (_issue.format === "ends_with")
+ return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B "${_issue.suffix}"-\u0578\u057E`;
+ if (_issue.format === "includes")
+ return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057A\u0561\u0580\u0578\u0582\u0576\u0561\u056F\u056B "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0570\u0561\u0574\u0561\u057A\u0561\u057F\u0561\u057D\u056D\u0561\u0576\u056B ${_issue.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`;
+ return `\u054D\u056D\u0561\u056C ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `\u054D\u056D\u0561\u056C \u0569\u056B\u057E\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0562\u0561\u0566\u0574\u0561\u057A\u0561\u057F\u056B\u056F \u056C\u056B\u0576\u056B ${issue2.divisor}-\u056B`;
+ case "unrecognized_keys":
+ return `\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${issue2.keys.length > 1 ? "\u0576\u0565\u0580" : ""}. ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${withDefiniteArticle(issue2.origin)}-\u0578\u0582\u0574`;
+ case "invalid_union":
+ return "\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574";
+ case "invalid_element":
+ return `\u054D\u056D\u0561\u056C \u0561\u0580\u056A\u0565\u0584 ${withDefiniteArticle(issue2.origin)}-\u0578\u0582\u0574`;
+ default:
+ return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574`;
+ }
+ };
+}, "error");
+function hy_default() {
+ return {
+ localeError: error20()
+ };
+}
+__name(hy_default, "default");
+
+// node_modules/zod/v4/locales/id.js
+init_esbuild_shims();
+var error21 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "karakter", verb: "memiliki" },
+ file: { unit: "byte", verb: "memiliki" },
+ array: { unit: "item", verb: "memiliki" },
+ set: { unit: "item", verb: "memiliki" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "input",
+ email: "alamat email",
+ url: "URL",
+ emoji: "emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "tanggal dan waktu format ISO",
+ date: "tanggal format ISO",
+ time: "jam format ISO",
+ duration: "durasi format ISO",
+ ipv4: "alamat IPv4",
+ ipv6: "alamat IPv6",
+ cidrv4: "rentang alamat IPv4",
+ cidrv6: "rentang alamat IPv6",
+ base64: "string dengan enkode base64",
+ base64url: "string dengan enkode base64url",
+ json_string: "string JSON",
+ e164: "angka E.164",
+ jwt: "JWT",
+ template_literal: "input"
+ };
+ const TypeDictionary = {
+ nan: "NaN"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `Input tidak valid: diharapkan instanceof ${issue2.expected}, diterima ${received}`;
+ }
+ return `Input tidak valid: diharapkan ${expected}, diterima ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `Input tidak valid: diharapkan ${stringifyPrimitive(issue2.values[0])}`;
+ return `Pilihan tidak valid: diharapkan salah satu dari ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} memiliki ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`;
+ return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} menjadi ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `Terlalu kecil: diharapkan ${issue2.origin} memiliki ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
+ }
+ return `Terlalu kecil: diharapkan ${issue2.origin} menjadi ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with")
+ return `String tidak valid: harus dimulai dengan "${_issue.prefix}"`;
+ if (_issue.format === "ends_with")
+ return `String tidak valid: harus berakhir dengan "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `String tidak valid: harus menyertakan "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `String tidak valid: harus sesuai pola ${_issue.pattern}`;
+ return `${FormatDictionary[_issue.format] ?? issue2.format} tidak valid`;
+ }
+ case "not_multiple_of":
+ return `Angka tidak valid: harus kelipatan dari ${issue2.divisor}`;
+ case "unrecognized_keys":
+ return `Kunci tidak dikenali ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `Kunci tidak valid di ${issue2.origin}`;
+ case "invalid_union":
+ return "Input tidak valid";
+ case "invalid_element":
+ return `Nilai tidak valid di ${issue2.origin}`;
+ default:
+ return `Input tidak valid`;
+ }
+ };
+}, "error");
+function id_default() {
+ return {
+ localeError: error21()
+ };
+}
+__name(id_default, "default");
+
+// node_modules/zod/v4/locales/is.js
+init_esbuild_shims();
+var error22 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "stafi", verb: "a\xF0 hafa" },
+ file: { unit: "b\xE6ti", verb: "a\xF0 hafa" },
+ array: { unit: "hluti", verb: "a\xF0 hafa" },
+ set: { unit: "hluti", verb: "a\xF0 hafa" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "gildi",
+ email: "netfang",
+ url: "vefsl\xF3\xF0",
+ emoji: "emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "ISO dagsetning og t\xEDmi",
+ date: "ISO dagsetning",
+ time: "ISO t\xEDmi",
+ duration: "ISO t\xEDmalengd",
+ ipv4: "IPv4 address",
+ ipv6: "IPv6 address",
+ cidrv4: "IPv4 range",
+ cidrv6: "IPv6 range",
+ base64: "base64-encoded strengur",
+ base64url: "base64url-encoded strengur",
+ json_string: "JSON strengur",
+ e164: "E.164 t\xF6lugildi",
+ jwt: "JWT",
+ template_literal: "gildi"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "n\xFAmer",
+ array: "fylki"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera instanceof ${issue2.expected}`;
+ }
+ return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera ${expected}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `Rangt gildi: gert r\xE1\xF0 fyrir ${stringifyPrimitive(issue2.values[0])}`;
+ return `\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin ?? "gildi"} hafi ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "hluti"}`;
+ return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin ?? "gildi"} s\xE9 ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} hafi ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
+ }
+ return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} s\xE9 ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with") {
+ return `\xD3gildur strengur: ver\xF0ur a\xF0 byrja \xE1 "${_issue.prefix}"`;
+ }
+ if (_issue.format === "ends_with")
+ return `\xD3gildur strengur: ver\xF0ur a\xF0 enda \xE1 "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `\xD3gildur strengur: ver\xF0ur a\xF0 innihalda "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `\xD3gildur strengur: ver\xF0ur a\xF0 fylgja mynstri ${_issue.pattern}`;
+ return `Rangt ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${issue2.divisor}`;
+ case "unrecognized_keys":
+ return `\xD3\xFEekkt ${issue2.keys.length > 1 ? "ir lyklar" : "ur lykill"}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `Rangur lykill \xED ${issue2.origin}`;
+ case "invalid_union":
+ return "Rangt gildi";
+ case "invalid_element":
+ return `Rangt gildi \xED ${issue2.origin}`;
+ default:
+ return `Rangt gildi`;
+ }
+ };
+}, "error");
+function is_default() {
+ return {
+ localeError: error22()
+ };
+}
+__name(is_default, "default");
+
+// node_modules/zod/v4/locales/it.js
+init_esbuild_shims();
+var error23 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "caratteri", verb: "avere" },
+ file: { unit: "byte", verb: "avere" },
+ array: { unit: "elementi", verb: "avere" },
+ set: { unit: "elementi", verb: "avere" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "input",
+ email: "indirizzo email",
+ url: "URL",
+ emoji: "emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "data e ora ISO",
+ date: "data ISO",
+ time: "ora ISO",
+ duration: "durata ISO",
+ ipv4: "indirizzo IPv4",
+ ipv6: "indirizzo IPv6",
+ cidrv4: "intervallo IPv4",
+ cidrv6: "intervallo IPv6",
+ base64: "stringa codificata in base64",
+ base64url: "URL codificata in base64",
+ json_string: "stringa JSON",
+ e164: "numero E.164",
+ jwt: "JWT",
+ template_literal: "input"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "numero",
+ array: "vettore"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `Input non valido: atteso instanceof ${issue2.expected}, ricevuto ${received}`;
+ }
+ return `Input non valido: atteso ${expected}, ricevuto ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `Input non valido: atteso ${stringifyPrimitive(issue2.values[0])}`;
+ return `Opzione non valida: atteso uno tra ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `Troppo grande: ${issue2.origin ?? "valore"} deve avere ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementi"}`;
+ return `Troppo grande: ${issue2.origin ?? "valore"} deve essere ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `Troppo piccolo: ${issue2.origin} deve avere ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
+ }
+ return `Troppo piccolo: ${issue2.origin} deve essere ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with")
+ return `Stringa non valida: deve iniziare con "${_issue.prefix}"`;
+ if (_issue.format === "ends_with")
+ return `Stringa non valida: deve terminare con "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `Stringa non valida: deve includere "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`;
+ return `Input non valido: ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `Numero non valido: deve essere un multiplo di ${issue2.divisor}`;
+ case "unrecognized_keys":
+ return `Chiav${issue2.keys.length > 1 ? "i" : "e"} non riconosciut${issue2.keys.length > 1 ? "e" : "a"}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `Chiave non valida in ${issue2.origin}`;
+ case "invalid_union":
+ return "Input non valido";
+ case "invalid_element":
+ return `Valore non valido in ${issue2.origin}`;
+ default:
+ return `Input non valido`;
+ }
+ };
+}, "error");
+function it_default() {
+ return {
+ localeError: error23()
+ };
+}
+__name(it_default, "default");
+
+// node_modules/zod/v4/locales/ja.js
+init_esbuild_shims();
+var error24 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" },
+ file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" },
+ array: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" },
+ set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "\u5165\u529B\u5024",
+ email: "\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9",
+ url: "URL",
+ emoji: "\u7D75\u6587\u5B57",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "ISO\u65E5\u6642",
+ date: "ISO\u65E5\u4ED8",
+ time: "ISO\u6642\u523B",
+ duration: "ISO\u671F\u9593",
+ ipv4: "IPv4\u30A2\u30C9\u30EC\u30B9",
+ ipv6: "IPv6\u30A2\u30C9\u30EC\u30B9",
+ cidrv4: "IPv4\u7BC4\u56F2",
+ cidrv6: "IPv6\u7BC4\u56F2",
+ base64: "base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",
+ base64url: "base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",
+ json_string: "JSON\u6587\u5B57\u5217",
+ e164: "E.164\u756A\u53F7",
+ jwt: "JWT",
+ template_literal: "\u5165\u529B\u5024"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "\u6570\u5024",
+ array: "\u914D\u5217"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `\u7121\u52B9\u306A\u5165\u529B: instanceof ${issue2.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`;
+ }
+ return `\u7121\u52B9\u306A\u5165\u529B: ${expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `\u7121\u52B9\u306A\u5165\u529B: ${stringifyPrimitive(issue2.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`;
+ return `\u7121\u52B9\u306A\u9078\u629E: ${joinValues(issue2.values, "\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "\u4EE5\u4E0B\u3067\u3042\u308B" : "\u3088\u308A\u5C0F\u3055\u3044";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin ?? "\u5024"}\u306F${issue2.maximum.toString()}${sizing.unit ?? "\u8981\u7D20"}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
+ return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin ?? "\u5024"}\u306F${issue2.maximum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? "\u4EE5\u4E0A\u3067\u3042\u308B" : "\u3088\u308A\u5927\u304D\u3044";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${sizing.unit}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
+ return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with")
+ return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
+ if (_issue.format === "ends_with")
+ return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
+ if (_issue.format === "includes")
+ return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
+ if (_issue.format === "regex")
+ return `\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${_issue.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
+ return `\u7121\u52B9\u306A${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `\u7121\u52B9\u306A\u6570\u5024: ${issue2.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
+ case "unrecognized_keys":
+ return `\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${issue2.keys.length > 1 ? "\u7FA4" : ""}: ${joinValues(issue2.keys, "\u3001")}`;
+ case "invalid_key":
+ return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;
+ case "invalid_union":
+ return "\u7121\u52B9\u306A\u5165\u529B";
+ case "invalid_element":
+ return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;
+ default:
+ return `\u7121\u52B9\u306A\u5165\u529B`;
+ }
+ };
+}, "error");
+function ja_default() {
+ return {
+ localeError: error24()
+ };
+}
+__name(ja_default, "default");
+
+// node_modules/zod/v4/locales/ka.js
+init_esbuild_shims();
+var error25 = /* @__PURE__ */ __name(() => {
+ 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" },
+ array: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" },
+ set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0",
+ email: "\u10D4\u10DA-\u10E4\u10DD\u10E1\u10E2\u10D8\u10E1 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",
+ url: "URL",
+ emoji: "\u10D4\u10DB\u10DD\u10EF\u10D8",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8-\u10D3\u10E0\u10DD",
+ date: "\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8",
+ time: "\u10D3\u10E0\u10DD",
+ duration: "\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0",
+ ipv4: "IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",
+ ipv6: "IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",
+ cidrv4: "IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",
+ cidrv6: "IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",
+ base64: "base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8",
+ base64url: "base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8",
+ json_string: "JSON \u10D5\u10D4\u10DA\u10D8",
+ e164: "E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8",
+ jwt: "JWT",
+ template_literal: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "\u10E0\u10D8\u10EA\u10EE\u10D5\u10D8",
+ string: "\u10D5\u10D4\u10DA\u10D8",
+ boolean: "\u10D1\u10E3\u10DA\u10D4\u10D0\u10DC\u10D8",
+ function: "\u10E4\u10E3\u10DC\u10E5\u10EA\u10D8\u10D0",
+ array: "\u10DB\u10D0\u10E1\u10D8\u10D5\u10D8"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 instanceof ${issue2.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`;
+ }
+ return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${stringifyPrimitive(issue2.values[0])}`;
+ return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D0\u10E0\u10D8\u10D0\u10DC\u10E2\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8\u10D0 \u10D4\u10E0\u10D7-\u10D4\u10E0\u10D7\u10D8 ${joinValues(issue2.values, "|")}-\u10D3\u10D0\u10DC`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin ?? "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit}`;
+ return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin ?? "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
+ }
+ return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with") {
+ return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10EC\u10E7\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.prefix}"-\u10D8\u10D7`;
+ }
+ if (_issue.format === "ends_with")
+ return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10DB\u10D7\u10D0\u10D5\u10E0\u10D3\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.suffix}"-\u10D8\u10D7`;
+ if (_issue.format === "includes")
+ return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1 "${_issue.includes}"-\u10E1`;
+ if (_issue.format === "regex")
+ return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D4\u10E1\u10D0\u10D1\u10D0\u10DB\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \u10E8\u10D0\u10D1\u10DA\u10DD\u10DC\u10E1 ${_issue.pattern}`;
+ return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E0\u10D8\u10EA\u10EE\u10D5\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10E7\u10DD\u10E1 ${issue2.divisor}-\u10D8\u10E1 \u10EF\u10D4\u10E0\u10D0\u10D3\u10D8`;
+ case "unrecognized_keys":
+ return `\u10E3\u10EA\u10DC\u10DD\u10D1\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1${issue2.keys.length > 1 ? "\u10D4\u10D1\u10D8" : "\u10D8"}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${issue2.origin}-\u10E8\u10D8`;
+ case "invalid_union":
+ return "\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0";
+ case "invalid_element":
+ return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0 ${issue2.origin}-\u10E8\u10D8`;
+ default:
+ return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0`;
+ }
+ };
+}, "error");
+function ka_default() {
+ return {
+ localeError: error25()
+ };
+}
+__name(ka_default, "default");
+
+// node_modules/zod/v4/locales/kh.js
+init_esbuild_shims();
+
+// node_modules/zod/v4/locales/km.js
+init_esbuild_shims();
+var error26 = /* @__PURE__ */ __name(() => {
+ 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" },
+ array: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" },
+ set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B",
+ email: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B",
+ url: "URL",
+ emoji: "\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO",
+ date: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO",
+ time: "\u1798\u17C9\u17C4\u1784 ISO",
+ duration: "\u179A\u1799\u17C8\u1796\u17C1\u179B ISO",
+ ipv4: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",
+ ipv6: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",
+ cidrv4: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",
+ cidrv6: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",
+ base64: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64",
+ base64url: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url",
+ json_string: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON",
+ e164: "\u179B\u17C1\u1781 E.164",
+ jwt: "JWT",
+ template_literal: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "\u179B\u17C1\u1781",
+ array: "\u17A2\u17B6\u179A\u17C1 (Array)",
+ null: "\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A instanceof ${issue2.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`;
+ }
+ return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${stringifyPrimitive(issue2.values[0])}`;
+ return `\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u1792\u17B6\u178F\u17BB"}`;
+ return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
+ }
+ return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with") {
+ return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${_issue.prefix}"`;
+ }
+ if (_issue.format === "ends_with")
+ return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${_issue.pattern}`;
+ return `\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${issue2.divisor}`;
+ case "unrecognized_keys":
+ return `\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`;
+ case "invalid_union":
+ return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`;
+ case "invalid_element":
+ return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`;
+ default:
+ return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`;
+ }
+ };
+}, "error");
+function km_default() {
+ return {
+ localeError: error26()
+ };
+}
+__name(km_default, "default");
+
+// node_modules/zod/v4/locales/kh.js
+function kh_default() {
+ return km_default();
+}
+__name(kh_default, "default");
+
+// node_modules/zod/v4/locales/ko.js
+init_esbuild_shims();
+var error27 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "\uBB38\uC790", verb: "to have" },
+ file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" },
+ array: { unit: "\uAC1C", verb: "to have" },
+ set: { unit: "\uAC1C", verb: "to have" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "\uC785\uB825",
+ email: "\uC774\uBA54\uC77C \uC8FC\uC18C",
+ url: "URL",
+ emoji: "\uC774\uBAA8\uC9C0",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "ISO \uB0A0\uC9DC\uC2DC\uAC04",
+ date: "ISO \uB0A0\uC9DC",
+ time: "ISO \uC2DC\uAC04",
+ duration: "ISO \uAE30\uAC04",
+ ipv4: "IPv4 \uC8FC\uC18C",
+ ipv6: "IPv6 \uC8FC\uC18C",
+ cidrv4: "IPv4 \uBC94\uC704",
+ cidrv6: "IPv6 \uBC94\uC704",
+ base64: "base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",
+ base64url: "base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",
+ json_string: "JSON \uBB38\uC790\uC5F4",
+ e164: "E.164 \uBC88\uD638",
+ jwt: "JWT",
+ template_literal: "\uC785\uB825"
+ };
+ const TypeDictionary = {
+ nan: "NaN"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${issue2.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`;
+ }
+ return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${stringifyPrimitive(issue2.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`;
+ return `\uC798\uBABB\uB41C \uC635\uC158: ${joinValues(issue2.values, "\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "\uC774\uD558" : "\uBBF8\uB9CC";
+ const suffix = adj === "\uBBF8\uB9CC" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4";
+ const sizing = getSizing(issue2.origin);
+ const unit = sizing?.unit ?? "\uC694\uC18C";
+ if (sizing)
+ return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()}${unit} ${adj}${suffix}`;
+ return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()} ${adj}${suffix}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? "\uC774\uC0C1" : "\uCD08\uACFC";
+ const suffix = adj === "\uC774\uC0C1" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4";
+ const sizing = getSizing(issue2.origin);
+ const unit = sizing?.unit ?? "\uC694\uC18C";
+ if (sizing) {
+ return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()}${unit} ${adj}${suffix}`;
+ }
+ return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()} ${adj}${suffix}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with") {
+ return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`;
+ }
+ if (_issue.format === "ends_with")
+ return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`;
+ if (_issue.format === "includes")
+ return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`;
+ if (_issue.format === "regex")
+ return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${_issue.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`;
+ return `\uC798\uBABB\uB41C ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `\uC798\uBABB\uB41C \uC22B\uC790: ${issue2.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;
+ case "unrecognized_keys":
+ return `\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `\uC798\uBABB\uB41C \uD0A4: ${issue2.origin}`;
+ case "invalid_union":
+ return `\uC798\uBABB\uB41C \uC785\uB825`;
+ case "invalid_element":
+ return `\uC798\uBABB\uB41C \uAC12: ${issue2.origin}`;
+ default:
+ return `\uC798\uBABB\uB41C \uC785\uB825`;
+ }
+ };
+}, "error");
+function ko_default() {
+ return {
+ localeError: error27()
+ };
+}
+__name(ko_default, "default");
+
+// node_modules/zod/v4/locales/lt.js
+init_esbuild_shims();
+var capitalizeFirstCharacter = /* @__PURE__ */ __name((text) => {
+ return text.charAt(0).toUpperCase() + text.slice(1);
+}, "capitalizeFirstCharacter");
+function getUnitTypeFromNumber(number4) {
+ const abs = Math.abs(number4);
+ const last = abs % 10;
+ const last2 = abs % 100;
+ if (last2 >= 11 && last2 <= 19 || last === 0)
+ return "many";
+ if (last === 1)
+ return "one";
+ return "few";
+}
+__name(getUnitTypeFromNumber, "getUnitTypeFromNumber");
+var error28 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: {
+ unit: {
+ one: "simbolis",
+ few: "simboliai",
+ many: "simboli\u0173"
+ },
+ verb: {
+ smaller: {
+ inclusive: "turi b\u016Bti ne ilgesn\u0117 kaip",
+ notInclusive: "turi b\u016Bti trumpesn\u0117 kaip"
+ },
+ bigger: {
+ inclusive: "turi b\u016Bti ne trumpesn\u0117 kaip",
+ notInclusive: "turi b\u016Bti ilgesn\u0117 kaip"
+ }
+ }
+ },
+ file: {
+ unit: {
+ one: "baitas",
+ few: "baitai",
+ many: "bait\u0173"
+ },
+ verb: {
+ smaller: {
+ inclusive: "turi b\u016Bti ne didesnis kaip",
+ notInclusive: "turi b\u016Bti ma\u017Eesnis kaip"
+ },
+ bigger: {
+ inclusive: "turi b\u016Bti ne ma\u017Eesnis kaip",
+ notInclusive: "turi b\u016Bti didesnis kaip"
+ }
+ }
+ },
+ array: {
+ unit: {
+ one: "element\u0105",
+ few: "elementus",
+ many: "element\u0173"
+ },
+ verb: {
+ smaller: {
+ inclusive: "turi tur\u0117ti ne daugiau kaip",
+ notInclusive: "turi tur\u0117ti ma\u017Eiau kaip"
+ },
+ bigger: {
+ inclusive: "turi tur\u0117ti ne ma\u017Eiau kaip",
+ notInclusive: "turi tur\u0117ti daugiau kaip"
+ }
+ }
+ },
+ set: {
+ unit: {
+ one: "element\u0105",
+ few: "elementus",
+ many: "element\u0173"
+ },
+ verb: {
+ smaller: {
+ inclusive: "turi tur\u0117ti ne daugiau kaip",
+ notInclusive: "turi tur\u0117ti ma\u017Eiau kaip"
+ },
+ bigger: {
+ inclusive: "turi tur\u0117ti ne ma\u017Eiau kaip",
+ notInclusive: "turi tur\u0117ti daugiau kaip"
+ }
+ }
+ }
+ };
+ function getSizing(origin, unitType, inclusive, targetShouldBe) {
+ const result = Sizable[origin] ?? null;
+ if (result === null)
+ return result;
+ return {
+ unit: result.unit[unitType],
+ verb: result.verb[targetShouldBe][inclusive ? "inclusive" : "notInclusive"]
+ };
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "\u012Fvestis",
+ email: "el. pa\u0161to adresas",
+ url: "URL",
+ emoji: "jaustukas",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "ISO data ir laikas",
+ date: "ISO data",
+ time: "ISO laikas",
+ duration: "ISO trukm\u0117",
+ ipv4: "IPv4 adresas",
+ ipv6: "IPv6 adresas",
+ cidrv4: "IPv4 tinklo prefiksas (CIDR)",
+ cidrv6: "IPv6 tinklo prefiksas (CIDR)",
+ base64: "base64 u\u017Ekoduota eilut\u0117",
+ base64url: "base64url u\u017Ekoduota eilut\u0117",
+ json_string: "JSON eilut\u0117",
+ e164: "E.164 numeris",
+ jwt: "JWT",
+ template_literal: "\u012Fvestis"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "skai\u010Dius",
+ bigint: "sveikasis skai\u010Dius",
+ string: "eilut\u0117",
+ boolean: "login\u0117 reik\u0161m\u0117",
+ undefined: "neapibr\u0117\u017Eta reik\u0161m\u0117",
+ function: "funkcija",
+ symbol: "simbolis",
+ array: "masyvas",
+ object: "objektas",
+ null: "nulin\u0117 reik\u0161m\u0117"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `Gautas tipas ${received}, o tik\u0117tasi - instanceof ${issue2.expected}`;
+ }
+ return `Gautas tipas ${received}, o tik\u0117tasi - ${expected}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `Privalo b\u016Bti ${stringifyPrimitive(issue2.values[0])}`;
+ return `Privalo b\u016Bti vienas i\u0161 ${joinValues(issue2.values, "|")} pasirinkim\u0173`;
+ case "too_big": {
+ const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
+ const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.maximum)), issue2.inclusive ?? false, "smaller");
+ if (sizing?.verb)
+ return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} ${sizing.verb} ${issue2.maximum.toString()} ${sizing.unit ?? "element\u0173"}`;
+ const adj = issue2.inclusive ? "ne didesnis kaip" : "ma\u017Eesnis kaip";
+ return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.maximum.toString()} ${sizing?.unit}`;
+ }
+ case "too_small": {
+ const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
+ const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.minimum)), issue2.inclusive ?? false, "bigger");
+ if (sizing?.verb)
+ return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} ${sizing.verb} ${issue2.minimum.toString()} ${sizing.unit ?? "element\u0173"}`;
+ const adj = issue2.inclusive ? "ne ma\u017Eesnis kaip" : "didesnis kaip";
+ return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.minimum.toString()} ${sizing?.unit}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with") {
+ return `Eilut\u0117 privalo prasid\u0117ti "${_issue.prefix}"`;
+ }
+ if (_issue.format === "ends_with")
+ return `Eilut\u0117 privalo pasibaigti "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `Eilut\u0117 privalo \u012Ftraukti "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `Eilut\u0117 privalo atitikti ${_issue.pattern}`;
+ return `Neteisingas ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `Skai\u010Dius privalo b\u016Bti ${issue2.divisor} kartotinis.`;
+ case "unrecognized_keys":
+ return `Neatpa\u017Eint${issue2.keys.length > 1 ? "i" : "as"} rakt${issue2.keys.length > 1 ? "ai" : "as"}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return "Rastas klaidingas raktas";
+ case "invalid_union":
+ return "Klaidinga \u012Fvestis";
+ case "invalid_element": {
+ const origin = TypeDictionary[issue2.origin] ?? issue2.origin;
+ return `${capitalizeFirstCharacter(origin ?? issue2.origin ?? "reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`;
+ }
+ default:
+ return "Klaidinga \u012Fvestis";
+ }
+ };
+}, "error");
+function lt_default() {
+ return {
+ localeError: error28()
+ };
+}
+__name(lt_default, "default");
+
+// node_modules/zod/v4/locales/mk.js
+init_esbuild_shims();
+var error29 = /* @__PURE__ */ __name(() => {
+ 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" },
+ array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" },
+ set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "\u0432\u043D\u0435\u0441",
+ email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430",
+ url: "URL",
+ emoji: "\u0435\u043C\u043E\u045F\u0438",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435",
+ date: "ISO \u0434\u0430\u0442\u0443\u043C",
+ time: "ISO \u0432\u0440\u0435\u043C\u0435",
+ duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435",
+ ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430",
+ ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430",
+ cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433",
+ cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433",
+ base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",
+ base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",
+ json_string: "JSON \u043D\u0438\u0437\u0430",
+ e164: "E.164 \u0431\u0440\u043E\u0458",
+ jwt: "JWT",
+ template_literal: "\u0432\u043D\u0435\u0441"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "\u0431\u0440\u043E\u0458",
+ array: "\u043D\u0438\u0437\u0430"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${issue2.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`;
+ }
+ return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`;
+ return `\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`;
+ return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
+ }
+ return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with") {
+ return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${_issue.prefix}"`;
+ }
+ if (_issue.format === "ends_with")
+ return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${_issue.pattern}`;
+ return `Invalid ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${issue2.divisor}`;
+ case "unrecognized_keys":
+ return `${issue2.keys.length > 1 ? "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438" : "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${issue2.origin}`;
+ case "invalid_union":
+ return "\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441";
+ case "invalid_element":
+ return `\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${issue2.origin}`;
+ default:
+ return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441`;
+ }
+ };
+}, "error");
+function mk_default() {
+ return {
+ localeError: error29()
+ };
+}
+__name(mk_default, "default");
+
+// node_modules/zod/v4/locales/ms.js
+init_esbuild_shims();
+var error30 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "aksara", verb: "mempunyai" },
+ file: { unit: "bait", verb: "mempunyai" },
+ array: { unit: "elemen", verb: "mempunyai" },
+ set: { unit: "elemen", verb: "mempunyai" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "input",
+ email: "alamat e-mel",
+ url: "URL",
+ emoji: "emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "tarikh masa ISO",
+ date: "tarikh ISO",
+ time: "masa ISO",
+ duration: "tempoh ISO",
+ ipv4: "alamat IPv4",
+ ipv6: "alamat IPv6",
+ cidrv4: "julat IPv4",
+ cidrv6: "julat IPv6",
+ base64: "string dikodkan base64",
+ base64url: "string dikodkan base64url",
+ json_string: "string JSON",
+ e164: "nombor E.164",
+ jwt: "JWT",
+ template_literal: "input"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "nombor"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `Input tidak sah: dijangka instanceof ${issue2.expected}, diterima ${received}`;
+ }
+ return `Input tidak sah: dijangka ${expected}, diterima ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `Input tidak sah: dijangka ${stringifyPrimitive(issue2.values[0])}`;
+ return `Pilihan tidak sah: dijangka salah satu daripada ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`;
+ return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} adalah ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `Terlalu kecil: dijangka ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
+ }
+ return `Terlalu kecil: dijangka ${issue2.origin} adalah ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with")
+ return `String tidak sah: mesti bermula dengan "${_issue.prefix}"`;
+ if (_issue.format === "ends_with")
+ return `String tidak sah: mesti berakhir dengan "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `String tidak sah: mesti mengandungi "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`;
+ return `${FormatDictionary[_issue.format] ?? issue2.format} tidak sah`;
+ }
+ case "not_multiple_of":
+ return `Nombor tidak sah: perlu gandaan ${issue2.divisor}`;
+ case "unrecognized_keys":
+ return `Kunci tidak dikenali: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `Kunci tidak sah dalam ${issue2.origin}`;
+ case "invalid_union":
+ return "Input tidak sah";
+ case "invalid_element":
+ return `Nilai tidak sah dalam ${issue2.origin}`;
+ default:
+ return `Input tidak sah`;
+ }
+ };
+}, "error");
+function ms_default() {
+ return {
+ localeError: error30()
+ };
+}
+__name(ms_default, "default");
+
+// node_modules/zod/v4/locales/nl.js
+init_esbuild_shims();
+var error31 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "tekens", verb: "heeft" },
+ file: { unit: "bytes", verb: "heeft" },
+ array: { unit: "elementen", verb: "heeft" },
+ set: { unit: "elementen", verb: "heeft" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "invoer",
+ email: "emailadres",
+ url: "URL",
+ emoji: "emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "ISO datum en tijd",
+ date: "ISO datum",
+ time: "ISO tijd",
+ duration: "ISO duur",
+ ipv4: "IPv4-adres",
+ ipv6: "IPv6-adres",
+ cidrv4: "IPv4-bereik",
+ cidrv6: "IPv6-bereik",
+ base64: "base64-gecodeerde tekst",
+ base64url: "base64 URL-gecodeerde tekst",
+ json_string: "JSON string",
+ e164: "E.164-nummer",
+ jwt: "JWT",
+ template_literal: "invoer"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "getal"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `Ongeldige invoer: verwacht instanceof ${issue2.expected}, ontving ${received}`;
+ }
+ return `Ongeldige invoer: verwacht ${expected}, ontving ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `Ongeldige invoer: verwacht ${stringifyPrimitive(issue2.values[0])}`;
+ return `Ongeldige optie: verwacht \xE9\xE9n van ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ const longName = issue2.origin === "date" ? "laat" : issue2.origin === "string" ? "lang" : "groot";
+ if (sizing)
+ return `Te ${longName}: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementen"} ${sizing.verb}`;
+ return `Te ${longName}: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} is`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ const shortName = issue2.origin === "date" ? "vroeg" : issue2.origin === "string" ? "kort" : "klein";
+ if (sizing) {
+ return `Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`;
+ }
+ return `Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} is`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with") {
+ return `Ongeldige tekst: moet met "${_issue.prefix}" beginnen`;
+ }
+ if (_issue.format === "ends_with")
+ return `Ongeldige tekst: moet op "${_issue.suffix}" eindigen`;
+ if (_issue.format === "includes")
+ return `Ongeldige tekst: moet "${_issue.includes}" bevatten`;
+ if (_issue.format === "regex")
+ return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`;
+ return `Ongeldig: ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `Ongeldig getal: moet een veelvoud van ${issue2.divisor} zijn`;
+ case "unrecognized_keys":
+ return `Onbekende key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `Ongeldige key in ${issue2.origin}`;
+ case "invalid_union":
+ return "Ongeldige invoer";
+ case "invalid_element":
+ return `Ongeldige waarde in ${issue2.origin}`;
+ default:
+ return `Ongeldige invoer`;
+ }
+ };
+}, "error");
+function nl_default() {
+ return {
+ localeError: error31()
+ };
+}
+__name(nl_default, "default");
+
+// node_modules/zod/v4/locales/no.js
+init_esbuild_shims();
+var error32 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "tegn", verb: "\xE5 ha" },
+ file: { unit: "bytes", verb: "\xE5 ha" },
+ array: { unit: "elementer", verb: "\xE5 inneholde" },
+ set: { unit: "elementer", verb: "\xE5 inneholde" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "input",
+ email: "e-postadresse",
+ url: "URL",
+ emoji: "emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "ISO dato- og klokkeslett",
+ date: "ISO-dato",
+ time: "ISO-klokkeslett",
+ duration: "ISO-varighet",
+ ipv4: "IPv4-omr\xE5de",
+ ipv6: "IPv6-omr\xE5de",
+ cidrv4: "IPv4-spekter",
+ cidrv6: "IPv6-spekter",
+ base64: "base64-enkodet streng",
+ base64url: "base64url-enkodet streng",
+ json_string: "JSON-streng",
+ e164: "E.164-nummer",
+ jwt: "JWT",
+ template_literal: "input"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "tall",
+ array: "liste"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `Ugyldig input: forventet instanceof ${issue2.expected}, fikk ${received}`;
+ }
+ return `Ugyldig input: forventet ${expected}, fikk ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `Ugyldig verdi: forventet ${stringifyPrimitive(issue2.values[0])}`;
+ return `Ugyldig valg: forventet en av ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `For stor(t): forventet ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementer"}`;
+ return `For stor(t): forventet ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
+ }
+ return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with")
+ return `Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`;
+ if (_issue.format === "ends_with")
+ return `Ugyldig streng: m\xE5 ende med "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `Ugyldig streng: m\xE5 inneholde "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`;
+ return `Ugyldig ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `Ugyldig tall: m\xE5 v\xE6re et multiplum av ${issue2.divisor}`;
+ case "unrecognized_keys":
+ return `${issue2.keys.length > 1 ? "Ukjente n\xF8kler" : "Ukjent n\xF8kkel"}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `Ugyldig n\xF8kkel i ${issue2.origin}`;
+ case "invalid_union":
+ return "Ugyldig input";
+ case "invalid_element":
+ return `Ugyldig verdi i ${issue2.origin}`;
+ default:
+ return `Ugyldig input`;
+ }
+ };
+}, "error");
+function no_default() {
+ return {
+ localeError: error32()
+ };
+}
+__name(no_default, "default");
+
+// node_modules/zod/v4/locales/ota.js
+init_esbuild_shims();
+var error33 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "harf", verb: "olmal\u0131d\u0131r" },
+ file: { unit: "bayt", verb: "olmal\u0131d\u0131r" },
+ array: { unit: "unsur", verb: "olmal\u0131d\u0131r" },
+ set: { unit: "unsur", verb: "olmal\u0131d\u0131r" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "giren",
+ email: "epostag\xE2h",
+ url: "URL",
+ emoji: "emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "ISO heng\xE2m\u0131",
+ date: "ISO tarihi",
+ time: "ISO zaman\u0131",
+ duration: "ISO m\xFCddeti",
+ ipv4: "IPv4 ni\u015F\xE2n\u0131",
+ ipv6: "IPv6 ni\u015F\xE2n\u0131",
+ cidrv4: "IPv4 menzili",
+ cidrv6: "IPv6 menzili",
+ base64: "base64-\u015Fifreli metin",
+ base64url: "base64url-\u015Fifreli metin",
+ json_string: "JSON metin",
+ e164: "E.164 say\u0131s\u0131",
+ jwt: "JWT",
+ template_literal: "giren"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "numara",
+ array: "saf",
+ null: "gayb"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `F\xE2sit giren: umulan instanceof ${issue2.expected}, al\u0131nan ${received}`;
+ }
+ return `F\xE2sit giren: umulan ${expected}, al\u0131nan ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `F\xE2sit giren: umulan ${stringifyPrimitive(issue2.values[0])}`;
+ return `F\xE2sit tercih: m\xFBteberler ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `Fazla b\xFCy\xFCk: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"} sahip olmal\u0131yd\u0131.`;
+ return `Fazla b\xFCy\xFCk: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} olmal\u0131yd\u0131.`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} ${sizing.unit} sahip olmal\u0131yd\u0131.`;
+ }
+ return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} olmal\u0131yd\u0131.`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with")
+ return `F\xE2sit metin: "${_issue.prefix}" ile ba\u015Flamal\u0131.`;
+ if (_issue.format === "ends_with")
+ return `F\xE2sit metin: "${_issue.suffix}" ile bitmeli.`;
+ if (_issue.format === "includes")
+ return `F\xE2sit metin: "${_issue.includes}" ihtiv\xE2 etmeli.`;
+ if (_issue.format === "regex")
+ return `F\xE2sit metin: ${_issue.pattern} nak\u015F\u0131na uymal\u0131.`;
+ return `F\xE2sit ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `F\xE2sit say\u0131: ${issue2.divisor} kat\u0131 olmal\u0131yd\u0131.`;
+ case "unrecognized_keys":
+ return `Tan\u0131nmayan anahtar ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `${issue2.origin} i\xE7in tan\u0131nmayan anahtar var.`;
+ case "invalid_union":
+ return "Giren tan\u0131namad\u0131.";
+ case "invalid_element":
+ return `${issue2.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;
+ default:
+ return `K\u0131ymet tan\u0131namad\u0131.`;
+ }
+ };
+}, "error");
+function ota_default() {
+ return {
+ localeError: error33()
+ };
+}
+__name(ota_default, "default");
+
+// node_modules/zod/v4/locales/ps.js
+init_esbuild_shims();
+var error34 = /* @__PURE__ */ __name(() => {
+ 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" },
+ array: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" },
+ set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "\u0648\u0631\u0648\u062F\u064A",
+ email: "\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9",
+ url: "\u06CC\u0648 \u0622\u0631 \u0627\u0644",
+ emoji: "\u0627\u06CC\u0645\u0648\u062C\u064A",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A",
+ date: "\u0646\u06D0\u067C\u0647",
+ time: "\u0648\u062E\u062A",
+ duration: "\u0645\u0648\u062F\u0647",
+ ipv4: "\u062F IPv4 \u067E\u062A\u0647",
+ ipv6: "\u062F IPv6 \u067E\u062A\u0647",
+ cidrv4: "\u062F IPv4 \u0633\u0627\u062D\u0647",
+ cidrv6: "\u062F IPv6 \u0633\u0627\u062D\u0647",
+ base64: "base64-encoded \u0645\u062A\u0646",
+ base64url: "base64url-encoded \u0645\u062A\u0646",
+ json_string: "JSON \u0645\u062A\u0646",
+ e164: "\u062F E.164 \u0634\u0645\u06D0\u0631\u0647",
+ jwt: "JWT",
+ template_literal: "\u0648\u0631\u0648\u062F\u064A"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "\u0639\u062F\u062F",
+ array: "\u0627\u0631\u06D0"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${issue2.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`;
+ }
+ return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1) {
+ return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${stringifyPrimitive(issue2.values[0])} \u0648\u0627\u06CC`;
+ }
+ return `\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${joinValues(issue2.values, "|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`;
+ }
+ return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0648\u064A`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0648\u0644\u0631\u064A`;
+ }
+ return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0648\u064A`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with") {
+ return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`;
+ }
+ if (_issue.format === "ends_with") {
+ return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`;
+ }
+ if (_issue.format === "includes") {
+ return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${_issue.includes}" \u0648\u0644\u0631\u064A`;
+ }
+ if (_issue.format === "regex") {
+ return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${_issue.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`;
+ }
+ return `${FormatDictionary[_issue.format] ?? issue2.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`;
+ }
+ case "not_multiple_of":
+ return `\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${issue2.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;
+ case "unrecognized_keys":
+ return `\u0646\u0627\u0633\u0645 ${issue2.keys.length > 1 ? "\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647" : "\u06A9\u0644\u06CC\u0689"}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`;
+ case "invalid_union":
+ return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`;
+ case "invalid_element":
+ return `\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`;
+ default:
+ return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`;
+ }
+ };
+}, "error");
+function ps_default() {
+ return {
+ localeError: error34()
+ };
+}
+__name(ps_default, "default");
+
+// node_modules/zod/v4/locales/pl.js
+init_esbuild_shims();
+var error35 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "znak\xF3w", verb: "mie\u0107" },
+ file: { unit: "bajt\xF3w", verb: "mie\u0107" },
+ array: { unit: "element\xF3w", verb: "mie\u0107" },
+ set: { unit: "element\xF3w", verb: "mie\u0107" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "wyra\u017Cenie",
+ email: "adres email",
+ url: "URL",
+ emoji: "emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "data i godzina w formacie ISO",
+ date: "data w formacie ISO",
+ time: "godzina w formacie ISO",
+ duration: "czas trwania ISO",
+ ipv4: "adres IPv4",
+ ipv6: "adres IPv6",
+ cidrv4: "zakres IPv4",
+ cidrv6: "zakres IPv6",
+ base64: "ci\u0105g znak\xF3w zakodowany w formacie base64",
+ base64url: "ci\u0105g znak\xF3w zakodowany w formacie base64url",
+ json_string: "ci\u0105g znak\xF3w w formacie JSON",
+ e164: "liczba E.164",
+ jwt: "JWT",
+ template_literal: "wej\u015Bcie"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "liczba",
+ array: "tablica"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${issue2.expected}, otrzymano ${received}`;
+ }
+ return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${expected}, otrzymano ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${stringifyPrimitive(issue2.values[0])}`;
+ return `Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element\xF3w"}`;
+ }
+ return `Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "element\xF3w"}`;
+ }
+ return `Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with")
+ return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${_issue.prefix}"`;
+ if (_issue.format === "ends_with")
+ return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${_issue.pattern}`;
+ return `Nieprawid\u0142ow(y/a/e) ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${issue2.divisor}`;
+ case "unrecognized_keys":
+ return `Nierozpoznane klucze${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `Nieprawid\u0142owy klucz w ${issue2.origin}`;
+ case "invalid_union":
+ return "Nieprawid\u0142owe dane wej\u015Bciowe";
+ case "invalid_element":
+ return `Nieprawid\u0142owa warto\u015B\u0107 w ${issue2.origin}`;
+ default:
+ return `Nieprawid\u0142owe dane wej\u015Bciowe`;
+ }
+ };
+}, "error");
+function pl_default() {
+ return {
+ localeError: error35()
+ };
+}
+__name(pl_default, "default");
+
+// node_modules/zod/v4/locales/pt.js
+init_esbuild_shims();
+var error36 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "caracteres", verb: "ter" },
+ file: { unit: "bytes", verb: "ter" },
+ array: { unit: "itens", verb: "ter" },
+ set: { unit: "itens", verb: "ter" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "padr\xE3o",
+ email: "endere\xE7o de e-mail",
+ url: "URL",
+ emoji: "emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "data e hora ISO",
+ date: "data ISO",
+ time: "hora ISO",
+ duration: "dura\xE7\xE3o ISO",
+ ipv4: "endere\xE7o IPv4",
+ ipv6: "endere\xE7o IPv6",
+ cidrv4: "faixa de IPv4",
+ cidrv6: "faixa de IPv6",
+ base64: "texto codificado em base64",
+ base64url: "URL codificada em base64",
+ json_string: "texto JSON",
+ e164: "n\xFAmero E.164",
+ jwt: "JWT",
+ template_literal: "entrada"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "n\xFAmero",
+ null: "nulo"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `Tipo inv\xE1lido: esperado instanceof ${issue2.expected}, recebido ${received}`;
+ }
+ return `Tipo inv\xE1lido: esperado ${expected}, recebido ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue2.values[0])}`;
+ return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `Muito grande: esperado que ${issue2.origin ?? "valor"} tivesse ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`;
+ return `Muito grande: esperado que ${issue2.origin ?? "valor"} fosse ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
+ }
+ return `Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with")
+ return `Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`;
+ if (_issue.format === "ends_with")
+ return `Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`;
+ return `${FormatDictionary[_issue.format] ?? issue2.format} inv\xE1lido`;
+ }
+ case "not_multiple_of":
+ return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`;
+ case "unrecognized_keys":
+ return `Chave${issue2.keys.length > 1 ? "s" : ""} desconhecida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `Chave inv\xE1lida em ${issue2.origin}`;
+ case "invalid_union":
+ return "Entrada inv\xE1lida";
+ case "invalid_element":
+ return `Valor inv\xE1lido em ${issue2.origin}`;
+ default:
+ return `Campo inv\xE1lido`;
+ }
+ };
+}, "error");
+function pt_default() {
+ return {
+ localeError: error36()
+ };
+}
+__name(pt_default, "default");
+
+// node_modules/zod/v4/locales/ro.js
+init_esbuild_shims();
+var error37 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "caractere", verb: "s\u0103 aib\u0103" },
+ file: { unit: "octe\u021Bi", verb: "s\u0103 aib\u0103" },
+ array: { unit: "elemente", verb: "s\u0103 aib\u0103" },
+ set: { unit: "elemente", verb: "s\u0103 aib\u0103" },
+ map: { unit: "intr\u0103ri", verb: "s\u0103 aib\u0103" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "intrare",
+ email: "adres\u0103 de email",
+ url: "URL",
+ emoji: "emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "dat\u0103 \u0219i or\u0103 ISO",
+ date: "dat\u0103 ISO",
+ time: "or\u0103 ISO",
+ duration: "durat\u0103 ISO",
+ ipv4: "adres\u0103 IPv4",
+ ipv6: "adres\u0103 IPv6",
+ mac: "adres\u0103 MAC",
+ cidrv4: "interval IPv4",
+ cidrv6: "interval IPv6",
+ base64: "\u0219ir codat base64",
+ base64url: "\u0219ir codat base64url",
+ json_string: "\u0219ir JSON",
+ e164: "num\u0103r E.164",
+ jwt: "JWT",
+ template_literal: "intrare"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ string: "\u0219ir",
+ number: "num\u0103r",
+ boolean: "boolean",
+ function: "func\u021Bie",
+ array: "matrice",
+ object: "obiect",
+ undefined: "nedefinit",
+ symbol: "simbol",
+ bigint: "num\u0103r mare",
+ void: "void",
+ never: "never",
+ map: "hart\u0103",
+ set: "set"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ return `Intrare invalid\u0103: a\u0219teptat ${expected}, primit ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `Intrare invalid\u0103: a\u0219teptat ${stringifyPrimitive(issue2.values[0])}`;
+ return `Op\u021Biune invalid\u0103: a\u0219teptat una dintre ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `Prea mare: a\u0219teptat ca ${issue2.origin ?? "valoarea"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemente"}`;
+ return `Prea mare: a\u0219teptat ca ${issue2.origin ?? "valoarea"} s\u0103 fie ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `Prea mic: a\u0219teptat ca ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
+ }
+ return `Prea mic: a\u0219teptat ca ${issue2.origin} s\u0103 fie ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with") {
+ return `\u0218ir invalid: trebuie s\u0103 \xEEnceap\u0103 cu "${_issue.prefix}"`;
+ }
+ if (_issue.format === "ends_with")
+ return `\u0218ir invalid: trebuie s\u0103 se termine cu "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `\u0218ir invalid: trebuie s\u0103 includ\u0103 "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `\u0218ir invalid: trebuie s\u0103 se potriveasc\u0103 cu modelul ${_issue.pattern}`;
+ return `Format invalid: ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `Num\u0103r invalid: trebuie s\u0103 fie multiplu de ${issue2.divisor}`;
+ case "unrecognized_keys":
+ return `Chei nerecunoscute: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `Cheie invalid\u0103 \xEEn ${issue2.origin}`;
+ case "invalid_union":
+ return "Intrare invalid\u0103";
+ case "invalid_element":
+ return `Valoare invalid\u0103 \xEEn ${issue2.origin}`;
+ default:
+ return `Intrare invalid\u0103`;
+ }
+ };
+}, "error");
+function ro_default() {
+ return {
+ localeError: error37()
+ };
+}
+__name(ro_default, "default");
+
+// node_modules/zod/v4/locales/ru.js
+init_esbuild_shims();
+function getRussianPlural(count, one, few, many) {
+ const absCount = Math.abs(count);
+ const lastDigit = absCount % 10;
+ const lastTwoDigits = absCount % 100;
+ if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
+ return many;
+ }
+ if (lastDigit === 1) {
+ return one;
+ }
+ if (lastDigit >= 2 && lastDigit <= 4) {
+ return few;
+ }
+ return many;
+}
+__name(getRussianPlural, "getRussianPlural");
+var error38 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: {
+ unit: {
+ one: "\u0441\u0438\u043C\u0432\u043E\u043B",
+ few: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430",
+ many: "\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432"
+ },
+ verb: "\u0438\u043C\u0435\u0442\u044C"
+ },
+ file: {
+ unit: {
+ one: "\u0431\u0430\u0439\u0442",
+ few: "\u0431\u0430\u0439\u0442\u0430",
+ many: "\u0431\u0430\u0439\u0442"
+ },
+ verb: "\u0438\u043C\u0435\u0442\u044C"
+ },
+ array: {
+ unit: {
+ one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442",
+ few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",
+ many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"
+ },
+ verb: "\u0438\u043C\u0435\u0442\u044C"
+ },
+ set: {
+ unit: {
+ one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442",
+ few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",
+ many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"
+ },
+ verb: "\u0438\u043C\u0435\u0442\u044C"
+ }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "\u0432\u0432\u043E\u0434",
+ email: "email \u0430\u0434\u0440\u0435\u0441",
+ url: "URL",
+ emoji: "\u044D\u043C\u043E\u0434\u0437\u0438",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F",
+ date: "ISO \u0434\u0430\u0442\u0430",
+ time: "ISO \u0432\u0440\u0435\u043C\u044F",
+ duration: "ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",
+ ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441",
+ ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441",
+ cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",
+ cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",
+ base64: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64",
+ base64url: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url",
+ json_string: "JSON \u0441\u0442\u0440\u043E\u043A\u0430",
+ e164: "\u043D\u043E\u043C\u0435\u0440 E.164",
+ jwt: "JWT",
+ template_literal: "\u0432\u0432\u043E\u0434"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "\u0447\u0438\u0441\u043B\u043E",
+ array: "\u043C\u0430\u0441\u0441\u0438\u0432"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`;
+ }
+ return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${stringifyPrimitive(issue2.values[0])}`;
+ return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ const maxValue = Number(issue2.maximum);
+ const unit = getRussianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
+ return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.maximum.toString()} ${unit}`;
+ }
+ return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ const minValue = Number(issue2.minimum);
+ const unit = getRussianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
+ return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.minimum.toString()} ${unit}`;
+ }
+ return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with")
+ return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${_issue.prefix}"`;
+ if (_issue.format === "ends_with")
+ return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`;
+ return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`;
+ case "unrecognized_keys":
+ return `\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${issue2.keys.length > 1 ? "\u044B\u0435" : "\u044B\u0439"} \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0438" : ""}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`;
+ case "invalid_union":
+ return "\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435";
+ case "invalid_element":
+ return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${issue2.origin}`;
+ default:
+ return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435`;
+ }
+ };
+}, "error");
+function ru_default() {
+ return {
+ localeError: error38()
+ };
+}
+__name(ru_default, "default");
+
+// node_modules/zod/v4/locales/sl.js
+init_esbuild_shims();
+var error39 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "znakov", verb: "imeti" },
+ file: { unit: "bajtov", verb: "imeti" },
+ array: { unit: "elementov", verb: "imeti" },
+ set: { unit: "elementov", verb: "imeti" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "vnos",
+ email: "e-po\u0161tni naslov",
+ url: "URL",
+ emoji: "emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "ISO datum in \u010Das",
+ date: "ISO datum",
+ time: "ISO \u010Das",
+ duration: "ISO trajanje",
+ ipv4: "IPv4 naslov",
+ ipv6: "IPv6 naslov",
+ cidrv4: "obseg IPv4",
+ cidrv6: "obseg IPv6",
+ base64: "base64 kodiran niz",
+ base64url: "base64url kodiran niz",
+ json_string: "JSON niz",
+ e164: "E.164 \u0161tevilka",
+ jwt: "JWT",
+ template_literal: "vnos"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "\u0161tevilo",
+ array: "tabela"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `Neveljaven vnos: pri\u010Dakovano instanceof ${issue2.expected}, prejeto ${received}`;
+ }
+ return `Neveljaven vnos: pri\u010Dakovano ${expected}, prejeto ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `Neveljaven vnos: pri\u010Dakovano ${stringifyPrimitive(issue2.values[0])}`;
+ return `Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `Preveliko: pri\u010Dakovano, da bo ${issue2.origin ?? "vrednost"} imelo ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementov"}`;
+ return `Preveliko: pri\u010Dakovano, da bo ${issue2.origin ?? "vrednost"} ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} imelo ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
+ }
+ return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with") {
+ return `Neveljaven niz: mora se za\u010Deti z "${_issue.prefix}"`;
+ }
+ if (_issue.format === "ends_with")
+ return `Neveljaven niz: mora se kon\u010Dati z "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `Neveljaven niz: mora vsebovati "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`;
+ return `Neveljaven ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${issue2.divisor}`;
+ case "unrecognized_keys":
+ return `Neprepoznan${issue2.keys.length > 1 ? "i klju\u010Di" : " klju\u010D"}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `Neveljaven klju\u010D v ${issue2.origin}`;
+ case "invalid_union":
+ return "Neveljaven vnos";
+ case "invalid_element":
+ return `Neveljavna vrednost v ${issue2.origin}`;
+ default:
+ return "Neveljaven vnos";
+ }
+ };
+}, "error");
+function sl_default() {
+ return {
+ localeError: error39()
+ };
+}
+__name(sl_default, "default");
+
+// node_modules/zod/v4/locales/sv.js
+init_esbuild_shims();
+var error40 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "tecken", verb: "att ha" },
+ file: { unit: "bytes", verb: "att ha" },
+ array: { unit: "objekt", verb: "att inneh\xE5lla" },
+ set: { unit: "objekt", verb: "att inneh\xE5lla" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "regulj\xE4rt uttryck",
+ email: "e-postadress",
+ url: "URL",
+ emoji: "emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "ISO-datum och tid",
+ date: "ISO-datum",
+ time: "ISO-tid",
+ duration: "ISO-varaktighet",
+ ipv4: "IPv4-intervall",
+ ipv6: "IPv6-intervall",
+ cidrv4: "IPv4-spektrum",
+ cidrv6: "IPv6-spektrum",
+ base64: "base64-kodad str\xE4ng",
+ base64url: "base64url-kodad str\xE4ng",
+ json_string: "JSON-str\xE4ng",
+ e164: "E.164-nummer",
+ jwt: "JWT",
+ template_literal: "mall-literal"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "antal",
+ array: "lista"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `Ogiltig inmatning: f\xF6rv\xE4ntat instanceof ${issue2.expected}, fick ${received}`;
+ }
+ return `Ogiltig inmatning: f\xF6rv\xE4ntat ${expected}, fick ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `Ogiltig inmatning: f\xF6rv\xE4ntat ${stringifyPrimitive(issue2.values[0])}`;
+ return `Ogiltigt val: f\xF6rv\xE4ntade en av ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `F\xF6r stor(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`;
+ }
+ return `F\xF6r stor(t): f\xF6rv\xE4ntat ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
+ }
+ return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with") {
+ return `Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${_issue.prefix}"`;
+ }
+ if (_issue.format === "ends_with")
+ return `Ogiltig str\xE4ng: m\xE5ste sluta med "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${_issue.pattern}"`;
+ return `Ogiltig(t) ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `Ogiltigt tal: m\xE5ste vara en multipel av ${issue2.divisor}`;
+ case "unrecognized_keys":
+ return `${issue2.keys.length > 1 ? "Ok\xE4nda nycklar" : "Ok\xE4nd nyckel"}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `Ogiltig nyckel i ${issue2.origin ?? "v\xE4rdet"}`;
+ case "invalid_union":
+ return "Ogiltig input";
+ case "invalid_element":
+ return `Ogiltigt v\xE4rde i ${issue2.origin ?? "v\xE4rdet"}`;
+ default:
+ return `Ogiltig input`;
+ }
+ };
+}, "error");
+function sv_default() {
+ return {
+ localeError: error40()
+ };
+}
+__name(sv_default, "default");
+
+// node_modules/zod/v4/locales/ta.js
+init_esbuild_shims();
+var error41 = /* @__PURE__ */ __name(() => {
+ 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" },
+ array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" },
+ set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1",
+ email: "\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",
+ url: "URL",
+ emoji: "emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",
+ date: "ISO \u0BA4\u0BC7\u0BA4\u0BBF",
+ time: "ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",
+ duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1",
+ ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",
+ ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",
+ cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",
+ cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",
+ base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD",
+ base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD",
+ json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD",
+ e164: "E.164 \u0B8E\u0BA3\u0BCD",
+ jwt: "JWT",
+ template_literal: "input"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "\u0B8E\u0BA3\u0BCD",
+ array: "\u0B85\u0BA3\u0BBF",
+ null: "\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 instanceof ${issue2.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`;
+ }
+ return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${stringifyPrimitive(issue2.values[0])}`;
+ return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${joinValues(issue2.values, "|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
+ }
+ return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
+ }
+ return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with")
+ return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
+ if (_issue.format === "ends_with")
+ return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
+ if (_issue.format === "includes")
+ return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
+ if (_issue.format === "regex")
+ return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${_issue.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
+ return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${issue2.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
+ case "unrecognized_keys":
+ return `\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${issue2.keys.length > 1 ? "\u0B95\u0BB3\u0BCD" : ""}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;
+ case "invalid_union":
+ return "\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1";
+ case "invalid_element":
+ return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;
+ default:
+ return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1`;
+ }
+ };
+}, "error");
+function ta_default() {
+ return {
+ localeError: error41()
+ };
+}
+__name(ta_default, "default");
+
+// node_modules/zod/v4/locales/th.js
+init_esbuild_shims();
+var error42 = /* @__PURE__ */ __name(() => {
+ 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" },
+ array: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" },
+ set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19",
+ email: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25",
+ url: "URL",
+ emoji: "\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",
+ date: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO",
+ time: "\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",
+ duration: "\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",
+ ipv4: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4",
+ ipv6: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6",
+ cidrv4: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4",
+ cidrv6: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6",
+ base64: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64",
+ base64url: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL",
+ json_string: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON",
+ e164: "\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)",
+ jwt: "\u0E42\u0E17\u0E40\u0E04\u0E19 JWT",
+ template_literal: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02",
+ array: "\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)",
+ null: "\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 instanceof ${issue2.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`;
+ }
+ return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${stringifyPrimitive(issue2.values[0])}`;
+ return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19" : "\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`;
+ return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? "\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22" : "\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
+ }
+ return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with") {
+ return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${_issue.prefix}"`;
+ }
+ if (_issue.format === "ends_with")
+ return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${_issue.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`;
+ if (_issue.format === "regex")
+ return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${_issue.pattern}`;
+ return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${issue2.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`;
+ case "unrecognized_keys":
+ return `\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`;
+ case "invalid_union":
+ return "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49";
+ case "invalid_element":
+ return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`;
+ default:
+ return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07`;
+ }
+ };
+}, "error");
+function th_default() {
+ return {
+ localeError: error42()
+ };
+}
+__name(th_default, "default");
+
+// node_modules/zod/v4/locales/tr.js
+init_esbuild_shims();
+var error43 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "karakter", verb: "olmal\u0131" },
+ file: { unit: "bayt", verb: "olmal\u0131" },
+ array: { unit: "\xF6\u011Fe", verb: "olmal\u0131" },
+ set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "girdi",
+ email: "e-posta adresi",
+ url: "URL",
+ emoji: "emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "ISO tarih ve saat",
+ date: "ISO tarih",
+ time: "ISO saat",
+ duration: "ISO s\xFCre",
+ ipv4: "IPv4 adresi",
+ ipv6: "IPv6 adresi",
+ cidrv4: "IPv4 aral\u0131\u011F\u0131",
+ cidrv6: "IPv6 aral\u0131\u011F\u0131",
+ base64: "base64 ile \u015Fifrelenmi\u015F metin",
+ base64url: "base64url ile \u015Fifrelenmi\u015F metin",
+ json_string: "JSON dizesi",
+ e164: "E.164 say\u0131s\u0131",
+ jwt: "JWT",
+ template_literal: "\u015Eablon dizesi"
+ };
+ const TypeDictionary = {
+ nan: "NaN"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `Ge\xE7ersiz de\u011Fer: beklenen instanceof ${issue2.expected}, al\u0131nan ${received}`;
+ }
+ return `Ge\xE7ersiz de\u011Fer: beklenen ${expected}, al\u0131nan ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `Ge\xE7ersiz de\u011Fer: beklenen ${stringifyPrimitive(issue2.values[0])}`;
+ return `Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin ?? "de\u011Fer"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\xF6\u011Fe"}`;
+ return `\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin ?? "de\u011Fer"} ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
+ return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with")
+ return `Ge\xE7ersiz metin: "${_issue.prefix}" ile ba\u015Flamal\u0131`;
+ if (_issue.format === "ends_with")
+ return `Ge\xE7ersiz metin: "${_issue.suffix}" ile bitmeli`;
+ if (_issue.format === "includes")
+ return `Ge\xE7ersiz metin: "${_issue.includes}" i\xE7ermeli`;
+ if (_issue.format === "regex")
+ return `Ge\xE7ersiz metin: ${_issue.pattern} desenine uymal\u0131`;
+ return `Ge\xE7ersiz ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `Ge\xE7ersiz say\u0131: ${issue2.divisor} ile tam b\xF6l\xFCnebilmeli`;
+ case "unrecognized_keys":
+ return `Tan\u0131nmayan anahtar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `${issue2.origin} i\xE7inde ge\xE7ersiz anahtar`;
+ case "invalid_union":
+ return "Ge\xE7ersiz de\u011Fer";
+ case "invalid_element":
+ return `${issue2.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;
+ default:
+ return `Ge\xE7ersiz de\u011Fer`;
+ }
+ };
+}, "error");
+function tr_default() {
+ return {
+ localeError: error43()
+ };
+}
+__name(tr_default, "default");
+
+// node_modules/zod/v4/locales/ua.js
+init_esbuild_shims();
+
+// node_modules/zod/v4/locales/uk.js
+init_esbuild_shims();
+var error44 = /* @__PURE__ */ __name(() => {
+ 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" },
+ array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" },
+ set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456",
+ email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438",
+ url: "URL",
+ emoji: "\u0435\u043C\u043E\u0434\u0437\u0456",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO",
+ date: "\u0434\u0430\u0442\u0430 ISO",
+ time: "\u0447\u0430\u0441 ISO",
+ duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO",
+ ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4",
+ ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6",
+ cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4",
+ cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6",
+ base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64",
+ base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url",
+ json_string: "\u0440\u044F\u0434\u043E\u043A JSON",
+ e164: "\u043D\u043E\u043C\u0435\u0440 E.164",
+ jwt: "JWT",
+ template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "\u0447\u0438\u0441\u043B\u043E",
+ array: "\u043C\u0430\u0441\u0438\u0432"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F instanceof ${issue2.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`;
+ }
+ return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`;
+ return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`;
+ return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
+ }
+ return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} \u0431\u0443\u0434\u0435 ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with")
+ return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${_issue.prefix}"`;
+ if (_issue.format === "ends_with")
+ return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`;
+ return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${issue2.divisor}`;
+ case "unrecognized_keys":
+ return `\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0456" : ""}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`;
+ case "invalid_union":
+ return "\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456";
+ case "invalid_element":
+ return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${issue2.origin}`;
+ default:
+ return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456`;
+ }
+ };
+}, "error");
+function uk_default() {
+ return {
+ localeError: error44()
+ };
+}
+__name(uk_default, "default");
+
+// node_modules/zod/v4/locales/ua.js
+function ua_default() {
+ return uk_default();
+}
+__name(ua_default, "default");
+
+// node_modules/zod/v4/locales/ur.js
+init_esbuild_shims();
+var error45 = /* @__PURE__ */ __name(() => {
+ 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" },
+ array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" },
+ set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "\u0627\u0646 \u067E\u0679",
+ email: "\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633",
+ url: "\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644",
+ emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC",
+ uuid: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",
+ uuidv4: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4",
+ uuidv6: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6",
+ nanoid: "\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC",
+ guid: "\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",
+ cuid: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",
+ cuid2: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2",
+ ulid: "\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC",
+ xid: "\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC",
+ ksuid: "\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",
+ datetime: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645",
+ date: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E",
+ time: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A",
+ duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A",
+ ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633",
+ ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633",
+ cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C",
+ cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C",
+ base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",
+ base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",
+ json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF",
+ e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631",
+ jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC",
+ template_literal: "\u0627\u0646 \u067E\u0679"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "\u0646\u0645\u0628\u0631",
+ array: "\u0622\u0631\u06D2",
+ null: "\u0646\u0644"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${issue2.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;
+ }
+ return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${stringifyPrimitive(issue2.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
+ return `\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${joinValues(issue2.values, "|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;
+ return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${adj}${issue2.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u06D2 ${adj}${issue2.minimum.toString()} ${sizing.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;
+ }
+ return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u0627 ${adj}${issue2.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with") {
+ return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
+ }
+ if (_issue.format === "ends_with")
+ return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
+ if (_issue.format === "includes")
+ return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
+ if (_issue.format === "regex")
+ return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${_issue.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
+ return `\u063A\u0644\u0637 ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${issue2.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
+ case "unrecognized_keys":
+ return `\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${issue2.keys.length > 1 ? "\u0632" : ""}: ${joinValues(issue2.keys, "\u060C ")}`;
+ case "invalid_key":
+ return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;
+ case "invalid_union":
+ return "\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";
+ case "invalid_element":
+ return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;
+ default:
+ return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679`;
+ }
+ };
+}, "error");
+function ur_default() {
+ return {
+ localeError: error45()
+ };
+}
+__name(ur_default, "default");
+
+// node_modules/zod/v4/locales/uz.js
+init_esbuild_shims();
+var error46 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "belgi", verb: "bo\u2018lishi kerak" },
+ file: { unit: "bayt", verb: "bo\u2018lishi kerak" },
+ array: { unit: "element", verb: "bo\u2018lishi kerak" },
+ set: { unit: "element", verb: "bo\u2018lishi kerak" },
+ map: { unit: "yozuv", verb: "bo\u2018lishi kerak" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "kirish",
+ email: "elektron pochta manzili",
+ url: "URL",
+ emoji: "emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "ISO sana va vaqti",
+ date: "ISO sana",
+ time: "ISO vaqt",
+ duration: "ISO davomiylik",
+ ipv4: "IPv4 manzil",
+ ipv6: "IPv6 manzil",
+ mac: "MAC manzil",
+ cidrv4: "IPv4 diapazon",
+ cidrv6: "IPv6 diapazon",
+ base64: "base64 kodlangan satr",
+ base64url: "base64url kodlangan satr",
+ json_string: "JSON satr",
+ e164: "E.164 raqam",
+ jwt: "JWT",
+ template_literal: "kirish"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "raqam",
+ array: "massiv"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `Noto\u2018g\u2018ri kirish: kutilgan instanceof ${issue2.expected}, qabul qilingan ${received}`;
+ }
+ return `Noto\u2018g\u2018ri kirish: kutilgan ${expected}, qabul qilingan ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `Noto\u2018g\u2018ri kirish: kutilgan ${stringifyPrimitive(issue2.values[0])}`;
+ return `Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `Juda katta: kutilgan ${issue2.origin ?? "qiymat"} ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`;
+ return `Juda katta: kutilgan ${issue2.origin ?? "qiymat"} ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`;
+ }
+ return `Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with")
+ return `Noto\u2018g\u2018ri satr: "${_issue.prefix}" bilan boshlanishi kerak`;
+ if (_issue.format === "ends_with")
+ return `Noto\u2018g\u2018ri satr: "${_issue.suffix}" bilan tugashi kerak`;
+ if (_issue.format === "includes")
+ return `Noto\u2018g\u2018ri satr: "${_issue.includes}" ni o\u2018z ichiga olishi kerak`;
+ if (_issue.format === "regex")
+ return `Noto\u2018g\u2018ri satr: ${_issue.pattern} shabloniga mos kelishi kerak`;
+ return `Noto\u2018g\u2018ri ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `Noto\u2018g\u2018ri raqam: ${issue2.divisor} ning karralisi bo\u2018lishi kerak`;
+ case "unrecognized_keys":
+ return `Noma\u2019lum kalit${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `${issue2.origin} dagi kalit noto\u2018g\u2018ri`;
+ case "invalid_union":
+ return "Noto\u2018g\u2018ri kirish";
+ case "invalid_element":
+ return `${issue2.origin} da noto\u2018g\u2018ri qiymat`;
+ default:
+ return `Noto\u2018g\u2018ri kirish`;
+ }
+ };
+}, "error");
+function uz_default() {
+ return {
+ localeError: error46()
+ };
+}
+__name(uz_default, "default");
+
+// node_modules/zod/v4/locales/vi.js
+init_esbuild_shims();
+var error47 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" },
+ file: { unit: "byte", verb: "c\xF3" },
+ array: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" },
+ set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "\u0111\u1EA7u v\xE0o",
+ email: "\u0111\u1ECBa ch\u1EC9 email",
+ url: "URL",
+ emoji: "emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "ng\xE0y gi\u1EDD ISO",
+ date: "ng\xE0y ISO",
+ time: "gi\u1EDD ISO",
+ duration: "kho\u1EA3ng th\u1EDDi gian ISO",
+ ipv4: "\u0111\u1ECBa ch\u1EC9 IPv4",
+ ipv6: "\u0111\u1ECBa ch\u1EC9 IPv6",
+ cidrv4: "d\u1EA3i IPv4",
+ cidrv6: "d\u1EA3i IPv6",
+ base64: "chu\u1ED7i m\xE3 h\xF3a base64",
+ base64url: "chu\u1ED7i m\xE3 h\xF3a base64url",
+ json_string: "chu\u1ED7i JSON",
+ e164: "s\u1ED1 E.164",
+ jwt: "JWT",
+ template_literal: "\u0111\u1EA7u v\xE0o"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "s\u1ED1",
+ array: "m\u1EA3ng"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${issue2.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`;
+ }
+ return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${stringifyPrimitive(issue2.values[0])}`;
+ return `T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin ?? "gi\xE1 tr\u1ECB"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "ph\u1EA7n t\u1EED"}`;
+ return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin ?? "gi\xE1 tr\u1ECB"} ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
+ }
+ return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with")
+ return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${_issue.prefix}"`;
+ if (_issue.format === "ends_with")
+ return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${_issue.pattern}`;
+ return `${FormatDictionary[_issue.format] ?? issue2.format} kh\xF4ng h\u1EE3p l\u1EC7`;
+ }
+ case "not_multiple_of":
+ return `S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${issue2.divisor}`;
+ case "unrecognized_keys":
+ return `Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`;
+ case "invalid_union":
+ return "\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7";
+ case "invalid_element":
+ return `Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`;
+ default:
+ return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7`;
+ }
+ };
+}, "error");
+function vi_default() {
+ return {
+ localeError: error47()
+ };
+}
+__name(vi_default, "default");
+
+// node_modules/zod/v4/locales/zh-CN.js
+init_esbuild_shims();
+var error48 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" },
+ file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" },
+ array: { unit: "\u9879", verb: "\u5305\u542B" },
+ set: { unit: "\u9879", verb: "\u5305\u542B" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "\u8F93\u5165",
+ email: "\u7535\u5B50\u90AE\u4EF6",
+ url: "URL",
+ emoji: "\u8868\u60C5\u7B26\u53F7",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "ISO\u65E5\u671F\u65F6\u95F4",
+ date: "ISO\u65E5\u671F",
+ time: "ISO\u65F6\u95F4",
+ duration: "ISO\u65F6\u957F",
+ ipv4: "IPv4\u5730\u5740",
+ ipv6: "IPv6\u5730\u5740",
+ cidrv4: "IPv4\u7F51\u6BB5",
+ cidrv6: "IPv6\u7F51\u6BB5",
+ base64: "base64\u7F16\u7801\u5B57\u7B26\u4E32",
+ base64url: "base64url\u7F16\u7801\u5B57\u7B26\u4E32",
+ json_string: "JSON\u5B57\u7B26\u4E32",
+ e164: "E.164\u53F7\u7801",
+ jwt: "JWT",
+ template_literal: "\u8F93\u5165"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "\u6570\u5B57",
+ array: "\u6570\u7EC4",
+ null: "\u7A7A\u503C(null)"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${issue2.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`;
+ }
+ return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${stringifyPrimitive(issue2.values[0])}`;
+ return `\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin ?? "\u503C"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u4E2A\u5143\u7D20"}`;
+ return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin ?? "\u503C"} ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
+ }
+ return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with")
+ return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.prefix}" \u5F00\u5934`;
+ if (_issue.format === "ends_with")
+ return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.suffix}" \u7ED3\u5C3E`;
+ if (_issue.format === "includes")
+ return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${_issue.pattern}`;
+ return `\u65E0\u6548${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${issue2.divisor} \u7684\u500D\u6570`;
+ case "unrecognized_keys":
+ return `\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `${issue2.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;
+ case "invalid_union":
+ return "\u65E0\u6548\u8F93\u5165";
+ case "invalid_element":
+ return `${issue2.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;
+ default:
+ return `\u65E0\u6548\u8F93\u5165`;
+ }
+ };
+}, "error");
+function zh_CN_default() {
+ return {
+ localeError: error48()
+ };
+}
+__name(zh_CN_default, "default");
+
+// node_modules/zod/v4/locales/zh-TW.js
+init_esbuild_shims();
+var error49 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" },
+ file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" },
+ array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" },
+ set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "\u8F38\u5165",
+ email: "\u90F5\u4EF6\u5730\u5740",
+ url: "URL",
+ emoji: "emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "ISO \u65E5\u671F\u6642\u9593",
+ date: "ISO \u65E5\u671F",
+ time: "ISO \u6642\u9593",
+ duration: "ISO \u671F\u9593",
+ ipv4: "IPv4 \u4F4D\u5740",
+ ipv6: "IPv6 \u4F4D\u5740",
+ cidrv4: "IPv4 \u7BC4\u570D",
+ cidrv6: "IPv6 \u7BC4\u570D",
+ base64: "base64 \u7DE8\u78BC\u5B57\u4E32",
+ base64url: "base64url \u7DE8\u78BC\u5B57\u4E32",
+ json_string: "JSON \u5B57\u4E32",
+ e164: "E.164 \u6578\u503C",
+ jwt: "JWT",
+ template_literal: "\u8F38\u5165"
+ };
+ const TypeDictionary = {
+ nan: "NaN"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${issue2.expected}\uFF0C\u4F46\u6536\u5230 ${received}`;
+ }
+ return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${expected}\uFF0C\u4F46\u6536\u5230 ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${stringifyPrimitive(issue2.values[0])}`;
+ return `\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u500B\u5143\u7D20"}`;
+ return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing) {
+ return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
+ }
+ return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with") {
+ return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.prefix}" \u958B\u982D`;
+ }
+ if (_issue.format === "ends_with")
+ return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.suffix}" \u7D50\u5C3E`;
+ if (_issue.format === "includes")
+ return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${_issue.pattern}`;
+ return `\u7121\u6548\u7684 ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${issue2.divisor} \u7684\u500D\u6578`;
+ case "unrecognized_keys":
+ return `\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${issue2.keys.length > 1 ? "\u5011" : ""}\uFF1A${joinValues(issue2.keys, "\u3001")}`;
+ case "invalid_key":
+ return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;
+ case "invalid_union":
+ return "\u7121\u6548\u7684\u8F38\u5165\u503C";
+ case "invalid_element":
+ return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;
+ default:
+ return `\u7121\u6548\u7684\u8F38\u5165\u503C`;
+ }
+ };
+}, "error");
+function zh_TW_default() {
+ return {
+ localeError: error49()
+ };
+}
+__name(zh_TW_default, "default");
+
+// node_modules/zod/v4/locales/yo.js
+init_esbuild_shims();
+var error50 = /* @__PURE__ */ __name(() => {
+ const Sizable = {
+ string: { unit: "\xE0mi", verb: "n\xED" },
+ file: { unit: "bytes", verb: "n\xED" },
+ array: { unit: "nkan", verb: "n\xED" },
+ set: { unit: "nkan", verb: "n\xED" }
+ };
+ function getSizing(origin) {
+ return Sizable[origin] ?? null;
+ }
+ __name(getSizing, "getSizing");
+ const FormatDictionary = {
+ regex: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9",
+ email: "\xE0d\xEDr\u1EB9\u0301s\xEC \xECm\u1EB9\u0301l\xEC",
+ url: "URL",
+ emoji: "emoji",
+ uuid: "UUID",
+ uuidv4: "UUIDv4",
+ uuidv6: "UUIDv6",
+ nanoid: "nanoid",
+ guid: "GUID",
+ cuid: "cuid",
+ cuid2: "cuid2",
+ ulid: "ULID",
+ xid: "XID",
+ ksuid: "KSUID",
+ datetime: "\xE0k\xF3k\xF2 ISO",
+ date: "\u1ECDj\u1ECD\u0301 ISO",
+ time: "\xE0k\xF3k\xF2 ISO",
+ duration: "\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO",
+ ipv4: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv4",
+ ipv6: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv6",
+ cidrv4: "\xE0gb\xE8gb\xE8 IPv4",
+ cidrv6: "\xE0gb\xE8gb\xE8 IPv6",
+ base64: "\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64",
+ base64url: "\u1ECD\u0300r\u1ECD\u0300 base64url",
+ json_string: "\u1ECD\u0300r\u1ECD\u0300 JSON",
+ e164: "n\u1ECD\u0301mb\xE0 E.164",
+ jwt: "JWT",
+ template_literal: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9"
+ };
+ const TypeDictionary = {
+ nan: "NaN",
+ number: "n\u1ECD\u0301mb\xE0",
+ array: "akop\u1ECD"
+ };
+ return (issue2) => {
+ switch (issue2.code) {
+ case "invalid_type": {
+ const expected = TypeDictionary[issue2.expected] ?? issue2.expected;
+ const receivedType = parsedType(issue2.input);
+ const received = TypeDictionary[receivedType] ?? receivedType;
+ if (/^[A-Z]/.test(issue2.expected)) {
+ return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi instanceof ${issue2.expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`;
+ }
+ return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`;
+ }
+ case "invalid_value":
+ if (issue2.values.length === 1)
+ return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${stringifyPrimitive(issue2.values[0])}`;
+ return `\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${joinValues(issue2.values, "|")}`;
+ case "too_big": {
+ const adj = issue2.inclusive ? "<=" : "<";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue2.origin ?? "iye"} ${sizing.verb} ${adj}${issue2.maximum} ${sizing.unit}`;
+ return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.maximum}`;
+ }
+ case "too_small": {
+ const adj = issue2.inclusive ? ">=" : ">";
+ const sizing = getSizing(issue2.origin);
+ if (sizing)
+ return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum} ${sizing.unit}`;
+ return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.minimum}`;
+ }
+ case "invalid_format": {
+ const _issue = issue2;
+ if (_issue.format === "starts_with")
+ return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u1EB9\u0300r\u1EB9\u0300 p\u1EB9\u0300l\xFA "${_issue.prefix}"`;
+ if (_issue.format === "ends_with")
+ return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\xED p\u1EB9\u0300l\xFA "${_issue.suffix}"`;
+ if (_issue.format === "includes")
+ return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\xED "${_issue.includes}"`;
+ if (_issue.format === "regex")
+ return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\xE1 \xE0p\u1EB9\u1EB9r\u1EB9 mu ${_issue.pattern}`;
+ return `A\u1E63\xEC\u1E63e: ${FormatDictionary[_issue.format] ?? issue2.format}`;
+ }
+ case "not_multiple_of":
+ return `N\u1ECD\u0301mb\xE0 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 j\u1EB9\u0301 \xE8y\xE0 p\xEDp\xEDn ti ${issue2.divisor}`;
+ case "unrecognized_keys":
+ return `B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${joinValues(issue2.keys, ", ")}`;
+ case "invalid_key":
+ return `B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`;
+ case "invalid_union":
+ return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e";
+ case "invalid_element":
+ return `Iye a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`;
+ default:
+ return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e";
+ }
+ };
+}, "error");
+function yo_default() {
+ return {
+ localeError: error50()
+ };
+}
+__name(yo_default, "default");
+
+// node_modules/zod/v4/core/registries.js
+init_esbuild_shims();
+var _a2;
+var $output = /* @__PURE__ */ Symbol("ZodOutput");
+var $input = /* @__PURE__ */ Symbol("ZodInput");
+var $ZodRegistry = class {
+ static {
+ __name(this, "$ZodRegistry");
+ }
+ constructor() {
+ this._map = /* @__PURE__ */ new WeakMap();
+ this._idmap = /* @__PURE__ */ new Map();
+ }
+ add(schema, ..._meta) {
+ const meta3 = _meta[0];
+ this._map.set(schema, meta3);
+ if (meta3 && typeof meta3 === "object" && "id" in meta3) {
+ this._idmap.set(meta3.id, schema);
+ }
+ return this;
+ }
+ clear() {
+ this._map = /* @__PURE__ */ new WeakMap();
+ this._idmap = /* @__PURE__ */ new Map();
+ return this;
+ }
+ remove(schema) {
+ const meta3 = this._map.get(schema);
+ if (meta3 && typeof meta3 === "object" && "id" in meta3) {
+ this._idmap.delete(meta3.id);
+ }
+ this._map.delete(schema);
+ return this;
+ }
+ get(schema) {
+ const p = schema._zod.parent;
+ if (p) {
+ const pm = { ...this.get(p) ?? {} };
+ delete pm.id;
+ const f = { ...pm, ...this._map.get(schema) };
+ return Object.keys(f).length ? f : void 0;
+ }
+ return this._map.get(schema);
+ }
+ has(schema) {
+ return this._map.has(schema);
+ }
+};
+function registry() {
+ return new $ZodRegistry();
+}
+__name(registry, "registry");
+(_a2 = globalThis).__zod_globalRegistry ?? (_a2.__zod_globalRegistry = registry());
+var globalRegistry = globalThis.__zod_globalRegistry;
+
+// node_modules/zod/v4/core/api.js
+init_esbuild_shims();
+// @__NO_SIDE_EFFECTS__
+function _string(Class2, params) {
+ return new Class2({
+ type: "string",
+ ...normalizeParams(params)
+ });
+}
+__name(_string, "_string");
+// @__NO_SIDE_EFFECTS__
+function _coercedString(Class2, params) {
+ return new Class2({
+ type: "string",
+ coerce: true,
+ ...normalizeParams(params)
+ });
+}
+__name(_coercedString, "_coercedString");
+// @__NO_SIDE_EFFECTS__
+function _email(Class2, params) {
+ return new Class2({
+ type: "string",
+ format: "email",
+ check: "string_format",
+ abort: false,
+ ...normalizeParams(params)
+ });
+}
+__name(_email, "_email");
+// @__NO_SIDE_EFFECTS__
+function _guid(Class2, params) {
+ return new Class2({
+ type: "string",
+ format: "guid",
+ check: "string_format",
+ abort: false,
+ ...normalizeParams(params)
+ });
+}
+__name(_guid, "_guid");
+// @__NO_SIDE_EFFECTS__
+function _uuid(Class2, params) {
+ return new Class2({
+ type: "string",
+ format: "uuid",
+ check: "string_format",
+ abort: false,
+ ...normalizeParams(params)
+ });
+}
+__name(_uuid, "_uuid");
+// @__NO_SIDE_EFFECTS__
+function _uuidv4(Class2, params) {
+ return new Class2({
+ type: "string",
+ format: "uuid",
+ check: "string_format",
+ abort: false,
+ version: "v4",
+ ...normalizeParams(params)
+ });
+}
+__name(_uuidv4, "_uuidv4");
+// @__NO_SIDE_EFFECTS__
+function _uuidv6(Class2, params) {
+ return new Class2({
+ type: "string",
+ format: "uuid",
+ check: "string_format",
+ abort: false,
+ version: "v6",
+ ...normalizeParams(params)
+ });
+}
+__name(_uuidv6, "_uuidv6");
+// @__NO_SIDE_EFFECTS__
+function _uuidv7(Class2, params) {
+ return new Class2({
+ type: "string",
+ format: "uuid",
+ check: "string_format",
+ abort: false,
+ version: "v7",
+ ...normalizeParams(params)
+ });
+}
+__name(_uuidv7, "_uuidv7");
+// @__NO_SIDE_EFFECTS__
+function _url(Class2, params) {
+ return new Class2({
+ type: "string",
+ format: "url",
+ check: "string_format",
+ abort: false,
+ ...normalizeParams(params)
+ });
+}
+__name(_url, "_url");
+// @__NO_SIDE_EFFECTS__
+function _emoji2(Class2, params) {
+ return new Class2({
+ type: "string",
+ format: "emoji",
+ check: "string_format",
+ abort: false,
+ ...normalizeParams(params)
+ });
+}
+__name(_emoji2, "_emoji");
+// @__NO_SIDE_EFFECTS__
+function _nanoid(Class2, params) {
+ return new Class2({
+ type: "string",
+ format: "nanoid",
+ check: "string_format",
+ abort: false,
+ ...normalizeParams(params)
+ });
+}
+__name(_nanoid, "_nanoid");
+// @__NO_SIDE_EFFECTS__
+function _cuid(Class2, params) {
+ return new Class2({
+ type: "string",
+ format: "cuid",
+ check: "string_format",
+ abort: false,
+ ...normalizeParams(params)
+ });
+}
+__name(_cuid, "_cuid");
+// @__NO_SIDE_EFFECTS__
+function _cuid2(Class2, params) {
+ return new Class2({
+ type: "string",
+ format: "cuid2",
+ check: "string_format",
+ abort: false,
+ ...normalizeParams(params)
+ });
+}
+__name(_cuid2, "_cuid2");
+// @__NO_SIDE_EFFECTS__
+function _ulid(Class2, params) {
+ return new Class2({
+ type: "string",
+ format: "ulid",
+ check: "string_format",
+ abort: false,
+ ...normalizeParams(params)
+ });
+}
+__name(_ulid, "_ulid");
+// @__NO_SIDE_EFFECTS__
+function _xid(Class2, params) {
+ return new Class2({
+ type: "string",
+ format: "xid",
+ check: "string_format",
+ abort: false,
+ ...normalizeParams(params)
+ });
+}
+__name(_xid, "_xid");
+// @__NO_SIDE_EFFECTS__
+function _ksuid(Class2, params) {
+ return new Class2({
+ type: "string",
+ format: "ksuid",
+ check: "string_format",
+ abort: false,
+ ...normalizeParams(params)
+ });
+}
+__name(_ksuid, "_ksuid");
+// @__NO_SIDE_EFFECTS__
+function _ipv4(Class2, params) {
+ return new Class2({
+ type: "string",
+ format: "ipv4",
+ check: "string_format",
+ abort: false,
+ ...normalizeParams(params)
+ });
+}
+__name(_ipv4, "_ipv4");
+// @__NO_SIDE_EFFECTS__
+function _ipv6(Class2, params) {
+ return new Class2({
+ type: "string",
+ format: "ipv6",
+ check: "string_format",
+ abort: false,
+ ...normalizeParams(params)
+ });
+}
+__name(_ipv6, "_ipv6");
+// @__NO_SIDE_EFFECTS__
+function _mac(Class2, params) {
+ return new Class2({
+ type: "string",
+ format: "mac",
+ check: "string_format",
+ abort: false,
+ ...normalizeParams(params)
+ });
+}
+__name(_mac, "_mac");
+// @__NO_SIDE_EFFECTS__
+function _cidrv4(Class2, params) {
+ return new Class2({
+ type: "string",
+ format: "cidrv4",
+ check: "string_format",
+ abort: false,
+ ...normalizeParams(params)
+ });
+}
+__name(_cidrv4, "_cidrv4");
+// @__NO_SIDE_EFFECTS__
+function _cidrv6(Class2, params) {
+ return new Class2({
+ type: "string",
+ format: "cidrv6",
+ check: "string_format",
+ abort: false,
+ ...normalizeParams(params)
+ });
+}
+__name(_cidrv6, "_cidrv6");
+// @__NO_SIDE_EFFECTS__
+function _base64(Class2, params) {
+ return new Class2({
+ type: "string",
+ format: "base64",
+ check: "string_format",
+ abort: false,
+ ...normalizeParams(params)
+ });
+}
+__name(_base64, "_base64");
+// @__NO_SIDE_EFFECTS__
+function _base64url(Class2, params) {
+ return new Class2({
+ type: "string",
+ format: "base64url",
+ check: "string_format",
+ abort: false,
+ ...normalizeParams(params)
+ });
+}
+__name(_base64url, "_base64url");
+// @__NO_SIDE_EFFECTS__
+function _e164(Class2, params) {
+ return new Class2({
+ type: "string",
+ format: "e164",
+ check: "string_format",
+ abort: false,
+ ...normalizeParams(params)
+ });
+}
+__name(_e164, "_e164");
+// @__NO_SIDE_EFFECTS__
+function _jwt(Class2, params) {
+ return new Class2({
+ type: "string",
+ format: "jwt",
+ check: "string_format",
+ abort: false,
+ ...normalizeParams(params)
+ });
+}
+__name(_jwt, "_jwt");
+var TimePrecision = {
+ Any: null,
+ Minute: -1,
+ Second: 0,
+ Millisecond: 3,
+ Microsecond: 6
+};
+// @__NO_SIDE_EFFECTS__
+function _isoDateTime(Class2, params) {
+ return new Class2({
+ type: "string",
+ format: "datetime",
+ check: "string_format",
+ offset: false,
+ local: false,
+ precision: null,
+ ...normalizeParams(params)
+ });
+}
+__name(_isoDateTime, "_isoDateTime");
+// @__NO_SIDE_EFFECTS__
+function _isoDate(Class2, params) {
+ return new Class2({
+ type: "string",
+ format: "date",
+ check: "string_format",
+ ...normalizeParams(params)
+ });
+}
+__name(_isoDate, "_isoDate");
+// @__NO_SIDE_EFFECTS__
+function _isoTime(Class2, params) {
+ return new Class2({
+ type: "string",
+ format: "time",
+ check: "string_format",
+ precision: null,
+ ...normalizeParams(params)
+ });
+}
+__name(_isoTime, "_isoTime");
+// @__NO_SIDE_EFFECTS__
+function _isoDuration(Class2, params) {
+ return new Class2({
+ type: "string",
+ format: "duration",
+ check: "string_format",
+ ...normalizeParams(params)
+ });
+}
+__name(_isoDuration, "_isoDuration");
+// @__NO_SIDE_EFFECTS__
+function _number(Class2, params) {
+ return new Class2({
+ type: "number",
+ checks: [],
+ ...normalizeParams(params)
+ });
+}
+__name(_number, "_number");
+// @__NO_SIDE_EFFECTS__
+function _coercedNumber(Class2, params) {
+ return new Class2({
+ type: "number",
+ coerce: true,
+ checks: [],
+ ...normalizeParams(params)
+ });
+}
+__name(_coercedNumber, "_coercedNumber");
+// @__NO_SIDE_EFFECTS__
+function _int(Class2, params) {
+ return new Class2({
+ type: "number",
+ check: "number_format",
+ abort: false,
+ format: "safeint",
+ ...normalizeParams(params)
+ });
+}
+__name(_int, "_int");
+// @__NO_SIDE_EFFECTS__
+function _float32(Class2, params) {
+ return new Class2({
+ type: "number",
+ check: "number_format",
+ abort: false,
+ format: "float32",
+ ...normalizeParams(params)
+ });
+}
+__name(_float32, "_float32");
+// @__NO_SIDE_EFFECTS__
+function _float64(Class2, params) {
+ return new Class2({
+ type: "number",
+ check: "number_format",
+ abort: false,
+ format: "float64",
+ ...normalizeParams(params)
+ });
+}
+__name(_float64, "_float64");
+// @__NO_SIDE_EFFECTS__
+function _int32(Class2, params) {
+ return new Class2({
+ type: "number",
+ check: "number_format",
+ abort: false,
+ format: "int32",
+ ...normalizeParams(params)
+ });
+}
+__name(_int32, "_int32");
+// @__NO_SIDE_EFFECTS__
+function _uint32(Class2, params) {
+ return new Class2({
+ type: "number",
+ check: "number_format",
+ abort: false,
+ format: "uint32",
+ ...normalizeParams(params)
+ });
+}
+__name(_uint32, "_uint32");
+// @__NO_SIDE_EFFECTS__
+function _boolean(Class2, params) {
+ return new Class2({
+ type: "boolean",
+ ...normalizeParams(params)
+ });
+}
+__name(_boolean, "_boolean");
+// @__NO_SIDE_EFFECTS__
+function _coercedBoolean(Class2, params) {
+ return new Class2({
+ type: "boolean",
+ coerce: true,
+ ...normalizeParams(params)
+ });
+}
+__name(_coercedBoolean, "_coercedBoolean");
+// @__NO_SIDE_EFFECTS__
+function _bigint(Class2, params) {
+ return new Class2({
+ type: "bigint",
+ ...normalizeParams(params)
+ });
+}
+__name(_bigint, "_bigint");
+// @__NO_SIDE_EFFECTS__
+function _coercedBigint(Class2, params) {
+ return new Class2({
+ type: "bigint",
+ coerce: true,
+ ...normalizeParams(params)
+ });
+}
+__name(_coercedBigint, "_coercedBigint");
+// @__NO_SIDE_EFFECTS__
+function _int64(Class2, params) {
+ return new Class2({
+ type: "bigint",
+ check: "bigint_format",
+ abort: false,
+ format: "int64",
+ ...normalizeParams(params)
+ });
+}
+__name(_int64, "_int64");
+// @__NO_SIDE_EFFECTS__
+function _uint64(Class2, params) {
+ return new Class2({
+ type: "bigint",
+ check: "bigint_format",
+ abort: false,
+ format: "uint64",
+ ...normalizeParams(params)
+ });
+}
+__name(_uint64, "_uint64");
+// @__NO_SIDE_EFFECTS__
+function _symbol(Class2, params) {
+ return new Class2({
+ type: "symbol",
+ ...normalizeParams(params)
+ });
+}
+__name(_symbol, "_symbol");
+// @__NO_SIDE_EFFECTS__
+function _undefined2(Class2, params) {
+ return new Class2({
+ type: "undefined",
+ ...normalizeParams(params)
+ });
+}
+__name(_undefined2, "_undefined");
+// @__NO_SIDE_EFFECTS__
+function _null2(Class2, params) {
+ return new Class2({
+ type: "null",
+ ...normalizeParams(params)
+ });
+}
+__name(_null2, "_null");
+// @__NO_SIDE_EFFECTS__
+function _any(Class2) {
+ return new Class2({
+ type: "any"
+ });
+}
+__name(_any, "_any");
+// @__NO_SIDE_EFFECTS__
+function _unknown(Class2) {
+ return new Class2({
+ type: "unknown"
+ });
+}
+__name(_unknown, "_unknown");
+// @__NO_SIDE_EFFECTS__
+function _never(Class2, params) {
+ return new Class2({
+ type: "never",
+ ...normalizeParams(params)
+ });
+}
+__name(_never, "_never");
+// @__NO_SIDE_EFFECTS__
+function _void(Class2, params) {
+ return new Class2({
+ type: "void",
+ ...normalizeParams(params)
+ });
+}
+__name(_void, "_void");
+// @__NO_SIDE_EFFECTS__
+function _date(Class2, params) {
+ return new Class2({
+ type: "date",
+ ...normalizeParams(params)
+ });
+}
+__name(_date, "_date");
+// @__NO_SIDE_EFFECTS__
+function _coercedDate(Class2, params) {
+ return new Class2({
+ type: "date",
+ coerce: true,
+ ...normalizeParams(params)
+ });
+}
+__name(_coercedDate, "_coercedDate");
+// @__NO_SIDE_EFFECTS__
+function _nan(Class2, params) {
+ return new Class2({
+ type: "nan",
+ ...normalizeParams(params)
+ });
+}
+__name(_nan, "_nan");
+// @__NO_SIDE_EFFECTS__
+function _lt(value, params) {
+ return new $ZodCheckLessThan({
+ check: "less_than",
+ ...normalizeParams(params),
+ value,
+ inclusive: false
+ });
+}
+__name(_lt, "_lt");
+// @__NO_SIDE_EFFECTS__
+function _lte(value, params) {
+ return new $ZodCheckLessThan({
+ check: "less_than",
+ ...normalizeParams(params),
+ value,
+ inclusive: true
+ });
+}
+__name(_lte, "_lte");
+// @__NO_SIDE_EFFECTS__
+function _gt(value, params) {
+ return new $ZodCheckGreaterThan({
+ check: "greater_than",
+ ...normalizeParams(params),
+ value,
+ inclusive: false
+ });
+}
+__name(_gt, "_gt");
+// @__NO_SIDE_EFFECTS__
+function _gte(value, params) {
+ return new $ZodCheckGreaterThan({
+ check: "greater_than",
+ ...normalizeParams(params),
+ value,
+ inclusive: true
+ });
+}
+__name(_gte, "_gte");
+// @__NO_SIDE_EFFECTS__
+function _positive(params) {
+ return /* @__PURE__ */ _gt(0, params);
+}
+__name(_positive, "_positive");
+// @__NO_SIDE_EFFECTS__
+function _negative(params) {
+ return /* @__PURE__ */ _lt(0, params);
+}
+__name(_negative, "_negative");
+// @__NO_SIDE_EFFECTS__
+function _nonpositive(params) {
+ return /* @__PURE__ */ _lte(0, params);
+}
+__name(_nonpositive, "_nonpositive");
+// @__NO_SIDE_EFFECTS__
+function _nonnegative(params) {
+ return /* @__PURE__ */ _gte(0, params);
+}
+__name(_nonnegative, "_nonnegative");
+// @__NO_SIDE_EFFECTS__
+function _multipleOf(value, params) {
+ return new $ZodCheckMultipleOf({
+ check: "multiple_of",
+ ...normalizeParams(params),
+ value
+ });
+}
+__name(_multipleOf, "_multipleOf");
+// @__NO_SIDE_EFFECTS__
+function _maxSize(maximum, params) {
+ return new $ZodCheckMaxSize({
+ check: "max_size",
+ ...normalizeParams(params),
+ maximum
+ });
+}
+__name(_maxSize, "_maxSize");
+// @__NO_SIDE_EFFECTS__
+function _minSize(minimum, params) {
+ return new $ZodCheckMinSize({
+ check: "min_size",
+ ...normalizeParams(params),
+ minimum
+ });
+}
+__name(_minSize, "_minSize");
+// @__NO_SIDE_EFFECTS__
+function _size(size, params) {
+ return new $ZodCheckSizeEquals({
+ check: "size_equals",
+ ...normalizeParams(params),
+ size
+ });
+}
+__name(_size, "_size");
+// @__NO_SIDE_EFFECTS__
+function _maxLength(maximum, params) {
+ const ch = new $ZodCheckMaxLength({
+ check: "max_length",
+ ...normalizeParams(params),
+ maximum
+ });
+ return ch;
+}
+__name(_maxLength, "_maxLength");
+// @__NO_SIDE_EFFECTS__
+function _minLength(minimum, params) {
+ return new $ZodCheckMinLength({
+ check: "min_length",
+ ...normalizeParams(params),
+ minimum
+ });
+}
+__name(_minLength, "_minLength");
+// @__NO_SIDE_EFFECTS__
+function _length(length, params) {
+ return new $ZodCheckLengthEquals({
+ check: "length_equals",
+ ...normalizeParams(params),
+ length
+ });
+}
+__name(_length, "_length");
+// @__NO_SIDE_EFFECTS__
+function _regex(pattern, params) {
+ return new $ZodCheckRegex({
+ check: "string_format",
+ format: "regex",
+ ...normalizeParams(params),
+ pattern
+ });
+}
+__name(_regex, "_regex");
+// @__NO_SIDE_EFFECTS__
+function _lowercase(params) {
+ return new $ZodCheckLowerCase({
+ check: "string_format",
+ format: "lowercase",
+ ...normalizeParams(params)
+ });
+}
+__name(_lowercase, "_lowercase");
+// @__NO_SIDE_EFFECTS__
+function _uppercase(params) {
+ return new $ZodCheckUpperCase({
+ check: "string_format",
+ format: "uppercase",
+ ...normalizeParams(params)
+ });
+}
+__name(_uppercase, "_uppercase");
+// @__NO_SIDE_EFFECTS__
+function _includes(includes, params) {
+ return new $ZodCheckIncludes({
+ check: "string_format",
+ format: "includes",
+ ...normalizeParams(params),
+ includes
+ });
+}
+__name(_includes, "_includes");
+// @__NO_SIDE_EFFECTS__
+function _startsWith(prefix, params) {
+ return new $ZodCheckStartsWith({
+ check: "string_format",
+ format: "starts_with",
+ ...normalizeParams(params),
+ prefix
+ });
+}
+__name(_startsWith, "_startsWith");
+// @__NO_SIDE_EFFECTS__
+function _endsWith(suffix, params) {
+ return new $ZodCheckEndsWith({
+ check: "string_format",
+ format: "ends_with",
+ ...normalizeParams(params),
+ suffix
+ });
+}
+__name(_endsWith, "_endsWith");
+// @__NO_SIDE_EFFECTS__
+function _property(property, schema, params) {
+ return new $ZodCheckProperty({
+ check: "property",
+ property,
+ schema,
+ ...normalizeParams(params)
+ });
+}
+__name(_property, "_property");
+// @__NO_SIDE_EFFECTS__
+function _mime(types, params) {
+ return new $ZodCheckMimeType({
+ check: "mime_type",
+ mime: types,
+ ...normalizeParams(params)
+ });
+}
+__name(_mime, "_mime");
+// @__NO_SIDE_EFFECTS__
+function _overwrite(tx) {
+ return new $ZodCheckOverwrite({
+ check: "overwrite",
+ tx
+ });
+}
+__name(_overwrite, "_overwrite");
+// @__NO_SIDE_EFFECTS__
+function _normalize(form) {
+ return /* @__PURE__ */ _overwrite((input) => input.normalize(form));
+}
+__name(_normalize, "_normalize");
+// @__NO_SIDE_EFFECTS__
+function _trim() {
+ return /* @__PURE__ */ _overwrite((input) => input.trim());
+}
+__name(_trim, "_trim");
+// @__NO_SIDE_EFFECTS__
+function _toLowerCase() {
+ return /* @__PURE__ */ _overwrite((input) => input.toLowerCase());
+}
+__name(_toLowerCase, "_toLowerCase");
+// @__NO_SIDE_EFFECTS__
+function _toUpperCase() {
+ return /* @__PURE__ */ _overwrite((input) => input.toUpperCase());
+}
+__name(_toUpperCase, "_toUpperCase");
+// @__NO_SIDE_EFFECTS__
+function _slugify() {
+ return /* @__PURE__ */ _overwrite((input) => slugify(input));
+}
+__name(_slugify, "_slugify");
+// @__NO_SIDE_EFFECTS__
+function _array(Class2, element, params) {
+ return new Class2({
+ type: "array",
+ element,
+ // get element() {
+ // return element;
+ // },
+ ...normalizeParams(params)
+ });
+}
+__name(_array, "_array");
+// @__NO_SIDE_EFFECTS__
+function _union(Class2, options2, params) {
+ return new Class2({
+ type: "union",
+ options: options2,
+ ...normalizeParams(params)
+ });
+}
+__name(_union, "_union");
+function _xor(Class2, options2, params) {
+ return new Class2({
+ type: "union",
+ options: options2,
+ inclusive: false,
+ ...normalizeParams(params)
+ });
+}
+__name(_xor, "_xor");
+// @__NO_SIDE_EFFECTS__
+function _discriminatedUnion(Class2, discriminator, options2, params) {
+ return new Class2({
+ type: "union",
+ options: options2,
+ discriminator,
+ ...normalizeParams(params)
+ });
+}
+__name(_discriminatedUnion, "_discriminatedUnion");
+// @__NO_SIDE_EFFECTS__
+function _intersection(Class2, left2, right2) {
+ return new Class2({
+ type: "intersection",
+ left: left2,
+ right: right2
+ });
+}
+__name(_intersection, "_intersection");
+// @__NO_SIDE_EFFECTS__
+function _tuple(Class2, items, _paramsOrRest, _params) {
+ const hasRest = _paramsOrRest instanceof $ZodType;
+ const params = hasRest ? _params : _paramsOrRest;
+ const rest = hasRest ? _paramsOrRest : null;
+ return new Class2({
+ type: "tuple",
+ items,
+ rest,
+ ...normalizeParams(params)
+ });
+}
+__name(_tuple, "_tuple");
+// @__NO_SIDE_EFFECTS__
+function _record(Class2, keyType, valueType, params) {
+ return new Class2({
+ type: "record",
+ keyType,
+ valueType,
+ ...normalizeParams(params)
+ });
+}
+__name(_record, "_record");
+// @__NO_SIDE_EFFECTS__
+function _map(Class2, keyType, valueType, params) {
+ return new Class2({
+ type: "map",
+ keyType,
+ valueType,
+ ...normalizeParams(params)
+ });
+}
+__name(_map, "_map");
+// @__NO_SIDE_EFFECTS__
+function _set(Class2, valueType, params) {
+ return new Class2({
+ type: "set",
+ valueType,
+ ...normalizeParams(params)
+ });
+}
+__name(_set, "_set");
+// @__NO_SIDE_EFFECTS__
+function _enum(Class2, values, params) {
+ const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
+ return new Class2({
+ type: "enum",
+ entries,
+ ...normalizeParams(params)
+ });
+}
+__name(_enum, "_enum");
+// @__NO_SIDE_EFFECTS__
+function _nativeEnum(Class2, entries, params) {
+ return new Class2({
+ type: "enum",
+ entries,
+ ...normalizeParams(params)
+ });
+}
+__name(_nativeEnum, "_nativeEnum");
+// @__NO_SIDE_EFFECTS__
+function _literal(Class2, value, params) {
+ return new Class2({
+ type: "literal",
+ values: Array.isArray(value) ? value : [value],
+ ...normalizeParams(params)
+ });
+}
+__name(_literal, "_literal");
+// @__NO_SIDE_EFFECTS__
+function _file(Class2, params) {
+ return new Class2({
+ type: "file",
+ ...normalizeParams(params)
+ });
+}
+__name(_file, "_file");
+// @__NO_SIDE_EFFECTS__
+function _transform(Class2, fn) {
+ return new Class2({
+ type: "transform",
+ transform: fn
+ });
+}
+__name(_transform, "_transform");
+// @__NO_SIDE_EFFECTS__
+function _optional(Class2, innerType) {
+ return new Class2({
+ type: "optional",
+ innerType
+ });
+}
+__name(_optional, "_optional");
+// @__NO_SIDE_EFFECTS__
+function _nullable(Class2, innerType) {
+ return new Class2({
+ type: "nullable",
+ innerType
+ });
+}
+__name(_nullable, "_nullable");
+// @__NO_SIDE_EFFECTS__
+function _default(Class2, innerType, defaultValue2) {
+ return new Class2({
+ type: "default",
+ innerType,
+ get defaultValue() {
+ return typeof defaultValue2 === "function" ? defaultValue2() : shallowClone(defaultValue2);
+ }
+ });
+}
+__name(_default, "_default");
+// @__NO_SIDE_EFFECTS__
+function _nonoptional(Class2, innerType, params) {
+ return new Class2({
+ type: "nonoptional",
+ innerType,
+ ...normalizeParams(params)
+ });
+}
+__name(_nonoptional, "_nonoptional");
+// @__NO_SIDE_EFFECTS__
+function _success(Class2, innerType) {
+ return new Class2({
+ type: "success",
+ innerType
+ });
+}
+__name(_success, "_success");
+// @__NO_SIDE_EFFECTS__
+function _catch(Class2, innerType, catchValue) {
+ return new Class2({
+ type: "catch",
+ innerType,
+ catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
+ });
+}
+__name(_catch, "_catch");
+// @__NO_SIDE_EFFECTS__
+function _pipe(Class2, in_, out) {
+ return new Class2({
+ type: "pipe",
+ in: in_,
+ out
+ });
+}
+__name(_pipe, "_pipe");
+// @__NO_SIDE_EFFECTS__
+function _readonly(Class2, innerType) {
+ return new Class2({
+ type: "readonly",
+ innerType
+ });
+}
+__name(_readonly, "_readonly");
+// @__NO_SIDE_EFFECTS__
+function _templateLiteral(Class2, parts, params) {
+ return new Class2({
+ type: "template_literal",
+ parts,
+ ...normalizeParams(params)
+ });
+}
+__name(_templateLiteral, "_templateLiteral");
+// @__NO_SIDE_EFFECTS__
+function _lazy(Class2, getter) {
+ return new Class2({
+ type: "lazy",
+ getter
+ });
+}
+__name(_lazy, "_lazy");
+// @__NO_SIDE_EFFECTS__
+function _promise(Class2, innerType) {
+ return new Class2({
+ type: "promise",
+ innerType
+ });
+}
+__name(_promise, "_promise");
+// @__NO_SIDE_EFFECTS__
+function _custom(Class2, fn, _params) {
+ const norm = normalizeParams(_params);
+ norm.abort ?? (norm.abort = true);
+ const schema = new Class2({
+ type: "custom",
+ check: "custom",
+ fn,
+ ...norm
+ });
+ return schema;
+}
+__name(_custom, "_custom");
+// @__NO_SIDE_EFFECTS__
+function _refine(Class2, fn, _params) {
+ const schema = new Class2({
+ type: "custom",
+ check: "custom",
+ fn,
+ ...normalizeParams(_params)
+ });
+ return schema;
+}
+__name(_refine, "_refine");
+// @__NO_SIDE_EFFECTS__
+function _superRefine(fn, params) {
+ const ch = /* @__PURE__ */ _check((payload) => {
+ payload.addIssue = (issue2) => {
+ if (typeof issue2 === "string") {
+ payload.issues.push(issue(issue2, payload.value, ch._zod.def));
+ } else {
+ const _issue = issue2;
+ if (_issue.fatal)
+ _issue.continue = false;
+ _issue.code ?? (_issue.code = "custom");
+ _issue.input ?? (_issue.input = payload.value);
+ _issue.inst ?? (_issue.inst = ch);
+ _issue.continue ?? (_issue.continue = !ch._zod.def.abort);
+ payload.issues.push(issue(_issue));
+ }
+ };
+ return fn(payload.value, payload);
+ }, params);
+ return ch;
+}
+__name(_superRefine, "_superRefine");
+// @__NO_SIDE_EFFECTS__
+function _check(fn, params) {
+ const ch = new $ZodCheck({
+ check: "custom",
+ ...normalizeParams(params)
+ });
+ ch._zod.check = fn;
+ return ch;
+}
+__name(_check, "_check");
+// @__NO_SIDE_EFFECTS__
+function describe(description) {
+ const ch = new $ZodCheck({ check: "describe" });
+ ch._zod.onattach = [
+ (inst) => {
+ const existing = globalRegistry.get(inst) ?? {};
+ globalRegistry.add(inst, { ...existing, description });
+ }
+ ];
+ ch._zod.check = () => {
+ };
+ return ch;
+}
+__name(describe, "describe");
+// @__NO_SIDE_EFFECTS__
+function meta(metadata) {
+ const ch = new $ZodCheck({ check: "meta" });
+ ch._zod.onattach = [
+ (inst) => {
+ const existing = globalRegistry.get(inst) ?? {};
+ globalRegistry.add(inst, { ...existing, ...metadata });
+ }
+ ];
+ ch._zod.check = () => {
+ };
+ return ch;
+}
+__name(meta, "meta");
+// @__NO_SIDE_EFFECTS__
+function _stringbool(Classes, _params) {
+ const params = normalizeParams(_params);
+ let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"];
+ let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"];
+ if (params.case !== "sensitive") {
+ truthyArray = truthyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v);
+ falsyArray = falsyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v);
+ }
+ const truthySet = new Set(truthyArray);
+ const falsySet = new Set(falsyArray);
+ const _Codec = Classes.Codec ?? $ZodCodec;
+ const _Boolean = Classes.Boolean ?? $ZodBoolean;
+ const _String = Classes.String ?? $ZodString;
+ const stringSchema = new _String({ type: "string", error: params.error });
+ const booleanSchema = new _Boolean({ type: "boolean", error: params.error });
+ const codec2 = new _Codec({
+ type: "pipe",
+ in: stringSchema,
+ out: booleanSchema,
+ transform: /* @__PURE__ */ __name(((input, payload) => {
+ let data = input;
+ if (params.case !== "sensitive")
+ data = data.toLowerCase();
+ if (truthySet.has(data)) {
+ return true;
+ } else if (falsySet.has(data)) {
+ return false;
+ } else {
+ payload.issues.push({
+ code: "invalid_value",
+ expected: "stringbool",
+ values: [...truthySet, ...falsySet],
+ input: payload.value,
+ inst: codec2,
+ continue: false
+ });
+ return {};
+ }
+ }), "transform"),
+ reverseTransform: /* @__PURE__ */ __name(((input, _payload) => {
+ if (input === true) {
+ return truthyArray[0] || "true";
+ } else {
+ return falsyArray[0] || "false";
+ }
+ }), "reverseTransform"),
+ error: params.error
+ });
+ return codec2;
+}
+__name(_stringbool, "_stringbool");
+// @__NO_SIDE_EFFECTS__
+function _stringFormat(Class2, format3, fnOrRegex, _params = {}) {
+ const params = normalizeParams(_params);
+ const def = {
+ ...normalizeParams(_params),
+ check: "string_format",
+ type: "string",
+ format: format3,
+ fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val),
+ ...params
+ };
+ if (fnOrRegex instanceof RegExp) {
+ def.pattern = fnOrRegex;
+ }
+ const inst = new Class2(def);
+ return inst;
+}
+__name(_stringFormat, "_stringFormat");
+
+// node_modules/zod/v4/core/to-json-schema.js
+init_esbuild_shims();
+function initializeContext(params) {
+ let target = params?.target ?? "draft-2020-12";
+ if (target === "draft-4")
+ target = "draft-04";
+ if (target === "draft-7")
+ target = "draft-07";
+ return {
+ processors: params.processors ?? {},
+ metadataRegistry: params?.metadata ?? globalRegistry,
+ target,
+ unrepresentable: params?.unrepresentable ?? "throw",
+ override: params?.override ?? (() => {
+ }),
+ io: params?.io ?? "output",
+ counter: 0,
+ seen: /* @__PURE__ */ new Map(),
+ cycles: params?.cycles ?? "ref",
+ reused: params?.reused ?? "inline",
+ external: params?.external ?? void 0
+ };
+}
+__name(initializeContext, "initializeContext");
+function process14(schema, ctx, _params = { path: [], schemaPath: [] }) {
+ var _a6;
+ const def = schema._zod.def;
+ const seen = ctx.seen.get(schema);
+ if (seen) {
+ seen.count++;
+ const isCycle = _params.schemaPath.includes(schema);
+ if (isCycle) {
+ seen.cycle = _params.path;
+ }
+ return seen.schema;
+ }
+ const result = { schema: {}, count: 1, cycle: void 0, path: _params.path };
+ ctx.seen.set(schema, result);
+ const overrideSchema = schema._zod.toJSONSchema?.();
+ if (overrideSchema) {
+ result.schema = overrideSchema;
+ } else {
+ const params = {
+ ..._params,
+ schemaPath: [..._params.schemaPath, schema],
+ path: _params.path
+ };
+ if (schema._zod.processJSONSchema) {
+ schema._zod.processJSONSchema(ctx, result.schema, params);
+ } else {
+ const _json = result.schema;
+ const processor = ctx.processors[def.type];
+ if (!processor) {
+ throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);
+ }
+ processor(schema, ctx, _json, params);
+ }
+ const parent = schema._zod.parent;
+ if (parent) {
+ if (!result.ref)
+ result.ref = parent;
+ process14(parent, ctx, params);
+ ctx.seen.get(parent).isParent = true;
+ }
+ }
+ const meta3 = ctx.metadataRegistry.get(schema);
+ if (meta3)
+ Object.assign(result.schema, meta3);
+ if (ctx.io === "input" && isTransforming(schema)) {
+ delete result.schema.examples;
+ delete result.schema.default;
+ }
+ if (ctx.io === "input" && "_prefault" in result.schema)
+ (_a6 = result.schema).default ?? (_a6.default = result.schema._prefault);
+ delete result.schema._prefault;
+ const _result = ctx.seen.get(schema);
+ return _result.schema;
+}
+__name(process14, "process");
+function extractDefs(ctx, schema) {
+ const root = ctx.seen.get(schema);
+ if (!root)
+ throw new Error("Unprocessed schema. This is a bug in Zod.");
+ const idToSchema = /* @__PURE__ */ new Map();
+ for (const entry of ctx.seen.entries()) {
+ const id = ctx.metadataRegistry.get(entry[0])?.id;
+ if (id) {
+ const existing = idToSchema.get(id);
+ if (existing && existing !== entry[0]) {
+ throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
+ }
+ idToSchema.set(id, entry[0]);
+ }
+ }
+ const makeURI = /* @__PURE__ */ __name((entry) => {
+ const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
+ if (ctx.external) {
+ const externalId = ctx.external.registry.get(entry[0])?.id;
+ const uriGenerator = ctx.external.uri ?? ((id2) => id2);
+ if (externalId) {
+ return { ref: uriGenerator(externalId) };
+ }
+ const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
+ entry[1].defId = id;
+ return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` };
+ }
+ if (entry[1] === root) {
+ return { ref: "#" };
+ }
+ const uriPrefix = `#`;
+ const defUriPrefix = `${uriPrefix}/${defsSegment}/`;
+ const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;
+ return { defId, ref: defUriPrefix + defId };
+ }, "makeURI");
+ const extractToDef = /* @__PURE__ */ __name((entry) => {
+ if (entry[1].schema.$ref) {
+ return;
+ }
+ const seen = entry[1];
+ const { ref, defId } = makeURI(entry);
+ seen.def = { ...seen.schema };
+ if (defId)
+ seen.defId = defId;
+ const schema2 = seen.schema;
+ for (const key in schema2) {
+ delete schema2[key];
+ }
+ schema2.$ref = ref;
+ }, "extractToDef");
+ if (ctx.cycles === "throw") {
+ for (const entry of ctx.seen.entries()) {
+ const seen = entry[1];
+ if (seen.cycle) {
+ throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/
+
+Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`);
+ }
+ }
+ }
+ for (const entry of ctx.seen.entries()) {
+ const seen = entry[1];
+ if (schema === entry[0]) {
+ extractToDef(entry);
+ continue;
+ }
+ if (ctx.external) {
+ const ext = ctx.external.registry.get(entry[0])?.id;
+ if (schema !== entry[0] && ext) {
+ extractToDef(entry);
+ continue;
+ }
+ }
+ const id = ctx.metadataRegistry.get(entry[0])?.id;
+ if (id) {
+ extractToDef(entry);
+ continue;
+ }
+ if (seen.cycle) {
+ extractToDef(entry);
+ continue;
+ }
+ if (seen.count > 1) {
+ if (ctx.reused === "ref") {
+ extractToDef(entry);
+ continue;
+ }
+ }
+ }
+}
+__name(extractDefs, "extractDefs");
+function finalize(ctx, schema) {
+ const root = ctx.seen.get(schema);
+ if (!root)
+ throw new Error("Unprocessed schema. This is a bug in Zod.");
+ const flattenRef = /* @__PURE__ */ __name((zodSchema) => {
+ const seen = ctx.seen.get(zodSchema);
+ if (seen.ref === null)
+ return;
+ const schema2 = seen.def ?? seen.schema;
+ const _cached = { ...schema2 };
+ const ref = seen.ref;
+ seen.ref = null;
+ if (ref) {
+ flattenRef(ref);
+ const refSeen = ctx.seen.get(ref);
+ const refSchema = refSeen.schema;
+ if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) {
+ schema2.allOf = schema2.allOf ?? [];
+ schema2.allOf.push(refSchema);
+ } else {
+ Object.assign(schema2, refSchema);
+ }
+ Object.assign(schema2, _cached);
+ const isParentRef = zodSchema._zod.parent === ref;
+ if (isParentRef) {
+ for (const key in schema2) {
+ if (key === "$ref" || key === "allOf")
+ continue;
+ if (!(key in _cached)) {
+ delete schema2[key];
+ }
+ }
+ }
+ if (refSchema.$ref && refSeen.def) {
+ for (const key in schema2) {
+ if (key === "$ref" || key === "allOf")
+ continue;
+ if (key in refSeen.def && JSON.stringify(schema2[key]) === JSON.stringify(refSeen.def[key])) {
+ delete schema2[key];
+ }
+ }
+ }
+ }
+ const parent = zodSchema._zod.parent;
+ if (parent && parent !== ref) {
+ flattenRef(parent);
+ const parentSeen = ctx.seen.get(parent);
+ if (parentSeen?.schema.$ref) {
+ schema2.$ref = parentSeen.schema.$ref;
+ if (parentSeen.def) {
+ for (const key in schema2) {
+ if (key === "$ref" || key === "allOf")
+ continue;
+ if (key in parentSeen.def && JSON.stringify(schema2[key]) === JSON.stringify(parentSeen.def[key])) {
+ delete schema2[key];
+ }
+ }
+ }
+ }
+ }
+ ctx.override({
+ zodSchema,
+ jsonSchema: schema2,
+ path: seen.path ?? []
+ });
+ }, "flattenRef");
+ for (const entry of [...ctx.seen.entries()].reverse()) {
+ flattenRef(entry[0]);
+ }
+ const result = {};
+ if (ctx.target === "draft-2020-12") {
+ result.$schema = "https://json-schema.org/draft/2020-12/schema";
+ } else if (ctx.target === "draft-07") {
+ result.$schema = "http://json-schema.org/draft-07/schema#";
+ } else if (ctx.target === "draft-04") {
+ result.$schema = "http://json-schema.org/draft-04/schema#";
+ } else if (ctx.target === "openapi-3.0") {
+ } else {
+ }
+ if (ctx.external?.uri) {
+ const id = ctx.external.registry.get(schema)?.id;
+ if (!id)
+ throw new Error("Schema is missing an `id` property");
+ result.$id = ctx.external.uri(id);
+ }
+ Object.assign(result, root.def ?? root.schema);
+ const rootMetaId = ctx.metadataRegistry.get(schema)?.id;
+ if (rootMetaId !== void 0 && result.id === rootMetaId)
+ delete result.id;
+ const defs = ctx.external?.defs ?? {};
+ for (const entry of ctx.seen.entries()) {
+ const seen = entry[1];
+ if (seen.def && seen.defId) {
+ if (seen.def.id === seen.defId)
+ delete seen.def.id;
+ defs[seen.defId] = seen.def;
+ }
+ }
+ if (ctx.external) {
+ } else {
+ if (Object.keys(defs).length > 0) {
+ if (ctx.target === "draft-2020-12") {
+ result.$defs = defs;
+ } else {
+ result.definitions = defs;
+ }
+ }
+ }
+ try {
+ const finalized = JSON.parse(JSON.stringify(result));
+ Object.defineProperty(finalized, "~standard", {
+ value: {
+ ...schema["~standard"],
+ jsonSchema: {
+ input: createStandardJSONSchemaMethod(schema, "input", ctx.processors),
+ output: createStandardJSONSchemaMethod(schema, "output", ctx.processors)
+ }
+ },
+ enumerable: false,
+ writable: false
+ });
+ return finalized;
+ } catch (_err) {
+ throw new Error("Error converting schema to JSON.");
+ }
+}
+__name(finalize, "finalize");
+function isTransforming(_schema, _ctx) {
+ const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() };
+ if (ctx.seen.has(_schema))
+ return false;
+ ctx.seen.add(_schema);
+ const def = _schema._zod.def;
+ if (def.type === "transform")
+ return true;
+ if (def.type === "array")
+ return isTransforming(def.element, ctx);
+ if (def.type === "set")
+ return isTransforming(def.valueType, ctx);
+ if (def.type === "lazy")
+ return isTransforming(def.getter(), ctx);
+ if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") {
+ return isTransforming(def.innerType, ctx);
+ }
+ if (def.type === "intersection") {
+ return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);
+ }
+ if (def.type === "record" || def.type === "map") {
+ return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);
+ }
+ if (def.type === "pipe") {
+ if (_schema._zod.traits.has("$ZodCodec"))
+ return true;
+ return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);
+ }
+ if (def.type === "object") {
+ for (const key in def.shape) {
+ if (isTransforming(def.shape[key], ctx))
+ return true;
+ }
+ return false;
+ }
+ if (def.type === "union") {
+ for (const option of def.options) {
+ if (isTransforming(option, ctx))
+ return true;
+ }
+ return false;
+ }
+ if (def.type === "tuple") {
+ for (const item of def.items) {
+ if (isTransforming(item, ctx))
+ return true;
+ }
+ if (def.rest && isTransforming(def.rest, ctx))
+ return true;
+ return false;
+ }
+ return false;
+}
+__name(isTransforming, "isTransforming");
+var createToJSONSchemaMethod = /* @__PURE__ */ __name((schema, processors = {}) => (params) => {
+ const ctx = initializeContext({ ...params, processors });
+ process14(schema, ctx);
+ extractDefs(ctx, schema);
+ return finalize(ctx, schema);
+}, "createToJSONSchemaMethod");
+var createStandardJSONSchemaMethod = /* @__PURE__ */ __name((schema, io, processors = {}) => (params) => {
+ const { libraryOptions, target } = params ?? {};
+ const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors });
+ process14(schema, ctx);
+ extractDefs(ctx, schema);
+ return finalize(ctx, schema);
+}, "createStandardJSONSchemaMethod");
+
+// node_modules/zod/v4/core/json-schema-processors.js
+init_esbuild_shims();
+var formatMap = {
+ guid: "uuid",
+ url: "uri",
+ datetime: "date-time",
+ json_string: "json-string",
+ regex: ""
+ // do not set
+};
+var stringProcessor = /* @__PURE__ */ __name((schema, ctx, _json, _params) => {
+ const json2 = _json;
+ json2.type = "string";
+ const { minimum, maximum, format: format3, patterns, contentEncoding } = schema._zod.bag;
+ if (typeof minimum === "number")
+ json2.minLength = minimum;
+ if (typeof maximum === "number")
+ json2.maxLength = maximum;
+ if (format3) {
+ json2.format = formatMap[format3] ?? format3;
+ if (json2.format === "")
+ delete json2.format;
+ if (format3 === "time") {
+ delete json2.format;
+ }
+ }
+ if (contentEncoding)
+ json2.contentEncoding = contentEncoding;
+ if (patterns && patterns.size > 0) {
+ const regexes = [...patterns];
+ if (regexes.length === 1)
+ json2.pattern = regexes[0].source;
+ else if (regexes.length > 1) {
+ json2.allOf = [
+ ...regexes.map((regex2) => ({
+ ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {},
+ pattern: regex2.source
+ }))
+ ];
+ }
+ }
+}, "stringProcessor");
+var numberProcessor = /* @__PURE__ */ __name((schema, ctx, _json, _params) => {
+ const json2 = _json;
+ const { minimum, maximum, format: format3, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;
+ if (typeof format3 === "string" && format3.includes("int"))
+ json2.type = "integer";
+ else
+ json2.type = "number";
+ const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);
+ const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);
+ const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0";
+ if (exMin) {
+ if (legacy) {
+ json2.minimum = exclusiveMinimum;
+ json2.exclusiveMinimum = true;
+ } else {
+ json2.exclusiveMinimum = exclusiveMinimum;
+ }
+ } else if (typeof minimum === "number") {
+ json2.minimum = minimum;
+ }
+ if (exMax) {
+ if (legacy) {
+ json2.maximum = exclusiveMaximum;
+ json2.exclusiveMaximum = true;
+ } else {
+ json2.exclusiveMaximum = exclusiveMaximum;
+ }
+ } else if (typeof maximum === "number") {
+ json2.maximum = maximum;
+ }
+ if (typeof multipleOf === "number")
+ json2.multipleOf = multipleOf;
+}, "numberProcessor");
+var booleanProcessor = /* @__PURE__ */ __name((_schema, _ctx, json2, _params) => {
+ json2.type = "boolean";
+}, "booleanProcessor");
+var bigintProcessor = /* @__PURE__ */ __name((_schema, ctx, _json, _params) => {
+ if (ctx.unrepresentable === "throw") {
+ throw new Error("BigInt cannot be represented in JSON Schema");
+ }
+}, "bigintProcessor");
+var symbolProcessor = /* @__PURE__ */ __name((_schema, ctx, _json, _params) => {
+ if (ctx.unrepresentable === "throw") {
+ throw new Error("Symbols cannot be represented in JSON Schema");
+ }
+}, "symbolProcessor");
+var nullProcessor = /* @__PURE__ */ __name((_schema, ctx, json2, _params) => {
+ if (ctx.target === "openapi-3.0") {
+ json2.type = "string";
+ json2.nullable = true;
+ json2.enum = [null];
+ } else {
+ json2.type = "null";
+ }
+}, "nullProcessor");
+var undefinedProcessor = /* @__PURE__ */ __name((_schema, ctx, _json, _params) => {
+ if (ctx.unrepresentable === "throw") {
+ throw new Error("Undefined cannot be represented in JSON Schema");
+ }
+}, "undefinedProcessor");
+var voidProcessor = /* @__PURE__ */ __name((_schema, ctx, _json, _params) => {
+ if (ctx.unrepresentable === "throw") {
+ throw new Error("Void cannot be represented in JSON Schema");
+ }
+}, "voidProcessor");
+var neverProcessor = /* @__PURE__ */ __name((_schema, _ctx, json2, _params) => {
+ json2.not = {};
+}, "neverProcessor");
+var anyProcessor = /* @__PURE__ */ __name((_schema, _ctx, _json, _params) => {
+}, "anyProcessor");
+var unknownProcessor = /* @__PURE__ */ __name((_schema, _ctx, _json, _params) => {
+}, "unknownProcessor");
+var dateProcessor = /* @__PURE__ */ __name((_schema, ctx, _json, _params) => {
+ if (ctx.unrepresentable === "throw") {
+ throw new Error("Date cannot be represented in JSON Schema");
+ }
+}, "dateProcessor");
+var enumProcessor = /* @__PURE__ */ __name((schema, _ctx, json2, _params) => {
+ const def = schema._zod.def;
+ const values = getEnumValues(def.entries);
+ if (values.every((v) => typeof v === "number"))
+ json2.type = "number";
+ if (values.every((v) => typeof v === "string"))
+ json2.type = "string";
+ json2.enum = values;
+}, "enumProcessor");
+var literalProcessor = /* @__PURE__ */ __name((schema, ctx, json2, _params) => {
+ const def = schema._zod.def;
+ const vals = [];
+ for (const val of def.values) {
+ if (val === void 0) {
+ if (ctx.unrepresentable === "throw") {
+ throw new Error("Literal `undefined` cannot be represented in JSON Schema");
+ } else {
+ }
+ } else if (typeof val === "bigint") {
+ if (ctx.unrepresentable === "throw") {
+ throw new Error("BigInt literals cannot be represented in JSON Schema");
+ } else {
+ vals.push(Number(val));
+ }
+ } else {
+ vals.push(val);
+ }
+ }
+ if (vals.length === 0) {
+ } else if (vals.length === 1) {
+ const val = vals[0];
+ json2.type = val === null ? "null" : typeof val;
+ if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
+ json2.enum = [val];
+ } else {
+ json2.const = val;
+ }
+ } else {
+ if (vals.every((v) => typeof v === "number"))
+ json2.type = "number";
+ if (vals.every((v) => typeof v === "string"))
+ json2.type = "string";
+ if (vals.every((v) => typeof v === "boolean"))
+ json2.type = "boolean";
+ if (vals.every((v) => v === null))
+ json2.type = "null";
+ json2.enum = vals;
+ }
+}, "literalProcessor");
+var nanProcessor = /* @__PURE__ */ __name((_schema, ctx, _json, _params) => {
+ if (ctx.unrepresentable === "throw") {
+ throw new Error("NaN cannot be represented in JSON Schema");
+ }
+}, "nanProcessor");
+var templateLiteralProcessor = /* @__PURE__ */ __name((schema, _ctx, json2, _params) => {
+ const _json = json2;
+ const pattern = schema._zod.pattern;
+ if (!pattern)
+ throw new Error("Pattern not found in template literal");
+ _json.type = "string";
+ _json.pattern = pattern.source;
+}, "templateLiteralProcessor");
+var fileProcessor = /* @__PURE__ */ __name((schema, _ctx, json2, _params) => {
+ const _json = json2;
+ const file2 = {
+ type: "string",
+ format: "binary",
+ contentEncoding: "binary"
+ };
+ const { minimum, maximum, mime } = schema._zod.bag;
+ if (minimum !== void 0)
+ file2.minLength = minimum;
+ if (maximum !== void 0)
+ file2.maxLength = maximum;
+ if (mime) {
+ if (mime.length === 1) {
+ file2.contentMediaType = mime[0];
+ Object.assign(_json, file2);
+ } else {
+ Object.assign(_json, file2);
+ _json.anyOf = mime.map((m) => ({ contentMediaType: m }));
+ }
+ } else {
+ Object.assign(_json, file2);
+ }
+}, "fileProcessor");
+var successProcessor = /* @__PURE__ */ __name((_schema, _ctx, json2, _params) => {
+ json2.type = "boolean";
+}, "successProcessor");
+var customProcessor = /* @__PURE__ */ __name((_schema, ctx, _json, _params) => {
+ if (ctx.unrepresentable === "throw") {
+ throw new Error("Custom types cannot be represented in JSON Schema");
+ }
+}, "customProcessor");
+var functionProcessor = /* @__PURE__ */ __name((_schema, ctx, _json, _params) => {
+ if (ctx.unrepresentable === "throw") {
+ throw new Error("Function types cannot be represented in JSON Schema");
+ }
+}, "functionProcessor");
+var transformProcessor = /* @__PURE__ */ __name((_schema, ctx, _json, _params) => {
+ if (ctx.unrepresentable === "throw") {
+ throw new Error("Transforms cannot be represented in JSON Schema");
+ }
+}, "transformProcessor");
+var mapProcessor = /* @__PURE__ */ __name((_schema, ctx, _json, _params) => {
+ if (ctx.unrepresentable === "throw") {
+ throw new Error("Map cannot be represented in JSON Schema");
+ }
+}, "mapProcessor");
+var setProcessor = /* @__PURE__ */ __name((_schema, ctx, _json, _params) => {
+ if (ctx.unrepresentable === "throw") {
+ throw new Error("Set cannot be represented in JSON Schema");
+ }
+}, "setProcessor");
+var arrayProcessor = /* @__PURE__ */ __name((schema, ctx, _json, params) => {
+ const json2 = _json;
+ const def = schema._zod.def;
+ const { minimum, maximum } = schema._zod.bag;
+ if (typeof minimum === "number")
+ json2.minItems = minimum;
+ if (typeof maximum === "number")
+ json2.maxItems = maximum;
+ json2.type = "array";
+ json2.items = process14(def.element, ctx, {
+ ...params,
+ path: [...params.path, "items"]
+ });
+}, "arrayProcessor");
+var objectProcessor = /* @__PURE__ */ __name((schema, ctx, _json, params) => {
+ const json2 = _json;
+ const def = schema._zod.def;
+ json2.type = "object";
+ json2.properties = {};
+ const shape = def.shape;
+ for (const key in shape) {
+ json2.properties[key] = process14(shape[key], ctx, {
+ ...params,
+ path: [...params.path, "properties", key]
+ });
+ }
+ const allKeys = new Set(Object.keys(shape));
+ const requiredKeys = new Set([...allKeys].filter((key) => {
+ const v = def.shape[key]._zod;
+ if (ctx.io === "input") {
+ return v.optin === void 0;
+ } else {
+ return v.optout === void 0;
+ }
+ }));
+ if (requiredKeys.size > 0) {
+ json2.required = Array.from(requiredKeys);
+ }
+ if (def.catchall?._zod.def.type === "never") {
+ json2.additionalProperties = false;
+ } else if (!def.catchall) {
+ if (ctx.io === "output")
+ json2.additionalProperties = false;
+ } else if (def.catchall) {
+ json2.additionalProperties = process14(def.catchall, ctx, {
+ ...params,
+ path: [...params.path, "additionalProperties"]
+ });
+ }
+}, "objectProcessor");
+var unionProcessor = /* @__PURE__ */ __name((schema, ctx, json2, params) => {
+ const def = schema._zod.def;
+ const isExclusive = def.inclusive === false;
+ const options2 = def.options.map((x, i) => process14(x, ctx, {
+ ...params,
+ path: [...params.path, isExclusive ? "oneOf" : "anyOf", i]
+ }));
+ if (isExclusive) {
+ json2.oneOf = options2;
+ } else {
+ json2.anyOf = options2;
+ }
+}, "unionProcessor");
+var intersectionProcessor = /* @__PURE__ */ __name((schema, ctx, json2, params) => {
+ const def = schema._zod.def;
+ const a = process14(def.left, ctx, {
+ ...params,
+ path: [...params.path, "allOf", 0]
+ });
+ const b = process14(def.right, ctx, {
+ ...params,
+ path: [...params.path, "allOf", 1]
+ });
+ const isSimpleIntersection = /* @__PURE__ */ __name((val) => "allOf" in val && Object.keys(val).length === 1, "isSimpleIntersection");
+ const allOf = [
+ ...isSimpleIntersection(a) ? a.allOf : [a],
+ ...isSimpleIntersection(b) ? b.allOf : [b]
+ ];
+ json2.allOf = allOf;
+}, "intersectionProcessor");
+var tupleProcessor = /* @__PURE__ */ __name((schema, ctx, _json, params) => {
+ const json2 = _json;
+ const def = schema._zod.def;
+ json2.type = "array";
+ const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items";
+ const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems";
+ const prefixItems = def.items.map((x, i) => process14(x, ctx, {
+ ...params,
+ path: [...params.path, prefixPath, i]
+ }));
+ const rest = def.rest ? process14(def.rest, ctx, {
+ ...params,
+ path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []]
+ }) : null;
+ if (ctx.target === "draft-2020-12") {
+ json2.prefixItems = prefixItems;
+ if (rest) {
+ json2.items = rest;
+ }
+ } else if (ctx.target === "openapi-3.0") {
+ json2.items = {
+ anyOf: prefixItems
+ };
+ if (rest) {
+ json2.items.anyOf.push(rest);
+ }
+ json2.minItems = prefixItems.length;
+ if (!rest) {
+ json2.maxItems = prefixItems.length;
+ }
+ } else {
+ json2.items = prefixItems;
+ if (rest) {
+ json2.additionalItems = rest;
+ }
+ }
+ const { minimum, maximum } = schema._zod.bag;
+ if (typeof minimum === "number")
+ json2.minItems = minimum;
+ if (typeof maximum === "number")
+ json2.maxItems = maximum;
+}, "tupleProcessor");
+var recordProcessor = /* @__PURE__ */ __name((schema, ctx, _json, params) => {
+ const json2 = _json;
+ const def = schema._zod.def;
+ json2.type = "object";
+ const keyType = def.keyType;
+ const keyBag = keyType._zod.bag;
+ const patterns = keyBag?.patterns;
+ if (def.mode === "loose" && patterns && patterns.size > 0) {
+ const valueSchema = process14(def.valueType, ctx, {
+ ...params,
+ path: [...params.path, "patternProperties", "*"]
+ });
+ json2.patternProperties = {};
+ for (const pattern of patterns) {
+ json2.patternProperties[pattern.source] = valueSchema;
+ }
+ } else {
+ if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") {
+ json2.propertyNames = process14(def.keyType, ctx, {
+ ...params,
+ path: [...params.path, "propertyNames"]
+ });
+ }
+ json2.additionalProperties = process14(def.valueType, ctx, {
+ ...params,
+ path: [...params.path, "additionalProperties"]
+ });
+ }
+ const keyValues = keyType._zod.values;
+ if (keyValues) {
+ const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number");
+ if (validKeyValues.length > 0) {
+ json2.required = validKeyValues;
+ }
+ }
+}, "recordProcessor");
+var nullableProcessor = /* @__PURE__ */ __name((schema, ctx, json2, params) => {
+ const def = schema._zod.def;
+ const inner = process14(def.innerType, ctx, params);
+ const seen = ctx.seen.get(schema);
+ if (ctx.target === "openapi-3.0") {
+ seen.ref = def.innerType;
+ json2.nullable = true;
+ } else {
+ json2.anyOf = [inner, { type: "null" }];
+ }
+}, "nullableProcessor");
+var nonoptionalProcessor = /* @__PURE__ */ __name((schema, ctx, _json, params) => {
+ const def = schema._zod.def;
+ process14(def.innerType, ctx, params);
+ const seen = ctx.seen.get(schema);
+ seen.ref = def.innerType;
+}, "nonoptionalProcessor");
+var defaultProcessor = /* @__PURE__ */ __name((schema, ctx, json2, params) => {
+ const def = schema._zod.def;
+ process14(def.innerType, ctx, params);
+ const seen = ctx.seen.get(schema);
+ seen.ref = def.innerType;
+ json2.default = JSON.parse(JSON.stringify(def.defaultValue));
+}, "defaultProcessor");
+var prefaultProcessor = /* @__PURE__ */ __name((schema, ctx, json2, params) => {
+ const def = schema._zod.def;
+ process14(def.innerType, ctx, params);
+ const seen = ctx.seen.get(schema);
+ seen.ref = def.innerType;
+ if (ctx.io === "input")
+ json2._prefault = JSON.parse(JSON.stringify(def.defaultValue));
+}, "prefaultProcessor");
+var catchProcessor = /* @__PURE__ */ __name((schema, ctx, json2, params) => {
+ const def = schema._zod.def;
+ process14(def.innerType, ctx, params);
+ const seen = ctx.seen.get(schema);
+ seen.ref = def.innerType;
+ let catchValue;
+ try {
+ catchValue = def.catchValue(void 0);
+ } catch {
+ throw new Error("Dynamic catch values are not supported in JSON Schema");
+ }
+ json2.default = catchValue;
+}, "catchProcessor");
+var pipeProcessor = /* @__PURE__ */ __name((schema, ctx, _json, params) => {
+ const def = schema._zod.def;
+ const inIsTransform = def.in._zod.traits.has("$ZodTransform");
+ const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out;
+ process14(innerType, ctx, params);
+ const seen = ctx.seen.get(schema);
+ seen.ref = innerType;
+}, "pipeProcessor");
+var readonlyProcessor = /* @__PURE__ */ __name((schema, ctx, json2, params) => {
+ const def = schema._zod.def;
+ process14(def.innerType, ctx, params);
+ const seen = ctx.seen.get(schema);
+ seen.ref = def.innerType;
+ json2.readOnly = true;
+}, "readonlyProcessor");
+var promiseProcessor = /* @__PURE__ */ __name((schema, ctx, _json, params) => {
+ const def = schema._zod.def;
+ process14(def.innerType, ctx, params);
+ const seen = ctx.seen.get(schema);
+ seen.ref = def.innerType;
+}, "promiseProcessor");
+var optionalProcessor = /* @__PURE__ */ __name((schema, ctx, _json, params) => {
+ const def = schema._zod.def;
+ process14(def.innerType, ctx, params);
+ const seen = ctx.seen.get(schema);
+ seen.ref = def.innerType;
+}, "optionalProcessor");
+var lazyProcessor = /* @__PURE__ */ __name((schema, ctx, _json, params) => {
+ const innerType = schema._zod.innerType;
+ process14(innerType, ctx, params);
+ const seen = ctx.seen.get(schema);
+ seen.ref = innerType;
+}, "lazyProcessor");
+var allProcessors = {
+ string: stringProcessor,
+ number: numberProcessor,
+ boolean: booleanProcessor,
+ bigint: bigintProcessor,
+ symbol: symbolProcessor,
+ null: nullProcessor,
+ undefined: undefinedProcessor,
+ void: voidProcessor,
+ never: neverProcessor,
+ any: anyProcessor,
+ unknown: unknownProcessor,
+ date: dateProcessor,
+ enum: enumProcessor,
+ literal: literalProcessor,
+ nan: nanProcessor,
+ template_literal: templateLiteralProcessor,
+ file: fileProcessor,
+ success: successProcessor,
+ custom: customProcessor,
+ function: functionProcessor,
+ transform: transformProcessor,
+ map: mapProcessor,
+ set: setProcessor,
+ array: arrayProcessor,
+ object: objectProcessor,
+ union: unionProcessor,
+ intersection: intersectionProcessor,
+ tuple: tupleProcessor,
+ record: recordProcessor,
+ nullable: nullableProcessor,
+ nonoptional: nonoptionalProcessor,
+ default: defaultProcessor,
+ prefault: prefaultProcessor,
+ catch: catchProcessor,
+ pipe: pipeProcessor,
+ readonly: readonlyProcessor,
+ promise: promiseProcessor,
+ optional: optionalProcessor,
+ lazy: lazyProcessor
+};
+function toJSONSchema(input, params) {
+ if ("_idmap" in input) {
+ const registry2 = input;
+ const ctx2 = initializeContext({ ...params, processors: allProcessors });
+ const defs = {};
+ for (const entry of registry2._idmap.entries()) {
+ const [_, schema] = entry;
+ process14(schema, ctx2);
+ }
+ const schemas = {};
+ const external = {
+ registry: registry2,
+ uri: params?.uri,
+ defs
+ };
+ ctx2.external = external;
+ for (const entry of registry2._idmap.entries()) {
+ const [key, schema] = entry;
+ extractDefs(ctx2, schema);
+ schemas[key] = finalize(ctx2, schema);
+ }
+ if (Object.keys(defs).length > 0) {
+ const defsSegment = ctx2.target === "draft-2020-12" ? "$defs" : "definitions";
+ schemas.__shared = {
+ [defsSegment]: defs
+ };
+ }
+ return { schemas };
+ }
+ const ctx = initializeContext({ ...params, processors: allProcessors });
+ process14(input, ctx);
+ extractDefs(ctx, input);
+ return finalize(ctx, input);
+}
+__name(toJSONSchema, "toJSONSchema");
+
+// node_modules/zod/v4/core/json-schema-generator.js
+init_esbuild_shims();
+var JSONSchemaGenerator = class {
+ static {
+ __name(this, "JSONSchemaGenerator");
+ }
+ /** @deprecated Access via ctx instead */
+ get metadataRegistry() {
+ return this.ctx.metadataRegistry;
+ }
+ /** @deprecated Access via ctx instead */
+ get target() {
+ return this.ctx.target;
+ }
+ /** @deprecated Access via ctx instead */
+ get unrepresentable() {
+ return this.ctx.unrepresentable;
+ }
+ /** @deprecated Access via ctx instead */
+ get override() {
+ return this.ctx.override;
+ }
+ /** @deprecated Access via ctx instead */
+ get io() {
+ return this.ctx.io;
+ }
+ /** @deprecated Access via ctx instead */
+ get counter() {
+ return this.ctx.counter;
+ }
+ set counter(value) {
+ this.ctx.counter = value;
+ }
+ /** @deprecated Access via ctx instead */
+ get seen() {
+ return this.ctx.seen;
+ }
+ constructor(params) {
+ let normalizedTarget = params?.target ?? "draft-2020-12";
+ if (normalizedTarget === "draft-4")
+ normalizedTarget = "draft-04";
+ if (normalizedTarget === "draft-7")
+ normalizedTarget = "draft-07";
+ this.ctx = initializeContext({
+ processors: allProcessors,
+ target: normalizedTarget,
+ ...params?.metadata && { metadata: params.metadata },
+ ...params?.unrepresentable && { unrepresentable: params.unrepresentable },
+ ...params?.override && { override: params.override },
+ ...params?.io && { io: params.io }
+ });
+ }
+ /**
+ * Process a schema to prepare it for JSON Schema generation.
+ * This must be called before emit().
+ */
+ process(schema, _params = { path: [], schemaPath: [] }) {
+ return process14(schema, this.ctx, _params);
+ }
+ /**
+ * Emit the final JSON Schema after processing.
+ * Must call process() first.
+ */
+ emit(schema, _params) {
+ if (_params) {
+ if (_params.cycles)
+ this.ctx.cycles = _params.cycles;
+ if (_params.reused)
+ this.ctx.reused = _params.reused;
+ if (_params.external)
+ this.ctx.external = _params.external;
+ }
+ extractDefs(this.ctx, schema);
+ const result = finalize(this.ctx, schema);
+ const { "~standard": _, ...plainResult } = result;
+ return plainResult;
+ }
+};
+
+// node_modules/zod/v4/core/json-schema.js
+var json_schema_exports = {};
+init_esbuild_shims();
+
+// node_modules/zod/v4/classic/schemas.js
+var schemas_exports2 = {};
+__export(schemas_exports2, {
+ ZodAny: () => ZodAny,
+ ZodArray: () => ZodArray,
+ ZodBase64: () => ZodBase64,
+ ZodBase64URL: () => ZodBase64URL,
+ ZodBigInt: () => ZodBigInt,
+ ZodBigIntFormat: () => ZodBigIntFormat,
+ ZodBoolean: () => ZodBoolean,
+ ZodCIDRv4: () => ZodCIDRv4,
+ ZodCIDRv6: () => ZodCIDRv6,
+ ZodCUID: () => ZodCUID,
+ ZodCUID2: () => ZodCUID2,
+ ZodCatch: () => ZodCatch,
+ ZodCodec: () => ZodCodec,
+ ZodCustom: () => ZodCustom,
+ ZodCustomStringFormat: () => ZodCustomStringFormat,
+ ZodDate: () => ZodDate,
+ ZodDefault: () => ZodDefault,
+ ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
+ ZodE164: () => ZodE164,
+ ZodEmail: () => ZodEmail,
+ ZodEmoji: () => ZodEmoji,
+ ZodEnum: () => ZodEnum,
+ ZodExactOptional: () => ZodExactOptional,
+ ZodFile: () => ZodFile,
+ ZodFunction: () => ZodFunction,
+ ZodGUID: () => ZodGUID,
+ ZodIPv4: () => ZodIPv4,
+ ZodIPv6: () => ZodIPv6,
+ ZodIntersection: () => ZodIntersection,
+ ZodJWT: () => ZodJWT,
+ ZodKSUID: () => ZodKSUID,
+ ZodLazy: () => ZodLazy,
+ ZodLiteral: () => ZodLiteral,
+ ZodMAC: () => ZodMAC,
+ ZodMap: () => ZodMap,
+ ZodNaN: () => ZodNaN,
+ ZodNanoID: () => ZodNanoID,
+ ZodNever: () => ZodNever,
+ ZodNonOptional: () => ZodNonOptional,
+ ZodNull: () => ZodNull,
+ ZodNullable: () => ZodNullable,
+ ZodNumber: () => ZodNumber,
+ ZodNumberFormat: () => ZodNumberFormat,
+ ZodObject: () => ZodObject,
+ ZodOptional: () => ZodOptional,
+ ZodPipe: () => ZodPipe,
+ ZodPrefault: () => ZodPrefault,
+ ZodPreprocess: () => ZodPreprocess,
+ ZodPromise: () => ZodPromise,
+ ZodReadonly: () => ZodReadonly,
+ ZodRecord: () => ZodRecord,
+ ZodSet: () => ZodSet,
+ ZodString: () => ZodString,
+ ZodStringFormat: () => ZodStringFormat,
+ ZodSuccess: () => ZodSuccess,
+ ZodSymbol: () => ZodSymbol,
+ ZodTemplateLiteral: () => ZodTemplateLiteral,
+ ZodTransform: () => ZodTransform,
+ ZodTuple: () => ZodTuple,
+ ZodType: () => ZodType,
+ ZodULID: () => ZodULID,
+ ZodURL: () => ZodURL,
+ ZodUUID: () => ZodUUID,
+ ZodUndefined: () => ZodUndefined,
+ ZodUnion: () => ZodUnion,
+ ZodUnknown: () => ZodUnknown,
+ ZodVoid: () => ZodVoid,
+ ZodXID: () => ZodXID,
+ ZodXor: () => ZodXor,
+ _ZodString: () => _ZodString,
+ _default: () => _default2,
+ _function: () => _function,
+ any: () => any,
+ array: () => array,
+ base64: () => base642,
+ base64url: () => base64url2,
+ bigint: () => bigint2,
+ boolean: () => boolean2,
+ catch: () => _catch2,
+ check: () => check2,
+ cidrv4: () => cidrv42,
+ cidrv6: () => cidrv62,
+ codec: () => codec,
+ cuid: () => cuid3,
+ cuid2: () => cuid22,
+ custom: () => custom,
+ date: () => date3,
+ describe: () => describe2,
+ discriminatedUnion: () => discriminatedUnion,
+ e164: () => e1642,
+ email: () => email2,
+ emoji: () => emoji2,
+ enum: () => _enum2,
+ exactOptional: () => exactOptional,
+ file: () => file,
+ float32: () => float32,
+ float64: () => float64,
+ function: () => _function,
+ guid: () => guid2,
+ hash: () => hash,
+ hex: () => hex2,
+ hostname: () => hostname2,
+ httpUrl: () => httpUrl,
+ instanceof: () => _instanceof,
+ int: () => int,
+ int32: () => int32,
+ int64: () => int64,
+ intersection: () => intersection,
+ invertCodec: () => invertCodec,
+ ipv4: () => ipv42,
+ ipv6: () => ipv62,
+ json: () => json,
+ jwt: () => jwt,
+ keyof: () => keyof,
+ ksuid: () => ksuid2,
+ lazy: () => lazy,
+ literal: () => literal,
+ looseObject: () => looseObject,
+ looseRecord: () => looseRecord,
+ mac: () => mac2,
+ map: () => map,
+ meta: () => meta2,
+ nan: () => nan,
+ nanoid: () => nanoid2,
+ nativeEnum: () => nativeEnum,
+ never: () => never,
+ nonoptional: () => nonoptional,
+ null: () => _null3,
+ nullable: () => nullable,
+ nullish: () => nullish2,
+ number: () => number2,
+ object: () => object,
+ optional: () => optional,
+ partialRecord: () => partialRecord,
+ pipe: () => pipe,
+ prefault: () => prefault,
+ preprocess: () => preprocess,
+ promise: () => promise,
+ readonly: () => readonly,
+ record: () => record,
+ refine: () => refine,
+ set: () => set,
+ strictObject: () => strictObject,
+ string: () => string2,
+ stringFormat: () => stringFormat,
+ stringbool: () => stringbool,
+ success: () => success,
+ superRefine: () => superRefine,
+ symbol: () => symbol,
+ templateLiteral: () => templateLiteral,
+ transform: () => transform,
+ tuple: () => tuple,
+ uint32: () => uint32,
+ uint64: () => uint64,
+ ulid: () => ulid2,
+ undefined: () => _undefined3,
+ union: () => union,
+ unknown: () => unknown,
+ url: () => url,
+ uuid: () => uuid2,
+ uuidv4: () => uuidv4,
+ uuidv6: () => uuidv6,
+ uuidv7: () => uuidv7,
+ void: () => _void2,
+ xid: () => xid2,
+ xor: () => xor
+});
+init_esbuild_shims();
+
+// node_modules/zod/v4/classic/checks.js
+var checks_exports2 = {};
+__export(checks_exports2, {
+ endsWith: () => _endsWith,
+ gt: () => _gt,
+ gte: () => _gte,
+ includes: () => _includes,
+ length: () => _length,
+ lowercase: () => _lowercase,
+ lt: () => _lt,
+ lte: () => _lte,
+ maxLength: () => _maxLength,
+ maxSize: () => _maxSize,
+ mime: () => _mime,
+ minLength: () => _minLength,
+ minSize: () => _minSize,
+ multipleOf: () => _multipleOf,
+ negative: () => _negative,
+ nonnegative: () => _nonnegative,
+ nonpositive: () => _nonpositive,
+ normalize: () => _normalize,
+ overwrite: () => _overwrite,
+ positive: () => _positive,
+ property: () => _property,
+ regex: () => _regex,
+ size: () => _size,
+ slugify: () => _slugify,
+ startsWith: () => _startsWith,
+ toLowerCase: () => _toLowerCase,
+ toUpperCase: () => _toUpperCase,
+ trim: () => _trim,
+ uppercase: () => _uppercase
+});
+init_esbuild_shims();
+
+// node_modules/zod/v4/classic/iso.js
+var iso_exports = {};
+__export(iso_exports, {
+ ZodISODate: () => ZodISODate,
+ ZodISODateTime: () => ZodISODateTime,
+ ZodISODuration: () => ZodISODuration,
+ ZodISOTime: () => ZodISOTime,
+ date: () => date2,
+ datetime: () => datetime2,
+ duration: () => duration2,
+ time: () => time2
+});
+init_esbuild_shims();
+var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => {
+ $ZodISODateTime.init(inst, def);
+ ZodStringFormat.init(inst, def);
+});
+function datetime2(params) {
+ return _isoDateTime(ZodISODateTime, params);
+}
+__name(datetime2, "datetime");
+var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => {
+ $ZodISODate.init(inst, def);
+ ZodStringFormat.init(inst, def);
+});
+function date2(params) {
+ return _isoDate(ZodISODate, params);
+}
+__name(date2, "date");
+var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => {
+ $ZodISOTime.init(inst, def);
+ ZodStringFormat.init(inst, def);
+});
+function time2(params) {
+ return _isoTime(ZodISOTime, params);
+}
+__name(time2, "time");
+var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => {
+ $ZodISODuration.init(inst, def);
+ ZodStringFormat.init(inst, def);
+});
+function duration2(params) {
+ return _isoDuration(ZodISODuration, params);
+}
+__name(duration2, "duration");
+
+// node_modules/zod/v4/classic/parse.js
+init_esbuild_shims();
+
+// node_modules/zod/v4/classic/errors.js
+init_esbuild_shims();
+var initializer2 = /* @__PURE__ */ __name((inst, issues) => {
+ $ZodError.init(inst, issues);
+ inst.name = "ZodError";
+ Object.defineProperties(inst, {
+ format: {
+ value: /* @__PURE__ */ __name((mapper) => formatError(inst, mapper), "value")
+ // enumerable: false,
+ },
+ flatten: {
+ value: /* @__PURE__ */ __name((mapper) => flattenError(inst, mapper), "value")
+ // enumerable: false,
+ },
+ addIssue: {
+ value: /* @__PURE__ */ __name((issue2) => {
+ inst.issues.push(issue2);
+ inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
+ }, "value")
+ // enumerable: false,
+ },
+ addIssues: {
+ value: /* @__PURE__ */ __name((issues2) => {
+ inst.issues.push(...issues2);
+ inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
+ }, "value")
+ // enumerable: false,
+ },
+ isEmpty: {
+ get() {
+ return inst.issues.length === 0;
+ }
+ // enumerable: false,
+ }
+ });
+}, "initializer");
+var ZodError = /* @__PURE__ */ $constructor("ZodError", initializer2);
+var ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, {
+ Parent: Error
+});
+
+// node_modules/zod/v4/classic/parse.js
+var parse3 = /* @__PURE__ */ _parse(ZodRealError);
+var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError);
+var safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError);
+var safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError);
+var encode2 = /* @__PURE__ */ _encode(ZodRealError);
+var decode2 = /* @__PURE__ */ _decode(ZodRealError);
+var encodeAsync2 = /* @__PURE__ */ _encodeAsync(ZodRealError);
+var decodeAsync2 = /* @__PURE__ */ _decodeAsync(ZodRealError);
+var safeEncode2 = /* @__PURE__ */ _safeEncode(ZodRealError);
+var safeDecode2 = /* @__PURE__ */ _safeDecode(ZodRealError);
+var safeEncodeAsync2 = /* @__PURE__ */ _safeEncodeAsync(ZodRealError);
+var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);
+
+// node_modules/zod/v4/classic/schemas.js
+var _installedGroups = /* @__PURE__ */ new WeakMap();
+function _installLazyMethods(inst, group, methods) {
+ const proto4 = Object.getPrototypeOf(inst);
+ let installed = _installedGroups.get(proto4);
+ if (!installed) {
+ installed = /* @__PURE__ */ new Set();
+ _installedGroups.set(proto4, installed);
+ }
+ if (installed.has(group))
+ return;
+ installed.add(group);
+ for (const key in methods) {
+ const fn = methods[key];
+ Object.defineProperty(proto4, key, {
+ configurable: true,
+ enumerable: false,
+ get() {
+ const bound = fn.bind(this);
+ Object.defineProperty(this, key, {
+ configurable: true,
+ writable: true,
+ enumerable: true,
+ value: bound
+ });
+ return bound;
+ },
+ set(v) {
+ Object.defineProperty(this, key, {
+ configurable: true,
+ writable: true,
+ enumerable: true,
+ value: v
+ });
+ }
+ });
+ }
+}
+__name(_installLazyMethods, "_installLazyMethods");
+var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
+ $ZodType.init(inst, def);
+ Object.assign(inst["~standard"], {
+ jsonSchema: {
+ input: createStandardJSONSchemaMethod(inst, "input"),
+ output: createStandardJSONSchemaMethod(inst, "output")
+ }
+ });
+ inst.toJSONSchema = createToJSONSchemaMethod(inst, {});
+ inst.def = def;
+ inst.type = def.type;
+ Object.defineProperty(inst, "_def", { value: def });
+ inst.parse = (data, params) => parse3(inst, data, params, { callee: inst.parse });
+ inst.safeParse = (data, params) => safeParse2(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.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);
+ inst.safeEncode = (data, params) => safeEncode2(inst, data, params);
+ inst.safeDecode = (data, params) => safeDecode2(inst, data, params);
+ inst.safeEncodeAsync = async (data, params) => safeEncodeAsync2(inst, data, params);
+ inst.safeDecodeAsync = async (data, params) => safeDecodeAsync2(inst, data, params);
+ _installLazyMethods(inst, "ZodType", {
+ check(...chks) {
+ const def2 = this.def;
+ return this.clone(util_exports.mergeDefs(def2, {
+ checks: [
+ ...def2.checks ?? [],
+ ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch)
+ ]
+ }), { parent: true });
+ },
+ with(...chks) {
+ return this.check(...chks);
+ },
+ clone(def2, params) {
+ return clone(this, def2, params);
+ },
+ brand() {
+ return this;
+ },
+ register(reg, meta3) {
+ reg.add(this, meta3);
+ return this;
+ },
+ refine(check3, params) {
+ return this.check(refine(check3, params));
+ },
+ superRefine(refinement, params) {
+ return this.check(superRefine(refinement, params));
+ },
+ overwrite(fn) {
+ return this.check(_overwrite(fn));
+ },
+ optional() {
+ return optional(this);
+ },
+ exactOptional() {
+ return exactOptional(this);
+ },
+ nullable() {
+ return nullable(this);
+ },
+ nullish() {
+ return optional(nullable(this));
+ },
+ nonoptional(params) {
+ return nonoptional(this, params);
+ },
+ array() {
+ return array(this);
+ },
+ or(arg) {
+ return union([this, arg]);
+ },
+ and(arg) {
+ return intersection(this, arg);
+ },
+ transform(tx) {
+ return pipe(this, transform(tx));
+ },
+ default(d) {
+ return _default2(this, d);
+ },
+ prefault(d) {
+ return prefault(this, d);
+ },
+ catch(params) {
+ return _catch2(this, params);
+ },
+ pipe(target) {
+ return pipe(this, target);
+ },
+ readonly() {
+ return readonly(this);
+ },
+ describe(description) {
+ const cl = this.clone();
+ globalRegistry.add(cl, { description });
+ return cl;
+ },
+ meta(...args) {
+ if (args.length === 0)
+ return globalRegistry.get(this);
+ const cl = this.clone();
+ globalRegistry.add(cl, args[0]);
+ return cl;
+ },
+ isOptional() {
+ return this.safeParse(void 0).success;
+ },
+ isNullable() {
+ return this.safeParse(null).success;
+ },
+ apply(fn) {
+ return fn(this);
+ }
+ });
+ Object.defineProperty(inst, "description", {
+ get() {
+ return globalRegistry.get(inst)?.description;
+ },
+ configurable: true
+ });
+ return inst;
+});
+var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => {
+ $ZodString.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => stringProcessor(inst, ctx, json2, params);
+ const bag = inst._zod.bag;
+ inst.format = bag.format ?? null;
+ inst.minLength = bag.minimum ?? null;
+ inst.maxLength = bag.maximum ?? null;
+ _installLazyMethods(inst, "_ZodString", {
+ regex(...args) {
+ return this.check(_regex(...args));
+ },
+ includes(...args) {
+ return this.check(_includes(...args));
+ },
+ startsWith(...args) {
+ return this.check(_startsWith(...args));
+ },
+ endsWith(...args) {
+ return this.check(_endsWith(...args));
+ },
+ min(...args) {
+ return this.check(_minLength(...args));
+ },
+ max(...args) {
+ return this.check(_maxLength(...args));
+ },
+ length(...args) {
+ return this.check(_length(...args));
+ },
+ nonempty(...args) {
+ return this.check(_minLength(1, ...args));
+ },
+ lowercase(params) {
+ return this.check(_lowercase(params));
+ },
+ uppercase(params) {
+ return this.check(_uppercase(params));
+ },
+ trim() {
+ return this.check(_trim());
+ },
+ normalize(...args) {
+ return this.check(_normalize(...args));
+ },
+ toLowerCase() {
+ return this.check(_toLowerCase());
+ },
+ toUpperCase() {
+ return this.check(_toUpperCase());
+ },
+ slugify() {
+ return this.check(_slugify());
+ }
+ });
+});
+var ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => {
+ $ZodString.init(inst, def);
+ _ZodString.init(inst, def);
+ inst.email = (params) => inst.check(_email(ZodEmail, params));
+ inst.url = (params) => inst.check(_url(ZodURL, params));
+ inst.jwt = (params) => inst.check(_jwt(ZodJWT, params));
+ inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params));
+ inst.guid = (params) => inst.check(_guid(ZodGUID, params));
+ inst.uuid = (params) => inst.check(_uuid(ZodUUID, params));
+ inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params));
+ inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params));
+ inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params));
+ inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params));
+ inst.guid = (params) => inst.check(_guid(ZodGUID, params));
+ inst.cuid = (params) => inst.check(_cuid(ZodCUID, params));
+ inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params));
+ inst.ulid = (params) => inst.check(_ulid(ZodULID, params));
+ inst.base64 = (params) => inst.check(_base64(ZodBase64, params));
+ inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params));
+ inst.xid = (params) => inst.check(_xid(ZodXID, params));
+ inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params));
+ inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params));
+ inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params));
+ inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params));
+ inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params));
+ inst.e164 = (params) => inst.check(_e164(ZodE164, params));
+ inst.datetime = (params) => inst.check(datetime2(params));
+ inst.date = (params) => inst.check(date2(params));
+ inst.time = (params) => inst.check(time2(params));
+ inst.duration = (params) => inst.check(duration2(params));
+});
+function string2(params) {
+ return _string(ZodString, params);
+}
+__name(string2, "string");
+var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => {
+ $ZodStringFormat.init(inst, def);
+ _ZodString.init(inst, def);
+});
+var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => {
+ $ZodEmail.init(inst, def);
+ ZodStringFormat.init(inst, def);
+});
+function email2(params) {
+ return _email(ZodEmail, params);
+}
+__name(email2, "email");
+var ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => {
+ $ZodGUID.init(inst, def);
+ ZodStringFormat.init(inst, def);
+});
+function guid2(params) {
+ return _guid(ZodGUID, params);
+}
+__name(guid2, "guid");
+var ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => {
+ $ZodUUID.init(inst, def);
+ ZodStringFormat.init(inst, def);
+});
+function uuid2(params) {
+ return _uuid(ZodUUID, params);
+}
+__name(uuid2, "uuid");
+function uuidv4(params) {
+ return _uuidv4(ZodUUID, params);
+}
+__name(uuidv4, "uuidv4");
+function uuidv6(params) {
+ return _uuidv6(ZodUUID, params);
+}
+__name(uuidv6, "uuidv6");
+function uuidv7(params) {
+ return _uuidv7(ZodUUID, params);
+}
+__name(uuidv7, "uuidv7");
+var ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => {
+ $ZodURL.init(inst, def);
+ ZodStringFormat.init(inst, def);
+});
+function url(params) {
+ return _url(ZodURL, params);
+}
+__name(url, "url");
+function httpUrl(params) {
+ return _url(ZodURL, {
+ protocol: regexes_exports.httpProtocol,
+ hostname: regexes_exports.domain,
+ ...util_exports.normalizeParams(params)
+ });
+}
+__name(httpUrl, "httpUrl");
+var ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => {
+ $ZodEmoji.init(inst, def);
+ ZodStringFormat.init(inst, def);
+});
+function emoji2(params) {
+ return _emoji2(ZodEmoji, params);
+}
+__name(emoji2, "emoji");
+var ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => {
+ $ZodNanoID.init(inst, def);
+ ZodStringFormat.init(inst, def);
+});
+function nanoid2(params) {
+ return _nanoid(ZodNanoID, params);
+}
+__name(nanoid2, "nanoid");
+var ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => {
+ $ZodCUID.init(inst, def);
+ ZodStringFormat.init(inst, def);
+});
+function cuid3(params) {
+ return _cuid(ZodCUID, params);
+}
+__name(cuid3, "cuid");
+var ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => {
+ $ZodCUID2.init(inst, def);
+ ZodStringFormat.init(inst, def);
+});
+function cuid22(params) {
+ return _cuid2(ZodCUID2, params);
+}
+__name(cuid22, "cuid2");
+var ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => {
+ $ZodULID.init(inst, def);
+ ZodStringFormat.init(inst, def);
+});
+function ulid2(params) {
+ return _ulid(ZodULID, params);
+}
+__name(ulid2, "ulid");
+var ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => {
+ $ZodXID.init(inst, def);
+ ZodStringFormat.init(inst, def);
+});
+function xid2(params) {
+ return _xid(ZodXID, params);
+}
+__name(xid2, "xid");
+var ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => {
+ $ZodKSUID.init(inst, def);
+ ZodStringFormat.init(inst, def);
+});
+function ksuid2(params) {
+ return _ksuid(ZodKSUID, params);
+}
+__name(ksuid2, "ksuid");
+var ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => {
+ $ZodIPv4.init(inst, def);
+ ZodStringFormat.init(inst, def);
+});
+function ipv42(params) {
+ return _ipv4(ZodIPv4, params);
+}
+__name(ipv42, "ipv4");
+var ZodMAC = /* @__PURE__ */ $constructor("ZodMAC", (inst, def) => {
+ $ZodMAC.init(inst, def);
+ ZodStringFormat.init(inst, def);
+});
+function mac2(params) {
+ return _mac(ZodMAC, params);
+}
+__name(mac2, "mac");
+var ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => {
+ $ZodIPv6.init(inst, def);
+ ZodStringFormat.init(inst, def);
+});
+function ipv62(params) {
+ return _ipv6(ZodIPv6, params);
+}
+__name(ipv62, "ipv6");
+var ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => {
+ $ZodCIDRv4.init(inst, def);
+ ZodStringFormat.init(inst, def);
+});
+function cidrv42(params) {
+ return _cidrv4(ZodCIDRv4, params);
+}
+__name(cidrv42, "cidrv4");
+var ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => {
+ $ZodCIDRv6.init(inst, def);
+ ZodStringFormat.init(inst, def);
+});
+function cidrv62(params) {
+ return _cidrv6(ZodCIDRv6, params);
+}
+__name(cidrv62, "cidrv6");
+var ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => {
+ $ZodBase64.init(inst, def);
+ ZodStringFormat.init(inst, def);
+});
+function base642(params) {
+ return _base64(ZodBase64, params);
+}
+__name(base642, "base64");
+var ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => {
+ $ZodBase64URL.init(inst, def);
+ ZodStringFormat.init(inst, def);
+});
+function base64url2(params) {
+ return _base64url(ZodBase64URL, params);
+}
+__name(base64url2, "base64url");
+var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => {
+ $ZodE164.init(inst, def);
+ ZodStringFormat.init(inst, def);
+});
+function e1642(params) {
+ return _e164(ZodE164, params);
+}
+__name(e1642, "e164");
+var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => {
+ $ZodJWT.init(inst, def);
+ ZodStringFormat.init(inst, def);
+});
+function jwt(params) {
+ return _jwt(ZodJWT, params);
+}
+__name(jwt, "jwt");
+var ZodCustomStringFormat = /* @__PURE__ */ $constructor("ZodCustomStringFormat", (inst, def) => {
+ $ZodCustomStringFormat.init(inst, def);
+ ZodStringFormat.init(inst, def);
+});
+function stringFormat(format3, fnOrRegex, _params = {}) {
+ return _stringFormat(ZodCustomStringFormat, format3, fnOrRegex, _params);
+}
+__name(stringFormat, "stringFormat");
+function hostname2(_params) {
+ return _stringFormat(ZodCustomStringFormat, "hostname", regexes_exports.hostname, _params);
+}
+__name(hostname2, "hostname");
+function hex2(_params) {
+ return _stringFormat(ZodCustomStringFormat, "hex", regexes_exports.hex, _params);
+}
+__name(hex2, "hex");
+function hash(alg, params) {
+ const enc = params?.enc ?? "hex";
+ const format3 = `${alg}_${enc}`;
+ const regex2 = regexes_exports[format3];
+ if (!regex2)
+ throw new Error(`Unrecognized hash format: ${format3}`);
+ return _stringFormat(ZodCustomStringFormat, format3, regex2, params);
+}
+__name(hash, "hash");
+var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => {
+ $ZodNumber.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => numberProcessor(inst, ctx, json2, params);
+ _installLazyMethods(inst, "ZodNumber", {
+ gt(value, params) {
+ return this.check(_gt(value, params));
+ },
+ gte(value, params) {
+ return this.check(_gte(value, params));
+ },
+ min(value, params) {
+ return this.check(_gte(value, params));
+ },
+ lt(value, params) {
+ return this.check(_lt(value, params));
+ },
+ lte(value, params) {
+ return this.check(_lte(value, params));
+ },
+ max(value, params) {
+ return this.check(_lte(value, params));
+ },
+ int(params) {
+ return this.check(int(params));
+ },
+ safe(params) {
+ return this.check(int(params));
+ },
+ positive(params) {
+ return this.check(_gt(0, params));
+ },
+ nonnegative(params) {
+ return this.check(_gte(0, params));
+ },
+ negative(params) {
+ return this.check(_lt(0, params));
+ },
+ nonpositive(params) {
+ return this.check(_lte(0, params));
+ },
+ multipleOf(value, params) {
+ return this.check(_multipleOf(value, params));
+ },
+ step(value, params) {
+ return this.check(_multipleOf(value, params));
+ },
+ finite() {
+ return this;
+ }
+ });
+ const bag = inst._zod.bag;
+ inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;
+ inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;
+ inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5);
+ inst.isFinite = true;
+ inst.format = bag.format ?? null;
+});
+function number2(params) {
+ return _number(ZodNumber, params);
+}
+__name(number2, "number");
+var ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => {
+ $ZodNumberFormat.init(inst, def);
+ ZodNumber.init(inst, def);
+});
+function int(params) {
+ return _int(ZodNumberFormat, params);
+}
+__name(int, "int");
+function float32(params) {
+ return _float32(ZodNumberFormat, params);
+}
+__name(float32, "float32");
+function float64(params) {
+ return _float64(ZodNumberFormat, params);
+}
+__name(float64, "float64");
+function int32(params) {
+ return _int32(ZodNumberFormat, params);
+}
+__name(int32, "int32");
+function uint32(params) {
+ return _uint32(ZodNumberFormat, params);
+}
+__name(uint32, "uint32");
+var ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => {
+ $ZodBoolean.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => booleanProcessor(inst, ctx, json2, params);
+});
+function boolean2(params) {
+ return _boolean(ZodBoolean, params);
+}
+__name(boolean2, "boolean");
+var ZodBigInt = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => {
+ $ZodBigInt.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => bigintProcessor(inst, ctx, json2, params);
+ inst.gte = (value, params) => inst.check(_gte(value, params));
+ inst.min = (value, params) => inst.check(_gte(value, params));
+ inst.gt = (value, params) => inst.check(_gt(value, params));
+ inst.gte = (value, params) => inst.check(_gte(value, params));
+ inst.min = (value, params) => inst.check(_gte(value, params));
+ inst.lt = (value, params) => inst.check(_lt(value, params));
+ inst.lte = (value, params) => inst.check(_lte(value, params));
+ inst.max = (value, params) => inst.check(_lte(value, params));
+ inst.positive = (params) => inst.check(_gt(BigInt(0), params));
+ inst.negative = (params) => inst.check(_lt(BigInt(0), params));
+ inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params));
+ inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params));
+ inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params));
+ const bag = inst._zod.bag;
+ inst.minValue = bag.minimum ?? null;
+ inst.maxValue = bag.maximum ?? null;
+ inst.format = bag.format ?? null;
+});
+function bigint2(params) {
+ return _bigint(ZodBigInt, params);
+}
+__name(bigint2, "bigint");
+var ZodBigIntFormat = /* @__PURE__ */ $constructor("ZodBigIntFormat", (inst, def) => {
+ $ZodBigIntFormat.init(inst, def);
+ ZodBigInt.init(inst, def);
+});
+function int64(params) {
+ return _int64(ZodBigIntFormat, params);
+}
+__name(int64, "int64");
+function uint64(params) {
+ return _uint64(ZodBigIntFormat, params);
+}
+__name(uint64, "uint64");
+var ZodSymbol = /* @__PURE__ */ $constructor("ZodSymbol", (inst, def) => {
+ $ZodSymbol.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => symbolProcessor(inst, ctx, json2, params);
+});
+function symbol(params) {
+ return _symbol(ZodSymbol, params);
+}
+__name(symbol, "symbol");
+var ZodUndefined = /* @__PURE__ */ $constructor("ZodUndefined", (inst, def) => {
+ $ZodUndefined.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => undefinedProcessor(inst, ctx, json2, params);
+});
+function _undefined3(params) {
+ return _undefined2(ZodUndefined, params);
+}
+__name(_undefined3, "_undefined");
+var ZodNull = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => {
+ $ZodNull.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => nullProcessor(inst, ctx, json2, params);
+});
+function _null3(params) {
+ return _null2(ZodNull, params);
+}
+__name(_null3, "_null");
+var ZodAny = /* @__PURE__ */ $constructor("ZodAny", (inst, def) => {
+ $ZodAny.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => anyProcessor(inst, ctx, json2, params);
+});
+function any() {
+ return _any(ZodAny);
+}
+__name(any, "any");
+var ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => {
+ $ZodUnknown.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => unknownProcessor(inst, ctx, json2, params);
+});
+function unknown() {
+ return _unknown(ZodUnknown);
+}
+__name(unknown, "unknown");
+var ZodNever = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => {
+ $ZodNever.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => neverProcessor(inst, ctx, json2, params);
+});
+function never(params) {
+ return _never(ZodNever, params);
+}
+__name(never, "never");
+var ZodVoid = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => {
+ $ZodVoid.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => voidProcessor(inst, ctx, json2, params);
+});
+function _void2(params) {
+ return _void(ZodVoid, params);
+}
+__name(_void2, "_void");
+var ZodDate = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => {
+ $ZodDate.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => dateProcessor(inst, ctx, json2, params);
+ inst.min = (value, params) => inst.check(_gte(value, params));
+ inst.max = (value, params) => inst.check(_lte(value, params));
+ const c = inst._zod.bag;
+ inst.minDate = c.minimum ? new Date(c.minimum) : null;
+ inst.maxDate = c.maximum ? new Date(c.maximum) : null;
+});
+function date3(params) {
+ return _date(ZodDate, params);
+}
+__name(date3, "date");
+var ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => {
+ $ZodArray.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => arrayProcessor(inst, ctx, json2, params);
+ inst.element = def.element;
+ _installLazyMethods(inst, "ZodArray", {
+ min(n, params) {
+ return this.check(_minLength(n, params));
+ },
+ nonempty(params) {
+ return this.check(_minLength(1, params));
+ },
+ max(n, params) {
+ return this.check(_maxLength(n, params));
+ },
+ length(n, params) {
+ return this.check(_length(n, params));
+ },
+ unwrap() {
+ return this.element;
+ }
+ });
+});
+function array(element, params) {
+ return _array(ZodArray, element, params);
+}
+__name(array, "array");
+function keyof(schema) {
+ const shape = schema._zod.def.shape;
+ return _enum2(Object.keys(shape));
+}
+__name(keyof, "keyof");
+var ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => {
+ $ZodObjectJIT.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => objectProcessor(inst, ctx, json2, params);
+ util_exports.defineLazy(inst, "shape", () => {
+ return def.shape;
+ });
+ _installLazyMethods(inst, "ZodObject", {
+ keyof() {
+ return _enum2(Object.keys(this._zod.def.shape));
+ },
+ catchall(catchall) {
+ return this.clone({ ...this._zod.def, catchall });
+ },
+ passthrough() {
+ return this.clone({ ...this._zod.def, catchall: unknown() });
+ },
+ loose() {
+ return this.clone({ ...this._zod.def, catchall: unknown() });
+ },
+ strict() {
+ return this.clone({ ...this._zod.def, catchall: never() });
+ },
+ strip() {
+ return this.clone({ ...this._zod.def, catchall: void 0 });
+ },
+ extend(incoming) {
+ return util_exports.extend(this, incoming);
+ },
+ safeExtend(incoming) {
+ return util_exports.safeExtend(this, incoming);
+ },
+ merge(other) {
+ return util_exports.merge(this, other);
+ },
+ pick(mask) {
+ return util_exports.pick(this, mask);
+ },
+ omit(mask) {
+ return util_exports.omit(this, mask);
+ },
+ partial(...args) {
+ return util_exports.partial(ZodOptional, this, args[0]);
+ },
+ required(...args) {
+ return util_exports.required(ZodNonOptional, this, args[0]);
+ }
+ });
+});
+function object(shape, params) {
+ const def = {
+ type: "object",
+ shape: shape ?? {},
+ ...util_exports.normalizeParams(params)
+ };
+ return new ZodObject(def);
+}
+__name(object, "object");
+function strictObject(shape, params) {
+ return new ZodObject({
+ type: "object",
+ shape,
+ catchall: never(),
+ ...util_exports.normalizeParams(params)
+ });
+}
+__name(strictObject, "strictObject");
+function looseObject(shape, params) {
+ return new ZodObject({
+ type: "object",
+ shape,
+ catchall: unknown(),
+ ...util_exports.normalizeParams(params)
+ });
+}
+__name(looseObject, "looseObject");
+var ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => {
+ $ZodUnion.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => unionProcessor(inst, ctx, json2, params);
+ inst.options = def.options;
+});
+function union(options2, params) {
+ return new ZodUnion({
+ type: "union",
+ options: options2,
+ ...util_exports.normalizeParams(params)
+ });
+}
+__name(union, "union");
+var ZodXor = /* @__PURE__ */ $constructor("ZodXor", (inst, def) => {
+ ZodUnion.init(inst, def);
+ $ZodXor.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => unionProcessor(inst, ctx, json2, params);
+ inst.options = def.options;
+});
+function xor(options2, params) {
+ return new ZodXor({
+ type: "union",
+ options: options2,
+ inclusive: false,
+ ...util_exports.normalizeParams(params)
+ });
+}
+__name(xor, "xor");
+var ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => {
+ ZodUnion.init(inst, def);
+ $ZodDiscriminatedUnion.init(inst, def);
+});
+function discriminatedUnion(discriminator, options2, params) {
+ return new ZodDiscriminatedUnion({
+ type: "union",
+ options: options2,
+ discriminator,
+ ...util_exports.normalizeParams(params)
+ });
+}
+__name(discriminatedUnion, "discriminatedUnion");
+var ZodIntersection = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => {
+ $ZodIntersection.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => intersectionProcessor(inst, ctx, json2, params);
+});
+function intersection(left2, right2) {
+ return new ZodIntersection({
+ type: "intersection",
+ left: left2,
+ right: right2
+ });
+}
+__name(intersection, "intersection");
+var ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => {
+ $ZodTuple.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => tupleProcessor(inst, ctx, json2, params);
+ inst.rest = (rest) => inst.clone({
+ ...inst._zod.def,
+ rest
+ });
+});
+function tuple(items, _paramsOrRest, _params) {
+ const hasRest = _paramsOrRest instanceof $ZodType;
+ const params = hasRest ? _params : _paramsOrRest;
+ const rest = hasRest ? _paramsOrRest : null;
+ return new ZodTuple({
+ type: "tuple",
+ items,
+ rest,
+ ...util_exports.normalizeParams(params)
+ });
+}
+__name(tuple, "tuple");
+var ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => {
+ $ZodRecord.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => recordProcessor(inst, ctx, json2, params);
+ inst.keyType = def.keyType;
+ inst.valueType = def.valueType;
+});
+function record(keyType, valueType, params) {
+ if (!valueType || !valueType._zod) {
+ return new ZodRecord({
+ type: "record",
+ keyType: string2(),
+ valueType: keyType,
+ ...util_exports.normalizeParams(valueType)
+ });
+ }
+ return new ZodRecord({
+ type: "record",
+ keyType,
+ valueType,
+ ...util_exports.normalizeParams(params)
+ });
+}
+__name(record, "record");
+function partialRecord(keyType, valueType, params) {
+ const k = clone(keyType);
+ k._zod.values = void 0;
+ return new ZodRecord({
+ type: "record",
+ keyType: k,
+ valueType,
+ ...util_exports.normalizeParams(params)
+ });
+}
+__name(partialRecord, "partialRecord");
+function looseRecord(keyType, valueType, params) {
+ return new ZodRecord({
+ type: "record",
+ keyType,
+ valueType,
+ mode: "loose",
+ ...util_exports.normalizeParams(params)
+ });
+}
+__name(looseRecord, "looseRecord");
+var ZodMap = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => {
+ $ZodMap.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => mapProcessor(inst, ctx, json2, params);
+ inst.keyType = def.keyType;
+ inst.valueType = def.valueType;
+ inst.min = (...args) => inst.check(_minSize(...args));
+ inst.nonempty = (params) => inst.check(_minSize(1, params));
+ inst.max = (...args) => inst.check(_maxSize(...args));
+ inst.size = (...args) => inst.check(_size(...args));
+});
+function map(keyType, valueType, params) {
+ return new ZodMap({
+ type: "map",
+ keyType,
+ valueType,
+ ...util_exports.normalizeParams(params)
+ });
+}
+__name(map, "map");
+var ZodSet = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => {
+ $ZodSet.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => setProcessor(inst, ctx, json2, params);
+ inst.min = (...args) => inst.check(_minSize(...args));
+ inst.nonempty = (params) => inst.check(_minSize(1, params));
+ inst.max = (...args) => inst.check(_maxSize(...args));
+ inst.size = (...args) => inst.check(_size(...args));
+});
+function set(valueType, params) {
+ return new ZodSet({
+ type: "set",
+ valueType,
+ ...util_exports.normalizeParams(params)
+ });
+}
+__name(set, "set");
+var ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => {
+ $ZodEnum.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => enumProcessor(inst, ctx, json2, params);
+ inst.enum = def.entries;
+ inst.options = Object.values(def.entries);
+ const keys = new Set(Object.keys(def.entries));
+ inst.extract = (values, params) => {
+ const newEntries = {};
+ for (const value of values) {
+ if (keys.has(value)) {
+ newEntries[value] = def.entries[value];
+ } else
+ throw new Error(`Key ${value} not found in enum`);
+ }
+ return new ZodEnum({
+ ...def,
+ checks: [],
+ ...util_exports.normalizeParams(params),
+ entries: newEntries
+ });
+ };
+ inst.exclude = (values, params) => {
+ const newEntries = { ...def.entries };
+ for (const value of values) {
+ if (keys.has(value)) {
+ delete newEntries[value];
+ } else
+ throw new Error(`Key ${value} not found in enum`);
+ }
+ return new ZodEnum({
+ ...def,
+ checks: [],
+ ...util_exports.normalizeParams(params),
+ entries: newEntries
+ });
+ };
+});
+function _enum2(values, params) {
+ const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
+ return new ZodEnum({
+ type: "enum",
+ entries,
+ ...util_exports.normalizeParams(params)
+ });
+}
+__name(_enum2, "_enum");
+function nativeEnum(entries, params) {
+ return new ZodEnum({
+ type: "enum",
+ entries,
+ ...util_exports.normalizeParams(params)
+ });
+}
+__name(nativeEnum, "nativeEnum");
+var ZodLiteral = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => {
+ $ZodLiteral.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => literalProcessor(inst, ctx, json2, params);
+ inst.values = new Set(def.values);
+ Object.defineProperty(inst, "value", {
+ get() {
+ if (def.values.length > 1) {
+ throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");
+ }
+ return def.values[0];
+ }
+ });
+});
+function literal(value, params) {
+ return new ZodLiteral({
+ type: "literal",
+ values: Array.isArray(value) ? value : [value],
+ ...util_exports.normalizeParams(params)
+ });
+}
+__name(literal, "literal");
+var ZodFile = /* @__PURE__ */ $constructor("ZodFile", (inst, def) => {
+ $ZodFile.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => fileProcessor(inst, ctx, json2, params);
+ inst.min = (size, params) => inst.check(_minSize(size, params));
+ inst.max = (size, params) => inst.check(_maxSize(size, params));
+ inst.mime = (types, params) => inst.check(_mime(Array.isArray(types) ? types : [types], params));
+});
+function file(params) {
+ return _file(ZodFile, params);
+}
+__name(file, "file");
+var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
+ $ZodTransform.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => transformProcessor(inst, ctx, json2, params);
+ inst._zod.parse = (payload, _ctx) => {
+ if (_ctx.direction === "backward") {
+ throw new $ZodEncodeError(inst.constructor.name);
+ }
+ payload.addIssue = (issue2) => {
+ if (typeof issue2 === "string") {
+ payload.issues.push(util_exports.issue(issue2, payload.value, def));
+ } else {
+ const _issue = issue2;
+ if (_issue.fatal)
+ _issue.continue = false;
+ _issue.code ?? (_issue.code = "custom");
+ _issue.input ?? (_issue.input = payload.value);
+ _issue.inst ?? (_issue.inst = inst);
+ payload.issues.push(util_exports.issue(_issue));
+ }
+ };
+ const output = def.transform(payload.value, payload);
+ if (output instanceof Promise) {
+ return output.then((output2) => {
+ payload.value = output2;
+ payload.fallback = true;
+ return payload;
+ });
+ }
+ payload.value = output;
+ payload.fallback = true;
+ return payload;
+ };
+});
+function transform(fn) {
+ return new ZodTransform({
+ type: "transform",
+ transform: fn
+ });
+}
+__name(transform, "transform");
+var ZodOptional = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => {
+ $ZodOptional.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => optionalProcessor(inst, ctx, json2, params);
+ inst.unwrap = () => inst._zod.def.innerType;
+});
+function optional(innerType) {
+ return new ZodOptional({
+ type: "optional",
+ innerType
+ });
+}
+__name(optional, "optional");
+var ZodExactOptional = /* @__PURE__ */ $constructor("ZodExactOptional", (inst, def) => {
+ $ZodExactOptional.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => optionalProcessor(inst, ctx, json2, params);
+ inst.unwrap = () => inst._zod.def.innerType;
+});
+function exactOptional(innerType) {
+ return new ZodExactOptional({
+ type: "optional",
+ innerType
+ });
+}
+__name(exactOptional, "exactOptional");
+var ZodNullable = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => {
+ $ZodNullable.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => nullableProcessor(inst, ctx, json2, params);
+ inst.unwrap = () => inst._zod.def.innerType;
+});
+function nullable(innerType) {
+ return new ZodNullable({
+ type: "nullable",
+ innerType
+ });
+}
+__name(nullable, "nullable");
+function nullish2(innerType) {
+ return optional(nullable(innerType));
+}
+__name(nullish2, "nullish");
+var ZodDefault = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => {
+ $ZodDefault.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => defaultProcessor(inst, ctx, json2, params);
+ inst.unwrap = () => inst._zod.def.innerType;
+ inst.removeDefault = inst.unwrap;
+});
+function _default2(innerType, defaultValue2) {
+ return new ZodDefault({
+ type: "default",
+ innerType,
+ get defaultValue() {
+ return typeof defaultValue2 === "function" ? defaultValue2() : util_exports.shallowClone(defaultValue2);
+ }
+ });
+}
+__name(_default2, "_default");
+var ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => {
+ $ZodPrefault.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => prefaultProcessor(inst, ctx, json2, params);
+ inst.unwrap = () => inst._zod.def.innerType;
+});
+function prefault(innerType, defaultValue2) {
+ return new ZodPrefault({
+ type: "prefault",
+ innerType,
+ get defaultValue() {
+ return typeof defaultValue2 === "function" ? defaultValue2() : util_exports.shallowClone(defaultValue2);
+ }
+ });
+}
+__name(prefault, "prefault");
+var ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => {
+ $ZodNonOptional.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => nonoptionalProcessor(inst, ctx, json2, params);
+ inst.unwrap = () => inst._zod.def.innerType;
+});
+function nonoptional(innerType, params) {
+ return new ZodNonOptional({
+ type: "nonoptional",
+ innerType,
+ ...util_exports.normalizeParams(params)
+ });
+}
+__name(nonoptional, "nonoptional");
+var ZodSuccess = /* @__PURE__ */ $constructor("ZodSuccess", (inst, def) => {
+ $ZodSuccess.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => successProcessor(inst, ctx, json2, params);
+ inst.unwrap = () => inst._zod.def.innerType;
+});
+function success(innerType) {
+ return new ZodSuccess({
+ type: "success",
+ innerType
+ });
+}
+__name(success, "success");
+var ZodCatch = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => {
+ $ZodCatch.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => catchProcessor(inst, ctx, json2, params);
+ inst.unwrap = () => inst._zod.def.innerType;
+ inst.removeCatch = inst.unwrap;
+});
+function _catch2(innerType, catchValue) {
+ return new ZodCatch({
+ type: "catch",
+ innerType,
+ catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
+ });
+}
+__name(_catch2, "_catch");
+var ZodNaN = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => {
+ $ZodNaN.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => nanProcessor(inst, ctx, json2, params);
+});
+function nan(params) {
+ return _nan(ZodNaN, params);
+}
+__name(nan, "nan");
+var ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => {
+ $ZodPipe.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => pipeProcessor(inst, ctx, json2, params);
+ inst.in = def.in;
+ inst.out = def.out;
+});
+function pipe(in_, out) {
+ return new ZodPipe({
+ type: "pipe",
+ in: in_,
+ out
+ // ...util.normalizeParams(params),
+ });
+}
+__name(pipe, "pipe");
+var ZodCodec = /* @__PURE__ */ $constructor("ZodCodec", (inst, def) => {
+ ZodPipe.init(inst, def);
+ $ZodCodec.init(inst, def);
+});
+function codec(in_, out, params) {
+ return new ZodCodec({
+ type: "pipe",
+ in: in_,
+ out,
+ transform: params.decode,
+ reverseTransform: params.encode
+ });
+}
+__name(codec, "codec");
+function invertCodec(codec2) {
+ const def = codec2._zod.def;
+ return new ZodCodec({
+ type: "pipe",
+ in: def.out,
+ out: def.in,
+ transform: def.reverseTransform,
+ reverseTransform: def.transform
+ });
+}
+__name(invertCodec, "invertCodec");
+var ZodPreprocess = /* @__PURE__ */ $constructor("ZodPreprocess", (inst, def) => {
+ ZodPipe.init(inst, def);
+ $ZodPreprocess.init(inst, def);
+});
+var ZodReadonly = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => {
+ $ZodReadonly.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => readonlyProcessor(inst, ctx, json2, params);
+ inst.unwrap = () => inst._zod.def.innerType;
+});
+function readonly(innerType) {
+ return new ZodReadonly({
+ type: "readonly",
+ innerType
+ });
+}
+__name(readonly, "readonly");
+var ZodTemplateLiteral = /* @__PURE__ */ $constructor("ZodTemplateLiteral", (inst, def) => {
+ $ZodTemplateLiteral.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => templateLiteralProcessor(inst, ctx, json2, params);
+});
+function templateLiteral(parts, params) {
+ return new ZodTemplateLiteral({
+ type: "template_literal",
+ parts,
+ ...util_exports.normalizeParams(params)
+ });
+}
+__name(templateLiteral, "templateLiteral");
+var ZodLazy = /* @__PURE__ */ $constructor("ZodLazy", (inst, def) => {
+ $ZodLazy.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => lazyProcessor(inst, ctx, json2, params);
+ inst.unwrap = () => inst._zod.def.getter();
+});
+function lazy(getter) {
+ return new ZodLazy({
+ type: "lazy",
+ getter
+ });
+}
+__name(lazy, "lazy");
+var ZodPromise = /* @__PURE__ */ $constructor("ZodPromise", (inst, def) => {
+ $ZodPromise.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => promiseProcessor(inst, ctx, json2, params);
+ inst.unwrap = () => inst._zod.def.innerType;
+});
+function promise(innerType) {
+ return new ZodPromise({
+ type: "promise",
+ innerType
+ });
+}
+__name(promise, "promise");
+var ZodFunction = /* @__PURE__ */ $constructor("ZodFunction", (inst, def) => {
+ $ZodFunction.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => functionProcessor(inst, ctx, json2, params);
+});
+function _function(params) {
+ return new ZodFunction({
+ type: "function",
+ input: Array.isArray(params?.input) ? tuple(params?.input) : params?.input ?? array(unknown()),
+ output: params?.output ?? unknown()
+ });
+}
+__name(_function, "_function");
+var ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => {
+ $ZodCustom.init(inst, def);
+ ZodType.init(inst, def);
+ inst._zod.processJSONSchema = (ctx, json2, params) => customProcessor(inst, ctx, json2, params);
+});
+function check2(fn) {
+ const ch = new $ZodCheck({
+ check: "custom"
+ // ...util.normalizeParams(params),
+ });
+ ch._zod.check = fn;
+ return ch;
+}
+__name(check2, "check");
+function custom(fn, _params) {
+ return _custom(ZodCustom, fn ?? (() => true), _params);
+}
+__name(custom, "custom");
+function refine(fn, _params = {}) {
+ return _refine(ZodCustom, fn, _params);
+}
+__name(refine, "refine");
+function superRefine(fn, params) {
+ return _superRefine(fn, params);
+}
+__name(superRefine, "superRefine");
+var describe2 = describe;
+var meta2 = meta;
+function _instanceof(cls, params = {}) {
+ const inst = new ZodCustom({
+ type: "custom",
+ check: "custom",
+ fn: /* @__PURE__ */ __name((data) => data instanceof cls, "fn"),
+ abort: true,
+ ...util_exports.normalizeParams(params)
+ });
+ inst._zod.bag.Class = cls;
+ inst._zod.check = (payload) => {
+ if (!(payload.value instanceof cls)) {
+ payload.issues.push({
+ code: "invalid_type",
+ expected: cls.name,
+ input: payload.value,
+ inst,
+ path: [...inst._zod.def.path ?? []]
+ });
+ }
+ };
+ return inst;
+}
+__name(_instanceof, "_instanceof");
+var stringbool = /* @__PURE__ */ __name((...args) => _stringbool({
+ Codec: ZodCodec,
+ Boolean: ZodBoolean,
+ String: ZodString
+}, ...args), "stringbool");
+function json(params) {
+ const jsonSchema = lazy(() => {
+ return union([string2(params), number2(), boolean2(), _null3(), array(jsonSchema), record(string2(), jsonSchema)]);
+ });
+ return jsonSchema;
+}
+__name(json, "json");
+function preprocess(fn, schema) {
+ return new ZodPreprocess({
+ type: "pipe",
+ in: transform(fn),
+ out: schema
+ });
+}
+__name(preprocess, "preprocess");
+
+// node_modules/zod/v4/classic/compat.js
+init_esbuild_shims();
+var ZodIssueCode = {
+ invalid_type: "invalid_type",
+ too_big: "too_big",
+ too_small: "too_small",
+ invalid_format: "invalid_format",
+ not_multiple_of: "not_multiple_of",
+ unrecognized_keys: "unrecognized_keys",
+ invalid_union: "invalid_union",
+ invalid_key: "invalid_key",
+ invalid_element: "invalid_element",
+ invalid_value: "invalid_value",
+ custom: "custom"
+};
+function setErrorMap(map2) {
+ config({
+ customError: map2
+ });
+}
+__name(setErrorMap, "setErrorMap");
+function getErrorMap() {
+ return config().customError;
+}
+__name(getErrorMap, "getErrorMap");
+var ZodFirstPartyTypeKind;
+/* @__PURE__ */ (function(ZodFirstPartyTypeKind2) {
+})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
+
+// node_modules/zod/v4/classic/from-json-schema.js
+init_esbuild_shims();
+var z = {
+ ...schemas_exports2,
+ ...checks_exports2,
+ iso: iso_exports
+};
+var RECOGNIZED_KEYS = /* @__PURE__ */ new Set([
+ // Schema identification
+ "$schema",
+ "$ref",
+ "$defs",
+ "definitions",
+ // Core schema keywords
+ "$id",
+ "id",
+ "$comment",
+ "$anchor",
+ "$vocabulary",
+ "$dynamicRef",
+ "$dynamicAnchor",
+ // Type
+ "type",
+ "enum",
+ "const",
+ // Composition
+ "anyOf",
+ "oneOf",
+ "allOf",
+ "not",
+ // Object
+ "properties",
+ "required",
+ "additionalProperties",
+ "patternProperties",
+ "propertyNames",
+ "minProperties",
+ "maxProperties",
+ // Array
+ "items",
+ "prefixItems",
+ "additionalItems",
+ "minItems",
+ "maxItems",
+ "uniqueItems",
+ "contains",
+ "minContains",
+ "maxContains",
+ // String
+ "minLength",
+ "maxLength",
+ "pattern",
+ "format",
+ // Number
+ "minimum",
+ "maximum",
+ "exclusiveMinimum",
+ "exclusiveMaximum",
+ "multipleOf",
+ // Already handled metadata
+ "description",
+ "default",
+ // Content
+ "contentEncoding",
+ "contentMediaType",
+ "contentSchema",
+ // Unsupported (error-throwing)
+ "unevaluatedItems",
+ "unevaluatedProperties",
+ "if",
+ "then",
+ "else",
+ "dependentSchemas",
+ "dependentRequired",
+ // OpenAPI
+ "nullable",
+ "readOnly"
+]);
+function detectVersion(schema, defaultTarget) {
+ const $schema = schema.$schema;
+ if ($schema === "https://json-schema.org/draft/2020-12/schema") {
+ return "draft-2020-12";
+ }
+ if ($schema === "http://json-schema.org/draft-07/schema#") {
+ return "draft-7";
+ }
+ if ($schema === "http://json-schema.org/draft-04/schema#") {
+ return "draft-4";
+ }
+ return defaultTarget ?? "draft-2020-12";
+}
+__name(detectVersion, "detectVersion");
+function resolveRef(ref, ctx) {
+ if (!ref.startsWith("#")) {
+ throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
+ }
+ const path27 = ref.slice(1).split("/").filter(Boolean);
+ if (path27.length === 0) {
+ return ctx.rootSchema;
+ }
+ const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
+ if (path27[0] === defsKey) {
+ const key = path27[1];
+ if (!key || !ctx.defs[key]) {
+ throw new Error(`Reference not found: ${ref}`);
+ }
+ return ctx.defs[key];
+ }
+ throw new Error(`Reference not found: ${ref}`);
+}
+__name(resolveRef, "resolveRef");
+function convertBaseSchema(schema, ctx) {
+ if (schema.not !== void 0) {
+ if (typeof schema.not === "object" && Object.keys(schema.not).length === 0) {
+ return z.never();
+ }
+ throw new Error("not is not supported in Zod (except { not: {} } for never)");
+ }
+ if (schema.unevaluatedItems !== void 0) {
+ throw new Error("unevaluatedItems is not supported");
+ }
+ if (schema.unevaluatedProperties !== void 0) {
+ throw new Error("unevaluatedProperties is not supported");
+ }
+ if (schema.if !== void 0 || schema.then !== void 0 || schema.else !== void 0) {
+ throw new Error("Conditional schemas (if/then/else) are not supported");
+ }
+ if (schema.dependentSchemas !== void 0 || schema.dependentRequired !== void 0) {
+ throw new Error("dependentSchemas and dependentRequired are not supported");
+ }
+ if (schema.$ref) {
+ const refPath = schema.$ref;
+ if (ctx.refs.has(refPath)) {
+ return ctx.refs.get(refPath);
+ }
+ if (ctx.processing.has(refPath)) {
+ return z.lazy(() => {
+ if (!ctx.refs.has(refPath)) {
+ throw new Error(`Circular reference not resolved: ${refPath}`);
+ }
+ return ctx.refs.get(refPath);
+ });
+ }
+ ctx.processing.add(refPath);
+ const resolved = resolveRef(refPath, ctx);
+ const zodSchema2 = convertSchema(resolved, ctx);
+ ctx.refs.set(refPath, zodSchema2);
+ ctx.processing.delete(refPath);
+ return zodSchema2;
+ }
+ if (schema.enum !== void 0) {
+ const enumValues = schema.enum;
+ if (ctx.version === "openapi-3.0" && schema.nullable === true && enumValues.length === 1 && enumValues[0] === null) {
+ return z.null();
+ }
+ if (enumValues.length === 0) {
+ return z.never();
+ }
+ if (enumValues.length === 1) {
+ return z.literal(enumValues[0]);
+ }
+ if (enumValues.every((v) => typeof v === "string")) {
+ return z.enum(enumValues);
+ }
+ const literalSchemas = enumValues.map((v) => z.literal(v));
+ if (literalSchemas.length < 2) {
+ return literalSchemas[0];
+ }
+ return z.union([literalSchemas[0], literalSchemas[1], ...literalSchemas.slice(2)]);
+ }
+ if (schema.const !== void 0) {
+ return z.literal(schema.const);
+ }
+ const type2 = schema.type;
+ if (Array.isArray(type2)) {
+ const typeSchemas = type2.map((t) => {
+ const typeSchema = { ...schema, type: t };
+ return convertBaseSchema(typeSchema, ctx);
+ });
+ if (typeSchemas.length === 0) {
+ return z.never();
+ }
+ if (typeSchemas.length === 1) {
+ return typeSchemas[0];
+ }
+ return z.union(typeSchemas);
+ }
+ if (!type2) {
+ return z.any();
+ }
+ let zodSchema;
+ switch (type2) {
+ case "string": {
+ let stringSchema = z.string();
+ if (schema.format) {
+ const format3 = schema.format;
+ if (format3 === "email") {
+ stringSchema = stringSchema.check(z.email());
+ } else if (format3 === "uri" || format3 === "uri-reference") {
+ stringSchema = stringSchema.check(z.url());
+ } else if (format3 === "uuid" || format3 === "guid") {
+ stringSchema = stringSchema.check(z.uuid());
+ } else if (format3 === "date-time") {
+ stringSchema = stringSchema.check(z.iso.datetime());
+ } else if (format3 === "date") {
+ stringSchema = stringSchema.check(z.iso.date());
+ } else if (format3 === "time") {
+ stringSchema = stringSchema.check(z.iso.time());
+ } else if (format3 === "duration") {
+ stringSchema = stringSchema.check(z.iso.duration());
+ } else if (format3 === "ipv4") {
+ stringSchema = stringSchema.check(z.ipv4());
+ } else if (format3 === "ipv6") {
+ stringSchema = stringSchema.check(z.ipv6());
+ } else if (format3 === "mac") {
+ stringSchema = stringSchema.check(z.mac());
+ } else if (format3 === "cidr") {
+ stringSchema = stringSchema.check(z.cidrv4());
+ } else if (format3 === "cidr-v6") {
+ stringSchema = stringSchema.check(z.cidrv6());
+ } else if (format3 === "base64") {
+ stringSchema = stringSchema.check(z.base64());
+ } else if (format3 === "base64url") {
+ stringSchema = stringSchema.check(z.base64url());
+ } else if (format3 === "e164") {
+ stringSchema = stringSchema.check(z.e164());
+ } else if (format3 === "jwt") {
+ stringSchema = stringSchema.check(z.jwt());
+ } else if (format3 === "emoji") {
+ stringSchema = stringSchema.check(z.emoji());
+ } else if (format3 === "nanoid") {
+ stringSchema = stringSchema.check(z.nanoid());
+ } else if (format3 === "cuid") {
+ stringSchema = stringSchema.check(z.cuid());
+ } else if (format3 === "cuid2") {
+ stringSchema = stringSchema.check(z.cuid2());
+ } else if (format3 === "ulid") {
+ stringSchema = stringSchema.check(z.ulid());
+ } else if (format3 === "xid") {
+ stringSchema = stringSchema.check(z.xid());
+ } else if (format3 === "ksuid") {
+ stringSchema = stringSchema.check(z.ksuid());
+ }
+ }
+ if (typeof schema.minLength === "number") {
+ stringSchema = stringSchema.min(schema.minLength);
+ }
+ if (typeof schema.maxLength === "number") {
+ stringSchema = stringSchema.max(schema.maxLength);
+ }
+ if (schema.pattern) {
+ stringSchema = stringSchema.regex(new RegExp(schema.pattern));
+ }
+ zodSchema = stringSchema;
+ break;
+ }
+ case "number":
+ case "integer": {
+ let numberSchema = type2 === "integer" ? z.number().int() : z.number();
+ if (typeof schema.minimum === "number") {
+ numberSchema = numberSchema.min(schema.minimum);
+ }
+ if (typeof schema.maximum === "number") {
+ numberSchema = numberSchema.max(schema.maximum);
+ }
+ if (typeof schema.exclusiveMinimum === "number") {
+ numberSchema = numberSchema.gt(schema.exclusiveMinimum);
+ } else if (schema.exclusiveMinimum === true && typeof schema.minimum === "number") {
+ numberSchema = numberSchema.gt(schema.minimum);
+ }
+ if (typeof schema.exclusiveMaximum === "number") {
+ numberSchema = numberSchema.lt(schema.exclusiveMaximum);
+ } else if (schema.exclusiveMaximum === true && typeof schema.maximum === "number") {
+ numberSchema = numberSchema.lt(schema.maximum);
+ }
+ if (typeof schema.multipleOf === "number") {
+ numberSchema = numberSchema.multipleOf(schema.multipleOf);
+ }
+ zodSchema = numberSchema;
+ break;
+ }
+ case "boolean": {
+ zodSchema = z.boolean();
+ break;
+ }
+ case "null": {
+ zodSchema = z.null();
+ break;
+ }
+ case "object": {
+ const shape = {};
+ const properties = schema.properties || {};
+ const requiredSet = new Set(schema.required || []);
+ for (const [key, propSchema] of Object.entries(properties)) {
+ const propZodSchema = convertSchema(propSchema, ctx);
+ shape[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional();
+ }
+ if (schema.propertyNames) {
+ const keySchema = convertSchema(schema.propertyNames, ctx);
+ const valueSchema = schema.additionalProperties && typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : z.any();
+ if (Object.keys(shape).length === 0) {
+ zodSchema = z.record(keySchema, valueSchema);
+ break;
+ }
+ const objectSchema2 = z.object(shape).passthrough();
+ const recordSchema = z.looseRecord(keySchema, valueSchema);
+ zodSchema = z.intersection(objectSchema2, recordSchema);
+ break;
+ }
+ if (schema.patternProperties) {
+ const patternProps = schema.patternProperties;
+ const patternKeys = Object.keys(patternProps);
+ const looseRecords = [];
+ for (const pattern of patternKeys) {
+ const patternValue = convertSchema(patternProps[pattern], ctx);
+ const keySchema = z.string().regex(new RegExp(pattern));
+ looseRecords.push(z.looseRecord(keySchema, patternValue));
+ }
+ const schemasToIntersect = [];
+ if (Object.keys(shape).length > 0) {
+ schemasToIntersect.push(z.object(shape).passthrough());
+ }
+ schemasToIntersect.push(...looseRecords);
+ if (schemasToIntersect.length === 0) {
+ zodSchema = z.object({}).passthrough();
+ } else if (schemasToIntersect.length === 1) {
+ zodSchema = schemasToIntersect[0];
+ } else {
+ let result = z.intersection(schemasToIntersect[0], schemasToIntersect[1]);
+ for (let i = 2; i < schemasToIntersect.length; i++) {
+ result = z.intersection(result, schemasToIntersect[i]);
+ }
+ zodSchema = result;
+ }
+ break;
+ }
+ const objectSchema = z.object(shape);
+ if (schema.additionalProperties === false) {
+ zodSchema = objectSchema.strict();
+ } else if (typeof schema.additionalProperties === "object") {
+ zodSchema = objectSchema.catchall(convertSchema(schema.additionalProperties, ctx));
+ } else {
+ zodSchema = objectSchema.passthrough();
+ }
+ break;
+ }
+ case "array": {
+ const prefixItems = schema.prefixItems;
+ const items = schema.items;
+ if (prefixItems && Array.isArray(prefixItems)) {
+ const tupleItems = prefixItems.map((item) => convertSchema(item, ctx));
+ const rest = items && typeof items === "object" && !Array.isArray(items) ? convertSchema(items, ctx) : void 0;
+ if (rest) {
+ zodSchema = z.tuple(tupleItems).rest(rest);
+ } else {
+ zodSchema = z.tuple(tupleItems);
+ }
+ if (typeof schema.minItems === "number") {
+ zodSchema = zodSchema.check(z.minLength(schema.minItems));
+ }
+ if (typeof schema.maxItems === "number") {
+ zodSchema = zodSchema.check(z.maxLength(schema.maxItems));
+ }
+ } else if (Array.isArray(items)) {
+ const tupleItems = items.map((item) => convertSchema(item, ctx));
+ const rest = schema.additionalItems && typeof schema.additionalItems === "object" ? convertSchema(schema.additionalItems, ctx) : void 0;
+ if (rest) {
+ zodSchema = z.tuple(tupleItems).rest(rest);
+ } else {
+ zodSchema = z.tuple(tupleItems);
+ }
+ if (typeof schema.minItems === "number") {
+ zodSchema = zodSchema.check(z.minLength(schema.minItems));
+ }
+ if (typeof schema.maxItems === "number") {
+ zodSchema = zodSchema.check(z.maxLength(schema.maxItems));
+ }
+ } else if (items !== void 0) {
+ const element = convertSchema(items, ctx);
+ let arraySchema = z.array(element);
+ if (typeof schema.minItems === "number") {
+ arraySchema = arraySchema.min(schema.minItems);
+ }
+ if (typeof schema.maxItems === "number") {
+ arraySchema = arraySchema.max(schema.maxItems);
+ }
+ zodSchema = arraySchema;
+ } else {
+ zodSchema = z.array(z.any());
+ }
+ break;
+ }
+ default:
+ throw new Error(`Unsupported type: ${type2}`);
+ }
+ return zodSchema;
+}
+__name(convertBaseSchema, "convertBaseSchema");
+function convertSchema(schema, ctx) {
+ if (typeof schema === "boolean") {
+ return schema ? z.any() : z.never();
+ }
+ let baseSchema = convertBaseSchema(schema, ctx);
+ const hasExplicitType = schema.type || schema.enum !== void 0 || schema.const !== void 0;
+ if (schema.anyOf && Array.isArray(schema.anyOf)) {
+ const options2 = schema.anyOf.map((s) => convertSchema(s, ctx));
+ const anyOfUnion = z.union(options2);
+ baseSchema = hasExplicitType ? z.intersection(baseSchema, anyOfUnion) : anyOfUnion;
+ }
+ if (schema.oneOf && Array.isArray(schema.oneOf)) {
+ const options2 = schema.oneOf.map((s) => convertSchema(s, ctx));
+ const oneOfUnion = z.xor(options2);
+ baseSchema = hasExplicitType ? z.intersection(baseSchema, oneOfUnion) : oneOfUnion;
+ }
+ if (schema.allOf && Array.isArray(schema.allOf)) {
+ if (schema.allOf.length === 0) {
+ baseSchema = hasExplicitType ? baseSchema : z.any();
+ } else {
+ let result = hasExplicitType ? baseSchema : convertSchema(schema.allOf[0], ctx);
+ const startIdx = hasExplicitType ? 0 : 1;
+ for (let i = startIdx; i < schema.allOf.length; i++) {
+ result = z.intersection(result, convertSchema(schema.allOf[i], ctx));
+ }
+ baseSchema = result;
+ }
+ }
+ if (schema.nullable === true && ctx.version === "openapi-3.0") {
+ baseSchema = z.nullable(baseSchema);
+ }
+ if (schema.readOnly === true) {
+ baseSchema = z.readonly(baseSchema);
+ }
+ if (schema.default !== void 0) {
+ baseSchema = baseSchema.default(schema.default);
+ }
+ const extraMeta = {};
+ const coreMetadataKeys = ["$id", "id", "$comment", "$anchor", "$vocabulary", "$dynamicRef", "$dynamicAnchor"];
+ for (const key of coreMetadataKeys) {
+ if (key in schema) {
+ extraMeta[key] = schema[key];
+ }
+ }
+ const contentMetadataKeys = ["contentEncoding", "contentMediaType", "contentSchema"];
+ for (const key of contentMetadataKeys) {
+ if (key in schema) {
+ extraMeta[key] = schema[key];
+ }
+ }
+ for (const key of Object.keys(schema)) {
+ if (!RECOGNIZED_KEYS.has(key)) {
+ extraMeta[key] = schema[key];
+ }
+ }
+ if (Object.keys(extraMeta).length > 0) {
+ ctx.registry.add(baseSchema, extraMeta);
+ }
+ if (schema.description) {
+ baseSchema = baseSchema.describe(schema.description);
+ }
+ return baseSchema;
+}
+__name(convertSchema, "convertSchema");
+function fromJSONSchema(schema, params) {
+ if (typeof schema === "boolean") {
+ return schema ? z.any() : z.never();
+ }
+ let normalized;
+ try {
+ normalized = JSON.parse(JSON.stringify(schema));
+ } catch {
+ throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas");
+ }
+ const version2 = detectVersion(normalized, params?.defaultTarget);
+ const defs = normalized.$defs || normalized.definitions || {};
+ const ctx = {
+ version: version2,
+ defs,
+ refs: /* @__PURE__ */ new Map(),
+ processing: /* @__PURE__ */ new Set(),
+ rootSchema: normalized,
+ registry: params?.registry ?? globalRegistry
+ };
+ return convertSchema(normalized, ctx);
+}
+__name(fromJSONSchema, "fromJSONSchema");
+
+// node_modules/zod/v4/classic/coerce.js
+var coerce_exports = {};
+__export(coerce_exports, {
+ bigint: () => bigint3,
+ boolean: () => boolean3,
+ date: () => date4,
+ number: () => number3,
+ string: () => string3
+});
+init_esbuild_shims();
+function string3(params) {
+ return _coercedString(ZodString, params);
+}
+__name(string3, "string");
+function number3(params) {
+ return _coercedNumber(ZodNumber, params);
+}
+__name(number3, "number");
+function boolean3(params) {
+ return _coercedBoolean(ZodBoolean, params);
+}
+__name(boolean3, "boolean");
+function bigint3(params) {
+ return _coercedBigint(ZodBigInt, params);
+}
+__name(bigint3, "bigint");
+function date4(params) {
+ return _coercedDate(ZodDate, params);
+}
+__name(date4, "date");
+
+// node_modules/zod/v4/classic/external.js
+config(en_default());
+
+// packages/core/src/common/validate.ts
+init_esbuild_shims();
+function semanticBoolean(defaultValue2 = false) {
+ return external_exports.preprocess((value) => {
+ if (value === "true") {
+ return true;
+ }
+ if (value === "false") {
+ return false;
+ }
+ return value;
+ }, external_exports.boolean().default(defaultValue2));
+}
+__name(semanticBoolean, "semanticBoolean");
+async function executeValidatedTool(name, schema, rawArgs, context, handler, options2 = {}) {
+ const preprocessed = options2.preprocess ? options2.preprocess(rawArgs) : { ok: true, input: rawArgs };
+ if (!preprocessed.ok) {
+ return {
+ ok: false,
+ name,
+ error: `InputValidationError: ${preprocessed.error}`
+ };
+ }
+ const parsed = schema.safeParse(preprocessed.input);
+ if (!parsed.success) {
+ return {
+ ok: false,
+ name,
+ error: `InputValidationError: ${formatZodError(parsed.error)}`
+ };
+ }
+ return handler(parsed.data, context);
+}
+__name(executeValidatedTool, "executeValidatedTool");
+function formatZodError(error51) {
+ const issue2 = error51.issues[0];
+ if (!issue2) {
+ return "Invalid tool input.";
+ }
+ const path27 = issue2.path.length > 0 ? `${issue2.path.join(".")}: ` : "";
+ return `${path27}${issue2.message}`;
+}
+__name(formatZodError, "formatZodError");
+
+// packages/core/src/common/state.ts
+init_esbuild_shims();
+import * as fs9 from "fs";
+import * as path7 from "path";
+var fileStatesBySession = /* @__PURE__ */ new Map();
+var snippetsBySession = /* @__PURE__ */ new Map();
+var snippetCountersBySession = /* @__PURE__ */ new Map();
+var fullFileSnippetCountersBySession = /* @__PURE__ */ new Map();
+var fileVersionsBySession = /* @__PURE__ */ new Map();
+function clearSessionState(sessionId) {
+ if (!sessionId) {
+ return;
+ }
+ fileStatesBySession.delete(sessionId);
+ snippetsBySession.delete(sessionId);
+ snippetCountersBySession.delete(sessionId);
+ fullFileSnippetCountersBySession.delete(sessionId);
+ fileVersionsBySession.delete(sessionId);
+}
+__name(clearSessionState, "clearSessionState");
+function hasSessionState(sessionId) {
+ if (!sessionId) {
+ return false;
+ }
+ return Boolean(
+ fileStatesBySession.get(sessionId)?.size || snippetsBySession.get(sessionId)?.size || snippetCountersBySession.has(sessionId) || fullFileSnippetCountersBySession.has(sessionId) || fileVersionsBySession.get(sessionId)?.size
+ );
+}
+__name(hasSessionState, "hasSessionState");
+function normalizeFilePath(filePath, platform2 = process.platform) {
+ const nativePath = normalizeNativeFilePath(filePath, platform2);
+ return platform2 === "win32" ? path7.win32.normalize(nativePath) : path7.normalize(nativePath);
+}
+__name(normalizeFilePath, "normalizeFilePath");
+function normalizeNativeFilePath(filePath, platform2 = process.platform) {
+ if (platform2 !== "win32") {
+ return filePath;
+ }
+ if (isGitBashAbsolutePath(filePath)) {
+ return posixPathToWindowsPath(filePath);
+ }
+ return filePath;
+}
+__name(normalizeNativeFilePath, "normalizeNativeFilePath");
+function isAbsoluteFilePath(filePath, platform2 = process.platform) {
+ const nativePath = normalizeNativeFilePath(filePath, platform2);
+ if (platform2 !== "win32") {
+ return path7.isAbsolute(nativePath);
+ }
+ const normalized = path7.win32.normalize(nativePath);
+ return path7.win32.isAbsolute(normalized) && (/^[A-Za-z]:[\\/]/.test(normalized) || /^\\\\/.test(normalized));
+}
+__name(isAbsoluteFilePath, "isAbsoluteFilePath");
+function isGitBashAbsolutePath(filePath) {
+ return /^\/[A-Za-z](?:\/|$)/.test(filePath) || /^\/cygdrive\/[A-Za-z](?:\/|$)/.test(filePath);
+}
+__name(isGitBashAbsolutePath, "isGitBashAbsolutePath");
+function recordFileState(sessionId, state, options2 = {}) {
+ if (!sessionId || !state.filePath) {
+ return;
+ }
+ let sessionState = fileStatesBySession.get(sessionId);
+ if (!sessionState) {
+ sessionState = /* @__PURE__ */ new Map();
+ fileStatesBySession.set(sessionId, sessionState);
+ }
+ const normalizedPath = normalizeFilePath(state.filePath);
+ const currentVersion = getFileVersion(sessionId, normalizedPath);
+ const nextVersion = options2.incrementVersion ? currentVersion + 1 : currentVersion;
+ setFileVersion(sessionId, normalizedPath, nextVersion);
+ sessionState.set(normalizedPath, {
+ ...state,
+ filePath: normalizedPath,
+ version: nextVersion
+ });
+}
+__name(recordFileState, "recordFileState");
+function markFileRead(sessionId, filePath, state = null) {
+ if (!sessionId || !filePath) {
+ return;
+ }
+ recordFileState(sessionId, {
+ filePath,
+ content: state?.content ?? "",
+ timestamp: state?.timestamp ?? 0,
+ offset: state?.offset,
+ limit: state?.limit,
+ isPartialView: state?.isPartialView,
+ encoding: state?.encoding,
+ lineEndings: state?.lineEndings
+ });
+}
+__name(markFileRead, "markFileRead");
+function getFileState(sessionId, filePath) {
+ if (!sessionId || !filePath) {
+ return null;
+ }
+ return fileStatesBySession.get(sessionId)?.get(normalizeFilePath(filePath)) ?? null;
+}
+__name(getFileState, "getFileState");
+function getFileVersion(sessionId, filePath) {
+ if (!sessionId || !filePath) {
+ return 0;
+ }
+ return fileVersionsBySession.get(sessionId)?.get(normalizeFilePath(filePath)) ?? 0;
+}
+__name(getFileVersion, "getFileVersion");
+function setFileVersion(sessionId, filePath, version2) {
+ let sessionVersions = fileVersionsBySession.get(sessionId);
+ if (!sessionVersions) {
+ sessionVersions = /* @__PURE__ */ new Map();
+ fileVersionsBySession.set(sessionId, sessionVersions);
+ }
+ sessionVersions.set(normalizeFilePath(filePath), version2);
+}
+__name(setFileVersion, "setFileVersion");
+function isFullFileView(state) {
+ return Boolean(
+ state && !state.isPartialView && typeof state.offset === "undefined" && typeof state.limit === "undefined"
+ );
+}
+__name(isFullFileView, "isFullFileView");
+function createSnippet(sessionId, filePath, startLine, endLine, preview) {
+ const nextCounter = (snippetCountersBySession.get(sessionId) ?? 0) + 1;
+ snippetCountersBySession.set(sessionId, nextCounter);
+ return createSnippetWithId(sessionId, filePath, startLine, endLine, preview, `snippet_${nextCounter}`, "snippet");
+}
+__name(createSnippet, "createSnippet");
+function createFullFileSnippet(sessionId, filePath, startLine, endLine, preview) {
+ const nextCounter = fullFileSnippetCountersBySession.get(sessionId) ?? 0;
+ fullFileSnippetCountersBySession.set(sessionId, nextCounter + 1);
+ return createSnippetWithId(sessionId, filePath, startLine, endLine, preview, `full_file_${nextCounter}`, "full");
+}
+__name(createFullFileSnippet, "createFullFileSnippet");
+function restoreSnippet(sessionId, snippet) {
+ const restored = createSnippetWithId(
+ sessionId,
+ snippet.filePath,
+ snippet.startLine,
+ snippet.endLine,
+ snippet.preview ?? "",
+ snippet.id,
+ snippet.scopeType ?? inferSnippetScopeType(snippet.id)
+ );
+ if (restored) {
+ updateSnippetCounters(sessionId, snippet.id);
+ }
+ return restored;
+}
+__name(restoreSnippet, "restoreSnippet");
+function createSnippetWithId(sessionId, filePath, startLine, endLine, preview, id, scopeType) {
+ if (!sessionId || !filePath || startLine < 1 || endLine < startLine) {
+ return null;
+ }
+ const snippet = {
+ id,
+ filePath: normalizeFilePath(filePath),
+ startLine,
+ endLine,
+ preview,
+ fileVersion: getFileVersion(sessionId, filePath),
+ scopeType
+ };
+ let snippets = snippetsBySession.get(sessionId);
+ if (!snippets) {
+ snippets = /* @__PURE__ */ new Map();
+ snippetsBySession.set(sessionId, snippets);
+ }
+ snippets.set(snippet.id, snippet);
+ return snippet;
+}
+__name(createSnippetWithId, "createSnippetWithId");
+function inferSnippetScopeType(id) {
+ return id.startsWith("full_file_") ? "full" : "snippet";
+}
+__name(inferSnippetScopeType, "inferSnippetScopeType");
+function updateSnippetCounters(sessionId, id) {
+ const fullFileMatch = /^full_file_(\d+)$/.exec(id);
+ if (fullFileMatch) {
+ const nextCounter = Number(fullFileMatch[1]) + 1;
+ const current = fullFileSnippetCountersBySession.get(sessionId) ?? 0;
+ fullFileSnippetCountersBySession.set(sessionId, Math.max(current, nextCounter));
+ return;
+ }
+ const snippetMatch = /^snippet_(\d+)$/.exec(id);
+ if (snippetMatch) {
+ const currentCounter = Number(snippetMatch[1]);
+ const current = snippetCountersBySession.get(sessionId) ?? 0;
+ snippetCountersBySession.set(sessionId, Math.max(current, currentCounter));
+ }
+}
+__name(updateSnippetCounters, "updateSnippetCounters");
+function getSnippet(sessionId, snippetId) {
+ if (!sessionId || !snippetId) {
+ return null;
+ }
+ return snippetsBySession.get(sessionId)?.get(snippetId) ?? null;
+}
+__name(getSnippet, "getSnippet");
+function hasSnippetOutdatedFileVersion(sessionId, snippet) {
+ return getFileVersion(sessionId, snippet.filePath) > snippet.fileVersion;
+}
+__name(hasSnippetOutdatedFileVersion, "hasSnippetOutdatedFileVersion");
+function rebuildSessionStateFromHistory(sessionId, messages) {
+ if (!sessionId || hasSessionState(sessionId)) {
+ return;
+ }
+ for (const message of messages) {
+ if (message.role !== "tool" || typeof message.content !== "string") {
+ continue;
+ }
+ const result = parsePersistedToolResult(message.content);
+ if (!result || result.ok !== true) {
+ continue;
+ }
+ const metadata = asRecord(result.metadata);
+ if (!metadata) {
+ continue;
+ }
+ if (result.name === "read") {
+ rebuildReadResult(sessionId, result, metadata);
+ } else if (result.name === "edit") {
+ rebuildEditResult(sessionId, metadata);
+ } else if (result.name === "write") {
+ rebuildWriteResult(sessionId, metadata);
+ }
+ }
+}
+__name(rebuildSessionStateFromHistory, "rebuildSessionStateFromHistory");
+function rebuildReadResult(sessionId, result, metadata) {
+ const snippet = asRecord(metadata.snippet);
+ if (!snippet) {
+ return;
+ }
+ const restored = restoreSnippetFromRecord(sessionId, snippet, {
+ idKey: "id",
+ filePathKey: "filePath",
+ startLineKey: "startLine",
+ endLineKey: "endLine",
+ preview: typeof result.output === "string" ? result.output : ""
+ });
+ if (!restored) {
+ return;
+ }
+ refreshRebuiltFileState(sessionId, restored.filePath, {
+ scopeType: restored.scopeType,
+ startLine: restored.startLine,
+ endLine: restored.endLine,
+ incrementVersion: false
+ });
+}
+__name(rebuildReadResult, "rebuildReadResult");
+function rebuildEditResult(sessionId, metadata) {
+ const scope = asRecord(metadata.scope);
+ if (scope) {
+ restoreSnippetFromRecord(sessionId, scope, {
+ idKey: "snippet_id",
+ filePathKey: "file_path",
+ startLineKey: "start_line",
+ endLineKey: "end_line",
+ scopeType: metadata.read_scope_type === "full" ? "full" : void 0
+ });
+ }
+ const scopeFilePath = typeof scope?.file_path === "string" ? scope.file_path : void 0;
+ rebuildCandidateSnippets(sessionId, metadata, scopeFilePath);
+ const filePath = typeof metadata.file_path === "string" ? metadata.file_path : scopeFilePath;
+ if (filePath && metadata.cache_refreshed === true) {
+ refreshRebuiltFileState(sessionId, filePath, { incrementVersion: true });
+ }
+}
+__name(rebuildEditResult, "rebuildEditResult");
+function rebuildWriteResult(sessionId, metadata) {
+ if (metadata.cache_refreshed !== true || typeof metadata.file_path !== "string") {
+ return;
+ }
+ refreshRebuiltFileState(sessionId, metadata.file_path, { incrementVersion: true });
+}
+__name(rebuildWriteResult, "rebuildWriteResult");
+function rebuildCandidateSnippets(sessionId, metadata, filePath) {
+ if (!filePath) {
+ return;
+ }
+ const candidates = Array.isArray(metadata.candidates) ? metadata.candidates : [];
+ for (const candidate of candidates) {
+ const record2 = asRecord(candidate);
+ if (!record2) {
+ continue;
+ }
+ restoreSnippetFromRecord(
+ sessionId,
+ { ...record2, file_path: filePath },
+ {
+ idKey: "snippet_id",
+ filePathKey: "file_path",
+ startLineKey: "start_line",
+ endLineKey: "end_line",
+ scopeType: "snippet",
+ preview: typeof record2.preview === "string" ? record2.preview : ""
+ }
+ );
+ }
+ const closestMatch = asRecord(metadata.closest_match);
+ if (closestMatch) {
+ restoreSnippetFromRecord(
+ sessionId,
+ { ...closestMatch, file_path: filePath },
+ {
+ idKey: "snippet_id",
+ filePathKey: "file_path",
+ startLineKey: "start_line",
+ endLineKey: "end_line",
+ scopeType: "snippet",
+ preview: typeof closestMatch.preview === "string" ? closestMatch.preview : ""
+ }
+ );
+ }
+}
+__name(rebuildCandidateSnippets, "rebuildCandidateSnippets");
+function restoreSnippetFromRecord(sessionId, record2, options2) {
+ const rawId = record2[options2.idKey];
+ const rawFilePath = record2[options2.filePathKey];
+ const id = typeof rawId === "string" ? rawId.trim() : "";
+ const filePath = typeof rawFilePath === "string" ? normalizeFilePath(rawFilePath) : "";
+ const startLine = toPositiveInteger(record2[options2.startLineKey]);
+ const endLine = toPositiveInteger(record2[options2.endLineKey]);
+ if (!id || !filePath || startLine === null || endLine === null) {
+ return null;
+ }
+ return restoreSnippet(sessionId, {
+ id,
+ filePath,
+ startLine,
+ endLine,
+ preview: options2.preview,
+ scopeType: options2.scopeType
+ });
+}
+__name(restoreSnippetFromRecord, "restoreSnippetFromRecord");
+function refreshRebuiltFileState(sessionId, rawFilePath, options2 = {}) {
+ const filePath = normalizeFilePath(rawFilePath);
+ if (!filePath || !fs9.existsSync(filePath)) {
+ return;
+ }
+ try {
+ const stat = fs9.statSync(filePath);
+ if (stat.isDirectory()) {
+ return;
+ }
+ const metadata = readTextFileWithMetadata(filePath);
+ const isPartialView = options2.scopeType === "snippet";
+ const content = isPartialView ? metadata.content.split("\n").slice((options2.startLine ?? 1) - 1, options2.endLine).join("\n") : metadata.content;
+ recordFileState(
+ sessionId,
+ {
+ filePath,
+ content,
+ timestamp: metadata.timestamp,
+ offset: isPartialView ? options2.startLine : void 0,
+ limit: isPartialView && options2.startLine !== void 0 && options2.endLine !== void 0 ? Math.max(1, options2.endLine - options2.startLine + 1) : void 0,
+ isPartialView,
+ encoding: metadata.encoding,
+ lineEndings: metadata.lineEndings
+ },
+ { incrementVersion: options2.incrementVersion }
+ );
+ } catch {
+ }
+}
+__name(refreshRebuiltFileState, "refreshRebuiltFileState");
+function parsePersistedToolResult(content) {
+ try {
+ return asRecord(JSON.parse(content));
+ } catch {
+ return null;
+ }
+}
+__name(parsePersistedToolResult, "parsePersistedToolResult");
+function asRecord(value) {
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
+ return null;
+ }
+ return value;
+}
+__name(asRecord, "asRecord");
+function toPositiveInteger(value) {
+ const numberValue = typeof value === "number" ? value : typeof value === "string" ? Number(value) : NaN;
+ if (!Number.isInteger(numberValue) || numberValue < 1) {
+ return null;
+ }
+ return numberValue;
+}
+__name(toPositiveInteger, "toPositiveInteger");
+
+// packages/core/src/tools/edit-handler.ts
+var MAX_CANDIDATE_COUNT = 5;
+var REPLACE_ALL_MATCH_THRESHOLD = 5;
+var SHORT_REPLACE_ALL_LENGTH = 40;
+var OUTDATED_SNIPPET_NOT_FOUND_ERROR = "old_string was not found in this snippet scope. The file has changed since this snippet was created. Read the file again before editing.";
+var editSchema = external_exports.strictObject({
+ file_path: external_exports.string().optional(),
+ snippet_id: external_exports.string().min(1, "snippet_id is required."),
+ old_string: external_exports.string(),
+ new_string: external_exports.string(),
+ replace_all: semanticBoolean(false).optional(),
+ expected_occurrences: external_exports.preprocess((value) => {
+ if (value === void 0 || value === null || value === "") {
+ return void 0;
+ }
+ if (typeof value === "string") {
+ return Number(value);
+ }
+ return value;
+ }, external_exports.number().int().min(1, "expected_occurrences must be >= 1.").optional())
+});
+async function handleEditTool(args, context) {
+ return executeValidatedTool(
+ "edit",
+ editSchema,
+ args,
+ context,
+ async (input) => {
+ const snippetId = input.snippet_id.trim();
+ const snippet = getSnippet(context.sessionId, snippetId);
+ let filePath = input.file_path?.trim() ?? "";
+ if (!snippet) {
+ return {
+ ok: false,
+ name: "edit",
+ error: `Unknown snippet_id: ${snippetId}`
+ };
+ }
+ if (!filePath) {
+ filePath = snippet.filePath;
+ }
+ filePath = normalizeFilePath(filePath);
+ if (!isAbsoluteFilePath(filePath)) {
+ return {
+ ok: false,
+ name: "edit",
+ error: "file_path must be an absolute path."
+ };
+ }
+ if (snippet.filePath !== filePath) {
+ return {
+ ok: false,
+ name: "edit",
+ error: "snippet_id does not belong to the provided file_path."
+ };
+ }
+ if (input.old_string === input.new_string) {
+ return {
+ ok: false,
+ name: "edit",
+ error: "new_string must differ from old_string."
+ };
+ }
+ if (!fs10.existsSync(filePath)) {
+ return {
+ ok: false,
+ name: "edit",
+ error: `File not found: ${filePath}`
+ };
+ }
+ let stat;
+ try {
+ stat = fs10.statSync(filePath);
+ } catch (error51) {
+ const message = error51 instanceof Error ? error51.message : String(error51);
+ return {
+ ok: false,
+ name: "edit",
+ error: `Failed to stat file: ${message}`
+ };
+ }
+ if (stat.isDirectory()) {
+ return {
+ ok: false,
+ name: "edit",
+ error: "file_path points to a directory."
+ };
+ }
+ const fileState = getFileState(context.sessionId, filePath);
+ if (!fileState) {
+ return {
+ ok: false,
+ name: "edit",
+ error: "Must read file before editing."
+ };
+ }
+ if (hasFileChangedSinceState(filePath, fileState)) {
+ return {
+ ok: false,
+ name: "edit",
+ error: "File has been modified since read. Read it again before editing."
+ };
+ }
+ try {
+ const metadata = readTextFileWithMetadata(filePath);
+ const raw = metadata.content;
+ const oldString = input.old_string;
+ const newString = input.new_string;
+ const replaceAll = input.replace_all ?? false;
+ const lineIndex = buildLineIndex(raw);
+ const scope = buildSearchScope(filePath, raw, lineIndex, snippet);
+ let matches = [];
+ let matchedVia = "exact";
+ let replacementOldString = oldString;
+ let replacementNewString = newString;
+ if (oldString === "") {
+ if (raw !== "") {
+ return {
+ ok: false,
+ name: "edit",
+ error: "old_string must not be empty unless the file is empty.",
+ metadata: {
+ scope: formatScopeMetadata(scope)
+ }
+ };
+ }
+ matches = [
+ {
+ startOffset: 0,
+ endOffset: 0,
+ startLine: 1,
+ endLine: 1
+ }
+ ];
+ matchedVia = "empty_file";
+ } else {
+ matches = findOccurrences(raw, oldString, scope);
+ }
+ if (matches.length === 0) {
+ const tabStrippedOldString = stripReadResultLineTabs(oldString);
+ if (tabStrippedOldString !== oldString) {
+ const tabStrippedMatches = findOccurrences(raw, tabStrippedOldString, scope);
+ if (tabStrippedMatches.length === 1) {
+ matches = tabStrippedMatches;
+ matchedVia = "line_leading_tab_correction";
+ replacementOldString = tabStrippedOldString;
+ replacementNewString = stripReadResultLineTabs(newString);
+ }
+ }
+ }
+ if (matches.length === 0) {
+ const looseEscapeMatches = findLooseEscapeMatches(raw, oldString, scope);
+ if (looseEscapeMatches.length === 1 && looseEscapeMatches[0]?.score === 1) {
+ const correctedStrings = await correctEscapedStringsWithLLM(
+ raw.slice(scope.startOffset, scope.endOffset),
+ oldString,
+ newString,
+ looseEscapeMatches[0].text,
+ context
+ );
+ if (correctedStrings) {
+ const correctedMatches = findOccurrences(raw, correctedStrings.oldString, scope);
+ if (correctedMatches.length > 0) {
+ matches = correctedMatches;
+ matchedVia = "llm_escape_correction";
+ replacementOldString = correctedStrings.oldString;
+ replacementNewString = correctedStrings.newString;
+ }
+ }
+ if (matches.length === 0) {
+ matches = [looseEscapeMatches[0]];
+ matchedVia = "loose_escape";
+ }
+ }
+ }
+ if (matches.length === 0) {
+ if (snippet && hasSnippetOutdatedFileVersion(context.sessionId, snippet)) {
+ return {
+ ok: false,
+ name: "edit",
+ error: OUTDATED_SNIPPET_NOT_FOUND_ERROR,
+ metadata: {
+ scope: formatScopeMetadata(scope)
+ }
+ };
+ }
+ const notFoundReason = await inferOldStringNotFoundReasonWithLLM(
+ raw,
+ lineIndex,
+ scope,
+ oldString,
+ newString,
+ context
+ );
+ return {
+ ok: false,
+ name: "edit",
+ error: notFoundReason ? `old_string not found in file. ${notFoundReason}` : "old_string not found in file.",
+ metadata: {
+ scope: formatScopeMetadata(scope)
+ }
+ };
+ }
+ if (!replaceAll && matches.length > 1) {
+ return {
+ ok: false,
+ name: "edit",
+ error: "old_string is not unique; use snippet_id, replace_all, or provide more context.",
+ metadata: {
+ match_count: matches.length,
+ scope: formatScopeMetadata(scope),
+ candidates: buildCandidateMetadata(context.sessionId, filePath, raw, matches)
+ }
+ };
+ }
+ const expectedOccurrences = input.expected_occurrences ?? null;
+ const replaceAllGuardError = validateReplaceAllGuard({
+ replaceAll,
+ matchCount: matches.length,
+ oldString: replacementOldString,
+ expectedOccurrences
+ });
+ if (replaceAllGuardError) {
+ return {
+ ok: false,
+ name: "edit",
+ error: replaceAllGuardError,
+ metadata: {
+ match_count: matches.length,
+ scope: formatScopeMetadata(scope),
+ candidates: buildCandidateMetadata(context.sessionId, filePath, raw, matches)
+ }
+ };
+ }
+ const updated = applyReplacement(raw, replacementOldString, replacementNewString, matches, replaceAll);
+ const diffPreview = buildDiffPreview(filePath, raw, updated);
+ context.onBeforeFileMutation?.(filePath);
+ writeTextFile(filePath, updated, metadata.encoding, metadata.lineEndings);
+ context.onAfterFileMutation?.(filePath);
+ const freshMetadata = readTextFileWithMetadata(filePath);
+ recordFileState(
+ context.sessionId,
+ {
+ filePath,
+ content: freshMetadata.content,
+ timestamp: freshMetadata.timestamp,
+ encoding: freshMetadata.encoding,
+ lineEndings: freshMetadata.lineEndings
+ },
+ { incrementVersion: true }
+ );
+ const replacedCount = replaceAll ? matches.length : 1;
+ return {
+ ok: true,
+ name: "edit",
+ output: `Replaced ${replacedCount} occurrence(s) in ${filePath}.`,
+ metadata: {
+ file_path: filePath,
+ replaced_count: replacedCount,
+ matched_via: matchedVia,
+ cache_refreshed: true,
+ read_scope_type: snippet.scopeType,
+ encoding: freshMetadata.encoding,
+ line_endings: freshMetadata.lineEndings,
+ diff_preview: diffPreview,
+ scope: formatScopeMetadata(scope)
+ }
+ };
+ } catch (error51) {
+ const message = error51 instanceof Error ? error51.message : String(error51);
+ return {
+ ok: false,
+ name: "edit",
+ error: message
+ };
+ }
+ },
+ {
+ preprocess: /* @__PURE__ */ __name((rawInput) => {
+ const nextInput = { ...rawInput };
+ if (typeof nextInput.file_path === "string") {
+ nextInput.file_path = normalizeFilePath(nextInput.file_path);
+ }
+ if (typeof nextInput.snippet_id === "string") {
+ nextInput.snippet_id = nextInput.snippet_id.trim();
+ }
+ return { ok: true, input: nextInput };
+ }, "preprocess")
+ }
+ );
+}
+__name(handleEditTool, "handleEditTool");
+function buildLineIndex(raw) {
+ const lines = raw.split(/\r?\n/);
+ const lineStarts = new Array(lines.length + 2).fill(raw.length);
+ let cursor = 0;
+ for (let index = 0; index < lines.length; index += 1) {
+ lineStarts[index + 1] = cursor;
+ cursor += lines[index].length;
+ if (index < lines.length - 1) {
+ if (raw.slice(cursor, cursor + 2) === "\r\n") {
+ cursor += 2;
+ } else if (raw[cursor] === "\n") {
+ cursor += 1;
+ }
+ }
+ }
+ lineStarts[lines.length + 1] = raw.length;
+ return { lines, lineStarts };
+}
+__name(buildLineIndex, "buildLineIndex");
+function buildSearchScope(filePath, raw, lineIndex, snippet) {
+ if (!snippet) {
+ return {
+ filePath,
+ startOffset: 0,
+ endOffset: raw.length,
+ startLine: 1,
+ endLine: lineIndex.lines.length,
+ snippetId: null
+ };
+ }
+ const safeStartLine = clamp(snippet.startLine, 1, lineIndex.lines.length);
+ const safeEndLine = clamp(snippet.endLine, safeStartLine, lineIndex.lines.length);
+ return {
+ filePath,
+ startOffset: lineIndex.lineStarts[safeStartLine],
+ endOffset: lineIndex.lineStarts[safeEndLine + 1],
+ startLine: safeStartLine,
+ endLine: safeEndLine,
+ snippetId: snippet.id
+ };
+}
+__name(buildSearchScope, "buildSearchScope");
+function clamp(value, min, max) {
+ return Math.min(max, Math.max(min, value));
+}
+__name(clamp, "clamp");
+function findOccurrences(raw, needle, scope) {
+ if (!raw || !needle) {
+ return [];
+ }
+ const scopeText = raw.slice(scope.startOffset, scope.endOffset);
+ const matches = [];
+ let searchIndex = 0;
+ while (true) {
+ const found = scopeText.indexOf(needle, searchIndex);
+ if (found === -1) {
+ break;
+ }
+ const startOffset = scope.startOffset + found;
+ const endOffset = startOffset + needle.length;
+ matches.push({
+ startOffset,
+ endOffset,
+ startLine: offsetToLine(raw, startOffset),
+ endLine: offsetToLine(raw, Math.max(startOffset, endOffset - 1))
+ });
+ searchIndex = found + needle.length;
+ }
+ return matches;
+}
+__name(findOccurrences, "findOccurrences");
+function findLooseEscapeMatches(raw, needle, scope) {
+ if (!raw || !needle) {
+ return [];
+ }
+ const scopeText = raw.slice(scope.startOffset, scope.endOffset);
+ const looseEscapeRegex = buildLooseEscapeRegex(needle);
+ if (!looseEscapeRegex) {
+ return [];
+ }
+ const normalizedNeedle = normalizeLooseText(needle);
+ const matches = [];
+ for (const match of scopeText.matchAll(looseEscapeRegex)) {
+ if (typeof match.index !== "number") {
+ continue;
+ }
+ const text = match[0];
+ const startOffset = scope.startOffset + match.index;
+ const endOffset = startOffset + text.length;
+ matches.push({
+ text,
+ score: similarityScore(normalizedNeedle, normalizeLooseText(text)),
+ startOffset,
+ endOffset,
+ startLine: offsetToLine(raw, startOffset),
+ endLine: offsetToLine(raw, Math.max(startOffset, endOffset - 1))
+ });
+ }
+ return matches;
+}
+__name(findLooseEscapeMatches, "findLooseEscapeMatches");
+function offsetToLine(raw, offset) {
+ if (offset <= 0) {
+ return 1;
+ }
+ let line = 1;
+ for (let index = 0; index < raw.length && index < offset; index += 1) {
+ if (raw[index] === "\n") {
+ line += 1;
+ }
+ }
+ return line;
+}
+__name(offsetToLine, "offsetToLine");
+function validateReplaceAllGuard(input) {
+ if (!input.replaceAll) {
+ if (input.expectedOccurrences !== null && input.expectedOccurrences !== 1) {
+ return "expected_occurrences can only be greater than 1 when replace_all is true.";
+ }
+ return null;
+ }
+ if (input.expectedOccurrences !== null && input.expectedOccurrences !== input.matchCount) {
+ return `replace_all expected ${input.expectedOccurrences} occurrence(s), but found ${input.matchCount}.`;
+ }
+ const isShortFragment = input.oldString.trim().length < SHORT_REPLACE_ALL_LENGTH;
+ const needsExplicitCount = input.expectedOccurrences === null && (input.matchCount > REPLACE_ALL_MATCH_THRESHOLD || isShortFragment && input.matchCount > 1);
+ if (needsExplicitCount) {
+ return `replace_all would affect ${input.matchCount} occurrence(s); provide expected_occurrences to confirm this broader replacement.`;
+ }
+ return null;
+}
+__name(validateReplaceAllGuard, "validateReplaceAllGuard");
+function applyReplacement(raw, oldString, newString, matches, replaceAll) {
+ if (!replaceAll) {
+ return raw.slice(0, matches[0].startOffset) + newString + raw.slice(matches[0].endOffset);
+ }
+ let result = "";
+ let cursor = 0;
+ for (const match of matches) {
+ result += raw.slice(cursor, match.startOffset);
+ result += newString;
+ cursor = match.endOffset;
+ }
+ result += raw.slice(cursor);
+ return result;
+}
+__name(applyReplacement, "applyReplacement");
+function stripReadResultLineTabs(value) {
+ return value.replaceAll("\n ", "\n");
+}
+__name(stripReadResultLineTabs, "stripReadResultLineTabs");
+function buildCandidateMetadata(sessionId, filePath, raw, matches) {
+ return matches.slice(0, MAX_CANDIDATE_COUNT).map((match) => {
+ const preview = buildPreview(raw, match.startLine, match.endLine);
+ const snippet = createSnippet(sessionId, filePath, match.startLine, match.endLine, preview);
+ return {
+ snippet_id: snippet?.id ?? null,
+ start_line: match.startLine,
+ end_line: match.endLine,
+ preview
+ };
+ });
+}
+__name(buildCandidateMetadata, "buildCandidateMetadata");
+function formatScopeMetadata(scope) {
+ return {
+ file_path: scope.filePath,
+ start_line: scope.startLine,
+ end_line: scope.endLine,
+ snippet_id: scope.snippetId
+ };
+}
+__name(formatScopeMetadata, "formatScopeMetadata");
+function buildPreview(raw, startLine, endLine) {
+ const lines = raw.split(/\r?\n/);
+ const selected = lines.slice(startLine - 1, endLine);
+ return formatWithLineNumbers(selected, startLine);
+}
+__name(buildPreview, "buildPreview");
+function formatWithLineNumbers(lines, startLine) {
+ return lines.map((line, index) => `${String(startLine + index).padStart(6, " ")} ${line}`).join("\n");
+}
+__name(formatWithLineNumbers, "formatWithLineNumbers");
+function buildLooseEscapeRegex(source) {
+ if (!source) {
+ return null;
+ }
+ let pattern = "";
+ for (let index = 0; index < source.length; index += 1) {
+ if (source[index] === "\\") {
+ let slashEnd = index;
+ while (slashEnd < source.length && source[slashEnd] === "\\") {
+ slashEnd += 1;
+ }
+ if (slashEnd < source.length) {
+ pattern += "\\\\*";
+ pattern += escapeRegExp(source[slashEnd]);
+ index = slashEnd;
+ continue;
+ }
+ pattern += escapeRegExp(source.slice(index, slashEnd));
+ index = slashEnd - 1;
+ continue;
+ }
+ pattern += escapeRegExp(source[index]);
+ }
+ return new RegExp(pattern, "g");
+}
+__name(buildLooseEscapeRegex, "buildLooseEscapeRegex");
+async function inferOldStringNotFoundReasonWithLLM(raw, lineIndex, scope, oldString, newString, context) {
+ const clientFactory = context.createOpenAIClient;
+ if (!clientFactory) {
+ return null;
+ }
+ const { client, model, baseURL, thinkingEnabled, reasoningEffort } = clientFactory();
+ if (!client) {
+ return null;
+ }
+ const contextLineLimit = Math.max(1, oldString.split(/\r?\n/).length);
+ const snippetText = raw.slice(scope.startOffset, scope.endOffset);
+ const contentBeforeSnippet = getLinesBeforeScope(lineIndex, scope, contextLineLimit);
+ const contentAfterSnippet = getLinesAfterScope(lineIndex, scope, contextLineLimit);
+ try {
+ const response = await client.chat.completions.create({
+ model,
+ messages: [
+ {
+ role: "system",
+ content: "You diagnose failed file edits when old_string was not found. Return XML only using .... Be concise and specific. Explain the likely mismatch between old_string and the content. Do not suggest unrelated changes."
+ },
+ {
+ role: "user",
+ content: `
+
+
+
+
+
+
+
+
+
+
+`
+ }
+ ],
+ ...buildThinkingRequestOptions(thinkingEnabled, baseURL, reasoningEffort)
+ });
+ return parseOldStringNotFoundReason(response.choices?.[0]?.message?.content ?? "");
+ } catch {
+ return null;
+ }
+}
+__name(inferOldStringNotFoundReasonWithLLM, "inferOldStringNotFoundReasonWithLLM");
+function getLinesBeforeScope(lineIndex, scope, lineLimit) {
+ const startIndex = Math.max(0, scope.startLine - 1 - lineLimit);
+ const endIndex = Math.max(0, scope.startLine - 1);
+ return lineIndex.lines.slice(startIndex, endIndex).join("\n");
+}
+__name(getLinesBeforeScope, "getLinesBeforeScope");
+function getLinesAfterScope(lineIndex, scope, lineLimit) {
+ const startIndex = Math.min(lineIndex.lines.length, scope.endLine);
+ const endIndex = Math.min(lineIndex.lines.length, startIndex + lineLimit);
+ return lineIndex.lines.slice(startIndex, endIndex).join("\n");
+}
+__name(getLinesAfterScope, "getLinesAfterScope");
+function parseOldStringNotFoundReason(content) {
+ const trimmed = content.trim();
+ if (!trimmed) {
+ return null;
+ }
+ const normalized = trimmed.replace(/```(?:xml)?\s*([\s\S]*?)```/i, "$1").trim();
+ const reasonMatch = normalized.match(/(?:|([\s\S]*?))<\/reason>/i);
+ const reason = (reasonMatch?.[1] ?? reasonMatch?.[2])?.trim();
+ return reason || null;
+}
+__name(parseOldStringNotFoundReason, "parseOldStringNotFoundReason");
+async function correctEscapedStringsWithLLM(snippetText, oldString, newString, matchedText, context) {
+ const clientFactory = context.createOpenAIClient;
+ if (!clientFactory) {
+ return null;
+ }
+ const { client, model, baseURL, thinkingEnabled, reasoningEffort } = clientFactory();
+ if (!client) {
+ return null;
+ }
+ try {
+ const response = await client.chat.completions.create({
+ model,
+ messages: [
+ {
+ role: "system",
+ content: "You correct file-edit strings when the only problem is escaping. Return XML only using ....... Do not change semantics; only fix quoting or escaping so corrected_old_string matches the snippet exactly."
+ },
+ {
+ role: "user",
+ content: `
+
+
+
+
+
+
+
+
+
+
+`
+ }
+ ],
+ ...buildThinkingRequestOptions(thinkingEnabled, baseURL, reasoningEffort)
+ });
+ const content = response.choices?.[0]?.message?.content ?? "";
+ const parsed = parseCorrectedEditStrings(content);
+ if (!parsed) {
+ return null;
+ }
+ const normalizedOld = normalizeLooseText(oldString);
+ const normalizedNew = normalizeLooseText(newString);
+ if (normalizeLooseText(parsed.oldString) !== normalizedOld) {
+ return null;
+ }
+ if (normalizeLooseText(parsed.newString) !== normalizedNew) {
+ return null;
+ }
+ if (parsed.oldString === parsed.newString) {
+ return null;
+ }
+ return parsed;
+ } catch {
+ return null;
+ }
+}
+__name(correctEscapedStringsWithLLM, "correctEscapedStringsWithLLM");
+function parseCorrectedEditStrings(content) {
+ const trimmed = content.trim();
+ if (!trimmed) {
+ return null;
+ }
+ const normalized = trimmed.replace(/```(?:xml)?\s*([\s\S]*?)```/i, "$1").trim();
+ const oldMatch = normalized.match(
+ /(?:|([\s\S]*?))<\/corrected_old_string>/i
+ );
+ const newMatch = normalized.match(
+ /(?:|([\s\S]*?))<\/corrected_new_string>/i
+ );
+ const correctedOldString = oldMatch?.[1] ?? oldMatch?.[2];
+ const correctedNewString = newMatch?.[1] ?? newMatch?.[2];
+ if (typeof correctedOldString === "string" && typeof correctedNewString === "string") {
+ return {
+ oldString: correctedOldString,
+ newString: correctedNewString
+ };
+ }
+ return null;
+}
+__name(parseCorrectedEditStrings, "parseCorrectedEditStrings");
+function escapeRegExp(value) {
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
+__name(escapeRegExp, "escapeRegExp");
+function normalizeLooseText(value) {
+ return value.replace(/\r\n?/g, "\n").replace(/\\+(?=["'`\\])/g, "").replace(/[ \t]+/g, " ").trim();
+}
+__name(normalizeLooseText, "normalizeLooseText");
+function similarityScore(left2, right2) {
+ if (left2 === right2) {
+ return 1;
+ }
+ if (!left2 || !right2) {
+ return 0;
+ }
+ const leftBigrams = toBigrams(left2);
+ const rightBigrams = toBigrams(right2);
+ if (leftBigrams.length === 0 || rightBigrams.length === 0) {
+ return left2 === right2 ? 1 : 0;
+ }
+ const rightCounts = /* @__PURE__ */ new Map();
+ for (const bigram of rightBigrams) {
+ rightCounts.set(bigram, (rightCounts.get(bigram) ?? 0) + 1);
+ }
+ let overlap = 0;
+ for (const bigram of leftBigrams) {
+ const count = rightCounts.get(bigram) ?? 0;
+ if (count > 0) {
+ overlap += 1;
+ rightCounts.set(bigram, count - 1);
+ }
+ }
+ return 2 * overlap / (leftBigrams.length + rightBigrams.length);
+}
+__name(similarityScore, "similarityScore");
+function toBigrams(value) {
+ if (value.length < 2) {
+ return [value];
+ }
+ const result = [];
+ for (let index = 0; index < value.length - 1; index += 1) {
+ result.push(value.slice(index, index + 2));
+ }
+ return result;
+}
+__name(toBigrams, "toBigrams");
+
+// packages/core/src/tools/read-handler.ts
+init_esbuild_shims();
+var import_ignore = __toESM(require_ignore(), 1);
+import * as fs11 from "fs";
+import * as path8 from "path";
+var DEFAULT_LINE_LIMIT = 2e3;
+var MAX_LINE_LENGTH = 2e3;
+var PDF_LARGE_PAGE_THRESHOLD = 10;
+var PDF_MAX_PAGE_RANGE = 20;
+var LINE_NUMBER_WIDTH = 6;
+var DEFAULT_GITIGNORE = [
+ "node_modules/",
+ ".git/",
+ "dist/",
+ "build/",
+ "out/",
+ ".next/",
+ ".nuxt/",
+ ".venv/",
+ "venv/",
+ "__pycache__/",
+ "*.pyc",
+ "*.pyo",
+ ".pytest_cache/",
+ ".mypy_cache/",
+ ".ruff_cache/",
+ ".gradle/",
+ ".idea/",
+ ".vscode/",
+ "*.class",
+ "*.jar",
+ "*.war",
+ "target/"
+];
+async function handleReadTool(args, context) {
+ let filePath = typeof args.file_path === "string" ? normalizeFilePath(args.file_path) : "";
+ if (!filePath.trim()) {
+ return {
+ ok: false,
+ name: "read",
+ error: 'Missing required "file_path" string.'
+ };
+ }
+ if (!isAbsoluteFilePath(filePath)) {
+ if (filePath.startsWith("../") || filePath.startsWith("..\\")) {
+ return {
+ ok: false,
+ name: "read",
+ error: "file_path must be an absolute path."
+ };
+ }
+ const normalizedSuffix = normalizeRelativeSuffix(filePath);
+ const isIgnored = loadGitignoreMatcher(context.projectRoot);
+ const matches = normalizedSuffix ? findSuffixMatches(context.projectRoot, normalizedSuffix, isIgnored) : [];
+ if (matches.length > 1) {
+ return {
+ ok: false,
+ name: "read",
+ error: `file_path must be an absolute path. The file_path is ambiguous and may refer to multiple files:
+${matches.slice(0, 3).join("\n")}` + (matches.length > 3 ? `
+...and ${matches.length - 3} more.` : "")
+ };
+ }
+ const resolvedPath = path8.resolve(context.projectRoot, filePath);
+ if (!fs11.existsSync(resolvedPath)) {
+ if (matches.length > 0) {
+ return {
+ ok: false,
+ name: "read",
+ error: `file_path must be an absolute path. The file_path "${filePath}" is ambiguous.`
+ };
+ } else {
+ return {
+ ok: false,
+ name: "read",
+ error: `File not found: ${filePath}`
+ };
+ }
+ }
+ filePath = resolvedPath;
+ }
+ if (!fs11.existsSync(filePath)) {
+ return {
+ ok: false,
+ name: "read",
+ error: `File not found: ${filePath}`
+ };
+ }
+ let stat;
+ try {
+ stat = fs11.statSync(filePath);
+ } catch (error51) {
+ const message = error51 instanceof Error ? error51.message : String(error51);
+ return {
+ ok: false,
+ name: "read",
+ error: `Failed to stat file: ${message}`
+ };
+ }
+ if (stat.isDirectory()) {
+ return {
+ ok: false,
+ name: "read",
+ error: "file_path points to a directory. Use bash ls for directories."
+ };
+ }
+ const ext = path8.extname(filePath).toLowerCase();
+ try {
+ if (ext === ".ipynb") {
+ const output = readNotebook(filePath);
+ markFileRead(context.sessionId, filePath, {
+ content: "",
+ timestamp: Math.floor(stat.mtimeMs),
+ isPartialView: true
+ });
+ return {
+ ok: true,
+ name: "read",
+ output
+ };
+ }
+ if (ext === ".pdf") {
+ const pagesParam = typeof args.pages === "string" ? args.pages.trim() : "";
+ const buffer = fs11.readFileSync(filePath);
+ const pageCount = countPdfPages(buffer);
+ const pageRange = pagesParam ? parsePageRange(pagesParam) : null;
+ if (!pageRange && pageCount !== null && pageCount > PDF_LARGE_PAGE_THRESHOLD) {
+ return {
+ ok: false,
+ name: "read",
+ error: `PDF has ${pageCount} pages; provide "pages" to read a range.`
+ };
+ }
+ if (pageRange && pageRange.count > PDF_MAX_PAGE_RANGE) {
+ return {
+ ok: false,
+ name: "read",
+ error: `PDF page range exceeds ${PDF_MAX_PAGE_RANGE} pages.`
+ };
+ }
+ if (pageRange && pageCount !== null && pageRange.end > pageCount) {
+ return {
+ ok: false,
+ name: "read",
+ error: `PDF page range exceeds total page count (${pageCount}).`
+ };
+ }
+ const base643 = buffer.toString("base64");
+ markFileRead(context.sessionId, filePath, {
+ content: "",
+ timestamp: Math.floor(stat.mtimeMs),
+ isPartialView: true
+ });
+ return {
+ ok: true,
+ name: "read",
+ output: `data:application/pdf;base64,${base643}`,
+ metadata: {
+ mime: "application/pdf",
+ encoding: "base64",
+ bytes: buffer.length,
+ pageCount,
+ pages: pageRange ? `${pageRange.start}-${pageRange.end}` : null
+ }
+ };
+ }
+ if (isImageExtension(ext)) {
+ const buffer = fs11.readFileSync(filePath);
+ const mime = getImageMimeType(ext);
+ markFileRead(context.sessionId, filePath, {
+ content: "",
+ timestamp: Math.floor(stat.mtimeMs),
+ isPartialView: true
+ });
+ return {
+ ok: true,
+ name: "read",
+ output: "File loaded.",
+ metadata: {
+ mime,
+ bytes: buffer.length
+ },
+ followUpMessages: [buildImageFollowUpMessage(filePath, mime, buffer)]
+ };
+ }
+ const offset = parseLineNumber(args.offset, "offset");
+ const limit2 = parseLineLimit(args.limit);
+ if (!offset.ok) {
+ return {
+ ok: false,
+ name: "read",
+ error: offset.error
+ };
+ }
+ if (!limit2.ok) {
+ return {
+ ok: false,
+ name: "read",
+ error: limit2.error
+ };
+ }
+ const textResult = readTextFile(filePath, offset.value, limit2.value);
+ markFileRead(context.sessionId, filePath, {
+ content: textResult.content,
+ timestamp: textResult.timestamp,
+ offset: textResult.isPartialView ? textResult.startLine : void 0,
+ limit: textResult.isPartialView ? Math.max(1, textResult.endLine - textResult.startLine + 1) : void 0,
+ isPartialView: textResult.isPartialView,
+ encoding: textResult.encoding,
+ lineEndings: textResult.lineEndings
+ });
+ const snippet = textResult.isPartialView ? createSnippet(context.sessionId, filePath, textResult.startLine, textResult.endLine, textResult.output) : createFullFileSnippet(context.sessionId, filePath, textResult.startLine, textResult.endLine, textResult.output);
+ return {
+ ok: true,
+ name: "read",
+ output: textResult.output,
+ metadata: snippet ? {
+ snippet: {
+ id: snippet.id,
+ filePath: snippet.filePath,
+ startLine: snippet.startLine,
+ endLine: snippet.endLine
+ }
+ } : void 0
+ };
+ } catch (error51) {
+ const message = error51 instanceof Error ? error51.message : String(error51);
+ return {
+ ok: false,
+ name: "read",
+ error: message
+ };
+ }
+}
+__name(handleReadTool, "handleReadTool");
+function normalizeRelativeSuffix(relativePath) {
+ const normalized = path8.normalize(relativePath).replace(/^(\.\/|\\)+/, "");
+ return normalized.trim() ? path8.sep + normalized : null;
+}
+__name(normalizeRelativeSuffix, "normalizeRelativeSuffix");
+function findSuffixMatches(root, suffix, isIgnored) {
+ const matches = [];
+ const queue = [root];
+ while (queue.length > 0) {
+ const current = queue.pop();
+ if (!current) {
+ continue;
+ }
+ let entries;
+ try {
+ entries = fs11.readdirSync(current, { withFileTypes: true });
+ } catch {
+ continue;
+ }
+ for (const entry of entries) {
+ const fullPath = path8.join(current, entry.name);
+ const relPath = path8.relative(root, fullPath).replace(/\\/g, "/");
+ if (isIgnored && isIgnored(relPath, entry.isDirectory())) {
+ continue;
+ }
+ if (entry.isDirectory()) {
+ queue.push(fullPath);
+ continue;
+ }
+ if (entry.isFile() && fullPath.endsWith(suffix)) {
+ matches.push(fullPath);
+ }
+ }
+ }
+ return matches;
+}
+__name(findSuffixMatches, "findSuffixMatches");
+function loadGitignoreMatcher(projectRoot) {
+ const gitignorePath = path8.join(projectRoot, ".gitignore");
+ if (!fs11.existsSync(gitignorePath)) {
+ const ig2 = (0, import_ignore.default)();
+ ig2.add(DEFAULT_GITIGNORE);
+ return (relPath, isDir) => {
+ if (!relPath) {
+ return false;
+ }
+ const candidate = isDir ? `${relPath}/` : relPath;
+ return ig2.ignores(candidate);
+ };
+ }
+ let content = "";
+ try {
+ content = fs11.readFileSync(gitignorePath, "utf8");
+ } catch {
+ const ig2 = (0, import_ignore.default)();
+ ig2.add(DEFAULT_GITIGNORE);
+ return (relPath, isDir) => {
+ if (!relPath) {
+ return false;
+ }
+ const candidate = isDir ? `${relPath}/` : relPath;
+ return ig2.ignores(candidate);
+ };
+ }
+ const ig = (0, import_ignore.default)();
+ ig.add(DEFAULT_GITIGNORE);
+ ig.add(content);
+ return (relPath, isDir) => {
+ if (!relPath) {
+ return false;
+ }
+ const candidate = isDir ? `${relPath}/` : relPath;
+ return ig.ignores(candidate);
+ };
+}
+__name(loadGitignoreMatcher, "loadGitignoreMatcher");
+function parseLineNumber(value, label) {
+ if (value === void 0 || value === null) {
+ return { ok: true, value: null };
+ }
+ const numeric = typeof value === "number" ? value : Number(value);
+ if (!Number.isFinite(numeric)) {
+ return { ok: false, error: `${label} must be a number.` };
+ }
+ const integer2 = Math.trunc(numeric);
+ if (integer2 < 1) {
+ return { ok: false, error: `${label} must be >= 1.` };
+ }
+ return { ok: true, value: integer2 };
+}
+__name(parseLineNumber, "parseLineNumber");
+function parseLineLimit(value) {
+ if (value === void 0 || value === null) {
+ return { ok: true, value: DEFAULT_LINE_LIMIT };
+ }
+ const numeric = typeof value === "number" ? value : Number(value);
+ if (!Number.isFinite(numeric)) {
+ return { ok: false, error: "limit must be a number." };
+ }
+ const integer2 = Math.trunc(numeric);
+ if (integer2 <= 0) {
+ return { ok: false, error: "limit must be > 0." };
+ }
+ return { ok: true, value: integer2 };
+}
+__name(parseLineLimit, "parseLineLimit");
+function readTextFile(filePath, offset, limit2) {
+ const metadata = readTextFileWithMetadata(filePath);
+ const raw = metadata.content;
+ if (!raw) {
+ return {
+ content: "",
+ output: "WARNING: File is empty.",
+ startLine: offset ?? 1,
+ endLine: offset ?? 1,
+ totalLines: 0,
+ isPartialView: false,
+ encoding: metadata.encoding,
+ lineEndings: metadata.lineEndings,
+ timestamp: metadata.timestamp
+ };
+ }
+ const lines = raw.split("\n");
+ if (lines.length === 1 && lines[0] === "") {
+ return {
+ content: "",
+ output: "WARNING: File is empty.",
+ startLine: offset ?? 1,
+ endLine: offset ?? 1,
+ totalLines: 0,
+ isPartialView: false,
+ encoding: metadata.encoding,
+ lineEndings: metadata.lineEndings,
+ timestamp: metadata.timestamp
+ };
+ }
+ const startIndex = offset ? offset - 1 : 0;
+ const endIndex = startIndex + limit2;
+ const selected = lines.slice(startIndex, endIndex);
+ const startLine = startIndex + 1;
+ const endLine = selected.length > 0 ? startIndex + selected.length : startLine;
+ const isPartialView = startLine !== 1 || endLine < lines.length;
+ return {
+ content: selected.join("\n"),
+ output: formatWithLineNumbers2(selected, startLine),
+ startLine,
+ endLine,
+ totalLines: lines.length,
+ isPartialView,
+ encoding: metadata.encoding,
+ lineEndings: metadata.lineEndings,
+ timestamp: metadata.timestamp
+ };
+}
+__name(readTextFile, "readTextFile");
+function formatWithLineNumbers2(lines, startLineNumber) {
+ return lines.map((line, index) => {
+ const lineNumber = startLineNumber + index;
+ const trimmedLine = line.length > MAX_LINE_LENGTH ? line.slice(0, MAX_LINE_LENGTH) : line;
+ return `${String(lineNumber).padStart(LINE_NUMBER_WIDTH, " ")} ${trimmedLine}`;
+ }).join("\n");
+}
+__name(formatWithLineNumbers2, "formatWithLineNumbers");
+function isImageExtension(ext) {
+ return [".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tif", ".tiff", ".svg", ".ico", ".avif"].includes(ext);
+}
+__name(isImageExtension, "isImageExtension");
+function getImageMimeType(ext) {
+ switch (ext) {
+ case ".jpg":
+ case ".jpeg":
+ return "image/jpeg";
+ case ".gif":
+ return "image/gif";
+ case ".webp":
+ return "image/webp";
+ case ".bmp":
+ return "image/bmp";
+ case ".tif":
+ case ".tiff":
+ return "image/tiff";
+ case ".svg":
+ return "image/svg+xml";
+ case ".ico":
+ return "image/x-icon";
+ case ".avif":
+ return "image/avif";
+ case ".png":
+ default:
+ return "image/png";
+ }
+}
+__name(getImageMimeType, "getImageMimeType");
+function buildImageFollowUpMessage(filePath, mime, buffer) {
+ const fileName = path8.basename(filePath);
+ return {
+ role: "system",
+ content: `The read tool has loaded \`${fileName}\`. Use the attached image content to answer the original request.`,
+ contentParams: [
+ {
+ type: "image_url",
+ image_url: {
+ url: `data:${mime};base64,${buffer.toString("base64")}`
+ }
+ }
+ ]
+ };
+}
+__name(buildImageFollowUpMessage, "buildImageFollowUpMessage");
+function countPdfPages(buffer) {
+ try {
+ const content = buffer.toString("latin1");
+ const matches = content.match(/\/Type\s*\/Page\b(?!s)/g);
+ return matches ? matches.length : 0;
+ } catch {
+ return null;
+ }
+}
+__name(countPdfPages, "countPdfPages");
+function parsePageRange(input) {
+ const trimmed = input.trim();
+ if (!trimmed) {
+ throw new Error("pages must be a non-empty string.");
+ }
+ if (trimmed.includes(",")) {
+ throw new Error('pages must be a single range like "1-5" or "3".');
+ }
+ const parts = trimmed.split("-").map((part) => part.trim());
+ if (parts.length === 1) {
+ const value = parsePositiveInt(parts[0], "pages");
+ return { start: value, end: value, count: 1 };
+ }
+ if (parts.length === 2) {
+ const start = parsePositiveInt(parts[0], "pages");
+ const end = parsePositiveInt(parts[1], "pages");
+ if (end < start) {
+ throw new Error("pages range end must be >= start.");
+ }
+ return { start, end, count: end - start + 1 };
+ }
+ throw new Error('pages must be a single range like "1-5" or "3".');
+}
+__name(parsePageRange, "parsePageRange");
+function parsePositiveInt(value, label) {
+ const numeric = Number(value);
+ if (!Number.isFinite(numeric)) {
+ throw new Error(`${label} must be a number.`);
+ }
+ const integer2 = Math.trunc(numeric);
+ if (integer2 < 1) {
+ throw new Error(`${label} must be >= 1.`);
+ }
+ return integer2;
+}
+__name(parsePositiveInt, "parsePositiveInt");
+function readNotebook(filePath) {
+ const raw = fs11.readFileSync(filePath, "utf8");
+ if (!raw) {
+ return "WARNING: File is empty.";
+ }
+ const parsed = JSON.parse(raw);
+ const lines = [];
+ const cells = Array.isArray(parsed.cells) ? parsed.cells : [];
+ cells.forEach((cell, index) => {
+ const cellType = cell.cell_type ?? "unknown";
+ lines.push(`# Cell ${index + 1} (${cellType})`);
+ const source = normalizeNotebookField(cell.source);
+ if (source.length > 0) {
+ lines.push(...source);
+ }
+ const outputs = Array.isArray(cell.outputs) ? cell.outputs : [];
+ outputs.forEach((output, outputIndex) => {
+ const outputType = typeof output.output_type === "string" ? output.output_type : "output";
+ lines.push(`# Output ${outputIndex + 1} (${outputType})`);
+ lines.push(...formatNotebookOutput(output));
+ });
+ });
+ if (lines.length === 0) {
+ return "WARNING: Notebook has no cells.";
+ }
+ return formatWithLineNumbers2(lines, 1);
+}
+__name(readNotebook, "readNotebook");
+function normalizeNotebookField(value) {
+ if (Array.isArray(value)) {
+ return value.map((item) => String(item).replace(/\r?\n$/, ""));
+ }
+ if (typeof value === "string") {
+ return value.split(/\r?\n/);
+ }
+ return [];
+}
+__name(normalizeNotebookField, "normalizeNotebookField");
+function formatNotebookOutput(output) {
+ const lines = [];
+ const text = output.text;
+ if (Array.isArray(text)) {
+ lines.push(...text.map((item) => String(item).replace(/\r?\n$/, "")));
+ } else if (typeof text === "string") {
+ lines.push(...text.split(/\r?\n/));
+ }
+ const data = output.data;
+ if (data && typeof data === "object") {
+ const record2 = data;
+ const textPlain = record2["text/plain"];
+ if (Array.isArray(textPlain)) {
+ lines.push(...textPlain.map((item) => String(item).replace(/\r?\n$/, "")));
+ } else if (typeof textPlain === "string") {
+ lines.push(...textPlain.split(/\r?\n/));
+ }
+ const imagePng = record2["image/png"];
+ if (typeof imagePng === "string") {
+ lines.push(`[image/png ${imagePng.length} chars]`);
+ }
+ const imageJpeg = record2["image/jpeg"];
+ if (typeof imageJpeg === "string") {
+ lines.push(`[image/jpeg ${imageJpeg.length} chars]`);
+ }
+ }
+ const trace = output.traceback;
+ if (Array.isArray(trace)) {
+ lines.push(...trace.map((item) => String(item).replace(/\r?\n$/, "")));
+ }
+ if (lines.length === 0) {
+ lines.push("[output omitted]");
+ }
+ return lines;
+}
+__name(formatNotebookOutput, "formatNotebookOutput");
+
+// packages/core/src/tools/update-plan-handler.ts
+init_esbuild_shims();
+var updatePlanSchema = external_exports.strictObject({
+ plan: external_exports.string().trim().min(1, "plan must not be empty."),
+ explanation: external_exports.string().trim().optional()
+});
+async function handleUpdatePlanTool(args, _context) {
+ return executeValidatedTool("UpdatePlan", updatePlanSchema, args, _context, async (input) => ({
+ ok: true,
+ name: "UpdatePlan",
+ output: "Plan updated.",
+ metadata: {
+ plan: input.plan,
+ ...input.explanation ? { explanation: input.explanation } : {}
+ }
+ }));
+}
+__name(handleUpdatePlanTool, "handleUpdatePlanTool");
+
+// packages/core/src/tools/web-search-handler.ts
+init_esbuild_shims();
+import { randomUUID as randomUUID2 } from "crypto";
+import { spawn as spawn3 } from "child_process";
+var MAX_OUTPUT_CHARS2 = 3e4;
+var MAX_CAPTURE_CHARS2 = 10 * 1024 * 1024;
+var WEB_SEARCH_TOOL_ACTIVITY_PREFIX = "WebSearch:";
+var DEFAULT_WEB_SEARCH_API_URL = "https://deepcode.vegamo.cn/api/plugin/web-search";
+async function handleWebSearchTool(args, context) {
+ const query = typeof args.query === "string" ? args.query : "";
+ if (!query.trim()) {
+ return {
+ ok: false,
+ name: "WebSearch",
+ error: 'Missing required "query" string.'
+ };
+ }
+ const llmContext = context.createOpenAIClient?.();
+ const scriptPath = llmContext?.webSearchTool?.trim();
+ if (scriptPath) {
+ return executeConfiguredWebSearch(query, scriptPath, context, llmContext?.env ?? {});
+ }
+ if (!hasUsableClient(llmContext)) {
+ return {
+ ok: false,
+ name: "WebSearch",
+ error: "WebSearch default mode requires a valid LLM configuration in ~/.deepcode/settings.json or ./.deepcode/settings.json."
+ };
+ }
+ return executeDefaultWebSearch(query, llmContext, context);
+}
+__name(handleWebSearchTool, "handleWebSearchTool");
+function hasUsableClient(value) {
+ return Boolean(value?.client);
+}
+__name(hasUsableClient, "hasUsableClient");
+async function executeConfiguredWebSearch(query, scriptPath, context, configuredEnv) {
+ const execution = await runWebSearchScript(scriptPath, query, context, configuredEnv);
+ const output = execution.stdout.slice(0, MAX_OUTPUT_CHARS2);
+ const truncated = execution.stdout.length > MAX_OUTPUT_CHARS2;
+ if (execution.error) {
+ return {
+ ok: false,
+ name: "WebSearch",
+ error: execution.error,
+ output: output || void 0,
+ metadata: {
+ exitCode: execution.exitCode,
+ signal: execution.signal,
+ stderr: execution.stderr || void 0,
+ truncated
+ }
+ };
+ }
+ if (execution.exitCode !== 0 || execution.signal !== null) {
+ return {
+ ok: false,
+ name: "WebSearch",
+ error: buildCommandError(execution.exitCode, execution.signal),
+ output: output || void 0,
+ metadata: {
+ exitCode: execution.exitCode,
+ signal: execution.signal,
+ stderr: execution.stderr || void 0,
+ truncated
+ }
+ };
+ }
+ return {
+ ok: true,
+ name: "WebSearch",
+ output: output || void 0,
+ metadata: {
+ exitCode: execution.exitCode,
+ signal: execution.signal,
+ truncated,
+ stderr: execution.stderr || void 0
+ }
+ };
+}
+__name(executeConfiguredWebSearch, "executeConfiguredWebSearch");
+async function executeDefaultWebSearch(query, llmContext, context) {
+ try {
+ const prepared = await prepareSearchQuery(query, llmContext);
+ const output = await runDefaultWebSearchRequest(prepared.resolvedQuery, llmContext.machineId, context);
+ return {
+ ok: true,
+ name: "WebSearch",
+ output,
+ metadata: {
+ originalQuery: query,
+ resolvedQuery: prepared.resolvedQuery,
+ translated: prepared.translated,
+ dominantLanguage: prepared.decision.dominantLanguage,
+ languageReason: prepared.decision.reason
+ }
+ };
+ } catch (error51) {
+ const message = error51 instanceof Error ? error51.message : String(error51);
+ return {
+ ok: false,
+ name: "WebSearch",
+ error: `WebSearch default mode failed: ${message}`
+ };
+ }
+}
+__name(executeDefaultWebSearch, "executeDefaultWebSearch");
+async function runWebSearchScript(scriptPath, query, context, configuredEnv) {
+ return new Promise((resolve16) => {
+ const child = spawn3(scriptPath, [query], {
+ cwd: context.projectRoot,
+ env: { ...process.env, ...configuredEnv },
+ stdio: ["ignore", "pipe", "pipe"]
+ });
+ const pid = child.pid;
+ if (typeof pid === "number") {
+ context.onProcessStart?.(pid, formatWebSearchActivityLabel(query));
+ }
+ let stdout = "";
+ let stderr = "";
+ let error51;
+ child.stdout?.on("data", (chunk) => {
+ stdout = appendChunk2(stdout, chunk);
+ });
+ child.stderr?.on("data", (chunk) => {
+ stderr = appendChunk2(stderr, chunk);
+ });
+ child.on("error", (spawnError) => {
+ error51 = spawnError.message;
+ });
+ child.on("close", (code, signal) => {
+ if (typeof pid === "number") {
+ context.onProcessExit?.(pid);
+ }
+ resolve16({
+ stdout,
+ stderr,
+ exitCode: typeof code === "number" ? code : null,
+ signal: signal ?? null,
+ error: error51
+ });
+ });
+ });
+}
+__name(runWebSearchScript, "runWebSearchScript");
+async function prepareSearchQuery(query, llmContext) {
+ const decision = await decideSearchLanguage(query, llmContext);
+ const containsChinese = containsChineseChar(query);
+ if (decision.dominantLanguage === "en" && containsChinese) {
+ const translatedQuery = await translateQuery(query, "English", llmContext);
+ if (translatedQuery) {
+ return {
+ resolvedQuery: translatedQuery,
+ decision,
+ translated: true
+ };
+ }
+ }
+ if (decision.dominantLanguage === "zh" && !containsChinese) {
+ const translatedQuery = await translateQuery(query, "Chinese", llmContext);
+ if (translatedQuery) {
+ return {
+ resolvedQuery: translatedQuery,
+ decision,
+ translated: true
+ };
+ }
+ }
+ return {
+ resolvedQuery: query,
+ decision,
+ translated: false
+ };
+}
+__name(prepareSearchQuery, "prepareSearchQuery");
+function containsChineseChar(text) {
+ return /[\u4e00-\u9fff]/.test(text);
+}
+__name(containsChineseChar, "containsChineseChar");
+async function decideSearchLanguage(query, llmContext) {
+ const prompt = `Decide whether the topic below has more useful online material in English or Chinese.
+
+Topic:
+\`\`\`text
+${query}
+\`\`\`
+
+Return strict JSON:
+{"dominant_language":"en"|"zh","reason":"one short sentence"}
+Do not include markdown or any extra text.`;
+ const result = parseJsonResponse(await chat(llmContext, prompt));
+ const dominantLanguage = result.dominant_language;
+ if (dominantLanguage !== "en" && dominantLanguage !== "zh") {
+ throw new Error(`Unexpected dominant language: ${String(dominantLanguage)}`);
+ }
+ return {
+ dominantLanguage,
+ reason: typeof result.reason === "string" ? result.reason : ""
+ };
+}
+__name(decideSearchLanguage, "decideSearchLanguage");
+async function translateQuery(query, targetLanguage, llmContext) {
+ const prompt = `Translate the query text below into ${targetLanguage}.
+
+Requirements:
+- Preserve product names, library names, API names, versions, and abbreviations when appropriate.
+- Return only the translated query, without quotes or explanation.
+
+Query:
+\`\`\`text
+${query}
+\`\`\``;
+ return stripCodeFence(await chat(llmContext, prompt)).trim().replace(/^['"]|['"]$/g, "");
+}
+__name(translateQuery, "translateQuery");
+async function chat(llmContext, prompt) {
+ const response = await llmContext.client.chat.completions.create({
+ model: llmContext.model,
+ messages: [{ role: "user", content: prompt }]
+ });
+ const content = response.choices?.[0]?.message?.content;
+ if (typeof content === "string") {
+ return content.trim();
+ }
+ if (Array.isArray(content)) {
+ return content.map((part) => typeof part.text === "string" ? part.text : "").join("\n").trim();
+ }
+ return "";
+}
+__name(chat, "chat");
+function parseJsonResponse(text) {
+ const cleaned = stripCodeFence(text).trim();
+ try {
+ return JSON.parse(cleaned);
+ } catch {
+ const firstBrace = cleaned.indexOf("{");
+ const lastBrace = cleaned.lastIndexOf("}");
+ if (firstBrace >= 0 && lastBrace > firstBrace) {
+ return JSON.parse(cleaned.slice(firstBrace, lastBrace + 1));
+ }
+ throw new Error(`Failed to parse JSON response: ${cleaned || ""}`);
+ }
+}
+__name(parseJsonResponse, "parseJsonResponse");
+function stripCodeFence(text) {
+ const trimmed = text.trim();
+ const fenceMatch = trimmed.match(/^```(?:[\w-]+)?\n([\s\S]*?)\n```$/);
+ return fenceMatch ? fenceMatch[1] : trimmed;
+}
+__name(stripCodeFence, "stripCodeFence");
+async function runDefaultWebSearchRequest(query, machineId, context) {
+ if (!machineId) {
+ throw new Error("Missing vscode.env.machineId for the default WebSearch request.");
+ }
+ const activityId = `web-search-${randomUUID2()}`;
+ context.onProcessStart?.(activityId, formatWebSearchActivityLabel(query));
+ try {
+ const response = await fetch(DEFAULT_WEB_SEARCH_API_URL, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Token: machineId
+ },
+ body: JSON.stringify({ query })
+ });
+ if (!response.ok) {
+ const body = await response.text().catch(() => "");
+ throw new Error(`WebSearch API request failed with status ${response.status}${body ? `: ${body}` : ""}`);
+ }
+ const payload = await response.json();
+ if (typeof payload.result === "string" && payload.result.trim()) {
+ return payload.result.trim();
+ }
+ } finally {
+ context.onProcessExit?.(activityId);
+ }
+ throw new Error("The web search response was empty.");
+}
+__name(runDefaultWebSearchRequest, "runDefaultWebSearchRequest");
+function appendChunk2(existing, chunk) {
+ if (existing.length >= MAX_CAPTURE_CHARS2) {
+ return existing;
+ }
+ const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
+ const remaining = MAX_CAPTURE_CHARS2 - existing.length;
+ return `${existing}${text.slice(0, remaining)}`;
+}
+__name(appendChunk2, "appendChunk");
+function formatWebSearchActivityLabel(query) {
+ const normalizedQuery = query.replace(/\s+/g, " ").trim();
+ const maxQueryLength = 180;
+ const clippedQuery = normalizedQuery.length > maxQueryLength ? `${normalizedQuery.slice(0, maxQueryLength - 3)}...` : normalizedQuery;
+ return `${WEB_SEARCH_TOOL_ACTIVITY_PREFIX} ${clippedQuery}`;
+}
+__name(formatWebSearchActivityLabel, "formatWebSearchActivityLabel");
+function buildCommandError(exitCode, signal) {
+ if (signal) {
+ return `WebSearch command terminated by signal ${signal}.`;
+ }
+ if (exitCode !== null) {
+ return `WebSearch command failed with exit code ${exitCode}.`;
+ }
+ return "WebSearch command failed.";
+}
+__name(buildCommandError, "buildCommandError");
+
+// packages/core/src/tools/write-handler.ts
+init_esbuild_shims();
+import * as fs12 from "fs";
+var writeSchema = external_exports.strictObject({
+ file_path: external_exports.string().min(1, "file_path is required."),
+ content: external_exports.string({
+ error: "content must be a string. If you are writing JSON, serialize the full document to text before calling write."
+ })
+});
+async function handleWriteTool(args, context) {
+ let repairMetadata = null;
+ return executeValidatedTool(
+ "write",
+ writeSchema,
+ args,
+ context,
+ async (input) => {
+ const filePath = normalizeFilePath(input.file_path);
+ if (!isAbsoluteFilePath(filePath)) {
+ return {
+ ok: false,
+ name: "write",
+ error: "file_path must be an absolute path."
+ };
+ }
+ const existingFile = fs12.existsSync(filePath);
+ if (existingFile) {
+ let stat;
+ try {
+ stat = fs12.statSync(filePath);
+ } catch (error51) {
+ const message = error51 instanceof Error ? error51.message : String(error51);
+ return {
+ ok: false,
+ name: "write",
+ error: `Failed to stat file: ${message}`
+ };
+ }
+ if (stat.isDirectory()) {
+ return {
+ ok: false,
+ name: "write",
+ error: "file_path points to a directory."
+ };
+ }
+ if (stat.size > 0) {
+ const fileState = getFileState(context.sessionId, filePath);
+ if (!fileState || !isFullFileView(fileState)) {
+ return {
+ ok: false,
+ name: "write",
+ error: "Must read the full existing file before writing."
+ };
+ }
+ if (hasFileChangedSinceState(filePath, fileState)) {
+ return {
+ ok: false,
+ name: "write",
+ error: "File has been modified since read. Read it again before writing."
+ };
+ }
+ }
+ }
+ const normalizedContent = normalizeContent(input.content);
+ try {
+ ensureParentDirectory(filePath);
+ const existingMetadata = existingFile ? readTextFileWithMetadata(filePath) : null;
+ const encoding = existingMetadata?.encoding ?? "utf8";
+ const lineEndings = existingMetadata?.lineEndings ?? (input.content.includes("\r\n") ? "CRLF" : "LF");
+ const diffPreview = buildDiffPreview(filePath, existingMetadata?.content ?? null, normalizedContent);
+ context.onBeforeFileMutation?.(filePath);
+ const bytes = writeTextFile(filePath, normalizedContent, encoding, lineEndings);
+ context.onAfterFileMutation?.(filePath);
+ const freshMetadata = readTextFileWithMetadata(filePath);
+ recordFileState(
+ context.sessionId,
+ {
+ filePath,
+ content: freshMetadata.content,
+ timestamp: freshMetadata.timestamp,
+ encoding: freshMetadata.encoding,
+ lineEndings: freshMetadata.lineEndings
+ },
+ { incrementVersion: true }
+ );
+ return {
+ ok: true,
+ name: "write",
+ output: existingMetadata ? "Updated file." : "Created file.",
+ metadata: {
+ type: existingMetadata ? "update" : "create",
+ file_path: filePath,
+ bytes,
+ encoding: freshMetadata.encoding,
+ line_endings: freshMetadata.lineEndings,
+ cache_refreshed: true,
+ diff_preview: diffPreview,
+ ...repairMetadata
+ }
+ };
+ } catch (error51) {
+ const message = error51 instanceof Error ? error51.message : String(error51);
+ return {
+ ok: false,
+ name: "write",
+ error: message
+ };
+ }
+ },
+ {
+ preprocess: /* @__PURE__ */ __name((rawInput) => {
+ const filePath = typeof rawInput.file_path === "string" ? normalizeFilePath(rawInput.file_path) : "";
+ const content = rawInput.content;
+ if (filePath.toLowerCase().endsWith(".json") && content !== null && typeof content === "object" && !Buffer.isBuffer(content)) {
+ repairMetadata = {
+ input_repaired: true,
+ repair_kind: "json-stringify-content"
+ };
+ return {
+ ok: true,
+ input: {
+ ...rawInput,
+ file_path: filePath,
+ content: JSON.stringify(content, null, 2)
+ }
+ };
+ }
+ repairMetadata = null;
+ return {
+ ok: true,
+ input: typeof rawInput.file_path === "string" ? { ...rawInput, file_path: filePath } : rawInput
+ };
+ }, "preprocess")
+ }
+ );
+}
+__name(handleWriteTool, "handleWriteTool");
+
+// packages/core/src/tools/executor.ts
+var BUILT_IN_TOOL_NAME_ALIASES = /* @__PURE__ */ new Map([
+ ["Bash", "bash"],
+ ["Read", "read"],
+ ["Write", "write"],
+ ["Edit", "edit"]
+]);
+var ToolExecutor = class {
+ static {
+ __name(this, "ToolExecutor");
+ }
+ projectRoot;
+ createOpenAIClient;
+ mcpManager;
+ toolHandlers = /* @__PURE__ */ new Map();
+ constructor(projectRoot, createOpenAIClient2, mcpManager) {
+ this.projectRoot = projectRoot;
+ this.createOpenAIClient = createOpenAIClient2;
+ this.mcpManager = mcpManager;
+ this.registerToolHandlers();
+ }
+ async executeToolCalls(sessionId, toolCalls, hooks) {
+ const parsedCalls = toolCalls.map((toolCall) => this.parseToolCall(toolCall)).filter((toolCall) => Boolean(toolCall));
+ const executions = [];
+ for (const toolCall of parsedCalls) {
+ if (hooks?.shouldStop?.()) {
+ break;
+ }
+ const result = await this.executeToolCall(sessionId, toolCall, hooks);
+ executions.push({
+ toolCallId: toolCall.id,
+ content: this.formatToolResult(result),
+ result
+ });
+ if (hooks?.shouldStop?.()) {
+ break;
+ }
+ }
+ return executions;
+ }
+ registerToolHandlers() {
+ this.toolHandlers.set("bash", handleBashTool);
+ this.toolHandlers.set("read", handleReadTool);
+ this.toolHandlers.set("write", handleWriteTool);
+ this.toolHandlers.set("edit", handleEditTool);
+ this.toolHandlers.set("AskUserQuestion", handleAskUserQuestionTool);
+ this.toolHandlers.set("UpdatePlan", handleUpdatePlanTool);
+ this.toolHandlers.set("WebSearch", handleWebSearchTool);
+ }
+ parseToolCall(toolCall) {
+ if (!toolCall || typeof toolCall !== "object") {
+ return null;
+ }
+ const record2 = toolCall;
+ if (typeof record2.id !== "string") {
+ return null;
+ }
+ const functionRecord = record2.function;
+ if (!functionRecord || typeof functionRecord !== "object") {
+ return null;
+ }
+ if (typeof functionRecord.name !== "string") {
+ return null;
+ }
+ const rawArguments = typeof functionRecord.arguments === "string" ? functionRecord.arguments : "";
+ return {
+ id: record2.id,
+ type: "function",
+ function: {
+ name: functionRecord.name,
+ arguments: rawArguments
+ }
+ };
+ }
+ async executeToolCall(sessionId, toolCall, hooks) {
+ const toolName = toolCall.function.name;
+ const handlerName = BUILT_IN_TOOL_NAME_ALIASES.get(toolName) ?? toolName;
+ const handler = this.toolHandlers.get(handlerName);
+ if (!handler) {
+ if (this.mcpManager?.isMcpTool(toolName)) {
+ const parsedArgs2 = this.parseToolArguments(toolCall.function.arguments);
+ const args = parsedArgs2.ok ? parsedArgs2.args : {};
+ return this.mcpManager.executeMcpTool(toolName, args);
+ }
+ return {
+ ok: false,
+ name: toolName,
+ error: `Unknown tool: ${toolName}`
+ };
+ }
+ const parsedArgs = this.parseToolArguments(toolCall.function.arguments);
+ if (!parsedArgs.ok) {
+ return {
+ ok: false,
+ name: toolName,
+ error: parsedArgs.error
+ };
+ }
+ try {
+ return await handler(parsedArgs.args, {
+ sessionId,
+ projectRoot: this.projectRoot,
+ toolCall,
+ createOpenAIClient: this.createOpenAIClient,
+ onProcessStart: hooks?.onProcessStart,
+ onProcessExit: hooks?.onProcessExit,
+ onProcessStdout: hooks?.onProcessStdout,
+ onProcessTimeoutControl: hooks?.onProcessTimeoutControl,
+ onBackgroundProcessComplete: hooks?.onBackgroundProcessComplete,
+ onBeforeFileMutation: hooks?.onBeforeFileMutation,
+ onAfterFileMutation: hooks?.onAfterFileMutation
+ });
+ } catch (error51) {
+ const message = error51 instanceof Error ? error51.message : String(error51);
+ return {
+ ok: false,
+ name: toolName,
+ error: message
+ };
+ }
+ }
+ parseToolArguments(rawArguments) {
+ if (!rawArguments) {
+ return { ok: true, args: {} };
+ }
+ try {
+ const parsed = JSON.parse(rawArguments);
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
+ return { ok: false, error: "InputParseError: Tool arguments must be a JSON object." };
+ }
+ return { ok: true, args: parsed };
+ } catch (error51) {
+ const message = error51 instanceof Error ? error51.message : String(error51);
+ return {
+ ok: false,
+ error: `InputParseError: Failed to parse tool arguments: ${message}. Ensure the tool call arguments are valid JSON. Prefer Edit over Write for large existing-file changes.`
+ };
+ }
+ }
+ formatToolResult(result) {
+ const payload = {
+ ok: result.ok,
+ name: result.name
+ };
+ if (typeof result.output !== "undefined") {
+ payload.output = result.output;
+ }
+ if (result.error) {
+ payload.error = result.error;
+ }
+ if (result.metadata && Object.keys(result.metadata).length > 0) {
+ payload.metadata = result.metadata;
+ }
+ if (result.awaitUserResponse === true) {
+ payload.awaitUserResponse = true;
+ }
+ return JSON.stringify(payload, null, 2);
+ }
+};
+
+// packages/core/src/mcp/mcp-manager.ts
+init_esbuild_shims();
+import { createHash } from "crypto";
+
+// packages/core/src/mcp/mcp-client.ts
+init_esbuild_shims();
+import { spawn as spawn4 } from "child_process";
+import { createInterface } from "readline";
+import * as path9 from "path";
+var McpClient = class {
+ constructor(serverName, command2, args = [], env6, onNotification, onDisconnect) {
+ this.serverName = serverName;
+ this.command = command2;
+ this.args = args;
+ this.env = env6;
+ this.notificationHandler = onNotification ?? null;
+ this.disconnectHandler = onDisconnect ?? null;
+ }
+ serverName;
+ command;
+ args;
+ env;
+ static {
+ __name(this, "McpClient");
+ }
+ process = null;
+ reader = null;
+ nextId = 1;
+ pendingRequests = /* @__PURE__ */ new Map();
+ stderrBuffer = "";
+ notificationHandler = null;
+ disconnectHandler = null;
+ intentionallyDisconnected = false;
+ async connect(timeoutMs) {
+ return new Promise((resolve16, reject) => {
+ this.intentionallyDisconnected = false;
+ const childEnv = {
+ ...process.env,
+ ...this.env
+ };
+ const args = this.withNpxYesArg(this.command, this.args);
+ const spawnSpec = createMcpSpawnSpec(this.command, args);
+ this.process = spawn4(spawnSpec.command, spawnSpec.args, {
+ stdio: ["pipe", "pipe", "pipe"],
+ env: childEnv,
+ shell: spawnSpec.shell,
+ windowsHide: spawnSpec.windowsHide
+ });
+ let resolved = false;
+ const safeReject = /* @__PURE__ */ __name((err) => {
+ if (!resolved) {
+ resolved = true;
+ reject(err);
+ }
+ }, "safeReject");
+ this.process.on("error", (err) => {
+ safeReject(
+ this.withStderr(`Failed to start MCP server "${this.serverName}" (${this.command}): ${err.message}`)
+ );
+ });
+ this.process.on("close", (code) => {
+ const reason = `MCP server "${this.serverName}" exited with code ${code}`;
+ const error51 = this.withStderr(reason);
+ for (const [, pending] of this.pendingRequests) {
+ clearTimeout(pending.timer);
+ pending.reject(error51);
+ }
+ this.pendingRequests.clear();
+ this.reader?.close();
+ this.reader = null;
+ this.process = null;
+ if (!this.intentionallyDisconnected && this.disconnectHandler) {
+ this.disconnectHandler(reason);
+ }
+ safeReject(error51);
+ });
+ if (this.process.stderr) {
+ this.process.stderr.on("data", (data) => {
+ this.appendStderr(data.toString("utf8"));
+ });
+ }
+ this.reader = createInterface({ input: this.process.stdout });
+ this.reader.on("line", (line) => {
+ this.handleLine(line);
+ });
+ this.sendRequest(
+ "initialize",
+ {
+ protocolVersion: "2025-03-26",
+ capabilities: {},
+ clientInfo: { name: "deepcode-cli", version: "0.1.0" }
+ },
+ timeoutMs
+ ).then((result) => {
+ const initResult = result;
+ const serverVersion = initResult?.protocolVersion;
+ if (serverVersion && serverVersion !== "2025-03-26" && serverVersion !== "2024-11-05") {
+ reject(
+ new Error(
+ `Unsupported MCP protocol version "${serverVersion}" from server "${this.serverName}". Client supports 2025-03-26 and 2024-11-05.`
+ )
+ );
+ return;
+ }
+ this.sendNotification("notifications/initialized");
+ resolve16();
+ }).catch(reject);
+ });
+ }
+ async listTools(timeoutMs) {
+ const tools = [];
+ let cursor;
+ for (let page = 0; page < 100; page++) {
+ const params = cursor ? { cursor } : {};
+ const result = await this.sendRequest("tools/list", params, timeoutMs);
+ tools.push(...result.tools ?? []);
+ cursor = typeof result.nextCursor === "string" && result.nextCursor ? result.nextCursor : void 0;
+ if (!cursor) {
+ return tools;
+ }
+ }
+ throw this.withStderr(`MCP server "${this.serverName}" returned too many tools/list pages`);
+ }
+ async callTool(name, args, timeoutMs = 6e4) {
+ return await this.sendRequest("tools/call", { name, arguments: args }, timeoutMs);
+ }
+ async listPrompts(timeoutMs) {
+ const prompts = [];
+ let cursor;
+ for (let page = 0; page < 100; page++) {
+ const params = cursor ? { cursor } : {};
+ const result = await this.sendRequest("prompts/list", params, timeoutMs);
+ prompts.push(...result.prompts ?? []);
+ cursor = typeof result.nextCursor === "string" && result.nextCursor ? result.nextCursor : void 0;
+ if (!cursor) {
+ return prompts;
+ }
+ }
+ throw this.withStderr(`MCP server "${this.serverName}" returned too many prompts/list pages`);
+ }
+ async getPrompt(name, args, timeoutMs = 3e4) {
+ return await this.sendRequest("prompts/get", { name, arguments: args }, timeoutMs);
+ }
+ async listResources(timeoutMs) {
+ const resources = [];
+ let cursor;
+ for (let page = 0; page < 100; page++) {
+ const params = cursor ? { cursor } : {};
+ const result = await this.sendRequest("resources/list", params, timeoutMs);
+ resources.push(...result.resources ?? []);
+ cursor = typeof result.nextCursor === "string" && result.nextCursor ? result.nextCursor : void 0;
+ if (!cursor) {
+ return resources;
+ }
+ }
+ throw this.withStderr(`MCP server "${this.serverName}" returned too many resources/list pages`);
+ }
+ async readResource(uri, timeoutMs = 3e4) {
+ return await this.sendRequest("resources/read", { uri }, timeoutMs);
+ }
+ disconnect() {
+ this.intentionallyDisconnected = true;
+ if (this.reader) {
+ this.reader.close();
+ this.reader = null;
+ }
+ if (this.process) {
+ if (typeof this.process.pid === "number") {
+ killProcessTree(this.process.pid, "SIGTERM", { killGroupOnNonWindows: false });
+ } else {
+ this.process.kill();
+ }
+ this.process = null;
+ }
+ }
+ isConnected() {
+ return this.process !== null && this.process.exitCode === null;
+ }
+ sendRequest(method, params, timeoutMs = 3e4) {
+ return new Promise((resolve16, reject) => {
+ const id = this.nextId++;
+ const request = {
+ jsonrpc: "2.0",
+ id,
+ method,
+ params
+ };
+ const timer = setTimeout(() => {
+ this.pendingRequests.delete(id);
+ reject(
+ this.withStderr(
+ `Timed out after ${timeoutMs}ms waiting for MCP server "${this.serverName}" to respond to ${method}`
+ )
+ );
+ }, timeoutMs);
+ this.pendingRequests.set(id, { resolve: resolve16, reject, timer });
+ this.writeLine(JSON.stringify(request));
+ });
+ }
+ sendNotification(method, params) {
+ const notification = {
+ jsonrpc: "2.0",
+ method,
+ params
+ };
+ this.writeLine(JSON.stringify(notification));
+ }
+ writeLine(data) {
+ if (this.process?.stdin) {
+ this.process.stdin.write(data + "\n");
+ }
+ }
+ handleLine(line) {
+ try {
+ const parsed = JSON.parse(line);
+ if (Array.isArray(parsed)) {
+ for (const item of parsed) {
+ if (item && typeof item === "object") {
+ this.handleSingleMessage(item);
+ }
+ }
+ return;
+ }
+ if (parsed && typeof parsed === "object") {
+ this.handleSingleMessage(parsed);
+ }
+ } catch {
+ }
+ }
+ handleSingleMessage(msg) {
+ if (!("id" in msg)) {
+ const notification = msg;
+ if (this.notificationHandler && typeof notification.method === "string") {
+ try {
+ this.notificationHandler(notification.method, notification.params);
+ } catch {
+ }
+ }
+ return;
+ }
+ const message = msg;
+ if (message.id !== void 0 && this.pendingRequests.has(message.id)) {
+ const pending = this.pendingRequests.get(message.id);
+ this.pendingRequests.delete(message.id);
+ clearTimeout(pending.timer);
+ if (message.error) {
+ pending.reject(this.withStderr(`MCP error: ${message.error.message}`));
+ } else {
+ pending.resolve(message.result);
+ }
+ }
+ }
+ withNpxYesArg(command2, args) {
+ const executable = path9.basename(command2).toLowerCase().replace(/\.cmd$/, "");
+ if (executable !== "npx") {
+ return args;
+ }
+ if (args.includes("-y") || args.includes("--yes")) {
+ return args;
+ }
+ return ["-y", ...args];
+ }
+ appendStderr(text) {
+ this.stderrBuffer = `${this.stderrBuffer}${text}`;
+ if (this.stderrBuffer.length > 4e3) {
+ this.stderrBuffer = this.stderrBuffer.slice(-4e3);
+ }
+ }
+ withStderr(message) {
+ const stderr = this.stderrBuffer.trim();
+ return new Error(stderr ? `${message}. stderr: ${stderr}` : message);
+ }
+};
+function createMcpSpawnSpec(command2, args, platform2 = process.platform) {
+ if (platform2 === "win32") {
+ return {
+ // On Windows, shell: true lets cmd.exe resolve the command via PATHEXT
+ // (npx -> npx.cmd, etc.). Join command and args into a single string
+ // with empty spawn args to avoid Node 24 DEP0190.
+ // Only quote arguments that need protection from cmd.exe to prevent
+ // double-wrapping by Node.js's own shell quoting.
+ command: [command2, ...args].map(quoteWindowsArgIfNeeded).join(" "),
+ args: [],
+ shell: true,
+ windowsHide: true
+ };
+ }
+ return {
+ command: command2,
+ args,
+ shell: false
+ };
+}
+__name(createMcpSpawnSpec, "createMcpSpawnSpec");
+function quoteWindowsArgIfNeeded(arg) {
+ if (/[\s"&|<>^()]/.test(arg)) {
+ return `"${arg.replace(/(\\*)"/g, '$1$1\\"').replace(/\\+$/g, "$&$&")}"`;
+ }
+ return arg;
+}
+__name(quoteWindowsArgIfNeeded, "quoteWindowsArgIfNeeded");
+
+// packages/core/src/mcp/mcp-manager.ts
+var MCP_STARTUP_TIMEOUT_MS = process.env.DEEPCODE_MCP_TIMEOUT ? parseInt(process.env.DEEPCODE_MCP_TIMEOUT, 10) : 3e4;
+var MCP_CALL_TOOL_TIMEOUT_MS = 6e4;
+var API_TOOL_NAME_PATTERN = /^[a-zA-Z0-9_-]+$/;
+var API_TOOL_NAME_MAX_LENGTH = 64;
+function buildMcpNamespacedName(serverName, toolName, usedNames = /* @__PURE__ */ new Set()) {
+ const rawName = buildRawMcpNamespacedName(serverName, toolName);
+ const sanitizedName = `mcp__${sanitizeApiToolNamePart(serverName)}__${sanitizeApiToolNamePart(toolName)}`;
+ let candidate = fitApiToolName(sanitizedName, rawName);
+ if (!usedNames.has(candidate)) {
+ return candidate;
+ }
+ const hash2 = hashToolName(rawName);
+ candidate = fitApiToolNameWithSuffix(sanitizedName, `_${hash2}`);
+ if (!usedNames.has(candidate)) {
+ return candidate;
+ }
+ for (let index = 2; ; index += 1) {
+ candidate = fitApiToolNameWithSuffix(sanitizedName, `_${hash2}_${index}`);
+ if (!usedNames.has(candidate)) {
+ return candidate;
+ }
+ }
+}
+__name(buildMcpNamespacedName, "buildMcpNamespacedName");
+var McpManager = class {
+ static {
+ __name(this, "McpManager");
+ }
+ clients = [];
+ tools = [];
+ prompts = [];
+ resources = [];
+ initialized = false;
+ disposed = false;
+ configuredServerNames = [];
+ serverStatuses = [];
+ onToolsListChanged = null;
+ onStatusChanged = null;
+ serverConfigs = {};
+ prepare(servers) {
+ if (!servers || Object.keys(servers).length === 0) return;
+ this.disposed = false;
+ for (const name of Object.keys(servers)) {
+ if (!this.configuredServerNames.includes(name)) {
+ this.configuredServerNames.push(name);
+ }
+ if (this.serverStatuses.some((status) => status.name === name)) {
+ continue;
+ }
+ this.setStatus({
+ name,
+ status: "starting",
+ connected: false,
+ toolCount: 0,
+ tools: [],
+ promptCount: 0,
+ prompts: [],
+ resourceCount: 0,
+ resources: []
+ });
+ }
+ }
+ async initialize(servers) {
+ if (this.initialized || this.disposed) return;
+ this.initialized = true;
+ if (!servers || Object.keys(servers).length === 0) return;
+ this.serverConfigs = servers;
+ this.prepare(servers);
+ for (const [name, config2] of Object.entries(servers)) {
+ if (this.disposed) break;
+ await this.connectServer(name, config2);
+ }
+ }
+ async reconnect(name, config2) {
+ if (this.disposed) return;
+ const effectiveConfig = config2 ?? this.serverConfigs[name];
+ if (!effectiveConfig) return;
+ if (config2) {
+ this.serverConfigs[name] = config2;
+ }
+ this.setStatus({
+ name,
+ status: "reconnecting",
+ connected: false,
+ error: "Reconnecting...",
+ toolCount: 0,
+ tools: [],
+ promptCount: 0,
+ prompts: [],
+ resourceCount: 0,
+ resources: []
+ });
+ await this.connectServer(name, effectiveConfig);
+ }
+ async connectServer(name, config2) {
+ if (this.disposed) return;
+ this.clients = this.clients.filter((c) => c.isConnected());
+ this.tools = this.tools.filter((t) => t.serverName !== name);
+ this.prompts = this.prompts.filter((p) => p.serverName !== name);
+ this.resources = this.resources.filter((r) => r.serverName !== name);
+ let client = null;
+ try {
+ client = new McpClient(
+ name,
+ config2.command,
+ config2.args ?? [],
+ config2.env,
+ (method) => {
+ if (method === "notifications/tools/list_changed") {
+ this.refreshServerTools(name, client).catch(() => {
+ });
+ }
+ },
+ (reason) => {
+ if (!this.disposed && this.serverConfigs[name]) {
+ this.onServerCrash(name, reason);
+ }
+ }
+ );
+ await client.connect(MCP_STARTUP_TIMEOUT_MS);
+ if (this.disposed) {
+ client.disconnect();
+ return;
+ }
+ this.clients.push(client);
+ const serverTools = await client.listTools(MCP_STARTUP_TIMEOUT_MS);
+ if (this.disposed) return;
+ const toolNamespacedNames = [];
+ const usedToolNames = new Set(this.tools.map((tool) => tool.namespacedName));
+ for (const tool of serverTools) {
+ const namespacedName = buildMcpNamespacedName(name, tool.name, usedToolNames);
+ usedToolNames.add(namespacedName);
+ this.tools.push({
+ serverName: name,
+ originalName: tool.name,
+ namespacedName,
+ definition: tool,
+ client
+ });
+ toolNamespacedNames.push(namespacedName);
+ }
+ let serverPrompts = [];
+ try {
+ serverPrompts = await client.listPrompts(MCP_STARTUP_TIMEOUT_MS);
+ } catch {
+ }
+ if (this.disposed) return;
+ const promptNamespacedNames = [];
+ for (const prompt of serverPrompts) {
+ const namespacedName = `mcp__${name}__${prompt.name}`;
+ this.prompts.push({
+ serverName: name,
+ namespacedName,
+ definition: prompt,
+ client
+ });
+ promptNamespacedNames.push(namespacedName);
+ }
+ let serverResources = [];
+ try {
+ serverResources = await client.listResources(MCP_STARTUP_TIMEOUT_MS);
+ } catch {
+ }
+ if (this.disposed) return;
+ const resourceNamespacedNames = [];
+ for (const resource of serverResources) {
+ const namespacedName = `mcp__${name}__${resource.name}`;
+ this.resources.push({
+ serverName: name,
+ namespacedName,
+ definition: resource,
+ client
+ });
+ resourceNamespacedNames.push(namespacedName);
+ }
+ this.setStatus({
+ name,
+ status: "ready",
+ connected: true,
+ toolCount: serverTools.length,
+ tools: toolNamespacedNames,
+ promptCount: serverPrompts.length,
+ prompts: promptNamespacedNames,
+ resourceCount: serverResources.length,
+ resources: resourceNamespacedNames
+ });
+ } catch (err) {
+ client?.disconnect();
+ const message = err instanceof Error ? err.message : String(err);
+ this.setStatus({
+ name,
+ status: "failed",
+ connected: false,
+ error: message,
+ toolCount: 0,
+ tools: [],
+ promptCount: 0,
+ prompts: [],
+ resourceCount: 0,
+ resources: []
+ });
+ }
+ }
+ onServerCrash(name, reason) {
+ if (this.disposed) return;
+ this.clients = this.clients.filter((c) => c.isConnected());
+ this.tools = this.tools.filter((t) => t.serverName !== name);
+ this.prompts = this.prompts.filter((p) => p.serverName !== name);
+ this.resources = this.resources.filter((r) => r.serverName !== name);
+ this.onToolsListChanged?.();
+ this.setStatus({
+ name,
+ status: "failed",
+ connected: false,
+ error: reason,
+ toolCount: 0,
+ tools: [],
+ promptCount: 0,
+ prompts: [],
+ resourceCount: 0,
+ resources: []
+ });
+ }
+ getStatus() {
+ const result = [...this.serverStatuses];
+ const knownNames = new Set(result.map((s) => s.name));
+ for (const name of this.configuredServerNames) {
+ if (!knownNames.has(name)) {
+ result.push({
+ name,
+ status: "starting",
+ connected: false,
+ toolCount: 0,
+ tools: [],
+ promptCount: 0,
+ prompts: [],
+ resourceCount: 0,
+ resources: []
+ });
+ }
+ }
+ return result;
+ }
+ getMcpToolDefinitions() {
+ return this.tools.map((t) => ({
+ type: "function",
+ function: {
+ name: t.namespacedName,
+ description: this.buildMcpToolDescription(t),
+ parameters: {
+ type: "object",
+ properties: t.definition.inputSchema.properties,
+ required: t.definition.inputSchema.required,
+ ...t.definition.inputSchema.additionalProperties !== void 0 ? { additionalProperties: t.definition.inputSchema.additionalProperties } : {}
+ }
+ }
+ }));
+ }
+ isMcpTool(name) {
+ return name.startsWith("mcp__");
+ }
+ async executeMcpTool(name, args, timeoutMs = MCP_CALL_TOOL_TIMEOUT_MS) {
+ const tool = this.tools.find((t) => t.namespacedName === name);
+ if (!tool) {
+ return { ok: false, name, error: `Unknown MCP tool: ${name}` };
+ }
+ try {
+ const result = await tool.client.callTool(tool.originalName, args, timeoutMs);
+ const text = result.content.filter((c) => c.type === "text" && c.text).map((c) => c.text).join("\n");
+ return {
+ ok: !result.isError,
+ name,
+ output: text || JSON.stringify(result.content)
+ };
+ } catch (err) {
+ return {
+ ok: false,
+ name,
+ error: err instanceof Error ? err.message : String(err)
+ };
+ }
+ }
+ async getMcpPrompt(name, args) {
+ const prompt = this.prompts.find((p) => p.namespacedName === name);
+ if (!prompt) {
+ return { ok: false, name, error: `Unknown MCP prompt: ${name}` };
+ }
+ try {
+ const result = await prompt.client.getPrompt(prompt.definition.name, args);
+ const text = result.messages.filter((m) => m.content.type === "text" && m.content.text).map((m) => `[${m.role}] ${m.content.text}`).join("\n");
+ return {
+ ok: true,
+ name,
+ output: text || JSON.stringify(result)
+ };
+ } catch (err) {
+ return {
+ ok: false,
+ name,
+ error: err instanceof Error ? err.message : String(err)
+ };
+ }
+ }
+ async readMcpResource(name, uri) {
+ const resource = this.resources.find((r) => r.namespacedName === name);
+ if (!resource) {
+ return { ok: false, name, error: `Unknown MCP resource: ${name}` };
+ }
+ try {
+ const result = await resource.client.readResource(uri);
+ const text = result.contents.filter((c) => c.text).map((c) => c.text).join("\n");
+ return {
+ ok: true,
+ name,
+ output: text || JSON.stringify(result.contents)
+ };
+ } catch (err) {
+ return {
+ ok: false,
+ name,
+ error: err instanceof Error ? err.message : String(err)
+ };
+ }
+ }
+ disconnect() {
+ this.disposed = true;
+ for (const client of this.clients) {
+ client.disconnect();
+ }
+ this.clients = [];
+ this.tools = [];
+ this.prompts = [];
+ this.resources = [];
+ this.serverStatuses = [];
+ this.configuredServerNames = [];
+ this.serverConfigs = {};
+ this.initialized = false;
+ }
+ async refreshServerTools(serverName, client) {
+ const serverTools = await client.listTools(MCP_STARTUP_TIMEOUT_MS);
+ this.tools = this.tools.filter((t) => t.serverName !== serverName);
+ const toolNamespacedNames = [];
+ const usedToolNames = new Set(this.tools.map((tool) => tool.namespacedName));
+ for (const tool of serverTools) {
+ const namespacedName = buildMcpNamespacedName(serverName, tool.name, usedToolNames);
+ usedToolNames.add(namespacedName);
+ this.tools.push({
+ serverName,
+ originalName: tool.name,
+ namespacedName,
+ definition: tool,
+ client
+ });
+ toolNamespacedNames.push(namespacedName);
+ }
+ const existing = this.serverStatuses.find((s) => s.name === serverName);
+ if (existing) {
+ existing.toolCount = serverTools.length;
+ existing.tools = toolNamespacedNames;
+ }
+ this.onToolsListChanged?.();
+ }
+ setOnToolsListChanged(handler) {
+ this.onToolsListChanged = handler;
+ }
+ setOnStatusChanged(handler) {
+ this.onStatusChanged = handler;
+ }
+ setStatus(status) {
+ if (this.disposed) return;
+ const index = this.serverStatuses.findIndex((s) => s.name === status.name);
+ if (index === -1) {
+ this.serverStatuses.push(status);
+ } else {
+ this.serverStatuses[index] = status;
+ }
+ this.onStatusChanged?.();
+ }
+ buildMcpToolDescription(tool) {
+ const description = tool.definition.description?.trim();
+ const source = `${tool.serverName}: ${tool.originalName}`;
+ if (!description) {
+ return source;
+ }
+ if (tool.namespacedName === buildRawMcpNamespacedName(tool.serverName, tool.originalName)) {
+ return description;
+ }
+ return `${description}
+MCP source: ${source}`;
+ }
+};
+function buildRawMcpNamespacedName(serverName, toolName) {
+ return `mcp__${serverName}__${toolName}`;
+}
+__name(buildRawMcpNamespacedName, "buildRawMcpNamespacedName");
+function sanitizeApiToolNamePart(value) {
+ const sanitized = value.replace(/[^a-zA-Z0-9_-]/g, "_");
+ return sanitized || "unnamed";
+}
+__name(sanitizeApiToolNamePart, "sanitizeApiToolNamePart");
+function fitApiToolName(name, rawName) {
+ if (API_TOOL_NAME_PATTERN.test(name) && name.length <= API_TOOL_NAME_MAX_LENGTH) {
+ return name;
+ }
+ return fitApiToolNameWithSuffix(name, `_${hashToolName(rawName)}`);
+}
+__name(fitApiToolName, "fitApiToolName");
+function fitApiToolNameWithSuffix(name, suffix) {
+ const maxPrefixLength = API_TOOL_NAME_MAX_LENGTH - suffix.length;
+ const prefix = name.slice(0, Math.max(1, maxPrefixLength));
+ return `${prefix}${suffix}`;
+}
+__name(fitApiToolNameWithSuffix, "fitApiToolNameWithSuffix");
+function hashToolName(value) {
+ return createHash("sha256").update(value).digest("hex").slice(0, 8);
+}
+__name(hashToolName, "hashToolName");
+
+// packages/core/src/common/error-logger.ts
+init_esbuild_shims();
+import * as fs13 from "fs";
+import * as path10 from "path";
+import * as os7 from "os";
+var LOG_DIR = path10.join(os7.homedir(), ".deepcode", "logs");
+var ERROR_LOG_PATH = path10.join(LOG_DIR, "error.log");
+function ensureLogDir() {
+ if (!fs13.existsSync(LOG_DIR)) {
+ fs13.mkdirSync(LOG_DIR, { recursive: true });
+ }
+}
+__name(ensureLogDir, "ensureLogDir");
+function maskSensitive(text) {
+ return text.replace(/(Authorization:\s*Bearer\s+)[^\s\r\n]+/gi, "$1***MASKED***").replace(/((?:api[Kk]ey|api_key|secret)\s*[:=]\s*"?)[^",}\s]+/gi, "$1***MASKED***");
+}
+__name(maskSensitive, "maskSensitive");
+var CONTENT_TRUNCATE_PREVIEW = 100;
+function truncateContent(value) {
+ if (value.length <= CONTENT_TRUNCATE_PREVIEW) {
+ return value;
+ }
+ return `${value.slice(0, CONTENT_TRUNCATE_PREVIEW)}...(total ${value.length} chars)`;
+}
+__name(truncateContent, "truncateContent");
+function sanitizeRequestPayload(request) {
+ function walk(value) {
+ if (!value || typeof value !== "object") {
+ return value;
+ }
+ if (Array.isArray(value)) {
+ return value.map(walk);
+ }
+ const record2 = value;
+ const result = {};
+ for (const [key, val] of Object.entries(record2)) {
+ if (key === "content" && typeof val === "string") {
+ result[key] = truncateContent(val);
+ } else {
+ result[key] = walk(val);
+ }
+ }
+ return result;
+ }
+ __name(walk, "walk");
+ return walk(request);
+}
+__name(sanitizeRequestPayload, "sanitizeRequestPayload");
+function logApiError(entry) {
+ try {
+ ensureLogDir();
+ const logLine = {
+ timestamp: entry.timestamp,
+ location: entry.location,
+ requestId: entry.requestId,
+ sessionId: entry.sessionId,
+ model: entry.model,
+ baseURL: entry.baseURL,
+ error: {
+ name: entry.error.name,
+ message: maskSensitive(entry.error.message),
+ stack: entry.error.stack ? maskSensitive(entry.error.stack) : void 0
+ },
+ request: sanitizeRequestPayload(entry.request)
+ };
+ if (entry.response !== void 0) {
+ logLine.response = typeof entry.response === "string" ? maskSensitive(entry.response) : entry.response;
+ }
+ const newLine = JSON.stringify(logLine) + "\n";
+ fs13.appendFileSync(ERROR_LOG_PATH, newLine, "utf8");
+ const MAX_ENTRIES = 20;
+ const raw = fs13.readFileSync(ERROR_LOG_PATH, "utf8");
+ const lines = raw.split("\n").filter((line) => line.trim().length > 0);
+ if (lines.length > MAX_ENTRIES) {
+ fs13.writeFileSync(ERROR_LOG_PATH, lines.slice(-MAX_ENTRIES).join("\n") + "\n", "utf8");
+ }
+ } catch {
+ }
+}
+__name(logApiError, "logApiError");
+
+// packages/core/src/common/debug-logger.ts
+init_esbuild_shims();
+import * as fs14 from "fs";
+import * as os8 from "os";
+import * as path11 from "path";
+var DEBUG_LOG_FILE = "debug.log";
+function logOpenAIChatCompletionDebug(entry) {
+ try {
+ const logPath = getDebugLogPath();
+ fs14.mkdirSync(path11.dirname(logPath), { recursive: true });
+ fs14.appendFileSync(logPath, `${JSON.stringify(toSerializable(entry))}
+`, "utf8");
+ } catch {
+ }
+}
+__name(logOpenAIChatCompletionDebug, "logOpenAIChatCompletionDebug");
+function getDebugLogPath() {
+ return path11.join(os8.homedir(), ".deepcode", "logs", DEBUG_LOG_FILE);
+}
+__name(getDebugLogPath, "getDebugLogPath");
+function normalizeDebugError(error51) {
+ if (error51 instanceof Error) {
+ return {
+ name: error51.name,
+ message: error51.message,
+ stack: error51.stack
+ };
+ }
+ return {
+ name: "UnknownError",
+ message: String(error51)
+ };
+}
+__name(normalizeDebugError, "normalizeDebugError");
+function toSerializable(value) {
+ const seen = /* @__PURE__ */ new WeakSet();
+ function walk(current) {
+ if (typeof current === "bigint") {
+ return current.toString();
+ }
+ if (current instanceof Error) {
+ return normalizeDebugError(current);
+ }
+ if (!current || typeof current !== "object") {
+ return current;
+ }
+ if (seen.has(current)) {
+ return "[Circular]";
+ }
+ seen.add(current);
+ if (Array.isArray(current)) {
+ return current.map(walk);
+ }
+ const result = {};
+ for (const [key, val] of Object.entries(current)) {
+ result[key] = walk(val);
+ }
+ return result;
+ }
+ __name(walk, "walk");
+ return walk(value);
+}
+__name(toSerializable, "toSerializable");
+
+// packages/core/src/common/hooks.ts
+init_esbuild_shims();
+import { execSync as execSync2 } from "child_process";
+function runHook(command2) {
+ try {
+ const stdout = execSync2(command2, {
+ encoding: "utf8",
+ timeout: 15e3,
+ windowsHide: true
+ });
+ return { stdout: stdout.trim(), exitCode: 0 };
+ } catch (error51) {
+ const err = error51;
+ return {
+ stdout: (err.stdout ?? err.stderr ?? String(error51)).toString().trim(),
+ exitCode: err.status ?? 1
+ };
+ }
+}
+__name(runHook, "runHook");
+function fireHook(hooks, event, context = {}) {
+ const command2 = hooks?.[event];
+ if (!command2) {
+ return;
+ }
+ const resolved = command2.replace(/\{(\w+)\}/g, (_, key) => context[key] ?? "");
+ const { stdout, exitCode } = runHook(resolved);
+ if (exitCode !== 0) {
+ console.error(`[hook:${event}] exited ${exitCode}: ${stdout}`);
+ }
+}
+__name(fireHook, "fireHook");
+
+// packages/core/src/common/file-history.ts
+init_esbuild_shims();
+import * as childProcess from "child_process";
+import * as crypto2 from "crypto";
+import * as fs15 from "fs";
+import * as path12 from "path";
+var FILE_HISTORY_AUTHOR_NAME = "DeepCode Checkpoint";
+var FILE_HISTORY_AUTHOR_EMAIL = "deepcode-checkpoint@localhost";
+var MANIFEST_PATH = ".deepcode-file-history.json";
+var GitFileHistory = class {
+ constructor(_projectRoot, gitDir) {
+ this.gitDir = gitDir;
+ }
+ gitDir;
+ static {
+ __name(this, "GitFileHistory");
+ }
+ ensureSession(sessionId) {
+ const branchRef = this.getSessionBranchRef(sessionId);
+ if (!branchRef) {
+ return void 0;
+ }
+ try {
+ if (!fs15.existsSync(this.gitDir)) {
+ fs15.mkdirSync(path12.dirname(this.gitDir), { recursive: true });
+ this.runGit(["init"]);
+ }
+ const current = this.getCurrentCheckpointHash(sessionId);
+ if (current) {
+ return current;
+ }
+ const treeHash = this.createTree(emptyManifest());
+ const commitHash = this.createCommit(treeHash, null, "Initial checkpoint");
+ this.runGit(["update-ref", branchRef, commitHash]);
+ return commitHash;
+ } catch {
+ return void 0;
+ }
+ }
+ getCurrentCheckpointHash(sessionId) {
+ const branchRef = this.getSessionBranchRef(sessionId);
+ if (!branchRef || !fs15.existsSync(this.gitDir)) {
+ return void 0;
+ }
+ try {
+ const hash2 = this.runGit(["rev-parse", "--verify", `${branchRef}^{commit}`]).trim();
+ return isCommitHash(hash2) ? hash2 : void 0;
+ } catch {
+ return void 0;
+ }
+ }
+ recordCheckpoint(sessionId, filePaths, message) {
+ const branchRef = this.getSessionBranchRef(sessionId);
+ if (!branchRef) {
+ return void 0;
+ }
+ const absolutePaths = uniqueAbsolutePaths(filePaths);
+ if (absolutePaths.length === 0) {
+ return this.getCurrentCheckpointHash(sessionId);
+ }
+ try {
+ const parentHash = this.ensureSession(sessionId);
+ if (!parentHash) {
+ return void 0;
+ }
+ const manifest = this.readManifest(parentHash);
+ for (const filePath of absolutePaths) {
+ const key = this.getFileKey(filePath);
+ if (!fs15.existsSync(filePath) || !fs15.statSync(filePath).isFile()) {
+ manifest.files[key] = {
+ path: filePath,
+ blob: null,
+ mode: "100644"
+ };
+ continue;
+ }
+ manifest.files[key] = {
+ path: filePath,
+ blob: this.hashFile(filePath),
+ mode: "100644"
+ };
+ }
+ const treeHash = this.createTree(manifest);
+ const parentTreeHash = this.runGit(["rev-parse", `${parentHash}^{tree}`]).trim();
+ if (treeHash === parentTreeHash) {
+ return parentHash;
+ }
+ const commitHash = this.createCommit(treeHash, parentHash, message);
+ this.runGit(["update-ref", branchRef, commitHash, parentHash]);
+ return commitHash;
+ } catch {
+ return void 0;
+ }
+ }
+ recordTrackedFilesCheckpoint(sessionId, message) {
+ const currentHash = this.ensureSession(sessionId);
+ if (!currentHash) {
+ return { checkpointHash: void 0, changedFilePaths: [] };
+ }
+ try {
+ const manifest = this.readManifest(currentHash);
+ const trackedPaths = Object.values(manifest.files).map((entry) => entry.path).sort((left2, right2) => left2.localeCompare(right2));
+ if (trackedPaths.length === 0) {
+ return { checkpointHash: currentHash, changedFilePaths: [] };
+ }
+ const nextHash = this.recordCheckpoint(sessionId, trackedPaths, message);
+ if (!nextHash) {
+ return { checkpointHash: void 0, changedFilePaths: [] };
+ }
+ const nextManifest = this.readManifest(nextHash);
+ const changedFilePaths = Object.entries(manifest.files).filter(([key, entry]) => !isSameFileHistoryEntry(entry, nextManifest.files[key])).map(([key, entry]) => nextManifest.files[key]?.path ?? entry.path).sort((left2, right2) => left2.localeCompare(right2));
+ return { checkpointHash: nextHash, changedFilePaths };
+ } catch {
+ return { checkpointHash: void 0, changedFilePaths: [] };
+ }
+ }
+ canRestore(sessionId, checkpointHash) {
+ if (!isCommitHash(checkpointHash)) {
+ return false;
+ }
+ if (!this.getSessionBranchRef(sessionId)) {
+ return false;
+ }
+ if (!fs15.existsSync(this.gitDir)) {
+ return false;
+ }
+ try {
+ this.runGit(["cat-file", "-e", `${checkpointHash}^{commit}`]);
+ this.readManifest(checkpointHash);
+ return true;
+ } catch {
+ return false;
+ }
+ }
+ restore(sessionId, checkpointHash) {
+ if (!isCommitHash(checkpointHash)) {
+ throw new Error("Invalid checkpoint hash.");
+ }
+ const branchRef = this.getSessionBranchRef(sessionId);
+ if (!branchRef || !fs15.existsSync(this.gitDir)) {
+ throw new Error("File history Git repository was not found for this project.");
+ }
+ this.runGit(["cat-file", "-e", `${checkpointHash}^{commit}`]);
+ const currentHash = this.getCurrentCheckpointHash(sessionId);
+ const currentManifest = currentHash ? this.readManifest(currentHash) : emptyManifest();
+ const targetManifest = this.readManifest(checkpointHash);
+ for (const [key, entry] of Object.entries(currentManifest.files)) {
+ if (!targetManifest.files[key]) {
+ this.restoreFirstKnownEntry(currentHash, key, entry.path);
+ }
+ }
+ for (const entry of Object.values(targetManifest.files)) {
+ if (!entry.blob) {
+ removeTrackedFile(entry.path);
+ continue;
+ }
+ fs15.mkdirSync(path12.dirname(entry.path), { recursive: true });
+ fs15.writeFileSync(entry.path, this.readBlob(entry.blob));
+ }
+ this.runGit(["update-ref", branchRef, checkpointHash]);
+ }
+ restoreFirstKnownEntry(currentHash, key, fallbackPath) {
+ const firstEntry = currentHash ? this.findFirstKnownEntry(currentHash, key) : void 0;
+ const entry = firstEntry ?? { path: fallbackPath, blob: null, mode: "100644" };
+ if (!entry.blob) {
+ removeTrackedFile(entry.path);
+ return;
+ }
+ fs15.mkdirSync(path12.dirname(entry.path), { recursive: true });
+ fs15.writeFileSync(entry.path, this.readBlob(entry.blob));
+ }
+ findFirstKnownEntry(currentHash, key) {
+ const commitHashes = this.runGit(["rev-list", "--reverse", currentHash]).split(/\r?\n/).map((line) => line.trim()).filter(isCommitHash);
+ for (const commitHash of commitHashes) {
+ const entry = this.readManifest(commitHash).files[key];
+ if (entry) {
+ return entry;
+ }
+ }
+ return void 0;
+ }
+ getSessionBranchRef(sessionId) {
+ if (!/^[A-Za-z0-9._-]+$/.test(sessionId)) {
+ return null;
+ }
+ return `refs/heads/${sessionId}`;
+ }
+ createCommit(treeHash, parentHash, message) {
+ const args = ["commit-tree", treeHash];
+ if (parentHash) {
+ args.push("-p", parentHash);
+ }
+ args.push("-m", message);
+ return this.runGit(args, {
+ env: getFileHistoryGitEnv()
+ }).trim();
+ }
+ createTree(manifest) {
+ const normalizedManifest = normalizeManifest(manifest);
+ const manifestBlob = this.hashContent(`${JSON.stringify(normalizedManifest, null, 2)}
+`);
+ const entries = [`100644 blob ${manifestBlob} ${MANIFEST_PATH}\0`];
+ for (const [key, entry] of Object.entries(normalizedManifest.files)) {
+ if (!entry.blob) {
+ continue;
+ }
+ entries.push(`${entry.mode} blob ${entry.blob} ${key}\0`);
+ }
+ return this.runGit(["mktree", "-z"], { input: entries.join("") }).trim();
+ }
+ readManifest(commitHash) {
+ const buffer = this.runGitBuffer(["cat-file", "blob", `${commitHash}:${MANIFEST_PATH}`]);
+ const parsed = JSON.parse(buffer.toString("utf8"));
+ if (!parsed || parsed.version !== 1 && parsed.version !== 2 || !parsed.files || typeof parsed.files !== "object") {
+ throw new Error("Invalid file history manifest.");
+ }
+ return normalizeManifest(parsed);
+ }
+ readBlob(blobHash) {
+ if (!isCommitHash(blobHash)) {
+ throw new Error("Invalid file history blob hash.");
+ }
+ return this.runGitBuffer(["cat-file", "blob", blobHash]);
+ }
+ hashFile(filePath) {
+ const blobHash = this.runGit(["hash-object", "-w", "--", filePath]).trim();
+ if (!isCommitHash(blobHash)) {
+ throw new Error("Invalid file history blob hash.");
+ }
+ return blobHash;
+ }
+ hashContent(content) {
+ const blobHash = this.runGit(["hash-object", "-w", "--stdin"], { input: content }).trim();
+ if (!isCommitHash(blobHash)) {
+ throw new Error("Invalid file history blob hash.");
+ }
+ return blobHash;
+ }
+ getFileKey(filePath) {
+ const hash2 = crypto2.createHash("sha256").update(filePath).digest("hex");
+ return `files-${hash2}`;
+ }
+ runGit(args, options2 = {}) {
+ return this.spawnGit(args, options2, "utf8");
+ }
+ runGitBuffer(args, options2 = {}) {
+ return this.spawnGit(args, options2, "buffer");
+ }
+ spawnGit(args, options2, encoding) {
+ const gitArgs = ["-c", "core.autocrlf=false", "-c", "core.eol=lf", `--git-dir=${this.gitDir}`, ...args];
+ const result = childProcess.spawnSync("git", gitArgs, {
+ encoding,
+ input: options2.input,
+ env: options2.env,
+ stdio: ["pipe", "pipe", "pipe"]
+ });
+ if (result.status !== 0) {
+ const stderr = Buffer.isBuffer(result.stderr) ? result.stderr.toString("utf8") : result.stderr;
+ const stdout = Buffer.isBuffer(result.stdout) ? result.stdout.toString("utf8") : result.stdout;
+ const detail = (stderr || stdout || "").trim();
+ throw new Error(detail || `git ${args.join(" ")} failed`);
+ }
+ return result.stdout ?? (encoding === "buffer" ? Buffer.alloc(0) : "");
+ }
+};
+function emptyManifest() {
+ return { version: 2, files: {} };
+}
+__name(emptyManifest, "emptyManifest");
+function normalizeManifest(manifest) {
+ const files = {};
+ for (const [key, entry] of Object.entries(manifest.files).sort(([left2], [right2]) => left2.localeCompare(right2))) {
+ if (!isValidStoredPath(key) || !entry || entry.mode !== "100644" || entry.blob !== null && !isCommitHash(entry.blob)) {
+ throw new Error("Invalid file history manifest.");
+ }
+ files[key] = {
+ path: path12.resolve(entry.path),
+ blob: entry.blob,
+ mode: "100644"
+ };
+ }
+ return { version: 2, files };
+}
+__name(normalizeManifest, "normalizeManifest");
+function isSameFileHistoryEntry(left2, right2) {
+ if (!right2) {
+ return false;
+ }
+ return left2.path === right2.path && left2.blob === right2.blob && left2.mode === right2.mode;
+}
+__name(isSameFileHistoryEntry, "isSameFileHistoryEntry");
+function uniqueAbsolutePaths(filePaths) {
+ return Array.from(new Set(filePaths.map((filePath) => path12.resolve(filePath))));
+}
+__name(uniqueAbsolutePaths, "uniqueAbsolutePaths");
+function isValidStoredPath(value) {
+ return /^files-[0-9a-f]{64}$/.test(value);
+}
+__name(isValidStoredPath, "isValidStoredPath");
+function removeTrackedFile(filePath) {
+ if (!fs15.existsSync(filePath)) {
+ return;
+ }
+ const stat = fs15.lstatSync(filePath);
+ if (stat.isDirectory()) {
+ return;
+ }
+ fs15.unlinkSync(filePath);
+}
+__name(removeTrackedFile, "removeTrackedFile");
+function getFileHistoryGitEnv() {
+ return {
+ ...process.env,
+ GIT_AUTHOR_NAME: process.env.GIT_AUTHOR_NAME || FILE_HISTORY_AUTHOR_NAME,
+ GIT_AUTHOR_EMAIL: process.env.GIT_AUTHOR_EMAIL || FILE_HISTORY_AUTHOR_EMAIL,
+ GIT_COMMITTER_NAME: process.env.GIT_COMMITTER_NAME || FILE_HISTORY_AUTHOR_NAME,
+ GIT_COMMITTER_EMAIL: process.env.GIT_COMMITTER_EMAIL || FILE_HISTORY_AUTHOR_EMAIL
+ };
+}
+__name(getFileHistoryGitEnv, "getFileHistoryGitEnv");
+function isCommitHash(value) {
+ return /^[0-9a-f]{40}$/i.test(value);
+}
+__name(isCommitHash, "isCommitHash");
+
+// packages/core/src/common/permissions.ts
+init_esbuild_shims();
+import * as fs16 from "fs";
+import * as path13 from "path";
+function parseToolCallForPermissions(toolCall) {
+ if (!toolCall || typeof toolCall !== "object") {
+ return null;
+ }
+ const record2 = toolCall;
+ if (typeof record2.id !== "string" || !record2.function || typeof record2.function !== "object") {
+ return null;
+ }
+ if (typeof record2.function.name !== "string") {
+ return null;
+ }
+ return {
+ id: record2.id,
+ type: "function",
+ function: {
+ name: record2.function.name,
+ arguments: typeof record2.function.arguments === "string" ? record2.function.arguments : ""
+ }
+ };
+}
+__name(parseToolCallForPermissions, "parseToolCallForPermissions");
+function buildPermissionToolExecution(toolCall, options2) {
+ const permission = resolveToolCallPermission(toolCall.id, options2);
+ if (permission === "allow") {
+ return null;
+ }
+ if (permission === "deny") {
+ return buildSyntheticToolExecution(
+ toolCall,
+ "User denied the required permission for this tool call. Do not try to bypass this decision."
+ );
+ }
+ return buildSyntheticToolExecution(
+ toolCall,
+ "The user has not authorized this tool call yet. Retry only if the permission is still necessary."
+ );
+}
+__name(buildPermissionToolExecution, "buildPermissionToolExecution");
+function resolveToolCallPermission(toolCallId, options2) {
+ const override = options2.permissionOverrides?.find((item) => item.toolCallId === toolCallId);
+ if (override?.permission === "allow" || override?.permission === "deny") {
+ return override.permission;
+ }
+ const messagePermission = options2.messagePermissions?.find((item) => item.toolCallId === toolCallId);
+ if (messagePermission?.permission === "allow" || messagePermission?.permission === "deny" || messagePermission?.permission === "ask") {
+ return messagePermission.permission;
+ }
+ return "allow";
+}
+__name(resolveToolCallPermission, "resolveToolCallPermission");
+function buildSyntheticToolExecution(toolCall, error51) {
+ const result = {
+ ok: false,
+ name: toolCall.function.name,
+ error: error51
+ };
+ return {
+ toolCallId: toolCall.id,
+ content: JSON.stringify(result, null, 2),
+ result
+ };
+}
+__name(buildSyntheticToolExecution, "buildSyntheticToolExecution");
+function computeToolCallPermissions(options2) {
+ const permissions = [];
+ const askPermissions = [];
+ for (const rawToolCall of options2.toolCalls) {
+ const toolCall = parseToolCallForPermissions(rawToolCall);
+ if (!toolCall) {
+ continue;
+ }
+ const request = describeToolPermissionRequest({
+ sessionId: options2.sessionId,
+ projectRoot: options2.projectRoot,
+ toolCall,
+ readPermissionExemptPaths: options2.readPermissionExemptPaths,
+ resolveSnippetPath: options2.resolveSnippetPath
+ });
+ const permission = evaluatePermissionScopes(request.scopes, options2.settings);
+ permissions.push({ toolCallId: toolCall.id, permission });
+ if (permission === "ask") {
+ const askScopes = getPermissionScopesRequiringAsk(request.scopes, options2.settings);
+ askPermissions.push({
+ toolCallId: toolCall.id,
+ scopes: askScopes.length > 0 ? askScopes : request.scopes,
+ name: request.name,
+ command: request.command,
+ description: request.description
+ });
+ }
+ }
+ return { permissions, askPermissions };
+}
+__name(computeToolCallPermissions, "computeToolCallPermissions");
+function describeToolPermissionRequest(options2) {
+ const name = options2.toolCall.function.name;
+ const args = parseToolArgumentsForPermissions(options2.toolCall.function.arguments);
+ if (name === "read" || name === "Read") {
+ const filePath = typeof args.file_path === "string" ? args.file_path : "";
+ return {
+ toolCallId: options2.toolCall.id,
+ name,
+ command: formatToolPathCommand("read", filePath),
+ scopes: filePath && !isPathInAnyDirectory(options2.projectRoot, filePath, options2.readPermissionExemptPaths) ? [isPathInProject(options2.projectRoot, filePath) ? "read-in-cwd" : "read-out-cwd"] : []
+ };
+ }
+ if (name === "write" || name === "Write") {
+ const filePath = typeof args.file_path === "string" ? args.file_path : "";
+ return {
+ toolCallId: options2.toolCall.id,
+ name,
+ command: formatToolPathCommand("write", filePath),
+ scopes: filePath ? [isPathInProject(options2.projectRoot, filePath) ? "write-in-cwd" : "write-out-cwd"] : []
+ };
+ }
+ if (name === "edit" || name === "Edit") {
+ const filePath = resolveEditPermissionPath(options2.sessionId, args, options2.resolveSnippetPath);
+ return {
+ toolCallId: options2.toolCall.id,
+ name,
+ command: formatToolPathCommand("edit", filePath),
+ scopes: filePath ? [isPathInProject(options2.projectRoot, filePath) ? "write-in-cwd" : "write-out-cwd"] : ["write-out-cwd"]
+ };
+ }
+ if (name === "bash" || name === "Bash") {
+ const command2 = typeof args.command === "string" ? args.command : "bash";
+ const description = typeof args.description === "string" ? args.description : void 0;
+ return {
+ toolCallId: options2.toolCall.id,
+ name: "bash",
+ command: command2,
+ description,
+ scopes: parseBashSideEffects(args.sideEffects)
+ };
+ }
+ if (name === "WebSearch") {
+ const query = typeof args.query === "string" ? args.query : "WebSearch";
+ return {
+ toolCallId: options2.toolCall.id,
+ name,
+ command: query,
+ scopes: ["network"]
+ };
+ }
+ if (name.startsWith("mcp__")) {
+ return {
+ toolCallId: options2.toolCall.id,
+ name,
+ command: name,
+ scopes: ["mcp"]
+ };
+ }
+ return {
+ toolCallId: options2.toolCall.id,
+ name,
+ command: name,
+ scopes: []
+ };
+}
+__name(describeToolPermissionRequest, "describeToolPermissionRequest");
+function evaluatePermissionScopes(scopes, settings = {
+ allow: [],
+ deny: [],
+ ask: [],
+ defaultMode: "allowAll"
+}) {
+ if (scopes.includes("unknown") && settings.defaultMode !== "allowAll") {
+ return "ask";
+ }
+ if (scopes.length === 0) {
+ return "allow";
+ }
+ const permissionScopes = scopes.filter((scope) => scope !== "unknown");
+ if (permissionScopes.some((scope) => settings.deny.includes(scope))) {
+ return "deny";
+ }
+ if (permissionScopes.some((scope) => settings.ask.includes(scope))) {
+ return "ask";
+ }
+ if (permissionScopes.every((scope) => settings.allow.includes(scope))) {
+ return "allow";
+ }
+ return settings.defaultMode === "askAll" ? "ask" : "allow";
+}
+__name(evaluatePermissionScopes, "evaluatePermissionScopes");
+function getPermissionScopesRequiringAsk(scopes, settings = {
+ allow: [],
+ deny: [],
+ ask: [],
+ defaultMode: "allowAll"
+}) {
+ const result = [];
+ for (const scope of scopes) {
+ if (scope === "unknown") {
+ if (settings.defaultMode !== "allowAll") {
+ result.push(scope);
+ }
+ continue;
+ }
+ if (settings.deny.includes(scope)) {
+ continue;
+ }
+ if (settings.ask.includes(scope)) {
+ result.push(scope);
+ continue;
+ }
+ if (settings.allow.includes(scope)) {
+ continue;
+ }
+ if (settings.defaultMode === "askAll") {
+ result.push(scope);
+ }
+ }
+ return result;
+}
+__name(getPermissionScopesRequiringAsk, "getPermissionScopesRequiringAsk");
+function parseBashSideEffects(value) {
+ const validScopes = /* @__PURE__ */ new Set([
+ "read-in-cwd",
+ "read-out-cwd",
+ "write-in-cwd",
+ "write-out-cwd",
+ "delete-in-cwd",
+ "delete-out-cwd",
+ "query-git-log",
+ "mutate-git-log",
+ "network",
+ "unknown"
+ ]);
+ if (!Array.isArray(value)) {
+ return ["unknown"];
+ }
+ const scopes = [];
+ for (const item of value) {
+ if (typeof item !== "string" || !validScopes.has(item)) {
+ return ["unknown"];
+ }
+ const scope = item;
+ if (!scopes.includes(scope)) {
+ scopes.push(scope);
+ }
+ }
+ if (scopes.includes("unknown")) {
+ return ["unknown"];
+ }
+ return scopes;
+}
+__name(parseBashSideEffects, "parseBashSideEffects");
+function parseToolArgumentsForPermissions(rawArguments) {
+ if (!rawArguments) {
+ return {};
+ }
+ try {
+ const parsed = JSON.parse(rawArguments);
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
+ } catch {
+ return {};
+ }
+}
+__name(parseToolArgumentsForPermissions, "parseToolArgumentsForPermissions");
+function resolveEditPermissionPath(sessionId, args, resolveSnippetPath) {
+ const filePath = typeof args.file_path === "string" ? args.file_path : "";
+ if (filePath) {
+ return filePath;
+ }
+ const snippetId = typeof args.snippet_id === "string" ? args.snippet_id : "";
+ return snippetId ? resolveSnippetPath?.(sessionId, snippetId) ?? "" : "";
+}
+__name(resolveEditPermissionPath, "resolveEditPermissionPath");
+function formatToolPathCommand(toolName, filePath) {
+ return filePath ? `${toolName} ${filePath}` : toolName;
+}
+__name(formatToolPathCommand, "formatToolPathCommand");
+function isPathInProject(projectRoot, filePath) {
+ const normalized = normalizeFilePath(filePath);
+ const absolutePath = isAbsoluteFilePath(normalized) ? normalized : path13.resolve(projectRoot, normalized);
+ const relative5 = path13.relative(path13.resolve(projectRoot), path13.resolve(absolutePath));
+ return relative5 === "" || !relative5.startsWith("..") && !path13.isAbsolute(relative5);
+}
+__name(isPathInProject, "isPathInProject");
+function isPathInAnyDirectory(projectRoot, filePath, directories) {
+ if (!directories?.length) {
+ return false;
+ }
+ const normalized = normalizeFilePath(filePath);
+ const absolutePath = isAbsoluteFilePath(normalized) ? normalized : path13.resolve(projectRoot, normalized);
+ for (const directory of directories) {
+ const normalizedDirectory = normalizeFilePath(directory);
+ const absoluteDirectory = isAbsoluteFilePath(normalizedDirectory) ? normalizedDirectory : path13.resolve(projectRoot, normalizedDirectory);
+ const relative5 = path13.relative(path13.resolve(absoluteDirectory), path13.resolve(absolutePath));
+ if (relative5 === "" || !relative5.startsWith("..") && !path13.isAbsolute(relative5)) {
+ return true;
+ }
+ }
+ return false;
+}
+__name(isPathInAnyDirectory, "isPathInAnyDirectory");
+function hasUserPermissionReplies(value) {
+ return Boolean(
+ Array.isArray(value.permissions) && value.permissions.length > 0 || Array.isArray(value.alwaysAllows) && value.alwaysAllows.length > 0
+ );
+}
+__name(hasUserPermissionReplies, "hasUserPermissionReplies");
+function appendProjectPermissionAllows(projectRoot, scopes, options2 = {}) {
+ if (!Array.isArray(scopes) || scopes.length === 0) {
+ return;
+ }
+ const validScopes = /* @__PURE__ */ new Set([
+ "read-in-cwd",
+ "read-out-cwd",
+ "write-in-cwd",
+ "write-out-cwd",
+ "delete-in-cwd",
+ "delete-out-cwd",
+ "query-git-log",
+ "mutate-git-log",
+ "network",
+ "mcp"
+ ]);
+ const nextScopes = scopes.filter((scope) => validScopes.has(scope));
+ if (nextScopes.length === 0) {
+ return;
+ }
+ const settingsPath = path13.join(projectRoot, ".deepcode", "settings.json");
+ let settings = {};
+ try {
+ if (fs16.existsSync(settingsPath)) {
+ const parsed = JSON.parse(fs16.readFileSync(settingsPath, "utf8"));
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
+ settings = parsed;
+ }
+ }
+ } catch {
+ settings = {};
+ }
+ const existingPermissions = settings.permissions;
+ const permissions = existingPermissions ? { ...existingPermissions } : options2.inheritedPermissions ? {
+ allow: [...options2.inheritedPermissions.allow],
+ deny: [...options2.inheritedPermissions.deny],
+ ask: [...options2.inheritedPermissions.ask],
+ defaultMode: options2.inheritedPermissions.defaultMode
+ } : {};
+ const currentAllow = Array.isArray(permissions.allow) ? permissions.allow : [];
+ const allow = [...currentAllow];
+ for (const scope of nextScopes) {
+ if (!allow.includes(scope)) {
+ allow.push(scope);
+ }
+ }
+ const currentDeny = Array.isArray(permissions.deny) ? permissions.deny : void 0;
+ const currentAsk = Array.isArray(permissions.ask) ? permissions.ask : void 0;
+ const deny = currentDeny ? currentDeny.filter((scope) => !nextScopes.includes(scope)) : permissions.deny;
+ const ask = currentAsk ? currentAsk.filter((scope) => !nextScopes.includes(scope)) : permissions.ask;
+ const changed = allow.length !== currentAllow.length || (currentDeny ? deny.length !== currentDeny.length : false) || (currentAsk ? ask.length !== currentAsk.length : false);
+ if (existingPermissions && !changed) {
+ return;
+ }
+ fs16.mkdirSync(path13.dirname(settingsPath), { recursive: true });
+ fs16.writeFileSync(
+ settingsPath,
+ `${JSON.stringify(
+ {
+ ...settings,
+ permissions: {
+ ...permissions,
+ deny,
+ ask,
+ allow
+ }
+ },
+ null,
+ 2
+ )}
+`,
+ "utf8"
+ );
+}
+__name(appendProjectPermissionAllows, "appendProjectPermissionAllows");
+function normalizeAskPermissions(value) {
+ if (!Array.isArray(value)) {
+ return void 0;
+ }
+ const result = [];
+ for (const item of value) {
+ if (!item || typeof item !== "object") {
+ continue;
+ }
+ const record2 = item;
+ if (typeof record2.toolCallId !== "string" || typeof record2.name !== "string") {
+ continue;
+ }
+ const scopes = Array.isArray(record2.scopes) ? record2.scopes.filter((scope) => isAskPermissionScope(scope)) : [];
+ result.push({
+ toolCallId: record2.toolCallId,
+ scopes,
+ name: record2.name,
+ command: typeof record2.command === "string" ? record2.command : record2.name,
+ description: typeof record2.description === "string" ? record2.description : void 0
+ });
+ }
+ return result.length > 0 ? result : void 0;
+}
+__name(normalizeAskPermissions, "normalizeAskPermissions");
+function isAskPermissionScope(value) {
+ return value === "read-in-cwd" || value === "read-out-cwd" || value === "write-in-cwd" || value === "write-out-cwd" || value === "delete-in-cwd" || value === "delete-out-cwd" || value === "query-git-log" || value === "mutate-git-log" || value === "network" || value === "mcp" || value === "unknown";
+}
+__name(isAskPermissionScope, "isAskPermissionScope");
+
+// packages/core/src/common/telemetry.ts
+init_esbuild_shims();
+var DEFAULT_NEW_PROMPT_API_URL = "https://deepcode.vegamo.cn/api/plugin/new";
+var DEFAULT_REPORT_TIMEOUT_MS = 3e3;
+function reportNewPrompt(options2) {
+ if (!options2.enabled || !options2.machineId) {
+ return;
+ }
+ const timeoutMs = options2.timeoutMs ?? DEFAULT_REPORT_TIMEOUT_MS;
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
+ void fetch(DEFAULT_NEW_PROMPT_API_URL, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Token: options2.machineId
+ },
+ body: JSON.stringify({}),
+ signal: controller.signal
+ }).catch(() => {
+ }).finally(() => clearTimeout(timeout));
+}
+__name(reportNewPrompt, "reportNewPrompt");
+
+// packages/core/src/common/openai-message-converter.ts
+init_esbuild_shims();
+var OpenAIMessageConverter = class {
+ constructor(options2 = {}) {
+ this.options = options2;
+ }
+ options;
+ static {
+ __name(this, "OpenAIMessageConverter");
+ }
+ /**
+ * Build the OpenAI messages array from session messages, applying compaction
+ * filtering, tool pairing, and format conversion.
+ */
+ buildMessages(messages, thinkingEnabled, model) {
+ const activeMessages = messages.filter((message) => !message.compacted);
+ const toolPairings = this.pairToolMessages(activeMessages);
+ const openAIMessages = [];
+ for (let index = 0; index < activeMessages.length; index += 1) {
+ const message = activeMessages[index];
+ if (message.role === "tool") {
+ continue;
+ }
+ openAIMessages.push(this.convertMessage(message, thinkingEnabled, model));
+ const toolCalls = this.getAssistantToolCalls(message);
+ if (toolCalls.length === 0) {
+ continue;
+ }
+ for (let toolCallIndex = 0; toolCallIndex < toolCalls.length; toolCallIndex += 1) {
+ const toolCallId = this.getToolCallId(toolCalls[toolCallIndex]);
+ if (!toolCallId) {
+ continue;
+ }
+ const pairedToolIndex = toolPairings.get(this.buildToolPairingKey(index, toolCallIndex));
+ if (pairedToolIndex != null) {
+ openAIMessages.push(this.convertMessage(activeMessages[pairedToolIndex], thinkingEnabled, model));
+ continue;
+ }
+ openAIMessages.push(this.buildInterruptedOpenAIToolMessage(toolCalls, toolCallId));
+ }
+ }
+ return openAIMessages;
+ }
+ /**
+ * Returns the trailing assistant message with pending (unexecuted) tool calls,
+ * if one exists at the end of the conversation.
+ */
+ getTrailingPendingToolCallMessage(messages) {
+ const activeMessages = messages.filter((message) => !message.compacted);
+ const latestMessage = activeMessages[activeMessages.length - 1];
+ if (!latestMessage || latestMessage.role !== "assistant") {
+ return { message: null, toolCalls: [] };
+ }
+ const toolCalls = this.getAssistantToolCalls(latestMessage);
+ if (toolCalls.length === 0) {
+ return { message: null, toolCalls: [] };
+ }
+ return {
+ message: latestMessage,
+ toolCalls: toolCalls.filter((toolCall) => Boolean(this.getToolCallId(toolCall)))
+ };
+ }
+ // ---------------------------------------------------------------------------
+ // Private helpers
+ // ---------------------------------------------------------------------------
+ convertMessage(message, thinkingEnabled, model) {
+ const content = this.renderContent(message);
+ const base = {
+ role: message.role,
+ content
+ };
+ const messageParams = message.messageParams;
+ if (messageParams?.tool_calls) {
+ base.tool_calls = messageParams.tool_calls;
+ }
+ if (messageParams?.tool_call_id) {
+ base.tool_call_id = messageParams.tool_call_id;
+ }
+ if (typeof messageParams?.reasoning_content === "string") {
+ base.reasoning_content = messageParams.reasoning_content;
+ } else if (thinkingEnabled && message.role === "assistant") {
+ base.reasoning_content = "";
+ }
+ if ((message.role === "user" || message.role === "system") && message.contentParams) {
+ const contentParts = [];
+ if (content) {
+ contentParts.push({ type: "text", text: content });
+ }
+ const params = Array.isArray(message.contentParams) ? message.contentParams : [message.contentParams];
+ for (const param of params) {
+ const part = param;
+ if (part && (part.type !== "image_url" || supportsMultimodal(model))) {
+ contentParts.push(part);
+ }
+ }
+ const contentValue = contentParts.length > 0 ? contentParts : content;
+ base.content = contentValue;
+ }
+ return base;
+ }
+ renderContent(message) {
+ if (message.role === "user" && message.content === "/init") {
+ return this.options.renderInitPrompt?.() ?? "";
+ }
+ return message.content ?? "";
+ }
+ pairToolMessages(messages) {
+ const pairings = /* @__PURE__ */ new Map();
+ const usedToolMessageIndexes = /* @__PURE__ */ new Set();
+ for (let assistantIndex = 0; assistantIndex < messages.length; assistantIndex += 1) {
+ const toolCalls = this.getAssistantToolCalls(messages[assistantIndex]);
+ for (let toolCallIndex = 0; toolCallIndex < toolCalls.length; toolCallIndex += 1) {
+ const toolCallId = this.getToolCallId(toolCalls[toolCallIndex]);
+ if (!toolCallId) {
+ continue;
+ }
+ const toolIndex = this.findPairableToolMessageIndex(
+ messages,
+ assistantIndex,
+ toolCallId,
+ usedToolMessageIndexes
+ );
+ if (toolIndex == null) {
+ continue;
+ }
+ usedToolMessageIndexes.add(toolIndex);
+ pairings.set(this.buildToolPairingKey(assistantIndex, toolCallIndex), toolIndex);
+ }
+ }
+ return pairings;
+ }
+ findPairableToolMessageIndex(messages, assistantIndex, toolCallId, usedToolMessageIndexes) {
+ let firstMatchingIndex = null;
+ for (let index = assistantIndex + 1; index < messages.length; index += 1) {
+ const message = messages[index];
+ if (message.role !== "tool" || usedToolMessageIndexes.has(index)) {
+ continue;
+ }
+ const candidateToolCallId = this.getToolMessageCallId(message);
+ if (candidateToolCallId !== toolCallId) {
+ continue;
+ }
+ if (firstMatchingIndex == null) {
+ firstMatchingIndex = index;
+ }
+ if (!this.isInterruptedToolMessage(message)) {
+ return index;
+ }
+ }
+ return firstMatchingIndex;
+ }
+ getAssistantToolCalls(message) {
+ if (message.role !== "assistant") {
+ return [];
+ }
+ const messageParams = message.messageParams;
+ return Array.isArray(messageParams?.tool_calls) ? messageParams.tool_calls : [];
+ }
+ getToolCallId(toolCall) {
+ if (!toolCall || typeof toolCall !== "object") {
+ return null;
+ }
+ const id = toolCall.id;
+ return typeof id === "string" && id ? id : null;
+ }
+ getToolMessageCallId(message) {
+ const messageParams = message.messageParams;
+ const toolCallId = messageParams?.tool_call_id;
+ return typeof toolCallId === "string" && toolCallId ? toolCallId : null;
+ }
+ buildToolPairingKey(assistantIndex, toolCallIndex) {
+ return `${assistantIndex}:${toolCallIndex}`;
+ }
+ isInterruptedToolMessage(message) {
+ if (typeof message.content !== "string" || !message.content.trim()) {
+ return false;
+ }
+ try {
+ const parsed = JSON.parse(message.content);
+ return parsed.metadata?.interrupted === true;
+ } catch {
+ return false;
+ }
+ }
+ buildInterruptedOpenAIToolMessage(toolCalls, toolCallId) {
+ const toolFunction = this.findToolFunction(toolCalls, toolCallId);
+ return {
+ role: "tool",
+ content: this.buildInterruptedToolResult(toolFunction, "Previous tool call did not complete."),
+ tool_call_id: toolCallId
+ };
+ }
+ /** Exposed for use by appendToolMessages in SessionManager. */
+ findToolFunction(toolCalls, toolCallId) {
+ for (const toolCall of toolCalls) {
+ if (!toolCall || typeof toolCall !== "object") {
+ continue;
+ }
+ const record2 = toolCall;
+ if (record2.id === toolCallId) {
+ return record2.function ?? null;
+ }
+ }
+ return null;
+ }
+ buildInterruptedToolResult(toolFunction, reason) {
+ const toolName = toolFunction && typeof toolFunction === "object" && typeof toolFunction.name === "string" ? toolFunction.name : "tool";
+ return JSON.stringify(
+ {
+ ok: false,
+ name: toolName,
+ error: reason,
+ metadata: {
+ interrupted: true
+ }
+ },
+ null,
+ 2
+ );
+ }
+};
+
+// packages/core/src/session.ts
+var MAX_SESSION_ENTRIES = 50;
+var MAX_PROJECT_CODE_LENGTH = 64;
+var PROJECT_CODE_HASH_LENGTH = 16;
+var BACKGROUND_FAILURE_LOG_TAIL_CHARS = 4e3;
+var DEFAULT_COMPACT_PROMPT_TOKEN_THRESHOLD = 128 * 1024;
+var DEEPSEEK_V4_COMPACT_PROMPT_TOKEN_THRESHOLD = 512 * 1024;
+var PLAN_MODE_STATUS_MESSAGE = "/plan\n \u2514 Set Plan Mode on. Awaiting .";
+function getCompactPromptTokenThreshold(model) {
+ return DEEPSEEK_V4_MODELS.has(model) ? DEEPSEEK_V4_COMPACT_PROMPT_TOKEN_THRESHOLD : DEFAULT_COMPACT_PROMPT_TOKEN_THRESHOLD;
+}
+__name(getCompactPromptTokenThreshold, "getCompactPromptTokenThreshold");
+function getProjectCode(projectRoot) {
+ const legacyCode = getLegacyProjectCode(projectRoot);
+ if (legacyCode.length <= MAX_PROJECT_CODE_LENGTH) {
+ return legacyCode;
+ }
+ const normalizedRoot = path14.resolve(projectRoot);
+ const hashInput = process.platform === "win32" ? normalizedRoot.toLowerCase() : normalizedRoot;
+ const hash2 = crypto3.createHash("sha256").update(hashInput).digest("hex").slice(0, PROJECT_CODE_HASH_LENGTH);
+ const prefixLimit = MAX_PROJECT_CODE_LENGTH - PROJECT_CODE_HASH_LENGTH - 1;
+ const basename6 = path14.basename(normalizedRoot);
+ const prefix = sanitizeProjectCodePart(basename6).slice(0, prefixLimit).replace(/[-.]+$/g, "") || "project";
+ return `${prefix}-${hash2}`;
+}
+__name(getProjectCode, "getProjectCode");
+function getLegacyProjectCode(projectRoot) {
+ return projectRoot.replace(/[\\/]/g, "-").replace(/:/g, "");
+}
+__name(getLegacyProjectCode, "getLegacyProjectCode");
+function sanitizeProjectCodePart(value) {
+ return value.replace(/[^A-Za-z0-9._-]/g, "-").replace(/-+/g, "-").replace(/^[-.]+|[-.]+$/g, "");
+}
+__name(sanitizeProjectCodePart, "sanitizeProjectCodePart");
+function isUsageRecord(value) {
+ return value !== null && typeof value === "object" && !Array.isArray(value);
+}
+__name(isUsageRecord, "isUsageRecord");
+function summarizeCompletionOptions(options2) {
+ if (!options2) {
+ return void 0;
+ }
+ return {
+ ...options2,
+ signal: options2.signal instanceof AbortSignal ? { aborted: options2.signal.aborted } : options2.signal
+ };
+}
+__name(summarizeCompletionOptions, "summarizeCompletionOptions");
+function addUsageValue(current, next) {
+ if (typeof next === "number") {
+ return (typeof current === "number" ? current : 0) + next;
+ }
+ if (isUsageRecord(next)) {
+ const currentRecord = isUsageRecord(current) ? current : {};
+ const result = { ...currentRecord };
+ for (const [key, value] of Object.entries(next)) {
+ result[key] = addUsageValue(currentRecord[key], value);
+ }
+ return result;
+ }
+ return next;
+}
+__name(addUsageValue, "addUsageValue");
+function accumulateUsage(current, next) {
+ if (next == null) {
+ return current ?? null;
+ }
+ return addUsageValue(current, next);
+}
+__name(accumulateUsage, "accumulateUsage");
+function usageWithRequestCount(usage2) {
+ const totalReqs = typeof usage2.total_reqs === "number" ? usage2.total_reqs + 1 : 1;
+ return {
+ ...usage2,
+ total_reqs: totalReqs
+ };
+}
+__name(usageWithRequestCount, "usageWithRequestCount");
+function accumulateUsagePerModel(current, model, next) {
+ if (next == null) {
+ return current ?? null;
+ }
+ const usagePerModel = { ...current ?? {} };
+ const modelName = model.trim() || "unknown";
+ usagePerModel[modelName] = accumulateUsage(usagePerModel[modelName] ?? null, usageWithRequestCount(next));
+ return usagePerModel;
+}
+__name(accumulateUsagePerModel, "accumulateUsagePerModel");
+function getTotalTokens(usage2) {
+ if (!isUsageRecord(usage2)) {
+ return 0;
+ }
+ const totalTokens = usage2.total_tokens;
+ return typeof totalTokens === "number" ? totalTokens : 0;
+}
+__name(getTotalTokens, "getTotalTokens");
+var SessionManager = class {
+ static {
+ __name(this, "SessionManager");
+ }
+ projectRoot;
+ createOpenAIClient;
+ getResolvedSettings;
+ onAssistantMessage;
+ onSessionEntryUpdated;
+ onLlmStreamProgress;
+ onMcpStatusChanged;
+ onProcessStdout;
+ activeSessionId = null;
+ activePromptController = null;
+ sessionControllers = /* @__PURE__ */ new Map();
+ processTimeoutControls = /* @__PURE__ */ new Map();
+ liveProcessKeys = /* @__PURE__ */ new Set();
+ toolExecutor;
+ mcpManager = new McpManager();
+ mcpToolDefinitions = [];
+ messageConverter;
+ constructor(options2) {
+ this.projectRoot = options2.projectRoot;
+ this.createOpenAIClient = options2.createOpenAIClient;
+ this.getResolvedSettings = options2.getResolvedSettings;
+ this.onAssistantMessage = options2.onAssistantMessage;
+ this.onSessionEntryUpdated = options2.onSessionEntryUpdated;
+ this.onLlmStreamProgress = options2.onLlmStreamProgress;
+ this.onMcpStatusChanged = options2.onMcpStatusChanged;
+ this.onProcessStdout = options2.onProcessStdout;
+ this.toolExecutor = new ToolExecutor(this.projectRoot, this.createOpenAIClient, this.mcpManager);
+ this.mcpManager.prepare(this.getResolvedSettings().mcpServers);
+ this.messageConverter = new OpenAIMessageConverter({
+ renderInitPrompt: /* @__PURE__ */ __name(() => this.renderInitCommandPrompt(), "renderInitPrompt")
+ });
+ }
+ /**
+ * @deprecated Use messageConverter.buildMessages directly.
+ * Kept for test compatibility.
+ */
+ buildOpenAIMessages(messages, thinkingEnabled, model) {
+ return this.messageConverter.buildMessages(messages, thinkingEnabled, model);
+ }
+ async initMcpServers(servers) {
+ this.mcpManager.setOnToolsListChanged(() => {
+ this.mcpToolDefinitions = this.mcpManager.getMcpToolDefinitions();
+ });
+ this.mcpManager.setOnStatusChanged(() => {
+ this.onMcpStatusChanged?.();
+ });
+ await this.mcpManager.initialize(servers);
+ this.mcpToolDefinitions = this.mcpManager.getMcpToolDefinitions();
+ }
+ getMcpStatus() {
+ return this.mcpManager.getStatus();
+ }
+ async reconnectMcpServer(name, config2) {
+ await this.mcpManager.reconnect(name, config2);
+ this.mcpToolDefinitions = this.mcpManager.getMcpToolDefinitions();
+ }
+ dispose() {
+ const controller = this.activePromptController;
+ if (controller && !controller.signal.aborted) {
+ controller.abort();
+ }
+ this.activePromptController = null;
+ for (const sessionController of this.sessionControllers.values()) {
+ if (!sessionController.signal.aborted) {
+ sessionController.abort();
+ }
+ }
+ this.killLiveProcesses();
+ this.sessionControllers.clear();
+ this.processTimeoutControls.clear();
+ this.mcpManager.disconnect();
+ }
+ estimateStreamTokens(text) {
+ let tokens = 0;
+ for (const char of text) {
+ tokens += /[\u3400-\u9fff\uf900-\ufaff]/u.test(char) ? 0.6 : 0.3;
+ }
+ return tokens;
+ }
+ formatEstimatedTokens(tokens) {
+ if (tokens <= 0) {
+ return "0";
+ }
+ const roundedTokens = Math.round(tokens);
+ if (roundedTokens <= 0) {
+ return "0";
+ }
+ if (roundedTokens < 100) {
+ return String(roundedTokens);
+ }
+ if (roundedTokens < 1e4) {
+ return `${Number((roundedTokens / 1e3).toFixed(1))}k`;
+ }
+ return `${Math.round(roundedTokens / 1e3)}k`;
+ }
+ emitLlmStreamProgress(requestId, startedAt, estimatedTokens, phase, sessionId) {
+ this.onLlmStreamProgress?.({
+ requestId,
+ sessionId,
+ startedAt,
+ estimatedTokens: Math.round(estimatedTokens),
+ formattedTokens: this.formatEstimatedTokens(estimatedTokens),
+ phase
+ });
+ }
+ isAbortLikeError(error51) {
+ if (!(error51 instanceof Error)) {
+ return false;
+ }
+ return error51.name === "AbortError" || error51.constructor.name === "APIUserAbortError";
+ }
+ throwIfAborted(signal) {
+ if (!signal?.aborted) {
+ return;
+ }
+ const error51 = new Error("Request was aborted.");
+ error51.name = "AbortError";
+ throw error51;
+ }
+ async createChatCompletionStream(client, request, options2, sessionId, debug) {
+ const requestId = crypto3.randomUUID();
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
+ const startedAtMs = Date.now();
+ let estimatedTokens = 0;
+ this.emitLlmStreamProgress(requestId, startedAt, estimatedTokens, "start", sessionId);
+ const streamRequest = {
+ ...request,
+ stream: true,
+ stream_options: {
+ ...isUsageRecord(request.stream_options) ? request.stream_options : {},
+ include_usage: true
+ }
+ };
+ let response;
+ try {
+ response = await client.chat.completions.create(streamRequest, options2);
+ } catch (error51) {
+ this.logChatCompletionDebug(debug, {
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
+ location: debug?.location ?? "SessionManager.createChatCompletionStream:create",
+ requestId,
+ sessionId,
+ model: typeof request.model === "string" ? request.model : void 0,
+ baseURL: debug?.baseURL,
+ durationMs: Date.now() - startedAtMs,
+ params: { ...debug?.params, options: summarizeCompletionOptions(options2) },
+ request: streamRequest,
+ error: normalizeDebugError(error51)
+ });
+ logApiError({
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
+ location: "SessionManager.createChatCompletionStream:create",
+ requestId,
+ sessionId,
+ model: typeof request.model === "string" ? request.model : void 0,
+ error: {
+ name: error51 instanceof Error ? error51.name : "UnknownError",
+ message: error51 instanceof Error ? error51.message : String(error51),
+ stack: error51 instanceof Error ? error51.stack : void 0
+ },
+ request: streamRequest
+ });
+ this.emitLlmStreamProgress(requestId, startedAt, estimatedTokens, "end", sessionId);
+ throw error51;
+ }
+ if (!response || typeof response[Symbol.asyncIterator] !== "function") {
+ this.emitLlmStreamProgress(requestId, startedAt, estimatedTokens, "end", sessionId);
+ this.logChatCompletionDebug(debug, {
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
+ location: debug?.location ?? "SessionManager.createChatCompletionStream",
+ requestId,
+ sessionId,
+ model: typeof request.model === "string" ? request.model : void 0,
+ baseURL: debug?.baseURL,
+ durationMs: Date.now() - startedAtMs,
+ params: { ...debug?.params, options: summarizeCompletionOptions(options2) },
+ request: streamRequest,
+ response
+ });
+ return response;
+ }
+ let content = "";
+ let reasoningContent = "";
+ let refusal = null;
+ let usage2 = null;
+ const responseChunks = [];
+ const toolCallsByIndex = /* @__PURE__ */ new Map();
+ const trackText = /* @__PURE__ */ __name((value) => {
+ if (typeof value !== "string" || value.length === 0) {
+ return;
+ }
+ estimatedTokens += this.estimateStreamTokens(value);
+ this.emitLlmStreamProgress(requestId, startedAt, estimatedTokens, "update", sessionId);
+ }, "trackText");
+ try {
+ for await (const chunk of response) {
+ if (debug?.enabled) {
+ responseChunks.push(chunk);
+ }
+ if ("usage" in chunk && chunk.usage != null) {
+ usage2 = chunk.usage;
+ }
+ const choices = Array.isArray(chunk.choices) ? chunk.choices : [];
+ for (const choice of choices) {
+ const delta = isUsageRecord(choice) && isUsageRecord(choice.delta) ? choice.delta : null;
+ if (!delta) {
+ continue;
+ }
+ const contentDelta = delta.content;
+ if (typeof contentDelta === "string") {
+ content += contentDelta;
+ trackText(contentDelta);
+ }
+ const reasoningDelta = delta.reasoning_content ?? delta.reasoning;
+ if (typeof reasoningDelta === "string") {
+ reasoningContent += reasoningDelta;
+ trackText(reasoningDelta);
+ }
+ if (typeof delta.refusal === "string") {
+ refusal = `${refusal ?? ""}${delta.refusal}`;
+ trackText(delta.refusal);
+ }
+ const rawToolCalls = delta.tool_calls;
+ if (Array.isArray(rawToolCalls)) {
+ for (const rawToolCall of rawToolCalls) {
+ if (!isUsageRecord(rawToolCall)) {
+ continue;
+ }
+ const index = typeof rawToolCall.index === "number" ? rawToolCall.index : toolCallsByIndex.size;
+ const current = toolCallsByIndex.get(index) ?? {};
+ if (typeof rawToolCall.id === "string") {
+ current.id = rawToolCall.id;
+ }
+ if (typeof rawToolCall.type === "string") {
+ current.type = rawToolCall.type;
+ }
+ const rawFunction = isUsageRecord(rawToolCall.function) ? rawToolCall.function : null;
+ if (rawFunction) {
+ current.function = current.function ?? {};
+ if (typeof rawFunction.name === "string") {
+ current.function.name = `${current.function.name ?? ""}${rawFunction.name}`;
+ trackText(rawFunction.name);
+ }
+ if (typeof rawFunction.arguments === "string") {
+ current.function.arguments = `${current.function.arguments ?? ""}${rawFunction.arguments}`;
+ trackText(rawFunction.arguments);
+ }
+ }
+ toolCallsByIndex.set(index, current);
+ }
+ }
+ }
+ }
+ } catch (error51) {
+ this.logChatCompletionDebug(debug, {
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
+ location: debug?.location ?? "SessionManager.createChatCompletionStream:stream",
+ requestId,
+ sessionId,
+ model: typeof request.model === "string" ? request.model : void 0,
+ baseURL: debug?.baseURL,
+ durationMs: Date.now() - startedAtMs,
+ params: { ...debug?.params, options: summarizeCompletionOptions(options2) },
+ request: streamRequest,
+ responseChunks,
+ error: normalizeDebugError(error51)
+ });
+ logApiError({
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
+ location: "SessionManager.createChatCompletionStream:stream",
+ requestId,
+ sessionId,
+ model: typeof request.model === "string" ? request.model : void 0,
+ error: {
+ name: error51 instanceof Error ? error51.name : "UnknownError",
+ message: error51 instanceof Error ? error51.message : String(error51),
+ stack: error51 instanceof Error ? error51.stack : void 0
+ },
+ request: streamRequest
+ });
+ throw error51;
+ } finally {
+ this.emitLlmStreamProgress(requestId, startedAt, estimatedTokens, "end", sessionId);
+ }
+ const toolCalls = Array.from(toolCallsByIndex.entries()).sort(([left2], [right2]) => left2 - right2).map(([, toolCall]) => toolCall);
+ const normalizedToolCalls = this.normalizeLlmToolCalls(toolCalls);
+ const message = { content };
+ if (normalizedToolCalls) {
+ message.tool_calls = normalizedToolCalls;
+ }
+ if (reasoningContent.length > 0) {
+ message.reasoning_content = reasoningContent;
+ }
+ if (refusal != null) {
+ message.refusal = refusal;
+ }
+ const finalResponse = {
+ choices: [{ message }],
+ usage: usage2
+ };
+ this.logChatCompletionDebug(debug, {
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
+ location: debug?.location ?? "SessionManager.createChatCompletionStream",
+ requestId,
+ sessionId,
+ model: typeof request.model === "string" ? request.model : void 0,
+ baseURL: debug?.baseURL,
+ durationMs: Date.now() - startedAtMs,
+ params: { ...debug?.params, options: summarizeCompletionOptions(options2) },
+ request: streamRequest,
+ responseChunks,
+ response: finalResponse
+ });
+ return finalResponse;
+ }
+ logChatCompletionDebug(debug, entry) {
+ if (!debug?.enabled) {
+ return;
+ }
+ logOpenAIChatCompletionDebug(entry);
+ }
+ async identifyMatchingSkillNames(skills, userPrompt, options2) {
+ this.throwIfAborted(options2?.signal);
+ let systemPrompt = `When users ask you to perform tasks, check if any of the available skills match the goal and situation. Skills provide specialized capabilities and domain knowledge.
+
+Response in JSON format:
+\`\`\`
+{
+ "skillNames": ["", ...]
+}
+\`\`\`
+
+If none of the available skills match, respond with an empty array, i.e. \`{"skillNames": []}\`.
+
+`;
+ const simpleSkills = skills.filter((x) => !x.isLoaded && x.allowImplicitInvocation !== false).map((x) => {
+ return { name: x.name, description: x.description };
+ });
+ if (simpleSkills.length === 0) {
+ return [];
+ }
+ const candidateSkillNames = new Set(simpleSkills.map((skill) => skill.name));
+ const { client, model, baseURL, debugLogEnabled } = this.createOpenAIClient();
+ if (!client) {
+ return [];
+ }
+ const agentInstructions = this.loadAgentInstructions();
+ if (agentInstructions) {
+ systemPrompt += `Use the current agent instructions as additional context when deciding which skills match:
+
+
+${agentInstructions}
+
+
+`;
+ }
+ systemPrompt += "The candidate skills are as follows:\n\n";
+ systemPrompt += "```\n" + JSON.stringify(simpleSkills, null, 2) + "\n```";
+ try {
+ const response = await this.createChatCompletionStream(
+ client,
+ {
+ model,
+ temperature: 0.1,
+ messages: [
+ { role: "system", content: systemPrompt },
+ { role: "user", content: userPrompt }
+ ],
+ response_format: { type: "json_object" }
+ },
+ options2?.signal ? { signal: options2.signal } : void 0,
+ options2?.sessionId,
+ {
+ enabled: debugLogEnabled,
+ location: "SessionManager.identifyMatchingSkillNames",
+ baseURL,
+ params: { purpose: "skill-matching", temperature: 0.1 }
+ }
+ );
+ this.throwIfAborted(options2?.signal);
+ const rawContent = response.choices?.[0]?.message?.content;
+ const content = typeof rawContent === "string" ? rawContent : "";
+ if (!content) {
+ return [];
+ }
+ const parsed = JSON.parse(content);
+ if (parsed && Array.isArray(parsed.skillNames)) {
+ return parsed.skillNames.filter(
+ (skillName) => typeof skillName === "string" && candidateSkillNames.has(skillName)
+ );
+ }
+ return [];
+ } catch (error51) {
+ if (this.isAbortLikeError(error51) || options2?.signal?.aborted) {
+ throw error51;
+ }
+ return [];
+ }
+ }
+ getSkillScanRoots() {
+ const homeDir = os9.homedir();
+ return [
+ { root: path14.join(this.projectRoot, ".deepcode", "skills"), displayRoot: "./.deepcode/skills" },
+ { root: path14.join(this.projectRoot, ".agents", "skills"), displayRoot: "./.agents/skills" },
+ { root: path14.join(homeDir, ".deepcode", "skills"), displayRoot: "~/.deepcode/skills" },
+ { root: path14.join(homeDir, ".agents", "skills"), displayRoot: "~/.agents/skills" },
+ { root: this.getBundledSkillsRoot(), displayRoot: "bundled:" }
+ ];
+ }
+ getBundledSkillsRoot() {
+ const extensionRoot = getExtensionRoot();
+ const sourceRoot = path14.join(extensionRoot, "templates", "skills", "bundled");
+ if (fs17.existsSync(path14.join(extensionRoot, "src", "session.ts")) && fs17.existsSync(sourceRoot)) {
+ return sourceRoot;
+ }
+ const distRoot = path14.join(extensionRoot, "bundled");
+ return fs17.existsSync(distRoot) ? distRoot : sourceRoot;
+ }
+ async listSkills(sessionId) {
+ const skillRoots = this.getSkillScanRoots();
+ const enabledSkills = this.getResolvedSettings().enabledSkills ?? {};
+ const skillsByName = /* @__PURE__ */ new Map();
+ const collectSkills = /* @__PURE__ */ __name((root, displayRoot) => {
+ if (!fs17.existsSync(root)) {
+ return [];
+ }
+ let entries;
+ try {
+ entries = fs17.readdirSync(root, { withFileTypes: true });
+ } catch {
+ return [];
+ }
+ const results = [];
+ for (const entry of entries) {
+ if (!entry.isDirectory() && !entry.isSymbolicLink()) {
+ continue;
+ }
+ const skillName = entry.name;
+ const skillPath = path14.join(root, skillName, "SKILL.md");
+ try {
+ if (!fs17.existsSync(skillPath)) {
+ continue;
+ }
+ const stat = fs17.statSync(skillPath);
+ if (!stat.isFile()) {
+ continue;
+ }
+ } catch {
+ continue;
+ }
+ const displayPath = displayRoot === "bundled:" ? `bundled:${skillName}/SKILL.md` : `${displayRoot}/${skillName}/SKILL.md`;
+ const skill = this.readSkillInfo(skillPath, displayPath, skillName);
+ if (enabledSkills[skill.name] === false) {
+ continue;
+ }
+ results.push(skill);
+ }
+ return results;
+ }, "collectSkills");
+ for (const { root, displayRoot } of skillRoots) {
+ for (const skill of collectSkills(root, displayRoot)) {
+ if (!skillsByName.has(skill.name)) {
+ skillsByName.set(skill.name, skill);
+ }
+ }
+ }
+ if (sessionId) {
+ const loadedSkillKeys = this.getLoadedSkillKeys(sessionId);
+ for (const skill of skillsByName.values()) {
+ if (loadedSkillKeys.has(this.getSkillKey(skill)) || loadedSkillKeys.has(this.getSkillKeyByName(skill.name))) {
+ skill.isLoaded = true;
+ }
+ }
+ }
+ return Array.from(skillsByName.values()).sort((a, b) => a.name.localeCompare(b.name));
+ }
+ resolveSkillPath(skillPath) {
+ if (skillPath.startsWith("bundled:")) {
+ const relativePath = skillPath.slice("bundled:".length);
+ const root = this.getBundledSkillsRoot();
+ const resolvedPath = path14.resolve(root, relativePath);
+ const resolvedRoot = path14.resolve(root);
+ if (resolvedPath === resolvedRoot || !resolvedPath.startsWith(`${resolvedRoot}${path14.sep}`)) {
+ return path14.join(root, "__invalid_bundled_skill__");
+ }
+ return resolvedPath;
+ }
+ if (skillPath.startsWith("~/")) {
+ return path14.join(os9.homedir(), skillPath.slice(2));
+ }
+ if (skillPath.startsWith("~\\")) {
+ return path14.join(os9.homedir(), skillPath.slice(2));
+ }
+ if (skillPath.startsWith("./")) {
+ return path14.join(this.projectRoot, skillPath.slice(2));
+ }
+ if (skillPath.startsWith(".\\")) {
+ return path14.join(this.projectRoot, skillPath.slice(2));
+ }
+ if (path14.isAbsolute(skillPath)) {
+ return skillPath;
+ }
+ return path14.join(os9.homedir(), skillPath);
+ }
+ buildSkillPrompt(skill) {
+ const skillPath = this.resolveSkillPath(skill.path);
+ return buildSkillDocumentsPrompt([
+ {
+ name: skill.name,
+ content: fs17.readFileSync(skillPath, "utf8"),
+ path: skillPath,
+ skillFilePath: skillPath
+ }
+ ]);
+ }
+ readSkillInfo(skillPath, displayPath, fallbackName) {
+ const fallbackSkill = {
+ name: fallbackName.replace(/_/g, "-"),
+ path: displayPath,
+ description: ""
+ };
+ try {
+ const skillMd = fs17.readFileSync(skillPath, "utf8");
+ const parsed = (0, import_gray_matter2.default)(skillMd);
+ const metadata = parsed.data.metadata;
+ const allowImplicitInvocation = metadata && typeof metadata === "object" && !Array.isArray(metadata) && metadata["allow-implicit-invocation"] === false ? false : void 0;
+ return {
+ name: typeof parsed.data.name === "string" && parsed.data.name.trim() ? parsed.data.name.trim() : fallbackSkill.name,
+ path: displayPath,
+ description: typeof parsed.data.description === "string" ? parsed.data.description.trim() : "",
+ allowImplicitInvocation
+ };
+ } catch {
+ return fallbackSkill;
+ }
+ }
+ getSkillKey(skill) {
+ return `path:${skill.path}`;
+ }
+ getSkillKeyByName(name) {
+ return `name:${name}`;
+ }
+ getLoadedSkillKeys(sessionId) {
+ const loadedSkillKeys = /* @__PURE__ */ new Set();
+ for (const message of this.listSessionMessages(sessionId)) {
+ if (message.role !== "system" || !message.meta?.skill) {
+ continue;
+ }
+ loadedSkillKeys.add(this.getSkillKey(message.meta.skill));
+ loadedSkillKeys.add(this.getSkillKeyByName(message.meta.skill.name));
+ }
+ return loadedSkillKeys;
+ }
+ dedupeSkills(skills) {
+ if (!skills || skills.length === 0) {
+ return void 0;
+ }
+ const dedupedSkills = /* @__PURE__ */ new Map();
+ for (const skill of skills) {
+ if (!skill?.name || !skill?.path) {
+ continue;
+ }
+ const key = this.getSkillKey(skill);
+ const existingSkill = dedupedSkills.get(key);
+ dedupedSkills.set(key, {
+ ...existingSkill,
+ ...skill,
+ description: skill.description ?? existingSkill?.description ?? "",
+ isLoaded: Boolean(existingSkill?.isLoaded || skill.isLoaded)
+ });
+ }
+ return Array.from(dedupedSkills.values());
+ }
+ async normalizeSkills(skills, sessionId) {
+ const dedupedSkills = this.dedupeSkills(skills);
+ if (!dedupedSkills || dedupedSkills.length === 0) {
+ return void 0;
+ }
+ const availableSkills = await this.listSkills(sessionId);
+ const availableSkillsByKey = /* @__PURE__ */ new Map();
+ for (const skill of availableSkills) {
+ availableSkillsByKey.set(this.getSkillKey(skill), skill);
+ availableSkillsByKey.set(this.getSkillKeyByName(skill.name), skill);
+ }
+ return dedupedSkills.map((skill) => {
+ const matchedSkill = availableSkillsByKey.get(this.getSkillKey(skill)) ?? availableSkillsByKey.get(this.getSkillKeyByName(skill.name));
+ if (!matchedSkill) {
+ return skill;
+ }
+ return {
+ ...matchedSkill,
+ ...skill,
+ description: matchedSkill.description || skill.description,
+ isLoaded: Boolean(matchedSkill.isLoaded || skill.isLoaded)
+ };
+ });
+ }
+ appendSkillMessages(sessionId, skills) {
+ if (!skills || skills.length === 0) {
+ return;
+ }
+ for (const skill of skills) {
+ if (skill.name === "plan") {
+ this.appendSessionMessage(sessionId, this.buildSystemMessage(sessionId, PLAN_MODE_STATUS_MESSAGE));
+ }
+ if (skill.isLoaded) {
+ continue;
+ }
+ const skillPrompt = this.buildSkillPrompt(skill);
+ const skillMessage = this.buildSkillMessage(sessionId, skillPrompt, skill);
+ this.appendSessionMessage(sessionId, skillMessage);
+ this.onAssistantMessage(skillMessage, true);
+ }
+ }
+ getActiveSessionId() {
+ return this.activeSessionId;
+ }
+ setActiveSessionId(sessionId) {
+ this.activeSessionId = sessionId;
+ }
+ addSessionSystemMessage(sessionId, content, visible, meta3) {
+ const message = this.buildSystemMessage(sessionId, content, null, visible, meta3);
+ if (sessionId) this.appendSessionMessage(sessionId, message);
+ this.onAssistantMessage(message, false);
+ }
+ async handleUserPrompt(userPrompt) {
+ const controller = new AbortController();
+ this.activePromptController = controller;
+ try {
+ if (!this.activeSessionId || !this.getSession(this.activeSessionId)) {
+ await this.createSession(userPrompt, controller);
+ } else {
+ await this.replySession(this.activeSessionId, userPrompt, controller);
+ }
+ } catch (error51) {
+ if (!this.isAbortLikeError(error51) && !controller.signal.aborted) {
+ throw error51;
+ }
+ } finally {
+ if (this.activePromptController === controller) {
+ this.activePromptController = null;
+ }
+ }
+ }
+ async createSession(userPrompt, controller) {
+ this.reportNewPrompt();
+ const signal = controller?.signal;
+ this.throwIfAborted(signal);
+ const sessionId = crypto3.randomUUID();
+ this.ensureFileHistorySession(sessionId);
+ const now = (/* @__PURE__ */ new Date()).toISOString();
+ const index = this.loadSessionsIndex();
+ const entry = {
+ id: sessionId,
+ summary: userPrompt.text ? userPrompt.text.slice(0, 100) : "[Image Prompt]",
+ assistantReply: null,
+ assistantThinking: null,
+ assistantRefusal: null,
+ toolCalls: null,
+ status: "pending",
+ failReason: null,
+ usage: null,
+ usagePerModel: null,
+ activeTokens: 0,
+ createTime: now,
+ updateTime: now,
+ processes: null
+ };
+ index.entries.push(entry);
+ const sortedEntries = index.entries.slice().sort((a, b) => {
+ const aTime = Date.parse(a.updateTime);
+ const bTime = Date.parse(b.updateTime);
+ if (Number.isNaN(aTime) || Number.isNaN(bTime)) {
+ return b.updateTime.localeCompare(a.updateTime);
+ }
+ return bTime - aTime;
+ });
+ const keptEntries = sortedEntries.slice(0, MAX_SESSION_ENTRIES);
+ const keptIds = new Set(keptEntries.map((item) => item.id));
+ const droppedEntries = sortedEntries.filter((item) => !keptIds.has(item.id));
+ index.entries = keptEntries;
+ this.saveSessionsIndex(index);
+ for (const dropped of droppedEntries) {
+ this.cleanupSessionResources(dropped.id, {
+ removeMessages: true,
+ processIds: this.getProcessIds(dropped.processes ?? null)
+ });
+ }
+ const promptToolOptions = this.getPromptToolOptions();
+ const systemPrompt = getSystemPrompt(this.projectRoot, promptToolOptions);
+ const systemMessage = this.buildSystemMessage(sessionId, systemPrompt);
+ this.appendSessionMessage(sessionId, systemMessage);
+ const defaultSkillPrompt = getDefaultSkillPrompt({ enabledSkills: this.getResolvedSettings().enabledSkills });
+ if (defaultSkillPrompt) {
+ const defaultSkillMessage = this.buildSystemMessage(sessionId, defaultSkillPrompt);
+ this.appendSessionMessage(sessionId, defaultSkillMessage);
+ }
+ const runtimeContextMessage = this.buildSystemMessage(
+ sessionId,
+ getRuntimeContext(this.projectRoot, promptToolOptions.model)
+ );
+ this.appendSessionMessage(sessionId, runtimeContextMessage);
+ const agentInstructions = this.loadAgentInstructions();
+ if (agentInstructions) {
+ const instructionsMessage = this.buildSystemMessage(sessionId, agentInstructions);
+ this.appendSessionMessage(sessionId, instructionsMessage);
+ }
+ const projectRules = this.loadProjectRules();
+ if (projectRules) {
+ const rulesMessage = this.buildSystemMessage(sessionId, projectRules);
+ this.appendSessionMessage(sessionId, rulesMessage);
+ }
+ this.recordUserPromptCheckpoint(sessionId);
+ const userMessage = this.buildUserMessage(sessionId, userPrompt);
+ this.appendSessionMessage(sessionId, userMessage);
+ if (userPrompt.text) {
+ const skills = await this.listSkills();
+ const skillNames = await this.identifyMatchingSkillNames(skills, userPrompt.text, { signal });
+ this.throwIfAborted(signal);
+ const skillSet = new Set(skillNames);
+ const matchedSkill = skills.filter((skill) => skillSet.has(skill.name));
+ if (Array.isArray(userPrompt.skills)) {
+ userPrompt.skills.push(...matchedSkill);
+ } else if (matchedSkill.length > 0) {
+ userPrompt.skills = matchedSkill;
+ }
+ }
+ userPrompt.skills = await this.normalizeSkills(userPrompt.skills);
+ this.throwIfAborted(signal);
+ this.appendSkillMessages(sessionId, userPrompt.skills);
+ this.activeSessionId = sessionId;
+ await this.activateSession(sessionId, controller);
+ return sessionId;
+ }
+ async replySession(sessionId, userPrompt, controller) {
+ const signal = controller?.signal;
+ this.throwIfAborted(signal);
+ appendProjectPermissionAllows(this.projectRoot, userPrompt.alwaysAllows, {
+ inheritedPermissions: this.getResolvedSettings().permissions
+ });
+ const now = (/* @__PURE__ */ new Date()).toISOString();
+ const updated = this.updateSessionEntry(sessionId, (entry) => ({
+ ...entry,
+ status: "pending",
+ failReason: null,
+ askPermissions: void 0,
+ updateTime: now
+ }));
+ if (!updated) {
+ await this.createSession(userPrompt, controller);
+ return;
+ }
+ if (hasUserPermissionReplies(userPrompt) && this.hasTrailingPendingToolCalls(sessionId)) {
+ this.activeSessionId = sessionId;
+ await this.activateSession(sessionId, controller, userPrompt);
+ return;
+ }
+ if (this.isContinuePrompt(userPrompt)) {
+ this.activeSessionId = sessionId;
+ await this.activateSession(sessionId, controller, userPrompt);
+ return;
+ }
+ this.reportNewPrompt();
+ this.ensureFileHistorySession(sessionId);
+ const checkpoint = this.recordUserPromptCheckpoint(sessionId);
+ if (checkpoint.changedFilePaths.length) {
+ const content = `Note that the user manually modified these files:
+${checkpoint.changedFilePaths.join("\n")}`;
+ this.appendSessionMessage(sessionId, this.buildSystemMessage(sessionId, content));
+ }
+ const userMessage = this.buildUserMessage(sessionId, userPrompt);
+ this.appendSessionMessage(sessionId, userMessage);
+ if (userPrompt.text) {
+ const skills = await this.listSkills(sessionId);
+ const skillNames = await this.identifyMatchingSkillNames(skills, userPrompt.text, { signal, sessionId });
+ this.throwIfAborted(signal);
+ const skillSet = new Set(skillNames);
+ const matchedSkill = skills.filter((skill) => skillSet.has(skill.name));
+ if (Array.isArray(userPrompt.skills)) {
+ userPrompt.skills.push(...matchedSkill);
+ } else if (matchedSkill.length > 0) {
+ userPrompt.skills = matchedSkill;
+ }
+ }
+ userPrompt.skills = await this.normalizeSkills(userPrompt.skills, sessionId);
+ this.throwIfAborted(signal);
+ this.appendSkillMessages(sessionId, userPrompt.skills);
+ this.activeSessionId = sessionId;
+ await this.activateSession(sessionId, controller);
+ }
+ isContinuePrompt(userPrompt) {
+ return typeof userPrompt.text === "string" && userPrompt.text.trim() === "/continue" && (!userPrompt.imageUrls || userPrompt.imageUrls.length === 0) && (!userPrompt.skills || userPrompt.skills.length === 0);
+ }
+ async activateSession(sessionId, controller, permissionPrompt) {
+ const startedAt = Date.now();
+ const { client, model, baseURL, temperature, thinkingEnabled, reasoningEffort, debugLogEnabled, notify, env: env6 } = this.createOpenAIClient();
+ const now = (/* @__PURE__ */ new Date()).toISOString();
+ rebuildSessionStateFromHistory(sessionId, this.listSessionMessages(sessionId));
+ if (!client) {
+ this.updateSessionEntry(sessionId, (entry) => ({
+ ...entry,
+ status: "failed",
+ failReason: "API key not found",
+ updateTime: now
+ }));
+ this.onAssistantMessage(
+ this.buildAssistantMessage(
+ sessionId,
+ "API key not found. Please configure ~/.deepcode/settings.json or ./.deepcode/settings.json.",
+ null
+ ),
+ false
+ );
+ this.maybeNotifyTaskCompletion(sessionId, notify, startedAt, env6);
+ return;
+ }
+ const sessionController = controller ?? new AbortController();
+ if (sessionController.signal.aborted) {
+ this.updateSessionEntry(sessionId, (entry) => ({
+ ...entry,
+ status: "interrupted",
+ failReason: "interrupted",
+ updateTime: now
+ }));
+ this.maybeNotifyTaskCompletion(sessionId, notify, startedAt, env6);
+ return;
+ }
+ this.updateSessionEntry(sessionId, (entry) => ({
+ ...entry,
+ status: "processing",
+ updateTime: now
+ }));
+ this.sessionControllers.set(sessionId, sessionController);
+ try {
+ const maxIterations = 8e4;
+ let toolCalls = null;
+ const errorFixCounts = /* @__PURE__ */ new Map();
+ let lastToolExecutionHadFailures = false;
+ for (let iteration = 0; iteration < maxIterations; iteration++) {
+ if (this.isInterrupted(sessionId)) {
+ return;
+ }
+ const session = this.getSession(sessionId);
+ if (session == null || session.status === "interrupted" || session.status === "failed") {
+ return;
+ }
+ const pendingToolCallMessage = this.messageConverter.getTrailingPendingToolCallMessage(
+ this.listSessionMessages(sessionId)
+ );
+ if (pendingToolCallMessage.toolCalls.length > 0) {
+ const toolAppendResult = await this.appendToolMessages(sessionId, pendingToolCallMessage.toolCalls, {
+ permissionOverrides: permissionPrompt?.permissions,
+ messagePermissions: pendingToolCallMessage.message?.meta?.permissions
+ });
+ await this.appendDeferredPermissionPrompt(sessionId, permissionPrompt, sessionController);
+ permissionPrompt = void 0;
+ if (this.isInterrupted(sessionId)) {
+ return;
+ }
+ if (toolAppendResult.waitingForUser) {
+ this.updateSessionEntry(sessionId, (entry) => ({
+ ...entry,
+ toolCalls: pendingToolCallMessage.toolCalls,
+ status: "waiting_for_user",
+ updateTime: (/* @__PURE__ */ new Date()).toISOString()
+ }));
+ return;
+ }
+ }
+ const compactPromptTokenThreshold = getCompactPromptTokenThreshold(model);
+ if (session.activeTokens > compactPromptTokenThreshold) {
+ const message2 = this.buildAssistantMessage(
+ sessionId,
+ "The conversation is getting long, compacting...",
+ null
+ );
+ message2.meta = { asThinking: true };
+ this.onAssistantMessage(message2, false);
+ await this.compactSession(sessionId, sessionController.signal);
+ }
+ const messages = this.messageConverter.buildMessages(
+ this.listSessionMessages(sessionId),
+ thinkingEnabled,
+ model
+ );
+ const thinkingOptions = buildThinkingRequestOptions(thinkingEnabled, baseURL, reasoningEffort);
+ const response = await this.createChatCompletionStream(
+ client,
+ {
+ model,
+ ...temperature !== void 0 ? { temperature } : {},
+ messages,
+ tools: getTools(this.getPromptToolOptions(), this.mcpToolDefinitions),
+ ...thinkingOptions
+ },
+ { signal: sessionController.signal },
+ sessionId,
+ {
+ enabled: debugLogEnabled,
+ location: "SessionManager.activateSession",
+ baseURL,
+ params: { iteration, temperature, thinkingEnabled, reasoningEffort }
+ }
+ );
+ const message = response.choices?.[0]?.message;
+ const rawContent = message?.content;
+ const content = typeof rawContent === "string" ? rawContent : "";
+ const rawToolCalls = message?.tool_calls ?? null;
+ toolCalls = this.normalizeLlmToolCalls(rawToolCalls);
+ const rawThinking = message?.reasoning_content;
+ const thinking = typeof rawThinking === "string" ? rawThinking : null;
+ const refusal = message?.refusal ?? null;
+ if (this.isInterrupted(sessionId)) {
+ return;
+ }
+ const assistantMessage = this.buildAssistantMessage(sessionId, content, toolCalls, thinking);
+ const permissionPlan = toolCalls ? computeToolCallPermissions({
+ sessionId,
+ projectRoot: this.projectRoot,
+ toolCalls,
+ settings: this.getResolvedSettings().permissions,
+ readPermissionExemptPaths: this.getSkillScanRoots().map((entry) => entry.root),
+ resolveSnippetPath: /* @__PURE__ */ __name((id, snippetId) => getSnippet(id, snippetId)?.filePath, "resolveSnippetPath")
+ }) : null;
+ if (permissionPlan) {
+ assistantMessage.meta = {
+ ...assistantMessage.meta ?? {},
+ permissions: permissionPlan.permissions
+ };
+ }
+ this.appendSessionMessage(sessionId, assistantMessage);
+ this.onAssistantMessage(assistantMessage, true);
+ let waitingForUser = false;
+ const responseUsage = response.usage ?? null;
+ if (toolCalls) {
+ if (permissionPlan?.askPermissions.length) {
+ this.updateSessionEntry(sessionId, (entry) => ({
+ ...entry,
+ assistantReply: content,
+ assistantThinking: thinking,
+ assistantRefusal: refusal,
+ toolCalls,
+ usage: accumulateUsage(entry.usage, responseUsage),
+ usagePerModel: accumulateUsagePerModel(entry.usagePerModel, model, responseUsage),
+ activeTokens: getTotalTokens(responseUsage),
+ status: "ask_permission",
+ failReason: null,
+ askPermissions: permissionPlan.askPermissions,
+ updateTime: (/* @__PURE__ */ new Date()).toISOString()
+ }));
+ return;
+ }
+ const toolAppendResult = await this.appendToolMessages(sessionId, toolCalls, {
+ messagePermissions: permissionPlan?.permissions
+ });
+ waitingForUser = toolAppendResult.waitingForUser;
+ lastToolExecutionHadFailures = this.hasRecentToolExecutionFailure(
+ this.listSessionMessages(sessionId)
+ );
+ if (lastToolExecutionHadFailures) {
+ const errorKey = `error_at_iter_${iteration}`;
+ errorFixCounts.set(errorKey, (errorFixCounts.get(errorKey) ?? 0) + 1);
+ }
+ }
+ if (this.isInterrupted(sessionId)) {
+ return;
+ }
+ if (lastToolExecutionHadFailures && !toolCalls) {
+ const failedToolMessages = this.getFailedToolMessages(sessionId);
+ if (failedToolMessages.length > 0 && errorFixCounts.size <= 3) {
+ const fixReminder = this.buildSystemMessage(
+ sessionId,
+ `[Auto Error Fix] The previous command failed. Do NOT move on. Analyze the error above, fix the code, then re-run the command to verify. If you've already tried multiple approaches, explain the issue to the user.`
+ );
+ this.appendSessionMessage(sessionId, fixReminder);
+ lastToolExecutionHadFailures = false;
+ continue;
+ }
+ }
+ this.updateSessionEntry(sessionId, (entry) => ({
+ ...entry,
+ assistantReply: content,
+ assistantThinking: thinking,
+ assistantRefusal: refusal,
+ toolCalls,
+ usage: accumulateUsage(entry.usage, responseUsage),
+ usagePerModel: accumulateUsagePerModel(entry.usagePerModel, model, responseUsage),
+ activeTokens: getTotalTokens(responseUsage),
+ status: refusal ? "failed" : waitingForUser ? "waiting_for_user" : toolCalls ? "processing" : "completed",
+ failReason: refusal ? refusal : entry.failReason,
+ askPermissions: void 0,
+ updateTime: (/* @__PURE__ */ new Date()).toISOString()
+ }));
+ if (refusal) {
+ return;
+ }
+ if (waitingForUser) {
+ return;
+ }
+ if (!toolCalls) {
+ return;
+ }
+ }
+ this.updateSessionEntry(sessionId, (entry) => ({
+ ...entry,
+ status: "completed",
+ updateTime: (/* @__PURE__ */ new Date()).toISOString()
+ }));
+ this.onAssistantMessage(
+ this.buildAssistantMessage(
+ sessionId,
+ "The AI agent has taken several steps but hasn't reached a conclusion yet. Do you want to continue?",
+ null
+ ),
+ false
+ );
+ } catch (error51) {
+ const errMessage = error51 instanceof Error ? error51.message : String(error51);
+ const aborted2 = this.isAbortLikeError(error51) || sessionController.signal.aborted;
+ if (!aborted2) {
+ fireHook(this.getResolvedSettings().hooks, "onError", { error: errMessage });
+ }
+ this.updateSessionEntry(sessionId, (entry) => ({
+ ...entry,
+ status: aborted2 ? "interrupted" : "failed",
+ failReason: aborted2 ? "interrupted" : errMessage,
+ updateTime: (/* @__PURE__ */ new Date()).toISOString()
+ }));
+ if (!aborted2) {
+ this.onAssistantMessage(this.buildAssistantMessage(sessionId, `Request failed: ${errMessage}`, null), false);
+ }
+ } finally {
+ if (this.sessionControllers.get(sessionId) === sessionController) {
+ this.sessionControllers.delete(sessionId);
+ }
+ this.maybeNotifyTaskCompletion(sessionId, notify, startedAt, env6);
+ }
+ }
+ async compactSession(sessionId, signal) {
+ this.throwIfAborted(signal);
+ const { client, model, baseURL, temperature, thinkingEnabled, reasoningEffort, debugLogEnabled } = this.createOpenAIClient();
+ if (!client) {
+ return;
+ }
+ const sessionMessages = this.listSessionMessages(sessionId).filter((message) => !message.compacted);
+ if (sessionMessages.length === 0) {
+ return;
+ }
+ const startIndex = sessionMessages.findIndex((message) => message.role !== "system");
+ if (startIndex === -1) {
+ return;
+ }
+ const searchStart = Math.floor(startIndex + (sessionMessages.length - startIndex) * 2 / 3);
+ let endIndex = -1;
+ for (let i = Math.max(searchStart, startIndex); i < sessionMessages.length; i += 1) {
+ if (sessionMessages[i].role !== "tool") {
+ endIndex = i;
+ break;
+ }
+ }
+ if (endIndex === -1 || endIndex <= startIndex) {
+ return;
+ }
+ const compactPrompt = getCompactPrompt(sessionMessages.slice(startIndex, endIndex));
+ const thinkingOptions = buildThinkingRequestOptions(thinkingEnabled, baseURL, reasoningEffort);
+ const response = await this.createChatCompletionStream(
+ client,
+ {
+ model,
+ ...temperature !== void 0 ? { temperature } : {},
+ messages: [{ role: "user", content: compactPrompt }],
+ ...thinkingOptions
+ },
+ signal ? { signal } : void 0,
+ sessionId,
+ {
+ enabled: debugLogEnabled,
+ location: "SessionManager.compactSession",
+ baseURL,
+ params: { temperature, thinkingEnabled, reasoningEffort }
+ }
+ );
+ this.throwIfAborted(signal);
+ const rawLlmResponse = response.choices?.[0]?.message?.content;
+ const llmResponse = typeof rawLlmResponse === "string" ? rawLlmResponse : "";
+ const compactedSummary = llmResponse.replace(/[\s\S]*?<\/analysis>/gi, "").trim();
+ const now = (/* @__PURE__ */ new Date()).toISOString();
+ const responseUsage = response.usage ?? null;
+ this.updateSessionEntry(sessionId, (entry) => ({
+ ...entry,
+ usage: accumulateUsage(entry.usage, responseUsage),
+ usagePerModel: accumulateUsagePerModel(entry.usagePerModel, model, responseUsage),
+ activeTokens: getTotalTokens(responseUsage),
+ updateTime: now
+ }));
+ for (let i = startIndex; i < endIndex; i += 1) {
+ sessionMessages[i] = { ...sessionMessages[i], compacted: true, updateTime: now };
+ }
+ const summaryMessage = {
+ id: crypto3.randomUUID(),
+ sessionId,
+ role: "system",
+ content: `There are earlier parts of the conversation. Here is a summary:
+
+${compactedSummary}`,
+ contentParams: null,
+ messageParams: null,
+ compacted: false,
+ visible: false,
+ createTime: now,
+ updateTime: now,
+ meta: {
+ isSummary: true
+ }
+ };
+ sessionMessages.splice(endIndex, 0, summaryMessage);
+ this.saveSessionMessages(sessionId, sessionMessages);
+ }
+ getPromptToolOptions() {
+ return {
+ model: this.getResolvedSettings().model,
+ webSearchEnabled: true
+ };
+ }
+ reportNewPrompt() {
+ const { machineId, telemetryEnabled } = this.createOpenAIClient();
+ reportNewPrompt({ enabled: telemetryEnabled ?? true, machineId });
+ }
+ interruptActiveSession() {
+ const controller = this.activePromptController;
+ if (controller && !controller.signal.aborted) {
+ controller.abort();
+ }
+ const sessionId = this.activeSessionId;
+ if (sessionId) {
+ this.interruptSession(sessionId);
+ }
+ }
+ interruptSession(sessionId) {
+ const session = this.getSession(sessionId);
+ const processIds = this.getProcessIds(session?.processes ?? null);
+ const killedPids = [];
+ const failedPids = [];
+ for (const pid of processIds) {
+ const processControlKey = this.getProcessControlKey(sessionId, pid);
+ this.processTimeoutControls.delete(processControlKey);
+ this.liveProcessKeys.delete(processControlKey);
+ if (killProcessTree(pid, "SIGKILL")) {
+ killedPids.push(pid);
+ continue;
+ }
+ failedPids.push(pid);
+ }
+ const controller = this.sessionControllers.get(sessionId);
+ if (controller) {
+ controller.abort();
+ this.sessionControllers.delete(sessionId);
+ }
+ const now = (/* @__PURE__ */ new Date()).toISOString();
+ this.updateSessionEntry(sessionId, (entry) => ({
+ ...entry,
+ status: "interrupted",
+ failReason: "interrupted",
+ processes: null,
+ updateTime: now
+ }));
+ const contentParts = ["Interrupted."];
+ if (killedPids.length > 0) {
+ contentParts.push(`Killed processes: ${killedPids.join(", ")}.`);
+ }
+ if (failedPids.length > 0) {
+ contentParts.push(`Failed to kill processes: ${failedPids.join(", ")}.`);
+ }
+ this.onAssistantMessage(this.buildUserMessage(sessionId, { text: contentParts.join(" ") }), false);
+ }
+ isInterrupted(sessionId) {
+ return !this.sessionControllers.has(sessionId);
+ }
+ /**
+ * Mark a session's permission as denied by the user.
+ * Updates the session entry status and failReason so the denial is visible in the session list.
+ */
+ denySessionPermission(sessionId, reason) {
+ const now = (/* @__PURE__ */ new Date()).toISOString();
+ this.updateSessionEntry(sessionId, (entry) => ({
+ ...entry,
+ status: "permission_denied",
+ failReason: reason ?? "Permission denied by user",
+ updateTime: now
+ }));
+ }
+ adjustActiveBashTimeout(deltaMs) {
+ const sessionId = this.activeSessionId;
+ if (!sessionId || !Number.isFinite(deltaMs)) {
+ return null;
+ }
+ const session = this.getSession(sessionId);
+ if (!session?.processes) {
+ return null;
+ }
+ let selectedPid = null;
+ for (const pid of session.processes.keys()) {
+ if (this.processTimeoutControls.has(this.getProcessControlKey(sessionId, pid))) {
+ selectedPid = pid;
+ }
+ }
+ if (!selectedPid) {
+ return null;
+ }
+ const control = this.processTimeoutControls.get(this.getProcessControlKey(sessionId, selectedPid));
+ if (!control) {
+ return null;
+ }
+ const current = control.getInfo();
+ const next = control.setTimeoutMs(current.timeoutMs + deltaMs);
+ this.updateSessionProcessTimeout(sessionId, selectedPid, next);
+ return this.buildBashTimeoutAdjustment(selectedPid, next);
+ }
+ listSessions() {
+ const index = this.loadSessionsIndex();
+ return index.entries;
+ }
+ getSession(sessionId) {
+ const index = this.loadSessionsIndex();
+ return index.entries.find((entry) => entry.id === sessionId) ?? null;
+ }
+ /**
+ * Delete a session by its ID.
+ * Removes the session entry from the index and cleans up associated resources
+ * such as message files, in-memory state caches, working directory state,
+ * session controllers, and tracked process timeout controls.
+ * Returns true if the session was found and deleted, false otherwise.
+ */
+ deleteSession(sessionId) {
+ const index = this.loadSessionsIndex();
+ const targetEntry = index.entries.find((entry) => entry.id === sessionId) ?? null;
+ const nextEntries = index.entries.filter((entry) => entry.id !== sessionId);
+ if (nextEntries.length === index.entries.length) {
+ return false;
+ }
+ index.entries = nextEntries;
+ this.saveSessionsIndex(index);
+ this.cleanupSessionResources(sessionId, {
+ removeMessages: true,
+ processIds: this.getProcessIds(targetEntry?.processes ?? null)
+ });
+ return true;
+ }
+ /**
+ * Rename a session by updating its summary (display title).
+ * Returns true if the session was found and renamed, false otherwise.
+ */
+ renameSession(sessionId, summary) {
+ const trimmed = summary.trim();
+ if (!trimmed) {
+ return false;
+ }
+ const entry = this.getSession(sessionId);
+ if (!entry) {
+ return false;
+ }
+ this.updateSessionEntry(sessionId, (existing) => ({
+ ...existing,
+ summary: trimmed,
+ updateTime: (/* @__PURE__ */ new Date()).toISOString()
+ }));
+ return true;
+ }
+ listSessionMessages(sessionId) {
+ const messagePath = this.getSessionMessagesPath(sessionId);
+ if (!fs17.existsSync(messagePath)) {
+ return [];
+ }
+ const raw = fs17.readFileSync(messagePath, "utf8");
+ const lines = raw.split(/\r?\n/).filter((line) => line.trim().length > 0);
+ const messages = [];
+ for (const line of lines) {
+ try {
+ const parsed = JSON.parse(line);
+ messages.push(this.normalizeSessionMessage(parsed));
+ } catch {
+ }
+ }
+ return messages;
+ }
+ listUndoTargets(sessionId) {
+ return this.listSessionMessages(sessionId).map((message, index) => ({ message, index })).filter(({ message }) => this.isUndoTargetMessage(message)).map(({ message, index }) => ({
+ message,
+ index,
+ canRestoreCode: Boolean(
+ message.checkpointHash && this.canRestoreCheckpointHash(sessionId, message.checkpointHash)
+ )
+ }));
+ }
+ restoreSessionConversation(sessionId, messageId) {
+ const messages = this.listSessionMessages(sessionId);
+ const targetIndex = messages.findIndex((message) => message.id === messageId);
+ if (targetIndex === -1) {
+ throw new Error("Selected message was not found in this session.");
+ }
+ const keptMessages = messages.slice(0, targetIndex);
+ this.saveSessionMessages(sessionId, keptMessages);
+ const now = (/* @__PURE__ */ new Date()).toISOString();
+ const latestAssistant = [...keptMessages].reverse().find((message) => message.role === "assistant");
+ const latestAssistantParams = latestAssistant?.messageParams;
+ this.updateSessionEntry(sessionId, (entry) => ({
+ ...entry,
+ assistantReply: latestAssistant?.content ?? null,
+ assistantThinking: typeof latestAssistantParams?.reasoning_content === "string" ? latestAssistantParams.reasoning_content : null,
+ assistantRefusal: null,
+ toolCalls: null,
+ status: "completed",
+ failReason: null,
+ processes: null,
+ updateTime: now
+ }));
+ return keptMessages;
+ }
+ restoreSessionCode(sessionId, messageId) {
+ const message = this.listSessionMessages(sessionId).find((item) => item.id === messageId);
+ if (!message) {
+ throw new Error("Selected message was not found in this session.");
+ }
+ if (!message.checkpointHash) {
+ throw new Error("Selected message has no code checkpoint.");
+ }
+ this.restoreCheckpointHash(sessionId, message.checkpointHash);
+ }
+ normalizeSessionMessage(message) {
+ if (message.role !== "tool") {
+ return message;
+ }
+ const nextMeta = message.meta ? { ...message.meta } : void 0;
+ const normalizedParamsMd = this.buildToolParamsSnippet(nextMeta?.function ?? null);
+ if (nextMeta && normalizedParamsMd) {
+ nextMeta.paramsMd = normalizedParamsMd;
+ }
+ const normalizedResultMd = typeof message.content === "string" ? this.buildToolResultSnippet(message.content) : "";
+ if (nextMeta && normalizedResultMd) {
+ nextMeta.resultMd = normalizedResultMd;
+ }
+ return {
+ ...message,
+ visible: typeof message.content === "string" ? !this.isInvisibleExecution(message.content) : message.visible,
+ meta: nextMeta
+ };
+ }
+ getProjectStorage() {
+ const projectCode = getProjectCode(this.projectRoot);
+ const projectDir = path14.join(os9.homedir(), ".deepcode", "projects", projectCode);
+ const sessionsIndexPath = path14.join(projectDir, "sessions-index.json");
+ return { projectCode, projectDir, sessionsIndexPath };
+ }
+ getFileHistory() {
+ return new GitFileHistory(this.projectRoot, this.getFileHistoryGitDir());
+ }
+ getFileHistoryGitDir() {
+ const { projectDir } = this.getProjectStorage();
+ return path14.join(projectDir, "file-history", ".git");
+ }
+ ensureFileHistorySession(sessionId) {
+ return this.getFileHistory().ensureSession(sessionId);
+ }
+ getCurrentCheckpointHash(sessionId) {
+ return this.getFileHistory().getCurrentCheckpointHash(sessionId);
+ }
+ recordUserPromptCheckpoint(sessionId) {
+ return this.getFileHistory().recordTrackedFilesCheckpoint(sessionId, "User prompt checkpoint");
+ }
+ prepareFileMutationCheckpoint(sessionId, filePath) {
+ const fileHistory = this.getFileHistory();
+ const previousHash = fileHistory.ensureSession(sessionId);
+ if (!previousHash) {
+ return;
+ }
+ this.updateLatestUserCheckpointHash(sessionId, void 0, previousHash);
+ const nextHash = fileHistory.recordCheckpoint(sessionId, [filePath], "Pre-mutation checkpoint");
+ if (nextHash && nextHash !== previousHash) {
+ this.updateLatestUserCheckpointHash(sessionId, previousHash, nextHash);
+ }
+ }
+ recordFileMutationCheckpoint(sessionId, filePath) {
+ const fileHistory = this.getFileHistory();
+ fileHistory.ensureSession(sessionId);
+ fileHistory.recordCheckpoint(sessionId, [filePath], "File mutation checkpoint");
+ }
+ updateLatestUserCheckpointHash(sessionId, previousHash, nextHash) {
+ const messages = this.listSessionMessages(sessionId);
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
+ const message = messages[index];
+ if (!message || !this.isUndoTargetMessage(message)) {
+ continue;
+ }
+ if (message.checkpointHash && message.checkpointHash !== previousHash) {
+ return;
+ }
+ messages[index] = {
+ ...message,
+ checkpointHash: nextHash,
+ updateTime: (/* @__PURE__ */ new Date()).toISOString()
+ };
+ this.saveSessionMessages(sessionId, messages);
+ return;
+ }
+ }
+ canRestoreCheckpointHash(sessionId, checkpointHash) {
+ return this.getFileHistory().canRestore(sessionId, checkpointHash);
+ }
+ restoreCheckpointHash(sessionId, checkpointHash) {
+ this.getFileHistory().restore(sessionId, checkpointHash);
+ }
+ isUndoTargetMessage(message) {
+ return message.role === "user" && message.visible && !message.compacted;
+ }
+ ensureProjectDir() {
+ const { projectDir } = this.getProjectStorage();
+ fs17.mkdirSync(projectDir, { recursive: true });
+ return projectDir;
+ }
+ loadSessionsIndex() {
+ const { sessionsIndexPath } = this.getProjectStorage();
+ this.ensureProjectDir();
+ if (!fs17.existsSync(sessionsIndexPath)) {
+ return { version: 1, entries: [], originalPath: this.projectRoot };
+ }
+ try {
+ const raw = fs17.readFileSync(sessionsIndexPath, "utf8");
+ const parsed = JSON.parse(raw);
+ const entries = Array.isArray(parsed.entries) ? parsed.entries.map((entry) => this.normalizeSessionEntry(entry)) : [];
+ return {
+ version: 1,
+ entries,
+ originalPath: parsed.originalPath || this.projectRoot
+ };
+ } catch {
+ return { version: 1, entries: [], originalPath: this.projectRoot };
+ }
+ }
+ saveSessionsIndex(index) {
+ const { sessionsIndexPath } = this.getProjectStorage();
+ this.ensureProjectDir();
+ const normalized = {
+ version: 1,
+ entries: index.entries.map((entry) => ({
+ ...entry,
+ processes: this.serializeProcesses(entry.processes)
+ })),
+ originalPath: this.projectRoot
+ };
+ fs17.writeFileSync(sessionsIndexPath, JSON.stringify(normalized, null, 2), "utf8");
+ }
+ getSessionMessagesPath(sessionId) {
+ const { projectDir } = this.getProjectStorage();
+ return path14.join(projectDir, `${sessionId}.jsonl`);
+ }
+ removeSessionMessages(sessionIds) {
+ for (const sessionId of sessionIds) {
+ const messagePath = this.getSessionMessagesPath(sessionId);
+ try {
+ if (fs17.existsSync(messagePath)) {
+ fs17.unlinkSync(messagePath);
+ }
+ } catch {
+ }
+ }
+ }
+ cleanupSessionResources(sessionId, options2) {
+ const processIds = options2.processIds ?? [];
+ for (const pid of processIds) {
+ const processControlKey = this.getProcessControlKey(sessionId, pid);
+ if (!this.processTimeoutControls.has(processControlKey) && !this.liveProcessKeys.has(processControlKey)) {
+ continue;
+ }
+ this.killTrackedProcess(processControlKey, pid);
+ }
+ clearSessionState(sessionId);
+ clearSessionWorkingDir(sessionId);
+ const controller = this.sessionControllers.get(sessionId);
+ if (controller && !controller.signal.aborted) {
+ controller.abort();
+ }
+ this.sessionControllers.delete(sessionId);
+ if (options2.removeMessages) {
+ this.removeSessionMessages([sessionId]);
+ }
+ }
+ appendSessionMessage(sessionId, message) {
+ this.ensureProjectDir();
+ const messagePath = this.getSessionMessagesPath(sessionId);
+ fs17.appendFileSync(messagePath, `${JSON.stringify(message)}
+`, "utf8");
+ }
+ saveSessionMessages(sessionId, messages) {
+ this.ensureProjectDir();
+ const messagePath = this.getSessionMessagesPath(sessionId);
+ const payload = messages.map((message) => JSON.stringify(message)).join("\n");
+ fs17.writeFileSync(messagePath, payload ? `${payload}
+` : "", "utf8");
+ }
+ updateSessionEntry(sessionId, updater) {
+ const index = this.loadSessionsIndex();
+ const entryIndex = index.entries.findIndex((entry) => entry.id === sessionId);
+ if (entryIndex === -1) {
+ return null;
+ }
+ const updated = updater({ ...index.entries[entryIndex] });
+ index.entries[entryIndex] = updated;
+ this.saveSessionsIndex(index);
+ this.onSessionEntryUpdated?.(updated);
+ return updated;
+ }
+ buildUserMessage(sessionId, prompt) {
+ const now = (/* @__PURE__ */ new Date()).toISOString();
+ const imageParams = prompt.imageUrls?.filter((url2) => Boolean(url2)).map((url2) => ({
+ type: "image_url",
+ image_url: { url: url2 }
+ })) ?? [];
+ return {
+ id: crypto3.randomUUID(),
+ sessionId,
+ role: "user",
+ content: prompt.text ?? "",
+ contentParams: imageParams.length > 0 ? imageParams : null,
+ messageParams: null,
+ compacted: false,
+ visible: true,
+ createTime: now,
+ updateTime: now,
+ meta: { userPrompt: this.cloneUserPromptForMeta(prompt) },
+ checkpointHash: this.getCurrentCheckpointHash(sessionId)
+ };
+ }
+ renderInitCommandPrompt() {
+ const templatePath = path14.join(getExtensionRoot(), "templates", "prompts", "init_command.md.ejs");
+ const template = fs17.readFileSync(templatePath, "utf8");
+ return ejs_default.render(template, {
+ agentsMdFile: this.getEffectiveProjectAgentsMdFile()
+ });
+ }
+ getEffectiveProjectAgentsMdFile() {
+ return this.loadProjectAgentInstructions()?.displayPath ?? null;
+ }
+ loadProjectAgentInstructions() {
+ const candidatePaths = [
+ {
+ absolutePath: path14.join(this.projectRoot, ".deepcode", "AGENTS.md"),
+ displayPath: "./.deepcode/AGENTS.md"
+ },
+ {
+ absolutePath: path14.join(this.projectRoot, "AGENTS.md"),
+ displayPath: "./AGENTS.md"
+ }
+ ];
+ for (const candidatePath of candidatePaths) {
+ const content = this.readNonEmptyFile(candidatePath.absolutePath);
+ if (content) {
+ return {
+ content,
+ displayPath: candidatePath.displayPath
+ };
+ }
+ }
+ return null;
+ }
+ readNonEmptyFile(filePath) {
+ try {
+ if (!fs17.existsSync(filePath)) {
+ return null;
+ }
+ const content = fs17.readFileSync(filePath, "utf8").trim();
+ return content || null;
+ } catch {
+ return null;
+ }
+ }
+ loadAgentInstructions() {
+ const projectInstructions = this.loadProjectAgentInstructions();
+ if (projectInstructions) {
+ return projectInstructions.content;
+ }
+ return this.readNonEmptyFile(path14.join(os9.homedir(), ".deepcode", "AGENTS.md"));
+ }
+ /**
+ * Load hierarchical rules from .deepcode/rules/ directory.
+ * Each .md file becomes a named rule section injected into system context.
+ * Supports subdirectory-based scoping (e.g., rules/api/*.md, rules/db/*.md).
+ */
+ loadProjectRules() {
+ const rulesDir = path14.join(this.projectRoot, ".deepcode", "rules");
+ if (!fs17.existsSync(rulesDir)) {
+ return null;
+ }
+ const sections = [];
+ const collectRules = /* @__PURE__ */ __name((dir, scope) => {
+ let entries;
+ try {
+ entries = fs17.readdirSync(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ entries.sort((a, b) => {
+ if (a.isDirectory() !== b.isDirectory()) {
+ return a.isDirectory() ? 1 : -1;
+ }
+ return a.name.localeCompare(b.name);
+ });
+ for (const entry of entries) {
+ const fullPath = path14.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ collectRules(fullPath, path14.join(scope, entry.name));
+ continue;
+ }
+ if (!entry.name.endsWith(".md")) {
+ continue;
+ }
+ const content = this.readNonEmptyFile(fullPath);
+ if (!content) {
+ continue;
+ }
+ const ruleName = entry.name.replace(/\.md$/, "");
+ const ruleHeader = scope ? `${scope}/${ruleName}` : ruleName;
+ sections.push(`### Rule: ${ruleHeader}
+
+${content}`);
+ }
+ }, "collectRules");
+ collectRules(rulesDir, "");
+ if (sections.length === 0) {
+ return null;
+ }
+ return `# Project Rules
+
+${sections.join("\n\n")}`;
+ }
+ buildSystemMessage(sessionId, content, contentParams = null, visible = false, meta3) {
+ const now = (/* @__PURE__ */ new Date()).toISOString();
+ return {
+ id: crypto3.randomUUID(),
+ sessionId,
+ role: "system",
+ content,
+ contentParams,
+ messageParams: null,
+ compacted: false,
+ visible,
+ createTime: now,
+ updateTime: now,
+ meta: meta3
+ };
+ }
+ buildSkillMessage(sessionId, content, skill) {
+ const now = (/* @__PURE__ */ new Date()).toISOString();
+ return {
+ id: crypto3.randomUUID(),
+ sessionId,
+ role: "system",
+ content,
+ contentParams: null,
+ messageParams: null,
+ compacted: false,
+ visible: true,
+ createTime: now,
+ updateTime: now,
+ meta: { skill: { ...skill, isLoaded: true } }
+ };
+ }
+ buildAssistantMessage(sessionId, content, toolCalls, reasoningContent) {
+ const now = (/* @__PURE__ */ new Date()).toISOString();
+ const hasReasoningContent = reasoningContent != null;
+ const messageParams = toolCalls || hasReasoningContent ? {} : null;
+ if (toolCalls) {
+ messageParams.tool_calls = toolCalls;
+ }
+ if (hasReasoningContent) {
+ messageParams.reasoning_content = reasoningContent;
+ }
+ return {
+ id: crypto3.randomUUID(),
+ sessionId,
+ role: "assistant",
+ content,
+ contentParams: null,
+ messageParams,
+ compacted: false,
+ visible: (content || reasoningContent || "").trim() ? true : false,
+ createTime: now,
+ updateTime: now,
+ meta: toolCalls ? { asThinking: true } : void 0
+ };
+ }
+ generateToolCallId() {
+ return crypto3.randomBytes(16).toString("hex");
+ }
+ normalizeLlmToolCalls(rawToolCalls) {
+ if (!Array.isArray(rawToolCalls) || rawToolCalls.length === 0) {
+ return null;
+ }
+ return rawToolCalls.map((toolCall) => {
+ if (!toolCall || typeof toolCall !== "object" || Array.isArray(toolCall)) {
+ return toolCall;
+ }
+ const record2 = toolCall;
+ const id = typeof record2.id === "string" ? record2.id.trim() : "";
+ if (id) {
+ return toolCall;
+ }
+ return {
+ ...record2,
+ id: this.generateToolCallId()
+ };
+ });
+ }
+ buildToolMessage(sessionId, toolCallId, content, toolFunction) {
+ const now = (/* @__PURE__ */ new Date()).toISOString();
+ const paramsMd = this.buildToolParamsSnippet(toolFunction);
+ const resultMd = this.buildToolResultSnippet(content);
+ const isInvisibleExecution = this.isInvisibleExecution(content);
+ return {
+ id: crypto3.randomUUID(),
+ sessionId,
+ role: "tool",
+ content,
+ contentParams: null,
+ messageParams: { tool_call_id: toolCallId },
+ compacted: false,
+ visible: !isInvisibleExecution,
+ createTime: now,
+ updateTime: now,
+ meta: {
+ function: toolFunction ?? void 0,
+ paramsMd,
+ resultMd
+ }
+ };
+ }
+ async appendToolMessages(sessionId, toolCalls, options2 = {}) {
+ const settings = this.getResolvedSettings();
+ const hooks = {
+ onProcessStart: /* @__PURE__ */ __name((pid, command2) => {
+ this.addSessionProcess(sessionId, pid, command2);
+ fireHook(settings.hooks, "beforeCommand", { command: command2 });
+ }, "onProcessStart"),
+ onProcessExit: /* @__PURE__ */ __name((pid) => this.removeSessionProcess(sessionId, pid), "onProcessExit"),
+ onProcessStdout: /* @__PURE__ */ __name((pid, chunk) => this.onProcessStdout?.(Number(pid), chunk), "onProcessStdout"),
+ onProcessTimeoutControl: /* @__PURE__ */ __name((pid, control) => this.setSessionProcessTimeoutControl(sessionId, pid, control), "onProcessTimeoutControl"),
+ onBackgroundProcessComplete: /* @__PURE__ */ __name((completion2) => this.addBackgroundProcessCompletionMessage(sessionId, completion2), "onBackgroundProcessComplete"),
+ onBeforeFileMutation: /* @__PURE__ */ __name((filePath) => {
+ this.prepareFileMutationCheckpoint(sessionId, filePath);
+ fireHook(settings.hooks, "beforeWrite", { filePath });
+ }, "onBeforeFileMutation"),
+ onAfterFileMutation: /* @__PURE__ */ __name((filePath) => {
+ this.recordFileMutationCheckpoint(sessionId, filePath);
+ fireHook(settings.hooks, "afterWrite", { filePath });
+ }, "onAfterFileMutation"),
+ shouldStop: /* @__PURE__ */ __name(() => this.isInterrupted(sessionId), "shouldStop")
+ };
+ const parsedToolCalls = toolCalls.map((toolCall) => parseToolCallForPermissions(toolCall)).filter((toolCall) => Boolean(toolCall));
+ const toolExecutions = [];
+ for (const toolCall of parsedToolCalls) {
+ if (hooks.shouldStop?.()) {
+ break;
+ }
+ const blockedResult = buildPermissionToolExecution(toolCall, options2);
+ if (blockedResult) {
+ toolExecutions.push(blockedResult);
+ continue;
+ }
+ const executions = await this.toolExecutor.executeToolCalls(sessionId, [toolCall], hooks);
+ toolExecutions.push(...executions);
+ }
+ if (this.isInterrupted(sessionId)) {
+ return { waitingForUser: false };
+ }
+ let waitingForUser = false;
+ const followUpMessages = [];
+ for (const execution of toolExecutions) {
+ if (execution.result.awaitUserResponse === true) {
+ waitingForUser = true;
+ }
+ const toolFunction = this.messageConverter.findToolFunction(toolCalls, execution.toolCallId);
+ const toolMessage = this.buildToolMessage(sessionId, execution.toolCallId, execution.content, toolFunction);
+ this.appendSessionMessage(sessionId, toolMessage);
+ this.onAssistantMessage(toolMessage, true);
+ for (const followUpMessage of execution.result.followUpMessages ?? []) {
+ if (followUpMessage.role !== "system") {
+ continue;
+ }
+ followUpMessages.push(
+ this.buildSystemMessage(sessionId, followUpMessage.content, followUpMessage.contentParams ?? null)
+ );
+ }
+ }
+ for (const followUpMessage of followUpMessages) {
+ this.appendSessionMessage(sessionId, followUpMessage);
+ }
+ return { waitingForUser };
+ }
+ cloneUserPromptForMeta(prompt) {
+ return {
+ text: prompt.text,
+ imageUrls: prompt.imageUrls ? [...prompt.imageUrls] : void 0,
+ skills: prompt.skills ? prompt.skills.map((skill) => ({ ...skill })) : void 0,
+ permissions: prompt.permissions ? prompt.permissions.map((permission) => ({ ...permission })) : void 0,
+ alwaysAllows: prompt.alwaysAllows ? [...prompt.alwaysAllows] : void 0
+ };
+ }
+ hasTrailingPendingToolCalls(sessionId) {
+ return this.messageConverter.getTrailingPendingToolCallMessage(this.listSessionMessages(sessionId)).toolCalls.length > 0;
+ }
+ async appendDeferredPermissionPrompt(sessionId, userPrompt, controller) {
+ if (!userPrompt || this.isContinuePrompt(userPrompt)) {
+ return;
+ }
+ const text = userPrompt.text ?? "";
+ const hasUserContent = text.trim().length > 0 || Array.isArray(userPrompt.imageUrls) && userPrompt.imageUrls.length > 0 || Array.isArray(userPrompt.skills) && userPrompt.skills.length > 0;
+ if (!hasUserContent) {
+ return;
+ }
+ this.reportNewPrompt();
+ const signal = controller.signal;
+ const userMessage = this.buildUserMessage(sessionId, userPrompt);
+ this.appendSessionMessage(sessionId, userMessage);
+ if (userPrompt.text) {
+ const skills = await this.listSkills(sessionId);
+ const skillNames = await this.identifyMatchingSkillNames(skills, userPrompt.text, { signal, sessionId });
+ this.throwIfAborted(signal);
+ const skillSet = new Set(skillNames);
+ const matchedSkill = skills.filter((skill) => skillSet.has(skill.name));
+ if (Array.isArray(userPrompt.skills)) {
+ userPrompt.skills.push(...matchedSkill);
+ } else if (matchedSkill.length > 0) {
+ userPrompt.skills = matchedSkill;
+ }
+ }
+ userPrompt.skills = await this.normalizeSkills(userPrompt.skills, sessionId);
+ this.throwIfAborted(signal);
+ this.appendSkillMessages(sessionId, userPrompt.skills);
+ }
+ /**
+ * Check if the most recent tool execution messages contain failures.
+ * Looks at the last batch of tool-call result messages for any with ok:false.
+ */
+ hasRecentToolExecutionFailure(messages) {
+ let foundToolMessages = false;
+ for (let i = messages.length - 1; i >= 0; i--) {
+ const msg = messages[i];
+ if (msg.role !== "tool") {
+ break;
+ }
+ foundToolMessages = true;
+ if (msg.content) {
+ try {
+ const parsed = JSON.parse(msg.content);
+ if (parsed && typeof parsed === "object" && parsed.ok === false) {
+ return true;
+ }
+ } catch {
+ }
+ }
+ }
+ return foundToolMessages;
+ }
+ /**
+ * Get the list of failed tool messages for error reporting.
+ */
+ getFailedToolMessages(sessionId) {
+ const messages = this.listSessionMessages(sessionId);
+ const failed = [];
+ for (let i = messages.length - 1; i >= 0; i--) {
+ const msg = messages[i];
+ if (msg.role !== "tool") {
+ break;
+ }
+ if (msg.content) {
+ try {
+ const parsed = JSON.parse(msg.content);
+ if (parsed && typeof parsed === "object" && parsed.ok === false) {
+ const errorMsg = parsed.error ?? parsed.output ?? "Unknown error";
+ const name = parsed.name ?? "unknown";
+ failed.push(`${name}: ${String(errorMsg).slice(0, 200)}`);
+ }
+ } catch {
+ }
+ }
+ }
+ return failed;
+ }
+ buildToolParamsSnippet(toolFunction) {
+ if (!toolFunction || typeof toolFunction !== "object") {
+ return "";
+ }
+ const args = toolFunction.arguments;
+ const toolName = toolFunction.name;
+ if (typeof args !== "string") {
+ return "";
+ }
+ const trimmed = args.trim();
+ if (!trimmed) {
+ return "";
+ }
+ try {
+ const parsed = JSON.parse(trimmed);
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
+ return this.formatToolParamsSnippet(
+ typeof toolName === "string" ? toolName : null,
+ parsed
+ );
+ }
+ } catch {
+ }
+ return trimmed;
+ }
+ formatToolParamsSnippet(toolName, args) {
+ if (toolName === "bash") {
+ const command2 = typeof args.command === "string" ? args.command.trim() : "";
+ const description = typeof args.description === "string" ? args.description.trim() : "";
+ if (command2 && description) {
+ return `${command2} # ${description}`;
+ }
+ if (command2) {
+ return command2;
+ }
+ if (description) {
+ return description;
+ }
+ } else if (toolName === "UpdatePlan") {
+ return typeof args.explanation === "string" ? args.explanation.trim() : "";
+ } else if (toolName === "write") {
+ return typeof args.file_path === "string" ? args.file_path.trim() : "";
+ } else if (toolName === "edit") {
+ const filePath = typeof args.file_path === "string" ? args.file_path.trim() : "";
+ if (filePath) {
+ return filePath;
+ }
+ return typeof args.snippet_id === "string" ? args.snippet_id.trim() : "";
+ }
+ const firstKey = Object.keys(args)[0];
+ if (!firstKey) {
+ return "";
+ }
+ const value = args[firstKey];
+ const text = typeof value === "string" ? value : JSON.stringify(value);
+ if (toolName === "read" && text.startsWith(this.projectRoot)) {
+ return text.slice(this.projectRoot.length).replace(/^[\\/]/, "");
+ }
+ return text;
+ }
+ buildToolResultSnippet(content) {
+ const trimmed = content.trim();
+ if (!trimmed) {
+ return "";
+ }
+ const maxLength = 2e3;
+ try {
+ const parsed = JSON.parse(content);
+ if (parsed.output !== void 0) {
+ if (typeof parsed.output === "string") {
+ return this.formatToolResultSnippet(parsed.output, maxLength);
+ }
+ return this.formatToolResultSnippet(JSON.stringify(parsed.output), maxLength);
+ }
+ } catch {
+ }
+ return this.formatToolResultSnippet(content, maxLength);
+ }
+ formatToolResultSnippet(value, maxLength) {
+ if (value.length <= maxLength) {
+ return value;
+ }
+ return `${value.slice(0, maxLength)}... (total ${value.length} chars)`;
+ }
+ isInvisibleExecution(content) {
+ if (!content.trim()) {
+ return false;
+ }
+ try {
+ const parsed = JSON.parse(content);
+ return parsed.name === "bash" && parsed.ok !== true;
+ } catch {
+ return false;
+ }
+ }
+ maybeNotifyTaskCompletion(sessionId, notifyCommand, startedAt, configuredEnv = {}) {
+ if (!notifyCommand) {
+ return;
+ }
+ const session = this.getSession(sessionId);
+ if (!session || session.status !== "completed" && session.status !== "failed") {
+ return;
+ }
+ let body;
+ const messages = this.listSessionMessages(sessionId);
+ for (let i = messages.length - 1; i >= 0; i--) {
+ const msg = messages[i];
+ if (msg && msg.role === "assistant" && msg.content) {
+ body = msg.content;
+ break;
+ }
+ }
+ launchNotifyScript(notifyCommand, Date.now() - startedAt, this.projectRoot, void 0, configuredEnv, {
+ status: session.status,
+ failReason: session.failReason ?? void 0,
+ body,
+ title: session.summary ?? void 0
+ });
+ }
+ addSessionProcess(sessionId, processId, command2) {
+ const now = (/* @__PURE__ */ new Date()).toISOString();
+ this.liveProcessKeys.add(this.getProcessControlKey(sessionId, processId));
+ this.updateSessionEntry(sessionId, (entry) => {
+ const processes = new Map(entry.processes ?? []);
+ processes.set(String(processId), { startTime: now, command: command2 });
+ return {
+ ...entry,
+ processes,
+ updateTime: now
+ };
+ });
+ }
+ addBackgroundProcessCompletionMessage(sessionId, completion2) {
+ const status = completion2.ok ? "completed" : "failed";
+ const exitText = completion2.exitCode !== null ? `exit code ${completion2.exitCode}` : completion2.signal ? `signal ${completion2.signal}` : completion2.error || "unknown status";
+ const durationMs = Math.max(0, completion2.completedAtMs - completion2.startedAtMs);
+ const baseContent = `Background command "${completion2.command}" ${status} with ${exitText} after ${this.formatBackgroundDuration(durationMs)}. Output: ${completion2.outputPath}`;
+ const logTail = completion2.ok ? null : this.buildBackgroundFailureLogTailSlice(completion2.outputPath);
+ const content = logTail ? `${baseContent}
+${logTail}` : baseContent;
+ this.addSessionSystemMessage(sessionId, content, true);
+ }
+ buildBackgroundFailureLogTailSlice(outputPath) {
+ const tail = this.readTextFileTail(outputPath, BACKGROUND_FAILURE_LOG_TAIL_CHARS);
+ if (!tail || !tail.content) {
+ return null;
+ }
+ const prefix = tail.truncated ? `(${tail.totalBytes} bytes)...
+` : "";
+ return [
+ ``,
+ `${prefix}${tail.content}`,
+ ""
+ ].join("\n");
+ }
+ readTextFileTail(filePath, maxChars) {
+ try {
+ const stat = fs17.statSync(filePath);
+ if (!stat.isFile() || stat.size <= 0) {
+ return null;
+ }
+ const content = readTextFileWithMetadata(filePath).content;
+ return {
+ content: content.slice(-maxChars).trimEnd(),
+ totalBytes: stat.size,
+ truncated: content.length > maxChars
+ };
+ } catch {
+ return null;
+ }
+ }
+ formatBackgroundDuration(durationMs) {
+ if (durationMs < 1e3) {
+ return `${durationMs}ms`;
+ }
+ const seconds = Math.round(durationMs / 1e3);
+ if (seconds < 60) {
+ return `${seconds}s`;
+ }
+ const minutes = Math.floor(seconds / 60);
+ const remainingSeconds = seconds % 60;
+ return remainingSeconds > 0 ? `${minutes}m ${remainingSeconds}s` : `${minutes}m`;
+ }
+ removeSessionProcess(sessionId, processId) {
+ const now = (/* @__PURE__ */ new Date()).toISOString();
+ const processControlKey = this.getProcessControlKey(sessionId, processId);
+ this.processTimeoutControls.delete(processControlKey);
+ this.liveProcessKeys.delete(processControlKey);
+ this.updateSessionEntry(sessionId, (entry) => {
+ const processes = new Map(entry.processes ?? []);
+ processes.delete(String(processId));
+ return {
+ ...entry,
+ processes: processes.size > 0 ? processes : null,
+ updateTime: now
+ };
+ });
+ }
+ setSessionProcessTimeoutControl(sessionId, processId, control) {
+ const key = this.getProcessControlKey(sessionId, processId);
+ if (!control) {
+ this.processTimeoutControls.delete(key);
+ return;
+ }
+ this.processTimeoutControls.set(key, control);
+ this.updateSessionProcessTimeout(sessionId, processId, control.getInfo());
+ }
+ updateSessionProcessTimeout(sessionId, processId, info) {
+ const now = (/* @__PURE__ */ new Date()).toISOString();
+ this.updateSessionEntry(sessionId, (entry) => {
+ const processes = new Map(entry.processes ?? []);
+ const pid = String(processId);
+ const processInfo = processes.get(pid);
+ if (!processInfo) {
+ return entry;
+ }
+ processes.set(pid, {
+ ...processInfo,
+ timeoutMs: info.timeoutMs,
+ deadlineAt: new Date(info.deadlineAtMs).toISOString(),
+ timedOut: info.timedOut
+ });
+ return {
+ ...entry,
+ processes,
+ updateTime: now
+ };
+ });
+ }
+ buildBashTimeoutAdjustment(processId, info) {
+ return {
+ processId,
+ timeoutMs: info.timeoutMs,
+ deadlineAt: new Date(info.deadlineAtMs).toISOString(),
+ timedOut: info.timedOut
+ };
+ }
+ getProcessControlKey(sessionId, processId) {
+ return `${sessionId}:${String(processId)}`;
+ }
+ killLiveProcesses() {
+ for (const processControlKey of Array.from(this.liveProcessKeys)) {
+ const processId = this.getProcessIdFromControlKey(processControlKey);
+ if (processId === null) {
+ this.liveProcessKeys.delete(processControlKey);
+ continue;
+ }
+ this.killTrackedProcess(processControlKey, processId);
+ }
+ }
+ killTrackedProcess(processControlKey, processId) {
+ const killedGroup = killProcessTree(processId, "SIGKILL");
+ if (!killedGroup) {
+ try {
+ process.kill(processId, "SIGKILL");
+ } catch {
+ }
+ }
+ this.processTimeoutControls.delete(processControlKey);
+ this.liveProcessKeys.delete(processControlKey);
+ }
+ getProcessIdFromControlKey(processControlKey) {
+ const separatorIndex = processControlKey.lastIndexOf(":");
+ const rawProcessId = separatorIndex >= 0 ? processControlKey.slice(separatorIndex + 1) : processControlKey;
+ const processId = Number(rawProcessId);
+ return Number.isInteger(processId) && processId > 0 ? processId : null;
+ }
+ getProcessIds(processes) {
+ if (!processes) {
+ return [];
+ }
+ const ids = [];
+ for (const pid of processes.keys()) {
+ const parsed = Number(pid);
+ if (Number.isInteger(parsed) && parsed > 0) {
+ ids.push(parsed);
+ }
+ }
+ return ids;
+ }
+ normalizeSessionEntry(entry) {
+ const value = entry && typeof entry === "object" ? entry : {};
+ return {
+ id: typeof value.id === "string" ? value.id : crypto3.randomUUID(),
+ summary: typeof value.summary === "string" ? value.summary : null,
+ assistantReply: typeof value.assistantReply === "string" ? value.assistantReply : null,
+ assistantThinking: typeof value.assistantThinking === "string" ? value.assistantThinking : null,
+ assistantRefusal: typeof value.assistantRefusal === "string" ? value.assistantRefusal : null,
+ toolCalls: Array.isArray(value.toolCalls) ? value.toolCalls : null,
+ status: this.normalizeSessionStatus(value.status),
+ failReason: typeof value.failReason === "string" ? value.failReason : null,
+ usage: value.usage ?? null,
+ usagePerModel: this.normalizeUsagePerModel(value),
+ activeTokens: typeof value.activeTokens === "number" ? value.activeTokens : 0,
+ createTime: typeof value.createTime === "string" ? value.createTime : (/* @__PURE__ */ new Date()).toISOString(),
+ updateTime: typeof value.updateTime === "string" ? value.updateTime : (/* @__PURE__ */ new Date()).toISOString(),
+ processes: this.deserializeProcesses(value.processes),
+ askPermissions: normalizeAskPermissions(value.askPermissions)
+ };
+ }
+ normalizeSessionStatus(status) {
+ if (status === "failed" || status === "pending" || status === "processing" || status === "waiting_for_user" || status === "completed" || status === "interrupted" || status === "ask_permission" || status === "permission_denied") {
+ return status;
+ }
+ return "pending";
+ }
+ normalizeUsagePerModel(entry) {
+ if (!Object.prototype.hasOwnProperty.call(entry, "usagePerModel")) {
+ return null;
+ }
+ if (!isUsageRecord(entry.usagePerModel)) {
+ return null;
+ }
+ const usagePerModel = {};
+ for (const [model, usage2] of Object.entries(entry.usagePerModel)) {
+ if (!model || !isUsageRecord(usage2)) {
+ continue;
+ }
+ usagePerModel[model] = usage2;
+ }
+ return usagePerModel;
+ }
+ deserializeProcesses(value) {
+ if (!value || typeof value !== "object") {
+ return null;
+ }
+ const processes = /* @__PURE__ */ new Map();
+ for (const [pid, entry] of Object.entries(value)) {
+ if (!pid) {
+ continue;
+ }
+ if (typeof entry === "string") {
+ processes.set(pid, { startTime: entry, command: "Running process..." });
+ } else if (typeof entry === "object" && entry !== null) {
+ const obj = entry;
+ const startTime = typeof obj.startTime === "string" ? obj.startTime : (/* @__PURE__ */ new Date()).toISOString();
+ const command2 = typeof obj.command === "string" ? obj.command : "Running process...";
+ processes.set(pid, {
+ startTime,
+ command: command2,
+ timeoutMs: typeof obj.timeoutMs === "number" ? obj.timeoutMs : void 0,
+ deadlineAt: typeof obj.deadlineAt === "string" ? obj.deadlineAt : void 0,
+ timedOut: typeof obj.timedOut === "boolean" ? obj.timedOut : void 0
+ });
+ }
+ }
+ return processes.size > 0 ? processes : null;
+ }
+ serializeProcesses(processes) {
+ if (!processes || processes.size === 0) {
+ return null;
+ }
+ const serialized = {};
+ for (const [pid, entry] of processes.entries()) {
+ serialized[pid] = entry;
+ }
+ return serialized;
+ }
+};
+
+// packages/core/src/common/openai-client.ts
+init_esbuild_shims();
+import * as fs18 from "fs";
+import * as os10 from "os";
+import * as path16 from "path";
+
+// node_modules/openai/index.mjs
+init_esbuild_shims();
+
+// node_modules/openai/client.mjs
+init_esbuild_shims();
+
+// node_modules/openai/internal/tslib.mjs
+init_esbuild_shims();
+function __classPrivateFieldSet(receiver, state, value, kind, f) {
+ if (kind === "m")
+ throw new TypeError("Private method is not writable");
+ if (kind === "a" && !f)
+ throw new TypeError("Private accessor was defined without a setter");
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
+ throw new TypeError("Cannot write private member to an object whose class did not declare it");
+ return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
+}
+__name(__classPrivateFieldSet, "__classPrivateFieldSet");
+function __classPrivateFieldGet(receiver, state, kind, f) {
+ if (kind === "a" && !f)
+ throw new TypeError("Private accessor was defined without a getter");
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
+ throw new TypeError("Cannot read private member from an object whose class did not declare it");
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
+}
+__name(__classPrivateFieldGet, "__classPrivateFieldGet");
+
+// node_modules/openai/internal/utils/uuid.mjs
+init_esbuild_shims();
+var uuid42 = /* @__PURE__ */ __name(function() {
+ const { crypto: crypto4 } = globalThis;
+ if (crypto4?.randomUUID) {
+ uuid42 = crypto4.randomUUID.bind(crypto4);
+ return crypto4.randomUUID();
+ }
+ const u8 = new Uint8Array(1);
+ const randomByte = crypto4 ? () => crypto4.getRandomValues(u8)[0] : () => Math.random() * 255 & 255;
+ return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (+c ^ randomByte() & 15 >> +c / 4).toString(16));
+}, "uuid4");
+
+// node_modules/openai/internal/utils/values.mjs
+init_esbuild_shims();
+
+// node_modules/openai/core/error.mjs
+init_esbuild_shims();
+
+// node_modules/openai/internal/errors.mjs
+init_esbuild_shims();
+function isAbortError(err) {
+ return typeof err === "object" && err !== null && // Spec-compliant fetch implementations
+ ("name" in err && err.name === "AbortError" || // Expo fetch
+ "message" in err && String(err.message).includes("FetchRequestCanceledException"));
+}
+__name(isAbortError, "isAbortError");
+var castToError = /* @__PURE__ */ __name((err) => {
+ if (err instanceof Error)
+ return err;
+ if (typeof err === "object" && err !== null) {
+ try {
+ if (Object.prototype.toString.call(err) === "[object Error]") {
+ const error51 = new Error(err.message, err.cause ? { cause: err.cause } : {});
+ if (err.stack)
+ error51.stack = err.stack;
+ if (err.cause && !error51.cause)
+ error51.cause = err.cause;
+ if (err.name)
+ error51.name = err.name;
+ return error51;
+ }
+ } catch {
+ }
+ try {
+ return new Error(JSON.stringify(err));
+ } catch {
+ }
+ }
+ return new Error(err);
+}, "castToError");
+
+// node_modules/openai/core/error.mjs
+var OpenAIError = class extends Error {
+ static {
+ __name(this, "OpenAIError");
+ }
+};
+var APIError = class _APIError extends OpenAIError {
+ static {
+ __name(this, "APIError");
+ }
+ constructor(status, error51, message, headers) {
+ super(`${_APIError.makeMessage(status, error51, message)}`);
+ this.status = status;
+ this.headers = headers;
+ this.requestID = headers?.get("x-request-id");
+ this.error = error51;
+ const data = error51;
+ this.code = data?.["code"];
+ this.param = data?.["param"];
+ this.type = data?.["type"];
+ }
+ static makeMessage(status, error51, message) {
+ const msg = error51?.message ? typeof error51.message === "string" ? error51.message : JSON.stringify(error51.message) : error51 ? JSON.stringify(error51) : message;
+ if (status && msg) {
+ return `${status} ${msg}`;
+ }
+ if (status) {
+ return `${status} status code (no body)`;
+ }
+ if (msg) {
+ return msg;
+ }
+ return "(no status code or body)";
+ }
+ static generate(status, errorResponse, message, headers) {
+ if (!status || !headers) {
+ return new APIConnectionError({ message, cause: castToError(errorResponse) });
+ }
+ const error51 = errorResponse?.["error"];
+ if (status === 400) {
+ return new BadRequestError(status, error51, message, headers);
+ }
+ if (status === 401) {
+ return new AuthenticationError(status, error51, message, headers);
+ }
+ if (status === 403) {
+ return new PermissionDeniedError(status, error51, message, headers);
+ }
+ if (status === 404) {
+ return new NotFoundError(status, error51, message, headers);
+ }
+ if (status === 409) {
+ return new ConflictError(status, error51, message, headers);
+ }
+ if (status === 422) {
+ return new UnprocessableEntityError(status, error51, message, headers);
+ }
+ if (status === 429) {
+ return new RateLimitError(status, error51, message, headers);
+ }
+ if (status >= 500) {
+ return new InternalServerError(status, error51, message, headers);
+ }
+ return new _APIError(status, error51, message, headers);
+ }
+};
+var APIUserAbortError = class extends APIError {
+ static {
+ __name(this, "APIUserAbortError");
+ }
+ constructor({ message } = {}) {
+ super(void 0, void 0, message || "Request was aborted.", void 0);
+ }
+};
+var APIConnectionError = class extends APIError {
+ static {
+ __name(this, "APIConnectionError");
+ }
+ constructor({ message, cause }) {
+ super(void 0, void 0, message || "Connection error.", void 0);
+ if (cause)
+ this.cause = cause;
+ }
+};
+var APIConnectionTimeoutError = class extends APIConnectionError {
+ static {
+ __name(this, "APIConnectionTimeoutError");
+ }
+ constructor({ message } = {}) {
+ super({ message: message ?? "Request timed out." });
+ }
+};
+var BadRequestError = class extends APIError {
+ static {
+ __name(this, "BadRequestError");
+ }
+};
+var AuthenticationError = class extends APIError {
+ static {
+ __name(this, "AuthenticationError");
+ }
+};
+var PermissionDeniedError = class extends APIError {
+ static {
+ __name(this, "PermissionDeniedError");
+ }
+};
+var NotFoundError = class extends APIError {
+ static {
+ __name(this, "NotFoundError");
+ }
+};
+var ConflictError = class extends APIError {
+ static {
+ __name(this, "ConflictError");
+ }
+};
+var UnprocessableEntityError = class extends APIError {
+ static {
+ __name(this, "UnprocessableEntityError");
+ }
+};
+var RateLimitError = class extends APIError {
+ static {
+ __name(this, "RateLimitError");
+ }
+};
+var InternalServerError = class extends APIError {
+ static {
+ __name(this, "InternalServerError");
+ }
+};
+var LengthFinishReasonError = class extends OpenAIError {
+ static {
+ __name(this, "LengthFinishReasonError");
+ }
+ constructor() {
+ super(`Could not parse response content as the length limit was reached`);
+ }
+};
+var ContentFilterFinishReasonError = class extends OpenAIError {
+ static {
+ __name(this, "ContentFilterFinishReasonError");
+ }
+ constructor() {
+ super(`Could not parse response content as the request was rejected by the content filter`);
+ }
+};
+var InvalidWebhookSignatureError = class extends Error {
+ static {
+ __name(this, "InvalidWebhookSignatureError");
+ }
+ constructor(message) {
+ super(message);
+ }
+};
+var OAuthError = class extends APIError {
+ static {
+ __name(this, "OAuthError");
+ }
+ constructor(status, error51, headers) {
+ let finalMessage = "OAuth2 authentication error";
+ let error_code = void 0;
+ if (error51 && typeof error51 === "object") {
+ const errorData = error51;
+ error_code = errorData["error"];
+ const description = errorData["error_description"];
+ if (description && typeof description === "string") {
+ finalMessage = description;
+ } else if (error_code) {
+ finalMessage = error_code;
+ }
+ }
+ super(status, error51, finalMessage, headers);
+ this.error_code = error_code;
+ }
+};
+var SubjectTokenProviderError = class extends OpenAIError {
+ static {
+ __name(this, "SubjectTokenProviderError");
+ }
+ constructor(message, provider, cause) {
+ super(message);
+ this.provider = provider;
+ this.cause = cause;
+ }
+};
+
+// node_modules/openai/internal/utils/values.mjs
+var startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;
+var isAbsoluteURL = /* @__PURE__ */ __name((url2) => {
+ return startsWithSchemeRegexp.test(url2);
+}, "isAbsoluteURL");
+var isArray = /* @__PURE__ */ __name((val) => (isArray = Array.isArray, isArray(val)), "isArray");
+var isReadonlyArray = isArray;
+function maybeObj(x) {
+ if (typeof x !== "object") {
+ return {};
+ }
+ return x ?? {};
+}
+__name(maybeObj, "maybeObj");
+function isEmptyObj(obj) {
+ if (!obj)
+ return true;
+ for (const _k in obj)
+ return false;
+ return true;
+}
+__name(isEmptyObj, "isEmptyObj");
+function hasOwn2(obj, key) {
+ return Object.prototype.hasOwnProperty.call(obj, key);
+}
+__name(hasOwn2, "hasOwn");
+function isObj(obj) {
+ return obj != null && typeof obj === "object" && !Array.isArray(obj);
+}
+__name(isObj, "isObj");
+var validatePositiveInteger = /* @__PURE__ */ __name((name, n) => {
+ if (typeof n !== "number" || !Number.isInteger(n)) {
+ throw new OpenAIError(`${name} must be an integer`);
+ }
+ if (n < 0) {
+ throw new OpenAIError(`${name} must be a positive integer`);
+ }
+ return n;
+}, "validatePositiveInteger");
+var safeJSON = /* @__PURE__ */ __name((text) => {
+ try {
+ return JSON.parse(text);
+ } catch (err) {
+ return void 0;
+ }
+}, "safeJSON");
+
+// node_modules/openai/internal/utils/sleep.mjs
+init_esbuild_shims();
+var sleep = /* @__PURE__ */ __name((ms) => new Promise((resolve16) => setTimeout(resolve16, ms)), "sleep");
+
+// node_modules/openai/internal/detect-platform.mjs
+init_esbuild_shims();
+
+// node_modules/openai/version.mjs
+init_esbuild_shims();
+var VERSION = "6.44.0";
+
+// node_modules/openai/internal/detect-platform.mjs
+var isRunningInBrowser = /* @__PURE__ */ __name(() => {
+ return (
+ // @ts-ignore
+ typeof window !== "undefined" && // @ts-ignore
+ typeof window.document !== "undefined" && // @ts-ignore
+ typeof navigator !== "undefined"
+ );
+}, "isRunningInBrowser");
+function getDetectedPlatform() {
+ if (typeof Deno !== "undefined" && Deno.build != null) {
+ return "deno";
+ }
+ if (typeof EdgeRuntime !== "undefined") {
+ return "edge";
+ }
+ if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") {
+ return "node";
+ }
+ return "unknown";
+}
+__name(getDetectedPlatform, "getDetectedPlatform");
+var getPlatformProperties = /* @__PURE__ */ __name(() => {
+ const detectedPlatform = getDetectedPlatform();
+ if (detectedPlatform === "deno") {
+ return {
+ "X-Stainless-Lang": "js",
+ "X-Stainless-Package-Version": VERSION,
+ "X-Stainless-OS": normalizePlatform(Deno.build.os),
+ "X-Stainless-Arch": normalizeArch(Deno.build.arch),
+ "X-Stainless-Runtime": "deno",
+ "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown"
+ };
+ }
+ if (typeof EdgeRuntime !== "undefined") {
+ return {
+ "X-Stainless-Lang": "js",
+ "X-Stainless-Package-Version": VERSION,
+ "X-Stainless-OS": "Unknown",
+ "X-Stainless-Arch": `other:${EdgeRuntime}`,
+ "X-Stainless-Runtime": "edge",
+ "X-Stainless-Runtime-Version": globalThis.process.version
+ };
+ }
+ if (detectedPlatform === "node") {
+ return {
+ "X-Stainless-Lang": "js",
+ "X-Stainless-Package-Version": VERSION,
+ "X-Stainless-OS": normalizePlatform(globalThis.process.platform ?? "unknown"),
+ "X-Stainless-Arch": normalizeArch(globalThis.process.arch ?? "unknown"),
+ "X-Stainless-Runtime": "node",
+ "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown"
+ };
+ }
+ const browserInfo = getBrowserInfo();
+ if (browserInfo) {
+ return {
+ "X-Stainless-Lang": "js",
+ "X-Stainless-Package-Version": VERSION,
+ "X-Stainless-OS": "Unknown",
+ "X-Stainless-Arch": "unknown",
+ "X-Stainless-Runtime": `browser:${browserInfo.browser}`,
+ "X-Stainless-Runtime-Version": browserInfo.version
+ };
+ }
+ return {
+ "X-Stainless-Lang": "js",
+ "X-Stainless-Package-Version": VERSION,
+ "X-Stainless-OS": "Unknown",
+ "X-Stainless-Arch": "unknown",
+ "X-Stainless-Runtime": "unknown",
+ "X-Stainless-Runtime-Version": "unknown"
+ };
+}, "getPlatformProperties");
+function getBrowserInfo() {
+ if (typeof navigator === "undefined" || !navigator) {
+ return null;
+ }
+ const browserPatterns = [
+ { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
+ { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
+ { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
+ { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
+ { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
+ { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }
+ ];
+ for (const { key, pattern } of browserPatterns) {
+ const match = pattern.exec(navigator.userAgent);
+ if (match) {
+ const major = match[1] || 0;
+ const minor = match[2] || 0;
+ const patch = match[3] || 0;
+ return { browser: key, version: `${major}.${minor}.${patch}` };
+ }
+ }
+ return null;
+}
+__name(getBrowserInfo, "getBrowserInfo");
+var normalizeArch = /* @__PURE__ */ __name((arch2) => {
+ if (arch2 === "x32")
+ return "x32";
+ if (arch2 === "x86_64" || arch2 === "x64")
+ return "x64";
+ if (arch2 === "arm")
+ return "arm";
+ if (arch2 === "aarch64" || arch2 === "arm64")
+ return "arm64";
+ if (arch2)
+ return `other:${arch2}`;
+ return "unknown";
+}, "normalizeArch");
+var normalizePlatform = /* @__PURE__ */ __name((platform2) => {
+ platform2 = platform2.toLowerCase();
+ if (platform2.includes("ios"))
+ return "iOS";
+ if (platform2 === "android")
+ return "Android";
+ if (platform2 === "darwin")
+ return "MacOS";
+ if (platform2 === "win32")
+ return "Windows";
+ if (platform2 === "freebsd")
+ return "FreeBSD";
+ if (platform2 === "openbsd")
+ return "OpenBSD";
+ if (platform2 === "linux")
+ return "Linux";
+ if (platform2)
+ return `Other:${platform2}`;
+ return "Unknown";
+}, "normalizePlatform");
+var _platformHeaders;
+var getPlatformHeaders = /* @__PURE__ */ __name(() => {
+ return _platformHeaders ?? (_platformHeaders = getPlatformProperties());
+}, "getPlatformHeaders");
+
+// node_modules/openai/internal/shims.mjs
+init_esbuild_shims();
+function getDefaultFetch() {
+ if (typeof fetch !== "undefined") {
+ return fetch;
+ }
+ throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`");
+}
+__name(getDefaultFetch, "getDefaultFetch");
+function makeReadableStream(...args) {
+ const ReadableStream2 = globalThis.ReadableStream;
+ if (typeof ReadableStream2 === "undefined") {
+ throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");
+ }
+ return new ReadableStream2(...args);
+}
+__name(makeReadableStream, "makeReadableStream");
+function ReadableStreamFrom(iterable) {
+ let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
+ return makeReadableStream({
+ start() {
+ },
+ async pull(controller) {
+ const { done, value } = await iter.next();
+ if (done) {
+ controller.close();
+ } else {
+ controller.enqueue(value);
+ }
+ },
+ async cancel() {
+ await iter.return?.();
+ }
+ });
+}
+__name(ReadableStreamFrom, "ReadableStreamFrom");
+function ReadableStreamToAsyncIterable(stream) {
+ if (stream[Symbol.asyncIterator])
+ return stream;
+ const reader = stream.getReader();
+ return {
+ async next() {
+ try {
+ const result = await reader.read();
+ if (result?.done)
+ reader.releaseLock();
+ return result;
+ } catch (e) {
+ reader.releaseLock();
+ throw e;
+ }
+ },
+ async return() {
+ const cancelPromise = reader.cancel();
+ reader.releaseLock();
+ await cancelPromise;
+ return { done: true, value: void 0 };
+ },
+ [Symbol.asyncIterator]() {
+ return this;
+ }
+ };
+}
+__name(ReadableStreamToAsyncIterable, "ReadableStreamToAsyncIterable");
+async function CancelReadableStream(stream) {
+ if (stream === null || typeof stream !== "object")
+ return;
+ if (stream[Symbol.asyncIterator]) {
+ await stream[Symbol.asyncIterator]().return?.();
+ return;
+ }
+ const reader = stream.getReader();
+ const cancelPromise = reader.cancel();
+ reader.releaseLock();
+ await cancelPromise;
+}
+__name(CancelReadableStream, "CancelReadableStream");
+
+// node_modules/openai/internal/request-options.mjs
+init_esbuild_shims();
+var FallbackEncoder = /* @__PURE__ */ __name(({ headers, body }) => {
+ return {
+ bodyHeaders: {
+ "content-type": "application/json"
+ },
+ body: JSON.stringify(body)
+ };
+}, "FallbackEncoder");
+
+// node_modules/openai/internal/utils/query.mjs
+init_esbuild_shims();
+
+// node_modules/openai/internal/qs/stringify.mjs
+init_esbuild_shims();
+
+// node_modules/openai/internal/qs/utils.mjs
+init_esbuild_shims();
+
+// node_modules/openai/internal/qs/formats.mjs
+init_esbuild_shims();
+var default_format = "RFC3986";
+var default_formatter = /* @__PURE__ */ __name((v) => String(v), "default_formatter");
+var formatters = {
+ RFC1738: /* @__PURE__ */ __name((v) => String(v).replace(/%20/g, "+"), "RFC1738"),
+ RFC3986: default_formatter
+};
+var RFC1738 = "RFC1738";
+
+// node_modules/openai/internal/qs/utils.mjs
+var has = /* @__PURE__ */ __name((obj, key) => (has = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty), has(obj, key)), "has");
+var hex_table = /* @__PURE__ */ (() => {
+ const array2 = [];
+ for (let i = 0; i < 256; ++i) {
+ array2.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase());
+ }
+ return array2;
+})();
+var limit = 1024;
+var encode3 = /* @__PURE__ */ __name((str3, _defaultEncoder, charset, _kind, format3) => {
+ if (str3.length === 0) {
+ return str3;
+ }
+ let string4 = str3;
+ if (typeof str3 === "symbol") {
+ string4 = Symbol.prototype.toString.call(str3);
+ } else if (typeof str3 !== "string") {
+ string4 = String(str3);
+ }
+ if (charset === "iso-8859-1") {
+ return escape(string4).replace(/%u[0-9a-f]{4}/gi, function($0) {
+ return "%26%23" + parseInt($0.slice(2), 16) + "%3B";
+ });
+ }
+ let out = "";
+ for (let j = 0; j < string4.length; j += limit) {
+ const segment = string4.length >= limit ? string4.slice(j, j + limit) : string4;
+ const arr = [];
+ for (let i = 0; i < segment.length; ++i) {
+ let c = segment.charCodeAt(i);
+ if (c === 45 || // -
+ c === 46 || // .
+ c === 95 || // _
+ c === 126 || // ~
+ c >= 48 && c <= 57 || // 0-9
+ c >= 65 && c <= 90 || // a-z
+ c >= 97 && c <= 122 || // A-Z
+ format3 === RFC1738 && (c === 40 || c === 41)) {
+ arr[arr.length] = segment.charAt(i);
+ continue;
+ }
+ if (c < 128) {
+ arr[arr.length] = hex_table[c];
+ continue;
+ }
+ if (c < 2048) {
+ arr[arr.length] = hex_table[192 | c >> 6] + hex_table[128 | c & 63];
+ continue;
+ }
+ if (c < 55296 || c >= 57344) {
+ arr[arr.length] = hex_table[224 | c >> 12] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63];
+ continue;
+ }
+ i += 1;
+ c = 65536 + ((c & 1023) << 10 | segment.charCodeAt(i) & 1023);
+ arr[arr.length] = hex_table[240 | c >> 18] + hex_table[128 | c >> 12 & 63] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63];
+ }
+ out += arr.join("");
+ }
+ return out;
+}, "encode");
+function is_buffer(obj) {
+ if (!obj || typeof obj !== "object") {
+ return false;
+ }
+ return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
+}
+__name(is_buffer, "is_buffer");
+function maybe_map(val, fn) {
+ if (isArray(val)) {
+ const mapped = [];
+ for (let i = 0; i < val.length; i += 1) {
+ mapped.push(fn(val[i]));
+ }
+ return mapped;
+ }
+ return fn(val);
+}
+__name(maybe_map, "maybe_map");
+
+// node_modules/openai/internal/qs/stringify.mjs
+var array_prefix_generators = {
+ brackets(prefix) {
+ return String(prefix) + "[]";
+ },
+ comma: "comma",
+ indices(prefix, key) {
+ return String(prefix) + "[" + key + "]";
+ },
+ repeat(prefix) {
+ return String(prefix);
+ }
+};
+var push_to_array = /* @__PURE__ */ __name(function(arr, value_or_array) {
+ Array.prototype.push.apply(arr, isArray(value_or_array) ? value_or_array : [value_or_array]);
+}, "push_to_array");
+var toISOString;
+var defaults = {
+ addQueryPrefix: false,
+ allowDots: false,
+ allowEmptyArrays: false,
+ arrayFormat: "indices",
+ charset: "utf-8",
+ charsetSentinel: false,
+ delimiter: "&",
+ encode: true,
+ encodeDotInKeys: false,
+ encoder: encode3,
+ encodeValuesOnly: false,
+ format: default_format,
+ formatter: default_formatter,
+ /** @deprecated */
+ indices: false,
+ serializeDate(date5) {
+ return (toISOString ?? (toISOString = Function.prototype.call.bind(Date.prototype.toISOString)))(date5);
+ },
+ skipNulls: false,
+ strictNullHandling: false
+};
+function is_non_nullish_primitive(v) {
+ return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint";
+}
+__name(is_non_nullish_primitive, "is_non_nullish_primitive");
+var sentinel = {};
+function inner_stringify(object2, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format3, formatter, encodeValuesOnly, charset, sideChannel) {
+ let obj = object2;
+ let tmp_sc = sideChannel;
+ let step = 0;
+ let find_flag = false;
+ while ((tmp_sc = tmp_sc.get(sentinel)) !== void 0 && !find_flag) {
+ const pos = tmp_sc.get(object2);
+ step += 1;
+ if (typeof pos !== "undefined") {
+ if (pos === step) {
+ throw new RangeError("Cyclic object value");
+ } else {
+ find_flag = true;
+ }
+ }
+ if (typeof tmp_sc.get(sentinel) === "undefined") {
+ step = 0;
+ }
+ }
+ if (typeof filter === "function") {
+ obj = filter(prefix, obj);
+ } else if (obj instanceof Date) {
+ obj = serializeDate?.(obj);
+ } else if (generateArrayPrefix === "comma" && isArray(obj)) {
+ obj = maybe_map(obj, function(value) {
+ if (value instanceof Date) {
+ return serializeDate?.(value);
+ }
+ return value;
+ });
+ }
+ if (obj === null) {
+ if (strictNullHandling) {
+ return encoder && !encodeValuesOnly ? (
+ // @ts-expect-error
+ encoder(prefix, defaults.encoder, charset, "key", format3)
+ ) : prefix;
+ }
+ obj = "";
+ }
+ if (is_non_nullish_primitive(obj) || is_buffer(obj)) {
+ if (encoder) {
+ const key_value = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, "key", format3);
+ return [
+ formatter?.(key_value) + "=" + // @ts-expect-error
+ formatter?.(encoder(obj, defaults.encoder, charset, "value", format3))
+ ];
+ }
+ return [formatter?.(prefix) + "=" + formatter?.(String(obj))];
+ }
+ const values = [];
+ if (typeof obj === "undefined") {
+ return values;
+ }
+ let obj_keys;
+ if (generateArrayPrefix === "comma" && isArray(obj)) {
+ if (encodeValuesOnly && encoder) {
+ obj = maybe_map(obj, encoder);
+ }
+ obj_keys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }];
+ } else if (isArray(filter)) {
+ obj_keys = filter;
+ } else {
+ const keys = Object.keys(obj);
+ obj_keys = sort ? keys.sort(sort) : keys;
+ }
+ const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix);
+ const adjusted_prefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encoded_prefix + "[]" : encoded_prefix;
+ if (allowEmptyArrays && isArray(obj) && obj.length === 0) {
+ return adjusted_prefix + "[]";
+ }
+ for (let j = 0; j < obj_keys.length; ++j) {
+ const key = obj_keys[j];
+ const value = (
+ // @ts-ignore
+ typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key]
+ );
+ if (skipNulls && value === null) {
+ continue;
+ }
+ const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key;
+ const key_prefix = isArray(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix : adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]");
+ sideChannel.set(object2, step);
+ const valueSideChannel = /* @__PURE__ */ new WeakMap();
+ valueSideChannel.set(sentinel, sideChannel);
+ push_to_array(values, inner_stringify(
+ value,
+ key_prefix,
+ generateArrayPrefix,
+ commaRoundTrip,
+ allowEmptyArrays,
+ strictNullHandling,
+ skipNulls,
+ encodeDotInKeys,
+ // @ts-ignore
+ generateArrayPrefix === "comma" && encodeValuesOnly && isArray(obj) ? null : encoder,
+ filter,
+ sort,
+ allowDots,
+ serializeDate,
+ format3,
+ formatter,
+ encodeValuesOnly,
+ charset,
+ valueSideChannel
+ ));
+ }
+ return values;
+}
+__name(inner_stringify, "inner_stringify");
+function normalize_stringify_options(opts = defaults) {
+ if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") {
+ throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");
+ }
+ if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") {
+ throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");
+ }
+ if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") {
+ throw new TypeError("Encoder has to be a function.");
+ }
+ const charset = opts.charset || defaults.charset;
+ if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") {
+ throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");
+ }
+ let format3 = default_format;
+ if (typeof opts.format !== "undefined") {
+ if (!has(formatters, opts.format)) {
+ throw new TypeError("Unknown format option provided.");
+ }
+ format3 = opts.format;
+ }
+ const formatter = formatters[format3];
+ let filter = defaults.filter;
+ if (typeof opts.filter === "function" || isArray(opts.filter)) {
+ filter = opts.filter;
+ }
+ let arrayFormat;
+ if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) {
+ arrayFormat = opts.arrayFormat;
+ } else if ("indices" in opts) {
+ arrayFormat = opts.indices ? "indices" : "repeat";
+ } else {
+ arrayFormat = defaults.arrayFormat;
+ }
+ if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") {
+ throw new TypeError("`commaRoundTrip` must be a boolean, or absent");
+ }
+ const allowDots = typeof opts.allowDots === "undefined" ? !!opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots;
+ return {
+ addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults.addQueryPrefix,
+ // @ts-ignore
+ allowDots,
+ allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays,
+ arrayFormat,
+ charset,
+ charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel,
+ commaRoundTrip: !!opts.commaRoundTrip,
+ delimiter: typeof opts.delimiter === "undefined" ? defaults.delimiter : opts.delimiter,
+ encode: typeof opts.encode === "boolean" ? opts.encode : defaults.encode,
+ encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults.encodeDotInKeys,
+ encoder: typeof opts.encoder === "function" ? opts.encoder : defaults.encoder,
+ encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults.encodeValuesOnly,
+ filter,
+ format: format3,
+ formatter,
+ serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults.serializeDate,
+ skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults.skipNulls,
+ // @ts-ignore
+ sort: typeof opts.sort === "function" ? opts.sort : null,
+ strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling
+ };
+}
+__name(normalize_stringify_options, "normalize_stringify_options");
+function stringify(object2, opts = {}) {
+ let obj = object2;
+ const options2 = normalize_stringify_options(opts);
+ let obj_keys;
+ let filter;
+ if (typeof options2.filter === "function") {
+ filter = options2.filter;
+ obj = filter("", obj);
+ } else if (isArray(options2.filter)) {
+ filter = options2.filter;
+ obj_keys = filter;
+ }
+ const keys = [];
+ if (typeof obj !== "object" || obj === null) {
+ return "";
+ }
+ const generateArrayPrefix = array_prefix_generators[options2.arrayFormat];
+ const commaRoundTrip = generateArrayPrefix === "comma" && options2.commaRoundTrip;
+ if (!obj_keys) {
+ obj_keys = Object.keys(obj);
+ }
+ if (options2.sort) {
+ obj_keys.sort(options2.sort);
+ }
+ const sideChannel = /* @__PURE__ */ new WeakMap();
+ for (let i = 0; i < obj_keys.length; ++i) {
+ const key = obj_keys[i];
+ if (options2.skipNulls && obj[key] === null) {
+ continue;
+ }
+ push_to_array(keys, inner_stringify(
+ obj[key],
+ key,
+ // @ts-expect-error
+ generateArrayPrefix,
+ commaRoundTrip,
+ options2.allowEmptyArrays,
+ options2.strictNullHandling,
+ options2.skipNulls,
+ options2.encodeDotInKeys,
+ options2.encode ? options2.encoder : null,
+ options2.filter,
+ options2.sort,
+ options2.allowDots,
+ options2.serializeDate,
+ options2.format,
+ options2.formatter,
+ options2.encodeValuesOnly,
+ options2.charset,
+ sideChannel
+ ));
+ }
+ const joined = keys.join(options2.delimiter);
+ let prefix = options2.addQueryPrefix === true ? "?" : "";
+ if (options2.charsetSentinel) {
+ if (options2.charset === "iso-8859-1") {
+ prefix += "utf8=%26%2310003%3B&";
+ } else {
+ prefix += "utf8=%E2%9C%93&";
+ }
+ }
+ return joined.length > 0 ? prefix + joined : "";
+}
+__name(stringify, "stringify");
+
+// node_modules/openai/internal/utils/query.mjs
+function stringifyQuery(query) {
+ return stringify(query, { arrayFormat: "brackets" });
+}
+__name(stringifyQuery, "stringifyQuery");
+
+// node_modules/openai/core/pagination.mjs
+init_esbuild_shims();
+
+// node_modules/openai/internal/parse.mjs
+init_esbuild_shims();
+
+// node_modules/openai/core/streaming.mjs
+init_esbuild_shims();
+
+// node_modules/openai/internal/decoders/line.mjs
+init_esbuild_shims();
+
+// node_modules/openai/internal/utils/bytes.mjs
+init_esbuild_shims();
+function concatBytes(buffers) {
+ let length = 0;
+ for (const buffer of buffers) {
+ length += buffer.length;
+ }
+ const output = new Uint8Array(length);
+ let index = 0;
+ for (const buffer of buffers) {
+ output.set(buffer, index);
+ index += buffer.length;
+ }
+ return output;
+}
+__name(concatBytes, "concatBytes");
+var encodeUTF8_;
+function encodeUTF8(str3) {
+ let encoder;
+ return (encodeUTF8_ ?? (encoder = new globalThis.TextEncoder(), encodeUTF8_ = encoder.encode.bind(encoder)))(str3);
+}
+__name(encodeUTF8, "encodeUTF8");
+var decodeUTF8_;
+function decodeUTF8(bytes) {
+ let decoder;
+ return (decodeUTF8_ ?? (decoder = new globalThis.TextDecoder(), decodeUTF8_ = decoder.decode.bind(decoder)))(bytes);
+}
+__name(decodeUTF8, "decodeUTF8");
+
+// node_modules/openai/internal/decoders/line.mjs
+var _LineDecoder_buffer;
+var _LineDecoder_carriageReturnIndex;
+var LineDecoder = class {
+ static {
+ __name(this, "LineDecoder");
+ }
+ constructor() {
+ _LineDecoder_buffer.set(this, void 0);
+ _LineDecoder_carriageReturnIndex.set(this, void 0);
+ __classPrivateFieldSet(this, _LineDecoder_buffer, new Uint8Array(), "f");
+ __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f");
+ }
+ decode(chunk) {
+ if (chunk == null) {
+ return [];
+ }
+ const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF8(chunk) : chunk;
+ __classPrivateFieldSet(this, _LineDecoder_buffer, concatBytes([__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), binaryChunk]), "f");
+ const lines = [];
+ let patternIndex;
+ while ((patternIndex = findNewlineIndex(__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f"))) != null) {
+ if (patternIndex.carriage && __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") == null) {
+ __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, patternIndex.index, "f");
+ continue;
+ }
+ if (__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") != null && (patternIndex.index !== __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) {
+ lines.push(decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") - 1)));
+ __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f")), "f");
+ __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f");
+ continue;
+ }
+ const endIndex = __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding;
+ const line = decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, endIndex));
+ lines.push(line);
+ __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(patternIndex.index), "f");
+ __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f");
+ }
+ return lines;
+ }
+ flush() {
+ if (!__classPrivateFieldGet(this, _LineDecoder_buffer, "f").length) {
+ return [];
+ }
+ return this.decode("\n");
+ }
+};
+_LineDecoder_buffer = /* @__PURE__ */ new WeakMap(), _LineDecoder_carriageReturnIndex = /* @__PURE__ */ new WeakMap();
+LineDecoder.NEWLINE_CHARS = /* @__PURE__ */ new Set(["\n", "\r"]);
+LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
+function findNewlineIndex(buffer, startIndex) {
+ const newline = 10;
+ const carriage = 13;
+ for (let i = startIndex ?? 0; i < buffer.length; i++) {
+ if (buffer[i] === newline) {
+ return { preceding: i, index: i + 1, carriage: false };
+ }
+ if (buffer[i] === carriage) {
+ return { preceding: i, index: i + 1, carriage: true };
+ }
+ }
+ return null;
+}
+__name(findNewlineIndex, "findNewlineIndex");
+function findDoubleNewlineIndex(buffer) {
+ const newline = 10;
+ const carriage = 13;
+ for (let i = 0; i < buffer.length - 1; i++) {
+ if (buffer[i] === newline && buffer[i + 1] === newline) {
+ return i + 2;
+ }
+ if (buffer[i] === carriage && buffer[i + 1] === carriage) {
+ return i + 2;
+ }
+ if (buffer[i] === carriage && buffer[i + 1] === newline && i + 3 < buffer.length && buffer[i + 2] === carriage && buffer[i + 3] === newline) {
+ return i + 4;
+ }
+ }
+ return -1;
+}
+__name(findDoubleNewlineIndex, "findDoubleNewlineIndex");
+
+// node_modules/openai/internal/utils/log.mjs
+init_esbuild_shims();
+var levelNumbers = {
+ off: 0,
+ error: 200,
+ warn: 300,
+ info: 400,
+ debug: 500
+};
+var parseLogLevel = /* @__PURE__ */ __name((maybeLevel, sourceName, client) => {
+ if (!maybeLevel) {
+ return void 0;
+ }
+ if (hasOwn2(levelNumbers, maybeLevel)) {
+ return maybeLevel;
+ }
+ loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`);
+ return void 0;
+}, "parseLogLevel");
+function noop2() {
+}
+__name(noop2, "noop");
+function makeLogFn(fnLevel, logger, logLevel) {
+ if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) {
+ return noop2;
+ } else {
+ return logger[fnLevel].bind(logger);
+ }
+}
+__name(makeLogFn, "makeLogFn");
+var noopLogger = {
+ error: noop2,
+ warn: noop2,
+ info: noop2,
+ debug: noop2
+};
+var cachedLoggers = /* @__PURE__ */ new WeakMap();
+function loggerFor(client) {
+ const logger = client.logger;
+ const logLevel = client.logLevel ?? "off";
+ if (!logger) {
+ return noopLogger;
+ }
+ const cachedLogger = cachedLoggers.get(logger);
+ if (cachedLogger && cachedLogger[0] === logLevel) {
+ return cachedLogger[1];
+ }
+ const levelLogger = {
+ error: makeLogFn("error", logger, logLevel),
+ warn: makeLogFn("warn", logger, logLevel),
+ info: makeLogFn("info", logger, logLevel),
+ debug: makeLogFn("debug", logger, logLevel)
+ };
+ cachedLoggers.set(logger, [logLevel, levelLogger]);
+ return levelLogger;
+}
+__name(loggerFor, "loggerFor");
+var formatRequestDetails = /* @__PURE__ */ __name((details) => {
+ if (details.options) {
+ details.options = { ...details.options };
+ delete details.options["headers"];
+ }
+ if (details.headers) {
+ details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [
+ name,
+ name.toLowerCase() === "authorization" || name.toLowerCase() === "api-key" || name.toLowerCase() === "x-api-key" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value
+ ]));
+ }
+ if ("retryOfRequestLogID" in details) {
+ if (details.retryOfRequestLogID) {
+ details.retryOf = details.retryOfRequestLogID;
+ }
+ delete details.retryOfRequestLogID;
+ }
+ return details;
+}, "formatRequestDetails");
+
+// node_modules/openai/core/streaming.mjs
+var _Stream_client;
+var Stream2 = class _Stream {
+ static {
+ __name(this, "Stream");
+ }
+ constructor(iterator, controller, client) {
+ this.iterator = iterator;
+ _Stream_client.set(this, void 0);
+ this.controller = controller;
+ __classPrivateFieldSet(this, _Stream_client, client, "f");
+ }
+ static fromSSEResponse(response, controller, client, synthesizeEventData) {
+ let consumed = false;
+ const logger = client ? loggerFor(client) : console;
+ async function* iterator() {
+ if (consumed) {
+ throw new OpenAIError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
+ }
+ consumed = true;
+ let done = false;
+ try {
+ for await (const sse of _iterSSEMessages(response, controller)) {
+ if (done)
+ continue;
+ if (sse.data.startsWith("[DONE]")) {
+ done = true;
+ continue;
+ }
+ if (sse.event === null || !sse.event.startsWith("thread.")) {
+ let data;
+ try {
+ data = JSON.parse(sse.data);
+ } catch (e) {
+ logger.error(`Could not parse message into JSON:`, sse.data);
+ logger.error(`From chunk:`, sse.raw);
+ throw e;
+ }
+ if (data && data.error) {
+ throw new APIError(void 0, data.error, void 0, response.headers);
+ }
+ yield synthesizeEventData ? { event: sse.event, data } : data;
+ } else {
+ let data;
+ try {
+ data = JSON.parse(sse.data);
+ } catch (e) {
+ console.error(`Could not parse message into JSON:`, sse.data);
+ console.error(`From chunk:`, sse.raw);
+ throw e;
+ }
+ if (sse.event == "error") {
+ throw new APIError(void 0, data.error, data.message, void 0);
+ }
+ yield { event: sse.event, data };
+ }
+ }
+ done = true;
+ } catch (e) {
+ if (isAbortError(e))
+ return;
+ throw e;
+ } finally {
+ if (!done)
+ controller.abort();
+ }
+ }
+ __name(iterator, "iterator");
+ return new _Stream(iterator, controller, client);
+ }
+ /**
+ * Generates a Stream from a newline-separated ReadableStream
+ * where each item is a JSON value.
+ */
+ static fromReadableStream(readableStream, controller, client) {
+ let consumed = false;
+ async function* iterLines() {
+ const lineDecoder = new LineDecoder();
+ const iter = ReadableStreamToAsyncIterable(readableStream);
+ for await (const chunk of iter) {
+ for (const line of lineDecoder.decode(chunk)) {
+ yield line;
+ }
+ }
+ for (const line of lineDecoder.flush()) {
+ yield line;
+ }
+ }
+ __name(iterLines, "iterLines");
+ async function* iterator() {
+ if (consumed) {
+ throw new OpenAIError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
+ }
+ consumed = true;
+ let done = false;
+ try {
+ for await (const line of iterLines()) {
+ if (done)
+ continue;
+ if (line)
+ yield JSON.parse(line);
+ }
+ done = true;
+ } catch (e) {
+ if (isAbortError(e))
+ return;
+ throw e;
+ } finally {
+ if (!done)
+ controller.abort();
+ }
+ }
+ __name(iterator, "iterator");
+ return new _Stream(iterator, controller, client);
+ }
+ [(_Stream_client = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() {
+ return this.iterator();
+ }
+ /**
+ * Splits the stream into two streams which can be
+ * independently read from at different speeds.
+ */
+ tee() {
+ const left2 = [];
+ const right2 = [];
+ const iterator = this.iterator();
+ const teeIterator = /* @__PURE__ */ __name((queue) => {
+ return {
+ next: /* @__PURE__ */ __name(() => {
+ if (queue.length === 0) {
+ const result = iterator.next();
+ left2.push(result);
+ right2.push(result);
+ }
+ return queue.shift();
+ }, "next")
+ };
+ }, "teeIterator");
+ return [
+ new _Stream(() => teeIterator(left2), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")),
+ new _Stream(() => teeIterator(right2), this.controller, __classPrivateFieldGet(this, _Stream_client, "f"))
+ ];
+ }
+ /**
+ * Converts this stream to a newline-separated ReadableStream of
+ * JSON stringified values in the stream
+ * which can be turned back into a Stream with `Stream.fromReadableStream()`.
+ */
+ toReadableStream() {
+ const self2 = this;
+ let iter;
+ return makeReadableStream({
+ async start() {
+ iter = self2[Symbol.asyncIterator]();
+ },
+ async pull(ctrl) {
+ try {
+ const { value, done } = await iter.next();
+ if (done)
+ return ctrl.close();
+ const bytes = encodeUTF8(JSON.stringify(value) + "\n");
+ ctrl.enqueue(bytes);
+ } catch (err) {
+ ctrl.error(err);
+ }
+ },
+ async cancel() {
+ await iter.return?.();
+ }
+ });
+ }
+};
+async function* _iterSSEMessages(response, controller) {
+ if (!response.body) {
+ controller.abort();
+ if (typeof globalThis.navigator !== "undefined" && globalThis.navigator.product === "ReactNative") {
+ throw new OpenAIError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
+ }
+ throw new OpenAIError(`Attempted to iterate over a response with no body`);
+ }
+ const sseDecoder = new SSEDecoder();
+ const lineDecoder = new LineDecoder();
+ const iter = ReadableStreamToAsyncIterable(response.body);
+ for await (const sseChunk of iterSSEChunks(iter)) {
+ for (const line of lineDecoder.decode(sseChunk)) {
+ const sse = sseDecoder.decode(line);
+ if (sse)
+ yield sse;
+ }
+ }
+ for (const line of lineDecoder.flush()) {
+ const sse = sseDecoder.decode(line);
+ if (sse)
+ yield sse;
+ }
+}
+__name(_iterSSEMessages, "_iterSSEMessages");
+async function* iterSSEChunks(iterator) {
+ let data = new Uint8Array();
+ for await (const chunk of iterator) {
+ if (chunk == null) {
+ continue;
+ }
+ const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF8(chunk) : chunk;
+ let newData = new Uint8Array(data.length + binaryChunk.length);
+ newData.set(data);
+ newData.set(binaryChunk, data.length);
+ data = newData;
+ let patternIndex;
+ while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {
+ yield data.slice(0, patternIndex);
+ data = data.slice(patternIndex);
+ }
+ }
+ if (data.length > 0) {
+ yield data;
+ }
+}
+__name(iterSSEChunks, "iterSSEChunks");
+var SSEDecoder = class {
+ static {
+ __name(this, "SSEDecoder");
+ }
+ constructor() {
+ this.event = null;
+ this.data = [];
+ this.chunks = [];
+ }
+ decode(line) {
+ if (line.endsWith("\r")) {
+ line = line.substring(0, line.length - 1);
+ }
+ if (!line) {
+ if (!this.event && !this.data.length)
+ return null;
+ const sse = {
+ event: this.event,
+ data: this.data.join("\n"),
+ raw: this.chunks
+ };
+ this.event = null;
+ this.data = [];
+ this.chunks = [];
+ return sse;
+ }
+ this.chunks.push(line);
+ if (line.startsWith(":")) {
+ return null;
+ }
+ let [fieldname, _, value] = partition(line, ":");
+ if (value.startsWith(" ")) {
+ value = value.substring(1);
+ }
+ if (fieldname === "event") {
+ this.event = value;
+ } else if (fieldname === "data") {
+ this.data.push(value);
+ }
+ return null;
+ }
+};
+function partition(str3, delimiter) {
+ const index = str3.indexOf(delimiter);
+ if (index !== -1) {
+ return [str3.substring(0, index), delimiter, str3.substring(index + delimiter.length)];
+ }
+ return [str3, "", ""];
+}
+__name(partition, "partition");
+
+// node_modules/openai/internal/parse.mjs
+async function defaultParseResponse(client, props) {
+ const { response, requestLogID, retryOfRequestLogID, startTime } = props;
+ const body = await (async () => {
+ if (props.options.stream) {
+ loggerFor(client).debug("response", response.status, response.url, response.headers, response.body);
+ if (props.options.__streamClass) {
+ return props.options.__streamClass.fromSSEResponse(response, props.controller, client, props.options.__synthesizeEventData);
+ }
+ return Stream2.fromSSEResponse(response, props.controller, client, props.options.__synthesizeEventData);
+ }
+ if (response.status === 204) {
+ return null;
+ }
+ if (props.options.__binaryResponse) {
+ return response;
+ }
+ const contentType = response.headers.get("content-type");
+ const mediaType = contentType?.split(";")[0]?.trim();
+ const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json");
+ if (isJSON) {
+ const contentLength = response.headers.get("content-length");
+ if (contentLength === "0") {
+ return void 0;
+ }
+ const json2 = await response.json();
+ return addRequestID(json2, response);
+ }
+ const text = await response.text();
+ return text;
+ })();
+ loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({
+ retryOfRequestLogID,
+ url: response.url,
+ status: response.status,
+ body,
+ durationMs: Date.now() - startTime
+ }));
+ return body;
+}
+__name(defaultParseResponse, "defaultParseResponse");
+function addRequestID(value, response) {
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
+ return value;
+ }
+ return Object.defineProperty(value, "_request_id", {
+ value: response.headers.get("x-request-id"),
+ enumerable: false
+ });
+}
+__name(addRequestID, "addRequestID");
+
+// node_modules/openai/core/api-promise.mjs
+init_esbuild_shims();
+var _APIPromise_client;
+var APIPromise = class _APIPromise extends Promise {
+ static {
+ __name(this, "APIPromise");
+ }
+ constructor(client, responsePromise, parseResponse2 = defaultParseResponse) {
+ super((resolve16) => {
+ resolve16(null);
+ });
+ this.responsePromise = responsePromise;
+ this.parseResponse = parseResponse2;
+ _APIPromise_client.set(this, void 0);
+ __classPrivateFieldSet(this, _APIPromise_client, client, "f");
+ }
+ _thenUnwrap(transform2) {
+ return new _APIPromise(__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => addRequestID(transform2(await this.parseResponse(client, props), props), props.response));
+ }
+ /**
+ * Gets the raw `Response` instance instead of parsing the response
+ * data.
+ *
+ * If you want to parse the response body but still get the `Response`
+ * instance, you can use {@link withResponse()}.
+ *
+ * 👋 Getting the wrong TypeScript type for `Response`?
+ * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
+ * to your `tsconfig.json`.
+ */
+ asResponse() {
+ return this.responsePromise.then((p) => p.response);
+ }
+ /**
+ * Gets the parsed response data, the raw `Response` instance and the ID of the request,
+ * returned via the X-Request-ID header which is useful for debugging requests and reporting
+ * issues to OpenAI.
+ *
+ * If you just want to get the raw `Response` instance without parsing it,
+ * you can use {@link asResponse()}.
+ *
+ * 👋 Getting the wrong TypeScript type for `Response`?
+ * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
+ * to your `tsconfig.json`.
+ */
+ async withResponse() {
+ const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
+ return { data, response, request_id: response.headers.get("x-request-id") };
+ }
+ parse() {
+ if (!this.parsedPromise) {
+ this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, "f"), data));
+ }
+ return this.parsedPromise;
+ }
+ then(onfulfilled, onrejected) {
+ return this.parse().then(onfulfilled, onrejected);
+ }
+ catch(onrejected) {
+ return this.parse().catch(onrejected);
+ }
+ finally(onfinally) {
+ return this.parse().finally(onfinally);
+ }
+};
+_APIPromise_client = /* @__PURE__ */ new WeakMap();
+
+// node_modules/openai/core/pagination.mjs
+var _AbstractPage_client;
+var AbstractPage = class {
+ static {
+ __name(this, "AbstractPage");
+ }
+ constructor(client, response, body, options2) {
+ _AbstractPage_client.set(this, void 0);
+ __classPrivateFieldSet(this, _AbstractPage_client, client, "f");
+ this.options = options2;
+ this.response = response;
+ this.body = body;
+ }
+ hasNextPage() {
+ const items = this.getPaginatedItems();
+ if (!items.length)
+ return false;
+ return this.nextPageRequestOptions() != null;
+ }
+ async getNextPage() {
+ const nextOptions = this.nextPageRequestOptions();
+ if (!nextOptions) {
+ throw new OpenAIError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");
+ }
+ return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions);
+ }
+ async *iterPages() {
+ let page = this;
+ yield page;
+ while (page.hasNextPage()) {
+ page = await page.getNextPage();
+ yield page;
+ }
+ }
+ async *[(_AbstractPage_client = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() {
+ for await (const page of this.iterPages()) {
+ for (const item of page.getPaginatedItems()) {
+ yield item;
+ }
+ }
+ }
+};
+var PagePromise = class extends APIPromise {
+ static {
+ __name(this, "PagePromise");
+ }
+ constructor(client, request, Page2) {
+ super(client, request, async (client2, props) => new Page2(client2, props.response, await defaultParseResponse(client2, props), props.options));
+ }
+ /**
+ * Allow auto-paginating iteration on an unawaited list call, eg:
+ *
+ * for await (const item of client.items.list()) {
+ * console.log(item)
+ * }
+ */
+ async *[Symbol.asyncIterator]() {
+ const page = await this;
+ for await (const item of page) {
+ yield item;
+ }
+ }
+};
+var Page = class extends AbstractPage {
+ static {
+ __name(this, "Page");
+ }
+ constructor(client, response, body, options2) {
+ super(client, response, body, options2);
+ this.data = body.data || [];
+ this.object = body.object;
+ }
+ getPaginatedItems() {
+ return this.data ?? [];
+ }
+ nextPageRequestOptions() {
+ return null;
+ }
+};
+var CursorPage = class extends AbstractPage {
+ static {
+ __name(this, "CursorPage");
+ }
+ constructor(client, response, body, options2) {
+ super(client, response, body, options2);
+ this.data = body.data || [];
+ this.has_more = body.has_more || false;
+ }
+ getPaginatedItems() {
+ return this.data ?? [];
+ }
+ hasNextPage() {
+ if (this.has_more === false) {
+ return false;
+ }
+ return super.hasNextPage();
+ }
+ nextPageRequestOptions() {
+ const data = this.getPaginatedItems();
+ const id = data[data.length - 1]?.id;
+ if (!id) {
+ return null;
+ }
+ return {
+ ...this.options,
+ query: {
+ ...maybeObj(this.options.query),
+ after: id
+ }
+ };
+ }
+};
+var ConversationCursorPage = class extends AbstractPage {
+ static {
+ __name(this, "ConversationCursorPage");
+ }
+ constructor(client, response, body, options2) {
+ super(client, response, body, options2);
+ this.data = body.data || [];
+ this.has_more = body.has_more || false;
+ this.last_id = body.last_id || "";
+ }
+ getPaginatedItems() {
+ return this.data ?? [];
+ }
+ hasNextPage() {
+ if (this.has_more === false) {
+ return false;
+ }
+ return super.hasNextPage();
+ }
+ nextPageRequestOptions() {
+ const cursor = this.last_id;
+ if (!cursor) {
+ return null;
+ }
+ return {
+ ...this.options,
+ query: {
+ ...maybeObj(this.options.query),
+ after: cursor
+ }
+ };
+ }
+};
+var NextCursorPage = class extends AbstractPage {
+ static {
+ __name(this, "NextCursorPage");
+ }
+ constructor(client, response, body, options2) {
+ super(client, response, body, options2);
+ this.data = body.data || [];
+ this.has_more = body.has_more || false;
+ this.next = body.next || null;
+ }
+ getPaginatedItems() {
+ return this.data ?? [];
+ }
+ hasNextPage() {
+ if (this.has_more === false) {
+ return false;
+ }
+ return super.hasNextPage();
+ }
+ nextPageRequestOptions() {
+ const cursor = this.next;
+ if (!cursor) {
+ return null;
+ }
+ return {
+ ...this.options,
+ query: {
+ ...maybeObj(this.options.query),
+ after: cursor
+ }
+ };
+ }
+};
+
+// node_modules/openai/auth/workload-identity-auth.mjs
+init_esbuild_shims();
+var SUBJECT_TOKEN_TYPES = {
+ jwt: "urn:ietf:params:oauth:token-type:jwt",
+ id: "urn:ietf:params:oauth:token-type:id_token"
+};
+var TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange";
+var WorkloadIdentityAuth = class {
+ static {
+ __name(this, "WorkloadIdentityAuth");
+ }
+ constructor(config2, fetch2) {
+ this.cachedToken = null;
+ this.refreshPromise = null;
+ this.tokenExchangeUrl = "https://auth.openai.com/oauth/token";
+ this.config = config2;
+ this.fetch = fetch2 ?? getDefaultFetch();
+ }
+ async getToken() {
+ if (!this.cachedToken || this.isTokenExpired(this.cachedToken)) {
+ if (this.refreshPromise) {
+ return await this.refreshPromise;
+ }
+ this.refreshPromise = this.refreshToken();
+ try {
+ const token = await this.refreshPromise;
+ return token;
+ } finally {
+ this.refreshPromise = null;
+ }
+ }
+ if (this.needsRefresh(this.cachedToken) && !this.refreshPromise) {
+ this.refreshPromise = this.refreshToken().finally(() => {
+ this.refreshPromise = null;
+ });
+ }
+ return this.cachedToken.token;
+ }
+ async refreshToken() {
+ const subjectToken = await this.config.provider.getToken();
+ const body = {
+ grant_type: TOKEN_EXCHANGE_GRANT_TYPE,
+ subject_token: subjectToken,
+ subject_token_type: SUBJECT_TOKEN_TYPES[this.config.provider.tokenType],
+ identity_provider_id: this.config.identityProviderId,
+ service_account_id: this.config.serviceAccountId
+ };
+ if (this.config.clientId) {
+ body["client_id"] = this.config.clientId;
+ }
+ const response = await this.fetch(this.tokenExchangeUrl, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json"
+ },
+ body: JSON.stringify(body)
+ });
+ if (!response.ok) {
+ const errorText = await response.text();
+ let body2 = void 0;
+ try {
+ body2 = JSON.parse(errorText);
+ } catch {
+ }
+ if (response.status === 400 || response.status === 401 || response.status === 403) {
+ throw new OAuthError(response.status, body2, response.headers);
+ }
+ throw APIError.generate(response.status, body2, `Token exchange failed with status ${response.status}`, response.headers);
+ }
+ const tokenResponse = await response.json();
+ const expiresIn = tokenResponse.expires_in || 3600;
+ const expiresAt = Date.now() + expiresIn * 1e3;
+ this.cachedToken = {
+ token: tokenResponse.access_token,
+ expiresAt
+ };
+ return tokenResponse.access_token;
+ }
+ isTokenExpired(cachedToken) {
+ return Date.now() >= cachedToken.expiresAt;
+ }
+ needsRefresh(cachedToken) {
+ const bufferSeconds = this.config.refreshBufferSeconds ?? 1200;
+ const bufferMs = bufferSeconds * 1e3;
+ return Date.now() >= cachedToken.expiresAt - bufferMs;
+ }
+ invalidateToken() {
+ this.cachedToken = null;
+ this.refreshPromise = null;
+ }
+};
+
+// node_modules/openai/core/uploads.mjs
+init_esbuild_shims();
+
+// node_modules/openai/internal/to-file.mjs
+init_esbuild_shims();
+
+// node_modules/openai/internal/uploads.mjs
+init_esbuild_shims();
+var checkFileSupport = /* @__PURE__ */ __name(() => {
+ if (typeof File === "undefined") {
+ const { process: process18 } = globalThis;
+ const isOldNode = typeof process18?.versions?.node === "string" && parseInt(process18.versions.node.split(".")) < 20;
+ throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : ""));
+ }
+}, "checkFileSupport");
+function makeFile(fileBits, fileName, options2) {
+ checkFileSupport();
+ return new File(fileBits, fileName ?? "unknown_file", options2);
+}
+__name(makeFile, "makeFile");
+function getName(value) {
+ return (typeof value === "object" && value !== null && ("name" in value && value.name && String(value.name) || "url" in value && value.url && String(value.url) || "filename" in value && value.filename && String(value.filename) || "path" in value && value.path && String(value.path)) || "").split(/[\\/]/).pop() || void 0;
+}
+__name(getName, "getName");
+var isAsyncIterable = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function", "isAsyncIterable");
+var maybeMultipartFormRequestOptions = /* @__PURE__ */ __name(async (opts, fetch2) => {
+ if (!hasUploadableValue(opts.body))
+ return opts;
+ return { ...opts, body: await createForm(opts.body, fetch2) };
+}, "maybeMultipartFormRequestOptions");
+var multipartFormRequestOptions = /* @__PURE__ */ __name(async (opts, fetch2) => {
+ return { ...opts, body: await createForm(opts.body, fetch2) };
+}, "multipartFormRequestOptions");
+var supportsFormDataMap = /* @__PURE__ */ new WeakMap();
+function supportsFormData(fetchObject) {
+ const fetch2 = typeof fetchObject === "function" ? fetchObject : fetchObject.fetch;
+ const cached2 = supportsFormDataMap.get(fetch2);
+ if (cached2)
+ return cached2;
+ const promise2 = (async () => {
+ try {
+ const FetchResponse = "Response" in fetch2 ? fetch2.Response : (await fetch2("data:,")).constructor;
+ const data = new FormData();
+ if (data.toString() === await new FetchResponse(data).text()) {
+ return false;
+ }
+ return true;
+ } catch {
+ return true;
+ }
+ })();
+ supportsFormDataMap.set(fetch2, promise2);
+ return promise2;
+}
+__name(supportsFormData, "supportsFormData");
+var createForm = /* @__PURE__ */ __name(async (body, fetch2) => {
+ if (!await supportsFormData(fetch2)) {
+ throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");
+ }
+ const form = new FormData();
+ await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value)));
+ return form;
+}, "createForm");
+var isNamedBlob = /* @__PURE__ */ __name((value) => value instanceof Blob && "name" in value, "isNamedBlob");
+var isUploadable = /* @__PURE__ */ __name((value) => typeof value === "object" && value !== null && (value instanceof Response || isAsyncIterable(value) || isNamedBlob(value)), "isUploadable");
+var hasUploadableValue = /* @__PURE__ */ __name((value) => {
+ if (isUploadable(value))
+ return true;
+ if (Array.isArray(value))
+ return value.some(hasUploadableValue);
+ if (value && typeof value === "object") {
+ for (const k in value) {
+ if (hasUploadableValue(value[k]))
+ return true;
+ }
+ }
+ return false;
+}, "hasUploadableValue");
+var addFormValue = /* @__PURE__ */ __name(async (form, key, value) => {
+ if (value === void 0)
+ return;
+ if (value == null) {
+ throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);
+ }
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
+ form.append(key, String(value));
+ } else if (value instanceof Response) {
+ form.append(key, makeFile([await value.blob()], getName(value)));
+ } else if (isAsyncIterable(value)) {
+ form.append(key, makeFile([await new Response(ReadableStreamFrom(value)).blob()], getName(value)));
+ } else if (isNamedBlob(value)) {
+ form.append(key, value, getName(value));
+ } else if (Array.isArray(value)) {
+ await Promise.all(value.map((entry) => addFormValue(form, key + "[]", entry)));
+ } else if (typeof value === "object") {
+ await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop)));
+ } else {
+ throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);
+ }
+}, "addFormValue");
+
+// node_modules/openai/internal/to-file.mjs
+var isBlobLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function", "isBlobLike");
+var isFileLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value), "isFileLike");
+var isResponseLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function", "isResponseLike");
+async function toFile(value, name, options2) {
+ checkFileSupport();
+ value = await value;
+ if (isFileLike(value)) {
+ if (value instanceof File) {
+ return value;
+ }
+ return makeFile([await value.arrayBuffer()], value.name);
+ }
+ if (isResponseLike(value)) {
+ const blob = await value.blob();
+ name || (name = new URL(value.url).pathname.split(/[\\/]/).pop());
+ return makeFile(await getBytes(blob), name, options2);
+ }
+ const parts = await getBytes(value);
+ name || (name = getName(value));
+ if (!options2?.type) {
+ const type2 = parts.find((part) => typeof part === "object" && "type" in part && part.type);
+ if (typeof type2 === "string") {
+ options2 = { ...options2, type: type2 };
+ }
+ }
+ return makeFile(parts, name, options2);
+}
+__name(toFile, "toFile");
+async function getBytes(value) {
+ let parts = [];
+ if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
+ value instanceof ArrayBuffer) {
+ parts.push(value);
+ } else if (isBlobLike(value)) {
+ parts.push(value instanceof Blob ? value : await value.arrayBuffer());
+ } else if (isAsyncIterable(value)) {
+ for await (const chunk of value) {
+ parts.push(...await getBytes(chunk));
+ }
+ } else {
+ const constructor = value?.constructor?.name;
+ throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ""}${propsForError(value)}`);
+ }
+ return parts;
+}
+__name(getBytes, "getBytes");
+function propsForError(value) {
+ if (typeof value !== "object" || value === null)
+ return "";
+ const props = Object.getOwnPropertyNames(value);
+ return `; props: [${props.map((p) => `"${p}"`).join(", ")}]`;
+}
+__name(propsForError, "propsForError");
+
+// node_modules/openai/resources/index.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/chat/index.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/chat/chat.mjs
+init_esbuild_shims();
+
+// node_modules/openai/core/resource.mjs
+init_esbuild_shims();
+var APIResource = class {
+ static {
+ __name(this, "APIResource");
+ }
+ constructor(client) {
+ this._client = client;
+ }
+};
+
+// node_modules/openai/resources/chat/completions/completions.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/chat/completions/messages.mjs
+init_esbuild_shims();
+
+// node_modules/openai/internal/utils/path.mjs
+init_esbuild_shims();
+function encodeURIPath(str3) {
+ return str3.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);
+}
+__name(encodeURIPath, "encodeURIPath");
+var EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null));
+var createPathTagFunction = /* @__PURE__ */ __name((pathEncoder = encodeURIPath) => /* @__PURE__ */ __name(function path27(statics, ...params) {
+ if (statics.length === 1)
+ return statics[0];
+ let postPath = false;
+ const invalidSegments = [];
+ const path28 = statics.reduce((previousValue, currentValue, index) => {
+ if (/[?#]/.test(currentValue)) {
+ postPath = true;
+ }
+ const value = params[index];
+ let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value);
+ if (index !== params.length && (value == null || typeof value === "object" && // handle values from other realms
+ value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY) ?? EMPTY)?.toString)) {
+ encoded = value + "";
+ invalidSegments.push({
+ start: previousValue.length + currentValue.length,
+ length: encoded.length,
+ error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter`
+ });
+ }
+ return previousValue + currentValue + (index === params.length ? "" : encoded);
+ }, "");
+ const pathOnly = path28.split(/[?#]/, 1)[0];
+ const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;
+ let match;
+ while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) {
+ invalidSegments.push({
+ start: match.index,
+ length: match[0].length,
+ error: `Value "${match[0]}" can't be safely passed as a path parameter`
+ });
+ }
+ invalidSegments.sort((a, b) => a.start - b.start);
+ if (invalidSegments.length > 0) {
+ let lastEnd = 0;
+ const underline = invalidSegments.reduce((acc, segment) => {
+ const spaces = " ".repeat(segment.start - lastEnd);
+ const arrows = "^".repeat(segment.length);
+ lastEnd = segment.start + segment.length;
+ return acc + spaces + arrows;
+ }, "");
+ throw new OpenAIError(`Path parameters result in path with invalid segments:
+${invalidSegments.map((e) => e.error).join("\n")}
+${path28}
+${underline}`);
+ }
+ return path28;
+}, "path"), "createPathTagFunction");
+var path15 = /* @__PURE__ */ createPathTagFunction(encodeURIPath);
+
+// node_modules/openai/resources/chat/completions/messages.mjs
+var Messages = class extends APIResource {
+ static {
+ __name(this, "Messages");
+ }
+ /**
+ * Get the messages in a stored chat completion. Only Chat Completions that have
+ * been created with the `store` parameter set to `true` will be returned.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const chatCompletionStoreMessage of client.chat.completions.messages.list(
+ * 'completion_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(completionID, query = {}, options2) {
+ return this._client.getAPIList(path15`/chat/completions/${completionID}/messages`, CursorPage, { query, ...options2, __security: { bearerAuth: true } });
+ }
+};
+
+// node_modules/openai/lib/ChatCompletionRunner.mjs
+init_esbuild_shims();
+
+// node_modules/openai/lib/AbstractChatCompletionRunner.mjs
+init_esbuild_shims();
+
+// node_modules/openai/error.mjs
+init_esbuild_shims();
+
+// node_modules/openai/lib/parser.mjs
+init_esbuild_shims();
+function isChatCompletionFunctionTool(tool) {
+ return tool !== void 0 && "function" in tool && tool.function !== void 0;
+}
+__name(isChatCompletionFunctionTool, "isChatCompletionFunctionTool");
+function isAutoParsableResponseFormat(response_format) {
+ return response_format?.["$brand"] === "auto-parseable-response-format";
+}
+__name(isAutoParsableResponseFormat, "isAutoParsableResponseFormat");
+function isAutoParsableTool(tool) {
+ return tool?.["$brand"] === "auto-parseable-tool";
+}
+__name(isAutoParsableTool, "isAutoParsableTool");
+function maybeParseChatCompletion(completion2, params) {
+ if (!params || !hasAutoParseableInput(params)) {
+ return {
+ ...completion2,
+ choices: completion2.choices.map((choice) => {
+ assertToolCallsAreChatCompletionFunctionToolCalls(choice.message.tool_calls);
+ return {
+ ...choice,
+ message: {
+ ...choice.message,
+ parsed: null,
+ ...choice.message.tool_calls ? {
+ tool_calls: choice.message.tool_calls
+ } : void 0
+ }
+ };
+ })
+ };
+ }
+ return parseChatCompletion(completion2, params);
+}
+__name(maybeParseChatCompletion, "maybeParseChatCompletion");
+function parseChatCompletion(completion2, params) {
+ const choices = completion2.choices.map((choice) => {
+ if (choice.finish_reason === "length") {
+ throw new LengthFinishReasonError();
+ }
+ if (choice.finish_reason === "content_filter") {
+ throw new ContentFilterFinishReasonError();
+ }
+ assertToolCallsAreChatCompletionFunctionToolCalls(choice.message.tool_calls);
+ return {
+ ...choice,
+ message: {
+ ...choice.message,
+ ...choice.message.tool_calls ? {
+ tool_calls: choice.message.tool_calls?.map((toolCall) => parseToolCall(params, toolCall)) ?? void 0
+ } : void 0,
+ parsed: choice.message.content && !choice.message.refusal ? parseResponseFormat(params, choice.message.content) : null
+ }
+ };
+ });
+ return { ...completion2, choices };
+}
+__name(parseChatCompletion, "parseChatCompletion");
+function parseResponseFormat(params, content) {
+ if (params.response_format?.type !== "json_schema") {
+ return null;
+ }
+ if (params.response_format?.type === "json_schema") {
+ if ("$parseRaw" in params.response_format) {
+ const response_format = params.response_format;
+ return response_format.$parseRaw(content);
+ }
+ return JSON.parse(content);
+ }
+ return null;
+}
+__name(parseResponseFormat, "parseResponseFormat");
+function parseToolCall(params, toolCall) {
+ const inputTool = params.tools?.find((inputTool2) => isChatCompletionFunctionTool(inputTool2) && inputTool2.function?.name === toolCall.function.name);
+ return {
+ ...toolCall,
+ function: {
+ ...toolCall.function,
+ parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.function.arguments) : inputTool?.function.strict ? JSON.parse(toolCall.function.arguments) : null
+ }
+ };
+}
+__name(parseToolCall, "parseToolCall");
+function shouldParseToolCall(params, toolCall) {
+ if (!params || !("tools" in params) || !params.tools) {
+ return false;
+ }
+ const inputTool = params.tools?.find((inputTool2) => isChatCompletionFunctionTool(inputTool2) && inputTool2.function?.name === toolCall.function.name);
+ return isChatCompletionFunctionTool(inputTool) && (isAutoParsableTool(inputTool) || inputTool?.function.strict || false);
+}
+__name(shouldParseToolCall, "shouldParseToolCall");
+function hasAutoParseableInput(params) {
+ if (isAutoParsableResponseFormat(params.response_format)) {
+ return true;
+ }
+ return params.tools?.some((t) => isAutoParsableTool(t) || t.type === "function" && t.function.strict === true) ?? false;
+}
+__name(hasAutoParseableInput, "hasAutoParseableInput");
+function assertToolCallsAreChatCompletionFunctionToolCalls(toolCalls) {
+ for (const toolCall of toolCalls || []) {
+ if (toolCall.type !== "function") {
+ throw new OpenAIError(`Currently only \`function\` tool calls are supported; Received \`${toolCall.type}\``);
+ }
+ }
+}
+__name(assertToolCallsAreChatCompletionFunctionToolCalls, "assertToolCallsAreChatCompletionFunctionToolCalls");
+function validateInputTools(tools) {
+ for (const tool of tools ?? []) {
+ if (tool.type !== "function") {
+ throw new OpenAIError(`Currently only \`function\` tool types support auto-parsing; Received \`${tool.type}\``);
+ }
+ if (tool.function.strict !== true) {
+ throw new OpenAIError(`The \`${tool.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`);
+ }
+ }
+}
+__name(validateInputTools, "validateInputTools");
+
+// node_modules/openai/lib/chatCompletionUtils.mjs
+init_esbuild_shims();
+var isAssistantMessage = /* @__PURE__ */ __name((message) => {
+ return message?.role === "assistant";
+}, "isAssistantMessage");
+var isToolMessage = /* @__PURE__ */ __name((message) => {
+ return message?.role === "tool";
+}, "isToolMessage");
+
+// node_modules/openai/lib/EventStream.mjs
+init_esbuild_shims();
+var _EventStream_instances;
+var _EventStream_connectedPromise;
+var _EventStream_resolveConnectedPromise;
+var _EventStream_rejectConnectedPromise;
+var _EventStream_endPromise;
+var _EventStream_resolveEndPromise;
+var _EventStream_rejectEndPromise;
+var _EventStream_listeners;
+var _EventStream_ended;
+var _EventStream_errored;
+var _EventStream_aborted;
+var _EventStream_catchingPromiseCreated;
+var _EventStream_handleError;
+var EventStream = class {
+ static {
+ __name(this, "EventStream");
+ }
+ constructor() {
+ _EventStream_instances.add(this);
+ this.controller = new AbortController();
+ _EventStream_connectedPromise.set(this, void 0);
+ _EventStream_resolveConnectedPromise.set(this, () => {
+ });
+ _EventStream_rejectConnectedPromise.set(this, () => {
+ });
+ _EventStream_endPromise.set(this, void 0);
+ _EventStream_resolveEndPromise.set(this, () => {
+ });
+ _EventStream_rejectEndPromise.set(this, () => {
+ });
+ _EventStream_listeners.set(this, {});
+ _EventStream_ended.set(this, false);
+ _EventStream_errored.set(this, false);
+ _EventStream_aborted.set(this, false);
+ _EventStream_catchingPromiseCreated.set(this, false);
+ __classPrivateFieldSet(this, _EventStream_connectedPromise, new Promise((resolve16, reject) => {
+ __classPrivateFieldSet(this, _EventStream_resolveConnectedPromise, resolve16, "f");
+ __classPrivateFieldSet(this, _EventStream_rejectConnectedPromise, reject, "f");
+ }), "f");
+ __classPrivateFieldSet(this, _EventStream_endPromise, new Promise((resolve16, reject) => {
+ __classPrivateFieldSet(this, _EventStream_resolveEndPromise, resolve16, "f");
+ __classPrivateFieldSet(this, _EventStream_rejectEndPromise, reject, "f");
+ }), "f");
+ __classPrivateFieldGet(this, _EventStream_connectedPromise, "f").catch(() => {
+ });
+ __classPrivateFieldGet(this, _EventStream_endPromise, "f").catch(() => {
+ });
+ }
+ _run(executor) {
+ setTimeout(() => {
+ executor().then(() => {
+ this._emitFinal();
+ this._emit("end");
+ }, __classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_handleError).bind(this));
+ }, 0);
+ }
+ _connected() {
+ if (this.ended)
+ return;
+ __classPrivateFieldGet(this, _EventStream_resolveConnectedPromise, "f").call(this);
+ this._emit("connect");
+ }
+ get ended() {
+ return __classPrivateFieldGet(this, _EventStream_ended, "f");
+ }
+ get errored() {
+ return __classPrivateFieldGet(this, _EventStream_errored, "f");
+ }
+ get aborted() {
+ return __classPrivateFieldGet(this, _EventStream_aborted, "f");
+ }
+ abort() {
+ this.controller.abort();
+ }
+ /**
+ * Adds the listener function to the end of the listeners array for the event.
+ * No checks are made to see if the listener has already been added. Multiple calls passing
+ * the same combination of event and listener will result in the listener being added, and
+ * called, multiple times.
+ * @returns this ChatCompletionStream, so that calls can be chained
+ */
+ on(event, listener) {
+ const listeners = __classPrivateFieldGet(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = []);
+ listeners.push({ listener });
+ return this;
+ }
+ /**
+ * Removes the specified listener from the listener array for the event.
+ * off() will remove, at most, one instance of a listener from the listener array. If any single
+ * listener has been added multiple times to the listener array for the specified event, then
+ * off() must be called multiple times to remove each instance.
+ * @returns this ChatCompletionStream, so that calls can be chained
+ */
+ off(event, listener) {
+ const listeners = __classPrivateFieldGet(this, _EventStream_listeners, "f")[event];
+ if (!listeners)
+ return this;
+ const index = listeners.findIndex((l) => l.listener === listener);
+ if (index >= 0)
+ listeners.splice(index, 1);
+ return this;
+ }
+ /**
+ * Adds a one-time listener function for the event. The next time the event is triggered,
+ * this listener is removed and then invoked.
+ * @returns this ChatCompletionStream, so that calls can be chained
+ */
+ once(event, listener) {
+ const listeners = __classPrivateFieldGet(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = []);
+ listeners.push({ listener, once: true });
+ return this;
+ }
+ /**
+ * This is similar to `.once()`, but returns a Promise that resolves the next time
+ * the event is triggered, instead of calling a listener callback.
+ * @returns a Promise that resolves the next time given event is triggered,
+ * or rejects if an error is emitted. (If you request the 'error' event,
+ * returns a promise that resolves with the error).
+ *
+ * Example:
+ *
+ * const message = await stream.emitted('message') // rejects if the stream errors
+ */
+ emitted(event) {
+ return new Promise((resolve16, reject) => {
+ __classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, "f");
+ if (event !== "error")
+ this.once("error", reject);
+ this.once(event, resolve16);
+ });
+ }
+ async done() {
+ __classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, "f");
+ await __classPrivateFieldGet(this, _EventStream_endPromise, "f");
+ }
+ _emit(event, ...args) {
+ if (__classPrivateFieldGet(this, _EventStream_ended, "f")) {
+ return;
+ }
+ if (event === "end") {
+ __classPrivateFieldSet(this, _EventStream_ended, true, "f");
+ __classPrivateFieldGet(this, _EventStream_resolveEndPromise, "f").call(this);
+ }
+ const listeners = __classPrivateFieldGet(this, _EventStream_listeners, "f")[event];
+ if (listeners) {
+ __classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = listeners.filter((l) => !l.once);
+ listeners.forEach(({ listener }) => listener(...args));
+ }
+ if (event === "abort") {
+ const error51 = args[0];
+ if (!__classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) {
+ Promise.reject(error51);
+ }
+ __classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, "f").call(this, error51);
+ __classPrivateFieldGet(this, _EventStream_rejectEndPromise, "f").call(this, error51);
+ this._emit("end");
+ return;
+ }
+ if (event === "error") {
+ const error51 = args[0];
+ if (!__classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) {
+ Promise.reject(error51);
+ }
+ __classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, "f").call(this, error51);
+ __classPrivateFieldGet(this, _EventStream_rejectEndPromise, "f").call(this, error51);
+ this._emit("end");
+ }
+ }
+ _emitFinal() {
+ }
+};
+_EventStream_connectedPromise = /* @__PURE__ */ new WeakMap(), _EventStream_resolveConnectedPromise = /* @__PURE__ */ new WeakMap(), _EventStream_rejectConnectedPromise = /* @__PURE__ */ new WeakMap(), _EventStream_endPromise = /* @__PURE__ */ new WeakMap(), _EventStream_resolveEndPromise = /* @__PURE__ */ new WeakMap(), _EventStream_rejectEndPromise = /* @__PURE__ */ new WeakMap(), _EventStream_listeners = /* @__PURE__ */ new WeakMap(), _EventStream_ended = /* @__PURE__ */ new WeakMap(), _EventStream_errored = /* @__PURE__ */ new WeakMap(), _EventStream_aborted = /* @__PURE__ */ new WeakMap(), _EventStream_catchingPromiseCreated = /* @__PURE__ */ new WeakMap(), _EventStream_instances = /* @__PURE__ */ new WeakSet(), _EventStream_handleError = /* @__PURE__ */ __name(function _EventStream_handleError2(error51) {
+ __classPrivateFieldSet(this, _EventStream_errored, true, "f");
+ if (error51 instanceof Error && error51.name === "AbortError") {
+ error51 = new APIUserAbortError();
+ }
+ if (error51 instanceof APIUserAbortError) {
+ __classPrivateFieldSet(this, _EventStream_aborted, true, "f");
+ return this._emit("abort", error51);
+ }
+ if (error51 instanceof OpenAIError) {
+ return this._emit("error", error51);
+ }
+ if (error51 instanceof Error) {
+ const openAIError = new OpenAIError(error51.message);
+ openAIError.cause = error51;
+ return this._emit("error", openAIError);
+ }
+ return this._emit("error", new OpenAIError(String(error51)));
+}, "_EventStream_handleError");
+
+// node_modules/openai/lib/RunnableFunction.mjs
+init_esbuild_shims();
+function isRunnableFunctionWithParse(fn) {
+ return typeof fn.parse === "function";
+}
+__name(isRunnableFunctionWithParse, "isRunnableFunctionWithParse");
+
+// node_modules/openai/lib/AbstractChatCompletionRunner.mjs
+var _AbstractChatCompletionRunner_instances;
+var _AbstractChatCompletionRunner_getFinalContent;
+var _AbstractChatCompletionRunner_getFinalMessage;
+var _AbstractChatCompletionRunner_getFinalFunctionToolCall;
+var _AbstractChatCompletionRunner_getFinalFunctionToolCallResult;
+var _AbstractChatCompletionRunner_calculateTotalUsage;
+var _AbstractChatCompletionRunner_validateParams;
+var _AbstractChatCompletionRunner_stringifyFunctionCallResult;
+var DEFAULT_MAX_CHAT_COMPLETIONS = 10;
+var AbstractChatCompletionRunner = class extends EventStream {
+ static {
+ __name(this, "AbstractChatCompletionRunner");
+ }
+ constructor() {
+ super(...arguments);
+ _AbstractChatCompletionRunner_instances.add(this);
+ this._chatCompletions = [];
+ this.messages = [];
+ }
+ _addChatCompletion(chatCompletion) {
+ this._chatCompletions.push(chatCompletion);
+ this._emit("chatCompletion", chatCompletion);
+ const message = chatCompletion.choices[0]?.message;
+ if (message)
+ this._addMessage(message);
+ return chatCompletion;
+ }
+ _addMessage(message, emit = true) {
+ if (!("content" in message))
+ message.content = null;
+ this.messages.push(message);
+ if (emit) {
+ this._emit("message", message);
+ if (isToolMessage(message) && message.content) {
+ this._emit("functionToolCallResult", message.content);
+ } else if (isAssistantMessage(message) && message.tool_calls) {
+ for (const tool_call of message.tool_calls) {
+ if (tool_call.type === "function") {
+ this._emit("functionToolCall", tool_call.function);
+ }
+ }
+ }
+ }
+ }
+ /**
+ * @returns a promise that resolves with the final ChatCompletion, or rejects
+ * if an error occurred or the stream ended prematurely without producing a ChatCompletion.
+ */
+ async finalChatCompletion() {
+ await this.done();
+ const completion2 = this._chatCompletions[this._chatCompletions.length - 1];
+ if (!completion2)
+ throw new OpenAIError("stream ended without producing a ChatCompletion");
+ return completion2;
+ }
+ /**
+ * @returns a promise that resolves with the content of the final ChatCompletionMessage, or rejects
+ * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage.
+ */
+ async finalContent() {
+ await this.done();
+ return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this);
+ }
+ /**
+ * @returns a promise that resolves with the the final assistant ChatCompletionMessage response,
+ * or rejects if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage.
+ */
+ async finalMessage() {
+ await this.done();
+ return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this);
+ }
+ /**
+ * @returns a promise that resolves with the content of the final FunctionCall, or rejects
+ * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage.
+ */
+ async finalFunctionToolCall() {
+ await this.done();
+ return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCall).call(this);
+ }
+ async finalFunctionToolCallResult() {
+ await this.done();
+ return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCallResult).call(this);
+ }
+ async totalUsage() {
+ await this.done();
+ return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this);
+ }
+ allChatCompletions() {
+ return [...this._chatCompletions];
+ }
+ _emitFinal() {
+ const completion2 = this._chatCompletions[this._chatCompletions.length - 1];
+ if (completion2)
+ this._emit("finalChatCompletion", completion2);
+ const finalMessage = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this);
+ if (finalMessage)
+ this._emit("finalMessage", finalMessage);
+ const finalContent = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this);
+ if (finalContent)
+ this._emit("finalContent", finalContent);
+ const finalFunctionCall = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCall).call(this);
+ if (finalFunctionCall)
+ this._emit("finalFunctionToolCall", finalFunctionCall);
+ const finalFunctionCallResult = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCallResult).call(this);
+ if (finalFunctionCallResult != null)
+ this._emit("finalFunctionToolCallResult", finalFunctionCallResult);
+ if (this._chatCompletions.some((c) => c.usage)) {
+ this._emit("totalUsage", __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this));
+ }
+ }
+ async _createChatCompletion(client, params, options2) {
+ const signal = options2?.signal;
+ if (signal) {
+ if (signal.aborted)
+ this.controller.abort();
+ signal.addEventListener("abort", () => this.controller.abort());
+ }
+ __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_validateParams).call(this, params);
+ const chatCompletion = await client.chat.completions.create({ ...params, stream: false }, { ...options2, signal: this.controller.signal });
+ this._connected();
+ return this._addChatCompletion(parseChatCompletion(chatCompletion, params));
+ }
+ async _runChatCompletion(client, params, options2) {
+ for (const message of params.messages) {
+ this._addMessage(message, false);
+ }
+ return await this._createChatCompletion(client, params, options2);
+ }
+ async _runTools(client, params, options2) {
+ const role = "tool";
+ const { tool_choice = "auto", stream, ...restParams } = params;
+ const singleFunctionToCall = typeof tool_choice !== "string" && tool_choice.type === "function" && tool_choice?.function?.name;
+ const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options2 || {};
+ const inputTools = params.tools.map((tool) => {
+ if (isAutoParsableTool(tool)) {
+ if (!tool.$callback) {
+ throw new OpenAIError("Tool given to `.runTools()` that does not have an associated function");
+ }
+ return {
+ type: "function",
+ function: {
+ function: tool.$callback,
+ name: tool.function.name,
+ description: tool.function.description || "",
+ parameters: tool.function.parameters,
+ parse: tool.$parseRaw,
+ strict: true
+ }
+ };
+ }
+ return tool;
+ });
+ const functionsByName = {};
+ for (const f of inputTools) {
+ if (f.type === "function") {
+ functionsByName[f.function.name || f.function.function.name] = f.function;
+ }
+ }
+ const tools = "tools" in params ? inputTools.map((t) => t.type === "function" ? {
+ type: "function",
+ function: {
+ name: t.function.name || t.function.function.name,
+ parameters: t.function.parameters,
+ description: t.function.description,
+ strict: t.function.strict
+ }
+ } : t) : void 0;
+ for (const message of params.messages) {
+ this._addMessage(message, false);
+ }
+ for (let i = 0; i < maxChatCompletions; ++i) {
+ const chatCompletion = await this._createChatCompletion(client, {
+ ...restParams,
+ tool_choice,
+ tools,
+ messages: [...this.messages]
+ }, options2);
+ const message = chatCompletion.choices[0]?.message;
+ if (!message) {
+ throw new OpenAIError(`missing message in ChatCompletion response`);
+ }
+ if (!message.tool_calls?.length) {
+ return;
+ }
+ for (const tool_call of message.tool_calls) {
+ if (tool_call.type !== "function")
+ continue;
+ const tool_call_id = tool_call.id;
+ const { name, arguments: args } = tool_call.function;
+ const fn = functionsByName[name];
+ if (!fn) {
+ const content2 = `Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${Object.keys(functionsByName).map((name2) => JSON.stringify(name2)).join(", ")}. Please try again`;
+ this._addMessage({ role, tool_call_id, content: content2 });
+ continue;
+ } else if (singleFunctionToCall && singleFunctionToCall !== name) {
+ const content2 = `Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`;
+ this._addMessage({ role, tool_call_id, content: content2 });
+ continue;
+ }
+ let parsed;
+ try {
+ parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args;
+ } catch (error51) {
+ const content2 = error51 instanceof Error ? error51.message : String(error51);
+ this._addMessage({ role, tool_call_id, content: content2 });
+ continue;
+ }
+ const rawContent = await fn.function(parsed, this);
+ const content = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent);
+ this._addMessage({ role, tool_call_id, content });
+ if (singleFunctionToCall) {
+ return;
+ }
+ }
+ }
+ return;
+ }
+};
+_AbstractChatCompletionRunner_instances = /* @__PURE__ */ new WeakSet(), _AbstractChatCompletionRunner_getFinalContent = /* @__PURE__ */ __name(function _AbstractChatCompletionRunner_getFinalContent2() {
+ return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this).content ?? null;
+}, "_AbstractChatCompletionRunner_getFinalContent"), _AbstractChatCompletionRunner_getFinalMessage = /* @__PURE__ */ __name(function _AbstractChatCompletionRunner_getFinalMessage2() {
+ let i = this.messages.length;
+ while (i-- > 0) {
+ const message = this.messages[i];
+ if (isAssistantMessage(message)) {
+ const ret = {
+ ...message,
+ content: message.content ?? null,
+ refusal: message.refusal ?? null
+ };
+ return ret;
+ }
+ }
+ throw new OpenAIError("stream ended without producing a ChatCompletionMessage with role=assistant");
+}, "_AbstractChatCompletionRunner_getFinalMessage"), _AbstractChatCompletionRunner_getFinalFunctionToolCall = /* @__PURE__ */ __name(function _AbstractChatCompletionRunner_getFinalFunctionToolCall2() {
+ for (let i = this.messages.length - 1; i >= 0; i--) {
+ const message = this.messages[i];
+ if (isAssistantMessage(message) && message?.tool_calls?.length) {
+ for (let j = message.tool_calls.length - 1; j >= 0; j--) {
+ const toolCall = message.tool_calls[j];
+ if (toolCall?.type === "function") {
+ return toolCall.function;
+ }
+ }
+ }
+ }
+ return;
+}, "_AbstractChatCompletionRunner_getFinalFunctionToolCall"), _AbstractChatCompletionRunner_getFinalFunctionToolCallResult = /* @__PURE__ */ __name(function _AbstractChatCompletionRunner_getFinalFunctionToolCallResult2() {
+ for (let i = this.messages.length - 1; i >= 0; i--) {
+ const message = this.messages[i];
+ if (isToolMessage(message) && message.content != null && typeof message.content === "string" && this.messages.some((x) => x.role === "assistant" && x.tool_calls?.some((y) => y.type === "function" && y.id === message.tool_call_id))) {
+ return message.content;
+ }
+ }
+ return;
+}, "_AbstractChatCompletionRunner_getFinalFunctionToolCallResult"), _AbstractChatCompletionRunner_calculateTotalUsage = /* @__PURE__ */ __name(function _AbstractChatCompletionRunner_calculateTotalUsage2() {
+ const total = {
+ completion_tokens: 0,
+ prompt_tokens: 0,
+ total_tokens: 0
+ };
+ for (const { usage: usage2 } of this._chatCompletions) {
+ if (usage2) {
+ total.completion_tokens += usage2.completion_tokens;
+ total.prompt_tokens += usage2.prompt_tokens;
+ total.total_tokens += usage2.total_tokens;
+ }
+ }
+ return total;
+}, "_AbstractChatCompletionRunner_calculateTotalUsage"), _AbstractChatCompletionRunner_validateParams = /* @__PURE__ */ __name(function _AbstractChatCompletionRunner_validateParams2(params) {
+ if (params.n != null && params.n > 1) {
+ throw new OpenAIError("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.");
+ }
+}, "_AbstractChatCompletionRunner_validateParams"), _AbstractChatCompletionRunner_stringifyFunctionCallResult = /* @__PURE__ */ __name(function _AbstractChatCompletionRunner_stringifyFunctionCallResult2(rawContent) {
+ return typeof rawContent === "string" ? rawContent : rawContent === void 0 ? "undefined" : JSON.stringify(rawContent);
+}, "_AbstractChatCompletionRunner_stringifyFunctionCallResult");
+
+// node_modules/openai/lib/ChatCompletionRunner.mjs
+var ChatCompletionRunner = class _ChatCompletionRunner extends AbstractChatCompletionRunner {
+ static {
+ __name(this, "ChatCompletionRunner");
+ }
+ static runTools(client, params, options2) {
+ const runner = new _ChatCompletionRunner();
+ const opts = {
+ ...options2,
+ headers: { ...options2?.headers, "X-Stainless-Helper-Method": "runTools" }
+ };
+ runner._run(() => runner._runTools(client, params, opts));
+ return runner;
+ }
+ _addMessage(message, emit = true) {
+ super._addMessage(message, emit);
+ if (isAssistantMessage(message) && message.content) {
+ this._emit("content", message.content);
+ }
+ }
+};
+
+// node_modules/openai/lib/ChatCompletionStreamingRunner.mjs
+init_esbuild_shims();
+
+// node_modules/openai/lib/ChatCompletionStream.mjs
+init_esbuild_shims();
+
+// node_modules/openai/_vendor/partial-json-parser/parser.mjs
+init_esbuild_shims();
+var STR = 1;
+var NUM = 2;
+var ARR = 4;
+var OBJ = 8;
+var NULL = 16;
+var BOOL = 32;
+var NAN = 64;
+var INFINITY = 128;
+var MINUS_INFINITY = 256;
+var INF = INFINITY | MINUS_INFINITY;
+var SPECIAL = NULL | BOOL | INF | NAN;
+var ATOM = STR | NUM | SPECIAL;
+var COLLECTION = ARR | OBJ;
+var ALL = ATOM | COLLECTION;
+var Allow = {
+ STR,
+ NUM,
+ ARR,
+ OBJ,
+ NULL,
+ BOOL,
+ NAN,
+ INFINITY,
+ MINUS_INFINITY,
+ INF,
+ SPECIAL,
+ ATOM,
+ COLLECTION,
+ ALL
+};
+var PartialJSON = class extends Error {
+ static {
+ __name(this, "PartialJSON");
+ }
+};
+var MalformedJSON = class extends Error {
+ static {
+ __name(this, "MalformedJSON");
+ }
+};
+function parseJSON(jsonString, allowPartial = Allow.ALL) {
+ if (typeof jsonString !== "string") {
+ throw new TypeError(`expecting str, got ${typeof jsonString}`);
+ }
+ if (!jsonString.trim()) {
+ throw new Error(`${jsonString} is empty`);
+ }
+ return _parseJSON(jsonString.trim(), allowPartial);
+}
+__name(parseJSON, "parseJSON");
+var _parseJSON = /* @__PURE__ */ __name((jsonString, allow) => {
+ const length = jsonString.length;
+ let index = 0;
+ const markPartialJSON = /* @__PURE__ */ __name((msg) => {
+ throw new PartialJSON(`${msg} at position ${index}`);
+ }, "markPartialJSON");
+ const throwMalformedError = /* @__PURE__ */ __name((msg) => {
+ throw new MalformedJSON(`${msg} at position ${index}`);
+ }, "throwMalformedError");
+ const parseAny = /* @__PURE__ */ __name(() => {
+ skipBlank();
+ if (index >= length)
+ markPartialJSON("Unexpected end of input");
+ if (jsonString[index] === '"')
+ return parseStr();
+ if (jsonString[index] === "{")
+ return parseObj();
+ if (jsonString[index] === "[")
+ return parseArr();
+ if (jsonString.substring(index, index + 4) === "null" || Allow.NULL & allow && length - index < 4 && "null".startsWith(jsonString.substring(index))) {
+ index += 4;
+ return null;
+ }
+ if (jsonString.substring(index, index + 4) === "true" || Allow.BOOL & allow && length - index < 4 && "true".startsWith(jsonString.substring(index))) {
+ index += 4;
+ return true;
+ }
+ if (jsonString.substring(index, index + 5) === "false" || Allow.BOOL & allow && length - index < 5 && "false".startsWith(jsonString.substring(index))) {
+ index += 5;
+ return false;
+ }
+ if (jsonString.substring(index, index + 8) === "Infinity" || Allow.INFINITY & allow && length - index < 8 && "Infinity".startsWith(jsonString.substring(index))) {
+ index += 8;
+ return Infinity;
+ }
+ if (jsonString.substring(index, index + 9) === "-Infinity" || Allow.MINUS_INFINITY & allow && 1 < length - index && length - index < 9 && "-Infinity".startsWith(jsonString.substring(index))) {
+ index += 9;
+ return -Infinity;
+ }
+ if (jsonString.substring(index, index + 3) === "NaN" || Allow.NAN & allow && length - index < 3 && "NaN".startsWith(jsonString.substring(index))) {
+ index += 3;
+ return NaN;
+ }
+ return parseNum();
+ }, "parseAny");
+ const parseStr = /* @__PURE__ */ __name(() => {
+ const start = index;
+ let escape4 = false;
+ index++;
+ while (index < length && (jsonString[index] !== '"' || escape4 && jsonString[index - 1] === "\\")) {
+ escape4 = jsonString[index] === "\\" ? !escape4 : false;
+ index++;
+ }
+ if (jsonString.charAt(index) == '"') {
+ try {
+ return JSON.parse(jsonString.substring(start, ++index - Number(escape4)));
+ } catch (e) {
+ throwMalformedError(String(e));
+ }
+ } else if (Allow.STR & allow) {
+ try {
+ return JSON.parse(jsonString.substring(start, index - Number(escape4)) + '"');
+ } catch (e) {
+ return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("\\")) + '"');
+ }
+ }
+ markPartialJSON("Unterminated string literal");
+ }, "parseStr");
+ const parseObj = /* @__PURE__ */ __name(() => {
+ index++;
+ skipBlank();
+ const obj = {};
+ try {
+ while (jsonString[index] !== "}") {
+ skipBlank();
+ if (index >= length && Allow.OBJ & allow)
+ return obj;
+ const key = parseStr();
+ skipBlank();
+ index++;
+ try {
+ const value = parseAny();
+ Object.defineProperty(obj, key, { value, writable: true, enumerable: true, configurable: true });
+ } catch (e) {
+ if (Allow.OBJ & allow)
+ return obj;
+ else
+ throw e;
+ }
+ skipBlank();
+ if (jsonString[index] === ",")
+ index++;
+ }
+ } catch (e) {
+ if (Allow.OBJ & allow)
+ return obj;
+ else
+ markPartialJSON("Expected '}' at end of object");
+ }
+ index++;
+ return obj;
+ }, "parseObj");
+ const parseArr = /* @__PURE__ */ __name(() => {
+ index++;
+ const arr = [];
+ try {
+ while (jsonString[index] !== "]") {
+ arr.push(parseAny());
+ skipBlank();
+ if (jsonString[index] === ",") {
+ index++;
+ }
+ }
+ } catch (e) {
+ if (Allow.ARR & allow) {
+ return arr;
+ }
+ markPartialJSON("Expected ']' at end of array");
+ }
+ index++;
+ return arr;
+ }, "parseArr");
+ const parseNum = /* @__PURE__ */ __name(() => {
+ if (index === 0) {
+ if (jsonString === "-" && Allow.NUM & allow)
+ markPartialJSON("Not sure what '-' is");
+ try {
+ return JSON.parse(jsonString);
+ } catch (e) {
+ if (Allow.NUM & allow) {
+ try {
+ if ("." === jsonString[jsonString.length - 1])
+ return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf(".")));
+ return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf("e")));
+ } catch (e2) {
+ }
+ }
+ throwMalformedError(String(e));
+ }
+ }
+ const start = index;
+ if (jsonString[index] === "-")
+ index++;
+ while (jsonString[index] && !",]}".includes(jsonString[index]))
+ index++;
+ if (index == length && !(Allow.NUM & allow))
+ markPartialJSON("Unterminated number literal");
+ try {
+ return JSON.parse(jsonString.substring(start, index));
+ } catch (e) {
+ if (jsonString.substring(start, index) === "-" && Allow.NUM & allow)
+ markPartialJSON("Not sure what '-' is");
+ try {
+ return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("e")));
+ } catch (e2) {
+ throwMalformedError(String(e2));
+ }
+ }
+ }, "parseNum");
+ const skipBlank = /* @__PURE__ */ __name(() => {
+ while (index < length && " \n\r ".includes(jsonString[index])) {
+ index++;
+ }
+ }, "skipBlank");
+ return parseAny();
+}, "_parseJSON");
+var partialParse = /* @__PURE__ */ __name((input) => parseJSON(input, Allow.ALL ^ Allow.NUM), "partialParse");
+
+// node_modules/openai/streaming.mjs
+init_esbuild_shims();
+
+// node_modules/openai/lib/ChatCompletionStream.mjs
+var _ChatCompletionStream_instances;
+var _ChatCompletionStream_params;
+var _ChatCompletionStream_choiceEventStates;
+var _ChatCompletionStream_currentChatCompletionSnapshot;
+var _ChatCompletionStream_beginRequest;
+var _ChatCompletionStream_getChoiceEventState;
+var _ChatCompletionStream_addChunk;
+var _ChatCompletionStream_emitToolCallDoneEvent;
+var _ChatCompletionStream_emitContentDoneEvents;
+var _ChatCompletionStream_endRequest;
+var _ChatCompletionStream_getAutoParseableResponseFormat;
+var _ChatCompletionStream_accumulateChatCompletion;
+var ChatCompletionStream = class _ChatCompletionStream extends AbstractChatCompletionRunner {
+ static {
+ __name(this, "ChatCompletionStream");
+ }
+ constructor(params) {
+ super();
+ _ChatCompletionStream_instances.add(this);
+ _ChatCompletionStream_params.set(this, void 0);
+ _ChatCompletionStream_choiceEventStates.set(this, void 0);
+ _ChatCompletionStream_currentChatCompletionSnapshot.set(this, void 0);
+ __classPrivateFieldSet(this, _ChatCompletionStream_params, params, "f");
+ __classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], "f");
+ }
+ get currentChatCompletionSnapshot() {
+ return __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
+ }
+ /**
+ * Intended for use on the frontend, consuming a stream produced with
+ * `.toReadableStream()` on the backend.
+ *
+ * Note that messages sent to the model do not appear in `.on('message')`
+ * in this context.
+ */
+ static fromReadableStream(stream) {
+ const runner = new _ChatCompletionStream(null);
+ runner._run(() => runner._fromReadableStream(stream));
+ return runner;
+ }
+ static createChatCompletion(client, params, options2) {
+ const runner = new _ChatCompletionStream(params);
+ runner._run(() => runner._runChatCompletion(client, { ...params, stream: true }, { ...options2, headers: { ...options2?.headers, "X-Stainless-Helper-Method": "stream" } }));
+ return runner;
+ }
+ async _createChatCompletion(client, params, options2) {
+ super._createChatCompletion;
+ const signal = options2?.signal;
+ if (signal) {
+ if (signal.aborted)
+ this.controller.abort();
+ signal.addEventListener("abort", () => this.controller.abort());
+ }
+ __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
+ const stream = await client.chat.completions.create({ ...params, stream: true }, { ...options2, signal: this.controller.signal });
+ this._connected();
+ for await (const chunk of stream) {
+ __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk);
+ }
+ if (stream.controller.signal?.aborted) {
+ throw new APIUserAbortError();
+ }
+ return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
+ }
+ async _fromReadableStream(readableStream, options2) {
+ const signal = options2?.signal;
+ if (signal) {
+ if (signal.aborted)
+ this.controller.abort();
+ signal.addEventListener("abort", () => this.controller.abort());
+ }
+ __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
+ this._connected();
+ const stream = Stream2.fromReadableStream(readableStream, this.controller);
+ let chatId;
+ for await (const chunk of stream) {
+ if (chatId && chatId !== chunk.id) {
+ this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
+ }
+ __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk);
+ chatId = chunk.id;
+ }
+ if (stream.controller.signal?.aborted) {
+ throw new APIUserAbortError();
+ }
+ return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
+ }
+ [(_ChatCompletionStream_params = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_choiceEventStates = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_currentChatCompletionSnapshot = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_instances = /* @__PURE__ */ new WeakSet(), _ChatCompletionStream_beginRequest = /* @__PURE__ */ __name(function _ChatCompletionStream_beginRequest2() {
+ if (this.ended)
+ return;
+ __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, void 0, "f");
+ }, "_ChatCompletionStream_beginRequest"), _ChatCompletionStream_getChoiceEventState = /* @__PURE__ */ __name(function _ChatCompletionStream_getChoiceEventState2(choice) {
+ let state = __classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index];
+ if (state) {
+ return state;
+ }
+ state = {
+ content_done: false,
+ refusal_done: false,
+ logprobs_content_done: false,
+ logprobs_refusal_done: false,
+ done_tool_calls: /* @__PURE__ */ new Set(),
+ current_tool_call_index: null
+ };
+ __classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index] = state;
+ return state;
+ }, "_ChatCompletionStream_getChoiceEventState"), _ChatCompletionStream_addChunk = /* @__PURE__ */ __name(function _ChatCompletionStream_addChunk2(chunk) {
+ if (this.ended)
+ return;
+ const completion2 = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_accumulateChatCompletion).call(this, chunk);
+ this._emit("chunk", chunk, completion2);
+ for (const choice of chunk.choices) {
+ const choiceSnapshot = completion2.choices[choice.index];
+ if (choice.delta.content != null && choiceSnapshot.message?.role === "assistant" && choiceSnapshot.message?.content) {
+ this._emit("content", choice.delta.content, choiceSnapshot.message.content);
+ this._emit("content.delta", {
+ delta: choice.delta.content,
+ snapshot: choiceSnapshot.message.content,
+ parsed: choiceSnapshot.message.parsed
+ });
+ }
+ if (choice.delta.refusal != null && choiceSnapshot.message?.role === "assistant" && choiceSnapshot.message?.refusal) {
+ this._emit("refusal.delta", {
+ delta: choice.delta.refusal,
+ snapshot: choiceSnapshot.message.refusal
+ });
+ }
+ if (choice.logprobs?.content != null && choiceSnapshot.message?.role === "assistant") {
+ this._emit("logprobs.content.delta", {
+ content: choice.logprobs?.content,
+ snapshot: choiceSnapshot.logprobs?.content ?? []
+ });
+ }
+ if (choice.logprobs?.refusal != null && choiceSnapshot.message?.role === "assistant") {
+ this._emit("logprobs.refusal.delta", {
+ refusal: choice.logprobs?.refusal,
+ snapshot: choiceSnapshot.logprobs?.refusal ?? []
+ });
+ }
+ const state = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
+ if (choiceSnapshot.finish_reason) {
+ __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);
+ if (state.current_tool_call_index != null) {
+ __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index);
+ }
+ }
+ for (const toolCall of choice.delta.tool_calls ?? []) {
+ if (state.current_tool_call_index !== toolCall.index) {
+ __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);
+ if (state.current_tool_call_index != null) {
+ __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index);
+ }
+ }
+ state.current_tool_call_index = toolCall.index;
+ }
+ for (const toolCallDelta of choice.delta.tool_calls ?? []) {
+ const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallDelta.index];
+ if (!toolCallSnapshot?.type) {
+ continue;
+ }
+ if (toolCallSnapshot?.type === "function") {
+ this._emit("tool_calls.function.arguments.delta", {
+ name: toolCallSnapshot.function?.name,
+ index: toolCallDelta.index,
+ arguments: toolCallSnapshot.function.arguments,
+ parsed_arguments: toolCallSnapshot.function.parsed_arguments,
+ arguments_delta: toolCallDelta.function?.arguments ?? ""
+ });
+ } else {
+ assertNever2(toolCallSnapshot?.type);
+ }
+ }
+ }
+ }, "_ChatCompletionStream_addChunk"), _ChatCompletionStream_emitToolCallDoneEvent = /* @__PURE__ */ __name(function _ChatCompletionStream_emitToolCallDoneEvent2(choiceSnapshot, toolCallIndex) {
+ const state = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
+ if (state.done_tool_calls.has(toolCallIndex)) {
+ return;
+ }
+ const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallIndex];
+ if (!toolCallSnapshot) {
+ throw new Error("no tool call snapshot");
+ }
+ if (!toolCallSnapshot.type) {
+ throw new Error("tool call snapshot missing `type`");
+ }
+ if (toolCallSnapshot.type === "function") {
+ const inputTool = __classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.tools?.find((tool) => isChatCompletionFunctionTool(tool) && tool.function.name === toolCallSnapshot.function.name);
+ this._emit("tool_calls.function.arguments.done", {
+ name: toolCallSnapshot.function.name,
+ index: toolCallIndex,
+ arguments: toolCallSnapshot.function.arguments,
+ parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCallSnapshot.function.arguments) : inputTool?.function.strict ? JSON.parse(toolCallSnapshot.function.arguments) : null
+ });
+ } else {
+ assertNever2(toolCallSnapshot.type);
+ }
+ }, "_ChatCompletionStream_emitToolCallDoneEvent"), _ChatCompletionStream_emitContentDoneEvents = /* @__PURE__ */ __name(function _ChatCompletionStream_emitContentDoneEvents2(choiceSnapshot) {
+ const state = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
+ if (choiceSnapshot.message.content && !state.content_done) {
+ state.content_done = true;
+ const responseFormat = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this);
+ this._emit("content.done", {
+ content: choiceSnapshot.message.content,
+ parsed: responseFormat ? responseFormat.$parseRaw(choiceSnapshot.message.content) : null
+ });
+ }
+ if (choiceSnapshot.message.refusal && !state.refusal_done) {
+ state.refusal_done = true;
+ this._emit("refusal.done", { refusal: choiceSnapshot.message.refusal });
+ }
+ if (choiceSnapshot.logprobs?.content && !state.logprobs_content_done) {
+ state.logprobs_content_done = true;
+ this._emit("logprobs.content.done", { content: choiceSnapshot.logprobs.content });
+ }
+ if (choiceSnapshot.logprobs?.refusal && !state.logprobs_refusal_done) {
+ state.logprobs_refusal_done = true;
+ this._emit("logprobs.refusal.done", { refusal: choiceSnapshot.logprobs.refusal });
+ }
+ }, "_ChatCompletionStream_emitContentDoneEvents"), _ChatCompletionStream_endRequest = /* @__PURE__ */ __name(function _ChatCompletionStream_endRequest2() {
+ if (this.ended) {
+ throw new OpenAIError(`stream has ended, this shouldn't happen`);
+ }
+ const snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
+ if (!snapshot) {
+ throw new OpenAIError(`request ended without sending any chunks`);
+ }
+ __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, void 0, "f");
+ __classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], "f");
+ return finalizeChatCompletion(snapshot, __classPrivateFieldGet(this, _ChatCompletionStream_params, "f"));
+ }, "_ChatCompletionStream_endRequest"), _ChatCompletionStream_getAutoParseableResponseFormat = /* @__PURE__ */ __name(function _ChatCompletionStream_getAutoParseableResponseFormat2() {
+ const responseFormat = __classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.response_format;
+ if (isAutoParsableResponseFormat(responseFormat)) {
+ return responseFormat;
+ }
+ return null;
+ }, "_ChatCompletionStream_getAutoParseableResponseFormat"), _ChatCompletionStream_accumulateChatCompletion = /* @__PURE__ */ __name(function _ChatCompletionStream_accumulateChatCompletion2(chunk) {
+ var _a6, _b2, _c2, _d;
+ let snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
+ const { choices, ...rest } = chunk;
+ if (!snapshot) {
+ snapshot = __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, {
+ ...rest,
+ choices: []
+ }, "f");
+ } else {
+ Object.assign(snapshot, rest);
+ }
+ for (const { delta, finish_reason, index, logprobs = null, ...other } of chunk.choices) {
+ let choice = snapshot.choices[index];
+ if (!choice) {
+ choice = snapshot.choices[index] = { finish_reason, index, message: {}, logprobs, ...other };
+ }
+ if (logprobs) {
+ if (!choice.logprobs) {
+ choice.logprobs = Object.assign({}, logprobs);
+ } else {
+ const { content: content2, refusal: refusal2, ...rest3 } = logprobs;
+ assertIsEmpty(rest3);
+ Object.assign(choice.logprobs, rest3);
+ if (content2) {
+ (_a6 = choice.logprobs).content ?? (_a6.content = []);
+ choice.logprobs.content.push(...content2);
+ }
+ if (refusal2) {
+ (_b2 = choice.logprobs).refusal ?? (_b2.refusal = []);
+ choice.logprobs.refusal.push(...refusal2);
+ }
+ }
+ }
+ if (finish_reason) {
+ choice.finish_reason = finish_reason;
+ if (__classPrivateFieldGet(this, _ChatCompletionStream_params, "f") && hasAutoParseableInput(__classPrivateFieldGet(this, _ChatCompletionStream_params, "f"))) {
+ if (finish_reason === "length") {
+ throw new LengthFinishReasonError();
+ }
+ if (finish_reason === "content_filter") {
+ throw new ContentFilterFinishReasonError();
+ }
+ }
+ }
+ Object.assign(choice, other);
+ if (!delta)
+ continue;
+ const { content, refusal, function_call, role, tool_calls, ...rest2 } = delta;
+ assertIsEmpty(rest2);
+ Object.assign(choice.message, rest2);
+ if (refusal) {
+ choice.message.refusal = (choice.message.refusal || "") + refusal;
+ }
+ if (role)
+ choice.message.role = role;
+ if (function_call) {
+ if (!choice.message.function_call) {
+ choice.message.function_call = function_call;
+ } else {
+ if (function_call.name)
+ choice.message.function_call.name = function_call.name;
+ if (function_call.arguments) {
+ (_c2 = choice.message.function_call).arguments ?? (_c2.arguments = "");
+ choice.message.function_call.arguments += function_call.arguments;
+ }
+ }
+ }
+ if (content) {
+ choice.message.content = (choice.message.content || "") + content;
+ if (!choice.message.refusal && __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this)) {
+ choice.message.parsed = partialParse(choice.message.content);
+ }
+ }
+ if (tool_calls) {
+ if (!choice.message.tool_calls)
+ choice.message.tool_calls = [];
+ for (const { index: index2, id, type: type2, function: fn, ...rest3 } of tool_calls) {
+ const tool_call = (_d = choice.message.tool_calls)[index2] ?? (_d[index2] = {});
+ Object.assign(tool_call, rest3);
+ if (id)
+ tool_call.id = id;
+ if (type2)
+ tool_call.type = type2;
+ if (fn)
+ tool_call.function ?? (tool_call.function = { name: fn.name ?? "", arguments: "" });
+ if (fn?.name)
+ tool_call.function.name = fn.name;
+ if (fn?.arguments) {
+ tool_call.function.arguments += fn.arguments;
+ if (shouldParseToolCall(__classPrivateFieldGet(this, _ChatCompletionStream_params, "f"), tool_call)) {
+ tool_call.function.parsed_arguments = partialParse(tool_call.function.arguments);
+ }
+ }
+ }
+ }
+ }
+ return snapshot;
+ }, "_ChatCompletionStream_accumulateChatCompletion"), Symbol.asyncIterator)]() {
+ const pushQueue = [];
+ const readQueue = [];
+ let done = false;
+ this.on("chunk", (chunk) => {
+ const reader = readQueue.shift();
+ if (reader) {
+ reader.resolve(chunk);
+ } else {
+ pushQueue.push(chunk);
+ }
+ });
+ this.on("end", () => {
+ done = true;
+ for (const reader of readQueue) {
+ reader.resolve(void 0);
+ }
+ readQueue.length = 0;
+ });
+ this.on("abort", (err) => {
+ done = true;
+ for (const reader of readQueue) {
+ reader.reject(err);
+ }
+ readQueue.length = 0;
+ });
+ this.on("error", (err) => {
+ done = true;
+ for (const reader of readQueue) {
+ reader.reject(err);
+ }
+ readQueue.length = 0;
+ });
+ return {
+ next: /* @__PURE__ */ __name(async () => {
+ if (!pushQueue.length) {
+ if (done) {
+ return { value: void 0, done: true };
+ }
+ return new Promise((resolve16, reject) => readQueue.push({ resolve: resolve16, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true });
+ }
+ const chunk = pushQueue.shift();
+ return { value: chunk, done: false };
+ }, "next"),
+ return: /* @__PURE__ */ __name(async () => {
+ this.abort();
+ return { value: void 0, done: true };
+ }, "return")
+ };
+ }
+ toReadableStream() {
+ const stream = new Stream2(this[Symbol.asyncIterator].bind(this), this.controller);
+ return stream.toReadableStream();
+ }
+};
+function finalizeChatCompletion(snapshot, params) {
+ const { id, choices, created, model, system_fingerprint, ...rest } = snapshot;
+ const completion2 = {
+ ...rest,
+ id,
+ choices: choices.map(({ message, finish_reason, index, logprobs, ...choiceRest }) => {
+ if (!finish_reason) {
+ throw new OpenAIError(`missing finish_reason for choice ${index}`);
+ }
+ const { content = null, function_call, tool_calls, ...messageRest } = message;
+ const role = message.role;
+ if (!role) {
+ throw new OpenAIError(`missing role for choice ${index}`);
+ }
+ if (function_call) {
+ const { arguments: args, name } = function_call;
+ if (args == null) {
+ throw new OpenAIError(`missing function_call.arguments for choice ${index}`);
+ }
+ if (!name) {
+ throw new OpenAIError(`missing function_call.name for choice ${index}`);
+ }
+ return {
+ ...choiceRest,
+ message: {
+ content,
+ function_call: { arguments: args, name },
+ role,
+ refusal: message.refusal ?? null
+ },
+ finish_reason,
+ index,
+ logprobs
+ };
+ }
+ if (tool_calls) {
+ return {
+ ...choiceRest,
+ index,
+ finish_reason,
+ logprobs,
+ message: {
+ ...messageRest,
+ role,
+ content,
+ refusal: message.refusal ?? null,
+ tool_calls: tool_calls.map((tool_call, i) => {
+ const { function: fn, type: type2, id: id2, ...toolRest } = tool_call;
+ const { arguments: args, name, ...fnRest } = fn || {};
+ if (id2 == null) {
+ throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].id
+${str2(snapshot)}`);
+ }
+ if (type2 == null) {
+ throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].type
+${str2(snapshot)}`);
+ }
+ if (name == null) {
+ throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].function.name
+${str2(snapshot)}`);
+ }
+ if (args == null) {
+ throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].function.arguments
+${str2(snapshot)}`);
+ }
+ return { ...toolRest, id: id2, type: type2, function: { ...fnRest, name, arguments: args } };
+ })
+ }
+ };
+ }
+ return {
+ ...choiceRest,
+ message: { ...messageRest, content, role, refusal: message.refusal ?? null },
+ finish_reason,
+ index,
+ logprobs
+ };
+ }),
+ created,
+ model,
+ object: "chat.completion",
+ ...system_fingerprint ? { system_fingerprint } : {}
+ };
+ return maybeParseChatCompletion(completion2, params);
+}
+__name(finalizeChatCompletion, "finalizeChatCompletion");
+function str2(x) {
+ return JSON.stringify(x);
+}
+__name(str2, "str");
+function assertIsEmpty(obj) {
+ return;
+}
+__name(assertIsEmpty, "assertIsEmpty");
+function assertNever2(_x) {
+}
+__name(assertNever2, "assertNever");
+
+// node_modules/openai/lib/ChatCompletionStreamingRunner.mjs
+var ChatCompletionStreamingRunner = class _ChatCompletionStreamingRunner extends ChatCompletionStream {
+ static {
+ __name(this, "ChatCompletionStreamingRunner");
+ }
+ static fromReadableStream(stream) {
+ const runner = new _ChatCompletionStreamingRunner(null);
+ runner._run(() => runner._fromReadableStream(stream));
+ return runner;
+ }
+ static runTools(client, params, options2) {
+ const runner = new _ChatCompletionStreamingRunner(
+ // @ts-expect-error TODO these types are incompatible
+ params
+ );
+ const opts = {
+ ...options2,
+ headers: { ...options2?.headers, "X-Stainless-Helper-Method": "runTools" }
+ };
+ runner._run(() => runner._runTools(client, params, opts));
+ return runner;
+ }
+};
+
+// node_modules/openai/resources/chat/completions/completions.mjs
+var Completions = class extends APIResource {
+ static {
+ __name(this, "Completions");
+ }
+ constructor() {
+ super(...arguments);
+ this.messages = new Messages(this._client);
+ }
+ create(body, options2) {
+ return this._client.post("/chat/completions", {
+ body,
+ ...options2,
+ stream: body.stream ?? false,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Get a stored chat completion. Only Chat Completions that have been created with
+ * the `store` parameter set to `true` will be returned.
+ *
+ * @example
+ * ```ts
+ * const chatCompletion =
+ * await client.chat.completions.retrieve('completion_id');
+ * ```
+ */
+ retrieve(completionID, options2) {
+ return this._client.get(path15`/chat/completions/${completionID}`, {
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Modify a stored chat completion. Only Chat Completions that have been created
+ * with the `store` parameter set to `true` can be modified. Currently, the only
+ * supported modification is to update the `metadata` field.
+ *
+ * @example
+ * ```ts
+ * const chatCompletion = await client.chat.completions.update(
+ * 'completion_id',
+ * { metadata: { foo: 'string' } },
+ * );
+ * ```
+ */
+ update(completionID, body, options2) {
+ return this._client.post(path15`/chat/completions/${completionID}`, {
+ body,
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * List stored Chat Completions. Only Chat Completions that have been stored with
+ * the `store` parameter set to `true` will be returned.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const chatCompletion of client.chat.completions.list()) {
+ * // ...
+ * }
+ * ```
+ */
+ list(query = {}, options2) {
+ return this._client.getAPIList("/chat/completions", CursorPage, {
+ query,
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Delete a stored chat completion. Only Chat Completions that have been created
+ * with the `store` parameter set to `true` can be deleted.
+ *
+ * @example
+ * ```ts
+ * const chatCompletionDeleted =
+ * await client.chat.completions.delete('completion_id');
+ * ```
+ */
+ delete(completionID, options2) {
+ return this._client.delete(path15`/chat/completions/${completionID}`, {
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ parse(body, options2) {
+ validateInputTools(body.tools);
+ return this._client.chat.completions.create(body, {
+ ...options2,
+ headers: {
+ ...options2?.headers,
+ "X-Stainless-Helper-Method": "chat.completions.parse"
+ }
+ })._thenUnwrap((completion2) => parseChatCompletion(completion2, body));
+ }
+ runTools(body, options2) {
+ if (body.stream) {
+ return ChatCompletionStreamingRunner.runTools(this._client, body, options2);
+ }
+ return ChatCompletionRunner.runTools(this._client, body, options2);
+ }
+ /**
+ * Creates a chat completion stream
+ */
+ stream(body, options2) {
+ return ChatCompletionStream.createChatCompletion(this._client, body, options2);
+ }
+};
+Completions.Messages = Messages;
+
+// node_modules/openai/resources/chat/chat.mjs
+var Chat = class extends APIResource {
+ static {
+ __name(this, "Chat");
+ }
+ constructor() {
+ super(...arguments);
+ this.completions = new Completions(this._client);
+ }
+};
+Chat.Completions = Completions;
+
+// node_modules/openai/resources/chat/completions/index.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/shared.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/admin/admin.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/admin/organization/organization.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/admin/organization/admin-api-keys.mjs
+init_esbuild_shims();
+var AdminAPIKeys = class extends APIResource {
+ static {
+ __name(this, "AdminAPIKeys");
+ }
+ /**
+ * Create an organization admin API key
+ *
+ * @example
+ * ```ts
+ * const adminAPIKey =
+ * await client.admin.organization.adminAPIKeys.create({
+ * name: 'New Admin Key',
+ * });
+ * ```
+ */
+ create(body, options2) {
+ return this._client.post("/organization/admin_api_keys", {
+ body,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieve a single organization API key
+ *
+ * @example
+ * ```ts
+ * const adminAPIKey =
+ * await client.admin.organization.adminAPIKeys.retrieve(
+ * 'key_id',
+ * );
+ * ```
+ */
+ retrieve(keyID, options2) {
+ return this._client.get(path15`/organization/admin_api_keys/${keyID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * List organization API keys
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const adminAPIKey of client.admin.organization.adminAPIKeys.list()) {
+ * // ...
+ * }
+ * ```
+ */
+ list(query = {}, options2) {
+ return this._client.getAPIList("/organization/admin_api_keys", CursorPage, {
+ query,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Delete an organization admin API key
+ *
+ * @example
+ * ```ts
+ * const adminAPIKey =
+ * await client.admin.organization.adminAPIKeys.delete(
+ * 'key_id',
+ * );
+ * ```
+ */
+ delete(keyID, options2) {
+ return this._client.delete(path15`/organization/admin_api_keys/${keyID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/admin/organization/audit-logs.mjs
+init_esbuild_shims();
+var AuditLogs = class extends APIResource {
+ static {
+ __name(this, "AuditLogs");
+ }
+ /**
+ * List user actions and configuration changes within this organization.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const auditLogListResponse of client.admin.organization.auditLogs.list()) {
+ * // ...
+ * }
+ * ```
+ */
+ list(query = {}, options2) {
+ return this._client.getAPIList("/organization/audit_logs", ConversationCursorPage, {
+ query,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/admin/organization/certificates.mjs
+init_esbuild_shims();
+var Certificates = class extends APIResource {
+ static {
+ __name(this, "Certificates");
+ }
+ /**
+ * Upload a certificate to the organization. This does **not** automatically
+ * activate the certificate.
+ *
+ * Organizations can upload up to 50 certificates.
+ *
+ * @example
+ * ```ts
+ * const certificate =
+ * await client.admin.organization.certificates.create({
+ * certificate: 'certificate',
+ * });
+ * ```
+ */
+ create(body, options2) {
+ return this._client.post("/organization/certificates", {
+ body,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Get a certificate that has been uploaded to the organization.
+ *
+ * You can get a certificate regardless of whether it is active or not.
+ *
+ * @example
+ * ```ts
+ * const certificate =
+ * await client.admin.organization.certificates.retrieve(
+ * 'certificate_id',
+ * );
+ * ```
+ */
+ retrieve(certificateID, query = {}, options2) {
+ return this._client.get(path15`/organization/certificates/${certificateID}`, {
+ query,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Modify a certificate. Note that only the name can be modified.
+ *
+ * @example
+ * ```ts
+ * const certificate =
+ * await client.admin.organization.certificates.update(
+ * 'certificate_id',
+ * );
+ * ```
+ */
+ update(certificateID, body, options2) {
+ return this._client.post(path15`/organization/certificates/${certificateID}`, {
+ body,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * List uploaded certificates for this organization.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const certificateListResponse of client.admin.organization.certificates.list()) {
+ * // ...
+ * }
+ * ```
+ */
+ list(query = {}, options2) {
+ return this._client.getAPIList("/organization/certificates", ConversationCursorPage, { query, ...options2, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Delete a certificate from the organization.
+ *
+ * The certificate must be inactive for the organization and all projects.
+ *
+ * @example
+ * ```ts
+ * const certificate =
+ * await client.admin.organization.certificates.delete(
+ * 'certificate_id',
+ * );
+ * ```
+ */
+ delete(certificateID, options2) {
+ return this._client.delete(path15`/organization/certificates/${certificateID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Activate certificates at the organization level.
+ *
+ * You can atomically and idempotently activate up to 10 certificates at a time.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const certificateActivateResponse of client.admin.organization.certificates.activate(
+ * { certificate_ids: ['cert_abc'] },
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ activate(body, options2) {
+ return this._client.getAPIList("/organization/certificates/activate", Page, {
+ body,
+ method: "post",
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Deactivate certificates at the organization level.
+ *
+ * You can atomically and idempotently deactivate up to 10 certificates at a time.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const certificateDeactivateResponse of client.admin.organization.certificates.deactivate(
+ * { certificate_ids: ['cert_abc'] },
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ deactivate(body, options2) {
+ return this._client.getAPIList("/organization/certificates/deactivate", Page, { body, method: "post", ...options2, __security: { adminAPIKeyAuth: true } });
+ }
+};
+
+// node_modules/openai/resources/admin/organization/data-retention.mjs
+init_esbuild_shims();
+var DataRetention = class extends APIResource {
+ static {
+ __name(this, "DataRetention");
+ }
+ /**
+ * Retrieves organization data retention controls.
+ *
+ * @example
+ * ```ts
+ * const organizationDataRetention =
+ * await client.admin.organization.dataRetention.retrieve();
+ * ```
+ */
+ retrieve(options2) {
+ return this._client.get("/organization/data_retention", {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Updates organization data retention controls.
+ *
+ * @example
+ * ```ts
+ * const organizationDataRetention =
+ * await client.admin.organization.dataRetention.update({
+ * retention_type: 'zero_data_retention',
+ * });
+ * ```
+ */
+ update(body, options2) {
+ return this._client.post("/organization/data_retention", {
+ body,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/admin/organization/invites.mjs
+init_esbuild_shims();
+var Invites = class extends APIResource {
+ static {
+ __name(this, "Invites");
+ }
+ /**
+ * Create an invite for a user to the organization. The invite must be accepted by
+ * the user before they have access to the organization.
+ *
+ * @example
+ * ```ts
+ * const invite =
+ * await client.admin.organization.invites.create({
+ * email: 'email',
+ * role: 'reader',
+ * });
+ * ```
+ */
+ create(body, options2) {
+ return this._client.post("/organization/invites", {
+ body,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieves an invite.
+ *
+ * @example
+ * ```ts
+ * const invite =
+ * await client.admin.organization.invites.retrieve(
+ * 'invite_id',
+ * );
+ * ```
+ */
+ retrieve(inviteID, options2) {
+ return this._client.get(path15`/organization/invites/${inviteID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Returns a list of invites in the organization.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const invite of client.admin.organization.invites.list()) {
+ * // ...
+ * }
+ * ```
+ */
+ list(query = {}, options2) {
+ return this._client.getAPIList("/organization/invites", ConversationCursorPage, {
+ query,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Delete an invite. If the invite has already been accepted, it cannot be deleted.
+ *
+ * @example
+ * ```ts
+ * const invite =
+ * await client.admin.organization.invites.delete(
+ * 'invite_id',
+ * );
+ * ```
+ */
+ delete(inviteID, options2) {
+ return this._client.delete(path15`/organization/invites/${inviteID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/admin/organization/roles.mjs
+init_esbuild_shims();
+var Roles = class extends APIResource {
+ static {
+ __name(this, "Roles");
+ }
+ /**
+ * Creates a custom role for the organization.
+ *
+ * @example
+ * ```ts
+ * const role = await client.admin.organization.roles.create({
+ * permissions: ['string'],
+ * role_name: 'role_name',
+ * });
+ * ```
+ */
+ create(body, options2) {
+ return this._client.post("/organization/roles", {
+ body,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieves an organization role.
+ *
+ * @example
+ * ```ts
+ * const role = await client.admin.organization.roles.retrieve(
+ * 'role_id',
+ * );
+ * ```
+ */
+ retrieve(roleID, options2) {
+ return this._client.get(path15`/organization/roles/${roleID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Updates an existing organization role.
+ *
+ * @example
+ * ```ts
+ * const role = await client.admin.organization.roles.update(
+ * 'role_id',
+ * );
+ * ```
+ */
+ update(roleID, body, options2) {
+ return this._client.post(path15`/organization/roles/${roleID}`, {
+ body,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Lists the roles configured for the organization.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const role of client.admin.organization.roles.list()) {
+ * // ...
+ * }
+ * ```
+ */
+ list(query = {}, options2) {
+ return this._client.getAPIList("/organization/roles", NextCursorPage, {
+ query,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Deletes a custom role from the organization.
+ *
+ * @example
+ * ```ts
+ * const role = await client.admin.organization.roles.delete(
+ * 'role_id',
+ * );
+ * ```
+ */
+ delete(roleID, options2) {
+ return this._client.delete(path15`/organization/roles/${roleID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/admin/organization/spend-alerts.mjs
+init_esbuild_shims();
+var SpendAlerts = class extends APIResource {
+ static {
+ __name(this, "SpendAlerts");
+ }
+ /**
+ * Creates an organization spend alert.
+ *
+ * @example
+ * ```ts
+ * const organizationSpendAlert =
+ * await client.admin.organization.spendAlerts.create({
+ * currency: 'USD',
+ * interval: 'month',
+ * notification_channel: {
+ * recipients: ['string'],
+ * type: 'email',
+ * },
+ * threshold_amount: 0,
+ * });
+ * ```
+ */
+ create(body, options2) {
+ return this._client.post("/organization/spend_alerts", {
+ body,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieves an organization spend alert.
+ *
+ * @example
+ * ```ts
+ * const organizationSpendAlert =
+ * await client.admin.organization.spendAlerts.retrieve(
+ * 'alert_id',
+ * );
+ * ```
+ */
+ retrieve(alertID, options2) {
+ return this._client.get(path15`/organization/spend_alerts/${alertID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Updates an organization spend alert.
+ *
+ * @example
+ * ```ts
+ * const organizationSpendAlert =
+ * await client.admin.organization.spendAlerts.update(
+ * 'alert_id',
+ * {
+ * currency: 'USD',
+ * interval: 'month',
+ * notification_channel: {
+ * recipients: ['string'],
+ * type: 'email',
+ * },
+ * threshold_amount: 0,
+ * },
+ * );
+ * ```
+ */
+ update(alertID, body, options2) {
+ return this._client.post(path15`/organization/spend_alerts/${alertID}`, {
+ body,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Lists organization spend alerts.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const organizationSpendAlert of client.admin.organization.spendAlerts.list()) {
+ * // ...
+ * }
+ * ```
+ */
+ list(query = {}, options2) {
+ return this._client.getAPIList("/organization/spend_alerts", ConversationCursorPage, { query, ...options2, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Deletes an organization spend alert.
+ *
+ * @example
+ * ```ts
+ * const organizationSpendAlertDeleted =
+ * await client.admin.organization.spendAlerts.delete(
+ * 'alert_id',
+ * );
+ * ```
+ */
+ delete(alertID, options2) {
+ return this._client.delete(path15`/organization/spend_alerts/${alertID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/admin/organization/usage.mjs
+init_esbuild_shims();
+var Usage = class extends APIResource {
+ static {
+ __name(this, "Usage");
+ }
+ /**
+ * Get audio speeches usage details for the organization.
+ *
+ * @example
+ * ```ts
+ * const response =
+ * await client.admin.organization.usage.audioSpeeches({
+ * start_time: 0,
+ * });
+ * ```
+ */
+ audioSpeeches(query, options2) {
+ return this._client.get("/organization/usage/audio_speeches", {
+ query,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Get audio transcriptions usage details for the organization.
+ *
+ * @example
+ * ```ts
+ * const response =
+ * await client.admin.organization.usage.audioTranscriptions(
+ * { start_time: 0 },
+ * );
+ * ```
+ */
+ audioTranscriptions(query, options2) {
+ return this._client.get("/organization/usage/audio_transcriptions", {
+ query,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Get code interpreter sessions usage details for the organization.
+ *
+ * @example
+ * ```ts
+ * const response =
+ * await client.admin.organization.usage.codeInterpreterSessions(
+ * { start_time: 0 },
+ * );
+ * ```
+ */
+ codeInterpreterSessions(query, options2) {
+ return this._client.get("/organization/usage/code_interpreter_sessions", {
+ query,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Get completions usage details for the organization.
+ *
+ * @example
+ * ```ts
+ * const response =
+ * await client.admin.organization.usage.completions({
+ * start_time: 0,
+ * });
+ * ```
+ */
+ completions(query, options2) {
+ return this._client.get("/organization/usage/completions", {
+ query,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Get costs details for the organization.
+ *
+ * @example
+ * ```ts
+ * const response =
+ * await client.admin.organization.usage.costs({
+ * start_time: 0,
+ * });
+ * ```
+ */
+ costs(query, options2) {
+ return this._client.get("/organization/costs", {
+ query,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Get embeddings usage details for the organization.
+ *
+ * @example
+ * ```ts
+ * const response =
+ * await client.admin.organization.usage.embeddings({
+ * start_time: 0,
+ * });
+ * ```
+ */
+ embeddings(query, options2) {
+ return this._client.get("/organization/usage/embeddings", {
+ query,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Get file search calls usage details for the organization.
+ *
+ * @example
+ * ```ts
+ * const response =
+ * await client.admin.organization.usage.fileSearchCalls({
+ * start_time: 0,
+ * });
+ * ```
+ */
+ fileSearchCalls(query, options2) {
+ return this._client.get("/organization/usage/file_search_calls", {
+ query,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Get images usage details for the organization.
+ *
+ * @example
+ * ```ts
+ * const response =
+ * await client.admin.organization.usage.images({
+ * start_time: 0,
+ * });
+ * ```
+ */
+ images(query, options2) {
+ return this._client.get("/organization/usage/images", {
+ query,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Get moderations usage details for the organization.
+ *
+ * @example
+ * ```ts
+ * const response =
+ * await client.admin.organization.usage.moderations({
+ * start_time: 0,
+ * });
+ * ```
+ */
+ moderations(query, options2) {
+ return this._client.get("/organization/usage/moderations", {
+ query,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Get vector stores usage details for the organization.
+ *
+ * @example
+ * ```ts
+ * const response =
+ * await client.admin.organization.usage.vectorStores({
+ * start_time: 0,
+ * });
+ * ```
+ */
+ vectorStores(query, options2) {
+ return this._client.get("/organization/usage/vector_stores", {
+ query,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Get web search calls usage details for the organization.
+ *
+ * @example
+ * ```ts
+ * const response =
+ * await client.admin.organization.usage.webSearchCalls({
+ * start_time: 0,
+ * });
+ * ```
+ */
+ webSearchCalls(query, options2) {
+ return this._client.get("/organization/usage/web_search_calls", {
+ query,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/admin/organization/groups/groups.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/admin/organization/groups/roles.mjs
+init_esbuild_shims();
+var Roles2 = class extends APIResource {
+ static {
+ __name(this, "Roles");
+ }
+ /**
+ * Assigns an organization role to a group within the organization.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.groups.roles.create(
+ * 'group_id',
+ * { role_id: 'role_id' },
+ * );
+ * ```
+ */
+ create(groupID, body, options2) {
+ return this._client.post(path15`/organization/groups/${groupID}/roles`, {
+ body,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieves an organization role assigned to a group.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.groups.roles.retrieve(
+ * 'role_id',
+ * { group_id: 'group_id' },
+ * );
+ * ```
+ */
+ retrieve(roleID, params, options2) {
+ const { group_id } = params;
+ return this._client.get(path15`/organization/groups/${group_id}/roles/${roleID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Lists the organization roles assigned to a group within the organization.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const roleListResponse of client.admin.organization.groups.roles.list(
+ * 'group_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(groupID, query = {}, options2) {
+ return this._client.getAPIList(path15`/organization/groups/${groupID}/roles`, NextCursorPage, { query, ...options2, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Unassigns an organization role from a group within the organization.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.groups.roles.delete(
+ * 'role_id',
+ * { group_id: 'group_id' },
+ * );
+ * ```
+ */
+ delete(roleID, params, options2) {
+ const { group_id } = params;
+ return this._client.delete(path15`/organization/groups/${group_id}/roles/${roleID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/admin/organization/groups/users.mjs
+init_esbuild_shims();
+var Users = class extends APIResource {
+ static {
+ __name(this, "Users");
+ }
+ /**
+ * Adds a user to a group.
+ *
+ * @example
+ * ```ts
+ * const user =
+ * await client.admin.organization.groups.users.create(
+ * 'group_id',
+ * { user_id: 'user_id' },
+ * );
+ * ```
+ */
+ create(groupID, body, options2) {
+ return this._client.post(path15`/organization/groups/${groupID}/users`, {
+ body,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieves a user in a group.
+ *
+ * @example
+ * ```ts
+ * const user =
+ * await client.admin.organization.groups.users.retrieve(
+ * 'user_id',
+ * { group_id: 'group_id' },
+ * );
+ * ```
+ */
+ retrieve(userID, params, options2) {
+ const { group_id } = params;
+ return this._client.get(path15`/organization/groups/${group_id}/users/${userID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Lists the users assigned to a group.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const organizationGroupUser of client.admin.organization.groups.users.list(
+ * 'group_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(groupID, query = {}, options2) {
+ return this._client.getAPIList(path15`/organization/groups/${groupID}/users`, NextCursorPage, { query, ...options2, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Removes a user from a group.
+ *
+ * @example
+ * ```ts
+ * const user =
+ * await client.admin.organization.groups.users.delete(
+ * 'user_id',
+ * { group_id: 'group_id' },
+ * );
+ * ```
+ */
+ delete(userID, params, options2) {
+ const { group_id } = params;
+ return this._client.delete(path15`/organization/groups/${group_id}/users/${userID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/admin/organization/groups/groups.mjs
+var Groups = class extends APIResource {
+ static {
+ __name(this, "Groups");
+ }
+ constructor() {
+ super(...arguments);
+ this.users = new Users(this._client);
+ this.roles = new Roles2(this._client);
+ }
+ /**
+ * Creates a new group in the organization.
+ *
+ * @example
+ * ```ts
+ * const group = await client.admin.organization.groups.create(
+ * { name: 'x' },
+ * );
+ * ```
+ */
+ create(body, options2) {
+ return this._client.post("/organization/groups", {
+ body,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieves a group.
+ *
+ * @example
+ * ```ts
+ * const group =
+ * await client.admin.organization.groups.retrieve(
+ * 'group_id',
+ * );
+ * ```
+ */
+ retrieve(groupID, options2) {
+ return this._client.get(path15`/organization/groups/${groupID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Updates a group's information.
+ *
+ * @example
+ * ```ts
+ * const group = await client.admin.organization.groups.update(
+ * 'group_id',
+ * { name: 'x' },
+ * );
+ * ```
+ */
+ update(groupID, body, options2) {
+ return this._client.post(path15`/organization/groups/${groupID}`, {
+ body,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Lists all groups in the organization.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const group of client.admin.organization.groups.list()) {
+ * // ...
+ * }
+ * ```
+ */
+ list(query = {}, options2) {
+ return this._client.getAPIList("/organization/groups", NextCursorPage, {
+ query,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Deletes a group from the organization.
+ *
+ * @example
+ * ```ts
+ * const group = await client.admin.organization.groups.delete(
+ * 'group_id',
+ * );
+ * ```
+ */
+ delete(groupID, options2) {
+ return this._client.delete(path15`/organization/groups/${groupID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+};
+Groups.Users = Users;
+Groups.Roles = Roles2;
+
+// node_modules/openai/resources/admin/organization/projects/projects.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/admin/organization/projects/api-keys.mjs
+init_esbuild_shims();
+var APIKeys = class extends APIResource {
+ static {
+ __name(this, "APIKeys");
+ }
+ /**
+ * Retrieves an API key in the project.
+ *
+ * @example
+ * ```ts
+ * const projectAPIKey =
+ * await client.admin.organization.projects.apiKeys.retrieve(
+ * 'api_key_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ retrieve(apiKeyID, params, options2) {
+ const { project_id } = params;
+ return this._client.get(path15`/organization/projects/${project_id}/api_keys/${apiKeyID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Returns a list of API keys in the project.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const projectAPIKey of client.admin.organization.projects.apiKeys.list(
+ * 'project_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(projectID, query = {}, options2) {
+ return this._client.getAPIList(path15`/organization/projects/${projectID}/api_keys`, ConversationCursorPage, { query, ...options2, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Deletes an API key from the project.
+ *
+ * Returns confirmation of the key deletion, or an error if the key belonged to a
+ * service account.
+ *
+ * @example
+ * ```ts
+ * const apiKey =
+ * await client.admin.organization.projects.apiKeys.delete(
+ * 'api_key_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ delete(apiKeyID, params, options2) {
+ const { project_id } = params;
+ return this._client.delete(path15`/organization/projects/${project_id}/api_keys/${apiKeyID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/admin/organization/projects/certificates.mjs
+init_esbuild_shims();
+var Certificates2 = class extends APIResource {
+ static {
+ __name(this, "Certificates");
+ }
+ /**
+ * List certificates for this project.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const certificateListResponse of client.admin.organization.projects.certificates.list(
+ * 'project_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(projectID, query = {}, options2) {
+ return this._client.getAPIList(path15`/organization/projects/${projectID}/certificates`, ConversationCursorPage, { query, ...options2, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Activate certificates at the project level.
+ *
+ * You can atomically and idempotently activate up to 10 certificates at a time.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const certificateActivateResponse of client.admin.organization.projects.certificates.activate(
+ * 'project_id',
+ * { certificate_ids: ['cert_abc'] },
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ activate(projectID, body, options2) {
+ return this._client.getAPIList(path15`/organization/projects/${projectID}/certificates/activate`, Page, { body, method: "post", ...options2, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Deactivate certificates at the project level. You can atomically and
+ * idempotently deactivate up to 10 certificates at a time.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const certificateDeactivateResponse of client.admin.organization.projects.certificates.deactivate(
+ * 'project_id',
+ * { certificate_ids: ['cert_abc'] },
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ deactivate(projectID, body, options2) {
+ return this._client.getAPIList(path15`/organization/projects/${projectID}/certificates/deactivate`, Page, { body, method: "post", ...options2, __security: { adminAPIKeyAuth: true } });
+ }
+};
+
+// node_modules/openai/resources/admin/organization/projects/data-retention.mjs
+init_esbuild_shims();
+var DataRetention2 = class extends APIResource {
+ static {
+ __name(this, "DataRetention");
+ }
+ /**
+ * Retrieves project data retention controls.
+ *
+ * @example
+ * ```ts
+ * const projectDataRetention =
+ * await client.admin.organization.projects.dataRetention.retrieve(
+ * 'project_id',
+ * );
+ * ```
+ */
+ retrieve(projectID, options2) {
+ return this._client.get(path15`/organization/projects/${projectID}/data_retention`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Updates project data retention controls.
+ *
+ * @example
+ * ```ts
+ * const projectDataRetention =
+ * await client.admin.organization.projects.dataRetention.update(
+ * 'project_id',
+ * { retention_type: 'organization_default' },
+ * );
+ * ```
+ */
+ update(projectID, body, options2) {
+ return this._client.post(path15`/organization/projects/${projectID}/data_retention`, {
+ body,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/admin/organization/projects/hosted-tool-permissions.mjs
+init_esbuild_shims();
+var HostedToolPermissions = class extends APIResource {
+ static {
+ __name(this, "HostedToolPermissions");
+ }
+ /**
+ * Returns hosted tool permissions for a project.
+ *
+ * @example
+ * ```ts
+ * const projectHostedToolPermissions =
+ * await client.admin.organization.projects.hostedToolPermissions.retrieve(
+ * 'project_id',
+ * );
+ * ```
+ */
+ retrieve(projectID, options2) {
+ return this._client.get(path15`/organization/projects/${projectID}/hosted_tool_permissions`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Updates hosted tool permissions for a project.
+ *
+ * @example
+ * ```ts
+ * const projectHostedToolPermissions =
+ * await client.admin.organization.projects.hostedToolPermissions.update(
+ * 'project_id',
+ * );
+ * ```
+ */
+ update(projectID, body, options2) {
+ return this._client.post(path15`/organization/projects/${projectID}/hosted_tool_permissions`, {
+ body,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/admin/organization/projects/model-permissions.mjs
+init_esbuild_shims();
+var ModelPermissions = class extends APIResource {
+ static {
+ __name(this, "ModelPermissions");
+ }
+ /**
+ * Returns model permissions for a project.
+ *
+ * @example
+ * ```ts
+ * const projectModelPermissions =
+ * await client.admin.organization.projects.modelPermissions.retrieve(
+ * 'project_id',
+ * );
+ * ```
+ */
+ retrieve(projectID, options2) {
+ return this._client.get(path15`/organization/projects/${projectID}/model_permissions`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Updates model permissions for a project.
+ *
+ * @example
+ * ```ts
+ * const projectModelPermissions =
+ * await client.admin.organization.projects.modelPermissions.update(
+ * 'project_id',
+ * { mode: 'allow_list', model_ids: ['string'] },
+ * );
+ * ```
+ */
+ update(projectID, body, options2) {
+ return this._client.post(path15`/organization/projects/${projectID}/model_permissions`, {
+ body,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Deletes model permissions for a project.
+ *
+ * @example
+ * ```ts
+ * const projectModelPermissionsDeleted =
+ * await client.admin.organization.projects.modelPermissions.delete(
+ * 'project_id',
+ * );
+ * ```
+ */
+ delete(projectID, options2) {
+ return this._client.delete(path15`/organization/projects/${projectID}/model_permissions`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/admin/organization/projects/rate-limits.mjs
+init_esbuild_shims();
+var RateLimits = class extends APIResource {
+ static {
+ __name(this, "RateLimits");
+ }
+ /**
+ * Returns the rate limits per model for a project.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const projectRateLimit of client.admin.organization.projects.rateLimits.listRateLimits(
+ * 'project_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ listRateLimits(projectID, query = {}, options2) {
+ return this._client.getAPIList(path15`/organization/projects/${projectID}/rate_limits`, ConversationCursorPage, { query, ...options2, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Updates a project rate limit.
+ *
+ * @example
+ * ```ts
+ * const projectRateLimit =
+ * await client.admin.organization.projects.rateLimits.updateRateLimit(
+ * 'rate_limit_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ updateRateLimit(rateLimitID, params, options2) {
+ const { project_id, ...body } = params;
+ return this._client.post(path15`/organization/projects/${project_id}/rate_limits/${rateLimitID}`, {
+ body,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/admin/organization/projects/roles.mjs
+init_esbuild_shims();
+var Roles3 = class extends APIResource {
+ static {
+ __name(this, "Roles");
+ }
+ /**
+ * Creates a custom role for a project.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.projects.roles.create(
+ * 'project_id',
+ * { permissions: ['string'], role_name: 'role_name' },
+ * );
+ * ```
+ */
+ create(projectID, body, options2) {
+ return this._client.post(path15`/projects/${projectID}/roles`, {
+ body,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieves a project role.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.projects.roles.retrieve(
+ * 'role_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ retrieve(roleID, params, options2) {
+ const { project_id } = params;
+ return this._client.get(path15`/projects/${project_id}/roles/${roleID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Updates an existing project role.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.projects.roles.update(
+ * 'role_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ update(roleID, params, options2) {
+ const { project_id, ...body } = params;
+ return this._client.post(path15`/projects/${project_id}/roles/${roleID}`, {
+ body,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Lists the roles configured for a project.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const role of client.admin.organization.projects.roles.list(
+ * 'project_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(projectID, query = {}, options2) {
+ return this._client.getAPIList(path15`/projects/${projectID}/roles`, NextCursorPage, {
+ query,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Deletes a custom role from a project.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.projects.roles.delete(
+ * 'role_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ delete(roleID, params, options2) {
+ const { project_id } = params;
+ return this._client.delete(path15`/projects/${project_id}/roles/${roleID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/admin/organization/projects/service-accounts.mjs
+init_esbuild_shims();
+var ServiceAccounts = class extends APIResource {
+ static {
+ __name(this, "ServiceAccounts");
+ }
+ /**
+ * Creates a new service account in the project. This also returns an unredacted
+ * API key for the service account.
+ *
+ * @example
+ * ```ts
+ * const serviceAccount =
+ * await client.admin.organization.projects.serviceAccounts.create(
+ * 'project_id',
+ * { name: 'name' },
+ * );
+ * ```
+ */
+ create(projectID, body, options2) {
+ return this._client.post(path15`/organization/projects/${projectID}/service_accounts`, {
+ body,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieves a service account in the project.
+ *
+ * @example
+ * ```ts
+ * const projectServiceAccount =
+ * await client.admin.organization.projects.serviceAccounts.retrieve(
+ * 'service_account_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ retrieve(serviceAccountID, params, options2) {
+ const { project_id } = params;
+ return this._client.get(path15`/organization/projects/${project_id}/service_accounts/${serviceAccountID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Updates a service account in the project.
+ *
+ * @example
+ * ```ts
+ * const projectServiceAccount =
+ * await client.admin.organization.projects.serviceAccounts.update(
+ * 'service_account_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ update(serviceAccountID, params, options2) {
+ const { project_id, ...body } = params;
+ return this._client.post(path15`/organization/projects/${project_id}/service_accounts/${serviceAccountID}`, { body, ...options2, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Returns a list of service accounts in the project.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const projectServiceAccount of client.admin.organization.projects.serviceAccounts.list(
+ * 'project_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(projectID, query = {}, options2) {
+ return this._client.getAPIList(path15`/organization/projects/${projectID}/service_accounts`, ConversationCursorPage, { query, ...options2, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Deletes a service account from the project.
+ *
+ * Returns confirmation of service account deletion, or an error if the project is
+ * archived (archived projects have no service accounts).
+ *
+ * @example
+ * ```ts
+ * const serviceAccount =
+ * await client.admin.organization.projects.serviceAccounts.delete(
+ * 'service_account_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ delete(serviceAccountID, params, options2) {
+ const { project_id } = params;
+ return this._client.delete(path15`/organization/projects/${project_id}/service_accounts/${serviceAccountID}`, { ...options2, __security: { adminAPIKeyAuth: true } });
+ }
+};
+
+// node_modules/openai/resources/admin/organization/projects/spend-alerts.mjs
+init_esbuild_shims();
+var SpendAlerts2 = class extends APIResource {
+ static {
+ __name(this, "SpendAlerts");
+ }
+ /**
+ * Creates a project spend alert.
+ *
+ * @example
+ * ```ts
+ * const projectSpendAlert =
+ * await client.admin.organization.projects.spendAlerts.create(
+ * 'project_id',
+ * {
+ * currency: 'USD',
+ * interval: 'month',
+ * notification_channel: {
+ * recipients: ['string'],
+ * type: 'email',
+ * },
+ * threshold_amount: 0,
+ * },
+ * );
+ * ```
+ */
+ create(projectID, body, options2) {
+ return this._client.post(path15`/organization/projects/${projectID}/spend_alerts`, {
+ body,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieves a project spend alert.
+ *
+ * @example
+ * ```ts
+ * const projectSpendAlert =
+ * await client.admin.organization.projects.spendAlerts.retrieve(
+ * 'alert_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ retrieve(alertID, params, options2) {
+ const { project_id } = params;
+ return this._client.get(path15`/organization/projects/${project_id}/spend_alerts/${alertID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Updates a project spend alert.
+ *
+ * @example
+ * ```ts
+ * const projectSpendAlert =
+ * await client.admin.organization.projects.spendAlerts.update(
+ * 'alert_id',
+ * {
+ * project_id: 'project_id',
+ * currency: 'USD',
+ * interval: 'month',
+ * notification_channel: {
+ * recipients: ['string'],
+ * type: 'email',
+ * },
+ * threshold_amount: 0,
+ * },
+ * );
+ * ```
+ */
+ update(alertID, params, options2) {
+ const { project_id, ...body } = params;
+ return this._client.post(path15`/organization/projects/${project_id}/spend_alerts/${alertID}`, {
+ body,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Lists project spend alerts.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const projectSpendAlert of client.admin.organization.projects.spendAlerts.list(
+ * 'project_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(projectID, query = {}, options2) {
+ return this._client.getAPIList(path15`/organization/projects/${projectID}/spend_alerts`, ConversationCursorPage, { query, ...options2, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Deletes a project spend alert.
+ *
+ * @example
+ * ```ts
+ * const projectSpendAlertDeleted =
+ * await client.admin.organization.projects.spendAlerts.delete(
+ * 'alert_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ delete(alertID, params, options2) {
+ const { project_id } = params;
+ return this._client.delete(path15`/organization/projects/${project_id}/spend_alerts/${alertID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/admin/organization/projects/groups/groups.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/admin/organization/projects/groups/roles.mjs
+init_esbuild_shims();
+var Roles4 = class extends APIResource {
+ static {
+ __name(this, "Roles");
+ }
+ /**
+ * Assigns a project role to a group within a project.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.projects.groups.roles.create(
+ * 'group_id',
+ * { project_id: 'project_id', role_id: 'role_id' },
+ * );
+ * ```
+ */
+ create(groupID, params, options2) {
+ const { project_id, ...body } = params;
+ return this._client.post(path15`/projects/${project_id}/groups/${groupID}/roles`, {
+ body,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieves a project role assigned to a group.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.projects.groups.roles.retrieve(
+ * 'role_id',
+ * { project_id: 'project_id', group_id: 'group_id' },
+ * );
+ * ```
+ */
+ retrieve(roleID, params, options2) {
+ const { project_id, group_id } = params;
+ return this._client.get(path15`/projects/${project_id}/groups/${group_id}/roles/${roleID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Lists the project roles assigned to a group within a project.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const roleListResponse of client.admin.organization.projects.groups.roles.list(
+ * 'group_id',
+ * { project_id: 'project_id' },
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(groupID, params, options2) {
+ const { project_id, ...query } = params;
+ return this._client.getAPIList(path15`/projects/${project_id}/groups/${groupID}/roles`, NextCursorPage, { query, ...options2, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Unassigns a project role from a group within a project.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.projects.groups.roles.delete(
+ * 'role_id',
+ * { project_id: 'project_id', group_id: 'group_id' },
+ * );
+ * ```
+ */
+ delete(roleID, params, options2) {
+ const { project_id, group_id } = params;
+ return this._client.delete(path15`/projects/${project_id}/groups/${group_id}/roles/${roleID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/admin/organization/projects/groups/groups.mjs
+var Groups2 = class extends APIResource {
+ static {
+ __name(this, "Groups");
+ }
+ constructor() {
+ super(...arguments);
+ this.roles = new Roles4(this._client);
+ }
+ /**
+ * Grants a group access to a project.
+ *
+ * @example
+ * ```ts
+ * const projectGroup =
+ * await client.admin.organization.projects.groups.create(
+ * 'project_id',
+ * { group_id: 'group_id', role: 'role' },
+ * );
+ * ```
+ */
+ create(projectID, body, options2) {
+ return this._client.post(path15`/organization/projects/${projectID}/groups`, {
+ body,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieves a project's group.
+ *
+ * @example
+ * ```ts
+ * const projectGroup =
+ * await client.admin.organization.projects.groups.retrieve(
+ * 'group_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ retrieve(groupID, params, options2) {
+ const { project_id, ...query } = params;
+ return this._client.get(path15`/organization/projects/${project_id}/groups/${groupID}`, {
+ query,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Lists the groups that have access to a project.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const projectGroup of client.admin.organization.projects.groups.list(
+ * 'project_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(projectID, query = {}, options2) {
+ return this._client.getAPIList(path15`/organization/projects/${projectID}/groups`, NextCursorPage, { query, ...options2, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Revokes a group's access to a project.
+ *
+ * @example
+ * ```ts
+ * const group =
+ * await client.admin.organization.projects.groups.delete(
+ * 'group_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ delete(groupID, params, options2) {
+ const { project_id } = params;
+ return this._client.delete(path15`/organization/projects/${project_id}/groups/${groupID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+};
+Groups2.Roles = Roles4;
+
+// node_modules/openai/resources/admin/organization/projects/users/users.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/admin/organization/projects/users/roles.mjs
+init_esbuild_shims();
+var Roles5 = class extends APIResource {
+ static {
+ __name(this, "Roles");
+ }
+ /**
+ * Assigns a project role to a user within a project.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.projects.users.roles.create(
+ * 'user_id',
+ * { project_id: 'project_id', role_id: 'role_id' },
+ * );
+ * ```
+ */
+ create(userID, params, options2) {
+ const { project_id, ...body } = params;
+ return this._client.post(path15`/projects/${project_id}/users/${userID}/roles`, {
+ body,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieves a project role assigned to a user.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.projects.users.roles.retrieve(
+ * 'role_id',
+ * { project_id: 'project_id', user_id: 'user_id' },
+ * );
+ * ```
+ */
+ retrieve(roleID, params, options2) {
+ const { project_id, user_id } = params;
+ return this._client.get(path15`/projects/${project_id}/users/${user_id}/roles/${roleID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Lists the project roles assigned to a user within a project.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const roleListResponse of client.admin.organization.projects.users.roles.list(
+ * 'user_id',
+ * { project_id: 'project_id' },
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(userID, params, options2) {
+ const { project_id, ...query } = params;
+ return this._client.getAPIList(path15`/projects/${project_id}/users/${userID}/roles`, NextCursorPage, { query, ...options2, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Unassigns a project role from a user within a project.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.projects.users.roles.delete(
+ * 'role_id',
+ * { project_id: 'project_id', user_id: 'user_id' },
+ * );
+ * ```
+ */
+ delete(roleID, params, options2) {
+ const { project_id, user_id } = params;
+ return this._client.delete(path15`/projects/${project_id}/users/${user_id}/roles/${roleID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/admin/organization/projects/users/users.mjs
+var Users2 = class extends APIResource {
+ static {
+ __name(this, "Users");
+ }
+ constructor() {
+ super(...arguments);
+ this.roles = new Roles5(this._client);
+ }
+ /**
+ * Adds a user to the project. Users must already be members of the organization to
+ * be added to a project.
+ *
+ * @example
+ * ```ts
+ * const projectUser =
+ * await client.admin.organization.projects.users.create(
+ * 'project_id',
+ * { role: 'role' },
+ * );
+ * ```
+ */
+ create(projectID, body, options2) {
+ return this._client.post(path15`/organization/projects/${projectID}/users`, {
+ body,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieves a user in the project.
+ *
+ * @example
+ * ```ts
+ * const projectUser =
+ * await client.admin.organization.projects.users.retrieve(
+ * 'user_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ retrieve(userID, params, options2) {
+ const { project_id } = params;
+ return this._client.get(path15`/organization/projects/${project_id}/users/${userID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Modifies a user's role in the project.
+ *
+ * @example
+ * ```ts
+ * const projectUser =
+ * await client.admin.organization.projects.users.update(
+ * 'user_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ update(userID, params, options2) {
+ const { project_id, ...body } = params;
+ return this._client.post(path15`/organization/projects/${project_id}/users/${userID}`, {
+ body,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Returns a list of users in the project.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const projectUser of client.admin.organization.projects.users.list(
+ * 'project_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(projectID, query = {}, options2) {
+ return this._client.getAPIList(path15`/organization/projects/${projectID}/users`, ConversationCursorPage, { query, ...options2, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Deletes a user from the project.
+ *
+ * Returns confirmation of project user deletion, or an error if the project is
+ * archived (archived projects have no users).
+ *
+ * @example
+ * ```ts
+ * const user =
+ * await client.admin.organization.projects.users.delete(
+ * 'user_id',
+ * { project_id: 'project_id' },
+ * );
+ * ```
+ */
+ delete(userID, params, options2) {
+ const { project_id } = params;
+ return this._client.delete(path15`/organization/projects/${project_id}/users/${userID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+};
+Users2.Roles = Roles5;
+
+// node_modules/openai/resources/admin/organization/projects/projects.mjs
+var Projects = class extends APIResource {
+ static {
+ __name(this, "Projects");
+ }
+ constructor() {
+ super(...arguments);
+ this.users = new Users2(this._client);
+ this.serviceAccounts = new ServiceAccounts(this._client);
+ this.apiKeys = new APIKeys(this._client);
+ this.rateLimits = new RateLimits(this._client);
+ this.modelPermissions = new ModelPermissions(this._client);
+ this.hostedToolPermissions = new HostedToolPermissions(this._client);
+ this.groups = new Groups2(this._client);
+ this.roles = new Roles3(this._client);
+ this.dataRetention = new DataRetention2(this._client);
+ this.spendAlerts = new SpendAlerts2(this._client);
+ this.certificates = new Certificates2(this._client);
+ }
+ /**
+ * Create a new project in the organization. Projects can be created and archived,
+ * but cannot be deleted.
+ *
+ * @example
+ * ```ts
+ * const project =
+ * await client.admin.organization.projects.create({
+ * name: 'name',
+ * });
+ * ```
+ */
+ create(body, options2) {
+ return this._client.post("/organization/projects", {
+ body,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieves a project.
+ *
+ * @example
+ * ```ts
+ * const project =
+ * await client.admin.organization.projects.retrieve(
+ * 'project_id',
+ * );
+ * ```
+ */
+ retrieve(projectID, options2) {
+ return this._client.get(path15`/organization/projects/${projectID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Modifies a project in the organization.
+ *
+ * @example
+ * ```ts
+ * const project =
+ * await client.admin.organization.projects.update(
+ * 'project_id',
+ * );
+ * ```
+ */
+ update(projectID, body, options2) {
+ return this._client.post(path15`/organization/projects/${projectID}`, {
+ body,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Returns a list of projects.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const project of client.admin.organization.projects.list()) {
+ * // ...
+ * }
+ * ```
+ */
+ list(query = {}, options2) {
+ return this._client.getAPIList("/organization/projects", ConversationCursorPage, {
+ query,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Archives a project in the organization. Archived projects cannot be used or
+ * updated.
+ *
+ * @example
+ * ```ts
+ * const project =
+ * await client.admin.organization.projects.archive(
+ * 'project_id',
+ * );
+ * ```
+ */
+ archive(projectID, options2) {
+ return this._client.post(path15`/organization/projects/${projectID}/archive`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+};
+Projects.Users = Users2;
+Projects.ServiceAccounts = ServiceAccounts;
+Projects.APIKeys = APIKeys;
+Projects.RateLimits = RateLimits;
+Projects.ModelPermissions = ModelPermissions;
+Projects.HostedToolPermissions = HostedToolPermissions;
+Projects.Groups = Groups2;
+Projects.Roles = Roles3;
+Projects.DataRetention = DataRetention2;
+Projects.SpendAlerts = SpendAlerts2;
+Projects.Certificates = Certificates2;
+
+// node_modules/openai/resources/admin/organization/users/users.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/admin/organization/users/roles.mjs
+init_esbuild_shims();
+var Roles6 = class extends APIResource {
+ static {
+ __name(this, "Roles");
+ }
+ /**
+ * Assigns an organization role to a user within the organization.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.users.roles.create(
+ * 'user_id',
+ * { role_id: 'role_id' },
+ * );
+ * ```
+ */
+ create(userID, body, options2) {
+ return this._client.post(path15`/organization/users/${userID}/roles`, {
+ body,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Retrieves an organization role assigned to a user.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.users.roles.retrieve(
+ * 'role_id',
+ * { user_id: 'user_id' },
+ * );
+ * ```
+ */
+ retrieve(roleID, params, options2) {
+ const { user_id } = params;
+ return this._client.get(path15`/organization/users/${user_id}/roles/${roleID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Lists the organization roles assigned to a user within the organization.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const roleListResponse of client.admin.organization.users.roles.list(
+ * 'user_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(userID, query = {}, options2) {
+ return this._client.getAPIList(path15`/organization/users/${userID}/roles`, NextCursorPage, { query, ...options2, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * Unassigns an organization role from a user within the organization.
+ *
+ * @example
+ * ```ts
+ * const role =
+ * await client.admin.organization.users.roles.delete(
+ * 'role_id',
+ * { user_id: 'user_id' },
+ * );
+ * ```
+ */
+ delete(roleID, params, options2) {
+ const { user_id } = params;
+ return this._client.delete(path15`/organization/users/${user_id}/roles/${roleID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/admin/organization/users/users.mjs
+var Users3 = class extends APIResource {
+ static {
+ __name(this, "Users");
+ }
+ constructor() {
+ super(...arguments);
+ this.roles = new Roles6(this._client);
+ }
+ /**
+ * Retrieves a user by their identifier.
+ *
+ * @example
+ * ```ts
+ * const organizationUser =
+ * await client.admin.organization.users.retrieve('user_id');
+ * ```
+ */
+ retrieve(userID, options2) {
+ return this._client.get(path15`/organization/users/${userID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Modifies a user's role in the organization.
+ *
+ * @example
+ * ```ts
+ * const organizationUser =
+ * await client.admin.organization.users.update('user_id');
+ * ```
+ */
+ update(userID, body, options2) {
+ return this._client.post(path15`/organization/users/${userID}`, {
+ body,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Lists all of the users in the organization.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const organizationUser of client.admin.organization.users.list()) {
+ * // ...
+ * }
+ * ```
+ */
+ list(query = {}, options2) {
+ return this._client.getAPIList("/organization/users", ConversationCursorPage, {
+ query,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * Deletes a user from the organization.
+ *
+ * @example
+ * ```ts
+ * const user = await client.admin.organization.users.delete(
+ * 'user_id',
+ * );
+ * ```
+ */
+ delete(userID, options2) {
+ return this._client.delete(path15`/organization/users/${userID}`, {
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+};
+Users3.Roles = Roles6;
+
+// node_modules/openai/resources/admin/organization/organization.mjs
+var Organization = class extends APIResource {
+ static {
+ __name(this, "Organization");
+ }
+ constructor() {
+ super(...arguments);
+ this.auditLogs = new AuditLogs(this._client);
+ this.adminAPIKeys = new AdminAPIKeys(this._client);
+ this.usage = new Usage(this._client);
+ this.invites = new Invites(this._client);
+ this.users = new Users3(this._client);
+ this.groups = new Groups(this._client);
+ this.roles = new Roles(this._client);
+ this.dataRetention = new DataRetention(this._client);
+ this.spendAlerts = new SpendAlerts(this._client);
+ this.certificates = new Certificates(this._client);
+ this.projects = new Projects(this._client);
+ }
+};
+Organization.AuditLogs = AuditLogs;
+Organization.AdminAPIKeys = AdminAPIKeys;
+Organization.Usage = Usage;
+Organization.Invites = Invites;
+Organization.Users = Users3;
+Organization.Groups = Groups;
+Organization.Roles = Roles;
+Organization.DataRetention = DataRetention;
+Organization.SpendAlerts = SpendAlerts;
+Organization.Certificates = Certificates;
+Organization.Projects = Projects;
+
+// node_modules/openai/resources/admin/admin.mjs
+var Admin = class extends APIResource {
+ static {
+ __name(this, "Admin");
+ }
+ constructor() {
+ super(...arguments);
+ this.organization = new Organization(this._client);
+ }
+};
+Admin.Organization = Organization;
+
+// node_modules/openai/resources/audio/audio.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/audio/speech.mjs
+init_esbuild_shims();
+
+// node_modules/openai/internal/headers.mjs
+init_esbuild_shims();
+var brand_privateNullableHeaders = /* @__PURE__ */ Symbol("brand.privateNullableHeaders");
+function* iterateHeaders(headers) {
+ if (!headers)
+ return;
+ if (brand_privateNullableHeaders in headers) {
+ const { values, nulls } = headers;
+ yield* values.entries();
+ for (const name of nulls) {
+ yield [name, null];
+ }
+ return;
+ }
+ let shouldClear = false;
+ let iter;
+ if (headers instanceof Headers) {
+ iter = headers.entries();
+ } else if (isReadonlyArray(headers)) {
+ iter = headers;
+ } else {
+ shouldClear = true;
+ iter = Object.entries(headers ?? {});
+ }
+ for (let row of iter) {
+ const name = row[0];
+ if (typeof name !== "string")
+ throw new TypeError("expected header name to be a string");
+ const values = isReadonlyArray(row[1]) ? row[1] : [row[1]];
+ let didClear = false;
+ for (const value of values) {
+ if (value === void 0)
+ continue;
+ if (shouldClear && !didClear) {
+ didClear = true;
+ yield [name, null];
+ }
+ yield [name, value];
+ }
+ }
+}
+__name(iterateHeaders, "iterateHeaders");
+var buildHeaders = /* @__PURE__ */ __name((newHeaders) => {
+ const targetHeaders = new Headers();
+ const nullHeaders = /* @__PURE__ */ new Set();
+ for (const headers of newHeaders) {
+ const seenHeaders = /* @__PURE__ */ new Set();
+ for (const [name, value] of iterateHeaders(headers)) {
+ const lowerName = name.toLowerCase();
+ if (!seenHeaders.has(lowerName)) {
+ targetHeaders.delete(name);
+ seenHeaders.add(lowerName);
+ }
+ if (value === null) {
+ targetHeaders.delete(name);
+ nullHeaders.add(lowerName);
+ } else {
+ targetHeaders.append(name, value);
+ nullHeaders.delete(lowerName);
+ }
+ }
+ }
+ return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders };
+}, "buildHeaders");
+
+// node_modules/openai/resources/audio/speech.mjs
+var Speech = class extends APIResource {
+ static {
+ __name(this, "Speech");
+ }
+ /**
+ * Generates audio from the input text.
+ *
+ * Returns the audio file content, or a stream of audio events.
+ *
+ * @example
+ * ```ts
+ * const speech = await client.audio.speech.create({
+ * input: 'input',
+ * model: 'tts-1',
+ * voice: 'alloy',
+ * });
+ *
+ * const content = await speech.blob();
+ * console.log(content);
+ * ```
+ */
+ create(body, options2) {
+ return this._client.post("/audio/speech", {
+ body,
+ ...options2,
+ headers: buildHeaders([{ Accept: "application/octet-stream" }, options2?.headers]),
+ __security: { bearerAuth: true },
+ __binaryResponse: true
+ });
+ }
+};
+
+// node_modules/openai/resources/audio/transcriptions.mjs
+init_esbuild_shims();
+var Transcriptions = class extends APIResource {
+ static {
+ __name(this, "Transcriptions");
+ }
+ create(body, options2) {
+ return this._client.post("/audio/transcriptions", multipartFormRequestOptions({
+ body,
+ ...options2,
+ stream: body.stream ?? false,
+ __metadata: { model: body.model },
+ __security: { bearerAuth: true }
+ }, this._client));
+ }
+};
+
+// node_modules/openai/resources/audio/translations.mjs
+init_esbuild_shims();
+var Translations = class extends APIResource {
+ static {
+ __name(this, "Translations");
+ }
+ create(body, options2) {
+ return this._client.post("/audio/translations", multipartFormRequestOptions({ body, ...options2, __metadata: { model: body.model }, __security: { bearerAuth: true } }, this._client));
+ }
+};
+
+// node_modules/openai/resources/audio/audio.mjs
+var Audio = class extends APIResource {
+ static {
+ __name(this, "Audio");
+ }
+ constructor() {
+ super(...arguments);
+ this.transcriptions = new Transcriptions(this._client);
+ this.translations = new Translations(this._client);
+ this.speech = new Speech(this._client);
+ }
+};
+Audio.Transcriptions = Transcriptions;
+Audio.Translations = Translations;
+Audio.Speech = Speech;
+
+// node_modules/openai/resources/batches.mjs
+init_esbuild_shims();
+var Batches = class extends APIResource {
+ static {
+ __name(this, "Batches");
+ }
+ /**
+ * Creates and executes a batch from an uploaded file of requests
+ */
+ create(body, options2) {
+ return this._client.post("/batches", { body, ...options2, __security: { bearerAuth: true } });
+ }
+ /**
+ * Retrieves a batch.
+ */
+ retrieve(batchID, options2) {
+ return this._client.get(path15`/batches/${batchID}`, { ...options2, __security: { bearerAuth: true } });
+ }
+ /**
+ * List your organization's batches.
+ */
+ list(query = {}, options2) {
+ return this._client.getAPIList("/batches", CursorPage, {
+ query,
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Cancels an in-progress batch. The batch will be in status `cancelling` for up to
+ * 10 minutes, before changing to `cancelled`, where it will have partial results
+ * (if any) available in the output file.
+ */
+ cancel(batchID, options2) {
+ return this._client.post(path15`/batches/${batchID}/cancel`, {
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/beta/beta.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/beta/assistants.mjs
+init_esbuild_shims();
+var Assistants = class extends APIResource {
+ static {
+ __name(this, "Assistants");
+ }
+ /**
+ * Create an assistant with a model and instructions.
+ *
+ * @deprecated
+ */
+ create(body, options2) {
+ return this._client.post("/assistants", {
+ body,
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Retrieves an assistant.
+ *
+ * @deprecated
+ */
+ retrieve(assistantID, options2) {
+ return this._client.get(path15`/assistants/${assistantID}`, {
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Modifies an assistant.
+ *
+ * @deprecated
+ */
+ update(assistantID, body, options2) {
+ return this._client.post(path15`/assistants/${assistantID}`, {
+ body,
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Returns a list of assistants.
+ *
+ * @deprecated
+ */
+ list(query = {}, options2) {
+ return this._client.getAPIList("/assistants", CursorPage, {
+ query,
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Delete an assistant.
+ *
+ * @deprecated
+ */
+ delete(assistantID, options2) {
+ return this._client.delete(path15`/assistants/${assistantID}`, {
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/beta/realtime/realtime.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/beta/realtime/sessions.mjs
+init_esbuild_shims();
+var Sessions = class extends APIResource {
+ static {
+ __name(this, "Sessions");
+ }
+ /**
+ * Create an ephemeral API token for use in client-side applications with the
+ * Realtime API. Can be configured with the same session parameters as the
+ * `session.update` client event.
+ *
+ * It responds with a session object, plus a `client_secret` key which contains a
+ * usable ephemeral API token that can be used to authenticate browser clients for
+ * the Realtime API.
+ *
+ * @example
+ * ```ts
+ * const session =
+ * await client.beta.realtime.sessions.create();
+ * ```
+ */
+ create(body, options2) {
+ return this._client.post("/realtime/sessions", {
+ body,
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/beta/realtime/transcription-sessions.mjs
+init_esbuild_shims();
+var TranscriptionSessions = class extends APIResource {
+ static {
+ __name(this, "TranscriptionSessions");
+ }
+ /**
+ * Create an ephemeral API token for use in client-side applications with the
+ * Realtime API specifically for realtime transcriptions. Can be configured with
+ * the same session parameters as the `transcription_session.update` client event.
+ *
+ * It responds with a session object, plus a `client_secret` key which contains a
+ * usable ephemeral API token that can be used to authenticate browser clients for
+ * the Realtime API.
+ *
+ * @example
+ * ```ts
+ * const transcriptionSession =
+ * await client.beta.realtime.transcriptionSessions.create();
+ * ```
+ */
+ create(body, options2) {
+ return this._client.post("/realtime/transcription_sessions", {
+ body,
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/beta/realtime/realtime.mjs
+var Realtime = class extends APIResource {
+ static {
+ __name(this, "Realtime");
+ }
+ constructor() {
+ super(...arguments);
+ this.sessions = new Sessions(this._client);
+ this.transcriptionSessions = new TranscriptionSessions(this._client);
+ }
+};
+Realtime.Sessions = Sessions;
+Realtime.TranscriptionSessions = TranscriptionSessions;
+
+// node_modules/openai/resources/beta/chatkit/chatkit.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/beta/chatkit/sessions.mjs
+init_esbuild_shims();
+var Sessions2 = class extends APIResource {
+ static {
+ __name(this, "Sessions");
+ }
+ /**
+ * Create a ChatKit session.
+ *
+ * @example
+ * ```ts
+ * const chatSession =
+ * await client.beta.chatkit.sessions.create({
+ * user: 'x',
+ * workflow: { id: 'id' },
+ * });
+ * ```
+ */
+ create(body, options2) {
+ return this._client.post("/chatkit/sessions", {
+ body,
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "chatkit_beta=v1" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Cancel an active ChatKit session and return its most recent metadata.
+ *
+ * Cancelling prevents new requests from using the issued client secret.
+ *
+ * @example
+ * ```ts
+ * const chatSession =
+ * await client.beta.chatkit.sessions.cancel('cksess_123');
+ * ```
+ */
+ cancel(sessionID, options2) {
+ return this._client.post(path15`/chatkit/sessions/${sessionID}/cancel`, {
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "chatkit_beta=v1" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/beta/chatkit/threads.mjs
+init_esbuild_shims();
+var Threads = class extends APIResource {
+ static {
+ __name(this, "Threads");
+ }
+ /**
+ * Retrieve a ChatKit thread by its identifier.
+ *
+ * @example
+ * ```ts
+ * const chatkitThread =
+ * await client.beta.chatkit.threads.retrieve('cthr_123');
+ * ```
+ */
+ retrieve(threadID, options2) {
+ return this._client.get(path15`/chatkit/threads/${threadID}`, {
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "chatkit_beta=v1" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * List ChatKit threads with optional pagination and user filters.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const chatkitThread of client.beta.chatkit.threads.list()) {
+ * // ...
+ * }
+ * ```
+ */
+ list(query = {}, options2) {
+ return this._client.getAPIList("/chatkit/threads", ConversationCursorPage, {
+ query,
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "chatkit_beta=v1" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Delete a ChatKit thread along with its items and stored attachments.
+ *
+ * @example
+ * ```ts
+ * const thread = await client.beta.chatkit.threads.delete(
+ * 'cthr_123',
+ * );
+ * ```
+ */
+ delete(threadID, options2) {
+ return this._client.delete(path15`/chatkit/threads/${threadID}`, {
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "chatkit_beta=v1" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * List items that belong to a ChatKit thread.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const thread of client.beta.chatkit.threads.listItems(
+ * 'cthr_123',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ listItems(threadID, query = {}, options2) {
+ return this._client.getAPIList(path15`/chatkit/threads/${threadID}/items`, ConversationCursorPage, {
+ query,
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "chatkit_beta=v1" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/beta/chatkit/chatkit.mjs
+var ChatKit = class extends APIResource {
+ static {
+ __name(this, "ChatKit");
+ }
+ constructor() {
+ super(...arguments);
+ this.sessions = new Sessions2(this._client);
+ this.threads = new Threads(this._client);
+ }
+};
+ChatKit.Sessions = Sessions2;
+ChatKit.Threads = Threads;
+
+// node_modules/openai/resources/beta/threads/threads.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/beta/threads/messages.mjs
+init_esbuild_shims();
+var Messages2 = class extends APIResource {
+ static {
+ __name(this, "Messages");
+ }
+ /**
+ * Create a message.
+ *
+ * @deprecated The Assistants API is deprecated in favor of the Responses API
+ */
+ create(threadID, body, options2) {
+ return this._client.post(path15`/threads/${threadID}/messages`, {
+ body,
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Retrieve a message.
+ *
+ * @deprecated The Assistants API is deprecated in favor of the Responses API
+ */
+ retrieve(messageID, params, options2) {
+ const { thread_id } = params;
+ return this._client.get(path15`/threads/${thread_id}/messages/${messageID}`, {
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Modifies a message.
+ *
+ * @deprecated The Assistants API is deprecated in favor of the Responses API
+ */
+ update(messageID, params, options2) {
+ const { thread_id, ...body } = params;
+ return this._client.post(path15`/threads/${thread_id}/messages/${messageID}`, {
+ body,
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Returns a list of messages for a given thread.
+ *
+ * @deprecated The Assistants API is deprecated in favor of the Responses API
+ */
+ list(threadID, query = {}, options2) {
+ return this._client.getAPIList(path15`/threads/${threadID}/messages`, CursorPage, {
+ query,
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Deletes a message.
+ *
+ * @deprecated The Assistants API is deprecated in favor of the Responses API
+ */
+ delete(messageID, params, options2) {
+ const { thread_id } = params;
+ return this._client.delete(path15`/threads/${thread_id}/messages/${messageID}`, {
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/beta/threads/runs/runs.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/beta/threads/runs/steps.mjs
+init_esbuild_shims();
+var Steps = class extends APIResource {
+ static {
+ __name(this, "Steps");
+ }
+ /**
+ * Retrieves a run step.
+ *
+ * @deprecated The Assistants API is deprecated in favor of the Responses API
+ */
+ retrieve(stepID, params, options2) {
+ const { thread_id, run_id, ...query } = params;
+ return this._client.get(path15`/threads/${thread_id}/runs/${run_id}/steps/${stepID}`, {
+ query,
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Returns a list of run steps belonging to a run.
+ *
+ * @deprecated The Assistants API is deprecated in favor of the Responses API
+ */
+ list(runID, params, options2) {
+ const { thread_id, ...query } = params;
+ return this._client.getAPIList(path15`/threads/${thread_id}/runs/${runID}/steps`, CursorPage, {
+ query,
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/lib/AssistantStream.mjs
+init_esbuild_shims();
+
+// node_modules/openai/internal/utils.mjs
+init_esbuild_shims();
+
+// node_modules/openai/internal/utils/base64.mjs
+init_esbuild_shims();
+var toFloat32Array = /* @__PURE__ */ __name((base64Str) => {
+ if (typeof Buffer !== "undefined") {
+ const buf = Buffer.from(base64Str, "base64");
+ return Array.from(new Float32Array(buf.buffer, buf.byteOffset, buf.length / Float32Array.BYTES_PER_ELEMENT));
+ } else {
+ const binaryStr = atob(base64Str);
+ const len = binaryStr.length;
+ const bytes = new Uint8Array(len);
+ for (let i = 0; i < len; i++) {
+ bytes[i] = binaryStr.charCodeAt(i);
+ }
+ return Array.from(new Float32Array(bytes.buffer));
+ }
+}, "toFloat32Array");
+
+// node_modules/openai/internal/utils/env.mjs
+init_esbuild_shims();
+var readEnv = /* @__PURE__ */ __name((env6) => {
+ if (typeof globalThis.process !== "undefined") {
+ return globalThis.process.env?.[env6]?.trim() || void 0;
+ }
+ if (typeof globalThis.Deno !== "undefined") {
+ return globalThis.Deno.env?.get?.(env6)?.trim() || void 0;
+ }
+ return void 0;
+}, "readEnv");
+
+// node_modules/openai/lib/AssistantStream.mjs
+var _AssistantStream_instances;
+var _a3;
+var _AssistantStream_events;
+var _AssistantStream_runStepSnapshots;
+var _AssistantStream_messageSnapshots;
+var _AssistantStream_messageSnapshot;
+var _AssistantStream_finalRun;
+var _AssistantStream_currentContentIndex;
+var _AssistantStream_currentContent;
+var _AssistantStream_currentToolCallIndex;
+var _AssistantStream_currentToolCall;
+var _AssistantStream_currentEvent;
+var _AssistantStream_currentRunSnapshot;
+var _AssistantStream_currentRunStepSnapshot;
+var _AssistantStream_addEvent;
+var _AssistantStream_endRequest;
+var _AssistantStream_handleMessage;
+var _AssistantStream_handleRunStep;
+var _AssistantStream_handleEvent;
+var _AssistantStream_accumulateRunStep;
+var _AssistantStream_accumulateMessage;
+var _AssistantStream_accumulateContent;
+var _AssistantStream_handleRun;
+var AssistantStream = class extends EventStream {
+ static {
+ __name(this, "AssistantStream");
+ }
+ constructor() {
+ super(...arguments);
+ _AssistantStream_instances.add(this);
+ _AssistantStream_events.set(this, []);
+ _AssistantStream_runStepSnapshots.set(this, {});
+ _AssistantStream_messageSnapshots.set(this, {});
+ _AssistantStream_messageSnapshot.set(this, void 0);
+ _AssistantStream_finalRun.set(this, void 0);
+ _AssistantStream_currentContentIndex.set(this, void 0);
+ _AssistantStream_currentContent.set(this, void 0);
+ _AssistantStream_currentToolCallIndex.set(this, void 0);
+ _AssistantStream_currentToolCall.set(this, void 0);
+ _AssistantStream_currentEvent.set(this, void 0);
+ _AssistantStream_currentRunSnapshot.set(this, void 0);
+ _AssistantStream_currentRunStepSnapshot.set(this, void 0);
+ }
+ [(_AssistantStream_events = /* @__PURE__ */ new WeakMap(), _AssistantStream_runStepSnapshots = /* @__PURE__ */ new WeakMap(), _AssistantStream_messageSnapshots = /* @__PURE__ */ new WeakMap(), _AssistantStream_messageSnapshot = /* @__PURE__ */ new WeakMap(), _AssistantStream_finalRun = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentContentIndex = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentContent = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentToolCallIndex = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentToolCall = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentEvent = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentRunSnapshot = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentRunStepSnapshot = /* @__PURE__ */ new WeakMap(), _AssistantStream_instances = /* @__PURE__ */ new WeakSet(), Symbol.asyncIterator)]() {
+ const pushQueue = [];
+ const readQueue = [];
+ let done = false;
+ this.on("event", (event) => {
+ const reader = readQueue.shift();
+ if (reader) {
+ reader.resolve(event);
+ } else {
+ pushQueue.push(event);
+ }
+ });
+ this.on("end", () => {
+ done = true;
+ for (const reader of readQueue) {
+ reader.resolve(void 0);
+ }
+ readQueue.length = 0;
+ });
+ this.on("abort", (err) => {
+ done = true;
+ for (const reader of readQueue) {
+ reader.reject(err);
+ }
+ readQueue.length = 0;
+ });
+ this.on("error", (err) => {
+ done = true;
+ for (const reader of readQueue) {
+ reader.reject(err);
+ }
+ readQueue.length = 0;
+ });
+ return {
+ next: /* @__PURE__ */ __name(async () => {
+ if (!pushQueue.length) {
+ if (done) {
+ return { value: void 0, done: true };
+ }
+ return new Promise((resolve16, reject) => readQueue.push({ resolve: resolve16, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true });
+ }
+ const chunk = pushQueue.shift();
+ return { value: chunk, done: false };
+ }, "next"),
+ return: /* @__PURE__ */ __name(async () => {
+ this.abort();
+ return { value: void 0, done: true };
+ }, "return")
+ };
+ }
+ static fromReadableStream(stream) {
+ const runner = new _a3();
+ runner._run(() => runner._fromReadableStream(stream));
+ return runner;
+ }
+ async _fromReadableStream(readableStream, options2) {
+ const signal = options2?.signal;
+ if (signal) {
+ if (signal.aborted)
+ this.controller.abort();
+ signal.addEventListener("abort", () => this.controller.abort());
+ }
+ this._connected();
+ const stream = Stream2.fromReadableStream(readableStream, this.controller);
+ for await (const event of stream) {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
+ }
+ if (stream.controller.signal?.aborted) {
+ throw new APIUserAbortError();
+ }
+ return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
+ }
+ toReadableStream() {
+ const stream = new Stream2(this[Symbol.asyncIterator].bind(this), this.controller);
+ return stream.toReadableStream();
+ }
+ static createToolAssistantStream(runId, runs, params, options2) {
+ const runner = new _a3();
+ runner._run(() => runner._runToolAssistantStream(runId, runs, params, {
+ ...options2,
+ headers: { ...options2?.headers, "X-Stainless-Helper-Method": "stream" }
+ }));
+ return runner;
+ }
+ async _createToolAssistantStream(run, runId, params, options2) {
+ const signal = options2?.signal;
+ if (signal) {
+ if (signal.aborted)
+ this.controller.abort();
+ signal.addEventListener("abort", () => this.controller.abort());
+ }
+ const body = { ...params, stream: true };
+ const stream = await run.submitToolOutputs(runId, body, {
+ ...options2,
+ signal: this.controller.signal
+ });
+ this._connected();
+ for await (const event of stream) {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
+ }
+ if (stream.controller.signal?.aborted) {
+ throw new APIUserAbortError();
+ }
+ return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
+ }
+ static createThreadAssistantStream(params, thread, options2) {
+ const runner = new _a3();
+ runner._run(() => runner._threadAssistantStream(params, thread, {
+ ...options2,
+ headers: { ...options2?.headers, "X-Stainless-Helper-Method": "stream" }
+ }));
+ return runner;
+ }
+ static createAssistantStream(threadId, runs, params, options2) {
+ const runner = new _a3();
+ runner._run(() => runner._runAssistantStream(threadId, runs, params, {
+ ...options2,
+ headers: { ...options2?.headers, "X-Stainless-Helper-Method": "stream" }
+ }));
+ return runner;
+ }
+ currentEvent() {
+ return __classPrivateFieldGet(this, _AssistantStream_currentEvent, "f");
+ }
+ currentRun() {
+ return __classPrivateFieldGet(this, _AssistantStream_currentRunSnapshot, "f");
+ }
+ currentMessageSnapshot() {
+ return __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f");
+ }
+ currentRunStepSnapshot() {
+ return __classPrivateFieldGet(this, _AssistantStream_currentRunStepSnapshot, "f");
+ }
+ async finalRunSteps() {
+ await this.done();
+ return Object.values(__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f"));
+ }
+ async finalMessages() {
+ await this.done();
+ return Object.values(__classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f"));
+ }
+ async finalRun() {
+ await this.done();
+ if (!__classPrivateFieldGet(this, _AssistantStream_finalRun, "f"))
+ throw Error("Final run was not received.");
+ return __classPrivateFieldGet(this, _AssistantStream_finalRun, "f");
+ }
+ async _createThreadAssistantStream(thread, params, options2) {
+ const signal = options2?.signal;
+ if (signal) {
+ if (signal.aborted)
+ this.controller.abort();
+ signal.addEventListener("abort", () => this.controller.abort());
+ }
+ const body = { ...params, stream: true };
+ const stream = await thread.createAndRun(body, { ...options2, signal: this.controller.signal });
+ this._connected();
+ for await (const event of stream) {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
+ }
+ if (stream.controller.signal?.aborted) {
+ throw new APIUserAbortError();
+ }
+ return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
+ }
+ async _createAssistantStream(run, threadId, params, options2) {
+ const signal = options2?.signal;
+ if (signal) {
+ if (signal.aborted)
+ this.controller.abort();
+ signal.addEventListener("abort", () => this.controller.abort());
+ }
+ const body = { ...params, stream: true };
+ const stream = await run.create(threadId, body, { ...options2, signal: this.controller.signal });
+ this._connected();
+ for await (const event of stream) {
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
+ }
+ if (stream.controller.signal?.aborted) {
+ throw new APIUserAbortError();
+ }
+ return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
+ }
+ static accumulateDelta(acc, delta) {
+ for (const [key, deltaValue] of Object.entries(delta)) {
+ if (!acc.hasOwnProperty(key)) {
+ acc[key] = deltaValue;
+ continue;
+ }
+ let accValue = acc[key];
+ if (accValue === null || accValue === void 0) {
+ acc[key] = deltaValue;
+ continue;
+ }
+ if (key === "index" || key === "type") {
+ acc[key] = deltaValue;
+ continue;
+ }
+ if (typeof accValue === "string" && typeof deltaValue === "string") {
+ accValue += deltaValue;
+ } else if (typeof accValue === "number" && typeof deltaValue === "number") {
+ accValue += deltaValue;
+ } else if (isObj(accValue) && isObj(deltaValue)) {
+ accValue = this.accumulateDelta(accValue, deltaValue);
+ } else if (Array.isArray(accValue) && Array.isArray(deltaValue)) {
+ if (accValue.every((x) => typeof x === "string" || typeof x === "number")) {
+ accValue.push(...deltaValue);
+ continue;
+ }
+ for (const deltaEntry of deltaValue) {
+ if (!isObj(deltaEntry)) {
+ throw new Error(`Expected array delta entry to be an object but got: ${deltaEntry}`);
+ }
+ const index = deltaEntry["index"];
+ if (index == null) {
+ console.error(deltaEntry);
+ throw new Error("Expected array delta entry to have an `index` property");
+ }
+ if (typeof index !== "number") {
+ throw new Error(`Expected array delta entry \`index\` property to be a number but got ${index}`);
+ }
+ const accEntry = accValue[index];
+ if (accEntry == null) {
+ accValue.push(deltaEntry);
+ } else {
+ accValue[index] = this.accumulateDelta(accEntry, deltaEntry);
+ }
+ }
+ continue;
+ } else {
+ throw Error(`Unhandled record type: ${key}, deltaValue: ${deltaValue}, accValue: ${accValue}`);
+ }
+ acc[key] = accValue;
+ }
+ return acc;
+ }
+ _addRun(run) {
+ return run;
+ }
+ async _threadAssistantStream(params, thread, options2) {
+ return await this._createThreadAssistantStream(thread, params, options2);
+ }
+ async _runAssistantStream(threadId, runs, params, options2) {
+ return await this._createAssistantStream(runs, threadId, params, options2);
+ }
+ async _runToolAssistantStream(runId, runs, params, options2) {
+ return await this._createToolAssistantStream(runs, runId, params, options2);
+ }
+};
+_a3 = AssistantStream, _AssistantStream_addEvent = /* @__PURE__ */ __name(function _AssistantStream_addEvent2(event) {
+ if (this.ended)
+ return;
+ __classPrivateFieldSet(this, _AssistantStream_currentEvent, event, "f");
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleEvent).call(this, event);
+ switch (event.event) {
+ case "thread.created":
+ break;
+ case "thread.run.created":
+ case "thread.run.queued":
+ case "thread.run.in_progress":
+ case "thread.run.requires_action":
+ case "thread.run.completed":
+ case "thread.run.incomplete":
+ case "thread.run.failed":
+ case "thread.run.cancelling":
+ case "thread.run.cancelled":
+ case "thread.run.expired":
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRun).call(this, event);
+ break;
+ case "thread.run.step.created":
+ case "thread.run.step.in_progress":
+ case "thread.run.step.delta":
+ case "thread.run.step.completed":
+ case "thread.run.step.failed":
+ case "thread.run.step.cancelled":
+ case "thread.run.step.expired":
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRunStep).call(this, event);
+ break;
+ case "thread.message.created":
+ case "thread.message.in_progress":
+ case "thread.message.delta":
+ case "thread.message.completed":
+ case "thread.message.incomplete":
+ __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleMessage).call(this, event);
+ break;
+ case "error":
+ throw new Error("Encountered an error event in event processing - errors should be processed earlier");
+ default:
+ assertNever3(event);
+ }
+}, "_AssistantStream_addEvent"), _AssistantStream_endRequest = /* @__PURE__ */ __name(function _AssistantStream_endRequest2() {
+ if (this.ended) {
+ throw new OpenAIError(`stream has ended, this shouldn't happen`);
+ }
+ if (!__classPrivateFieldGet(this, _AssistantStream_finalRun, "f"))
+ throw Error("Final run has not been received");
+ return __classPrivateFieldGet(this, _AssistantStream_finalRun, "f");
+}, "_AssistantStream_endRequest"), _AssistantStream_handleMessage = /* @__PURE__ */ __name(function _AssistantStream_handleMessage2(event) {
+ const [accumulatedMessage, newContent] = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateMessage).call(this, event, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
+ __classPrivateFieldSet(this, _AssistantStream_messageSnapshot, accumulatedMessage, "f");
+ __classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f")[accumulatedMessage.id] = accumulatedMessage;
+ for (const content of newContent) {
+ const snapshotContent = accumulatedMessage.content[content.index];
+ if (snapshotContent?.type == "text") {
+ this._emit("textCreated", snapshotContent.text);
+ }
+ }
+ switch (event.event) {
+ case "thread.message.created":
+ this._emit("messageCreated", event.data);
+ break;
+ case "thread.message.in_progress":
+ break;
+ case "thread.message.delta":
+ this._emit("messageDelta", event.data.delta, accumulatedMessage);
+ if (event.data.delta.content) {
+ for (const content of event.data.delta.content) {
+ if (content.type == "text" && content.text) {
+ let textDelta = content.text;
+ let snapshot = accumulatedMessage.content[content.index];
+ if (snapshot && snapshot.type == "text") {
+ this._emit("textDelta", textDelta, snapshot.text);
+ } else {
+ throw Error("The snapshot associated with this text delta is not text or missing");
+ }
+ }
+ if (content.index != __classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")) {
+ if (__classPrivateFieldGet(this, _AssistantStream_currentContent, "f")) {
+ switch (__classPrivateFieldGet(this, _AssistantStream_currentContent, "f").type) {
+ case "text":
+ this._emit("textDone", __classPrivateFieldGet(this, _AssistantStream_currentContent, "f").text, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
+ break;
+ case "image_file":
+ this._emit("imageFileDone", __classPrivateFieldGet(this, _AssistantStream_currentContent, "f").image_file, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
+ break;
+ }
+ }
+ __classPrivateFieldSet(this, _AssistantStream_currentContentIndex, content.index, "f");
+ }
+ __classPrivateFieldSet(this, _AssistantStream_currentContent, accumulatedMessage.content[content.index], "f");
+ }
+ }
+ break;
+ case "thread.message.completed":
+ case "thread.message.incomplete":
+ if (__classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f") !== void 0) {
+ const currentContent = event.data.content[__classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")];
+ if (currentContent) {
+ switch (currentContent.type) {
+ case "image_file":
+ this._emit("imageFileDone", currentContent.image_file, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
+ break;
+ case "text":
+ this._emit("textDone", currentContent.text, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
+ break;
+ }
+ }
+ }
+ if (__classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")) {
+ this._emit("messageDone", event.data);
+ }
+ __classPrivateFieldSet(this, _AssistantStream_messageSnapshot, void 0, "f");
+ }
+}, "_AssistantStream_handleMessage"), _AssistantStream_handleRunStep = /* @__PURE__ */ __name(function _AssistantStream_handleRunStep2(event) {
+ const accumulatedRunStep = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateRunStep).call(this, event);
+ __classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, accumulatedRunStep, "f");
+ switch (event.event) {
+ case "thread.run.step.created":
+ this._emit("runStepCreated", event.data);
+ break;
+ case "thread.run.step.delta":
+ const delta = event.data.delta;
+ if (delta.step_details && delta.step_details.type == "tool_calls" && delta.step_details.tool_calls && accumulatedRunStep.step_details.type == "tool_calls") {
+ for (const toolCall of delta.step_details.tool_calls) {
+ if (toolCall.index == __classPrivateFieldGet(this, _AssistantStream_currentToolCallIndex, "f")) {
+ this._emit("toolCallDelta", toolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index]);
+ } else {
+ if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) {
+ this._emit("toolCallDone", __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f"));
+ }
+ __classPrivateFieldSet(this, _AssistantStream_currentToolCallIndex, toolCall.index, "f");
+ __classPrivateFieldSet(this, _AssistantStream_currentToolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index], "f");
+ if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f"))
+ this._emit("toolCallCreated", __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f"));
+ }
+ }
+ }
+ this._emit("runStepDelta", event.data.delta, accumulatedRunStep);
+ break;
+ case "thread.run.step.completed":
+ case "thread.run.step.failed":
+ case "thread.run.step.cancelled":
+ case "thread.run.step.expired":
+ __classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, void 0, "f");
+ const details = event.data.step_details;
+ if (details.type == "tool_calls") {
+ if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) {
+ this._emit("toolCallDone", __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f"));
+ __classPrivateFieldSet(this, _AssistantStream_currentToolCall, void 0, "f");
+ }
+ }
+ this._emit("runStepDone", event.data, accumulatedRunStep);
+ break;
+ case "thread.run.step.in_progress":
+ break;
+ }
+}, "_AssistantStream_handleRunStep"), _AssistantStream_handleEvent = /* @__PURE__ */ __name(function _AssistantStream_handleEvent2(event) {
+ __classPrivateFieldGet(this, _AssistantStream_events, "f").push(event);
+ this._emit("event", event);
+}, "_AssistantStream_handleEvent"), _AssistantStream_accumulateRunStep = /* @__PURE__ */ __name(function _AssistantStream_accumulateRunStep2(event) {
+ switch (event.event) {
+ case "thread.run.step.created":
+ __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data;
+ return event.data;
+ case "thread.run.step.delta":
+ let snapshot = __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id];
+ if (!snapshot) {
+ throw Error("Received a RunStepDelta before creation of a snapshot");
+ }
+ let data = event.data;
+ if (data.delta) {
+ const accumulated = _a3.accumulateDelta(snapshot, data.delta);
+ __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = accumulated;
+ }
+ return __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id];
+ case "thread.run.step.completed":
+ case "thread.run.step.failed":
+ case "thread.run.step.cancelled":
+ case "thread.run.step.expired":
+ case "thread.run.step.in_progress":
+ __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data;
+ break;
+ }
+ if (__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id])
+ return __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id];
+ throw new Error("No snapshot available");
+}, "_AssistantStream_accumulateRunStep"), _AssistantStream_accumulateMessage = /* @__PURE__ */ __name(function _AssistantStream_accumulateMessage2(event, snapshot) {
+ let newContent = [];
+ switch (event.event) {
+ case "thread.message.created":
+ return [event.data, newContent];
+ case "thread.message.delta":
+ if (!snapshot) {
+ throw Error("Received a delta with no existing snapshot (there should be one from message creation)");
+ }
+ let data = event.data;
+ if (data.delta.content) {
+ for (const contentElement of data.delta.content) {
+ if (contentElement.index in snapshot.content) {
+ let currentContent = snapshot.content[contentElement.index];
+ snapshot.content[contentElement.index] = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateContent).call(this, contentElement, currentContent);
+ } else {
+ snapshot.content[contentElement.index] = contentElement;
+ newContent.push(contentElement);
+ }
+ }
+ }
+ return [snapshot, newContent];
+ case "thread.message.in_progress":
+ case "thread.message.completed":
+ case "thread.message.incomplete":
+ if (snapshot) {
+ return [snapshot, newContent];
+ } else {
+ throw Error("Received thread message event with no existing snapshot");
+ }
+ }
+ throw Error("Tried to accumulate a non-message event");
+}, "_AssistantStream_accumulateMessage"), _AssistantStream_accumulateContent = /* @__PURE__ */ __name(function _AssistantStream_accumulateContent2(contentElement, currentContent) {
+ return _a3.accumulateDelta(currentContent, contentElement);
+}, "_AssistantStream_accumulateContent"), _AssistantStream_handleRun = /* @__PURE__ */ __name(function _AssistantStream_handleRun2(event) {
+ __classPrivateFieldSet(this, _AssistantStream_currentRunSnapshot, event.data, "f");
+ switch (event.event) {
+ case "thread.run.created":
+ break;
+ case "thread.run.queued":
+ break;
+ case "thread.run.in_progress":
+ break;
+ case "thread.run.requires_action":
+ case "thread.run.cancelled":
+ case "thread.run.failed":
+ case "thread.run.completed":
+ case "thread.run.expired":
+ case "thread.run.incomplete":
+ __classPrivateFieldSet(this, _AssistantStream_finalRun, event.data, "f");
+ if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) {
+ this._emit("toolCallDone", __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f"));
+ __classPrivateFieldSet(this, _AssistantStream_currentToolCall, void 0, "f");
+ }
+ break;
+ case "thread.run.cancelling":
+ break;
+ }
+}, "_AssistantStream_handleRun");
+function assertNever3(_x) {
+}
+__name(assertNever3, "assertNever");
+
+// node_modules/openai/resources/beta/threads/runs/runs.mjs
+var Runs = class extends APIResource {
+ static {
+ __name(this, "Runs");
+ }
+ constructor() {
+ super(...arguments);
+ this.steps = new Steps(this._client);
+ }
+ create(threadID, params, options2) {
+ const { include, ...body } = params;
+ return this._client.post(path15`/threads/${threadID}/runs`, {
+ query: { include },
+ body,
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ stream: params.stream ?? false,
+ __synthesizeEventData: true,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Retrieves a run.
+ *
+ * @deprecated The Assistants API is deprecated in favor of the Responses API
+ */
+ retrieve(runID, params, options2) {
+ const { thread_id } = params;
+ return this._client.get(path15`/threads/${thread_id}/runs/${runID}`, {
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Modifies a run.
+ *
+ * @deprecated The Assistants API is deprecated in favor of the Responses API
+ */
+ update(runID, params, options2) {
+ const { thread_id, ...body } = params;
+ return this._client.post(path15`/threads/${thread_id}/runs/${runID}`, {
+ body,
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Returns a list of runs belonging to a thread.
+ *
+ * @deprecated The Assistants API is deprecated in favor of the Responses API
+ */
+ list(threadID, query = {}, options2) {
+ return this._client.getAPIList(path15`/threads/${threadID}/runs`, CursorPage, {
+ query,
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Cancels a run that is `in_progress`.
+ *
+ * @deprecated The Assistants API is deprecated in favor of the Responses API
+ */
+ cancel(runID, params, options2) {
+ const { thread_id } = params;
+ return this._client.post(path15`/threads/${thread_id}/runs/${runID}/cancel`, {
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * A helper to create a run an poll for a terminal state. More information on Run
+ * lifecycles can be found here:
+ * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps
+ */
+ async createAndPoll(threadId, body, options2) {
+ const run = await this.create(threadId, body, options2);
+ return await this.poll(run.id, { thread_id: threadId }, options2);
+ }
+ /**
+ * Create a Run stream
+ *
+ * @deprecated use `stream` instead
+ */
+ createAndStream(threadId, body, options2) {
+ return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options2);
+ }
+ /**
+ * A helper to poll a run status until it reaches a terminal state. More
+ * information on Run lifecycles can be found here:
+ * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps
+ */
+ async poll(runId, params, options2) {
+ const headers = buildHeaders([
+ options2?.headers,
+ {
+ "X-Stainless-Poll-Helper": "true",
+ "X-Stainless-Custom-Poll-Interval": options2?.pollIntervalMs?.toString() ?? void 0
+ }
+ ]);
+ while (true) {
+ const { data: run, response } = await this.retrieve(runId, params, {
+ ...options2,
+ headers: { ...options2?.headers, ...headers }
+ }).withResponse();
+ switch (run.status) {
+ //If we are in any sort of intermediate state we poll
+ case "queued":
+ case "in_progress":
+ case "cancelling":
+ let sleepInterval = 5e3;
+ if (options2?.pollIntervalMs) {
+ sleepInterval = options2.pollIntervalMs;
+ } else {
+ const headerInterval = response.headers.get("openai-poll-after-ms");
+ if (headerInterval) {
+ const headerIntervalMs = parseInt(headerInterval);
+ if (!isNaN(headerIntervalMs)) {
+ sleepInterval = headerIntervalMs;
+ }
+ }
+ }
+ await sleep(sleepInterval);
+ break;
+ //We return the run in any terminal state.
+ case "requires_action":
+ case "incomplete":
+ case "cancelled":
+ case "completed":
+ case "failed":
+ case "expired":
+ return run;
+ }
+ }
+ }
+ /**
+ * Create a Run stream
+ */
+ stream(threadId, body, options2) {
+ return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options2);
+ }
+ submitToolOutputs(runID, params, options2) {
+ const { thread_id, ...body } = params;
+ return this._client.post(path15`/threads/${thread_id}/runs/${runID}/submit_tool_outputs`, {
+ body,
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ stream: params.stream ?? false,
+ __synthesizeEventData: true,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * A helper to submit a tool output to a run and poll for a terminal run state.
+ * More information on Run lifecycles can be found here:
+ * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps
+ */
+ async submitToolOutputsAndPoll(runId, params, options2) {
+ const run = await this.submitToolOutputs(runId, params, options2);
+ return await this.poll(run.id, params, options2);
+ }
+ /**
+ * Submit the tool outputs from a previous run and stream the run to a terminal
+ * state. More information on Run lifecycles can be found here:
+ * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps
+ */
+ submitToolOutputsStream(runId, params, options2) {
+ return AssistantStream.createToolAssistantStream(runId, this._client.beta.threads.runs, params, options2);
+ }
+};
+Runs.Steps = Steps;
+
+// node_modules/openai/resources/beta/threads/threads.mjs
+var Threads2 = class extends APIResource {
+ static {
+ __name(this, "Threads");
+ }
+ constructor() {
+ super(...arguments);
+ this.runs = new Runs(this._client);
+ this.messages = new Messages2(this._client);
+ }
+ /**
+ * Create a thread.
+ *
+ * @deprecated The Assistants API is deprecated in favor of the Responses API
+ */
+ create(body = {}, options2) {
+ return this._client.post("/threads", {
+ body,
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Retrieves a thread.
+ *
+ * @deprecated The Assistants API is deprecated in favor of the Responses API
+ */
+ retrieve(threadID, options2) {
+ return this._client.get(path15`/threads/${threadID}`, {
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Modifies a thread.
+ *
+ * @deprecated The Assistants API is deprecated in favor of the Responses API
+ */
+ update(threadID, body, options2) {
+ return this._client.post(path15`/threads/${threadID}`, {
+ body,
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Delete a thread.
+ *
+ * @deprecated The Assistants API is deprecated in favor of the Responses API
+ */
+ delete(threadID, options2) {
+ return this._client.delete(path15`/threads/${threadID}`, {
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ createAndRun(body, options2) {
+ return this._client.post("/threads/runs", {
+ body,
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ stream: body.stream ?? false,
+ __synthesizeEventData: true,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * A helper to create a thread, start a run and then poll for a terminal state.
+ * More information on Run lifecycles can be found here:
+ * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps
+ */
+ async createAndRunPoll(body, options2) {
+ const run = await this.createAndRun(body, options2);
+ return await this.runs.poll(run.id, { thread_id: run.thread_id }, options2);
+ }
+ /**
+ * Create a thread and stream the run back
+ */
+ createAndRunStream(body, options2) {
+ return AssistantStream.createThreadAssistantStream(body, this._client.beta.threads, options2);
+ }
+};
+Threads2.Runs = Runs;
+Threads2.Messages = Messages2;
+
+// node_modules/openai/resources/beta/beta.mjs
+var Beta = class extends APIResource {
+ static {
+ __name(this, "Beta");
+ }
+ constructor() {
+ super(...arguments);
+ this.realtime = new Realtime(this._client);
+ this.chatkit = new ChatKit(this._client);
+ this.assistants = new Assistants(this._client);
+ this.threads = new Threads2(this._client);
+ }
+};
+Beta.Realtime = Realtime;
+Beta.ChatKit = ChatKit;
+Beta.Assistants = Assistants;
+Beta.Threads = Threads2;
+
+// node_modules/openai/resources/completions.mjs
+init_esbuild_shims();
+var Completions2 = class extends APIResource {
+ static {
+ __name(this, "Completions");
+ }
+ create(body, options2) {
+ return this._client.post("/completions", {
+ body,
+ ...options2,
+ stream: body.stream ?? false,
+ __security: { bearerAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/containers/containers.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/containers/files/files.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/containers/files/content.mjs
+init_esbuild_shims();
+var Content = class extends APIResource {
+ static {
+ __name(this, "Content");
+ }
+ /**
+ * Retrieve Container File Content
+ */
+ retrieve(fileID, params, options2) {
+ const { container_id } = params;
+ return this._client.get(path15`/containers/${container_id}/files/${fileID}/content`, {
+ ...options2,
+ headers: buildHeaders([{ Accept: "application/binary" }, options2?.headers]),
+ __security: { bearerAuth: true },
+ __binaryResponse: true
+ });
+ }
+};
+
+// node_modules/openai/resources/containers/files/files.mjs
+var Files = class extends APIResource {
+ static {
+ __name(this, "Files");
+ }
+ constructor() {
+ super(...arguments);
+ this.content = new Content(this._client);
+ }
+ /**
+ * Create a Container File
+ *
+ * You can send either a multipart/form-data request with the raw file content, or
+ * a JSON request with a file ID.
+ */
+ create(containerID, body, options2) {
+ return this._client.post(path15`/containers/${containerID}/files`, maybeMultipartFormRequestOptions({ body, ...options2, __security: { bearerAuth: true } }, this._client));
+ }
+ /**
+ * Retrieve Container File
+ */
+ retrieve(fileID, params, options2) {
+ const { container_id } = params;
+ return this._client.get(path15`/containers/${container_id}/files/${fileID}`, {
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * List Container files
+ */
+ list(containerID, query = {}, options2) {
+ return this._client.getAPIList(path15`/containers/${containerID}/files`, CursorPage, {
+ query,
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Delete Container File
+ */
+ delete(fileID, params, options2) {
+ const { container_id } = params;
+ return this._client.delete(path15`/containers/${container_id}/files/${fileID}`, {
+ ...options2,
+ headers: buildHeaders([{ Accept: "*/*" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+};
+Files.Content = Content;
+
+// node_modules/openai/resources/containers/containers.mjs
+var Containers = class extends APIResource {
+ static {
+ __name(this, "Containers");
+ }
+ constructor() {
+ super(...arguments);
+ this.files = new Files(this._client);
+ }
+ /**
+ * Create Container
+ */
+ create(body, options2) {
+ return this._client.post("/containers", { body, ...options2, __security: { bearerAuth: true } });
+ }
+ /**
+ * Retrieve Container
+ */
+ retrieve(containerID, options2) {
+ return this._client.get(path15`/containers/${containerID}`, {
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * List Containers
+ */
+ list(query = {}, options2) {
+ return this._client.getAPIList("/containers", CursorPage, {
+ query,
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Delete Container
+ */
+ delete(containerID, options2) {
+ return this._client.delete(path15`/containers/${containerID}`, {
+ ...options2,
+ headers: buildHeaders([{ Accept: "*/*" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+};
+Containers.Files = Files;
+
+// node_modules/openai/resources/conversations/conversations.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/conversations/items.mjs
+init_esbuild_shims();
+var Items = class extends APIResource {
+ static {
+ __name(this, "Items");
+ }
+ /**
+ * Create items in a conversation with the given ID.
+ */
+ create(conversationID, params, options2) {
+ const { include, ...body } = params;
+ return this._client.post(path15`/conversations/${conversationID}/items`, {
+ query: { include },
+ body,
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Get a single item from a conversation with the given IDs.
+ */
+ retrieve(itemID, params, options2) {
+ const { conversation_id, ...query } = params;
+ return this._client.get(path15`/conversations/${conversation_id}/items/${itemID}`, {
+ query,
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * List all items for a conversation with the given ID.
+ */
+ list(conversationID, query = {}, options2) {
+ return this._client.getAPIList(path15`/conversations/${conversationID}/items`, ConversationCursorPage, { query, ...options2, __security: { bearerAuth: true } });
+ }
+ /**
+ * Delete an item from a conversation with the given IDs.
+ */
+ delete(itemID, params, options2) {
+ const { conversation_id } = params;
+ return this._client.delete(path15`/conversations/${conversation_id}/items/${itemID}`, {
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/conversations/conversations.mjs
+var Conversations = class extends APIResource {
+ static {
+ __name(this, "Conversations");
+ }
+ constructor() {
+ super(...arguments);
+ this.items = new Items(this._client);
+ }
+ /**
+ * Create a conversation.
+ */
+ create(body = {}, options2) {
+ return this._client.post("/conversations", { body, ...options2, __security: { bearerAuth: true } });
+ }
+ /**
+ * Get a conversation
+ */
+ retrieve(conversationID, options2) {
+ return this._client.get(path15`/conversations/${conversationID}`, {
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Update a conversation
+ */
+ update(conversationID, body, options2) {
+ return this._client.post(path15`/conversations/${conversationID}`, {
+ body,
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Delete a conversation. Items in the conversation will not be deleted.
+ */
+ delete(conversationID, options2) {
+ return this._client.delete(path15`/conversations/${conversationID}`, {
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+};
+Conversations.Items = Items;
+
+// node_modules/openai/resources/embeddings.mjs
+init_esbuild_shims();
+var Embeddings = class extends APIResource {
+ static {
+ __name(this, "Embeddings");
+ }
+ /**
+ * Creates an embedding vector representing the input text.
+ *
+ * @example
+ * ```ts
+ * const createEmbeddingResponse =
+ * await client.embeddings.create({
+ * input: 'The quick brown fox jumped over the lazy dog',
+ * model: 'text-embedding-3-small',
+ * });
+ * ```
+ */
+ create(body, options2) {
+ const hasUserProvidedEncodingFormat = !!body.encoding_format;
+ let encoding_format = hasUserProvidedEncodingFormat ? body.encoding_format : "base64";
+ if (hasUserProvidedEncodingFormat) {
+ loggerFor(this._client).debug("embeddings/user defined encoding_format:", body.encoding_format);
+ }
+ const response = this._client.post("/embeddings", {
+ body: {
+ ...body,
+ encoding_format
+ },
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ if (hasUserProvidedEncodingFormat) {
+ return response;
+ }
+ loggerFor(this._client).debug("embeddings/decoding base64 embeddings from base64");
+ return response._thenUnwrap((response2) => {
+ if (response2 && response2.data) {
+ response2.data.forEach((embeddingBase64Obj) => {
+ const embeddingBase64Str = embeddingBase64Obj.embedding;
+ embeddingBase64Obj.embedding = toFloat32Array(embeddingBase64Str);
+ });
+ }
+ return response2;
+ });
+ }
+};
+
+// node_modules/openai/resources/evals/evals.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/evals/runs/runs.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/evals/runs/output-items.mjs
+init_esbuild_shims();
+var OutputItems = class extends APIResource {
+ static {
+ __name(this, "OutputItems");
+ }
+ /**
+ * Get an evaluation run output item by ID.
+ */
+ retrieve(outputItemID, params, options2) {
+ const { eval_id, run_id } = params;
+ return this._client.get(path15`/evals/${eval_id}/runs/${run_id}/output_items/${outputItemID}`, {
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Get a list of output items for an evaluation run.
+ */
+ list(runID, params, options2) {
+ const { eval_id, ...query } = params;
+ return this._client.getAPIList(path15`/evals/${eval_id}/runs/${runID}/output_items`, CursorPage, { query, ...options2, __security: { bearerAuth: true } });
+ }
+};
+
+// node_modules/openai/resources/evals/runs/runs.mjs
+var Runs2 = class extends APIResource {
+ static {
+ __name(this, "Runs");
+ }
+ constructor() {
+ super(...arguments);
+ this.outputItems = new OutputItems(this._client);
+ }
+ /**
+ * Kicks off a new run for a given evaluation, specifying the data source, and what
+ * model configuration to use to test. The datasource will be validated against the
+ * schema specified in the config of the evaluation.
+ */
+ create(evalID, body, options2) {
+ return this._client.post(path15`/evals/${evalID}/runs`, {
+ body,
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Get an evaluation run by ID.
+ */
+ retrieve(runID, params, options2) {
+ const { eval_id } = params;
+ return this._client.get(path15`/evals/${eval_id}/runs/${runID}`, {
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Get a list of runs for an evaluation.
+ */
+ list(evalID, query = {}, options2) {
+ return this._client.getAPIList(path15`/evals/${evalID}/runs`, CursorPage, {
+ query,
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Delete an eval run.
+ */
+ delete(runID, params, options2) {
+ const { eval_id } = params;
+ return this._client.delete(path15`/evals/${eval_id}/runs/${runID}`, {
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Cancel an ongoing evaluation run.
+ */
+ cancel(runID, params, options2) {
+ const { eval_id } = params;
+ return this._client.post(path15`/evals/${eval_id}/runs/${runID}`, {
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+};
+Runs2.OutputItems = OutputItems;
+
+// node_modules/openai/resources/evals/evals.mjs
+var Evals = class extends APIResource {
+ static {
+ __name(this, "Evals");
+ }
+ constructor() {
+ super(...arguments);
+ this.runs = new Runs2(this._client);
+ }
+ /**
+ * Create the structure of an evaluation that can be used to test a model's
+ * performance. An evaluation is a set of testing criteria and the config for a
+ * data source, which dictates the schema of the data used in the evaluation. After
+ * creating an evaluation, you can run it on different models and model parameters.
+ * We support several types of graders and datasources. For more information, see
+ * the [Evals guide](https://platform.openai.com/docs/guides/evals).
+ */
+ create(body, options2) {
+ return this._client.post("/evals", { body, ...options2, __security: { bearerAuth: true } });
+ }
+ /**
+ * Get an evaluation by ID.
+ */
+ retrieve(evalID, options2) {
+ return this._client.get(path15`/evals/${evalID}`, { ...options2, __security: { bearerAuth: true } });
+ }
+ /**
+ * Update certain properties of an evaluation.
+ */
+ update(evalID, body, options2) {
+ return this._client.post(path15`/evals/${evalID}`, { body, ...options2, __security: { bearerAuth: true } });
+ }
+ /**
+ * List evaluations for a project.
+ */
+ list(query = {}, options2) {
+ return this._client.getAPIList("/evals", CursorPage, {
+ query,
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Delete an evaluation.
+ */
+ delete(evalID, options2) {
+ return this._client.delete(path15`/evals/${evalID}`, { ...options2, __security: { bearerAuth: true } });
+ }
+};
+Evals.Runs = Runs2;
+
+// node_modules/openai/resources/files.mjs
+init_esbuild_shims();
+var Files2 = class extends APIResource {
+ static {
+ __name(this, "Files");
+ }
+ /**
+ * Upload a file that can be used across various endpoints. Individual files can be
+ * up to 512 MB, and each project can store up to 2.5 TB of files in total. There
+ * is no organization-wide storage limit. Uploads to this endpoint are rate-limited
+ * to 1,000 requests per minute per authenticated user.
+ *
+ * - The Assistants API supports files up to 2 million tokens and of specific file
+ * types. See the
+ * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools)
+ * for details.
+ * - The Fine-tuning API only supports `.jsonl` files. The input also has certain
+ * required formats for fine-tuning
+ * [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input)
+ * or
+ * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input)
+ * models.
+ * - The Batch API only supports `.jsonl` files up to 200 MB in size. The input
+ * also has a specific required
+ * [format](https://platform.openai.com/docs/api-reference/batch/request-input).
+ * - For Retrieval or `file_search` ingestion, upload files here first. If you need
+ * to attach multiple uploaded files to the same vector store, use
+ * [`/vector_stores/{vector_store_id}/file_batches`](https://platform.openai.com/docs/api-reference/vector-stores-file-batches/createBatch)
+ * instead of attaching them one by one. Vector store attachment has separate
+ * limits from file upload, including 2,000 attached files per minute per
+ * organization.
+ *
+ * Please [contact us](https://help.openai.com/) if you need to increase these
+ * storage limits.
+ */
+ create(body, options2) {
+ return this._client.post("/files", multipartFormRequestOptions({ body, ...options2, __security: { bearerAuth: true } }, this._client));
+ }
+ /**
+ * Returns information about a specific file.
+ */
+ retrieve(fileID, options2) {
+ return this._client.get(path15`/files/${fileID}`, { ...options2, __security: { bearerAuth: true } });
+ }
+ /**
+ * Returns a list of files.
+ */
+ list(query = {}, options2) {
+ return this._client.getAPIList("/files", CursorPage, {
+ query,
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Delete a file and remove it from all vector stores.
+ */
+ delete(fileID, options2) {
+ return this._client.delete(path15`/files/${fileID}`, { ...options2, __security: { bearerAuth: true } });
+ }
+ /**
+ * Returns the contents of the specified file.
+ */
+ content(fileID, options2) {
+ return this._client.get(path15`/files/${fileID}/content`, {
+ ...options2,
+ headers: buildHeaders([{ Accept: "application/binary" }, options2?.headers]),
+ __security: { bearerAuth: true },
+ __binaryResponse: true
+ });
+ }
+ /**
+ * Waits for the given file to be processed, default timeout is 30 mins.
+ */
+ async waitForProcessing(id, { pollInterval = 5e3, maxWait = 30 * 60 * 1e3 } = {}) {
+ const TERMINAL_STATES = /* @__PURE__ */ new Set(["processed", "error", "deleted"]);
+ const start = Date.now();
+ let file2 = await this.retrieve(id);
+ while (!file2.status || !TERMINAL_STATES.has(file2.status)) {
+ await sleep(pollInterval);
+ file2 = await this.retrieve(id);
+ if (Date.now() - start > maxWait) {
+ throw new APIConnectionTimeoutError({
+ message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`
+ });
+ }
+ }
+ return file2;
+ }
+};
+
+// node_modules/openai/resources/fine-tuning/fine-tuning.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/fine-tuning/methods.mjs
+init_esbuild_shims();
+var Methods = class extends APIResource {
+ static {
+ __name(this, "Methods");
+ }
+};
+
+// node_modules/openai/resources/fine-tuning/alpha/alpha.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/fine-tuning/alpha/graders.mjs
+init_esbuild_shims();
+var Graders = class extends APIResource {
+ static {
+ __name(this, "Graders");
+ }
+ /**
+ * Run a grader.
+ *
+ * @example
+ * ```ts
+ * const response = await client.fineTuning.alpha.graders.run({
+ * grader: {
+ * input: 'input',
+ * name: 'name',
+ * operation: 'eq',
+ * reference: 'reference',
+ * type: 'string_check',
+ * },
+ * model_sample: 'model_sample',
+ * });
+ * ```
+ */
+ run(body, options2) {
+ return this._client.post("/fine_tuning/alpha/graders/run", {
+ body,
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Validate a grader.
+ *
+ * @example
+ * ```ts
+ * const response =
+ * await client.fineTuning.alpha.graders.validate({
+ * grader: {
+ * input: 'input',
+ * name: 'name',
+ * operation: 'eq',
+ * reference: 'reference',
+ * type: 'string_check',
+ * },
+ * });
+ * ```
+ */
+ validate(body, options2) {
+ return this._client.post("/fine_tuning/alpha/graders/validate", {
+ body,
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/fine-tuning/alpha/alpha.mjs
+var Alpha = class extends APIResource {
+ static {
+ __name(this, "Alpha");
+ }
+ constructor() {
+ super(...arguments);
+ this.graders = new Graders(this._client);
+ }
+};
+Alpha.Graders = Graders;
+
+// node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs
+init_esbuild_shims();
+var Permissions = class extends APIResource {
+ static {
+ __name(this, "Permissions");
+ }
+ /**
+ * **NOTE:** Calling this endpoint requires an [admin API key](../admin-api-keys).
+ *
+ * This enables organization owners to share fine-tuned models with other projects
+ * in their organization.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const permissionCreateResponse of client.fineTuning.checkpoints.permissions.create(
+ * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd',
+ * { project_ids: ['string'] },
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ create(fineTunedModelCheckpoint, body, options2) {
+ return this._client.getAPIList(path15`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, Page, { body, method: "post", ...options2, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys).
+ *
+ * Organization owners can use this endpoint to view all permissions for a
+ * fine-tuned model checkpoint.
+ *
+ * @deprecated Retrieve is deprecated. Please swap to the paginated list method instead.
+ */
+ retrieve(fineTunedModelCheckpoint, query = {}, options2) {
+ return this._client.get(path15`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, {
+ query,
+ ...options2,
+ __security: { adminAPIKeyAuth: true }
+ });
+ }
+ /**
+ * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys).
+ *
+ * Organization owners can use this endpoint to view all permissions for a
+ * fine-tuned model checkpoint.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const permissionListResponse of client.fineTuning.checkpoints.permissions.list(
+ * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(fineTunedModelCheckpoint, query = {}, options2) {
+ return this._client.getAPIList(path15`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, ConversationCursorPage, { query, ...options2, __security: { adminAPIKeyAuth: true } });
+ }
+ /**
+ * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys).
+ *
+ * Organization owners can use this endpoint to delete a permission for a
+ * fine-tuned model checkpoint.
+ *
+ * @example
+ * ```ts
+ * const permission =
+ * await client.fineTuning.checkpoints.permissions.delete(
+ * 'cp_zc4Q7MP6XxulcVzj4MZdwsAB',
+ * {
+ * fine_tuned_model_checkpoint:
+ * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd',
+ * },
+ * );
+ * ```
+ */
+ delete(permissionID, params, options2) {
+ const { fine_tuned_model_checkpoint } = params;
+ return this._client.delete(path15`/fine_tuning/checkpoints/${fine_tuned_model_checkpoint}/permissions/${permissionID}`, { ...options2, __security: { adminAPIKeyAuth: true } });
+ }
+};
+
+// node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs
+var Checkpoints = class extends APIResource {
+ static {
+ __name(this, "Checkpoints");
+ }
+ constructor() {
+ super(...arguments);
+ this.permissions = new Permissions(this._client);
+ }
+};
+Checkpoints.Permissions = Permissions;
+
+// node_modules/openai/resources/fine-tuning/jobs/jobs.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs
+init_esbuild_shims();
+var Checkpoints2 = class extends APIResource {
+ static {
+ __name(this, "Checkpoints");
+ }
+ /**
+ * List checkpoints for a fine-tuning job.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const fineTuningJobCheckpoint of client.fineTuning.jobs.checkpoints.list(
+ * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(fineTuningJobID, query = {}, options2) {
+ return this._client.getAPIList(path15`/fine_tuning/jobs/${fineTuningJobID}/checkpoints`, CursorPage, { query, ...options2, __security: { bearerAuth: true } });
+ }
+};
+
+// node_modules/openai/resources/fine-tuning/jobs/jobs.mjs
+var Jobs = class extends APIResource {
+ static {
+ __name(this, "Jobs");
+ }
+ constructor() {
+ super(...arguments);
+ this.checkpoints = new Checkpoints2(this._client);
+ }
+ /**
+ * Creates a fine-tuning job which begins the process of creating a new model from
+ * a given dataset.
+ *
+ * Response includes details of the enqueued job including job status and the name
+ * of the fine-tuned models once complete.
+ *
+ * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization)
+ *
+ * @example
+ * ```ts
+ * const fineTuningJob = await client.fineTuning.jobs.create({
+ * model: 'gpt-4o-mini',
+ * training_file: 'file-abc123',
+ * });
+ * ```
+ */
+ create(body, options2) {
+ return this._client.post("/fine_tuning/jobs", { body, ...options2, __security: { bearerAuth: true } });
+ }
+ /**
+ * Get info about a fine-tuning job.
+ *
+ * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization)
+ *
+ * @example
+ * ```ts
+ * const fineTuningJob = await client.fineTuning.jobs.retrieve(
+ * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
+ * );
+ * ```
+ */
+ retrieve(fineTuningJobID, options2) {
+ return this._client.get(path15`/fine_tuning/jobs/${fineTuningJobID}`, {
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * List your organization's fine-tuning jobs
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const fineTuningJob of client.fineTuning.jobs.list()) {
+ * // ...
+ * }
+ * ```
+ */
+ list(query = {}, options2) {
+ return this._client.getAPIList("/fine_tuning/jobs", CursorPage, {
+ query,
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Immediately cancel a fine-tune job.
+ *
+ * @example
+ * ```ts
+ * const fineTuningJob = await client.fineTuning.jobs.cancel(
+ * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
+ * );
+ * ```
+ */
+ cancel(fineTuningJobID, options2) {
+ return this._client.post(path15`/fine_tuning/jobs/${fineTuningJobID}/cancel`, {
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Get status updates for a fine-tuning job.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const fineTuningJobEvent of client.fineTuning.jobs.listEvents(
+ * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ listEvents(fineTuningJobID, query = {}, options2) {
+ return this._client.getAPIList(path15`/fine_tuning/jobs/${fineTuningJobID}/events`, CursorPage, { query, ...options2, __security: { bearerAuth: true } });
+ }
+ /**
+ * Pause a fine-tune job.
+ *
+ * @example
+ * ```ts
+ * const fineTuningJob = await client.fineTuning.jobs.pause(
+ * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
+ * );
+ * ```
+ */
+ pause(fineTuningJobID, options2) {
+ return this._client.post(path15`/fine_tuning/jobs/${fineTuningJobID}/pause`, {
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Resume a fine-tune job.
+ *
+ * @example
+ * ```ts
+ * const fineTuningJob = await client.fineTuning.jobs.resume(
+ * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
+ * );
+ * ```
+ */
+ resume(fineTuningJobID, options2) {
+ return this._client.post(path15`/fine_tuning/jobs/${fineTuningJobID}/resume`, {
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+};
+Jobs.Checkpoints = Checkpoints2;
+
+// node_modules/openai/resources/fine-tuning/fine-tuning.mjs
+var FineTuning = class extends APIResource {
+ static {
+ __name(this, "FineTuning");
+ }
+ constructor() {
+ super(...arguments);
+ this.methods = new Methods(this._client);
+ this.jobs = new Jobs(this._client);
+ this.checkpoints = new Checkpoints(this._client);
+ this.alpha = new Alpha(this._client);
+ }
+};
+FineTuning.Methods = Methods;
+FineTuning.Jobs = Jobs;
+FineTuning.Checkpoints = Checkpoints;
+FineTuning.Alpha = Alpha;
+
+// node_modules/openai/resources/graders/graders.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/graders/grader-models.mjs
+init_esbuild_shims();
+var GraderModels = class extends APIResource {
+ static {
+ __name(this, "GraderModels");
+ }
+};
+
+// node_modules/openai/resources/graders/graders.mjs
+var Graders2 = class extends APIResource {
+ static {
+ __name(this, "Graders");
+ }
+ constructor() {
+ super(...arguments);
+ this.graderModels = new GraderModels(this._client);
+ }
+};
+Graders2.GraderModels = GraderModels;
+
+// node_modules/openai/resources/images.mjs
+init_esbuild_shims();
+var Images = class extends APIResource {
+ static {
+ __name(this, "Images");
+ }
+ /**
+ * Creates a variation of a given image. This endpoint only supports `dall-e-2`.
+ *
+ * @example
+ * ```ts
+ * const imagesResponse = await client.images.createVariation({
+ * image: fs.createReadStream('otter.png'),
+ * });
+ * ```
+ */
+ createVariation(body, options2) {
+ return this._client.post("/images/variations", multipartFormRequestOptions({ body, ...options2, __security: { bearerAuth: true } }, this._client));
+ }
+ edit(body, options2) {
+ return this._client.post("/images/edits", multipartFormRequestOptions({ body, ...options2, stream: body.stream ?? false, __security: { bearerAuth: true } }, this._client));
+ }
+ generate(body, options2) {
+ return this._client.post("/images/generations", {
+ body,
+ ...options2,
+ stream: body.stream ?? false,
+ __security: { bearerAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/models.mjs
+init_esbuild_shims();
+var Models = class extends APIResource {
+ static {
+ __name(this, "Models");
+ }
+ /**
+ * Retrieves a model instance, providing basic information about the model such as
+ * the owner and permissioning.
+ */
+ retrieve(model, options2) {
+ return this._client.get(path15`/models/${model}`, { ...options2, __security: { bearerAuth: true } });
+ }
+ /**
+ * Lists the currently available models, and provides basic information about each
+ * one such as the owner and availability.
+ */
+ list(options2) {
+ return this._client.getAPIList("/models", Page, { ...options2, __security: { bearerAuth: true } });
+ }
+ /**
+ * Delete a fine-tuned model. You must have the Owner role in your organization to
+ * delete a model.
+ */
+ delete(model, options2) {
+ return this._client.delete(path15`/models/${model}`, { ...options2, __security: { bearerAuth: true } });
+ }
+};
+
+// node_modules/openai/resources/moderations.mjs
+init_esbuild_shims();
+var Moderations = class extends APIResource {
+ static {
+ __name(this, "Moderations");
+ }
+ /**
+ * Classifies if text and/or image inputs are potentially harmful. Learn more in
+ * the [moderation guide](https://platform.openai.com/docs/guides/moderation).
+ */
+ create(body, options2) {
+ return this._client.post("/moderations", { body, ...options2, __security: { bearerAuth: true } });
+ }
+};
+
+// node_modules/openai/resources/realtime/realtime.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/realtime/calls.mjs
+init_esbuild_shims();
+var Calls = class extends APIResource {
+ static {
+ __name(this, "Calls");
+ }
+ /**
+ * Accept an incoming SIP call and configure the realtime session that will handle
+ * it.
+ *
+ * @example
+ * ```ts
+ * await client.realtime.calls.accept('call_id', {
+ * type: 'realtime',
+ * });
+ * ```
+ */
+ accept(callID, body, options2) {
+ return this._client.post(path15`/realtime/calls/${callID}/accept`, {
+ body,
+ ...options2,
+ headers: buildHeaders([{ Accept: "*/*" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * End an active Realtime API call, whether it was initiated over SIP or WebRTC.
+ *
+ * @example
+ * ```ts
+ * await client.realtime.calls.hangup('call_id');
+ * ```
+ */
+ hangup(callID, options2) {
+ return this._client.post(path15`/realtime/calls/${callID}/hangup`, {
+ ...options2,
+ headers: buildHeaders([{ Accept: "*/*" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Transfer an active SIP call to a new destination using the SIP REFER verb.
+ *
+ * @example
+ * ```ts
+ * await client.realtime.calls.refer('call_id', {
+ * target_uri: 'tel:+14155550123',
+ * });
+ * ```
+ */
+ refer(callID, body, options2) {
+ return this._client.post(path15`/realtime/calls/${callID}/refer`, {
+ body,
+ ...options2,
+ headers: buildHeaders([{ Accept: "*/*" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Decline an incoming SIP call by returning a SIP status code to the caller.
+ *
+ * @example
+ * ```ts
+ * await client.realtime.calls.reject('call_id');
+ * ```
+ */
+ reject(callID, body = {}, options2) {
+ return this._client.post(path15`/realtime/calls/${callID}/reject`, {
+ body,
+ ...options2,
+ headers: buildHeaders([{ Accept: "*/*" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/realtime/client-secrets.mjs
+init_esbuild_shims();
+var ClientSecrets = class extends APIResource {
+ static {
+ __name(this, "ClientSecrets");
+ }
+ /**
+ * Create a Realtime client secret with an associated session configuration.
+ *
+ * Client secrets are short-lived tokens that can be passed to a client app, such
+ * as a web frontend or mobile client, which grants access to the Realtime API
+ * without leaking your main API key. You can configure a custom TTL for each
+ * client secret.
+ *
+ * You can also attach session configuration options to the client secret, which
+ * will be applied to any sessions created using that client secret, but these can
+ * also be overridden by the client connection.
+ *
+ * [Learn more about authentication with client secrets over WebRTC](https://platform.openai.com/docs/guides/realtime-webrtc).
+ *
+ * Returns the created client secret and the effective session object. The client
+ * secret is a string that looks like `ek_1234`.
+ *
+ * @example
+ * ```ts
+ * const clientSecret =
+ * await client.realtime.clientSecrets.create();
+ * ```
+ */
+ create(body, options2) {
+ return this._client.post("/realtime/client_secrets", {
+ body,
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/realtime/realtime.mjs
+var Realtime2 = class extends APIResource {
+ static {
+ __name(this, "Realtime");
+ }
+ constructor() {
+ super(...arguments);
+ this.clientSecrets = new ClientSecrets(this._client);
+ this.calls = new Calls(this._client);
+ }
+};
+Realtime2.ClientSecrets = ClientSecrets;
+Realtime2.Calls = Calls;
+
+// node_modules/openai/resources/responses/responses.mjs
+init_esbuild_shims();
+
+// node_modules/openai/lib/ResponsesParser.mjs
+init_esbuild_shims();
+function maybeParseResponse(response, params) {
+ if (!params || !hasAutoParseableInput2(params)) {
+ return {
+ ...response,
+ output_parsed: null,
+ output: response.output.map((item) => {
+ if (item.type === "function_call") {
+ return {
+ ...item,
+ parsed_arguments: null
+ };
+ }
+ if (item.type === "message") {
+ return {
+ ...item,
+ content: item.content.map((content) => ({
+ ...content,
+ parsed: null
+ }))
+ };
+ } else {
+ return item;
+ }
+ })
+ };
+ }
+ return parseResponse(response, params);
+}
+__name(maybeParseResponse, "maybeParseResponse");
+function parseResponse(response, params) {
+ const output = response.output.map((item) => {
+ if (item.type === "function_call") {
+ return {
+ ...item,
+ parsed_arguments: parseToolCall2(params, item)
+ };
+ }
+ if (item.type === "message") {
+ const content = item.content.map((content2) => {
+ if (content2.type === "output_text") {
+ return {
+ ...content2,
+ parsed: parseTextFormat(params, content2.text)
+ };
+ }
+ return content2;
+ });
+ return {
+ ...item,
+ content
+ };
+ }
+ return item;
+ });
+ const parsed = Object.assign({}, response, { output });
+ if (!Object.getOwnPropertyDescriptor(response, "output_text")) {
+ addOutputText(parsed);
+ }
+ Object.defineProperty(parsed, "output_parsed", {
+ enumerable: true,
+ get() {
+ for (const output2 of parsed.output) {
+ if (output2.type !== "message") {
+ continue;
+ }
+ for (const content of output2.content) {
+ if (content.type === "output_text" && content.parsed !== null) {
+ return content.parsed;
+ }
+ }
+ }
+ return null;
+ }
+ });
+ return parsed;
+}
+__name(parseResponse, "parseResponse");
+function parseTextFormat(params, content) {
+ if (params.text?.format?.type !== "json_schema") {
+ return null;
+ }
+ if ("$parseRaw" in params.text?.format) {
+ const text_format = params.text?.format;
+ return text_format.$parseRaw(content);
+ }
+ return JSON.parse(content);
+}
+__name(parseTextFormat, "parseTextFormat");
+function hasAutoParseableInput2(params) {
+ if (isAutoParsableResponseFormat(params.text?.format)) {
+ return true;
+ }
+ return false;
+}
+__name(hasAutoParseableInput2, "hasAutoParseableInput");
+function isAutoParsableTool2(tool) {
+ return tool?.["$brand"] === "auto-parseable-tool";
+}
+__name(isAutoParsableTool2, "isAutoParsableTool");
+function getInputToolByName(input_tools, name) {
+ return input_tools.find((tool) => tool.type === "function" && tool.name === name);
+}
+__name(getInputToolByName, "getInputToolByName");
+function parseToolCall2(params, toolCall) {
+ const inputTool = getInputToolByName(params.tools ?? [], toolCall.name);
+ return {
+ ...toolCall,
+ ...toolCall,
+ parsed_arguments: isAutoParsableTool2(inputTool) ? inputTool.$parseRaw(toolCall.arguments) : inputTool?.strict ? JSON.parse(toolCall.arguments) : null
+ };
+}
+__name(parseToolCall2, "parseToolCall");
+function addOutputText(rsp) {
+ const texts = [];
+ for (const output of rsp.output) {
+ if (output.type !== "message") {
+ continue;
+ }
+ for (const content of output.content) {
+ if (content.type === "output_text") {
+ texts.push(content.text);
+ }
+ }
+ }
+ rsp.output_text = texts.join("");
+}
+__name(addOutputText, "addOutputText");
+
+// node_modules/openai/lib/responses/ResponseStream.mjs
+init_esbuild_shims();
+var _ResponseStream_instances;
+var _ResponseStream_params;
+var _ResponseStream_currentResponseSnapshot;
+var _ResponseStream_finalResponse;
+var _ResponseStream_beginRequest;
+var _ResponseStream_addEvent;
+var _ResponseStream_endRequest;
+var _ResponseStream_accumulateResponse;
+var ResponseStream = class _ResponseStream extends EventStream {
+ static {
+ __name(this, "ResponseStream");
+ }
+ constructor(params) {
+ super();
+ _ResponseStream_instances.add(this);
+ _ResponseStream_params.set(this, void 0);
+ _ResponseStream_currentResponseSnapshot.set(this, void 0);
+ _ResponseStream_finalResponse.set(this, void 0);
+ __classPrivateFieldSet(this, _ResponseStream_params, params, "f");
+ }
+ static createResponse(client, params, options2) {
+ const runner = new _ResponseStream(params);
+ runner._run(() => runner._createOrRetrieveResponse(client, params, {
+ ...options2,
+ headers: { ...options2?.headers, "X-Stainless-Helper-Method": "stream" }
+ }));
+ return runner;
+ }
+ async _createOrRetrieveResponse(client, params, options2) {
+ const signal = options2?.signal;
+ if (signal) {
+ if (signal.aborted)
+ this.controller.abort();
+ signal.addEventListener("abort", () => this.controller.abort());
+ }
+ __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_beginRequest).call(this);
+ let stream;
+ let starting_after = null;
+ if ("response_id" in params) {
+ stream = await client.responses.retrieve(params.response_id, { stream: true }, { ...options2, signal: this.controller.signal, stream: true });
+ starting_after = params.starting_after ?? null;
+ } else {
+ stream = await client.responses.create({ ...params, stream: true }, { ...options2, signal: this.controller.signal });
+ }
+ this._connected();
+ for await (const event of stream) {
+ __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_addEvent).call(this, event, starting_after);
+ }
+ if (stream.controller.signal?.aborted) {
+ throw new APIUserAbortError();
+ }
+ return __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_endRequest).call(this);
+ }
+ [(_ResponseStream_params = /* @__PURE__ */ new WeakMap(), _ResponseStream_currentResponseSnapshot = /* @__PURE__ */ new WeakMap(), _ResponseStream_finalResponse = /* @__PURE__ */ new WeakMap(), _ResponseStream_instances = /* @__PURE__ */ new WeakSet(), _ResponseStream_beginRequest = /* @__PURE__ */ __name(function _ResponseStream_beginRequest2() {
+ if (this.ended)
+ return;
+ __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, void 0, "f");
+ }, "_ResponseStream_beginRequest"), _ResponseStream_addEvent = /* @__PURE__ */ __name(function _ResponseStream_addEvent2(event, starting_after) {
+ if (this.ended)
+ return;
+ const maybeEmit = /* @__PURE__ */ __name((name, event2) => {
+ if (starting_after == null || event2.sequence_number > starting_after) {
+ this._emit(name, event2);
+ }
+ }, "maybeEmit");
+ const response = __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_accumulateResponse).call(this, event);
+ maybeEmit("event", event);
+ switch (event.type) {
+ case "response.output_text.delta": {
+ const output = response.output[event.output_index];
+ if (!output) {
+ throw new OpenAIError(`missing output at index ${event.output_index}`);
+ }
+ if (output.type === "message") {
+ const content = output.content[event.content_index];
+ if (!content) {
+ throw new OpenAIError(`missing content at index ${event.content_index}`);
+ }
+ if (content.type !== "output_text") {
+ throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);
+ }
+ maybeEmit("response.output_text.delta", {
+ ...event,
+ snapshot: content.text
+ });
+ }
+ break;
+ }
+ case "response.function_call_arguments.delta": {
+ const output = response.output[event.output_index];
+ if (!output) {
+ throw new OpenAIError(`missing output at index ${event.output_index}`);
+ }
+ if (output.type === "function_call") {
+ maybeEmit("response.function_call_arguments.delta", {
+ ...event,
+ snapshot: output.arguments
+ });
+ }
+ break;
+ }
+ default:
+ maybeEmit(event.type, event);
+ break;
+ }
+ }, "_ResponseStream_addEvent"), _ResponseStream_endRequest = /* @__PURE__ */ __name(function _ResponseStream_endRequest2() {
+ if (this.ended) {
+ throw new OpenAIError(`stream has ended, this shouldn't happen`);
+ }
+ const snapshot = __classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, "f");
+ if (!snapshot) {
+ throw new OpenAIError(`request ended without sending any events`);
+ }
+ __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, void 0, "f");
+ const parsedResponse = finalizeResponse(snapshot, __classPrivateFieldGet(this, _ResponseStream_params, "f"));
+ __classPrivateFieldSet(this, _ResponseStream_finalResponse, parsedResponse, "f");
+ return parsedResponse;
+ }, "_ResponseStream_endRequest"), _ResponseStream_accumulateResponse = /* @__PURE__ */ __name(function _ResponseStream_accumulateResponse2(event) {
+ let snapshot = __classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, "f");
+ if (!snapshot) {
+ if (event.type !== "response.created") {
+ throw new OpenAIError(`When snapshot hasn't been set yet, expected 'response.created' event, got ${event.type}`);
+ }
+ snapshot = __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, event.response, "f");
+ return snapshot;
+ }
+ switch (event.type) {
+ case "response.output_item.added": {
+ snapshot.output.push(event.item);
+ break;
+ }
+ case "response.content_part.added": {
+ const output = snapshot.output[event.output_index];
+ if (!output) {
+ throw new OpenAIError(`missing output at index ${event.output_index}`);
+ }
+ const type2 = output.type;
+ const part = event.part;
+ if (type2 === "message" && part.type !== "reasoning_text") {
+ output.content.push(part);
+ } else if (type2 === "reasoning" && part.type === "reasoning_text") {
+ if (!output.content) {
+ output.content = [];
+ }
+ output.content.push(part);
+ }
+ break;
+ }
+ case "response.output_text.delta": {
+ const output = snapshot.output[event.output_index];
+ if (!output) {
+ throw new OpenAIError(`missing output at index ${event.output_index}`);
+ }
+ if (output.type === "message") {
+ const content = output.content[event.content_index];
+ if (!content) {
+ throw new OpenAIError(`missing content at index ${event.content_index}`);
+ }
+ if (content.type !== "output_text") {
+ throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);
+ }
+ content.text += event.delta;
+ }
+ break;
+ }
+ case "response.function_call_arguments.delta": {
+ const output = snapshot.output[event.output_index];
+ if (!output) {
+ throw new OpenAIError(`missing output at index ${event.output_index}`);
+ }
+ if (output.type === "function_call") {
+ output.arguments += event.delta;
+ }
+ break;
+ }
+ case "response.reasoning_text.delta": {
+ const output = snapshot.output[event.output_index];
+ if (!output) {
+ throw new OpenAIError(`missing output at index ${event.output_index}`);
+ }
+ if (output.type === "reasoning") {
+ const content = output.content?.[event.content_index];
+ if (!content) {
+ throw new OpenAIError(`missing content at index ${event.content_index}`);
+ }
+ if (content.type !== "reasoning_text") {
+ throw new OpenAIError(`expected content to be 'reasoning_text', got ${content.type}`);
+ }
+ content.text += event.delta;
+ }
+ break;
+ }
+ case "response.completed": {
+ __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, event.response, "f");
+ break;
+ }
+ }
+ return snapshot;
+ }, "_ResponseStream_accumulateResponse"), Symbol.asyncIterator)]() {
+ const pushQueue = [];
+ const readQueue = [];
+ let done = false;
+ this.on("event", (event) => {
+ const reader = readQueue.shift();
+ if (reader) {
+ reader.resolve(event);
+ } else {
+ pushQueue.push(event);
+ }
+ });
+ this.on("end", () => {
+ done = true;
+ for (const reader of readQueue) {
+ reader.resolve(void 0);
+ }
+ readQueue.length = 0;
+ });
+ this.on("abort", (err) => {
+ done = true;
+ for (const reader of readQueue) {
+ reader.reject(err);
+ }
+ readQueue.length = 0;
+ });
+ this.on("error", (err) => {
+ done = true;
+ for (const reader of readQueue) {
+ reader.reject(err);
+ }
+ readQueue.length = 0;
+ });
+ return {
+ next: /* @__PURE__ */ __name(async () => {
+ if (!pushQueue.length) {
+ if (done) {
+ return { value: void 0, done: true };
+ }
+ return new Promise((resolve16, reject) => readQueue.push({ resolve: resolve16, reject })).then((event2) => event2 ? { value: event2, done: false } : { value: void 0, done: true });
+ }
+ const event = pushQueue.shift();
+ return { value: event, done: false };
+ }, "next"),
+ return: /* @__PURE__ */ __name(async () => {
+ this.abort();
+ return { value: void 0, done: true };
+ }, "return")
+ };
+ }
+ /**
+ * @returns a promise that resolves with the final Response, or rejects
+ * if an error occurred or the stream ended prematurely without producing a REsponse.
+ */
+ async finalResponse() {
+ await this.done();
+ const response = __classPrivateFieldGet(this, _ResponseStream_finalResponse, "f");
+ if (!response)
+ throw new OpenAIError("stream ended without producing a ChatCompletion");
+ return response;
+ }
+};
+function finalizeResponse(snapshot, params) {
+ return maybeParseResponse(snapshot, params);
+}
+__name(finalizeResponse, "finalizeResponse");
+
+// node_modules/openai/resources/responses/input-items.mjs
+init_esbuild_shims();
+var InputItems = class extends APIResource {
+ static {
+ __name(this, "InputItems");
+ }
+ /**
+ * Returns a list of input items for a given response.
+ *
+ * @example
+ * ```ts
+ * // Automatically fetches more pages as needed.
+ * for await (const responseItem of client.responses.inputItems.list(
+ * 'response_id',
+ * )) {
+ * // ...
+ * }
+ * ```
+ */
+ list(responseID, query = {}, options2) {
+ return this._client.getAPIList(path15`/responses/${responseID}/input_items`, CursorPage, { query, ...options2, __security: { bearerAuth: true } });
+ }
+};
+
+// node_modules/openai/resources/responses/input-tokens.mjs
+init_esbuild_shims();
+var InputTokens = class extends APIResource {
+ static {
+ __name(this, "InputTokens");
+ }
+ /**
+ * Returns input token counts of the request.
+ *
+ * Returns an object with `object` set to `response.input_tokens` and an
+ * `input_tokens` count.
+ *
+ * @example
+ * ```ts
+ * const response = await client.responses.inputTokens.count();
+ * ```
+ */
+ count(body = {}, options2) {
+ return this._client.post("/responses/input_tokens", {
+ body,
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/responses/responses.mjs
+var Responses = class extends APIResource {
+ static {
+ __name(this, "Responses");
+ }
+ constructor() {
+ super(...arguments);
+ this.inputItems = new InputItems(this._client);
+ this.inputTokens = new InputTokens(this._client);
+ }
+ create(body, options2) {
+ return this._client.post("/responses", {
+ body,
+ ...options2,
+ stream: body.stream ?? false,
+ __security: { bearerAuth: true }
+ })._thenUnwrap((rsp) => {
+ if ("object" in rsp && rsp.object === "response") {
+ addOutputText(rsp);
+ }
+ return rsp;
+ });
+ }
+ retrieve(responseID, query = {}, options2) {
+ return this._client.get(path15`/responses/${responseID}`, {
+ query,
+ ...options2,
+ stream: query?.stream ?? false,
+ __security: { bearerAuth: true }
+ })._thenUnwrap((rsp) => {
+ if ("object" in rsp && rsp.object === "response") {
+ addOutputText(rsp);
+ }
+ return rsp;
+ });
+ }
+ /**
+ * Deletes a model response with the given ID.
+ *
+ * @example
+ * ```ts
+ * await client.responses.delete(
+ * 'resp_677efb5139a88190b512bc3fef8e535d',
+ * );
+ * ```
+ */
+ delete(responseID, options2) {
+ return this._client.delete(path15`/responses/${responseID}`, {
+ ...options2,
+ headers: buildHeaders([{ Accept: "*/*" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ parse(body, options2) {
+ return this._client.responses.create(body, options2)._thenUnwrap((response) => parseResponse(response, body));
+ }
+ /**
+ * Creates a model response stream
+ */
+ stream(body, options2) {
+ return ResponseStream.createResponse(this._client, body, options2);
+ }
+ /**
+ * Cancels a model response with the given ID. Only responses created with the
+ * `background` parameter set to `true` can be cancelled.
+ * [Learn more](https://platform.openai.com/docs/guides/background).
+ *
+ * @example
+ * ```ts
+ * const response = await client.responses.cancel(
+ * 'resp_677efb5139a88190b512bc3fef8e535d',
+ * );
+ * ```
+ */
+ cancel(responseID, options2) {
+ return this._client.post(path15`/responses/${responseID}/cancel`, {
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Compact a conversation. Returns a compacted response object.
+ *
+ * Learn when and how to compact long-running conversations in the
+ * [conversation state guide](https://platform.openai.com/docs/guides/conversation-state#managing-the-context-window).
+ * For ZDR-compatible compaction details, see
+ * [Compaction (advanced)](https://platform.openai.com/docs/guides/conversation-state#compaction-advanced).
+ *
+ * @example
+ * ```ts
+ * const compactedResponse = await client.responses.compact({
+ * model: 'gpt-5.4',
+ * });
+ * ```
+ */
+ compact(body, options2) {
+ return this._client.post("/responses/compact", { body, ...options2, __security: { bearerAuth: true } });
+ }
+};
+Responses.InputItems = InputItems;
+Responses.InputTokens = InputTokens;
+
+// node_modules/openai/resources/skills/skills.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/skills/content.mjs
+init_esbuild_shims();
+var Content2 = class extends APIResource {
+ static {
+ __name(this, "Content");
+ }
+ /**
+ * Download a skill zip bundle by its ID.
+ */
+ retrieve(skillID, options2) {
+ return this._client.get(path15`/skills/${skillID}/content`, {
+ ...options2,
+ headers: buildHeaders([{ Accept: "application/binary" }, options2?.headers]),
+ __security: { bearerAuth: true },
+ __binaryResponse: true
+ });
+ }
+};
+
+// node_modules/openai/resources/skills/versions/versions.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/skills/versions/content.mjs
+init_esbuild_shims();
+var Content3 = class extends APIResource {
+ static {
+ __name(this, "Content");
+ }
+ /**
+ * Download a skill version zip bundle.
+ */
+ retrieve(version2, params, options2) {
+ const { skill_id } = params;
+ return this._client.get(path15`/skills/${skill_id}/versions/${version2}/content`, {
+ ...options2,
+ headers: buildHeaders([{ Accept: "application/binary" }, options2?.headers]),
+ __security: { bearerAuth: true },
+ __binaryResponse: true
+ });
+ }
+};
+
+// node_modules/openai/resources/skills/versions/versions.mjs
+var Versions = class extends APIResource {
+ static {
+ __name(this, "Versions");
+ }
+ constructor() {
+ super(...arguments);
+ this.content = new Content3(this._client);
+ }
+ /**
+ * Create a new immutable skill version.
+ */
+ create(skillID, body = {}, options2) {
+ return this._client.post(path15`/skills/${skillID}/versions`, maybeMultipartFormRequestOptions({ body, ...options2, __security: { bearerAuth: true } }, this._client));
+ }
+ /**
+ * Get a specific skill version.
+ */
+ retrieve(version2, params, options2) {
+ const { skill_id } = params;
+ return this._client.get(path15`/skills/${skill_id}/versions/${version2}`, {
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * List skill versions for a skill.
+ */
+ list(skillID, query = {}, options2) {
+ return this._client.getAPIList(path15`/skills/${skillID}/versions`, CursorPage, {
+ query,
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Delete a skill version.
+ */
+ delete(version2, params, options2) {
+ const { skill_id } = params;
+ return this._client.delete(path15`/skills/${skill_id}/versions/${version2}`, {
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+};
+Versions.Content = Content3;
+
+// node_modules/openai/resources/skills/skills.mjs
+var Skills = class extends APIResource {
+ static {
+ __name(this, "Skills");
+ }
+ constructor() {
+ super(...arguments);
+ this.content = new Content2(this._client);
+ this.versions = new Versions(this._client);
+ }
+ /**
+ * Create a new skill.
+ */
+ create(body = {}, options2) {
+ return this._client.post("/skills", maybeMultipartFormRequestOptions({ body, ...options2, __security: { bearerAuth: true } }, this._client));
+ }
+ /**
+ * Get a skill by its ID.
+ */
+ retrieve(skillID, options2) {
+ return this._client.get(path15`/skills/${skillID}`, { ...options2, __security: { bearerAuth: true } });
+ }
+ /**
+ * Update the default version pointer for a skill.
+ */
+ update(skillID, body, options2) {
+ return this._client.post(path15`/skills/${skillID}`, {
+ body,
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * List all skills for the current project.
+ */
+ list(query = {}, options2) {
+ return this._client.getAPIList("/skills", CursorPage, {
+ query,
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Delete a skill by its ID.
+ */
+ delete(skillID, options2) {
+ return this._client.delete(path15`/skills/${skillID}`, { ...options2, __security: { bearerAuth: true } });
+ }
+};
+Skills.Content = Content2;
+Skills.Versions = Versions;
+
+// node_modules/openai/resources/uploads/uploads.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/uploads/parts.mjs
+init_esbuild_shims();
+var Parts = class extends APIResource {
+ static {
+ __name(this, "Parts");
+ }
+ /**
+ * Adds a
+ * [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an
+ * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object.
+ * A Part represents a chunk of bytes from the file you are trying to upload.
+ *
+ * Each Part can be at most 64 MB, and you can add Parts until you hit the Upload
+ * maximum of 8 GB.
+ *
+ * It is possible to add multiple Parts in parallel. You can decide the intended
+ * order of the Parts when you
+ * [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete).
+ */
+ create(uploadID, body, options2) {
+ return this._client.post(path15`/uploads/${uploadID}/parts`, multipartFormRequestOptions({ body, ...options2, __security: { bearerAuth: true } }, this._client));
+ }
+};
+
+// node_modules/openai/resources/uploads/uploads.mjs
+var Uploads = class extends APIResource {
+ static {
+ __name(this, "Uploads");
+ }
+ constructor() {
+ super(...arguments);
+ this.parts = new Parts(this._client);
+ }
+ /**
+ * Creates an intermediate
+ * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object
+ * that you can add
+ * [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to.
+ * Currently, an Upload can accept at most 8 GB in total and expires after an hour
+ * after you create it.
+ *
+ * Once you complete the Upload, we will create a
+ * [File](https://platform.openai.com/docs/api-reference/files/object) object that
+ * contains all the parts you uploaded. This File is usable in the rest of our
+ * platform as a regular File object.
+ *
+ * For certain `purpose` values, the correct `mime_type` must be specified. Please
+ * refer to documentation for the
+ * [supported MIME types for your use case](https://platform.openai.com/docs/assistants/tools/file-search#supported-files).
+ *
+ * For guidance on the proper filename extensions for each purpose, please follow
+ * the documentation on
+ * [creating a File](https://platform.openai.com/docs/api-reference/files/create).
+ *
+ * Returns the Upload object with status `pending`.
+ */
+ create(body, options2) {
+ return this._client.post("/uploads", { body, ...options2, __security: { bearerAuth: true } });
+ }
+ /**
+ * Cancels the Upload. No Parts may be added after an Upload is cancelled.
+ *
+ * Returns the Upload object with status `cancelled`.
+ */
+ cancel(uploadID, options2) {
+ return this._client.post(path15`/uploads/${uploadID}/cancel`, {
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Completes the
+ * [Upload](https://platform.openai.com/docs/api-reference/uploads/object).
+ *
+ * Within the returned Upload object, there is a nested
+ * [File](https://platform.openai.com/docs/api-reference/files/object) object that
+ * is ready to use in the rest of the platform.
+ *
+ * You can specify the order of the Parts by passing in an ordered list of the Part
+ * IDs.
+ *
+ * The number of bytes uploaded upon completion must match the number of bytes
+ * initially specified when creating the Upload object. No Parts may be added after
+ * an Upload is completed. Returns the Upload object with status `completed`,
+ * including an additional `file` property containing the created usable File
+ * object.
+ */
+ complete(uploadID, body, options2) {
+ return this._client.post(path15`/uploads/${uploadID}/complete`, {
+ body,
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+};
+Uploads.Parts = Parts;
+
+// node_modules/openai/resources/vector-stores/vector-stores.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/vector-stores/file-batches.mjs
+init_esbuild_shims();
+
+// node_modules/openai/lib/Util.mjs
+init_esbuild_shims();
+var allSettledWithThrow = /* @__PURE__ */ __name(async (promises) => {
+ const results = await Promise.allSettled(promises);
+ const rejected = results.filter((result) => result.status === "rejected");
+ if (rejected.length) {
+ for (const result of rejected) {
+ console.error(result.reason);
+ }
+ throw new Error(`${rejected.length} promise(s) failed - see the above errors`);
+ }
+ const values = [];
+ for (const result of results) {
+ if (result.status === "fulfilled") {
+ values.push(result.value);
+ }
+ }
+ return values;
+}, "allSettledWithThrow");
+
+// node_modules/openai/resources/vector-stores/file-batches.mjs
+var FileBatches = class extends APIResource {
+ static {
+ __name(this, "FileBatches");
+ }
+ /**
+ * Create a vector store file batch.
+ */
+ create(vectorStoreID, body, options2) {
+ return this._client.post(path15`/vector_stores/${vectorStoreID}/file_batches`, {
+ body,
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Retrieves a vector store file batch.
+ */
+ retrieve(batchID, params, options2) {
+ const { vector_store_id } = params;
+ return this._client.get(path15`/vector_stores/${vector_store_id}/file_batches/${batchID}`, {
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Cancel a vector store file batch. This attempts to cancel the processing of
+ * files in this batch as soon as possible.
+ */
+ cancel(batchID, params, options2) {
+ const { vector_store_id } = params;
+ return this._client.post(path15`/vector_stores/${vector_store_id}/file_batches/${batchID}/cancel`, {
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Create a vector store batch and poll until all files have been processed.
+ */
+ async createAndPoll(vectorStoreId, body, options2) {
+ const batch = await this.create(vectorStoreId, body);
+ return await this.poll(vectorStoreId, batch.id, options2);
+ }
+ /**
+ * Returns a list of vector store files in a batch.
+ */
+ listFiles(batchID, params, options2) {
+ const { vector_store_id, ...query } = params;
+ return this._client.getAPIList(path15`/vector_stores/${vector_store_id}/file_batches/${batchID}/files`, CursorPage, {
+ query,
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Wait for the given file batch to be processed.
+ *
+ * Note: this will return even if one of the files failed to process, you need to
+ * check batch.file_counts.failed_count to handle this case.
+ */
+ async poll(vectorStoreID, batchID, options2) {
+ const headers = buildHeaders([
+ options2?.headers,
+ {
+ "X-Stainless-Poll-Helper": "true",
+ "X-Stainless-Custom-Poll-Interval": options2?.pollIntervalMs?.toString() ?? void 0
+ }
+ ]);
+ while (true) {
+ const { data: batch, response } = await this.retrieve(batchID, { vector_store_id: vectorStoreID }, {
+ ...options2,
+ headers
+ }).withResponse();
+ switch (batch.status) {
+ case "in_progress":
+ let sleepInterval = 5e3;
+ if (options2?.pollIntervalMs) {
+ sleepInterval = options2.pollIntervalMs;
+ } else {
+ const headerInterval = response.headers.get("openai-poll-after-ms");
+ if (headerInterval) {
+ const headerIntervalMs = parseInt(headerInterval);
+ if (!isNaN(headerIntervalMs)) {
+ sleepInterval = headerIntervalMs;
+ }
+ }
+ }
+ await sleep(sleepInterval);
+ break;
+ case "failed":
+ case "cancelled":
+ case "completed":
+ return batch;
+ }
+ }
+ }
+ /**
+ * Uploads the given files concurrently and then creates a vector store file batch.
+ *
+ * The concurrency limit is configurable using the `maxConcurrency` parameter.
+ */
+ async uploadAndPoll(vectorStoreId, { files, fileIds = [] }, options2) {
+ if (files == null || files.length == 0) {
+ throw new Error(`No \`files\` provided to process. If you've already uploaded files you should use \`.createAndPoll()\` instead`);
+ }
+ const configuredConcurrency = options2?.maxConcurrency ?? 5;
+ const concurrencyLimit = Math.min(configuredConcurrency, files.length);
+ const client = this._client;
+ const fileIterator = files.values();
+ const allFileIds = [...fileIds];
+ async function processFiles(iterator) {
+ for (let item of iterator) {
+ const fileObj = await client.files.create({ file: item, purpose: "assistants" }, options2);
+ allFileIds.push(fileObj.id);
+ }
+ }
+ __name(processFiles, "processFiles");
+ const workers = Array(concurrencyLimit).fill(fileIterator).map(processFiles);
+ await allSettledWithThrow(workers);
+ return await this.createAndPoll(vectorStoreId, {
+ file_ids: allFileIds
+ });
+ }
+};
+
+// node_modules/openai/resources/vector-stores/files.mjs
+init_esbuild_shims();
+var Files3 = class extends APIResource {
+ static {
+ __name(this, "Files");
+ }
+ /**
+ * Create a vector store file by attaching a
+ * [File](https://platform.openai.com/docs/api-reference/files) to a
+ * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object).
+ */
+ create(vectorStoreID, body, options2) {
+ return this._client.post(path15`/vector_stores/${vectorStoreID}/files`, {
+ body,
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Retrieves a vector store file.
+ */
+ retrieve(fileID, params, options2) {
+ const { vector_store_id } = params;
+ return this._client.get(path15`/vector_stores/${vector_store_id}/files/${fileID}`, {
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Update attributes on a vector store file.
+ */
+ update(fileID, params, options2) {
+ const { vector_store_id, ...body } = params;
+ return this._client.post(path15`/vector_stores/${vector_store_id}/files/${fileID}`, {
+ body,
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Returns a list of vector store files.
+ */
+ list(vectorStoreID, query = {}, options2) {
+ return this._client.getAPIList(path15`/vector_stores/${vectorStoreID}/files`, CursorPage, {
+ query,
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Delete a vector store file. This will remove the file from the vector store but
+ * the file itself will not be deleted. To delete the file, use the
+ * [delete file](https://platform.openai.com/docs/api-reference/files/delete)
+ * endpoint.
+ */
+ delete(fileID, params, options2) {
+ const { vector_store_id } = params;
+ return this._client.delete(path15`/vector_stores/${vector_store_id}/files/${fileID}`, {
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Attach a file to the given vector store and wait for it to be processed.
+ */
+ async createAndPoll(vectorStoreId, body, options2) {
+ const file2 = await this.create(vectorStoreId, body, options2);
+ return await this.poll(vectorStoreId, file2.id, options2);
+ }
+ /**
+ * Wait for the vector store file to finish processing.
+ *
+ * Note: this will return even if the file failed to process, you need to check
+ * file.last_error and file.status to handle these cases
+ */
+ async poll(vectorStoreID, fileID, options2) {
+ const headers = buildHeaders([
+ options2?.headers,
+ {
+ "X-Stainless-Poll-Helper": "true",
+ "X-Stainless-Custom-Poll-Interval": options2?.pollIntervalMs?.toString() ?? void 0
+ }
+ ]);
+ while (true) {
+ const fileResponse = await this.retrieve(fileID, {
+ vector_store_id: vectorStoreID
+ }, { ...options2, headers }).withResponse();
+ const file2 = fileResponse.data;
+ switch (file2.status) {
+ case "in_progress":
+ let sleepInterval = 5e3;
+ if (options2?.pollIntervalMs) {
+ sleepInterval = options2.pollIntervalMs;
+ } else {
+ const headerInterval = fileResponse.response.headers.get("openai-poll-after-ms");
+ if (headerInterval) {
+ const headerIntervalMs = parseInt(headerInterval);
+ if (!isNaN(headerIntervalMs)) {
+ sleepInterval = headerIntervalMs;
+ }
+ }
+ }
+ await sleep(sleepInterval);
+ break;
+ case "failed":
+ case "completed":
+ return file2;
+ }
+ }
+ }
+ /**
+ * Upload a file to the `files` API and then attach it to the given vector store.
+ *
+ * Note the file will be asynchronously processed (you can use the alternative
+ * polling helper method to wait for processing to complete).
+ */
+ async upload(vectorStoreId, file2, options2) {
+ const fileInfo = await this._client.files.create({ file: file2, purpose: "assistants" }, options2);
+ return this.create(vectorStoreId, { file_id: fileInfo.id }, options2);
+ }
+ /**
+ * Add a file to a vector store and poll until processing is complete.
+ */
+ async uploadAndPoll(vectorStoreId, file2, options2) {
+ const fileInfo = await this.upload(vectorStoreId, file2, options2);
+ return await this.poll(vectorStoreId, fileInfo.id, options2);
+ }
+ /**
+ * Retrieve the parsed contents of a vector store file.
+ */
+ content(fileID, params, options2) {
+ const { vector_store_id } = params;
+ return this._client.getAPIList(path15`/vector_stores/${vector_store_id}/files/${fileID}/content`, Page, {
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+};
+
+// node_modules/openai/resources/vector-stores/vector-stores.mjs
+var VectorStores = class extends APIResource {
+ static {
+ __name(this, "VectorStores");
+ }
+ constructor() {
+ super(...arguments);
+ this.files = new Files3(this._client);
+ this.fileBatches = new FileBatches(this._client);
+ }
+ /**
+ * Create a vector store.
+ */
+ create(body, options2) {
+ return this._client.post("/vector_stores", {
+ body,
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Retrieves a vector store.
+ */
+ retrieve(vectorStoreID, options2) {
+ return this._client.get(path15`/vector_stores/${vectorStoreID}`, {
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Modifies a vector store.
+ */
+ update(vectorStoreID, body, options2) {
+ return this._client.post(path15`/vector_stores/${vectorStoreID}`, {
+ body,
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Returns a list of vector stores.
+ */
+ list(query = {}, options2) {
+ return this._client.getAPIList("/vector_stores", CursorPage, {
+ query,
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Delete a vector store.
+ */
+ delete(vectorStoreID, options2) {
+ return this._client.delete(path15`/vector_stores/${vectorStoreID}`, {
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Search a vector store for relevant chunks based on a query and file attributes
+ * filter.
+ */
+ search(vectorStoreID, body, options2) {
+ return this._client.getAPIList(path15`/vector_stores/${vectorStoreID}/search`, Page, {
+ body,
+ method: "post",
+ ...options2,
+ headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options2?.headers]),
+ __security: { bearerAuth: true }
+ });
+ }
+};
+VectorStores.Files = Files3;
+VectorStores.FileBatches = FileBatches;
+
+// node_modules/openai/resources/videos.mjs
+init_esbuild_shims();
+var Videos = class extends APIResource {
+ static {
+ __name(this, "Videos");
+ }
+ /**
+ * Create a new video generation job from a prompt and optional reference assets.
+ */
+ create(body, options2) {
+ return this._client.post("/videos", multipartFormRequestOptions({ body, ...options2, __security: { bearerAuth: true } }, this._client));
+ }
+ /**
+ * Fetch the latest metadata for a generated video.
+ */
+ retrieve(videoID, options2) {
+ return this._client.get(path15`/videos/${videoID}`, { ...options2, __security: { bearerAuth: true } });
+ }
+ /**
+ * List recently generated videos for the current project.
+ */
+ list(query = {}, options2) {
+ return this._client.getAPIList("/videos", ConversationCursorPage, {
+ query,
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Permanently delete a completed or failed video and its stored assets.
+ */
+ delete(videoID, options2) {
+ return this._client.delete(path15`/videos/${videoID}`, { ...options2, __security: { bearerAuth: true } });
+ }
+ /**
+ * Create a character from an uploaded video.
+ */
+ createCharacter(body, options2) {
+ return this._client.post("/videos/characters", multipartFormRequestOptions({ body, ...options2, __security: { bearerAuth: true } }, this._client));
+ }
+ /**
+ * Download the generated video bytes or a derived preview asset.
+ *
+ * Streams the rendered video content for the specified video job.
+ */
+ downloadContent(videoID, query = {}, options2) {
+ return this._client.get(path15`/videos/${videoID}/content`, {
+ query,
+ ...options2,
+ headers: buildHeaders([{ Accept: "application/binary" }, options2?.headers]),
+ __security: { bearerAuth: true },
+ __binaryResponse: true
+ });
+ }
+ /**
+ * Create a new video generation job by editing a source video or existing
+ * generated video.
+ */
+ edit(body, options2) {
+ return this._client.post("/videos/edits", multipartFormRequestOptions({ body, ...options2, __security: { bearerAuth: true } }, this._client));
+ }
+ /**
+ * Create an extension of a completed video.
+ */
+ extend(body, options2) {
+ return this._client.post("/videos/extensions", multipartFormRequestOptions({ body, ...options2, __security: { bearerAuth: true } }, this._client));
+ }
+ /**
+ * Fetch a character.
+ */
+ getCharacter(characterID, options2) {
+ return this._client.get(path15`/videos/characters/${characterID}`, {
+ ...options2,
+ __security: { bearerAuth: true }
+ });
+ }
+ /**
+ * Create a remix of a completed video using a refreshed prompt.
+ */
+ remix(videoID, body, options2) {
+ return this._client.post(path15`/videos/${videoID}/remix`, maybeMultipartFormRequestOptions({ body, ...options2, __security: { bearerAuth: true } }, this._client));
+ }
+};
+
+// node_modules/openai/resources/webhooks.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/webhooks/index.mjs
+init_esbuild_shims();
+
+// node_modules/openai/resources/webhooks/webhooks.mjs
+init_esbuild_shims();
+var _Webhooks_instances;
+var _Webhooks_validateSecret;
+var _Webhooks_getRequiredHeader;
+var Webhooks = class extends APIResource {
+ static {
+ __name(this, "Webhooks");
+ }
+ constructor() {
+ super(...arguments);
+ _Webhooks_instances.add(this);
+ }
+ /**
+ * Validates that the given payload was sent by OpenAI and parses the payload.
+ */
+ async unwrap(payload, headers, secret = this._client.webhookSecret, tolerance = 300) {
+ await this.verifySignature(payload, headers, secret, tolerance);
+ return JSON.parse(payload);
+ }
+ /**
+ * Validates whether or not the webhook payload was sent by OpenAI.
+ *
+ * An error will be raised if the webhook payload was not sent by OpenAI.
+ *
+ * @param payload - The webhook payload
+ * @param headers - The webhook headers
+ * @param secret - The webhook secret (optional, will use client secret if not provided)
+ * @param tolerance - Maximum age of the webhook in seconds (default: 300 = 5 minutes)
+ */
+ async verifySignature(payload, headers, secret = this._client.webhookSecret, tolerance = 300) {
+ if (typeof crypto === "undefined" || typeof crypto.subtle.importKey !== "function" || typeof crypto.subtle.verify !== "function") {
+ throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");
+ }
+ __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_validateSecret).call(this, secret);
+ const headersObj = buildHeaders([headers]).values;
+ const signatureHeader = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-signature");
+ const timestamp = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-timestamp");
+ const webhookId = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-id");
+ const timestampSeconds = parseInt(timestamp, 10);
+ if (isNaN(timestampSeconds)) {
+ throw new InvalidWebhookSignatureError("Invalid webhook timestamp format");
+ }
+ const nowSeconds = Math.floor(Date.now() / 1e3);
+ if (nowSeconds - timestampSeconds > tolerance) {
+ throw new InvalidWebhookSignatureError("Webhook timestamp is too old");
+ }
+ if (timestampSeconds > nowSeconds + tolerance) {
+ throw new InvalidWebhookSignatureError("Webhook timestamp is too new");
+ }
+ const signatures = signatureHeader.split(" ").map((part) => part.startsWith("v1,") ? part.substring(3) : part);
+ const decodedSecret = secret.startsWith("whsec_") ? Buffer.from(secret.replace("whsec_", ""), "base64") : Buffer.from(secret, "utf-8");
+ const signedPayload = webhookId ? `${webhookId}.${timestamp}.${payload}` : `${timestamp}.${payload}`;
+ const key = await crypto.subtle.importKey("raw", decodedSecret, { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
+ for (const signature of signatures) {
+ try {
+ const signatureBytes = Buffer.from(signature, "base64");
+ const isValid = await crypto.subtle.verify("HMAC", key, signatureBytes, new TextEncoder().encode(signedPayload));
+ if (isValid) {
+ return;
+ }
+ } catch {
+ continue;
+ }
+ }
+ throw new InvalidWebhookSignatureError("The given webhook signature does not match the expected signature");
+ }
+};
+_Webhooks_instances = /* @__PURE__ */ new WeakSet(), _Webhooks_validateSecret = /* @__PURE__ */ __name(function _Webhooks_validateSecret2(secret) {
+ if (typeof secret !== "string" || secret.length === 0) {
+ throw new Error(`The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function`);
+ }
+}, "_Webhooks_validateSecret"), _Webhooks_getRequiredHeader = /* @__PURE__ */ __name(function _Webhooks_getRequiredHeader2(headers, name) {
+ if (!headers) {
+ throw new Error(`Headers are required`);
+ }
+ const value = headers.get(name);
+ if (value === null || value === void 0) {
+ throw new Error(`Missing required header: ${name}`);
+ }
+ return value;
+}, "_Webhooks_getRequiredHeader");
+
+// node_modules/openai/client.mjs
+var _OpenAI_instances;
+var _a4;
+var _OpenAI_encoder;
+var _OpenAI_baseURLOverridden;
+var WORKLOAD_IDENTITY_API_KEY_PLACEHOLDER = "workload-identity-auth";
+var OpenAI = class {
+ static {
+ __name(this, "OpenAI");
+ }
+ /**
+ * API Client for interfacing with the OpenAI API.
+ *
+ * @param {string | null | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? null]
+ * @param {string | null | undefined} [opts.adminAPIKey=process.env['OPENAI_ADMIN_KEY'] ?? null]
+ * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null]
+ * @param {string | null | undefined} [opts.project=process.env['OPENAI_PROJECT_ID'] ?? null]
+ * @param {string | null | undefined} [opts.webhookSecret=process.env['OPENAI_WEBHOOK_SECRET'] ?? null]
+ * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API.
+ * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
+ * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
+ * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
+ * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
+ * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
+ * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API.
+ * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.
+ */
+ constructor({ baseURL = readEnv("OPENAI_BASE_URL"), apiKey = readEnv("OPENAI_API_KEY") ?? null, adminAPIKey = readEnv("OPENAI_ADMIN_KEY") ?? null, organization = readEnv("OPENAI_ORG_ID") ?? null, project = readEnv("OPENAI_PROJECT_ID") ?? null, webhookSecret = readEnv("OPENAI_WEBHOOK_SECRET") ?? null, workloadIdentity, ...opts } = {}) {
+ _OpenAI_instances.add(this);
+ _OpenAI_encoder.set(this, void 0);
+ this.completions = new Completions2(this);
+ this.chat = new Chat(this);
+ this.embeddings = new Embeddings(this);
+ this.files = new Files2(this);
+ this.images = new Images(this);
+ this.audio = new Audio(this);
+ this.moderations = new Moderations(this);
+ this.models = new Models(this);
+ this.fineTuning = new FineTuning(this);
+ this.graders = new Graders2(this);
+ this.vectorStores = new VectorStores(this);
+ this.webhooks = new Webhooks(this);
+ this.beta = new Beta(this);
+ this.batches = new Batches(this);
+ this.uploads = new Uploads(this);
+ this.admin = new Admin(this);
+ this.responses = new Responses(this);
+ this.realtime = new Realtime2(this);
+ this.conversations = new Conversations(this);
+ this.evals = new Evals(this);
+ this.containers = new Containers(this);
+ this.skills = new Skills(this);
+ this.videos = new Videos(this);
+ const options2 = {
+ apiKey,
+ adminAPIKey,
+ organization,
+ project,
+ webhookSecret,
+ workloadIdentity,
+ ...opts,
+ baseURL: baseURL || `https://api.openai.com/v1`
+ };
+ if (apiKey && workloadIdentity) {
+ throw new OpenAIError("The `apiKey` and `workloadIdentity` options are mutually exclusive");
+ }
+ if (!apiKey && !adminAPIKey && !workloadIdentity) {
+ throw new OpenAIError("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");
+ }
+ if (!options2.dangerouslyAllowBrowser && isRunningInBrowser()) {
+ throw new OpenAIError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");
+ }
+ this.baseURL = options2.baseURL;
+ this.timeout = options2.timeout ?? _a4.DEFAULT_TIMEOUT;
+ this.logger = options2.logger ?? console;
+ const defaultLogLevel = "warn";
+ this.logLevel = defaultLogLevel;
+ this.logLevel = parseLogLevel(options2.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel(readEnv("OPENAI_LOG"), "process.env['OPENAI_LOG']", this) ?? defaultLogLevel;
+ this.fetchOptions = options2.fetchOptions;
+ this.maxRetries = options2.maxRetries ?? 2;
+ this.fetch = options2.fetch ?? getDefaultFetch();
+ __classPrivateFieldSet(this, _OpenAI_encoder, FallbackEncoder, "f");
+ const customHeadersEnv = readEnv("OPENAI_CUSTOM_HEADERS");
+ if (customHeadersEnv) {
+ const parsed = {};
+ for (const line of customHeadersEnv.split("\n")) {
+ const colon = line.indexOf(":");
+ if (colon >= 0) {
+ parsed[line.substring(0, colon).trim()] = line.substring(colon + 1).trim();
+ }
+ }
+ options2.defaultHeaders = buildHeaders([parsed, options2.defaultHeaders]);
+ }
+ this._options = options2;
+ if (workloadIdentity) {
+ this._workloadIdentityAuth = new WorkloadIdentityAuth(workloadIdentity, this.fetch);
+ }
+ this.apiKey = typeof apiKey === "string" ? apiKey : null;
+ this.adminAPIKey = adminAPIKey;
+ this.organization = organization;
+ this.project = project;
+ this.webhookSecret = webhookSecret;
+ }
+ /**
+ * Create a new client instance re-using the same options given to the current client with optional overriding.
+ */
+ withOptions(options2) {
+ const client = new this.constructor({
+ ...this._options,
+ baseURL: this.baseURL,
+ maxRetries: this.maxRetries,
+ timeout: this.timeout,
+ logger: this.logger,
+ logLevel: this.logLevel,
+ fetch: this.fetch,
+ fetchOptions: this.fetchOptions,
+ apiKey: this._options.apiKey,
+ adminAPIKey: this.adminAPIKey,
+ workloadIdentity: this._options.workloadIdentity,
+ organization: this.organization,
+ project: this.project,
+ webhookSecret: this.webhookSecret,
+ ...options2
+ });
+ return client;
+ }
+ defaultQuery() {
+ return this._options.defaultQuery;
+ }
+ validateHeaders({ values, nulls }, schemes = {
+ bearerAuth: true,
+ adminAPIKeyAuth: true
+ }) {
+ if (values.get("authorization") || values.get("api-key")) {
+ return;
+ }
+ if (nulls.has("authorization") || nulls.has("api-key")) {
+ return;
+ }
+ if (this._workloadIdentityAuth && schemes.bearerAuth) {
+ return;
+ }
+ throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted');
+ }
+ async authHeaders(opts, schemes = {
+ bearerAuth: true,
+ adminAPIKeyAuth: true
+ }) {
+ return buildHeaders([
+ schemes.bearerAuth ? await this.bearerAuth(opts) : null,
+ schemes.adminAPIKeyAuth ? await this.adminAPIKeyAuth(opts) : null
+ ]);
+ }
+ async bearerAuth(opts) {
+ if (this._workloadIdentityAuth) {
+ return buildHeaders([{ Authorization: `Bearer ${await this._workloadIdentityAuth.getToken()}` }]);
+ }
+ if (this.apiKey == null) {
+ return void 0;
+ }
+ return buildHeaders([{ Authorization: `Bearer ${this.apiKey}` }]);
+ }
+ async adminAPIKeyAuth(opts) {
+ if (this.adminAPIKey == null) {
+ return void 0;
+ }
+ return buildHeaders([{ Authorization: `Bearer ${this.adminAPIKey}` }]);
+ }
+ stringifyQuery(query) {
+ return stringifyQuery(query);
+ }
+ getUserAgent() {
+ return `${this.constructor.name}/JS ${VERSION}`;
+ }
+ defaultIdempotencyKey() {
+ return `stainless-node-retry-${uuid42()}`;
+ }
+ makeStatusError(status, error51, message, headers) {
+ return APIError.generate(status, error51, message, headers);
+ }
+ async _callApiKey() {
+ const apiKey = this._options.apiKey;
+ if (typeof apiKey !== "function")
+ return false;
+ let token;
+ try {
+ token = await apiKey();
+ } catch (err) {
+ if (err instanceof OpenAIError)
+ throw err;
+ throw new OpenAIError(
+ `Failed to get token from 'apiKey' function: ${err.message}`,
+ // @ts-ignore
+ { cause: err }
+ );
+ }
+ if (typeof token !== "string" || !token) {
+ throw new OpenAIError(`Expected 'apiKey' function argument to return a string but it returned ${token}`);
+ }
+ this.apiKey = token;
+ return true;
+ }
+ buildURL(path27, query, defaultBaseURL) {
+ const baseURL = !__classPrivateFieldGet(this, _OpenAI_instances, "m", _OpenAI_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL;
+ const url2 = isAbsoluteURL(path27) ? new URL(path27) : new URL(baseURL + (baseURL.endsWith("/") && path27.startsWith("/") ? path27.slice(1) : path27));
+ const defaultQuery = this.defaultQuery();
+ const pathQuery = Object.fromEntries(url2.searchParams);
+ if (!isEmptyObj(defaultQuery) || !isEmptyObj(pathQuery)) {
+ query = { ...pathQuery, ...defaultQuery, ...query };
+ }
+ if (typeof query === "object" && query && !Array.isArray(query)) {
+ url2.search = this.stringifyQuery(query);
+ }
+ return url2.toString();
+ }
+ /**
+ * Used as a callback for mutating the given `FinalRequestOptions` object.
+ */
+ async prepareOptions(options2) {
+ const security = options2.__security ?? { bearerAuth: true };
+ if (security.bearerAuth) {
+ await this._callApiKey();
+ }
+ }
+ /**
+ * Used as a callback for mutating the given `RequestInit` object.
+ *
+ * This is useful for cases where you want to add certain headers based off of
+ * the request properties, e.g. `method` or `url`.
+ */
+ async prepareRequest(request, { url: url2, options: options2 }) {
+ }
+ get(path27, opts) {
+ return this.methodRequest("get", path27, opts);
+ }
+ post(path27, opts) {
+ return this.methodRequest("post", path27, opts);
+ }
+ patch(path27, opts) {
+ return this.methodRequest("patch", path27, opts);
+ }
+ put(path27, opts) {
+ return this.methodRequest("put", path27, opts);
+ }
+ delete(path27, opts) {
+ return this.methodRequest("delete", path27, opts);
+ }
+ methodRequest(method, path27, opts) {
+ return this.request(Promise.resolve(opts).then((opts2) => {
+ return { method, path: path27, ...opts2 };
+ }));
+ }
+ request(options2, remainingRetries = null) {
+ return new APIPromise(this, this.makeRequest(options2, remainingRetries, void 0));
+ }
+ async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
+ const options2 = await optionsInput;
+ const maxRetries = options2.maxRetries ?? this.maxRetries;
+ if (retriesRemaining == null) {
+ retriesRemaining = maxRetries;
+ }
+ await this.prepareOptions(options2);
+ const { req, url: url2, timeout } = await this.buildRequest(options2, {
+ retryCount: maxRetries - retriesRemaining
+ });
+ await this.prepareRequest(req, { url: url2, options: options2 });
+ const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0");
+ const retryLogStr = retryOfRequestLogID === void 0 ? "" : `, retryOf: ${retryOfRequestLogID}`;
+ const startTime = Date.now();
+ loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
+ retryOfRequestLogID,
+ method: options2.method,
+ url: url2,
+ options: options2,
+ headers: req.headers
+ }));
+ if (options2.signal?.aborted) {
+ throw new APIUserAbortError();
+ }
+ const security = options2.__security ?? { bearerAuth: true };
+ const controller = new AbortController();
+ const response = await this.fetchWithAuth(url2, req, timeout, controller, security).catch(castToError);
+ const headersTime = Date.now();
+ if (response instanceof globalThis.Error) {
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
+ if (options2.signal?.aborted) {
+ throw new APIUserAbortError();
+ }
+ const isTimeout = isAbortError(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : ""));
+ if (retriesRemaining) {
+ loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`);
+ loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails({
+ retryOfRequestLogID,
+ url: url2,
+ durationMs: headersTime - startTime,
+ message: response.message
+ }));
+ return this.retryRequest(options2, retriesRemaining, retryOfRequestLogID ?? requestLogID);
+ }
+ loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`);
+ loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails({
+ retryOfRequestLogID,
+ url: url2,
+ durationMs: headersTime - startTime,
+ message: response.message
+ }));
+ if (response instanceof OAuthError || response instanceof SubjectTokenProviderError) {
+ throw response;
+ }
+ if (isTimeout) {
+ throw new APIConnectionTimeoutError();
+ }
+ throw new APIConnectionError({
+ message: getConnectionErrorMessage(response),
+ cause: response
+ });
+ }
+ const specialHeaders = [...response.headers.entries()].filter(([name]) => name === "x-request-id").map(([name, value]) => ", " + name + ": " + JSON.stringify(value)).join("");
+ const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url2} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`;
+ if (!response.ok) {
+ if (response.status === 401 && this._workloadIdentityAuth && security.bearerAuth && !options2.__metadata?.["hasStreamingBody"] && !options2.__metadata?.["workloadIdentityTokenRefreshed"]) {
+ await CancelReadableStream(response.body);
+ this._workloadIdentityAuth.invalidateToken();
+ return this.makeRequest({
+ ...options2,
+ __metadata: {
+ ...options2.__metadata,
+ workloadIdentityTokenRefreshed: true
+ }
+ }, retriesRemaining, retryOfRequestLogID ?? requestLogID);
+ }
+ const shouldRetry = await this.shouldRetry(response);
+ if (retriesRemaining && shouldRetry) {
+ const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`;
+ await CancelReadableStream(response.body);
+ loggerFor(this).info(`${responseInfo} - ${retryMessage2}`);
+ loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails({
+ retryOfRequestLogID,
+ url: response.url,
+ status: response.status,
+ headers: response.headers,
+ durationMs: headersTime - startTime
+ }));
+ return this.retryRequest(options2, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
+ }
+ const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
+ loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
+ const errText = await response.text().catch((err2) => castToError(err2).message);
+ const errJSON = safeJSON(errText);
+ const errMessage = errJSON ? void 0 : errText;
+ loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
+ retryOfRequestLogID,
+ url: response.url,
+ status: response.status,
+ headers: response.headers,
+ message: errMessage,
+ durationMs: Date.now() - startTime
+ }));
+ const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
+ throw err;
+ }
+ loggerFor(this).info(responseInfo);
+ loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
+ retryOfRequestLogID,
+ url: response.url,
+ status: response.status,
+ headers: response.headers,
+ durationMs: headersTime - startTime
+ }));
+ return { response, options: options2, controller, requestLogID, retryOfRequestLogID, startTime };
+ }
+ getAPIList(path27, Page2, opts) {
+ return this.requestAPIList(Page2, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path27, ...opts2 })) : { method: "get", path: path27, ...opts });
+ }
+ requestAPIList(Page2, options2) {
+ const request = this.makeRequest(options2, null, void 0);
+ return new PagePromise(this, request, Page2);
+ }
+ async fetchWithAuth(url2, init, timeout, controller, schemes = {
+ bearerAuth: true,
+ adminAPIKeyAuth: true
+ }) {
+ if (this._workloadIdentityAuth && schemes.bearerAuth) {
+ const headers = init.headers;
+ const authHeader = headers.get("Authorization");
+ if (!authHeader || authHeader === `Bearer ${WORKLOAD_IDENTITY_API_KEY_PLACEHOLDER}`) {
+ const token = await this._workloadIdentityAuth.getToken();
+ headers.set("Authorization", `Bearer ${token}`);
+ }
+ }
+ const response = await this.fetchWithTimeout(url2, init, timeout, controller);
+ return response;
+ }
+ async fetchWithTimeout(url2, init, ms, controller) {
+ const { signal, method, ...options2 } = init || {};
+ const abort = this._makeAbort(controller);
+ if (signal)
+ signal.addEventListener("abort", abort, { once: true });
+ const timeout = setTimeout(abort, ms);
+ const isReadableBody = globalThis.ReadableStream && options2.body instanceof globalThis.ReadableStream || typeof options2.body === "object" && options2.body !== null && Symbol.asyncIterator in options2.body;
+ const fetchOptions = {
+ signal: controller.signal,
+ ...isReadableBody ? { duplex: "half" } : {},
+ method: "GET",
+ ...options2
+ };
+ if (method) {
+ fetchOptions.method = method.toUpperCase();
+ }
+ try {
+ return await this.fetch.call(void 0, url2, fetchOptions);
+ } finally {
+ clearTimeout(timeout);
+ }
+ }
+ async shouldRetry(response) {
+ const shouldRetryHeader = response.headers.get("x-should-retry");
+ if (shouldRetryHeader === "true")
+ return true;
+ if (shouldRetryHeader === "false")
+ return false;
+ if (response.status === 408)
+ return true;
+ if (response.status === 409)
+ return true;
+ if (response.status === 429)
+ return true;
+ if (response.status >= 500)
+ return true;
+ return false;
+ }
+ async retryRequest(options2, retriesRemaining, requestLogID, responseHeaders) {
+ let timeoutMillis;
+ const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms");
+ if (retryAfterMillisHeader) {
+ const timeoutMs = parseFloat(retryAfterMillisHeader);
+ if (!Number.isNaN(timeoutMs)) {
+ timeoutMillis = timeoutMs;
+ }
+ }
+ const retryAfterHeader = responseHeaders?.get("retry-after");
+ if (retryAfterHeader && !timeoutMillis) {
+ const timeoutSeconds = parseFloat(retryAfterHeader);
+ if (!Number.isNaN(timeoutSeconds)) {
+ timeoutMillis = timeoutSeconds * 1e3;
+ } else {
+ timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
+ }
+ }
+ if (timeoutMillis === void 0) {
+ const maxRetries = options2.maxRetries ?? this.maxRetries;
+ timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
+ }
+ await sleep(timeoutMillis);
+ return this.makeRequest(options2, retriesRemaining - 1, requestLogID);
+ }
+ calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
+ const initialRetryDelay = 0.5;
+ const maxRetryDelay = 8;
+ const numRetries = maxRetries - retriesRemaining;
+ const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
+ const jitter = 1 - Math.random() * 0.25;
+ return sleepSeconds * jitter * 1e3;
+ }
+ async buildRequest(inputOptions, { retryCount = 0 } = {}) {
+ const options2 = { ...inputOptions };
+ const { method, path: path27, query, defaultBaseURL } = options2;
+ const url2 = this.buildURL(path27, query, defaultBaseURL);
+ if ("timeout" in options2)
+ validatePositiveInteger("timeout", options2.timeout);
+ options2.timeout = options2.timeout ?? this.timeout;
+ const { bodyHeaders, body, isStreamingBody } = this.buildBody({ options: options2 });
+ if (isStreamingBody) {
+ inputOptions.__metadata = {
+ ...inputOptions.__metadata,
+ hasStreamingBody: true
+ };
+ }
+ const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
+ const req = {
+ method,
+ headers: reqHeaders,
+ ...options2.signal && { signal: options2.signal },
+ ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" },
+ ...body && { body },
+ ...this.fetchOptions ?? {},
+ ...options2.fetchOptions ?? {}
+ };
+ return { req, url: url2, timeout: options2.timeout };
+ }
+ async buildHeaders({ options: options2, method, bodyHeaders, retryCount }) {
+ let idempotencyHeaders = {};
+ if (this.idempotencyHeader && method !== "get") {
+ if (!options2.idempotencyKey)
+ options2.idempotencyKey = this.defaultIdempotencyKey();
+ idempotencyHeaders[this.idempotencyHeader] = options2.idempotencyKey;
+ }
+ const headers = buildHeaders([
+ idempotencyHeaders,
+ {
+ Accept: "application/json",
+ "User-Agent": this.getUserAgent(),
+ "X-Stainless-Retry-Count": String(retryCount),
+ ...options2.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options2.timeout / 1e3)) } : {},
+ ...getPlatformHeaders(),
+ "OpenAI-Organization": this.organization,
+ "OpenAI-Project": this.project
+ },
+ await this.authHeaders(options2, options2.__security ?? { bearerAuth: true }),
+ this._options.defaultHeaders,
+ bodyHeaders,
+ options2.headers
+ ]);
+ this.validateHeaders(headers, options2.__security ?? { bearerAuth: true });
+ return headers.values;
+ }
+ _makeAbort(controller) {
+ return () => controller.abort();
+ }
+ buildBody({ options: { body, headers: rawHeaders } }) {
+ if (!body) {
+ return { bodyHeaders: void 0, body: void 0, isStreamingBody: false };
+ }
+ const headers = buildHeaders([rawHeaders]);
+ const isReadableStream = typeof globalThis.ReadableStream !== "undefined" && body instanceof globalThis.ReadableStream;
+ const isRetryableBody = !isReadableStream && (typeof body === "string" || body instanceof ArrayBuffer || ArrayBuffer.isView(body) || typeof globalThis.Blob !== "undefined" && body instanceof globalThis.Blob || body instanceof URLSearchParams || body instanceof FormData);
+ if (
+ // Pass raw type verbatim
+ ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && // Preserve legacy string encoding behavior for now
+ headers.values.has("content-type") || // `Blob` is superset of `File`
+ globalThis.Blob && body instanceof globalThis.Blob || // `FormData` -> `multipart/form-data`
+ body instanceof FormData || // `URLSearchParams` -> `application/x-www-form-urlencoded`
+ body instanceof URLSearchParams || // Send chunked stream (each chunk has own `length`)
+ isReadableStream
+ ) {
+ return { bodyHeaders: void 0, body, isStreamingBody: !isRetryableBody };
+ } else if (typeof body === "object" && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function")) {
+ return {
+ bodyHeaders: void 0,
+ body: ReadableStreamFrom(body),
+ isStreamingBody: true
+ };
+ } else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") {
+ return {
+ bodyHeaders: { "content-type": "application/x-www-form-urlencoded" },
+ body: this.stringifyQuery(body),
+ isStreamingBody: false
+ };
+ } else {
+ return { ...__classPrivateFieldGet(this, _OpenAI_encoder, "f").call(this, { body, headers }), isStreamingBody: false };
+ }
+ }
+};
+_a4 = OpenAI, _OpenAI_encoder = /* @__PURE__ */ new WeakMap(), _OpenAI_instances = /* @__PURE__ */ new WeakSet(), _OpenAI_baseURLOverridden = /* @__PURE__ */ __name(function _OpenAI_baseURLOverridden2() {
+ return this.baseURL !== "https://api.openai.com/v1";
+}, "_OpenAI_baseURLOverridden");
+OpenAI.OpenAI = _a4;
+OpenAI.DEFAULT_TIMEOUT = 6e5;
+OpenAI.OpenAIError = OpenAIError;
+OpenAI.APIError = APIError;
+OpenAI.APIConnectionError = APIConnectionError;
+OpenAI.APIConnectionTimeoutError = APIConnectionTimeoutError;
+OpenAI.APIUserAbortError = APIUserAbortError;
+OpenAI.NotFoundError = NotFoundError;
+OpenAI.ConflictError = ConflictError;
+OpenAI.RateLimitError = RateLimitError;
+OpenAI.BadRequestError = BadRequestError;
+OpenAI.AuthenticationError = AuthenticationError;
+OpenAI.InternalServerError = InternalServerError;
+OpenAI.PermissionDeniedError = PermissionDeniedError;
+OpenAI.UnprocessableEntityError = UnprocessableEntityError;
+OpenAI.InvalidWebhookSignatureError = InvalidWebhookSignatureError;
+OpenAI.toFile = toFile;
+OpenAI.Completions = Completions2;
+OpenAI.Chat = Chat;
+OpenAI.Embeddings = Embeddings;
+OpenAI.Files = Files2;
+OpenAI.Images = Images;
+OpenAI.Audio = Audio;
+OpenAI.Moderations = Moderations;
+OpenAI.Models = Models;
+OpenAI.FineTuning = FineTuning;
+OpenAI.Graders = Graders2;
+OpenAI.VectorStores = VectorStores;
+OpenAI.Webhooks = Webhooks;
+OpenAI.Beta = Beta;
+OpenAI.Batches = Batches;
+OpenAI.Uploads = Uploads;
+OpenAI.Admin = Admin;
+OpenAI.Responses = Responses;
+OpenAI.Realtime = Realtime2;
+OpenAI.Conversations = Conversations;
+OpenAI.Evals = Evals;
+OpenAI.Containers = Containers;
+OpenAI.Skills = Skills;
+OpenAI.Videos = Videos;
+function getConnectionErrorMessage(error51) {
+ if (isUndiciDispatcherVersionMismatchError(error51)) {
+ return `Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });`;
+ }
+ return void 0;
+}
+__name(getConnectionErrorMessage, "getConnectionErrorMessage");
+function isUndiciDispatcherVersionMismatchError(error51) {
+ let current = error51;
+ for (let i = 0; i < 8 && current && typeof current === "object"; i++) {
+ const err = current;
+ if (err.code === "UND_ERR_INVALID_ARG" && typeof err.message === "string" && err.message.includes("invalid onRequestStart method")) {
+ return true;
+ }
+ current = err.cause;
+ }
+ return false;
+}
+__name(isUndiciDispatcherVersionMismatchError, "isUndiciDispatcherVersionMismatchError");
+
+// node_modules/openai/azure.mjs
+init_esbuild_shims();
+
+// node_modules/openai/bedrock.mjs
+init_esbuild_shims();
+
+// packages/core/src/common/openai-client.ts
+var import_undici = __toESM(require_undici(), 1);
+var keepAliveAgent = new import_undici.Agent({ keepAliveTimeout: 18e4 });
+var cachedOpenAI = null;
+var cachedOpenAIKey = "";
+function createOpenAIClient(projectRoot = process.cwd()) {
+ const settings = resolveCurrentSettings(projectRoot);
+ if (!settings.apiKey) {
+ return {
+ client: null,
+ model: settings.model,
+ baseURL: settings.baseURL,
+ temperature: settings.temperature,
+ thinkingEnabled: settings.thinkingEnabled,
+ reasoningEffort: settings.reasoningEffort,
+ debugLogEnabled: settings.debugLogEnabled,
+ telemetryEnabled: settings.telemetryEnabled,
+ notify: settings.notify,
+ webSearchTool: settings.webSearchTool,
+ env: settings.env,
+ machineId: getMachineId()
+ };
+ }
+ const cacheKey = `${settings.apiKey}::${settings.baseURL}`;
+ if (cachedOpenAI && cachedOpenAIKey === cacheKey) {
+ return {
+ client: cachedOpenAI,
+ model: settings.model,
+ baseURL: settings.baseURL,
+ temperature: settings.temperature,
+ thinkingEnabled: settings.thinkingEnabled,
+ reasoningEffort: settings.reasoningEffort,
+ debugLogEnabled: settings.debugLogEnabled,
+ telemetryEnabled: settings.telemetryEnabled,
+ notify: settings.notify,
+ webSearchTool: settings.webSearchTool,
+ env: settings.env,
+ machineId: getMachineId()
+ };
+ }
+ cachedOpenAI = new OpenAI({
+ apiKey: settings.apiKey,
+ baseURL: settings.baseURL || void 0,
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ fetch: /* @__PURE__ */ __name((url2, init) => (0, import_undici.fetch)(url2, { ...init, dispatcher: keepAliveAgent }), "fetch")
+ });
+ cachedOpenAIKey = cacheKey;
+ void (async () => {
+ const ac = new AbortController();
+ const timer = setTimeout(() => ac.abort(), 3e3);
+ try {
+ await cachedOpenAI.models.list({ signal: ac.signal }).catch(() => {
+ });
+ } finally {
+ clearTimeout(timer);
+ }
+ })();
+ return {
+ client: cachedOpenAI,
+ model: settings.model,
+ baseURL: settings.baseURL,
+ temperature: settings.temperature,
+ thinkingEnabled: settings.thinkingEnabled,
+ reasoningEffort: settings.reasoningEffort,
+ debugLogEnabled: settings.debugLogEnabled,
+ telemetryEnabled: settings.telemetryEnabled,
+ notify: settings.notify,
+ webSearchTool: settings.webSearchTool,
+ env: settings.env,
+ machineId: getMachineId()
+ };
+}
+__name(createOpenAIClient, "createOpenAIClient");
+function getMachineId() {
+ try {
+ const idPath = path16.join(os10.homedir(), ".deepcode", "machine-id");
+ if (fs18.existsSync(idPath)) {
+ const raw = fs18.readFileSync(idPath, "utf8").trim();
+ if (raw) {
+ return raw;
+ }
+ }
+ const generated = `${os10.hostname()}-${Math.random().toString(36).slice(2)}-${Date.now()}`;
+ fs18.mkdirSync(path16.dirname(idPath), { recursive: true });
+ fs18.writeFileSync(idPath, generated, "utf8");
+ return generated;
+ } catch {
+ return void 0;
+ }
+}
+__name(getMachineId, "getMachineId");
+
+// packages/cli/src/common/update-check.ts
+init_esbuild_shims();
+var import_react59 = __toESM(require_react(), 1);
+import { spawn as spawn6 } from "child_process";
+import * as fs21 from "fs";
+import * as os15 from "os";
+import * as path22 from "path";
+
+// packages/cli/src/ui/index.ts
+init_esbuild_shims();
+
+// packages/cli/src/ui/components/ModelsDropdown/index.tsx
+init_esbuild_shims();
+var import_react35 = __toESM(require_react(), 1);
+
+// packages/cli/src/ui/components/DropdownMenu/index.tsx
+init_esbuild_shims();
+var import_react34 = __toESM(require_react(), 1);
+var import_jsx_runtime = __toESM(require_jsx_runtime(), 1);
+function calculateVisibleStart(activeIndex, totalItems, maxVisible) {
+ return Math.min(Math.max(0, activeIndex - Math.floor((maxVisible - 1) / 2)), Math.max(0, totalItems - maxVisible));
+}
+__name(calculateVisibleStart, "calculateVisibleStart");
+var DropdownMenu = import_react34.default.memo(/* @__PURE__ */ __name(function DropdownMenu2({
+ items,
+ activeIndex,
+ maxVisible = 8,
+ width,
+ title,
+ titleColor = "#229ac3",
+ activeColor = "cyanBright",
+ helpText,
+ emptyText = "No items found",
+ renderItem
+}) {
+ const visibleStart = calculateVisibleStart(activeIndex, items?.length, maxVisible);
+ const visibleItems = items?.slice(visibleStart, visibleStart + maxVisible);
+ const labelColumnWidth = (0, import_react34.useMemo)(() => {
+ if (visibleItems.length === 0) {
+ return 0;
+ }
+ const maxContentWidth = Math.max(
+ ...visibleItems.map((item) => {
+ let width2 = 2;
+ if (item.selected !== void 0) {
+ width2 += 2;
+ }
+ width2 += item.label.length;
+ if (item.statusIndicator) {
+ width2 += 2;
+ }
+ return width2;
+ })
+ );
+ const maxAllowed = Math.max(10, width - 2 >> 1);
+ return Math.min(maxContentWidth, maxAllowed);
+ }, [visibleItems, width]);
+ if (items?.length === 0) {
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, width, children: [
+ title ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { color: titleColor, bold: true, children: title }) : null,
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { dimColor: true, children: emptyText }),
+ helpText ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { dimColor: true, children: helpText }) : null
+ ] });
+ }
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, borderStyle: "round", borderDimColor: true, width, children: [
+ title ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
+ Box_default,
+ {
+ borderStyle: "single",
+ borderDimColor: true,
+ borderBottom: true,
+ borderRight: false,
+ borderTop: false,
+ borderLeft: false,
+ paddingX: 1,
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { color: titleColor, bold: true, children: title })
+ }
+ ) : null,
+ visibleStart > 0 ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Text, { dimColor: true, children: [
+ "\u2026 ",
+ visibleStart,
+ " above"
+ ] }) }) : null,
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Box_default, { flexDirection: "column", children: visibleItems.map((item, idx) => {
+ const actualIndex = visibleStart + idx;
+ const isActive = actualIndex === activeIndex;
+ if (renderItem) {
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react34.default.Fragment, { children: renderItem(item, isActive) }, item.key);
+ }
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Box_default, { flexGrow: 1, flexDirection: "row", gap: 2, paddingX: 1, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Box_default, { width: labelColumnWidth, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Text, { color: isActive ? activeColor : void 0, wrap: "truncate-end", children: [
+ isActive ? "> " : " ",
+ item.selected !== void 0 ? item.selected ? "\u25CF" : "\u25CB" : null,
+ " ",
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { bold: true, children: item.label }),
+ item.statusIndicator ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Text, { color: item.statusIndicator.color, children: [
+ " ",
+ item.statusIndicator.symbol
+ ] }) : null
+ ] }) }),
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Box_default, { flexGrow: 1, children: item.description ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { dimColor: true, children: `${item.description}` }) : null })
+ ] }, item.key);
+ }) }),
+ visibleStart + visibleItems.length < items.length ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Text, { dimColor: true, children: [
+ "\u2026 ",
+ items.length - visibleStart - visibleItems.length,
+ " more"
+ ] }) }) : null,
+ helpText ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
+ Box_default,
+ {
+ borderStyle: "single",
+ borderDimColor: true,
+ borderBottom: false,
+ borderRight: false,
+ borderTop: true,
+ borderLeft: false,
+ paddingX: 1,
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Text, { dimColor: true, children: helpText })
+ }
+ ) : null
+ ] });
+}, "DropdownMenu"));
+var DropdownMenu_default = DropdownMenu;
+
+// packages/cli/src/ui/components/ModelsDropdown/index.tsx
+var import_jsx_runtime2 = __toESM(require_jsx_runtime(), 1);
+var MODEL_COMMAND_MODELS = ["deepseek-v4-pro", "deepseek-v4-flash"];
+var MODEL_COMMAND_THINKING_OPTIONS = [
+ { label: "Thinking mode [max]", thinkingEnabled: true, reasoningEffort: "max" },
+ { label: "Thinking mode [high]", thinkingEnabled: true, reasoningEffort: "high" },
+ { label: "No thinking", thinkingEnabled: false }
+];
+function getThinkingOptionIndex(config2) {
+ const index = MODEL_COMMAND_THINKING_OPTIONS.findIndex((option) => {
+ if (!config2.thinkingEnabled) {
+ return !option.thinkingEnabled;
+ }
+ return option.thinkingEnabled && option.reasoningEffort === config2.reasoningEffort;
+ });
+ return index >= 0 ? index : 0;
+}
+__name(getThinkingOptionIndex, "getThinkingOptionIndex");
+var ModelsDropdown = /* @__PURE__ */ __name(({
+ open,
+ modelConfig,
+ width,
+ onClose,
+ onModelConfigChange,
+ onStatusMessage
+}) => {
+ const [step, setStep] = (0, import_react35.useState)(null);
+ const [activeIndex, setActiveIndex] = (0, import_react35.useState)(0);
+ const [pendingModel, setPendingModel] = (0, import_react35.useState)(null);
+ (0, import_react35.useEffect)(() => {
+ if (open) {
+ const currentIndex = MODEL_COMMAND_MODELS.findIndex((m) => m === modelConfig.model);
+ setPendingModel(null);
+ setStep("model");
+ setActiveIndex(currentIndex >= 0 ? currentIndex : 0);
+ } else {
+ setStep(null);
+ }
+ }, [open, modelConfig.model]);
+ (0, import_react35.useEffect)(() => {
+ if (!step) {
+ return;
+ }
+ const optionCount = step === "model" ? MODEL_COMMAND_MODELS.length : MODEL_COMMAND_THINKING_OPTIONS.length;
+ if (activeIndex >= optionCount) {
+ setActiveIndex(Math.max(0, optionCount - 1));
+ }
+ }, [activeIndex, step]);
+ function selectItem() {
+ if (step === "model") {
+ const model = MODEL_COMMAND_MODELS[activeIndex] ?? modelConfig.model;
+ setPendingModel(model);
+ setStep("thinking");
+ setActiveIndex(getThinkingOptionIndex(modelConfig));
+ return;
+ }
+ const option = MODEL_COMMAND_THINKING_OPTIONS[activeIndex] ?? MODEL_COMMAND_THINKING_OPTIONS[0];
+ const selection = {
+ model: pendingModel ?? modelConfig.model,
+ thinkingEnabled: option.thinkingEnabled,
+ reasoningEffort: option.reasoningEffort ?? modelConfig.reasoningEffort
+ };
+ onClose();
+ Promise.resolve(onModelConfigChange(selection)).then((message) => {
+ if (message) {
+ onStatusMessage?.(message);
+ }
+ }).catch((error51) => {
+ const msg = error51 instanceof Error ? error51.message : String(error51);
+ onStatusMessage?.(`Failed to update model settings: ${msg}`);
+ });
+ }
+ __name(selectItem, "selectItem");
+ use_input_default(
+ (input, key) => {
+ if (!step) {
+ return;
+ }
+ const optionCount = step === "model" ? MODEL_COMMAND_MODELS.length : MODEL_COMMAND_THINKING_OPTIONS.length;
+ if (key.upArrow) {
+ setActiveIndex((idx) => (idx - 1 + optionCount) % optionCount);
+ return;
+ }
+ if (key.downArrow) {
+ setActiveIndex((idx) => (idx + 1) % optionCount);
+ return;
+ }
+ if (input === " " && !key.ctrl && !key.meta || key.return && !key.shift && !key.meta) {
+ selectItem();
+ return;
+ }
+ if (key.tab || key.escape) {
+ onClose();
+ return;
+ }
+ },
+ { isActive: open }
+ );
+ if (!open || !step) {
+ return null;
+ }
+ const items = step === "model" ? MODEL_COMMAND_MODELS.map((model) => ({
+ key: model,
+ label: model,
+ description: model === modelConfig.model ? "current model" : "",
+ selected: model === (pendingModel ?? modelConfig.model)
+ })) : MODEL_COMMAND_THINKING_OPTIONS.map((option, i) => ({
+ key: option.label,
+ label: option.label,
+ description: option.thinkingEnabled ? `reasoningEffort: ${option.reasoningEffort}` : "thinking disabled",
+ selected: getThinkingOptionIndex(modelConfig) === i
+ }));
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
+ DropdownMenu_default,
+ {
+ width,
+ title: step === "model" ? "Select Model" : "Select Thinking Mode",
+ helpText: step === "model" ? "Space/Enter select model \xB7 Esc to cancel" : "Space/Enter apply \xB7 Esc to cancel",
+ items,
+ activeIndex,
+ activeColor: "#229ac3",
+ maxVisible: 6
+ }
+ );
+}, "ModelsDropdown");
+var ModelsDropdown_default = ModelsDropdown;
+
+// packages/cli/src/ui/utils/index.ts
+init_esbuild_shims();
+
+// packages/cli/node_modules/chalk/source/index.js
+init_esbuild_shims();
+
+// packages/cli/node_modules/chalk/source/vendor/ansi-styles/index.js
+init_esbuild_shims();
+var ANSI_BACKGROUND_OFFSET5 = 10;
+var wrapAnsi165 = /* @__PURE__ */ __name((offset = 0) => (code) => `\x1B[${code + offset}m`, "wrapAnsi16");
+var wrapAnsi2565 = /* @__PURE__ */ __name((offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`, "wrapAnsi256");
+var wrapAnsi16m5 = /* @__PURE__ */ __name((offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`, "wrapAnsi16m");
+var styles7 = {
+ 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],
+ overline: [53, 55],
+ 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],
+ gray: [90, 39],
+ // Alias of `blackBright`
+ grey: [90, 39],
+ // Alias of `blackBright`
+ 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],
+ bgGray: [100, 49],
+ // Alias of `bgBlackBright`
+ bgGrey: [100, 49],
+ // Alias of `bgBlackBright`
+ bgRedBright: [101, 49],
+ bgGreenBright: [102, 49],
+ bgYellowBright: [103, 49],
+ bgBlueBright: [104, 49],
+ bgMagentaBright: [105, 49],
+ bgCyanBright: [106, 49],
+ bgWhiteBright: [107, 49]
+ }
+};
+var modifierNames5 = Object.keys(styles7.modifier);
+var foregroundColorNames5 = Object.keys(styles7.color);
+var backgroundColorNames5 = Object.keys(styles7.bgColor);
+var colorNames5 = [...foregroundColorNames5, ...backgroundColorNames5];
+function assembleStyles5() {
+ const codes = /* @__PURE__ */ new Map();
+ for (const [groupName, group] of Object.entries(styles7)) {
+ for (const [styleName, style] of Object.entries(group)) {
+ styles7[styleName] = {
+ open: `\x1B[${style[0]}m`,
+ close: `\x1B[${style[1]}m`
+ };
+ group[styleName] = styles7[styleName];
+ codes.set(style[0], style[1]);
+ }
+ Object.defineProperty(styles7, groupName, {
+ value: group,
+ enumerable: false
+ });
+ }
+ Object.defineProperty(styles7, "codes", {
+ value: codes,
+ enumerable: false
+ });
+ styles7.color.close = "\x1B[39m";
+ styles7.bgColor.close = "\x1B[49m";
+ styles7.color.ansi = wrapAnsi165();
+ styles7.color.ansi256 = wrapAnsi2565();
+ styles7.color.ansi16m = wrapAnsi16m5();
+ styles7.bgColor.ansi = wrapAnsi165(ANSI_BACKGROUND_OFFSET5);
+ styles7.bgColor.ansi256 = wrapAnsi2565(ANSI_BACKGROUND_OFFSET5);
+ styles7.bgColor.ansi16m = wrapAnsi16m5(ANSI_BACKGROUND_OFFSET5);
+ Object.defineProperties(styles7, {
+ rgbToAnsi256: {
+ value(red, green, blue) {
+ if (red === green && green === blue) {
+ if (red < 8) {
+ return 16;
+ }
+ if (red > 248) {
+ return 231;
+ }
+ return Math.round((red - 8) / 247 * 24) + 232;
+ }
+ return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
+ },
+ enumerable: false
+ },
+ hexToRgb: {
+ value(hex3) {
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex3.toString(16));
+ if (!matches) {
+ return [0, 0, 0];
+ }
+ let [colorString] = matches;
+ if (colorString.length === 3) {
+ colorString = [...colorString].map((character) => character + character).join("");
+ }
+ const integer2 = Number.parseInt(colorString, 16);
+ return [
+ /* eslint-disable no-bitwise */
+ integer2 >> 16 & 255,
+ integer2 >> 8 & 255,
+ integer2 & 255
+ /* eslint-enable no-bitwise */
+ ];
+ },
+ enumerable: false
+ },
+ hexToAnsi256: {
+ value: /* @__PURE__ */ __name((hex3) => styles7.rgbToAnsi256(...styles7.hexToRgb(hex3)), "value"),
+ enumerable: false
+ },
+ ansi256ToAnsi: {
+ value(code) {
+ if (code < 8) {
+ return 30 + code;
+ }
+ if (code < 16) {
+ return 90 + (code - 8);
+ }
+ let red;
+ let green;
+ let blue;
+ if (code >= 232) {
+ red = ((code - 232) * 10 + 8) / 255;
+ green = red;
+ blue = red;
+ } else {
+ code -= 16;
+ const remainder = code % 36;
+ red = Math.floor(code / 36) / 5;
+ green = Math.floor(remainder / 6) / 5;
+ blue = remainder % 6 / 5;
+ }
+ const value = Math.max(red, green, blue) * 2;
+ if (value === 0) {
+ return 30;
+ }
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
+ if (value === 2) {
+ result += 60;
+ }
+ return result;
+ },
+ enumerable: false
+ },
+ rgbToAnsi: {
+ value: /* @__PURE__ */ __name((red, green, blue) => styles7.ansi256ToAnsi(styles7.rgbToAnsi256(red, green, blue)), "value"),
+ enumerable: false
+ },
+ hexToAnsi: {
+ value: /* @__PURE__ */ __name((hex3) => styles7.ansi256ToAnsi(styles7.hexToAnsi256(hex3)), "value"),
+ enumerable: false
+ }
+ });
+ return styles7;
+}
+__name(assembleStyles5, "assembleStyles");
+var ansiStyles5 = assembleStyles5();
+var ansi_styles_default5 = ansiStyles5;
+
+// packages/cli/node_modules/chalk/source/vendor/supports-color/index.js
+init_esbuild_shims();
+import process15 from "node:process";
+import os11 from "node:os";
+import tty3 from "node:tty";
+function hasFlag2(flag, argv = globalThis.Deno ? globalThis.Deno.args : process15.argv) {
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
+ const position = argv.indexOf(prefix + flag);
+ const terminatorPosition = argv.indexOf("--");
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
+}
+__name(hasFlag2, "hasFlag");
+var { env: env3 } = process15;
+var flagForceColor2;
+if (hasFlag2("no-color") || hasFlag2("no-colors") || hasFlag2("color=false") || hasFlag2("color=never")) {
+ flagForceColor2 = 0;
+} else if (hasFlag2("color") || hasFlag2("colors") || hasFlag2("color=true") || hasFlag2("color=always")) {
+ flagForceColor2 = 1;
+}
+function envForceColor2() {
+ if ("FORCE_COLOR" in env3) {
+ if (env3.FORCE_COLOR === "true") {
+ return 1;
+ }
+ if (env3.FORCE_COLOR === "false") {
+ return 0;
+ }
+ return env3.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env3.FORCE_COLOR, 10), 3);
+ }
+}
+__name(envForceColor2, "envForceColor");
+function translateLevel2(level) {
+ if (level === 0) {
+ return false;
+ }
+ return {
+ level,
+ hasBasic: true,
+ has256: level >= 2,
+ has16m: level >= 3
+ };
+}
+__name(translateLevel2, "translateLevel");
+function _supportsColor2(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
+ const noFlagForceColor = envForceColor2();
+ if (noFlagForceColor !== void 0) {
+ flagForceColor2 = noFlagForceColor;
+ }
+ const forceColor = sniffFlags ? flagForceColor2 : noFlagForceColor;
+ if (forceColor === 0) {
+ return 0;
+ }
+ if (sniffFlags) {
+ if (hasFlag2("color=16m") || hasFlag2("color=full") || hasFlag2("color=truecolor")) {
+ return 3;
+ }
+ if (hasFlag2("color=256")) {
+ return 2;
+ }
+ }
+ if ("TF_BUILD" in env3 && "AGENT_NAME" in env3) {
+ return 1;
+ }
+ if (haveStream && !streamIsTTY && forceColor === void 0) {
+ return 0;
+ }
+ const min = forceColor || 0;
+ if (env3.TERM === "dumb") {
+ return min;
+ }
+ if (process15.platform === "win32") {
+ const osRelease = os11.release().split(".");
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
+ }
+ return 1;
+ }
+ if ("CI" in env3) {
+ if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => key in env3)) {
+ return 3;
+ }
+ if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env3) || env3.CI_NAME === "codeship") {
+ return 1;
+ }
+ return min;
+ }
+ if ("TEAMCITY_VERSION" in env3) {
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env3.TEAMCITY_VERSION) ? 1 : 0;
+ }
+ if (env3.COLORTERM === "truecolor") {
+ return 3;
+ }
+ if (env3.TERM === "xterm-kitty") {
+ return 3;
+ }
+ if (env3.TERM === "xterm-ghostty") {
+ return 3;
+ }
+ if (env3.TERM === "wezterm") {
+ return 3;
+ }
+ if ("TERM_PROGRAM" in env3) {
+ const version2 = Number.parseInt((env3.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
+ switch (env3.TERM_PROGRAM) {
+ case "iTerm.app": {
+ return version2 >= 3 ? 3 : 2;
+ }
+ case "Apple_Terminal": {
+ return 2;
+ }
+ }
+ }
+ if (/-256(color)?$/i.test(env3.TERM)) {
+ return 2;
+ }
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env3.TERM)) {
+ return 1;
+ }
+ if ("COLORTERM" in env3) {
+ return 1;
+ }
+ return min;
+}
+__name(_supportsColor2, "_supportsColor");
+function createSupportsColor2(stream, options2 = {}) {
+ const level = _supportsColor2(stream, {
+ streamIsTTY: stream && stream.isTTY,
+ ...options2
+ });
+ return translateLevel2(level);
+}
+__name(createSupportsColor2, "createSupportsColor");
+var supportsColor2 = {
+ stdout: createSupportsColor2({ isTTY: tty3.isatty(1) }),
+ stderr: createSupportsColor2({ isTTY: tty3.isatty(2) })
+};
+var supports_color_default2 = supportsColor2;
+
+// packages/cli/node_modules/chalk/source/utilities.js
+init_esbuild_shims();
+function stringReplaceAll2(string4, substring, replacer) {
+ let index = string4.indexOf(substring);
+ if (index === -1) {
+ return string4;
+ }
+ const substringLength = substring.length;
+ let endIndex = 0;
+ let returnValue = "";
+ do {
+ returnValue += string4.slice(endIndex, index) + substring + replacer;
+ endIndex = index + substringLength;
+ index = string4.indexOf(substring, endIndex);
+ } while (index !== -1);
+ returnValue += string4.slice(endIndex);
+ return returnValue;
+}
+__name(stringReplaceAll2, "stringReplaceAll");
+function stringEncaseCRLFWithFirstIndex2(string4, prefix, postfix, index) {
+ let endIndex = 0;
+ let returnValue = "";
+ do {
+ const gotCR = string4[index - 1] === "\r";
+ returnValue += string4.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
+ endIndex = index + 1;
+ index = string4.indexOf("\n", endIndex);
+ } while (index !== -1);
+ returnValue += string4.slice(endIndex);
+ return returnValue;
+}
+__name(stringEncaseCRLFWithFirstIndex2, "stringEncaseCRLFWithFirstIndex");
+
+// packages/cli/node_modules/chalk/source/index.js
+var { stdout: stdoutColor2, stderr: stderrColor2 } = supports_color_default2;
+var GENERATOR2 = /* @__PURE__ */ Symbol("GENERATOR");
+var STYLER2 = /* @__PURE__ */ Symbol("STYLER");
+var IS_EMPTY2 = /* @__PURE__ */ Symbol("IS_EMPTY");
+var levelMapping2 = [
+ "ansi",
+ "ansi",
+ "ansi256",
+ "ansi16m"
+];
+var styles8 = /* @__PURE__ */ Object.create(null);
+var applyOptions2 = /* @__PURE__ */ __name((object2, options2 = {}) => {
+ if (options2.level && !(Number.isInteger(options2.level) && options2.level >= 0 && options2.level <= 3)) {
+ throw new Error("The `level` option should be an integer from 0 to 3");
+ }
+ const colorLevel = stdoutColor2 ? stdoutColor2.level : 0;
+ object2.level = options2.level === void 0 ? colorLevel : options2.level;
+}, "applyOptions");
+var chalkFactory2 = /* @__PURE__ */ __name((options2) => {
+ const chalk4 = /* @__PURE__ */ __name((...strings) => strings.join(" "), "chalk");
+ applyOptions2(chalk4, options2);
+ Object.setPrototypeOf(chalk4, createChalk2.prototype);
+ return chalk4;
+}, "chalkFactory");
+function createChalk2(options2) {
+ return chalkFactory2(options2);
+}
+__name(createChalk2, "createChalk");
+Object.setPrototypeOf(createChalk2.prototype, Function.prototype);
+for (const [styleName, style] of Object.entries(ansi_styles_default5)) {
+ styles8[styleName] = {
+ get() {
+ const builder = createBuilder2(this, createStyler2(style.open, style.close, this[STYLER2]), this[IS_EMPTY2]);
+ Object.defineProperty(this, styleName, { value: builder });
+ return builder;
+ }
+ };
+}
+styles8.visible = {
+ get() {
+ const builder = createBuilder2(this, this[STYLER2], true);
+ Object.defineProperty(this, "visible", { value: builder });
+ return builder;
+ }
+};
+var getModelAnsi2 = /* @__PURE__ */ __name((model, level, type2, ...arguments_) => {
+ if (model === "rgb") {
+ if (level === "ansi16m") {
+ return ansi_styles_default5[type2].ansi16m(...arguments_);
+ }
+ if (level === "ansi256") {
+ return ansi_styles_default5[type2].ansi256(ansi_styles_default5.rgbToAnsi256(...arguments_));
+ }
+ return ansi_styles_default5[type2].ansi(ansi_styles_default5.rgbToAnsi(...arguments_));
+ }
+ if (model === "hex") {
+ return getModelAnsi2("rgb", level, type2, ...ansi_styles_default5.hexToRgb(...arguments_));
+ }
+ return ansi_styles_default5[type2][model](...arguments_);
+}, "getModelAnsi");
+var usedModels2 = ["rgb", "hex", "ansi256"];
+for (const model of usedModels2) {
+ styles8[model] = {
+ get() {
+ const { level } = this;
+ return function(...arguments_) {
+ const styler = createStyler2(getModelAnsi2(model, levelMapping2[level], "color", ...arguments_), ansi_styles_default5.color.close, this[STYLER2]);
+ return createBuilder2(this, styler, this[IS_EMPTY2]);
+ };
+ }
+ };
+ const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
+ styles8[bgModel] = {
+ get() {
+ const { level } = this;
+ return function(...arguments_) {
+ const styler = createStyler2(getModelAnsi2(model, levelMapping2[level], "bgColor", ...arguments_), ansi_styles_default5.bgColor.close, this[STYLER2]);
+ return createBuilder2(this, styler, this[IS_EMPTY2]);
+ };
+ }
+ };
+}
+var proto2 = Object.defineProperties(() => {
+}, {
+ ...styles8,
+ level: {
+ enumerable: true,
+ get() {
+ return this[GENERATOR2].level;
+ },
+ set(level) {
+ this[GENERATOR2].level = level;
+ }
+ }
+});
+var createStyler2 = /* @__PURE__ */ __name((open, close, parent) => {
+ let openAll;
+ let closeAll;
+ if (parent === void 0) {
+ openAll = open;
+ closeAll = close;
+ } else {
+ openAll = parent.openAll + open;
+ closeAll = close + parent.closeAll;
+ }
+ return {
+ open,
+ close,
+ openAll,
+ closeAll,
+ parent
+ };
+}, "createStyler");
+var createBuilder2 = /* @__PURE__ */ __name((self2, _styler, _isEmpty) => {
+ const builder = /* @__PURE__ */ __name((...arguments_) => applyStyle2(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" ")), "builder");
+ Object.setPrototypeOf(builder, proto2);
+ builder[GENERATOR2] = self2;
+ builder[STYLER2] = _styler;
+ builder[IS_EMPTY2] = _isEmpty;
+ return builder;
+}, "createBuilder");
+var applyStyle2 = /* @__PURE__ */ __name((self2, string4) => {
+ if (self2.level <= 0 || !string4) {
+ return self2[IS_EMPTY2] ? "" : string4;
+ }
+ let styler = self2[STYLER2];
+ if (styler === void 0) {
+ return string4;
+ }
+ const { openAll, closeAll } = styler;
+ if (string4.includes("\x1B")) {
+ while (styler !== void 0) {
+ string4 = stringReplaceAll2(string4, styler.close, styler.open);
+ styler = styler.parent;
+ }
+ }
+ const lfIndex = string4.indexOf("\n");
+ if (lfIndex !== -1) {
+ string4 = stringEncaseCRLFWithFirstIndex2(string4, closeAll, openAll, lfIndex);
+ }
+ return openAll + string4 + closeAll;
+}, "applyStyle");
+Object.defineProperties(createChalk2.prototype, styles8);
+var chalk2 = createChalk2();
+var chalkStderr2 = createChalk2({ level: stderrColor2 ? stderrColor2.level : 0 });
+var source_default2 = chalk2;
+
+// packages/cli/src/ui/components/MessageView/utils.ts
+init_esbuild_shims();
+
+// packages/cli/src/ui/contexts/index.ts
+init_esbuild_shims();
+
+// packages/cli/src/ui/contexts/AppContext.tsx
+init_esbuild_shims();
+var import_react36 = __toESM(require_react(), 1);
+var AppContext2 = (0, import_react36.createContext)(null);
+var useAppContext = /* @__PURE__ */ __name(() => {
+ const context = (0, import_react36.useContext)(AppContext2);
+ if (!context) {
+ return { version: "unknown" };
+ }
+ return context;
+}, "useAppContext");
+
+// packages/cli/src/ui/contexts/RawModeContext.tsx
+init_esbuild_shims();
+var import_react37 = __toESM(require_react(), 1);
+var import_jsx_runtime3 = __toESM(require_jsx_runtime(), 1);
+var RAW_COMMAND_MODELS = [
+ {
+ label: "Lite mode",
+ key: "Lite mode" /* Lite */,
+ description: "Collapse chain-of-thought reasoning."
+ },
+ {
+ label: "Normal mode",
+ key: "Normal mode" /* None */,
+ description: "Show full chain-of-thought reasoning."
+ },
+ {
+ label: "Raw scrollback mode",
+ key: "Raw scrollback mode" /* Raw */,
+ description: "Show scrollback mode for copy-friendly terminal selection."
+ }
+];
+var RawModeContext = (0, import_react37.createContext)({
+ mode: "Lite mode" /* Lite */,
+ setMode: /* @__PURE__ */ __name(() => {
+ }, "setMode"),
+ previousMode: "Lite mode" /* Lite */
+});
+function useRawModeContext() {
+ const context = (0, import_react37.useContext)(RawModeContext);
+ if (!context) {
+ throw new Error("useRawModeContext must be used within a RawModeProvider");
+ }
+ return context;
+}
+__name(useRawModeContext, "useRawModeContext");
+var RawModeProvider = /* @__PURE__ */ __name(({ children }) => {
+ const [mode, _setMode] = (0, import_react37.useState)("Lite mode" /* Lite */);
+ const previousModeRef = (0, import_react37.useRef)("Lite mode" /* Lite */);
+ const setMode = (0, import_react37.useCallback)((next) => {
+ _setMode((current) => {
+ const resolved = typeof next === "function" ? next(current) : next;
+ if (resolved !== current) {
+ previousModeRef.current = current;
+ }
+ return resolved;
+ });
+ }, []);
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(RawModeContext.Provider, { value: { mode, setMode, previousMode: previousModeRef.current }, children });
+}, "RawModeProvider");
+
+// packages/cli/src/ui/components/MessageView/utils.ts
+function isPlainRecord(value) {
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
+}
+__name(isPlainRecord, "isPlainRecord");
+function formatStatusName(value) {
+ return value ? `${value.charAt(0).toUpperCase()}${value.slice(1)}` : "Tool";
+}
+__name(formatStatusName, "formatStatusName");
+function truncate(value, max) {
+ if (value.length <= max) {
+ return value;
+ }
+ return `${value.slice(0, max)}\u2026`;
+}
+__name(truncate, "truncate");
+function firstNonEmptyLine(value) {
+ for (const line of value.split(/\r?\n/)) {
+ const trimmed = line.trim().replace(/\s+/g, " ");
+ if (trimmed) {
+ return trimmed;
+ }
+ }
+ return "";
+}
+__name(firstNonEmptyLine, "firstNonEmptyLine");
+function buildThinkingSummary(content, messageParams, mode) {
+ if (content) {
+ const normalized = content.replace(/\r?\n/g, " ").replace(/\s+/g, " ");
+ let result = truncate(normalized, 100);
+ if (result.endsWith(":") || result.endsWith("\uFF1A")) {
+ result = result.slice(0, -1);
+ }
+ return result;
+ }
+ const params = messageParams;
+ if (typeof params?.reasoning_content === "string" && params.reasoning_content.trim()) {
+ return mode !== "Lite mode" /* Lite */ ? params?.reasoning_content || "" : "(reasoning...)";
+ }
+ return "";
+}
+__name(buildThinkingSummary, "buildThinkingSummary");
+function formatBashStatusParams(params) {
+ const value = params.trim();
+ if (!value) {
+ return "";
+ }
+ const lines = value.split(/\r?\n/);
+ if (lines.length <= 1) {
+ return value;
+ }
+ return `${lines[0]} ... ${lines[lines.length - 1].trimStart()}`;
+}
+__name(formatBashStatusParams, "formatBashStatusParams");
+function formatToolStatusParams(summary) {
+ if (summary.name.toLowerCase() === "bash") {
+ return formatBashStatusParams(summary.params);
+ }
+ const params = firstNonEmptyLine(summary.params);
+ return truncate(params, 120);
+}
+__name(formatToolStatusParams, "formatToolStatusParams");
+function buildToolSummary(message) {
+ const payload = parseToolPayload(message.content);
+ const metaFunctionName = message.meta?.function && typeof message.meta.function.name === "string" ? message.meta.function.name : null;
+ const name = payload.name || metaFunctionName || "tool";
+ const params = name === "AskUserQuestion" ? extractAskUserQuestionParams(message) || getMetaParams(message) : getMetaParams(message);
+ return {
+ name,
+ params,
+ ok: payload.ok !== false,
+ metadata: payload.metadata
+ };
+}
+__name(buildToolSummary, "buildToolSummary");
+function getMetaParams(message) {
+ return typeof message.meta?.paramsMd === "string" ? message.meta.paramsMd.trim() : "";
+}
+__name(getMetaParams, "getMetaParams");
+function extractAskUserQuestionParams(message) {
+ const fromFunction = extractQuestionsFromToolFunction(message.meta?.function);
+ if (fromFunction) {
+ return fromFunction;
+ }
+ const params = getMetaParams(message);
+ if (!params) {
+ return "";
+ }
+ try {
+ const parsed = JSON.parse(params);
+ return extractQuestionsFromValue(parsed);
+ } catch {
+ return "";
+ }
+}
+__name(extractAskUserQuestionParams, "extractAskUserQuestionParams");
+function extractQuestionsFromToolFunction(toolFunction) {
+ if (!toolFunction || typeof toolFunction !== "object") {
+ return "";
+ }
+ const args = toolFunction.arguments;
+ if (typeof args !== "string" || !args.trim()) {
+ return "";
+ }
+ try {
+ const parsed = JSON.parse(args);
+ return extractQuestionsFromValue(parsed?.questions);
+ } catch {
+ return "";
+ }
+}
+__name(extractQuestionsFromToolFunction, "extractQuestionsFromToolFunction");
+function extractQuestionsFromValue(value) {
+ if (!Array.isArray(value)) {
+ return "";
+ }
+ return value.map((item) => {
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
+ return "";
+ }
+ return typeof item.question === "string" ? item.question.trim() : "";
+ }).filter(Boolean).join(" / ");
+}
+__name(extractQuestionsFromValue, "extractQuestionsFromValue");
+function parseToolPayload(content) {
+ if (!content) {
+ return { name: null, ok: true, metadata: null };
+ }
+ try {
+ const parsed = JSON.parse(content);
+ return {
+ name: typeof parsed.name === "string" && parsed.name.trim() ? parsed.name.trim() : null,
+ ok: parsed.ok !== false,
+ metadata: isPlainRecord(parsed.metadata) ? parsed.metadata : null
+ };
+ } catch {
+ return { name: null, ok: true, metadata: null };
+ }
+}
+__name(parseToolPayload, "parseToolPayload");
+function getToolDiffPreviewLines(summary) {
+ if (!summary.ok || !["edit", "write"].includes(summary.name.toLowerCase())) {
+ return [];
+ }
+ const diffPreview = summary.metadata?.diff_preview;
+ if (typeof diffPreview !== "string" || !diffPreview.trim()) {
+ return [];
+ }
+ return parseDiffPreview(diffPreview);
+}
+__name(getToolDiffPreviewLines, "getToolDiffPreviewLines");
+function parseDiffPreview(diffPreview) {
+ return diffPreview.split("\n").filter((line) => line && !line.startsWith("--- ") && !line.startsWith("+++ ") && !line.startsWith("@@ ")).map((line) => {
+ if (line.startsWith("+")) {
+ return { marker: "+", content: line.slice(1), kind: "added" };
+ }
+ if (line.startsWith("-")) {
+ return { marker: "-", content: line.slice(1), kind: "removed" };
+ }
+ return {
+ marker: " ",
+ content: line.startsWith(" ") ? line.slice(1) : line,
+ kind: "context"
+ };
+ });
+}
+__name(parseDiffPreview, "parseDiffPreview");
+function renderMessageToStdout(message, mode) {
+ if (!message.visible) {
+ return "";
+ }
+ if (message.role === "user") {
+ const text = message.content || "(no content)";
+ return source_default2(`> ${text}`);
+ }
+ if (message.role === "assistant") {
+ const isThinking = Boolean(message.meta?.asThinking);
+ const content = (message.content || "").trim();
+ if (isThinking) {
+ const summary = buildThinkingSummary(content, message.messageParams, mode);
+ return `${source_default2("\u2727")} ${source_default2("Thinking")}${summary ? ` ${source_default2(summary)}` : ""}`;
+ }
+ return `${source_default2("\u2726")} ${content}`;
+ }
+ if (message.role === "tool") {
+ const summary = buildToolSummary(message);
+ const params = formatToolStatusParams(summary);
+ const statusLine = `${source_default2("\u2727")} ${source_default2(formatStatusName(summary.name))}${params ? ` ${source_default2(params)}` : ""}`;
+ const metaResultMd = typeof message.meta?.resultMd === "string" ? message.meta.resultMd.trim() : "";
+ const result = metaResultMd ? `
+${source_default2.dim(" \u2514 Result")}
+${metaResultMd}` : "";
+ const planLines = getUpdatePlanPreviewLines(summary);
+ if (planLines.length > 0) {
+ const planText = planLines.map((line) => ` ${line}`).join("\n");
+ return `${statusLine}
+${source_default2.dim(" \u2514 Plan")}
+${planText}${result}`;
+ }
+ return `${statusLine}${result}`;
+ }
+ if (message.role === "system") {
+ if (message.meta?.isModelChange) {
+ return source_default2(`> ${message.content}`);
+ }
+ if (message.meta?.skill && typeof message.meta.skill === "object") {
+ const skillName = message.meta.skill.name;
+ return source_default2(`\u26A1 Loaded skill: ${typeof skillName === "string" ? skillName : ""}`);
+ }
+ if (message.meta?.isSummary) {
+ return source_default2.dim.italic("(conversation summary inserted)");
+ }
+ return "";
+ }
+ return "";
+}
+__name(renderMessageToStdout, "renderMessageToStdout");
+function getUpdatePlanPreviewLines(summary) {
+ if (!summary.ok || summary.name !== "UpdatePlan") {
+ return [];
+ }
+ const plan = summary.metadata?.plan;
+ if (typeof plan !== "string" || !plan.trim()) {
+ return [];
+ }
+ return plan.split(/\r?\n/).map((line) => line.trimEnd()).filter((line) => line.trim().length > 0);
+}
+__name(getUpdatePlanPreviewLines, "getUpdatePlanPreviewLines");
+
+// packages/cli/src/ui/utils/index.ts
+function renderRawModeMessages(allMessages, mode) {
+ for (const msg of allMessages) {
+ process.stdout.write("\n");
+ process.stdout.write(renderMessageToStdout(msg, mode) + "\n\n");
+ }
+ if (allMessages.length > 0) {
+ process.stdout.write("\n\n");
+ process.stdout.write(source_default2.dim("Press ESC to exit raw mode"));
+ } else {
+ process.stdout.write("\n");
+ process.stdout.write(source_default2.dim("(No messages in this session yet. Start chatting to see them here.)"));
+ process.stdout.write("\n\n");
+ process.stdout.write(source_default2.dim("Press ESC to exit raw mode"));
+ }
+}
+__name(renderRawModeMessages, "renderRawModeMessages");
+function buildSyntheticUserMessage(content, imageCount) {
+ const now = (/* @__PURE__ */ new Date()).toISOString();
+ return {
+ id: `local-${Math.random().toString(36).slice(2)}`,
+ sessionId: "local",
+ role: "user",
+ content,
+ contentParams: imageCount > 0 ? Array.from({ length: imageCount }, () => ({
+ type: "image_url",
+ image_url: { url: "" }
+ })) : null,
+ messageParams: null,
+ compacted: false,
+ visible: true,
+ createTime: now,
+ updateTime: now
+ };
+}
+__name(buildSyntheticUserMessage, "buildSyntheticUserMessage");
+function buildPromptDraftFromSessionMessage(message, nonce) {
+ return {
+ nonce,
+ text: typeof message.content === "string" ? message.content : "",
+ imageUrls: extractImageUrlsFromContentParams(message.contentParams)
+ };
+}
+__name(buildPromptDraftFromSessionMessage, "buildPromptDraftFromSessionMessage");
+function extractImageUrlsFromContentParams(contentParams) {
+ const params = Array.isArray(contentParams) ? contentParams : contentParams ? [contentParams] : [];
+ const imageUrls = [];
+ for (const param of params) {
+ if (!param || typeof param !== "object") {
+ continue;
+ }
+ const record2 = param;
+ const url2 = record2.image_url?.url;
+ if (record2.type === "image_url" && typeof url2 === "string" && url2) {
+ imageUrls.push(url2);
+ }
+ }
+ return imageUrls;
+}
+__name(extractImageUrlsFromContentParams, "extractImageUrlsFromContentParams");
+function isCurrentSessionEmpty(sessionManager) {
+ const activeSessionId = sessionManager.getActiveSessionId();
+ return !activeSessionId || !sessionManager.getSession(activeSessionId);
+}
+__name(isCurrentSessionEmpty, "isCurrentSessionEmpty");
+function buildStatusLine(entry) {
+ const parts = [];
+ parts.push(`status: ${entry.status}`);
+ if (typeof entry.activeTokens === "number" && entry.activeTokens > 0) {
+ parts.push(`tokens: ${entry.activeTokens}`);
+ }
+ if (entry.failReason) {
+ parts.push(`fail: ${entry.failReason}`);
+ }
+ return parts.join(" \xB7 ");
+}
+__name(buildStatusLine, "buildStatusLine");
+function formatThinkingMode(settings) {
+ if (!settings.thinkingEnabled) {
+ return "no thinking";
+ }
+ return `thinking ${settings.reasoningEffort}`;
+}
+__name(formatThinkingMode, "formatThinkingMode");
+function formatModelConfig(settings) {
+ return `${settings.model}, ${formatThinkingMode(settings)}`;
+}
+__name(formatModelConfig, "formatModelConfig");
+
+// packages/cli/src/ui/hooks/cursor.ts
+init_esbuild_shims();
+var import_react38 = __toESM(require_react(), 1);
+function showCursor() {
+ return "\x1B[?25h";
+}
+__name(showCursor, "showCursor");
+function hideCursor() {
+ return "\x1B[?25l";
+}
+__name(hideCursor, "hideCursor");
+function enableTerminalFocusReporting() {
+ return "\x1B[?1004h";
+}
+__name(enableTerminalFocusReporting, "enableTerminalFocusReporting");
+function disableTerminalFocusReporting() {
+ return "\x1B[?1004l";
+}
+__name(disableTerminalFocusReporting, "disableTerminalFocusReporting");
+function enableBracketedPaste() {
+ return "\x1B[?2004h";
+}
+__name(enableBracketedPaste, "enableBracketedPaste");
+function disableBracketedPaste() {
+ return "\x1B[?2004l";
+}
+__name(disableBracketedPaste, "disableBracketedPaste");
+function enableTerminalExtendedKeys() {
+ return "\x1B[>4;1m";
+}
+__name(enableTerminalExtendedKeys, "enableTerminalExtendedKeys");
+function disableTerminalExtendedKeys() {
+ return "\x1B[>4;0m";
+}
+__name(disableTerminalExtendedKeys, "disableTerminalExtendedKeys");
+function getPromptCursorPlacement(state, screenWidth, initialColumn = 0) {
+ const width = Math.max(1, screenWidth);
+ const cursor = Math.max(0, Math.min(state.cursor, state.text.length));
+ const beforeCursor = state.text.slice(0, cursor);
+ const cursorPosition = measureTextPosition(beforeCursor, width, initialColumn);
+ return { row: cursorPosition.row, column: cursorPosition.column };
+}
+__name(getPromptCursorPlacement, "getPromptCursorPlacement");
+function isPromptCursorAtWrapBoundary(state, screenWidth) {
+ const width = Math.max(1, screenWidth);
+ const cursor = Math.max(0, Math.min(state.cursor, state.text.length));
+ const currentLineStart = state.text.lastIndexOf("\n", Math.max(0, cursor - 1)) + 1;
+ const currentLineBeforeCursor = state.text.slice(currentLineStart, cursor);
+ return measureTextPosition(currentLineBeforeCursor, width, 0).row > 0;
+}
+__name(isPromptCursorAtWrapBoundary, "isPromptCursorAtWrapBoundary");
+function measureTextPosition(text, width, initialColumn) {
+ let row = 0;
+ let column = Math.min(initialColumn, width - 1);
+ let pendingWrap = false;
+ for (const char of Array.from(text)) {
+ if (char === "\n") {
+ row++;
+ column = Math.min(initialColumn, width - 1);
+ pendingWrap = false;
+ continue;
+ }
+ if (pendingWrap) {
+ row++;
+ column = Math.min(initialColumn, width - 1);
+ pendingWrap = false;
+ }
+ const charColumns = textWidth(char);
+ if (column + charColumns > width) {
+ row++;
+ column = Math.min(initialColumn, width - 1);
+ }
+ column += charColumns;
+ if (column >= width) {
+ column = width;
+ pendingWrap = true;
+ }
+ }
+ if (pendingWrap) {
+ return { row: row + 1, column: Math.min(initialColumn, width - 1) };
+ }
+ return { row, column };
+}
+__name(measureTextPosition, "measureTextPosition");
+function textWidth(value) {
+ let width = 0;
+ for (const char of Array.from(value.normalize())) {
+ width += characterWidth(char);
+ }
+ return width;
+}
+__name(textWidth, "textWidth");
+function characterWidth(char) {
+ const codePoint = char.codePointAt(0) ?? 0;
+ if (codePoint === 0 || codePoint < 32 || codePoint >= 127 && codePoint < 160) {
+ return 0;
+ }
+ if (codePoint >= 768 && codePoint <= 879) {
+ return 0;
+ }
+ if (codePoint >= 4352 && codePoint <= 4447 || codePoint >= 11904 && codePoint <= 42191 || codePoint >= 44032 && codePoint <= 55203 || codePoint >= 63744 && codePoint <= 64255 || codePoint >= 65040 && codePoint <= 65049 || codePoint >= 65072 && codePoint <= 65135 || codePoint >= 65280 && codePoint <= 65376 || codePoint >= 65504 && codePoint <= 65510) {
+ return 2;
+ }
+ return 1;
+}
+__name(characterWidth, "characterWidth");
+function usePromptTerminalCursor(targetRef, placement, isActive, layoutKey = "default") {
+ const { setCursorPosition } = use_cursor_default();
+ const metrics = use_box_metrics_default(targetRef);
+ const [origin, setOrigin] = (0, import_react38.useState)(null);
+ (0, import_react38.useLayoutEffect)(() => {
+ if (!isActive || !metrics.hasMeasured) {
+ return;
+ }
+ const absolutePosition = getAbsoluteElementPosition(targetRef.current);
+ setOrigin((previous) => {
+ if (!absolutePosition) {
+ return previous === null ? previous : null;
+ }
+ if (previous?.layoutKey === layoutKey && previous.left === absolutePosition.left && previous.top === absolutePosition.top) {
+ return previous;
+ }
+ return {
+ layoutKey,
+ left: absolutePosition.left,
+ top: absolutePosition.top
+ };
+ });
+ }, [isActive, layoutKey, metrics.hasMeasured, metrics.height, metrics.left, metrics.top, metrics.width, targetRef]);
+ const cursorPosition = resolvePromptTerminalCursorPosition(placement, isActive, layoutKey, origin);
+ setCursorPosition(cursorPosition);
+ return cursorPosition !== void 0;
+}
+__name(usePromptTerminalCursor, "usePromptTerminalCursor");
+function resolvePromptTerminalCursorPosition(placement, isActive, layoutKey, origin) {
+ if (!isActive || origin?.layoutKey !== layoutKey) {
+ return void 0;
+ }
+ return {
+ x: Math.max(0, Math.round(origin.left + placement.column)),
+ y: Math.max(0, Math.round(origin.top + placement.row))
+ };
+}
+__name(resolvePromptTerminalCursorPosition, "resolvePromptTerminalCursorPosition");
+function getAbsoluteElementPosition(element) {
+ let current = element ?? void 0;
+ let left2 = 0;
+ let top2 = 0;
+ while (current) {
+ const layout = current.yogaNode?.getComputedLayout();
+ if (!layout) {
+ return null;
+ }
+ left2 += layout.left;
+ top2 += layout.top;
+ current = current.parentNode;
+ }
+ return { left: left2, top: top2 };
+}
+__name(getAbsoluteElementPosition, "getAbsoluteElementPosition");
+function useHiddenTerminalCursor(stdout, isActive) {
+ (0, import_react38.useLayoutEffect)(() => {
+ if (!isActive || !stdout?.isTTY) {
+ return;
+ }
+ stdout.write(hideCursor());
+ return () => {
+ stdout.write(showCursor());
+ };
+ }, [isActive, stdout]);
+}
+__name(useHiddenTerminalCursor, "useHiddenTerminalCursor");
+function useTerminalFocusReporting(stdout, isActive) {
+ (0, import_react38.useLayoutEffect)(() => {
+ if (!isActive || !stdout?.isTTY) {
+ return;
+ }
+ stdout.write(enableTerminalFocusReporting());
+ return () => {
+ stdout.write(disableTerminalFocusReporting());
+ };
+ }, [isActive, stdout]);
+}
+__name(useTerminalFocusReporting, "useTerminalFocusReporting");
+function useTerminalExtendedKeys(stdout, isActive) {
+ (0, import_react38.useLayoutEffect)(() => {
+ if (!isActive || !stdout?.isTTY) {
+ return;
+ }
+ stdout.write(enableTerminalExtendedKeys());
+ return () => {
+ stdout.write(disableTerminalExtendedKeys());
+ };
+ }, [isActive, stdout]);
+}
+__name(useTerminalExtendedKeys, "useTerminalExtendedKeys");
+function useBracketedPaste(stdout, isActive) {
+ (0, import_react38.useLayoutEffect)(() => {
+ if (!isActive || !stdout?.isTTY) {
+ return;
+ }
+ stdout.write(enableBracketedPaste());
+ return () => {
+ stdout.write(disableBracketedPaste());
+ };
+ }, [isActive, stdout]);
+}
+__name(useBracketedPaste, "useBracketedPaste");
+
+// packages/cli/src/ui/views/AppContainer.tsx
+init_esbuild_shims();
+
+// packages/cli/src/ui/views/App.tsx
+init_esbuild_shims();
+var import_react57 = __toESM(require_react(), 1);
+
+// packages/cli/src/ui/views/PromptInput.tsx
+init_esbuild_shims();
+var import_react48 = __toESM(require_react(), 1);
+
+// packages/cli/src/ui/constants.ts
+init_esbuild_shims();
+var ARGS_SEPARATOR = " | ";
+var ANSI_CLEAR_SCREEN = "\x1B[2J\x1B[3J\x1B[H";
+
+// packages/cli/src/ui/core/prompt-buffer.ts
+init_esbuild_shims();
+var EMPTY_BUFFER = { text: "", cursor: 0 };
+function insertText(state, value) {
+ if (!value) {
+ return state;
+ }
+ const text = state.text.slice(0, state.cursor) + value + state.text.slice(state.cursor);
+ return { text, cursor: state.cursor + value.length };
+}
+__name(insertText, "insertText");
+function backspace(state) {
+ if (state.cursor === 0) {
+ return state;
+ }
+ const text = state.text.slice(0, state.cursor - 1) + state.text.slice(state.cursor);
+ return { text, cursor: state.cursor - 1 };
+}
+__name(backspace, "backspace");
+function deleteForward(state) {
+ if (state.cursor >= state.text.length) {
+ return state;
+ }
+ const text = state.text.slice(0, state.cursor) + state.text.slice(state.cursor + 1);
+ return { text, cursor: state.cursor };
+}
+__name(deleteForward, "deleteForward");
+function moveLeft(state) {
+ if (state.cursor === 0) {
+ return state;
+ }
+ return { ...state, cursor: state.cursor - 1 };
+}
+__name(moveLeft, "moveLeft");
+function moveRight(state) {
+ if (state.cursor >= state.text.length) {
+ return state;
+ }
+ return { ...state, cursor: state.cursor + 1 };
+}
+__name(moveRight, "moveRight");
+function moveWordLeft(state) {
+ let cursor = state.cursor;
+ while (cursor > 0 && /\s/.test(state.text[cursor - 1] ?? "")) {
+ cursor--;
+ }
+ while (cursor > 0 && !/\s/.test(state.text[cursor - 1] ?? "")) {
+ cursor--;
+ }
+ return { ...state, cursor };
+}
+__name(moveWordLeft, "moveWordLeft");
+function moveWordRight(state) {
+ let cursor = state.cursor;
+ while (cursor < state.text.length && /\s/.test(state.text[cursor] ?? "")) {
+ cursor++;
+ }
+ while (cursor < state.text.length && !/\s/.test(state.text[cursor] ?? "")) {
+ cursor++;
+ }
+ return { ...state, cursor };
+}
+__name(moveWordRight, "moveWordRight");
+function moveUp(state) {
+ const { line, column, lineStart } = locate(state);
+ if (line === 0) {
+ return { ...state, cursor: 0 };
+ }
+ const previousLineEnd = lineStart - 1;
+ const previousLineStart = state.text.lastIndexOf("\n", previousLineEnd - 1) + 1;
+ const previousLineLength = previousLineEnd - previousLineStart;
+ const targetColumn = Math.min(column, previousLineLength);
+ return { ...state, cursor: previousLineStart + targetColumn };
+}
+__name(moveUp, "moveUp");
+function moveDown(state) {
+ const { column, lineEnd } = locate(state);
+ if (lineEnd >= state.text.length) {
+ return { ...state, cursor: state.text.length };
+ }
+ const nextLineStart = lineEnd + 1;
+ const nextLineNewline = state.text.indexOf("\n", nextLineStart);
+ const nextLineEnd = nextLineNewline === -1 ? state.text.length : nextLineNewline;
+ const nextLineLength = nextLineEnd - nextLineStart;
+ const targetColumn = Math.min(column, nextLineLength);
+ return { ...state, cursor: nextLineStart + targetColumn };
+}
+__name(moveDown, "moveDown");
+function moveLineStart(state) {
+ const { lineStart } = locate(state);
+ return { ...state, cursor: lineStart };
+}
+__name(moveLineStart, "moveLineStart");
+function moveLineEnd(state) {
+ const { lineEnd } = locate(state);
+ return { ...state, cursor: lineEnd };
+}
+__name(moveLineEnd, "moveLineEnd");
+function killLine(state) {
+ const { lineEnd } = locate(state);
+ if (state.cursor >= lineEnd) {
+ return state;
+ }
+ const text = state.text.slice(0, state.cursor) + state.text.slice(lineEnd);
+ return { text, cursor: state.cursor };
+}
+__name(killLine, "killLine");
+function deleteWordBefore(state) {
+ const end = state.cursor;
+ let start = end;
+ while (start > 0 && /\s/.test(state.text[start - 1] ?? "")) {
+ start--;
+ }
+ while (start > 0 && !/\s/.test(state.text[start - 1] ?? "")) {
+ start--;
+ }
+ if (start === end) {
+ return state;
+ }
+ return {
+ text: state.text.slice(0, start) + state.text.slice(end),
+ cursor: start
+ };
+}
+__name(deleteWordBefore, "deleteWordBefore");
+function deleteWordAfter(state) {
+ const start = state.cursor;
+ let end = start;
+ while (end < state.text.length && /\s/.test(state.text[end] ?? "")) {
+ end++;
+ }
+ while (end < state.text.length && !/\s/.test(state.text[end] ?? "")) {
+ end++;
+ }
+ if (start === end) {
+ return state;
+ }
+ return {
+ text: state.text.slice(0, start) + state.text.slice(end),
+ cursor: start
+ };
+}
+__name(deleteWordAfter, "deleteWordAfter");
+function isEmpty(state) {
+ return state.text.length === 0;
+}
+__name(isEmpty, "isEmpty");
+function getCurrentSlashToken(state) {
+ const text = state.text;
+ if (text.length === 0 || !text.startsWith("/")) {
+ return null;
+ }
+ return text;
+}
+__name(getCurrentSlashToken, "getCurrentSlashToken");
+var PASTE_MARKER_REGEX = /\[paste #(\d+) (\+?\d+ lines|\d+ chars)\]/g;
+function findPasteMarkerBefore(state) {
+ let match;
+ PASTE_MARKER_REGEX.lastIndex = 0;
+ while ((match = PASTE_MARKER_REGEX.exec(state.text)) !== null) {
+ if (match.index + match[0].length === state.cursor) {
+ return { start: match.index, end: match.index + match[0].length };
+ }
+ }
+ return null;
+}
+__name(findPasteMarkerBefore, "findPasteMarkerBefore");
+function findPasteMarkerAt(state) {
+ let match;
+ PASTE_MARKER_REGEX.lastIndex = 0;
+ while ((match = PASTE_MARKER_REGEX.exec(state.text)) !== null) {
+ if (match.index === state.cursor) {
+ return { start: match.index, end: match.index + match[0].length };
+ }
+ }
+ return null;
+}
+__name(findPasteMarkerAt, "findPasteMarkerAt");
+function deletePasteMarkerBackward(state, validIds) {
+ const marker = findPasteMarkerBefore(state);
+ if (!marker) return null;
+ PASTE_MARKER_REGEX.lastIndex = 0;
+ const m = PASTE_MARKER_REGEX.exec(state.text.slice(marker.start, marker.end));
+ if (!m || !validIds.has(Number.parseInt(m[1], 10))) return null;
+ const text = state.text.slice(0, marker.start) + state.text.slice(marker.end);
+ return { text, cursor: marker.start };
+}
+__name(deletePasteMarkerBackward, "deletePasteMarkerBackward");
+function deletePasteMarkerForward(state, validIds) {
+ const marker = findPasteMarkerAt(state);
+ if (!marker) return null;
+ PASTE_MARKER_REGEX.lastIndex = 0;
+ const m = PASTE_MARKER_REGEX.exec(state.text.slice(marker.start, marker.end));
+ if (!m || !validIds.has(Number.parseInt(m[1], 10))) return null;
+ const text = state.text.slice(0, marker.start) + state.text.slice(marker.end);
+ return { text, cursor: marker.start };
+}
+__name(deletePasteMarkerForward, "deletePasteMarkerForward");
+function cleanPasteContent(text) {
+ return text.replace(/\r\n|\r/g, "\n").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, "").replace(/\t/g, " ");
+}
+__name(cleanPasteContent, "cleanPasteContent");
+function expandPasteMarkers(text, pastes) {
+ if (pastes.size === 0) return text;
+ let result = text;
+ for (const [pasteId, pasteContent] of pastes) {
+ const markerRegex = new RegExp(`\\[paste #${pasteId} (\\+?\\d+ lines|\\d+ chars)\\]`, "g");
+ result = result.replace(markerRegex, () => cleanPasteContent(pasteContent));
+ }
+ return result;
+}
+__name(expandPasteMarkers, "expandPasteMarkers");
+function findPasteMarkerContaining(state) {
+ let match;
+ PASTE_MARKER_REGEX.lastIndex = 0;
+ while ((match = PASTE_MARKER_REGEX.exec(state.text)) !== null) {
+ if (match.index <= state.cursor && match.index + match[0].length >= state.cursor) {
+ return {
+ start: match.index,
+ end: match.index + match[0].length,
+ id: Number.parseInt(match[1], 10)
+ };
+ }
+ }
+ return null;
+}
+__name(findPasteMarkerContaining, "findPasteMarkerContaining");
+function hasActivePasteMarkers(text, validIds) {
+ if (!text.includes("[paste #")) return false;
+ PASTE_MARKER_REGEX.lastIndex = 0;
+ let match;
+ while ((match = PASTE_MARKER_REGEX.exec(text)) !== null) {
+ if (validIds.has(Number.parseInt(match[1], 10))) {
+ return true;
+ }
+ }
+ return false;
+}
+__name(hasActivePasteMarkers, "hasActivePasteMarkers");
+function locate(state) {
+ const before = state.text.slice(0, state.cursor);
+ const lineStart = before.lastIndexOf("\n") + 1;
+ const lineNumber = before.split("\n").length - 1;
+ const after = state.text.slice(state.cursor);
+ const nextNewline = after.indexOf("\n");
+ const lineEnd = nextNewline === -1 ? state.text.length : state.cursor + nextNewline;
+ return {
+ line: lineNumber,
+ column: state.cursor - lineStart,
+ lineStart,
+ lineEnd
+ };
+}
+__name(locate, "locate");
+
+// packages/cli/src/ui/core/prompt-undo-redo.ts
+init_esbuild_shims();
+function createPromptUndoRedoState() {
+ return { undoStack: [], redoStack: [] };
+}
+__name(createPromptUndoRedoState, "createPromptUndoRedoState");
+function recordPromptEdit(history, current, next, maxUndoEntries = 1e3) {
+ if (next.text === current.text || next.text === history.undoStack.at(-1)?.text) {
+ return;
+ }
+ history.undoStack.push(current);
+ if (history.undoStack.length > maxUndoEntries) {
+ history.undoStack = history.undoStack.slice(-maxUndoEntries);
+ }
+ history.redoStack = [];
+}
+__name(recordPromptEdit, "recordPromptEdit");
+function undoPromptEdit(history, current) {
+ const previous = history.undoStack.pop();
+ if (!previous) {
+ return null;
+ }
+ history.redoStack.push(current);
+ return previous;
+}
+__name(undoPromptEdit, "undoPromptEdit");
+function redoPromptEdit(history, current) {
+ const next = history.redoStack.pop();
+ if (!next) {
+ return null;
+ }
+ history.undoStack.push(current);
+ return next;
+}
+__name(redoPromptEdit, "redoPromptEdit");
+function clearPromptUndoRedoState(history) {
+ history.undoStack = [];
+ history.redoStack = [];
+}
+__name(clearPromptUndoRedoState, "clearPromptUndoRedoState");
+
+// packages/cli/src/ui/core/slash-commands.ts
+init_esbuild_shims();
+var BUILTIN_SLASH_COMMANDS = [
+ {
+ kind: "skills",
+ name: "skills",
+ label: "/skills",
+ description: "List available skills"
+ },
+ {
+ kind: "model",
+ name: "model",
+ label: "/model",
+ description: "Select model, thinking mode and effort control"
+ },
+ {
+ kind: "new",
+ name: "new",
+ label: "/new",
+ description: "Start a fresh conversation"
+ },
+ {
+ kind: "init",
+ name: "init",
+ label: "/init",
+ description: "Initialize an AGENTS.md file with instructions for LLM"
+ },
+ {
+ kind: "resume",
+ name: "resume",
+ label: "/resume",
+ description: "Pick a previous conversation to continue"
+ },
+ {
+ kind: "continue",
+ name: "continue",
+ label: "/continue",
+ description: "Continue the active conversation or pick one to resume"
+ },
+ {
+ kind: "undo",
+ name: "undo",
+ label: "/undo",
+ description: "Restore code and/or conversation to a previous point"
+ },
+ {
+ kind: "mcp",
+ name: "mcp",
+ label: "/mcp",
+ description: "Show MCP server status and available tools"
+ },
+ {
+ kind: "raw",
+ name: "raw",
+ label: "/raw",
+ args: ["lite", "normal", "raw-scrollback"],
+ description: "Toggle display mode for viewing or collapsing reasoning content"
+ },
+ {
+ kind: "compact",
+ name: "compact",
+ label: "/compact",
+ description: "Compress conversation context to reduce token usage"
+ },
+ {
+ kind: "context",
+ name: "context",
+ label: "/context",
+ description: "Show current conversation token usage and context stats"
+ },
+ {
+ kind: "exit",
+ name: "exit",
+ label: "/exit",
+ description: "Quit Deep Code CLI"
+ }
+];
+function buildSlashCommands(skills) {
+ const skillItems = skills.map((skill) => ({
+ kind: "skill",
+ name: skill.name,
+ label: `/${skill.name}`,
+ description: skill.description || "(no description)",
+ skill
+ }));
+ return [...skillItems, ...BUILTIN_SLASH_COMMANDS];
+}
+__name(buildSlashCommands, "buildSlashCommands");
+function filterSlashCommands(items, token) {
+ if (!token.startsWith("/")) {
+ return [];
+ }
+ const query = token.slice(1).toLowerCase();
+ if (!query) {
+ return items;
+ }
+ return items.filter((item) => item.name.toLowerCase().includes(query));
+}
+__name(filterSlashCommands, "filterSlashCommands");
+function findExactSlashCommand(items, token) {
+ if (!token.startsWith("/")) {
+ return null;
+ }
+ const query = token.slice(1);
+ const matches = items.filter((item) => item.name === query);
+ return matches.find((item) => item.kind !== "skill") ?? matches[0] ?? null;
+}
+__name(findExactSlashCommand, "findExactSlashCommand");
+function formatSlashCommandDescription(description) {
+ return (description || "(no description)").trim().replace(/\s+/g, " ");
+}
+__name(formatSlashCommandDescription, "formatSlashCommandDescription");
+function formatSlashCommandLabel(item) {
+ return item.kind === "skill" && item.skill?.isLoaded ? `${item.label} \u2713` : item.label;
+}
+__name(formatSlashCommandLabel, "formatSlashCommandLabel");
+
+// packages/cli/src/ui/core/file-mentions.ts
+init_esbuild_shims();
+var import_ignore2 = __toESM(require_ignore2(), 1);
+import * as fs19 from "fs";
+import * as path17 from "path";
+var DEFAULT_MAX_ITEMS = 2e4;
+var DEFAULT_MAX_DEPTH = 8;
+var DEFAULT_NOISY_DIR_NAMES = [
+ ".git",
+ ".next",
+ ".pytest_cache",
+ ".ruff_cache",
+ "__pycache__",
+ "build",
+ "dist",
+ "node_modules",
+ "out",
+ "target"
+];
+function scanFileMentionItems(root, maxItems = DEFAULT_MAX_ITEMS) {
+ const items = [];
+ const seen = /* @__PURE__ */ new Set();
+ const gitRoot = findGitRoot(root);
+ const visitedDirectories = /* @__PURE__ */ new Set();
+ function addItem(item) {
+ if (items.length >= maxItems || seen.has(item.path)) {
+ return;
+ }
+ seen.add(item.path);
+ items.push(item);
+ }
+ __name(addItem, "addItem");
+ function visit(directory, depth, matchers) {
+ if (items.length >= maxItems || depth > DEFAULT_MAX_DEPTH) {
+ return;
+ }
+ const currentMatchers = [...matchers, ...loadDirectoryIgnoreMatchers(directory, gitRoot)];
+ let entries;
+ try {
+ entries = fs19.readdirSync(directory, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ entries.sort((a, b) => {
+ if (a.isDirectory() !== b.isDirectory()) {
+ return a.isDirectory() ? -1 : 1;
+ }
+ return a.name.localeCompare(b.name);
+ });
+ for (const entry of entries) {
+ if (items.length >= maxItems) {
+ return;
+ }
+ if (entry.name === "." || entry.name === ".." || entry.name === ".git") {
+ continue;
+ }
+ const absolute = path17.join(directory, entry.name);
+ const relative5 = toMentionPath(path17.relative(root, absolute));
+ if (!relative5) {
+ continue;
+ }
+ const entryType = getMentionEntryType(entry, absolute);
+ if (!entryType) {
+ continue;
+ }
+ if (matchesAnyIgnore(absolute, entryType === "directory", currentMatchers)) {
+ continue;
+ }
+ if (entryType === "directory") {
+ const realPath = safeRealpath(absolute);
+ if (realPath) {
+ if (visitedDirectories.has(realPath)) {
+ continue;
+ }
+ visitedDirectories.add(realPath);
+ }
+ addItem({ path: `${relative5}/`, type: "directory" });
+ visit(absolute, depth + 1, currentMatchers);
+ continue;
+ }
+ if (entryType === "file") {
+ addItem({ path: relative5, type: "file" });
+ }
+ }
+ }
+ __name(visit, "visit");
+ const rootRealPath = safeRealpath(root);
+ if (rootRealPath) {
+ visitedDirectories.add(rootRealPath);
+ }
+ const initialMatchers = [...loadDefaultIgnoreMatchers(root, gitRoot), ...loadAncestorIgnoreMatchers(root, gitRoot)];
+ visit(root, 0, initialMatchers);
+ return items;
+}
+__name(scanFileMentionItems, "scanFileMentionItems");
+function getMentionEntryType(entry, absolute) {
+ if (entry.isDirectory()) {
+ return "directory";
+ }
+ if (entry.isFile()) {
+ return "file";
+ }
+ if (!entry.isSymbolicLink()) {
+ return null;
+ }
+ try {
+ const stat = fs19.statSync(absolute);
+ if (stat.isDirectory()) {
+ return "directory";
+ }
+ if (stat.isFile()) {
+ return "file";
+ }
+ } catch {
+ return null;
+ }
+ return null;
+}
+__name(getMentionEntryType, "getMentionEntryType");
+function safeRealpath(absolute) {
+ try {
+ return fs19.realpathSync(absolute);
+ } catch {
+ return null;
+ }
+}
+__name(safeRealpath, "safeRealpath");
+function loadDirectoryIgnoreMatchers(directory, gitRoot) {
+ const matchers = [];
+ if (gitRoot && isPathInsideOrEqual(directory, gitRoot)) {
+ const gitignoreMatcher = loadIgnoreFileMatcher(directory, path17.join(directory, ".gitignore"));
+ if (gitignoreMatcher) {
+ matchers.push(gitignoreMatcher);
+ }
+ if (path17.resolve(directory) === path17.resolve(gitRoot)) {
+ const gitExcludeMatcher = loadIgnoreFileMatcher(directory, path17.join(directory, ".git", "info", "exclude"));
+ if (gitExcludeMatcher) {
+ matchers.push(gitExcludeMatcher);
+ }
+ }
+ }
+ const ignoreMatcher = loadIgnoreFileMatcher(directory, path17.join(directory, ".ignore"));
+ if (ignoreMatcher) {
+ matchers.push(ignoreMatcher);
+ }
+ return matchers;
+}
+__name(loadDirectoryIgnoreMatchers, "loadDirectoryIgnoreMatchers");
+function loadDefaultIgnoreMatchers(root, gitRoot) {
+ if (hasApplicableGitignore(root, gitRoot)) {
+ return [];
+ }
+ const patterns = DEFAULT_NOISY_DIR_NAMES.map((name) => `${name}/`);
+ return [{ base: root, matcher: (0, import_ignore2.default)().add(patterns) }];
+}
+__name(loadDefaultIgnoreMatchers, "loadDefaultIgnoreMatchers");
+function hasApplicableGitignore(root, gitRoot) {
+ if (!gitRoot) {
+ return false;
+ }
+ const resolvedGitRoot = path17.resolve(gitRoot);
+ let current = path17.resolve(root);
+ while (isPathInsideOrEqual(current, resolvedGitRoot)) {
+ if (fs19.existsSync(path17.join(current, ".gitignore"))) {
+ return true;
+ }
+ if (current === resolvedGitRoot) {
+ break;
+ }
+ current = path17.dirname(current);
+ }
+ return false;
+}
+__name(hasApplicableGitignore, "hasApplicableGitignore");
+function loadAncestorIgnoreMatchers(root, gitRoot) {
+ const resolvedRoot = path17.resolve(root);
+ const ancestors = [];
+ let current = path17.dirname(resolvedRoot);
+ while (gitRoot && isPathInsideOrEqual(current, gitRoot)) {
+ ancestors.push(current);
+ if (path17.resolve(current) === path17.resolve(gitRoot)) {
+ break;
+ }
+ current = path17.dirname(current);
+ }
+ return ancestors.reverse().flatMap((directory) => loadDirectoryIgnoreMatchers(directory, gitRoot));
+}
+__name(loadAncestorIgnoreMatchers, "loadAncestorIgnoreMatchers");
+function loadIgnoreFileMatcher(base, ignoreFilePath) {
+ try {
+ if (!fs19.existsSync(ignoreFilePath)) {
+ return null;
+ }
+ const content = fs19.readFileSync(ignoreFilePath, "utf8");
+ if (!content.trim()) {
+ return null;
+ }
+ return { base, matcher: (0, import_ignore2.default)().add(content) };
+ } catch {
+ return null;
+ }
+}
+__name(loadIgnoreFileMatcher, "loadIgnoreFileMatcher");
+function matchesAnyIgnore(absolute, isDir, matchers) {
+ let ignored = false;
+ for (const { base, matcher } of matchers) {
+ const relative5 = toMentionPath(path17.relative(base, absolute));
+ if (!relative5 || relative5.startsWith("../")) {
+ continue;
+ }
+ const result = matcher.test(isDir ? `${relative5}/` : relative5);
+ if (result.ignored) {
+ ignored = true;
+ }
+ if (result.unignored) {
+ ignored = false;
+ }
+ }
+ return ignored;
+}
+__name(matchesAnyIgnore, "matchesAnyIgnore");
+function findGitRoot(start) {
+ let current = path17.resolve(start);
+ while (true) {
+ if (fs19.existsSync(path17.join(current, ".git"))) {
+ return current;
+ }
+ const parent = path17.dirname(current);
+ if (parent === current) {
+ return null;
+ }
+ current = parent;
+ }
+}
+__name(findGitRoot, "findGitRoot");
+function isPathInsideOrEqual(candidate, parent) {
+ const relative5 = path17.relative(parent, candidate);
+ return relative5 === "" || !relative5.startsWith("..") && !path17.isAbsolute(relative5);
+}
+__name(isPathInsideOrEqual, "isPathInsideOrEqual");
+function filterFileMentionItems(items, query, maxResults = 12) {
+ const normalizedQuery = normalizeForSearch(query);
+ const scored = items.map((item, index) => ({ item, index, score: scoreFileMention(item.path, normalizedQuery) })).filter((entry) => entry.score !== Number.POSITIVE_INFINITY).sort((a, b) => a.score - b.score || a.item.path.length - b.item.path.length || a.index - b.index);
+ return scored.slice(0, maxResults).map((entry) => entry.item);
+}
+__name(filterFileMentionItems, "filterFileMentionItems");
+function getCurrentFileMentionToken(state) {
+ const text = state.text;
+ const cursor = clampCursorToBoundary(text, state.cursor);
+ const quoted = getCurrentQuotedFileMentionToken(text, cursor);
+ if (quoted) {
+ return quoted;
+ }
+ return getCurrentBareFileMentionToken(text, cursor);
+}
+__name(getCurrentFileMentionToken, "getCurrentFileMentionToken");
+function replaceCurrentFileMentionToken(state, token, selectedPath) {
+ const inserted = `${formatFileMentionPath(selectedPath)} `;
+ const end = token.end < state.text.length && isWhitespace(state.text[token.end] ?? "") ? token.end + 1 : token.end;
+ const text = `${state.text.slice(0, token.start)}${inserted}${state.text.slice(end)}`;
+ return { text, cursor: token.start + inserted.length };
+}
+__name(replaceCurrentFileMentionToken, "replaceCurrentFileMentionToken");
+function formatFileMentionPath(filePath) {
+ if (!/[\s"]/.test(filePath)) {
+ return `@${filePath}`;
+ }
+ return `@"${filePath.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
+}
+__name(formatFileMentionPath, "formatFileMentionPath");
+function getCurrentBareFileMentionToken(text, cursor) {
+ const beforeCursor = text.slice(0, cursor);
+ const afterCursor = text.slice(cursor);
+ const start = findTokenStart(beforeCursor);
+ const end = cursor + findTokenEnd(afterCursor);
+ const token = text.slice(start, end);
+ if (!token.startsWith("@") || token.startsWith('@"')) {
+ return null;
+ }
+ if (start > 0 && !isWhitespace(text[start - 1] ?? "")) {
+ return null;
+ }
+ return { query: token.slice(1), start, end, quoted: false };
+}
+__name(getCurrentBareFileMentionToken, "getCurrentBareFileMentionToken");
+function getCurrentQuotedFileMentionToken(text, cursor) {
+ for (let index = cursor; index >= 0; index--) {
+ if (text[index] !== "@" || text[index + 1] !== '"') {
+ continue;
+ }
+ if (index > 0 && !isWhitespace(text[index - 1] ?? "")) {
+ continue;
+ }
+ const closeQuote = findClosingQuote(text, index + 2);
+ if (closeQuote !== -1 && cursor > closeQuote) {
+ continue;
+ }
+ const end = closeQuote === -1 ? cursor : closeQuote + 1;
+ return {
+ query: unescapeQuotedMentionQuery(
+ text.slice(index + 2, Math.min(cursor, closeQuote === -1 ? cursor : closeQuote))
+ ),
+ start: index,
+ end,
+ quoted: true
+ };
+ }
+ return null;
+}
+__name(getCurrentQuotedFileMentionToken, "getCurrentQuotedFileMentionToken");
+function findTokenStart(beforeCursor) {
+ const whitespaceIndex = findLastWhitespaceIndex(beforeCursor);
+ return whitespaceIndex === -1 ? 0 : whitespaceIndex + 1;
+}
+__name(findTokenStart, "findTokenStart");
+function findTokenEnd(afterCursor) {
+ const whitespaceIndex = afterCursor.search(/\s/);
+ return whitespaceIndex === -1 ? afterCursor.length : whitespaceIndex;
+}
+__name(findTokenEnd, "findTokenEnd");
+function findLastWhitespaceIndex(value) {
+ for (let index = value.length - 1; index >= 0; index--) {
+ if (isWhitespace(value[index] ?? "")) {
+ return index;
+ }
+ }
+ return -1;
+}
+__name(findLastWhitespaceIndex, "findLastWhitespaceIndex");
+function findClosingQuote(text, start) {
+ let escaped = false;
+ for (let index = start; index < text.length; index++) {
+ const char = text[index];
+ if (escaped) {
+ escaped = false;
+ continue;
+ }
+ if (char === "\\") {
+ escaped = true;
+ continue;
+ }
+ if (char === '"') {
+ return index;
+ }
+ }
+ return -1;
+}
+__name(findClosingQuote, "findClosingQuote");
+function unescapeQuotedMentionQuery(query) {
+ return query.replace(/\\(["\\])/g, "$1");
+}
+__name(unescapeQuotedMentionQuery, "unescapeQuotedMentionQuery");
+function clampCursorToBoundary(text, cursor) {
+ return Math.max(0, Math.min(cursor, text.length));
+}
+__name(clampCursorToBoundary, "clampCursorToBoundary");
+function scoreFileMention(itemPath, normalizedQuery) {
+ if (!normalizedQuery) {
+ return itemPath.endsWith("/") ? 5 : 10;
+ }
+ const normalizedPath = normalizeForSearch(itemPath);
+ const normalizedBase = normalizeForSearch(path17.posix.basename(itemPath.replace(/\/$/, "")));
+ if (normalizedPath === normalizedQuery) {
+ return 0;
+ }
+ if (normalizedPath.startsWith(normalizedQuery)) {
+ return 1;
+ }
+ if (normalizedBase.startsWith(normalizedQuery)) {
+ return isQueryBoundary(normalizedBase[normalizedQuery.length] ?? "") ? 2 : 3;
+ }
+ const pathIndex = normalizedPath.indexOf(normalizedQuery);
+ if (pathIndex !== -1) {
+ return 20 + pathIndex;
+ }
+ const fuzzyScore = fuzzyMatchScore(normalizedPath, normalizedQuery);
+ return fuzzyScore === null ? Number.POSITIVE_INFINITY : 100 + fuzzyScore;
+}
+__name(scoreFileMention, "scoreFileMention");
+function fuzzyMatchScore(value, query) {
+ let valueIndex = 0;
+ let score = 0;
+ for (const char of query) {
+ const nextIndex = value.indexOf(char, valueIndex);
+ if (nextIndex === -1) {
+ return null;
+ }
+ score += nextIndex - valueIndex;
+ valueIndex = nextIndex + 1;
+ }
+ return score;
+}
+__name(fuzzyMatchScore, "fuzzyMatchScore");
+function normalizeForSearch(value) {
+ return value.trim().toLocaleLowerCase();
+}
+__name(normalizeForSearch, "normalizeForSearch");
+function isQueryBoundary(value) {
+ return value === "" || /[\s._/-]/.test(value);
+}
+__name(isQueryBoundary, "isQueryBoundary");
+function toMentionPath(value) {
+ return value.split(path17.sep).join("/");
+}
+__name(toMentionPath, "toMentionPath");
+function isWhitespace(value) {
+ return /\s/.test(value);
+}
+__name(isWhitespace, "isWhitespace");
+
+// packages/cli/src/ui/core/clipboard.ts
+init_esbuild_shims();
+import { spawnSync as spawnSync3 } from "child_process";
+import * as fs20 from "fs";
+import * as os12 from "os";
+import * as path18 from "path";
+var PNG_MIME = "image/png";
+var IMAGE_MIME_BY_EXT = /* @__PURE__ */ new Map([
+ [".png", "image/png"],
+ [".jpg", "image/jpeg"],
+ [".jpeg", "image/jpeg"],
+ [".gif", "image/gif"],
+ [".webp", "image/webp"]
+]);
+function bufferToDataUrl(buffer, mimeType) {
+ return `data:${mimeType};base64,${buffer.toString("base64")}`;
+}
+__name(bufferToDataUrl, "bufferToDataUrl");
+function isImageFilePath(value) {
+ return IMAGE_MIME_BY_EXT.has(path18.extname(value.trim()).toLowerCase());
+}
+__name(isImageFilePath, "isImageFilePath");
+function mimeTypeForPath(value) {
+ return IMAGE_MIME_BY_EXT.get(path18.extname(value.trim()).toLowerCase()) ?? PNG_MIME;
+}
+__name(mimeTypeForPath, "mimeTypeForPath");
+function tryRun(command2, args) {
+ try {
+ const result = spawnSync3(command2, args, { encoding: "buffer", maxBuffer: 32 * 1024 * 1024 });
+ if (result.status !== 0 || !result.stdout || result.stdout.length === 0) {
+ return null;
+ }
+ return result.stdout;
+ } catch {
+ return null;
+ }
+}
+__name(tryRun, "tryRun");
+function tryRunStatus(command2, args) {
+ try {
+ const result = spawnSync3(command2, args, { encoding: "buffer", maxBuffer: 32 * 1024 * 1024 });
+ return result.status === 0;
+ } catch {
+ return false;
+ }
+}
+__name(tryRunStatus, "tryRunStatus");
+function readImageFile(filePath) {
+ try {
+ if (!isImageFilePath(filePath)) {
+ return null;
+ }
+ const buffer = fs20.readFileSync(filePath);
+ if (buffer.length === 0) {
+ return null;
+ }
+ const mimeType = mimeTypeForPath(filePath);
+ return { dataUrl: bufferToDataUrl(buffer, mimeType), mimeType };
+ } catch {
+ return null;
+ }
+}
+__name(readImageFile, "readImageFile");
+function readMacClipboardImage() {
+ const pngpaste = tryRun("pngpaste", ["-"]);
+ if (pngpaste && pngpaste.length > 0) {
+ return { dataUrl: bufferToDataUrl(pngpaste, PNG_MIME), mimeType: PNG_MIME };
+ }
+ const tempDir = fs20.mkdtempSync(path18.join(os12.tmpdir(), "deepcode-clipboard-"));
+ const screenshotPath = path18.join(tempDir, "clipboard.png");
+ try {
+ const saved = tryRunStatus("osascript", [
+ "-e",
+ "set png_data to (the clipboard as \xABclass PNGf\xBB)",
+ "-e",
+ `set fp to open for access POSIX file "${screenshotPath}" with write permission`,
+ "-e",
+ "write png_data to fp",
+ "-e",
+ "close access fp"
+ ]);
+ if (saved) {
+ const image2 = readImageFile(screenshotPath);
+ if (image2) {
+ return image2;
+ }
+ }
+ const fileUrl = tryRun("osascript", ["-e", "get POSIX path of (the clipboard as \xABclass furl\xBB)"]);
+ const filePath = fileUrl?.toString("utf8").trim();
+ if (filePath) {
+ return readImageFile(filePath);
+ }
+ return null;
+ } finally {
+ try {
+ fs20.rmSync(tempDir, { recursive: true, force: true });
+ } catch {
+ }
+ }
+}
+__name(readMacClipboardImage, "readMacClipboardImage");
+function readClipboardImage() {
+ if (process.platform === "darwin") {
+ return readMacClipboardImage();
+ }
+ if (process.platform === "linux") {
+ const xclip = tryRun("xclip", ["-selection", "clipboard", "-t", "image/png", "-o"]);
+ if (xclip && xclip.length > 0) {
+ return { dataUrl: bufferToDataUrl(xclip, PNG_MIME), mimeType: PNG_MIME };
+ }
+ const wlPaste = tryRun("wl-paste", ["--type", "image/png"]);
+ if (wlPaste && wlPaste.length > 0) {
+ return { dataUrl: bufferToDataUrl(wlPaste, PNG_MIME), mimeType: PNG_MIME };
+ }
+ return null;
+ }
+ if (process.platform === "win32") {
+ const script = "Add-Type -AssemblyName System.Windows.Forms;$img = [System.Windows.Forms.Clipboard]::GetImage();if ($img) { $ms = New-Object System.IO.MemoryStream;$img.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png);[Console]::OpenStandardOutput().Write($ms.ToArray(), 0, $ms.Length); }";
+ const out = tryRun("powershell", ["-NoProfile", "-Command", script]);
+ if (out && out.length > 0) {
+ return { dataUrl: bufferToDataUrl(out, PNG_MIME), mimeType: PNG_MIME };
+ }
+ return null;
+ }
+ return null;
+}
+__name(readClipboardImage, "readClipboardImage");
+async function readClipboardImageAsync() {
+ return new Promise((resolve16, reject) => {
+ setImmediate(() => {
+ try {
+ const result = readClipboardImage();
+ resolve16(result);
+ } catch (error51) {
+ reject(error51);
+ }
+ });
+ });
+}
+__name(readClipboardImageAsync, "readClipboardImageAsync");
+
+// packages/cli/src/ui/hooks/index.ts
+init_esbuild_shims();
+
+// packages/cli/src/ui/hooks/useTerminalInput.ts
+init_esbuild_shims();
+var import_react39 = __toESM(require_react(), 1);
+var BACKSPACE_BYTES = /* @__PURE__ */ new Set(["\x7F", "\b"]);
+var FORWARD_DELETE_SEQUENCES = /* @__PURE__ */ new Set(["\x1B[3~", "\x1B[P"]);
+var HOME_SEQUENCES = /* @__PURE__ */ new Set(["\x1B[H", "\x1B[1~", "\x1B[7~", "\x1BOH"]);
+var END_SEQUENCES = /* @__PURE__ */ new Set(["\x1B[F", "\x1B[4~", "\x1B[8~", "\x1BOF"]);
+var SHIFT_RETURN_SEQUENCES = /* @__PURE__ */ new Set(["\x1B\r", "\x1B[13;2u", "\x1B[13;2~", "\x1B[27;2;13~"]);
+var META_RETURN_SEQUENCES = /* @__PURE__ */ new Set(["\x1B[13;3u", "\x1B[13;4u"]);
+var CTRL_LEFT_SEQUENCES = /* @__PURE__ */ new Set(["\x1B[1;5D", "\x1B[5D"]);
+var CTRL_RIGHT_SEQUENCES = /* @__PURE__ */ new Set(["\x1B[1;5C", "\x1B[5C"]);
+var META_LEFT_SEQUENCES = /* @__PURE__ */ new Set(["\x1B[1;3D", "\x1B[3D", "\x1Bb"]);
+var META_RIGHT_SEQUENCES = /* @__PURE__ */ new Set(["\x1B[1;3C", "\x1B[3C", "\x1Bf"]);
+var TERMINAL_FOCUS_IN = "\x1B[I";
+var TERMINAL_FOCUS_OUT = "\x1B[O";
+var PASTE_START = "\x1B[200~";
+var PASTE_END = "\x1B[201~";
+var PASTE_END_LENGTH = 6;
+var CTRL_MINUS_SEQUENCES = /* @__PURE__ */ new Set(["\x1B[45;5u", "\x1B[27;5;45~"]);
+var CTRL_SHIFT_MINUS_SEQUENCES = /* @__PURE__ */ new Set(["\x1B[45;6u", "\x1B[27;6;45~"]);
+function parseTerminalInput(data) {
+ const raw = String(data);
+ let input = raw;
+ if (CTRL_MINUS_SEQUENCES.has(raw)) {
+ input = "-";
+ const key2 = {
+ upArrow: false,
+ downArrow: false,
+ leftArrow: false,
+ rightArrow: false,
+ home: false,
+ end: false,
+ pageDown: false,
+ pageUp: false,
+ return: false,
+ escape: false,
+ ctrl: true,
+ shift: false,
+ tab: false,
+ backspace: false,
+ delete: false,
+ meta: false,
+ focusIn: false,
+ focusOut: false,
+ paste: false
+ };
+ return { input, key: key2 };
+ }
+ if (CTRL_SHIFT_MINUS_SEQUENCES.has(raw) || raw === "") {
+ input = "-";
+ const key2 = {
+ upArrow: false,
+ downArrow: false,
+ leftArrow: false,
+ rightArrow: false,
+ home: false,
+ end: false,
+ pageDown: false,
+ pageUp: false,
+ return: false,
+ escape: false,
+ ctrl: true,
+ shift: true,
+ tab: false,
+ backspace: false,
+ delete: false,
+ meta: false,
+ focusIn: false,
+ focusOut: false,
+ paste: false
+ };
+ return { input, key: key2 };
+ }
+ const key = {
+ upArrow: raw === "\x1B[A",
+ downArrow: raw === "\x1B[B",
+ leftArrow: raw === "\x1B[D" || CTRL_LEFT_SEQUENCES.has(raw) || META_LEFT_SEQUENCES.has(raw),
+ rightArrow: raw === "\x1B[C" || CTRL_RIGHT_SEQUENCES.has(raw) || META_RIGHT_SEQUENCES.has(raw),
+ home: HOME_SEQUENCES.has(raw),
+ end: END_SEQUENCES.has(raw),
+ pageDown: raw === "\x1B[6~",
+ pageUp: raw === "\x1B[5~",
+ return: raw === "\r" || SHIFT_RETURN_SEQUENCES.has(raw) || META_RETURN_SEQUENCES.has(raw),
+ escape: raw === "\x1B",
+ ctrl: CTRL_LEFT_SEQUENCES.has(raw) || CTRL_RIGHT_SEQUENCES.has(raw),
+ shift: SHIFT_RETURN_SEQUENCES.has(raw),
+ tab: raw === " " || raw === "\x1B[Z",
+ backspace: BACKSPACE_BYTES.has(raw),
+ delete: FORWARD_DELETE_SEQUENCES.has(raw),
+ meta: META_LEFT_SEQUENCES.has(raw) || META_RIGHT_SEQUENCES.has(raw) || META_RETURN_SEQUENCES.has(raw),
+ focusIn: raw === TERMINAL_FOCUS_IN,
+ focusOut: raw === TERMINAL_FOCUS_OUT,
+ paste: false
+ };
+ if (input <= "" && !key.return) {
+ input = String.fromCharCode(input.charCodeAt(0) + "a".charCodeAt(0) - 1);
+ key.ctrl = true;
+ }
+ const isKnownEscapeSequence = key.upArrow || key.downArrow || key.leftArrow || key.rightArrow || key.home || key.end || key.pageDown || key.pageUp || key.tab || key.delete || key.return || key.ctrl || key.meta || key.focusIn || key.focusOut;
+ if (raw.startsWith("\x1B")) {
+ input = raw.slice(1);
+ key.meta = key.meta || !isKnownEscapeSequence;
+ }
+ const isLatinUppercase = input >= "A" && input <= "Z";
+ const isCyrillicUppercase = input >= "\u0410" && input <= "\u042F";
+ if (input.length === 1 && (isLatinUppercase || isCyrillicUppercase)) {
+ key.shift = true;
+ }
+ if (key.tab && input === "[Z") {
+ key.shift = true;
+ }
+ if (key.tab || key.backspace || key.delete) {
+ input = "";
+ }
+ return { input, key };
+}
+__name(parseTerminalInput, "parseTerminalInput");
+function dispatchTerminalInput(data, inputHandler) {
+ const raw = String(data);
+ if (!raw.startsWith("\x1B") && raw.includes("\x7F") && raw.length > 1) {
+ const parts = raw.split("\x7F");
+ if (parts[0]) {
+ const { input: input2, key: key2 } = parseTerminalInput(parts[0]);
+ inputHandler(input2, key2);
+ }
+ for (let i = 1; i < parts.length; i++) {
+ const bs = parseTerminalInput("\x7F");
+ inputHandler(bs.input, bs.key);
+ if (parts[i]) {
+ const { input: input2, key: key2 } = parseTerminalInput(parts[i]);
+ inputHandler(input2, key2);
+ }
+ }
+ return;
+ }
+ const { input, key } = parseTerminalInput(data);
+ inputHandler(input, key);
+}
+__name(dispatchTerminalInput, "dispatchTerminalInput");
+var EMPTY_KEY = {
+ upArrow: false,
+ downArrow: false,
+ leftArrow: false,
+ rightArrow: false,
+ home: false,
+ end: false,
+ pageDown: false,
+ pageUp: false,
+ return: false,
+ escape: false,
+ ctrl: false,
+ shift: false,
+ tab: false,
+ backspace: false,
+ delete: false,
+ meta: false,
+ focusIn: false,
+ focusOut: false,
+ paste: false
+};
+function useTerminalInput(inputHandler, options2 = {}) {
+ const { stdin, setRawMode } = use_stdin_default();
+ const isActive = options2.isActive ?? true;
+ const handlerRef = (0, import_react39.useRef)(inputHandler);
+ handlerRef.current = inputHandler;
+ const pasteRef = (0, import_react39.useRef)({ active: false, chunks: [] });
+ (0, import_react39.useLayoutEffect)(() => {
+ if (!isActive) {
+ pasteRef.current.active = false;
+ pasteRef.current.chunks = [];
+ return;
+ }
+ setRawMode(true);
+ return () => {
+ setRawMode(false);
+ };
+ }, [isActive, setRawMode]);
+ (0, import_react39.useLayoutEffect)(() => {
+ if (!isActive) {
+ return;
+ }
+ const handleData = /* @__PURE__ */ __name((data) => {
+ const raw = String(data);
+ if (raw.includes(PASTE_START)) {
+ pasteRef.current.active = true;
+ pasteRef.current.chunks = [];
+ const startIdx = raw.indexOf(PASTE_START);
+ const afterStart = raw.slice(startIdx + PASTE_START.length);
+ const endIdx = afterStart.indexOf(PASTE_END);
+ if (endIdx !== -1) {
+ const pasteContent = afterStart.slice(0, endIdx);
+ pasteRef.current.active = false;
+ const remaining = afterStart.slice(endIdx + PASTE_END_LENGTH);
+ if (pasteContent.length > 0) {
+ handlerRef.current(pasteContent, { ...EMPTY_KEY, paste: true });
+ }
+ if (remaining.length > 0) {
+ dispatchTerminalInput(remaining, handlerRef.current);
+ }
+ return;
+ }
+ if (afterStart) {
+ pasteRef.current.chunks.push(afterStart);
+ }
+ return;
+ }
+ if (pasteRef.current.active) {
+ pasteRef.current.chunks.push(raw);
+ if (raw.includes("201~")) {
+ const combined = pasteRef.current.chunks.join("");
+ const endIdx = combined.indexOf(PASTE_END);
+ if (endIdx !== -1) {
+ const pasteContent = combined.slice(0, endIdx);
+ pasteRef.current.active = false;
+ const remaining = combined.slice(endIdx + PASTE_END_LENGTH);
+ pasteRef.current.chunks = [];
+ if (pasteContent.length > 0) {
+ handlerRef.current(pasteContent, { ...EMPTY_KEY, paste: true });
+ }
+ if (remaining.length > 0) {
+ dispatchTerminalInput(remaining, handlerRef.current);
+ }
+ return;
+ }
+ return;
+ }
+ return;
+ }
+ dispatchTerminalInput(data, handlerRef.current);
+ }, "handleData");
+ stdin?.on("data", handleData);
+ return () => {
+ stdin?.off("data", handleData);
+ };
+ }, [isActive, stdin]);
+}
+__name(useTerminalInput, "useTerminalInput");
+
+// packages/cli/src/ui/hooks/usePasteHandling.ts
+init_esbuild_shims();
+var import_react40 = __toESM(require_react(), 1);
+function usePasteHandling(buffer, updateBuffer, setStatusMessage) {
+ const pastesRef = (0, import_react40.useRef)(/* @__PURE__ */ new Map());
+ const pasteCounterRef = (0, import_react40.useRef)(0);
+ const expandedRegionsRef = (0, import_react40.useRef)(/* @__PURE__ */ new Map());
+ const [hasCollapsedMarkers, setHasCollapsedMarkers] = (0, import_react40.useState)(false);
+ const [hasExpandedRegions, setHasExpandedRegions] = (0, import_react40.useState)(false);
+ function refreshDerivedFlags() {
+ setHasCollapsedMarkers(hasActivePasteMarkers(buffer.text, pastesRef.current));
+ setHasExpandedRegions(expandedRegionsRef.current.size > 0);
+ }
+ __name(refreshDerivedFlags, "refreshDerivedFlags");
+ (0, import_react40.useEffect)(() => {
+ refreshDerivedFlags();
+ }, [buffer.text]);
+ function handlePaste(pastedText) {
+ const totalChars = pastedText.length;
+ if (totalChars <= 1e3) {
+ const newlineCount = (pastedText.match(/\n/g) ?? []).length;
+ if (newlineCount <= 9) {
+ const clean = pastedText.replace(/\r\n|\r/g, "\n").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, "").replace(/\t/g, " ");
+ updateBuffer((s) => insertText(s, clean));
+ return;
+ }
+ }
+ const lineCount = (pastedText.match(/\n/g) ?? []).length + 1;
+ pasteCounterRef.current += 1;
+ const pasteId = pasteCounterRef.current;
+ pastesRef.current.set(pasteId, pastedText);
+ const marker = lineCount > 10 ? `[paste #${pasteId} +${lineCount} lines]` : `[paste #${pasteId} ${totalChars} chars]`;
+ updateBuffer((s) => insertText(s, marker));
+ refreshDerivedFlags();
+ }
+ __name(handlePaste, "handlePaste");
+ function expandPasteMarkerAtCursor() {
+ for (const [id, region] of expandedRegionsRef.current) {
+ if (buffer.cursor >= region.start && buffer.cursor <= region.end) {
+ expandedRegionsRef.current.delete(id);
+ pastesRef.current.set(id, region.content);
+ setTimeout(() => {
+ updateBuffer((s) => {
+ const text = s.text.slice(0, region.start) + region.marker + s.text.slice(region.end);
+ return { text, cursor: region.start + region.marker.length };
+ });
+ refreshDerivedFlags();
+ }, 0);
+ refreshDerivedFlags();
+ return;
+ }
+ }
+ const marker = findPasteMarkerContaining(buffer);
+ if (!marker) {
+ setStatusMessage("No paste marker at cursor");
+ return;
+ }
+ const content = pastesRef.current.get(marker.id);
+ if (!content) {
+ setStatusMessage("Paste content not found");
+ return;
+ }
+ const pasteId = marker.id;
+ const originalMarker = buffer.text.slice(marker.start, marker.end);
+ pastesRef.current.delete(pasteId);
+ setTimeout(() => {
+ updateBuffer((s) => {
+ const text = s.text.slice(0, marker.start) + cleanPasteContent(content) + s.text.slice(marker.end);
+ const newEnd = marker.start + content.length;
+ expandedRegionsRef.current.set(pasteId, {
+ start: marker.start,
+ end: newEnd,
+ content,
+ marker: originalMarker
+ });
+ return { text, cursor: marker.start };
+ });
+ refreshDerivedFlags();
+ }, 0);
+ refreshDerivedFlags();
+ }
+ __name(expandPasteMarkerAtCursor, "expandPasteMarkerAtCursor");
+ function resetPastes() {
+ pastesRef.current.clear();
+ expandedRegionsRef.current.clear();
+ pasteCounterRef.current = 0;
+ refreshDerivedFlags();
+ }
+ __name(resetPastes, "resetPastes");
+ return {
+ pastesRef,
+ expandedRegionsRef,
+ pasteCounterRef,
+ hasCollapsedMarkers,
+ hasExpandedRegions,
+ handlePaste,
+ expandPasteMarkerAtCursor,
+ resetPastes
+ };
+}
+__name(usePasteHandling, "usePasteHandling");
+
+// packages/cli/src/ui/hooks/useHistoryNavigation.ts
+init_esbuild_shims();
+var import_react41 = __toESM(require_react(), 1);
+function useHistoryNavigation(buffer, setBuffer, promptHistory) {
+ const [historyCursor, setHistoryCursor] = (0, import_react41.useState)(-1);
+ const [draftBeforeHistory, setDraftBeforeHistory] = (0, import_react41.useState)(null);
+ const exitHistoryBrowsing = (0, import_react41.useCallback)(() => {
+ setHistoryCursor(-1);
+ setDraftBeforeHistory(null);
+ }, []);
+ function navigateHistory(direction) {
+ if (promptHistory.length === 0) {
+ return;
+ }
+ const previousCursor = historyCursor === -1 ? promptHistory.length : historyCursor;
+ const nextCursor = Math.max(0, Math.min(promptHistory.length, previousCursor + direction));
+ const draft = historyCursor === -1 ? buffer.text : draftBeforeHistory;
+ if (historyCursor === -1) {
+ setDraftBeforeHistory(buffer.text);
+ }
+ if (nextCursor === promptHistory.length) {
+ const text2 = draft ?? "";
+ setBuffer({ text: text2, cursor: text2.length });
+ setHistoryCursor(-1);
+ setDraftBeforeHistory(null);
+ return;
+ }
+ const text = promptHistory[nextCursor] ?? "";
+ setBuffer({ text, cursor: text.length });
+ setHistoryCursor(nextCursor);
+ }
+ __name(navigateHistory, "navigateHistory");
+ return {
+ historyCursor,
+ draftBeforeHistory,
+ navigateHistory,
+ exitHistoryBrowsing
+ };
+}
+__name(useHistoryNavigation, "useHistoryNavigation");
+
+// packages/cli/src/ui/hooks/useStatusLine.ts
+init_esbuild_shims();
+var import_react42 = __toESM(require_react(), 1);
+
+// packages/cli/src/ui/statusline/index.ts
+init_esbuild_shims();
+
+// packages/cli/src/ui/statusline/manager.ts
+init_esbuild_shims();
+
+// packages/cli/src/ui/statusline/sanitize.ts
+init_esbuild_shims();
+var STATUS_SEGMENT_MAX_LENGTH = 40;
+var ANSI_PATTERN = /\x1B\[[0-?]*[ -/]*[@-~]/g;
+function sanitizeStatusText(value, maxLength = STATUS_SEGMENT_MAX_LENGTH) {
+ if (value === null || value === void 0) {
+ return "";
+ }
+ const text = typeof value === "string" ? value : String(value);
+ if (!text) {
+ return "";
+ }
+ const firstLine = text.split(/\r?\n/).find((line) => line.trim().length > 0) ?? "";
+ const stripped = firstLine.replace(ANSI_PATTERN, "");
+ const collapsed = stripped.replace(/\s+/g, " ").trim();
+ if (collapsed.length <= maxLength) {
+ return collapsed;
+ }
+ return collapsed.slice(0, Math.max(1, maxLength - 1)) + "\u2026";
+}
+__name(sanitizeStatusText, "sanitizeStatusText");
+
+// packages/cli/src/ui/statusline/command-provider.ts
+init_esbuild_shims();
+import { spawn as spawn5 } from "child_process";
+import * as path19 from "path";
+var DEFAULT_TIMEOUT_MS = 1500;
+var MIN_TIMEOUT_MS = 100;
+var MAX_OUTPUT_BYTES = 4096;
+function resolveTimeout(value) {
+ if (typeof value !== "number" || !Number.isFinite(value) || value < MIN_TIMEOUT_MS) {
+ return DEFAULT_TIMEOUT_MS;
+ }
+ return Math.floor(value);
+}
+__name(resolveTimeout, "resolveTimeout");
+function resolveCwd(configCwd, projectRoot) {
+ if (!configCwd) {
+ return projectRoot;
+ }
+ return path19.isAbsolute(configCwd) ? configCwd : path19.resolve(projectRoot, configCwd);
+}
+__name(resolveCwd, "resolveCwd");
+function createCommandStatusProvider(config2, projectRoot, id) {
+ const timeoutMs = resolveTimeout(config2.timeoutMs);
+ const cwd2 = resolveCwd(config2.cwd, projectRoot);
+ return {
+ id,
+ color: config2.color,
+ newLine: config2.newLine,
+ maxLength: config2.maxLength,
+ fetch: /* @__PURE__ */ __name(({ signal }) => new Promise((resolve16) => {
+ if (signal.aborted) {
+ resolve16("");
+ return;
+ }
+ const isWindows3 = process.platform === "win32";
+ const child = spawn5(config2.command, {
+ cwd: cwd2,
+ shell: isWindows3 ? true : "/bin/sh",
+ windowsHide: true,
+ stdio: ["ignore", "pipe", "pipe"]
+ });
+ let stdout = "";
+ let stdoutBytes = 0;
+ let settled = false;
+ const finish = /* @__PURE__ */ __name((value) => {
+ if (settled) {
+ return;
+ }
+ settled = true;
+ cleanup();
+ if (!child.killed) {
+ child.kill();
+ }
+ resolve16(value);
+ }, "finish");
+ const onAbort = /* @__PURE__ */ __name(() => finish(""), "onAbort");
+ signal.addEventListener("abort", onAbort, { once: true });
+ const timer = setTimeout(() => finish(""), timeoutMs);
+ const cleanup = /* @__PURE__ */ __name(() => {
+ clearTimeout(timer);
+ signal.removeEventListener("abort", onAbort);
+ }, "cleanup");
+ child.stdout?.on("data", (chunk) => {
+ if (settled) {
+ return;
+ }
+ const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
+ if (stdoutBytes >= MAX_OUTPUT_BYTES) {
+ return;
+ }
+ const remaining = MAX_OUTPUT_BYTES - stdoutBytes;
+ const slice = text.length > remaining ? text.slice(0, remaining) : text;
+ stdout += slice;
+ stdoutBytes += slice.length;
+ });
+ child.stderr?.on("data", () => void 0);
+ child.on("error", () => finish(""));
+ child.on("close", () => finish(stdout));
+ }), "fetch")
+ };
+}
+__name(createCommandStatusProvider, "createCommandStatusProvider");
+
+// packages/cli/src/ui/statusline/module-provider.ts
+init_esbuild_shims();
+import * as path20 from "path";
+var DEFAULT_TIMEOUT_MS2 = 2e3;
+function validateModulePath(modulePath, projectRoot) {
+ const resolved = path20.isAbsolute(modulePath) ? modulePath : path20.resolve(projectRoot, modulePath);
+ const normalized = path20.normalize(resolved);
+ const homeDir = process.env.HOME || process.env.USERPROFILE || "";
+ const allowedBases = [projectRoot];
+ if (homeDir) {
+ allowedBases.push(homeDir);
+ }
+ for (const base of allowedBases) {
+ const normalizedBase = path20.normalize(base);
+ if (normalized.startsWith(normalizedBase + path20.sep) || normalized === normalizedBase) {
+ return normalized;
+ }
+ }
+ return null;
+}
+__name(validateModulePath, "validateModulePath");
+async function loadModuleProvider(resolvedPath, color, id, timeoutMs, maxLength) {
+ try {
+ const timeout = typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs >= 100 ? Math.floor(timeoutMs) : DEFAULT_TIMEOUT_MS2;
+ let mod;
+ try {
+ mod = await import(resolvedPath);
+ } catch {
+ const fileUrl = path20.isAbsolute(resolvedPath) ? `file://${resolvedPath}` : resolvedPath;
+ mod = await import(fileUrl);
+ }
+ const providerFn = mod.default ?? mod.provider;
+ if (typeof providerFn !== "function") {
+ return null;
+ }
+ return {
+ id,
+ color,
+ maxLength,
+ fetch: /* @__PURE__ */ __name(async (ctx) => {
+ if (ctx.signal.aborted) {
+ return "";
+ }
+ let timer = null;
+ let onAbort = null;
+ const timeoutPromise = new Promise((_, reject) => {
+ timer = setTimeout(() => reject(new Error("timeout")), timeout);
+ onAbort = /* @__PURE__ */ __name(() => reject(new Error("aborted")), "onAbort");
+ ctx.signal.addEventListener("abort", onAbort, { once: true });
+ });
+ try {
+ const result = await Promise.race([
+ Promise.resolve().then(
+ () => providerFn({
+ projectRoot: ctx.projectRoot,
+ session: ctx.getSessionInfo ? ctx.getSessionInfo() : null
+ })
+ ),
+ timeoutPromise
+ ]);
+ return typeof result === "string" ? result : "";
+ } finally {
+ if (timer) {
+ clearTimeout(timer);
+ }
+ if (onAbort) {
+ ctx.signal.removeEventListener("abort", onAbort);
+ }
+ }
+ }, "fetch")
+ };
+ } catch {
+ return null;
+ }
+}
+__name(loadModuleProvider, "loadModuleProvider");
+
+// packages/cli/src/ui/statusline/manager.ts
+function segmentsEqual(a, b) {
+ if (a.length !== b.length) {
+ return false;
+ }
+ for (let i = 0; i < a.length; i++) {
+ if (a[i]?.id !== b[i]?.id || a[i]?.text !== b[i]?.text || a[i]?.color !== b[i]?.color || a[i]?.newLine !== b[i]?.newLine) {
+ return false;
+ }
+ }
+ return true;
+}
+__name(segmentsEqual, "segmentsEqual");
+var StatusLineManager = class {
+ static {
+ __name(this, "StatusLineManager");
+ }
+ providers = [];
+ ac = null;
+ timer = null;
+ subscribers = /* @__PURE__ */ new Set();
+ segments = [];
+ running = false;
+ projectRoot = "";
+ getSessionInfo;
+ get currentSegments() {
+ return this.segments;
+ }
+ subscribe(fn) {
+ this.subscribers.add(fn);
+ return () => {
+ this.subscribers.delete(fn);
+ };
+ }
+ emit(segments) {
+ if (segmentsEqual(this.segments, segments)) {
+ return;
+ }
+ this.segments = segments;
+ for (const fn of this.subscribers) {
+ try {
+ fn(segments);
+ } catch {
+ }
+ }
+ }
+ async start(config2, projectRoot, getSessionInfo) {
+ if (this.running) {
+ this.stop();
+ }
+ if (!config2.enabled || config2.providers.length === 0) {
+ return;
+ }
+ this.projectRoot = projectRoot;
+ this.getSessionInfo = getSessionInfo;
+ const { providers, refreshMs } = config2;
+ this.ac = new AbortController();
+ const { signal } = this.ac;
+ const built = [];
+ let nextId = 0;
+ for (const entry of providers) {
+ const providerId = entry.id || `${entry.type}-${nextId}`;
+ const provider = await this.buildProvider(entry, projectRoot, providerId);
+ if (provider) {
+ built.push(provider);
+ }
+ nextId += 1;
+ }
+ if (built.length === 0) {
+ return;
+ }
+ this.providers = built;
+ this.running = true;
+ void this.fetchAll();
+ this.timer = setInterval(() => {
+ if (signal.aborted) {
+ return;
+ }
+ void this.fetchAll();
+ }, refreshMs);
+ }
+ stop() {
+ this.running = false;
+ if (this.timer !== null) {
+ clearInterval(this.timer);
+ this.timer = null;
+ }
+ if (this.ac) {
+ this.ac.abort();
+ this.ac = null;
+ }
+ for (const provider of this.providers) {
+ provider.dispose?.();
+ }
+ this.providers = [];
+ this.getSessionInfo = void 0;
+ }
+ async buildProvider(config2, projectRoot, providerId) {
+ if (config2.type === "command") {
+ return createCommandStatusProvider(config2, projectRoot, providerId);
+ }
+ if (config2.type === "module") {
+ const resolvedPath = validateModulePath(config2.path, projectRoot);
+ if (!resolvedPath) {
+ return null;
+ }
+ const provider = await loadModuleProvider(
+ resolvedPath,
+ config2.color,
+ providerId,
+ config2.timeoutMs,
+ config2.maxLength
+ );
+ if (provider && config2.newLine) {
+ provider.newLine = true;
+ }
+ return provider;
+ }
+ return null;
+ }
+ async fetchAll() {
+ if (!this.ac || this.ac.signal.aborted) {
+ return;
+ }
+ const results = await Promise.all(
+ this.providers.map(async (provider) => {
+ try {
+ const text = await provider.fetch({
+ projectRoot: this.projectRoot,
+ signal: this.ac.signal,
+ getSessionInfo: this.getSessionInfo
+ });
+ const sanitized = sanitizeStatusText(text, provider.maxLength);
+ if (!sanitized) {
+ return null;
+ }
+ const segment = { id: provider.id, text: sanitized };
+ if (provider.color) {
+ segment.color = provider.color;
+ }
+ if (provider.newLine) {
+ segment.newLine = true;
+ }
+ return segment;
+ } catch {
+ return null;
+ }
+ })
+ );
+ const segments = results.filter((s) => s !== null);
+ this.emit(segments);
+ }
+};
+
+// packages/cli/src/ui/hooks/useStatusLine.ts
+function useStatusLine(config2, projectRoot, getSessionInfo) {
+ const [segments, setSegments] = (0, import_react42.useState)([]);
+ const managerRef = (0, import_react42.useRef)(null);
+ const getSessionInfoRef = (0, import_react42.useRef)(getSessionInfo);
+ getSessionInfoRef.current = getSessionInfo;
+ const configKey = (0, import_react42.useMemo)(
+ () => JSON.stringify({
+ enabled: config2.enabled,
+ refreshMs: config2.refreshMs,
+ separator: config2.separator,
+ providers: config2.providers
+ }),
+ [config2]
+ );
+ (0, import_react42.useEffect)(() => {
+ const manager = new StatusLineManager();
+ managerRef.current = manager;
+ const unsub = manager.subscribe(setSegments);
+ void manager.start(config2, projectRoot, () => getSessionInfoRef.current ? getSessionInfoRef.current() : null);
+ return () => {
+ unsub();
+ manager.stop();
+ managerRef.current = null;
+ };
+ }, [configKey, projectRoot]);
+ return segments;
+}
+__name(useStatusLine, "useStatusLine");
+
+// packages/cli/src/ui/views/SlashCommandMenu.tsx
+init_esbuild_shims();
+var import_react43 = __toESM(require_react(), 1);
+var import_jsx_runtime4 = __toESM(require_jsx_runtime(), 1);
+function isSkillSelected(skills, skill) {
+ return skills.some((item) => item.name === skill.name);
+}
+__name(isSkillSelected, "isSkillSelected");
+var SlashCommandMenu = import_react43.default.memo(/* @__PURE__ */ __name(function SlashCommandMenu2({
+ items,
+ activeIndex,
+ maxVisible = 6,
+ width
+}) {
+ const labelColumnWidth = import_react43.default.useMemo(() => {
+ if (items.length === 0) {
+ return 0;
+ }
+ const longestLabel = Math.max(
+ ...items.map((s) => s.label.length + (s.args ? s.args?.join(ARGS_SEPARATOR)?.length + 4 : 0))
+ );
+ const contentWidth = longestLabel + 2;
+ const maxAllowed = Math.max(10, width - 2 >> 1);
+ return Math.min(contentWidth, maxAllowed);
+ }, [items, width]);
+ if (items.length === 0) {
+ return null;
+ }
+ const visibleStart = Math.min(
+ Math.max(0, activeIndex - Math.floor((maxVisible - 1) / 2)),
+ Math.max(0, items.length - maxVisible)
+ );
+ const visibleItems = items.slice(visibleStart, visibleStart + maxVisible);
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, width, children: [
+ visibleStart > 0 ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Box_default, { marginLeft: 2, children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Text, { dimColor: true, children: "\u25B2" }) }) : null,
+ visibleItems.map((item, idx) => {
+ const actualIndex = visibleStart + idx;
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(Box_default, { gap: 2, flexDirection: "row", flexGrow: 1, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(Box_default, { width: labelColumnWidth, flexShrink: 0, gap: 2, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(Text, { color: actualIndex === activeIndex ? "#229ac3" : void 0, wrap: "truncate-end", children: [
+ actualIndex === activeIndex ? "> " : " ",
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Text, { bold: true, children: formatSlashCommandLabel(item) })
+ ] }),
+ item.args ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Text, { dimColor: true, children: item.args.join(ARGS_SEPARATOR) }) : null
+ ] }),
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Text, { color: actualIndex === activeIndex ? "#229ac3" : void 0, wrap: "truncate-end", dimColor: true, children: formatSlashCommandDescription(item.description) }) })
+ ] }, item.label);
+ }),
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(Box_default, { marginLeft: 2, flexDirection: "column", children: [
+ visibleStart + visibleItems.length < items.length ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Text, { dimColor: true, children: "\u25BC" }) : null,
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(Text, { dimColor: true, children: [
+ "(",
+ activeIndex + 1,
+ "/",
+ items.length,
+ ") \u2191\u2193 to navigate \xB7 Enter to select"
+ ] })
+ ] })
+ ] });
+}, "SlashCommandMenu"));
+var SlashCommandMenu_default = SlashCommandMenu;
+
+// packages/cli/src/ui/components/index.ts
+init_esbuild_shims();
+
+// packages/cli/src/ui/components/RawModelDropdown/index.tsx
+init_esbuild_shims();
+var import_react44 = __toESM(require_react(), 1);
+var import_jsx_runtime5 = __toESM(require_jsx_runtime(), 1);
+var RawModelDropdown = /* @__PURE__ */ __name(({ open = false, screenWidth, onSelect, onClose }) => {
+ const { mode, setMode } = useRawModeContext();
+ const [index, setIndex] = (0, import_react44.useState)(0);
+ use_input_default(
+ (input, key) => {
+ if (key.upArrow) {
+ setIndex((i) => Math.max(0, i - 1));
+ return;
+ }
+ if (key.downArrow) {
+ setIndex((i) => Math.min(RAW_COMMAND_MODELS.length - 1, i + 1));
+ return;
+ }
+ if (input === " " && !key.ctrl && !key.meta || key.return && !key.shift && !key.meta) {
+ setMode(RAW_COMMAND_MODELS[index].key);
+ onClose?.(false);
+ onSelect?.(RAW_COMMAND_MODELS[index].key);
+ return;
+ }
+ if (key.escape) {
+ onClose?.(false);
+ return;
+ }
+ },
+ { isActive: open }
+ );
+ if (!open) {
+ return null;
+ }
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
+ DropdownMenu_default,
+ {
+ title: "Select mode",
+ items: RAW_COMMAND_MODELS.map((model) => ({ ...model, selected: model.key === mode })),
+ helpText: "Space/Enter select mode \xB7 Esc to close",
+ activeColor: "#229ac3",
+ maxVisible: 6,
+ activeIndex: index,
+ width: screenWidth
+ }
+ );
+}, "RawModelDropdown");
+var RawModelDropdown_default = RawModelDropdown;
+
+// packages/cli/src/ui/components/MessageView/index.tsx
+init_esbuild_shims();
+
+// packages/cli/src/ui/components/MessageView/markdown.ts
+init_esbuild_shims();
+function renderMarkdown(text, maxWidth) {
+ return renderMarkdownSegments(text, maxWidth).map((s) => s.body).reduce((out, body) => {
+ if (!out) return body;
+ if (!body) return out;
+ return out.endsWith("\n") || body.startsWith("\n") ? out + body : `${out}
+${body}`;
+ }, "");
+}
+__name(renderMarkdown, "renderMarkdown");
+function renderMarkdownSegments(text, maxWidth) {
+ if (!text) return [];
+ const segments = [];
+ const fenceSegments = splitByFences(text);
+ for (const seg of fenceSegments) {
+ if (seg.kind === "code") {
+ const langTag = seg.lang ? source_default2.dim(`[${seg.lang}]`) + "\n" : "";
+ segments.push({ kind: "code", body: langTag + source_default2.cyan(seg.body), lang: seg.lang });
+ continue;
+ }
+ const blocks = splitTableBlocks(seg.body);
+ for (const b of blocks) {
+ if (b.kind === "table") {
+ segments.push({ kind: "table", body: renderTableBorder(b.rows, maxWidth) });
+ } else {
+ const body = b.body.split("\n").map((line) => renderInlineLine(line)).join("\n");
+ if (body) segments.push({ kind: "text", body });
+ }
+ }
+ }
+ return segments;
+}
+__name(renderMarkdownSegments, "renderMarkdownSegments");
+function splitByFences(text) {
+ const segments = [];
+ const lines = text.split(/\r?\n/);
+ let buffer = [];
+ let inFence = false;
+ let fenceLang = "";
+ let fenceBody = [];
+ const flushText = /* @__PURE__ */ __name(() => {
+ if (buffer.length > 0) {
+ segments.push({ kind: "text", body: buffer.join("\n") });
+ buffer = [];
+ }
+ }, "flushText");
+ for (const line of lines) {
+ const m = /^\s*```(\w*)\s*$/.exec(line);
+ if (m) {
+ if (!inFence) {
+ flushText();
+ inFence = true;
+ fenceLang = m[1] ?? "";
+ fenceBody = [];
+ } else {
+ segments.push({ kind: "code", lang: fenceLang, body: fenceBody.join("\n") });
+ inFence = false;
+ }
+ continue;
+ }
+ (inFence ? fenceBody : buffer).push(line);
+ }
+ if (inFence) {
+ segments.push({ kind: "code", lang: fenceLang, body: fenceBody.join("\n") });
+ } else {
+ flushText();
+ }
+ return segments;
+}
+__name(splitByFences, "splitByFences");
+function splitTableBlocks(text) {
+ const lines = text.split(/\r?\n/);
+ const blocks = [];
+ let buffer = [];
+ let tableRows = [];
+ let inTable = false;
+ const flushText = /* @__PURE__ */ __name(() => {
+ if (buffer.length > 0) {
+ blocks.push({ kind: "text", body: buffer.join("\n") });
+ buffer = [];
+ }
+ }, "flushText");
+ const flushTable = /* @__PURE__ */ __name(() => {
+ if (tableRows.length >= 2) {
+ blocks.push({ kind: "table", rows: tableRows });
+ } else if (tableRows.length > 0) {
+ buffer.push(...tableRows.map((r) => r.join(" | ")));
+ }
+ tableRows = [];
+ }, "flushTable");
+ const sepRe = /^\|?\s*:?[-]{3,}:?\s*(\|\s*:?[-]{3,}:?\s*)*\|?\s*$/;
+ const parseRow = /* @__PURE__ */ __name((row) => {
+ let body = row.trim();
+ if (body.startsWith("|")) body = body.slice(1);
+ if (body.endsWith("|")) body = body.slice(0, -1);
+ return body.split("|").map((s) => s.trim());
+ }, "parseRow");
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+ const trimmed = line.trim();
+ const nextTrimmed = (lines[i + 1] ?? "").trim();
+ if (inTable && sepRe.test(trimmed) && tableRows.length === 1) continue;
+ const isRow = /^\|.+\|$/.test(trimmed);
+ const isHeader = isRow && i + 1 < lines.length && sepRe.test(nextTrimmed);
+ if (isHeader && !inTable) {
+ flushText();
+ inTable = true;
+ tableRows = [parseRow(trimmed)];
+ continue;
+ }
+ if (isRow && inTable) {
+ tableRows.push(parseRow(trimmed));
+ continue;
+ }
+ if (inTable && !isRow) {
+ flushTable();
+ inTable = false;
+ }
+ buffer.push(line);
+ }
+ return inTable ? [...blocks, ...flushTableResult(tableRows)] : [...blocks, ...flushTextOnly(buffer, tableRows)];
+}
+__name(splitTableBlocks, "splitTableBlocks");
+function flushTableResult(rows) {
+ if (rows.length >= 2) return [{ kind: "table", rows }];
+ if (rows.length > 0) return [{ kind: "text", body: rows.map((r) => r.join(" | ")).join("\n") }];
+ return [];
+}
+__name(flushTableResult, "flushTableResult");
+function flushTextOnly(buffer, tableRows) {
+ const result = [];
+ if (buffer.length > 0) result.push({ kind: "text", body: buffer.join("\n") });
+ if (tableRows.length >= 2) result.push({ kind: "table", rows: tableRows });
+ else if (tableRows.length > 0) result.push({ kind: "text", body: tableRows.map((r) => r.join(" | ")).join("\n") });
+ return result;
+}
+__name(flushTextOnly, "flushTextOnly");
+function visualWidth(text) {
+ let w = 0;
+ for (const ch of text) {
+ if (ch.length >= 2) {
+ w += 2;
+ continue;
+ }
+ const code = ch.codePointAt(0) ?? ch.charCodeAt(0);
+ w += isWideChar(code) ? 2 : 1;
+ }
+ return w;
+}
+__name(visualWidth, "visualWidth");
+function isWideChar(code) {
+ return code >= 4352 && code <= 4447 || // Hangul Jamo
+ code >= 9001 && code <= 9002 || // Misc technical
+ code >= 11904 && code <= 42191 || // CJK Radicals, Kangxi, CJK all
+ code >= 44032 && code <= 55215 || // Hangul Syllables
+ code >= 63744 && code <= 64255 || // CJK Compat
+ code >= 65040 && code <= 65135 || // CJK Compat Forms
+ code >= 65280 && code <= 65510 || // Fullwidth
+ code >= 131072 && code <= 262141 || // CJK Ext B+
+ code >= 127744 && code <= 129791 || // Emoji & pictographs
+ code >= 9728 && code <= 10175 || // Misc Symbols
+ code >= 8960 && code <= 9215 || // Misc Technical
+ code >= 11008 && code <= 11263 || // Misc Symbols & Arrows
+ code >= 126976 && code <= 127023;
+}
+__name(isWideChar, "isWideChar");
+function renderTableBorder(rows, maxWidth) {
+ if (rows.length === 0) return "";
+ const colCount = rows[0].length;
+ const normalizedRows = rows.map(
+ (row) => Array.from({ length: colCount }, (_, i) => {
+ return row[i] ?? "";
+ })
+ );
+ const calcW = /* @__PURE__ */ __name((cs) => cs.reduce((a, b) => a + b + 2, 0) + cs.length + 1, "calcW");
+ const natural = Array.from({ length: colCount }, (_, i) => {
+ const texts = normalizedRows.map((r) => r[i] ?? "");
+ const maxLine = Math.max(4, ...texts.map((t) => visualWidth(t)));
+ return maxLine;
+ });
+ const minWidths = Array.from({ length: colCount }, (_, i) => {
+ const headerWidth = visualWidth(normalizedRows[0]?.[i] ?? "");
+ const labelColumn = natural[i] <= 12;
+ const minReadable = labelColumn ? natural[i] : Math.max(4, Math.min(headerWidth, 12));
+ return Math.min(natural[i], minReadable);
+ });
+ let colWidths;
+ const totalNatural = calcW(natural);
+ const totalMin = calcW(minWidths);
+ const effectiveMax = maxWidth ?? 120;
+ if (totalNatural <= effectiveMax) {
+ colWidths = [...natural];
+ const slack = effectiveMax - totalNatural;
+ if (slack > 0) {
+ const isLabel = colWidths.map((w) => w <= 8);
+ const candidates = colWidths.map((w, i) => isLabel[i] ? 0 : w);
+ const totalWeight = candidates.reduce((a, b) => a + b, 0);
+ if (totalWeight > 0) {
+ for (let ci = 0; ci < colCount; ci++) {
+ if (candidates[ci] > 0) {
+ colWidths[ci] += Math.floor(slack * candidates[ci] / totalWeight);
+ }
+ }
+ }
+ }
+ } else if (totalMin >= effectiveMax) {
+ colWidths = [...minWidths];
+ while (calcW(colWidths) > effectiveMax && colWidths.some((w) => w > 1)) {
+ const widest = colWidths.reduce((maxIdx, width, idx) => width > colWidths[maxIdx] ? idx : maxIdx, 0);
+ colWidths[widest]--;
+ }
+ } else {
+ const budget = effectiveMax - totalMin;
+ const deficits = natural.map((n, i) => Math.max(0, n - minWidths[i]));
+ const totalDeficit = deficits.reduce((a, b) => a + b, 0);
+ colWidths = [...minWidths];
+ if (totalDeficit > 0) {
+ for (let ci = 0; ci < colCount; ci++) {
+ colWidths[ci] += Math.floor(budget * deficits[ci] / totalDeficit);
+ }
+ }
+ let used = calcW(colWidths);
+ const deficitByIdx = colWidths.map((w, i) => ({ i, gap: natural[i] - w }));
+ deficitByIdx.sort((a, b) => b.gap - a.gap);
+ for (const { i } of deficitByIdx) {
+ if (used >= effectiveMax) break;
+ if (colWidths[i] < natural[i]) {
+ colWidths[i]++;
+ used = calcW(colWidths);
+ }
+ }
+ }
+ const wrapCell = /* @__PURE__ */ __name((text, width) => {
+ if (!text) return [""];
+ const lines = [];
+ let cur = "";
+ const flush = /* @__PURE__ */ __name(() => {
+ if (cur.trim()) lines.push(cur.replace(/\s+$/, ""));
+ cur = "";
+ }, "flush");
+ for (const ch of text) {
+ const cw = visualWidth(ch);
+ if (visualWidth(cur) + cw > width) {
+ const lastSpace = cur.lastIndexOf(" ");
+ if (lastSpace > width / 3) {
+ const carry = cur.slice(lastSpace + 1);
+ cur = cur.slice(0, lastSpace);
+ flush();
+ cur = carry + ch;
+ } else {
+ flush();
+ cur = ch;
+ }
+ } else {
+ cur += ch;
+ }
+ }
+ if (cur.trim()) lines.push(cur.replace(/\s+$/, ""));
+ return lines.length > 0 ? lines : [""];
+ }, "wrapCell");
+ const wrapped = normalizedRows.map((r) => r.map((c, ci) => wrapCell(c, colWidths[ci])));
+ const heights = wrapped.map((wr) => Math.max(1, ...wr.map((lines) => lines.length)));
+ const pad = /* @__PURE__ */ __name((s, w) => s + " ".repeat(Math.max(0, w - visualWidth(s))), "pad");
+ const top2 = "\u250C" + colWidths.map((w) => "\u2500".repeat(w + 2)).join("\u252C") + "\u2510";
+ const hdr = "\u251C" + colWidths.map((w) => "\u2500".repeat(w + 2)).join("\u253C") + "\u2524";
+ const sep7 = "\u251C" + colWidths.map((w) => "\u2500".repeat(w + 2)).join("\u253C") + "\u2524";
+ const bot = "\u2514" + colWidths.map((w) => "\u2500".repeat(w + 2)).join("\u2534") + "\u2518";
+ const out = [top2];
+ for (let ri = 0; ri < wrapped.length; ri++) {
+ const h = heights[ri];
+ for (let li = 0; li < h; li++) {
+ const line = wrapped[ri].map((cellLines, ci) => " " + pad(cellLines[li] ?? "", colWidths[ci]) + " ");
+ out.push("\u2502" + line.join("\u2502") + "\u2502");
+ }
+ if (ri === 0 && rows.length > 1) out.push(hdr);
+ else if (ri < rows.length - 1) out.push(sep7);
+ }
+ out.push(bot);
+ return out.join("\n");
+}
+__name(renderTableBorder, "renderTableBorder");
+function renderInlineLine(line) {
+ const headingMatch = /^(\s*)(#{1,6})\s+(.*)$/.exec(line);
+ if (headingMatch) {
+ const [, lead, hashes, content] = headingMatch;
+ const styled = hashes.length <= 2 ? source_default2.bold.cyanBright(content) : source_default2.bold.cyan(content);
+ return `${lead}${source_default2.dim(hashes)} ${styled}`;
+ }
+ const listMatch = /^(\s*)([-*+])\s+(.*)$/.exec(line);
+ if (listMatch) {
+ const [, lead, bullet, content] = listMatch;
+ return `${lead}${source_default2.yellow(bullet)} ${renderInlineSpans(content)}`;
+ }
+ const numListMatch = /^(\s*)(\d+\.)\s+(.*)$/.exec(line);
+ if (numListMatch) {
+ const [, lead, marker, content] = numListMatch;
+ return `${lead}${source_default2.yellow(marker)} ${renderInlineSpans(content)}`;
+ }
+ const quoteMatch = /^(\s*)>\s?(.*)$/.exec(line);
+ if (quoteMatch) {
+ const [, lead, content] = quoteMatch;
+ return `${lead}${source_default2.dim("\u2502 ")}${source_default2.italic(renderInlineSpans(content))}`;
+ }
+ return renderInlineSpans(line);
+}
+__name(renderInlineLine, "renderInlineLine");
+function renderInlineSpans(text) {
+ if (!text) return text;
+ const parts = [];
+ const codeRe = /`([^`]+)`/g;
+ let lastIndex = 0;
+ let match;
+ while ((match = codeRe.exec(text)) !== null) {
+ if (match.index > lastIndex) {
+ parts.push(renderEmphasisSpans(text.slice(lastIndex, match.index)));
+ }
+ parts.push(source_default2.cyan(match[1] ?? ""));
+ lastIndex = match.index + match[0].length;
+ }
+ if (lastIndex < text.length) {
+ parts.push(renderEmphasisSpans(text.slice(lastIndex)));
+ }
+ return parts.join("");
+}
+__name(renderInlineSpans, "renderInlineSpans");
+function renderEmphasisSpans(text) {
+ let result = text;
+ result = result.replace(/\*\*([^*]+)\*\*/g, (_, inner) => source_default2.bold(inner));
+ result = result.replace(/(? source_default2.italic(inner));
+ result = result.replace(/(? source_default2.italic(inner));
+ return result;
+}
+__name(renderEmphasisSpans, "renderEmphasisSpans");
+
+// packages/cli/src/ui/components/MessageView/index.tsx
+var import_jsx_runtime6 = __toESM(require_jsx_runtime(), 1);
+var PROMPT_ECHO_PREFIX_WIDTH = 2;
+var PROMPT_ECHO_MARGIN_LEFT = 1;
+function MessageView({ message, collapsed, width = 80 }) {
+ const { mode } = useRawModeContext();
+ if (!message.visible) {
+ return null;
+ }
+ if (message.role === "user") {
+ const text = message.content || "(no content)";
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
+ PromptEchoLine,
+ {
+ text,
+ width,
+ attachmentCount: Array.isArray(message.contentParams) ? message.contentParams.length : 0
+ }
+ );
+ }
+ if (message.role === "assistant") {
+ const isThinking = Boolean(message.meta?.asThinking);
+ const content = (message.content || "").trim();
+ if (isThinking) {
+ const summary = buildThinkingSummary(content, message.messageParams, mode);
+ if (collapsed !== false) {
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Box_default, { marginLeft: 1, marginBottom: 1, marginY: 0, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(StatusLine, { width, bulletColor: "gray", name: "Thinking", params: summary }) });
+ }
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(Box_default, { marginLeft: 1, flexDirection: "column", marginBottom: 1, marginY: 0, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(StatusLine, { width, bulletColor: "gray", name: "Thinking", params: content ? "" : summary }),
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Box_default, { flexDirection: "column", marginLeft: 2, children: content ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { dimColor: true, children: renderMarkdown(content) }) : null })
+ ] });
+ }
+ const containerWidth = Math.max(1, width - 2);
+ const contentWidth = Math.max(1, width - 4);
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(Box_default, { marginLeft: 1, marginBottom: 1, width: containerWidth, gap: 1, marginY: 0, flexDirection: "row", children: [
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Box_default, { alignSelf: "stretch", children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { color: "#229ac3", children: "\u2726" }) }),
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Box_default, { flexGrow: 1, width: contentWidth, flexDirection: "column", children: content ? renderMarkdownSegments(content, Math.max(20, contentWidth - 4)).map((seg, i) => {
+ if (seg.kind === "table") {
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Box_default, { flexDirection: "column", children: seg.body.split("\n").map((line, lineIndex) => /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { wrap: "truncate-end", children: line }, lineIndex)) }, i);
+ }
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { children: seg.body }, i);
+ }) : null })
+ ] });
+ }
+ if (message.role === "tool") {
+ const summary = buildToolSummary(message);
+ const diffLines = getToolDiffPreviewLines(summary);
+ const planLines = getUpdatePlanPreviewLines(summary);
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(Box_default, { flexDirection: "column", marginLeft: 1, marginBottom: 1, marginY: 0, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
+ StatusLine,
+ {
+ width,
+ bulletColor: summary.ok ? "green" : "red",
+ name: formatStatusName(summary.name),
+ params: formatToolStatusParams(summary)
+ }
+ ),
+ diffLines.length > 0 ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(DiffPreview, { lines: diffLines }) : null,
+ planLines.length > 0 ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(PlanPreview, { lines: planLines }) : null
+ ] });
+ }
+ if (message.role === "system") {
+ if (message.meta?.isModelChange) {
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(PromptEchoLine, { text: message.content || "", width });
+ }
+ if (message.meta?.skill) {
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Box_default, { marginY: 0, marginLeft: 1, marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(Text, { color: "magenta", children: [
+ "\u26A1 Loaded skill: ",
+ message.meta.skill.name
+ ] }) });
+ }
+ if (message.meta?.isSummary) {
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Box_default, { marginY: 0, marginLeft: 1, marginBottom: 1, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { dimColor: true, italic: true, children: "(conversation summary inserted)" }) });
+ }
+ return null;
+ }
+ return null;
+}
+__name(MessageView, "MessageView");
+function getPromptEchoContentWidth(width) {
+ return Math.max(1, width - PROMPT_ECHO_MARGIN_LEFT - PROMPT_ECHO_PREFIX_WIDTH);
+}
+__name(getPromptEchoContentWidth, "getPromptEchoContentWidth");
+function PromptEchoLine({
+ text,
+ width,
+ attachmentCount = 0
+}) {
+ const contentWidth = getPromptEchoContentWidth(width);
+ const containerWidth = Math.max(1, width - PROMPT_ECHO_MARGIN_LEFT);
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(Box_default, { marginBottom: 1, marginLeft: PROMPT_ECHO_MARGIN_LEFT, marginY: 0, width: containerWidth, flexDirection: "row", children: [
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Box_default, { width: PROMPT_ECHO_PREFIX_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { color: "#229ac3", children: "> " }) }),
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(Box_default, { flexGrow: 1, flexShrink: 1, width: contentWidth, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { color: "#229ac3", wrap: "hard", children: text }),
+ attachmentCount > 0 ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { color: "#229ac3", children: ` \u{1F4CE} ${attachmentCount} image attachment(s)` }) : null
+ ] })
+ ] });
+}
+__name(PromptEchoLine, "PromptEchoLine");
+function StatusLine({
+ bulletColor,
+ name,
+ params,
+ width
+}) {
+ const { mode } = useRawModeContext();
+ const containerWidth = Math.max(1, width - 2);
+ const contentWidth = Math.max(1, width - 4);
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(Box_default, { gap: 1, width: containerWidth, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Box_default, { alignSelf: "stretch", children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { color: bulletColor, children: "\u2727" }, "bullet") }),
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Box_default, { flexGrow: 1, width: contentWidth, gap: 1, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(Text, { wrap: mode === "Lite mode" /* Lite */ ? "truncate-end" : "wrap", children: [
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { bold: true, children: name }, "name"),
+ params ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { color: "white", children: ` ${params}` }, "params") : null
+ ] }) })
+ ] });
+}
+__name(StatusLine, "StatusLine");
+function DiffPreview({ lines }) {
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(Box_default, { flexDirection: "column", marginLeft: 2, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { dimColor: true, children: "\u2514 Changes" }),
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Box_default, { flexDirection: "column", marginLeft: 2, children: lines.map((line, index) => /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(Text, { wrap: "truncate-end", children: [
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { color: line.kind === "added" ? "green" : line.kind === "removed" ? "red" : "gray", children: line.marker }),
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { color: line.kind === "added" ? "green" : line.kind === "removed" ? "red" : void 0, children: line.content })
+ ] }, `${index}-${line.marker}-${line.content}`)) })
+ ] });
+}
+__name(DiffPreview, "DiffPreview");
+function PlanPreview({ lines }) {
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(Box_default, { flexDirection: "column", marginLeft: 2, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { dimColor: true, children: "\u2514 Plan" }),
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Box_default, { flexDirection: "column", marginLeft: 2, children: lines.map((line, index) => /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Text, { wrap: "wrap", children: line }, `${index}-${line}`)) })
+ ] });
+}
+__name(PlanPreview, "PlanPreview");
+
+// packages/cli/src/ui/components/RawModeExitPrompt/index.tsx
+init_esbuild_shims();
+var import_react45 = __toESM(require_react(), 1);
+function RawModeExitPrompt({ onExit }) {
+ const { previousMode } = useRawModeContext();
+ const snapshotRef = (0, import_react45.useRef)(previousMode);
+ use_input_default(
+ (_input, key) => {
+ if (key.escape) {
+ onExit(snapshotRef.current);
+ }
+ },
+ { isActive: true }
+ );
+ return null;
+}
+__name(RawModeExitPrompt, "RawModeExitPrompt");
+
+// packages/cli/src/ui/components/SkillsDropdown/index.tsx
+init_esbuild_shims();
+var import_react46 = __toESM(require_react(), 1);
+var import_jsx_runtime7 = __toESM(require_jsx_runtime(), 1);
+var SkillsDropdown = /* @__PURE__ */ __name(({ open, width, skills, selectedSkills, onSelect, onClose }) => {
+ const [skillsDropdownIndex, setSkillsDropdownIndex] = (0, import_react46.useState)(0);
+ use_input_default(
+ (input, key) => {
+ if (key.upArrow) {
+ setSkillsDropdownIndex((idx) => (idx - 1 + skills.length) % skills.length);
+ return;
+ }
+ if (key.downArrow) {
+ setSkillsDropdownIndex((idx) => (idx + 1) % skills.length);
+ return;
+ }
+ if (input === " " && !key.ctrl && !key.meta || key.return && !key.shift && !key.meta) {
+ const skill = skills[skillsDropdownIndex];
+ if (skill) {
+ onSelect?.(skill);
+ }
+ return;
+ }
+ if (key.tab) {
+ onClose?.(false);
+ return;
+ }
+ if (key.escape) {
+ onClose?.(false);
+ }
+ },
+ { isActive: open }
+ );
+ (0, import_react46.useEffect)(() => {
+ if (skillsDropdownIndex >= skills.length) {
+ setSkillsDropdownIndex(Math.max(0, skills.length - 1));
+ }
+ }, [skills.length, skillsDropdownIndex]);
+ if (!open) {
+ return null;
+ }
+ return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
+ DropdownMenu_default,
+ {
+ width,
+ title: "Select Skills",
+ helpText: "Space toggle \xB7 Enter toggle \xB7 Esc to close",
+ emptyText: "No skills found",
+ items: skills.map((skill) => ({
+ key: skill.path || skill.name,
+ label: skill.name,
+ description: skill.path,
+ selected: isSkillSelected(selectedSkills, skill),
+ statusIndicator: skill.isLoaded ? { symbol: "\u2713", color: "green" } : void 0
+ })),
+ activeIndex: skillsDropdownIndex,
+ activeColor: "#229ac3",
+ maxVisible: 6
+ }
+ );
+}, "SkillsDropdown");
+var SkillsDropdown_default = SkillsDropdown;
+
+// packages/cli/src/ui/components/FileMentionMenu/index.tsx
+init_esbuild_shims();
+var import_react47 = __toESM(require_react(), 1);
+var import_jsx_runtime8 = __toESM(require_jsx_runtime(), 1);
+var FileMentionMenu = /* @__PURE__ */ __name(({ open, width, token, items, onClose, onSelect }) => {
+ const [activeIndex, setActiveIndex] = (0, import_react47.useState)(0);
+ (0, import_react47.useEffect)(() => {
+ if (open) {
+ setActiveIndex(0);
+ }
+ }, [open]);
+ (0, import_react47.useEffect)(() => {
+ if (!open) {
+ return;
+ }
+ if (items.length === 0) {
+ setActiveIndex(0);
+ return;
+ }
+ if (activeIndex >= items.length) {
+ setActiveIndex(Math.max(0, items.length - 1));
+ }
+ }, [activeIndex, items.length, open]);
+ use_input_default(
+ (input, key) => {
+ if (!open) {
+ return;
+ }
+ if (key.escape) {
+ onClose();
+ return;
+ }
+ if (key.upArrow) {
+ if (items.length > 0) {
+ setActiveIndex((idx) => (idx - 1 + items.length) % items.length);
+ }
+ return;
+ }
+ if (key.downArrow) {
+ if (items.length > 0) {
+ setActiveIndex((idx) => (idx + 1) % items.length);
+ }
+ return;
+ }
+ if (key.tab || key.return && !key.shift && !key.meta) {
+ const selected = items[activeIndex];
+ if (selected) {
+ onSelect(selected);
+ return;
+ }
+ if (key.tab) {
+ onClose();
+ }
+ return;
+ }
+ },
+ { isActive: open }
+ );
+ if (!open) {
+ return null;
+ }
+ return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
+ DropdownMenu_default,
+ {
+ width,
+ title: "Mention File",
+ helpText: "Enter/Tab insert \xB7 Esc close",
+ emptyText: token?.query ? "No matching files" : "Type after @ to search files",
+ items: items.map((item) => ({
+ key: item.path,
+ label: item.path,
+ description: item.type === "directory" ? "directory" : "file"
+ })),
+ activeIndex,
+ activeColor: "#229ac3",
+ maxVisible: 8,
+ renderItem: (item, isActive) => /* @__PURE__ */ (0, import_jsx_runtime8.jsxs)(Box_default, { flexDirection: "row", paddingX: 1, gap: 1, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Text, { color: isActive ? "#229ac3" : void 0, children: isActive ? "> " : " " }),
+ /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Text, { color: isActive ? "#229ac3" : void 0, wrap: "truncate-end", bold: isActive, children: item.label }) }),
+ item.description ? /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Box_default, { width: 10, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(Text, { dimColor: true, children: item.description }) }) : null
+ ] })
+ }
+ );
+}, "FileMentionMenu");
+var FileMentionMenu_default = FileMentionMenu;
+
+// packages/cli/src/ui/views/PromptInput.tsx
+var import_jsx_runtime9 = __toESM(require_jsx_runtime(), 1);
+var PROMPT_PREFIX_WIDTH = 2;
+var PromptPrefixLine = import_react48.default.memo(/* @__PURE__ */ __name(function PromptPrefixLine2() {
+ return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Box_default, { width: PROMPT_PREFIX_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Text, { color: "#229ac3", children: "> " }) });
+}, "PromptPrefixLine"));
+var PromptInput = import_react48.default.memo(/* @__PURE__ */ __name(function PromptInput2({
+ projectRoot,
+ skills,
+ modelConfig,
+ screenWidth,
+ promptHistory,
+ busy,
+ cursorLayoutKey,
+ loadingText,
+ disabled,
+ placeholder,
+ runningProcesses,
+ promptDraft,
+ statusLineSegments,
+ statusLineSeparator,
+ onSubmit,
+ onModelConfigChange,
+ onInterrupt,
+ onToggleProcessStdout,
+ onExitShortcut,
+ onRawModeChange
+}) {
+ const { stdout } = use_stdout_default();
+ const inputTextRef = (0, import_react48.useRef)(null);
+ const [buffer, setBuffer] = (0, import_react48.useState)(EMPTY_BUFFER);
+ const [imageUrls, setImageUrls] = (0, import_react48.useState)([]);
+ const [selectedSkills, setSelectedSkills] = (0, import_react48.useState)([]);
+ const [statusMessage, setStatusMessage] = (0, import_react48.useState)(null);
+ const [pendingExit, setPendingExit] = (0, import_react48.useState)(false);
+ const [menuIndex, setMenuIndex] = (0, import_react48.useState)(0);
+ const [showSkillsDropdown, setShowSkillsDropdown] = (0, import_react48.useState)(false);
+ const [openRawModelDropdown, setOpenRawModelDropdown] = (0, import_react48.useState)(false);
+ const [showModelDropdown, setShowModelDropdown] = (0, import_react48.useState)(false);
+ const [fileMentionItems, setFileMentionItems] = (0, import_react48.useState)(() => scanFileMentionItems(projectRoot));
+ const [dismissedFileMentionKey, setDismissedFileMentionKey] = (0, import_react48.useState)(null);
+ const [hasTerminalFocus, setHasTerminalFocus] = (0, import_react48.useState)(true);
+ const lastCtrlDAt = import_react48.default.useRef(0);
+ const undoRedoRef = import_react48.default.useRef(createPromptUndoRedoState());
+ const wasBusyRef = import_react48.default.useRef(busy);
+ const hadFileMentionTokenRef = import_react48.default.useRef(false);
+ const appliedDraftNonceRef = import_react48.default.useRef(null);
+ const { historyCursor, navigateHistory, exitHistoryBrowsing } = useHistoryNavigation(
+ buffer,
+ setBuffer,
+ promptHistory
+ );
+ const { pastesRef, handlePaste, expandPasteMarkerAtCursor, resetPastes, hasCollapsedMarkers, hasExpandedRegions } = usePasteHandling(buffer, updateBuffer, setStatusMessage);
+ const fileMentionToken = getCurrentFileMentionToken(buffer);
+ const hasFileMentionToken = fileMentionToken !== null;
+ const fileMentionKey = fileMentionToken ? `${fileMentionToken.start}:${fileMentionToken.query}` : null;
+ const fileMentionMatches = import_react48.default.useMemo(
+ () => fileMentionToken ? filterFileMentionItems(fileMentionItems, fileMentionToken.query) : [],
+ [fileMentionItems, fileMentionToken]
+ );
+ const showFileMentionMenu = !showSkillsDropdown && !showModelDropdown && !openRawModelDropdown && fileMentionToken !== null && fileMentionKey !== dismissedFileMentionKey;
+ const slashItems = import_react48.default.useMemo(() => buildSlashCommands(skills), [skills]);
+ const slashToken = getCurrentSlashToken(buffer);
+ const slashMenu = import_react48.default.useMemo(
+ () => showSkillsDropdown || showModelDropdown || openRawModelDropdown || showFileMentionMenu ? [] : slashToken ? filterSlashCommands(slashItems, slashToken) : [],
+ [showSkillsDropdown, showModelDropdown, openRawModelDropdown, showFileMentionMenu, slashToken, slashItems]
+ );
+ const showMenu = slashMenu.length > 0;
+ const promptHistoryKey = import_react48.default.useMemo(() => promptHistory.join("\0"), [promptHistory]);
+ const hasRunningProcess = runningProcesses && runningProcesses.size > 0;
+ const processOrPasteHint = hasRunningProcess ? " \xB7 ctrl+o view output" : hasCollapsedMarkers ? " \xB7 ctrl+o expand" : hasExpandedRegions ? " \xB7 ctrl+o collapse" : "";
+ const busyStatusText = loadingText && loadingText.trim() ? `${loadingText}${processOrPasteHint}` : `esc to interrupt \xB7 ctrl+c to cancel input${processOrPasteHint}`;
+ const footerText = statusMessage ? statusMessage : busy ? busyStatusText : `enter send \xB7 shift+enter newline \xB7 @ files \xB7 ctrl+v image \xB7 / commands \xB7 ctrl+d exit${processOrPasteHint}`;
+ const showFooterText = (0, import_react48.useMemo)(
+ () => showMenu || showSkillsDropdown || openRawModelDropdown || showModelDropdown || showFileMentionMenu,
+ [showMenu, showSkillsDropdown, showModelDropdown, openRawModelDropdown, showFileMentionMenu]
+ );
+ const inputContentWidth = Math.max(1, screenWidth - PROMPT_PREFIX_WIDTH);
+ const cursorPlacement = (0, import_react48.useMemo)(
+ () => getPromptCursorPlacement(buffer, inputContentWidth),
+ [buffer, inputContentWidth]
+ );
+ const useInlineCursor = isPromptCursorAtWrapBoundary(buffer, inputContentWidth);
+ const usePositionedCursor = !disabled && hasTerminalFocus && !showFooterText && stdout.isTTY && !useInlineCursor;
+ const promptCursorLayoutKey = (0, import_react48.useMemo)(
+ () => [
+ screenWidth,
+ cursorLayoutKey ?? "default",
+ imageUrls.length,
+ selectedSkills.map((skill) => skill.name).join("")
+ ].join(""),
+ [cursorLayoutKey, imageUrls.length, screenWidth, selectedSkills]
+ );
+ useTerminalFocusReporting(stdout, !disabled);
+ useTerminalExtendedKeys(stdout, !disabled);
+ useBracketedPaste(stdout, !disabled);
+ const terminalCursorActive = usePromptTerminalCursor(
+ inputTextRef,
+ cursorPlacement,
+ !busy && usePositionedCursor,
+ promptCursorLayoutKey
+ );
+ useHiddenTerminalCursor(stdout, !disabled && (busy || !terminalCursorActive));
+ const refreshFileMentionItems = import_react48.default.useCallback(() => {
+ setFileMentionItems(scanFileMentionItems(projectRoot));
+ }, [projectRoot]);
+ (0, import_react48.useEffect)(() => {
+ refreshFileMentionItems();
+ }, [refreshFileMentionItems]);
+ (0, import_react48.useEffect)(() => {
+ if (wasBusyRef.current && !busy) {
+ refreshFileMentionItems();
+ }
+ wasBusyRef.current = busy;
+ }, [busy, refreshFileMentionItems]);
+ (0, import_react48.useEffect)(() => {
+ if (hasFileMentionToken && !hadFileMentionTokenRef.current) {
+ refreshFileMentionItems();
+ }
+ hadFileMentionTokenRef.current = hasFileMentionToken;
+ }, [hasFileMentionToken, refreshFileMentionItems]);
+ (0, import_react48.useEffect)(() => {
+ if (!showMenu) {
+ setMenuIndex(0);
+ return;
+ }
+ if (menuIndex >= slashMenu.length) {
+ setMenuIndex(slashMenu.length - 1);
+ }
+ }, [slashMenu, showMenu, menuIndex]);
+ (0, import_react48.useEffect)(() => {
+ if (!fileMentionKey) {
+ setDismissedFileMentionKey(null);
+ }
+ }, [fileMentionKey]);
+ (0, import_react48.useEffect)(() => {
+ if (!statusMessage) {
+ return;
+ }
+ const timer = setTimeout(() => setStatusMessage(null), 2500);
+ return () => clearTimeout(timer);
+ }, [statusMessage]);
+ (0, import_react48.useEffect)(() => {
+ if (!promptDraft || appliedDraftNonceRef.current === promptDraft.nonce) {
+ return;
+ }
+ appliedDraftNonceRef.current = promptDraft.nonce;
+ setBuffer({ text: promptDraft.text, cursor: promptDraft.text.length });
+ setImageUrls(promptDraft.imageUrls);
+ setSelectedSkills([]);
+ setShowSkillsDropdown(false);
+ setOpenRawModelDropdown(false);
+ exitHistoryBrowsing();
+ clearPromptUndoRedoState(undoRedoRef.current);
+ resetPastes();
+ }, [promptDraft, exitHistoryBrowsing, resetPastes]);
+ (0, import_react48.useEffect)(() => {
+ exitHistoryBrowsing();
+ }, [promptHistoryKey, exitHistoryBrowsing]);
+ useTerminalInput(
+ (input, key) => {
+ if (key.focusIn) {
+ setHasTerminalFocus(true);
+ return;
+ }
+ if (key.focusOut) {
+ setHasTerminalFocus(false);
+ return;
+ }
+ if (disabled) {
+ return;
+ }
+ if (key.escape) {
+ if (openRawModelDropdown) {
+ return;
+ }
+ if (showFileMentionMenu) {
+ return;
+ }
+ if (busy) {
+ onInterrupt();
+ setStatusMessage("Interrupting\u2026");
+ }
+ return;
+ }
+ if (isRawModeShortcut(input, key)) {
+ setShowSkillsDropdown(false);
+ setShowModelDropdown(false);
+ setOpenRawModelDropdown(true);
+ return;
+ }
+ if (key.ctrl && (input === "o" || input === "O")) {
+ if (runningProcesses && runningProcesses.size > 0 && onToggleProcessStdout) {
+ onToggleProcessStdout();
+ } else {
+ expandPasteMarkerAtCursor();
+ }
+ return;
+ }
+ if (key.ctrl && (input === "d" || input === "D")) {
+ if (!isEmpty(buffer)) {
+ updateBuffer((s) => deleteForward(s));
+ return;
+ }
+ const now = Date.now();
+ if (pendingExit && now - lastCtrlDAt.current < 2e3) {
+ onExitShortcut?.();
+ return;
+ }
+ lastCtrlDAt.current = now;
+ setPendingExit(true);
+ setStatusMessage("press ctrl+d again to exit");
+ return;
+ }
+ if (key.ctrl && (input === "c" || input === "C")) {
+ if (busy) {
+ onInterrupt();
+ setStatusMessage("Interrupting\u2026");
+ } else if (!isEmpty(buffer)) {
+ setBuffer(EMPTY_BUFFER);
+ clearUndoRedoStacks();
+ resetPastes();
+ } else {
+ setStatusMessage("press ctrl+d to exit");
+ }
+ return;
+ }
+ if (pendingExit && (!key.ctrl || input !== "d" && input !== "D")) {
+ setPendingExit(false);
+ }
+ if (openRawModelDropdown || showSkillsDropdown || showModelDropdown) {
+ return;
+ }
+ if (historyCursor !== -1 && !key.upArrow && !key.downArrow) {
+ exitHistoryBrowsing();
+ }
+ if (key.paste) {
+ handlePaste(input);
+ return;
+ }
+ if (key.ctrl && (input === "v" || input === "V")) {
+ setStatusMessage("Reading clipboard...");
+ readClipboardImageAsync().then((image2) => {
+ if (image2) {
+ setImageUrls((prev) => [...prev, image2.dataUrl]);
+ setStatusMessage("Attached image from clipboard");
+ } else {
+ setStatusMessage("No image found in clipboard");
+ }
+ }).catch(() => {
+ setStatusMessage("Failed to read clipboard");
+ });
+ return;
+ }
+ if (isClearImageAttachmentsShortcut(input, key)) {
+ if (imageUrls.length > 0) {
+ setImageUrls([]);
+ setStatusMessage("Cleared attached images");
+ } else {
+ setStatusMessage("No attached images to clear");
+ }
+ return;
+ }
+ const noModifier = !key.shift && !key.ctrl && !key.meta;
+ const returnAction = getPromptReturnKeyAction(key);
+ const isPlainReturn = returnAction === "submit";
+ if (showFileMentionMenu) {
+ if (key.upArrow || key.downArrow || key.tab || returnAction === "submit") {
+ return;
+ }
+ }
+ if (showMenu) {
+ if (key.upArrow) {
+ setMenuIndex((idx) => (idx - 1 + slashMenu.length) % slashMenu.length);
+ return;
+ }
+ if (key.downArrow) {
+ setMenuIndex((idx) => (idx + 1) % slashMenu.length);
+ return;
+ }
+ if (key.tab || returnAction === "submit") {
+ const selected = slashMenu[menuIndex];
+ if (selected) {
+ handleSlashSelection(selected);
+ return;
+ }
+ }
+ }
+ if (busy && isPlainReturn) {
+ setStatusMessage("wait for the current response or press esc to interrupt");
+ return;
+ }
+ if (returnAction === "newline") {
+ updateBuffer((s) => insertText(s, "\n"));
+ return;
+ }
+ if (returnAction === "submit") {
+ submitCurrentBuffer();
+ return;
+ }
+ if (key.delete) {
+ updateBuffer((s) => deletePasteMarkerForward(s, pastesRef.current) ?? deleteForward(s));
+ return;
+ }
+ if (key.backspace) {
+ updateBuffer((s) => deletePasteMarkerBackward(s, pastesRef.current) ?? backspace(s));
+ return;
+ }
+ if ((key.ctrl || key.meta) && key.leftArrow) {
+ updateBuffer((s) => moveWordLeft(s));
+ return;
+ }
+ if ((key.ctrl || key.meta) && key.rightArrow) {
+ updateBuffer((s) => moveWordRight(s));
+ return;
+ }
+ if (key.leftArrow) {
+ updateBuffer((s) => moveLeft(s));
+ return;
+ }
+ if (key.rightArrow) {
+ updateBuffer((s) => moveRight(s));
+ return;
+ }
+ if (key.home) {
+ updateBuffer((s) => moveLineStart(s));
+ return;
+ }
+ if (key.end) {
+ updateBuffer((s) => moveLineEnd(s));
+ return;
+ }
+ if (key.upArrow) {
+ if (noModifier && (historyCursor !== -1 || buffer.cursor === 0) && promptHistory.length > 0) {
+ navigateHistory(-1);
+ return;
+ }
+ updateBuffer((s) => moveUp(s));
+ return;
+ }
+ if (key.downArrow) {
+ if (noModifier && (historyCursor !== -1 || buffer.cursor === buffer.text.length)) {
+ navigateHistory(1);
+ return;
+ }
+ updateBuffer((s) => moveDown(s));
+ return;
+ }
+ if (key.ctrl && (input === "p" || input === "P")) {
+ navigateHistory(-1);
+ return;
+ }
+ if (key.ctrl && (input === "n" || input === "N")) {
+ navigateHistory(1);
+ return;
+ }
+ if (key.ctrl && (input === "a" || input === "A")) {
+ updateBuffer((s) => moveLineStart(s));
+ return;
+ }
+ if (key.ctrl && (input === "e" || input === "E")) {
+ updateBuffer((s) => moveLineEnd(s));
+ return;
+ }
+ if (key.ctrl && (input === "b" || input === "B")) {
+ updateBuffer((s) => moveLeft(s));
+ return;
+ }
+ if (key.ctrl && (input === "f" || input === "F")) {
+ updateBuffer((s) => moveRight(s));
+ return;
+ }
+ if (key.meta && (input === "b" || input === "B")) {
+ updateBuffer((s) => moveWordLeft(s));
+ return;
+ }
+ if (key.meta && (input === "f" || input === "F")) {
+ updateBuffer((s) => moveWordRight(s));
+ return;
+ }
+ if (key.ctrl && (input === "k" || input === "K")) {
+ updateBuffer((s) => killLine(s));
+ return;
+ }
+ if (key.ctrl && (input === "u" || input === "U")) {
+ updateBuffer(() => EMPTY_BUFFER);
+ resetPastes();
+ return;
+ }
+ if (key.ctrl && (input === "w" || input === "W")) {
+ updateBuffer((s) => deleteWordBefore(s));
+ return;
+ }
+ if (key.meta && (input === "d" || input === "D")) {
+ updateBuffer((s) => deleteWordAfter(s));
+ return;
+ }
+ if (key.meta && (input === "\x7F" || input === "\b")) {
+ updateBuffer((s) => deleteWordBefore(s));
+ return;
+ }
+ if (key.ctrl && (input === "j" || input === "J")) {
+ updateBuffer((s) => insertText(s, "\n"));
+ return;
+ }
+ if (key.ctrl && key.shift && input === "-") {
+ redo();
+ return;
+ }
+ if (key.ctrl && input === "-") {
+ undo();
+ return;
+ }
+ if (input.startsWith("\x1B")) {
+ return;
+ }
+ if (input && !key.ctrl && !key.meta) {
+ const sanitized = input.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
+ updateBuffer((s) => insertText(s, sanitized));
+ }
+ },
+ { isActive: !disabled }
+ );
+ function undo() {
+ const previous = undoPromptEdit(undoRedoRef.current, buffer);
+ if (!previous) {
+ return;
+ }
+ exitHistoryBrowsing();
+ setBuffer(previous);
+ }
+ __name(undo, "undo");
+ function redo() {
+ const next = redoPromptEdit(undoRedoRef.current, buffer);
+ if (!next) {
+ return;
+ }
+ exitHistoryBrowsing();
+ setBuffer(next);
+ }
+ __name(redo, "redo");
+ function clearUndoRedoStacks() {
+ clearPromptUndoRedoState(undoRedoRef.current);
+ }
+ __name(clearUndoRedoStacks, "clearUndoRedoStacks");
+ function updateBuffer(updater) {
+ exitHistoryBrowsing();
+ setBuffer((current) => {
+ const next = updater(current);
+ recordPromptEdit(undoRedoRef.current, current, next);
+ return next;
+ });
+ }
+ __name(updateBuffer, "updateBuffer");
+ function insertFileMentionSelection(item) {
+ if (!fileMentionToken) {
+ return;
+ }
+ updateBuffer((state) => replaceCurrentFileMentionToken(state, fileMentionToken, item.path));
+ setDismissedFileMentionKey(null);
+ }
+ __name(insertFileMentionSelection, "insertFileMentionSelection");
+ function resetPromptInput() {
+ setBuffer(EMPTY_BUFFER);
+ clearUndoRedoStacks();
+ setImageUrls([]);
+ setSelectedSkills([]);
+ setShowSkillsDropdown(false);
+ exitHistoryBrowsing();
+ resetPastes();
+ }
+ __name(resetPromptInput, "resetPromptInput");
+ function handleSlashSelection(item) {
+ if (busy && item.kind !== "exit") {
+ setStatusMessage("wait for the current response or press esc to interrupt");
+ return;
+ }
+ if (item.kind === "skill" && item.skill) {
+ addSelectedSkill(item.skill);
+ clearSlashToken();
+ setShowSkillsDropdown(false);
+ return;
+ }
+ if (item.kind === "skills") {
+ clearSlashToken();
+ setShowSkillsDropdown(true);
+ return;
+ }
+ if (item.kind === "model") {
+ clearSlashToken();
+ setShowSkillsDropdown(false);
+ setShowModelDropdown(true);
+ return;
+ }
+ if (item.kind === "raw") {
+ clearSlashToken();
+ setOpenRawModelDropdown(true);
+ return;
+ }
+ if (item.kind === "new") {
+ onSubmit({ text: "", imageUrls: [], command: "new" });
+ resetPromptInput();
+ return;
+ }
+ if (item.kind === "init") {
+ onSubmit(buildInitPromptSubmission(selectedSkills));
+ resetPromptInput();
+ return;
+ }
+ if (item.kind === "resume") {
+ onSubmit({ text: "", imageUrls: [], command: "resume" });
+ resetPromptInput();
+ return;
+ }
+ if (item.kind === "continue") {
+ onSubmit({ text: "/continue", imageUrls: [], command: "continue" });
+ resetPromptInput();
+ return;
+ }
+ if (item.kind === "undo") {
+ onSubmit({ text: "/undo", imageUrls: [], command: "undo" });
+ resetPromptInput();
+ return;
+ }
+ if (item.kind === "compact") {
+ onSubmit({ text: "/compact", imageUrls: [], command: "compact" });
+ resetPromptInput();
+ return;
+ }
+ if (item.kind === "context") {
+ onSubmit({ text: "/context", imageUrls: [], command: "context" });
+ resetPromptInput();
+ return;
+ }
+ if (item.kind === "mcp") {
+ onSubmit({ text: "/mcp", imageUrls: [], command: "mcp" });
+ resetPromptInput();
+ return;
+ }
+ if (item.kind === "exit") {
+ onSubmit({ text: "/exit", imageUrls: [], command: "exit" });
+ setBuffer(EMPTY_BUFFER);
+ clearUndoRedoStacks();
+ return;
+ }
+ }
+ __name(handleSlashSelection, "handleSlashSelection");
+ function submitCurrentBuffer() {
+ if (busy) {
+ setStatusMessage("wait for the current response or press esc to interrupt");
+ return;
+ }
+ const trimmed = buffer.text.trim();
+ if (!trimmed && imageUrls.length === 0 && selectedSkills.length === 0) {
+ return;
+ }
+ if (trimmed.startsWith("/")) {
+ const exactMatch = findExactSlashCommand(slashItems, trimmed.split(/\s+/, 1)[0]);
+ if (exactMatch) {
+ handleSlashSelection(exactMatch);
+ return;
+ }
+ }
+ onSubmit({
+ text: expandPasteMarkers(buffer.text, pastesRef.current),
+ imageUrls,
+ selectedSkills
+ });
+ resetPromptInput();
+ }
+ __name(submitCurrentBuffer, "submitCurrentBuffer");
+ function addSelectedSkill(skill) {
+ setSelectedSkills((prev) => addUniqueSkill(prev, skill));
+ }
+ __name(addSelectedSkill, "addSelectedSkill");
+ function toggleSelectedSkill(skill) {
+ setSelectedSkills((prev) => toggleSkillSelection(prev, skill));
+ }
+ __name(toggleSelectedSkill, "toggleSelectedSkill");
+ function clearSlashToken() {
+ exitHistoryBrowsing();
+ setBuffer((state) => removeCurrentSlashToken(state));
+ clearUndoRedoStacks();
+ }
+ __name(clearSlashToken, "clearSlashToken");
+ const matchedCommand = slashToken ? findExactSlashCommand(slashItems, slashToken) : null;
+ const inlineHint = matchedCommand?.args ? ` ${matchedCommand.args.join(ARGS_SEPARATOR)}` : "";
+ return /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(Box_default, { flexDirection: "column", width: screenWidth, children: [
+ imageUrls.length > 0 ? /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(Box_default, { children: [
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Text, { color: "magenta", children: formatImageAttachmentStatus(imageUrls.length) }),
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Text, { dimColor: true, children: ` (${IMAGE_ATTACHMENT_CLEAR_HINT})` })
+ ] }) : null,
+ selectedSkills.length > 0 ? /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(Box_default, { children: [
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Text, { color: "magenta", wrap: "truncate-end", children: formatSelectedSkillsStatus(selectedSkills) }),
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Text, { dimColor: true, children: " (use /skills to edit)" })
+ ] }) : null,
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(
+ Box_default,
+ {
+ width: screenWidth,
+ borderStyle: "single",
+ borderTop: true,
+ borderBottom: true,
+ borderLeft: false,
+ borderRight: false,
+ borderDimColor: true,
+ children: [
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(PromptPrefixLine, {}),
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(Box_default, { ref: inputTextRef, flexGrow: 1, flexShrink: 1, width: inputContentWidth, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Text, { wrap: "hard", children: renderBufferWithCursor(
+ buffer,
+ !disabled && hasTerminalFocus,
+ placeholder,
+ pastesRef.current,
+ !busy && !terminalCursorActive
+ ) }),
+ inlineHint ? /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Text, { dimColor: true, children: inlineHint }) : null
+ ] })
+ ]
+ }
+ ),
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
+ RawModelDropdown_default,
+ {
+ open: openRawModelDropdown,
+ onClose: setOpenRawModelDropdown,
+ onSelect: (mode) => onRawModeChange?.(mode),
+ screenWidth
+ }
+ ),
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
+ SkillsDropdown_default,
+ {
+ width: screenWidth,
+ open: showSkillsDropdown,
+ onClose: setShowSkillsDropdown,
+ skills,
+ selectedSkills,
+ onSelect: toggleSelectedSkill
+ }
+ ),
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
+ ModelsDropdown_default,
+ {
+ open: showModelDropdown,
+ modelConfig,
+ width: screenWidth,
+ onClose: () => setShowModelDropdown(false),
+ onModelConfigChange,
+ onStatusMessage: setStatusMessage
+ }
+ ),
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
+ FileMentionMenu_default,
+ {
+ open: showFileMentionMenu,
+ width: screenWidth,
+ token: fileMentionToken,
+ items: fileMentionMatches,
+ onClose: () => {
+ if (fileMentionKey) {
+ setDismissedFileMentionKey(fileMentionKey);
+ }
+ },
+ onSelect: insertFileMentionSelection
+ }
+ ),
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(SlashCommandMenu_default, { width: screenWidth, items: slashMenu, activeIndex: menuIndex }),
+ !showFooterText && /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Text, { dimColor: true, children: footerText }) }),
+ statusLineSegments && statusLineSegments.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Box_default, { flexDirection: "column", children: (() => {
+ const lines = [];
+ let currentLine = [];
+ for (const segment of statusLineSegments) {
+ if (segment.newLine && currentLine.length > 0) {
+ lines.push(currentLine);
+ currentLine = [];
+ }
+ currentLine.push(segment);
+ }
+ if (currentLine.length > 0) {
+ lines.push(currentLine);
+ }
+ return lines.map((line, lineIndex) => /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Box_default, { children: line.map((segment, index) => /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(import_react48.default.Fragment, { children: [
+ index > 0 && /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Text, { dimColor: true, children: statusLineSeparator ?? " \xB7 " }),
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(Text, { color: segment.color, dimColor: !segment.color, children: segment.text })
+ ] }, segment.id)) }, lineIndex));
+ })() })
+ ] });
+}, "PromptInput"));
+var IMAGE_ATTACHMENT_CLEAR_HINT = "ctrl+x clear images";
+function formatImageAttachmentStatus(count) {
+ if (count <= 0) {
+ return "";
+ }
+ return `\u{1F4CE} ${count} image${count === 1 ? "" : "s"} attached`;
+}
+__name(formatImageAttachmentStatus, "formatImageAttachmentStatus");
+function formatSelectedSkillsStatus(skills) {
+ const names = skills.map((skill) => skill.name).filter(Boolean);
+ if (names.length === 0) {
+ return "";
+ }
+ return `\u26A1 ${names.join(", ")}`;
+}
+__name(formatSelectedSkillsStatus, "formatSelectedSkillsStatus");
+function addUniqueSkill(skills, skill) {
+ if (isSkillSelected(skills, skill)) {
+ return skills;
+ }
+ return [...skills, skill];
+}
+__name(addUniqueSkill, "addUniqueSkill");
+function toggleSkillSelection(skills, skill) {
+ return isSkillSelected(skills, skill) ? skills.filter((item) => item.name !== skill.name) : [...skills, skill];
+}
+__name(toggleSkillSelection, "toggleSkillSelection");
+function buildInitPromptSubmission(selectedSkills) {
+ return {
+ text: "/init",
+ imageUrls: [],
+ selectedSkills: selectedSkills.length > 0 ? selectedSkills : void 0
+ };
+}
+__name(buildInitPromptSubmission, "buildInitPromptSubmission");
+function removeCurrentSlashToken(state) {
+ let start = state.cursor;
+ while (start > 0 && !/\s/.test(state.text[start - 1] ?? "")) {
+ start -= 1;
+ }
+ const token = state.text.slice(start, state.cursor);
+ if (!token.startsWith("/")) {
+ return state;
+ }
+ const text = `${state.text.slice(0, start)}${state.text.slice(state.cursor)}`;
+ return { text, cursor: start };
+}
+__name(removeCurrentSlashToken, "removeCurrentSlashToken");
+function isClearImageAttachmentsShortcut(input, key) {
+ return key.ctrl && (input === "x" || input === "X");
+}
+__name(isClearImageAttachmentsShortcut, "isClearImageAttachmentsShortcut");
+function isRawModeShortcut(input, key) {
+ return key.ctrl && (input === "r" || input === "R");
+}
+__name(isRawModeShortcut, "isRawModeShortcut");
+function getPromptReturnKeyAction(key) {
+ if (!key.return) {
+ return null;
+ }
+ if (key.shift || key.meta) {
+ return "newline";
+ }
+ return "submit";
+}
+__name(getPromptReturnKeyAction, "getPromptReturnKeyAction");
+function renderBufferWithCursor(state, isFocused, placeholder, validPastes, showSimulatedCursor = true) {
+ const text = state.text || "";
+ const cursor = Math.max(0, Math.min(state.cursor, text.length));
+ const validIds = validPastes ?? /* @__PURE__ */ new Map();
+ if (text.length === 0 && placeholder) {
+ if (!isFocused || !showSimulatedCursor) {
+ return source_default2.dim(` ${placeholder}`);
+ }
+ return renderCursorCell(" ") + source_default2.dim(` ${placeholder}`);
+ }
+ if (text.length === 0) {
+ if (!isFocused) {
+ return "";
+ }
+ return showSimulatedCursor ? renderCursorCell(" ") : " ";
+ }
+ if (!isFocused || !showSimulatedCursor) {
+ return highlightPasteMarkersInText(text, validIds);
+ }
+ return renderFocusedText(text, cursor, validIds);
+}
+__name(renderBufferWithCursor, "renderBufferWithCursor");
+function highlightPasteMarkersInText(s, validIds) {
+ if (!s.includes("[paste #")) return s.endsWith("\n") ? `${s} ` : s;
+ PASTE_MARKER_REGEX.lastIndex = 0;
+ let result = "";
+ let pos = 0;
+ let match;
+ while ((match = PASTE_MARKER_REGEX.exec(s)) !== null) {
+ result += s.slice(pos, match.index);
+ const id = Number.parseInt(match[1], 10);
+ result += validIds.has(id) ? source_default2.yellow(match[0]) : match[0];
+ pos = match.index + match[0].length;
+ }
+ result += s.slice(pos);
+ return result.endsWith("\n") ? `${result} ` : result;
+}
+__name(highlightPasteMarkersInText, "highlightPasteMarkersInText");
+function renderFocusedText(text, cursor, validIds) {
+ let result = "";
+ let pos = 0;
+ PASTE_MARKER_REGEX.lastIndex = 0;
+ let match;
+ while ((match = PASTE_MARKER_REGEX.exec(text)) !== null) {
+ const markerStart = match.index;
+ const markerEnd = match.index + match[0].length;
+ const id = Number.parseInt(match[1], 10);
+ const isReal = validIds.has(id);
+ result += renderTextSegmentWithCursor(text, pos, markerStart, cursor, false);
+ pos = markerStart;
+ result += renderTextSegmentWithCursor(text, pos, markerEnd, cursor, isReal);
+ pos = markerEnd;
+ }
+ result += renderTextSegmentWithCursor(text, pos, text.length, cursor, false);
+ return result;
+}
+__name(renderFocusedText, "renderFocusedText");
+function renderTextSegmentWithCursor(text, start, end, cursor, highlighted) {
+ if (start >= end) return "";
+ const segText = text.slice(start, end);
+ const cursorRel = cursor - start;
+ if (cursorRel < 0 || cursorRel > segText.length) {
+ return highlighted ? source_default2.yellow(segText) : segText;
+ }
+ if (cursorRel === segText.length) {
+ return highlighted ? source_default2.yellow(segText) + renderCursorCell(" ") : segText + renderCursorCell(" ");
+ }
+ const at = segText[cursorRel];
+ if (at === "\n") {
+ const before2 = segText.slice(0, cursorRel);
+ const after2 = segText.slice(cursorRel + 1);
+ return before2 + renderCursorCell(" ") + "\n" + after2;
+ }
+ const before = segText.slice(0, cursorRel);
+ const after = segText.slice(cursorRel + 1);
+ if (highlighted) {
+ return source_default2.yellow(before) + renderCursorCell(at) + source_default2.yellow(after);
+ }
+ return before + renderCursorCell(at) + after;
+}
+__name(renderTextSegmentWithCursor, "renderTextSegmentWithCursor");
+function renderCursorCell(value) {
+ return `\x1B[7m${value}\x1B[27m`;
+}
+__name(renderCursorCell, "renderCursorCell");
+
+// packages/cli/src/ui/views/SessionList.tsx
+init_esbuild_shims();
+var import_react49 = __toESM(require_react(), 1);
+var import_jsx_runtime10 = __toESM(require_jsx_runtime(), 1);
+function filterSessions(sessions, query) {
+ if (!query.trim()) {
+ return sessions;
+ }
+ const lowerQuery = query.toLowerCase().trim();
+ return sessions.filter((session) => {
+ if (session.summary && session.summary.toLowerCase().includes(lowerQuery)) {
+ return true;
+ }
+ if (session.status.toLowerCase().includes(lowerQuery)) {
+ return true;
+ }
+ if (session.failReason && session.failReason.toLowerCase().includes(lowerQuery)) {
+ return true;
+ }
+ if (session.assistantReply && session.assistantReply.toLowerCase().includes(lowerQuery)) {
+ return true;
+ }
+ return false;
+ });
+}
+__name(filterSessions, "filterSessions");
+function SessionList({ sessions, onSelect, onCancel, onDelete, onRename }) {
+ const [index, setIndex] = (0, import_react49.useState)(0);
+ const [searchQuery, setSearchQuery] = (0, import_react49.useState)("");
+ const [confirmDeleteSessionId, setConfirmDeleteSessionId] = (0, import_react49.useState)(null);
+ const [renameSessionId, setRenameSessionId] = (0, import_react49.useState)(null);
+ const [renameValue, setRenameValue] = (0, import_react49.useState)("");
+ const [renameCursor, setRenameCursor] = (0, import_react49.useState)(0);
+ const { columns, rows } = use_window_size_default();
+ const filteredSessions = (0, import_react49.useMemo)(() => filterSessions(sessions, searchQuery), [sessions, searchQuery]);
+ const safeIndex = (0, import_react49.useMemo)(() => {
+ if (filteredSessions.length === 0) return 0;
+ return Math.max(0, Math.min(index, filteredSessions.length - 1));
+ }, [index, filteredSessions.length]);
+ const maxVisibleSessions = (0, import_react49.useMemo)(() => {
+ const reservedLines = searchQuery ? 12 : 9;
+ const linesPerSession = 3;
+ const availableLines = Math.max(0, Math.min(rows, 30) - reservedLines);
+ return Math.max(1, Math.floor(availableLines / linesPerSession));
+ }, [rows, searchQuery]);
+ const scrollOffset = (0, import_react49.useMemo)(() => {
+ if (safeIndex < maxVisibleSessions) return 0;
+ return safeIndex - maxVisibleSessions + 1;
+ }, [safeIndex, maxVisibleSessions]);
+ const visibleSessions = (0, import_react49.useMemo)(() => {
+ return filteredSessions.slice(scrollOffset, scrollOffset + maxVisibleSessions);
+ }, [filteredSessions, scrollOffset, maxVisibleSessions]);
+ const handleBackspace = (0, import_react49.useCallback)(() => {
+ setSearchQuery((prev) => prev.slice(0, -1));
+ setIndex(0);
+ }, []);
+ const selectedSession = filteredSessions[safeIndex];
+ use_input_default((input, key) => {
+ if (renameSessionId) {
+ if (key.return) {
+ if (renameValue.trim()) {
+ onRename?.(renameSessionId, renameValue.trim());
+ }
+ setRenameSessionId(null);
+ setRenameValue("");
+ setRenameCursor(0);
+ return;
+ }
+ if (key.escape) {
+ setRenameSessionId(null);
+ setRenameValue("");
+ setRenameCursor(0);
+ return;
+ }
+ if (key.leftArrow) {
+ setRenameCursor((c) => Math.max(0, c - 1));
+ return;
+ }
+ if (key.rightArrow) {
+ setRenameCursor((c) => Math.min(renameValue.length, c + 1));
+ return;
+ }
+ if (key.home) {
+ setRenameCursor(0);
+ return;
+ }
+ if (key.end) {
+ setRenameCursor(renameValue.length);
+ return;
+ }
+ if (key.delete) {
+ if (renameCursor < renameValue.length) {
+ setRenameValue((prev) => prev.slice(0, renameCursor) + prev.slice(renameCursor + 1));
+ }
+ return;
+ }
+ if (key.backspace) {
+ if (renameCursor > 0) {
+ setRenameValue((prev) => prev.slice(0, renameCursor - 1) + prev.slice(renameCursor));
+ setRenameCursor((c) => c - 1);
+ }
+ return;
+ }
+ if (input && input.length > 0 && !key.meta && !key.ctrl && !key.tab) {
+ if (key.upArrow || key.downArrow) {
+ return;
+ }
+ setRenameValue((prev) => prev.slice(0, renameCursor) + input + prev.slice(renameCursor));
+ setRenameCursor((c) => c + input.length);
+ return;
+ }
+ return;
+ }
+ if (confirmDeleteSessionId) {
+ if (key.return) {
+ onDelete?.(confirmDeleteSessionId);
+ setConfirmDeleteSessionId(null);
+ return;
+ }
+ if (key.escape) {
+ setConfirmDeleteSessionId(null);
+ return;
+ }
+ return;
+ }
+ if (key.escape) {
+ if (searchQuery) {
+ setSearchQuery("");
+ setIndex(0);
+ return;
+ }
+ onCancel();
+ return;
+ }
+ if (key.ctrl && (input === "c" || input === "C")) {
+ onCancel();
+ return;
+ }
+ if (key.ctrl && (input === "r" || input === "R")) {
+ if (selectedSession && onRename) {
+ const name = selectedSession.summary || "";
+ setRenameSessionId(selectedSession.id);
+ setRenameValue(name);
+ setRenameCursor(name.length);
+ return;
+ }
+ }
+ if (key.delete || key.backspace) {
+ if (searchQuery) {
+ handleBackspace();
+ return;
+ }
+ if (selectedSession && onDelete) {
+ setConfirmDeleteSessionId(selectedSession.id);
+ return;
+ }
+ }
+ if (input && input.length > 0 && !key.meta && !key.ctrl && !key.tab && !key.return) {
+ if (key.upArrow || key.downArrow || key.leftArrow || key.rightArrow) {
+ return;
+ }
+ setSearchQuery((prev) => prev + input);
+ setIndex(0);
+ return;
+ }
+ if (filteredSessions.length === 0) {
+ return;
+ }
+ if (key.upArrow) {
+ setIndex((i) => Math.max(0, i - 1));
+ return;
+ }
+ if (key.downArrow) {
+ setIndex((i) => Math.min(filteredSessions.length - 1, i + 1));
+ return;
+ }
+ if (key.pageUp) {
+ setIndex((i) => Math.max(0, i - maxVisibleSessions));
+ return;
+ }
+ if (key.pageDown) {
+ setIndex((i) => Math.min(filteredSessions.length - 1, i + maxVisibleSessions));
+ return;
+ }
+ if (key.home) {
+ setIndex(0);
+ return;
+ }
+ if (key.end) {
+ setIndex(filteredSessions.length - 1);
+ return;
+ }
+ if (key.return) {
+ const session = filteredSessions[safeIndex];
+ if (session) {
+ onSelect(session.id);
+ }
+ }
+ });
+ const hasActiveSearch = searchQuery.trim().length > 0;
+ if (sessions.length === 0) {
+ return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(Box_default, { flexDirection: "column", children: [
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Text, { color: "yellow", children: "No previous sessions found." }),
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Text, { dimColor: true, children: "Press Esc to go back." })
+ ] });
+ }
+ return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
+ Box_default,
+ {
+ flexDirection: "column",
+ width: Math.max(20, columns - 6),
+ height: Math.max(5, Math.min(rows - 1, 30)),
+ overflow: "hidden",
+ paddingX: 1,
+ marginTop: 1,
+ children: /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(Box_default, { flexDirection: "column", borderStyle: "round", borderDimColor: true, flexGrow: 1, overflow: "hidden", children: [
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(Box_default, { paddingX: 1, flexDirection: "column", children: [
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(Box_default, { children: [
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Text, { bold: true, color: "cyanBright", children: "Resume a session" }),
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(Text, { bold: true, color: "#229ac3", children: [
+ " ",
+ "(",
+ sessions.length,
+ " total",
+ hasActiveSearch ? `, ${filteredSessions.length} matched` : "",
+ ")"
+ ] })
+ ] }),
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(Box_default, { marginTop: hasActiveSearch || searchQuery ? 0 : 0, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Text, { dimColor: true, children: searchQuery ? `Search: ${searchQuery}` : "Type to search\u2026" }),
+ searchQuery ? /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Text, { bold: true, children: "|" }) : null
+ ] })
+ ] }),
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(
+ Box_default,
+ {
+ borderTop: true,
+ borderBottom: true,
+ borderLeft: false,
+ borderRight: false,
+ borderStyle: "round",
+ borderDimColor: true,
+ flexDirection: "column",
+ flexGrow: 1,
+ paddingX: 1,
+ overflow: "hidden",
+ children: [
+ filteredSessions.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Box_default, { paddingY: 1, children: /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(Text, { color: "yellow", children: [
+ 'No sessions match "',
+ searchQuery,
+ '".'
+ ] }) }) : visibleSessions.map((session, i) => {
+ const actualIndex = scrollOffset + i;
+ const isSelected = actualIndex === safeIndex;
+ const isConfirming = confirmDeleteSessionId === session.id;
+ const isRenaming = renameSessionId === session.id;
+ return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(Box_default, { height: 2, marginBottom: 1, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Text, { color: "#229ac3", children: isSelected ? "> " : " " }) }),
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(Box_default, { flexDirection: "column", flexGrow: 1, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(Box_default, { width: "100%", children: [
+ isRenaming ? /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(Text, { color: "yellow", children: [
+ "Rename: ",
+ renameValue.slice(0, renameCursor),
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Text, { bold: true, children: "|" }),
+ renameValue.slice(renameCursor)
+ ] }) : /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Text, { ...isSelected ? { bold: true } : {}, color: isSelected ? "#229ac3" : void 0, children: formatSessionTitle(session.summary || "Untitled") }),
+ isConfirming ? /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Text, { color: "yellow", children: " [Delete? Enter=yes, Esc=no]" }) : isRenaming ? null : /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(Text, { dimColor: true, children: [
+ " (",
+ formatSessionStatus(session.status),
+ ")"
+ ] })
+ ] }),
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Box_default, { width: "100%", children: /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(Text, { dimColor: true, children: [
+ formatTimestamp(session.updateTime),
+ " "
+ ] }) })
+ ] })
+ ] }, session.id);
+ }),
+ scrollOffset > 0 || scrollOffset + maxVisibleSessions < filteredSessions.length ? /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(Box_default, { marginTop: 1, children: [
+ scrollOffset > 0 ? /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(Text, { dimColor: true, children: [
+ "\u2026 ",
+ scrollOffset,
+ " sessions above. "
+ ] }) : null,
+ scrollOffset + maxVisibleSessions < filteredSessions.length ? /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(Text, { dimColor: true, children: [
+ "\u2026 ",
+ filteredSessions.length - scrollOffset - maxVisibleSessions,
+ " sessions below."
+ ] }) : null
+ ] }) : null
+ ]
+ }
+ ),
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Box_default, { flexDirection: "column", children: renameSessionId ? /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(Box_default, { children: [
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Text, { color: "yellow", children: "Input new session name, " }),
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Text, { bold: true, color: "green", children: "Enter" }),
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Text, { dimColor: true, children: " to save \xB7 " }),
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Text, { bold: true, color: "red", children: "Esc" }),
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Text, { dimColor: true, children: " to cancel" })
+ ] }) : confirmDeleteSessionId ? /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(Box_default, { children: [
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Text, { color: "yellow", children: "Delete this session? " }),
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Text, { bold: true, color: "green", children: "Enter" }),
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Text, { dimColor: true, children: " to confirm \xB7 " }),
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Text, { bold: true, color: "red", children: "Esc" }),
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Text, { dimColor: true, children: " to cancel" })
+ ] }) : hasActiveSearch ? /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(Box_default, { children: [
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Text, { dimColor: true, children: "Esc clear search \xB7 " }),
+ /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Text, { dimColor: true, children: "\u2191/\u2193 navigate \xB7 Enter select \xB7 Esc again to cancel" })
+ ] }) : /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(Text, { dimColor: true, children: "Type to search \xB7 \u2191/\u2193 navigate \xB7 PgUp/PgDn page \xB7 Enter select \xB7 Esc cancel \xB7 Del delete \xB7 Ctrl+r rename" }) }) })
+ ] })
+ }
+ );
+}
+__name(SessionList, "SessionList");
+function formatTimestamp(value) {
+ try {
+ const date5 = new Date(value);
+ if (Number.isNaN(date5.valueOf())) {
+ return value;
+ }
+ return date5.toLocaleString();
+ } catch {
+ return value;
+ }
+}
+__name(formatTimestamp, "formatTimestamp");
+function formatSessionTitle(value, max = 70) {
+ return truncate(value.replace(/\r?\n/g, " ").replace(/\s+/g, " ").trim(), max);
+}
+__name(formatSessionTitle, "formatSessionTitle");
+function formatSessionStatus(status) {
+ switch (status) {
+ case "completed":
+ return "done";
+ case "processing":
+ return "running";
+ case "pending":
+ return "pending";
+ case "waiting_for_user":
+ return "waiting";
+ case "failed":
+ return "failed";
+ case "interrupted":
+ return "stopped";
+ case "ask_permission":
+ return "waiting";
+ case "permission_denied":
+ return "denied";
+ default:
+ return status;
+ }
+}
+__name(formatSessionStatus, "formatSessionStatus");
+
+// packages/cli/src/ui/views/UndoSelector.tsx
+init_esbuild_shims();
+var import_react50 = __toESM(require_react(), 1);
+var import_jsx_runtime11 = __toESM(require_jsx_runtime(), 1);
+var MAX_VISIBLE_TARGETS = 7;
+function UndoSelector({ targets, onSelect, onCancel }) {
+ const [phase, setPhase] = (0, import_react50.useState)("message");
+ const [targetIndex, setTargetIndex] = (0, import_react50.useState)(Math.max(0, targets.length - 1));
+ const [modeIndex, setModeIndex] = (0, import_react50.useState)(0);
+ const { columns, rows } = use_window_size_default();
+ const safeTargetIndex = (0, import_react50.useMemo)(() => {
+ if (targets.length === 0) {
+ return 0;
+ }
+ return Math.max(0, Math.min(targetIndex, targets.length - 1));
+ }, [targetIndex, targets.length]);
+ const selectedTarget = targets[safeTargetIndex] ?? null;
+ const maxVisible = Math.max(1, Math.min(MAX_VISIBLE_TARGETS, rows - 8));
+ const scrollOffset = Math.max(0, Math.min(safeTargetIndex - Math.floor(maxVisible / 2), targets.length - maxVisible));
+ const visibleTargets = targets.slice(scrollOffset, scrollOffset + maxVisible);
+ use_input_default((input, key) => {
+ if (key.escape || key.ctrl && (input === "c" || input === "C")) {
+ if (phase === "mode") {
+ setPhase("message");
+ return;
+ }
+ onCancel();
+ return;
+ }
+ if (targets.length === 0) {
+ return;
+ }
+ if (phase === "message") {
+ if (key.upArrow) {
+ setTargetIndex((index) => Math.max(0, index - 1));
+ return;
+ }
+ if (key.downArrow) {
+ setTargetIndex((index) => Math.min(targets.length - 1, index + 1));
+ return;
+ }
+ if (key.home) {
+ setTargetIndex(0);
+ return;
+ }
+ if (key.end) {
+ setTargetIndex(targets.length - 1);
+ return;
+ }
+ if (key.return) {
+ setModeIndex(selectedTarget?.canRestoreCode ? 0 : 1);
+ setPhase("mode");
+ }
+ return;
+ }
+ if (key.upArrow || key.downArrow) {
+ setModeIndex((index) => index === 0 ? 1 : 0);
+ return;
+ }
+ if (key.return && selectedTarget) {
+ onSelect(selectedTarget, modeIndex === 0 ? "code-and-conversation" : "conversation");
+ }
+ });
+ if (targets.length === 0) {
+ return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(Box_default, { flexDirection: "column", marginTop: 1, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(Text, { color: "yellow", children: "Nothing to undo yet." }),
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(Text, { dimColor: true, children: "Press Esc to go back." })
+ ] });
+ }
+ return /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
+ Box_default,
+ {
+ flexDirection: "column",
+ width: Math.max(20, columns - 6),
+ height: Math.max(5, Math.min(rows - 1, 30)),
+ overflow: "hidden",
+ paddingX: 1,
+ marginTop: 1,
+ children: /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(Box_default, { flexDirection: "column", borderStyle: "round", borderDimColor: true, flexGrow: 1, overflow: "hidden", children: [
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(Box_default, { paddingX: 1, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(Text, { bold: true, color: "#229ac3", children: "Undo" }),
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(Text, { dimColor: true, children: " restore to the point before a prompt" })
+ ] }),
+ phase === "message" ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
+ Box_default,
+ {
+ borderTop: true,
+ borderBottom: true,
+ borderLeft: false,
+ borderRight: false,
+ borderStyle: "round",
+ borderDimColor: true,
+ flexDirection: "column",
+ flexGrow: 1,
+ paddingX: 1,
+ overflow: "hidden",
+ children: visibleTargets.map((target, visibleIndex) => {
+ const actualIndex = scrollOffset + visibleIndex;
+ const isActive = actualIndex === safeTargetIndex;
+ return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(Box_default, { height: 2, marginBottom: 1, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(Text, { color: "#229ac3", children: isActive ? "> " : " " }),
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(Box_default, { flexDirection: "column", flexGrow: 1, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(Text, { color: isActive ? "#229ac3" : void 0, bold: isActive, children: formatUndoMessage(target.message.content) }),
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(Text, { dimColor: true, children: [
+ formatTimestamp2(target.message.createTime),
+ target.canRestoreCode ? " \xB7 code checkpoint available" : " \xB7 conversation only"
+ ] })
+ ] })
+ ] }, target.message.id);
+ })
+ }
+ ) : /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(
+ Box_default,
+ {
+ borderTop: true,
+ borderBottom: true,
+ borderLeft: false,
+ borderRight: false,
+ borderStyle: "round",
+ borderDimColor: true,
+ flexDirection: "column",
+ flexGrow: 1,
+ paddingX: 1,
+ overflow: "hidden",
+ children: [
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(Text, { dimColor: true, children: "Selected prompt:" }),
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(Text, { children: formatUndoMessage(selectedTarget?.message.content ?? "") }),
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(Box_default, { marginTop: 1, flexDirection: "column", children: [
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(Text, { color: modeIndex === 0 ? "cyanBright" : void 0, children: [
+ modeIndex === 0 ? "> " : " ",
+ "Restore code and conversation"
+ ] }),
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(Text, { dimColor: true, children: [
+ " ",
+ selectedTarget?.canRestoreCode ? "Restore files from the recorded Git checkpoint, then fork the conversation." : "No code checkpoint is recorded for this prompt."
+ ] }),
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(Text, { color: modeIndex === 1 ? "cyanBright" : void 0, children: [
+ modeIndex === 1 ? "> " : " ",
+ "Restore conversation"
+ ] }),
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(Text, { dimColor: true, children: [
+ " ",
+ "Fork the conversation without changing files."
+ ] })
+ ] })
+ ]
+ }
+ ),
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(Text, { dimColor: true, children: phase === "message" ? "\u2191/\u2193 navigate \xB7 Enter choose \xB7 Esc cancel" : "\u2191/\u2193 choose restore mode \xB7 Enter restore \xB7 Esc back" }) })
+ ] })
+ }
+ );
+}
+__name(UndoSelector, "UndoSelector");
+function formatUndoMessage(content) {
+ const text = typeof content === "string" && content.trim() ? content.trim() : "(empty message)";
+ const singleLine = text.replace(/\r?\n/g, " ").replace(/\s+/g, " ");
+ return singleLine.length > 90 ? `${singleLine.slice(0, 89)}\u2026` : singleLine;
+}
+__name(formatUndoMessage, "formatUndoMessage");
+function formatTimestamp2(value) {
+ const date5 = new Date(value);
+ if (Number.isNaN(date5.valueOf())) {
+ return value;
+ }
+ return date5.toLocaleString();
+}
+__name(formatTimestamp2, "formatTimestamp");
+
+// packages/cli/src/ui/core/loading-text.ts
+init_esbuild_shims();
+var STALL_THRESHOLD_MS = 3e3;
+function buildLoadingText(input) {
+ const { progress, processes, now } = input;
+ const processText = buildProcessLoadingText(processes, now);
+ if (processText) {
+ return processText;
+ }
+ if (!progress) {
+ return "Thinking...";
+ }
+ const startedAt = parseTimestamp(progress.startedAt);
+ if (startedAt === null) {
+ return "Thinking...";
+ }
+ const elapsedMs = Math.max(0, now - startedAt);
+ if (elapsedMs < STALL_THRESHOLD_MS) {
+ return "Thinking...";
+ }
+ const elapsedSeconds = Math.floor(elapsedMs / 1e3);
+ const tokens = progress.formattedTokens || "0";
+ return `Thinking... (${elapsedSeconds}s) \xB7 \u2193 ${tokens} tokens`;
+}
+__name(buildLoadingText, "buildLoadingText");
+function buildProcessLoadingText(processes, now) {
+ if (!processes || processes.size === 0) {
+ return null;
+ }
+ const first = processes.values().next().value;
+ if (!first) {
+ return null;
+ }
+ return `(${formatElapsedTime(first.startTime, now)}) ${first.command}`;
+}
+__name(buildProcessLoadingText, "buildProcessLoadingText");
+function formatElapsedTime(startTimeIso, now) {
+ const startTime = parseTimestamp(startTimeIso);
+ const elapsedMs = startTime === null ? 0 : Math.max(0, now - startTime);
+ const elapsedSeconds = Math.floor(elapsedMs / 1e3);
+ const minutes = Math.floor(elapsedSeconds / 60);
+ const seconds = elapsedSeconds % 60;
+ if (minutes > 0) {
+ return `${minutes}m${seconds}s`;
+ }
+ return `${seconds}s`;
+}
+__name(formatElapsedTime, "formatElapsedTime");
+function parseTimestamp(value) {
+ const parsed = Date.parse(value);
+ if (Number.isNaN(parsed)) {
+ return null;
+ }
+ return parsed;
+}
+__name(parseTimestamp, "parseTimestamp");
+
+// packages/cli/src/ui/core/thinking-state.ts
+init_esbuild_shims();
+function findExpandedThinkingId(messages) {
+ let expanded = null;
+ for (const message of messages) {
+ if (message.role !== "assistant") {
+ continue;
+ }
+ if (message.meta?.asThinking) {
+ expanded = message.id;
+ } else {
+ expanded = null;
+ }
+ }
+ return expanded;
+}
+__name(findExpandedThinkingId, "findExpandedThinkingId");
+function isCollapsedThinking(message, expandedId) {
+ if (message.role !== "assistant") {
+ return false;
+ }
+ if (!message.meta?.asThinking) {
+ return false;
+ }
+ return message.id !== expandedId;
+}
+__name(isCollapsedThinking, "isCollapsedThinking");
+
+// packages/cli/src/ui/views/WelcomeScreen.tsx
+init_esbuild_shims();
+var import_react52 = __toESM(require_react(), 1);
+import * as os14 from "node:os";
+import path21 from "node:path";
+
+// packages/cli/src/ui/views/ThemedGradient.tsx
+init_esbuild_shims();
+
+// node_modules/ink-gradient/dist/index.js
+init_esbuild_shims();
+var import_jsx_runtime12 = __toESM(require_jsx_runtime(), 1);
+var import_react51 = __toESM(require_react(), 1);
+
+// node_modules/gradient-string/dist/index.js
+init_esbuild_shims();
+
+// node_modules/gradient-string/node_modules/chalk/source/index.js
+init_esbuild_shims();
+
+// node_modules/gradient-string/node_modules/chalk/source/vendor/ansi-styles/index.js
+init_esbuild_shims();
+var ANSI_BACKGROUND_OFFSET6 = 10;
+var wrapAnsi166 = /* @__PURE__ */ __name((offset = 0) => (code) => `\x1B[${code + offset}m`, "wrapAnsi16");
+var wrapAnsi2566 = /* @__PURE__ */ __name((offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`, "wrapAnsi256");
+var wrapAnsi16m6 = /* @__PURE__ */ __name((offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`, "wrapAnsi16m");
+var styles9 = {
+ 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],
+ overline: [53, 55],
+ 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],
+ gray: [90, 39],
+ // Alias of `blackBright`
+ grey: [90, 39],
+ // Alias of `blackBright`
+ 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],
+ bgGray: [100, 49],
+ // Alias of `bgBlackBright`
+ bgGrey: [100, 49],
+ // Alias of `bgBlackBright`
+ bgRedBright: [101, 49],
+ bgGreenBright: [102, 49],
+ bgYellowBright: [103, 49],
+ bgBlueBright: [104, 49],
+ bgMagentaBright: [105, 49],
+ bgCyanBright: [106, 49],
+ bgWhiteBright: [107, 49]
+ }
+};
+var modifierNames6 = Object.keys(styles9.modifier);
+var foregroundColorNames6 = Object.keys(styles9.color);
+var backgroundColorNames6 = Object.keys(styles9.bgColor);
+var colorNames6 = [...foregroundColorNames6, ...backgroundColorNames6];
+function assembleStyles6() {
+ const codes = /* @__PURE__ */ new Map();
+ for (const [groupName, group] of Object.entries(styles9)) {
+ for (const [styleName, style] of Object.entries(group)) {
+ styles9[styleName] = {
+ open: `\x1B[${style[0]}m`,
+ close: `\x1B[${style[1]}m`
+ };
+ group[styleName] = styles9[styleName];
+ codes.set(style[0], style[1]);
+ }
+ Object.defineProperty(styles9, groupName, {
+ value: group,
+ enumerable: false
+ });
+ }
+ Object.defineProperty(styles9, "codes", {
+ value: codes,
+ enumerable: false
+ });
+ styles9.color.close = "\x1B[39m";
+ styles9.bgColor.close = "\x1B[49m";
+ styles9.color.ansi = wrapAnsi166();
+ styles9.color.ansi256 = wrapAnsi2566();
+ styles9.color.ansi16m = wrapAnsi16m6();
+ styles9.bgColor.ansi = wrapAnsi166(ANSI_BACKGROUND_OFFSET6);
+ styles9.bgColor.ansi256 = wrapAnsi2566(ANSI_BACKGROUND_OFFSET6);
+ styles9.bgColor.ansi16m = wrapAnsi16m6(ANSI_BACKGROUND_OFFSET6);
+ Object.defineProperties(styles9, {
+ rgbToAnsi256: {
+ value(red, green, blue) {
+ if (red === green && green === blue) {
+ if (red < 8) {
+ return 16;
+ }
+ if (red > 248) {
+ return 231;
+ }
+ return Math.round((red - 8) / 247 * 24) + 232;
+ }
+ return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
+ },
+ enumerable: false
+ },
+ hexToRgb: {
+ value(hex3) {
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex3.toString(16));
+ if (!matches) {
+ return [0, 0, 0];
+ }
+ let [colorString] = matches;
+ if (colorString.length === 3) {
+ colorString = [...colorString].map((character) => character + character).join("");
+ }
+ const integer2 = Number.parseInt(colorString, 16);
+ return [
+ /* eslint-disable no-bitwise */
+ integer2 >> 16 & 255,
+ integer2 >> 8 & 255,
+ integer2 & 255
+ /* eslint-enable no-bitwise */
+ ];
+ },
+ enumerable: false
+ },
+ hexToAnsi256: {
+ value: /* @__PURE__ */ __name((hex3) => styles9.rgbToAnsi256(...styles9.hexToRgb(hex3)), "value"),
+ enumerable: false
+ },
+ ansi256ToAnsi: {
+ value(code) {
+ if (code < 8) {
+ return 30 + code;
+ }
+ if (code < 16) {
+ return 90 + (code - 8);
+ }
+ let red;
+ let green;
+ let blue;
+ if (code >= 232) {
+ red = ((code - 232) * 10 + 8) / 255;
+ green = red;
+ blue = red;
+ } else {
+ code -= 16;
+ const remainder = code % 36;
+ red = Math.floor(code / 36) / 5;
+ green = Math.floor(remainder / 6) / 5;
+ blue = remainder % 6 / 5;
+ }
+ const value = Math.max(red, green, blue) * 2;
+ if (value === 0) {
+ return 30;
+ }
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
+ if (value === 2) {
+ result += 60;
+ }
+ return result;
+ },
+ enumerable: false
+ },
+ rgbToAnsi: {
+ value: /* @__PURE__ */ __name((red, green, blue) => styles9.ansi256ToAnsi(styles9.rgbToAnsi256(red, green, blue)), "value"),
+ enumerable: false
+ },
+ hexToAnsi: {
+ value: /* @__PURE__ */ __name((hex3) => styles9.ansi256ToAnsi(styles9.hexToAnsi256(hex3)), "value"),
+ enumerable: false
+ }
+ });
+ return styles9;
+}
+__name(assembleStyles6, "assembleStyles");
+var ansiStyles6 = assembleStyles6();
+var ansi_styles_default6 = ansiStyles6;
+
+// node_modules/gradient-string/node_modules/chalk/source/vendor/supports-color/index.js
+init_esbuild_shims();
+import process16 from "node:process";
+import os13 from "node:os";
+import tty4 from "node:tty";
+function hasFlag3(flag, argv = globalThis.Deno ? globalThis.Deno.args : process16.argv) {
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
+ const position = argv.indexOf(prefix + flag);
+ const terminatorPosition = argv.indexOf("--");
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
+}
+__name(hasFlag3, "hasFlag");
+var { env: env4 } = process16;
+var flagForceColor3;
+if (hasFlag3("no-color") || hasFlag3("no-colors") || hasFlag3("color=false") || hasFlag3("color=never")) {
+ flagForceColor3 = 0;
+} else if (hasFlag3("color") || hasFlag3("colors") || hasFlag3("color=true") || hasFlag3("color=always")) {
+ flagForceColor3 = 1;
+}
+function envForceColor3() {
+ if ("FORCE_COLOR" in env4) {
+ if (env4.FORCE_COLOR === "true") {
+ return 1;
+ }
+ if (env4.FORCE_COLOR === "false") {
+ return 0;
+ }
+ return env4.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env4.FORCE_COLOR, 10), 3);
+ }
+}
+__name(envForceColor3, "envForceColor");
+function translateLevel3(level) {
+ if (level === 0) {
+ return false;
+ }
+ return {
+ level,
+ hasBasic: true,
+ has256: level >= 2,
+ has16m: level >= 3
+ };
+}
+__name(translateLevel3, "translateLevel");
+function _supportsColor3(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
+ const noFlagForceColor = envForceColor3();
+ if (noFlagForceColor !== void 0) {
+ flagForceColor3 = noFlagForceColor;
+ }
+ const forceColor = sniffFlags ? flagForceColor3 : noFlagForceColor;
+ if (forceColor === 0) {
+ return 0;
+ }
+ if (sniffFlags) {
+ if (hasFlag3("color=16m") || hasFlag3("color=full") || hasFlag3("color=truecolor")) {
+ return 3;
+ }
+ if (hasFlag3("color=256")) {
+ return 2;
+ }
+ }
+ if ("TF_BUILD" in env4 && "AGENT_NAME" in env4) {
+ return 1;
+ }
+ if (haveStream && !streamIsTTY && forceColor === void 0) {
+ return 0;
+ }
+ const min = forceColor || 0;
+ if (env4.TERM === "dumb") {
+ return min;
+ }
+ if (process16.platform === "win32") {
+ const osRelease = os13.release().split(".");
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
+ }
+ return 1;
+ }
+ if ("CI" in env4) {
+ if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => key in env4)) {
+ return 3;
+ }
+ if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env4) || env4.CI_NAME === "codeship") {
+ return 1;
+ }
+ return min;
+ }
+ if ("TEAMCITY_VERSION" in env4) {
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env4.TEAMCITY_VERSION) ? 1 : 0;
+ }
+ if (env4.COLORTERM === "truecolor") {
+ return 3;
+ }
+ if (env4.TERM === "xterm-kitty") {
+ return 3;
+ }
+ if (env4.TERM === "xterm-ghostty") {
+ return 3;
+ }
+ if (env4.TERM === "wezterm") {
+ return 3;
+ }
+ if ("TERM_PROGRAM" in env4) {
+ const version2 = Number.parseInt((env4.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
+ switch (env4.TERM_PROGRAM) {
+ case "iTerm.app": {
+ return version2 >= 3 ? 3 : 2;
+ }
+ case "Apple_Terminal": {
+ return 2;
+ }
+ }
+ }
+ if (/-256(color)?$/i.test(env4.TERM)) {
+ return 2;
+ }
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env4.TERM)) {
+ return 1;
+ }
+ if ("COLORTERM" in env4) {
+ return 1;
+ }
+ return min;
+}
+__name(_supportsColor3, "_supportsColor");
+function createSupportsColor3(stream, options2 = {}) {
+ const level = _supportsColor3(stream, {
+ streamIsTTY: stream && stream.isTTY,
+ ...options2
+ });
+ return translateLevel3(level);
+}
+__name(createSupportsColor3, "createSupportsColor");
+var supportsColor3 = {
+ stdout: createSupportsColor3({ isTTY: tty4.isatty(1) }),
+ stderr: createSupportsColor3({ isTTY: tty4.isatty(2) })
+};
+var supports_color_default3 = supportsColor3;
+
+// node_modules/gradient-string/node_modules/chalk/source/utilities.js
+init_esbuild_shims();
+function stringReplaceAll3(string4, substring, replacer) {
+ let index = string4.indexOf(substring);
+ if (index === -1) {
+ return string4;
+ }
+ const substringLength = substring.length;
+ let endIndex = 0;
+ let returnValue = "";
+ do {
+ returnValue += string4.slice(endIndex, index) + substring + replacer;
+ endIndex = index + substringLength;
+ index = string4.indexOf(substring, endIndex);
+ } while (index !== -1);
+ returnValue += string4.slice(endIndex);
+ return returnValue;
+}
+__name(stringReplaceAll3, "stringReplaceAll");
+function stringEncaseCRLFWithFirstIndex3(string4, prefix, postfix, index) {
+ let endIndex = 0;
+ let returnValue = "";
+ do {
+ const gotCR = string4[index - 1] === "\r";
+ returnValue += string4.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
+ endIndex = index + 1;
+ index = string4.indexOf("\n", endIndex);
+ } while (index !== -1);
+ returnValue += string4.slice(endIndex);
+ return returnValue;
+}
+__name(stringEncaseCRLFWithFirstIndex3, "stringEncaseCRLFWithFirstIndex");
+
+// node_modules/gradient-string/node_modules/chalk/source/index.js
+var { stdout: stdoutColor3, stderr: stderrColor3 } = supports_color_default3;
+var GENERATOR3 = /* @__PURE__ */ Symbol("GENERATOR");
+var STYLER3 = /* @__PURE__ */ Symbol("STYLER");
+var IS_EMPTY3 = /* @__PURE__ */ Symbol("IS_EMPTY");
+var levelMapping3 = [
+ "ansi",
+ "ansi",
+ "ansi256",
+ "ansi16m"
+];
+var styles10 = /* @__PURE__ */ Object.create(null);
+var applyOptions3 = /* @__PURE__ */ __name((object2, options2 = {}) => {
+ if (options2.level && !(Number.isInteger(options2.level) && options2.level >= 0 && options2.level <= 3)) {
+ throw new Error("The `level` option should be an integer from 0 to 3");
+ }
+ const colorLevel = stdoutColor3 ? stdoutColor3.level : 0;
+ object2.level = options2.level === void 0 ? colorLevel : options2.level;
+}, "applyOptions");
+var chalkFactory3 = /* @__PURE__ */ __name((options2) => {
+ const chalk4 = /* @__PURE__ */ __name((...strings) => strings.join(" "), "chalk");
+ applyOptions3(chalk4, options2);
+ Object.setPrototypeOf(chalk4, createChalk3.prototype);
+ return chalk4;
+}, "chalkFactory");
+function createChalk3(options2) {
+ return chalkFactory3(options2);
+}
+__name(createChalk3, "createChalk");
+Object.setPrototypeOf(createChalk3.prototype, Function.prototype);
+for (const [styleName, style] of Object.entries(ansi_styles_default6)) {
+ styles10[styleName] = {
+ get() {
+ const builder = createBuilder3(this, createStyler3(style.open, style.close, this[STYLER3]), this[IS_EMPTY3]);
+ Object.defineProperty(this, styleName, { value: builder });
+ return builder;
+ }
+ };
+}
+styles10.visible = {
+ get() {
+ const builder = createBuilder3(this, this[STYLER3], true);
+ Object.defineProperty(this, "visible", { value: builder });
+ return builder;
+ }
+};
+var getModelAnsi3 = /* @__PURE__ */ __name((model, level, type2, ...arguments_) => {
+ if (model === "rgb") {
+ if (level === "ansi16m") {
+ return ansi_styles_default6[type2].ansi16m(...arguments_);
+ }
+ if (level === "ansi256") {
+ return ansi_styles_default6[type2].ansi256(ansi_styles_default6.rgbToAnsi256(...arguments_));
+ }
+ return ansi_styles_default6[type2].ansi(ansi_styles_default6.rgbToAnsi(...arguments_));
+ }
+ if (model === "hex") {
+ return getModelAnsi3("rgb", level, type2, ...ansi_styles_default6.hexToRgb(...arguments_));
+ }
+ return ansi_styles_default6[type2][model](...arguments_);
+}, "getModelAnsi");
+var usedModels3 = ["rgb", "hex", "ansi256"];
+for (const model of usedModels3) {
+ styles10[model] = {
+ get() {
+ const { level } = this;
+ return function(...arguments_) {
+ const styler = createStyler3(getModelAnsi3(model, levelMapping3[level], "color", ...arguments_), ansi_styles_default6.color.close, this[STYLER3]);
+ return createBuilder3(this, styler, this[IS_EMPTY3]);
+ };
+ }
+ };
+ const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
+ styles10[bgModel] = {
+ get() {
+ const { level } = this;
+ return function(...arguments_) {
+ const styler = createStyler3(getModelAnsi3(model, levelMapping3[level], "bgColor", ...arguments_), ansi_styles_default6.bgColor.close, this[STYLER3]);
+ return createBuilder3(this, styler, this[IS_EMPTY3]);
+ };
+ }
+ };
+}
+var proto3 = Object.defineProperties(() => {
+}, {
+ ...styles10,
+ level: {
+ enumerable: true,
+ get() {
+ return this[GENERATOR3].level;
+ },
+ set(level) {
+ this[GENERATOR3].level = level;
+ }
+ }
+});
+var createStyler3 = /* @__PURE__ */ __name((open, close, parent) => {
+ let openAll;
+ let closeAll;
+ if (parent === void 0) {
+ openAll = open;
+ closeAll = close;
+ } else {
+ openAll = parent.openAll + open;
+ closeAll = close + parent.closeAll;
+ }
+ return {
+ open,
+ close,
+ openAll,
+ closeAll,
+ parent
+ };
+}, "createStyler");
+var createBuilder3 = /* @__PURE__ */ __name((self2, _styler, _isEmpty) => {
+ const builder = /* @__PURE__ */ __name((...arguments_) => applyStyle3(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" ")), "builder");
+ Object.setPrototypeOf(builder, proto3);
+ builder[GENERATOR3] = self2;
+ builder[STYLER3] = _styler;
+ builder[IS_EMPTY3] = _isEmpty;
+ return builder;
+}, "createBuilder");
+var applyStyle3 = /* @__PURE__ */ __name((self2, string4) => {
+ if (self2.level <= 0 || !string4) {
+ return self2[IS_EMPTY3] ? "" : string4;
+ }
+ let styler = self2[STYLER3];
+ if (styler === void 0) {
+ return string4;
+ }
+ const { openAll, closeAll } = styler;
+ if (string4.includes("\x1B")) {
+ while (styler !== void 0) {
+ string4 = stringReplaceAll3(string4, styler.close, styler.open);
+ styler = styler.parent;
+ }
+ }
+ const lfIndex = string4.indexOf("\n");
+ if (lfIndex !== -1) {
+ string4 = stringEncaseCRLFWithFirstIndex3(string4, closeAll, openAll, lfIndex);
+ }
+ return openAll + string4 + closeAll;
+}, "applyStyle");
+Object.defineProperties(createChalk3.prototype, styles10);
+var chalk3 = createChalk3();
+var chalkStderr3 = createChalk3({ level: stderrColor3 ? stderrColor3.level : 0 });
+var source_default3 = chalk3;
+
+// node_modules/gradient-string/dist/index.js
+var import_tinygradient = __toESM(require_tinygradient(), 1);
+var gradient = /* @__PURE__ */ __name((...colors) => {
+ let gradient2;
+ let options2;
+ if (colors.length === 0) {
+ throw new Error("Missing gradient colors");
+ }
+ if (!Array.isArray(colors[0])) {
+ if (colors.length === 1) {
+ throw new Error(`Expected an array of colors, received ${JSON.stringify(colors[0])}`);
+ }
+ gradient2 = (0, import_tinygradient.default)(...colors);
+ } else {
+ gradient2 = (0, import_tinygradient.default)(colors[0]);
+ options2 = validateOptions(colors[1]);
+ }
+ const fn = /* @__PURE__ */ __name((str3, deprecatedOptions) => {
+ return applyGradient(str3 ? str3.toString() : "", gradient2, deprecatedOptions ?? options2);
+ }, "fn");
+ fn.multiline = (str3, deprecatedOptions) => multiline(str3 ? str3.toString() : "", gradient2, deprecatedOptions ?? options2);
+ return fn;
+}, "gradient");
+var getColors = /* @__PURE__ */ __name((gradient2, options2, count) => {
+ return options2.interpolation?.toLowerCase() === "hsv" ? gradient2.hsv(count, options2.hsvSpin?.toLowerCase() || false) : gradient2.rgb(count);
+}, "getColors");
+function applyGradient(str3, gradient2, opts) {
+ const options2 = validateOptions(opts);
+ const colorsCount = Math.max(str3.replace(/\s/g, "").length, gradient2.stops.length);
+ const colors = getColors(gradient2, options2, colorsCount);
+ let result = "";
+ for (const s of str3) {
+ result += s.match(/\s/g) ? s : source_default3.hex(colors.shift()?.toHex() || "#000")(s);
+ }
+ return result;
+}
+__name(applyGradient, "applyGradient");
+function multiline(str3, gradient2, opts) {
+ const options2 = validateOptions(opts);
+ const lines = str3.split("\n");
+ const maxLength = Math.max(...lines.map((l) => l.length), gradient2.stops.length);
+ const colors = getColors(gradient2, options2, maxLength);
+ const results = [];
+ for (const line of lines) {
+ const lineColors = colors.slice(0);
+ let lineResult = "";
+ for (const l of line) {
+ lineResult += source_default3.hex(lineColors.shift()?.toHex() || "#000")(l);
+ }
+ results.push(lineResult);
+ }
+ return results.join("\n");
+}
+__name(multiline, "multiline");
+function validateOptions(opts) {
+ const options2 = { interpolation: "rgb", hsvSpin: "short", ...opts };
+ if (opts !== void 0 && typeof opts !== "object") {
+ throw new TypeError(`Expected \`options\` to be an \`object\`, got \`${typeof opts}\``);
+ }
+ if (typeof options2.interpolation !== "string") {
+ throw new TypeError(`Expected \`options.interpolation\` to be \`rgb\` or \`hsv\`, got \`${typeof options2.interpolation}\``);
+ }
+ if (options2.interpolation.toLowerCase() === "hsv" && typeof options2.hsvSpin !== "string") {
+ throw new TypeError(`Expected \`options.hsvSpin\` to be a \`short\` or \`long\`, got \`${typeof options2.hsvSpin}\``);
+ }
+ return options2;
+}
+__name(validateOptions, "validateOptions");
+var aliases = {
+ atlas: { colors: ["#feac5e", "#c779d0", "#4bc0c8"], options: {} },
+ cristal: { colors: ["#bdfff3", "#4ac29a"], options: {} },
+ teen: { colors: ["#77a1d3", "#79cbca", "#e684ae"], options: {} },
+ mind: { colors: ["#473b7b", "#3584a7", "#30d2be"], options: {} },
+ morning: { colors: ["#ff5f6d", "#ffc371"], options: { interpolation: "hsv" } },
+ vice: { colors: ["#5ee7df", "#b490ca"], options: { interpolation: "hsv" } },
+ passion: { colors: ["#f43b47", "#453a94"], options: {} },
+ fruit: { colors: ["#ff4e50", "#f9d423"], options: {} },
+ instagram: { colors: ["#833ab4", "#fd1d1d", "#fcb045"], options: {} },
+ retro: {
+ colors: ["#3f51b1", "#5a55ae", "#7b5fac", "#8f6aae", "#a86aa4", "#cc6b8e", "#f18271", "#f3a469", "#f7c978"],
+ options: {}
+ },
+ summer: { colors: ["#fdbb2d", "#22c1c3"], options: {} },
+ rainbow: { colors: ["#ff0000", "#ff0100"], options: { interpolation: "hsv", hsvSpin: "long" } },
+ pastel: { colors: ["#74ebd5", "#74ecd5"], options: { interpolation: "hsv", hsvSpin: "long" } }
+};
+function gradientAlias(alias) {
+ const result = /* @__PURE__ */ __name((str3) => gradient(...alias.colors)(str3, alias.options), "result");
+ result.multiline = (str3 = "") => gradient(...alias.colors).multiline(str3, alias.options);
+ return result;
+}
+__name(gradientAlias, "gradientAlias");
+var dist_default4 = gradient;
+var atlas = gradientAlias(aliases.atlas);
+var cristal = gradientAlias(aliases.cristal);
+var teen = gradientAlias(aliases.teen);
+var mind = gradientAlias(aliases.mind);
+var morning = gradientAlias(aliases.morning);
+var vice = gradientAlias(aliases.vice);
+var passion = gradientAlias(aliases.passion);
+var fruit = gradientAlias(aliases.fruit);
+var instagram = gradientAlias(aliases.instagram);
+var retro = gradientAlias(aliases.retro);
+var summer = gradientAlias(aliases.summer);
+var rainbow = gradientAlias(aliases.rainbow);
+var pastel = gradientAlias(aliases.pastel);
+gradient.atlas = atlas;
+gradient.cristal = cristal;
+gradient.teen = teen;
+gradient.mind = mind;
+gradient.morning = morning;
+gradient.vice = vice;
+gradient.passion = passion;
+gradient.fruit = fruit;
+gradient.instagram = instagram;
+gradient.retro = retro;
+gradient.summer = summer;
+gradient.rainbow = rainbow;
+gradient.pastel = pastel;
+
+// node_modules/ink-gradient/dist/index.js
+var Gradient = /* @__PURE__ */ __name((props) => {
+ if (props.name && props.colors) {
+ throw new Error("The `name` and `colors` props are mutually exclusive");
+ }
+ let gradient2;
+ if (props.name) {
+ gradient2 = dist_default4[props.name];
+ } else if (props.colors) {
+ gradient2 = dist_default4(props.colors);
+ } else {
+ throw new Error("Either `name` or `colors` prop must be provided");
+ }
+ const applyGradient2 = /* @__PURE__ */ __name((text) => gradient2.multiline(stripAnsi(text)), "applyGradient");
+ const containsBoxDescendant = /* @__PURE__ */ __name((nodeChildren) => {
+ let hasBox = false;
+ const search = /* @__PURE__ */ __name((value) => {
+ import_react51.Children.forEach(value, (child) => {
+ if (hasBox) {
+ return;
+ }
+ if (!(0, import_react51.isValidElement)(child)) {
+ return;
+ }
+ if (child.type === Box_default) {
+ hasBox = true;
+ return;
+ }
+ const childProps = child.props;
+ if (Object.hasOwn(childProps, "children")) {
+ search(childProps["children"]);
+ }
+ });
+ }, "search");
+ search(nodeChildren);
+ return hasBox;
+ }, "containsBoxDescendant");
+ const hasChildrenProp = /* @__PURE__ */ __name((props2) => Object.hasOwn(props2, "children"), "hasChildrenProp");
+ const isPlainTextNode = /* @__PURE__ */ __name((node) => typeof node === "string" || typeof node === "number", "isPlainTextNode");
+ const isNonRenderableChild = /* @__PURE__ */ __name((node) => node === null || node === void 0 || typeof node === "boolean", "isNonRenderableChild");
+ const childrenCount = import_react51.Children.count(props.children);
+ if (isPlainTextNode(props.children)) {
+ return (0, import_jsx_runtime12.jsx)(Transform, { transform: applyGradient2, children: props.children });
+ }
+ if (childrenCount === 1 && !containsBoxDescendant(props.children)) {
+ return (0, import_jsx_runtime12.jsx)(Transform, { transform: applyGradient2, children: props.children });
+ }
+ const applyGradientToChildren = /* @__PURE__ */ __name((children) => {
+ const nodes = [];
+ let bufferedText = "";
+ let nodeIndex = 0;
+ const createKey = /* @__PURE__ */ __name(() => `gradient-node-${nodeIndex++}`, "createKey");
+ const pushTransformed = /* @__PURE__ */ __name((node, key) => {
+ nodes.push((0, import_jsx_runtime12.jsx)(Transform, { transform: applyGradient2, children: node }, key));
+ }, "pushTransformed");
+ const flushText = /* @__PURE__ */ __name(() => {
+ if (bufferedText === "") {
+ return;
+ }
+ const text = bufferedText;
+ bufferedText = "";
+ pushTransformed((0, import_jsx_runtime12.jsx)(Text, { children: text }), createKey());
+ }, "flushText");
+ import_react51.Children.forEach(children, (child) => {
+ if (isNonRenderableChild(child)) {
+ return;
+ }
+ if (isPlainTextNode(child)) {
+ bufferedText += String(child);
+ return;
+ }
+ flushText();
+ if ((0, import_react51.isValidElement)(child)) {
+ const childKey = child.key ?? createKey();
+ const childProps = child.props;
+ if (child.type === Text) {
+ pushTransformed(child, childKey);
+ return;
+ }
+ if (child.type === Box_default) {
+ if (hasChildrenProp(childProps)) {
+ const childChildren = childProps["children"];
+ nodes.push((0, import_react51.cloneElement)(child, { key: childKey }, applyGradientToChildren(childChildren)));
+ return;
+ }
+ nodes.push((0, import_react51.cloneElement)(child, { key: childKey }));
+ return;
+ }
+ if (hasChildrenProp(childProps)) {
+ const childChildren = childProps["children"];
+ if (!containsBoxDescendant(childChildren)) {
+ pushTransformed(child, childKey);
+ return;
+ }
+ nodes.push((0, import_react51.cloneElement)(child, { key: childKey }, applyGradientToChildren(childChildren)));
+ return;
+ }
+ pushTransformed(child, childKey);
+ return;
+ }
+ nodes.push(child);
+ });
+ flushText();
+ return nodes;
+ }, "applyGradientToChildren");
+ return (0, import_jsx_runtime12.jsx)(import_jsx_runtime12.Fragment, { children: applyGradientToChildren(props.children) });
+}, "Gradient");
+var dist_default5 = Gradient;
+
+// packages/cli/src/ui/views/ThemedGradient.tsx
+var import_jsx_runtime13 = __toESM(require_jsx_runtime(), 1);
+var ThemedGradient = /* @__PURE__ */ __name(({ children, ...props }) => {
+ const gradient2 = ["#229ac3e6", "#229ac3e6"];
+ if (gradient2 && gradient2.length >= 2) {
+ return /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(dist_default5, { colors: gradient2, children: /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(Text, { ...props, children }) });
+ }
+ if (gradient2 && gradient2.length === 1) {
+ return /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(Text, { color: gradient2[0], ...props, children });
+ }
+ return /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(Text, { color: "yellow", ...props, children });
+}, "ThemedGradient");
+
+// packages/cli/src/ui/ascii-art.ts
+init_esbuild_shims();
+var AsciiLogo = [
+ "\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557",
+ "\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557 \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D",
+ "\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557",
+ "\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2550\u255D \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D",
+ "\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557",
+ "\u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"
+].join("\n");
+
+// packages/cli/src/ui/views/WelcomeScreen.tsx
+var import_jsx_runtime14 = __toESM(require_jsx_runtime(), 1);
+var TITLE_PANEL_WIDTH = 70;
+var PANEL_CONTENT_HEIGHT = 8;
+var SHORTCUT_TIPS = [
+ { label: "Enter", description: "Send the prompt" },
+ { label: "Shift+Enter", description: "Insert a newline" },
+ { label: "Ctrl+V", description: "Paste an image from the clipboard" },
+ { label: "Ctrl+R", description: "Open raw display mode selection" },
+ { label: "Esc", description: "Interrupt the current model turn" },
+ { label: "/", description: "Open the skills and commands menu" },
+ { label: "Ctrl+D twice", description: "Quit Deep Code CLI" }
+];
+function WelcomeScreen({ projectRoot, settings, skills, width }) {
+ const { version: version2 } = useAppContext();
+ const tips = (0, import_react52.useMemo)(() => buildWelcomeTips(skills), [skills]);
+ const [tipIndex] = (0, import_react52.useState)(() => randomTipIndex(tips.length));
+ const compact = width < TITLE_PANEL_WIDTH + 42;
+ const cwd2 = formatHomeRelativePath(projectRoot);
+ const tip = tips[Math.min(tipIndex, Math.max(0, tips.length - 1))] ?? tips[0];
+ const panelWidth = compact ? void 0 : Math.min(width, 72);
+ return /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(Box_default, { flexDirection: "column", marginY: 1, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Box_default, { flexDirection: "column", width: panelWidth, children: /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(Box_default, { flexDirection: "column", paddingX: 1, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Box_default, { flexDirection: "column", justifyContent: "center", paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Box_default, { justifyContent: "center", width: compact ? void 0 : TITLE_PANEL_WIDTH, children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(ThemedGradient, { children: AsciiLogo }) }) }),
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(
+ Box_default,
+ {
+ borderStyle: "round",
+ borderColor: "#229ac3e6",
+ flexDirection: "column",
+ flexGrow: 1,
+ height: compact ? void 0 : PANEL_CONTENT_HEIGHT,
+ marginTop: compact ? 1 : 0,
+ paddingX: 1,
+ children: [
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(Box_default, { flexGrow: 1, marginBottom: compact ? 1 : 0, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(Text, { bold: true, color: "#229ac3e6", children: [
+ ">",
+ "_ Deep Code",
+ " "
+ ] }),
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(Text, { color: "gray", children: [
+ " (v",
+ version2 || "unknown",
+ ")"
+ ] })
+ ] }),
+ !compact ? /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Text, { children: " " }) : null,
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(SettingRow, { label: "Model", value: settings.model }),
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(SettingRow, { label: "Thinking Enabled", value: String(settings.thinkingEnabled) }),
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(SettingRow, { label: "Reasoning Effort", value: settings.thinkingEnabled ? settings.reasoningEffort : "-" }),
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(SettingRow, { label: "CWD", value: cwd2 })
+ ]
+ }
+ )
+ ] }) }),
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Box_default, { flexDirection: "column", width: panelWidth, paddingX: 1, children: tip ? /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(Text, { dimColor: true, children: [
+ "Tips: ",
+ tip.label,
+ " - ",
+ tip.description
+ ] }) }) : null })
+ ] });
+}
+__name(WelcomeScreen, "WelcomeScreen");
+function SettingRow({ label, value }) {
+ return /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(Box_default, { flexDirection: "row", children: [
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Box_default, { width: 20, children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Text, { children: label }) }),
+ /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Box_default, { flexGrow: 1, justifyContent: "flex-end", children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Text, { children: value }) })
+ ] });
+}
+__name(SettingRow, "SettingRow");
+function formatHomeRelativePath(value, home = os14.homedir()) {
+ const normalizedValue = path21.resolve(value);
+ const normalizedHome = path21.resolve(home);
+ const relative5 = path21.relative(normalizedHome, normalizedValue);
+ if (relative5 === "") {
+ return "~";
+ }
+ if (!relative5.startsWith("..") && !path21.isAbsolute(relative5)) {
+ return `~${path21.sep}${relative5}`;
+ }
+ return normalizedValue;
+}
+__name(formatHomeRelativePath, "formatHomeRelativePath");
+function buildWelcomeTips(skills) {
+ const slashTips = buildSlashCommands(skills).filter((item) => item.kind !== "skill" || item.skill?.isLoaded).map((item) => ({
+ label: item.label,
+ description: formatSlashCommandDescription(item.description)
+ }));
+ return [
+ ...slashTips,
+ ...SHORTCUT_TIPS.filter((tip) => !BUILTIN_SLASH_COMMANDS.some((command2) => command2.label === tip.label))
+ ];
+}
+__name(buildWelcomeTips, "buildWelcomeTips");
+function randomTipIndex(length) {
+ return length > 0 ? Math.floor(Math.random() * length) : 0;
+}
+__name(randomTipIndex, "randomTipIndex");
+
+// packages/cli/src/ui/views/AskUserQuestionPrompt.tsx
+init_esbuild_shims();
+var import_react53 = __toESM(require_react(), 1);
+var import_jsx_runtime15 = __toESM(require_jsx_runtime(), 1);
+var OTHER_VALUE = "__other__";
+function AskUserQuestionPrompt({ questions, onSubmit, onCancel }) {
+ const [questionIndex, setQuestionIndex] = (0, import_react53.useState)(0);
+ const [cursorIndex, setCursorIndex] = (0, import_react53.useState)(0);
+ const [answers, setAnswers] = (0, import_react53.useState)({});
+ const [selectedValues, setSelectedValues] = (0, import_react53.useState)({});
+ const [otherTexts, setOtherTexts] = (0, import_react53.useState)({});
+ const [statusMessage, setStatusMessage] = (0, import_react53.useState)(null);
+ const question = questions[questionIndex];
+ const options2 = (0, import_react53.useMemo)(() => buildOptions(question), [question]);
+ const selectedForQuestion = selectedValues[questionIndex] ?? [];
+ const otherText = otherTexts[questionIndex] ?? "";
+ const isCurrentOther = options2[cursorIndex]?.isOther === true;
+ (0, import_react53.useEffect)(() => {
+ if (!statusMessage) {
+ return;
+ }
+ const timer = setTimeout(() => setStatusMessage(null), 2500);
+ return () => clearTimeout(timer);
+ }, [statusMessage]);
+ (0, import_react53.useEffect)(() => {
+ setQuestionIndex(0);
+ setCursorIndex(0);
+ setAnswers({});
+ setSelectedValues({});
+ setOtherTexts({});
+ setStatusMessage(null);
+ }, [questions]);
+ (0, import_react53.useEffect)(() => {
+ if (cursorIndex >= options2.length) {
+ setCursorIndex(Math.max(0, options2.length - 1));
+ }
+ }, [cursorIndex, options2.length]);
+ useTerminalInput((input, key) => {
+ if (!question) {
+ return;
+ }
+ if (key.escape) {
+ onCancel();
+ return;
+ }
+ if (key.ctrl && (input === "c" || input === "C")) {
+ onCancel();
+ return;
+ }
+ if (key.upArrow) {
+ setCursorIndex((index) => Math.max(0, index - 1));
+ return;
+ }
+ if (key.downArrow) {
+ setCursorIndex((index) => Math.min(options2.length - 1, index + 1));
+ return;
+ }
+ if (key.backspace && isCurrentOther) {
+ setOtherTexts((prev) => ({
+ ...prev,
+ [questionIndex]: (prev[questionIndex] ?? "").slice(0, -1)
+ }));
+ return;
+ }
+ if (key.return) {
+ commitCurrentQuestion();
+ return;
+ }
+ if (isCurrentOther && input && !key.ctrl && !key.meta && !input.startsWith("\x1B")) {
+ const sanitized = input.replace(/\r/g, "");
+ if (sanitized) {
+ setOtherTexts((prev) => ({
+ ...prev,
+ [questionIndex]: `${prev[questionIndex] ?? ""}${sanitized}`
+ }));
+ }
+ return;
+ }
+ if (question.multiSelect && input === " " && !key.ctrl && !key.meta) {
+ toggleCurrentOption();
+ return;
+ }
+ if (question.multiSelect && input && /^[1-9]$/.test(input)) {
+ const nextIndex = Number(input) - 1;
+ if (nextIndex >= 0 && nextIndex < options2.length) {
+ toggleOption(options2[nextIndex]?.value ?? "");
+ }
+ }
+ });
+ if (!question) {
+ return null;
+ }
+ function toggleCurrentOption() {
+ const value = options2[cursorIndex]?.value;
+ if (value) {
+ toggleOption(value);
+ }
+ }
+ __name(toggleCurrentOption, "toggleCurrentOption");
+ function toggleOption(value) {
+ setSelectedValues((prev) => {
+ const current = prev[questionIndex] ?? [];
+ const next = current.includes(value) ? current.filter((item) => item !== value) : [...current, value];
+ return { ...prev, [questionIndex]: next };
+ });
+ }
+ __name(toggleOption, "toggleOption");
+ function commitCurrentQuestion() {
+ const answer = buildAnswerForQuestion(question, options2[cursorIndex], selectedForQuestion, otherText);
+ if (!answer) {
+ setStatusMessage(
+ question.multiSelect ? "Select at least one option with Space, or type an Other answer." : "Select an option, or type an Other answer."
+ );
+ return;
+ }
+ const nextAnswers = {
+ ...answers,
+ [question.question]: answer
+ };
+ setAnswers(nextAnswers);
+ if (questionIndex >= questions.length - 1) {
+ onSubmit(nextAnswers);
+ return;
+ }
+ setQuestionIndex((index) => index + 1);
+ setCursorIndex(0);
+ }
+ __name(commitCurrentQuestion, "commitCurrentQuestion");
+ return /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(Box_default, { flexDirection: "column", borderStyle: "round", borderColor: "yellow", paddingX: 1, marginY: 1, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(Box_default, { marginBottom: 1, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Text, { color: "yellow", bold: true, children: "Answer questions" }),
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(Text, { dimColor: true, children: [
+ " ",
+ questionIndex + 1,
+ "/",
+ questions.length
+ ] })
+ ] }),
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Text, { bold: true, children: question.question }),
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Box_default, { flexDirection: "column", marginTop: 1, children: options2.map((option, index) => {
+ const isCursor = index === cursorIndex;
+ const isSelected = option.isOther ? selectedForQuestion.includes(OTHER_VALUE) || Boolean(otherText.trim()) : selectedForQuestion.includes(option.value) || answers[question.question] === option.label;
+ const marker = question.multiSelect ? isSelected ? "[x]" : "[ ]" : isSelected ? "\u25CF" : "\u25CB";
+ return /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(Box_default, { flexDirection: "column", children: [
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(Text, { color: isCursor ? "cyanBright" : void 0, children: [
+ isCursor ? "> " : " ",
+ marker,
+ " ",
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Text, { bold: isCursor, children: option.label })
+ ] }),
+ option.isOther ? /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
+ Box_default,
+ {
+ marginLeft: 4,
+ marginTop: 0,
+ borderStyle: "single",
+ borderColor: isCursor ? "cyanBright" : "gray",
+ paddingX: 1,
+ width: 64,
+ children: otherText ? /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(Text, { color: "white", children: [
+ otherText,
+ isCursor ? /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Text, { color: "cyanBright", children: "\u258C" }) : null
+ ] }) : /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Text, { dimColor: true, children: isCursor ? "type your answer here" : "type a custom answer" })
+ }
+ ) : null,
+ option.description ? /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Box_default, { marginLeft: 3, children: /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(Text, { dimColor: true, children: [
+ " ",
+ option.description
+ ] }) }) : null
+ ] }, option.value);
+ }) }),
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(Text, { dimColor: true, children: statusMessage ?? (isCurrentOther ? "Type your answer \xB7 Backspace edit \xB7 Enter submit/next \xB7 \u2191 choose presets \xB7 Esc type manually" : question.multiSelect ? "\u2191/\u2193 move \xB7 Space toggle \xB7 Enter submit/next \xB7 Esc type manually" : "\u2191/\u2193 move \xB7 Enter select/next \xB7 Esc type manually") }) })
+ ] });
+}
+__name(AskUserQuestionPrompt, "AskUserQuestionPrompt");
+function buildOptions(question) {
+ if (!question) {
+ return [];
+ }
+ return [
+ ...question.options.map((option) => ({
+ label: option.label,
+ description: option.description,
+ value: option.label
+ })),
+ {
+ label: "Other",
+ value: OTHER_VALUE,
+ isOther: true
+ }
+ ];
+}
+__name(buildOptions, "buildOptions");
+function buildAnswerForQuestion(question, focusedOption, selectedValues, otherText) {
+ const trimmedOther = otherText.trim();
+ if (question.multiSelect) {
+ const labels = selectedValues.filter((value) => value !== OTHER_VALUE).map((value) => value.trim()).filter(Boolean);
+ if (selectedValues.includes(OTHER_VALUE) && !trimmedOther) {
+ return null;
+ }
+ if (trimmedOther) {
+ labels.push(trimmedOther);
+ }
+ return labels.length > 0 ? labels.join(", ") : null;
+ }
+ if (!focusedOption) {
+ return null;
+ }
+ if (focusedOption.isOther) {
+ return trimmedOther || null;
+ }
+ return focusedOption.label;
+}
+__name(buildAnswerForQuestion, "buildAnswerForQuestion");
+
+// packages/cli/src/ui/views/McpStatusList.tsx
+init_esbuild_shims();
+var import_react54 = __toESM(require_react(), 1);
+var import_jsx_runtime16 = __toESM(require_jsx_runtime(), 1);
+function McpStatusList({ statuses, onCancel, onReconnect }) {
+ const { columns, rows } = use_window_size_default();
+ const [viewMode, setViewMode] = (0, import_react54.useState)("server-list");
+ const [selectedServerIndex, setSelectedServerIndex] = (0, import_react54.useState)(0);
+ const goBack = (0, import_react54.useCallback)(() => {
+ setViewMode("server-list");
+ }, []);
+ const enterDetail = (0, import_react54.useCallback)(() => {
+ const server = statuses[selectedServerIndex];
+ if (server && (server.status === "ready" || server.status === "failed" || server.status === "reconnecting")) {
+ setViewMode("server-detail");
+ }
+ }, [statuses, selectedServerIndex]);
+ use_input_default((input, key) => {
+ if (statuses.length === 0 && (key.escape || key.ctrl && (input === "c" || input === "C"))) {
+ onCancel();
+ }
+ });
+ if (statuses.length === 0) {
+ return /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(Box_default, { flexDirection: "column", marginLeft: 1, paddingX: 1, gap: 1, borderStyle: "round", borderDimColor: true, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(Box_default, { flexDirection: "column", children: [
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Text, { color: "#229ac3", bold: true, children: "Manage MCP servers" }),
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Text, { dimColor: true, children: "0 servers" })
+ ] }),
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(Box_default, { flexDirection: "column", children: [
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Text, { dimColor: true, children: "No MCP servers configured." }),
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Text, { dimColor: true, children: "Add MCP servers to your settings to get started." })
+ ] }),
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Text, { dimColor: true, children: "Esc to close" })
+ ] });
+ }
+ if (viewMode === "server-detail") {
+ return /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(
+ ServerDetailView,
+ {
+ server: statuses[selectedServerIndex],
+ onBack: goBack,
+ onCancel,
+ onReconnect,
+ rows,
+ columns
+ }
+ );
+ }
+ return /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(
+ ServerListView,
+ {
+ statuses,
+ selectedIndex: selectedServerIndex,
+ onSelect: setSelectedServerIndex,
+ onEnter: enterDetail,
+ onCancel,
+ rows,
+ columns
+ }
+ );
+}
+__name(McpStatusList, "McpStatusList");
+function ServerListView({
+ statuses,
+ selectedIndex,
+ onSelect,
+ onEnter,
+ onCancel,
+ rows,
+ columns
+}) {
+ const [scrollOffset, setScrollOffset] = (0, import_react54.useState)(0);
+ const serverCount = statuses.length;
+ const maxVisible = (0, import_react54.useMemo)(() => {
+ const reservedLines = 8;
+ const availableLines = Math.max(0, Math.min(rows, 30) - reservedLines);
+ return Math.max(1, Math.floor(availableLines / 3));
+ }, [rows]);
+ const labelColumnWidth = (0, import_react54.useMemo)(() => {
+ if (serverCount === 0) return 0;
+ const longestName = Math.max(...statuses.map((s) => s.name.length));
+ const contentWidth = longestName + 5;
+ const maxAllowed = Math.max(15, Math.floor((columns - 6) * 0.4));
+ return Math.min(contentWidth, maxAllowed);
+ }, [statuses, serverCount, columns]);
+ const safeIndex = (0, import_react54.useMemo)(() => {
+ if (serverCount === 0) return 0;
+ return Math.max(0, Math.min(selectedIndex, serverCount - 1));
+ }, [selectedIndex, serverCount]);
+ import_react54.default.useEffect(() => {
+ if (safeIndex < scrollOffset) {
+ setScrollOffset(safeIndex);
+ } else if (safeIndex >= scrollOffset + maxVisible) {
+ setScrollOffset(safeIndex - maxVisible + 1);
+ }
+ }, [safeIndex, scrollOffset, maxVisible]);
+ const visibleServers = (0, import_react54.useMemo)(() => {
+ return statuses.slice(scrollOffset, scrollOffset + maxVisible);
+ }, [statuses, scrollOffset, maxVisible]);
+ use_input_default((input, key) => {
+ if (key.escape || key.ctrl && (input === "c" || input === "C")) {
+ onCancel();
+ return;
+ }
+ if (serverCount === 0) {
+ return;
+ }
+ if (key.upArrow) {
+ onSelect(Math.max(0, selectedIndex - 1));
+ return;
+ }
+ if (key.downArrow) {
+ onSelect(Math.min(serverCount - 1, selectedIndex + 1));
+ return;
+ }
+ if (key.pageUp) {
+ onSelect(Math.max(0, selectedIndex - maxVisible));
+ return;
+ }
+ if (key.pageDown) {
+ onSelect(Math.min(serverCount - 1, selectedIndex + maxVisible));
+ return;
+ }
+ if (key.home) {
+ onSelect(0);
+ return;
+ }
+ if (key.end) {
+ onSelect(serverCount - 1);
+ }
+ if (key.return) {
+ onEnter();
+ return;
+ }
+ });
+ const readyCount = statuses.filter((s) => s.status === "ready").length;
+ const startingCount = statuses.filter((s) => s.status === "starting").length;
+ const reconnectingCount = statuses.filter((s) => s.status === "reconnecting").length;
+ const failedCount = statuses.filter((s) => s.status === "failed").length;
+ return /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(
+ Box_default,
+ {
+ flexDirection: "column",
+ width: Math.max(20, columns - 6),
+ height: Math.max(5, Math.min(rows - 1, 30)),
+ overflow: "hidden",
+ paddingX: 1,
+ marginTop: 1,
+ children: /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(Box_default, { flexDirection: "column", borderStyle: "round", borderDimColor: true, flexGrow: 1, overflow: "hidden", children: [
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(Box_default, { paddingX: 1, gap: 1, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Text, { bold: true, color: "#229ac3", children: "Manage MCP servers" }),
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(Box_default, { gap: 1, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Text, { dimColor: true, children: "(" }),
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(Text, { color: "green", children: [
+ readyCount,
+ " ready,"
+ ] }),
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(Text, { color: "yellow", children: [
+ startingCount,
+ " starting,"
+ ] }),
+ reconnectingCount > 0 && /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(Text, { color: "#ff9900", children: [
+ reconnectingCount,
+ " reconnecting,"
+ ] }),
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(Text, { color: "red", children: [
+ failedCount,
+ " failed"
+ ] }),
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Text, { dimColor: true, children: ")" })
+ ] })
+ ] }),
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(
+ Box_default,
+ {
+ borderTop: true,
+ borderBottom: true,
+ borderLeft: false,
+ borderRight: false,
+ borderStyle: "round",
+ borderDimColor: true,
+ flexDirection: "column",
+ flexGrow: 1,
+ paddingX: 1,
+ overflow: "hidden",
+ children: [
+ visibleServers.map((status, i) => {
+ const actualIndex = scrollOffset + i;
+ const isSelected = actualIndex === safeIndex;
+ return /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(
+ ServerRow,
+ {
+ status,
+ selected: isSelected,
+ labelColumnWidth
+ },
+ `server-${status.name}`
+ );
+ }),
+ scrollOffset > 0 || scrollOffset + maxVisible < serverCount ? /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(Box_default, { marginTop: 1, children: [
+ scrollOffset > 0 ? /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(Text, { dimColor: true, children: [
+ "\u2026 ",
+ scrollOffset,
+ " servers above. "
+ ] }) : null,
+ scrollOffset + maxVisible < serverCount ? /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(Text, { dimColor: true, children: [
+ "\u2026 ",
+ serverCount - scrollOffset - maxVisible,
+ " servers below."
+ ] }) : null
+ ] }) : null
+ ]
+ }
+ ),
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Box_default, { paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Text, { dimColor: true, children: "\u2191/\u2193 navigate \xB7 Enter view details \xB7 Esc close" }) })
+ ] })
+ }
+ );
+}
+__name(ServerListView, "ServerListView");
+function ServerRow({
+ status,
+ selected,
+ labelColumnWidth
+}) {
+ const icon = status.status === "ready" ? "\u2713" : status.status === "failed" ? "\u2717" : status.status === "reconnecting" ? "\u21BB" : "\u25CF";
+ const color = status.status === "ready" ? "green" : status.status === "failed" ? "red" : status.status === "reconnecting" ? "#ff9900" : "yellow";
+ const [dots, setDots] = import_react54.default.useState(0);
+ import_react54.default.useEffect(() => {
+ if (status.status !== "starting" && status.status !== "reconnecting") return;
+ const interval = setInterval(() => {
+ setDots((d) => (d + 1) % 4);
+ }, 500);
+ return () => clearInterval(interval);
+ }, [status.status]);
+ const detail = status.status === "ready" ? `Ready (${status.toolCount} tools, ${status.promptCount} prompts, ${status.resourceCount} resources)` : status.status === "failed" ? `Failed` : status.status === "reconnecting" ? `Reconnecting${dots > 0 ? ".".repeat(dots) : " "}` : "Starting" + (dots > 0 ? ".".repeat(dots) : " ");
+ return /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(Box_default, { flexDirection: "column", marginBottom: 1, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(Box_default, { gap: 2, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Box_default, { width: labelColumnWidth, flexShrink: 0, children: /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(Text, { color: selected ? "#229ac3" : void 0, children: [
+ selected ? "> " : " ",
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(Text, { color, children: [
+ icon,
+ " "
+ ] }),
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Text, { bold: true, children: status.name })
+ ] }) }),
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Box_default, { flexGrow: 1, children: /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Text, { dimColor: true, children: detail }) })
+ ] }),
+ (status.status === "failed" || status.status === "reconnecting") && status.error ? /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(ErrorRow, { error: status.error }) : null
+ ] });
+}
+__name(ServerRow, "ServerRow");
+function ServerDetailView({
+ server,
+ onBack,
+ onCancel,
+ onReconnect,
+ rows,
+ columns
+}) {
+ const [activeIndex, setActiveIndex] = import_react54.default.useState(0);
+ const hasReconnect = server.status === "failed";
+ const canScroll = server.status === "ready";
+ const allItems = (0, import_react54.useMemo)(() => {
+ const items = [];
+ if (hasReconnect) {
+ items.push({ type: "action", name: "Reconnect" });
+ }
+ server.tools.forEach((tool) => items.push({ type: "tool", name: tool }));
+ server.prompts.forEach((prompt) => items.push({ type: "prompt", name: prompt }));
+ server.resources.forEach((resource) => items.push({ type: "resource", name: resource }));
+ return items;
+ }, [server, hasReconnect]);
+ const totalItems = allItems.length;
+ const maxVisible = (0, import_react54.useMemo)(() => {
+ const reservedLines = 12;
+ const availableLines = Math.max(0, Math.min(rows, 30) - reservedLines);
+ return Math.max(1, availableLines);
+ }, [rows]);
+ const visibleStartRef = import_react54.default.useRef(0);
+ const visibleStart = (0, import_react54.useMemo)(() => {
+ if (totalItems === 0) return 0;
+ const currentStart = visibleStartRef.current;
+ let newStart = currentStart;
+ if (activeIndex < currentStart) {
+ newStart = activeIndex;
+ } else if (activeIndex >= currentStart + maxVisible) {
+ newStart = activeIndex - maxVisible + 1;
+ }
+ newStart = Math.max(0, Math.min(newStart, Math.max(0, totalItems - maxVisible)));
+ visibleStartRef.current = newStart;
+ return newStart;
+ }, [activeIndex, maxVisible, totalItems]);
+ const visibleItems = allItems.slice(visibleStart, visibleStart + maxVisible);
+ use_input_default((input, key) => {
+ if (key.ctrl && (input === "c" || input === "C")) {
+ onCancel();
+ return;
+ }
+ if (key.escape) {
+ onBack();
+ return;
+ }
+ if (key.return || input === " ") {
+ if (activeIndex === 0 && hasReconnect) {
+ onReconnect(server.name);
+ onBack();
+ return;
+ }
+ onBack();
+ return;
+ }
+ if (!canScroll && !hasReconnect) return;
+ if (key.upArrow) {
+ setActiveIndex((prev) => Math.max(0, prev - 1));
+ return;
+ }
+ if (key.downArrow) {
+ setActiveIndex((prev) => Math.min(totalItems - 1, prev + 1));
+ return;
+ }
+ if (key.pageUp && canScroll) {
+ setActiveIndex((prev) => Math.max(0, prev - maxVisible));
+ return;
+ }
+ if (key.pageDown && canScroll) {
+ setActiveIndex((prev) => Math.min(totalItems - 1, prev + maxVisible));
+ return;
+ }
+ if (key.home && canScroll) {
+ setActiveIndex(0);
+ return;
+ }
+ if (key.end && canScroll) {
+ setActiveIndex(totalItems - 1);
+ }
+ });
+ const statusIcon = server.status === "ready" ? "\u2713" : server.status === "failed" ? "\u2717" : server.status === "reconnecting" ? "\u21BB" : "\u25CF";
+ const statusColor = server.status === "ready" ? "green" : server.status === "failed" ? "red" : server.status === "reconnecting" ? "#ff9900" : "yellow";
+ return /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(
+ Box_default,
+ {
+ flexDirection: "column",
+ width: Math.max(20, columns - 6),
+ height: Math.max(5, Math.min(rows - 1, 30)),
+ overflow: "hidden",
+ paddingX: 1,
+ marginTop: 1,
+ children: /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(Box_default, { flexDirection: "column", borderStyle: "round", borderDimColor: true, flexGrow: 1, overflow: "hidden", children: [
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(Box_default, { paddingX: 1, gap: 1, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(Text, { color: statusColor, children: [
+ statusIcon,
+ " "
+ ] }),
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Text, { bold: true, color: "#229ac3", wrap: "truncate-end", children: server.name }),
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(Text, { dimColor: true, children: [
+ "\u2014 ",
+ server.status === "ready" ? "Details" : "Status"
+ ] })
+ ] }),
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Box_default, { paddingX: 1, marginLeft: 3, children: /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Text, { wrap: "truncate-end", children: server.status === "ready" ? `${server.toolCount} tools, ${server.promptCount} prompts, ${server.resourceCount} resources` : `Status: ${server.status}` }) }),
+ server.error && (server.status === "failed" || server.status === "reconnecting") ? /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Box_default, { paddingX: 1, marginLeft: 3, children: /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(ErrorRow, { error: server.error }) }) : null,
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(
+ Box_default,
+ {
+ borderTop: true,
+ borderBottom: true,
+ borderLeft: false,
+ borderRight: false,
+ borderStyle: "round",
+ borderDimColor: true,
+ flexDirection: "column",
+ flexGrow: 1,
+ paddingX: 1,
+ overflow: "hidden",
+ children: [
+ visibleStart > 0 ? /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Text, { dimColor: true, children: "\u25B2" }) }) : /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Text, { children: " " }),
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Box_default, { paddingX: 1, flexDirection: "column", children: visibleItems.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Box_default, { paddingY: 1, children: /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Text, { dimColor: true, children: "No items available" }) }) : visibleItems.map((item, idx) => {
+ const actualIndex = visibleStart + idx;
+ const isSelected = actualIndex === activeIndex;
+ return /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(ItemRow, { item, selected: isSelected }, `${item.type}-${item.name}-${actualIndex}`);
+ }) }),
+ visibleStart > 0 || visibleStart + maxVisible < totalItems ? /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(Box_default, { marginTop: 1, gap: 1, children: [
+ totalItems - visibleStart - maxVisible > 0 ? /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Text, { dimColor: true, children: "\u25BC" }) : /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Text, { children: " " }),
+ visibleStart > 0 ? /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(Text, { dimColor: true, children: [
+ "\u2026 ",
+ visibleStart,
+ " items above. "
+ ] }) : null,
+ totalItems - visibleStart - maxVisible > 0 ? /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(Text, { dimColor: true, children: [
+ "\u2026 ",
+ totalItems - visibleStart - maxVisible,
+ " items below."
+ ] }) : null
+ ] }) : null
+ ]
+ }
+ ),
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Box_default, { paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Text, { dimColor: true, children: hasReconnect ? "Enter to reconnect \xB7 Esc back \xB7 Ctrl+C close" : canScroll ? "\u2191/\u2193 scroll \xB7 Space/Enter back \xB7 Esc back \xB7 Ctrl+C close" : "Space/Enter back \xB7 Esc back \xB7 Ctrl+C close" }) })
+ ] })
+ }
+ );
+}
+__name(ServerDetailView, "ServerDetailView");
+function ItemRow({ item, selected }) {
+ const isAction = item.type === "action";
+ const icon = isAction ? "\u21BB" : item.type === "tool" ? "\u{1F527}" : item.type === "prompt" ? "\u{1F4DD}" : "\u{1F4E6}";
+ const color = isAction && selected ? "#ff9900" : selected ? "#229ac3" : void 0;
+ return /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(Box_default, { height: 1, flexDirection: "row", children: [
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Text, { color: selected ? "#229ac3" : void 0, children: selected ? "> " : " " }),
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(Text, { dimColor: true, children: [
+ icon,
+ " "
+ ] }),
+ /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Text, { color, dimColor: !selected, bold: isAction, wrap: "truncate-end", children: isAction ? `[${item.name}]` : item.name })
+ ] });
+}
+__name(ItemRow, "ItemRow");
+function ErrorRow({ error: error51 }) {
+ const lines = error51.split("\n").filter((line) => line.trim().length > 0);
+ return /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(
+ Box_default,
+ {
+ flexDirection: "column",
+ marginLeft: 4,
+ marginTop: 0,
+ marginBottom: 0,
+ borderStyle: "round",
+ borderColor: "red",
+ borderDimColor: true,
+ children: lines.map((line, index) => /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Text, { color: "red", dimColor: true, children: line }) }, index))
+ }
+ );
+}
+__name(ErrorRow, "ErrorRow");
+
+// packages/cli/src/ui/views/ProcessStdoutView.tsx
+init_esbuild_shims();
+var import_react55 = __toESM(require_react(), 1);
+var import_jsx_runtime17 = __toESM(require_jsx_runtime(), 1);
+var REFRESH_INTERVAL_MS = 150;
+var MAX_PANEL_HEIGHT = 30;
+var MIN_PANEL_HEIGHT = 5;
+var ProcessStdoutView = import_react55.default.memo(/* @__PURE__ */ __name(function ProcessStdoutView2({
+ processStdoutRef,
+ runningProcesses,
+ onDismiss,
+ onAdjustTimeout,
+ screenWidth,
+ screenHeight
+}) {
+ const [stdoutText, setStdoutText] = (0, import_react55.useState)("");
+ const [scrollOffset, setScrollOffset] = (0, import_react55.useState)(0);
+ const [statusMessage, setStatusMessage] = (0, import_react55.useState)("");
+ const statusTimerRef = (0, import_react55.useRef)(null);
+ const panelHeight = Math.max(MIN_PANEL_HEIGHT, Math.min(screenHeight - 1, MAX_PANEL_HEIGHT));
+ const reservedRows = statusMessage ? 2 : 1;
+ const visibleLineLimit = Math.max(1, panelHeight - reservedRows);
+ (0, import_react55.useEffect)(() => {
+ const updateStdout = /* @__PURE__ */ __name(() => {
+ let text = "";
+ if (runningProcesses && runningProcesses.size > 0) {
+ for (const [pid, proc] of runningProcesses.entries()) {
+ const pidNum = Number(pid);
+ const stdout = processStdoutRef.current.get(pidNum) ?? "";
+ if (text) {
+ text += "\n";
+ }
+ if (runningProcesses.size > 1) {
+ text += `\u2500\u2500 Process ${pid} [${proc.command}] \u2500\u2500
+`;
+ }
+ text += stdout || "(no output yet)";
+ }
+ } else {
+ text = "(no running processes)";
+ }
+ setStdoutText(text);
+ }, "updateStdout");
+ updateStdout();
+ const interval = setInterval(updateStdout, REFRESH_INTERVAL_MS);
+ return () => clearInterval(interval);
+ }, [processStdoutRef, runningProcesses]);
+ (0, import_react55.useEffect)(() => {
+ return () => {
+ if (statusTimerRef.current) {
+ clearTimeout(statusTimerRef.current);
+ }
+ };
+ }, []);
+ const lines = (0, import_react55.useMemo)(() => stdoutText.split("\n"), [stdoutText]);
+ const timeoutProcess = (0, import_react55.useMemo)(() => getLatestTimeoutProcess(runningProcesses), [runningProcesses]);
+ const visibleLines = (0, import_react55.useMemo)(() => {
+ if (lines.length <= visibleLineLimit) {
+ return lines;
+ }
+ const outputLineLimit = Math.max(1, visibleLineLimit - 1);
+ const start = Math.max(0, lines.length - outputLineLimit - scrollOffset);
+ const slice = lines.slice(start, start + outputLineLimit);
+ if (lines.length > visibleLineLimit) {
+ slice.unshift(`... (${start} lines above \xB7 \u2191/\u2193 to scroll \xB7 ${lines.length} total lines) ...`);
+ }
+ return slice;
+ }, [lines, scrollOffset, visibleLineLimit]);
+ const setTemporaryStatus = /* @__PURE__ */ __name((message) => {
+ setStatusMessage(message);
+ if (statusTimerRef.current) {
+ clearTimeout(statusTimerRef.current);
+ }
+ statusTimerRef.current = setTimeout(() => setStatusMessage(""), 2e3);
+ }, "setTemporaryStatus");
+ useTerminalInput(
+ (input, key) => {
+ if (key.ctrl && (input === "o" || input === "O") || key.escape) {
+ onDismiss();
+ return;
+ }
+ if (input === "+") {
+ const adjustment = onAdjustTimeout(BASH_TIMEOUT_INCREMENT_MS);
+ setTemporaryStatus(formatAdjustmentStatus(adjustment));
+ return;
+ }
+ if (input === "-") {
+ const adjustment = onAdjustTimeout(-BASH_TIMEOUT_DECREMENT_MS);
+ setTemporaryStatus(formatAdjustmentStatus(adjustment));
+ return;
+ }
+ if (key.upArrow) {
+ setScrollOffset((s) => Math.min(s + 10, Math.max(0, lines.length - visibleLineLimit)));
+ return;
+ }
+ if (key.downArrow) {
+ setScrollOffset((s) => Math.max(s - 10, 0));
+ return;
+ }
+ if (key.pageUp) {
+ setScrollOffset((s) => Math.min(s + visibleLineLimit, Math.max(0, lines.length - visibleLineLimit)));
+ return;
+ }
+ if (key.pageDown) {
+ setScrollOffset((s) => Math.max(s - visibleLineLimit, 0));
+ return;
+ }
+ },
+ { isActive: true }
+ );
+ return /* @__PURE__ */ (0, import_jsx_runtime17.jsxs)(Box_default, { flexDirection: "column", width: screenWidth, minWidth: 80, height: panelHeight, overflow: "hidden", children: [
+ /* @__PURE__ */ (0, import_jsx_runtime17.jsxs)(Box_default, { borderStyle: "single", borderBottom: true, borderLeft: false, borderRight: false, borderTop: false, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(Text, { bold: true, children: "\u{1F4DF} Process Output" }),
+ /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(Text, { dimColor: true, children: ` (${formatTimeoutHint(
+ timeoutProcess?.entry
+ )} \xB7 +/- adjust \xB7 Ctrl+O or Esc to close \xB7 \u2191\u2193 PageUp/PageDown to scroll)` })
+ ] }),
+ /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(Box_default, { flexDirection: "column", paddingX: 1, overflow: "hidden", children: visibleLines.map((line, index) => /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(Text, { children: line }, `${index}`)) }),
+ statusMessage ? /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(Box_default, { paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(Text, { dimColor: true, children: statusMessage }) }) : null
+ ] });
+}, "ProcessStdoutView"));
+function getLatestTimeoutProcess(runningProcesses) {
+ if (!runningProcesses) {
+ return null;
+ }
+ let latest = null;
+ for (const [pid, entry] of runningProcesses.entries()) {
+ if (typeof entry.timeoutMs !== "number") {
+ continue;
+ }
+ latest = { pid, entry };
+ }
+ return latest;
+}
+__name(getLatestTimeoutProcess, "getLatestTimeoutProcess");
+function formatTimeoutHint(entry) {
+ if (!entry || typeof entry.timeoutMs !== "number") {
+ return "timeout unavailable";
+ }
+ return `timeout ${formatDuration(entry.timeoutMs)}`;
+}
+__name(formatTimeoutHint, "formatTimeoutHint");
+function formatAdjustmentStatus(adjustment) {
+ if (!adjustment) {
+ return "No adjustable Bash timeout";
+ }
+ return `Timeout set to ${formatDuration(adjustment.timeoutMs)}`;
+}
+__name(formatAdjustmentStatus, "formatAdjustmentStatus");
+function formatDuration(ms) {
+ const totalMinutes = Math.max(1, Math.round(ms / 6e4));
+ return `${totalMinutes}m`;
+}
+__name(formatDuration, "formatDuration");
+
+// packages/cli/src/ui/core/ask-user-question.ts
+init_esbuild_shims();
+function findPendingAskUserQuestion(messages, status) {
+ if (status !== "waiting_for_user") {
+ return null;
+ }
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
+ const message = messages[index];
+ if (!message || message.role !== "tool" || message.visible === false) {
+ continue;
+ }
+ const questions = parseAskUserQuestionContent(message.content);
+ if (questions.length === 0) {
+ continue;
+ }
+ return {
+ messageId: message.id,
+ sessionId: message.sessionId,
+ questions
+ };
+ }
+ return null;
+}
+__name(findPendingAskUserQuestion, "findPendingAskUserQuestion");
+function formatAskUserQuestionAnswers(answers) {
+ const answersText = Object.entries(answers).map(([question, answer]) => `"${escapeAnswerPart(question)}"="${escapeAnswerPart(answer)}"`).join(", ");
+ return `User has answered your questions: ${answersText}. You can now continue with the user's answers in mind.`;
+}
+__name(formatAskUserQuestionAnswers, "formatAskUserQuestionAnswers");
+function parseAskUserQuestionContent(content) {
+ if (!content) {
+ return [];
+ }
+ try {
+ const parsed = JSON.parse(content);
+ if (parsed.awaitUserResponse !== true) {
+ return [];
+ }
+ const metadata = parsed.metadata;
+ if (!metadata || metadata.kind !== "ask_user_question") {
+ return [];
+ }
+ return normalizeQuestions(metadata.questions);
+ } catch {
+ return [];
+ }
+}
+__name(parseAskUserQuestionContent, "parseAskUserQuestionContent");
+function normalizeQuestions(raw) {
+ if (!Array.isArray(raw)) {
+ return [];
+ }
+ const questions = [];
+ for (const item of raw) {
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
+ continue;
+ }
+ const question = typeof item.question === "string" ? item.question.trim() : "";
+ const rawOptions = item.options;
+ if (!question || !Array.isArray(rawOptions) || rawOptions.length === 0) {
+ continue;
+ }
+ const options2 = rawOptions.map((option) => normalizeOption(option)).filter((option) => Boolean(option));
+ if (options2.length === 0) {
+ continue;
+ }
+ const multiSelect = typeof item.multiSelect === "boolean" ? item.multiSelect : void 0;
+ questions.push({ question, multiSelect, options: options2 });
+ }
+ return questions;
+}
+__name(normalizeQuestions, "normalizeQuestions");
+function normalizeOption(raw) {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
+ return null;
+ }
+ const label = typeof raw.label === "string" ? raw.label.trim() : "";
+ if (!label) {
+ return null;
+ }
+ const description = typeof raw.description === "string" ? raw.description.trim() : "";
+ return {
+ label,
+ description: description || void 0
+ };
+}
+__name(normalizeOption, "normalizeOption");
+function escapeAnswerPart(value) {
+ return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\s+/g, " ").trim();
+}
+__name(escapeAnswerPart, "escapeAnswerPart");
+
+// packages/cli/src/ui/views/PermissionPrompt.tsx
+init_esbuild_shims();
+var import_react56 = __toESM(require_react(), 1);
+var import_jsx_runtime18 = __toESM(require_jsx_runtime(), 1);
+var ALWAYS_ALLOWED_SCOPES = /* @__PURE__ */ new Set([
+ "read-in-cwd",
+ "read-out-cwd",
+ "write-in-cwd",
+ "write-out-cwd",
+ "delete-in-cwd",
+ "delete-out-cwd",
+ "query-git-log",
+ "mutate-git-log",
+ "network",
+ "mcp"
+]);
+function PermissionPrompt({ requests, onSubmit, onCancel }) {
+ const prompts = (0, import_react56.useMemo)(() => buildScopePrompts(requests), [requests]);
+ const [index, setIndex] = (0, import_react56.useState)(0);
+ const [cursor, setCursor] = (0, import_react56.useState)(0);
+ const [decisions, setDecisions] = (0, import_react56.useState)({});
+ const [alwaysAllows, setAlwaysAllows] = (0, import_react56.useState)([]);
+ const effectiveIndex = findNextPromptIndex(prompts, index, alwaysAllows);
+ const prompt = prompts[effectiveIndex] ?? null;
+ const options2 = prompt ? buildOptions2(prompt.scope) : [];
+ (0, import_react56.useEffect)(() => {
+ setIndex(0);
+ setCursor(0);
+ setDecisions({});
+ setAlwaysAllows([]);
+ }, [requests]);
+ (0, import_react56.useEffect)(() => {
+ if (!prompt) {
+ onSubmit(buildResult(requests, decisions, alwaysAllows));
+ }
+ }, [alwaysAllows, decisions, onSubmit, prompt, requests]);
+ (0, import_react56.useEffect)(() => {
+ if (cursor >= options2.length) {
+ setCursor(Math.max(0, options2.length - 1));
+ }
+ }, [cursor, options2.length]);
+ useTerminalInput((input, key) => {
+ if (!prompt) {
+ return;
+ }
+ if (key.escape || key.ctrl && (input === "c" || input === "C")) {
+ onCancel();
+ return;
+ }
+ if (key.upArrow) {
+ setCursor((value) => Math.max(0, value - 1));
+ return;
+ }
+ if (key.downArrow) {
+ setCursor((value) => Math.min(options2.length - 1, value + 1));
+ return;
+ }
+ if (input && /^[1-3]$/.test(input)) {
+ const nextCursor = Number(input) - 1;
+ if (nextCursor >= 0 && nextCursor < options2.length) {
+ commit(options2[nextCursor].kind);
+ }
+ return;
+ }
+ if (key.return) {
+ commit(options2[cursor]?.kind ?? "allow");
+ }
+ });
+ if (!prompt) {
+ return null;
+ }
+ function commit(kind) {
+ if (!prompt) {
+ return;
+ }
+ if (kind === "always" && isAlwaysAllowedScope(prompt.scope)) {
+ const scope = prompt.scope;
+ setAlwaysAllows((prev) => prev.includes(scope) ? prev : [...prev, scope]);
+ setDecisions((prev) => ({
+ ...prev,
+ [prompt.request.toolCallId]: prev[prompt.request.toolCallId] === "deny" ? "deny" : "allow"
+ }));
+ } else {
+ setDecisions((prev) => ({
+ ...prev,
+ [prompt.request.toolCallId]: kind === "deny" ? "deny" : prev[prompt.request.toolCallId] === "deny" ? "deny" : "allow"
+ }));
+ }
+ setIndex(effectiveIndex + 1);
+ setCursor(0);
+ }
+ __name(commit, "commit");
+ return /* @__PURE__ */ (0, import_jsx_runtime18.jsxs)(Box_default, { flexDirection: "column", borderStyle: "round", borderColor: "yellow", paddingX: 1, marginY: 1, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime18.jsxs)(Box_default, { marginBottom: 1, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Text, { color: "yellow", bold: true, children: "Permission required" }),
+ /* @__PURE__ */ (0, import_jsx_runtime18.jsxs)(Text, { dimColor: true, children: [
+ " ",
+ Math.min(effectiveIndex + 1, prompts.length),
+ "/",
+ prompts.length
+ ] })
+ ] }),
+ /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Text, { bold: true, children: prompt.request.name }),
+ /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Text, { children: prompt.request.command }),
+ prompt.request.description ? /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Text, { dimColor: true, children: prompt.request.description }) : null,
+ /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Text, { children: "Do you want to proceed?" }) }),
+ /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Box_default, { flexDirection: "column", marginTop: 1, children: options2.map((option, optionIndex) => /* @__PURE__ */ (0, import_jsx_runtime18.jsxs)(Text, { color: optionIndex === cursor ? "cyanBright" : void 0, children: [
+ optionIndex === cursor ? "> " : " ",
+ optionIndex + 1,
+ ". ",
+ renderOptionLabel(option)
+ ] }, option.kind)) }),
+ /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Text, { dimColor: true, children: "\u2191/\u2193 move \xB7 Enter select \xB7 Esc interrupt" }) })
+ ] });
+}
+__name(PermissionPrompt, "PermissionPrompt");
+function renderOptionLabel(option) {
+ if (option.scopeDescription && option.scopeColor) {
+ return /* @__PURE__ */ (0, import_jsx_runtime18.jsxs)(import_jsx_runtime18.Fragment, { children: [
+ option.label,
+ /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Text, { color: option.scopeColor, children: option.scopeDescription })
+ ] });
+ }
+ return option.label;
+}
+__name(renderOptionLabel, "renderOptionLabel");
+function buildScopePrompts(requests) {
+ const prompts = [];
+ for (const request of requests) {
+ for (const scope of request.scopes.length > 0 ? request.scopes : ["unknown"]) {
+ prompts.push({ request, scope });
+ }
+ }
+ return prompts;
+}
+__name(buildScopePrompts, "buildScopePrompts");
+function buildOptions2(scope) {
+ const options2 = [{ kind: "allow", label: "Yes" }];
+ if (isAlwaysAllowedScope(scope)) {
+ options2.push({
+ kind: "always",
+ label: "Yes, and always allow ",
+ scopeDescription: describeScope(scope),
+ scopeColor: getScopeRiskColor(scope)
+ });
+ }
+ options2.push({ kind: "deny", label: "No" });
+ return options2;
+}
+__name(buildOptions2, "buildOptions");
+function findNextPromptIndex(prompts, startIndex, alwaysAllows) {
+ let index = startIndex;
+ while (index < prompts.length) {
+ const scope = prompts[index].scope;
+ if (isAlwaysAllowedScope(scope) && alwaysAllows.includes(scope)) {
+ index += 1;
+ continue;
+ }
+ return index;
+ }
+ return prompts.length;
+}
+__name(findNextPromptIndex, "findNextPromptIndex");
+function buildResult(requests, decisions, alwaysAllows) {
+ const permissions = requests.map((request) => ({
+ toolCallId: request.toolCallId,
+ permission: decisions[request.toolCallId] === "deny" ? "deny" : "allow"
+ }));
+ return {
+ permissions,
+ alwaysAllows,
+ hasDeny: permissions.some((permission) => permission.permission === "deny")
+ };
+}
+__name(buildResult, "buildResult");
+function isAlwaysAllowedScope(scope) {
+ return ALWAYS_ALLOWED_SCOPES.has(scope);
+}
+__name(isAlwaysAllowedScope, "isAlwaysAllowedScope");
+function getScopeRiskColor(scope) {
+ switch (scope) {
+ case "read-in-cwd":
+ case "query-git-log":
+ return "#22c55e";
+ case "read-out-cwd":
+ case "write-in-cwd":
+ case "network":
+ case "mcp":
+ return "#f59e0b";
+ case "write-out-cwd":
+ case "delete-in-cwd":
+ case "delete-out-cwd":
+ case "mutate-git-log":
+ case "unknown":
+ return "#ef4444";
+ default:
+ return "#ef4444";
+ }
+}
+__name(getScopeRiskColor, "getScopeRiskColor");
+function describeScope(scope) {
+ switch (scope) {
+ case "read-in-cwd":
+ return "reads inside this workspace";
+ case "read-out-cwd":
+ return "reads outside this workspace";
+ case "write-in-cwd":
+ return "writes inside this workspace";
+ case "write-out-cwd":
+ return "writes outside this workspace";
+ case "delete-in-cwd":
+ return "deletes inside this workspace";
+ case "delete-out-cwd":
+ return "deletes outside this workspace";
+ case "query-git-log":
+ return "Git history queries";
+ case "mutate-git-log":
+ return "Git history changes";
+ case "network":
+ return "network access";
+ case "mcp":
+ return "MCP tool access";
+ default:
+ return scope;
+ }
+}
+__name(describeScope, "describeScope");
+
+// packages/cli/src/ui/exit-summary.ts
+init_esbuild_shims();
+var ANSI_RE = /\u001b\[[0-9;]*[a-zA-Z]/g;
+function visibleLength(text) {
+ return text.replace(ANSI_RE, "").length;
+}
+__name(visibleLength, "visibleLength");
+function padRight(text, width) {
+ const padding = Math.max(0, width - visibleLength(text));
+ return text + " ".repeat(padding);
+}
+__name(padRight, "padRight");
+function padLeft(text, width) {
+ const padding = Math.max(0, width - visibleLength(text));
+ return " ".repeat(padding) + text;
+}
+__name(padLeft, "padLeft");
+function formatNumber(n) {
+ return n.toLocaleString("en-US");
+}
+__name(formatNumber, "formatNumber");
+function extractUsageFields(usage2) {
+ const empty = {
+ promptTokens: 0,
+ completionTokens: 0,
+ cachedTokens: 0,
+ totalReqs: 0
+ };
+ if (!usage2 || typeof usage2 !== "object" || Array.isArray(usage2)) {
+ return empty;
+ }
+ const record2 = usage2;
+ const promptTokens = typeof record2.prompt_tokens === "number" ? record2.prompt_tokens : 0;
+ const completionTokens = typeof record2.completion_tokens === "number" ? record2.completion_tokens : 0;
+ let cachedTokens = 0;
+ const promptDetails = record2.prompt_tokens_details;
+ if (promptDetails && typeof promptDetails === "object" && !Array.isArray(promptDetails)) {
+ const cached2 = promptDetails.cached_tokens;
+ if (typeof cached2 === "number") {
+ cachedTokens = cached2;
+ }
+ }
+ if (cachedTokens === 0 && typeof record2.prompt_cache_hit_tokens === "number") {
+ cachedTokens = record2.prompt_cache_hit_tokens;
+ }
+ const totalReqs = typeof record2.total_reqs === "number" ? record2.total_reqs : 0;
+ return { promptTokens, completionTokens, cachedTokens, totalReqs };
+}
+__name(extractUsageFields, "extractUsageFields");
+function buildExitSummaryText(input) {
+ const { session } = input;
+ const innerWidth = 98;
+ const contentWidth = innerWidth - 4;
+ const borderColor = source_default2.dim;
+ const titleColor = dist_default4("#229ac3e6", "rgb(125 51 247 / 0.7)");
+ const line = /* @__PURE__ */ __name((text) => `${borderColor("\u2502")} ${padRight(text, contentWidth)} ${borderColor("\u2502")}`, "line");
+ const header = source_default2.bold(titleColor("Goodbye!"));
+ const rows = ["", `${header}`, ""];
+ const usageRows = Object.entries(session?.usagePerModel ?? {}).map(([modelName, usage2]) => ({
+ modelName,
+ usage: extractUsageFields(usage2)
+ })).filter(
+ (row) => row.usage.totalReqs > 0 || row.usage.promptTokens > 0 || row.usage.completionTokens > 0 || row.usage.cachedTokens > 0
+ ).sort(
+ (left2, right2) => right2.usage.totalReqs - left2.usage.totalReqs || left2.modelName.localeCompare(right2.modelName)
+ );
+ const hasUsage = usageRows.length > 0;
+ if (hasUsage) {
+ const colModel = 34;
+ const colReqs = 8;
+ const colInput = 16;
+ const colOutput = 16;
+ const colCached = 18;
+ const tableWidth = colModel + colReqs + colInput + colOutput + colCached;
+ const divider = "\u2500".repeat(tableWidth);
+ const headerRow = padRight("Model Usage", colModel) + padLeft("Reqs", colReqs) + padLeft("Input Tokens", colInput) + padLeft("Output Tokens", colOutput) + padLeft("Cached Tokens", colCached);
+ rows.push(source_default2.bold(headerRow));
+ rows.push(source_default2.gray(divider));
+ for (const { modelName, usage: usage2 } of usageRows) {
+ const reqsStr = formatNumber(usage2.totalReqs).padStart(colReqs);
+ const inputStr = formatNumber(usage2.promptTokens).padStart(colInput);
+ const outputStr = formatNumber(usage2.completionTokens).padStart(colOutput);
+ const cachedStr = formatNumber(usage2.cachedTokens).padStart(colCached);
+ const dataRow = padRight(modelName, colModel) + padRight(reqsStr, colReqs) + padRight(source_default2.yellow(inputStr), colInput) + padRight(source_default2.yellow(outputStr), colOutput) + padRight(source_default2.yellow(cachedStr), colCached);
+ rows.push(dataRow);
+ }
+ rows.push("");
+ }
+ rows.push("");
+ const border = borderColor("\u2500".repeat(innerWidth));
+ const top2 = `${borderColor("\u256D")}${border}${borderColor("\u256E")}`;
+ const bottom2 = `${borderColor("\u2570")}${border}${borderColor("\u256F")}`;
+ const body = rows.map((row) => line(row)).join("\n");
+ return [top2, body, bottom2].join("\n");
+}
+__name(buildExitSummaryText, "buildExitSummaryText");
+function buildResumeHintText(sessionId) {
+ if (!sessionId) {
+ return null;
+ }
+ return source_default2.dim(`To continue this session, run `) + source_default2.hex("#229ac3")(`deepcode --resume ${sessionId}`);
+}
+__name(buildResumeHintText, "buildResumeHintText");
+
+// packages/cli/src/utils/stdio-helpers.ts
+init_esbuild_shims();
+var writeStdout = /* @__PURE__ */ __name((message) => {
+ process.stdout.write(message);
+}, "writeStdout");
+var writeStdoutLine = /* @__PURE__ */ __name((message) => {
+ process.stdout.write(message.endsWith("\n") ? message : `${message}
+`);
+}, "writeStdoutLine");
+var writeStderrLine = /* @__PURE__ */ __name((message) => {
+ process.stderr.write(message.endsWith("\n") ? message : `${message}
+`);
+}, "writeStderrLine");
+
+// packages/cli/src/ui/views/App.tsx
+var import_jsx_runtime19 = __toESM(require_jsx_runtime(), 1);
+var STATUS_SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
+var StatusLine2 = import_react57.default.memo(/* @__PURE__ */ __name(function StatusLine3({
+ busy,
+ text
+}) {
+ const [spinnerIndex, setSpinnerIndex] = (0, import_react57.useState)(0);
+ (0, import_react57.useEffect)(() => {
+ if (!busy) {
+ setSpinnerIndex(0);
+ return;
+ }
+ const timer = setInterval(() => {
+ setSpinnerIndex((index) => (index + 1) % STATUS_SPINNER_FRAMES.length);
+ }, 80);
+ return () => clearInterval(timer);
+ }, [busy]);
+ return /* @__PURE__ */ (0, import_jsx_runtime19.jsxs)(Box_default, { children: [
+ busy ? /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(Box_default, { marginRight: 1, children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(Text, { color: "yellow", children: STATUS_SPINNER_FRAMES[spinnerIndex] }) }) : null,
+ text ? /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(Text, { dimColor: true, children: text }) : null
+ ] });
+}, "StatusLine"));
+function App2({ projectRoot, initialPrompt, resumeSessionId, onRestart }) {
+ const { exit } = use_app_default();
+ const { stdout, write } = use_stdout_default();
+ const { columns, rows } = use_window_size_default();
+ const { mode, setMode } = useRawModeContext();
+ const initialPromptSubmittedRef = (0, import_react57.useRef)(false);
+ const resumeSessionIdRef = (0, import_react57.useRef)(false);
+ const startupDoneRef = (0, import_react57.useRef)(false);
+ const processStdoutRef = (0, import_react57.useRef)(/* @__PURE__ */ new Map());
+ const rawModeRef = (0, import_react57.useRef)(mode);
+ const writeRef = (0, import_react57.useRef)(write);
+ const lastRenderedColumnsRef = (0, import_react57.useRef)(null);
+ const messagesRef = (0, import_react57.useRef)([]);
+ const [view, setView] = (0, import_react57.useState)("chat");
+ const [busy, setBusy] = (0, import_react57.useState)(false);
+ const [skills, setSkills] = (0, import_react57.useState)([]);
+ const [messages, setMessages] = (0, import_react57.useState)([]);
+ const [sessions, setSessions] = (0, import_react57.useState)([]);
+ const [undoTargets, setUndoTargets] = (0, import_react57.useState)([]);
+ const [promptDraft, setPromptDraft] = (0, import_react57.useState)(null);
+ const [statusLine, setStatusLine] = (0, import_react57.useState)("");
+ const [errorLine, setErrorLine] = (0, import_react57.useState)(null);
+ const [streamProgress, setStreamProgress] = (0, import_react57.useState)(null);
+ const [runningProcesses, setRunningProcesses] = (0, import_react57.useState)(null);
+ const [activeStatus, setActiveStatus] = (0, import_react57.useState)(null);
+ const [activeAskPermissions, setActiveAskPermissions] = (0, import_react57.useState)(void 0);
+ const [pendingPermissionReply, setPendingPermissionReply] = (0, import_react57.useState)(null);
+ const [dismissedQuestionIds, setDismissedQuestionIds] = (0, import_react57.useState)(() => /* @__PURE__ */ new Set());
+ const [isExiting, setIsExiting] = (0, import_react57.useState)(false);
+ const [showWelcome, setShowWelcome] = (0, import_react57.useState)(true);
+ const [welcomeNonce, setWelcomeNonce] = (0, import_react57.useState)(0);
+ const [resolvedSettings, setResolvedSettings] = (0, import_react57.useState)(() => resolveCurrentSettings(projectRoot));
+ const [nowTick, setNowTick] = (0, import_react57.useState)(0);
+ const [mcpStatuses, setMcpStatuses] = (0, import_react57.useState)([]);
+ const [showProcessStdout, setShowProcessStdout] = (0, import_react57.useState)(false);
+ rawModeRef.current = mode;
+ messagesRef.current = messages;
+ const sessionManager = (0, import_react57.useMemo)(() => {
+ return new SessionManager({
+ projectRoot,
+ createOpenAIClient: /* @__PURE__ */ __name(() => createOpenAIClient(projectRoot), "createOpenAIClient"),
+ getResolvedSettings: /* @__PURE__ */ __name(() => resolveCurrentSettings(projectRoot), "getResolvedSettings"),
+ renderMarkdown: /* @__PURE__ */ __name((text) => text, "renderMarkdown"),
+ onAssistantMessage: /* @__PURE__ */ __name((message) => {
+ setMessages((prev) => [...prev, message]);
+ if (rawModeRef.current === "Raw scrollback mode" /* Raw */) {
+ writeStdoutLine("\n");
+ writeStdoutLine(renderMessageToStdout(message, rawModeRef.current) + "\n\n");
+ }
+ }, "onAssistantMessage"),
+ onSessionEntryUpdated: /* @__PURE__ */ __name((entry) => {
+ setStatusLine(buildStatusLine(entry));
+ setRunningProcesses(entry.processes);
+ setActiveStatus(entry.status);
+ setActiveAskPermissions(entry.askPermissions);
+ }, "onSessionEntryUpdated"),
+ onLlmStreamProgress: /* @__PURE__ */ __name((progress) => {
+ if (progress.phase === "end") {
+ setStreamProgress(null);
+ return;
+ }
+ setStreamProgress(progress);
+ }, "onLlmStreamProgress"),
+ onMcpStatusChanged: /* @__PURE__ */ __name(() => {
+ setMcpStatuses(sessionManager.getMcpStatus());
+ }, "onMcpStatusChanged"),
+ onProcessStdout: /* @__PURE__ */ __name((pid, chunk) => {
+ const buf = processStdoutRef.current;
+ const current = buf.get(pid) ?? "";
+ const MAX_STDOUT_BUFFER = 1e6;
+ if (current.length >= MAX_STDOUT_BUFFER) {
+ return;
+ }
+ const text = typeof chunk === "string" ? chunk : String(chunk);
+ const available = MAX_STDOUT_BUFFER - current.length;
+ buf.set(pid, current + text.slice(0, available));
+ }, "onProcessStdout")
+ });
+ }, [projectRoot]);
+ const navigateToSubView = (0, import_react57.useCallback)((targetView) => {
+ setShowWelcome(false);
+ setView(targetView);
+ }, []);
+ const resetStaticView = (0, import_react57.useCallback)(
+ (loadedMessages, options2) => {
+ if (options2?.clearScreen) {
+ writeStdout(ANSI_CLEAR_SCREEN);
+ }
+ setMessages([]);
+ setWelcomeNonce((n) => n + 1);
+ navigateToSubView("chat");
+ return new Promise((resolve16) => {
+ setTimeout(() => {
+ setMessages(loadedMessages);
+ setShowWelcome(true);
+ resolve16();
+ }, 0);
+ });
+ },
+ [navigateToSubView]
+ );
+ (0, import_react57.useEffect)(() => {
+ if (!busy) {
+ return;
+ }
+ const id = setInterval(() => setNowTick((tick) => tick + 1), 500);
+ return () => clearInterval(id);
+ }, [busy]);
+ function loadVisibleMessages(manager, sessionId) {
+ return manager.listSessionMessages(sessionId).filter((m) => m.visible);
+ }
+ __name(loadVisibleMessages, "loadVisibleMessages");
+ const refreshSessionsList = (0, import_react57.useCallback)(() => {
+ setSessions(sessionManager.listSessions());
+ }, [sessionManager]);
+ const refreshSkills = (0, import_react57.useCallback)(
+ async (sessionId) => {
+ try {
+ const list = await sessionManager.listSkills(sessionId ?? sessionManager.getActiveSessionId() ?? void 0);
+ setSkills(list);
+ } catch {
+ }
+ },
+ [sessionManager]
+ );
+ const resetToWelcome = (0, import_react57.useCallback)(async () => {
+ writeRef.current(ANSI_CLEAR_SCREEN);
+ sessionManager.setActiveSessionId(null);
+ setStatusLine("");
+ setErrorLine(null);
+ setRunningProcesses(null);
+ setActiveStatus(null);
+ setActiveAskPermissions(void 0);
+ setPendingPermissionReply(null);
+ setDismissedQuestionIds(/* @__PURE__ */ new Set());
+ await resetStaticView([]);
+ await refreshSkills();
+ }, [sessionManager, resetStaticView, refreshSkills]);
+ (0, import_react57.useEffect)(() => {
+ refreshSessionsList();
+ void refreshSkills();
+ }, [refreshSessionsList, refreshSkills]);
+ (0, import_react57.useEffect)(() => {
+ createOpenAIClient(projectRoot);
+ }, [projectRoot]);
+ (0, import_react57.useLayoutEffect)(() => {
+ const settings = resolveCurrentSettings(projectRoot);
+ void sessionManager.initMcpServers(settings.mcpServers);
+ }, [projectRoot, sessionManager]);
+ (0, import_react57.useEffect)(() => {
+ return () => {
+ sessionManager.dispose();
+ };
+ }, [sessionManager]);
+ writeRef.current = write;
+ const handleExit = (0, import_react57.useCallback)(
+ ({ showCommand, showSummary }) => {
+ setIsExiting(true);
+ setTimeout(() => {
+ const activeSessionId = sessionManager.getActiveSessionId();
+ const session = activeSessionId ? sessionManager.getSession(activeSessionId) : null;
+ const resumeHint = buildResumeHintText(activeSessionId ?? void 0);
+ writeStdoutLine("\n");
+ if (showCommand) {
+ writeStdoutLine(source_default2.rgb(34, 154, 195)(" > /exit "));
+ writeStdoutLine("\n");
+ }
+ if (showSummary) {
+ const summary = buildExitSummaryText({ session, sessionId: activeSessionId ?? void 0 });
+ writeStdoutLine(summary);
+ writeStdoutLine("\n");
+ }
+ if (resumeHint) {
+ writeStdoutLine(resumeHint);
+ writeStdoutLine("\n");
+ }
+ sessionManager.dispose();
+ exit();
+ }, 0);
+ },
+ [exit, sessionManager]
+ );
+ const handlePrompt = (0, import_react57.useCallback)(
+ async (submission) => {
+ if (submission.command === "exit") {
+ handleExit({ showCommand: true, showSummary: true });
+ return;
+ }
+ if (submission.command === "new") {
+ if (onRestart) {
+ onRestart();
+ } else {
+ await resetToWelcome();
+ refreshSessionsList();
+ }
+ return;
+ }
+ if (submission.command === "resume") {
+ refreshSessionsList();
+ navigateToSubView("session-list");
+ return;
+ }
+ if (submission.command === "continue" && isCurrentSessionEmpty(sessionManager)) {
+ refreshSessionsList();
+ navigateToSubView("session-list");
+ return;
+ }
+ if (submission.command === "undo") {
+ const activeSessionId2 = sessionManager.getActiveSessionId();
+ if (!activeSessionId2) {
+ setErrorLine("No active session to undo.");
+ return;
+ }
+ setUndoTargets(sessionManager.listUndoTargets(activeSessionId2));
+ navigateToSubView("undo");
+ return;
+ }
+ if (submission.command === "mcp") {
+ setMcpStatuses(sessionManager.getMcpStatus());
+ navigateToSubView("mcp-status");
+ return;
+ }
+ if (submission.command === "compact") {
+ const activeSessionId2 = sessionManager.getActiveSessionId();
+ if (!activeSessionId2) {
+ setErrorLine("No active session to compact.");
+ return;
+ }
+ setBusy(true);
+ sessionManager.addSessionSystemMessage(
+ activeSessionId2,
+ "Compacting conversation context to reduce token usage...",
+ true,
+ { asThinking: true }
+ );
+ sessionManager.compactSession(activeSessionId2).then(() => {
+ setBusy(false);
+ refreshSessionsList();
+ }).catch((err) => {
+ setBusy(false);
+ setErrorLine(`Compact failed: ${err instanceof Error ? err.message : String(err)}`);
+ });
+ return;
+ }
+ if (submission.command === "context") {
+ const sessionInfo = getSessionInfo();
+ if (!sessionInfo.activeSessionId) {
+ setErrorLine("No active session.");
+ return;
+ }
+ const pct = sessionInfo.maxContextTokens > 0 ? Math.round(sessionInfo.activeTokens / sessionInfo.maxContextTokens * 100) : 0;
+ const summary = [
+ `Model: ${sessionInfo.model}`,
+ `Messages: ${sessionInfo.messageCount}`,
+ `API requests: ${sessionInfo.requestCount}`,
+ `Active tokens: ${sessionInfo.activeTokens.toLocaleString()} / ${sessionInfo.maxContextTokens.toLocaleString()} (${pct}%)`,
+ `Total tokens used: ${sessionInfo.totalTokens.toLocaleString()}`
+ ];
+ if (Object.keys(sessionInfo.toolUsage).length > 0) {
+ const tools = Object.entries(sessionInfo.toolUsage).sort(([, a], [, b]) => b - a).slice(0, 5).map(([name, count]) => ` ${name}: ${count}x`).join("\n");
+ summary.push(`
+Top tools:
+${tools}`);
+ }
+ sessionManager.addSessionSystemMessage(sessionInfo.activeSessionId, summary.join("\n"), true, { asThinking: true });
+ return;
+ }
+ const prompt = {
+ text: submission.text,
+ imageUrls: submission.imageUrls,
+ skills: submission.selectedSkills && submission.selectedSkills.length > 0 ? submission.selectedSkills : void 0,
+ permissions: submission.permissions,
+ alwaysAllows: submission.alwaysAllows
+ };
+ const activeSessionId = sessionManager.getActiveSessionId();
+ const permissionReply = pendingPermissionReply && activeSessionId === pendingPermissionReply.sessionId ? pendingPermissionReply : null;
+ if (permissionReply) {
+ prompt.permissions = permissionReply.permissions;
+ prompt.alwaysAllows = permissionReply.alwaysAllows;
+ }
+ const trimmedText = (submission.text ?? "").trim();
+ const selectedSkillNames = submission.selectedSkills?.map((skill) => skill.name).filter(Boolean) ?? [];
+ const userDisplayContent = trimmedText || (selectedSkillNames.length > 0 ? `Use skills: ${selectedSkillNames.join(", ")}` : "") || (submission.imageUrls.length > 0 ? "[Image]" : "");
+ if (userDisplayContent && submission.command !== "continue") {
+ setMessages((prev) => [...prev, buildSyntheticUserMessage(userDisplayContent, submission.imageUrls.length)]);
+ }
+ setBusy(true);
+ setErrorLine(null);
+ const activeProcesses = activeSessionId ? sessionManager.getSession(activeSessionId)?.processes ?? null : null;
+ setRunningProcesses(activeProcesses);
+ setShowProcessStdout(false);
+ if (!activeProcesses || activeProcesses.size === 0) {
+ processStdoutRef.current.clear();
+ }
+ try {
+ await sessionManager.handleUserPrompt(prompt);
+ if (permissionReply) {
+ setPendingPermissionReply(null);
+ }
+ await refreshSkills();
+ refreshSessionsList();
+ } catch (error51) {
+ const message = error51 instanceof Error ? error51.message : String(error51);
+ setErrorLine(message);
+ } finally {
+ setBusy(false);
+ setStreamProgress(null);
+ const finalActiveSessionId = sessionManager.getActiveSessionId();
+ setRunningProcesses(
+ finalActiveSessionId ? sessionManager.getSession(finalActiveSessionId)?.processes ?? null : null
+ );
+ }
+ },
+ [
+ sessionManager,
+ pendingPermissionReply,
+ handleExit,
+ onRestart,
+ refreshSkills,
+ refreshSessionsList,
+ navigateToSubView,
+ resetToWelcome
+ ]
+ );
+ const handleInterrupt = (0, import_react57.useCallback)(() => {
+ sessionManager.interruptActiveSession();
+ }, [sessionManager]);
+ const handleToggleProcessStdout = (0, import_react57.useCallback)(() => {
+ setShowProcessStdout(true);
+ }, []);
+ const handleDismissProcessStdout = (0, import_react57.useCallback)(() => {
+ setShowProcessStdout(false);
+ }, []);
+ const handleAdjustBashTimeout = (0, import_react57.useCallback)(
+ (deltaMs) => sessionManager.adjustActiveBashTimeout(deltaMs),
+ [sessionManager]
+ );
+ const handleModelConfigChange = (0, import_react57.useCallback)(
+ (selection) => {
+ const current = resolveCurrentSettings(projectRoot);
+ const { changed } = writeModelConfigSelection(selection, current, projectRoot);
+ const next = resolveCurrentSettings(projectRoot);
+ setResolvedSettings(next);
+ if (!changed) {
+ return "Model settings unchanged";
+ }
+ const activeSessionId = sessionManager.getActiveSessionId();
+ const meta3 = {
+ isModelChange: true
+ };
+ const content = `/model
+\u2514 Set model to ${selection.model} (${selection?.thinkingEnabled ? selection?.reasoningEffort : "no thinking"})`;
+ if (activeSessionId) {
+ sessionManager.addSessionSystemMessage(activeSessionId, content, true, meta3);
+ } else {
+ const now = (/* @__PURE__ */ new Date()).toISOString();
+ setMessages((prev) => [
+ ...prev,
+ {
+ id: crypto.randomUUID(),
+ sessionId: "local",
+ role: "system",
+ content,
+ contentParams: null,
+ messageParams: null,
+ compacted: false,
+ visible: true,
+ createTime: now,
+ updateTime: now,
+ meta: meta3
+ }
+ ]);
+ }
+ return `Model settings updated: ${formatModelConfig(current)} \u2192 ${formatModelConfig(next)}`;
+ },
+ [projectRoot, sessionManager]
+ );
+ const handleSubmit = (0, import_react57.useCallback)(
+ (submission) => {
+ void handlePrompt(submission);
+ },
+ [handlePrompt]
+ );
+ const handleExitShortcut = (0, import_react57.useCallback)(() => {
+ handleExit({ showCommand: false, showSummary: false });
+ }, [handleExit]);
+ const reloadActiveSessionView = (0, import_react57.useCallback)(
+ (sessionId) => {
+ resetStaticView(loadVisibleMessages(sessionManager, sessionId), { clearScreen: true });
+ },
+ [resetStaticView, sessionManager]
+ );
+ const handleSelectSession = (0, import_react57.useCallback)(
+ async (sessionId) => {
+ sessionManager.setActiveSessionId(sessionId);
+ await resetStaticView(loadVisibleMessages(sessionManager, sessionId), { clearScreen: true });
+ const session = sessionManager.getSession(sessionId);
+ setStatusLine(session ? buildStatusLine(session) : "");
+ setRunningProcesses(session?.processes ?? null);
+ setActiveStatus(session?.status ?? null);
+ setActiveAskPermissions(session?.askPermissions);
+ if (pendingPermissionReply && pendingPermissionReply.sessionId !== sessionId) {
+ setPendingPermissionReply(null);
+ }
+ await refreshSkills(sessionId);
+ },
+ [sessionManager, resetStaticView, pendingPermissionReply, refreshSkills]
+ );
+ (0, import_react57.useEffect)(() => {
+ if (startupDoneRef.current) {
+ return;
+ }
+ startupDoneRef.current = true;
+ async function run() {
+ if (resumeSessionId) {
+ resumeSessionIdRef.current = true;
+ if (resumeSessionId === true) {
+ refreshSessionsList();
+ navigateToSubView("session-list");
+ return;
+ }
+ await handleSelectSession(resumeSessionId);
+ }
+ if (initialPrompt && initialPrompt.trim()) {
+ initialPromptSubmittedRef.current = true;
+ handleSubmit({
+ text: initialPrompt,
+ imageUrls: [],
+ selectedSkills: void 0
+ });
+ }
+ }
+ __name(run, "run");
+ void run();
+ }, [handleSubmit, handleSelectSession, initialPrompt, navigateToSubView, refreshSessionsList, resumeSessionId]);
+ const handleDeleteSession = (0, import_react57.useCallback)(
+ async (id) => {
+ const isActiveSession = sessionManager.getActiveSessionId() === id;
+ if (isActiveSession) {
+ sessionManager.setActiveSessionId(null);
+ }
+ sessionManager.deleteSession(id);
+ refreshSessionsList();
+ if (isActiveSession) {
+ await resetToWelcome();
+ }
+ },
+ [sessionManager, refreshSessionsList, resetToWelcome]
+ );
+ const handleUndoRestore = (0, import_react57.useCallback)(
+ async (target, restoreMode) => {
+ const sessionId = sessionManager.getActiveSessionId();
+ if (!sessionId) {
+ setErrorLine("No active session to undo.");
+ setView("chat");
+ setShowWelcome(true);
+ return;
+ }
+ const errors = [];
+ if (restoreMode === "code-and-conversation") {
+ try {
+ sessionManager.restoreSessionCode(sessionId, target.message.id);
+ } catch (error51) {
+ errors.push(`Code restore failed: ${error51 instanceof Error ? error51.message : String(error51)}`);
+ }
+ }
+ let conversationRestored = false;
+ try {
+ sessionManager.restoreSessionConversation(sessionId, target.message.id);
+ conversationRestored = true;
+ } catch (error51) {
+ errors.push(`Conversation restore failed: ${error51 instanceof Error ? error51.message : String(error51)}`);
+ }
+ refreshSessionsList();
+ await refreshSkills(sessionId);
+ setView("chat");
+ setErrorLine(errors.length > 0 ? errors.join(" ") : null);
+ if (conversationRestored) {
+ setPromptDraft(buildPromptDraftFromSessionMessage(target.message, Date.now()));
+ }
+ reloadActiveSessionView(sessionId);
+ },
+ [reloadActiveSessionView, refreshSessionsList, refreshSkills, sessionManager]
+ );
+ const handleRawModeChange = (0, import_react57.useCallback)(
+ (nextMode) => {
+ const activeSessionId = sessionManager.getActiveSessionId();
+ setMode(nextMode);
+ setShowWelcome(false);
+ setMessages([]);
+ writeStdout(ANSI_CLEAR_SCREEN);
+ setTimeout(() => {
+ if (nextMode === "Raw scrollback mode" /* Raw */) {
+ const allMessages = activeSessionId ? loadVisibleMessages(sessionManager, activeSessionId) : [];
+ renderRawModeMessages(allMessages, nextMode);
+ } else if (activeSessionId) {
+ handleSelectSession(activeSessionId);
+ } else {
+ setWelcomeNonce((n) => n + 1);
+ setShowWelcome(true);
+ }
+ }, 200);
+ },
+ [handleSelectSession, sessionManager, setMode]
+ );
+ (0, import_react57.useEffect)(() => {
+ if (!stdout?.isTTY) {
+ return;
+ }
+ if (columns <= 0) {
+ return;
+ }
+ if (lastRenderedColumnsRef.current === null) {
+ lastRenderedColumnsRef.current = columns;
+ return;
+ }
+ if (lastRenderedColumnsRef.current === columns) {
+ return;
+ }
+ lastRenderedColumnsRef.current = columns;
+ if (mode === "Raw scrollback mode" /* Raw */) {
+ writeStdout(ANSI_CLEAR_SCREEN);
+ const activeSessionId2 = sessionManager.getActiveSessionId();
+ const allMessages = activeSessionId2 ? loadVisibleMessages(sessionManager, activeSessionId2) : [];
+ renderRawModeMessages(allMessages, mode);
+ return;
+ }
+ writeRef.current("\x1B[2J\x1B[H");
+ setMessages([]);
+ setShowWelcome(false);
+ setWelcomeNonce((n) => n + 1);
+ const activeSessionId = sessionManager.getActiveSessionId();
+ const nextMessages = activeSessionId && !busy ? loadVisibleMessages(sessionManager, activeSessionId) : messagesRef.current;
+ setTimeout(() => {
+ setMessages(nextMessages);
+ setShowWelcome(true);
+ }, 0);
+ }, [busy, mode, sessionManager, columns, stdout]);
+ const screenWidth = (0, import_react57.useMemo)(() => columns ?? stdout?.columns ?? 80, [columns, stdout]);
+ const screenHeight = (0, import_react57.useMemo)(() => rows ?? stdout?.rows ?? 24, [rows, stdout]);
+ const getSessionInfo = (0, import_react57.useCallback)(() => {
+ const activeSessionId = sessionManager.getActiveSessionId();
+ const settings = resolveCurrentSettings(projectRoot);
+ const model = settings.model || "";
+ const thinkingEnabled = settings.thinkingEnabled;
+ const reasoningEffort = settings.reasoningEffort;
+ const maxContextTokens = getCompactPromptTokenThreshold(model);
+ if (!activeSessionId) {
+ return {
+ activeSessionId: null,
+ messageCount: 0,
+ requestCount: 0,
+ totalTokens: 0,
+ activeTokens: 0,
+ maxContextTokens,
+ model,
+ thinkingEnabled,
+ reasoningEffort,
+ toolUsage: {}
+ };
+ }
+ const session = sessionManager.getSession(activeSessionId);
+ const messages2 = sessionManager.listSessionMessages(activeSessionId);
+ const usage2 = session?.usage;
+ const totalTokens = usage2 && typeof usage2.total_tokens === "number" ? usage2.total_tokens ?? 0 : 0;
+ const requestCount = usage2 && typeof usage2.total_reqs === "number" ? usage2.total_reqs ?? 0 : 0;
+ const toolUsage = {};
+ for (const msg of messages2) {
+ if (msg.role === "tool" && msg.meta?.function) {
+ const fn = msg.meta.function;
+ if (fn.name) {
+ toolUsage[fn.name] = (toolUsage[fn.name] || 0) + 1;
+ }
+ }
+ }
+ return {
+ activeSessionId,
+ messageCount: messages2.length,
+ requestCount,
+ totalTokens,
+ activeTokens: session?.activeTokens ?? 0,
+ maxContextTokens,
+ model,
+ thinkingEnabled,
+ reasoningEffort,
+ toolUsage
+ };
+ }, [sessionManager, projectRoot]);
+ const statusLineSegments = useStatusLine(resolvedSettings.statusline, projectRoot, getSessionInfo);
+ const promptHistory = (0, import_react57.useMemo)(() => {
+ return messages.filter((message) => message.role === "user" && typeof message.content === "string").map((message) => (message.content ?? "").trim()).filter((content) => content.length > 0);
+ }, [messages]);
+ const expandedThinkingId = findExpandedThinkingId(messages);
+ const pendingQuestion = (0, import_react57.useMemo)(() => findPendingAskUserQuestion(messages, activeStatus), [activeStatus, messages]);
+ const shouldShowQuestionPrompt = Boolean(pendingQuestion && !dismissedQuestionIds.has(pendingQuestion.messageId));
+ const loadingText = (0, import_react57.useMemo)(
+ () => busy ? buildLoadingText({ progress: streamProgress, processes: runningProcesses, now: Date.now() }) : null,
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- nowTick forces periodic recalculation for spinner animation
+ [busy, streamProgress, runningProcesses, nowTick]
+ );
+ const welcomeItem = (0, import_react57.useMemo)(
+ () => ({
+ id: `__welcome__${welcomeNonce}`,
+ sessionId: "",
+ role: "system",
+ content: "",
+ contentParams: null,
+ messageParams: null,
+ compacted: false,
+ visible: true,
+ createTime: "",
+ updateTime: ""
+ }),
+ [welcomeNonce]
+ );
+ const staticItems = (0, import_react57.useMemo)(() => {
+ if (mode === "Raw scrollback mode" /* Raw */) {
+ return [];
+ }
+ if (showWelcome && view === "chat") {
+ return [welcomeItem, ...messages];
+ }
+ return messages;
+ }, [mode, showWelcome, view, messages, welcomeItem]);
+ const promptCursorLayoutKey = (0, import_react57.useMemo)(() => {
+ const lastStaticItem = staticItems.at(-1);
+ return [
+ view,
+ busy ? "busy" : "idle",
+ statusLine,
+ errorLine ?? "",
+ showProcessStdout ? "stdout" : "main",
+ activeStatus ?? "",
+ staticItems.length,
+ lastStaticItem?.id ?? "",
+ lastStaticItem?.updateTime ?? "",
+ shouldShowQuestionPrompt ? pendingQuestion?.messageId ?? "" : "",
+ activeAskPermissions?.length ?? 0,
+ pendingPermissionReply ? "pending-permission-reply" : "no-pending-permission-reply"
+ ].join("");
+ }, [
+ activeAskPermissions,
+ activeStatus,
+ busy,
+ errorLine,
+ pendingPermissionReply,
+ pendingQuestion,
+ shouldShowQuestionPrompt,
+ showProcessStdout,
+ staticItems,
+ statusLine,
+ view
+ ]);
+ const handleQuestionAnswers = (0, import_react57.useCallback)(
+ (answers) => {
+ void handlePrompt({
+ text: formatAskUserQuestionAnswers(answers),
+ imageUrls: []
+ });
+ },
+ [handlePrompt]
+ );
+ const handleQuestionCancel = (0, import_react57.useCallback)(() => {
+ if (!pendingQuestion) {
+ return;
+ }
+ setDismissedQuestionIds((prev) => new Set(prev).add(pendingQuestion.messageId));
+ }, [pendingQuestion]);
+ const handlePermissionResult = (0, import_react57.useCallback)(
+ (result) => {
+ const sessionId = sessionManager.getActiveSessionId();
+ if (!sessionId) {
+ return;
+ }
+ setPromptDraft(null);
+ if (result.hasDeny) {
+ setPendingPermissionReply({
+ sessionId,
+ permissions: result.permissions,
+ alwaysAllows: result.alwaysAllows
+ });
+ setStatusLine("Permission denied. Add a reply, then press Enter to continue.");
+ sessionManager.denySessionPermission(sessionId);
+ return;
+ }
+ void handlePrompt({
+ text: "/continue",
+ imageUrls: [],
+ command: "continue",
+ permissions: result.permissions,
+ alwaysAllows: result.alwaysAllows
+ });
+ },
+ [handlePrompt, sessionManager]
+ );
+ const handlePermissionCancel = (0, import_react57.useCallback)(() => {
+ sessionManager.interruptActiveSession();
+ setActiveStatus("interrupted");
+ setActiveAskPermissions(void 0);
+ setPromptDraft(null);
+ refreshSessionsList();
+ }, [refreshSessionsList, sessionManager]);
+ if (mode === "Raw scrollback mode" /* Raw */) {
+ return /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(RawModeExitPrompt, { onExit: (prev) => handleRawModeChange(prev) });
+ }
+ return /* @__PURE__ */ (0, import_jsx_runtime19.jsxs)(Box_default, { flexDirection: "column", width: screenWidth, minWidth: 80, overflowX: "visible", children: [
+ /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(Static, { items: staticItems, children: (item) => {
+ if (item.id.startsWith("__welcome__")) {
+ return /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(
+ WelcomeScreen,
+ {
+ projectRoot,
+ settings: resolvedSettings,
+ skills,
+ width: screenWidth
+ },
+ item.id
+ );
+ }
+ return /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(
+ MessageView,
+ {
+ message: item,
+ collapsed: isCollapsedThinking(item, expandedThinkingId),
+ width: screenWidth
+ },
+ item.id
+ );
+ } }),
+ (busy || statusLine) && !isExiting ? /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(StatusLine2, { busy, text: statusLine }) : null,
+ errorLine ? /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(Box_default, { children: /* @__PURE__ */ (0, import_jsx_runtime19.jsxs)(Text, { color: "red", children: [
+ "Error: ",
+ errorLine
+ ] }) }) : null,
+ showProcessStdout ? /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(
+ ProcessStdoutView,
+ {
+ processStdoutRef,
+ runningProcesses,
+ onDismiss: handleDismissProcessStdout,
+ onAdjustTimeout: handleAdjustBashTimeout,
+ screenWidth,
+ screenHeight
+ }
+ ) : view === "session-list" ? /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(
+ SessionList,
+ {
+ sessions,
+ onSelect: (id) => void handleSelectSession(id),
+ onCancel: () => setView("chat"),
+ onDelete: (id) => {
+ void handleDeleteSession(id);
+ },
+ onRename: (id, newName) => {
+ if (sessionManager.renameSession(id, newName)) {
+ refreshSessionsList();
+ setStatusLine(`Session renamed to "${newName}".`);
+ } else {
+ setErrorLine("Failed to rename session.");
+ }
+ }
+ }
+ ) : view === "undo" ? /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(
+ UndoSelector,
+ {
+ targets: undoTargets,
+ onSelect: (target, restoreMode) => void handleUndoRestore(target, restoreMode),
+ onCancel: () => {
+ setPromptDraft(null);
+ setView("chat");
+ }
+ }
+ ) : view === "mcp-status" ? /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(
+ McpStatusList,
+ {
+ statuses: mcpStatuses,
+ onCancel: () => setView("chat"),
+ onReconnect: (name) => {
+ const latest = resolveCurrentSettings(projectRoot);
+ void sessionManager.reconnectMcpServer(name, latest.mcpServers?.[name]);
+ }
+ }
+ ) : shouldShowQuestionPrompt && pendingQuestion && !busy ? /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(
+ AskUserQuestionPrompt,
+ {
+ questions: pendingQuestion.questions,
+ onSubmit: handleQuestionAnswers,
+ onCancel: handleQuestionCancel
+ }
+ ) : activeStatus === "ask_permission" && activeAskPermissions && activeAskPermissions.length > 0 && !pendingPermissionReply && !busy ? /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(
+ PermissionPrompt,
+ {
+ requests: activeAskPermissions,
+ onSubmit: handlePermissionResult,
+ onCancel: handlePermissionCancel
+ }
+ ) : isExiting ? null : /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(
+ PromptInput,
+ {
+ projectRoot,
+ screenWidth,
+ skills,
+ modelConfig: resolvedSettings,
+ promptHistory,
+ busy,
+ cursorLayoutKey: promptCursorLayoutKey,
+ loadingText,
+ runningProcesses,
+ promptDraft,
+ onSubmit: handleSubmit,
+ onModelConfigChange: handleModelConfigChange,
+ onRawModeChange: handleRawModeChange,
+ onInterrupt: handleInterrupt,
+ onToggleProcessStdout: handleToggleProcessStdout,
+ onExitShortcut: handleExitShortcut,
+ placeholder: "Type your message...",
+ statusLineSegments,
+ statusLineSeparator: resolvedSettings.statusline.separator
+ }
+ )
+ ] });
+}
+__name(App2, "App");
+var App_default2 = App2;
+
+// packages/cli/src/ui/views/AppContainer.tsx
+var import_jsx_runtime20 = __toESM(require_jsx_runtime(), 1);
+var AppContainer = /* @__PURE__ */ __name(({ version: version2, projectRoot, initialPrompt, resumeSessionId, onRestart }) => {
+ return /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(AppContext2.Provider, { value: { version: version2 }, children: /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(RawModeProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime20.jsx)(
+ App_default2,
+ {
+ initialPrompt,
+ resumeSessionId,
+ projectRoot,
+ onRestart
+ }
+ ) }) });
+}, "AppContainer");
+var AppContainer_default = AppContainer;
+
+// packages/cli/src/ui/views/UpdatePrompt.tsx
+init_esbuild_shims();
+var import_react58 = __toESM(require_react(), 1);
+var import_jsx_runtime21 = __toESM(require_jsx_runtime(), 1);
+function UpdatePrompt({ currentVersion, latestVersion, installCommand, onSelect }) {
+ const { exit } = use_app_default();
+ const [selectedIndex, setSelectedIndex] = (0, import_react58.useState)(0);
+ const options2 = [
+ {
+ value: "install",
+ label: `Install the latest version with \`${installCommand}\``
+ },
+ {
+ value: "ignore-once",
+ label: "Ignore once"
+ },
+ {
+ value: "ignore-version",
+ label: `Ignore this version (${latestVersion})`
+ }
+ ];
+ use_input_default((input, key) => {
+ if (key.upArrow) {
+ setSelectedIndex((index) => (index - 1 + options2.length) % options2.length);
+ return;
+ }
+ if (key.downArrow || key.tab) {
+ setSelectedIndex((index) => (index + 1) % options2.length);
+ return;
+ }
+ if (key.return) {
+ onSelect(options2[selectedIndex]?.value ?? "ignore-once");
+ exit();
+ return;
+ }
+ if (key.escape || key.ctrl && (input === "c" || input === "C")) {
+ onSelect("ignore-once");
+ exit();
+ return;
+ }
+ if (/^[1-3]$/.test(input)) {
+ onSelect(options2[Number(input) - 1]?.value ?? "ignore-once");
+ exit();
+ }
+ });
+ return /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)(Box_default, { flexDirection: "column", marginY: 1, children: [
+ /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)(Text, { bold: true, children: [
+ "Deep Code latest version has been released: ",
+ currentVersion,
+ " -> ",
+ latestVersion
+ ] }),
+ /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Box_default, { flexDirection: "column", marginTop: 1, children: options2.map((option, index) => {
+ const selected = index === selectedIndex;
+ return /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)(Text, { color: selected ? "green" : void 0, children: [
+ selected ? "> " : " ",
+ index + 1,
+ ". ",
+ option.label
+ ] }, option.value);
+ }) }),
+ /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Box_default, { marginTop: 1, children: /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(Text, { dimColor: true, children: "Use Up/Down to choose, Enter to confirm, Esc to ignore once." }) })
+ ] });
+}
+__name(UpdatePrompt, "UpdatePrompt");
+
+// packages/cli/src/common/update-check.ts
+var UPDATE_STATE_FILE = "update-check.json";
+var NPM_VIEW_TIMEOUT_MS = 5e3;
+var MAX_NPM_VIEW_OUTPUT_CHARS = 64 * 1024;
+var TENCENT_MIRROR_REGISTRY = "https://mirrors.cloud.tencent.com/npm/";
+var UPDATE_SUCCESS_MESSAGE = "\u{1F389} Update ran successfully! Please restart Deep Code.";
+async function promptForPendingUpdate(packageInfo2) {
+ const state = readUpdateState();
+ const pending = state.pending;
+ if (!pending) {
+ return { installed: false };
+ }
+ if (compareVersions(packageInfo2.version, pending.latestVersion) >= 0) {
+ writeUpdateState({ ...state, pending: null });
+ return { installed: false };
+ }
+ if (state.ignoredVersions?.includes(pending.latestVersion)) {
+ writeUpdateState({ ...state, pending: null });
+ return { installed: false };
+ }
+ const installSpec = `${pending.packageName}@${pending.latestVersion}`;
+ const installCommand = `npm install -g ${installSpec}`;
+ const choice = await promptUpdateChoice({
+ currentVersion: packageInfo2.version,
+ latestVersion: pending.latestVersion,
+ installCommand
+ });
+ if (choice === "install") {
+ const ok = await runNpmInstallGlobal(installSpec);
+ if (ok) {
+ writeUpdateState({ ...state, pending: null });
+ process.stdout.write(`${UPDATE_SUCCESS_MESSAGE}
+
+`);
+ }
+ return { installed: ok };
+ }
+ if (choice === "ignore-version") {
+ const ignoredVersions = Array.from(/* @__PURE__ */ new Set([...state.ignoredVersions ?? [], pending.latestVersion]));
+ writeUpdateState({ ...state, pending: null, ignoredVersions });
+ return { installed: false };
+ }
+ writeUpdateState({ ...state, pending: null });
+ return { installed: false };
+}
+__name(promptForPendingUpdate, "promptForPendingUpdate");
+async function checkForNpmUpdate(packageInfo2) {
+ if (!packageInfo2.name || !packageInfo2.version) {
+ return;
+ }
+ try {
+ const latestVersion = await fetchLatestNpmVersion(packageInfo2.name);
+ if (!latestVersion || compareVersions(latestVersion, packageInfo2.version) <= 0) {
+ clearPendingUpdate();
+ return;
+ }
+ const state = readUpdateState();
+ if (state.ignoredVersions?.includes(latestVersion)) {
+ clearPendingUpdate(state);
+ return;
+ }
+ writeUpdateState({
+ ...state,
+ pending: {
+ currentVersion: packageInfo2.version,
+ latestVersion,
+ packageName: packageInfo2.name,
+ checkedAt: (/* @__PURE__ */ new Date()).toISOString()
+ }
+ });
+ } catch {
+ }
+}
+__name(checkForNpmUpdate, "checkForNpmUpdate");
+function compareVersions(a, b) {
+ const left2 = parseVersion(a);
+ const right2 = parseVersion(b);
+ const width = Math.max(left2.length, right2.length);
+ for (let index = 0; index < width; index += 1) {
+ const leftPart = left2[index] ?? 0;
+ const rightPart = right2[index] ?? 0;
+ if (leftPart > rightPart) {
+ return 1;
+ }
+ if (leftPart < rightPart) {
+ return -1;
+ }
+ }
+ return 0;
+}
+__name(compareVersions, "compareVersions");
+function getUpdateStatePath() {
+ return path22.join(os15.homedir(), ".deepcode", UPDATE_STATE_FILE);
+}
+__name(getUpdateStatePath, "getUpdateStatePath");
+async function promptUpdateChoice({
+ currentVersion,
+ latestVersion,
+ installCommand
+}) {
+ return new Promise((resolve16) => {
+ let selected = false;
+ let instance = null;
+ const handleSelect = /* @__PURE__ */ __name((choice) => {
+ if (selected) {
+ return;
+ }
+ selected = true;
+ resolve16(choice);
+ instance?.unmount();
+ }, "handleSelect");
+ instance = render_default(
+ import_react59.default.createElement(UpdatePrompt, {
+ currentVersion,
+ latestVersion,
+ installCommand,
+ onSelect: handleSelect
+ }),
+ { exitOnCtrlC: false }
+ );
+ });
+}
+__name(promptUpdateChoice, "promptUpdateChoice");
+async function runNpmInstallGlobal(installSpec) {
+ return new Promise((resolve16) => {
+ const child = spawnNpm(["install", "-g", installSpec], {
+ stdio: "inherit"
+ });
+ child.on("error", (error51) => {
+ process.stderr.write(`Failed to start npm install: ${error51.message}
+`);
+ resolve16(false);
+ });
+ child.on("close", (code) => {
+ if (code === 0) {
+ resolve16(true);
+ return;
+ }
+ process.stderr.write(`npm install exited with code ${code ?? "unknown"}.
+`);
+ resolve16(false);
+ });
+ });
+}
+__name(runNpmInstallGlobal, "runNpmInstallGlobal");
+async function fetchLatestNpmVersion(packageName) {
+ const mirrorResult = await runNpmViewLatestVersion(packageName, TENCENT_MIRROR_REGISTRY, NPM_VIEW_TIMEOUT_MS);
+ if (mirrorResult.ok) {
+ return parseNpmViewVersion(mirrorResult.stdout);
+ }
+ const result = await runNpmViewLatestVersion(packageName, void 0, NPM_VIEW_TIMEOUT_MS);
+ if (!result.ok) {
+ return null;
+ }
+ return parseNpmViewVersion(result.stdout);
+}
+__name(fetchLatestNpmVersion, "fetchLatestNpmVersion");
+function runNpmViewLatestVersion(packageName, registry2, timeoutMs) {
+ return new Promise((resolve16) => {
+ const args = ["view", packageName, "dist-tags.latest", "--json"];
+ if (registry2) {
+ args.push("--registry", registry2);
+ }
+ const child = spawnNpm(args, {
+ stdio: ["ignore", "pipe", "pipe"]
+ });
+ let stdout = "";
+ let settled = false;
+ const finish = /* @__PURE__ */ __name((result) => {
+ if (settled) {
+ return;
+ }
+ settled = true;
+ clearTimeout(timer);
+ resolve16(result);
+ }, "finish");
+ const timer = setTimeout(() => {
+ if (typeof child.pid === "number") {
+ killProcessTree(child.pid, "SIGTERM", { killGroupOnNonWindows: false });
+ } else {
+ child.kill();
+ }
+ finish({ ok: false });
+ }, timeoutMs);
+ child.stdout?.on("data", (chunk) => {
+ if (stdout.length >= MAX_NPM_VIEW_OUTPUT_CHARS) {
+ return;
+ }
+ const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
+ stdout += text.slice(0, MAX_NPM_VIEW_OUTPUT_CHARS - stdout.length);
+ });
+ child.on("error", () => finish({ ok: false }));
+ child.on("close", (code) => {
+ finish(code === 0 ? { ok: true, stdout } : { ok: false });
+ });
+ });
+}
+__name(runNpmViewLatestVersion, "runNpmViewLatestVersion");
+function spawnNpm(args, options2) {
+ if (process.platform === "win32") {
+ return spawn6(["npm", ...args.map(quoteCmdArg)].join(" "), [], {
+ ...options2,
+ shell: true
+ });
+ }
+ return spawn6("npm", args, {
+ ...options2,
+ shell: false
+ });
+}
+__name(spawnNpm, "spawnNpm");
+function quoteCmdArg(arg) {
+ return `"${String(arg).replace(/"/g, '\\"')}"`;
+}
+__name(quoteCmdArg, "quoteCmdArg");
+function parseNpmViewVersion(output) {
+ const trimmed = output.trim();
+ if (!trimmed) {
+ return null;
+ }
+ try {
+ const parsed = JSON.parse(trimmed);
+ return typeof parsed === "string" && parsed.trim() ? parsed.trim() : null;
+ } catch {
+ return trimmed.split(/\r?\n/)[0]?.trim() || null;
+ }
+}
+__name(parseNpmViewVersion, "parseNpmViewVersion");
+function readUpdateState() {
+ const statePath = getUpdateStatePath();
+ if (!fs21.existsSync(statePath)) {
+ return {};
+ }
+ try {
+ const parsed = JSON.parse(fs21.readFileSync(statePath, "utf8"));
+ return {
+ pending: parsed.pending ?? null,
+ ignoredVersions: Array.isArray(parsed.ignoredVersions) ? parsed.ignoredVersions.filter(
+ (value) => typeof value === "string" && value.trim().length > 0
+ ) : []
+ };
+ } catch {
+ return {};
+ }
+}
+__name(readUpdateState, "readUpdateState");
+function writeUpdateState(state) {
+ const statePath = getUpdateStatePath();
+ fs21.mkdirSync(path22.dirname(statePath), { recursive: true });
+ fs21.writeFileSync(statePath, `${JSON.stringify(state, null, 2)}
+`, "utf8");
+}
+__name(writeUpdateState, "writeUpdateState");
+function clearPendingUpdate(state = readUpdateState()) {
+ if (!state.pending) {
+ return;
+ }
+ writeUpdateState({ ...state, pending: null });
+}
+__name(clearPendingUpdate, "clearPendingUpdate");
+function parseVersion(value) {
+ return value.split("-", 1)[0].split(".").map((part) => Number.parseInt(part, 10)).map((part) => Number.isFinite(part) ? part : 0);
+}
+__name(parseVersion, "parseVersion");
+
+// packages/cli/src/cli-args.ts
+init_esbuild_shims();
+
+// node_modules/yargs/index.mjs
+init_esbuild_shims();
+
+// node_modules/yargs/lib/platform-shims/esm.mjs
+init_esbuild_shims();
+import { notStrictEqual, strictEqual } from "assert";
+
+// node_modules/cliui/index.mjs
+init_esbuild_shims();
+
+// node_modules/cliui/build/lib/index.js
+init_esbuild_shims();
+var align = {
+ right: alignRight,
+ center: alignCenter
+};
+var top = 0;
+var right = 1;
+var bottom = 2;
+var left = 3;
+var UI = class {
+ static {
+ __name(this, "UI");
+ }
+ constructor(opts) {
+ var _a6;
+ this.width = opts.width;
+ this.wrap = (_a6 = opts.wrap) !== null && _a6 !== void 0 ? _a6 : true;
+ this.rows = [];
+ }
+ span(...args) {
+ const cols = this.div(...args);
+ cols.span = true;
+ }
+ resetOutput() {
+ this.rows = [];
+ }
+ div(...args) {
+ if (args.length === 0) {
+ this.div("");
+ }
+ if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === "string") {
+ return this.applyLayoutDSL(args[0]);
+ }
+ const cols = args.map((arg) => {
+ if (typeof arg === "string") {
+ return this.colFromString(arg);
+ }
+ return arg;
+ });
+ this.rows.push(cols);
+ return cols;
+ }
+ shouldApplyLayoutDSL(...args) {
+ return args.length === 1 && typeof args[0] === "string" && /[\t\n]/.test(args[0]);
+ }
+ applyLayoutDSL(str3) {
+ const rows = str3.split("\n").map((row) => row.split(" "));
+ let leftColumnWidth = 0;
+ rows.forEach((columns) => {
+ if (columns.length > 1 && mixin.stringWidth(columns[0]) > leftColumnWidth) {
+ leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin.stringWidth(columns[0]));
+ }
+ });
+ rows.forEach((columns) => {
+ this.div(...columns.map((r, i) => {
+ return {
+ text: r.trim(),
+ padding: this.measurePadding(r),
+ width: i === 0 && columns.length > 1 ? leftColumnWidth : void 0
+ };
+ }));
+ });
+ return this.rows[this.rows.length - 1];
+ }
+ colFromString(text) {
+ return {
+ text,
+ padding: this.measurePadding(text)
+ };
+ }
+ measurePadding(str3) {
+ const noAnsi = mixin.stripAnsi(str3);
+ return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length];
+ }
+ toString() {
+ const lines = [];
+ this.rows.forEach((row) => {
+ this.rowToString(row, lines);
+ });
+ return lines.filter((line) => !line.hidden).map((line) => line.text).join("\n");
+ }
+ rowToString(row, lines) {
+ this.rasterize(row).forEach((rrow, r) => {
+ let str3 = "";
+ rrow.forEach((col, c) => {
+ const { width } = row[c];
+ const wrapWidth = this.negatePadding(row[c]);
+ let ts = col;
+ if (wrapWidth > mixin.stringWidth(col)) {
+ ts += " ".repeat(wrapWidth - mixin.stringWidth(col));
+ }
+ if (row[c].align && row[c].align !== "left" && this.wrap) {
+ const fn = align[row[c].align];
+ ts = fn(ts, wrapWidth);
+ if (mixin.stringWidth(ts) < wrapWidth) {
+ ts += " ".repeat((width || 0) - mixin.stringWidth(ts) - 1);
+ }
+ }
+ const padding = row[c].padding || [0, 0, 0, 0];
+ if (padding[left]) {
+ str3 += " ".repeat(padding[left]);
+ }
+ str3 += addBorder(row[c], ts, "| ");
+ str3 += ts;
+ str3 += addBorder(row[c], ts, " |");
+ if (padding[right]) {
+ str3 += " ".repeat(padding[right]);
+ }
+ if (r === 0 && lines.length > 0) {
+ str3 = this.renderInline(str3, lines[lines.length - 1]);
+ }
+ });
+ lines.push({
+ text: str3.replace(/ +$/, ""),
+ span: row.span
+ });
+ });
+ return lines;
+ }
+ // if the full 'source' can render in
+ // the target line, do so.
+ renderInline(source, previousLine) {
+ const match = source.match(/^ */);
+ const leadingWhitespace = match ? match[0].length : 0;
+ const target = previousLine.text;
+ const targetTextWidth = mixin.stringWidth(target.trimRight());
+ if (!previousLine.span) {
+ return source;
+ }
+ if (!this.wrap) {
+ previousLine.hidden = true;
+ return target + source;
+ }
+ if (leadingWhitespace < targetTextWidth) {
+ return source;
+ }
+ previousLine.hidden = true;
+ return target.trimRight() + " ".repeat(leadingWhitespace - targetTextWidth) + source.trimLeft();
+ }
+ rasterize(row) {
+ const rrows = [];
+ const widths = this.columnWidths(row);
+ let wrapped;
+ row.forEach((col, c) => {
+ col.width = widths[c];
+ if (this.wrap) {
+ wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split("\n");
+ } else {
+ wrapped = col.text.split("\n");
+ }
+ if (col.border) {
+ wrapped.unshift("." + "-".repeat(this.negatePadding(col) + 2) + ".");
+ wrapped.push("'" + "-".repeat(this.negatePadding(col) + 2) + "'");
+ }
+ if (col.padding) {
+ wrapped.unshift(...new Array(col.padding[top] || 0).fill(""));
+ wrapped.push(...new Array(col.padding[bottom] || 0).fill(""));
+ }
+ wrapped.forEach((str3, r) => {
+ if (!rrows[r]) {
+ rrows.push([]);
+ }
+ const rrow = rrows[r];
+ for (let i = 0; i < c; i++) {
+ if (rrow[i] === void 0) {
+ rrow.push("");
+ }
+ }
+ rrow.push(str3);
+ });
+ });
+ return rrows;
+ }
+ negatePadding(col) {
+ let wrapWidth = col.width || 0;
+ if (col.padding) {
+ wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0);
+ }
+ if (col.border) {
+ wrapWidth -= 4;
+ }
+ return wrapWidth;
+ }
+ columnWidths(row) {
+ if (!this.wrap) {
+ return row.map((col) => {
+ return col.width || mixin.stringWidth(col.text);
+ });
+ }
+ let unset = row.length;
+ let remainingWidth = this.width;
+ const widths = row.map((col) => {
+ if (col.width) {
+ unset--;
+ remainingWidth -= col.width;
+ return col.width;
+ }
+ return void 0;
+ });
+ const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0;
+ return widths.map((w, i) => {
+ if (w === void 0) {
+ return Math.max(unsetWidth, _minWidth(row[i]));
+ }
+ return w;
+ });
+ }
+};
+function addBorder(col, ts, style) {
+ if (col.border) {
+ if (/[.']-+[.']/.test(ts)) {
+ return "";
+ }
+ if (ts.trim().length !== 0) {
+ return style;
+ }
+ return " ";
+ }
+ return "";
+}
+__name(addBorder, "addBorder");
+function _minWidth(col) {
+ const padding = col.padding || [];
+ const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0);
+ if (col.border) {
+ return minWidth + 4;
+ }
+ return minWidth;
+}
+__name(_minWidth, "_minWidth");
+function getWindowWidth() {
+ if (typeof process === "object" && process.stdout && process.stdout.columns) {
+ return process.stdout.columns;
+ }
+ return 80;
+}
+__name(getWindowWidth, "getWindowWidth");
+function alignRight(str3, width) {
+ str3 = str3.trim();
+ const strWidth = mixin.stringWidth(str3);
+ if (strWidth < width) {
+ return " ".repeat(width - strWidth) + str3;
+ }
+ return str3;
+}
+__name(alignRight, "alignRight");
+function alignCenter(str3, width) {
+ str3 = str3.trim();
+ const strWidth = mixin.stringWidth(str3);
+ if (strWidth >= width) {
+ return str3;
+ }
+ return " ".repeat(width - strWidth >> 1) + str3;
+}
+__name(alignCenter, "alignCenter");
+var mixin;
+function cliui(opts, _mixin) {
+ mixin = _mixin;
+ return new UI({
+ width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(),
+ wrap: opts === null || opts === void 0 ? void 0 : opts.wrap
+ });
+}
+__name(cliui, "cliui");
+
+// node_modules/cliui/node_modules/string-width/index.js
+init_esbuild_shims();
+var import_emoji_regex = __toESM(require_emoji_regex(), 1);
+var segmenter4 = new Intl.Segmenter();
+var defaultIgnorableCodePointRegex = new RegExp("^\\p{Default_Ignorable_Code_Point}$", "u");
+function stringWidth2(string4, options2 = {}) {
+ if (typeof string4 !== "string" || string4.length === 0) {
+ return 0;
+ }
+ const {
+ ambiguousIsNarrow = true,
+ countAnsiEscapeCodes = false
+ } = options2;
+ if (!countAnsiEscapeCodes) {
+ string4 = stripAnsi(string4);
+ }
+ if (string4.length === 0) {
+ return 0;
+ }
+ let width = 0;
+ const eastAsianWidthOptions = { ambiguousAsWide: !ambiguousIsNarrow };
+ for (const { segment: character } of segmenter4.segment(string4)) {
+ const codePoint = character.codePointAt(0);
+ if (codePoint <= 31 || codePoint >= 127 && codePoint <= 159) {
+ continue;
+ }
+ if (codePoint >= 8203 && codePoint <= 8207 || codePoint === 65279) {
+ continue;
+ }
+ if (codePoint >= 768 && codePoint <= 879 || codePoint >= 6832 && codePoint <= 6911 || codePoint >= 7616 && codePoint <= 7679 || codePoint >= 8400 && codePoint <= 8447 || codePoint >= 65056 && codePoint <= 65071) {
+ continue;
+ }
+ if (codePoint >= 55296 && codePoint <= 57343) {
+ continue;
+ }
+ if (codePoint >= 65024 && codePoint <= 65039) {
+ continue;
+ }
+ if (defaultIgnorableCodePointRegex.test(character)) {
+ continue;
+ }
+ if ((0, import_emoji_regex.default)().test(character)) {
+ width += 2;
+ continue;
+ }
+ width += eastAsianWidth(codePoint, eastAsianWidthOptions);
+ }
+ return width;
+}
+__name(stringWidth2, "stringWidth");
+
+// node_modules/cliui/node_modules/wrap-ansi/index.js
+init_esbuild_shims();
+
+// node_modules/cliui/node_modules/ansi-styles/index.js
+init_esbuild_shims();
+var ANSI_BACKGROUND_OFFSET7 = 10;
+var wrapAnsi167 = /* @__PURE__ */ __name((offset = 0) => (code) => `\x1B[${code + offset}m`, "wrapAnsi16");
+var wrapAnsi2567 = /* @__PURE__ */ __name((offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`, "wrapAnsi256");
+var wrapAnsi16m7 = /* @__PURE__ */ __name((offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`, "wrapAnsi16m");
+var styles11 = {
+ 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],
+ overline: [53, 55],
+ 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],
+ gray: [90, 39],
+ // Alias of `blackBright`
+ grey: [90, 39],
+ // Alias of `blackBright`
+ 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],
+ bgGray: [100, 49],
+ // Alias of `bgBlackBright`
+ bgGrey: [100, 49],
+ // Alias of `bgBlackBright`
+ bgRedBright: [101, 49],
+ bgGreenBright: [102, 49],
+ bgYellowBright: [103, 49],
+ bgBlueBright: [104, 49],
+ bgMagentaBright: [105, 49],
+ bgCyanBright: [106, 49],
+ bgWhiteBright: [107, 49]
+ }
+};
+var modifierNames7 = Object.keys(styles11.modifier);
+var foregroundColorNames7 = Object.keys(styles11.color);
+var backgroundColorNames7 = Object.keys(styles11.bgColor);
+var colorNames7 = [...foregroundColorNames7, ...backgroundColorNames7];
+function assembleStyles7() {
+ const codes = /* @__PURE__ */ new Map();
+ for (const [groupName, group] of Object.entries(styles11)) {
+ for (const [styleName, style] of Object.entries(group)) {
+ styles11[styleName] = {
+ open: `\x1B[${style[0]}m`,
+ close: `\x1B[${style[1]}m`
+ };
+ group[styleName] = styles11[styleName];
+ codes.set(style[0], style[1]);
+ }
+ Object.defineProperty(styles11, groupName, {
+ value: group,
+ enumerable: false
+ });
+ }
+ Object.defineProperty(styles11, "codes", {
+ value: codes,
+ enumerable: false
+ });
+ styles11.color.close = "\x1B[39m";
+ styles11.bgColor.close = "\x1B[49m";
+ styles11.color.ansi = wrapAnsi167();
+ styles11.color.ansi256 = wrapAnsi2567();
+ styles11.color.ansi16m = wrapAnsi16m7();
+ styles11.bgColor.ansi = wrapAnsi167(ANSI_BACKGROUND_OFFSET7);
+ styles11.bgColor.ansi256 = wrapAnsi2567(ANSI_BACKGROUND_OFFSET7);
+ styles11.bgColor.ansi16m = wrapAnsi16m7(ANSI_BACKGROUND_OFFSET7);
+ Object.defineProperties(styles11, {
+ rgbToAnsi256: {
+ value(red, green, blue) {
+ if (red === green && green === blue) {
+ if (red < 8) {
+ return 16;
+ }
+ if (red > 248) {
+ return 231;
+ }
+ return Math.round((red - 8) / 247 * 24) + 232;
+ }
+ return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
+ },
+ enumerable: false
+ },
+ hexToRgb: {
+ value(hex3) {
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex3.toString(16));
+ if (!matches) {
+ return [0, 0, 0];
+ }
+ let [colorString] = matches;
+ if (colorString.length === 3) {
+ colorString = [...colorString].map((character) => character + character).join("");
+ }
+ const integer2 = Number.parseInt(colorString, 16);
+ return [
+ /* eslint-disable no-bitwise */
+ integer2 >> 16 & 255,
+ integer2 >> 8 & 255,
+ integer2 & 255
+ /* eslint-enable no-bitwise */
+ ];
+ },
+ enumerable: false
+ },
+ hexToAnsi256: {
+ value: /* @__PURE__ */ __name((hex3) => styles11.rgbToAnsi256(...styles11.hexToRgb(hex3)), "value"),
+ enumerable: false
+ },
+ ansi256ToAnsi: {
+ value(code) {
+ if (code < 8) {
+ return 30 + code;
+ }
+ if (code < 16) {
+ return 90 + (code - 8);
+ }
+ let red;
+ let green;
+ let blue;
+ if (code >= 232) {
+ red = ((code - 232) * 10 + 8) / 255;
+ green = red;
+ blue = red;
+ } else {
+ code -= 16;
+ const remainder = code % 36;
+ red = Math.floor(code / 36) / 5;
+ green = Math.floor(remainder / 6) / 5;
+ blue = remainder % 6 / 5;
+ }
+ const value = Math.max(red, green, blue) * 2;
+ if (value === 0) {
+ return 30;
+ }
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
+ if (value === 2) {
+ result += 60;
+ }
+ return result;
+ },
+ enumerable: false
+ },
+ rgbToAnsi: {
+ value: /* @__PURE__ */ __name((red, green, blue) => styles11.ansi256ToAnsi(styles11.rgbToAnsi256(red, green, blue)), "value"),
+ enumerable: false
+ },
+ hexToAnsi: {
+ value: /* @__PURE__ */ __name((hex3) => styles11.ansi256ToAnsi(styles11.hexToAnsi256(hex3)), "value"),
+ enumerable: false
+ }
+ });
+ return styles11;
+}
+__name(assembleStyles7, "assembleStyles");
+var ansiStyles7 = assembleStyles7();
+var ansi_styles_default7 = ansiStyles7;
+
+// node_modules/cliui/node_modules/wrap-ansi/index.js
+var ESCAPES4 = /* @__PURE__ */ new Set([
+ "\x1B",
+ "\x9B"
+]);
+var END_CODE = 39;
+var ANSI_ESCAPE_BELL2 = "\x07";
+var ANSI_CSI3 = "[";
+var ANSI_OSC3 = "]";
+var ANSI_SGR_TERMINATOR3 = "m";
+var ANSI_ESCAPE_LINK2 = `${ANSI_OSC3}8;;`;
+var wrapAnsiCode2 = /* @__PURE__ */ __name((code) => `${ESCAPES4.values().next().value}${ANSI_CSI3}${code}${ANSI_SGR_TERMINATOR3}`, "wrapAnsiCode");
+var wrapAnsiHyperlink2 = /* @__PURE__ */ __name((url2) => `${ESCAPES4.values().next().value}${ANSI_ESCAPE_LINK2}${url2}${ANSI_ESCAPE_BELL2}`, "wrapAnsiHyperlink");
+var wordLengths2 = /* @__PURE__ */ __name((string4) => string4.split(" ").map((character) => stringWidth2(character)), "wordLengths");
+var wrapWord2 = /* @__PURE__ */ __name((rows, word, columns) => {
+ const characters = [...word];
+ let isInsideEscape = false;
+ let isInsideLinkEscape = false;
+ let visible = stringWidth2(stripAnsi(rows.at(-1)));
+ for (const [index, character] of characters.entries()) {
+ const characterLength = stringWidth2(character);
+ if (visible + characterLength <= columns) {
+ rows[rows.length - 1] += character;
+ } else {
+ rows.push(character);
+ visible = 0;
+ }
+ if (ESCAPES4.has(character)) {
+ isInsideEscape = true;
+ const ansiEscapeLinkCandidate = characters.slice(index + 1, index + 1 + ANSI_ESCAPE_LINK2.length).join("");
+ isInsideLinkEscape = ansiEscapeLinkCandidate === ANSI_ESCAPE_LINK2;
+ }
+ if (isInsideEscape) {
+ if (isInsideLinkEscape) {
+ if (character === ANSI_ESCAPE_BELL2) {
+ isInsideEscape = false;
+ isInsideLinkEscape = false;
+ }
+ } else if (character === ANSI_SGR_TERMINATOR3) {
+ isInsideEscape = false;
+ }
+ continue;
+ }
+ visible += characterLength;
+ if (visible === columns && index < characters.length - 1) {
+ rows.push("");
+ visible = 0;
+ }
+ }
+ if (!visible && rows.at(-1).length > 0 && rows.length > 1) {
+ rows[rows.length - 2] += rows.pop();
+ }
+}, "wrapWord");
+var stringVisibleTrimSpacesRight2 = /* @__PURE__ */ __name((string4) => {
+ const words = string4.split(" ");
+ let last = words.length;
+ while (last > 0) {
+ if (stringWidth2(words[last - 1]) > 0) {
+ break;
+ }
+ last--;
+ }
+ if (last === words.length) {
+ return string4;
+ }
+ return words.slice(0, last).join(" ") + words.slice(last).join("");
+}, "stringVisibleTrimSpacesRight");
+var exec3 = /* @__PURE__ */ __name((string4, columns, options2 = {}) => {
+ if (options2.trim !== false && string4.trim() === "") {
+ return "";
+ }
+ let returnValue = "";
+ let escapeCode;
+ let escapeUrl;
+ const lengths = wordLengths2(string4);
+ let rows = [""];
+ for (const [index, word] of string4.split(" ").entries()) {
+ if (options2.trim !== false) {
+ rows[rows.length - 1] = rows.at(-1).trimStart();
+ }
+ let rowLength = stringWidth2(rows.at(-1));
+ if (index !== 0) {
+ if (rowLength >= columns && (options2.wordWrap === false || options2.trim === false)) {
+ rows.push("");
+ rowLength = 0;
+ }
+ if (rowLength > 0 || options2.trim === false) {
+ rows[rows.length - 1] += " ";
+ rowLength++;
+ }
+ }
+ if (options2.hard && lengths[index] > columns) {
+ const remainingColumns = columns - rowLength;
+ const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns);
+ const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns);
+ if (breaksStartingNextLine < breaksStartingThisLine) {
+ rows.push("");
+ }
+ wrapWord2(rows, word, columns);
+ continue;
+ }
+ if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) {
+ if (options2.wordWrap === false && rowLength < columns) {
+ wrapWord2(rows, word, columns);
+ continue;
+ }
+ rows.push("");
+ }
+ if (rowLength + lengths[index] > columns && options2.wordWrap === false) {
+ wrapWord2(rows, word, columns);
+ continue;
+ }
+ rows[rows.length - 1] += word;
+ }
+ if (options2.trim !== false) {
+ rows = rows.map((row) => stringVisibleTrimSpacesRight2(row));
+ }
+ const preString = rows.join("\n");
+ const pre = [...preString];
+ let preStringIndex = 0;
+ for (const [index, character] of pre.entries()) {
+ returnValue += character;
+ if (ESCAPES4.has(character)) {
+ const { groups } = new RegExp(`(?:\\${ANSI_CSI3}(?\\d+)m|\\${ANSI_ESCAPE_LINK2}(?.*)${ANSI_ESCAPE_BELL2})`).exec(preString.slice(preStringIndex)) || { groups: {} };
+ if (groups.code !== void 0) {
+ const code2 = Number.parseFloat(groups.code);
+ escapeCode = code2 === END_CODE ? void 0 : code2;
+ } else if (groups.uri !== void 0) {
+ escapeUrl = groups.uri.length === 0 ? void 0 : groups.uri;
+ }
+ }
+ const code = ansi_styles_default7.codes.get(Number(escapeCode));
+ if (pre[index + 1] === "\n") {
+ if (escapeUrl) {
+ returnValue += wrapAnsiHyperlink2("");
+ }
+ if (escapeCode && code) {
+ returnValue += wrapAnsiCode2(code);
+ }
+ } else if (character === "\n") {
+ if (escapeCode && code) {
+ returnValue += wrapAnsiCode2(escapeCode);
+ }
+ if (escapeUrl) {
+ returnValue += wrapAnsiHyperlink2(escapeUrl);
+ }
+ }
+ preStringIndex += character.length;
+ }
+ return returnValue;
+}, "exec");
+function wrapAnsi2(string4, columns, options2) {
+ return String(string4).normalize().replaceAll("\r\n", "\n").split("\n").map((line) => exec3(line, columns, options2)).join("\n");
+}
+__name(wrapAnsi2, "wrapAnsi");
+
+// node_modules/cliui/index.mjs
+function ui(opts) {
+ return cliui(opts, {
+ stringWidth: stringWidth2,
+ stripAnsi,
+ wrap: wrapAnsi2
+ });
+}
+__name(ui, "ui");
+
+// node_modules/escalade/sync/index.mjs
+init_esbuild_shims();
+import { dirname as dirname11, resolve as resolve12 } from "path";
+import { readdirSync as readdirSync5, statSync as statSync9 } from "fs";
+function sync_default(start, callback) {
+ let dir = resolve12(".", start);
+ let tmp, stats = statSync9(dir);
+ if (!stats.isDirectory()) {
+ dir = dirname11(dir);
+ }
+ while (true) {
+ tmp = callback(dir, readdirSync5(dir));
+ if (tmp) return resolve12(dir, tmp);
+ dir = dirname11(tmp = dir);
+ if (tmp === dir) break;
+ }
+}
+__name(sync_default, "default");
+
+// node_modules/yargs/lib/platform-shims/esm.mjs
+import { inspect } from "util";
+import { fileURLToPath as fileURLToPath2 } from "url";
+
+// node_modules/yargs-parser/build/lib/index.js
+init_esbuild_shims();
+import { format } from "util";
+import { normalize as normalize4, resolve as resolve13 } from "path";
+
+// node_modules/yargs-parser/build/lib/string-utils.js
+init_esbuild_shims();
+function camelCase(str3) {
+ const isCamelCase = str3 !== str3.toLowerCase() && str3 !== str3.toUpperCase();
+ if (!isCamelCase) {
+ str3 = str3.toLowerCase();
+ }
+ if (str3.indexOf("-") === -1 && str3.indexOf("_") === -1) {
+ return str3;
+ } else {
+ let camelcase = "";
+ let nextChrUpper = false;
+ const leadingHyphens = str3.match(/^-+/);
+ for (let i = leadingHyphens ? leadingHyphens[0].length : 0; i < str3.length; i++) {
+ let chr = str3.charAt(i);
+ if (nextChrUpper) {
+ nextChrUpper = false;
+ chr = chr.toUpperCase();
+ }
+ if (i !== 0 && (chr === "-" || chr === "_")) {
+ nextChrUpper = true;
+ } else if (chr !== "-" && chr !== "_") {
+ camelcase += chr;
+ }
+ }
+ return camelcase;
+ }
+}
+__name(camelCase, "camelCase");
+function decamelize(str3, joinString) {
+ const lowercase2 = str3.toLowerCase();
+ joinString = joinString || "-";
+ let notCamelcase = "";
+ for (let i = 0; i < str3.length; i++) {
+ const chrLower = lowercase2.charAt(i);
+ const chrString = str3.charAt(i);
+ if (chrLower !== chrString && i > 0) {
+ notCamelcase += `${joinString}${lowercase2.charAt(i)}`;
+ } else {
+ notCamelcase += chrString;
+ }
+ }
+ return notCamelcase;
+}
+__name(decamelize, "decamelize");
+function looksLikeNumber(x) {
+ if (x === null || x === void 0)
+ return false;
+ if (typeof x === "number")
+ return true;
+ if (/^0x[0-9a-f]+$/i.test(x))
+ return true;
+ if (/^0[^.]/.test(x))
+ return false;
+ return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
+}
+__name(looksLikeNumber, "looksLikeNumber");
+
+// node_modules/yargs-parser/build/lib/yargs-parser.js
+init_esbuild_shims();
+
+// node_modules/yargs-parser/build/lib/tokenize-arg-string.js
+init_esbuild_shims();
+function tokenizeArgString(argString) {
+ if (Array.isArray(argString)) {
+ return argString.map((e) => typeof e !== "string" ? e + "" : e);
+ }
+ argString = argString.trim();
+ let i = 0;
+ let prevC = null;
+ let c = null;
+ let opening = null;
+ const args = [];
+ for (let ii = 0; ii < argString.length; ii++) {
+ prevC = c;
+ c = argString.charAt(ii);
+ if (c === " " && !opening) {
+ if (!(prevC === " ")) {
+ i++;
+ }
+ continue;
+ }
+ if (c === opening) {
+ opening = null;
+ } else if ((c === "'" || c === '"') && !opening) {
+ opening = c;
+ }
+ if (!args[i])
+ args[i] = "";
+ args[i] += c;
+ }
+ return args;
+}
+__name(tokenizeArgString, "tokenizeArgString");
+
+// node_modules/yargs-parser/build/lib/yargs-parser-types.js
+init_esbuild_shims();
+var DefaultValuesForTypeKey;
+(function(DefaultValuesForTypeKey2) {
+ DefaultValuesForTypeKey2["BOOLEAN"] = "boolean";
+ DefaultValuesForTypeKey2["STRING"] = "string";
+ DefaultValuesForTypeKey2["NUMBER"] = "number";
+ DefaultValuesForTypeKey2["ARRAY"] = "array";
+})(DefaultValuesForTypeKey || (DefaultValuesForTypeKey = {}));
+
+// node_modules/yargs-parser/build/lib/yargs-parser.js
+var mixin2;
+var YargsParser = class {
+ static {
+ __name(this, "YargsParser");
+ }
+ constructor(_mixin) {
+ mixin2 = _mixin;
+ }
+ parse(argsInput, options2) {
+ const opts = Object.assign({
+ alias: void 0,
+ array: void 0,
+ boolean: void 0,
+ config: void 0,
+ configObjects: void 0,
+ configuration: void 0,
+ coerce: void 0,
+ count: void 0,
+ default: void 0,
+ envPrefix: void 0,
+ narg: void 0,
+ normalize: void 0,
+ string: void 0,
+ number: void 0,
+ __: void 0,
+ key: void 0
+ }, options2);
+ const args = tokenizeArgString(argsInput);
+ const inputIsString = typeof argsInput === "string";
+ const aliases2 = combineAliases(Object.assign(/* @__PURE__ */ Object.create(null), opts.alias));
+ const configuration = Object.assign({
+ "boolean-negation": true,
+ "camel-case-expansion": true,
+ "combine-arrays": false,
+ "dot-notation": true,
+ "duplicate-arguments-array": true,
+ "flatten-duplicate-arrays": true,
+ "greedy-arrays": true,
+ "halt-at-non-option": false,
+ "nargs-eats-options": false,
+ "negation-prefix": "no-",
+ "parse-numbers": true,
+ "parse-positional-numbers": true,
+ "populate--": false,
+ "set-placeholder-key": false,
+ "short-option-groups": true,
+ "strip-aliased": false,
+ "strip-dashed": false,
+ "unknown-options-as-args": false
+ }, opts.configuration);
+ const defaults2 = Object.assign(/* @__PURE__ */ Object.create(null), opts.default);
+ const configObjects = opts.configObjects || [];
+ const envPrefix = opts.envPrefix;
+ const notFlagsOption = configuration["populate--"];
+ const notFlagsArgv = notFlagsOption ? "--" : "_";
+ const newAliases = /* @__PURE__ */ Object.create(null);
+ const defaulted = /* @__PURE__ */ Object.create(null);
+ const __ = opts.__ || mixin2.format;
+ const flags = {
+ aliases: /* @__PURE__ */ Object.create(null),
+ arrays: /* @__PURE__ */ Object.create(null),
+ bools: /* @__PURE__ */ Object.create(null),
+ strings: /* @__PURE__ */ Object.create(null),
+ numbers: /* @__PURE__ */ Object.create(null),
+ counts: /* @__PURE__ */ Object.create(null),
+ normalize: /* @__PURE__ */ Object.create(null),
+ configs: /* @__PURE__ */ Object.create(null),
+ nargs: /* @__PURE__ */ Object.create(null),
+ coercions: /* @__PURE__ */ Object.create(null),
+ keys: []
+ };
+ const negative = /^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/;
+ const negatedBoolean = new RegExp("^--" + configuration["negation-prefix"] + "(.+)");
+ [].concat(opts.array || []).filter(Boolean).forEach(function(opt) {
+ const key = typeof opt === "object" ? opt.key : opt;
+ const assignment = Object.keys(opt).map(function(key2) {
+ const arrayFlagKeys = {
+ boolean: "bools",
+ string: "strings",
+ number: "numbers"
+ };
+ return arrayFlagKeys[key2];
+ }).filter(Boolean).pop();
+ if (assignment) {
+ flags[assignment][key] = true;
+ }
+ flags.arrays[key] = true;
+ flags.keys.push(key);
+ });
+ [].concat(opts.boolean || []).filter(Boolean).forEach(function(key) {
+ flags.bools[key] = true;
+ flags.keys.push(key);
+ });
+ [].concat(opts.string || []).filter(Boolean).forEach(function(key) {
+ flags.strings[key] = true;
+ flags.keys.push(key);
+ });
+ [].concat(opts.number || []).filter(Boolean).forEach(function(key) {
+ flags.numbers[key] = true;
+ flags.keys.push(key);
+ });
+ [].concat(opts.count || []).filter(Boolean).forEach(function(key) {
+ flags.counts[key] = true;
+ flags.keys.push(key);
+ });
+ [].concat(opts.normalize || []).filter(Boolean).forEach(function(key) {
+ flags.normalize[key] = true;
+ flags.keys.push(key);
+ });
+ if (typeof opts.narg === "object") {
+ Object.entries(opts.narg).forEach(([key, value]) => {
+ if (typeof value === "number") {
+ flags.nargs[key] = value;
+ flags.keys.push(key);
+ }
+ });
+ }
+ if (typeof opts.coerce === "object") {
+ Object.entries(opts.coerce).forEach(([key, value]) => {
+ if (typeof value === "function") {
+ flags.coercions[key] = value;
+ flags.keys.push(key);
+ }
+ });
+ }
+ if (typeof opts.config !== "undefined") {
+ if (Array.isArray(opts.config) || typeof opts.config === "string") {
+ ;
+ [].concat(opts.config).filter(Boolean).forEach(function(key) {
+ flags.configs[key] = true;
+ });
+ } else if (typeof opts.config === "object") {
+ Object.entries(opts.config).forEach(([key, value]) => {
+ if (typeof value === "boolean" || typeof value === "function") {
+ flags.configs[key] = value;
+ }
+ });
+ }
+ }
+ extendAliases(opts.key, aliases2, opts.default, flags.arrays);
+ Object.keys(defaults2).forEach(function(key) {
+ (flags.aliases[key] || []).forEach(function(alias) {
+ defaults2[alias] = defaults2[key];
+ });
+ });
+ let error51 = null;
+ checkConfiguration();
+ let notFlags = [];
+ const argv = Object.assign(/* @__PURE__ */ Object.create(null), { _: [] });
+ const argvReturn = {};
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i];
+ const truncatedArg = arg.replace(/^-{3,}/, "---");
+ let broken;
+ let key;
+ let letters;
+ let m;
+ let next;
+ let value;
+ if (arg !== "--" && /^-/.test(arg) && isUnknownOptionAsArg(arg)) {
+ pushPositional(arg);
+ } else if (truncatedArg.match(/^---+(=|$)/)) {
+ pushPositional(arg);
+ continue;
+ } else if (arg.match(/^--.+=/) || !configuration["short-option-groups"] && arg.match(/^-.+=/)) {
+ m = arg.match(/^--?([^=]+)=([\s\S]*)$/);
+ if (m !== null && Array.isArray(m) && m.length >= 3) {
+ if (checkAllAliases(m[1], flags.arrays)) {
+ i = eatArray(i, m[1], args, m[2]);
+ } else if (checkAllAliases(m[1], flags.nargs) !== false) {
+ i = eatNargs(i, m[1], args, m[2]);
+ } else {
+ setArg(m[1], m[2], true);
+ }
+ }
+ } else if (arg.match(negatedBoolean) && configuration["boolean-negation"]) {
+ m = arg.match(negatedBoolean);
+ if (m !== null && Array.isArray(m) && m.length >= 2) {
+ key = m[1];
+ setArg(key, checkAllAliases(key, flags.arrays) ? [false] : false);
+ }
+ } else if (arg.match(/^--.+/) || !configuration["short-option-groups"] && arg.match(/^-[^-]+/)) {
+ m = arg.match(/^--?(.+)/);
+ if (m !== null && Array.isArray(m) && m.length >= 2) {
+ key = m[1];
+ if (checkAllAliases(key, flags.arrays)) {
+ i = eatArray(i, key, args);
+ } else if (checkAllAliases(key, flags.nargs) !== false) {
+ i = eatNargs(i, key, args);
+ } else {
+ next = args[i + 1];
+ if (next !== void 0 && (!next.match(/^-/) || next.match(negative)) && !checkAllAliases(key, flags.bools) && !checkAllAliases(key, flags.counts)) {
+ setArg(key, next);
+ i++;
+ } else if (/^(true|false)$/.test(next)) {
+ setArg(key, next);
+ i++;
+ } else {
+ setArg(key, defaultValue2(key));
+ }
+ }
+ }
+ } else if (arg.match(/^-.\..+=/)) {
+ m = arg.match(/^-([^=]+)=([\s\S]*)$/);
+ if (m !== null && Array.isArray(m) && m.length >= 3) {
+ setArg(m[1], m[2]);
+ }
+ } else if (arg.match(/^-.\..+/) && !arg.match(negative)) {
+ next = args[i + 1];
+ m = arg.match(/^-(.\..+)/);
+ if (m !== null && Array.isArray(m) && m.length >= 2) {
+ key = m[1];
+ if (next !== void 0 && !next.match(/^-/) && !checkAllAliases(key, flags.bools) && !checkAllAliases(key, flags.counts)) {
+ setArg(key, next);
+ i++;
+ } else {
+ setArg(key, defaultValue2(key));
+ }
+ }
+ } else if (arg.match(/^-[^-]+/) && !arg.match(negative)) {
+ letters = arg.slice(1, -1).split("");
+ broken = false;
+ for (let j = 0; j < letters.length; j++) {
+ next = arg.slice(j + 2);
+ if (letters[j + 1] && letters[j + 1] === "=") {
+ value = arg.slice(j + 3);
+ key = letters[j];
+ if (checkAllAliases(key, flags.arrays)) {
+ i = eatArray(i, key, args, value);
+ } else if (checkAllAliases(key, flags.nargs) !== false) {
+ i = eatNargs(i, key, args, value);
+ } else {
+ setArg(key, value);
+ }
+ broken = true;
+ break;
+ }
+ if (next === "-") {
+ setArg(letters[j], next);
+ continue;
+ }
+ if (/[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) && checkAllAliases(next, flags.bools) === false) {
+ setArg(letters[j], next);
+ broken = true;
+ break;
+ }
+ if (letters[j + 1] && letters[j + 1].match(/\W/)) {
+ setArg(letters[j], next);
+ broken = true;
+ break;
+ } else {
+ setArg(letters[j], defaultValue2(letters[j]));
+ }
+ }
+ key = arg.slice(-1)[0];
+ if (!broken && key !== "-") {
+ if (checkAllAliases(key, flags.arrays)) {
+ i = eatArray(i, key, args);
+ } else if (checkAllAliases(key, flags.nargs) !== false) {
+ i = eatNargs(i, key, args);
+ } else {
+ next = args[i + 1];
+ if (next !== void 0 && (!/^(-|--)[^-]/.test(next) || next.match(negative)) && !checkAllAliases(key, flags.bools) && !checkAllAliases(key, flags.counts)) {
+ setArg(key, next);
+ i++;
+ } else if (/^(true|false)$/.test(next)) {
+ setArg(key, next);
+ i++;
+ } else {
+ setArg(key, defaultValue2(key));
+ }
+ }
+ }
+ } else if (arg.match(/^-[0-9]$/) && arg.match(negative) && checkAllAliases(arg.slice(1), flags.bools)) {
+ key = arg.slice(1);
+ setArg(key, defaultValue2(key));
+ } else if (arg === "--") {
+ notFlags = args.slice(i + 1);
+ break;
+ } else if (configuration["halt-at-non-option"]) {
+ notFlags = args.slice(i);
+ break;
+ } else {
+ pushPositional(arg);
+ }
+ }
+ applyEnvVars(argv, true);
+ applyEnvVars(argv, false);
+ setConfig(argv);
+ setConfigObjects();
+ applyDefaultsAndAliases(argv, flags.aliases, defaults2, true);
+ applyCoercions(argv);
+ if (configuration["set-placeholder-key"])
+ setPlaceholderKeys(argv);
+ Object.keys(flags.counts).forEach(function(key) {
+ if (!hasKey(argv, key.split(".")))
+ setArg(key, 0);
+ });
+ if (notFlagsOption && notFlags.length)
+ argv[notFlagsArgv] = [];
+ notFlags.forEach(function(key) {
+ argv[notFlagsArgv].push(key);
+ });
+ if (configuration["camel-case-expansion"] && configuration["strip-dashed"]) {
+ Object.keys(argv).filter((key) => key !== "--" && key.includes("-")).forEach((key) => {
+ delete argv[key];
+ });
+ }
+ if (configuration["strip-aliased"]) {
+ ;
+ [].concat(...Object.keys(aliases2).map((k) => aliases2[k])).forEach((alias) => {
+ if (configuration["camel-case-expansion"] && alias.includes("-")) {
+ delete argv[alias.split(".").map((prop) => camelCase(prop)).join(".")];
+ }
+ delete argv[alias];
+ });
+ }
+ function pushPositional(arg) {
+ const maybeCoercedNumber = maybeCoerceNumber("_", arg);
+ if (typeof maybeCoercedNumber === "string" || typeof maybeCoercedNumber === "number") {
+ argv._.push(maybeCoercedNumber);
+ }
+ }
+ __name(pushPositional, "pushPositional");
+ function eatNargs(i, key, args2, argAfterEqualSign) {
+ let ii;
+ let toEat = checkAllAliases(key, flags.nargs);
+ toEat = typeof toEat !== "number" || isNaN(toEat) ? 1 : toEat;
+ if (toEat === 0) {
+ if (!isUndefined(argAfterEqualSign)) {
+ error51 = Error(__("Argument unexpected for: %s", key));
+ }
+ setArg(key, defaultValue2(key));
+ return i;
+ }
+ let available = isUndefined(argAfterEqualSign) ? 0 : 1;
+ if (configuration["nargs-eats-options"]) {
+ if (args2.length - (i + 1) + available < toEat) {
+ error51 = Error(__("Not enough arguments following: %s", key));
+ }
+ available = toEat;
+ } else {
+ for (ii = i + 1; ii < args2.length; ii++) {
+ if (!args2[ii].match(/^-[^0-9]/) || args2[ii].match(negative) || isUnknownOptionAsArg(args2[ii]))
+ available++;
+ else
+ break;
+ }
+ if (available < toEat)
+ error51 = Error(__("Not enough arguments following: %s", key));
+ }
+ let consumed = Math.min(available, toEat);
+ if (!isUndefined(argAfterEqualSign) && consumed > 0) {
+ setArg(key, argAfterEqualSign);
+ consumed--;
+ }
+ for (ii = i + 1; ii < consumed + i + 1; ii++) {
+ setArg(key, args2[ii]);
+ }
+ return i + consumed;
+ }
+ __name(eatNargs, "eatNargs");
+ function eatArray(i, key, args2, argAfterEqualSign) {
+ let argsToSet = [];
+ let next = argAfterEqualSign || args2[i + 1];
+ const nargsCount = checkAllAliases(key, flags.nargs);
+ if (checkAllAliases(key, flags.bools) && !/^(true|false)$/.test(next)) {
+ argsToSet.push(true);
+ } else if (isUndefined(next) || isUndefined(argAfterEqualSign) && /^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next)) {
+ if (defaults2[key] !== void 0) {
+ const defVal = defaults2[key];
+ argsToSet = Array.isArray(defVal) ? defVal : [defVal];
+ }
+ } else {
+ if (!isUndefined(argAfterEqualSign)) {
+ argsToSet.push(processValue(key, argAfterEqualSign, true));
+ }
+ for (let ii = i + 1; ii < args2.length; ii++) {
+ if (!configuration["greedy-arrays"] && argsToSet.length > 0 || nargsCount && typeof nargsCount === "number" && argsToSet.length >= nargsCount)
+ break;
+ next = args2[ii];
+ if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))
+ break;
+ i = ii;
+ argsToSet.push(processValue(key, next, inputIsString));
+ }
+ }
+ if (typeof nargsCount === "number" && (nargsCount && argsToSet.length < nargsCount || isNaN(nargsCount) && argsToSet.length === 0)) {
+ error51 = Error(__("Not enough arguments following: %s", key));
+ }
+ setArg(key, argsToSet);
+ return i;
+ }
+ __name(eatArray, "eatArray");
+ function setArg(key, val, shouldStripQuotes = inputIsString) {
+ if (/-/.test(key) && configuration["camel-case-expansion"]) {
+ const alias = key.split(".").map(function(prop) {
+ return camelCase(prop);
+ }).join(".");
+ addNewAlias(key, alias);
+ }
+ const value = processValue(key, val, shouldStripQuotes);
+ const splitKey = key.split(".");
+ setKey(argv, splitKey, value);
+ if (flags.aliases[key]) {
+ flags.aliases[key].forEach(function(x) {
+ const keyProperties = x.split(".");
+ setKey(argv, keyProperties, value);
+ });
+ }
+ if (splitKey.length > 1 && configuration["dot-notation"]) {
+ ;
+ (flags.aliases[splitKey[0]] || []).forEach(function(x) {
+ let keyProperties = x.split(".");
+ const a = [].concat(splitKey);
+ a.shift();
+ keyProperties = keyProperties.concat(a);
+ if (!(flags.aliases[key] || []).includes(keyProperties.join("."))) {
+ setKey(argv, keyProperties, value);
+ }
+ });
+ }
+ if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) {
+ const keys = [key].concat(flags.aliases[key] || []);
+ keys.forEach(function(key2) {
+ Object.defineProperty(argvReturn, key2, {
+ enumerable: true,
+ get() {
+ return val;
+ },
+ set(value2) {
+ val = typeof value2 === "string" ? mixin2.normalize(value2) : value2;
+ }
+ });
+ });
+ }
+ }
+ __name(setArg, "setArg");
+ function addNewAlias(key, alias) {
+ if (!(flags.aliases[key] && flags.aliases[key].length)) {
+ flags.aliases[key] = [alias];
+ newAliases[alias] = true;
+ }
+ if (!(flags.aliases[alias] && flags.aliases[alias].length)) {
+ addNewAlias(alias, key);
+ }
+ }
+ __name(addNewAlias, "addNewAlias");
+ function processValue(key, val, shouldStripQuotes) {
+ if (shouldStripQuotes) {
+ val = stripQuotes(val);
+ }
+ if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) {
+ if (typeof val === "string")
+ val = val === "true";
+ }
+ let value = Array.isArray(val) ? val.map(function(v) {
+ return maybeCoerceNumber(key, v);
+ }) : maybeCoerceNumber(key, val);
+ if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === "boolean")) {
+ value = increment();
+ }
+ if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) {
+ if (Array.isArray(val))
+ value = val.map((val2) => {
+ return mixin2.normalize(val2);
+ });
+ else
+ value = mixin2.normalize(val);
+ }
+ return value;
+ }
+ __name(processValue, "processValue");
+ function maybeCoerceNumber(key, value) {
+ if (!configuration["parse-positional-numbers"] && key === "_")
+ return value;
+ if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) {
+ const shouldCoerceNumber = looksLikeNumber(value) && configuration["parse-numbers"] && Number.isSafeInteger(Math.floor(parseFloat(`${value}`)));
+ if (shouldCoerceNumber || !isUndefined(value) && checkAllAliases(key, flags.numbers)) {
+ value = Number(value);
+ }
+ }
+ return value;
+ }
+ __name(maybeCoerceNumber, "maybeCoerceNumber");
+ function setConfig(argv2) {
+ const configLookup = /* @__PURE__ */ Object.create(null);
+ applyDefaultsAndAliases(configLookup, flags.aliases, defaults2);
+ Object.keys(flags.configs).forEach(function(configKey) {
+ const configPath = argv2[configKey] || configLookup[configKey];
+ if (configPath) {
+ try {
+ let config2 = null;
+ const resolvedConfigPath = mixin2.resolve(mixin2.cwd(), configPath);
+ const resolveConfig = flags.configs[configKey];
+ if (typeof resolveConfig === "function") {
+ try {
+ config2 = resolveConfig(resolvedConfigPath);
+ } catch (e) {
+ config2 = e;
+ }
+ if (config2 instanceof Error) {
+ error51 = config2;
+ return;
+ }
+ } else {
+ config2 = mixin2.require(resolvedConfigPath);
+ }
+ setConfigObject(config2);
+ } catch (ex) {
+ if (ex.name === "PermissionDenied")
+ error51 = ex;
+ else if (argv2[configKey])
+ error51 = Error(__("Invalid JSON config file: %s", configPath));
+ }
+ }
+ });
+ }
+ __name(setConfig, "setConfig");
+ function setConfigObject(config2, prev) {
+ Object.keys(config2).forEach(function(key) {
+ const value = config2[key];
+ const fullKey = prev ? prev + "." + key : key;
+ if (typeof value === "object" && value !== null && !Array.isArray(value) && configuration["dot-notation"]) {
+ setConfigObject(value, fullKey);
+ } else {
+ if (!hasKey(argv, fullKey.split(".")) || checkAllAliases(fullKey, flags.arrays) && configuration["combine-arrays"]) {
+ setArg(fullKey, value);
+ }
+ }
+ });
+ }
+ __name(setConfigObject, "setConfigObject");
+ function setConfigObjects() {
+ if (typeof configObjects !== "undefined") {
+ configObjects.forEach(function(configObject) {
+ setConfigObject(configObject);
+ });
+ }
+ }
+ __name(setConfigObjects, "setConfigObjects");
+ function applyEnvVars(argv2, configOnly) {
+ if (typeof envPrefix === "undefined")
+ return;
+ const prefix = typeof envPrefix === "string" ? envPrefix : "";
+ const env6 = mixin2.env();
+ Object.keys(env6).forEach(function(envVar) {
+ if (prefix === "" || envVar.lastIndexOf(prefix, 0) === 0) {
+ const keys = envVar.split("__").map(function(key, i) {
+ if (i === 0) {
+ key = key.substring(prefix.length);
+ }
+ return camelCase(key);
+ });
+ if ((configOnly && flags.configs[keys.join(".")] || !configOnly) && !hasKey(argv2, keys)) {
+ setArg(keys.join("."), env6[envVar]);
+ }
+ }
+ });
+ }
+ __name(applyEnvVars, "applyEnvVars");
+ function applyCoercions(argv2) {
+ let coerce;
+ const applied = /* @__PURE__ */ new Set();
+ Object.keys(argv2).forEach(function(key) {
+ if (!applied.has(key)) {
+ coerce = checkAllAliases(key, flags.coercions);
+ if (typeof coerce === "function") {
+ try {
+ const value = maybeCoerceNumber(key, coerce(argv2[key]));
+ [].concat(flags.aliases[key] || [], key).forEach((ali) => {
+ applied.add(ali);
+ argv2[ali] = value;
+ });
+ } catch (err) {
+ error51 = err;
+ }
+ }
+ }
+ });
+ }
+ __name(applyCoercions, "applyCoercions");
+ function setPlaceholderKeys(argv2) {
+ flags.keys.forEach((key) => {
+ if (~key.indexOf("."))
+ return;
+ if (typeof argv2[key] === "undefined")
+ argv2[key] = void 0;
+ });
+ return argv2;
+ }
+ __name(setPlaceholderKeys, "setPlaceholderKeys");
+ function applyDefaultsAndAliases(obj, aliases3, defaults3, canLog = false) {
+ Object.keys(defaults3).forEach(function(key) {
+ if (!hasKey(obj, key.split("."))) {
+ setKey(obj, key.split("."), defaults3[key]);
+ if (canLog)
+ defaulted[key] = true;
+ (aliases3[key] || []).forEach(function(x) {
+ if (hasKey(obj, x.split(".")))
+ return;
+ setKey(obj, x.split("."), defaults3[key]);
+ });
+ }
+ });
+ }
+ __name(applyDefaultsAndAliases, "applyDefaultsAndAliases");
+ function hasKey(obj, keys) {
+ let o = obj;
+ if (!configuration["dot-notation"])
+ keys = [keys.join(".")];
+ keys.slice(0, -1).forEach(function(key2) {
+ o = o[key2] || {};
+ });
+ const key = keys[keys.length - 1];
+ if (typeof o !== "object")
+ return false;
+ else
+ return key in o;
+ }
+ __name(hasKey, "hasKey");
+ function setKey(obj, keys, value) {
+ let o = obj;
+ if (!configuration["dot-notation"])
+ keys = [keys.join(".")];
+ keys.slice(0, -1).forEach(function(key2) {
+ key2 = sanitizeKey(key2);
+ if (typeof o === "object" && o[key2] === void 0) {
+ o[key2] = {};
+ }
+ if (typeof o[key2] !== "object" || Array.isArray(o[key2])) {
+ if (Array.isArray(o[key2])) {
+ o[key2].push({});
+ } else {
+ o[key2] = [o[key2], {}];
+ }
+ o = o[key2][o[key2].length - 1];
+ } else {
+ o = o[key2];
+ }
+ });
+ const key = sanitizeKey(keys[keys.length - 1]);
+ const isTypeArray = checkAllAliases(keys.join("."), flags.arrays);
+ const isValueArray = Array.isArray(value);
+ let duplicate = configuration["duplicate-arguments-array"];
+ if (!duplicate && checkAllAliases(key, flags.nargs)) {
+ duplicate = true;
+ if (!isUndefined(o[key]) && flags.nargs[key] === 1 || Array.isArray(o[key]) && o[key].length === flags.nargs[key]) {
+ o[key] = void 0;
+ }
+ }
+ if (value === increment()) {
+ o[key] = increment(o[key]);
+ } else if (Array.isArray(o[key])) {
+ if (duplicate && isTypeArray && isValueArray) {
+ o[key] = configuration["flatten-duplicate-arrays"] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value]);
+ } else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) {
+ o[key] = value;
+ } else {
+ o[key] = o[key].concat([value]);
+ }
+ } else if (o[key] === void 0 && isTypeArray) {
+ o[key] = isValueArray ? value : [value];
+ } else if (duplicate && !(o[key] === void 0 || checkAllAliases(key, flags.counts) || checkAllAliases(key, flags.bools))) {
+ o[key] = [o[key], value];
+ } else {
+ o[key] = value;
+ }
+ }
+ __name(setKey, "setKey");
+ function extendAliases(...args2) {
+ args2.forEach(function(obj) {
+ Object.keys(obj || {}).forEach(function(key) {
+ if (flags.aliases[key])
+ return;
+ flags.aliases[key] = [].concat(aliases2[key] || []);
+ flags.aliases[key].concat(key).forEach(function(x) {
+ if (/-/.test(x) && configuration["camel-case-expansion"]) {
+ const c = camelCase(x);
+ if (c !== key && flags.aliases[key].indexOf(c) === -1) {
+ flags.aliases[key].push(c);
+ newAliases[c] = true;
+ }
+ }
+ });
+ flags.aliases[key].concat(key).forEach(function(x) {
+ if (x.length > 1 && /[A-Z]/.test(x) && configuration["camel-case-expansion"]) {
+ const c = decamelize(x, "-");
+ if (c !== key && flags.aliases[key].indexOf(c) === -1) {
+ flags.aliases[key].push(c);
+ newAliases[c] = true;
+ }
+ }
+ });
+ flags.aliases[key].forEach(function(x) {
+ flags.aliases[x] = [key].concat(flags.aliases[key].filter(function(y) {
+ return x !== y;
+ }));
+ });
+ });
+ });
+ }
+ __name(extendAliases, "extendAliases");
+ function checkAllAliases(key, flag) {
+ const toCheck = [].concat(flags.aliases[key] || [], key);
+ const keys = Object.keys(flag);
+ const setAlias = toCheck.find((key2) => keys.includes(key2));
+ return setAlias ? flag[setAlias] : false;
+ }
+ __name(checkAllAliases, "checkAllAliases");
+ function hasAnyFlag(key) {
+ const flagsKeys = Object.keys(flags);
+ const toCheck = [].concat(flagsKeys.map((k) => flags[k]));
+ return toCheck.some(function(flag) {
+ return Array.isArray(flag) ? flag.includes(key) : flag[key];
+ });
+ }
+ __name(hasAnyFlag, "hasAnyFlag");
+ function hasFlagsMatching(arg, ...patterns) {
+ const toCheck = [].concat(...patterns);
+ return toCheck.some(function(pattern) {
+ const match = arg.match(pattern);
+ return match && hasAnyFlag(match[1]);
+ });
+ }
+ __name(hasFlagsMatching, "hasFlagsMatching");
+ function hasAllShortFlags(arg) {
+ if (arg.match(negative) || !arg.match(/^-[^-]+/)) {
+ return false;
+ }
+ let hasAllFlags = true;
+ let next;
+ const letters = arg.slice(1).split("");
+ for (let j = 0; j < letters.length; j++) {
+ next = arg.slice(j + 2);
+ if (!hasAnyFlag(letters[j])) {
+ hasAllFlags = false;
+ break;
+ }
+ if (letters[j + 1] && letters[j + 1] === "=" || next === "-" || /[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) || letters[j + 1] && letters[j + 1].match(/\W/)) {
+ break;
+ }
+ }
+ return hasAllFlags;
+ }
+ __name(hasAllShortFlags, "hasAllShortFlags");
+ function isUnknownOptionAsArg(arg) {
+ return configuration["unknown-options-as-args"] && isUnknownOption(arg);
+ }
+ __name(isUnknownOptionAsArg, "isUnknownOptionAsArg");
+ function isUnknownOption(arg) {
+ arg = arg.replace(/^-{3,}/, "--");
+ if (arg.match(negative)) {
+ return false;
+ }
+ if (hasAllShortFlags(arg)) {
+ return false;
+ }
+ const flagWithEquals = /^-+([^=]+?)=[\s\S]*$/;
+ const normalFlag = /^-+([^=]+?)$/;
+ const flagEndingInHyphen = /^-+([^=]+?)-$/;
+ const flagEndingInDigits = /^-+([^=]+?\d+)$/;
+ const flagEndingInNonWordCharacters = /^-+([^=]+?)\W+.*$/;
+ return !hasFlagsMatching(arg, flagWithEquals, negatedBoolean, normalFlag, flagEndingInHyphen, flagEndingInDigits, flagEndingInNonWordCharacters);
+ }
+ __name(isUnknownOption, "isUnknownOption");
+ function defaultValue2(key) {
+ if (!checkAllAliases(key, flags.bools) && !checkAllAliases(key, flags.counts) && `${key}` in defaults2) {
+ return defaults2[key];
+ } else {
+ return defaultForType(guessType2(key));
+ }
+ }
+ __name(defaultValue2, "defaultValue");
+ function defaultForType(type2) {
+ const def = {
+ [DefaultValuesForTypeKey.BOOLEAN]: true,
+ [DefaultValuesForTypeKey.STRING]: "",
+ [DefaultValuesForTypeKey.NUMBER]: void 0,
+ [DefaultValuesForTypeKey.ARRAY]: []
+ };
+ return def[type2];
+ }
+ __name(defaultForType, "defaultForType");
+ function guessType2(key) {
+ let type2 = DefaultValuesForTypeKey.BOOLEAN;
+ if (checkAllAliases(key, flags.strings))
+ type2 = DefaultValuesForTypeKey.STRING;
+ else if (checkAllAliases(key, flags.numbers))
+ type2 = DefaultValuesForTypeKey.NUMBER;
+ else if (checkAllAliases(key, flags.bools))
+ type2 = DefaultValuesForTypeKey.BOOLEAN;
+ else if (checkAllAliases(key, flags.arrays))
+ type2 = DefaultValuesForTypeKey.ARRAY;
+ return type2;
+ }
+ __name(guessType2, "guessType");
+ function isUndefined(num) {
+ return num === void 0;
+ }
+ __name(isUndefined, "isUndefined");
+ function checkConfiguration() {
+ Object.keys(flags.counts).find((key) => {
+ if (checkAllAliases(key, flags.arrays)) {
+ error51 = Error(__("Invalid configuration: %s, opts.count excludes opts.array.", key));
+ return true;
+ } else if (checkAllAliases(key, flags.nargs)) {
+ error51 = Error(__("Invalid configuration: %s, opts.count excludes opts.narg.", key));
+ return true;
+ }
+ return false;
+ });
+ }
+ __name(checkConfiguration, "checkConfiguration");
+ return {
+ aliases: Object.assign({}, flags.aliases),
+ argv: Object.assign(argvReturn, argv),
+ configuration,
+ defaulted: Object.assign({}, defaulted),
+ error: error51,
+ newAliases: Object.assign({}, newAliases)
+ };
+ }
+};
+function combineAliases(aliases2) {
+ const aliasArrays = [];
+ const combined = /* @__PURE__ */ Object.create(null);
+ let change = true;
+ Object.keys(aliases2).forEach(function(key) {
+ aliasArrays.push([].concat(aliases2[key], key));
+ });
+ while (change) {
+ change = false;
+ for (let i = 0; i < aliasArrays.length; i++) {
+ for (let ii = i + 1; ii < aliasArrays.length; ii++) {
+ const intersect = aliasArrays[i].filter(function(v) {
+ return aliasArrays[ii].indexOf(v) !== -1;
+ });
+ if (intersect.length) {
+ aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]);
+ aliasArrays.splice(ii, 1);
+ change = true;
+ break;
+ }
+ }
+ }
+ }
+ aliasArrays.forEach(function(aliasArray) {
+ aliasArray = aliasArray.filter(function(v, i, self2) {
+ return self2.indexOf(v) === i;
+ });
+ const lastAlias = aliasArray.pop();
+ if (lastAlias !== void 0 && typeof lastAlias === "string") {
+ combined[lastAlias] = aliasArray;
+ }
+ });
+ return combined;
+}
+__name(combineAliases, "combineAliases");
+function increment(orig) {
+ return orig !== void 0 ? orig + 1 : 1;
+}
+__name(increment, "increment");
+function sanitizeKey(key) {
+ if (key === "__proto__")
+ return "___proto___";
+ return key;
+}
+__name(sanitizeKey, "sanitizeKey");
+function stripQuotes(val) {
+ return typeof val === "string" && (val[0] === "'" || val[0] === '"') && val[val.length - 1] === val[0] ? val.substring(1, val.length - 1) : val;
+}
+__name(stripQuotes, "stripQuotes");
+
+// node_modules/yargs-parser/build/lib/index.js
+import { readFileSync as readFileSync13 } from "fs";
+import { createRequire } from "node:module";
+var _a5;
+var _b;
+var _c;
+var minNodeVersion = process && process.env && process.env.YARGS_MIN_NODE_VERSION ? Number(process.env.YARGS_MIN_NODE_VERSION) : 20;
+var nodeVersion = (_b = (_a5 = process === null || process === void 0 ? void 0 : process.versions) === null || _a5 === void 0 ? void 0 : _a5.node) !== null && _b !== void 0 ? _b : (_c = process === null || process === void 0 ? void 0 : process.version) === null || _c === void 0 ? void 0 : _c.slice(1);
+if (nodeVersion) {
+ const major = Number(nodeVersion.match(/^([^.]+)/)[1]);
+ if (major < minNodeVersion) {
+ throw Error(`yargs parser supports a minimum Node.js version of ${minNodeVersion}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`);
+ }
+}
+var env5 = process ? process.env : {};
+var require2 = createRequire ? createRequire(import.meta.url) : void 0;
+var parser = new YargsParser({
+ cwd: process.cwd,
+ env: /* @__PURE__ */ __name(() => {
+ return env5;
+ }, "env"),
+ format,
+ normalize: normalize4,
+ resolve: resolve13,
+ require: /* @__PURE__ */ __name((path27) => {
+ if (typeof require2 !== "undefined") {
+ return require2(path27);
+ } else if (path27.match(/\.json$/)) {
+ return JSON.parse(readFileSync13(path27, "utf8"));
+ } else {
+ throw Error("only .json config files are supported in ESM");
+ }
+ }, "require")
+});
+var yargsParser = /* @__PURE__ */ __name(function Parser(args, opts) {
+ const result = parser.parse(args.slice(), opts);
+ return result.argv;
+}, "Parser");
+yargsParser.detailed = function(args, opts) {
+ return parser.parse(args.slice(), opts);
+};
+yargsParser.camelCase = camelCase;
+yargsParser.decamelize = decamelize;
+yargsParser.looksLikeNumber = looksLikeNumber;
+var lib_default = yargsParser;
+
+// node_modules/yargs/lib/platform-shims/esm.mjs
+import { basename as basename5, dirname as dirname12, extname as extname3, relative as relative4, resolve as resolve15, join as join14 } from "path";
+
+// node_modules/yargs/build/lib/utils/process-argv.js
+init_esbuild_shims();
+function getProcessArgvBinIndex() {
+ if (isBundledElectronApp())
+ return 0;
+ return 1;
+}
+__name(getProcessArgvBinIndex, "getProcessArgvBinIndex");
+function isBundledElectronApp() {
+ return isElectronApp() && !process.defaultApp;
+}
+__name(isBundledElectronApp, "isBundledElectronApp");
+function isElectronApp() {
+ return !!process.versions.electron;
+}
+__name(isElectronApp, "isElectronApp");
+function hideBin(argv) {
+ return argv.slice(getProcessArgvBinIndex() + 1);
+}
+__name(hideBin, "hideBin");
+function getProcessArgvBin() {
+ return process.argv[getProcessArgvBinIndex()];
+}
+__name(getProcessArgvBin, "getProcessArgvBin");
+
+// node_modules/yargs/node_modules/string-width/index.js
+init_esbuild_shims();
+var import_emoji_regex2 = __toESM(require_emoji_regex(), 1);
+var segmenter5 = new Intl.Segmenter();
+var defaultIgnorableCodePointRegex2 = new RegExp("^\\p{Default_Ignorable_Code_Point}$", "u");
+function stringWidth3(string4, options2 = {}) {
+ if (typeof string4 !== "string" || string4.length === 0) {
+ return 0;
+ }
+ const {
+ ambiguousIsNarrow = true,
+ countAnsiEscapeCodes = false
+ } = options2;
+ if (!countAnsiEscapeCodes) {
+ string4 = stripAnsi(string4);
+ }
+ if (string4.length === 0) {
+ return 0;
+ }
+ let width = 0;
+ const eastAsianWidthOptions = { ambiguousAsWide: !ambiguousIsNarrow };
+ for (const { segment: character } of segmenter5.segment(string4)) {
+ const codePoint = character.codePointAt(0);
+ if (codePoint <= 31 || codePoint >= 127 && codePoint <= 159) {
+ continue;
+ }
+ if (codePoint >= 8203 && codePoint <= 8207 || codePoint === 65279) {
+ continue;
+ }
+ if (codePoint >= 768 && codePoint <= 879 || codePoint >= 6832 && codePoint <= 6911 || codePoint >= 7616 && codePoint <= 7679 || codePoint >= 8400 && codePoint <= 8447 || codePoint >= 65056 && codePoint <= 65071) {
+ continue;
+ }
+ if (codePoint >= 55296 && codePoint <= 57343) {
+ continue;
+ }
+ if (codePoint >= 65024 && codePoint <= 65039) {
+ continue;
+ }
+ if (defaultIgnorableCodePointRegex2.test(character)) {
+ continue;
+ }
+ if ((0, import_emoji_regex2.default)().test(character)) {
+ width += 2;
+ continue;
+ }
+ width += eastAsianWidth(codePoint, eastAsianWidthOptions);
+ }
+ return width;
+}
+__name(stringWidth3, "stringWidth");
+
+// node_modules/y18n/index.mjs
+init_esbuild_shims();
+
+// node_modules/y18n/build/lib/platform-shims/node.js
+init_esbuild_shims();
+import { readFileSync as readFileSync14, statSync as statSync10, writeFile } from "fs";
+import { format as format2 } from "util";
+import { resolve as resolve14 } from "path";
+var node_default = {
+ fs: {
+ readFileSync: readFileSync14,
+ writeFile
+ },
+ format: format2,
+ resolve: resolve14,
+ exists: /* @__PURE__ */ __name((file2) => {
+ try {
+ return statSync10(file2).isFile();
+ } catch (err) {
+ return false;
+ }
+ }, "exists")
+};
+
+// node_modules/y18n/build/lib/index.js
+init_esbuild_shims();
+var shim;
+var Y18N = class {
+ static {
+ __name(this, "Y18N");
+ }
+ constructor(opts) {
+ opts = opts || {};
+ this.directory = opts.directory || "./locales";
+ this.updateFiles = typeof opts.updateFiles === "boolean" ? opts.updateFiles : true;
+ this.locale = opts.locale || "en";
+ this.fallbackToLanguage = typeof opts.fallbackToLanguage === "boolean" ? opts.fallbackToLanguage : true;
+ this.cache = /* @__PURE__ */ Object.create(null);
+ this.writeQueue = [];
+ }
+ __(...args) {
+ if (typeof arguments[0] !== "string") {
+ return this._taggedLiteral(arguments[0], ...arguments);
+ }
+ const str3 = args.shift();
+ let cb = /* @__PURE__ */ __name(function() {
+ }, "cb");
+ if (typeof args[args.length - 1] === "function")
+ cb = args.pop();
+ cb = cb || function() {
+ };
+ if (!this.cache[this.locale])
+ this._readLocaleFile();
+ if (!this.cache[this.locale][str3] && this.updateFiles) {
+ this.cache[this.locale][str3] = str3;
+ this._enqueueWrite({
+ directory: this.directory,
+ locale: this.locale,
+ cb
+ });
+ } else {
+ cb();
+ }
+ return shim.format.apply(shim.format, [this.cache[this.locale][str3] || str3].concat(args));
+ }
+ __n() {
+ const args = Array.prototype.slice.call(arguments);
+ const singular = args.shift();
+ const plural = args.shift();
+ const quantity = args.shift();
+ let cb = /* @__PURE__ */ __name(function() {
+ }, "cb");
+ if (typeof args[args.length - 1] === "function")
+ cb = args.pop();
+ if (!this.cache[this.locale])
+ this._readLocaleFile();
+ let str3 = quantity === 1 ? singular : plural;
+ if (this.cache[this.locale][singular]) {
+ const entry = this.cache[this.locale][singular];
+ str3 = entry[quantity === 1 ? "one" : "other"];
+ }
+ if (!this.cache[this.locale][singular] && this.updateFiles) {
+ this.cache[this.locale][singular] = {
+ one: singular,
+ other: plural
+ };
+ this._enqueueWrite({
+ directory: this.directory,
+ locale: this.locale,
+ cb
+ });
+ } else {
+ cb();
+ }
+ const values = [str3];
+ if (~str3.indexOf("%d"))
+ values.push(quantity);
+ return shim.format.apply(shim.format, values.concat(args));
+ }
+ setLocale(locale) {
+ this.locale = locale;
+ }
+ getLocale() {
+ return this.locale;
+ }
+ updateLocale(obj) {
+ if (!this.cache[this.locale])
+ this._readLocaleFile();
+ for (const key in obj) {
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
+ this.cache[this.locale][key] = obj[key];
+ }
+ }
+ }
+ _taggedLiteral(parts, ...args) {
+ let str3 = "";
+ parts.forEach(function(part, i) {
+ const arg = args[i + 1];
+ str3 += part;
+ if (typeof arg !== "undefined") {
+ str3 += "%s";
+ }
+ });
+ return this.__.apply(this, [str3].concat([].slice.call(args, 1)));
+ }
+ _enqueueWrite(work) {
+ this.writeQueue.push(work);
+ if (this.writeQueue.length === 1)
+ this._processWriteQueue();
+ }
+ _processWriteQueue() {
+ const _this = this;
+ const work = this.writeQueue[0];
+ const directory = work.directory;
+ const locale = work.locale;
+ const cb = work.cb;
+ const languageFile = this._resolveLocaleFile(directory, locale);
+ const serializedLocale = JSON.stringify(this.cache[locale], null, 2);
+ shim.fs.writeFile(languageFile, serializedLocale, "utf-8", function(err) {
+ _this.writeQueue.shift();
+ if (_this.writeQueue.length > 0)
+ _this._processWriteQueue();
+ cb(err);
+ });
+ }
+ _readLocaleFile() {
+ let localeLookup = {};
+ const languageFile = this._resolveLocaleFile(this.directory, this.locale);
+ try {
+ if (shim.fs.readFileSync) {
+ localeLookup = JSON.parse(shim.fs.readFileSync(languageFile, "utf-8"));
+ }
+ } catch (err) {
+ if (err instanceof SyntaxError) {
+ err.message = "syntax error in " + languageFile;
+ }
+ if (err.code === "ENOENT")
+ localeLookup = {};
+ else
+ throw err;
+ }
+ this.cache[this.locale] = localeLookup;
+ }
+ _resolveLocaleFile(directory, locale) {
+ let file2 = shim.resolve(directory, "./", locale + ".json");
+ if (this.fallbackToLanguage && !this._fileExistsSync(file2) && ~locale.lastIndexOf("_")) {
+ const languageFile = shim.resolve(directory, "./", locale.split("_")[0] + ".json");
+ if (this._fileExistsSync(languageFile))
+ file2 = languageFile;
+ }
+ return file2;
+ }
+ _fileExistsSync(file2) {
+ return shim.exists(file2);
+ }
+};
+function y18n(opts, _shim) {
+ shim = _shim;
+ const y18n3 = new Y18N(opts);
+ return {
+ __: y18n3.__.bind(y18n3),
+ __n: y18n3.__n.bind(y18n3),
+ setLocale: y18n3.setLocale.bind(y18n3),
+ getLocale: y18n3.getLocale.bind(y18n3),
+ updateLocale: y18n3.updateLocale.bind(y18n3),
+ locale: y18n3.locale
+ };
+}
+__name(y18n, "y18n");
+
+// node_modules/y18n/index.mjs
+var y18n2 = /* @__PURE__ */ __name((opts) => {
+ return y18n(opts, node_default);
+}, "y18n");
+var y18n_default = y18n2;
+
+// node_modules/yargs/lib/platform-shims/esm.mjs
+var import_get_caller_file = __toESM(require_get_caller_file(), 1);
+import { createRequire as createRequire2 } from "node:module";
+import { readFileSync as readFileSync15, readdirSync as readdirSync6 } from "node:fs";
+var __dirname2 = fileURLToPath2(import.meta.url);
+var mainFilename = __dirname2.substring(0, __dirname2.lastIndexOf("node_modules"));
+var require3 = createRequire2(import.meta.url);
+var esm_default = {
+ assert: {
+ notStrictEqual,
+ strictEqual
+ },
+ cliui: ui,
+ findUp: sync_default,
+ getEnv: /* @__PURE__ */ __name((key) => {
+ return process.env[key];
+ }, "getEnv"),
+ inspect,
+ getProcessArgvBin,
+ mainFilename: mainFilename || process.cwd(),
+ Parser: lib_default,
+ path: {
+ basename: basename5,
+ dirname: dirname12,
+ extname: extname3,
+ relative: relative4,
+ resolve: resolve15,
+ join: join14
+ },
+ process: {
+ argv: /* @__PURE__ */ __name(() => process.argv, "argv"),
+ cwd: process.cwd,
+ emitWarning: /* @__PURE__ */ __name((warning, type2) => process.emitWarning(warning, type2), "emitWarning"),
+ execPath: /* @__PURE__ */ __name(() => process.execPath, "execPath"),
+ exit: /* @__PURE__ */ __name((code) => {
+ process.exit(code);
+ }, "exit"),
+ nextTick: process.nextTick,
+ stdColumns: typeof process.stdout.columns !== "undefined" ? process.stdout.columns : null
+ },
+ readFileSync: readFileSync15,
+ readdirSync: readdirSync6,
+ require: require3,
+ getCallerFile: /* @__PURE__ */ __name(() => {
+ const callerFile = (0, import_get_caller_file.default)(3);
+ return callerFile.match(/^file:\/\//) ? fileURLToPath2(callerFile) : callerFile;
+ }, "getCallerFile"),
+ stringWidth: stringWidth3,
+ y18n: y18n_default({
+ directory: resolve15(__dirname2, "../../../locales"),
+ updateFiles: false
+ })
+};
+
+// node_modules/yargs/build/lib/yargs-factory.js
+init_esbuild_shims();
+
+// node_modules/yargs/build/lib/command.js
+init_esbuild_shims();
+
+// node_modules/yargs/build/lib/typings/common-types.js
+init_esbuild_shims();
+function assertNotStrictEqual(actual, expected, shim3, message) {
+ shim3.assert.notStrictEqual(actual, expected, message);
+}
+__name(assertNotStrictEqual, "assertNotStrictEqual");
+function assertSingleKey(actual, shim3) {
+ shim3.assert.strictEqual(typeof actual, "string");
+}
+__name(assertSingleKey, "assertSingleKey");
+function objectKeys(object2) {
+ return Object.keys(object2);
+}
+__name(objectKeys, "objectKeys");
+
+// node_modules/yargs/build/lib/utils/is-promise.js
+init_esbuild_shims();
+function isPromise(maybePromise) {
+ return !!maybePromise && !!maybePromise.then && typeof maybePromise.then === "function";
+}
+__name(isPromise, "isPromise");
+
+// node_modules/yargs/build/lib/middleware.js
+init_esbuild_shims();
+
+// node_modules/yargs/build/lib/argsert.js
+init_esbuild_shims();
+
+// node_modules/yargs/build/lib/yerror.js
+init_esbuild_shims();
+var YError = class _YError extends Error {
+ static {
+ __name(this, "YError");
+ }
+ constructor(msg) {
+ super(msg || "yargs error");
+ this.name = "YError";
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, _YError);
+ }
+ }
+};
+
+// node_modules/yargs/build/lib/parse-command.js
+init_esbuild_shims();
+function parseCommand(cmd) {
+ const extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, " ");
+ const splitCommand = extraSpacesStrippedCommand.split(/\s+(?![^[]*]|[^<]*>)/);
+ const bregex = /\.*[\][<>]/g;
+ const firstCommand = splitCommand.shift();
+ if (!firstCommand)
+ throw new Error(`No command found in: ${cmd}`);
+ const parsedCommand = {
+ cmd: firstCommand.replace(bregex, ""),
+ demanded: [],
+ optional: []
+ };
+ splitCommand.forEach((cmd2, i) => {
+ let variadic = false;
+ cmd2 = cmd2.replace(/\s/g, "");
+ if (/\.+[\]>]/.test(cmd2) && i === splitCommand.length - 1)
+ variadic = true;
+ if (/^\[/.test(cmd2)) {
+ parsedCommand.optional.push({
+ cmd: cmd2.replace(bregex, "").split("|"),
+ variadic
+ });
+ } else {
+ parsedCommand.demanded.push({
+ cmd: cmd2.replace(bregex, "").split("|"),
+ variadic
+ });
+ }
+ });
+ return parsedCommand;
+}
+__name(parseCommand, "parseCommand");
+
+// node_modules/yargs/build/lib/argsert.js
+var positionName = ["first", "second", "third", "fourth", "fifth", "sixth"];
+function argsert(arg1, arg2, arg3) {
+ function parseArgs() {
+ return typeof arg1 === "object" ? [{ demanded: [], optional: [] }, arg1, arg2] : [
+ parseCommand(`cmd ${arg1}`),
+ arg2,
+ arg3
+ ];
+ }
+ __name(parseArgs, "parseArgs");
+ try {
+ let position = 0;
+ const [parsed, callerArguments, _length2] = parseArgs();
+ const args = [].slice.call(callerArguments);
+ while (args.length && args[args.length - 1] === void 0)
+ args.pop();
+ const length = _length2 || args.length;
+ if (length < parsed.demanded.length) {
+ throw new YError(`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args.length}.`);
+ }
+ const totalCommands = parsed.demanded.length + parsed.optional.length;
+ if (length > totalCommands) {
+ throw new YError(`Too many arguments provided. Expected max ${totalCommands} but received ${length}.`);
+ }
+ parsed.demanded.forEach((demanded) => {
+ const arg = args.shift();
+ const observedType = guessType(arg);
+ const matchingTypes = demanded.cmd.filter((type2) => type2 === observedType || type2 === "*");
+ if (matchingTypes.length === 0)
+ argumentTypeError(observedType, demanded.cmd, position);
+ position += 1;
+ });
+ parsed.optional.forEach((optional2) => {
+ if (args.length === 0)
+ return;
+ const arg = args.shift();
+ const observedType = guessType(arg);
+ const matchingTypes = optional2.cmd.filter((type2) => type2 === observedType || type2 === "*");
+ if (matchingTypes.length === 0)
+ argumentTypeError(observedType, optional2.cmd, position);
+ position += 1;
+ });
+ } catch (err) {
+ console.warn(err.stack);
+ }
+}
+__name(argsert, "argsert");
+function guessType(arg) {
+ if (Array.isArray(arg)) {
+ return "array";
+ } else if (arg === null) {
+ return "null";
+ }
+ return typeof arg;
+}
+__name(guessType, "guessType");
+function argumentTypeError(observedType, allowedTypes, position) {
+ throw new YError(`Invalid ${positionName[position] || "manyith"} argument. Expected ${allowedTypes.join(" or ")} but received ${observedType}.`);
+}
+__name(argumentTypeError, "argumentTypeError");
+
+// node_modules/yargs/build/lib/middleware.js
+var GlobalMiddleware = class {
+ static {
+ __name(this, "GlobalMiddleware");
+ }
+ constructor(yargs) {
+ this.globalMiddleware = [];
+ this.frozens = [];
+ this.yargs = yargs;
+ }
+ addMiddleware(callback, applyBeforeValidation, global2 = true, mutates = false) {
+ argsert(" [boolean] [boolean] [boolean]", [callback, applyBeforeValidation, global2], arguments.length);
+ if (Array.isArray(callback)) {
+ for (let i = 0; i < callback.length; i++) {
+ if (typeof callback[i] !== "function") {
+ throw Error("middleware must be a function");
+ }
+ const m = callback[i];
+ m.applyBeforeValidation = applyBeforeValidation;
+ m.global = global2;
+ }
+ Array.prototype.push.apply(this.globalMiddleware, callback);
+ } else if (typeof callback === "function") {
+ const m = callback;
+ m.applyBeforeValidation = applyBeforeValidation;
+ m.global = global2;
+ m.mutates = mutates;
+ this.globalMiddleware.push(callback);
+ }
+ return this.yargs;
+ }
+ addCoerceMiddleware(callback, option) {
+ const aliases2 = this.yargs.getAliases();
+ this.globalMiddleware = this.globalMiddleware.filter((m) => {
+ const toCheck = [...aliases2[option] || [], option];
+ if (!m.option)
+ return true;
+ else
+ return !toCheck.includes(m.option);
+ });
+ callback.option = option;
+ return this.addMiddleware(callback, true, true, true);
+ }
+ getMiddleware() {
+ return this.globalMiddleware;
+ }
+ freeze() {
+ this.frozens.push([...this.globalMiddleware]);
+ }
+ unfreeze() {
+ const frozen = this.frozens.pop();
+ if (frozen !== void 0)
+ this.globalMiddleware = frozen;
+ }
+ reset() {
+ this.globalMiddleware = this.globalMiddleware.filter((m) => m.global);
+ }
+};
+function commandMiddlewareFactory(commandMiddleware) {
+ if (!commandMiddleware)
+ return [];
+ return commandMiddleware.map((middleware) => {
+ middleware.applyBeforeValidation = false;
+ return middleware;
+ });
+}
+__name(commandMiddlewareFactory, "commandMiddlewareFactory");
+function applyMiddleware(argv, yargs, middlewares, beforeValidation) {
+ return middlewares.reduce((acc, middleware) => {
+ if (middleware.applyBeforeValidation !== beforeValidation) {
+ return acc;
+ }
+ if (middleware.mutates) {
+ if (middleware.applied)
+ return acc;
+ middleware.applied = true;
+ }
+ if (isPromise(acc)) {
+ return acc.then((initialObj) => Promise.all([initialObj, middleware(initialObj, yargs)])).then(([initialObj, middlewareObj]) => Object.assign(initialObj, middlewareObj));
+ } else {
+ const result = middleware(acc, yargs);
+ return isPromise(result) ? result.then((middlewareObj) => Object.assign(acc, middlewareObj)) : Object.assign(acc, result);
+ }
+ }, argv);
+}
+__name(applyMiddleware, "applyMiddleware");
+
+// node_modules/yargs/build/lib/utils/maybe-async-result.js
+init_esbuild_shims();
+function maybeAsyncResult(getResult, resultHandler, errorHandler = (err) => {
+ throw err;
+}) {
+ try {
+ const result = isFunction(getResult) ? getResult() : getResult;
+ return isPromise(result) ? result.then((result2) => resultHandler(result2)) : resultHandler(result);
+ } catch (err) {
+ return errorHandler(err);
+ }
+}
+__name(maybeAsyncResult, "maybeAsyncResult");
+function isFunction(arg) {
+ return typeof arg === "function";
+}
+__name(isFunction, "isFunction");
+
+// node_modules/yargs/build/lib/command.js
+var DEFAULT_MARKER = /(^\*)|(^\$0)/;
+var CommandInstance = class {
+ static {
+ __name(this, "CommandInstance");
+ }
+ constructor(usage2, validation2, globalMiddleware, shim3) {
+ this.requireCache = /* @__PURE__ */ new Set();
+ this.handlers = {};
+ this.aliasMap = {};
+ this.frozens = [];
+ this.shim = shim3;
+ this.usage = usage2;
+ this.globalMiddleware = globalMiddleware;
+ this.validation = validation2;
+ }
+ addDirectory(dir, req, callerFile, opts) {
+ opts = opts || {};
+ this.requireCache.add(callerFile);
+ const fullDirPath = this.shim.path.resolve(this.shim.path.dirname(callerFile), dir);
+ const files = this.shim.readdirSync(fullDirPath, {
+ recursive: opts.recurse ? true : false
+ });
+ if (!Array.isArray(opts.extensions))
+ opts.extensions = ["js"];
+ const visit = typeof opts.visit === "function" ? opts.visit : (o) => o;
+ for (const fileb of files) {
+ const file2 = fileb.toString();
+ if (opts.exclude) {
+ let exclude = false;
+ if (typeof opts.exclude === "function") {
+ exclude = opts.exclude(file2);
+ } else {
+ exclude = opts.exclude.test(file2);
+ }
+ if (exclude)
+ continue;
+ }
+ if (opts.include) {
+ let include = false;
+ if (typeof opts.include === "function") {
+ include = opts.include(file2);
+ } else {
+ include = opts.include.test(file2);
+ }
+ if (!include)
+ continue;
+ }
+ let supportedExtension = false;
+ for (const ext of opts.extensions) {
+ if (file2.endsWith(ext))
+ supportedExtension = true;
+ }
+ if (supportedExtension) {
+ const joined = this.shim.path.join(fullDirPath, file2);
+ const module2 = req(joined);
+ const extendableModule = Object.create(null, Object.getOwnPropertyDescriptors({ ...module2 }));
+ const visited = visit(extendableModule, joined, file2);
+ if (visited) {
+ if (this.requireCache.has(joined))
+ continue;
+ else
+ this.requireCache.add(joined);
+ if (!extendableModule.command) {
+ extendableModule.command = this.shim.path.basename(joined, this.shim.path.extname(joined));
+ }
+ this.addHandler(extendableModule);
+ }
+ }
+ }
+ }
+ addHandler(cmd, description, builder, handler, commandMiddleware, deprecated) {
+ let aliases2 = [];
+ const middlewares = commandMiddlewareFactory(commandMiddleware);
+ handler = handler || (() => {
+ });
+ if (Array.isArray(cmd)) {
+ if (isCommandAndAliases(cmd)) {
+ [cmd, ...aliases2] = cmd;
+ } else {
+ for (const command2 of cmd) {
+ this.addHandler(command2);
+ }
+ }
+ } else if (isCommandHandlerDefinition(cmd)) {
+ let command2 = Array.isArray(cmd.command) || typeof cmd.command === "string" ? cmd.command : null;
+ if (command2 === null) {
+ throw new Error(`No command name given for module: ${this.shim.inspect(cmd)}`);
+ }
+ if (cmd.aliases)
+ command2 = [].concat(command2).concat(cmd.aliases);
+ this.addHandler(command2, this.extractDesc(cmd), cmd.builder, cmd.handler, cmd.middlewares, cmd.deprecated);
+ return;
+ } else if (isCommandBuilderDefinition(builder)) {
+ this.addHandler([cmd].concat(aliases2), description, builder.builder, builder.handler, builder.middlewares, builder.deprecated);
+ return;
+ }
+ if (typeof cmd === "string") {
+ const parsedCommand = parseCommand(cmd);
+ aliases2 = aliases2.map((alias) => parseCommand(alias).cmd);
+ let isDefault = false;
+ const parsedAliases = [parsedCommand.cmd].concat(aliases2).filter((c) => {
+ if (DEFAULT_MARKER.test(c)) {
+ isDefault = true;
+ return false;
+ }
+ return true;
+ });
+ if (parsedAliases.length === 0 && isDefault)
+ parsedAliases.push("$0");
+ if (isDefault) {
+ parsedCommand.cmd = parsedAliases[0];
+ aliases2 = parsedAliases.slice(1);
+ cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd);
+ }
+ aliases2.forEach((alias) => {
+ this.aliasMap[alias] = parsedCommand.cmd;
+ });
+ if (description !== false) {
+ this.usage.command(cmd, description, isDefault, aliases2, deprecated);
+ }
+ this.handlers[parsedCommand.cmd] = {
+ original: cmd,
+ description,
+ handler,
+ builder: builder || {},
+ middlewares,
+ deprecated,
+ demanded: parsedCommand.demanded,
+ optional: parsedCommand.optional
+ };
+ if (isDefault)
+ this.defaultCommand = this.handlers[parsedCommand.cmd];
+ }
+ }
+ getCommandHandlers() {
+ return this.handlers;
+ }
+ getCommands() {
+ return Object.keys(this.handlers).concat(Object.keys(this.aliasMap));
+ }
+ hasDefaultCommand() {
+ return !!this.defaultCommand;
+ }
+ runCommand(command2, yargs, parsed, commandIndex, helpOnly, helpOrVersionSet) {
+ const commandHandler = this.handlers[command2] || this.handlers[this.aliasMap[command2]] || this.defaultCommand;
+ const currentContext = yargs.getInternalMethods().getContext();
+ const parentCommands = currentContext.commands.slice();
+ const isDefaultCommand = !command2;
+ if (command2) {
+ currentContext.commands.push(command2);
+ currentContext.fullCommands.push(commandHandler.original);
+ }
+ const builderResult = this.applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, parsed.aliases, parentCommands, commandIndex, helpOnly, helpOrVersionSet);
+ return isPromise(builderResult) ? builderResult.then((result) => this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, result.innerArgv, currentContext, helpOnly, result.aliases, yargs)) : this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, builderResult.innerArgv, currentContext, helpOnly, builderResult.aliases, yargs);
+ }
+ applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, aliases2, parentCommands, commandIndex, helpOnly, helpOrVersionSet) {
+ const builder = commandHandler.builder;
+ let innerYargs = yargs;
+ if (isCommandBuilderCallback(builder)) {
+ yargs.getInternalMethods().getUsageInstance().freeze();
+ const builderOutput = builder(yargs.getInternalMethods().reset(aliases2), helpOrVersionSet);
+ if (isPromise(builderOutput)) {
+ return builderOutput.then((output) => {
+ innerYargs = isYargsInstance(output) ? output : yargs;
+ return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly);
+ });
+ }
+ } else if (isCommandBuilderOptionDefinitions(builder)) {
+ yargs.getInternalMethods().getUsageInstance().freeze();
+ innerYargs = yargs.getInternalMethods().reset(aliases2);
+ Object.keys(commandHandler.builder).forEach((key) => {
+ innerYargs.option(key, builder[key]);
+ });
+ }
+ return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly);
+ }
+ parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly) {
+ if (isDefaultCommand)
+ innerYargs.getInternalMethods().getUsageInstance().unfreeze(true);
+ if (this.shouldUpdateUsage(innerYargs)) {
+ innerYargs.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(parentCommands, commandHandler), commandHandler.description);
+ }
+ const innerArgv = innerYargs.getInternalMethods().runYargsParserAndExecuteCommands(null, void 0, true, commandIndex, helpOnly);
+ return isPromise(innerArgv) ? innerArgv.then((argv) => ({
+ aliases: innerYargs.parsed.aliases,
+ innerArgv: argv
+ })) : {
+ aliases: innerYargs.parsed.aliases,
+ innerArgv
+ };
+ }
+ shouldUpdateUsage(yargs) {
+ return !yargs.getInternalMethods().getUsageInstance().getUsageDisabled() && yargs.getInternalMethods().getUsageInstance().getUsage().length === 0;
+ }
+ usageFromParentCommandsCommandHandler(parentCommands, commandHandler) {
+ const c = DEFAULT_MARKER.test(commandHandler.original) ? commandHandler.original.replace(DEFAULT_MARKER, "").trim() : commandHandler.original;
+ const pc = parentCommands.filter((c2) => {
+ return !DEFAULT_MARKER.test(c2);
+ });
+ pc.push(c);
+ return `$0 ${pc.join(" ")}`;
+ }
+ handleValidationAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, aliases2, yargs, middlewares, positionalMap) {
+ if (!yargs.getInternalMethods().getHasOutput()) {
+ const validation2 = yargs.getInternalMethods().runValidation(aliases2, positionalMap, yargs.parsed.error, isDefaultCommand);
+ innerArgv = maybeAsyncResult(innerArgv, (result) => {
+ validation2(result);
+ return result;
+ });
+ }
+ if (commandHandler.handler && !yargs.getInternalMethods().getHasOutput()) {
+ yargs.getInternalMethods().setHasOutput();
+ const populateDoubleDash = !!yargs.getOptions().configuration["populate--"];
+ yargs.getInternalMethods().postProcess(innerArgv, populateDoubleDash, false, false);
+ innerArgv = applyMiddleware(innerArgv, yargs, middlewares, false);
+ innerArgv = maybeAsyncResult(innerArgv, (result) => {
+ const handlerResult = commandHandler.handler(result);
+ return isPromise(handlerResult) ? handlerResult.then(() => result) : result;
+ });
+ if (!isDefaultCommand) {
+ yargs.getInternalMethods().getUsageInstance().cacheHelpMessage();
+ }
+ if (isPromise(innerArgv) && !yargs.getInternalMethods().hasParseCallback()) {
+ innerArgv.catch((error51) => {
+ try {
+ yargs.getInternalMethods().getUsageInstance().fail(null, error51);
+ } catch (_err) {
+ }
+ });
+ }
+ }
+ if (!isDefaultCommand) {
+ currentContext.commands.pop();
+ currentContext.fullCommands.pop();
+ }
+ return innerArgv;
+ }
+ applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, helpOnly, aliases2, yargs) {
+ let positionalMap = {};
+ if (helpOnly)
+ return innerArgv;
+ if (!yargs.getInternalMethods().getHasOutput()) {
+ positionalMap = this.populatePositionals(commandHandler, innerArgv, currentContext, yargs);
+ }
+ const middlewares = this.globalMiddleware.getMiddleware().slice(0).concat(commandHandler.middlewares);
+ const maybePromiseArgv = applyMiddleware(innerArgv, yargs, middlewares, true);
+ return isPromise(maybePromiseArgv) ? maybePromiseArgv.then((resolvedInnerArgv) => this.handleValidationAndGetResult(isDefaultCommand, commandHandler, resolvedInnerArgv, currentContext, aliases2, yargs, middlewares, positionalMap)) : this.handleValidationAndGetResult(isDefaultCommand, commandHandler, maybePromiseArgv, currentContext, aliases2, yargs, middlewares, positionalMap);
+ }
+ populatePositionals(commandHandler, argv, context, yargs) {
+ argv._ = argv._.slice(context.commands.length);
+ const demanded = commandHandler.demanded.slice(0);
+ const optional2 = commandHandler.optional.slice(0);
+ const positionalMap = {};
+ this.validation.positionalCount(demanded.length, argv._.length);
+ while (demanded.length) {
+ const demand = demanded.shift();
+ this.populatePositional(demand, argv, positionalMap);
+ }
+ while (optional2.length) {
+ const maybe = optional2.shift();
+ this.populatePositional(maybe, argv, positionalMap);
+ }
+ argv._ = context.commands.concat(argv._.map((a) => "" + a));
+ this.postProcessPositionals(argv, positionalMap, this.cmdToParseOptions(commandHandler.original), yargs);
+ return positionalMap;
+ }
+ populatePositional(positional, argv, positionalMap) {
+ const cmd = positional.cmd[0];
+ if (positional.variadic) {
+ positionalMap[cmd] = argv._.splice(0).map(String);
+ } else {
+ if (argv._.length)
+ positionalMap[cmd] = [String(argv._.shift())];
+ }
+ }
+ cmdToParseOptions(cmdString) {
+ const parseOptions = {
+ array: [],
+ default: {},
+ alias: {},
+ demand: {}
+ };
+ const parsed = parseCommand(cmdString);
+ parsed.demanded.forEach((d) => {
+ const [cmd, ...aliases2] = d.cmd;
+ if (d.variadic) {
+ parseOptions.array.push(cmd);
+ parseOptions.default[cmd] = [];
+ }
+ parseOptions.alias[cmd] = aliases2;
+ parseOptions.demand[cmd] = true;
+ });
+ parsed.optional.forEach((o) => {
+ const [cmd, ...aliases2] = o.cmd;
+ if (o.variadic) {
+ parseOptions.array.push(cmd);
+ parseOptions.default[cmd] = [];
+ }
+ parseOptions.alias[cmd] = aliases2;
+ });
+ return parseOptions;
+ }
+ postProcessPositionals(argv, positionalMap, parseOptions, yargs) {
+ const options2 = Object.assign({}, yargs.getOptions());
+ options2.default = Object.assign(parseOptions.default, options2.default);
+ for (const key of Object.keys(parseOptions.alias)) {
+ options2.alias[key] = (options2.alias[key] || []).concat(parseOptions.alias[key]);
+ }
+ options2.array = options2.array.concat(parseOptions.array);
+ options2.config = {};
+ const unparsed = [];
+ Object.keys(positionalMap).forEach((key) => {
+ positionalMap[key].map((value) => {
+ if (options2.configuration["unknown-options-as-args"])
+ options2.key[key] = true;
+ unparsed.push(`--${key}`);
+ unparsed.push(value);
+ });
+ });
+ if (!unparsed.length)
+ return;
+ const config2 = Object.assign({}, options2.configuration, {
+ "populate--": false
+ });
+ const parsed = this.shim.Parser.detailed(unparsed, Object.assign({}, options2, {
+ configuration: config2
+ }));
+ if (parsed.error) {
+ yargs.getInternalMethods().getUsageInstance().fail(parsed.error.message, parsed.error);
+ } else {
+ const positionalKeys = Object.keys(positionalMap);
+ Object.keys(positionalMap).forEach((key) => {
+ positionalKeys.push(...parsed.aliases[key]);
+ });
+ Object.keys(parsed.argv).forEach((key) => {
+ if (positionalKeys.includes(key)) {
+ if (!positionalMap[key])
+ positionalMap[key] = parsed.argv[key];
+ if (!this.isInConfigs(yargs, key) && !this.isDefaulted(yargs, key) && Object.prototype.hasOwnProperty.call(argv, key) && Object.prototype.hasOwnProperty.call(parsed.argv, key) && (Array.isArray(argv[key]) || Array.isArray(parsed.argv[key]))) {
+ argv[key] = [].concat(argv[key], parsed.argv[key]);
+ } else {
+ argv[key] = parsed.argv[key];
+ }
+ }
+ });
+ }
+ }
+ isDefaulted(yargs, key) {
+ const { default: defaults2 } = yargs.getOptions();
+ return Object.prototype.hasOwnProperty.call(defaults2, key) || Object.prototype.hasOwnProperty.call(defaults2, this.shim.Parser.camelCase(key));
+ }
+ isInConfigs(yargs, key) {
+ const { configObjects } = yargs.getOptions();
+ return configObjects.some((c) => Object.prototype.hasOwnProperty.call(c, key)) || configObjects.some((c) => Object.prototype.hasOwnProperty.call(c, this.shim.Parser.camelCase(key)));
+ }
+ runDefaultBuilderOn(yargs) {
+ if (!this.defaultCommand)
+ return;
+ if (this.shouldUpdateUsage(yargs)) {
+ const commandString = DEFAULT_MARKER.test(this.defaultCommand.original) ? this.defaultCommand.original : this.defaultCommand.original.replace(/^[^[\]<>]*/, "$0 ");
+ yargs.getInternalMethods().getUsageInstance().usage(commandString, this.defaultCommand.description);
+ }
+ const builder = this.defaultCommand.builder;
+ if (isCommandBuilderCallback(builder)) {
+ return builder(yargs, true);
+ } else if (!isCommandBuilderDefinition(builder)) {
+ Object.keys(builder).forEach((key) => {
+ yargs.option(key, builder[key]);
+ });
+ }
+ return void 0;
+ }
+ extractDesc({ describe: describe3, description, desc }) {
+ for (const test of [describe3, description, desc]) {
+ if (typeof test === "string" || test === false)
+ return test;
+ assertNotStrictEqual(test, true, this.shim);
+ }
+ return false;
+ }
+ freeze() {
+ this.frozens.push({
+ handlers: this.handlers,
+ aliasMap: this.aliasMap,
+ defaultCommand: this.defaultCommand
+ });
+ }
+ unfreeze() {
+ const frozen = this.frozens.pop();
+ assertNotStrictEqual(frozen, void 0, this.shim);
+ ({
+ handlers: this.handlers,
+ aliasMap: this.aliasMap,
+ defaultCommand: this.defaultCommand
+ } = frozen);
+ }
+ reset() {
+ this.handlers = {};
+ this.aliasMap = {};
+ this.defaultCommand = void 0;
+ this.requireCache = /* @__PURE__ */ new Set();
+ return this;
+ }
+};
+function command(usage2, validation2, globalMiddleware, shim3) {
+ return new CommandInstance(usage2, validation2, globalMiddleware, shim3);
+}
+__name(command, "command");
+function isCommandBuilderDefinition(builder) {
+ return typeof builder === "object" && !!builder.builder && typeof builder.handler === "function";
+}
+__name(isCommandBuilderDefinition, "isCommandBuilderDefinition");
+function isCommandAndAliases(cmd) {
+ return cmd.every((c) => typeof c === "string");
+}
+__name(isCommandAndAliases, "isCommandAndAliases");
+function isCommandBuilderCallback(builder) {
+ return typeof builder === "function";
+}
+__name(isCommandBuilderCallback, "isCommandBuilderCallback");
+function isCommandBuilderOptionDefinitions(builder) {
+ return typeof builder === "object";
+}
+__name(isCommandBuilderOptionDefinitions, "isCommandBuilderOptionDefinitions");
+function isCommandHandlerDefinition(cmd) {
+ return typeof cmd === "object" && !Array.isArray(cmd);
+}
+__name(isCommandHandlerDefinition, "isCommandHandlerDefinition");
+
+// node_modules/yargs/build/lib/usage.js
+init_esbuild_shims();
+
+// node_modules/yargs/build/lib/utils/obj-filter.js
+init_esbuild_shims();
+function objFilter(original = {}, filter = () => true) {
+ const obj = {};
+ objectKeys(original).forEach((key) => {
+ if (filter(key, original[key])) {
+ obj[key] = original[key];
+ }
+ });
+ return obj;
+}
+__name(objFilter, "objFilter");
+
+// node_modules/yargs/build/lib/utils/set-blocking.js
+init_esbuild_shims();
+function setBlocking(blocking) {
+ if (typeof process === "undefined")
+ return;
+ [process.stdout, process.stderr].forEach((_stream) => {
+ const stream = _stream;
+ if (stream._handle && stream.isTTY && typeof stream._handle.setBlocking === "function") {
+ stream._handle.setBlocking(blocking);
+ }
+ });
+}
+__name(setBlocking, "setBlocking");
+
+// node_modules/yargs/build/lib/usage.js
+function isBoolean(fail) {
+ return typeof fail === "boolean";
+}
+__name(isBoolean, "isBoolean");
+function usage(yargs, shim3) {
+ const __ = shim3.y18n.__;
+ const self2 = {};
+ const fails = [];
+ self2.failFn = /* @__PURE__ */ __name(function failFn(f) {
+ fails.push(f);
+ }, "failFn");
+ let failMessage = null;
+ let globalFailMessage = null;
+ let showHelpOnFail = true;
+ self2.showHelpOnFail = /* @__PURE__ */ __name(function showHelpOnFailFn(arg1 = true, arg2) {
+ const [enabled, message] = typeof arg1 === "string" ? [true, arg1] : [arg1, arg2];
+ if (yargs.getInternalMethods().isGlobalContext()) {
+ globalFailMessage = message;
+ }
+ failMessage = message;
+ showHelpOnFail = enabled;
+ return self2;
+ }, "showHelpOnFailFn");
+ let failureOutput = false;
+ self2.fail = /* @__PURE__ */ __name(function fail(msg, err) {
+ const logger = yargs.getInternalMethods().getLoggerInstance();
+ if (fails.length) {
+ for (let i = fails.length - 1; i >= 0; --i) {
+ const fail2 = fails[i];
+ if (isBoolean(fail2)) {
+ if (err)
+ throw err;
+ else if (msg)
+ throw Error(msg);
+ } else {
+ fail2(msg, err, self2);
+ }
+ }
+ } else {
+ if (yargs.getExitProcess())
+ setBlocking(true);
+ if (!failureOutput) {
+ failureOutput = true;
+ if (showHelpOnFail) {
+ yargs.showHelp("error");
+ logger.error();
+ }
+ if (msg || err)
+ logger.error(msg || err);
+ const globalOrCommandFailMessage = failMessage || globalFailMessage;
+ if (globalOrCommandFailMessage) {
+ if (msg || err)
+ logger.error("");
+ logger.error(globalOrCommandFailMessage);
+ }
+ }
+ err = err || new YError(msg);
+ if (yargs.getExitProcess()) {
+ return yargs.exit(1);
+ } else if (yargs.getInternalMethods().hasParseCallback()) {
+ return yargs.exit(1, err);
+ } else {
+ throw err;
+ }
+ }
+ }, "fail");
+ let usages = [];
+ let usageDisabled = false;
+ self2.usage = (msg, description) => {
+ if (msg === null) {
+ usageDisabled = true;
+ usages = [];
+ return self2;
+ }
+ usageDisabled = false;
+ usages.push([msg, description || ""]);
+ return self2;
+ };
+ self2.getUsage = () => {
+ return usages;
+ };
+ self2.getUsageDisabled = () => {
+ return usageDisabled;
+ };
+ self2.getPositionalGroupName = () => {
+ return __("Positionals:");
+ };
+ let examples = [];
+ self2.example = (cmd, description) => {
+ examples.push([cmd, description || ""]);
+ };
+ let commands = [];
+ self2.command = /* @__PURE__ */ __name(function command2(cmd, description, isDefault, aliases2, deprecated = false) {
+ if (isDefault) {
+ commands = commands.map((cmdArray) => {
+ cmdArray[2] = false;
+ return cmdArray;
+ });
+ }
+ commands.push([cmd, description || "", isDefault, aliases2, deprecated]);
+ }, "command");
+ self2.getCommands = () => commands;
+ let descriptions = {};
+ self2.describe = /* @__PURE__ */ __name(function describe3(keyOrKeys, desc) {
+ if (Array.isArray(keyOrKeys)) {
+ keyOrKeys.forEach((k) => {
+ self2.describe(k, desc);
+ });
+ } else if (typeof keyOrKeys === "object") {
+ Object.keys(keyOrKeys).forEach((k) => {
+ self2.describe(k, keyOrKeys[k]);
+ });
+ } else {
+ descriptions[keyOrKeys] = desc;
+ }
+ }, "describe");
+ self2.getDescriptions = () => descriptions;
+ let epilogs = [];
+ self2.epilog = (msg) => {
+ epilogs.push(msg);
+ };
+ let wrapSet = false;
+ let wrap2;
+ self2.wrap = (cols) => {
+ wrapSet = true;
+ wrap2 = cols;
+ };
+ self2.getWrap = () => {
+ if (shim3.getEnv("YARGS_DISABLE_WRAP")) {
+ return null;
+ }
+ if (!wrapSet) {
+ wrap2 = windowWidth();
+ wrapSet = true;
+ }
+ return wrap2;
+ };
+ const deferY18nLookupPrefix = "__yargsString__:";
+ self2.deferY18nLookup = (str3) => deferY18nLookupPrefix + str3;
+ self2.help = /* @__PURE__ */ __name(function help() {
+ if (cachedHelpMessage)
+ return cachedHelpMessage;
+ normalizeAliases();
+ const base$0 = yargs.customScriptName ? yargs.$0 : shim3.path.basename(yargs.$0);
+ const demandedOptions = yargs.getDemandedOptions();
+ const demandedCommands = yargs.getDemandedCommands();
+ const deprecatedOptions = yargs.getDeprecatedOptions();
+ const groups = yargs.getGroups();
+ const options2 = yargs.getOptions();
+ let keys = [];
+ keys = keys.concat(Object.keys(descriptions));
+ keys = keys.concat(Object.keys(demandedOptions));
+ keys = keys.concat(Object.keys(demandedCommands));
+ keys = keys.concat(Object.keys(options2.default));
+ keys = keys.filter(filterHiddenOptions);
+ keys = Object.keys(keys.reduce((acc, key) => {
+ if (key !== "_")
+ acc[key] = true;
+ return acc;
+ }, {}));
+ const theWrap = self2.getWrap();
+ const ui2 = shim3.cliui({
+ width: theWrap,
+ wrap: !!theWrap
+ });
+ if (!usageDisabled) {
+ if (usages.length) {
+ usages.forEach((usage2) => {
+ ui2.div({ text: `${usage2[0].replace(/\$0/g, base$0)}` });
+ if (usage2[1]) {
+ ui2.div({ text: `${usage2[1]}`, padding: [1, 0, 0, 0] });
+ }
+ });
+ ui2.div();
+ } else if (commands.length) {
+ let u = null;
+ if (demandedCommands._) {
+ u = `${base$0} <${__("command")}>
+`;
+ } else {
+ u = `${base$0} [${__("command")}]
+`;
+ }
+ ui2.div(`${u}`);
+ }
+ }
+ if (commands.length > 1 || commands.length === 1 && !commands[0][2]) {
+ ui2.div(__("Commands:"));
+ const context = yargs.getInternalMethods().getContext();
+ const parentCommands = context.commands.length ? `${context.commands.join(" ")} ` : "";
+ if (yargs.getInternalMethods().getParserConfiguration()["sort-commands"] === true) {
+ commands = commands.sort((a, b) => a[0].localeCompare(b[0]));
+ }
+ const prefix = base$0 ? `${base$0} ` : "";
+ commands.forEach((command2) => {
+ const commandString = `${prefix}${parentCommands}${command2[0].replace(/^\$0 ?/, "")}`;
+ ui2.span({
+ text: commandString,
+ padding: [0, 2, 0, 2],
+ width: maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4
+ }, { text: command2[1] });
+ const hints = [];
+ if (command2[2])
+ hints.push(`[${__("default")}]`);
+ if (command2[3] && command2[3].length) {
+ hints.push(`[${__("aliases:")} ${command2[3].join(", ")}]`);
+ }
+ if (command2[4]) {
+ if (typeof command2[4] === "string") {
+ hints.push(`[${__("deprecated: %s", command2[4])}]`);
+ } else {
+ hints.push(`[${__("deprecated")}]`);
+ }
+ }
+ if (hints.length) {
+ ui2.div({
+ text: hints.join(" "),
+ padding: [0, 0, 0, 2],
+ align: "right"
+ });
+ } else {
+ ui2.div();
+ }
+ });
+ ui2.div();
+ }
+ const aliasKeys = (Object.keys(options2.alias) || []).concat(Object.keys(yargs.parsed.newAliases) || []);
+ keys = keys.filter((key) => !yargs.parsed.newAliases[key] && aliasKeys.every((alias) => (options2.alias[alias] || []).indexOf(key) === -1));
+ const defaultGroup = __("Options:");
+ if (!groups[defaultGroup])
+ groups[defaultGroup] = [];
+ addUngroupedKeys(keys, options2.alias, groups, defaultGroup);
+ const isLongSwitch = /* @__PURE__ */ __name((sw) => /^--/.test(getText(sw)), "isLongSwitch");
+ const displayedGroups = Object.keys(groups).filter((groupName) => groups[groupName].length > 0).map((groupName) => {
+ const normalizedKeys = groups[groupName].filter(filterHiddenOptions).map((key) => {
+ if (aliasKeys.includes(key))
+ return key;
+ for (let i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== void 0; i++) {
+ if ((options2.alias[aliasKey] || []).includes(key))
+ return aliasKey;
+ }
+ return key;
+ });
+ return { groupName, normalizedKeys };
+ }).filter(({ normalizedKeys }) => normalizedKeys.length > 0).map(({ groupName, normalizedKeys }) => {
+ const switches = normalizedKeys.reduce((acc, key) => {
+ acc[key] = [key].concat(options2.alias[key] || []).map((sw) => {
+ if (groupName === self2.getPositionalGroupName())
+ return sw;
+ else {
+ return (/^[0-9]$/.test(sw) ? options2.boolean.includes(key) ? "-" : "--" : sw.length > 1 ? "--" : "-") + sw;
+ }
+ }).sort((sw1, sw2) => isLongSwitch(sw1) === isLongSwitch(sw2) ? 0 : isLongSwitch(sw1) ? 1 : -1).join(", ");
+ return acc;
+ }, {});
+ return { groupName, normalizedKeys, switches };
+ });
+ const shortSwitchesUsed = displayedGroups.filter(({ groupName }) => groupName !== self2.getPositionalGroupName()).some(({ normalizedKeys, switches }) => !normalizedKeys.every((key) => isLongSwitch(switches[key])));
+ if (shortSwitchesUsed) {
+ displayedGroups.filter(({ groupName }) => groupName !== self2.getPositionalGroupName()).forEach(({ normalizedKeys, switches }) => {
+ normalizedKeys.forEach((key) => {
+ if (isLongSwitch(switches[key])) {
+ switches[key] = addIndentation(switches[key], "-x, ".length);
+ }
+ });
+ });
+ }
+ displayedGroups.forEach(({ groupName, normalizedKeys, switches }) => {
+ ui2.div(groupName);
+ normalizedKeys.forEach((key) => {
+ const kswitch = switches[key];
+ let desc = descriptions[key] || "";
+ let type2 = null;
+ if (desc.includes(deferY18nLookupPrefix))
+ desc = __(desc.substring(deferY18nLookupPrefix.length));
+ if (options2.boolean.includes(key))
+ type2 = `[${__("boolean")}]`;
+ if (options2.count.includes(key))
+ type2 = `[${__("count")}]`;
+ if (options2.string.includes(key))
+ type2 = `[${__("string")}]`;
+ if (options2.normalize.includes(key))
+ type2 = `[${__("string")}]`;
+ if (options2.array.includes(key))
+ type2 = `[${__("array")}]`;
+ if (options2.number.includes(key))
+ type2 = `[${__("number")}]`;
+ const deprecatedExtra = /* @__PURE__ */ __name((deprecated) => typeof deprecated === "string" ? `[${__("deprecated: %s", deprecated)}]` : `[${__("deprecated")}]`, "deprecatedExtra");
+ const extra = [
+ key in deprecatedOptions ? deprecatedExtra(deprecatedOptions[key]) : null,
+ type2,
+ key in demandedOptions ? `[${__("required")}]` : null,
+ options2.choices && options2.choices[key] ? `[${__("choices:")} ${self2.stringifiedValues(options2.choices[key])}]` : null,
+ defaultString(options2.default[key], options2.defaultDescription[key])
+ ].filter(Boolean).join(" ");
+ ui2.span({
+ text: getText(kswitch),
+ padding: [0, 2, 0, 2 + getIndentation(kswitch)],
+ width: maxWidth(switches, theWrap) + 4
+ }, desc);
+ const shouldHideOptionExtras = yargs.getInternalMethods().getUsageConfiguration()["hide-types"] === true;
+ if (extra && !shouldHideOptionExtras)
+ ui2.div({ text: extra, padding: [0, 0, 0, 2], align: "right" });
+ else
+ ui2.div();
+ });
+ ui2.div();
+ });
+ if (examples.length) {
+ ui2.div(__("Examples:"));
+ examples.forEach((example) => {
+ example[0] = example[0].replace(/\$0/g, base$0);
+ });
+ examples.forEach((example) => {
+ if (example[1] === "") {
+ ui2.div({
+ text: example[0],
+ padding: [0, 2, 0, 2]
+ });
+ } else {
+ ui2.div({
+ text: example[0],
+ padding: [0, 2, 0, 2],
+ width: maxWidth(examples, theWrap) + 4
+ }, {
+ text: example[1]
+ });
+ }
+ });
+ ui2.div();
+ }
+ if (epilogs.length > 0) {
+ const e = epilogs.map((epilog) => epilog.replace(/\$0/g, base$0)).join("\n");
+ ui2.div(`${e}
+`);
+ }
+ return ui2.toString().replace(/\s*$/, "");
+ }, "help");
+ function maxWidth(table, theWrap, modifier) {
+ let width = 0;
+ if (!Array.isArray(table)) {
+ table = Object.values(table).map((v) => [v]);
+ }
+ table.forEach((v) => {
+ width = Math.max(shim3.stringWidth(modifier ? `${modifier} ${getText(v[0])}` : getText(v[0])) + getIndentation(v[0]), width);
+ });
+ if (theWrap)
+ width = Math.min(width, parseInt((theWrap * 0.5).toString(), 10));
+ return width;
+ }
+ __name(maxWidth, "maxWidth");
+ function normalizeAliases() {
+ const demandedOptions = yargs.getDemandedOptions();
+ const options2 = yargs.getOptions();
+ (Object.keys(options2.alias) || []).forEach((key) => {
+ options2.alias[key].forEach((alias) => {
+ if (descriptions[alias])
+ self2.describe(key, descriptions[alias]);
+ if (alias in demandedOptions)
+ yargs.demandOption(key, demandedOptions[alias]);
+ if (options2.boolean.includes(alias))
+ yargs.boolean(key);
+ if (options2.count.includes(alias))
+ yargs.count(key);
+ if (options2.string.includes(alias))
+ yargs.string(key);
+ if (options2.normalize.includes(alias))
+ yargs.normalize(key);
+ if (options2.array.includes(alias))
+ yargs.array(key);
+ if (options2.number.includes(alias))
+ yargs.number(key);
+ });
+ });
+ }
+ __name(normalizeAliases, "normalizeAliases");
+ let cachedHelpMessage;
+ self2.cacheHelpMessage = function() {
+ cachedHelpMessage = this.help();
+ };
+ self2.clearCachedHelpMessage = function() {
+ cachedHelpMessage = void 0;
+ };
+ self2.hasCachedHelpMessage = function() {
+ return !!cachedHelpMessage;
+ };
+ function addUngroupedKeys(keys, aliases2, groups, defaultGroup) {
+ let groupedKeys = [];
+ let toCheck = null;
+ Object.keys(groups).forEach((group) => {
+ groupedKeys = groupedKeys.concat(groups[group]);
+ });
+ keys.forEach((key) => {
+ toCheck = [key].concat(aliases2[key]);
+ if (!toCheck.some((k) => groupedKeys.indexOf(k) !== -1)) {
+ groups[defaultGroup].push(key);
+ }
+ });
+ return groupedKeys;
+ }
+ __name(addUngroupedKeys, "addUngroupedKeys");
+ function filterHiddenOptions(key) {
+ return yargs.getOptions().hiddenOptions.indexOf(key) < 0 || yargs.parsed.argv[yargs.getOptions().showHiddenOpt];
+ }
+ __name(filterHiddenOptions, "filterHiddenOptions");
+ self2.showHelp = (level) => {
+ const logger = yargs.getInternalMethods().getLoggerInstance();
+ if (!level)
+ level = "error";
+ const emit = typeof level === "function" ? level : logger[level];
+ emit(self2.help());
+ };
+ self2.functionDescription = (fn) => {
+ const description = fn.name ? shim3.Parser.decamelize(fn.name, "-") : __("generated-value");
+ return ["(", description, ")"].join("");
+ };
+ self2.stringifiedValues = /* @__PURE__ */ __name(function stringifiedValues(values, separator) {
+ let string4 = "";
+ const sep7 = separator || ", ";
+ const array2 = [].concat(values);
+ if (!values || !array2.length)
+ return string4;
+ array2.forEach((value) => {
+ if (string4.length)
+ string4 += sep7;
+ string4 += JSON.stringify(value);
+ });
+ return string4;
+ }, "stringifiedValues");
+ function defaultString(value, defaultDescription) {
+ let string4 = `[${__("default:")} `;
+ if (value === void 0 && !defaultDescription)
+ return null;
+ if (defaultDescription) {
+ string4 += defaultDescription;
+ } else {
+ switch (typeof value) {
+ case "string":
+ string4 += `"${value}"`;
+ break;
+ case "object":
+ string4 += JSON.stringify(value);
+ break;
+ default:
+ string4 += value;
+ }
+ }
+ return `${string4}]`;
+ }
+ __name(defaultString, "defaultString");
+ function windowWidth() {
+ const maxWidth2 = 80;
+ if (shim3.process.stdColumns) {
+ return Math.min(maxWidth2, shim3.process.stdColumns);
+ } else {
+ return maxWidth2;
+ }
+ }
+ __name(windowWidth, "windowWidth");
+ let version2 = null;
+ self2.version = (ver) => {
+ version2 = ver;
+ };
+ self2.showVersion = (level) => {
+ const logger = yargs.getInternalMethods().getLoggerInstance();
+ if (!level)
+ level = "error";
+ const emit = typeof level === "function" ? level : logger[level];
+ emit(version2);
+ };
+ self2.reset = /* @__PURE__ */ __name(function reset2(localLookup) {
+ failMessage = null;
+ failureOutput = false;
+ usages = [];
+ usageDisabled = false;
+ epilogs = [];
+ examples = [];
+ commands = [];
+ descriptions = objFilter(descriptions, (k) => !localLookup[k]);
+ return self2;
+ }, "reset");
+ const frozens = [];
+ self2.freeze = /* @__PURE__ */ __name(function freeze() {
+ frozens.push({
+ failMessage,
+ failureOutput,
+ usages,
+ usageDisabled,
+ epilogs,
+ examples,
+ commands,
+ descriptions
+ });
+ }, "freeze");
+ self2.unfreeze = /* @__PURE__ */ __name(function unfreeze(defaultCommand = false) {
+ const frozen = frozens.pop();
+ if (!frozen)
+ return;
+ if (defaultCommand) {
+ descriptions = { ...frozen.descriptions, ...descriptions };
+ commands = [...frozen.commands, ...commands];
+ usages = [...frozen.usages, ...usages];
+ examples = [...frozen.examples, ...examples];
+ epilogs = [...frozen.epilogs, ...epilogs];
+ } else {
+ ({
+ failMessage,
+ failureOutput,
+ usages,
+ usageDisabled,
+ epilogs,
+ examples,
+ commands,
+ descriptions
+ } = frozen);
+ }
+ }, "unfreeze");
+ return self2;
+}
+__name(usage, "usage");
+function isIndentedText(text) {
+ return typeof text === "object";
+}
+__name(isIndentedText, "isIndentedText");
+function addIndentation(text, indent) {
+ return isIndentedText(text) ? { text: text.text, indentation: text.indentation + indent } : { text, indentation: indent };
+}
+__name(addIndentation, "addIndentation");
+function getIndentation(text) {
+ return isIndentedText(text) ? text.indentation : 0;
+}
+__name(getIndentation, "getIndentation");
+function getText(text) {
+ return isIndentedText(text) ? text.text : text;
+}
+__name(getText, "getText");
+
+// node_modules/yargs/build/lib/completion.js
+init_esbuild_shims();
+
+// node_modules/yargs/build/lib/completion-templates.js
+init_esbuild_shims();
+var completionShTemplate = `###-begin-{{app_name}}-completions-###
+#
+# yargs command completion script
+#
+# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc
+# or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX.
+#
+_{{app_name}}_yargs_completions()
+{
+ local cur_word args type_list
+
+ cur_word="\${COMP_WORDS[COMP_CWORD]}"
+ args=("\${COMP_WORDS[@]}")
+
+ # ask yargs to generate completions.
+ # see https://stackoverflow.com/a/40944195/7080036 for the spaces-handling awk
+ mapfile -t type_list < <({{app_path}} --get-yargs-completions "\${args[@]}")
+ mapfile -t COMPREPLY < <(compgen -W "$( printf '%q ' "\${type_list[@]}" )" -- "\${cur_word}" |
+ awk '/ / { print "\\""$0"\\"" } /^[^ ]+$/ { print $0 }')
+
+ # if no match was found, fall back to filename completion
+ if [ \${#COMPREPLY[@]} -eq 0 ]; then
+ COMPREPLY=()
+ fi
+
+ return 0
+}
+complete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name}}
+###-end-{{app_name}}-completions-###
+`;
+var completionZshTemplate = `#compdef {{app_name}}
+###-begin-{{app_name}}-completions-###
+#
+# yargs command completion script
+#
+# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc
+# or {{app_path}} {{completion_command}} >> ~/.zprofile on OSX.
+#
+_{{app_name}}_yargs_completions()
+{
+ local reply
+ local si=$IFS
+ IFS=$'
+' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "\${words[@]}"))
+ IFS=$si
+ if [[ \${#reply} -gt 0 ]]; then
+ _describe 'values' reply
+ else
+ _default
+ fi
+}
+if [[ "'\${zsh_eval_context[-1]}" == "loadautofunc" ]]; then
+ _{{app_name}}_yargs_completions "$@"
+else
+ compdef _{{app_name}}_yargs_completions {{app_name}}
+fi
+###-end-{{app_name}}-completions-###
+`;
+
+// node_modules/yargs/build/lib/completion.js
+var Completion = class {
+ static {
+ __name(this, "Completion");
+ }
+ constructor(yargs, usage2, command2, shim3) {
+ var _a6, _b2, _c2;
+ this.yargs = yargs;
+ this.usage = usage2;
+ this.command = command2;
+ this.shim = shim3;
+ this.completionKey = "get-yargs-completions";
+ this.aliases = null;
+ this.customCompletionFunction = null;
+ this.indexAfterLastReset = 0;
+ this.zshShell = (_c2 = ((_a6 = this.shim.getEnv("SHELL")) === null || _a6 === void 0 ? void 0 : _a6.includes("zsh")) || ((_b2 = this.shim.getEnv("ZSH_NAME")) === null || _b2 === void 0 ? void 0 : _b2.includes("zsh"))) !== null && _c2 !== void 0 ? _c2 : false;
+ }
+ defaultCompletion(args, argv, current, done) {
+ const handlers = this.command.getCommandHandlers();
+ for (let i = 0, ii = args.length; i < ii; ++i) {
+ if (handlers[args[i]] && handlers[args[i]].builder) {
+ const builder = handlers[args[i]].builder;
+ if (isCommandBuilderCallback(builder)) {
+ this.indexAfterLastReset = i + 1;
+ const y = this.yargs.getInternalMethods().reset();
+ builder(y, true);
+ return y.argv;
+ }
+ }
+ }
+ const completions = [];
+ this.commandCompletions(completions, args, current);
+ this.optionCompletions(completions, args, argv, current);
+ this.choicesFromOptionsCompletions(completions, args, argv, current);
+ this.choicesFromPositionalsCompletions(completions, args, argv, current);
+ done(null, completions);
+ }
+ commandCompletions(completions, args, current) {
+ const parentCommands = this.yargs.getInternalMethods().getContext().commands;
+ if (!current.match(/^-/) && parentCommands[parentCommands.length - 1] !== current && !this.previousArgHasChoices(args)) {
+ this.usage.getCommands().forEach((usageCommand) => {
+ const commandName = parseCommand(usageCommand[0]).cmd;
+ if (args.indexOf(commandName) === -1) {
+ if (!this.zshShell) {
+ completions.push(commandName);
+ } else {
+ const desc = usageCommand[1] || "";
+ completions.push(commandName.replace(/:/g, "\\:") + ":" + desc);
+ }
+ }
+ });
+ }
+ }
+ optionCompletions(completions, args, argv, current) {
+ if ((current.match(/^-/) || current === "" && completions.length === 0) && !this.previousArgHasChoices(args)) {
+ const options2 = this.yargs.getOptions();
+ const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || [];
+ Object.keys(options2.key).forEach((key) => {
+ const negable = !!options2.configuration["boolean-negation"] && options2.boolean.includes(key);
+ const isPositionalKey = positionalKeys.includes(key);
+ if (!isPositionalKey && !options2.hiddenOptions.includes(key) && !this.argsContainKey(args, key, negable)) {
+ this.completeOptionKey(key, completions, current, negable && !!options2.default[key]);
+ }
+ });
+ }
+ }
+ choicesFromOptionsCompletions(completions, args, argv, current) {
+ if (this.previousArgHasChoices(args)) {
+ const choices = this.getPreviousArgChoices(args);
+ if (choices && choices.length > 0) {
+ completions.push(...choices.map((c) => c.replace(/:/g, "\\:")));
+ }
+ }
+ }
+ choicesFromPositionalsCompletions(completions, args, argv, current) {
+ if (current === "" && completions.length > 0 && this.previousArgHasChoices(args)) {
+ return;
+ }
+ const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || [];
+ const offset = Math.max(this.indexAfterLastReset, this.yargs.getInternalMethods().getContext().commands.length + 1);
+ const positionalKey = positionalKeys[argv._.length - offset - 1];
+ if (!positionalKey) {
+ return;
+ }
+ const choices = this.yargs.getOptions().choices[positionalKey] || [];
+ for (const choice of choices) {
+ if (choice.startsWith(current)) {
+ completions.push(choice.replace(/:/g, "\\:"));
+ }
+ }
+ }
+ getPreviousArgChoices(args) {
+ if (args.length < 1)
+ return;
+ let previousArg = args[args.length - 1];
+ let filter = "";
+ if (!previousArg.startsWith("-") && args.length > 1) {
+ filter = previousArg;
+ previousArg = args[args.length - 2];
+ }
+ if (!previousArg.startsWith("-"))
+ return;
+ const previousArgKey = previousArg.replace(/^-+/, "");
+ const options2 = this.yargs.getOptions();
+ const possibleAliases = [
+ previousArgKey,
+ ...this.yargs.getAliases()[previousArgKey] || []
+ ];
+ let choices;
+ for (const possibleAlias of possibleAliases) {
+ if (Object.prototype.hasOwnProperty.call(options2.key, possibleAlias) && Array.isArray(options2.choices[possibleAlias])) {
+ choices = options2.choices[possibleAlias];
+ break;
+ }
+ }
+ if (choices) {
+ return choices.filter((choice) => !filter || choice.startsWith(filter));
+ }
+ }
+ previousArgHasChoices(args) {
+ const choices = this.getPreviousArgChoices(args);
+ return choices !== void 0 && choices.length > 0;
+ }
+ argsContainKey(args, key, negable) {
+ const argsContains = /* @__PURE__ */ __name((s) => args.indexOf((/^[^0-9]$/.test(s) ? "-" : "--") + s) !== -1, "argsContains");
+ if (argsContains(key))
+ return true;
+ if (negable && argsContains(`no-${key}`))
+ return true;
+ if (this.aliases) {
+ for (const alias of this.aliases[key]) {
+ if (argsContains(alias))
+ return true;
+ }
+ }
+ return false;
+ }
+ completeOptionKey(key, completions, current, negable) {
+ var _a6, _b2, _c2, _d;
+ let keyWithDesc = key;
+ if (this.zshShell) {
+ const descs = this.usage.getDescriptions();
+ const aliasKey = (_b2 = (_a6 = this === null || this === void 0 ? void 0 : this.aliases) === null || _a6 === void 0 ? void 0 : _a6[key]) === null || _b2 === void 0 ? void 0 : _b2.find((alias) => {
+ const desc2 = descs[alias];
+ return typeof desc2 === "string" && desc2.length > 0;
+ });
+ const descFromAlias = aliasKey ? descs[aliasKey] : void 0;
+ const desc = (_d = (_c2 = descs[key]) !== null && _c2 !== void 0 ? _c2 : descFromAlias) !== null && _d !== void 0 ? _d : "";
+ keyWithDesc = `${key.replace(/:/g, "\\:")}:${desc.replace("__yargsString__:", "").replace(/(\r\n|\n|\r)/gm, " ")}`;
+ }
+ const startsByTwoDashes = /* @__PURE__ */ __name((s) => /^--/.test(s), "startsByTwoDashes");
+ const isShortOption = /* @__PURE__ */ __name((s) => /^[^0-9]$/.test(s), "isShortOption");
+ const dashes = !startsByTwoDashes(current) && isShortOption(key) ? "-" : "--";
+ completions.push(dashes + keyWithDesc);
+ if (negable) {
+ completions.push(dashes + "no-" + keyWithDesc);
+ }
+ }
+ customCompletion(args, argv, current, done) {
+ assertNotStrictEqual(this.customCompletionFunction, null, this.shim);
+ if (isSyncCompletionFunction(this.customCompletionFunction)) {
+ const result = this.customCompletionFunction(current, argv);
+ if (isPromise(result)) {
+ return result.then((list) => {
+ this.shim.process.nextTick(() => {
+ done(null, list);
+ });
+ }).catch((err) => {
+ this.shim.process.nextTick(() => {
+ done(err, void 0);
+ });
+ });
+ }
+ return done(null, result);
+ } else if (isFallbackCompletionFunction(this.customCompletionFunction)) {
+ return this.customCompletionFunction(current, argv, (onCompleted = done) => this.defaultCompletion(args, argv, current, onCompleted), (completions) => {
+ done(null, completions);
+ });
+ } else {
+ return this.customCompletionFunction(current, argv, (completions) => {
+ done(null, completions);
+ });
+ }
+ }
+ getCompletion(args, done) {
+ const current = args.length ? args[args.length - 1] : "";
+ const argv = this.yargs.parse(args, true);
+ const completionFunction = this.customCompletionFunction ? (argv2) => this.customCompletion(args, argv2, current, done) : (argv2) => this.defaultCompletion(args, argv2, current, done);
+ return isPromise(argv) ? argv.then(completionFunction) : completionFunction(argv);
+ }
+ generateCompletionScript($0, cmd) {
+ let script = this.zshShell ? completionZshTemplate : completionShTemplate;
+ const name = this.shim.path.basename($0);
+ if ($0.match(/\.js$/))
+ $0 = `./${$0}`;
+ script = script.replace(/{{app_name}}/g, name);
+ script = script.replace(/{{completion_command}}/g, cmd);
+ return script.replace(/{{app_path}}/g, $0);
+ }
+ registerFunction(fn) {
+ this.customCompletionFunction = fn;
+ }
+ setParsed(parsed) {
+ this.aliases = parsed.aliases;
+ }
+};
+function completion(yargs, usage2, command2, shim3) {
+ return new Completion(yargs, usage2, command2, shim3);
+}
+__name(completion, "completion");
+function isSyncCompletionFunction(completionFunction) {
+ return completionFunction.length < 3;
+}
+__name(isSyncCompletionFunction, "isSyncCompletionFunction");
+function isFallbackCompletionFunction(completionFunction) {
+ return completionFunction.length > 3;
+}
+__name(isFallbackCompletionFunction, "isFallbackCompletionFunction");
+
+// node_modules/yargs/build/lib/validation.js
+init_esbuild_shims();
+
+// node_modules/yargs/build/lib/utils/levenshtein.js
+init_esbuild_shims();
+function levenshtein(a, b) {
+ if (a.length === 0)
+ return b.length;
+ if (b.length === 0)
+ return a.length;
+ const matrix = [];
+ let i;
+ for (i = 0; i <= b.length; i++) {
+ matrix[i] = [i];
+ }
+ let j;
+ for (j = 0; j <= a.length; j++) {
+ matrix[0][j] = j;
+ }
+ for (i = 1; i <= b.length; i++) {
+ for (j = 1; j <= a.length; j++) {
+ if (b.charAt(i - 1) === a.charAt(j - 1)) {
+ matrix[i][j] = matrix[i - 1][j - 1];
+ } else {
+ if (i > 1 && j > 1 && b.charAt(i - 2) === a.charAt(j - 1) && b.charAt(i - 1) === a.charAt(j - 2)) {
+ matrix[i][j] = matrix[i - 2][j - 2] + 1;
+ } else {
+ matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, Math.min(matrix[i][j - 1] + 1, matrix[i - 1][j] + 1));
+ }
+ }
+ }
+ }
+ return matrix[b.length][a.length];
+}
+__name(levenshtein, "levenshtein");
+
+// node_modules/yargs/build/lib/validation.js
+var specialKeys = ["$0", "--", "_"];
+function validation(yargs, usage2, shim3) {
+ const __ = shim3.y18n.__;
+ const __n = shim3.y18n.__n;
+ const self2 = {};
+ self2.nonOptionCount = /* @__PURE__ */ __name(function nonOptionCount(argv) {
+ const demandedCommands = yargs.getDemandedCommands();
+ const positionalCount = argv._.length + (argv["--"] ? argv["--"].length : 0);
+ const _s = positionalCount - yargs.getInternalMethods().getContext().commands.length;
+ if (demandedCommands._ && (_s < demandedCommands._.min || _s > demandedCommands._.max)) {
+ if (_s < demandedCommands._.min) {
+ if (demandedCommands._.minMsg !== void 0) {
+ usage2.fail(demandedCommands._.minMsg ? demandedCommands._.minMsg.replace(/\$0/g, _s.toString()).replace(/\$1/, demandedCommands._.min.toString()) : null);
+ } else {
+ usage2.fail(__n("Not enough non-option arguments: got %s, need at least %s", "Not enough non-option arguments: got %s, need at least %s", _s, _s.toString(), demandedCommands._.min.toString()));
+ }
+ } else if (_s > demandedCommands._.max) {
+ if (demandedCommands._.maxMsg !== void 0) {
+ usage2.fail(demandedCommands._.maxMsg ? demandedCommands._.maxMsg.replace(/\$0/g, _s.toString()).replace(/\$1/, demandedCommands._.max.toString()) : null);
+ } else {
+ usage2.fail(__n("Too many non-option arguments: got %s, maximum of %s", "Too many non-option arguments: got %s, maximum of %s", _s, _s.toString(), demandedCommands._.max.toString()));
+ }
+ }
+ }
+ }, "nonOptionCount");
+ self2.positionalCount = /* @__PURE__ */ __name(function positionalCount(required2, observed) {
+ if (observed < required2) {
+ usage2.fail(__n("Not enough non-option arguments: got %s, need at least %s", "Not enough non-option arguments: got %s, need at least %s", observed, observed + "", required2 + ""));
+ }
+ }, "positionalCount");
+ self2.requiredArguments = /* @__PURE__ */ __name(function requiredArguments(argv, demandedOptions) {
+ let missing = null;
+ for (const key of Object.keys(demandedOptions)) {
+ if (!Object.prototype.hasOwnProperty.call(argv, key) || typeof argv[key] === "undefined") {
+ missing = missing || {};
+ missing[key] = demandedOptions[key];
+ }
+ }
+ if (missing) {
+ const customMsgs = [];
+ for (const key of Object.keys(missing)) {
+ const msg = missing[key];
+ if (msg && customMsgs.indexOf(msg) < 0) {
+ customMsgs.push(msg);
+ }
+ }
+ const customMsg = customMsgs.length ? `
+${customMsgs.join("\n")}` : "";
+ usage2.fail(__n("Missing required argument: %s", "Missing required arguments: %s", Object.keys(missing).length, Object.keys(missing).join(", ") + customMsg));
+ }
+ }, "requiredArguments");
+ self2.unknownArguments = /* @__PURE__ */ __name(function unknownArguments(argv, aliases2, positionalMap, isDefaultCommand, checkPositionals = true) {
+ var _a6;
+ const commandKeys = yargs.getInternalMethods().getCommandInstance().getCommands();
+ const unknown2 = [];
+ const currentContext = yargs.getInternalMethods().getContext();
+ Object.keys(argv).forEach((key) => {
+ if (!specialKeys.includes(key) && !Object.prototype.hasOwnProperty.call(positionalMap, key) && !Object.prototype.hasOwnProperty.call(yargs.getInternalMethods().getParseContext(), key) && !self2.isValidAndSomeAliasIsNotNew(key, aliases2)) {
+ unknown2.push(key);
+ }
+ });
+ if (checkPositionals && (currentContext.commands.length > 0 || commandKeys.length > 0 || isDefaultCommand)) {
+ argv._.slice(currentContext.commands.length).forEach((key) => {
+ if (!commandKeys.includes("" + key)) {
+ unknown2.push("" + key);
+ }
+ });
+ }
+ if (checkPositionals) {
+ const demandedCommands = yargs.getDemandedCommands();
+ const maxNonOptDemanded = ((_a6 = demandedCommands._) === null || _a6 === void 0 ? void 0 : _a6.max) || 0;
+ const expected = currentContext.commands.length + maxNonOptDemanded;
+ if (expected < argv._.length) {
+ argv._.slice(expected).forEach((key) => {
+ key = String(key);
+ if (!currentContext.commands.includes(key) && !unknown2.includes(key)) {
+ unknown2.push(key);
+ }
+ });
+ }
+ }
+ if (unknown2.length) {
+ usage2.fail(__n("Unknown argument: %s", "Unknown arguments: %s", unknown2.length, unknown2.map((s) => s.trim() ? s : `"${s}"`).join(", ")));
+ }
+ }, "unknownArguments");
+ self2.unknownCommands = /* @__PURE__ */ __name(function unknownCommands(argv) {
+ const commandKeys = yargs.getInternalMethods().getCommandInstance().getCommands();
+ const unknown2 = [];
+ const currentContext = yargs.getInternalMethods().getContext();
+ if (currentContext.commands.length > 0 || commandKeys.length > 0) {
+ argv._.slice(currentContext.commands.length).forEach((key) => {
+ if (!commandKeys.includes("" + key)) {
+ unknown2.push("" + key);
+ }
+ });
+ }
+ if (unknown2.length > 0) {
+ usage2.fail(__n("Unknown command: %s", "Unknown commands: %s", unknown2.length, unknown2.join(", ")));
+ return true;
+ } else {
+ return false;
+ }
+ }, "unknownCommands");
+ self2.isValidAndSomeAliasIsNotNew = /* @__PURE__ */ __name(function isValidAndSomeAliasIsNotNew(key, aliases2) {
+ if (!Object.prototype.hasOwnProperty.call(aliases2, key)) {
+ return false;
+ }
+ const newAliases = yargs.parsed.newAliases;
+ return [key, ...aliases2[key]].some((a) => !Object.prototype.hasOwnProperty.call(newAliases, a) || !newAliases[key]);
+ }, "isValidAndSomeAliasIsNotNew");
+ self2.limitedChoices = /* @__PURE__ */ __name(function limitedChoices(argv) {
+ const options2 = yargs.getOptions();
+ const invalid = {};
+ if (!Object.keys(options2.choices).length)
+ return;
+ Object.keys(argv).forEach((key) => {
+ if (specialKeys.indexOf(key) === -1 && Object.prototype.hasOwnProperty.call(options2.choices, key)) {
+ [].concat(argv[key]).forEach((value) => {
+ if (options2.choices[key].indexOf(value) === -1 && value !== void 0) {
+ invalid[key] = (invalid[key] || []).concat(value);
+ }
+ });
+ }
+ });
+ const invalidKeys = Object.keys(invalid);
+ if (!invalidKeys.length)
+ return;
+ let msg = __("Invalid values:");
+ invalidKeys.forEach((key) => {
+ msg += `
+ ${__("Argument: %s, Given: %s, Choices: %s", key, usage2.stringifiedValues(invalid[key]), usage2.stringifiedValues(options2.choices[key]))}`;
+ });
+ usage2.fail(msg);
+ }, "limitedChoices");
+ let implied = {};
+ self2.implies = /* @__PURE__ */ __name(function implies(key, value) {
+ argsert(" [array|number|string]", [key, value], arguments.length);
+ if (typeof key === "object") {
+ Object.keys(key).forEach((k) => {
+ self2.implies(k, key[k]);
+ });
+ } else {
+ yargs.global(key);
+ if (!implied[key]) {
+ implied[key] = [];
+ }
+ if (Array.isArray(value)) {
+ value.forEach((i) => self2.implies(key, i));
+ } else {
+ assertNotStrictEqual(value, void 0, shim3);
+ implied[key].push(value);
+ }
+ }
+ }, "implies");
+ self2.getImplied = /* @__PURE__ */ __name(function getImplied() {
+ return implied;
+ }, "getImplied");
+ function keyExists(argv, val) {
+ const num = Number(val);
+ val = isNaN(num) ? val : num;
+ if (typeof val === "number") {
+ val = argv._.length >= val;
+ } else if (val.match(/^--no-.+/)) {
+ val = val.match(/^--no-(.+)/)[1];
+ val = !Object.prototype.hasOwnProperty.call(argv, val);
+ } else {
+ val = Object.prototype.hasOwnProperty.call(argv, val);
+ }
+ return val;
+ }
+ __name(keyExists, "keyExists");
+ self2.implications = /* @__PURE__ */ __name(function implications(argv) {
+ const implyFail = [];
+ Object.keys(implied).forEach((key) => {
+ const origKey = key;
+ (implied[key] || []).forEach((value) => {
+ let key2 = origKey;
+ const origValue = value;
+ key2 = keyExists(argv, key2);
+ value = keyExists(argv, value);
+ if (key2 && !value) {
+ implyFail.push(` ${origKey} -> ${origValue}`);
+ }
+ });
+ });
+ if (implyFail.length) {
+ let msg = `${__("Implications failed:")}
+`;
+ implyFail.forEach((value) => {
+ msg += value;
+ });
+ usage2.fail(msg);
+ }
+ }, "implications");
+ let conflicting = {};
+ self2.conflicts = /* @__PURE__ */ __name(function conflicts(key, value) {
+ argsert(" [array|string]", [key, value], arguments.length);
+ if (typeof key === "object") {
+ Object.keys(key).forEach((k) => {
+ self2.conflicts(k, key[k]);
+ });
+ } else {
+ yargs.global(key);
+ if (!conflicting[key]) {
+ conflicting[key] = [];
+ }
+ if (Array.isArray(value)) {
+ value.forEach((i) => self2.conflicts(key, i));
+ } else {
+ conflicting[key].push(value);
+ }
+ }
+ }, "conflicts");
+ self2.getConflicting = () => conflicting;
+ self2.conflicting = /* @__PURE__ */ __name(function conflictingFn(argv) {
+ Object.keys(argv).forEach((key) => {
+ if (conflicting[key]) {
+ conflicting[key].forEach((value) => {
+ if (value && argv[key] !== void 0 && argv[value] !== void 0) {
+ usage2.fail(__("Arguments %s and %s are mutually exclusive", key, value));
+ }
+ });
+ }
+ });
+ if (yargs.getInternalMethods().getParserConfiguration()["strip-dashed"]) {
+ Object.keys(conflicting).forEach((key) => {
+ conflicting[key].forEach((value) => {
+ if (value && argv[shim3.Parser.camelCase(key)] !== void 0 && argv[shim3.Parser.camelCase(value)] !== void 0) {
+ usage2.fail(__("Arguments %s and %s are mutually exclusive", key, value));
+ }
+ });
+ });
+ }
+ }, "conflictingFn");
+ self2.recommendCommands = /* @__PURE__ */ __name(function recommendCommands(cmd, potentialCommands) {
+ const threshold = 3;
+ potentialCommands = potentialCommands.sort((a, b) => b.length - a.length);
+ let recommended = null;
+ let bestDistance = Infinity;
+ for (let i = 0, candidate; (candidate = potentialCommands[i]) !== void 0; i++) {
+ const d = levenshtein(cmd, candidate);
+ if (d <= threshold && d < bestDistance) {
+ bestDistance = d;
+ recommended = candidate;
+ }
+ }
+ if (recommended)
+ usage2.fail(__("Did you mean %s?", recommended));
+ }, "recommendCommands");
+ self2.reset = /* @__PURE__ */ __name(function reset2(localLookup) {
+ implied = objFilter(implied, (k) => !localLookup[k]);
+ conflicting = objFilter(conflicting, (k) => !localLookup[k]);
+ return self2;
+ }, "reset");
+ const frozens = [];
+ self2.freeze = /* @__PURE__ */ __name(function freeze() {
+ frozens.push({
+ implied,
+ conflicting
+ });
+ }, "freeze");
+ self2.unfreeze = /* @__PURE__ */ __name(function unfreeze() {
+ const frozen = frozens.pop();
+ assertNotStrictEqual(frozen, void 0, shim3);
+ ({ implied, conflicting } = frozen);
+ }, "unfreeze");
+ return self2;
+}
+__name(validation, "validation");
+
+// node_modules/yargs/build/lib/utils/apply-extends.js
+init_esbuild_shims();
+var previouslyVisitedConfigs = [];
+var shim2;
+function applyExtends(config2, cwd2, mergeExtends, _shim) {
+ shim2 = _shim;
+ let defaultConfig = {};
+ if (Object.prototype.hasOwnProperty.call(config2, "extends")) {
+ if (typeof config2.extends !== "string")
+ return defaultConfig;
+ const isPath = /\.json|\..*rc$/.test(config2.extends);
+ let pathToDefault = null;
+ if (!isPath) {
+ try {
+ pathToDefault = import.meta.resolve(config2.extends);
+ } catch (_err) {
+ return config2;
+ }
+ } else {
+ pathToDefault = getPathToDefaultConfig(cwd2, config2.extends);
+ }
+ checkForCircularExtends(pathToDefault);
+ previouslyVisitedConfigs.push(pathToDefault);
+ defaultConfig = isPath ? JSON.parse(shim2.readFileSync(pathToDefault, "utf8")) : _shim.require(config2.extends);
+ delete config2.extends;
+ defaultConfig = applyExtends(defaultConfig, shim2.path.dirname(pathToDefault), mergeExtends, shim2);
+ }
+ previouslyVisitedConfigs = [];
+ return mergeExtends ? mergeDeep(defaultConfig, config2) : Object.assign({}, defaultConfig, config2);
+}
+__name(applyExtends, "applyExtends");
+function checkForCircularExtends(cfgPath) {
+ if (previouslyVisitedConfigs.indexOf(cfgPath) > -1) {
+ throw new YError(`Circular extended configurations: '${cfgPath}'.`);
+ }
+}
+__name(checkForCircularExtends, "checkForCircularExtends");
+function getPathToDefaultConfig(cwd2, pathToExtend) {
+ return shim2.path.resolve(cwd2, pathToExtend);
+}
+__name(getPathToDefaultConfig, "getPathToDefaultConfig");
+function mergeDeep(config1, config2) {
+ const target = {};
+ function isObject2(obj) {
+ return obj && typeof obj === "object" && !Array.isArray(obj);
+ }
+ __name(isObject2, "isObject");
+ Object.assign(target, config1);
+ for (const key of Object.keys(config2)) {
+ if (isObject2(config2[key]) && isObject2(target[key])) {
+ target[key] = mergeDeep(config1[key], config2[key]);
+ } else {
+ target[key] = config2[key];
+ }
+ }
+ return target;
+}
+__name(mergeDeep, "mergeDeep");
+
+// node_modules/yargs/build/lib/yargs-factory.js
+var __classPrivateFieldSet2 = function(receiver, state, value, kind, f) {
+ if (kind === "m") throw new TypeError("Private method is not writable");
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
+ return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
+};
+var __classPrivateFieldGet2 = function(receiver, state, kind, f) {
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
+};
+var _YargsInstance_command;
+var _YargsInstance_cwd;
+var _YargsInstance_context;
+var _YargsInstance_completion;
+var _YargsInstance_completionCommand;
+var _YargsInstance_defaultShowHiddenOpt;
+var _YargsInstance_exitError;
+var _YargsInstance_detectLocale;
+var _YargsInstance_emittedWarnings;
+var _YargsInstance_exitProcess;
+var _YargsInstance_frozens;
+var _YargsInstance_globalMiddleware;
+var _YargsInstance_groups;
+var _YargsInstance_hasOutput;
+var _YargsInstance_helpOpt;
+var _YargsInstance_isGlobalContext;
+var _YargsInstance_logger;
+var _YargsInstance_output;
+var _YargsInstance_options;
+var _YargsInstance_parentRequire;
+var _YargsInstance_parserConfig;
+var _YargsInstance_parseFn;
+var _YargsInstance_parseContext;
+var _YargsInstance_pkgs;
+var _YargsInstance_preservedGroups;
+var _YargsInstance_processArgs;
+var _YargsInstance_recommendCommands;
+var _YargsInstance_shim;
+var _YargsInstance_strict;
+var _YargsInstance_strictCommands;
+var _YargsInstance_strictOptions;
+var _YargsInstance_usage;
+var _YargsInstance_usageConfig;
+var _YargsInstance_versionOpt;
+var _YargsInstance_validation;
+function YargsFactory(_shim) {
+ return (processArgs = [], cwd2 = _shim.process.cwd(), parentRequire) => {
+ const yargs = new YargsInstance(processArgs, cwd2, parentRequire, _shim);
+ Object.defineProperty(yargs, "argv", {
+ get: /* @__PURE__ */ __name(() => {
+ return yargs.parse();
+ }, "get"),
+ enumerable: true
+ });
+ yargs.help();
+ yargs.version();
+ return yargs;
+ };
+}
+__name(YargsFactory, "YargsFactory");
+var kCopyDoubleDash = /* @__PURE__ */ Symbol("copyDoubleDash");
+var kCreateLogger = /* @__PURE__ */ Symbol("copyDoubleDash");
+var kDeleteFromParserHintObject = /* @__PURE__ */ Symbol("deleteFromParserHintObject");
+var kEmitWarning = /* @__PURE__ */ Symbol("emitWarning");
+var kFreeze = /* @__PURE__ */ Symbol("freeze");
+var kGetDollarZero = /* @__PURE__ */ Symbol("getDollarZero");
+var kGetParserConfiguration = /* @__PURE__ */ Symbol("getParserConfiguration");
+var kGetUsageConfiguration = /* @__PURE__ */ Symbol("getUsageConfiguration");
+var kGuessLocale = /* @__PURE__ */ Symbol("guessLocale");
+var kGuessVersion = /* @__PURE__ */ Symbol("guessVersion");
+var kParsePositionalNumbers = /* @__PURE__ */ Symbol("parsePositionalNumbers");
+var kPkgUp = /* @__PURE__ */ Symbol("pkgUp");
+var kPopulateParserHintArray = /* @__PURE__ */ Symbol("populateParserHintArray");
+var kPopulateParserHintSingleValueDictionary = /* @__PURE__ */ Symbol("populateParserHintSingleValueDictionary");
+var kPopulateParserHintArrayDictionary = /* @__PURE__ */ Symbol("populateParserHintArrayDictionary");
+var kPopulateParserHintDictionary = /* @__PURE__ */ Symbol("populateParserHintDictionary");
+var kSanitizeKey = /* @__PURE__ */ Symbol("sanitizeKey");
+var kSetKey = /* @__PURE__ */ Symbol("setKey");
+var kUnfreeze = /* @__PURE__ */ Symbol("unfreeze");
+var kValidateAsync = /* @__PURE__ */ Symbol("validateAsync");
+var kGetCommandInstance = /* @__PURE__ */ Symbol("getCommandInstance");
+var kGetContext = /* @__PURE__ */ Symbol("getContext");
+var kGetHasOutput = /* @__PURE__ */ Symbol("getHasOutput");
+var kGetLoggerInstance = /* @__PURE__ */ Symbol("getLoggerInstance");
+var kGetParseContext = /* @__PURE__ */ Symbol("getParseContext");
+var kGetUsageInstance = /* @__PURE__ */ Symbol("getUsageInstance");
+var kGetValidationInstance = /* @__PURE__ */ Symbol("getValidationInstance");
+var kHasParseCallback = /* @__PURE__ */ Symbol("hasParseCallback");
+var kIsGlobalContext = /* @__PURE__ */ Symbol("isGlobalContext");
+var kPostProcess = /* @__PURE__ */ Symbol("postProcess");
+var kRebase = /* @__PURE__ */ Symbol("rebase");
+var kReset = /* @__PURE__ */ Symbol("reset");
+var kRunYargsParserAndExecuteCommands = /* @__PURE__ */ Symbol("runYargsParserAndExecuteCommands");
+var kRunValidation = /* @__PURE__ */ Symbol("runValidation");
+var kSetHasOutput = /* @__PURE__ */ Symbol("setHasOutput");
+var kTrackManuallySetKeys = /* @__PURE__ */ Symbol("kTrackManuallySetKeys");
+var DEFAULT_LOCALE = "en_US";
+var YargsInstance = class {
+ static {
+ __name(this, "YargsInstance");
+ }
+ constructor(processArgs = [], cwd2, parentRequire, shim3) {
+ this.customScriptName = false;
+ this.parsed = false;
+ _YargsInstance_command.set(this, void 0);
+ _YargsInstance_cwd.set(this, void 0);
+ _YargsInstance_context.set(this, { commands: [], fullCommands: [] });
+ _YargsInstance_completion.set(this, null);
+ _YargsInstance_completionCommand.set(this, null);
+ _YargsInstance_defaultShowHiddenOpt.set(this, "show-hidden");
+ _YargsInstance_exitError.set(this, null);
+ _YargsInstance_detectLocale.set(this, true);
+ _YargsInstance_emittedWarnings.set(this, {});
+ _YargsInstance_exitProcess.set(this, true);
+ _YargsInstance_frozens.set(this, []);
+ _YargsInstance_globalMiddleware.set(this, void 0);
+ _YargsInstance_groups.set(this, {});
+ _YargsInstance_hasOutput.set(this, false);
+ _YargsInstance_helpOpt.set(this, null);
+ _YargsInstance_isGlobalContext.set(this, true);
+ _YargsInstance_logger.set(this, void 0);
+ _YargsInstance_output.set(this, "");
+ _YargsInstance_options.set(this, void 0);
+ _YargsInstance_parentRequire.set(this, void 0);
+ _YargsInstance_parserConfig.set(this, {});
+ _YargsInstance_parseFn.set(this, null);
+ _YargsInstance_parseContext.set(this, null);
+ _YargsInstance_pkgs.set(this, {});
+ _YargsInstance_preservedGroups.set(this, {});
+ _YargsInstance_processArgs.set(this, void 0);
+ _YargsInstance_recommendCommands.set(this, false);
+ _YargsInstance_shim.set(this, void 0);
+ _YargsInstance_strict.set(this, false);
+ _YargsInstance_strictCommands.set(this, false);
+ _YargsInstance_strictOptions.set(this, false);
+ _YargsInstance_usage.set(this, void 0);
+ _YargsInstance_usageConfig.set(this, {});
+ _YargsInstance_versionOpt.set(this, null);
+ _YargsInstance_validation.set(this, void 0);
+ __classPrivateFieldSet2(this, _YargsInstance_shim, shim3, "f");
+ __classPrivateFieldSet2(this, _YargsInstance_processArgs, processArgs, "f");
+ __classPrivateFieldSet2(this, _YargsInstance_cwd, cwd2, "f");
+ __classPrivateFieldSet2(this, _YargsInstance_parentRequire, parentRequire, "f");
+ __classPrivateFieldSet2(this, _YargsInstance_globalMiddleware, new GlobalMiddleware(this), "f");
+ this.$0 = this[kGetDollarZero]();
+ this[kReset]();
+ __classPrivateFieldSet2(this, _YargsInstance_command, __classPrivateFieldGet2(this, _YargsInstance_command, "f"), "f");
+ __classPrivateFieldSet2(this, _YargsInstance_usage, __classPrivateFieldGet2(this, _YargsInstance_usage, "f"), "f");
+ __classPrivateFieldSet2(this, _YargsInstance_validation, __classPrivateFieldGet2(this, _YargsInstance_validation, "f"), "f");
+ __classPrivateFieldSet2(this, _YargsInstance_options, __classPrivateFieldGet2(this, _YargsInstance_options, "f"), "f");
+ __classPrivateFieldGet2(this, _YargsInstance_options, "f").showHiddenOpt = __classPrivateFieldGet2(this, _YargsInstance_defaultShowHiddenOpt, "f");
+ __classPrivateFieldSet2(this, _YargsInstance_logger, this[kCreateLogger](), "f");
+ __classPrivateFieldGet2(this, _YargsInstance_shim, "f").y18n.setLocale(DEFAULT_LOCALE);
+ }
+ addHelpOpt(opt, msg) {
+ const defaultHelpOpt = "help";
+ argsert("[string|boolean] [string]", [opt, msg], arguments.length);
+ if (__classPrivateFieldGet2(this, _YargsInstance_helpOpt, "f")) {
+ this[kDeleteFromParserHintObject](__classPrivateFieldGet2(this, _YargsInstance_helpOpt, "f"));
+ __classPrivateFieldSet2(this, _YargsInstance_helpOpt, null, "f");
+ }
+ if (opt === false && msg === void 0)
+ return this;
+ __classPrivateFieldSet2(this, _YargsInstance_helpOpt, typeof opt === "string" ? opt : defaultHelpOpt, "f");
+ this.boolean(__classPrivateFieldGet2(this, _YargsInstance_helpOpt, "f"));
+ this.describe(__classPrivateFieldGet2(this, _YargsInstance_helpOpt, "f"), msg || __classPrivateFieldGet2(this, _YargsInstance_usage, "f").deferY18nLookup("Show help"));
+ return this;
+ }
+ help(opt, msg) {
+ return this.addHelpOpt(opt, msg);
+ }
+ addShowHiddenOpt(opt, msg) {
+ argsert("[string|boolean] [string]", [opt, msg], arguments.length);
+ if (opt === false && msg === void 0)
+ return this;
+ const showHiddenOpt = typeof opt === "string" ? opt : __classPrivateFieldGet2(this, _YargsInstance_defaultShowHiddenOpt, "f");
+ this.boolean(showHiddenOpt);
+ this.describe(showHiddenOpt, msg || __classPrivateFieldGet2(this, _YargsInstance_usage, "f").deferY18nLookup("Show hidden options"));
+ __classPrivateFieldGet2(this, _YargsInstance_options, "f").showHiddenOpt = showHiddenOpt;
+ return this;
+ }
+ showHidden(opt, msg) {
+ return this.addShowHiddenOpt(opt, msg);
+ }
+ alias(key, value) {
+ argsert("