"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __esm = (fn, res, err) => function __init() {
  if (err) throw err[0];
  try {
    return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
  } catch (e) {
    throw err = [e], e;
  }
};
var __commonJS = (cb, mod) => function __require2() {
  try {
    return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  } catch (e) {
    throw mod = 0, e;
  }
};
var __export = (target, all2) => {
  for (var name in all2)
    __defProp(target, name, { get: all2[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// ../workers-utils/dist/chunk-Q72B4Q5Z.mjs
var __create2, __defProp2, __getOwnPropDesc2, __getOwnPropNames2, __getProtoOf2, __hasOwnProp2, __name, __require, __commonJS2, __export2, __copyProps2, __toESM2;
var init_chunk_Q72B4Q5Z = __esm({
  "../workers-utils/dist/chunk-Q72B4Q5Z.mjs"() {
    "use strict";
    __create2 = Object.create;
    __defProp2 = Object.defineProperty;
    __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
    __getOwnPropNames2 = Object.getOwnPropertyNames;
    __getProtoOf2 = Object.getPrototypeOf;
    __hasOwnProp2 = Object.prototype.hasOwnProperty;
    __name = (target, value) => __defProp2(target, "name", { value, configurable: true });
    __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
      get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
    }) : x)(function(x) {
      if (typeof require !== "undefined") return require.apply(this, arguments);
      throw Error('Dynamic require of "' + x + '" is not supported');
    });
    __commonJS2 = (cb, mod) => function __require2() {
      return mod || (0, cb[__getOwnPropNames2(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
    };
    __export2 = (target, all2) => {
      for (var name in all2)
        __defProp2(target, name, { get: all2[name], enumerable: true });
    };
    __copyProps2 = (to, from, except, desc) => {
      if (from && typeof from === "object" || typeof from === "function") {
        for (let key of __getOwnPropNames2(from))
          if (!__hasOwnProp2.call(to, key) && key !== except)
            __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
      }
      return to;
    };
    __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2(
      // If the importer is in node compatibility mode or this is not an ESM
      // file that has been converted to a CommonJS file using a Babel-
      // compatible transform (i.e. "__esModule" has not been set), then set
      // "default" to the CommonJS "module.exports" for node compatibility.
      isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target,
      mod
    ));
  }
});

// ../workers-utils/dist/open-PBXRGS4R.mjs
var open_PBXRGS4R_exports = {};
__export(open_PBXRGS4R_exports, {
  apps: () => apps,
  default: () => open_default,
  openApp: () => openApp
});
function hasDockerEnv() {
  try {
    import_node_fs3.default.statSync("/.dockerenv");
    return true;
  } catch {
    return false;
  }
}
function hasDockerCGroup() {
  try {
    return import_node_fs3.default.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
  } catch {
    return false;
  }
}
function isDocker() {
  if (isDockerCached === void 0) {
    isDockerCached = hasDockerEnv() || hasDockerCGroup();
  }
  return isDockerCached;
}
function isInsideContainer() {
  if (cachedResult === void 0) {
    cachedResult = hasContainerEnv() || isDocker();
  }
  return cachedResult;
}
function parseMountPointFromConfig(content) {
  for (const line of content.split("\n")) {
    if (/^\s*#/.test(line)) {
      continue;
    }
    const match = /^\s*root\s*=\s*(?<mountPoint>"[^"]*"|'[^']*'|[^#]*)/.exec(line);
    if (!match) {
      continue;
    }
    return match.groups.mountPoint.trim().replaceAll(/^["']|["']$/g, "");
  }
}
function defineLazyProperty(object3, propertyName, valueGetter) {
  const define2 = /* @__PURE__ */ __name((value) => Object.defineProperty(object3, propertyName, { value, enumerable: true, writable: true }), "define");
  Object.defineProperty(object3, propertyName, {
    configurable: true,
    enumerable: true,
    get() {
      const result = valueGetter();
      define2(result);
      return result;
    },
    set(value) {
      define2(value);
    }
  });
  return object3;
}
async function defaultBrowserId() {
  if (import_node_process2.default.platform !== "darwin") {
    throw new Error("macOS only");
  }
  const { stdout: stdout2 } = await execFileAsync("defaults", ["read", "com.apple.LaunchServices/com.apple.launchservices.secure", "LSHandlers"]);
  const match = /LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout2);
  const browserId = match?.groups.id ?? "com.apple.Safari";
  if (browserId === "com.apple.safari") {
    return "com.apple.Safari";
  }
  return browserId;
}
async function runAppleScript(script, { humanReadableOutput = true, signal } = {}) {
  if (import_node_process2.default.platform !== "darwin") {
    throw new Error("macOS only");
  }
  const outputArguments = humanReadableOutput ? [] : ["-ss"];
  const execOptions = {};
  if (signal) {
    execOptions.signal = signal;
  }
  const { stdout: stdout2 } = await execFileAsync2("osascript", ["-e", script, outputArguments], execOptions);
  return stdout2.trim();
}
async function bundleName(bundleId) {
  return runAppleScript(`tell application "Finder" to set app_path to application file id "${bundleId}" as string
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`);
}
async function defaultBrowser(_execFileAsync = execFileAsync3) {
  const { stdout: stdout2 } = await _execFileAsync("reg", [
    "QUERY",
    " HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice",
    "/v",
    "ProgId"
  ]);
  const match = /ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout2);
  if (!match) {
    throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout2)}`);
  }
  const { id } = match.groups;
  const browser = windowsBrowserProgIds[id];
  if (!browser) {
    throw new UnknownBrowserError(`Unknown browser ID: ${id}`);
  }
  return browser;
}
async function defaultBrowser2() {
  if (import_node_process2.default.platform === "darwin") {
    const id = await defaultBrowserId();
    const name = await bundleName(id);
    return { name, id };
  }
  if (import_node_process2.default.platform === "linux") {
    const { stdout: stdout2 } = await execFileAsync4("xdg-mime", ["query", "default", "x-scheme-handler/http"]);
    const id = stdout2.trim();
    const name = titleize(id.replace(/.desktop$/, "").replace("-", " "));
    return { name, id };
  }
  if (import_node_process2.default.platform === "win32") {
    return defaultBrowser();
  }
  throw new Error("Only macOS, Linux, and Windows are supported");
}
function detectArchBinary(binary) {
  if (typeof binary === "string" || Array.isArray(binary)) {
    return binary;
  }
  const { [arch]: archBinary } = binary;
  if (!archBinary) {
    throw new Error(`${arch} is not supported`);
  }
  return archBinary;
}
function detectPlatformBinary({ [platform]: platformBinary }, { wsl } = {}) {
  if (wsl && is_wsl_default) {
    return detectArchBinary(wsl);
  }
  if (!platformBinary) {
    throw new Error(`${platform} is not supported`);
  }
  return detectArchBinary(platformBinary);
}
var import_node_process2, import_node_path3, import_node_url, import_node_child_process, import_promises, import_node_util, import_node_os3, import_node_fs3, import_node_buffer, import_meta, isDockerCached, cachedResult, hasContainerEnv, isWsl, is_wsl_default, execFile, powerShellPath, executePowerShell, execFile2, wslDrivesMountPoint, powerShellPathFromWsl, powerShellPath2, canAccessPowerShellPromise, canAccessPowerShell, wslDefaultBrowser, convertWslPathToWindows, execFileAsync, execFileAsync2, execFileAsync3, windowsBrowserProgIds, _windowsBrowserProgIdMap, UnknownBrowserError, execFileAsync4, titleize, isInSsh, is_in_ssh_default, fallbackAttemptSymbol, __dirname2, localXdgOpenPath, platform, arch, tryEachApp, baseOpen, open, openApp, apps, open_default;
var init_open_PBXRGS4R = __esm({
  "../workers-utils/dist/open-PBXRGS4R.mjs"() {
    "use strict";
    init_chunk_Q72B4Q5Z();
    import_node_process2 = __toESM(require("node:process"), 1);
    import_node_path3 = __toESM(require("node:path"), 1);
    import_node_url = require("node:url");
    import_node_child_process = __toESM(require("node:child_process"), 1);
    import_promises = __toESM(require("node:fs/promises"), 1);
    import_node_util = require("node:util");
    import_node_os3 = __toESM(require("node:os"), 1);
    import_node_fs3 = __toESM(require("node:fs"), 1);
    import_node_buffer = require("node:buffer");
    import_meta = {};
    __name(hasDockerEnv, "hasDockerEnv");
    __name(hasDockerCGroup, "hasDockerCGroup");
    __name(isDocker, "isDocker");
    hasContainerEnv = /* @__PURE__ */ __name(() => {
      try {
        import_node_fs3.default.statSync("/run/.containerenv");
        return true;
      } catch {
        return false;
      }
    }, "hasContainerEnv");
    __name(isInsideContainer, "isInsideContainer");
    isWsl = /* @__PURE__ */ __name(() => {
      if (import_node_process2.default.platform !== "linux") {
        return false;
      }
      if (import_node_os3.default.release().toLowerCase().includes("microsoft")) {
        if (isInsideContainer()) {
          return false;
        }
        return true;
      }
      try {
        return import_node_fs3.default.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft") ? !isInsideContainer() : false;
      } catch {
        return false;
      }
    }, "isWsl");
    is_wsl_default = import_node_process2.default.env.__IS_WSL_TEST__ ? isWsl : isWsl();
    execFile = (0, import_node_util.promisify)(import_node_child_process.default.execFile);
    powerShellPath = /* @__PURE__ */ __name(() => `${import_node_process2.default.env.SYSTEMROOT || import_node_process2.default.env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`, "powerShellPath");
    executePowerShell = /* @__PURE__ */ __name(async (command, options = {}) => {
      const {
        powerShellPath: psPath,
        ...execFileOptions
      } = options;
      const encodedCommand = executePowerShell.encodeCommand(command);
      return execFile(
        psPath ?? powerShellPath(),
        [
          ...executePowerShell.argumentsPrefix,
          encodedCommand
        ],
        {
          encoding: "utf8",
          ...execFileOptions
        }
      );
    }, "executePowerShell");
    executePowerShell.argumentsPrefix = [
      "-NoProfile",
      "-NonInteractive",
      "-ExecutionPolicy",
      "Bypass",
      "-EncodedCommand"
    ];
    executePowerShell.encodeCommand = (command) => import_node_buffer.Buffer.from(command, "utf16le").toString("base64");
    executePowerShell.escapeArgument = (value) => `'${String(value).replaceAll("'", "''")}'`;
    __name(parseMountPointFromConfig, "parseMountPointFromConfig");
    execFile2 = (0, import_node_util.promisify)(import_node_child_process.default.execFile);
    wslDrivesMountPoint = /* @__PURE__ */ (() => {
      const defaultMountPoint = "/mnt/";
      let mountPoint;
      return async function() {
        if (mountPoint) {
          return mountPoint;
        }
        const configFilePath = "/etc/wsl.conf";
        let isConfigFileExists = false;
        try {
          await import_promises.default.access(configFilePath, import_promises.constants.F_OK);
          isConfigFileExists = true;
        } catch {
        }
        if (!isConfigFileExists) {
          return defaultMountPoint;
        }
        const configContent = await import_promises.default.readFile(configFilePath, { encoding: "utf8" });
        const parsedMountPoint = parseMountPointFromConfig(configContent);
        if (parsedMountPoint === void 0) {
          return defaultMountPoint;
        }
        mountPoint = parsedMountPoint;
        mountPoint = mountPoint.endsWith("/") ? mountPoint : `${mountPoint}/`;
        return mountPoint;
      };
    })();
    powerShellPathFromWsl = /* @__PURE__ */ __name(async () => {
      const mountPoint = await wslDrivesMountPoint();
      return `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`;
    }, "powerShellPathFromWsl");
    powerShellPath2 = is_wsl_default ? powerShellPathFromWsl : powerShellPath;
    canAccessPowerShell = /* @__PURE__ */ __name(async () => {
      canAccessPowerShellPromise ??= (async () => {
        try {
          const psPath = await powerShellPath2();
          await import_promises.default.access(psPath, import_promises.constants.X_OK);
          return true;
        } catch {
          return false;
        }
      })();
      return canAccessPowerShellPromise;
    }, "canAccessPowerShell");
    wslDefaultBrowser = /* @__PURE__ */ __name(async () => {
      const psPath = await powerShellPath2();
      const command = String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`;
      const { stdout: stdout2 } = await executePowerShell(command, { powerShellPath: psPath });
      return stdout2.trim();
    }, "wslDefaultBrowser");
    convertWslPathToWindows = /* @__PURE__ */ __name(async (path210) => {
      if (/^[a-z]+:\/\//i.test(path210)) {
        return path210;
      }
      try {
        const { stdout: stdout2 } = await execFile2("wslpath", ["-aw", path210], { encoding: "utf8" });
        return stdout2.trim();
      } catch {
        return path210;
      }
    }, "convertWslPathToWindows");
    __name(defineLazyProperty, "defineLazyProperty");
    execFileAsync = (0, import_node_util.promisify)(import_node_child_process.execFile);
    __name(defaultBrowserId, "defaultBrowserId");
    execFileAsync2 = (0, import_node_util.promisify)(import_node_child_process.execFile);
    __name(runAppleScript, "runAppleScript");
    __name(bundleName, "bundleName");
    execFileAsync3 = (0, import_node_util.promisify)(import_node_child_process.execFile);
    windowsBrowserProgIds = {
      MSEdgeHTM: { name: "Edge", id: "com.microsoft.edge" },
      // The missing `L` is correct.
      MSEdgeBHTML: { name: "Edge Beta", id: "com.microsoft.edge.beta" },
      MSEdgeDHTML: { name: "Edge Dev", id: "com.microsoft.edge.dev" },
      AppXq0fevzme2pys62n3e0fbqa7peapykr8v: { name: "Edge", id: "com.microsoft.edge.old" },
      ChromeHTML: { name: "Chrome", id: "com.google.chrome" },
      ChromeBHTML: { name: "Chrome Beta", id: "com.google.chrome.beta" },
      ChromeDHTML: { name: "Chrome Dev", id: "com.google.chrome.dev" },
      ChromiumHTM: { name: "Chromium", id: "org.chromium.Chromium" },
      BraveHTML: { name: "Brave", id: "com.brave.Browser" },
      BraveBHTML: { name: "Brave Beta", id: "com.brave.Browser.beta" },
      BraveDHTML: { name: "Brave Dev", id: "com.brave.Browser.dev" },
      BraveSSHTM: { name: "Brave Nightly", id: "com.brave.Browser.nightly" },
      FirefoxURL: { name: "Firefox", id: "org.mozilla.firefox" },
      OperaStable: { name: "Opera", id: "com.operasoftware.Opera" },
      VivaldiHTM: { name: "Vivaldi", id: "com.vivaldi.Vivaldi" },
      "IE.HTTP": { name: "Internet Explorer", id: "com.microsoft.ie" }
    };
    _windowsBrowserProgIdMap = new Map(Object.entries(windowsBrowserProgIds));
    UnknownBrowserError = class extends Error {
      static {
        __name(this, "UnknownBrowserError");
      }
    };
    __name(defaultBrowser, "defaultBrowser");
    execFileAsync4 = (0, import_node_util.promisify)(import_node_child_process.execFile);
    titleize = /* @__PURE__ */ __name((string7) => string7.toLowerCase().replaceAll(/(?:^|\s|-)\S/g, (x) => x.toUpperCase()), "titleize");
    __name(defaultBrowser2, "defaultBrowser");
    isInSsh = Boolean(import_node_process2.default.env.SSH_CONNECTION || import_node_process2.default.env.SSH_CLIENT || import_node_process2.default.env.SSH_TTY);
    is_in_ssh_default = isInSsh;
    fallbackAttemptSymbol = /* @__PURE__ */ Symbol("fallbackAttempt");
    __dirname2 = import_meta.url ? import_node_path3.default.dirname((0, import_node_url.fileURLToPath)(import_meta.url)) : "";
    localXdgOpenPath = import_node_path3.default.join(__dirname2, "xdg-open");
    ({ platform, arch } = import_node_process2.default);
    tryEachApp = /* @__PURE__ */ __name(async (apps2, opener) => {
      if (apps2.length === 0) {
        return;
      }
      const errors = [];
      for (const app of apps2) {
        try {
          return await opener(app);
        } catch (error101) {
          errors.push(error101);
        }
      }
      throw new AggregateError(errors, "Failed to open in all supported apps");
    }, "tryEachApp");
    baseOpen = /* @__PURE__ */ __name(async (options) => {
      options = {
        wait: false,
        background: false,
        newInstance: false,
        allowNonzeroExitCode: false,
        ...options
      };
      const isFallbackAttempt = options[fallbackAttemptSymbol] === true;
      delete options[fallbackAttemptSymbol];
      if (Array.isArray(options.app)) {
        return tryEachApp(options.app, (singleApp) => baseOpen({
          ...options,
          app: singleApp,
          [fallbackAttemptSymbol]: true
        }));
      }
      let { name: app, arguments: appArguments = [] } = options.app ?? {};
      appArguments = [...appArguments];
      if (Array.isArray(app)) {
        return tryEachApp(app, (appName) => baseOpen({
          ...options,
          app: {
            name: appName,
            arguments: appArguments
          },
          [fallbackAttemptSymbol]: true
        }));
      }
      if (app === "browser" || app === "browserPrivate") {
        const ids = {
          "com.google.chrome": "chrome",
          "google-chrome.desktop": "chrome",
          "com.brave.browser": "brave",
          "org.mozilla.firefox": "firefox",
          "firefox.desktop": "firefox",
          "com.microsoft.msedge": "edge",
          "com.microsoft.edge": "edge",
          "com.microsoft.edgemac": "edge",
          "microsoft-edge.desktop": "edge",
          "com.apple.safari": "safari"
        };
        const flags = {
          chrome: "--incognito",
          brave: "--incognito",
          firefox: "--private-window",
          edge: "--inPrivate"
          // Safari doesn't support private mode via command line
        };
        let browser;
        if (is_wsl_default) {
          const progId = await wslDefaultBrowser();
          const browserInfo = _windowsBrowserProgIdMap.get(progId);
          browser = browserInfo ?? {};
        } else {
          browser = await defaultBrowser2();
        }
        if (browser.id in ids) {
          const browserName = ids[browser.id.toLowerCase()];
          if (app === "browserPrivate") {
            if (browserName === "safari") {
              throw new Error("Safari doesn't support opening in private mode via command line");
            }
            appArguments.push(flags[browserName]);
          }
          return baseOpen({
            ...options,
            app: {
              name: apps[browserName],
              arguments: appArguments
            }
          });
        }
        throw new Error(`${browser.name} is not supported as a default browser`);
      }
      let command;
      const cliArguments = [];
      const childProcessOptions = {};
      let shouldUseWindowsInWsl = false;
      if (is_wsl_default && !isInsideContainer() && !is_in_ssh_default && !app) {
        shouldUseWindowsInWsl = await canAccessPowerShell();
      }
      if (platform === "darwin") {
        command = "open";
        if (options.wait) {
          cliArguments.push("--wait-apps");
        }
        if (options.background) {
          cliArguments.push("--background");
        }
        if (options.newInstance) {
          cliArguments.push("--new");
        }
        if (app) {
          cliArguments.push("-a", app);
        }
      } else if (platform === "win32" || shouldUseWindowsInWsl) {
        command = await powerShellPath2();
        cliArguments.push(...executePowerShell.argumentsPrefix);
        if (!is_wsl_default) {
          childProcessOptions.windowsVerbatimArguments = true;
        }
        if (is_wsl_default && options.target) {
          options.target = await convertWslPathToWindows(options.target);
        }
        const encodedArguments = ["$ProgressPreference = 'SilentlyContinue';", "Start"];
        if (options.wait) {
          encodedArguments.push("-Wait");
        }
        if (app) {
          encodedArguments.push(executePowerShell.escapeArgument(app));
          if (options.target) {
            appArguments.push(options.target);
          }
        } else if (options.target) {
          encodedArguments.push(executePowerShell.escapeArgument(options.target));
        }
        if (appArguments.length > 0) {
          appArguments = appArguments.map((argument) => executePowerShell.escapeArgument(argument));
          encodedArguments.push("-ArgumentList", appArguments.join(","));
        }
        options.target = executePowerShell.encodeCommand(encodedArguments.join(" "));
        if (!options.wait) {
          childProcessOptions.stdio = "ignore";
        }
      } else {
        if (app) {
          command = app;
        } else {
          const isBundled = !__dirname2 || __dirname2 === "/";
          let exeLocalXdgOpen = false;
          try {
            await import_promises.default.access(localXdgOpenPath, import_promises.constants.X_OK);
            exeLocalXdgOpen = true;
          } catch {
          }
          const useSystemXdgOpen = import_node_process2.default.versions.electron ?? (platform === "android" || isBundled || !exeLocalXdgOpen);
          command = useSystemXdgOpen ? "xdg-open" : localXdgOpenPath;
        }
        if (appArguments.length > 0) {
          cliArguments.push(...appArguments);
        }
        if (!options.wait) {
          childProcessOptions.stdio = "ignore";
          childProcessOptions.detached = true;
        }
      }
      if (platform === "darwin" && appArguments.length > 0) {
        cliArguments.push("--args", ...appArguments);
      }
      if (options.target) {
        cliArguments.push(options.target);
      }
      const subprocess = import_node_child_process.default.spawn(command, cliArguments, childProcessOptions);
      if (options.wait) {
        return new Promise((resolve8, reject) => {
          subprocess.once("error", reject);
          subprocess.once("close", (exitCode) => {
            if (!options.allowNonzeroExitCode && exitCode !== 0) {
              reject(new Error(`Exited with code ${exitCode}`));
              return;
            }
            resolve8(subprocess);
          });
        });
      }
      if (isFallbackAttempt) {
        return new Promise((resolve8, reject) => {
          subprocess.once("error", reject);
          subprocess.once("spawn", () => {
            subprocess.once("close", (exitCode) => {
              subprocess.off("error", reject);
              if (exitCode !== 0) {
                reject(new Error(`Exited with code ${exitCode}`));
                return;
              }
              subprocess.unref();
              resolve8(subprocess);
            });
          });
        });
      }
      subprocess.unref();
      return new Promise((resolve8, reject) => {
        subprocess.once("error", reject);
        subprocess.once("spawn", () => {
          subprocess.off("error", reject);
          resolve8(subprocess);
        });
      });
    }, "baseOpen");
    open = /* @__PURE__ */ __name((target, options) => {
      if (typeof target !== "string") {
        throw new TypeError("Expected a `target`");
      }
      return baseOpen({
        ...options,
        target
      });
    }, "open");
    openApp = /* @__PURE__ */ __name((name, options) => {
      if (typeof name !== "string" && !Array.isArray(name)) {
        throw new TypeError("Expected a valid `name`");
      }
      const { arguments: appArguments = [] } = options ?? {};
      if (appArguments !== void 0 && appArguments !== null && !Array.isArray(appArguments)) {
        throw new TypeError("Expected `appArguments` as Array type");
      }
      return baseOpen({
        ...options,
        app: {
          name,
          arguments: appArguments
        }
      });
    }, "openApp");
    __name(detectArchBinary, "detectArchBinary");
    __name(detectPlatformBinary, "detectPlatformBinary");
    apps = {
      browser: "browser",
      browserPrivate: "browserPrivate"
    };
    defineLazyProperty(apps, "chrome", () => detectPlatformBinary({
      darwin: "google chrome",
      win32: "chrome",
      // `chromium-browser` is the older deb package name used by Ubuntu/Debian before snap.
      linux: ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser"]
    }, {
      wsl: {
        ia32: "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",
        x64: ["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe", "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]
      }
    }));
    defineLazyProperty(apps, "brave", () => detectPlatformBinary({
      darwin: "brave browser",
      win32: "brave",
      linux: ["brave-browser", "brave"]
    }, {
      wsl: {
        ia32: "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",
        x64: ["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe", "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]
      }
    }));
    defineLazyProperty(apps, "firefox", () => detectPlatformBinary({
      darwin: "firefox",
      win32: String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,
      linux: "firefox"
    }, {
      wsl: "/mnt/c/Program Files/Mozilla Firefox/firefox.exe"
    }));
    defineLazyProperty(apps, "edge", () => detectPlatformBinary({
      darwin: "microsoft edge",
      win32: "msedge",
      linux: ["microsoft-edge", "microsoft-edge-dev"]
    }, {
      wsl: "/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"
    }));
    defineLazyProperty(apps, "safari", () => detectPlatformBinary({
      darwin: "Safari"
    }));
    open_default = open;
  }
});

// ../../node_modules/.pnpm/ci-info@4.4.0/node_modules/ci-info/vendors.json
var require_vendors2 = __commonJS({
  "../../node_modules/.pnpm/ci-info@4.4.0/node_modules/ci-info/vendors.json"(exports2, module2) {
    module2.exports = [
      {
        name: "Agola CI",
        constant: "AGOLA",
        env: "AGOLA_GIT_REF",
        pr: "AGOLA_PULL_REQUEST_ID"
      },
      {
        name: "Alpic",
        constant: "ALPIC",
        env: "ALPIC_HOST"
      },
      {
        name: "Appcircle",
        constant: "APPCIRCLE",
        env: "AC_APPCIRCLE",
        pr: {
          env: "AC_GIT_PR",
          ne: "false"
        }
      },
      {
        name: "AppVeyor",
        constant: "APPVEYOR",
        env: "APPVEYOR",
        pr: "APPVEYOR_PULL_REQUEST_NUMBER"
      },
      {
        name: "AWS CodeBuild",
        constant: "CODEBUILD",
        env: "CODEBUILD_BUILD_ARN",
        pr: {
          env: "CODEBUILD_WEBHOOK_EVENT",
          any: [
            "PULL_REQUEST_CREATED",
            "PULL_REQUEST_UPDATED",
            "PULL_REQUEST_REOPENED"
          ]
        }
      },
      {
        name: "Azure Pipelines",
        constant: "AZURE_PIPELINES",
        env: "TF_BUILD",
        pr: {
          BUILD_REASON: "PullRequest"
        }
      },
      {
        name: "Bamboo",
        constant: "BAMBOO",
        env: "bamboo_planKey"
      },
      {
        name: "Bitbucket Pipelines",
        constant: "BITBUCKET",
        env: "BITBUCKET_COMMIT",
        pr: "BITBUCKET_PR_ID"
      },
      {
        name: "Bitrise",
        constant: "BITRISE",
        env: "BITRISE_IO",
        pr: "BITRISE_PULL_REQUEST"
      },
      {
        name: "Buddy",
        constant: "BUDDY",
        env: "BUDDY_WORKSPACE_ID",
        pr: "BUDDY_EXECUTION_PULL_REQUEST_ID"
      },
      {
        name: "Buildkite",
        constant: "BUILDKITE",
        env: "BUILDKITE",
        pr: {
          env: "BUILDKITE_PULL_REQUEST",
          ne: "false"
        }
      },
      {
        name: "CircleCI",
        constant: "CIRCLE",
        env: "CIRCLECI",
        pr: "CIRCLE_PULL_REQUEST"
      },
      {
        name: "Cirrus CI",
        constant: "CIRRUS",
        env: "CIRRUS_CI",
        pr: "CIRRUS_PR"
      },
      {
        name: "Cloudflare Pages",
        constant: "CLOUDFLARE_PAGES",
        env: "CF_PAGES"
      },
      {
        name: "Cloudflare Workers",
        constant: "CLOUDFLARE_WORKERS",
        env: "WORKERS_CI"
      },
      {
        name: "Codefresh",
        constant: "CODEFRESH",
        env: "CF_BUILD_ID",
        pr: {
          any: [
            "CF_PULL_REQUEST_NUMBER",
            "CF_PULL_REQUEST_ID"
          ]
        }
      },
      {
        name: "Codemagic",
        constant: "CODEMAGIC",
        env: "CM_BUILD_ID",
        pr: "CM_PULL_REQUEST"
      },
      {
        name: "Codeship",
        constant: "CODESHIP",
        env: {
          CI_NAME: "codeship"
        }
      },
      {
        name: "Drone",
        constant: "DRONE",
        env: "DRONE",
        pr: {
          DRONE_BUILD_EVENT: "pull_request"
        }
      },
      {
        name: "dsari",
        constant: "DSARI",
        env: "DSARI"
      },
      {
        name: "Earthly",
        constant: "EARTHLY",
        env: "EARTHLY_CI"
      },
      {
        name: "Expo Application Services",
        constant: "EAS",
        env: "EAS_BUILD"
      },
      {
        name: "Gerrit",
        constant: "GERRIT",
        env: "GERRIT_PROJECT"
      },
      {
        name: "Gitea Actions",
        constant: "GITEA_ACTIONS",
        env: "GITEA_ACTIONS"
      },
      {
        name: "GitHub Actions",
        constant: "GITHUB_ACTIONS",
        env: "GITHUB_ACTIONS",
        pr: {
          GITHUB_EVENT_NAME: "pull_request"
        }
      },
      {
        name: "GitLab CI",
        constant: "GITLAB",
        env: "GITLAB_CI",
        pr: "CI_MERGE_REQUEST_ID"
      },
      {
        name: "GoCD",
        constant: "GOCD",
        env: "GO_PIPELINE_LABEL"
      },
      {
        name: "Google Cloud Build",
        constant: "GOOGLE_CLOUD_BUILD",
        env: "BUILDER_OUTPUT"
      },
      {
        name: "Harness CI",
        constant: "HARNESS",
        env: "HARNESS_BUILD_ID"
      },
      {
        name: "Heroku",
        constant: "HEROKU",
        env: {
          env: "NODE",
          includes: "/app/.heroku/node/bin/node"
        }
      },
      {
        name: "Hudson",
        constant: "HUDSON",
        env: "HUDSON_URL"
      },
      {
        name: "Jenkins",
        constant: "JENKINS",
        env: [
          "JENKINS_URL",
          "BUILD_ID"
        ],
        pr: {
          any: [
            "ghprbPullId",
            "CHANGE_ID"
          ]
        }
      },
      {
        name: "LayerCI",
        constant: "LAYERCI",
        env: "LAYERCI",
        pr: "LAYERCI_PULL_REQUEST"
      },
      {
        name: "Magnum CI",
        constant: "MAGNUM",
        env: "MAGNUM"
      },
      {
        name: "Netlify CI",
        constant: "NETLIFY",
        env: "NETLIFY",
        pr: {
          env: "PULL_REQUEST",
          ne: "false"
        }
      },
      {
        name: "Nevercode",
        constant: "NEVERCODE",
        env: "NEVERCODE",
        pr: {
          env: "NEVERCODE_PULL_REQUEST",
          ne: "false"
        }
      },
      {
        name: "Prow",
        constant: "PROW",
        env: "PROW_JOB_ID"
      },
      {
        name: "ReleaseHub",
        constant: "RELEASEHUB",
        env: "RELEASE_BUILD_ID"
      },
      {
        name: "Render",
        constant: "RENDER",
        env: "RENDER",
        pr: {
          IS_PULL_REQUEST: "true"
        }
      },
      {
        name: "Sail CI",
        constant: "SAIL",
        env: "SAILCI",
        pr: "SAIL_PULL_REQUEST_NUMBER"
      },
      {
        name: "Screwdriver",
        constant: "SCREWDRIVER",
        env: "SCREWDRIVER",
        pr: {
          env: "SD_PULL_REQUEST",
          ne: "false"
        }
      },
      {
        name: "Semaphore",
        constant: "SEMAPHORE",
        env: "SEMAPHORE",
        pr: "PULL_REQUEST_NUMBER"
      },
      {
        name: "Sourcehut",
        constant: "SOURCEHUT",
        env: {
          CI_NAME: "sourcehut"
        }
      },
      {
        name: "Strider CD",
        constant: "STRIDER",
        env: "STRIDER"
      },
      {
        name: "TaskCluster",
        constant: "TASKCLUSTER",
        env: [
          "TASK_ID",
          "RUN_ID"
        ]
      },
      {
        name: "TeamCity",
        constant: "TEAMCITY",
        env: "TEAMCITY_VERSION"
      },
      {
        name: "Travis CI",
        constant: "TRAVIS",
        env: "TRAVIS",
        pr: {
          env: "TRAVIS_PULL_REQUEST",
          ne: "false"
        }
      },
      {
        name: "Vela",
        constant: "VELA",
        env: "VELA",
        pr: {
          VELA_PULL_REQUEST: "1"
        }
      },
      {
        name: "Vercel",
        constant: "VERCEL",
        env: {
          any: [
            "NOW_BUILDER",
            "VERCEL"
          ]
        },
        pr: "VERCEL_GIT_PULL_REQUEST_ID"
      },
      {
        name: "Visual Studio App Center",
        constant: "APPCENTER",
        env: "APPCENTER_BUILD_ID"
      },
      {
        name: "Woodpecker",
        constant: "WOODPECKER",
        env: {
          CI: "woodpecker"
        },
        pr: {
          CI_BUILD_EVENT: "pull_request"
        }
      },
      {
        name: "Xcode Cloud",
        constant: "XCODE_CLOUD",
        env: "CI_XCODE_PROJECT",
        pr: "CI_PULL_REQUEST_NUMBER"
      },
      {
        name: "Xcode Server",
        constant: "XCODE_SERVER",
        env: "XCS"
      }
    ];
  }
});

// ../../node_modules/.pnpm/ci-info@4.4.0/node_modules/ci-info/index.js
var require_ci_info2 = __commonJS({
  "../../node_modules/.pnpm/ci-info@4.4.0/node_modules/ci-info/index.js"(exports2) {
    "use strict";
    var vendors = require_vendors2();
    var env3 = process.env;
    Object.defineProperty(exports2, "_vendors", {
      value: vendors.map(function(v) {
        return v.constant;
      })
    });
    exports2.name = null;
    exports2.isPR = null;
    exports2.id = null;
    if (env3.CI !== "false") {
      vendors.forEach(function(vendor) {
        const envs = Array.isArray(vendor.env) ? vendor.env : [vendor.env];
        const isCI2 = envs.every(function(obj) {
          return checkEnv(obj);
        });
        exports2[vendor.constant] = isCI2;
        if (!isCI2) {
          return;
        }
        exports2.name = vendor.name;
        exports2.isPR = checkPR(vendor);
        exports2.id = vendor.constant;
      });
    }
    exports2.isCI = !!(env3.CI !== "false" && // Bypass all checks if CI env is explicitly set to 'false'
    (env3.BUILD_ID || // Jenkins, Cloudbees
    env3.BUILD_NUMBER || // Jenkins, TeamCity
    env3.CI || // Travis CI, CircleCI, Cirrus CI, Gitlab CI, Appveyor, CodeShip, dsari, Cloudflare Pages/Workers
    env3.CI_APP_ID || // Appflow
    env3.CI_BUILD_ID || // Appflow
    env3.CI_BUILD_NUMBER || // Appflow
    env3.CI_NAME || // Codeship and others
    env3.CONTINUOUS_INTEGRATION || // Travis CI, Cirrus CI
    env3.RUN_ID || // TaskCluster, dsari
    exports2.name || false));
    function checkEnv(obj) {
      if (typeof obj === "string") return !!env3[obj];
      if ("env" in obj) {
        return env3[obj.env] && env3[obj.env].includes(obj.includes);
      }
      if ("any" in obj) {
        return obj.any.some(function(k) {
          return !!env3[k];
        });
      }
      return Object.keys(obj).every(function(k) {
        return env3[k] === obj[k];
      });
    }
    function checkPR(vendor) {
      switch (typeof vendor.pr) {
        case "string":
          return !!env3[vendor.pr];
        case "object":
          if ("env" in vendor.pr) {
            if ("any" in vendor.pr) {
              return vendor.pr.any.some(function(key) {
                return env3[vendor.pr.env] === key;
              });
            } else {
              return vendor.pr.env in env3 && env3[vendor.pr.env] !== vendor.pr.ne;
            }
          } else if ("any" in vendor.pr) {
            return vendor.pr.any.some(function(key) {
              return !!env3[key];
            });
          } else {
            return checkEnv(vendor.pr);
          }
        default:
          return null;
      }
    }
  }
});

// ../../node_modules/.pnpm/stoppable@1.1.0/node_modules/stoppable/lib/stoppable.js
var require_stoppable = __commonJS({
  "../../node_modules/.pnpm/stoppable@1.1.0/node_modules/stoppable/lib/stoppable.js"(exports2, module2) {
    "use strict";
    var https2 = require("https");
    module2.exports = (server, grace) => {
      grace = typeof grace === "undefined" ? Infinity : grace;
      const reqsPerSocket = /* @__PURE__ */ new Map();
      let stopped = false;
      let gracefully = true;
      if (server instanceof https2.Server) {
        server.on("secureConnection", onConnection);
      } else {
        server.on("connection", onConnection);
      }
      server.on("request", onRequest);
      server.stop = stop;
      server._pendingSockets = reqsPerSocket;
      return server;
      function onConnection(socket) {
        reqsPerSocket.set(socket, 0);
        socket.once("close", () => reqsPerSocket.delete(socket));
      }
      function onRequest(req, res) {
        reqsPerSocket.set(req.socket, reqsPerSocket.get(req.socket) + 1);
        res.once("finish", () => {
          const pending = reqsPerSocket.get(req.socket) - 1;
          reqsPerSocket.set(req.socket, pending);
          if (stopped && pending === 0) {
            req.socket.end();
          }
        });
      }
      function stop(callback) {
        setImmediate(() => {
          stopped = true;
          if (grace < Infinity) {
            setTimeout(destroyAll, grace).unref();
          }
          server.close((e) => {
            if (callback) {
              callback(e, gracefully);
            }
          });
          reqsPerSocket.forEach(endIfIdle);
        });
      }
      function endIfIdle(requests, socket) {
        if (requests === 0) socket.end();
      }
      function destroyAll() {
        gracefully = false;
        reqsPerSocket.forEach((reqs, socket) => socket.end());
        setImmediate(() => {
          reqsPerSocket.forEach((reqs, socket) => socket.destroy());
        });
      }
    };
  }
});

// ../../node_modules/.pnpm/glob-to-regexp@0.4.1/node_modules/glob-to-regexp/index.js
var require_glob_to_regexp = __commonJS({
  "../../node_modules/.pnpm/glob-to-regexp@0.4.1/node_modules/glob-to-regexp/index.js"(exports2, module2) {
    "use strict";
    module2.exports = function(glob, opts) {
      if (typeof glob !== "string") {
        throw new TypeError("Expected a string");
      }
      var str = String(glob);
      var reStr = "";
      var extended = opts ? !!opts.extended : false;
      var globstar = opts ? !!opts.globstar : false;
      var inGroup = false;
      var flags = opts && typeof opts.flags === "string" ? opts.flags : "";
      var c2;
      for (var i = 0, len = str.length; i < len; i++) {
        c2 = str[i];
        switch (c2) {
          case "/":
          case "$":
          case "^":
          case "+":
          case ".":
          case "(":
          case ")":
          case "=":
          case "!":
          case "|":
            reStr += "\\" + c2;
            break;
          case "?":
            if (extended) {
              reStr += ".";
              break;
            }
          case "[":
          case "]":
            if (extended) {
              reStr += c2;
              break;
            }
          case "{":
            if (extended) {
              inGroup = true;
              reStr += "(";
              break;
            }
          case "}":
            if (extended) {
              inGroup = false;
              reStr += ")";
              break;
            }
          case ",":
            if (inGroup) {
              reStr += "|";
              break;
            }
            reStr += "\\" + c2;
            break;
          case "*":
            var prevChar = str[i - 1];
            var starCount = 1;
            while (str[i + 1] === "*") {
              starCount++;
              i++;
            }
            var nextChar = str[i + 1];
            if (!globstar) {
              reStr += ".*";
            } else {
              var isGlobstar = starCount > 1 && (prevChar === "/" || prevChar === void 0) && (nextChar === "/" || nextChar === void 0);
              if (isGlobstar) {
                reStr += "((?:[^/]*(?:/|$))*)";
                i++;
              } else {
                reStr += "([^/]*)";
              }
            }
            break;
          default:
            reStr += c2;
        }
      }
      if (!flags || !~flags.indexOf("g")) {
        reStr = "^" + reStr + "$";
      }
      return new RegExp(reStr, flags);
    };
  }
});

// ../../node_modules/.pnpm/ignore@5.3.1/node_modules/ignore/index.js
var require_ignore = __commonJS({
  "../../node_modules/.pnpm/ignore@5.3.1/node_modules/ignore/index.js"(exports2, module2) {
    "use strict";
    function makeArray(subject) {
      return Array.isArray(subject) ? subject : [subject];
    }
    var EMPTY = "";
    var SPACE = " ";
    var ESCAPE = "\\";
    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 = /^\.*\/|^\.+$/;
    var SLASH2 = "/";
    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 = (object3, key, value) => Object.defineProperty(object3, key, { value });
    var REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g;
    var RETURN_FALSE = () => false;
    var sanitizeRange = (range) => range.replace(
      REGEX_REGEXP_RANGE,
      (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) ? match : EMPTY
    );
    var cleanRangeBackSlash = (slashes) => {
      const { length } = slashes;
      return slashes.slice(0, length - length % 2);
    };
    var REPLACERS = [
      [
        // remove BOM
        // TODO:
        // Other similar zero-width characters?
        /^\uFEFF/,
        () => EMPTY
      ],
      // > Trailing spaces are ignored unless they are quoted with backslash ("\")
      [
        // (a\ ) -> (a )
        // (a  ) -> (a)
        // (a \ ) -> (a  )
        /\\?\s+$/,
        (match) => match.indexOf("\\") === 0 ? SPACE : EMPTY
      ],
      // replace (\ ) with ' '
      [
        /\\\s/g,
        () => 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
        /^(?=[^^])/,
        function startingReplacer() {
          return !/\/(?!$)/.test(this) ? "(?:^|\\/)" : "^";
        }
      ],
      // 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, str) => index + 6 < str.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,
        () => ESCAPE
      ],
      [
        // '\\\\' -> '\\'
        /\\\\/g,
        () => ESCAPE
      ],
      [
        // > 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 === ESCAPE ? `\\[${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}(?=$|\\/$)`
      ],
      // trailing wildcard
      [
        /(\^|\\\/)?\\\*$/,
        (_, p1) => {
          const prefix = p1 ? `${p1}[^/]+` : "[^/]*";
          return `${prefix}(?=$|\\/$)`;
        }
      ]
    ];
    var regexCache = /* @__PURE__ */ Object.create(null);
    var makeRegex = (pattern, ignoreCase) => {
      let source = regexCache[pattern];
      if (!source) {
        source = REPLACERS.reduce(
          (prev, current) => prev.replace(current[0], current[1].bind(pattern)),
          pattern
        );
        regexCache[pattern] = source;
      }
      return ignoreCase ? new RegExp(source, "i") : new RegExp(source);
    };
    var isString2 = (subject) => typeof subject === "string";
    var checkPattern = (pattern) => pattern && isString2(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) && pattern.indexOf("#") !== 0;
    var splitPattern = (pattern) => pattern.split(REGEX_SPLITALL_CRLF);
    var IgnoreRule = class {
      constructor(origin, pattern, negative, regex3) {
        this.origin = origin;
        this.pattern = pattern;
        this.negative = negative;
        this.regex = regex3;
      }
    };
    var createRule = (pattern, ignoreCase) => {
      const origin = pattern;
      let negative = false;
      if (pattern.indexOf("!") === 0) {
        negative = true;
        pattern = pattern.substr(1);
      }
      pattern = pattern.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, "!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, "#");
      const regex3 = makeRegex(pattern, ignoreCase);
      return new IgnoreRule(
        origin,
        pattern,
        negative,
        regex3
      );
    };
    var throwError = (message, Ctor) => {
      throw new Ctor(message);
    };
    var checkPath = (path73, originalPath, doThrow) => {
      if (!isString2(path73)) {
        return doThrow(
          `path must be a string, but got \`${originalPath}\``,
          TypeError
        );
      }
      if (!path73) {
        return doThrow(`path must not be empty`, TypeError);
      }
      if (checkPath.isNotRelative(path73)) {
        const r = "`path.relative()`d";
        return doThrow(
          `path should be a ${r} string, but got "${originalPath}"`,
          RangeError
        );
      }
      return true;
    };
    var isNotRelative = (path73) => REGEX_TEST_INVALID_PATH.test(path73);
    checkPath.isNotRelative = isNotRelative;
    checkPath.convert = (p2) => p2;
    var Ignore = class {
      constructor({
        ignorecase = true,
        ignoreCase = ignorecase,
        allowRelativePaths = false
      } = {}) {
        define2(this, KEY_IGNORE, true);
        this._rules = [];
        this._ignoreCase = ignoreCase;
        this._allowRelativePaths = allowRelativePaths;
        this._initCache();
      }
      _initCache() {
        this._ignoreCache = /* @__PURE__ */ Object.create(null);
        this._testCache = /* @__PURE__ */ Object.create(null);
      }
      _addPattern(pattern) {
        if (pattern && pattern[KEY_IGNORE]) {
          this._rules = this._rules.concat(pattern._rules);
          this._added = true;
          return;
        }
        if (checkPattern(pattern)) {
          const rule = createRule(pattern, this._ignoreCase);
          this._added = true;
          this._rules.push(rule);
        }
      }
      // @param {Array<string> | string | Ignore} pattern
      add(pattern) {
        this._added = false;
        makeArray(
          isString2(pattern) ? splitPattern(pattern) : pattern
        ).forEach(this._addPattern, this);
        if (this._added) {
          this._initCache();
        }
        return this;
      }
      // legacy
      addPattern(pattern) {
        return this.add(pattern);
      }
      //          |           ignored : unignored
      // negative |   0:0   |   0:1   |   1:0   |   1:1
      // -------- | ------- | ------- | ------- | --------
      //     0    |  TEST   |  TEST   |  SKIP   |    X
      //     1    |  TESTIF |  SKIP   |  TEST   |    X
      // - SKIP: always skip
      // - TEST: always test
      // - TESTIF: only test if checkUnignored
      // - X: that never happen
      // @param {boolean} whether should check if the path is unignored,
      //   setting `checkUnignored` to `false` could reduce additional
      //   path matching.
      // @returns {TestResult} true if a file is ignored
      _testOne(path73, checkUnignored) {
        let ignored2 = false;
        let unignored = false;
        this._rules.forEach((rule) => {
          const { negative } = rule;
          if (unignored === negative && ignored2 !== unignored || negative && !ignored2 && !unignored && !checkUnignored) {
            return;
          }
          const matched = rule.regex.test(path73);
          if (matched) {
            ignored2 = !negative;
            unignored = negative;
          }
        });
        return {
          ignored: ignored2,
          unignored
        };
      }
      // @returns {TestResult}
      _test(originalPath, cache, checkUnignored, slices) {
        const path73 = originalPath && checkPath.convert(originalPath);
        checkPath(
          path73,
          originalPath,
          this._allowRelativePaths ? RETURN_FALSE : throwError
        );
        return this._t(path73, cache, checkUnignored, slices);
      }
      _t(path73, cache, checkUnignored, slices) {
        if (path73 in cache) {
          return cache[path73];
        }
        if (!slices) {
          slices = path73.split(SLASH2);
        }
        slices.pop();
        if (!slices.length) {
          return cache[path73] = this._testOne(path73, checkUnignored);
        }
        const parent = this._t(
          slices.join(SLASH2) + SLASH2,
          cache,
          checkUnignored,
          slices
        );
        return cache[path73] = parent.ignored ? parent : this._testOne(path73, checkUnignored);
      }
      ignores(path73) {
        return this._test(path73, this._ignoreCache, false).ignored;
      }
      createFilter() {
        return (path73) => !this.ignores(path73);
      }
      filter(paths) {
        return makeArray(paths).filter(this.createFilter());
      }
      // @returns {TestResult}
      test(path73) {
        return this._test(path73, this._testCache, true);
      }
    };
    var factory = (options) => new Ignore(options);
    var isPathValid = (path73) => checkPath(path73 && checkPath.convert(path73), path73, RETURN_FALSE);
    factory.isPathValid = isPathValid;
    factory.default = factory;
    module2.exports = factory;
    if (
      // Detect `process` so that it can run in browsers.
      typeof process !== "undefined" && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === "win32")
    ) {
      const makePosix = (str) => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, "/");
      checkPath.convert = makePosix;
      const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
      checkPath.isNotRelative = (path73) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path73) || isNotRelative(path73);
    }
  }
});

// ../../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js
var require_src = __commonJS({
  "../../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js"(exports2, module2) {
    "use strict";
    var ESC2 = "\x1B";
    var CSI = `${ESC2}[`;
    var beep = "\x07";
    var cursor = {
      to(x, y) {
        if (!y) return `${CSI}${x + 1}G`;
        return `${CSI}${y + 1};${x + 1}H`;
      },
      move(x, y) {
        let ret = "";
        if (x < 0) ret += `${CSI}${-x}D`;
        else if (x > 0) ret += `${CSI}${x}C`;
        if (y < 0) ret += `${CSI}${-y}A`;
        else if (y > 0) ret += `${CSI}${y}B`;
        return ret;
      },
      up: (count = 1) => `${CSI}${count}A`,
      down: (count = 1) => `${CSI}${count}B`,
      forward: (count = 1) => `${CSI}${count}C`,
      backward: (count = 1) => `${CSI}${count}D`,
      nextLine: (count = 1) => `${CSI}E`.repeat(count),
      prevLine: (count = 1) => `${CSI}F`.repeat(count),
      left: `${CSI}G`,
      hide: `${CSI}?25l`,
      show: `${CSI}?25h`,
      save: `${ESC2}7`,
      restore: `${ESC2}8`
    };
    var scroll = {
      up: (count = 1) => `${CSI}S`.repeat(count),
      down: (count = 1) => `${CSI}T`.repeat(count)
    };
    var erase2 = {
      screen: `${CSI}2J`,
      up: (count = 1) => `${CSI}1J`.repeat(count),
      down: (count = 1) => `${CSI}J`.repeat(count),
      line: `${CSI}2K`,
      lineEnd: `${CSI}K`,
      lineStart: `${CSI}1K`,
      lines(count) {
        let clear = "";
        for (let i = 0; i < count; i++)
          clear += this.line + (i < count - 1 ? cursor.up() : "");
        if (count)
          clear += cursor.left;
        return clear;
      }
    };
    module2.exports = { cursor, scroll, erase: erase2, beep };
  }
});

// ../../node_modules/.pnpm/mimic-fn@2.1.0/node_modules/mimic-fn/index.js
var require_mimic_fn = __commonJS({
  "../../node_modules/.pnpm/mimic-fn@2.1.0/node_modules/mimic-fn/index.js"(exports2, module2) {
    "use strict";
    var mimicFn = (to, from) => {
      for (const prop of Reflect.ownKeys(from)) {
        Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop));
      }
      return to;
    };
    module2.exports = mimicFn;
    module2.exports.default = mimicFn;
  }
});

// ../../node_modules/.pnpm/onetime@5.1.2/node_modules/onetime/index.js
var require_onetime = __commonJS({
  "../../node_modules/.pnpm/onetime@5.1.2/node_modules/onetime/index.js"(exports2, module2) {
    "use strict";
    var mimicFn = require_mimic_fn();
    var calledFunctions = /* @__PURE__ */ new WeakMap();
    var onetime2 = (function_, options = {}) => {
      if (typeof function_ !== "function") {
        throw new TypeError("Expected a function");
      }
      let returnValue;
      let callCount = 0;
      const functionName = function_.displayName || function_.name || "<anonymous>";
      const onetime3 = function(...arguments_) {
        calledFunctions.set(onetime3, ++callCount);
        if (callCount === 1) {
          returnValue = function_.apply(this, arguments_);
          function_ = null;
        } else if (options.throw === true) {
          throw new Error(`Function \`${functionName}\` can only be called once`);
        }
        return returnValue;
      };
      mimicFn(onetime3, function_);
      calledFunctions.set(onetime3, callCount);
      return onetime3;
    };
    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/.pnpm/signal-exit@3.0.7/node_modules/signal-exit/signals.js
var require_signals = __commonJS({
  "../../node_modules/.pnpm/signal-exit@3.0.7/node_modules/signal-exit/signals.js"(exports2, module2) {
    "use strict";
    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/.pnpm/signal-exit@3.0.7/node_modules/signal-exit/index.js
var require_signal_exit = __commonJS({
  "../../node_modules/.pnpm/signal-exit@3.0.7/node_modules/signal-exit/index.js"(exports2, module2) {
    "use strict";
    var process10 = global.process;
    var processOk2 = function(process11) {
      return process11 && typeof process11 === "object" && typeof process11.removeListener === "function" && typeof process11.emit === "function" && typeof process11.reallyExit === "function" && typeof process11.listeners === "function" && typeof process11.kill === "function" && typeof process11.pid === "number" && typeof process11.on === "function";
    };
    if (!processOk2(process10)) {
      module2.exports = function() {
        return function() {
        };
      };
    } else {
      assert24 = require("assert");
      signals2 = require_signals();
      isWin = /^win/i.test(process10.platform);
      EE = require("events");
      if (typeof EE !== "function") {
        EE = EE.EventEmitter;
      }
      if (process10.__signal_exit_emitter__) {
        emitter = process10.__signal_exit_emitter__;
      } else {
        emitter = process10.__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 (!processOk2(global.process)) {
          return function() {
          };
        }
        assert24.equal(typeof cb, "function", "a callback must be provided for exit handler");
        if (loaded === false) {
          load2();
        }
        var ev = "exit";
        if (opts && opts.alwaysLast) {
          ev = "afterexit";
        }
        var remove = function() {
          emitter.removeListener(ev, cb);
          if (emitter.listeners("exit").length === 0 && emitter.listeners("afterexit").length === 0) {
            unload2();
          }
        };
        emitter.on(ev, cb);
        return remove;
      };
      unload2 = function unload3() {
        if (!loaded || !processOk2(global.process)) {
          return;
        }
        loaded = false;
        signals2.forEach(function(sig) {
          try {
            process10.removeListener(sig, sigListeners[sig]);
          } catch (er) {
          }
        });
        process10.emit = originalProcessEmit;
        process10.reallyExit = originalProcessReallyExit;
        emitter.count -= 1;
      };
      module2.exports.unload = unload2;
      emit = function emit2(event, code, signal) {
        if (emitter.emitted[event]) {
          return;
        }
        emitter.emitted[event] = true;
        emitter.emit(event, code, signal);
      };
      sigListeners = {};
      signals2.forEach(function(sig) {
        sigListeners[sig] = function listener() {
          if (!processOk2(global.process)) {
            return;
          }
          var listeners = process10.listeners(sig);
          if (listeners.length === emitter.count) {
            unload2();
            emit("exit", null, sig);
            emit("afterexit", null, sig);
            if (isWin && sig === "SIGHUP") {
              sig = "SIGINT";
            }
            process10.kill(process10.pid, sig);
          }
        };
      });
      module2.exports.signals = function() {
        return signals2;
      };
      loaded = false;
      load2 = function load3() {
        if (loaded || !processOk2(global.process)) {
          return;
        }
        loaded = true;
        emitter.count += 1;
        signals2 = signals2.filter(function(sig) {
          try {
            process10.on(sig, sigListeners[sig]);
            return true;
          } catch (er) {
            return false;
          }
        });
        process10.emit = processEmit;
        process10.reallyExit = processReallyExit;
      };
      module2.exports.load = load2;
      originalProcessReallyExit = process10.reallyExit;
      processReallyExit = function processReallyExit2(code) {
        if (!processOk2(global.process)) {
          return;
        }
        process10.exitCode = code || /* istanbul ignore next */
        0;
        emit("exit", process10.exitCode, null);
        emit("afterexit", process10.exitCode, null);
        originalProcessReallyExit.call(process10, process10.exitCode);
      };
      originalProcessEmit = process10.emit;
      processEmit = function processEmit2(ev, arg) {
        if (ev === "exit" && processOk2(global.process)) {
          if (arg !== void 0) {
            process10.exitCode = arg;
          }
          var ret = originalProcessEmit.apply(this, arguments);
          emit("exit", process10.exitCode, null);
          emit("afterexit", process10.exitCode, null);
          return ret;
        } else {
          return originalProcessEmit.apply(this, arguments);
        }
      };
    }
    var assert24;
    var signals2;
    var isWin;
    var EE;
    var emitter;
    var unload2;
    var emit;
    var sigListeners;
    var loaded;
    var load2;
    var originalProcessReallyExit;
    var processReallyExit;
    var originalProcessEmit;
    var processEmit;
  }
});

// ../../node_modules/.pnpm/eastasianwidth@0.2.0/node_modules/eastasianwidth/eastasianwidth.js
var require_eastasianwidth = __commonJS({
  "../../node_modules/.pnpm/eastasianwidth@0.2.0/node_modules/eastasianwidth/eastasianwidth.js"(exports2, module2) {
    "use strict";
    var eaw = {};
    if ("undefined" == typeof module2) {
      window.eastasianwidth = eaw;
    } else {
      module2.exports = eaw;
    }
    eaw.eastAsianWidth = function(character) {
      var x = character.charCodeAt(0);
      var y = character.length == 2 ? character.charCodeAt(1) : 0;
      var codePoint = x;
      if (55296 <= x && x <= 56319 && (56320 <= y && y <= 57343)) {
        x &= 1023;
        y &= 1023;
        codePoint = x << 10 | y;
        codePoint += 65536;
      }
      if (12288 == codePoint || 65281 <= codePoint && codePoint <= 65376 || 65504 <= codePoint && codePoint <= 65510) {
        return "F";
      }
      if (8361 == codePoint || 65377 <= codePoint && codePoint <= 65470 || 65474 <= codePoint && codePoint <= 65479 || 65482 <= codePoint && codePoint <= 65487 || 65490 <= codePoint && codePoint <= 65495 || 65498 <= codePoint && codePoint <= 65500 || 65512 <= codePoint && codePoint <= 65518) {
        return "H";
      }
      if (4352 <= codePoint && codePoint <= 4447 || 4515 <= codePoint && codePoint <= 4519 || 4602 <= codePoint && codePoint <= 4607 || 9001 <= codePoint && codePoint <= 9002 || 11904 <= codePoint && codePoint <= 11929 || 11931 <= codePoint && codePoint <= 12019 || 12032 <= codePoint && codePoint <= 12245 || 12272 <= codePoint && codePoint <= 12283 || 12289 <= codePoint && codePoint <= 12350 || 12353 <= codePoint && codePoint <= 12438 || 12441 <= codePoint && codePoint <= 12543 || 12549 <= codePoint && codePoint <= 12589 || 12593 <= codePoint && codePoint <= 12686 || 12688 <= codePoint && codePoint <= 12730 || 12736 <= codePoint && codePoint <= 12771 || 12784 <= codePoint && codePoint <= 12830 || 12832 <= codePoint && codePoint <= 12871 || 12880 <= codePoint && codePoint <= 13054 || 13056 <= codePoint && codePoint <= 19903 || 19968 <= codePoint && codePoint <= 42124 || 42128 <= codePoint && codePoint <= 42182 || 43360 <= codePoint && codePoint <= 43388 || 44032 <= codePoint && codePoint <= 55203 || 55216 <= codePoint && codePoint <= 55238 || 55243 <= codePoint && codePoint <= 55291 || 63744 <= codePoint && codePoint <= 64255 || 65040 <= codePoint && codePoint <= 65049 || 65072 <= codePoint && codePoint <= 65106 || 65108 <= codePoint && codePoint <= 65126 || 65128 <= codePoint && codePoint <= 65131 || 110592 <= codePoint && codePoint <= 110593 || 127488 <= codePoint && codePoint <= 127490 || 127504 <= codePoint && codePoint <= 127546 || 127552 <= codePoint && codePoint <= 127560 || 127568 <= codePoint && codePoint <= 127569 || 131072 <= codePoint && codePoint <= 194367 || 177984 <= codePoint && codePoint <= 196605 || 196608 <= codePoint && codePoint <= 262141) {
        return "W";
      }
      if (32 <= codePoint && codePoint <= 126 || 162 <= codePoint && codePoint <= 163 || 165 <= codePoint && codePoint <= 166 || 172 == codePoint || 175 == codePoint || 10214 <= codePoint && codePoint <= 10221 || 10629 <= codePoint && codePoint <= 10630) {
        return "Na";
      }
      if (161 == codePoint || 164 == codePoint || 167 <= codePoint && codePoint <= 168 || 170 == codePoint || 173 <= codePoint && codePoint <= 174 || 176 <= codePoint && codePoint <= 180 || 182 <= codePoint && codePoint <= 186 || 188 <= codePoint && codePoint <= 191 || 198 == codePoint || 208 == codePoint || 215 <= codePoint && codePoint <= 216 || 222 <= codePoint && codePoint <= 225 || 230 == codePoint || 232 <= codePoint && codePoint <= 234 || 236 <= codePoint && codePoint <= 237 || 240 == codePoint || 242 <= codePoint && codePoint <= 243 || 247 <= codePoint && codePoint <= 250 || 252 == codePoint || 254 == codePoint || 257 == codePoint || 273 == codePoint || 275 == codePoint || 283 == codePoint || 294 <= codePoint && codePoint <= 295 || 299 == codePoint || 305 <= codePoint && codePoint <= 307 || 312 == codePoint || 319 <= codePoint && codePoint <= 322 || 324 == codePoint || 328 <= codePoint && codePoint <= 331 || 333 == codePoint || 338 <= codePoint && codePoint <= 339 || 358 <= codePoint && codePoint <= 359 || 363 == codePoint || 462 == codePoint || 464 == codePoint || 466 == codePoint || 468 == codePoint || 470 == codePoint || 472 == codePoint || 474 == codePoint || 476 == codePoint || 593 == codePoint || 609 == codePoint || 708 == codePoint || 711 == codePoint || 713 <= codePoint && codePoint <= 715 || 717 == codePoint || 720 == codePoint || 728 <= codePoint && codePoint <= 731 || 733 == codePoint || 735 == codePoint || 768 <= codePoint && codePoint <= 879 || 913 <= codePoint && codePoint <= 929 || 931 <= codePoint && codePoint <= 937 || 945 <= codePoint && codePoint <= 961 || 963 <= codePoint && codePoint <= 969 || 1025 == codePoint || 1040 <= codePoint && codePoint <= 1103 || 1105 == codePoint || 8208 == codePoint || 8211 <= codePoint && codePoint <= 8214 || 8216 <= codePoint && codePoint <= 8217 || 8220 <= codePoint && codePoint <= 8221 || 8224 <= codePoint && codePoint <= 8226 || 8228 <= codePoint && codePoint <= 8231 || 8240 == codePoint || 8242 <= codePoint && codePoint <= 8243 || 8245 == codePoint || 8251 == codePoint || 8254 == codePoint || 8308 == codePoint || 8319 == codePoint || 8321 <= codePoint && codePoint <= 8324 || 8364 == codePoint || 8451 == codePoint || 8453 == codePoint || 8457 == codePoint || 8467 == codePoint || 8470 == codePoint || 8481 <= codePoint && codePoint <= 8482 || 8486 == codePoint || 8491 == codePoint || 8531 <= codePoint && codePoint <= 8532 || 8539 <= codePoint && codePoint <= 8542 || 8544 <= codePoint && codePoint <= 8555 || 8560 <= codePoint && codePoint <= 8569 || 8585 == codePoint || 8592 <= codePoint && codePoint <= 8601 || 8632 <= codePoint && codePoint <= 8633 || 8658 == codePoint || 8660 == codePoint || 8679 == codePoint || 8704 == codePoint || 8706 <= codePoint && codePoint <= 8707 || 8711 <= codePoint && codePoint <= 8712 || 8715 == codePoint || 8719 == codePoint || 8721 == codePoint || 8725 == codePoint || 8730 == codePoint || 8733 <= codePoint && codePoint <= 8736 || 8739 == codePoint || 8741 == codePoint || 8743 <= codePoint && codePoint <= 8748 || 8750 == codePoint || 8756 <= codePoint && codePoint <= 8759 || 8764 <= codePoint && codePoint <= 8765 || 8776 == codePoint || 8780 == codePoint || 8786 == codePoint || 8800 <= codePoint && codePoint <= 8801 || 8804 <= codePoint && codePoint <= 8807 || 8810 <= codePoint && codePoint <= 8811 || 8814 <= codePoint && codePoint <= 8815 || 8834 <= codePoint && codePoint <= 8835 || 8838 <= codePoint && codePoint <= 8839 || 8853 == codePoint || 8857 == codePoint || 8869 == codePoint || 8895 == codePoint || 8978 == codePoint || 9312 <= codePoint && codePoint <= 9449 || 9451 <= codePoint && codePoint <= 9547 || 9552 <= codePoint && codePoint <= 9587 || 9600 <= codePoint && codePoint <= 9615 || 9618 <= codePoint && codePoint <= 9621 || 9632 <= codePoint && codePoint <= 9633 || 9635 <= codePoint && codePoint <= 9641 || 9650 <= codePoint && codePoint <= 9651 || 9654 <= codePoint && codePoint <= 9655 || 9660 <= codePoint && codePoint <= 9661 || 9664 <= codePoint && codePoint <= 9665 || 9670 <= codePoint && codePoint <= 9672 || 9675 == codePoint || 9678 <= codePoint && codePoint <= 9681 || 9698 <= codePoint && codePoint <= 9701 || 9711 == codePoint || 9733 <= codePoint && codePoint <= 9734 || 9737 == codePoint || 9742 <= codePoint && codePoint <= 9743 || 9748 <= codePoint && codePoint <= 9749 || 9756 == codePoint || 9758 == codePoint || 9792 == codePoint || 9794 == codePoint || 9824 <= codePoint && codePoint <= 9825 || 9827 <= codePoint && codePoint <= 9829 || 9831 <= codePoint && codePoint <= 9834 || 9836 <= codePoint && codePoint <= 9837 || 9839 == codePoint || 9886 <= codePoint && codePoint <= 9887 || 9918 <= codePoint && codePoint <= 9919 || 9924 <= codePoint && codePoint <= 9933 || 9935 <= codePoint && codePoint <= 9953 || 9955 == codePoint || 9960 <= codePoint && codePoint <= 9983 || 10045 == codePoint || 10071 == codePoint || 10102 <= codePoint && codePoint <= 10111 || 11093 <= codePoint && codePoint <= 11097 || 12872 <= codePoint && codePoint <= 12879 || 57344 <= codePoint && codePoint <= 63743 || 65024 <= codePoint && codePoint <= 65039 || 65533 == codePoint || 127232 <= codePoint && codePoint <= 127242 || 127248 <= codePoint && codePoint <= 127277 || 127280 <= codePoint && codePoint <= 127337 || 127344 <= codePoint && codePoint <= 127386 || 917760 <= codePoint && codePoint <= 917999 || 983040 <= codePoint && codePoint <= 1048573 || 1048576 <= codePoint && codePoint <= 1114109) {
        return "A";
      }
      return "N";
    };
    eaw.characterLength = function(character) {
      var code = this.eastAsianWidth(character);
      if (code == "F" || code == "W" || code == "A") {
        return 2;
      } else {
        return 1;
      }
    };
    function stringToArray(string7) {
      return string7.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g) || [];
    }
    eaw.length = function(string7) {
      var characters = stringToArray(string7);
      var len = 0;
      for (var i = 0; i < characters.length; i++) {
        len = len + this.characterLength(characters[i]);
      }
      return len;
    };
    eaw.slice = function(text, start, end) {
      textLen = eaw.length(text);
      start = start ? start : 0;
      end = end ? end : 1;
      if (start < 0) {
        start = textLen + start;
      }
      if (end < 0) {
        end = textLen + end;
      }
      var result = "";
      var eawLen = 0;
      var chars = stringToArray(text);
      for (var i = 0; i < chars.length; i++) {
        var char = chars[i];
        var charLen = eaw.length(char);
        if (eawLen >= start - (charLen == 2 ? 1 : 0)) {
          if (eawLen + charLen <= end) {
            result += char;
          } else {
            break;
          }
        }
        eawLen += charLen;
      }
      return result;
    };
  }
});

// ../../node_modules/.pnpm/emoji-regex@9.2.2/node_modules/emoji-regex/index.js
var require_emoji_regex = __commonJS({
  "../../node_modules/.pnpm/emoji-regex@9.2.2/node_modules/emoji-regex/index.js"(exports2, module2) {
    "use strict";
    module2.exports = function() {
      return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\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|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\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]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\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-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g;
    };
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/constants.js
var require_constants = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/constants.js"(exports2, module2) {
    "use strict";
    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/.pnpm/semver@7.7.3/node_modules/semver/internal/debug.js
var require_debug = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/debug.js"(exports2, module2) {
    "use strict";
    var debug4 = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => {
    };
    module2.exports = debug4;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/re.js
var require_re = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/re.js"(exports2, module2) {
    "use strict";
    var {
      MAX_SAFE_COMPONENT_LENGTH,
      MAX_SAFE_BUILD_LENGTH,
      MAX_LENGTH
    } = require_constants();
    var debug4 = 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 = (value) => {
      for (const [token, max] of safeRegexReplacements) {
        value = value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`);
      }
      return value;
    };
    var createToken = (name, value, isGlobal) => {
      const safe = makeSafeRegex(value);
      const index = R++;
      debug4(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("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/.pnpm/semver@7.7.3/node_modules/semver/internal/parse-options.js
var require_parse_options = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/parse-options.js"(exports2, module2) {
    "use strict";
    var looseOption = Object.freeze({ loose: true });
    var emptyOpts = Object.freeze({});
    var parseOptions = (options) => {
      if (!options) {
        return emptyOpts;
      }
      if (typeof options !== "object") {
        return looseOption;
      }
      return options;
    };
    module2.exports = parseOptions;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/identifiers.js
var require_identifiers = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/identifiers.js"(exports2, module2) {
    "use strict";
    var numeric = /^[0-9]+$/;
    var compareIdentifiers = (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;
    };
    var rcompareIdentifiers = (a, b) => compareIdentifiers(b, a);
    module2.exports = {
      compareIdentifiers,
      rcompareIdentifiers
    };
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/classes/semver.js
var require_semver = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/classes/semver.js"(exports2, module2) {
    "use strict";
    var debug4 = require_debug();
    var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants();
    var { safeRe: re, t } = require_re();
    var parseOptions = require_parse_options();
    var { compareIdentifiers } = require_identifiers();
    var SemVer = class _SemVer {
      constructor(version4, options) {
        options = parseOptions(options);
        if (version4 instanceof _SemVer) {
          if (version4.loose === !!options.loose && version4.includePrerelease === !!options.includePrerelease) {
            return version4;
          } else {
            version4 = version4.version;
          }
        } else if (typeof version4 !== "string") {
          throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version4}".`);
        }
        if (version4.length > MAX_LENGTH) {
          throw new TypeError(
            `version is longer than ${MAX_LENGTH} characters`
          );
        }
        debug4("SemVer", version4, options);
        this.options = options;
        this.loose = !!options.loose;
        this.includePrerelease = !!options.includePrerelease;
        const m = version4.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]);
        if (!m) {
          throw new TypeError(`Invalid Version: ${version4}`);
        }
        this.raw = version4;
        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) {
        debug4("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];
          debug4("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];
          debug4("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(release, identifier, identifierBase) {
        if (release.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 (release) {
          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 (compareIdentifiers(this.prerelease[0], identifier) === 0) {
                if (isNaN(this.prerelease[1])) {
                  this.prerelease = prerelease;
                }
              } else {
                this.prerelease = prerelease;
              }
            }
            break;
          }
          default:
            throw new Error(`invalid increment argument: ${release}`);
        }
        this.raw = this.format();
        if (this.build.length) {
          this.raw += `+${this.build.join(".")}`;
        }
        return this;
      }
    };
    module2.exports = SemVer;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/parse.js
var require_parse = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/parse.js"(exports2, module2) {
    "use strict";
    var SemVer = require_semver();
    var parse9 = (version4, options, throwErrors = false) => {
      if (version4 instanceof SemVer) {
        return version4;
      }
      try {
        return new SemVer(version4, options);
      } catch (er) {
        if (!throwErrors) {
          return null;
        }
        throw er;
      }
    };
    module2.exports = parse9;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/valid.js
var require_valid = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/valid.js"(exports2, module2) {
    "use strict";
    var parse9 = require_parse();
    var valid = (version4, options) => {
      const v = parse9(version4, options);
      return v ? v.version : null;
    };
    module2.exports = valid;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/clean.js
var require_clean = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/clean.js"(exports2, module2) {
    "use strict";
    var parse9 = require_parse();
    var clean = (version4, options) => {
      const s = parse9(version4.trim().replace(/^[=v]+/, ""), options);
      return s ? s.version : null;
    };
    module2.exports = clean;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/inc.js
var require_inc = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/inc.js"(exports2, module2) {
    "use strict";
    var SemVer = require_semver();
    var inc = (version4, release, options, identifier, identifierBase) => {
      if (typeof options === "string") {
        identifierBase = identifier;
        identifier = options;
        options = void 0;
      }
      try {
        return new SemVer(
          version4 instanceof SemVer ? version4.version : version4,
          options
        ).inc(release, identifier, identifierBase).version;
      } catch (er) {
        return null;
      }
    };
    module2.exports = inc;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/diff.js
var require_diff = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/diff.js"(exports2, module2) {
    "use strict";
    var parse9 = require_parse();
    var diff = (version1, version22) => {
      const v1 = parse9(version1, null, true);
      const v2 = parse9(version22, null, true);
      const comparison = v1.compare(v2);
      if (comparison === 0) {
        return null;
      }
      const v1Higher = comparison > 0;
      const highVersion = v1Higher ? v1 : v2;
      const lowVersion = v1Higher ? v2 : v1;
      const highHasPre = !!highVersion.prerelease.length;
      const lowHasPre = !!lowVersion.prerelease.length;
      if (lowHasPre && !highHasPre) {
        if (!lowVersion.patch && !lowVersion.minor) {
          return "major";
        }
        if (lowVersion.compareMain(highVersion) === 0) {
          if (lowVersion.minor && !lowVersion.patch) {
            return "minor";
          }
          return "patch";
        }
      }
      const prefix = highHasPre ? "pre" : "";
      if (v1.major !== v2.major) {
        return prefix + "major";
      }
      if (v1.minor !== v2.minor) {
        return prefix + "minor";
      }
      if (v1.patch !== v2.patch) {
        return prefix + "patch";
      }
      return "prerelease";
    };
    module2.exports = diff;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/major.js
var require_major = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/major.js"(exports2, module2) {
    "use strict";
    var SemVer = require_semver();
    var major = (a, loose) => new SemVer(a, loose).major;
    module2.exports = major;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/minor.js
var require_minor = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/minor.js"(exports2, module2) {
    "use strict";
    var SemVer = require_semver();
    var minor = (a, loose) => new SemVer(a, loose).minor;
    module2.exports = minor;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/patch.js
var require_patch = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/patch.js"(exports2, module2) {
    "use strict";
    var SemVer = require_semver();
    var patch = (a, loose) => new SemVer(a, loose).patch;
    module2.exports = patch;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/prerelease.js
var require_prerelease = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/prerelease.js"(exports2, module2) {
    "use strict";
    var parse9 = require_parse();
    var prerelease = (version4, options) => {
      const parsed = parse9(version4, options);
      return parsed && parsed.prerelease.length ? parsed.prerelease : null;
    };
    module2.exports = prerelease;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/compare.js
var require_compare = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/compare.js"(exports2, module2) {
    "use strict";
    var SemVer = require_semver();
    var compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose));
    module2.exports = compare;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/rcompare.js
var require_rcompare = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/rcompare.js"(exports2, module2) {
    "use strict";
    var compare = require_compare();
    var rcompare = (a, b, loose) => compare(b, a, loose);
    module2.exports = rcompare;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/compare-loose.js
var require_compare_loose = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/compare-loose.js"(exports2, module2) {
    "use strict";
    var compare = require_compare();
    var compareLoose = (a, b) => compare(a, b, true);
    module2.exports = compareLoose;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/compare-build.js
var require_compare_build = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/compare-build.js"(exports2, module2) {
    "use strict";
    var SemVer = require_semver();
    var compareBuild = (a, b, loose) => {
      const versionA = new SemVer(a, loose);
      const versionB = new SemVer(b, loose);
      return versionA.compare(versionB) || versionA.compareBuild(versionB);
    };
    module2.exports = compareBuild;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/sort.js
var require_sort = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/sort.js"(exports2, module2) {
    "use strict";
    var compareBuild = require_compare_build();
    var sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose));
    module2.exports = sort;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/rsort.js
var require_rsort = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/rsort.js"(exports2, module2) {
    "use strict";
    var compareBuild = require_compare_build();
    var rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose));
    module2.exports = rsort;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/gt.js
var require_gt = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/gt.js"(exports2, module2) {
    "use strict";
    var compare = require_compare();
    var gt = (a, b, loose) => compare(a, b, loose) > 0;
    module2.exports = gt;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/lt.js
var require_lt = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/lt.js"(exports2, module2) {
    "use strict";
    var compare = require_compare();
    var lt = (a, b, loose) => compare(a, b, loose) < 0;
    module2.exports = lt;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/eq.js
var require_eq = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/eq.js"(exports2, module2) {
    "use strict";
    var compare = require_compare();
    var eq = (a, b, loose) => compare(a, b, loose) === 0;
    module2.exports = eq;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/neq.js
var require_neq = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/neq.js"(exports2, module2) {
    "use strict";
    var compare = require_compare();
    var neq = (a, b, loose) => compare(a, b, loose) !== 0;
    module2.exports = neq;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/gte.js
var require_gte = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/gte.js"(exports2, module2) {
    "use strict";
    var compare = require_compare();
    var gte = (a, b, loose) => compare(a, b, loose) >= 0;
    module2.exports = gte;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/lte.js
var require_lte = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/lte.js"(exports2, module2) {
    "use strict";
    var compare = require_compare();
    var lte = (a, b, loose) => compare(a, b, loose) <= 0;
    module2.exports = lte;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/cmp.js
var require_cmp = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/cmp.js"(exports2, module2) {
    "use strict";
    var eq = require_eq();
    var neq = require_neq();
    var gt = require_gt();
    var gte = require_gte();
    var lt = require_lt();
    var lte = require_lte();
    var cmp = (a, op, b, loose) => {
      switch (op) {
        case "===":
          if (typeof a === "object") {
            a = a.version;
          }
          if (typeof b === "object") {
            b = b.version;
          }
          return a === b;
        case "!==":
          if (typeof a === "object") {
            a = a.version;
          }
          if (typeof b === "object") {
            b = b.version;
          }
          return a !== b;
        case "":
        case "=":
        case "==":
          return eq(a, b, loose);
        case "!=":
          return neq(a, b, loose);
        case ">":
          return gt(a, b, loose);
        case ">=":
          return gte(a, b, loose);
        case "<":
          return lt(a, b, loose);
        case "<=":
          return lte(a, b, loose);
        default:
          throw new TypeError(`Invalid operator: ${op}`);
      }
    };
    module2.exports = cmp;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/coerce.js
var require_coerce = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/coerce.js"(exports2, module2) {
    "use strict";
    var SemVer = require_semver();
    var parse9 = require_parse();
    var { safeRe: re, t } = require_re();
    var coerce = (version4, options) => {
      if (version4 instanceof SemVer) {
        return version4;
      }
      if (typeof version4 === "number") {
        version4 = String(version4);
      }
      if (typeof version4 !== "string") {
        return null;
      }
      options = options || {};
      let match = null;
      if (!options.rtl) {
        match = version4.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]);
      } else {
        const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL];
        let next;
        while ((next = coerceRtlRegex.exec(version4)) && (!match || match.index + match[0].length !== version4.length)) {
          if (!match || next.index + next[0].length !== match.index + match[0].length) {
            match = next;
          }
          coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length;
        }
        coerceRtlRegex.lastIndex = -1;
      }
      if (match === null) {
        return null;
      }
      const major = match[2];
      const minor = match[3] || "0";
      const patch = match[4] || "0";
      const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : "";
      const build = options.includePrerelease && match[6] ? `+${match[6]}` : "";
      return parse9(`${major}.${minor}.${patch}${prerelease}${build}`, options);
    };
    module2.exports = coerce;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/lrucache.js
var require_lrucache = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/lrucache.js"(exports2, module2) {
    "use strict";
    var LRUCache = class {
      constructor() {
        this.max = 1e3;
        this.map = /* @__PURE__ */ new Map();
      }
      get(key) {
        const value = this.map.get(key);
        if (value === void 0) {
          return void 0;
        } else {
          this.map.delete(key);
          this.map.set(key, value);
          return value;
        }
      }
      delete(key) {
        return this.map.delete(key);
      }
      set(key, value) {
        const deleted = this.delete(key);
        if (!deleted && value !== void 0) {
          if (this.map.size >= this.max) {
            const firstKey = this.map.keys().next().value;
            this.delete(firstKey);
          }
          this.map.set(key, value);
        }
        return this;
      }
    };
    module2.exports = LRUCache;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/classes/range.js
var require_range = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/classes/range.js"(exports2, module2) {
    "use strict";
    var SPACE_CHARACTERS = /\s+/g;
    var Range = class _Range {
      constructor(range, options) {
        options = parseOptions(options);
        if (range instanceof _Range) {
          if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
            return range;
          } else {
            return new _Range(range.raw, options);
          }
        }
        if (range instanceof Comparator) {
          this.raw = range.value;
          this.set = [[range]];
          this.formatted = void 0;
          return this;
        }
        this.options = options;
        this.loose = !!options.loose;
        this.includePrerelease = !!options.includePrerelease;
        this.raw = range.trim().replace(SPACE_CHARACTERS, " ");
        this.set = this.raw.split("||").map((r) => this.parseRange(r.trim())).filter((c2) => c2.length);
        if (!this.set.length) {
          throw new TypeError(`Invalid SemVer Range: ${this.raw}`);
        }
        if (this.set.length > 1) {
          const first = this.set[0];
          this.set = this.set.filter((c2) => !isNullSet(c2[0]));
          if (this.set.length === 0) {
            this.set = [first];
          } else if (this.set.length > 1) {
            for (const c2 of this.set) {
              if (c2.length === 1 && isAny(c2[0])) {
                this.set = [c2];
                break;
              }
            }
          }
        }
        this.formatted = void 0;
      }
      get range() {
        if (this.formatted === void 0) {
          this.formatted = "";
          for (let i = 0; i < this.set.length; i++) {
            if (i > 0) {
              this.formatted += "||";
            }
            const comps = this.set[i];
            for (let k = 0; k < comps.length; k++) {
              if (k > 0) {
                this.formatted += " ";
              }
              this.formatted += comps[k].toString().trim();
            }
          }
        }
        return this.formatted;
      }
      format() {
        return this.range;
      }
      toString() {
        return this.range;
      }
      parseRange(range) {
        const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE);
        const memoKey = memoOpts + ":" + range;
        const cached3 = cache.get(memoKey);
        if (cached3) {
          return cached3;
        }
        const loose = this.options.loose;
        const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE];
        range = range.replace(hr, hyphenReplace(this.options.includePrerelease));
        debug4("hyphen replace", range);
        range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace);
        debug4("comparator trim", range);
        range = range.replace(re[t.TILDETRIM], tildeTrimReplace);
        debug4("tilde trim", range);
        range = range.replace(re[t.CARETTRIM], caretTrimReplace);
        debug4("caret trim", range);
        let rangeList = range.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options));
        if (loose) {
          rangeList = rangeList.filter((comp) => {
            debug4("loose invalid filter", comp, this.options);
            return !!comp.match(re[t.COMPARATORLOOSE]);
          });
        }
        debug4("range list", rangeList);
        const rangeMap = /* @__PURE__ */ new Map();
        const comparators = rangeList.map((comp) => new Comparator(comp, this.options));
        for (const comp of comparators) {
          if (isNullSet(comp)) {
            return [comp];
          }
          rangeMap.set(comp.value, comp);
        }
        if (rangeMap.size > 1 && rangeMap.has("")) {
          rangeMap.delete("");
        }
        const result = [...rangeMap.values()];
        cache.set(memoKey, result);
        return result;
      }
      intersects(range, options) {
        if (!(range instanceof _Range)) {
          throw new TypeError("a Range is required");
        }
        return this.set.some((thisComparators) => {
          return isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => {
            return isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => {
              return rangeComparators.every((rangeComparator) => {
                return thisComparator.intersects(rangeComparator, options);
              });
            });
          });
        });
      }
      // if ANY of the sets match ALL of its comparators, then pass
      test(version4) {
        if (!version4) {
          return false;
        }
        if (typeof version4 === "string") {
          try {
            version4 = new SemVer(version4, this.options);
          } catch (er) {
            return false;
          }
        }
        for (let i = 0; i < this.set.length; i++) {
          if (testSet(this.set[i], version4, this.options)) {
            return true;
          }
        }
        return false;
      }
    };
    module2.exports = Range;
    var LRU = require_lrucache();
    var cache = new LRU();
    var parseOptions = require_parse_options();
    var Comparator = require_comparator();
    var debug4 = require_debug();
    var SemVer = require_semver();
    var {
      safeRe: re,
      t,
      comparatorTrimReplace,
      tildeTrimReplace,
      caretTrimReplace
    } = require_re();
    var { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require_constants();
    var isNullSet = (c2) => c2.value === "<0.0.0-0";
    var isAny = (c2) => c2.value === "";
    var isSatisfiable = (comparators, options) => {
      let result = true;
      const remainingComparators = comparators.slice();
      let testComparator = remainingComparators.pop();
      while (result && remainingComparators.length) {
        result = remainingComparators.every((otherComparator) => {
          return testComparator.intersects(otherComparator, options);
        });
        testComparator = remainingComparators.pop();
      }
      return result;
    };
    var parseComparator = (comp, options) => {
      comp = comp.replace(re[t.BUILD], "");
      debug4("comp", comp, options);
      comp = replaceCarets(comp, options);
      debug4("caret", comp);
      comp = replaceTildes(comp, options);
      debug4("tildes", comp);
      comp = replaceXRanges(comp, options);
      debug4("xrange", comp);
      comp = replaceStars(comp, options);
      debug4("stars", comp);
      return comp;
    };
    var isX = (id) => !id || id.toLowerCase() === "x" || id === "*";
    var replaceTildes = (comp, options) => {
      return comp.trim().split(/\s+/).map((c2) => replaceTilde(c2, options)).join(" ");
    };
    var replaceTilde = (comp, options) => {
      const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE];
      return comp.replace(r, (_, M2, m, p2, pr) => {
        debug4("tilde", comp, _, M2, m, p2, pr);
        let ret;
        if (isX(M2)) {
          ret = "";
        } else if (isX(m)) {
          ret = `>=${M2}.0.0 <${+M2 + 1}.0.0-0`;
        } else if (isX(p2)) {
          ret = `>=${M2}.${m}.0 <${M2}.${+m + 1}.0-0`;
        } else if (pr) {
          debug4("replaceTilde pr", pr);
          ret = `>=${M2}.${m}.${p2}-${pr} <${M2}.${+m + 1}.0-0`;
        } else {
          ret = `>=${M2}.${m}.${p2} <${M2}.${+m + 1}.0-0`;
        }
        debug4("tilde return", ret);
        return ret;
      });
    };
    var replaceCarets = (comp, options) => {
      return comp.trim().split(/\s+/).map((c2) => replaceCaret(c2, options)).join(" ");
    };
    var replaceCaret = (comp, options) => {
      debug4("caret", comp, options);
      const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET];
      const z3 = options.includePrerelease ? "-0" : "";
      return comp.replace(r, (_, M2, m, p2, pr) => {
        debug4("caret", comp, _, M2, m, p2, pr);
        let ret;
        if (isX(M2)) {
          ret = "";
        } else if (isX(m)) {
          ret = `>=${M2}.0.0${z3} <${+M2 + 1}.0.0-0`;
        } else if (isX(p2)) {
          if (M2 === "0") {
            ret = `>=${M2}.${m}.0${z3} <${M2}.${+m + 1}.0-0`;
          } else {
            ret = `>=${M2}.${m}.0${z3} <${+M2 + 1}.0.0-0`;
          }
        } else if (pr) {
          debug4("replaceCaret pr", pr);
          if (M2 === "0") {
            if (m === "0") {
              ret = `>=${M2}.${m}.${p2}-${pr} <${M2}.${m}.${+p2 + 1}-0`;
            } else {
              ret = `>=${M2}.${m}.${p2}-${pr} <${M2}.${+m + 1}.0-0`;
            }
          } else {
            ret = `>=${M2}.${m}.${p2}-${pr} <${+M2 + 1}.0.0-0`;
          }
        } else {
          debug4("no pr");
          if (M2 === "0") {
            if (m === "0") {
              ret = `>=${M2}.${m}.${p2}${z3} <${M2}.${m}.${+p2 + 1}-0`;
            } else {
              ret = `>=${M2}.${m}.${p2}${z3} <${M2}.${+m + 1}.0-0`;
            }
          } else {
            ret = `>=${M2}.${m}.${p2} <${+M2 + 1}.0.0-0`;
          }
        }
        debug4("caret return", ret);
        return ret;
      });
    };
    var replaceXRanges = (comp, options) => {
      debug4("replaceXRanges", comp, options);
      return comp.split(/\s+/).map((c2) => replaceXRange(c2, options)).join(" ");
    };
    var replaceXRange = (comp, options) => {
      comp = comp.trim();
      const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE];
      return comp.replace(r, (ret, gtlt, M2, m, p2, pr) => {
        debug4("xRange", comp, ret, gtlt, M2, m, p2, pr);
        const xM = isX(M2);
        const xm = xM || isX(m);
        const xp = xm || isX(p2);
        const anyX = xp;
        if (gtlt === "=" && anyX) {
          gtlt = "";
        }
        pr = options.includePrerelease ? "-0" : "";
        if (xM) {
          if (gtlt === ">" || gtlt === "<") {
            ret = "<0.0.0-0";
          } else {
            ret = "*";
          }
        } else if (gtlt && anyX) {
          if (xm) {
            m = 0;
          }
          p2 = 0;
          if (gtlt === ">") {
            gtlt = ">=";
            if (xm) {
              M2 = +M2 + 1;
              m = 0;
              p2 = 0;
            } else {
              m = +m + 1;
              p2 = 0;
            }
          } else if (gtlt === "<=") {
            gtlt = "<";
            if (xm) {
              M2 = +M2 + 1;
            } else {
              m = +m + 1;
            }
          }
          if (gtlt === "<") {
            pr = "-0";
          }
          ret = `${gtlt + M2}.${m}.${p2}${pr}`;
        } else if (xm) {
          ret = `>=${M2}.0.0${pr} <${+M2 + 1}.0.0-0`;
        } else if (xp) {
          ret = `>=${M2}.${m}.0${pr} <${M2}.${+m + 1}.0-0`;
        }
        debug4("xRange return", ret);
        return ret;
      });
    };
    var replaceStars = (comp, options) => {
      debug4("replaceStars", comp, options);
      return comp.trim().replace(re[t.STAR], "");
    };
    var replaceGTE0 = (comp, options) => {
      debug4("replaceGTE0", comp, options);
      return comp.trim().replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], "");
    };
    var hyphenReplace = (incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => {
      if (isX(fM)) {
        from = "";
      } else if (isX(fm)) {
        from = `>=${fM}.0.0${incPr ? "-0" : ""}`;
      } else if (isX(fp)) {
        from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`;
      } else if (fpr) {
        from = `>=${from}`;
      } else {
        from = `>=${from}${incPr ? "-0" : ""}`;
      }
      if (isX(tM)) {
        to = "";
      } else if (isX(tm)) {
        to = `<${+tM + 1}.0.0-0`;
      } else if (isX(tp)) {
        to = `<${tM}.${+tm + 1}.0-0`;
      } else if (tpr) {
        to = `<=${tM}.${tm}.${tp}-${tpr}`;
      } else if (incPr) {
        to = `<${tM}.${tm}.${+tp + 1}-0`;
      } else {
        to = `<=${to}`;
      }
      return `${from} ${to}`.trim();
    };
    var testSet = (set3, version4, options) => {
      for (let i = 0; i < set3.length; i++) {
        if (!set3[i].test(version4)) {
          return false;
        }
      }
      if (version4.prerelease.length && !options.includePrerelease) {
        for (let i = 0; i < set3.length; i++) {
          debug4(set3[i].semver);
          if (set3[i].semver === Comparator.ANY) {
            continue;
          }
          if (set3[i].semver.prerelease.length > 0) {
            const allowed = set3[i].semver;
            if (allowed.major === version4.major && allowed.minor === version4.minor && allowed.patch === version4.patch) {
              return true;
            }
          }
        }
        return false;
      }
      return true;
    };
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/classes/comparator.js
var require_comparator = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/classes/comparator.js"(exports2, module2) {
    "use strict";
    var ANY = /* @__PURE__ */ Symbol("SemVer ANY");
    var Comparator = class _Comparator {
      static get ANY() {
        return ANY;
      }
      constructor(comp, options) {
        options = parseOptions(options);
        if (comp instanceof _Comparator) {
          if (comp.loose === !!options.loose) {
            return comp;
          } else {
            comp = comp.value;
          }
        }
        comp = comp.trim().split(/\s+/).join(" ");
        debug4("comparator", comp, options);
        this.options = options;
        this.loose = !!options.loose;
        this.parse(comp);
        if (this.semver === ANY) {
          this.value = "";
        } else {
          this.value = this.operator + this.semver.version;
        }
        debug4("comp", this);
      }
      parse(comp) {
        const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
        const m = comp.match(r);
        if (!m) {
          throw new TypeError(`Invalid comparator: ${comp}`);
        }
        this.operator = m[1] !== void 0 ? m[1] : "";
        if (this.operator === "=") {
          this.operator = "";
        }
        if (!m[2]) {
          this.semver = ANY;
        } else {
          this.semver = new SemVer(m[2], this.options.loose);
        }
      }
      toString() {
        return this.value;
      }
      test(version4) {
        debug4("Comparator.test", version4, this.options.loose);
        if (this.semver === ANY || version4 === ANY) {
          return true;
        }
        if (typeof version4 === "string") {
          try {
            version4 = new SemVer(version4, this.options);
          } catch (er) {
            return false;
          }
        }
        return cmp(version4, this.operator, this.semver, this.options);
      }
      intersects(comp, options) {
        if (!(comp instanceof _Comparator)) {
          throw new TypeError("a Comparator is required");
        }
        if (this.operator === "") {
          if (this.value === "") {
            return true;
          }
          return new Range(comp.value, options).test(this.value);
        } else if (comp.operator === "") {
          if (comp.value === "") {
            return true;
          }
          return new Range(this.value, options).test(comp.semver);
        }
        options = parseOptions(options);
        if (options.includePrerelease && (this.value === "<0.0.0-0" || comp.value === "<0.0.0-0")) {
          return false;
        }
        if (!options.includePrerelease && (this.value.startsWith("<0.0.0") || comp.value.startsWith("<0.0.0"))) {
          return false;
        }
        if (this.operator.startsWith(">") && comp.operator.startsWith(">")) {
          return true;
        }
        if (this.operator.startsWith("<") && comp.operator.startsWith("<")) {
          return true;
        }
        if (this.semver.version === comp.semver.version && this.operator.includes("=") && comp.operator.includes("=")) {
          return true;
        }
        if (cmp(this.semver, "<", comp.semver, options) && this.operator.startsWith(">") && comp.operator.startsWith("<")) {
          return true;
        }
        if (cmp(this.semver, ">", comp.semver, options) && this.operator.startsWith("<") && comp.operator.startsWith(">")) {
          return true;
        }
        return false;
      }
    };
    module2.exports = Comparator;
    var parseOptions = require_parse_options();
    var { safeRe: re, t } = require_re();
    var cmp = require_cmp();
    var debug4 = require_debug();
    var SemVer = require_semver();
    var Range = require_range();
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/satisfies.js
var require_satisfies = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/functions/satisfies.js"(exports2, module2) {
    "use strict";
    var Range = require_range();
    var satisfies = (version4, range, options) => {
      try {
        range = new Range(range, options);
      } catch (er) {
        return false;
      }
      return range.test(version4);
    };
    module2.exports = satisfies;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/to-comparators.js
var require_to_comparators = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/to-comparators.js"(exports2, module2) {
    "use strict";
    var Range = require_range();
    var toComparators = (range, options) => new Range(range, options).set.map((comp) => comp.map((c2) => c2.value).join(" ").trim().split(" "));
    module2.exports = toComparators;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/max-satisfying.js
var require_max_satisfying = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/max-satisfying.js"(exports2, module2) {
    "use strict";
    var SemVer = require_semver();
    var Range = require_range();
    var maxSatisfying = (versions, range, options) => {
      let max = null;
      let maxSV = null;
      let rangeObj = null;
      try {
        rangeObj = new Range(range, options);
      } catch (er) {
        return null;
      }
      versions.forEach((v) => {
        if (rangeObj.test(v)) {
          if (!max || maxSV.compare(v) === -1) {
            max = v;
            maxSV = new SemVer(max, options);
          }
        }
      });
      return max;
    };
    module2.exports = maxSatisfying;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/min-satisfying.js
var require_min_satisfying = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/min-satisfying.js"(exports2, module2) {
    "use strict";
    var SemVer = require_semver();
    var Range = require_range();
    var minSatisfying = (versions, range, options) => {
      let min = null;
      let minSV = null;
      let rangeObj = null;
      try {
        rangeObj = new Range(range, options);
      } catch (er) {
        return null;
      }
      versions.forEach((v) => {
        if (rangeObj.test(v)) {
          if (!min || minSV.compare(v) === 1) {
            min = v;
            minSV = new SemVer(min, options);
          }
        }
      });
      return min;
    };
    module2.exports = minSatisfying;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/min-version.js
var require_min_version = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/min-version.js"(exports2, module2) {
    "use strict";
    var SemVer = require_semver();
    var Range = require_range();
    var gt = require_gt();
    var minVersion = (range, loose) => {
      range = new Range(range, loose);
      let minver = new SemVer("0.0.0");
      if (range.test(minver)) {
        return minver;
      }
      minver = new SemVer("0.0.0-0");
      if (range.test(minver)) {
        return minver;
      }
      minver = null;
      for (let i = 0; i < range.set.length; ++i) {
        const comparators = range.set[i];
        let setMin = null;
        comparators.forEach((comparator) => {
          const compver = new SemVer(comparator.semver.version);
          switch (comparator.operator) {
            case ">":
              if (compver.prerelease.length === 0) {
                compver.patch++;
              } else {
                compver.prerelease.push(0);
              }
              compver.raw = compver.format();
            /* fallthrough */
            case "":
            case ">=":
              if (!setMin || gt(compver, setMin)) {
                setMin = compver;
              }
              break;
            case "<":
            case "<=":
              break;
            /* istanbul ignore next */
            default:
              throw new Error(`Unexpected operation: ${comparator.operator}`);
          }
        });
        if (setMin && (!minver || gt(minver, setMin))) {
          minver = setMin;
        }
      }
      if (minver && range.test(minver)) {
        return minver;
      }
      return null;
    };
    module2.exports = minVersion;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/valid.js
var require_valid2 = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/valid.js"(exports2, module2) {
    "use strict";
    var Range = require_range();
    var validRange = (range, options) => {
      try {
        return new Range(range, options).range || "*";
      } catch (er) {
        return null;
      }
    };
    module2.exports = validRange;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/outside.js
var require_outside = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/outside.js"(exports2, module2) {
    "use strict";
    var SemVer = require_semver();
    var Comparator = require_comparator();
    var { ANY } = Comparator;
    var Range = require_range();
    var satisfies = require_satisfies();
    var gt = require_gt();
    var lt = require_lt();
    var lte = require_lte();
    var gte = require_gte();
    var outside = (version4, range, hilo, options) => {
      version4 = new SemVer(version4, options);
      range = new Range(range, options);
      let gtfn, ltefn, ltfn, comp, ecomp;
      switch (hilo) {
        case ">":
          gtfn = gt;
          ltefn = lte;
          ltfn = lt;
          comp = ">";
          ecomp = ">=";
          break;
        case "<":
          gtfn = lt;
          ltefn = gte;
          ltfn = gt;
          comp = "<";
          ecomp = "<=";
          break;
        default:
          throw new TypeError('Must provide a hilo val of "<" or ">"');
      }
      if (satisfies(version4, range, options)) {
        return false;
      }
      for (let i = 0; i < range.set.length; ++i) {
        const comparators = range.set[i];
        let high = null;
        let low = null;
        comparators.forEach((comparator) => {
          if (comparator.semver === ANY) {
            comparator = new Comparator(">=0.0.0");
          }
          high = high || comparator;
          low = low || comparator;
          if (gtfn(comparator.semver, high.semver, options)) {
            high = comparator;
          } else if (ltfn(comparator.semver, low.semver, options)) {
            low = comparator;
          }
        });
        if (high.operator === comp || high.operator === ecomp) {
          return false;
        }
        if ((!low.operator || low.operator === comp) && ltefn(version4, low.semver)) {
          return false;
        } else if (low.operator === ecomp && ltfn(version4, low.semver)) {
          return false;
        }
      }
      return true;
    };
    module2.exports = outside;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/gtr.js
var require_gtr = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/gtr.js"(exports2, module2) {
    "use strict";
    var outside = require_outside();
    var gtr = (version4, range, options) => outside(version4, range, ">", options);
    module2.exports = gtr;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/ltr.js
var require_ltr = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/ltr.js"(exports2, module2) {
    "use strict";
    var outside = require_outside();
    var ltr = (version4, range, options) => outside(version4, range, "<", options);
    module2.exports = ltr;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/intersects.js
var require_intersects = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/intersects.js"(exports2, module2) {
    "use strict";
    var Range = require_range();
    var intersects = (r1, r2, options) => {
      r1 = new Range(r1, options);
      r2 = new Range(r2, options);
      return r1.intersects(r2, options);
    };
    module2.exports = intersects;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/simplify.js
var require_simplify = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/simplify.js"(exports2, module2) {
    "use strict";
    var satisfies = require_satisfies();
    var compare = require_compare();
    module2.exports = (versions, range, options) => {
      const set3 = [];
      let first = null;
      let prev = null;
      const v = versions.sort((a, b) => compare(a, b, options));
      for (const version4 of v) {
        const included = satisfies(version4, range, options);
        if (included) {
          prev = version4;
          if (!first) {
            first = version4;
          }
        } else {
          if (prev) {
            set3.push([first, prev]);
          }
          prev = null;
          first = null;
        }
      }
      if (first) {
        set3.push([first, null]);
      }
      const ranges = [];
      for (const [min, max] of set3) {
        if (min === max) {
          ranges.push(min);
        } else if (!max && min === v[0]) {
          ranges.push("*");
        } else if (!max) {
          ranges.push(`>=${min}`);
        } else if (min === v[0]) {
          ranges.push(`<=${max}`);
        } else {
          ranges.push(`${min} - ${max}`);
        }
      }
      const simplified = ranges.join(" || ");
      const original = typeof range.raw === "string" ? range.raw : String(range);
      return simplified.length < original.length ? simplified : range;
    };
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/subset.js
var require_subset = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/ranges/subset.js"(exports2, module2) {
    "use strict";
    var Range = require_range();
    var Comparator = require_comparator();
    var { ANY } = Comparator;
    var satisfies = require_satisfies();
    var compare = require_compare();
    var subset = (sub, dom, options = {}) => {
      if (sub === dom) {
        return true;
      }
      sub = new Range(sub, options);
      dom = new Range(dom, options);
      let sawNonNull = false;
      OUTER: for (const simpleSub of sub.set) {
        for (const simpleDom of dom.set) {
          const isSub = simpleSubset(simpleSub, simpleDom, options);
          sawNonNull = sawNonNull || isSub !== null;
          if (isSub) {
            continue OUTER;
          }
        }
        if (sawNonNull) {
          return false;
        }
      }
      return true;
    };
    var minimumVersionWithPreRelease = [new Comparator(">=0.0.0-0")];
    var minimumVersion = [new Comparator(">=0.0.0")];
    var simpleSubset = (sub, dom, options) => {
      if (sub === dom) {
        return true;
      }
      if (sub.length === 1 && sub[0].semver === ANY) {
        if (dom.length === 1 && dom[0].semver === ANY) {
          return true;
        } else if (options.includePrerelease) {
          sub = minimumVersionWithPreRelease;
        } else {
          sub = minimumVersion;
        }
      }
      if (dom.length === 1 && dom[0].semver === ANY) {
        if (options.includePrerelease) {
          return true;
        } else {
          dom = minimumVersion;
        }
      }
      const eqSet = /* @__PURE__ */ new Set();
      let gt, lt;
      for (const c2 of sub) {
        if (c2.operator === ">" || c2.operator === ">=") {
          gt = higherGT(gt, c2, options);
        } else if (c2.operator === "<" || c2.operator === "<=") {
          lt = lowerLT(lt, c2, options);
        } else {
          eqSet.add(c2.semver);
        }
      }
      if (eqSet.size > 1) {
        return null;
      }
      let gtltComp;
      if (gt && lt) {
        gtltComp = compare(gt.semver, lt.semver, options);
        if (gtltComp > 0) {
          return null;
        } else if (gtltComp === 0 && (gt.operator !== ">=" || lt.operator !== "<=")) {
          return null;
        }
      }
      for (const eq of eqSet) {
        if (gt && !satisfies(eq, String(gt), options)) {
          return null;
        }
        if (lt && !satisfies(eq, String(lt), options)) {
          return null;
        }
        for (const c2 of dom) {
          if (!satisfies(eq, String(c2), options)) {
            return false;
          }
        }
        return true;
      }
      let higher, lower;
      let hasDomLT, hasDomGT;
      let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false;
      let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false;
      if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === "<" && needDomLTPre.prerelease[0] === 0) {
        needDomLTPre = false;
      }
      for (const c2 of dom) {
        hasDomGT = hasDomGT || c2.operator === ">" || c2.operator === ">=";
        hasDomLT = hasDomLT || c2.operator === "<" || c2.operator === "<=";
        if (gt) {
          if (needDomGTPre) {
            if (c2.semver.prerelease && c2.semver.prerelease.length && c2.semver.major === needDomGTPre.major && c2.semver.minor === needDomGTPre.minor && c2.semver.patch === needDomGTPre.patch) {
              needDomGTPre = false;
            }
          }
          if (c2.operator === ">" || c2.operator === ">=") {
            higher = higherGT(gt, c2, options);
            if (higher === c2 && higher !== gt) {
              return false;
            }
          } else if (gt.operator === ">=" && !satisfies(gt.semver, String(c2), options)) {
            return false;
          }
        }
        if (lt) {
          if (needDomLTPre) {
            if (c2.semver.prerelease && c2.semver.prerelease.length && c2.semver.major === needDomLTPre.major && c2.semver.minor === needDomLTPre.minor && c2.semver.patch === needDomLTPre.patch) {
              needDomLTPre = false;
            }
          }
          if (c2.operator === "<" || c2.operator === "<=") {
            lower = lowerLT(lt, c2, options);
            if (lower === c2 && lower !== lt) {
              return false;
            }
          } else if (lt.operator === "<=" && !satisfies(lt.semver, String(c2), options)) {
            return false;
          }
        }
        if (!c2.operator && (lt || gt) && gtltComp !== 0) {
          return false;
        }
      }
      if (gt && hasDomLT && !lt && gtltComp !== 0) {
        return false;
      }
      if (lt && hasDomGT && !gt && gtltComp !== 0) {
        return false;
      }
      if (needDomGTPre || needDomLTPre) {
        return false;
      }
      return true;
    };
    var higherGT = (a, b, options) => {
      if (!a) {
        return b;
      }
      const comp = compare(a.semver, b.semver, options);
      return comp > 0 ? a : comp < 0 ? b : b.operator === ">" && a.operator === ">=" ? b : a;
    };
    var lowerLT = (a, b, options) => {
      if (!a) {
        return b;
      }
      const comp = compare(a.semver, b.semver, options);
      return comp < 0 ? a : comp > 0 ? b : b.operator === "<" && a.operator === "<=" ? b : a;
    };
    module2.exports = subset;
  }
});

// ../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/index.js
var require_semver2 = __commonJS({
  "../../node_modules/.pnpm/semver@7.7.3/node_modules/semver/index.js"(exports2, module2) {
    "use strict";
    var internalRe = require_re();
    var constants3 = require_constants();
    var SemVer = require_semver();
    var identifiers = require_identifiers();
    var parse9 = require_parse();
    var valid = require_valid();
    var clean = require_clean();
    var inc = require_inc();
    var diff = require_diff();
    var major = require_major();
    var minor = require_minor();
    var patch = require_patch();
    var prerelease = require_prerelease();
    var compare = require_compare();
    var rcompare = require_rcompare();
    var compareLoose = require_compare_loose();
    var compareBuild = require_compare_build();
    var sort = require_sort();
    var rsort = require_rsort();
    var gt = require_gt();
    var lt = require_lt();
    var eq = require_eq();
    var neq = require_neq();
    var gte = require_gte();
    var lte = require_lte();
    var cmp = require_cmp();
    var coerce = require_coerce();
    var Comparator = require_comparator();
    var Range = require_range();
    var satisfies = require_satisfies();
    var toComparators = require_to_comparators();
    var maxSatisfying = require_max_satisfying();
    var minSatisfying = require_min_satisfying();
    var minVersion = require_min_version();
    var validRange = require_valid2();
    var outside = require_outside();
    var gtr = require_gtr();
    var ltr = require_ltr();
    var intersects = require_intersects();
    var simplifyRange = require_simplify();
    var subset = require_subset();
    module2.exports = {
      parse: parse9,
      valid,
      clean,
      inc,
      diff,
      major,
      minor,
      patch,
      prerelease,
      compare,
      rcompare,
      compareLoose,
      compareBuild,
      sort,
      rsort,
      gt,
      lt,
      eq,
      neq,
      gte,
      lte,
      cmp,
      coerce,
      Comparator,
      Range,
      satisfies,
      toComparators,
      maxSatisfying,
      minSatisfying,
      minVersion,
      validRange,
      outside,
      gtr,
      ltr,
      intersects,
      simplifyRange,
      subset,
      SemVer,
      re: internalRe.re,
      src: internalRe.src,
      tokens: internalRe.t,
      SEMVER_SPEC_VERSION: constants3.SEMVER_SPEC_VERSION,
      RELEASE_TYPES: constants3.RELEASE_TYPES,
      compareIdentifiers: identifiers.compareIdentifiers,
      rcompareIdentifiers: identifiers.rcompareIdentifiers
    };
  }
});

// ../../node_modules/.pnpm/lru-cache@7.18.3/node_modules/lru-cache/index.js
var require_lru_cache = __commonJS({
  "../../node_modules/.pnpm/lru-cache@7.18.3/node_modules/lru-cache/index.js"(exports2, module2) {
    "use strict";
    var perf = typeof performance === "object" && performance && typeof performance.now === "function" ? performance : Date;
    var hasAbortController = typeof AbortController === "function";
    var AC = hasAbortController ? AbortController : class AbortController {
      constructor() {
        this.signal = new AS();
      }
      abort(reason = new Error("This operation was aborted")) {
        this.signal.reason = this.signal.reason || reason;
        this.signal.aborted = true;
        this.signal.dispatchEvent({
          type: "abort",
          target: this.signal
        });
      }
    };
    var hasAbortSignal = typeof AbortSignal === "function";
    var hasACAbortSignal = typeof AC.AbortSignal === "function";
    var AS = hasAbortSignal ? AbortSignal : hasACAbortSignal ? AC.AbortController : class AbortSignal {
      constructor() {
        this.reason = void 0;
        this.aborted = false;
        this._listeners = [];
      }
      dispatchEvent(e) {
        if (e.type === "abort") {
          this.aborted = true;
          this.onabort(e);
          this._listeners.forEach((f) => f(e), this);
        }
      }
      onabort() {
      }
      addEventListener(ev, fn) {
        if (ev === "abort") {
          this._listeners.push(fn);
        }
      }
      removeEventListener(ev, fn) {
        if (ev === "abort") {
          this._listeners = this._listeners.filter((f) => f !== fn);
        }
      }
    };
    var warned = /* @__PURE__ */ new Set();
    var deprecatedOption = (opt, instead) => {
      const code = `LRU_CACHE_OPTION_${opt}`;
      if (shouldWarn(code)) {
        warn(code, `${opt} option`, `options.${instead}`, LRUCache);
      }
    };
    var deprecatedMethod = (method, instead) => {
      const code = `LRU_CACHE_METHOD_${method}`;
      if (shouldWarn(code)) {
        const { prototype } = LRUCache;
        const { get } = Object.getOwnPropertyDescriptor(prototype, method);
        warn(code, `${method} method`, `cache.${instead}()`, get);
      }
    };
    var deprecatedProperty = (field, instead) => {
      const code = `LRU_CACHE_PROPERTY_${field}`;
      if (shouldWarn(code)) {
        const { prototype } = LRUCache;
        const { get } = Object.getOwnPropertyDescriptor(prototype, field);
        warn(code, `${field} property`, `cache.${instead}`, get);
      }
    };
    var emitWarning = (...a) => {
      typeof process === "object" && process && typeof process.emitWarning === "function" ? process.emitWarning(...a) : console.error(...a);
    };
    var shouldWarn = (code) => !warned.has(code);
    var warn = (code, what, instead, fn) => {
      warned.add(code);
      const msg = `The ${what} is deprecated. Please use ${instead} instead.`;
      emitWarning(msg, "DeprecationWarning", code, fn);
    };
    var isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n);
    var getUintArray = (max) => !isPosInt(max) ? null : max <= Math.pow(2, 8) ? Uint8Array : max <= Math.pow(2, 16) ? Uint16Array : max <= Math.pow(2, 32) ? Uint32Array : max <= Number.MAX_SAFE_INTEGER ? ZeroArray : null;
    var ZeroArray = class extends Array {
      constructor(size) {
        super(size);
        this.fill(0);
      }
    };
    var Stack = class {
      constructor(max) {
        if (max === 0) {
          return [];
        }
        const UintArray = getUintArray(max);
        this.heap = new UintArray(max);
        this.length = 0;
      }
      push(n) {
        this.heap[this.length++] = n;
      }
      pop() {
        return this.heap[--this.length];
      }
    };
    var LRUCache = class _LRUCache {
      constructor(options = {}) {
        const {
          max = 0,
          ttl,
          ttlResolution = 1,
          ttlAutopurge,
          updateAgeOnGet,
          updateAgeOnHas,
          allowStale,
          dispose,
          disposeAfter,
          noDisposeOnSet,
          noUpdateTTL,
          maxSize = 0,
          maxEntrySize = 0,
          sizeCalculation,
          fetchMethod,
          fetchContext,
          noDeleteOnFetchRejection,
          noDeleteOnStaleGet,
          allowStaleOnFetchRejection,
          allowStaleOnFetchAbort,
          ignoreFetchAbort
        } = options;
        const { length, maxAge, stale } = options instanceof _LRUCache ? {} : options;
        if (max !== 0 && !isPosInt(max)) {
          throw new TypeError("max option must be a nonnegative integer");
        }
        const UintArray = max ? getUintArray(max) : Array;
        if (!UintArray) {
          throw new Error("invalid max value: " + max);
        }
        this.max = max;
        this.maxSize = maxSize;
        this.maxEntrySize = maxEntrySize || this.maxSize;
        this.sizeCalculation = sizeCalculation || length;
        if (this.sizeCalculation) {
          if (!this.maxSize && !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");
          }
        }
        this.fetchMethod = fetchMethod || null;
        if (this.fetchMethod && typeof this.fetchMethod !== "function") {
          throw new TypeError(
            "fetchMethod must be a function if specified"
          );
        }
        this.fetchContext = fetchContext;
        if (!this.fetchMethod && fetchContext !== void 0) {
          throw new TypeError(
            "cannot set fetchContext without fetchMethod"
          );
        }
        this.keyMap = /* @__PURE__ */ new Map();
        this.keyList = new Array(max).fill(null);
        this.valList = new Array(max).fill(null);
        this.next = new UintArray(max);
        this.prev = new UintArray(max);
        this.head = 0;
        this.tail = 0;
        this.free = new Stack(max);
        this.initialFill = 1;
        this.size = 0;
        if (typeof dispose === "function") {
          this.dispose = dispose;
        }
        if (typeof disposeAfter === "function") {
          this.disposeAfter = disposeAfter;
          this.disposed = [];
        } else {
          this.disposeAfter = null;
          this.disposed = null;
        }
        this.noDisposeOnSet = !!noDisposeOnSet;
        this.noUpdateTTL = !!noUpdateTTL;
        this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
        this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
        this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
        this.ignoreFetchAbort = !!ignoreFetchAbort;
        if (this.maxEntrySize !== 0) {
          if (this.maxSize !== 0) {
            if (!isPosInt(this.maxSize)) {
              throw new TypeError(
                "maxSize must be a positive integer if specified"
              );
            }
          }
          if (!isPosInt(this.maxEntrySize)) {
            throw new TypeError(
              "maxEntrySize must be a positive integer if specified"
            );
          }
          this.initializeSizeTracking();
        }
        this.allowStale = !!allowStale || !!stale;
        this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;
        this.updateAgeOnGet = !!updateAgeOnGet;
        this.updateAgeOnHas = !!updateAgeOnHas;
        this.ttlResolution = isPosInt(ttlResolution) || ttlResolution === 0 ? ttlResolution : 1;
        this.ttlAutopurge = !!ttlAutopurge;
        this.ttl = ttl || maxAge || 0;
        if (this.ttl) {
          if (!isPosInt(this.ttl)) {
            throw new TypeError(
              "ttl must be a positive integer if specified"
            );
          }
          this.initializeTTLTracking();
        }
        if (this.max === 0 && this.ttl === 0 && this.maxSize === 0) {
          throw new TypeError(
            "At least one of max, maxSize, or ttl is required"
          );
        }
        if (!this.ttlAutopurge && !this.max && !this.maxSize) {
          const code = "LRU_CACHE_UNBOUNDED";
          if (shouldWarn(code)) {
            warned.add(code);
            const msg = "TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.";
            emitWarning(msg, "UnboundedCacheWarning", code, _LRUCache);
          }
        }
        if (stale) {
          deprecatedOption("stale", "allowStale");
        }
        if (maxAge) {
          deprecatedOption("maxAge", "ttl");
        }
        if (length) {
          deprecatedOption("length", "sizeCalculation");
        }
      }
      getRemainingTTL(key) {
        return this.has(key, { updateAgeOnHas: false }) ? Infinity : 0;
      }
      initializeTTLTracking() {
        this.ttls = new ZeroArray(this.max);
        this.starts = new ZeroArray(this.max);
        this.setItemTTL = (index, ttl, start = perf.now()) => {
          this.starts[index] = ttl !== 0 ? start : 0;
          this.ttls[index] = ttl;
          if (ttl !== 0 && this.ttlAutopurge) {
            const t = setTimeout(() => {
              if (this.isStale(index)) {
                this.delete(this.keyList[index]);
              }
            }, ttl + 1);
            if (t.unref) {
              t.unref();
            }
          }
        };
        this.updateItemAge = (index) => {
          this.starts[index] = this.ttls[index] !== 0 ? perf.now() : 0;
        };
        this.statusTTL = (status2, index) => {
          if (status2) {
            status2.ttl = this.ttls[index];
            status2.start = this.starts[index];
            status2.now = cachedNow || getNow();
            status2.remainingTTL = status2.now + status2.ttl - status2.start;
          }
        };
        let cachedNow = 0;
        const getNow = () => {
          const n = perf.now();
          if (this.ttlResolution > 0) {
            cachedNow = n;
            const t = setTimeout(
              () => cachedNow = 0,
              this.ttlResolution
            );
            if (t.unref) {
              t.unref();
            }
          }
          return n;
        };
        this.getRemainingTTL = (key) => {
          const index = this.keyMap.get(key);
          if (index === void 0) {
            return 0;
          }
          return this.ttls[index] === 0 || this.starts[index] === 0 ? Infinity : this.starts[index] + this.ttls[index] - (cachedNow || getNow());
        };
        this.isStale = (index) => {
          return this.ttls[index] !== 0 && this.starts[index] !== 0 && (cachedNow || getNow()) - this.starts[index] > this.ttls[index];
        };
      }
      updateItemAge(_index) {
      }
      statusTTL(_status, _index) {
      }
      setItemTTL(_index, _ttl, _start) {
      }
      isStale(_index) {
        return false;
      }
      initializeSizeTracking() {
        this.calculatedSize = 0;
        this.sizes = new ZeroArray(this.max);
        this.removeItemSize = (index) => {
          this.calculatedSize -= this.sizes[index];
          this.sizes[index] = 0;
        };
        this.requireSize = (k, v, size, sizeCalculation) => {
          if (this.isBackgroundFetch(v)) {
            return 0;
          }
          if (!isPosInt(size)) {
            if (sizeCalculation) {
              if (typeof sizeCalculation !== "function") {
                throw new TypeError("sizeCalculation must be a function");
              }
              size = sizeCalculation(v, k);
              if (!isPosInt(size)) {
                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 size;
        };
        this.addItemSize = (index, size, status2) => {
          this.sizes[index] = size;
          if (this.maxSize) {
            const maxSize = this.maxSize - this.sizes[index];
            while (this.calculatedSize > maxSize) {
              this.evict(true);
            }
          }
          this.calculatedSize += this.sizes[index];
          if (status2) {
            status2.entrySize = size;
            status2.totalCalculatedSize = this.calculatedSize;
          }
        };
      }
      removeItemSize(_index) {
      }
      addItemSize(_index, _size3) {
      }
      requireSize(_k, _v, size, sizeCalculation) {
        if (size || sizeCalculation) {
          throw new TypeError(
            "cannot set size without setting maxSize or maxEntrySize on cache"
          );
        }
      }
      *indexes({ allowStale = this.allowStale } = {}) {
        if (this.size) {
          for (let i = this.tail; true; ) {
            if (!this.isValidIndex(i)) {
              break;
            }
            if (allowStale || !this.isStale(i)) {
              yield i;
            }
            if (i === this.head) {
              break;
            } else {
              i = this.prev[i];
            }
          }
        }
      }
      *rindexes({ allowStale = this.allowStale } = {}) {
        if (this.size) {
          for (let i = this.head; true; ) {
            if (!this.isValidIndex(i)) {
              break;
            }
            if (allowStale || !this.isStale(i)) {
              yield i;
            }
            if (i === this.tail) {
              break;
            } else {
              i = this.next[i];
            }
          }
        }
      }
      isValidIndex(index) {
        return index !== void 0 && this.keyMap.get(this.keyList[index]) === index;
      }
      *entries() {
        for (const i of this.indexes()) {
          if (this.valList[i] !== void 0 && this.keyList[i] !== void 0 && !this.isBackgroundFetch(this.valList[i])) {
            yield [this.keyList[i], this.valList[i]];
          }
        }
      }
      *rentries() {
        for (const i of this.rindexes()) {
          if (this.valList[i] !== void 0 && this.keyList[i] !== void 0 && !this.isBackgroundFetch(this.valList[i])) {
            yield [this.keyList[i], this.valList[i]];
          }
        }
      }
      *keys() {
        for (const i of this.indexes()) {
          if (this.keyList[i] !== void 0 && !this.isBackgroundFetch(this.valList[i])) {
            yield this.keyList[i];
          }
        }
      }
      *rkeys() {
        for (const i of this.rindexes()) {
          if (this.keyList[i] !== void 0 && !this.isBackgroundFetch(this.valList[i])) {
            yield this.keyList[i];
          }
        }
      }
      *values() {
        for (const i of this.indexes()) {
          if (this.valList[i] !== void 0 && !this.isBackgroundFetch(this.valList[i])) {
            yield this.valList[i];
          }
        }
      }
      *rvalues() {
        for (const i of this.rindexes()) {
          if (this.valList[i] !== void 0 && !this.isBackgroundFetch(this.valList[i])) {
            yield this.valList[i];
          }
        }
      }
      [Symbol.iterator]() {
        return this.entries();
      }
      find(fn, getOptions) {
        for (const i of this.indexes()) {
          const v = this.valList[i];
          const value = this.isBackgroundFetch(v) ? v.__staleWhileFetching : v;
          if (value === void 0) continue;
          if (fn(value, this.keyList[i], this)) {
            return this.get(this.keyList[i], getOptions);
          }
        }
      }
      forEach(fn, thisp = this) {
        for (const i of this.indexes()) {
          const v = this.valList[i];
          const value = this.isBackgroundFetch(v) ? v.__staleWhileFetching : v;
          if (value === void 0) continue;
          fn.call(thisp, value, this.keyList[i], this);
        }
      }
      rforEach(fn, thisp = this) {
        for (const i of this.rindexes()) {
          const v = this.valList[i];
          const value = this.isBackgroundFetch(v) ? v.__staleWhileFetching : v;
          if (value === void 0) continue;
          fn.call(thisp, value, this.keyList[i], this);
        }
      }
      get prune() {
        deprecatedMethod("prune", "purgeStale");
        return this.purgeStale;
      }
      purgeStale() {
        let deleted = false;
        for (const i of this.rindexes({ allowStale: true })) {
          if (this.isStale(i)) {
            this.delete(this.keyList[i]);
            deleted = true;
          }
        }
        return deleted;
      }
      dump() {
        const arr = [];
        for (const i of this.indexes({ allowStale: true })) {
          const key = this.keyList[i];
          const v = this.valList[i];
          const value = this.isBackgroundFetch(v) ? v.__staleWhileFetching : v;
          if (value === void 0) continue;
          const entry = { value };
          if (this.ttls) {
            entry.ttl = this.ttls[i];
            const age = perf.now() - this.starts[i];
            entry.start = Math.floor(Date.now() - age);
          }
          if (this.sizes) {
            entry.size = this.sizes[i];
          }
          arr.unshift([key, entry]);
        }
        return arr;
      }
      load(arr) {
        this.clear();
        for (const [key, entry] of arr) {
          if (entry.start) {
            const age = Date.now() - entry.start;
            entry.start = perf.now() - age;
          }
          this.set(key, entry.value, entry);
        }
      }
      dispose(_v, _k, _reason) {
      }
      set(k, v, {
        ttl = this.ttl,
        start,
        noDisposeOnSet = this.noDisposeOnSet,
        size = 0,
        sizeCalculation = this.sizeCalculation,
        noUpdateTTL = this.noUpdateTTL,
        status: status2
      } = {}) {
        size = this.requireSize(k, v, size, sizeCalculation);
        if (this.maxEntrySize && size > this.maxEntrySize) {
          if (status2) {
            status2.set = "miss";
            status2.maxEntrySizeExceeded = true;
          }
          this.delete(k);
          return this;
        }
        let index = this.size === 0 ? void 0 : this.keyMap.get(k);
        if (index === void 0) {
          index = this.newIndex();
          this.keyList[index] = k;
          this.valList[index] = v;
          this.keyMap.set(k, index);
          this.next[this.tail] = index;
          this.prev[index] = this.tail;
          this.tail = index;
          this.size++;
          this.addItemSize(index, size, status2);
          if (status2) {
            status2.set = "add";
          }
          noUpdateTTL = false;
        } else {
          this.moveToTail(index);
          const oldVal = this.valList[index];
          if (v !== oldVal) {
            if (this.isBackgroundFetch(oldVal)) {
              oldVal.__abortController.abort(new Error("replaced"));
            } else {
              if (!noDisposeOnSet) {
                this.dispose(oldVal, k, "set");
                if (this.disposeAfter) {
                  this.disposed.push([oldVal, k, "set"]);
                }
              }
            }
            this.removeItemSize(index);
            this.valList[index] = v;
            this.addItemSize(index, size, status2);
            if (status2) {
              status2.set = "replace";
              const oldValue = oldVal && this.isBackgroundFetch(oldVal) ? oldVal.__staleWhileFetching : oldVal;
              if (oldValue !== void 0) status2.oldValue = oldValue;
            }
          } else if (status2) {
            status2.set = "update";
          }
        }
        if (ttl !== 0 && this.ttl === 0 && !this.ttls) {
          this.initializeTTLTracking();
        }
        if (!noUpdateTTL) {
          this.setItemTTL(index, ttl, start);
        }
        this.statusTTL(status2, index);
        if (this.disposeAfter) {
          while (this.disposed.length) {
            this.disposeAfter(...this.disposed.shift());
          }
        }
        return this;
      }
      newIndex() {
        if (this.size === 0) {
          return this.tail;
        }
        if (this.size === this.max && this.max !== 0) {
          return this.evict(false);
        }
        if (this.free.length !== 0) {
          return this.free.pop();
        }
        return this.initialFill++;
      }
      pop() {
        if (this.size) {
          const val = this.valList[this.head];
          this.evict(true);
          return val;
        }
      }
      evict(free) {
        const head = this.head;
        const k = this.keyList[head];
        const v = this.valList[head];
        if (this.isBackgroundFetch(v)) {
          v.__abortController.abort(new Error("evicted"));
        } else {
          this.dispose(v, k, "evict");
          if (this.disposeAfter) {
            this.disposed.push([v, k, "evict"]);
          }
        }
        this.removeItemSize(head);
        if (free) {
          this.keyList[head] = null;
          this.valList[head] = null;
          this.free.push(head);
        }
        this.head = this.next[head];
        this.keyMap.delete(k);
        this.size--;
        return head;
      }
      has(k, { updateAgeOnHas = this.updateAgeOnHas, status: status2 } = {}) {
        const index = this.keyMap.get(k);
        if (index !== void 0) {
          if (!this.isStale(index)) {
            if (updateAgeOnHas) {
              this.updateItemAge(index);
            }
            if (status2) status2.has = "hit";
            this.statusTTL(status2, index);
            return true;
          } else if (status2) {
            status2.has = "stale";
            this.statusTTL(status2, index);
          }
        } else if (status2) {
          status2.has = "miss";
        }
        return false;
      }
      // like get(), but without any LRU updating or TTL expiration
      peek(k, { allowStale = this.allowStale } = {}) {
        const index = this.keyMap.get(k);
        if (index !== void 0 && (allowStale || !this.isStale(index))) {
          const v = this.valList[index];
          return this.isBackgroundFetch(v) ? v.__staleWhileFetching : v;
        }
      }
      backgroundFetch(k, index, options, context) {
        const v = index === void 0 ? void 0 : this.valList[index];
        if (this.isBackgroundFetch(v)) {
          return v;
        }
        const ac = new AC();
        if (options.signal) {
          options.signal.addEventListener(
            "abort",
            () => ac.abort(options.signal.reason)
          );
        }
        const fetchOpts = {
          signal: ac.signal,
          options,
          context
        };
        const cb = (v2, updateCache = false) => {
          const { aborted: aborted3 } = ac.signal;
          const ignoreAbort = options.ignoreFetchAbort && v2 !== void 0;
          if (options.status) {
            if (aborted3 && !updateCache) {
              options.status.fetchAborted = true;
              options.status.fetchError = ac.signal.reason;
              if (ignoreAbort) options.status.fetchAbortIgnored = true;
            } else {
              options.status.fetchResolved = true;
            }
          }
          if (aborted3 && !ignoreAbort && !updateCache) {
            return fetchFail(ac.signal.reason);
          }
          if (this.valList[index] === p2) {
            if (v2 === void 0) {
              if (p2.__staleWhileFetching) {
                this.valList[index] = p2.__staleWhileFetching;
              } else {
                this.delete(k);
              }
            } else {
              if (options.status) options.status.fetchUpdated = true;
              this.set(k, v2, fetchOpts.options);
            }
          }
          return v2;
        };
        const eb = (er) => {
          if (options.status) {
            options.status.fetchRejected = true;
            options.status.fetchError = er;
          }
          return fetchFail(er);
        };
        const fetchFail = (er) => {
          const { aborted: aborted3 } = ac.signal;
          const allowStaleAborted = aborted3 && options.allowStaleOnFetchAbort;
          const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
          const noDelete = allowStale || options.noDeleteOnFetchRejection;
          if (this.valList[index] === p2) {
            const del = !noDelete || p2.__staleWhileFetching === void 0;
            if (del) {
              this.delete(k);
            } else if (!allowStaleAborted) {
              this.valList[index] = p2.__staleWhileFetching;
            }
          }
          if (allowStale) {
            if (options.status && p2.__staleWhileFetching !== void 0) {
              options.status.returnedStale = true;
            }
            return p2.__staleWhileFetching;
          } else if (p2.__returned === p2) {
            throw er;
          }
        };
        const pcall = (res, rej) => {
          this.fetchMethod(k, v, fetchOpts).then((v2) => res(v2), rej);
          ac.signal.addEventListener("abort", () => {
            if (!options.ignoreFetchAbort || options.allowStaleOnFetchAbort) {
              res();
              if (options.allowStaleOnFetchAbort) {
                res = (v2) => cb(v2, true);
              }
            }
          });
        };
        if (options.status) options.status.fetchDispatched = true;
        const p2 = new Promise(pcall).then(cb, eb);
        p2.__abortController = ac;
        p2.__staleWhileFetching = v;
        p2.__returned = null;
        if (index === void 0) {
          this.set(k, p2, { ...fetchOpts.options, status: void 0 });
          index = this.keyMap.get(k);
        } else {
          this.valList[index] = p2;
        }
        return p2;
      }
      isBackgroundFetch(p2) {
        return p2 && typeof p2 === "object" && typeof p2.then === "function" && Object.prototype.hasOwnProperty.call(
          p2,
          "__staleWhileFetching"
        ) && Object.prototype.hasOwnProperty.call(p2, "__returned") && (p2.__returned === p2 || p2.__returned === null);
      }
      // this takes the union of get() and set() opts, because it does both
      async fetch(k, {
        // get options
        allowStale = this.allowStale,
        updateAgeOnGet = this.updateAgeOnGet,
        noDeleteOnStaleGet = this.noDeleteOnStaleGet,
        // set options
        ttl = this.ttl,
        noDisposeOnSet = this.noDisposeOnSet,
        size = 0,
        sizeCalculation = this.sizeCalculation,
        noUpdateTTL = this.noUpdateTTL,
        // fetch exclusive options
        noDeleteOnFetchRejection = this.noDeleteOnFetchRejection,
        allowStaleOnFetchRejection = this.allowStaleOnFetchRejection,
        ignoreFetchAbort = this.ignoreFetchAbort,
        allowStaleOnFetchAbort = this.allowStaleOnFetchAbort,
        fetchContext = this.fetchContext,
        forceRefresh = false,
        status: status2,
        signal
      } = {}) {
        if (!this.fetchMethod) {
          if (status2) status2.fetch = "get";
          return this.get(k, {
            allowStale,
            updateAgeOnGet,
            noDeleteOnStaleGet,
            status: status2
          });
        }
        const options = {
          allowStale,
          updateAgeOnGet,
          noDeleteOnStaleGet,
          ttl,
          noDisposeOnSet,
          size,
          sizeCalculation,
          noUpdateTTL,
          noDeleteOnFetchRejection,
          allowStaleOnFetchRejection,
          allowStaleOnFetchAbort,
          ignoreFetchAbort,
          status: status2,
          signal
        };
        let index = this.keyMap.get(k);
        if (index === void 0) {
          if (status2) status2.fetch = "miss";
          const p2 = this.backgroundFetch(k, index, options, fetchContext);
          return p2.__returned = p2;
        } else {
          const v = this.valList[index];
          if (this.isBackgroundFetch(v)) {
            const stale = allowStale && v.__staleWhileFetching !== void 0;
            if (status2) {
              status2.fetch = "inflight";
              if (stale) status2.returnedStale = true;
            }
            return stale ? v.__staleWhileFetching : v.__returned = v;
          }
          const isStale = this.isStale(index);
          if (!forceRefresh && !isStale) {
            if (status2) status2.fetch = "hit";
            this.moveToTail(index);
            if (updateAgeOnGet) {
              this.updateItemAge(index);
            }
            this.statusTTL(status2, index);
            return v;
          }
          const p2 = this.backgroundFetch(k, index, options, fetchContext);
          const hasStale = p2.__staleWhileFetching !== void 0;
          const staleVal = hasStale && allowStale;
          if (status2) {
            status2.fetch = hasStale && isStale ? "stale" : "refresh";
            if (staleVal && isStale) status2.returnedStale = true;
          }
          return staleVal ? p2.__staleWhileFetching : p2.__returned = p2;
        }
      }
      get(k, {
        allowStale = this.allowStale,
        updateAgeOnGet = this.updateAgeOnGet,
        noDeleteOnStaleGet = this.noDeleteOnStaleGet,
        status: status2
      } = {}) {
        const index = this.keyMap.get(k);
        if (index !== void 0) {
          const value = this.valList[index];
          const fetching = this.isBackgroundFetch(value);
          this.statusTTL(status2, index);
          if (this.isStale(index)) {
            if (status2) status2.get = "stale";
            if (!fetching) {
              if (!noDeleteOnStaleGet) {
                this.delete(k);
              }
              if (status2) status2.returnedStale = allowStale;
              return allowStale ? value : void 0;
            } else {
              if (status2) {
                status2.returnedStale = allowStale && value.__staleWhileFetching !== void 0;
              }
              return allowStale ? value.__staleWhileFetching : void 0;
            }
          } else {
            if (status2) status2.get = "hit";
            if (fetching) {
              return value.__staleWhileFetching;
            }
            this.moveToTail(index);
            if (updateAgeOnGet) {
              this.updateItemAge(index);
            }
            return value;
          }
        } else if (status2) {
          status2.get = "miss";
        }
      }
      connect(p2, n) {
        this.prev[n] = p2;
        this.next[p2] = n;
      }
      moveToTail(index) {
        if (index !== this.tail) {
          if (index === this.head) {
            this.head = this.next[index];
          } else {
            this.connect(this.prev[index], this.next[index]);
          }
          this.connect(this.tail, index);
          this.tail = index;
        }
      }
      get del() {
        deprecatedMethod("del", "delete");
        return this.delete;
      }
      delete(k) {
        let deleted = false;
        if (this.size !== 0) {
          const index = this.keyMap.get(k);
          if (index !== void 0) {
            deleted = true;
            if (this.size === 1) {
              this.clear();
            } else {
              this.removeItemSize(index);
              const v = this.valList[index];
              if (this.isBackgroundFetch(v)) {
                v.__abortController.abort(new Error("deleted"));
              } else {
                this.dispose(v, k, "delete");
                if (this.disposeAfter) {
                  this.disposed.push([v, k, "delete"]);
                }
              }
              this.keyMap.delete(k);
              this.keyList[index] = null;
              this.valList[index] = null;
              if (index === this.tail) {
                this.tail = this.prev[index];
              } else if (index === this.head) {
                this.head = this.next[index];
              } else {
                this.next[this.prev[index]] = this.next[index];
                this.prev[this.next[index]] = this.prev[index];
              }
              this.size--;
              this.free.push(index);
            }
          }
        }
        if (this.disposed) {
          while (this.disposed.length) {
            this.disposeAfter(...this.disposed.shift());
          }
        }
        return deleted;
      }
      clear() {
        for (const index of this.rindexes({ allowStale: true })) {
          const v = this.valList[index];
          if (this.isBackgroundFetch(v)) {
            v.__abortController.abort(new Error("deleted"));
          } else {
            const k = this.keyList[index];
            this.dispose(v, k, "delete");
            if (this.disposeAfter) {
              this.disposed.push([v, k, "delete"]);
            }
          }
        }
        this.keyMap.clear();
        this.valList.fill(null);
        this.keyList.fill(null);
        if (this.ttls) {
          this.ttls.fill(0);
          this.starts.fill(0);
        }
        if (this.sizes) {
          this.sizes.fill(0);
        }
        this.head = 0;
        this.tail = 0;
        this.initialFill = 1;
        this.free.length = 0;
        this.calculatedSize = 0;
        this.size = 0;
        if (this.disposed) {
          while (this.disposed.length) {
            this.disposeAfter(...this.disposed.shift());
          }
        }
      }
      get reset() {
        deprecatedMethod("reset", "clear");
        return this.clear;
      }
      get length() {
        deprecatedProperty("length", "size");
        return this.size;
      }
      static get AbortController() {
        return AC;
      }
      static get AbortSignal() {
        return AS;
      }
    };
    module2.exports = LRUCache;
  }
});

// ../../node_modules/.pnpm/agent-base@7.1.3/node_modules/agent-base/dist/helpers.js
var require_helpers = __commonJS({
  "../../node_modules/.pnpm/agent-base@7.1.3/node_modules/agent-base/dist/helpers.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding2(result, mod, k);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.req = exports2.json = exports2.toBuffer = void 0;
    var http3 = __importStar2(require("http"));
    var https2 = __importStar2(require("https"));
    async function toBuffer(stream) {
      let length = 0;
      const chunks = [];
      for await (const chunk of stream) {
        length += chunk.length;
        chunks.push(chunk);
      }
      return Buffer.concat(chunks, length);
    }
    exports2.toBuffer = toBuffer;
    async function json3(stream) {
      const buf = await toBuffer(stream);
      const str = buf.toString("utf8");
      try {
        return JSON.parse(str);
      } catch (_err) {
        const err = _err;
        err.message += ` (input: ${str})`;
        throw err;
      }
    }
    exports2.json = json3;
    function req(url46, opts = {}) {
      const href = typeof url46 === "string" ? url46 : url46.href;
      const req2 = (href.startsWith("https:") ? https2 : http3).request(url46, opts);
      const promise3 = new Promise((resolve8, reject) => {
        req2.once("response", resolve8).once("error", reject).end();
      });
      req2.then = promise3.then.bind(promise3);
      return req2;
    }
    exports2.req = req;
  }
});

// ../../node_modules/.pnpm/agent-base@7.1.3/node_modules/agent-base/dist/index.js
var require_dist2 = __commonJS({
  "../../node_modules/.pnpm/agent-base@7.1.3/node_modules/agent-base/dist/index.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding2(result, mod, k);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    var __exportStar2 = exports2 && exports2.__exportStar || function(m, exports3) {
      for (var p2 in m) if (p2 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p2)) __createBinding2(exports3, m, p2);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Agent = void 0;
    var net3 = __importStar2(require("net"));
    var http3 = __importStar2(require("http"));
    var https_1 = require("https");
    __exportStar2(require_helpers(), exports2);
    var INTERNAL = /* @__PURE__ */ Symbol("AgentBaseInternalState");
    var Agent = class extends http3.Agent {
      constructor(opts) {
        super(opts);
        this[INTERNAL] = {};
      }
      /**
       * Determine whether this is an `http` or `https` request.
       */
      isSecureEndpoint(options) {
        if (options) {
          if (typeof options.secureEndpoint === "boolean") {
            return options.secureEndpoint;
          }
          if (typeof options.protocol === "string") {
            return options.protocol === "https:";
          }
        }
        const { stack } = new Error();
        if (typeof stack !== "string")
          return false;
        return stack.split("\n").some((l) => l.indexOf("(https.js:") !== -1 || l.indexOf("node:https:") !== -1);
      }
      // In order to support async signatures in `connect()` and Node's native
      // connection pooling in `http.Agent`, the array of sockets for each origin
      // has to be updated synchronously. This is so the length of the array is
      // accurate when `addRequest()` is next called. We achieve this by creating a
      // fake socket and adding it to `sockets[origin]` and incrementing
      // `totalSocketCount`.
      incrementSockets(name) {
        if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) {
          return null;
        }
        if (!this.sockets[name]) {
          this.sockets[name] = [];
        }
        const fakeSocket = new net3.Socket({ writable: false });
        this.sockets[name].push(fakeSocket);
        this.totalSocketCount++;
        return fakeSocket;
      }
      decrementSockets(name, socket) {
        if (!this.sockets[name] || socket === null) {
          return;
        }
        const sockets = this.sockets[name];
        const index = sockets.indexOf(socket);
        if (index !== -1) {
          sockets.splice(index, 1);
          this.totalSocketCount--;
          if (sockets.length === 0) {
            delete this.sockets[name];
          }
        }
      }
      // In order to properly update the socket pool, we need to call `getName()` on
      // the core `https.Agent` if it is a secureEndpoint.
      getName(options) {
        const secureEndpoint = typeof options.secureEndpoint === "boolean" ? options.secureEndpoint : this.isSecureEndpoint(options);
        if (secureEndpoint) {
          return https_1.Agent.prototype.getName.call(this, options);
        }
        return super.getName(options);
      }
      createSocket(req, options, cb) {
        const connectOpts = {
          ...options,
          secureEndpoint: this.isSecureEndpoint(options)
        };
        const name = this.getName(connectOpts);
        const fakeSocket = this.incrementSockets(name);
        Promise.resolve().then(() => this.connect(req, connectOpts)).then((socket) => {
          this.decrementSockets(name, fakeSocket);
          if (socket instanceof http3.Agent) {
            try {
              return socket.addRequest(req, connectOpts);
            } catch (err) {
              return cb(err);
            }
          }
          this[INTERNAL].currentSocket = socket;
          super.createSocket(req, options, cb);
        }, (err) => {
          this.decrementSockets(name, fakeSocket);
          cb(err);
        });
      }
      createConnection() {
        const socket = this[INTERNAL].currentSocket;
        this[INTERNAL].currentSocket = void 0;
        if (!socket) {
          throw new Error("No socket was returned in the `connect()` function");
        }
        return socket;
      }
      get defaultPort() {
        return this[INTERNAL].defaultPort ?? (this.protocol === "https:" ? 443 : 80);
      }
      set defaultPort(v) {
        if (this[INTERNAL]) {
          this[INTERNAL].defaultPort = v;
        }
      }
      get protocol() {
        return this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? "https:" : "http:");
      }
      set protocol(v) {
        if (this[INTERNAL]) {
          this[INTERNAL].protocol = v;
        }
      }
    };
    exports2.Agent = Agent;
  }
});

// ../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js
var require_ms = __commonJS({
  "../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js"(exports2, module2) {
    "use strict";
    var s = 1e3;
    var m = s * 60;
    var h = m * 60;
    var d = h * 24;
    var w = d * 7;
    var y = d * 365.25;
    module2.exports = function(val, options) {
      options = options || {};
      var type = typeof val;
      if (type === "string" && val.length > 0) {
        return parse9(val);
      } else if (type === "number" && isFinite(val)) {
        return options.long ? fmtLong(val) : fmtShort(val);
      }
      throw new Error(
        "val is not a non-empty string or a valid number. val=" + JSON.stringify(val)
      );
    };
    function parse9(str) {
      str = String(str);
      if (str.length > 100) {
        return;
      }
      var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
        str
      );
      if (!match) {
        return;
      }
      var n = parseFloat(match[1]);
      var type = (match[2] || "ms").toLowerCase();
      switch (type) {
        case "years":
        case "year":
        case "yrs":
        case "yr":
        case "y":
          return n * y;
        case "weeks":
        case "week":
        case "w":
          return n * w;
        case "days":
        case "day":
        case "d":
          return n * d;
        case "hours":
        case "hour":
        case "hrs":
        case "hr":
        case "h":
          return n * h;
        case "minutes":
        case "minute":
        case "mins":
        case "min":
        case "m":
          return n * m;
        case "seconds":
        case "second":
        case "secs":
        case "sec":
        case "s":
          return n * s;
        case "milliseconds":
        case "millisecond":
        case "msecs":
        case "msec":
        case "ms":
          return n;
        default:
          return void 0;
      }
    }
    function fmtShort(ms) {
      var msAbs = Math.abs(ms);
      if (msAbs >= d) {
        return Math.round(ms / d) + "d";
      }
      if (msAbs >= h) {
        return Math.round(ms / h) + "h";
      }
      if (msAbs >= m) {
        return Math.round(ms / m) + "m";
      }
      if (msAbs >= s) {
        return Math.round(ms / s) + "s";
      }
      return ms + "ms";
    }
    function fmtLong(ms) {
      var msAbs = Math.abs(ms);
      if (msAbs >= d) {
        return plural(ms, msAbs, d, "day");
      }
      if (msAbs >= h) {
        return plural(ms, msAbs, h, "hour");
      }
      if (msAbs >= m) {
        return plural(ms, msAbs, m, "minute");
      }
      if (msAbs >= s) {
        return plural(ms, msAbs, s, "second");
      }
      return ms + " ms";
    }
    function plural(ms, msAbs, n, name) {
      var isPlural = msAbs >= n * 1.5;
      return Math.round(ms / n) + " " + name + (isPlural ? "s" : "");
    }
  }
});

// ../../node_modules/.pnpm/debug@4.4.1_supports-color@9.2.2/node_modules/debug/src/common.js
var require_common = __commonJS({
  "../../node_modules/.pnpm/debug@4.4.1_supports-color@9.2.2/node_modules/debug/src/common.js"(exports2, module2) {
    "use strict";
    function setup(env3) {
      createDebug.debug = createDebug;
      createDebug.default = createDebug;
      createDebug.coerce = coerce;
      createDebug.disable = disable;
      createDebug.enable = enable;
      createDebug.enabled = enabled;
      createDebug.humanize = require_ms();
      createDebug.destroy = destroy;
      Object.keys(env3).forEach((key) => {
        createDebug[key] = env3[key];
      });
      createDebug.names = [];
      createDebug.skips = [];
      createDebug.formatters = {};
      function selectColor(namespace) {
        let hash3 = 0;
        for (let i = 0; i < namespace.length; i++) {
          hash3 = (hash3 << 5) - hash3 + namespace.charCodeAt(i);
          hash3 |= 0;
        }
        return createDebug.colors[Math.abs(hash3) % createDebug.colors.length];
      }
      createDebug.selectColor = selectColor;
      function createDebug(namespace) {
        let prevTime;
        let enableOverride = null;
        let namespacesCache;
        let enabledCache;
        function debug4(...args) {
          if (!debug4.enabled) {
            return;
          }
          const self2 = debug4;
          const curr = Number(/* @__PURE__ */ new Date());
          const ms = curr - (prevTime || curr);
          self2.diff = ms;
          self2.prev = prevTime;
          self2.curr = curr;
          prevTime = curr;
          args[0] = createDebug.coerce(args[0]);
          if (typeof args[0] !== "string") {
            args.unshift("%O");
          }
          let index = 0;
          args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format5) => {
            if (match === "%%") {
              return "%";
            }
            index++;
            const formatter = createDebug.formatters[format5];
            if (typeof formatter === "function") {
              const val = args[index];
              match = formatter.call(self2, val);
              args.splice(index, 1);
              index--;
            }
            return match;
          });
          createDebug.formatArgs.call(self2, args);
          const logFn = self2.log || createDebug.log;
          logFn.apply(self2, args);
        }
        debug4.namespace = namespace;
        debug4.useColors = createDebug.useColors();
        debug4.color = createDebug.selectColor(namespace);
        debug4.extend = extend3;
        debug4.destroy = createDebug.destroy;
        Object.defineProperty(debug4, "enabled", {
          enumerable: true,
          configurable: false,
          get: () => {
            if (enableOverride !== null) {
              return enableOverride;
            }
            if (namespacesCache !== createDebug.namespaces) {
              namespacesCache = createDebug.namespaces;
              enabledCache = createDebug.enabled(namespace);
            }
            return enabledCache;
          },
          set: (v) => {
            enableOverride = v;
          }
        });
        if (typeof createDebug.init === "function") {
          createDebug.init(debug4);
        }
        return debug4;
      }
      function extend3(namespace, delimiter) {
        const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
        newDebug.log = this.log;
        return newDebug;
      }
      function enable(namespaces) {
        createDebug.save(namespaces);
        createDebug.namespaces = namespaces;
        createDebug.names = [];
        createDebug.skips = [];
        const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean);
        for (const ns of split) {
          if (ns[0] === "-") {
            createDebug.skips.push(ns.slice(1));
          } else {
            createDebug.names.push(ns);
          }
        }
      }
      function matchesTemplate(search, template) {
        let searchIndex = 0;
        let templateIndex = 0;
        let starIndex = -1;
        let matchIndex = 0;
        while (searchIndex < search.length) {
          if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) {
            if (template[templateIndex] === "*") {
              starIndex = templateIndex;
              matchIndex = searchIndex;
              templateIndex++;
            } else {
              searchIndex++;
              templateIndex++;
            }
          } else if (starIndex !== -1) {
            templateIndex = starIndex + 1;
            matchIndex++;
            searchIndex = matchIndex;
          } else {
            return false;
          }
        }
        while (templateIndex < template.length && template[templateIndex] === "*") {
          templateIndex++;
        }
        return templateIndex === template.length;
      }
      function disable() {
        const namespaces = [
          ...createDebug.names,
          ...createDebug.skips.map((namespace) => "-" + namespace)
        ].join(",");
        createDebug.enable("");
        return namespaces;
      }
      function enabled(name) {
        for (const skip of createDebug.skips) {
          if (matchesTemplate(name, skip)) {
            return false;
          }
        }
        for (const ns of createDebug.names) {
          if (matchesTemplate(name, ns)) {
            return true;
          }
        }
        return false;
      }
      function coerce(val) {
        if (val instanceof Error) {
          return val.stack || val.message;
        }
        return val;
      }
      function destroy() {
        console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
      }
      createDebug.enable(createDebug.load());
      return createDebug;
    }
    module2.exports = setup;
  }
});

// ../../node_modules/.pnpm/debug@4.4.1_supports-color@9.2.2/node_modules/debug/src/browser.js
var require_browser = __commonJS({
  "../../node_modules/.pnpm/debug@4.4.1_supports-color@9.2.2/node_modules/debug/src/browser.js"(exports2, module2) {
    "use strict";
    exports2.formatArgs = formatArgs;
    exports2.save = save;
    exports2.load = load2;
    exports2.useColors = useColors;
    exports2.storage = localstorage();
    exports2.destroy = /* @__PURE__ */ (() => {
      let warned = false;
      return () => {
        if (!warned) {
          warned = true;
          console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
        }
      };
    })();
    exports2.colors = [
      "#0000CC",
      "#0000FF",
      "#0033CC",
      "#0033FF",
      "#0066CC",
      "#0066FF",
      "#0099CC",
      "#0099FF",
      "#00CC00",
      "#00CC33",
      "#00CC66",
      "#00CC99",
      "#00CCCC",
      "#00CCFF",
      "#3300CC",
      "#3300FF",
      "#3333CC",
      "#3333FF",
      "#3366CC",
      "#3366FF",
      "#3399CC",
      "#3399FF",
      "#33CC00",
      "#33CC33",
      "#33CC66",
      "#33CC99",
      "#33CCCC",
      "#33CCFF",
      "#6600CC",
      "#6600FF",
      "#6633CC",
      "#6633FF",
      "#66CC00",
      "#66CC33",
      "#9900CC",
      "#9900FF",
      "#9933CC",
      "#9933FF",
      "#99CC00",
      "#99CC33",
      "#CC0000",
      "#CC0033",
      "#CC0066",
      "#CC0099",
      "#CC00CC",
      "#CC00FF",
      "#CC3300",
      "#CC3333",
      "#CC3366",
      "#CC3399",
      "#CC33CC",
      "#CC33FF",
      "#CC6600",
      "#CC6633",
      "#CC9900",
      "#CC9933",
      "#CCCC00",
      "#CCCC33",
      "#FF0000",
      "#FF0033",
      "#FF0066",
      "#FF0099",
      "#FF00CC",
      "#FF00FF",
      "#FF3300",
      "#FF3333",
      "#FF3366",
      "#FF3399",
      "#FF33CC",
      "#FF33FF",
      "#FF6600",
      "#FF6633",
      "#FF9900",
      "#FF9933",
      "#FFCC00",
      "#FFCC33"
    ];
    function useColors() {
      if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) {
        return true;
      }
      if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
        return false;
      }
      let m;
      return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
      typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
      // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
      typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
      typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
    }
    function formatArgs(args) {
      args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff);
      if (!this.useColors) {
        return;
      }
      const c2 = "color: " + this.color;
      args.splice(1, 0, c2, "color: inherit");
      let index = 0;
      let lastC = 0;
      args[0].replace(/%[a-zA-Z%]/g, (match) => {
        if (match === "%%") {
          return;
        }
        index++;
        if (match === "%c") {
          lastC = index;
        }
      });
      args.splice(lastC, 0, c2);
    }
    exports2.log = console.debug || console.log || (() => {
    });
    function save(namespaces) {
      try {
        if (namespaces) {
          exports2.storage.setItem("debug", namespaces);
        } else {
          exports2.storage.removeItem("debug");
        }
      } catch (error101) {
      }
    }
    function load2() {
      let r;
      try {
        r = exports2.storage.getItem("debug") || exports2.storage.getItem("DEBUG");
      } catch (error101) {
      }
      if (!r && typeof process !== "undefined" && "env" in process) {
        r = process.env.DEBUG;
      }
      return r;
    }
    function localstorage() {
      try {
        return localStorage;
      } catch (error101) {
      }
    }
    module2.exports = require_common()(exports2);
    var { formatters } = module2.exports;
    formatters.j = function(v) {
      try {
        return JSON.stringify(v);
      } catch (error101) {
        return "[UnexpectedJSONParseError]: " + error101.message;
      }
    };
  }
});

// ../../node_modules/.pnpm/supports-color@9.2.2/node_modules/supports-color/index.js
var supports_color_exports = {};
__export(supports_color_exports, {
  createSupportsColor: () => createSupportsColor2,
  default: () => supports_color_default2
});
function hasFlag2(flag, argv = import_node_process6.default.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);
}
function envForceColor2() {
  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);
  }
}
function translateLevel2(level) {
  if (level === 0) {
    return false;
  }
  return {
    level,
    hasBasic: true,
    has256: level >= 2,
    has16m: level >= 3
  };
}
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 (haveStream && !streamIsTTY && forceColor === void 0) {
    return 0;
  }
  const min = forceColor || 0;
  if (env2.TERM === "dumb") {
    return min;
  }
  if (import_node_process6.default.platform === "win32") {
    const osRelease = import_node_os8.default.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 (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "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 ("TF_BUILD" in env2 && "AGENT_NAME" in env2) {
    return 1;
  }
  if (env2.COLORTERM === "truecolor") {
    return 3;
  }
  if ("TERM_PROGRAM" in env2) {
    const version4 = Number.parseInt((env2.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
    switch (env2.TERM_PROGRAM) {
      case "iTerm.app":
        return version4 >= 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;
}
function createSupportsColor2(stream, options = {}) {
  const level = _supportsColor2(stream, {
    streamIsTTY: stream && stream.isTTY,
    ...options
  });
  return translateLevel2(level);
}
var import_node_process6, import_node_os8, import_node_tty2, env2, flagForceColor2, supportsColor2, supports_color_default2;
var init_supports_color = __esm({
  "../../node_modules/.pnpm/supports-color@9.2.2/node_modules/supports-color/index.js"() {
    "use strict";
    import_node_process6 = __toESM(require("node:process"), 1);
    import_node_os8 = __toESM(require("node:os"), 1);
    import_node_tty2 = __toESM(require("node:tty"), 1);
    ({ env: env2 } = import_node_process6.default);
    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;
    }
    supportsColor2 = {
      stdout: createSupportsColor2({ isTTY: import_node_tty2.default.isatty(1) }),
      stderr: createSupportsColor2({ isTTY: import_node_tty2.default.isatty(2) })
    };
    supports_color_default2 = supportsColor2;
  }
});

// ../../node_modules/.pnpm/debug@4.4.1_supports-color@9.2.2/node_modules/debug/src/node.js
var require_node = __commonJS({
  "../../node_modules/.pnpm/debug@4.4.1_supports-color@9.2.2/node_modules/debug/src/node.js"(exports2, module2) {
    "use strict";
    var tty3 = require("tty");
    var util4 = require("util");
    exports2.init = init3;
    exports2.log = log2;
    exports2.formatArgs = formatArgs;
    exports2.save = save;
    exports2.load = load2;
    exports2.useColors = useColors;
    exports2.destroy = util4.deprecate(
      () => {
      },
      "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."
    );
    exports2.colors = [6, 2, 3, 4, 5, 1];
    try {
      const supportsColor3 = (init_supports_color(), __toCommonJS(supports_color_exports));
      if (supportsColor3 && (supportsColor3.stderr || supportsColor3).level >= 2) {
        exports2.colors = [
          20,
          21,
          26,
          27,
          32,
          33,
          38,
          39,
          40,
          41,
          42,
          43,
          44,
          45,
          56,
          57,
          62,
          63,
          68,
          69,
          74,
          75,
          76,
          77,
          78,
          79,
          80,
          81,
          92,
          93,
          98,
          99,
          112,
          113,
          128,
          129,
          134,
          135,
          148,
          149,
          160,
          161,
          162,
          163,
          164,
          165,
          166,
          167,
          168,
          169,
          170,
          171,
          172,
          173,
          178,
          179,
          184,
          185,
          196,
          197,
          198,
          199,
          200,
          201,
          202,
          203,
          204,
          205,
          206,
          207,
          208,
          209,
          214,
          215,
          220,
          221
        ];
      }
    } catch (error101) {
    }
    exports2.inspectOpts = Object.keys(process.env).filter((key) => {
      return /^debug_/i.test(key);
    }).reduce((obj, key) => {
      const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => {
        return k.toUpperCase();
      });
      let val = process.env[key];
      if (/^(yes|on|true|enabled)$/i.test(val)) {
        val = true;
      } else if (/^(no|off|false|disabled)$/i.test(val)) {
        val = false;
      } else if (val === "null") {
        val = null;
      } else {
        val = Number(val);
      }
      obj[prop] = val;
      return obj;
    }, {});
    function useColors() {
      return "colors" in exports2.inspectOpts ? Boolean(exports2.inspectOpts.colors) : tty3.isatty(process.stderr.fd);
    }
    function formatArgs(args) {
      const { namespace: name, useColors: useColors2 } = this;
      if (useColors2) {
        const c2 = this.color;
        const colorCode = "\x1B[3" + (c2 < 8 ? c2 : "8;5;" + c2);
        const prefix = `  ${colorCode};1m${name} \x1B[0m`;
        args[0] = prefix + args[0].split("\n").join("\n" + prefix);
        args.push(colorCode + "m+" + module2.exports.humanize(this.diff) + "\x1B[0m");
      } else {
        args[0] = getDate() + name + " " + args[0];
      }
    }
    function getDate() {
      if (exports2.inspectOpts.hideDate) {
        return "";
      }
      return (/* @__PURE__ */ new Date()).toISOString() + " ";
    }
    function log2(...args) {
      return process.stderr.write(util4.formatWithOptions(exports2.inspectOpts, ...args) + "\n");
    }
    function save(namespaces) {
      if (namespaces) {
        process.env.DEBUG = namespaces;
      } else {
        delete process.env.DEBUG;
      }
    }
    function load2() {
      return process.env.DEBUG;
    }
    function init3(debug4) {
      debug4.inspectOpts = {};
      const keys = Object.keys(exports2.inspectOpts);
      for (let i = 0; i < keys.length; i++) {
        debug4.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]];
      }
    }
    module2.exports = require_common()(exports2);
    var { formatters } = module2.exports;
    formatters.o = function(v) {
      this.inspectOpts.colors = this.useColors;
      return util4.inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" ");
    };
    formatters.O = function(v) {
      this.inspectOpts.colors = this.useColors;
      return util4.inspect(v, this.inspectOpts);
    };
  }
});

// ../../node_modules/.pnpm/debug@4.4.1_supports-color@9.2.2/node_modules/debug/src/index.js
var require_src2 = __commonJS({
  "../../node_modules/.pnpm/debug@4.4.1_supports-color@9.2.2/node_modules/debug/src/index.js"(exports2, module2) {
    "use strict";
    if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) {
      module2.exports = require_browser();
    } else {
      module2.exports = require_node();
    }
  }
});

// ../../node_modules/.pnpm/proxy-from-env@1.1.0/node_modules/proxy-from-env/index.js
var require_proxy_from_env = __commonJS({
  "../../node_modules/.pnpm/proxy-from-env@1.1.0/node_modules/proxy-from-env/index.js"(exports2) {
    "use strict";
    var parseUrl = require("url").parse;
    var DEFAULT_PORTS = {
      ftp: 21,
      gopher: 70,
      http: 80,
      https: 443,
      ws: 80,
      wss: 443
    };
    var stringEndsWith = String.prototype.endsWith || function(s) {
      return s.length <= this.length && this.indexOf(s, this.length - s.length) !== -1;
    };
    function getProxyForUrl(url46) {
      var parsedUrl = typeof url46 === "string" ? parseUrl(url46) : url46 || {};
      var proto2 = parsedUrl.protocol;
      var hostname5 = parsedUrl.host;
      var port = parsedUrl.port;
      if (typeof hostname5 !== "string" || !hostname5 || typeof proto2 !== "string") {
        return "";
      }
      proto2 = proto2.split(":", 1)[0];
      hostname5 = hostname5.replace(/:\d*$/, "");
      port = parseInt(port) || DEFAULT_PORTS[proto2] || 0;
      if (!shouldProxy(hostname5, port)) {
        return "";
      }
      var proxy = getEnv2("npm_config_" + proto2 + "_proxy") || getEnv2(proto2 + "_proxy") || getEnv2("npm_config_proxy") || getEnv2("all_proxy");
      if (proxy && proxy.indexOf("://") === -1) {
        proxy = proto2 + "://" + proxy;
      }
      return proxy;
    }
    function shouldProxy(hostname5, port) {
      var NO_PROXY = (getEnv2("npm_config_no_proxy") || getEnv2("no_proxy")).toLowerCase();
      if (!NO_PROXY) {
        return true;
      }
      if (NO_PROXY === "*") {
        return false;
      }
      return NO_PROXY.split(/[,\s]/).every(function(proxy) {
        if (!proxy) {
          return true;
        }
        var parsedProxy = proxy.match(/^(.+):(\d+)$/);
        var parsedProxyHostname = parsedProxy ? parsedProxy[1] : proxy;
        var parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0;
        if (parsedProxyPort && parsedProxyPort !== port) {
          return true;
        }
        if (!/^[.*]/.test(parsedProxyHostname)) {
          return hostname5 !== parsedProxyHostname;
        }
        if (parsedProxyHostname.charAt(0) === "*") {
          parsedProxyHostname = parsedProxyHostname.slice(1);
        }
        return !stringEndsWith.call(hostname5, parsedProxyHostname);
      });
    }
    function getEnv2(key) {
      return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || "";
    }
    exports2.getProxyForUrl = getProxyForUrl;
  }
});

// ../../node_modules/.pnpm/http-proxy-agent@7.0.2/node_modules/http-proxy-agent/dist/index.js
var require_dist3 = __commonJS({
  "../../node_modules/.pnpm/http-proxy-agent@7.0.2/node_modules/http-proxy-agent/dist/index.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding2(result, mod, k);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.HttpProxyAgent = void 0;
    var net3 = __importStar2(require("net"));
    var tls3 = __importStar2(require("tls"));
    var debug_1 = __importDefault2(require_src2());
    var events_1 = require("events");
    var agent_base_1 = require_dist2();
    var url_1 = require("url");
    var debug4 = (0, debug_1.default)("http-proxy-agent");
    var HttpProxyAgent = class extends agent_base_1.Agent {
      constructor(proxy, opts) {
        super(opts);
        this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy;
        this.proxyHeaders = opts?.headers ?? {};
        debug4("Creating new HttpProxyAgent instance: %o", this.proxy.href);
        const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, "");
        const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80;
        this.connectOpts = {
          ...opts ? omit3(opts, "headers") : null,
          host,
          port
        };
      }
      addRequest(req, opts) {
        req._header = null;
        this.setRequestProps(req, opts);
        super.addRequest(req, opts);
      }
      setRequestProps(req, opts) {
        const { proxy } = this;
        const protocol = opts.secureEndpoint ? "https:" : "http:";
        const hostname5 = req.getHeader("host") || "localhost";
        const base = `${protocol}//${hostname5}`;
        const url46 = new url_1.URL(req.path, base);
        if (opts.port !== 80) {
          url46.port = String(opts.port);
        }
        req.path = String(url46);
        const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders };
        if (proxy.username || proxy.password) {
          const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
          headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`;
        }
        if (!headers["Proxy-Connection"]) {
          headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close";
        }
        for (const name of Object.keys(headers)) {
          const value = headers[name];
          if (value) {
            req.setHeader(name, value);
          }
        }
      }
      async connect(req, opts) {
        req._header = null;
        if (!req.path.includes("://")) {
          this.setRequestProps(req, opts);
        }
        let first;
        let endOfHeaders;
        debug4("Regenerating stored HTTP header string for request");
        req._implicitHeader();
        if (req.outputData && req.outputData.length > 0) {
          debug4("Patching connection write() output buffer with updated header");
          first = req.outputData[0].data;
          endOfHeaders = first.indexOf("\r\n\r\n") + 4;
          req.outputData[0].data = req._header + first.substring(endOfHeaders);
          debug4("Output buffer: %o", req.outputData[0].data);
        }
        let socket;
        if (this.proxy.protocol === "https:") {
          debug4("Creating `tls.Socket`: %o", this.connectOpts);
          socket = tls3.connect(this.connectOpts);
        } else {
          debug4("Creating `net.Socket`: %o", this.connectOpts);
          socket = net3.connect(this.connectOpts);
        }
        await (0, events_1.once)(socket, "connect");
        return socket;
      }
    };
    HttpProxyAgent.protocols = ["http", "https"];
    exports2.HttpProxyAgent = HttpProxyAgent;
    function omit3(obj, ...keys) {
      const ret = {};
      let key;
      for (key in obj) {
        if (!keys.includes(key)) {
          ret[key] = obj[key];
        }
      }
      return ret;
    }
  }
});

// ../../node_modules/.pnpm/https-proxy-agent@7.0.6/node_modules/https-proxy-agent/dist/parse-proxy-response.js
var require_parse_proxy_response = __commonJS({
  "../../node_modules/.pnpm/https-proxy-agent@7.0.6/node_modules/https-proxy-agent/dist/parse-proxy-response.js"(exports2) {
    "use strict";
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.parseProxyResponse = void 0;
    var debug_1 = __importDefault2(require_src2());
    var debug4 = (0, debug_1.default)("https-proxy-agent:parse-proxy-response");
    function parseProxyResponse(socket) {
      return new Promise((resolve8, reject) => {
        let buffersLength = 0;
        const buffers = [];
        function read() {
          const b = socket.read();
          if (b)
            ondata(b);
          else
            socket.once("readable", read);
        }
        function cleanup() {
          socket.removeListener("end", onend);
          socket.removeListener("error", onerror);
          socket.removeListener("readable", read);
        }
        function onend() {
          cleanup();
          debug4("onend");
          reject(new Error("Proxy connection ended before receiving CONNECT response"));
        }
        function onerror(err) {
          cleanup();
          debug4("onerror %o", err);
          reject(err);
        }
        function ondata(b) {
          buffers.push(b);
          buffersLength += b.length;
          const buffered = Buffer.concat(buffers, buffersLength);
          const endOfHeaders = buffered.indexOf("\r\n\r\n");
          if (endOfHeaders === -1) {
            debug4("have not received end of HTTP headers yet...");
            read();
            return;
          }
          const headerParts = buffered.slice(0, endOfHeaders).toString("ascii").split("\r\n");
          const firstLine = headerParts.shift();
          if (!firstLine) {
            socket.destroy();
            return reject(new Error("No header received from proxy CONNECT response"));
          }
          const firstLineParts = firstLine.split(" ");
          const statusCode = +firstLineParts[1];
          const statusText = firstLineParts.slice(2).join(" ");
          const headers = {};
          for (const header of headerParts) {
            if (!header)
              continue;
            const firstColon = header.indexOf(":");
            if (firstColon === -1) {
              socket.destroy();
              return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`));
            }
            const key = header.slice(0, firstColon).toLowerCase();
            const value = header.slice(firstColon + 1).trimStart();
            const current = headers[key];
            if (typeof current === "string") {
              headers[key] = [current, value];
            } else if (Array.isArray(current)) {
              current.push(value);
            } else {
              headers[key] = value;
            }
          }
          debug4("got proxy server response: %o %o", firstLine, headers);
          cleanup();
          resolve8({
            connect: {
              statusCode,
              statusText,
              headers
            },
            buffered
          });
        }
        socket.on("error", onerror);
        socket.on("end", onend);
        read();
      });
    }
    exports2.parseProxyResponse = parseProxyResponse;
  }
});

// ../../node_modules/.pnpm/https-proxy-agent@7.0.6/node_modules/https-proxy-agent/dist/index.js
var require_dist4 = __commonJS({
  "../../node_modules/.pnpm/https-proxy-agent@7.0.6/node_modules/https-proxy-agent/dist/index.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding2(result, mod, k);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.HttpsProxyAgent = void 0;
    var net3 = __importStar2(require("net"));
    var tls3 = __importStar2(require("tls"));
    var assert_1 = __importDefault2(require("assert"));
    var debug_1 = __importDefault2(require_src2());
    var agent_base_1 = require_dist2();
    var url_1 = require("url");
    var parse_proxy_response_1 = require_parse_proxy_response();
    var debug4 = (0, debug_1.default)("https-proxy-agent");
    var setServernameFromNonIpHost = (options) => {
      if (options.servername === void 0 && options.host && !net3.isIP(options.host)) {
        return {
          ...options,
          servername: options.host
        };
      }
      return options;
    };
    var HttpsProxyAgent = class extends agent_base_1.Agent {
      constructor(proxy, opts) {
        super(opts);
        this.options = { path: void 0 };
        this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy;
        this.proxyHeaders = opts?.headers ?? {};
        debug4("Creating new HttpsProxyAgent instance: %o", this.proxy.href);
        const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, "");
        const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80;
        this.connectOpts = {
          // Attempt to negotiate http/1.1 for proxy servers that support http/2
          ALPNProtocols: ["http/1.1"],
          ...opts ? omit3(opts, "headers") : null,
          host,
          port
        };
      }
      /**
       * Called when the node-core HTTP client library is creating a
       * new HTTP request.
       */
      async connect(req, opts) {
        const { proxy } = this;
        if (!opts.host) {
          throw new TypeError('No "host" provided');
        }
        let socket;
        if (proxy.protocol === "https:") {
          debug4("Creating `tls.Socket`: %o", this.connectOpts);
          socket = tls3.connect(setServernameFromNonIpHost(this.connectOpts));
        } else {
          debug4("Creating `net.Socket`: %o", this.connectOpts);
          socket = net3.connect(this.connectOpts);
        }
        const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders };
        const host = net3.isIPv6(opts.host) ? `[${opts.host}]` : opts.host;
        let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r
`;
        if (proxy.username || proxy.password) {
          const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
          headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`;
        }
        headers.Host = `${host}:${opts.port}`;
        if (!headers["Proxy-Connection"]) {
          headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close";
        }
        for (const name of Object.keys(headers)) {
          payload += `${name}: ${headers[name]}\r
`;
        }
        const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket);
        socket.write(`${payload}\r
`);
        const { connect, buffered } = await proxyResponsePromise;
        req.emit("proxyConnect", connect);
        this.emit("proxyConnect", connect, req);
        if (connect.statusCode === 200) {
          req.once("socket", resume);
          if (opts.secureEndpoint) {
            debug4("Upgrading socket connection to TLS");
            return tls3.connect({
              ...omit3(setServernameFromNonIpHost(opts), "host", "path", "port"),
              socket
            });
          }
          return socket;
        }
        socket.destroy();
        const fakeSocket = new net3.Socket({ writable: false });
        fakeSocket.readable = true;
        req.once("socket", (s) => {
          debug4("Replaying proxy buffer for failed request");
          (0, assert_1.default)(s.listenerCount("data") > 0);
          s.push(buffered);
          s.push(null);
        });
        return fakeSocket;
      }
    };
    HttpsProxyAgent.protocols = ["http", "https"];
    exports2.HttpsProxyAgent = HttpsProxyAgent;
    function resume(socket) {
      socket.resume();
    }
    function omit3(obj, ...keys) {
      const ret = {};
      let key;
      for (key in obj) {
        if (!keys.includes(key)) {
          ret[key] = obj[key];
        }
      }
      return ret;
    }
  }
});

// ../../node_modules/.pnpm/smart-buffer@4.2.0/node_modules/smart-buffer/build/utils.js
var require_utils2 = __commonJS({
  "../../node_modules/.pnpm/smart-buffer@4.2.0/node_modules/smart-buffer/build/utils.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var buffer_1 = require("buffer");
    var ERRORS = {
      INVALID_ENCODING: "Invalid encoding provided. Please specify a valid encoding the internal Node.js Buffer supports.",
      INVALID_SMARTBUFFER_SIZE: "Invalid size provided. Size must be a valid integer greater than zero.",
      INVALID_SMARTBUFFER_BUFFER: "Invalid Buffer provided in SmartBufferOptions.",
      INVALID_SMARTBUFFER_OBJECT: "Invalid SmartBufferOptions object supplied to SmartBuffer constructor or factory methods.",
      INVALID_OFFSET: "An invalid offset value was provided.",
      INVALID_OFFSET_NON_NUMBER: "An invalid offset value was provided. A numeric value is required.",
      INVALID_LENGTH: "An invalid length value was provided.",
      INVALID_LENGTH_NON_NUMBER: "An invalid length value was provived. A numeric value is required.",
      INVALID_TARGET_OFFSET: "Target offset is beyond the bounds of the internal SmartBuffer data.",
      INVALID_TARGET_LENGTH: "Specified length value moves cursor beyong the bounds of the internal SmartBuffer data.",
      INVALID_READ_BEYOND_BOUNDS: "Attempted to read beyond the bounds of the managed data.",
      INVALID_WRITE_BEYOND_BOUNDS: "Attempted to write beyond the bounds of the managed data."
    };
    exports2.ERRORS = ERRORS;
    function checkEncoding(encoding) {
      if (!buffer_1.Buffer.isEncoding(encoding)) {
        throw new Error(ERRORS.INVALID_ENCODING);
      }
    }
    exports2.checkEncoding = checkEncoding;
    function isFiniteInteger(value) {
      return typeof value === "number" && isFinite(value) && isInteger(value);
    }
    exports2.isFiniteInteger = isFiniteInteger;
    function checkOffsetOrLengthValue(value, offset) {
      if (typeof value === "number") {
        if (!isFiniteInteger(value) || value < 0) {
          throw new Error(offset ? ERRORS.INVALID_OFFSET : ERRORS.INVALID_LENGTH);
        }
      } else {
        throw new Error(offset ? ERRORS.INVALID_OFFSET_NON_NUMBER : ERRORS.INVALID_LENGTH_NON_NUMBER);
      }
    }
    function checkLengthValue(length) {
      checkOffsetOrLengthValue(length, false);
    }
    exports2.checkLengthValue = checkLengthValue;
    function checkOffsetValue(offset) {
      checkOffsetOrLengthValue(offset, true);
    }
    exports2.checkOffsetValue = checkOffsetValue;
    function checkTargetOffset(offset, buff) {
      if (offset < 0 || offset > buff.length) {
        throw new Error(ERRORS.INVALID_TARGET_OFFSET);
      }
    }
    exports2.checkTargetOffset = checkTargetOffset;
    function isInteger(value) {
      return typeof value === "number" && isFinite(value) && Math.floor(value) === value;
    }
    function bigIntAndBufferInt64Check(bufferMethod) {
      if (typeof BigInt === "undefined") {
        throw new Error("Platform does not support JS BigInt type.");
      }
      if (typeof buffer_1.Buffer.prototype[bufferMethod] === "undefined") {
        throw new Error(`Platform does not support Buffer.prototype.${bufferMethod}.`);
      }
    }
    exports2.bigIntAndBufferInt64Check = bigIntAndBufferInt64Check;
  }
});

// ../../node_modules/.pnpm/smart-buffer@4.2.0/node_modules/smart-buffer/build/smartbuffer.js
var require_smartbuffer = __commonJS({
  "../../node_modules/.pnpm/smart-buffer@4.2.0/node_modules/smart-buffer/build/smartbuffer.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var utils_1 = require_utils2();
    var DEFAULT_SMARTBUFFER_SIZE = 4096;
    var DEFAULT_SMARTBUFFER_ENCODING = "utf8";
    var SmartBuffer = class _SmartBuffer {
      /**
       * Creates a new SmartBuffer instance.
       *
       * @param options { SmartBufferOptions } The SmartBufferOptions to apply to this instance.
       */
      constructor(options) {
        this.length = 0;
        this._encoding = DEFAULT_SMARTBUFFER_ENCODING;
        this._writeOffset = 0;
        this._readOffset = 0;
        if (_SmartBuffer.isSmartBufferOptions(options)) {
          if (options.encoding) {
            utils_1.checkEncoding(options.encoding);
            this._encoding = options.encoding;
          }
          if (options.size) {
            if (utils_1.isFiniteInteger(options.size) && options.size > 0) {
              this._buff = Buffer.allocUnsafe(options.size);
            } else {
              throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_SIZE);
            }
          } else if (options.buff) {
            if (Buffer.isBuffer(options.buff)) {
              this._buff = options.buff;
              this.length = options.buff.length;
            } else {
              throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_BUFFER);
            }
          } else {
            this._buff = Buffer.allocUnsafe(DEFAULT_SMARTBUFFER_SIZE);
          }
        } else {
          if (typeof options !== "undefined") {
            throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_OBJECT);
          }
          this._buff = Buffer.allocUnsafe(DEFAULT_SMARTBUFFER_SIZE);
        }
      }
      /**
       * Creates a new SmartBuffer instance with the provided internal Buffer size and optional encoding.
       *
       * @param size { Number } The size of the internal Buffer.
       * @param encoding { String } The BufferEncoding to use for strings.
       *
       * @return { SmartBuffer }
       */
      static fromSize(size, encoding) {
        return new this({
          size,
          encoding
        });
      }
      /**
       * Creates a new SmartBuffer instance with the provided Buffer and optional encoding.
       *
       * @param buffer { Buffer } The Buffer to use as the internal Buffer value.
       * @param encoding { String } The BufferEncoding to use for strings.
       *
       * @return { SmartBuffer }
       */
      static fromBuffer(buff, encoding) {
        return new this({
          buff,
          encoding
        });
      }
      /**
       * Creates a new SmartBuffer instance with the provided SmartBufferOptions options.
       *
       * @param options { SmartBufferOptions } The options to use when creating the SmartBuffer instance.
       */
      static fromOptions(options) {
        return new this(options);
      }
      /**
       * Type checking function that determines if an object is a SmartBufferOptions object.
       */
      static isSmartBufferOptions(options) {
        const castOptions = options;
        return castOptions && (castOptions.encoding !== void 0 || castOptions.size !== void 0 || castOptions.buff !== void 0);
      }
      // Signed integers
      /**
       * Reads an Int8 value from the current read position or an optionally provided offset.
       *
       * @param offset { Number } The offset to read data from (optional)
       * @return { Number }
       */
      readInt8(offset) {
        return this._readNumberValue(Buffer.prototype.readInt8, 1, offset);
      }
      /**
       * Reads an Int16BE value from the current read position or an optionally provided offset.
       *
       * @param offset { Number } The offset to read data from (optional)
       * @return { Number }
       */
      readInt16BE(offset) {
        return this._readNumberValue(Buffer.prototype.readInt16BE, 2, offset);
      }
      /**
       * Reads an Int16LE value from the current read position or an optionally provided offset.
       *
       * @param offset { Number } The offset to read data from (optional)
       * @return { Number }
       */
      readInt16LE(offset) {
        return this._readNumberValue(Buffer.prototype.readInt16LE, 2, offset);
      }
      /**
       * Reads an Int32BE value from the current read position or an optionally provided offset.
       *
       * @param offset { Number } The offset to read data from (optional)
       * @return { Number }
       */
      readInt32BE(offset) {
        return this._readNumberValue(Buffer.prototype.readInt32BE, 4, offset);
      }
      /**
       * Reads an Int32LE value from the current read position or an optionally provided offset.
       *
       * @param offset { Number } The offset to read data from (optional)
       * @return { Number }
       */
      readInt32LE(offset) {
        return this._readNumberValue(Buffer.prototype.readInt32LE, 4, offset);
      }
      /**
       * Reads a BigInt64BE value from the current read position or an optionally provided offset.
       *
       * @param offset { Number } The offset to read data from (optional)
       * @return { BigInt }
       */
      readBigInt64BE(offset) {
        utils_1.bigIntAndBufferInt64Check("readBigInt64BE");
        return this._readNumberValue(Buffer.prototype.readBigInt64BE, 8, offset);
      }
      /**
       * Reads a BigInt64LE value from the current read position or an optionally provided offset.
       *
       * @param offset { Number } The offset to read data from (optional)
       * @return { BigInt }
       */
      readBigInt64LE(offset) {
        utils_1.bigIntAndBufferInt64Check("readBigInt64LE");
        return this._readNumberValue(Buffer.prototype.readBigInt64LE, 8, offset);
      }
      /**
       * Writes an Int8 value to the current write position (or at optional offset).
       *
       * @param value { Number } The value to write.
       * @param offset { Number } The offset to write the value at.
       *
       * @return this
       */
      writeInt8(value, offset) {
        this._writeNumberValue(Buffer.prototype.writeInt8, 1, value, offset);
        return this;
      }
      /**
       * Inserts an Int8 value at the given offset value.
       *
       * @param value { Number } The value to insert.
       * @param offset { Number } The offset to insert the value at.
       *
       * @return this
       */
      insertInt8(value, offset) {
        return this._insertNumberValue(Buffer.prototype.writeInt8, 1, value, offset);
      }
      /**
       * Writes an Int16BE value to the current write position (or at optional offset).
       *
       * @param value { Number } The value to write.
       * @param offset { Number } The offset to write the value at.
       *
       * @return this
       */
      writeInt16BE(value, offset) {
        return this._writeNumberValue(Buffer.prototype.writeInt16BE, 2, value, offset);
      }
      /**
       * Inserts an Int16BE value at the given offset value.
       *
       * @param value { Number } The value to insert.
       * @param offset { Number } The offset to insert the value at.
       *
       * @return this
       */
      insertInt16BE(value, offset) {
        return this._insertNumberValue(Buffer.prototype.writeInt16BE, 2, value, offset);
      }
      /**
       * Writes an Int16LE value to the current write position (or at optional offset).
       *
       * @param value { Number } The value to write.
       * @param offset { Number } The offset to write the value at.
       *
       * @return this
       */
      writeInt16LE(value, offset) {
        return this._writeNumberValue(Buffer.prototype.writeInt16LE, 2, value, offset);
      }
      /**
       * Inserts an Int16LE value at the given offset value.
       *
       * @param value { Number } The value to insert.
       * @param offset { Number } The offset to insert the value at.
       *
       * @return this
       */
      insertInt16LE(value, offset) {
        return this._insertNumberValue(Buffer.prototype.writeInt16LE, 2, value, offset);
      }
      /**
       * Writes an Int32BE value to the current write position (or at optional offset).
       *
       * @param value { Number } The value to write.
       * @param offset { Number } The offset to write the value at.
       *
       * @return this
       */
      writeInt32BE(value, offset) {
        return this._writeNumberValue(Buffer.prototype.writeInt32BE, 4, value, offset);
      }
      /**
       * Inserts an Int32BE value at the given offset value.
       *
       * @param value { Number } The value to insert.
       * @param offset { Number } The offset to insert the value at.
       *
       * @return this
       */
      insertInt32BE(value, offset) {
        return this._insertNumberValue(Buffer.prototype.writeInt32BE, 4, value, offset);
      }
      /**
       * Writes an Int32LE value to the current write position (or at optional offset).
       *
       * @param value { Number } The value to write.
       * @param offset { Number } The offset to write the value at.
       *
       * @return this
       */
      writeInt32LE(value, offset) {
        return this._writeNumberValue(Buffer.prototype.writeInt32LE, 4, value, offset);
      }
      /**
       * Inserts an Int32LE value at the given offset value.
       *
       * @param value { Number } The value to insert.
       * @param offset { Number } The offset to insert the value at.
       *
       * @return this
       */
      insertInt32LE(value, offset) {
        return this._insertNumberValue(Buffer.prototype.writeInt32LE, 4, value, offset);
      }
      /**
       * Writes a BigInt64BE value to the current write position (or at optional offset).
       *
       * @param value { BigInt } The value to write.
       * @param offset { Number } The offset to write the value at.
       *
       * @return this
       */
      writeBigInt64BE(value, offset) {
        utils_1.bigIntAndBufferInt64Check("writeBigInt64BE");
        return this._writeNumberValue(Buffer.prototype.writeBigInt64BE, 8, value, offset);
      }
      /**
       * Inserts a BigInt64BE value at the given offset value.
       *
       * @param value { BigInt } The value to insert.
       * @param offset { Number } The offset to insert the value at.
       *
       * @return this
       */
      insertBigInt64BE(value, offset) {
        utils_1.bigIntAndBufferInt64Check("writeBigInt64BE");
        return this._insertNumberValue(Buffer.prototype.writeBigInt64BE, 8, value, offset);
      }
      /**
       * Writes a BigInt64LE value to the current write position (or at optional offset).
       *
       * @param value { BigInt } The value to write.
       * @param offset { Number } The offset to write the value at.
       *
       * @return this
       */
      writeBigInt64LE(value, offset) {
        utils_1.bigIntAndBufferInt64Check("writeBigInt64LE");
        return this._writeNumberValue(Buffer.prototype.writeBigInt64LE, 8, value, offset);
      }
      /**
       * Inserts a Int64LE value at the given offset value.
       *
       * @param value { BigInt } The value to insert.
       * @param offset { Number } The offset to insert the value at.
       *
       * @return this
       */
      insertBigInt64LE(value, offset) {
        utils_1.bigIntAndBufferInt64Check("writeBigInt64LE");
        return this._insertNumberValue(Buffer.prototype.writeBigInt64LE, 8, value, offset);
      }
      // Unsigned Integers
      /**
       * Reads an UInt8 value from the current read position or an optionally provided offset.
       *
       * @param offset { Number } The offset to read data from (optional)
       * @return { Number }
       */
      readUInt8(offset) {
        return this._readNumberValue(Buffer.prototype.readUInt8, 1, offset);
      }
      /**
       * Reads an UInt16BE value from the current read position or an optionally provided offset.
       *
       * @param offset { Number } The offset to read data from (optional)
       * @return { Number }
       */
      readUInt16BE(offset) {
        return this._readNumberValue(Buffer.prototype.readUInt16BE, 2, offset);
      }
      /**
       * Reads an UInt16LE value from the current read position or an optionally provided offset.
       *
       * @param offset { Number } The offset to read data from (optional)
       * @return { Number }
       */
      readUInt16LE(offset) {
        return this._readNumberValue(Buffer.prototype.readUInt16LE, 2, offset);
      }
      /**
       * Reads an UInt32BE value from the current read position or an optionally provided offset.
       *
       * @param offset { Number } The offset to read data from (optional)
       * @return { Number }
       */
      readUInt32BE(offset) {
        return this._readNumberValue(Buffer.prototype.readUInt32BE, 4, offset);
      }
      /**
       * Reads an UInt32LE value from the current read position or an optionally provided offset.
       *
       * @param offset { Number } The offset to read data from (optional)
       * @return { Number }
       */
      readUInt32LE(offset) {
        return this._readNumberValue(Buffer.prototype.readUInt32LE, 4, offset);
      }
      /**
       * Reads a BigUInt64BE value from the current read position or an optionally provided offset.
       *
       * @param offset { Number } The offset to read data from (optional)
       * @return { BigInt }
       */
      readBigUInt64BE(offset) {
        utils_1.bigIntAndBufferInt64Check("readBigUInt64BE");
        return this._readNumberValue(Buffer.prototype.readBigUInt64BE, 8, offset);
      }
      /**
       * Reads a BigUInt64LE value from the current read position or an optionally provided offset.
       *
       * @param offset { Number } The offset to read data from (optional)
       * @return { BigInt }
       */
      readBigUInt64LE(offset) {
        utils_1.bigIntAndBufferInt64Check("readBigUInt64LE");
        return this._readNumberValue(Buffer.prototype.readBigUInt64LE, 8, offset);
      }
      /**
       * Writes an UInt8 value to the current write position (or at optional offset).
       *
       * @param value { Number } The value to write.
       * @param offset { Number } The offset to write the value at.
       *
       * @return this
       */
      writeUInt8(value, offset) {
        return this._writeNumberValue(Buffer.prototype.writeUInt8, 1, value, offset);
      }
      /**
       * Inserts an UInt8 value at the given offset value.
       *
       * @param value { Number } The value to insert.
       * @param offset { Number } The offset to insert the value at.
       *
       * @return this
       */
      insertUInt8(value, offset) {
        return this._insertNumberValue(Buffer.prototype.writeUInt8, 1, value, offset);
      }
      /**
       * Writes an UInt16BE value to the current write position (or at optional offset).
       *
       * @param value { Number } The value to write.
       * @param offset { Number } The offset to write the value at.
       *
       * @return this
       */
      writeUInt16BE(value, offset) {
        return this._writeNumberValue(Buffer.prototype.writeUInt16BE, 2, value, offset);
      }
      /**
       * Inserts an UInt16BE value at the given offset value.
       *
       * @param value { Number } The value to insert.
       * @param offset { Number } The offset to insert the value at.
       *
       * @return this
       */
      insertUInt16BE(value, offset) {
        return this._insertNumberValue(Buffer.prototype.writeUInt16BE, 2, value, offset);
      }
      /**
       * Writes an UInt16LE value to the current write position (or at optional offset).
       *
       * @param value { Number } The value to write.
       * @param offset { Number } The offset to write the value at.
       *
       * @return this
       */
      writeUInt16LE(value, offset) {
        return this._writeNumberValue(Buffer.prototype.writeUInt16LE, 2, value, offset);
      }
      /**
       * Inserts an UInt16LE value at the given offset value.
       *
       * @param value { Number } The value to insert.
       * @param offset { Number } The offset to insert the value at.
       *
       * @return this
       */
      insertUInt16LE(value, offset) {
        return this._insertNumberValue(Buffer.prototype.writeUInt16LE, 2, value, offset);
      }
      /**
       * Writes an UInt32BE value to the current write position (or at optional offset).
       *
       * @param value { Number } The value to write.
       * @param offset { Number } The offset to write the value at.
       *
       * @return this
       */
      writeUInt32BE(value, offset) {
        return this._writeNumberValue(Buffer.prototype.writeUInt32BE, 4, value, offset);
      }
      /**
       * Inserts an UInt32BE value at the given offset value.
       *
       * @param value { Number } The value to insert.
       * @param offset { Number } The offset to insert the value at.
       *
       * @return this
       */
      insertUInt32BE(value, offset) {
        return this._insertNumberValue(Buffer.prototype.writeUInt32BE, 4, value, offset);
      }
      /**
       * Writes an UInt32LE value to the current write position (or at optional offset).
       *
       * @param value { Number } The value to write.
       * @param offset { Number } The offset to write the value at.
       *
       * @return this
       */
      writeUInt32LE(value, offset) {
        return this._writeNumberValue(Buffer.prototype.writeUInt32LE, 4, value, offset);
      }
      /**
       * Inserts an UInt32LE value at the given offset value.
       *
       * @param value { Number } The value to insert.
       * @param offset { Number } The offset to insert the value at.
       *
       * @return this
       */
      insertUInt32LE(value, offset) {
        return this._insertNumberValue(Buffer.prototype.writeUInt32LE, 4, value, offset);
      }
      /**
       * Writes a BigUInt64BE value to the current write position (or at optional offset).
       *
       * @param value { Number } The value to write.
       * @param offset { Number } The offset to write the value at.
       *
       * @return this
       */
      writeBigUInt64BE(value, offset) {
        utils_1.bigIntAndBufferInt64Check("writeBigUInt64BE");
        return this._writeNumberValue(Buffer.prototype.writeBigUInt64BE, 8, value, offset);
      }
      /**
       * Inserts a BigUInt64BE value at the given offset value.
       *
       * @param value { Number } The value to insert.
       * @param offset { Number } The offset to insert the value at.
       *
       * @return this
       */
      insertBigUInt64BE(value, offset) {
        utils_1.bigIntAndBufferInt64Check("writeBigUInt64BE");
        return this._insertNumberValue(Buffer.prototype.writeBigUInt64BE, 8, value, offset);
      }
      /**
       * Writes a BigUInt64LE value to the current write position (or at optional offset).
       *
       * @param value { Number } The value to write.
       * @param offset { Number } The offset to write the value at.
       *
       * @return this
       */
      writeBigUInt64LE(value, offset) {
        utils_1.bigIntAndBufferInt64Check("writeBigUInt64LE");
        return this._writeNumberValue(Buffer.prototype.writeBigUInt64LE, 8, value, offset);
      }
      /**
       * Inserts a BigUInt64LE value at the given offset value.
       *
       * @param value { Number } The value to insert.
       * @param offset { Number } The offset to insert the value at.
       *
       * @return this
       */
      insertBigUInt64LE(value, offset) {
        utils_1.bigIntAndBufferInt64Check("writeBigUInt64LE");
        return this._insertNumberValue(Buffer.prototype.writeBigUInt64LE, 8, value, offset);
      }
      // Floating Point
      /**
       * Reads an FloatBE value from the current read position or an optionally provided offset.
       *
       * @param offset { Number } The offset to read data from (optional)
       * @return { Number }
       */
      readFloatBE(offset) {
        return this._readNumberValue(Buffer.prototype.readFloatBE, 4, offset);
      }
      /**
       * Reads an FloatLE value from the current read position or an optionally provided offset.
       *
       * @param offset { Number } The offset to read data from (optional)
       * @return { Number }
       */
      readFloatLE(offset) {
        return this._readNumberValue(Buffer.prototype.readFloatLE, 4, offset);
      }
      /**
       * Writes a FloatBE value to the current write position (or at optional offset).
       *
       * @param value { Number } The value to write.
       * @param offset { Number } The offset to write the value at.
       *
       * @return this
       */
      writeFloatBE(value, offset) {
        return this._writeNumberValue(Buffer.prototype.writeFloatBE, 4, value, offset);
      }
      /**
       * Inserts a FloatBE value at the given offset value.
       *
       * @param value { Number } The value to insert.
       * @param offset { Number } The offset to insert the value at.
       *
       * @return this
       */
      insertFloatBE(value, offset) {
        return this._insertNumberValue(Buffer.prototype.writeFloatBE, 4, value, offset);
      }
      /**
       * Writes a FloatLE value to the current write position (or at optional offset).
       *
       * @param value { Number } The value to write.
       * @param offset { Number } The offset to write the value at.
       *
       * @return this
       */
      writeFloatLE(value, offset) {
        return this._writeNumberValue(Buffer.prototype.writeFloatLE, 4, value, offset);
      }
      /**
       * Inserts a FloatLE value at the given offset value.
       *
       * @param value { Number } The value to insert.
       * @param offset { Number } The offset to insert the value at.
       *
       * @return this
       */
      insertFloatLE(value, offset) {
        return this._insertNumberValue(Buffer.prototype.writeFloatLE, 4, value, offset);
      }
      // Double Floating Point
      /**
       * Reads an DoublEBE value from the current read position or an optionally provided offset.
       *
       * @param offset { Number } The offset to read data from (optional)
       * @return { Number }
       */
      readDoubleBE(offset) {
        return this._readNumberValue(Buffer.prototype.readDoubleBE, 8, offset);
      }
      /**
       * Reads an DoubleLE value from the current read position or an optionally provided offset.
       *
       * @param offset { Number } The offset to read data from (optional)
       * @return { Number }
       */
      readDoubleLE(offset) {
        return this._readNumberValue(Buffer.prototype.readDoubleLE, 8, offset);
      }
      /**
       * Writes a DoubleBE value to the current write position (or at optional offset).
       *
       * @param value { Number } The value to write.
       * @param offset { Number } The offset to write the value at.
       *
       * @return this
       */
      writeDoubleBE(value, offset) {
        return this._writeNumberValue(Buffer.prototype.writeDoubleBE, 8, value, offset);
      }
      /**
       * Inserts a DoubleBE value at the given offset value.
       *
       * @param value { Number } The value to insert.
       * @param offset { Number } The offset to insert the value at.
       *
       * @return this
       */
      insertDoubleBE(value, offset) {
        return this._insertNumberValue(Buffer.prototype.writeDoubleBE, 8, value, offset);
      }
      /**
       * Writes a DoubleLE value to the current write position (or at optional offset).
       *
       * @param value { Number } The value to write.
       * @param offset { Number } The offset to write the value at.
       *
       * @return this
       */
      writeDoubleLE(value, offset) {
        return this._writeNumberValue(Buffer.prototype.writeDoubleLE, 8, value, offset);
      }
      /**
       * Inserts a DoubleLE value at the given offset value.
       *
       * @param value { Number } The value to insert.
       * @param offset { Number } The offset to insert the value at.
       *
       * @return this
       */
      insertDoubleLE(value, offset) {
        return this._insertNumberValue(Buffer.prototype.writeDoubleLE, 8, value, offset);
      }
      // Strings
      /**
       * Reads a String from the current read position.
       *
       * @param arg1 { Number | String } The number of bytes to read as a String, or the BufferEncoding to use for
       *             the string (Defaults to instance level encoding).
       * @param encoding { String } The BufferEncoding to use for the string (Defaults to instance level encoding).
       *
       * @return { String }
       */
      readString(arg1, encoding) {
        let lengthVal;
        if (typeof arg1 === "number") {
          utils_1.checkLengthValue(arg1);
          lengthVal = Math.min(arg1, this.length - this._readOffset);
        } else {
          encoding = arg1;
          lengthVal = this.length - this._readOffset;
        }
        if (typeof encoding !== "undefined") {
          utils_1.checkEncoding(encoding);
        }
        const value = this._buff.slice(this._readOffset, this._readOffset + lengthVal).toString(encoding || this._encoding);
        this._readOffset += lengthVal;
        return value;
      }
      /**
       * Inserts a String
       *
       * @param value { String } The String value to insert.
       * @param offset { Number } The offset to insert the string at.
       * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding).
       *
       * @return this
       */
      insertString(value, offset, encoding) {
        utils_1.checkOffsetValue(offset);
        return this._handleString(value, true, offset, encoding);
      }
      /**
       * Writes a String
       *
       * @param value { String } The String value to write.
       * @param arg2 { Number | String } The offset to write the string at, or the BufferEncoding to use.
       * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding).
       *
       * @return this
       */
      writeString(value, arg2, encoding) {
        return this._handleString(value, false, arg2, encoding);
      }
      /**
       * Reads a null-terminated String from the current read position.
       *
       * @param encoding { String } The BufferEncoding to use for the string (Defaults to instance level encoding).
       *
       * @return { String }
       */
      readStringNT(encoding) {
        if (typeof encoding !== "undefined") {
          utils_1.checkEncoding(encoding);
        }
        let nullPos = this.length;
        for (let i = this._readOffset; i < this.length; i++) {
          if (this._buff[i] === 0) {
            nullPos = i;
            break;
          }
        }
        const value = this._buff.slice(this._readOffset, nullPos);
        this._readOffset = nullPos + 1;
        return value.toString(encoding || this._encoding);
      }
      /**
       * Inserts a null-terminated String.
       *
       * @param value { String } The String value to write.
       * @param arg2 { Number | String } The offset to write the string to, or the BufferEncoding to use.
       * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding).
       *
       * @return this
       */
      insertStringNT(value, offset, encoding) {
        utils_1.checkOffsetValue(offset);
        this.insertString(value, offset, encoding);
        this.insertUInt8(0, offset + value.length);
        return this;
      }
      /**
       * Writes a null-terminated String.
       *
       * @param value { String } The String value to write.
       * @param arg2 { Number | String } The offset to write the string to, or the BufferEncoding to use.
       * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding).
       *
       * @return this
       */
      writeStringNT(value, arg2, encoding) {
        this.writeString(value, arg2, encoding);
        this.writeUInt8(0, typeof arg2 === "number" ? arg2 + value.length : this.writeOffset);
        return this;
      }
      // Buffers
      /**
       * Reads a Buffer from the internal read position.
       *
       * @param length { Number } The length of data to read as a Buffer.
       *
       * @return { Buffer }
       */
      readBuffer(length) {
        if (typeof length !== "undefined") {
          utils_1.checkLengthValue(length);
        }
        const lengthVal = typeof length === "number" ? length : this.length;
        const endPoint = Math.min(this.length, this._readOffset + lengthVal);
        const value = this._buff.slice(this._readOffset, endPoint);
        this._readOffset = endPoint;
        return value;
      }
      /**
       * Writes a Buffer to the current write position.
       *
       * @param value { Buffer } The Buffer to write.
       * @param offset { Number } The offset to write the Buffer to.
       *
       * @return this
       */
      insertBuffer(value, offset) {
        utils_1.checkOffsetValue(offset);
        return this._handleBuffer(value, true, offset);
      }
      /**
       * Writes a Buffer to the current write position.
       *
       * @param value { Buffer } The Buffer to write.
       * @param offset { Number } The offset to write the Buffer to.
       *
       * @return this
       */
      writeBuffer(value, offset) {
        return this._handleBuffer(value, false, offset);
      }
      /**
       * Reads a null-terminated Buffer from the current read poisiton.
       *
       * @return { Buffer }
       */
      readBufferNT() {
        let nullPos = this.length;
        for (let i = this._readOffset; i < this.length; i++) {
          if (this._buff[i] === 0) {
            nullPos = i;
            break;
          }
        }
        const value = this._buff.slice(this._readOffset, nullPos);
        this._readOffset = nullPos + 1;
        return value;
      }
      /**
       * Inserts a null-terminated Buffer.
       *
       * @param value { Buffer } The Buffer to write.
       * @param offset { Number } The offset to write the Buffer to.
       *
       * @return this
       */
      insertBufferNT(value, offset) {
        utils_1.checkOffsetValue(offset);
        this.insertBuffer(value, offset);
        this.insertUInt8(0, offset + value.length);
        return this;
      }
      /**
       * Writes a null-terminated Buffer.
       *
       * @param value { Buffer } The Buffer to write.
       * @param offset { Number } The offset to write the Buffer to.
       *
       * @return this
       */
      writeBufferNT(value, offset) {
        if (typeof offset !== "undefined") {
          utils_1.checkOffsetValue(offset);
        }
        this.writeBuffer(value, offset);
        this.writeUInt8(0, typeof offset === "number" ? offset + value.length : this._writeOffset);
        return this;
      }
      /**
       * Clears the SmartBuffer instance to its original empty state.
       */
      clear() {
        this._writeOffset = 0;
        this._readOffset = 0;
        this.length = 0;
        return this;
      }
      /**
       * Gets the remaining data left to be read from the SmartBuffer instance.
       *
       * @return { Number }
       */
      remaining() {
        return this.length - this._readOffset;
      }
      /**
       * Gets the current read offset value of the SmartBuffer instance.
       *
       * @return { Number }
       */
      get readOffset() {
        return this._readOffset;
      }
      /**
       * Sets the read offset value of the SmartBuffer instance.
       *
       * @param offset { Number } - The offset value to set.
       */
      set readOffset(offset) {
        utils_1.checkOffsetValue(offset);
        utils_1.checkTargetOffset(offset, this);
        this._readOffset = offset;
      }
      /**
       * Gets the current write offset value of the SmartBuffer instance.
       *
       * @return { Number }
       */
      get writeOffset() {
        return this._writeOffset;
      }
      /**
       * Sets the write offset value of the SmartBuffer instance.
       *
       * @param offset { Number } - The offset value to set.
       */
      set writeOffset(offset) {
        utils_1.checkOffsetValue(offset);
        utils_1.checkTargetOffset(offset, this);
        this._writeOffset = offset;
      }
      /**
       * Gets the currently set string encoding of the SmartBuffer instance.
       *
       * @return { BufferEncoding } The string Buffer encoding currently set.
       */
      get encoding() {
        return this._encoding;
      }
      /**
       * Sets the string encoding of the SmartBuffer instance.
       *
       * @param encoding { BufferEncoding } The string Buffer encoding to set.
       */
      set encoding(encoding) {
        utils_1.checkEncoding(encoding);
        this._encoding = encoding;
      }
      /**
       * Gets the underlying internal Buffer. (This includes unmanaged data in the Buffer)
       *
       * @return { Buffer } The Buffer value.
       */
      get internalBuffer() {
        return this._buff;
      }
      /**
       * Gets the value of the internal managed Buffer (Includes managed data only)
       *
       * @param { Buffer }
       */
      toBuffer() {
        return this._buff.slice(0, this.length);
      }
      /**
       * Gets the String value of the internal managed Buffer
       *
       * @param encoding { String } The BufferEncoding to display the Buffer as (defaults to instance level encoding).
       */
      toString(encoding) {
        const encodingVal = typeof encoding === "string" ? encoding : this._encoding;
        utils_1.checkEncoding(encodingVal);
        return this._buff.toString(encodingVal, 0, this.length);
      }
      /**
       * Destroys the SmartBuffer instance.
       */
      destroy() {
        this.clear();
        return this;
      }
      /**
       * Handles inserting and writing strings.
       *
       * @param value { String } The String value to insert.
       * @param isInsert { Boolean } True if inserting a string, false if writing.
       * @param arg2 { Number | String } The offset to insert the string at, or the BufferEncoding to use.
       * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding).
       */
      _handleString(value, isInsert, arg3, encoding) {
        let offsetVal = this._writeOffset;
        let encodingVal = this._encoding;
        if (typeof arg3 === "number") {
          offsetVal = arg3;
        } else if (typeof arg3 === "string") {
          utils_1.checkEncoding(arg3);
          encodingVal = arg3;
        }
        if (typeof encoding === "string") {
          utils_1.checkEncoding(encoding);
          encodingVal = encoding;
        }
        const byteLength = Buffer.byteLength(value, encodingVal);
        if (isInsert) {
          this.ensureInsertable(byteLength, offsetVal);
        } else {
          this._ensureWriteable(byteLength, offsetVal);
        }
        this._buff.write(value, offsetVal, byteLength, encodingVal);
        if (isInsert) {
          this._writeOffset += byteLength;
        } else {
          if (typeof arg3 === "number") {
            this._writeOffset = Math.max(this._writeOffset, offsetVal + byteLength);
          } else {
            this._writeOffset += byteLength;
          }
        }
        return this;
      }
      /**
       * Handles writing or insert of a Buffer.
       *
       * @param value { Buffer } The Buffer to write.
       * @param offset { Number } The offset to write the Buffer to.
       */
      _handleBuffer(value, isInsert, offset) {
        const offsetVal = typeof offset === "number" ? offset : this._writeOffset;
        if (isInsert) {
          this.ensureInsertable(value.length, offsetVal);
        } else {
          this._ensureWriteable(value.length, offsetVal);
        }
        value.copy(this._buff, offsetVal);
        if (isInsert) {
          this._writeOffset += value.length;
        } else {
          if (typeof offset === "number") {
            this._writeOffset = Math.max(this._writeOffset, offsetVal + value.length);
          } else {
            this._writeOffset += value.length;
          }
        }
        return this;
      }
      /**
       * Ensures that the internal Buffer is large enough to read data.
       *
       * @param length { Number } The length of the data that needs to be read.
       * @param offset { Number } The offset of the data that needs to be read.
       */
      ensureReadable(length, offset) {
        let offsetVal = this._readOffset;
        if (typeof offset !== "undefined") {
          utils_1.checkOffsetValue(offset);
          offsetVal = offset;
        }
        if (offsetVal < 0 || offsetVal + length > this.length) {
          throw new Error(utils_1.ERRORS.INVALID_READ_BEYOND_BOUNDS);
        }
      }
      /**
       * Ensures that the internal Buffer is large enough to insert data.
       *
       * @param dataLength { Number } The length of the data that needs to be written.
       * @param offset { Number } The offset of the data to be written.
       */
      ensureInsertable(dataLength, offset) {
        utils_1.checkOffsetValue(offset);
        this._ensureCapacity(this.length + dataLength);
        if (offset < this.length) {
          this._buff.copy(this._buff, offset + dataLength, offset, this._buff.length);
        }
        if (offset + dataLength > this.length) {
          this.length = offset + dataLength;
        } else {
          this.length += dataLength;
        }
      }
      /**
       * Ensures that the internal Buffer is large enough to write data.
       *
       * @param dataLength { Number } The length of the data that needs to be written.
       * @param offset { Number } The offset of the data to be written (defaults to writeOffset).
       */
      _ensureWriteable(dataLength, offset) {
        const offsetVal = typeof offset === "number" ? offset : this._writeOffset;
        this._ensureCapacity(offsetVal + dataLength);
        if (offsetVal + dataLength > this.length) {
          this.length = offsetVal + dataLength;
        }
      }
      /**
       * Ensures that the internal Buffer is large enough to write at least the given amount of data.
       *
       * @param minLength { Number } The minimum length of the data needs to be written.
       */
      _ensureCapacity(minLength) {
        const oldLength = this._buff.length;
        if (minLength > oldLength) {
          let data = this._buff;
          let newLength = oldLength * 3 / 2 + 1;
          if (newLength < minLength) {
            newLength = minLength;
          }
          this._buff = Buffer.allocUnsafe(newLength);
          data.copy(this._buff, 0, 0, oldLength);
        }
      }
      /**
       * Reads a numeric number value using the provided function.
       *
       * @typeparam T { number | bigint } The type of the value to be read
       *
       * @param func { Function(offset: number) => number } The function to read data on the internal Buffer with.
       * @param byteSize { Number } The number of bytes read.
       * @param offset { Number } The offset to read from (optional). When this is not provided, the managed readOffset is used instead.
       *
       * @returns { T } the number value
       */
      _readNumberValue(func, byteSize, offset) {
        this.ensureReadable(byteSize, offset);
        const value = func.call(this._buff, typeof offset === "number" ? offset : this._readOffset);
        if (typeof offset === "undefined") {
          this._readOffset += byteSize;
        }
        return value;
      }
      /**
       * Inserts a numeric number value based on the given offset and value.
       *
       * @typeparam T { number | bigint } The type of the value to be written
       *
       * @param func { Function(offset: T, offset?) => number} The function to write data on the internal Buffer with.
       * @param byteSize { Number } The number of bytes written.
       * @param value { T } The number value to write.
       * @param offset { Number } the offset to write the number at (REQUIRED).
       *
       * @returns SmartBuffer this buffer
       */
      _insertNumberValue(func, byteSize, value, offset) {
        utils_1.checkOffsetValue(offset);
        this.ensureInsertable(byteSize, offset);
        func.call(this._buff, value, offset);
        this._writeOffset += byteSize;
        return this;
      }
      /**
       * Writes a numeric number value based on the given offset and value.
       *
       * @typeparam T { number | bigint } The type of the value to be written
       *
       * @param func { Function(offset: T, offset?) => number} The function to write data on the internal Buffer with.
       * @param byteSize { Number } The number of bytes written.
       * @param value { T } The number value to write.
       * @param offset { Number } the offset to write the number at (REQUIRED).
       *
       * @returns SmartBuffer this buffer
       */
      _writeNumberValue(func, byteSize, value, offset) {
        if (typeof offset === "number") {
          if (offset < 0) {
            throw new Error(utils_1.ERRORS.INVALID_WRITE_BEYOND_BOUNDS);
          }
          utils_1.checkOffsetValue(offset);
        }
        const offsetVal = typeof offset === "number" ? offset : this._writeOffset;
        this._ensureWriteable(byteSize, offsetVal);
        func.call(this._buff, value, offsetVal);
        if (typeof offset === "number") {
          this._writeOffset = Math.max(this._writeOffset, offsetVal + byteSize);
        } else {
          this._writeOffset += byteSize;
        }
        return this;
      }
    };
    exports2.SmartBuffer = SmartBuffer;
  }
});

// ../../node_modules/.pnpm/socks@2.8.5/node_modules/socks/build/common/constants.js
var require_constants2 = __commonJS({
  "../../node_modules/.pnpm/socks@2.8.5/node_modules/socks/build/common/constants.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SOCKS5_NO_ACCEPTABLE_AUTH = exports2.SOCKS5_CUSTOM_AUTH_END = exports2.SOCKS5_CUSTOM_AUTH_START = exports2.SOCKS_INCOMING_PACKET_SIZES = exports2.SocksClientState = exports2.Socks5Response = exports2.Socks5HostType = exports2.Socks5Auth = exports2.Socks4Response = exports2.SocksCommand = exports2.ERRORS = exports2.DEFAULT_TIMEOUT = void 0;
    var DEFAULT_TIMEOUT = 3e4;
    exports2.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT;
    var ERRORS = {
      InvalidSocksCommand: "An invalid SOCKS command was provided. Valid options are connect, bind, and associate.",
      InvalidSocksCommandForOperation: "An invalid SOCKS command was provided. Only a subset of commands are supported for this operation.",
      InvalidSocksCommandChain: "An invalid SOCKS command was provided. Chaining currently only supports the connect command.",
      InvalidSocksClientOptionsDestination: "An invalid destination host was provided.",
      InvalidSocksClientOptionsExistingSocket: "An invalid existing socket was provided. This should be an instance of stream.Duplex.",
      InvalidSocksClientOptionsProxy: "Invalid SOCKS proxy details were provided.",
      InvalidSocksClientOptionsTimeout: "An invalid timeout value was provided. Please enter a value above 0 (in ms).",
      InvalidSocksClientOptionsProxiesLength: "At least two socks proxies must be provided for chaining.",
      InvalidSocksClientOptionsCustomAuthRange: "Custom auth must be a value between 0x80 and 0xFE.",
      InvalidSocksClientOptionsCustomAuthOptions: "When a custom_auth_method is provided, custom_auth_request_handler, custom_auth_response_size, and custom_auth_response_handler must also be provided and valid.",
      NegotiationError: "Negotiation error",
      SocketClosed: "Socket closed",
      ProxyConnectionTimedOut: "Proxy connection timed out",
      InternalError: "SocksClient internal error (this should not happen)",
      InvalidSocks4HandshakeResponse: "Received invalid Socks4 handshake response",
      Socks4ProxyRejectedConnection: "Socks4 Proxy rejected connection",
      InvalidSocks4IncomingConnectionResponse: "Socks4 invalid incoming connection response",
      Socks4ProxyRejectedIncomingBoundConnection: "Socks4 Proxy rejected incoming bound connection",
      InvalidSocks5InitialHandshakeResponse: "Received invalid Socks5 initial handshake response",
      InvalidSocks5IntiailHandshakeSocksVersion: "Received invalid Socks5 initial handshake (invalid socks version)",
      InvalidSocks5InitialHandshakeNoAcceptedAuthType: "Received invalid Socks5 initial handshake (no accepted authentication type)",
      InvalidSocks5InitialHandshakeUnknownAuthType: "Received invalid Socks5 initial handshake (unknown authentication type)",
      Socks5AuthenticationFailed: "Socks5 Authentication failed",
      InvalidSocks5FinalHandshake: "Received invalid Socks5 final handshake response",
      InvalidSocks5FinalHandshakeRejected: "Socks5 proxy rejected connection",
      InvalidSocks5IncomingConnectionResponse: "Received invalid Socks5 incoming connection response",
      Socks5ProxyRejectedIncomingBoundConnection: "Socks5 Proxy rejected incoming bound connection"
    };
    exports2.ERRORS = ERRORS;
    var SOCKS_INCOMING_PACKET_SIZES = {
      Socks5InitialHandshakeResponse: 2,
      Socks5UserPassAuthenticationResponse: 2,
      // Command response + incoming connection (bind)
      Socks5ResponseHeader: 5,
      // We need at least 5 to read the hostname length, then we wait for the address+port information.
      Socks5ResponseIPv4: 10,
      // 4 header + 4 ip + 2 port
      Socks5ResponseIPv6: 22,
      // 4 header + 16 ip + 2 port
      Socks5ResponseHostname: (hostNameLength) => hostNameLength + 7,
      // 4 header + 1 host length + host + 2 port
      // Command response + incoming connection (bind)
      Socks4Response: 8
      // 2 header + 2 port + 4 ip
    };
    exports2.SOCKS_INCOMING_PACKET_SIZES = SOCKS_INCOMING_PACKET_SIZES;
    var SocksCommand;
    (function(SocksCommand2) {
      SocksCommand2[SocksCommand2["connect"] = 1] = "connect";
      SocksCommand2[SocksCommand2["bind"] = 2] = "bind";
      SocksCommand2[SocksCommand2["associate"] = 3] = "associate";
    })(SocksCommand || (exports2.SocksCommand = SocksCommand = {}));
    var Socks4Response;
    (function(Socks4Response2) {
      Socks4Response2[Socks4Response2["Granted"] = 90] = "Granted";
      Socks4Response2[Socks4Response2["Failed"] = 91] = "Failed";
      Socks4Response2[Socks4Response2["Rejected"] = 92] = "Rejected";
      Socks4Response2[Socks4Response2["RejectedIdent"] = 93] = "RejectedIdent";
    })(Socks4Response || (exports2.Socks4Response = Socks4Response = {}));
    var Socks5Auth;
    (function(Socks5Auth2) {
      Socks5Auth2[Socks5Auth2["NoAuth"] = 0] = "NoAuth";
      Socks5Auth2[Socks5Auth2["GSSApi"] = 1] = "GSSApi";
      Socks5Auth2[Socks5Auth2["UserPass"] = 2] = "UserPass";
    })(Socks5Auth || (exports2.Socks5Auth = Socks5Auth = {}));
    var SOCKS5_CUSTOM_AUTH_START = 128;
    exports2.SOCKS5_CUSTOM_AUTH_START = SOCKS5_CUSTOM_AUTH_START;
    var SOCKS5_CUSTOM_AUTH_END = 254;
    exports2.SOCKS5_CUSTOM_AUTH_END = SOCKS5_CUSTOM_AUTH_END;
    var SOCKS5_NO_ACCEPTABLE_AUTH = 255;
    exports2.SOCKS5_NO_ACCEPTABLE_AUTH = SOCKS5_NO_ACCEPTABLE_AUTH;
    var Socks5Response;
    (function(Socks5Response2) {
      Socks5Response2[Socks5Response2["Granted"] = 0] = "Granted";
      Socks5Response2[Socks5Response2["Failure"] = 1] = "Failure";
      Socks5Response2[Socks5Response2["NotAllowed"] = 2] = "NotAllowed";
      Socks5Response2[Socks5Response2["NetworkUnreachable"] = 3] = "NetworkUnreachable";
      Socks5Response2[Socks5Response2["HostUnreachable"] = 4] = "HostUnreachable";
      Socks5Response2[Socks5Response2["ConnectionRefused"] = 5] = "ConnectionRefused";
      Socks5Response2[Socks5Response2["TTLExpired"] = 6] = "TTLExpired";
      Socks5Response2[Socks5Response2["CommandNotSupported"] = 7] = "CommandNotSupported";
      Socks5Response2[Socks5Response2["AddressNotSupported"] = 8] = "AddressNotSupported";
    })(Socks5Response || (exports2.Socks5Response = Socks5Response = {}));
    var Socks5HostType;
    (function(Socks5HostType2) {
      Socks5HostType2[Socks5HostType2["IPv4"] = 1] = "IPv4";
      Socks5HostType2[Socks5HostType2["Hostname"] = 3] = "Hostname";
      Socks5HostType2[Socks5HostType2["IPv6"] = 4] = "IPv6";
    })(Socks5HostType || (exports2.Socks5HostType = Socks5HostType = {}));
    var SocksClientState;
    (function(SocksClientState2) {
      SocksClientState2[SocksClientState2["Created"] = 0] = "Created";
      SocksClientState2[SocksClientState2["Connecting"] = 1] = "Connecting";
      SocksClientState2[SocksClientState2["Connected"] = 2] = "Connected";
      SocksClientState2[SocksClientState2["SentInitialHandshake"] = 3] = "SentInitialHandshake";
      SocksClientState2[SocksClientState2["ReceivedInitialHandshakeResponse"] = 4] = "ReceivedInitialHandshakeResponse";
      SocksClientState2[SocksClientState2["SentAuthentication"] = 5] = "SentAuthentication";
      SocksClientState2[SocksClientState2["ReceivedAuthenticationResponse"] = 6] = "ReceivedAuthenticationResponse";
      SocksClientState2[SocksClientState2["SentFinalHandshake"] = 7] = "SentFinalHandshake";
      SocksClientState2[SocksClientState2["ReceivedFinalResponse"] = 8] = "ReceivedFinalResponse";
      SocksClientState2[SocksClientState2["BoundWaitingForConnection"] = 9] = "BoundWaitingForConnection";
      SocksClientState2[SocksClientState2["Established"] = 10] = "Established";
      SocksClientState2[SocksClientState2["Disconnected"] = 11] = "Disconnected";
      SocksClientState2[SocksClientState2["Error"] = 99] = "Error";
    })(SocksClientState || (exports2.SocksClientState = SocksClientState = {}));
  }
});

// ../../node_modules/.pnpm/socks@2.8.5/node_modules/socks/build/common/util.js
var require_util = __commonJS({
  "../../node_modules/.pnpm/socks@2.8.5/node_modules/socks/build/common/util.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.shuffleArray = exports2.SocksClientError = void 0;
    var SocksClientError = class extends Error {
      constructor(message, options) {
        super(message);
        this.options = options;
      }
    };
    exports2.SocksClientError = SocksClientError;
    function shuffleArray(array3) {
      for (let i = array3.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array3[i], array3[j]] = [array3[j], array3[i]];
      }
    }
    exports2.shuffleArray = shuffleArray;
  }
});

// ../../node_modules/.pnpm/ip-address@9.0.5/node_modules/ip-address/dist/common.js
var require_common2 = __commonJS({
  "../../node_modules/.pnpm/ip-address@9.0.5/node_modules/ip-address/dist/common.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.isCorrect = exports2.isInSubnet = void 0;
    function isInSubnet(address) {
      if (this.subnetMask < address.subnetMask) {
        return false;
      }
      if (this.mask(address.subnetMask) === address.mask()) {
        return true;
      }
      return false;
    }
    exports2.isInSubnet = isInSubnet;
    function isCorrect(defaultBits) {
      return function() {
        if (this.addressMinusSuffix !== this.correctForm()) {
          return false;
        }
        if (this.subnetMask === defaultBits && !this.parsedSubnet) {
          return true;
        }
        return this.parsedSubnet === String(this.subnetMask);
      };
    }
    exports2.isCorrect = isCorrect;
  }
});

// ../../node_modules/.pnpm/ip-address@9.0.5/node_modules/ip-address/dist/v4/constants.js
var require_constants3 = __commonJS({
  "../../node_modules/.pnpm/ip-address@9.0.5/node_modules/ip-address/dist/v4/constants.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.RE_SUBNET_STRING = exports2.RE_ADDRESS = exports2.GROUPS = exports2.BITS = void 0;
    exports2.BITS = 32;
    exports2.GROUPS = 4;
    exports2.RE_ADDRESS = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g;
    exports2.RE_SUBNET_STRING = /\/\d{1,2}$/;
  }
});

// ../../node_modules/.pnpm/ip-address@9.0.5/node_modules/ip-address/dist/address-error.js
var require_address_error = __commonJS({
  "../../node_modules/.pnpm/ip-address@9.0.5/node_modules/ip-address/dist/address-error.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.AddressError = void 0;
    var AddressError = class extends Error {
      constructor(message, parseMessage) {
        super(message);
        this.name = "AddressError";
        if (parseMessage !== null) {
          this.parseMessage = parseMessage;
        }
      }
    };
    exports2.AddressError = AddressError;
  }
});

// ../../node_modules/.pnpm/jsbn@1.1.0/node_modules/jsbn/index.js
var require_jsbn = __commonJS({
  "../../node_modules/.pnpm/jsbn@1.1.0/node_modules/jsbn/index.js"(exports2, module2) {
    "use strict";
    (function() {
      var dbits;
      var canary = 244837814094590;
      var j_lm = (canary & 16777215) == 15715070;
      function BigInteger(a, b, c2) {
        if (a != null)
          if ("number" == typeof a) this.fromNumber(a, b, c2);
          else if (b == null && "string" != typeof a) this.fromString(a, 256);
          else this.fromString(a, b);
      }
      function nbi() {
        return new BigInteger(null);
      }
      function am1(i, x, w, j, c2, n) {
        while (--n >= 0) {
          var v = x * this[i++] + w[j] + c2;
          c2 = Math.floor(v / 67108864);
          w[j++] = v & 67108863;
        }
        return c2;
      }
      function am2(i, x, w, j, c2, n) {
        var xl = x & 32767, xh = x >> 15;
        while (--n >= 0) {
          var l = this[i] & 32767;
          var h = this[i++] >> 15;
          var m = xh * l + h * xl;
          l = xl * l + ((m & 32767) << 15) + w[j] + (c2 & 1073741823);
          c2 = (l >>> 30) + (m >>> 15) + xh * h + (c2 >>> 30);
          w[j++] = l & 1073741823;
        }
        return c2;
      }
      function am3(i, x, w, j, c2, n) {
        var xl = x & 16383, xh = x >> 14;
        while (--n >= 0) {
          var l = this[i] & 16383;
          var h = this[i++] >> 14;
          var m = xh * l + h * xl;
          l = xl * l + ((m & 16383) << 14) + w[j] + c2;
          c2 = (l >> 28) + (m >> 14) + xh * h;
          w[j++] = l & 268435455;
        }
        return c2;
      }
      var inBrowser = typeof navigator !== "undefined";
      if (inBrowser && j_lm && navigator.appName == "Microsoft Internet Explorer") {
        BigInteger.prototype.am = am2;
        dbits = 30;
      } else if (inBrowser && j_lm && navigator.appName != "Netscape") {
        BigInteger.prototype.am = am1;
        dbits = 26;
      } else {
        BigInteger.prototype.am = am3;
        dbits = 28;
      }
      BigInteger.prototype.DB = dbits;
      BigInteger.prototype.DM = (1 << dbits) - 1;
      BigInteger.prototype.DV = 1 << dbits;
      var BI_FP = 52;
      BigInteger.prototype.FV = Math.pow(2, BI_FP);
      BigInteger.prototype.F1 = BI_FP - dbits;
      BigInteger.prototype.F2 = 2 * dbits - BI_FP;
      var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
      var BI_RC = new Array();
      var rr, vv;
      rr = "0".charCodeAt(0);
      for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv;
      rr = "a".charCodeAt(0);
      for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
      rr = "A".charCodeAt(0);
      for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
      function int2char(n) {
        return BI_RM.charAt(n);
      }
      function intAt(s, i) {
        var c2 = BI_RC[s.charCodeAt(i)];
        return c2 == null ? -1 : c2;
      }
      function bnpCopyTo(r) {
        for (var i = this.t - 1; i >= 0; --i) r[i] = this[i];
        r.t = this.t;
        r.s = this.s;
      }
      function bnpFromInt(x) {
        this.t = 1;
        this.s = x < 0 ? -1 : 0;
        if (x > 0) this[0] = x;
        else if (x < -1) this[0] = x + this.DV;
        else this.t = 0;
      }
      function nbv(i) {
        var r = nbi();
        r.fromInt(i);
        return r;
      }
      function bnpFromString(s, b) {
        var k;
        if (b == 16) k = 4;
        else if (b == 8) k = 3;
        else if (b == 256) k = 8;
        else if (b == 2) k = 1;
        else if (b == 32) k = 5;
        else if (b == 4) k = 2;
        else {
          this.fromRadix(s, b);
          return;
        }
        this.t = 0;
        this.s = 0;
        var i = s.length, mi = false, sh = 0;
        while (--i >= 0) {
          var x = k == 8 ? s[i] & 255 : intAt(s, i);
          if (x < 0) {
            if (s.charAt(i) == "-") mi = true;
            continue;
          }
          mi = false;
          if (sh == 0)
            this[this.t++] = x;
          else if (sh + k > this.DB) {
            this[this.t - 1] |= (x & (1 << this.DB - sh) - 1) << sh;
            this[this.t++] = x >> this.DB - sh;
          } else
            this[this.t - 1] |= x << sh;
          sh += k;
          if (sh >= this.DB) sh -= this.DB;
        }
        if (k == 8 && (s[0] & 128) != 0) {
          this.s = -1;
          if (sh > 0) this[this.t - 1] |= (1 << this.DB - sh) - 1 << sh;
        }
        this.clamp();
        if (mi) BigInteger.ZERO.subTo(this, this);
      }
      function bnpClamp() {
        var c2 = this.s & this.DM;
        while (this.t > 0 && this[this.t - 1] == c2) --this.t;
      }
      function bnToString(b) {
        if (this.s < 0) return "-" + this.negate().toString(b);
        var k;
        if (b == 16) k = 4;
        else if (b == 8) k = 3;
        else if (b == 2) k = 1;
        else if (b == 32) k = 5;
        else if (b == 4) k = 2;
        else return this.toRadix(b);
        var km = (1 << k) - 1, d, m = false, r = "", i = this.t;
        var p2 = this.DB - i * this.DB % k;
        if (i-- > 0) {
          if (p2 < this.DB && (d = this[i] >> p2) > 0) {
            m = true;
            r = int2char(d);
          }
          while (i >= 0) {
            if (p2 < k) {
              d = (this[i] & (1 << p2) - 1) << k - p2;
              d |= this[--i] >> (p2 += this.DB - k);
            } else {
              d = this[i] >> (p2 -= k) & km;
              if (p2 <= 0) {
                p2 += this.DB;
                --i;
              }
            }
            if (d > 0) m = true;
            if (m) r += int2char(d);
          }
        }
        return m ? r : "0";
      }
      function bnNegate() {
        var r = nbi();
        BigInteger.ZERO.subTo(this, r);
        return r;
      }
      function bnAbs() {
        return this.s < 0 ? this.negate() : this;
      }
      function bnCompareTo(a) {
        var r = this.s - a.s;
        if (r != 0) return r;
        var i = this.t;
        r = i - a.t;
        if (r != 0) return this.s < 0 ? -r : r;
        while (--i >= 0) if ((r = this[i] - a[i]) != 0) return r;
        return 0;
      }
      function nbits(x) {
        var r = 1, t2;
        if ((t2 = x >>> 16) != 0) {
          x = t2;
          r += 16;
        }
        if ((t2 = x >> 8) != 0) {
          x = t2;
          r += 8;
        }
        if ((t2 = x >> 4) != 0) {
          x = t2;
          r += 4;
        }
        if ((t2 = x >> 2) != 0) {
          x = t2;
          r += 2;
        }
        if ((t2 = x >> 1) != 0) {
          x = t2;
          r += 1;
        }
        return r;
      }
      function bnBitLength() {
        if (this.t <= 0) return 0;
        return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ this.s & this.DM);
      }
      function bnpDLShiftTo(n, r) {
        var i;
        for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i];
        for (i = n - 1; i >= 0; --i) r[i] = 0;
        r.t = this.t + n;
        r.s = this.s;
      }
      function bnpDRShiftTo(n, r) {
        for (var i = n; i < this.t; ++i) r[i - n] = this[i];
        r.t = Math.max(this.t - n, 0);
        r.s = this.s;
      }
      function bnpLShiftTo(n, r) {
        var bs = n % this.DB;
        var cbs = this.DB - bs;
        var bm = (1 << cbs) - 1;
        var ds = Math.floor(n / this.DB), c2 = this.s << bs & this.DM, i;
        for (i = this.t - 1; i >= 0; --i) {
          r[i + ds + 1] = this[i] >> cbs | c2;
          c2 = (this[i] & bm) << bs;
        }
        for (i = ds - 1; i >= 0; --i) r[i] = 0;
        r[ds] = c2;
        r.t = this.t + ds + 1;
        r.s = this.s;
        r.clamp();
      }
      function bnpRShiftTo(n, r) {
        r.s = this.s;
        var ds = Math.floor(n / this.DB);
        if (ds >= this.t) {
          r.t = 0;
          return;
        }
        var bs = n % this.DB;
        var cbs = this.DB - bs;
        var bm = (1 << bs) - 1;
        r[0] = this[ds] >> bs;
        for (var i = ds + 1; i < this.t; ++i) {
          r[i - ds - 1] |= (this[i] & bm) << cbs;
          r[i - ds] = this[i] >> bs;
        }
        if (bs > 0) r[this.t - ds - 1] |= (this.s & bm) << cbs;
        r.t = this.t - ds;
        r.clamp();
      }
      function bnpSubTo(a, r) {
        var i = 0, c2 = 0, m = Math.min(a.t, this.t);
        while (i < m) {
          c2 += this[i] - a[i];
          r[i++] = c2 & this.DM;
          c2 >>= this.DB;
        }
        if (a.t < this.t) {
          c2 -= a.s;
          while (i < this.t) {
            c2 += this[i];
            r[i++] = c2 & this.DM;
            c2 >>= this.DB;
          }
          c2 += this.s;
        } else {
          c2 += this.s;
          while (i < a.t) {
            c2 -= a[i];
            r[i++] = c2 & this.DM;
            c2 >>= this.DB;
          }
          c2 -= a.s;
        }
        r.s = c2 < 0 ? -1 : 0;
        if (c2 < -1) r[i++] = this.DV + c2;
        else if (c2 > 0) r[i++] = c2;
        r.t = i;
        r.clamp();
      }
      function bnpMultiplyTo(a, r) {
        var x = this.abs(), y = a.abs();
        var i = x.t;
        r.t = i + y.t;
        while (--i >= 0) r[i] = 0;
        for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t);
        r.s = 0;
        r.clamp();
        if (this.s != a.s) BigInteger.ZERO.subTo(r, r);
      }
      function bnpSquareTo(r) {
        var x = this.abs();
        var i = r.t = 2 * x.t;
        while (--i >= 0) r[i] = 0;
        for (i = 0; i < x.t - 1; ++i) {
          var c2 = x.am(i, x[i], r, 2 * i, 0, 1);
          if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c2, x.t - i - 1)) >= x.DV) {
            r[i + x.t] -= x.DV;
            r[i + x.t + 1] = 1;
          }
        }
        if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1);
        r.s = 0;
        r.clamp();
      }
      function bnpDivRemTo(m, q2, r) {
        var pm = m.abs();
        if (pm.t <= 0) return;
        var pt = this.abs();
        if (pt.t < pm.t) {
          if (q2 != null) q2.fromInt(0);
          if (r != null) this.copyTo(r);
          return;
        }
        if (r == null) r = nbi();
        var y = nbi(), ts = this.s, ms = m.s;
        var nsh = this.DB - nbits(pm[pm.t - 1]);
        if (nsh > 0) {
          pm.lShiftTo(nsh, y);
          pt.lShiftTo(nsh, r);
        } else {
          pm.copyTo(y);
          pt.copyTo(r);
        }
        var ys = y.t;
        var y0 = y[ys - 1];
        if (y0 == 0) return;
        var yt = y0 * (1 << this.F1) + (ys > 1 ? y[ys - 2] >> this.F2 : 0);
        var d1 = this.FV / yt, d2 = (1 << this.F1) / yt, e = 1 << this.F2;
        var i = r.t, j = i - ys, t2 = q2 == null ? nbi() : q2;
        y.dlShiftTo(j, t2);
        if (r.compareTo(t2) >= 0) {
          r[r.t++] = 1;
          r.subTo(t2, r);
        }
        BigInteger.ONE.dlShiftTo(ys, t2);
        t2.subTo(y, y);
        while (y.t < ys) y[y.t++] = 0;
        while (--j >= 0) {
          var qd = r[--i] == y0 ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2);
          if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) {
            y.dlShiftTo(j, t2);
            r.subTo(t2, r);
            while (r[i] < --qd) r.subTo(t2, r);
          }
        }
        if (q2 != null) {
          r.drShiftTo(ys, q2);
          if (ts != ms) BigInteger.ZERO.subTo(q2, q2);
        }
        r.t = ys;
        r.clamp();
        if (nsh > 0) r.rShiftTo(nsh, r);
        if (ts < 0) BigInteger.ZERO.subTo(r, r);
      }
      function bnMod(a) {
        var r = nbi();
        this.abs().divRemTo(a, null, r);
        if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r);
        return r;
      }
      function Classic(m) {
        this.m = m;
      }
      function cConvert(x) {
        if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);
        else return x;
      }
      function cRevert(x) {
        return x;
      }
      function cReduce(x) {
        x.divRemTo(this.m, null, x);
      }
      function cMulTo(x, y, r) {
        x.multiplyTo(y, r);
        this.reduce(r);
      }
      function cSqrTo(x, r) {
        x.squareTo(r);
        this.reduce(r);
      }
      Classic.prototype.convert = cConvert;
      Classic.prototype.revert = cRevert;
      Classic.prototype.reduce = cReduce;
      Classic.prototype.mulTo = cMulTo;
      Classic.prototype.sqrTo = cSqrTo;
      function bnpInvDigit() {
        if (this.t < 1) return 0;
        var x = this[0];
        if ((x & 1) == 0) return 0;
        var y = x & 3;
        y = y * (2 - (x & 15) * y) & 15;
        y = y * (2 - (x & 255) * y) & 255;
        y = y * (2 - ((x & 65535) * y & 65535)) & 65535;
        y = y * (2 - x * y % this.DV) % this.DV;
        return y > 0 ? this.DV - y : -y;
      }
      function Montgomery(m) {
        this.m = m;
        this.mp = m.invDigit();
        this.mpl = this.mp & 32767;
        this.mph = this.mp >> 15;
        this.um = (1 << m.DB - 15) - 1;
        this.mt2 = 2 * m.t;
      }
      function montConvert(x) {
        var r = nbi();
        x.abs().dlShiftTo(this.m.t, r);
        r.divRemTo(this.m, null, r);
        if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r);
        return r;
      }
      function montRevert(x) {
        var r = nbi();
        x.copyTo(r);
        this.reduce(r);
        return r;
      }
      function montReduce(x) {
        while (x.t <= this.mt2)
          x[x.t++] = 0;
        for (var i = 0; i < this.m.t; ++i) {
          var j = x[i] & 32767;
          var u0 = j * this.mpl + ((j * this.mph + (x[i] >> 15) * this.mpl & this.um) << 15) & x.DM;
          j = i + this.m.t;
          x[j] += this.m.am(0, u0, x, i, 0, this.m.t);
          while (x[j] >= x.DV) {
            x[j] -= x.DV;
            x[++j]++;
          }
        }
        x.clamp();
        x.drShiftTo(this.m.t, x);
        if (x.compareTo(this.m) >= 0) x.subTo(this.m, x);
      }
      function montSqrTo(x, r) {
        x.squareTo(r);
        this.reduce(r);
      }
      function montMulTo(x, y, r) {
        x.multiplyTo(y, r);
        this.reduce(r);
      }
      Montgomery.prototype.convert = montConvert;
      Montgomery.prototype.revert = montRevert;
      Montgomery.prototype.reduce = montReduce;
      Montgomery.prototype.mulTo = montMulTo;
      Montgomery.prototype.sqrTo = montSqrTo;
      function bnpIsEven() {
        return (this.t > 0 ? this[0] & 1 : this.s) == 0;
      }
      function bnpExp(e, z4) {
        if (e > 4294967295 || e < 1) return BigInteger.ONE;
        var r = nbi(), r2 = nbi(), g = z4.convert(this), i = nbits(e) - 1;
        g.copyTo(r);
        while (--i >= 0) {
          z4.sqrTo(r, r2);
          if ((e & 1 << i) > 0) z4.mulTo(r2, g, r);
          else {
            var t2 = r;
            r = r2;
            r2 = t2;
          }
        }
        return z4.revert(r);
      }
      function bnModPowInt(e, m) {
        var z4;
        if (e < 256 || m.isEven()) z4 = new Classic(m);
        else z4 = new Montgomery(m);
        return this.exp(e, z4);
      }
      BigInteger.prototype.copyTo = bnpCopyTo;
      BigInteger.prototype.fromInt = bnpFromInt;
      BigInteger.prototype.fromString = bnpFromString;
      BigInteger.prototype.clamp = bnpClamp;
      BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
      BigInteger.prototype.drShiftTo = bnpDRShiftTo;
      BigInteger.prototype.lShiftTo = bnpLShiftTo;
      BigInteger.prototype.rShiftTo = bnpRShiftTo;
      BigInteger.prototype.subTo = bnpSubTo;
      BigInteger.prototype.multiplyTo = bnpMultiplyTo;
      BigInteger.prototype.squareTo = bnpSquareTo;
      BigInteger.prototype.divRemTo = bnpDivRemTo;
      BigInteger.prototype.invDigit = bnpInvDigit;
      BigInteger.prototype.isEven = bnpIsEven;
      BigInteger.prototype.exp = bnpExp;
      BigInteger.prototype.toString = bnToString;
      BigInteger.prototype.negate = bnNegate;
      BigInteger.prototype.abs = bnAbs;
      BigInteger.prototype.compareTo = bnCompareTo;
      BigInteger.prototype.bitLength = bnBitLength;
      BigInteger.prototype.mod = bnMod;
      BigInteger.prototype.modPowInt = bnModPowInt;
      BigInteger.ZERO = nbv(0);
      BigInteger.ONE = nbv(1);
      function bnClone() {
        var r = nbi();
        this.copyTo(r);
        return r;
      }
      function bnIntValue() {
        if (this.s < 0) {
          if (this.t == 1) return this[0] - this.DV;
          else if (this.t == 0) return -1;
        } else if (this.t == 1) return this[0];
        else if (this.t == 0) return 0;
        return (this[1] & (1 << 32 - this.DB) - 1) << this.DB | this[0];
      }
      function bnByteValue() {
        return this.t == 0 ? this.s : this[0] << 24 >> 24;
      }
      function bnShortValue() {
        return this.t == 0 ? this.s : this[0] << 16 >> 16;
      }
      function bnpChunkSize(r) {
        return Math.floor(Math.LN2 * this.DB / Math.log(r));
      }
      function bnSigNum() {
        if (this.s < 0) return -1;
        else if (this.t <= 0 || this.t == 1 && this[0] <= 0) return 0;
        else return 1;
      }
      function bnpToRadix(b) {
        if (b == null) b = 10;
        if (this.signum() == 0 || b < 2 || b > 36) return "0";
        var cs = this.chunkSize(b);
        var a = Math.pow(b, cs);
        var d = nbv(a), y = nbi(), z4 = nbi(), r = "";
        this.divRemTo(d, y, z4);
        while (y.signum() > 0) {
          r = (a + z4.intValue()).toString(b).substr(1) + r;
          y.divRemTo(d, y, z4);
        }
        return z4.intValue().toString(b) + r;
      }
      function bnpFromRadix(s, b) {
        this.fromInt(0);
        if (b == null) b = 10;
        var cs = this.chunkSize(b);
        var d = Math.pow(b, cs), mi = false, j = 0, w = 0;
        for (var i = 0; i < s.length; ++i) {
          var x = intAt(s, i);
          if (x < 0) {
            if (s.charAt(i) == "-" && this.signum() == 0) mi = true;
            continue;
          }
          w = b * w + x;
          if (++j >= cs) {
            this.dMultiply(d);
            this.dAddOffset(w, 0);
            j = 0;
            w = 0;
          }
        }
        if (j > 0) {
          this.dMultiply(Math.pow(b, j));
          this.dAddOffset(w, 0);
        }
        if (mi) BigInteger.ZERO.subTo(this, this);
      }
      function bnpFromNumber(a, b, c2) {
        if ("number" == typeof b) {
          if (a < 2) this.fromInt(1);
          else {
            this.fromNumber(a, c2);
            if (!this.testBit(a - 1))
              this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this);
            if (this.isEven()) this.dAddOffset(1, 0);
            while (!this.isProbablePrime(b)) {
              this.dAddOffset(2, 0);
              if (this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a - 1), this);
            }
          }
        } else {
          var x = new Array(), t2 = a & 7;
          x.length = (a >> 3) + 1;
          b.nextBytes(x);
          if (t2 > 0) x[0] &= (1 << t2) - 1;
          else x[0] = 0;
          this.fromString(x, 256);
        }
      }
      function bnToByteArray() {
        var i = this.t, r = new Array();
        r[0] = this.s;
        var p2 = this.DB - i * this.DB % 8, d, k = 0;
        if (i-- > 0) {
          if (p2 < this.DB && (d = this[i] >> p2) != (this.s & this.DM) >> p2)
            r[k++] = d | this.s << this.DB - p2;
          while (i >= 0) {
            if (p2 < 8) {
              d = (this[i] & (1 << p2) - 1) << 8 - p2;
              d |= this[--i] >> (p2 += this.DB - 8);
            } else {
              d = this[i] >> (p2 -= 8) & 255;
              if (p2 <= 0) {
                p2 += this.DB;
                --i;
              }
            }
            if ((d & 128) != 0) d |= -256;
            if (k == 0 && (this.s & 128) != (d & 128)) ++k;
            if (k > 0 || d != this.s) r[k++] = d;
          }
        }
        return r;
      }
      function bnEquals(a) {
        return this.compareTo(a) == 0;
      }
      function bnMin(a) {
        return this.compareTo(a) < 0 ? this : a;
      }
      function bnMax(a) {
        return this.compareTo(a) > 0 ? this : a;
      }
      function bnpBitwiseTo(a, op, r) {
        var i, f, m = Math.min(a.t, this.t);
        for (i = 0; i < m; ++i) r[i] = op(this[i], a[i]);
        if (a.t < this.t) {
          f = a.s & this.DM;
          for (i = m; i < this.t; ++i) r[i] = op(this[i], f);
          r.t = this.t;
        } else {
          f = this.s & this.DM;
          for (i = m; i < a.t; ++i) r[i] = op(f, a[i]);
          r.t = a.t;
        }
        r.s = op(this.s, a.s);
        r.clamp();
      }
      function op_and(x, y) {
        return x & y;
      }
      function bnAnd(a) {
        var r = nbi();
        this.bitwiseTo(a, op_and, r);
        return r;
      }
      function op_or(x, y) {
        return x | y;
      }
      function bnOr(a) {
        var r = nbi();
        this.bitwiseTo(a, op_or, r);
        return r;
      }
      function op_xor(x, y) {
        return x ^ y;
      }
      function bnXor(a) {
        var r = nbi();
        this.bitwiseTo(a, op_xor, r);
        return r;
      }
      function op_andnot(x, y) {
        return x & ~y;
      }
      function bnAndNot(a) {
        var r = nbi();
        this.bitwiseTo(a, op_andnot, r);
        return r;
      }
      function bnNot() {
        var r = nbi();
        for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i];
        r.t = this.t;
        r.s = ~this.s;
        return r;
      }
      function bnShiftLeft(n) {
        var r = nbi();
        if (n < 0) this.rShiftTo(-n, r);
        else this.lShiftTo(n, r);
        return r;
      }
      function bnShiftRight(n) {
        var r = nbi();
        if (n < 0) this.lShiftTo(-n, r);
        else this.rShiftTo(n, r);
        return r;
      }
      function lbit(x) {
        if (x == 0) return -1;
        var r = 0;
        if ((x & 65535) == 0) {
          x >>= 16;
          r += 16;
        }
        if ((x & 255) == 0) {
          x >>= 8;
          r += 8;
        }
        if ((x & 15) == 0) {
          x >>= 4;
          r += 4;
        }
        if ((x & 3) == 0) {
          x >>= 2;
          r += 2;
        }
        if ((x & 1) == 0) ++r;
        return r;
      }
      function bnGetLowestSetBit() {
        for (var i = 0; i < this.t; ++i)
          if (this[i] != 0) return i * this.DB + lbit(this[i]);
        if (this.s < 0) return this.t * this.DB;
        return -1;
      }
      function cbit(x) {
        var r = 0;
        while (x != 0) {
          x &= x - 1;
          ++r;
        }
        return r;
      }
      function bnBitCount() {
        var r = 0, x = this.s & this.DM;
        for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x);
        return r;
      }
      function bnTestBit(n) {
        var j = Math.floor(n / this.DB);
        if (j >= this.t) return this.s != 0;
        return (this[j] & 1 << n % this.DB) != 0;
      }
      function bnpChangeBit(n, op) {
        var r = BigInteger.ONE.shiftLeft(n);
        this.bitwiseTo(r, op, r);
        return r;
      }
      function bnSetBit(n) {
        return this.changeBit(n, op_or);
      }
      function bnClearBit(n) {
        return this.changeBit(n, op_andnot);
      }
      function bnFlipBit(n) {
        return this.changeBit(n, op_xor);
      }
      function bnpAddTo(a, r) {
        var i = 0, c2 = 0, m = Math.min(a.t, this.t);
        while (i < m) {
          c2 += this[i] + a[i];
          r[i++] = c2 & this.DM;
          c2 >>= this.DB;
        }
        if (a.t < this.t) {
          c2 += a.s;
          while (i < this.t) {
            c2 += this[i];
            r[i++] = c2 & this.DM;
            c2 >>= this.DB;
          }
          c2 += this.s;
        } else {
          c2 += this.s;
          while (i < a.t) {
            c2 += a[i];
            r[i++] = c2 & this.DM;
            c2 >>= this.DB;
          }
          c2 += a.s;
        }
        r.s = c2 < 0 ? -1 : 0;
        if (c2 > 0) r[i++] = c2;
        else if (c2 < -1) r[i++] = this.DV + c2;
        r.t = i;
        r.clamp();
      }
      function bnAdd(a) {
        var r = nbi();
        this.addTo(a, r);
        return r;
      }
      function bnSubtract(a) {
        var r = nbi();
        this.subTo(a, r);
        return r;
      }
      function bnMultiply(a) {
        var r = nbi();
        this.multiplyTo(a, r);
        return r;
      }
      function bnSquare() {
        var r = nbi();
        this.squareTo(r);
        return r;
      }
      function bnDivide(a) {
        var r = nbi();
        this.divRemTo(a, r, null);
        return r;
      }
      function bnRemainder(a) {
        var r = nbi();
        this.divRemTo(a, null, r);
        return r;
      }
      function bnDivideAndRemainder(a) {
        var q2 = nbi(), r = nbi();
        this.divRemTo(a, q2, r);
        return new Array(q2, r);
      }
      function bnpDMultiply(n) {
        this[this.t] = this.am(0, n - 1, this, 0, 0, this.t);
        ++this.t;
        this.clamp();
      }
      function bnpDAddOffset(n, w) {
        if (n == 0) return;
        while (this.t <= w) this[this.t++] = 0;
        this[w] += n;
        while (this[w] >= this.DV) {
          this[w] -= this.DV;
          if (++w >= this.t) this[this.t++] = 0;
          ++this[w];
        }
      }
      function NullExp() {
      }
      function nNop(x) {
        return x;
      }
      function nMulTo(x, y, r) {
        x.multiplyTo(y, r);
      }
      function nSqrTo(x, r) {
        x.squareTo(r);
      }
      NullExp.prototype.convert = nNop;
      NullExp.prototype.revert = nNop;
      NullExp.prototype.mulTo = nMulTo;
      NullExp.prototype.sqrTo = nSqrTo;
      function bnPow(e) {
        return this.exp(e, new NullExp());
      }
      function bnpMultiplyLowerTo(a, n, r) {
        var i = Math.min(this.t + a.t, n);
        r.s = 0;
        r.t = i;
        while (i > 0) r[--i] = 0;
        var j;
        for (j = r.t - this.t; i < j; ++i) r[i + this.t] = this.am(0, a[i], r, i, 0, this.t);
        for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i);
        r.clamp();
      }
      function bnpMultiplyUpperTo(a, n, r) {
        --n;
        var i = r.t = this.t + a.t - n;
        r.s = 0;
        while (--i >= 0) r[i] = 0;
        for (i = Math.max(n - this.t, 0); i < a.t; ++i)
          r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n);
        r.clamp();
        r.drShiftTo(1, r);
      }
      function Barrett(m) {
        this.r2 = nbi();
        this.q3 = nbi();
        BigInteger.ONE.dlShiftTo(2 * m.t, this.r2);
        this.mu = this.r2.divide(m);
        this.m = m;
      }
      function barrettConvert(x) {
        if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m);
        else if (x.compareTo(this.m) < 0) return x;
        else {
          var r = nbi();
          x.copyTo(r);
          this.reduce(r);
          return r;
        }
      }
      function barrettRevert(x) {
        return x;
      }
      function barrettReduce(x) {
        x.drShiftTo(this.m.t - 1, this.r2);
        if (x.t > this.m.t + 1) {
          x.t = this.m.t + 1;
          x.clamp();
        }
        this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3);
        this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2);
        while (x.compareTo(this.r2) < 0) x.dAddOffset(1, this.m.t + 1);
        x.subTo(this.r2, x);
        while (x.compareTo(this.m) >= 0) x.subTo(this.m, x);
      }
      function barrettSqrTo(x, r) {
        x.squareTo(r);
        this.reduce(r);
      }
      function barrettMulTo(x, y, r) {
        x.multiplyTo(y, r);
        this.reduce(r);
      }
      Barrett.prototype.convert = barrettConvert;
      Barrett.prototype.revert = barrettRevert;
      Barrett.prototype.reduce = barrettReduce;
      Barrett.prototype.mulTo = barrettMulTo;
      Barrett.prototype.sqrTo = barrettSqrTo;
      function bnModPow(e, m) {
        var i = e.bitLength(), k, r = nbv(1), z4;
        if (i <= 0) return r;
        else if (i < 18) k = 1;
        else if (i < 48) k = 3;
        else if (i < 144) k = 4;
        else if (i < 768) k = 5;
        else k = 6;
        if (i < 8)
          z4 = new Classic(m);
        else if (m.isEven())
          z4 = new Barrett(m);
        else
          z4 = new Montgomery(m);
        var g = new Array(), n = 3, k1 = k - 1, km = (1 << k) - 1;
        g[1] = z4.convert(this);
        if (k > 1) {
          var g2 = nbi();
          z4.sqrTo(g[1], g2);
          while (n <= km) {
            g[n] = nbi();
            z4.mulTo(g2, g[n - 2], g[n]);
            n += 2;
          }
        }
        var j = e.t - 1, w, is1 = true, r2 = nbi(), t2;
        i = nbits(e[j]) - 1;
        while (j >= 0) {
          if (i >= k1) w = e[j] >> i - k1 & km;
          else {
            w = (e[j] & (1 << i + 1) - 1) << k1 - i;
            if (j > 0) w |= e[j - 1] >> this.DB + i - k1;
          }
          n = k;
          while ((w & 1) == 0) {
            w >>= 1;
            --n;
          }
          if ((i -= n) < 0) {
            i += this.DB;
            --j;
          }
          if (is1) {
            g[w].copyTo(r);
            is1 = false;
          } else {
            while (n > 1) {
              z4.sqrTo(r, r2);
              z4.sqrTo(r2, r);
              n -= 2;
            }
            if (n > 0) z4.sqrTo(r, r2);
            else {
              t2 = r;
              r = r2;
              r2 = t2;
            }
            z4.mulTo(r2, g[w], r);
          }
          while (j >= 0 && (e[j] & 1 << i) == 0) {
            z4.sqrTo(r, r2);
            t2 = r;
            r = r2;
            r2 = t2;
            if (--i < 0) {
              i = this.DB - 1;
              --j;
            }
          }
        }
        return z4.revert(r);
      }
      function bnGCD(a) {
        var x = this.s < 0 ? this.negate() : this.clone();
        var y = a.s < 0 ? a.negate() : a.clone();
        if (x.compareTo(y) < 0) {
          var t2 = x;
          x = y;
          y = t2;
        }
        var i = x.getLowestSetBit(), g = y.getLowestSetBit();
        if (g < 0) return x;
        if (i < g) g = i;
        if (g > 0) {
          x.rShiftTo(g, x);
          y.rShiftTo(g, y);
        }
        while (x.signum() > 0) {
          if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x);
          if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y);
          if (x.compareTo(y) >= 0) {
            x.subTo(y, x);
            x.rShiftTo(1, x);
          } else {
            y.subTo(x, y);
            y.rShiftTo(1, y);
          }
        }
        if (g > 0) y.lShiftTo(g, y);
        return y;
      }
      function bnpModInt(n) {
        if (n <= 0) return 0;
        var d = this.DV % n, r = this.s < 0 ? n - 1 : 0;
        if (this.t > 0)
          if (d == 0) r = this[0] % n;
          else for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n;
        return r;
      }
      function bnModInverse(m) {
        var ac = m.isEven();
        if (this.isEven() && ac || m.signum() == 0) return BigInteger.ZERO;
        var u2 = m.clone(), v = this.clone();
        var a = nbv(1), b = nbv(0), c2 = nbv(0), d = nbv(1);
        while (u2.signum() != 0) {
          while (u2.isEven()) {
            u2.rShiftTo(1, u2);
            if (ac) {
              if (!a.isEven() || !b.isEven()) {
                a.addTo(this, a);
                b.subTo(m, b);
              }
              a.rShiftTo(1, a);
            } else if (!b.isEven()) b.subTo(m, b);
            b.rShiftTo(1, b);
          }
          while (v.isEven()) {
            v.rShiftTo(1, v);
            if (ac) {
              if (!c2.isEven() || !d.isEven()) {
                c2.addTo(this, c2);
                d.subTo(m, d);
              }
              c2.rShiftTo(1, c2);
            } else if (!d.isEven()) d.subTo(m, d);
            d.rShiftTo(1, d);
          }
          if (u2.compareTo(v) >= 0) {
            u2.subTo(v, u2);
            if (ac) a.subTo(c2, a);
            b.subTo(d, b);
          } else {
            v.subTo(u2, v);
            if (ac) c2.subTo(a, c2);
            d.subTo(b, d);
          }
        }
        if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO;
        if (d.compareTo(m) >= 0) return d.subtract(m);
        if (d.signum() < 0) d.addTo(m, d);
        else return d;
        if (d.signum() < 0) return d.add(m);
        else return d;
      }
      var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997];
      var lplim = (1 << 26) / lowprimes[lowprimes.length - 1];
      function bnIsProbablePrime(t2) {
        var i, x = this.abs();
        if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) {
          for (i = 0; i < lowprimes.length; ++i)
            if (x[0] == lowprimes[i]) return true;
          return false;
        }
        if (x.isEven()) return false;
        i = 1;
        while (i < lowprimes.length) {
          var m = lowprimes[i], j = i + 1;
          while (j < lowprimes.length && m < lplim) m *= lowprimes[j++];
          m = x.modInt(m);
          while (i < j) if (m % lowprimes[i++] == 0) return false;
        }
        return x.millerRabin(t2);
      }
      function bnpMillerRabin(t2) {
        var n1 = this.subtract(BigInteger.ONE);
        var k = n1.getLowestSetBit();
        if (k <= 0) return false;
        var r = n1.shiftRight(k);
        t2 = t2 + 1 >> 1;
        if (t2 > lowprimes.length) t2 = lowprimes.length;
        var a = nbi();
        for (var i = 0; i < t2; ++i) {
          a.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]);
          var y = a.modPow(r, this);
          if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {
            var j = 1;
            while (j++ < k && y.compareTo(n1) != 0) {
              y = y.modPowInt(2, this);
              if (y.compareTo(BigInteger.ONE) == 0) return false;
            }
            if (y.compareTo(n1) != 0) return false;
          }
        }
        return true;
      }
      BigInteger.prototype.chunkSize = bnpChunkSize;
      BigInteger.prototype.toRadix = bnpToRadix;
      BigInteger.prototype.fromRadix = bnpFromRadix;
      BigInteger.prototype.fromNumber = bnpFromNumber;
      BigInteger.prototype.bitwiseTo = bnpBitwiseTo;
      BigInteger.prototype.changeBit = bnpChangeBit;
      BigInteger.prototype.addTo = bnpAddTo;
      BigInteger.prototype.dMultiply = bnpDMultiply;
      BigInteger.prototype.dAddOffset = bnpDAddOffset;
      BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;
      BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
      BigInteger.prototype.modInt = bnpModInt;
      BigInteger.prototype.millerRabin = bnpMillerRabin;
      BigInteger.prototype.clone = bnClone;
      BigInteger.prototype.intValue = bnIntValue;
      BigInteger.prototype.byteValue = bnByteValue;
      BigInteger.prototype.shortValue = bnShortValue;
      BigInteger.prototype.signum = bnSigNum;
      BigInteger.prototype.toByteArray = bnToByteArray;
      BigInteger.prototype.equals = bnEquals;
      BigInteger.prototype.min = bnMin;
      BigInteger.prototype.max = bnMax;
      BigInteger.prototype.and = bnAnd;
      BigInteger.prototype.or = bnOr;
      BigInteger.prototype.xor = bnXor;
      BigInteger.prototype.andNot = bnAndNot;
      BigInteger.prototype.not = bnNot;
      BigInteger.prototype.shiftLeft = bnShiftLeft;
      BigInteger.prototype.shiftRight = bnShiftRight;
      BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;
      BigInteger.prototype.bitCount = bnBitCount;
      BigInteger.prototype.testBit = bnTestBit;
      BigInteger.prototype.setBit = bnSetBit;
      BigInteger.prototype.clearBit = bnClearBit;
      BigInteger.prototype.flipBit = bnFlipBit;
      BigInteger.prototype.add = bnAdd;
      BigInteger.prototype.subtract = bnSubtract;
      BigInteger.prototype.multiply = bnMultiply;
      BigInteger.prototype.divide = bnDivide;
      BigInteger.prototype.remainder = bnRemainder;
      BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;
      BigInteger.prototype.modPow = bnModPow;
      BigInteger.prototype.modInverse = bnModInverse;
      BigInteger.prototype.pow = bnPow;
      BigInteger.prototype.gcd = bnGCD;
      BigInteger.prototype.isProbablePrime = bnIsProbablePrime;
      BigInteger.prototype.square = bnSquare;
      BigInteger.prototype.Barrett = Barrett;
      var rng_state;
      var rng_pool;
      var rng_pptr;
      function rng_seed_int(x) {
        rng_pool[rng_pptr++] ^= x & 255;
        rng_pool[rng_pptr++] ^= x >> 8 & 255;
        rng_pool[rng_pptr++] ^= x >> 16 & 255;
        rng_pool[rng_pptr++] ^= x >> 24 & 255;
        if (rng_pptr >= rng_psize) rng_pptr -= rng_psize;
      }
      function rng_seed_time() {
        rng_seed_int((/* @__PURE__ */ new Date()).getTime());
      }
      if (rng_pool == null) {
        rng_pool = new Array();
        rng_pptr = 0;
        var t;
        if (typeof window !== "undefined" && window.crypto) {
          if (window.crypto.getRandomValues) {
            var ua = new Uint8Array(32);
            window.crypto.getRandomValues(ua);
            for (t = 0; t < 32; ++t)
              rng_pool[rng_pptr++] = ua[t];
          } else if (navigator.appName == "Netscape" && navigator.appVersion < "5") {
            var z3 = window.crypto.random(32);
            for (t = 0; t < z3.length; ++t)
              rng_pool[rng_pptr++] = z3.charCodeAt(t) & 255;
          }
        }
        while (rng_pptr < rng_psize) {
          t = Math.floor(65536 * Math.random());
          rng_pool[rng_pptr++] = t >>> 8;
          rng_pool[rng_pptr++] = t & 255;
        }
        rng_pptr = 0;
        rng_seed_time();
      }
      function rng_get_byte() {
        if (rng_state == null) {
          rng_seed_time();
          rng_state = prng_newstate();
          rng_state.init(rng_pool);
          for (rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr)
            rng_pool[rng_pptr] = 0;
          rng_pptr = 0;
        }
        return rng_state.next();
      }
      function rng_get_bytes(ba) {
        var i;
        for (i = 0; i < ba.length; ++i) ba[i] = rng_get_byte();
      }
      function SecureRandom() {
      }
      SecureRandom.prototype.nextBytes = rng_get_bytes;
      function Arcfour() {
        this.i = 0;
        this.j = 0;
        this.S = new Array();
      }
      function ARC4init(key) {
        var i, j, t2;
        for (i = 0; i < 256; ++i)
          this.S[i] = i;
        j = 0;
        for (i = 0; i < 256; ++i) {
          j = j + this.S[i] + key[i % key.length] & 255;
          t2 = this.S[i];
          this.S[i] = this.S[j];
          this.S[j] = t2;
        }
        this.i = 0;
        this.j = 0;
      }
      function ARC4next() {
        var t2;
        this.i = this.i + 1 & 255;
        this.j = this.j + this.S[this.i] & 255;
        t2 = this.S[this.i];
        this.S[this.i] = this.S[this.j];
        this.S[this.j] = t2;
        return this.S[t2 + this.S[this.i] & 255];
      }
      Arcfour.prototype.init = ARC4init;
      Arcfour.prototype.next = ARC4next;
      function prng_newstate() {
        return new Arcfour();
      }
      var rng_psize = 256;
      if (typeof exports2 !== "undefined") {
        exports2 = module2.exports = {
          default: BigInteger,
          BigInteger,
          SecureRandom
        };
      } else {
        this.jsbn = {
          BigInteger,
          SecureRandom
        };
      }
    }).call(exports2);
  }
});

// ../../node_modules/.pnpm/sprintf-js@1.1.3/node_modules/sprintf-js/src/sprintf.js
var require_sprintf = __commonJS({
  "../../node_modules/.pnpm/sprintf-js@1.1.3/node_modules/sprintf-js/src/sprintf.js"(exports2) {
    "use strict";
    !(function() {
      "use strict";
      var re = {
        not_string: /[^s]/,
        not_bool: /[^t]/,
        not_type: /[^T]/,
        not_primitive: /[^v]/,
        number: /[diefg]/,
        numeric_arg: /[bcdiefguxX]/,
        json: /[j]/,
        not_json: /[^j]/,
        text: /^[^\x25]+/,
        modulo: /^\x25{2}/,
        placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,
        key: /^([a-z_][a-z_\d]*)/i,
        key_access: /^\.([a-z_][a-z_\d]*)/i,
        index_access: /^\[(\d+)\]/,
        sign: /^[+-]/
      };
      function sprintf(key) {
        return sprintf_format(sprintf_parse(key), arguments);
      }
      function vsprintf(fmt, argv) {
        return sprintf.apply(null, [fmt].concat(argv || []));
      }
      function sprintf_format(parse_tree, argv) {
        var cursor = 1, tree_length = parse_tree.length, arg, output = "", i, k, ph, pad2, pad_character, pad_length, is_positive, sign;
        for (i = 0; i < tree_length; i++) {
          if (typeof parse_tree[i] === "string") {
            output += parse_tree[i];
          } else if (typeof parse_tree[i] === "object") {
            ph = parse_tree[i];
            if (ph.keys) {
              arg = argv[cursor];
              for (k = 0; k < ph.keys.length; k++) {
                if (arg == void 0) {
                  throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k - 1]));
                }
                arg = arg[ph.keys[k]];
              }
            } else if (ph.param_no) {
              arg = argv[ph.param_no];
            } else {
              arg = argv[cursor++];
            }
            if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {
              arg = arg();
            }
            if (re.numeric_arg.test(ph.type) && (typeof arg !== "number" && isNaN(arg))) {
              throw new TypeError(sprintf("[sprintf] expecting number but found %T", arg));
            }
            if (re.number.test(ph.type)) {
              is_positive = arg >= 0;
            }
            switch (ph.type) {
              case "b":
                arg = parseInt(arg, 10).toString(2);
                break;
              case "c":
                arg = String.fromCharCode(parseInt(arg, 10));
                break;
              case "d":
              case "i":
                arg = parseInt(arg, 10);
                break;
              case "j":
                arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0);
                break;
              case "e":
                arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential();
                break;
              case "f":
                arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg);
                break;
              case "g":
                arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg);
                break;
              case "o":
                arg = (parseInt(arg, 10) >>> 0).toString(8);
                break;
              case "s":
                arg = String(arg);
                arg = ph.precision ? arg.substring(0, ph.precision) : arg;
                break;
              case "t":
                arg = String(!!arg);
                arg = ph.precision ? arg.substring(0, ph.precision) : arg;
                break;
              case "T":
                arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase();
                arg = ph.precision ? arg.substring(0, ph.precision) : arg;
                break;
              case "u":
                arg = parseInt(arg, 10) >>> 0;
                break;
              case "v":
                arg = arg.valueOf();
                arg = ph.precision ? arg.substring(0, ph.precision) : arg;
                break;
              case "x":
                arg = (parseInt(arg, 10) >>> 0).toString(16);
                break;
              case "X":
                arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase();
                break;
            }
            if (re.json.test(ph.type)) {
              output += arg;
            } else {
              if (re.number.test(ph.type) && (!is_positive || ph.sign)) {
                sign = is_positive ? "+" : "-";
                arg = arg.toString().replace(re.sign, "");
              } else {
                sign = "";
              }
              pad_character = ph.pad_char ? ph.pad_char === "0" ? "0" : ph.pad_char.charAt(1) : " ";
              pad_length = ph.width - (sign + arg).length;
              pad2 = ph.width ? pad_length > 0 ? pad_character.repeat(pad_length) : "" : "";
              output += ph.align ? sign + arg + pad2 : pad_character === "0" ? sign + pad2 + arg : pad2 + sign + arg;
            }
          }
        }
        return output;
      }
      var sprintf_cache = /* @__PURE__ */ Object.create(null);
      function sprintf_parse(fmt) {
        if (sprintf_cache[fmt]) {
          return sprintf_cache[fmt];
        }
        var _fmt = fmt, match, parse_tree = [], arg_names = 0;
        while (_fmt) {
          if ((match = re.text.exec(_fmt)) !== null) {
            parse_tree.push(match[0]);
          } else if ((match = re.modulo.exec(_fmt)) !== null) {
            parse_tree.push("%");
          } else if ((match = re.placeholder.exec(_fmt)) !== null) {
            if (match[2]) {
              arg_names |= 1;
              var field_list = [], replacement_field = match[2], field_match = [];
              if ((field_match = re.key.exec(replacement_field)) !== null) {
                field_list.push(field_match[1]);
                while ((replacement_field = replacement_field.substring(field_match[0].length)) !== "") {
                  if ((field_match = re.key_access.exec(replacement_field)) !== null) {
                    field_list.push(field_match[1]);
                  } else if ((field_match = re.index_access.exec(replacement_field)) !== null) {
                    field_list.push(field_match[1]);
                  } else {
                    throw new SyntaxError("[sprintf] failed to parse named argument key");
                  }
                }
              } else {
                throw new SyntaxError("[sprintf] failed to parse named argument key");
              }
              match[2] = field_list;
            } else {
              arg_names |= 2;
            }
            if (arg_names === 3) {
              throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");
            }
            parse_tree.push(
              {
                placeholder: match[0],
                param_no: match[1],
                keys: match[2],
                sign: match[3],
                pad_char: match[4],
                align: match[5],
                width: match[6],
                precision: match[7],
                type: match[8]
              }
            );
          } else {
            throw new SyntaxError("[sprintf] unexpected placeholder");
          }
          _fmt = _fmt.substring(match[0].length);
        }
        return sprintf_cache[fmt] = parse_tree;
      }
      if (typeof exports2 !== "undefined") {
        exports2["sprintf"] = sprintf;
        exports2["vsprintf"] = vsprintf;
      }
      if (typeof window !== "undefined") {
        window["sprintf"] = sprintf;
        window["vsprintf"] = vsprintf;
        if (typeof define === "function" && define["amd"]) {
          define(function() {
            return {
              "sprintf": sprintf,
              "vsprintf": vsprintf
            };
          });
        }
      }
    })();
  }
});

// ../../node_modules/.pnpm/ip-address@9.0.5/node_modules/ip-address/dist/ipv4.js
var require_ipv4 = __commonJS({
  "../../node_modules/.pnpm/ip-address@9.0.5/node_modules/ip-address/dist/ipv4.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding2(result, mod, k);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Address4 = void 0;
    var common = __importStar2(require_common2());
    var constants3 = __importStar2(require_constants3());
    var address_error_1 = require_address_error();
    var jsbn_1 = require_jsbn();
    var sprintf_js_1 = require_sprintf();
    var Address4 = class _Address4 {
      constructor(address) {
        this.groups = constants3.GROUPS;
        this.parsedAddress = [];
        this.parsedSubnet = "";
        this.subnet = "/32";
        this.subnetMask = 32;
        this.v4 = true;
        this.isCorrect = common.isCorrect(constants3.BITS);
        this.isInSubnet = common.isInSubnet;
        this.address = address;
        const subnet = constants3.RE_SUBNET_STRING.exec(address);
        if (subnet) {
          this.parsedSubnet = subnet[0].replace("/", "");
          this.subnetMask = parseInt(this.parsedSubnet, 10);
          this.subnet = `/${this.subnetMask}`;
          if (this.subnetMask < 0 || this.subnetMask > constants3.BITS) {
            throw new address_error_1.AddressError("Invalid subnet mask.");
          }
          address = address.replace(constants3.RE_SUBNET_STRING, "");
        }
        this.addressMinusSuffix = address;
        this.parsedAddress = this.parse(address);
      }
      static isValid(address) {
        try {
          new _Address4(address);
          return true;
        } catch (e) {
          return false;
        }
      }
      /*
       * Parses a v4 address
       */
      parse(address) {
        const groups = address.split(".");
        if (!address.match(constants3.RE_ADDRESS)) {
          throw new address_error_1.AddressError("Invalid IPv4 address.");
        }
        return groups;
      }
      /**
       * Returns the correct form of an address
       * @memberof Address4
       * @instance
       * @returns {String}
       */
      correctForm() {
        return this.parsedAddress.map((part) => parseInt(part, 10)).join(".");
      }
      /**
       * Converts a hex string to an IPv4 address object
       * @memberof Address4
       * @static
       * @param {string} hex - a hex string to convert
       * @returns {Address4}
       */
      static fromHex(hex5) {
        const padded = hex5.replace(/:/g, "").padStart(8, "0");
        const groups = [];
        let i;
        for (i = 0; i < 8; i += 2) {
          const h = padded.slice(i, i + 2);
          groups.push(parseInt(h, 16));
        }
        return new _Address4(groups.join("."));
      }
      /**
       * Converts an integer into a IPv4 address object
       * @memberof Address4
       * @static
       * @param {integer} integer - a number to convert
       * @returns {Address4}
       */
      static fromInteger(integer3) {
        return _Address4.fromHex(integer3.toString(16));
      }
      /**
       * Return an address from in-addr.arpa form
       * @memberof Address4
       * @static
       * @param {string} arpaFormAddress - an 'in-addr.arpa' form ipv4 address
       * @returns {Adress4}
       * @example
       * var address = Address4.fromArpa(42.2.0.192.in-addr.arpa.)
       * address.correctForm(); // '192.0.2.42'
       */
      static fromArpa(arpaFormAddress) {
        const leader = arpaFormAddress.replace(/(\.in-addr\.arpa)?\.$/, "");
        const address = leader.split(".").reverse().join(".");
        return new _Address4(address);
      }
      /**
       * Converts an IPv4 address object to a hex string
       * @memberof Address4
       * @instance
       * @returns {String}
       */
      toHex() {
        return this.parsedAddress.map((part) => (0, sprintf_js_1.sprintf)("%02x", parseInt(part, 10))).join(":");
      }
      /**
       * Converts an IPv4 address object to an array of bytes
       * @memberof Address4
       * @instance
       * @returns {Array}
       */
      toArray() {
        return this.parsedAddress.map((part) => parseInt(part, 10));
      }
      /**
       * Converts an IPv4 address object to an IPv6 address group
       * @memberof Address4
       * @instance
       * @returns {String}
       */
      toGroup6() {
        const output = [];
        let i;
        for (i = 0; i < constants3.GROUPS; i += 2) {
          const hex5 = (0, sprintf_js_1.sprintf)("%02x%02x", parseInt(this.parsedAddress[i], 10), parseInt(this.parsedAddress[i + 1], 10));
          output.push((0, sprintf_js_1.sprintf)("%x", parseInt(hex5, 16)));
        }
        return output.join(":");
      }
      /**
       * Returns the address as a BigInteger
       * @memberof Address4
       * @instance
       * @returns {BigInteger}
       */
      bigInteger() {
        return new jsbn_1.BigInteger(this.parsedAddress.map((n) => (0, sprintf_js_1.sprintf)("%02x", parseInt(n, 10))).join(""), 16);
      }
      /**
       * Helper function getting start address.
       * @memberof Address4
       * @instance
       * @returns {BigInteger}
       */
      _startAddress() {
        return new jsbn_1.BigInteger(this.mask() + "0".repeat(constants3.BITS - this.subnetMask), 2);
      }
      /**
       * The first address in the range given by this address' subnet.
       * Often referred to as the Network Address.
       * @memberof Address4
       * @instance
       * @returns {Address4}
       */
      startAddress() {
        return _Address4.fromBigInteger(this._startAddress());
      }
      /**
       * The first host address in the range given by this address's subnet ie
       * the first address after the Network Address
       * @memberof Address4
       * @instance
       * @returns {Address4}
       */
      startAddressExclusive() {
        const adjust = new jsbn_1.BigInteger("1");
        return _Address4.fromBigInteger(this._startAddress().add(adjust));
      }
      /**
       * Helper function getting end address.
       * @memberof Address4
       * @instance
       * @returns {BigInteger}
       */
      _endAddress() {
        return new jsbn_1.BigInteger(this.mask() + "1".repeat(constants3.BITS - this.subnetMask), 2);
      }
      /**
       * The last address in the range given by this address' subnet
       * Often referred to as the Broadcast
       * @memberof Address4
       * @instance
       * @returns {Address4}
       */
      endAddress() {
        return _Address4.fromBigInteger(this._endAddress());
      }
      /**
       * The last host address in the range given by this address's subnet ie
       * the last address prior to the Broadcast Address
       * @memberof Address4
       * @instance
       * @returns {Address4}
       */
      endAddressExclusive() {
        const adjust = new jsbn_1.BigInteger("1");
        return _Address4.fromBigInteger(this._endAddress().subtract(adjust));
      }
      /**
       * Converts a BigInteger to a v4 address object
       * @memberof Address4
       * @static
       * @param {BigInteger} bigInteger - a BigInteger to convert
       * @returns {Address4}
       */
      static fromBigInteger(bigInteger) {
        return _Address4.fromInteger(parseInt(bigInteger.toString(), 10));
      }
      /**
       * Returns the first n bits of the address, defaulting to the
       * subnet mask
       * @memberof Address4
       * @instance
       * @returns {String}
       */
      mask(mask) {
        if (mask === void 0) {
          mask = this.subnetMask;
        }
        return this.getBitsBase2(0, mask);
      }
      /**
       * Returns the bits in the given range as a base-2 string
       * @memberof Address4
       * @instance
       * @returns {string}
       */
      getBitsBase2(start, end) {
        return this.binaryZeroPad().slice(start, end);
      }
      /**
       * Return the reversed ip6.arpa form of the address
       * @memberof Address4
       * @param {Object} options
       * @param {boolean} options.omitSuffix - omit the "in-addr.arpa" suffix
       * @instance
       * @returns {String}
       */
      reverseForm(options) {
        if (!options) {
          options = {};
        }
        const reversed = this.correctForm().split(".").reverse().join(".");
        if (options.omitSuffix) {
          return reversed;
        }
        return (0, sprintf_js_1.sprintf)("%s.in-addr.arpa.", reversed);
      }
      /**
       * Returns true if the given address is a multicast address
       * @memberof Address4
       * @instance
       * @returns {boolean}
       */
      isMulticast() {
        return this.isInSubnet(new _Address4("224.0.0.0/4"));
      }
      /**
       * Returns a zero-padded base-2 string representation of the address
       * @memberof Address4
       * @instance
       * @returns {string}
       */
      binaryZeroPad() {
        return this.bigInteger().toString(2).padStart(constants3.BITS, "0");
      }
      /**
       * Groups an IPv4 address for inclusion at the end of an IPv6 address
       * @returns {String}
       */
      groupForV6() {
        const segments = this.parsedAddress;
        return this.address.replace(constants3.RE_ADDRESS, (0, sprintf_js_1.sprintf)('<span class="hover-group group-v4 group-6">%s</span>.<span class="hover-group group-v4 group-7">%s</span>', segments.slice(0, 2).join("."), segments.slice(2, 4).join(".")));
      }
    };
    exports2.Address4 = Address4;
  }
});

// ../../node_modules/.pnpm/ip-address@9.0.5/node_modules/ip-address/dist/v6/constants.js
var require_constants4 = __commonJS({
  "../../node_modules/.pnpm/ip-address@9.0.5/node_modules/ip-address/dist/v6/constants.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.RE_URL_WITH_PORT = exports2.RE_URL = exports2.RE_ZONE_STRING = exports2.RE_SUBNET_STRING = exports2.RE_BAD_ADDRESS = exports2.RE_BAD_CHARACTERS = exports2.TYPES = exports2.SCOPES = exports2.GROUPS = exports2.BITS = void 0;
    exports2.BITS = 128;
    exports2.GROUPS = 8;
    exports2.SCOPES = {
      0: "Reserved",
      1: "Interface local",
      2: "Link local",
      4: "Admin local",
      5: "Site local",
      8: "Organization local",
      14: "Global",
      15: "Reserved"
    };
    exports2.TYPES = {
      "ff01::1/128": "Multicast (All nodes on this interface)",
      "ff01::2/128": "Multicast (All routers on this interface)",
      "ff02::1/128": "Multicast (All nodes on this link)",
      "ff02::2/128": "Multicast (All routers on this link)",
      "ff05::2/128": "Multicast (All routers in this site)",
      "ff02::5/128": "Multicast (OSPFv3 AllSPF routers)",
      "ff02::6/128": "Multicast (OSPFv3 AllDR routers)",
      "ff02::9/128": "Multicast (RIP routers)",
      "ff02::a/128": "Multicast (EIGRP routers)",
      "ff02::d/128": "Multicast (PIM routers)",
      "ff02::16/128": "Multicast (MLDv2 reports)",
      "ff01::fb/128": "Multicast (mDNSv6)",
      "ff02::fb/128": "Multicast (mDNSv6)",
      "ff05::fb/128": "Multicast (mDNSv6)",
      "ff02::1:2/128": "Multicast (All DHCP servers and relay agents on this link)",
      "ff05::1:2/128": "Multicast (All DHCP servers and relay agents in this site)",
      "ff02::1:3/128": "Multicast (All DHCP servers on this link)",
      "ff05::1:3/128": "Multicast (All DHCP servers in this site)",
      "::/128": "Unspecified",
      "::1/128": "Loopback",
      "ff00::/8": "Multicast",
      "fe80::/10": "Link-local unicast"
    };
    exports2.RE_BAD_CHARACTERS = /([^0-9a-f:/%])/gi;
    exports2.RE_BAD_ADDRESS = /([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi;
    exports2.RE_SUBNET_STRING = /\/\d{1,3}(?=%|$)/;
    exports2.RE_ZONE_STRING = /%.*$/;
    exports2.RE_URL = new RegExp(/^\[{0,1}([0-9a-f:]+)\]{0,1}/);
    exports2.RE_URL_WITH_PORT = new RegExp(/\[([0-9a-f:]+)\]:([0-9]{1,5})/);
  }
});

// ../../node_modules/.pnpm/ip-address@9.0.5/node_modules/ip-address/dist/v6/helpers.js
var require_helpers2 = __commonJS({
  "../../node_modules/.pnpm/ip-address@9.0.5/node_modules/ip-address/dist/v6/helpers.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.simpleGroup = exports2.spanLeadingZeroes = exports2.spanAll = exports2.spanAllZeroes = void 0;
    var sprintf_js_1 = require_sprintf();
    function spanAllZeroes(s) {
      return s.replace(/(0+)/g, '<span class="zero">$1</span>');
    }
    exports2.spanAllZeroes = spanAllZeroes;
    function spanAll(s, offset = 0) {
      const letters = s.split("");
      return letters.map(
        (n, i) => (0, sprintf_js_1.sprintf)('<span class="digit value-%s position-%d">%s</span>', n, i + offset, spanAllZeroes(n))
        // XXX Use #base-2 .value-0 instead?
      ).join("");
    }
    exports2.spanAll = spanAll;
    function spanLeadingZeroesSimple(group) {
      return group.replace(/^(0+)/, '<span class="zero">$1</span>');
    }
    function spanLeadingZeroes(address) {
      const groups = address.split(":");
      return groups.map((g) => spanLeadingZeroesSimple(g)).join(":");
    }
    exports2.spanLeadingZeroes = spanLeadingZeroes;
    function simpleGroup(addressString, offset = 0) {
      const groups = addressString.split(":");
      return groups.map((g, i) => {
        if (/group-v4/.test(g)) {
          return g;
        }
        return (0, sprintf_js_1.sprintf)('<span class="hover-group group-%d">%s</span>', i + offset, spanLeadingZeroesSimple(g));
      });
    }
    exports2.simpleGroup = simpleGroup;
  }
});

// ../../node_modules/.pnpm/ip-address@9.0.5/node_modules/ip-address/dist/v6/regular-expressions.js
var require_regular_expressions = __commonJS({
  "../../node_modules/.pnpm/ip-address@9.0.5/node_modules/ip-address/dist/v6/regular-expressions.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding2(result, mod, k);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.possibleElisions = exports2.simpleRegularExpression = exports2.ADDRESS_BOUNDARY = exports2.padGroup = exports2.groupPossibilities = void 0;
    var v6 = __importStar2(require_constants4());
    var sprintf_js_1 = require_sprintf();
    function groupPossibilities(possibilities) {
      return (0, sprintf_js_1.sprintf)("(%s)", possibilities.join("|"));
    }
    exports2.groupPossibilities = groupPossibilities;
    function padGroup(group) {
      if (group.length < 4) {
        return (0, sprintf_js_1.sprintf)("0{0,%d}%s", 4 - group.length, group);
      }
      return group;
    }
    exports2.padGroup = padGroup;
    exports2.ADDRESS_BOUNDARY = "[^A-Fa-f0-9:]";
    function simpleRegularExpression(groups) {
      const zeroIndexes = [];
      groups.forEach((group, i) => {
        const groupInteger = parseInt(group, 16);
        if (groupInteger === 0) {
          zeroIndexes.push(i);
        }
      });
      const possibilities = zeroIndexes.map((zeroIndex) => groups.map((group, i) => {
        if (i === zeroIndex) {
          const elision = i === 0 || i === v6.GROUPS - 1 ? ":" : "";
          return groupPossibilities([padGroup(group), elision]);
        }
        return padGroup(group);
      }).join(":"));
      possibilities.push(groups.map(padGroup).join(":"));
      return groupPossibilities(possibilities);
    }
    exports2.simpleRegularExpression = simpleRegularExpression;
    function possibleElisions(elidedGroups, moreLeft, moreRight) {
      const left = moreLeft ? "" : ":";
      const right = moreRight ? "" : ":";
      const possibilities = [];
      if (!moreLeft && !moreRight) {
        possibilities.push("::");
      }
      if (moreLeft && moreRight) {
        possibilities.push("");
      }
      if (moreRight && !moreLeft || !moreRight && moreLeft) {
        possibilities.push(":");
      }
      possibilities.push((0, sprintf_js_1.sprintf)("%s(:0{1,4}){1,%d}", left, elidedGroups - 1));
      possibilities.push((0, sprintf_js_1.sprintf)("(0{1,4}:){1,%d}%s", elidedGroups - 1, right));
      possibilities.push((0, sprintf_js_1.sprintf)("(0{1,4}:){%d}0{1,4}", elidedGroups - 1));
      for (let groups = 1; groups < elidedGroups - 1; groups++) {
        for (let position = 1; position < elidedGroups - groups; position++) {
          possibilities.push((0, sprintf_js_1.sprintf)("(0{1,4}:){%d}:(0{1,4}:){%d}0{1,4}", position, elidedGroups - position - groups - 1));
        }
      }
      return groupPossibilities(possibilities);
    }
    exports2.possibleElisions = possibleElisions;
  }
});

// ../../node_modules/.pnpm/ip-address@9.0.5/node_modules/ip-address/dist/ipv6.js
var require_ipv6 = __commonJS({
  "../../node_modules/.pnpm/ip-address@9.0.5/node_modules/ip-address/dist/ipv6.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding2(result, mod, k);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Address6 = void 0;
    var common = __importStar2(require_common2());
    var constants4 = __importStar2(require_constants3());
    var constants6 = __importStar2(require_constants4());
    var helpers = __importStar2(require_helpers2());
    var ipv4_1 = require_ipv4();
    var regular_expressions_1 = require_regular_expressions();
    var address_error_1 = require_address_error();
    var jsbn_1 = require_jsbn();
    var sprintf_js_1 = require_sprintf();
    function assert24(condition) {
      if (!condition) {
        throw new Error("Assertion failed.");
      }
    }
    function addCommas(number7) {
      const r = /(\d+)(\d{3})/;
      while (r.test(number7)) {
        number7 = number7.replace(r, "$1,$2");
      }
      return number7;
    }
    function spanLeadingZeroes4(n) {
      n = n.replace(/^(0{1,})([1-9]+)$/, '<span class="parse-error">$1</span>$2');
      n = n.replace(/^(0{1,})(0)$/, '<span class="parse-error">$1</span>$2');
      return n;
    }
    function compact(address, slice) {
      const s1 = [];
      const s2 = [];
      let i;
      for (i = 0; i < address.length; i++) {
        if (i < slice[0]) {
          s1.push(address[i]);
        } else if (i > slice[1]) {
          s2.push(address[i]);
        }
      }
      return s1.concat(["compact"]).concat(s2);
    }
    function paddedHex(octet) {
      return (0, sprintf_js_1.sprintf)("%04x", parseInt(octet, 16));
    }
    function unsignByte(b) {
      return b & 255;
    }
    var Address6 = class _Address6 {
      constructor(address, optionalGroups) {
        this.addressMinusSuffix = "";
        this.parsedSubnet = "";
        this.subnet = "/128";
        this.subnetMask = 128;
        this.v4 = false;
        this.zone = "";
        this.isInSubnet = common.isInSubnet;
        this.isCorrect = common.isCorrect(constants6.BITS);
        if (optionalGroups === void 0) {
          this.groups = constants6.GROUPS;
        } else {
          this.groups = optionalGroups;
        }
        this.address = address;
        const subnet = constants6.RE_SUBNET_STRING.exec(address);
        if (subnet) {
          this.parsedSubnet = subnet[0].replace("/", "");
          this.subnetMask = parseInt(this.parsedSubnet, 10);
          this.subnet = `/${this.subnetMask}`;
          if (Number.isNaN(this.subnetMask) || this.subnetMask < 0 || this.subnetMask > constants6.BITS) {
            throw new address_error_1.AddressError("Invalid subnet mask.");
          }
          address = address.replace(constants6.RE_SUBNET_STRING, "");
        } else if (/\//.test(address)) {
          throw new address_error_1.AddressError("Invalid subnet mask.");
        }
        const zone = constants6.RE_ZONE_STRING.exec(address);
        if (zone) {
          this.zone = zone[0];
          address = address.replace(constants6.RE_ZONE_STRING, "");
        }
        this.addressMinusSuffix = address;
        this.parsedAddress = this.parse(this.addressMinusSuffix);
      }
      static isValid(address) {
        try {
          new _Address6(address);
          return true;
        } catch (e) {
          return false;
        }
      }
      /**
       * Convert a BigInteger to a v6 address object
       * @memberof Address6
       * @static
       * @param {BigInteger} bigInteger - a BigInteger to convert
       * @returns {Address6}
       * @example
       * var bigInteger = new BigInteger('1000000000000');
       * var address = Address6.fromBigInteger(bigInteger);
       * address.correctForm(); // '::e8:d4a5:1000'
       */
      static fromBigInteger(bigInteger) {
        const hex5 = bigInteger.toString(16).padStart(32, "0");
        const groups = [];
        let i;
        for (i = 0; i < constants6.GROUPS; i++) {
          groups.push(hex5.slice(i * 4, (i + 1) * 4));
        }
        return new _Address6(groups.join(":"));
      }
      /**
       * Convert a URL (with optional port number) to an address object
       * @memberof Address6
       * @static
       * @param {string} url - a URL with optional port number
       * @example
       * var addressAndPort = Address6.fromURL('http://[ffff::]:8080/foo/');
       * addressAndPort.address.correctForm(); // 'ffff::'
       * addressAndPort.port; // 8080
       */
      static fromURL(url46) {
        let host;
        let port = null;
        let result;
        if (url46.indexOf("[") !== -1 && url46.indexOf("]:") !== -1) {
          result = constants6.RE_URL_WITH_PORT.exec(url46);
          if (result === null) {
            return {
              error: "failed to parse address with port",
              address: null,
              port: null
            };
          }
          host = result[1];
          port = result[2];
        } else if (url46.indexOf("/") !== -1) {
          url46 = url46.replace(/^[a-z0-9]+:\/\//, "");
          result = constants6.RE_URL.exec(url46);
          if (result === null) {
            return {
              error: "failed to parse address from URL",
              address: null,
              port: null
            };
          }
          host = result[1];
        } else {
          host = url46;
        }
        if (port) {
          port = parseInt(port, 10);
          if (port < 0 || port > 65536) {
            port = null;
          }
        } else {
          port = null;
        }
        return {
          address: new _Address6(host),
          port
        };
      }
      /**
       * Create an IPv6-mapped address given an IPv4 address
       * @memberof Address6
       * @static
       * @param {string} address - An IPv4 address string
       * @returns {Address6}
       * @example
       * var address = Address6.fromAddress4('192.168.0.1');
       * address.correctForm(); // '::ffff:c0a8:1'
       * address.to4in6(); // '::ffff:192.168.0.1'
       */
      static fromAddress4(address) {
        const address4 = new ipv4_1.Address4(address);
        const mask6 = constants6.BITS - (constants4.BITS - address4.subnetMask);
        return new _Address6(`::ffff:${address4.correctForm()}/${mask6}`);
      }
      /**
       * Return an address from ip6.arpa form
       * @memberof Address6
       * @static
       * @param {string} arpaFormAddress - an 'ip6.arpa' form address
       * @returns {Adress6}
       * @example
       * var address = Address6.fromArpa(e.f.f.f.3.c.2.6.f.f.f.e.6.6.8.e.1.0.6.7.9.4.e.c.0.0.0.0.1.0.0.2.ip6.arpa.)
       * address.correctForm(); // '2001:0:ce49:7601:e866:efff:62c3:fffe'
       */
      static fromArpa(arpaFormAddress) {
        let address = arpaFormAddress.replace(/(\.ip6\.arpa)?\.$/, "");
        const semicolonAmount = 7;
        if (address.length !== 63) {
          throw new address_error_1.AddressError("Invalid 'ip6.arpa' form.");
        }
        const parts = address.split(".").reverse();
        for (let i = semicolonAmount; i > 0; i--) {
          const insertIndex = i * 4;
          parts.splice(insertIndex, 0, ":");
        }
        address = parts.join("");
        return new _Address6(address);
      }
      /**
       * Return the Microsoft UNC transcription of the address
       * @memberof Address6
       * @instance
       * @returns {String} the Microsoft UNC transcription of the address
       */
      microsoftTranscription() {
        return (0, sprintf_js_1.sprintf)("%s.ipv6-literal.net", this.correctForm().replace(/:/g, "-"));
      }
      /**
       * Return the first n bits of the address, defaulting to the subnet mask
       * @memberof Address6
       * @instance
       * @param {number} [mask=subnet] - the number of bits to mask
       * @returns {String} the first n bits of the address as a string
       */
      mask(mask = this.subnetMask) {
        return this.getBitsBase2(0, mask);
      }
      /**
       * Return the number of possible subnets of a given size in the address
       * @memberof Address6
       * @instance
       * @param {number} [size=128] - the subnet size
       * @returns {String}
       */
      // TODO: probably useful to have a numeric version of this too
      possibleSubnets(subnetSize = 128) {
        const availableBits = constants6.BITS - this.subnetMask;
        const subnetBits = Math.abs(subnetSize - constants6.BITS);
        const subnetPowers = availableBits - subnetBits;
        if (subnetPowers < 0) {
          return "0";
        }
        return addCommas(new jsbn_1.BigInteger("2", 10).pow(subnetPowers).toString(10));
      }
      /**
       * Helper function getting start address.
       * @memberof Address6
       * @instance
       * @returns {BigInteger}
       */
      _startAddress() {
        return new jsbn_1.BigInteger(this.mask() + "0".repeat(constants6.BITS - this.subnetMask), 2);
      }
      /**
       * The first address in the range given by this address' subnet
       * Often referred to as the Network Address.
       * @memberof Address6
       * @instance
       * @returns {Address6}
       */
      startAddress() {
        return _Address6.fromBigInteger(this._startAddress());
      }
      /**
       * The first host address in the range given by this address's subnet ie
       * the first address after the Network Address
       * @memberof Address6
       * @instance
       * @returns {Address6}
       */
      startAddressExclusive() {
        const adjust = new jsbn_1.BigInteger("1");
        return _Address6.fromBigInteger(this._startAddress().add(adjust));
      }
      /**
       * Helper function getting end address.
       * @memberof Address6
       * @instance
       * @returns {BigInteger}
       */
      _endAddress() {
        return new jsbn_1.BigInteger(this.mask() + "1".repeat(constants6.BITS - this.subnetMask), 2);
      }
      /**
       * The last address in the range given by this address' subnet
       * Often referred to as the Broadcast
       * @memberof Address6
       * @instance
       * @returns {Address6}
       */
      endAddress() {
        return _Address6.fromBigInteger(this._endAddress());
      }
      /**
       * The last host address in the range given by this address's subnet ie
       * the last address prior to the Broadcast Address
       * @memberof Address6
       * @instance
       * @returns {Address6}
       */
      endAddressExclusive() {
        const adjust = new jsbn_1.BigInteger("1");
        return _Address6.fromBigInteger(this._endAddress().subtract(adjust));
      }
      /**
       * Return the scope of the address
       * @memberof Address6
       * @instance
       * @returns {String}
       */
      getScope() {
        let scope = constants6.SCOPES[this.getBits(12, 16).intValue()];
        if (this.getType() === "Global unicast" && scope !== "Link local") {
          scope = "Global";
        }
        return scope || "Unknown";
      }
      /**
       * Return the type of the address
       * @memberof Address6
       * @instance
       * @returns {String}
       */
      getType() {
        for (const subnet of Object.keys(constants6.TYPES)) {
          if (this.isInSubnet(new _Address6(subnet))) {
            return constants6.TYPES[subnet];
          }
        }
        return "Global unicast";
      }
      /**
       * Return the bits in the given range as a BigInteger
       * @memberof Address6
       * @instance
       * @returns {BigInteger}
       */
      getBits(start, end) {
        return new jsbn_1.BigInteger(this.getBitsBase2(start, end), 2);
      }
      /**
       * Return the bits in the given range as a base-2 string
       * @memberof Address6
       * @instance
       * @returns {String}
       */
      getBitsBase2(start, end) {
        return this.binaryZeroPad().slice(start, end);
      }
      /**
       * Return the bits in the given range as a base-16 string
       * @memberof Address6
       * @instance
       * @returns {String}
       */
      getBitsBase16(start, end) {
        const length = end - start;
        if (length % 4 !== 0) {
          throw new Error("Length of bits to retrieve must be divisible by four");
        }
        return this.getBits(start, end).toString(16).padStart(length / 4, "0");
      }
      /**
       * Return the bits that are set past the subnet mask length
       * @memberof Address6
       * @instance
       * @returns {String}
       */
      getBitsPastSubnet() {
        return this.getBitsBase2(this.subnetMask, constants6.BITS);
      }
      /**
       * Return the reversed ip6.arpa form of the address
       * @memberof Address6
       * @param {Object} options
       * @param {boolean} options.omitSuffix - omit the "ip6.arpa" suffix
       * @instance
       * @returns {String}
       */
      reverseForm(options) {
        if (!options) {
          options = {};
        }
        const characters = Math.floor(this.subnetMask / 4);
        const reversed = this.canonicalForm().replace(/:/g, "").split("").slice(0, characters).reverse().join(".");
        if (characters > 0) {
          if (options.omitSuffix) {
            return reversed;
          }
          return (0, sprintf_js_1.sprintf)("%s.ip6.arpa.", reversed);
        }
        if (options.omitSuffix) {
          return "";
        }
        return "ip6.arpa.";
      }
      /**
       * Return the correct form of the address
       * @memberof Address6
       * @instance
       * @returns {String}
       */
      correctForm() {
        let i;
        let groups = [];
        let zeroCounter = 0;
        const zeroes = [];
        for (i = 0; i < this.parsedAddress.length; i++) {
          const value = parseInt(this.parsedAddress[i], 16);
          if (value === 0) {
            zeroCounter++;
          }
          if (value !== 0 && zeroCounter > 0) {
            if (zeroCounter > 1) {
              zeroes.push([i - zeroCounter, i - 1]);
            }
            zeroCounter = 0;
          }
        }
        if (zeroCounter > 1) {
          zeroes.push([this.parsedAddress.length - zeroCounter, this.parsedAddress.length - 1]);
        }
        const zeroLengths = zeroes.map((n) => n[1] - n[0] + 1);
        if (zeroes.length > 0) {
          const index = zeroLengths.indexOf(Math.max(...zeroLengths));
          groups = compact(this.parsedAddress, zeroes[index]);
        } else {
          groups = this.parsedAddress;
        }
        for (i = 0; i < groups.length; i++) {
          if (groups[i] !== "compact") {
            groups[i] = parseInt(groups[i], 16).toString(16);
          }
        }
        let correct = groups.join(":");
        correct = correct.replace(/^compact$/, "::");
        correct = correct.replace(/^compact|compact$/, ":");
        correct = correct.replace(/compact/, "");
        return correct;
      }
      /**
       * Return a zero-padded base-2 string representation of the address
       * @memberof Address6
       * @instance
       * @returns {String}
       * @example
       * var address = new Address6('2001:4860:4001:803::1011');
       * address.binaryZeroPad();
       * // '0010000000000001010010000110000001000000000000010000100000000011
       * //  0000000000000000000000000000000000000000000000000001000000010001'
       */
      binaryZeroPad() {
        return this.bigInteger().toString(2).padStart(constants6.BITS, "0");
      }
      // TODO: Improve the semantics of this helper function
      parse4in6(address) {
        const groups = address.split(":");
        const lastGroup = groups.slice(-1)[0];
        const address4 = lastGroup.match(constants4.RE_ADDRESS);
        if (address4) {
          this.parsedAddress4 = address4[0];
          this.address4 = new ipv4_1.Address4(this.parsedAddress4);
          for (let i = 0; i < this.address4.groups; i++) {
            if (/^0[0-9]+/.test(this.address4.parsedAddress[i])) {
              throw new address_error_1.AddressError("IPv4 addresses can't have leading zeroes.", address.replace(constants4.RE_ADDRESS, this.address4.parsedAddress.map(spanLeadingZeroes4).join(".")));
            }
          }
          this.v4 = true;
          groups[groups.length - 1] = this.address4.toGroup6();
          address = groups.join(":");
        }
        return address;
      }
      // TODO: Make private?
      parse(address) {
        address = this.parse4in6(address);
        const badCharacters = address.match(constants6.RE_BAD_CHARACTERS);
        if (badCharacters) {
          throw new address_error_1.AddressError((0, sprintf_js_1.sprintf)("Bad character%s detected in address: %s", badCharacters.length > 1 ? "s" : "", badCharacters.join("")), address.replace(constants6.RE_BAD_CHARACTERS, '<span class="parse-error">$1</span>'));
        }
        const badAddress = address.match(constants6.RE_BAD_ADDRESS);
        if (badAddress) {
          throw new address_error_1.AddressError((0, sprintf_js_1.sprintf)("Address failed regex: %s", badAddress.join("")), address.replace(constants6.RE_BAD_ADDRESS, '<span class="parse-error">$1</span>'));
        }
        let groups = [];
        const halves = address.split("::");
        if (halves.length === 2) {
          let first = halves[0].split(":");
          let last = halves[1].split(":");
          if (first.length === 1 && first[0] === "") {
            first = [];
          }
          if (last.length === 1 && last[0] === "") {
            last = [];
          }
          const remaining = this.groups - (first.length + last.length);
          if (!remaining) {
            throw new address_error_1.AddressError("Error parsing groups");
          }
          this.elidedGroups = remaining;
          this.elisionBegin = first.length;
          this.elisionEnd = first.length + this.elidedGroups;
          groups = groups.concat(first);
          for (let i = 0; i < remaining; i++) {
            groups.push("0");
          }
          groups = groups.concat(last);
        } else if (halves.length === 1) {
          groups = address.split(":");
          this.elidedGroups = 0;
        } else {
          throw new address_error_1.AddressError("Too many :: groups found");
        }
        groups = groups.map((group) => (0, sprintf_js_1.sprintf)("%x", parseInt(group, 16)));
        if (groups.length !== this.groups) {
          throw new address_error_1.AddressError("Incorrect number of groups found");
        }
        return groups;
      }
      /**
       * Return the canonical form of the address
       * @memberof Address6
       * @instance
       * @returns {String}
       */
      canonicalForm() {
        return this.parsedAddress.map(paddedHex).join(":");
      }
      /**
       * Return the decimal form of the address
       * @memberof Address6
       * @instance
       * @returns {String}
       */
      decimal() {
        return this.parsedAddress.map((n) => (0, sprintf_js_1.sprintf)("%05d", parseInt(n, 16))).join(":");
      }
      /**
       * Return the address as a BigInteger
       * @memberof Address6
       * @instance
       * @returns {BigInteger}
       */
      bigInteger() {
        return new jsbn_1.BigInteger(this.parsedAddress.map(paddedHex).join(""), 16);
      }
      /**
       * Return the last two groups of this address as an IPv4 address string
       * @memberof Address6
       * @instance
       * @returns {Address4}
       * @example
       * var address = new Address6('2001:4860:4001::1825:bf11');
       * address.to4().correctForm(); // '24.37.191.17'
       */
      to4() {
        const binary = this.binaryZeroPad().split("");
        return ipv4_1.Address4.fromHex(new jsbn_1.BigInteger(binary.slice(96, 128).join(""), 2).toString(16));
      }
      /**
       * Return the v4-in-v6 form of the address
       * @memberof Address6
       * @instance
       * @returns {String}
       */
      to4in6() {
        const address4 = this.to4();
        const address6 = new _Address6(this.parsedAddress.slice(0, 6).join(":"), 6);
        const correct = address6.correctForm();
        let infix = "";
        if (!/:$/.test(correct)) {
          infix = ":";
        }
        return correct + infix + address4.address;
      }
      /**
       * Return an object containing the Teredo properties of the address
       * @memberof Address6
       * @instance
       * @returns {Object}
       */
      inspectTeredo() {
        const prefix = this.getBitsBase16(0, 32);
        const udpPort = this.getBits(80, 96).xor(new jsbn_1.BigInteger("ffff", 16)).toString();
        const server4 = ipv4_1.Address4.fromHex(this.getBitsBase16(32, 64));
        const client4 = ipv4_1.Address4.fromHex(this.getBits(96, 128).xor(new jsbn_1.BigInteger("ffffffff", 16)).toString(16));
        const flags = this.getBits(64, 80);
        const flagsBase2 = this.getBitsBase2(64, 80);
        const coneNat = flags.testBit(15);
        const reserved = flags.testBit(14);
        const groupIndividual = flags.testBit(8);
        const universalLocal = flags.testBit(9);
        const nonce = new jsbn_1.BigInteger(flagsBase2.slice(2, 6) + flagsBase2.slice(8, 16), 2).toString(10);
        return {
          prefix: (0, sprintf_js_1.sprintf)("%s:%s", prefix.slice(0, 4), prefix.slice(4, 8)),
          server4: server4.address,
          client4: client4.address,
          flags: flagsBase2,
          coneNat,
          microsoft: {
            reserved,
            universalLocal,
            groupIndividual,
            nonce
          },
          udpPort
        };
      }
      /**
       * Return an object containing the 6to4 properties of the address
       * @memberof Address6
       * @instance
       * @returns {Object}
       */
      inspect6to4() {
        const prefix = this.getBitsBase16(0, 16);
        const gateway = ipv4_1.Address4.fromHex(this.getBitsBase16(16, 48));
        return {
          prefix: (0, sprintf_js_1.sprintf)("%s", prefix.slice(0, 4)),
          gateway: gateway.address
        };
      }
      /**
       * Return a v6 6to4 address from a v6 v4inv6 address
       * @memberof Address6
       * @instance
       * @returns {Address6}
       */
      to6to4() {
        if (!this.is4()) {
          return null;
        }
        const addr6to4 = [
          "2002",
          this.getBitsBase16(96, 112),
          this.getBitsBase16(112, 128),
          "",
          "/16"
        ].join(":");
        return new _Address6(addr6to4);
      }
      /**
       * Return a byte array
       * @memberof Address6
       * @instance
       * @returns {Array}
       */
      toByteArray() {
        const byteArray = this.bigInteger().toByteArray();
        if (byteArray.length === 17 && byteArray[0] === 0) {
          return byteArray.slice(1);
        }
        return byteArray;
      }
      /**
       * Return an unsigned byte array
       * @memberof Address6
       * @instance
       * @returns {Array}
       */
      toUnsignedByteArray() {
        return this.toByteArray().map(unsignByte);
      }
      /**
       * Convert a byte array to an Address6 object
       * @memberof Address6
       * @static
       * @returns {Address6}
       */
      static fromByteArray(bytes) {
        return this.fromUnsignedByteArray(bytes.map(unsignByte));
      }
      /**
       * Convert an unsigned byte array to an Address6 object
       * @memberof Address6
       * @static
       * @returns {Address6}
       */
      static fromUnsignedByteArray(bytes) {
        const BYTE_MAX = new jsbn_1.BigInteger("256", 10);
        let result = new jsbn_1.BigInteger("0", 10);
        let multiplier = new jsbn_1.BigInteger("1", 10);
        for (let i = bytes.length - 1; i >= 0; i--) {
          result = result.add(multiplier.multiply(new jsbn_1.BigInteger(bytes[i].toString(10), 10)));
          multiplier = multiplier.multiply(BYTE_MAX);
        }
        return _Address6.fromBigInteger(result);
      }
      /**
       * Returns true if the address is in the canonical form, false otherwise
       * @memberof Address6
       * @instance
       * @returns {boolean}
       */
      isCanonical() {
        return this.addressMinusSuffix === this.canonicalForm();
      }
      /**
       * Returns true if the address is a link local address, false otherwise
       * @memberof Address6
       * @instance
       * @returns {boolean}
       */
      isLinkLocal() {
        if (this.getBitsBase2(0, 64) === "1111111010000000000000000000000000000000000000000000000000000000") {
          return true;
        }
        return false;
      }
      /**
       * Returns true if the address is a multicast address, false otherwise
       * @memberof Address6
       * @instance
       * @returns {boolean}
       */
      isMulticast() {
        return this.getType() === "Multicast";
      }
      /**
       * Returns true if the address is a v4-in-v6 address, false otherwise
       * @memberof Address6
       * @instance
       * @returns {boolean}
       */
      is4() {
        return this.v4;
      }
      /**
       * Returns true if the address is a Teredo address, false otherwise
       * @memberof Address6
       * @instance
       * @returns {boolean}
       */
      isTeredo() {
        return this.isInSubnet(new _Address6("2001::/32"));
      }
      /**
       * Returns true if the address is a 6to4 address, false otherwise
       * @memberof Address6
       * @instance
       * @returns {boolean}
       */
      is6to4() {
        return this.isInSubnet(new _Address6("2002::/16"));
      }
      /**
       * Returns true if the address is a loopback address, false otherwise
       * @memberof Address6
       * @instance
       * @returns {boolean}
       */
      isLoopback() {
        return this.getType() === "Loopback";
      }
      // #endregion
      // #region HTML
      /**
       * @returns {String} the address in link form with a default port of 80
       */
      href(optionalPort) {
        if (optionalPort === void 0) {
          optionalPort = "";
        } else {
          optionalPort = (0, sprintf_js_1.sprintf)(":%s", optionalPort);
        }
        return (0, sprintf_js_1.sprintf)("http://[%s]%s/", this.correctForm(), optionalPort);
      }
      /**
       * @returns {String} a link suitable for conveying the address via a URL hash
       */
      link(options) {
        if (!options) {
          options = {};
        }
        if (options.className === void 0) {
          options.className = "";
        }
        if (options.prefix === void 0) {
          options.prefix = "/#address=";
        }
        if (options.v4 === void 0) {
          options.v4 = false;
        }
        let formFunction = this.correctForm;
        if (options.v4) {
          formFunction = this.to4in6;
        }
        if (options.className) {
          return (0, sprintf_js_1.sprintf)('<a href="%1$s%2$s" class="%3$s">%2$s</a>', options.prefix, formFunction.call(this), options.className);
        }
        return (0, sprintf_js_1.sprintf)('<a href="%1$s%2$s">%2$s</a>', options.prefix, formFunction.call(this));
      }
      /**
       * Groups an address
       * @returns {String}
       */
      group() {
        if (this.elidedGroups === 0) {
          return helpers.simpleGroup(this.address).join(":");
        }
        assert24(typeof this.elidedGroups === "number");
        assert24(typeof this.elisionBegin === "number");
        const output = [];
        const [left, right] = this.address.split("::");
        if (left.length) {
          output.push(...helpers.simpleGroup(left));
        } else {
          output.push("");
        }
        const classes = ["hover-group"];
        for (let i = this.elisionBegin; i < this.elisionBegin + this.elidedGroups; i++) {
          classes.push((0, sprintf_js_1.sprintf)("group-%d", i));
        }
        output.push((0, sprintf_js_1.sprintf)('<span class="%s"></span>', classes.join(" ")));
        if (right.length) {
          output.push(...helpers.simpleGroup(right, this.elisionEnd));
        } else {
          output.push("");
        }
        if (this.is4()) {
          assert24(this.address4 instanceof ipv4_1.Address4);
          output.pop();
          output.push(this.address4.groupForV6());
        }
        return output.join(":");
      }
      // #endregion
      // #region Regular expressions
      /**
       * Generate a regular expression string that can be used to find or validate
       * all variations of this address
       * @memberof Address6
       * @instance
       * @param {boolean} substringSearch
       * @returns {string}
       */
      regularExpressionString(substringSearch = false) {
        let output = [];
        const address6 = new _Address6(this.correctForm());
        if (address6.elidedGroups === 0) {
          output.push((0, regular_expressions_1.simpleRegularExpression)(address6.parsedAddress));
        } else if (address6.elidedGroups === constants6.GROUPS) {
          output.push((0, regular_expressions_1.possibleElisions)(constants6.GROUPS));
        } else {
          const halves = address6.address.split("::");
          if (halves[0].length) {
            output.push((0, regular_expressions_1.simpleRegularExpression)(halves[0].split(":")));
          }
          assert24(typeof address6.elidedGroups === "number");
          output.push((0, regular_expressions_1.possibleElisions)(address6.elidedGroups, halves[0].length !== 0, halves[1].length !== 0));
          if (halves[1].length) {
            output.push((0, regular_expressions_1.simpleRegularExpression)(halves[1].split(":")));
          }
          output = [output.join(":")];
        }
        if (!substringSearch) {
          output = [
            "(?=^|",
            regular_expressions_1.ADDRESS_BOUNDARY,
            "|[^\\w\\:])(",
            ...output,
            ")(?=[^\\w\\:]|",
            regular_expressions_1.ADDRESS_BOUNDARY,
            "|$)"
          ];
        }
        return output.join("");
      }
      /**
       * Generate a regular expression that can be used to find or validate all
       * variations of this address.
       * @memberof Address6
       * @instance
       * @param {boolean} substringSearch
       * @returns {RegExp}
       */
      regularExpression(substringSearch = false) {
        return new RegExp(this.regularExpressionString(substringSearch), "i");
      }
    };
    exports2.Address6 = Address6;
  }
});

// ../../node_modules/.pnpm/ip-address@9.0.5/node_modules/ip-address/dist/ip-address.js
var require_ip_address = __commonJS({
  "../../node_modules/.pnpm/ip-address@9.0.5/node_modules/ip-address/dist/ip-address.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding2(result, mod, k);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.v6 = exports2.AddressError = exports2.Address6 = exports2.Address4 = void 0;
    var ipv4_1 = require_ipv4();
    Object.defineProperty(exports2, "Address4", { enumerable: true, get: function() {
      return ipv4_1.Address4;
    } });
    var ipv6_1 = require_ipv6();
    Object.defineProperty(exports2, "Address6", { enumerable: true, get: function() {
      return ipv6_1.Address6;
    } });
    var address_error_1 = require_address_error();
    Object.defineProperty(exports2, "AddressError", { enumerable: true, get: function() {
      return address_error_1.AddressError;
    } });
    var helpers = __importStar2(require_helpers2());
    exports2.v6 = { helpers };
  }
});

// ../../node_modules/.pnpm/socks@2.8.5/node_modules/socks/build/common/helpers.js
var require_helpers3 = __commonJS({
  "../../node_modules/.pnpm/socks@2.8.5/node_modules/socks/build/common/helpers.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ipToBuffer = exports2.int32ToIpv4 = exports2.ipv4ToInt32 = exports2.validateSocksClientChainOptions = exports2.validateSocksClientOptions = void 0;
    var util_1 = require_util();
    var constants_1 = require_constants2();
    var stream = require("stream");
    var ip_address_1 = require_ip_address();
    var net3 = require("net");
    function validateSocksClientOptions(options, acceptedCommands = ["connect", "bind", "associate"]) {
      if (!constants_1.SocksCommand[options.command]) {
        throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommand, options);
      }
      if (acceptedCommands.indexOf(options.command) === -1) {
        throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommandForOperation, options);
      }
      if (!isValidSocksRemoteHost(options.destination)) {
        throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsDestination, options);
      }
      if (!isValidSocksProxy(options.proxy)) {
        throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxy, options);
      }
      validateCustomProxyAuth(options.proxy, options);
      if (options.timeout && !isValidTimeoutValue(options.timeout)) {
        throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsTimeout, options);
      }
      if (options.existing_socket && !(options.existing_socket instanceof stream.Duplex)) {
        throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsExistingSocket, options);
      }
    }
    exports2.validateSocksClientOptions = validateSocksClientOptions;
    function validateSocksClientChainOptions(options) {
      if (options.command !== "connect") {
        throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommandChain, options);
      }
      if (!isValidSocksRemoteHost(options.destination)) {
        throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsDestination, options);
      }
      if (!(options.proxies && Array.isArray(options.proxies) && options.proxies.length >= 2)) {
        throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxiesLength, options);
      }
      options.proxies.forEach((proxy) => {
        if (!isValidSocksProxy(proxy)) {
          throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxy, options);
        }
        validateCustomProxyAuth(proxy, options);
      });
      if (options.timeout && !isValidTimeoutValue(options.timeout)) {
        throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsTimeout, options);
      }
    }
    exports2.validateSocksClientChainOptions = validateSocksClientChainOptions;
    function validateCustomProxyAuth(proxy, options) {
      if (proxy.custom_auth_method !== void 0) {
        if (proxy.custom_auth_method < constants_1.SOCKS5_CUSTOM_AUTH_START || proxy.custom_auth_method > constants_1.SOCKS5_CUSTOM_AUTH_END) {
          throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthRange, options);
        }
        if (proxy.custom_auth_request_handler === void 0 || typeof proxy.custom_auth_request_handler !== "function") {
          throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions, options);
        }
        if (proxy.custom_auth_response_size === void 0) {
          throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions, options);
        }
        if (proxy.custom_auth_response_handler === void 0 || typeof proxy.custom_auth_response_handler !== "function") {
          throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions, options);
        }
      }
    }
    function isValidSocksRemoteHost(remoteHost) {
      return remoteHost && typeof remoteHost.host === "string" && typeof remoteHost.port === "number" && remoteHost.port >= 0 && remoteHost.port <= 65535;
    }
    function isValidSocksProxy(proxy) {
      return proxy && (typeof proxy.host === "string" || typeof proxy.ipaddress === "string") && typeof proxy.port === "number" && proxy.port >= 0 && proxy.port <= 65535 && (proxy.type === 4 || proxy.type === 5);
    }
    function isValidTimeoutValue(value) {
      return typeof value === "number" && value > 0;
    }
    function ipv4ToInt32(ip) {
      const address = new ip_address_1.Address4(ip);
      return address.toArray().reduce((acc, part) => (acc << 8) + part, 0) >>> 0;
    }
    exports2.ipv4ToInt32 = ipv4ToInt32;
    function int32ToIpv4(int323) {
      const octet1 = int323 >>> 24 & 255;
      const octet2 = int323 >>> 16 & 255;
      const octet3 = int323 >>> 8 & 255;
      const octet4 = int323 & 255;
      return [octet1, octet2, octet3, octet4].join(".");
    }
    exports2.int32ToIpv4 = int32ToIpv4;
    function ipToBuffer(ip) {
      if (net3.isIPv4(ip)) {
        const address = new ip_address_1.Address4(ip);
        return Buffer.from(address.toArray());
      } else if (net3.isIPv6(ip)) {
        const address = new ip_address_1.Address6(ip);
        return Buffer.from(address.canonicalForm().split(":").map((segment) => segment.padStart(4, "0")).join(""), "hex");
      } else {
        throw new Error("Invalid IP address format");
      }
    }
    exports2.ipToBuffer = ipToBuffer;
  }
});

// ../../node_modules/.pnpm/socks@2.8.5/node_modules/socks/build/common/receivebuffer.js
var require_receivebuffer = __commonJS({
  "../../node_modules/.pnpm/socks@2.8.5/node_modules/socks/build/common/receivebuffer.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ReceiveBuffer = void 0;
    var ReceiveBuffer = class {
      constructor(size = 4096) {
        this.buffer = Buffer.allocUnsafe(size);
        this.offset = 0;
        this.originalSize = size;
      }
      get length() {
        return this.offset;
      }
      append(data) {
        if (!Buffer.isBuffer(data)) {
          throw new Error("Attempted to append a non-buffer instance to ReceiveBuffer.");
        }
        if (this.offset + data.length >= this.buffer.length) {
          const tmp = this.buffer;
          this.buffer = Buffer.allocUnsafe(Math.max(this.buffer.length + this.originalSize, this.buffer.length + data.length));
          tmp.copy(this.buffer);
        }
        data.copy(this.buffer, this.offset);
        return this.offset += data.length;
      }
      peek(length) {
        if (length > this.offset) {
          throw new Error("Attempted to read beyond the bounds of the managed internal data.");
        }
        return this.buffer.slice(0, length);
      }
      get(length) {
        if (length > this.offset) {
          throw new Error("Attempted to read beyond the bounds of the managed internal data.");
        }
        const value = Buffer.allocUnsafe(length);
        this.buffer.slice(0, length).copy(value);
        this.buffer.copyWithin(0, length, length + this.offset - length);
        this.offset -= length;
        return value;
      }
    };
    exports2.ReceiveBuffer = ReceiveBuffer;
  }
});

// ../../node_modules/.pnpm/socks@2.8.5/node_modules/socks/build/client/socksclient.js
var require_socksclient = __commonJS({
  "../../node_modules/.pnpm/socks@2.8.5/node_modules/socks/build/client/socksclient.js"(exports2) {
    "use strict";
    var __awaiter2 = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
      function adopt2(value) {
        return value instanceof P ? value : new P(function(resolve8) {
          resolve8(value);
        });
      }
      return new (P || (P = Promise))(function(resolve8, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e) {
            reject(e);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e) {
            reject(e);
          }
        }
        function step(result) {
          result.done ? resolve8(result.value) : adopt2(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SocksClientError = exports2.SocksClient = void 0;
    var events_1 = require("events");
    var net3 = require("net");
    var smart_buffer_1 = require_smartbuffer();
    var constants_1 = require_constants2();
    var helpers_1 = require_helpers3();
    var receivebuffer_1 = require_receivebuffer();
    var util_1 = require_util();
    Object.defineProperty(exports2, "SocksClientError", { enumerable: true, get: function() {
      return util_1.SocksClientError;
    } });
    var ip_address_1 = require_ip_address();
    var SocksClient = class _SocksClient extends events_1.EventEmitter {
      constructor(options) {
        super();
        this.options = Object.assign({}, options);
        (0, helpers_1.validateSocksClientOptions)(options);
        this.setState(constants_1.SocksClientState.Created);
      }
      /**
       * Creates a new SOCKS connection.
       *
       * Note: Supports callbacks and promises. Only supports the connect command.
       * @param options { SocksClientOptions } Options.
       * @param callback { Function } An optional callback function.
       * @returns { Promise }
       */
      static createConnection(options, callback) {
        return new Promise((resolve8, reject) => {
          try {
            (0, helpers_1.validateSocksClientOptions)(options, ["connect"]);
          } catch (err) {
            if (typeof callback === "function") {
              callback(err);
              return resolve8(err);
            } else {
              return reject(err);
            }
          }
          const client = new _SocksClient(options);
          client.connect(options.existing_socket);
          client.once("established", (info) => {
            client.removeAllListeners();
            if (typeof callback === "function") {
              callback(null, info);
              resolve8(info);
            } else {
              resolve8(info);
            }
          });
          client.once("error", (err) => {
            client.removeAllListeners();
            if (typeof callback === "function") {
              callback(err);
              resolve8(err);
            } else {
              reject(err);
            }
          });
        });
      }
      /**
       * Creates a new SOCKS connection chain to a destination host through 2 or more SOCKS proxies.
       *
       * Note: Supports callbacks and promises. Only supports the connect method.
       * Note: Implemented via createConnection() factory function.
       * @param options { SocksClientChainOptions } Options
       * @param callback { Function } An optional callback function.
       * @returns { Promise }
       */
      static createConnectionChain(options, callback) {
        return new Promise((resolve8, reject) => __awaiter2(this, void 0, void 0, function* () {
          try {
            (0, helpers_1.validateSocksClientChainOptions)(options);
          } catch (err) {
            if (typeof callback === "function") {
              callback(err);
              return resolve8(err);
            } else {
              return reject(err);
            }
          }
          if (options.randomizeChain) {
            (0, util_1.shuffleArray)(options.proxies);
          }
          try {
            let sock;
            for (let i = 0; i < options.proxies.length; i++) {
              const nextProxy = options.proxies[i];
              const nextDestination = i === options.proxies.length - 1 ? options.destination : {
                host: options.proxies[i + 1].host || options.proxies[i + 1].ipaddress,
                port: options.proxies[i + 1].port
              };
              const result = yield _SocksClient.createConnection({
                command: "connect",
                proxy: nextProxy,
                destination: nextDestination,
                existing_socket: sock
              });
              sock = sock || result.socket;
            }
            if (typeof callback === "function") {
              callback(null, { socket: sock });
              resolve8({ socket: sock });
            } else {
              resolve8({ socket: sock });
            }
          } catch (err) {
            if (typeof callback === "function") {
              callback(err);
              resolve8(err);
            } else {
              reject(err);
            }
          }
        }));
      }
      /**
       * Creates a SOCKS UDP Frame.
       * @param options
       */
      static createUDPFrame(options) {
        const buff = new smart_buffer_1.SmartBuffer();
        buff.writeUInt16BE(0);
        buff.writeUInt8(options.frameNumber || 0);
        if (net3.isIPv4(options.remoteHost.host)) {
          buff.writeUInt8(constants_1.Socks5HostType.IPv4);
          buff.writeUInt32BE((0, helpers_1.ipv4ToInt32)(options.remoteHost.host));
        } else if (net3.isIPv6(options.remoteHost.host)) {
          buff.writeUInt8(constants_1.Socks5HostType.IPv6);
          buff.writeBuffer((0, helpers_1.ipToBuffer)(options.remoteHost.host));
        } else {
          buff.writeUInt8(constants_1.Socks5HostType.Hostname);
          buff.writeUInt8(Buffer.byteLength(options.remoteHost.host));
          buff.writeString(options.remoteHost.host);
        }
        buff.writeUInt16BE(options.remoteHost.port);
        buff.writeBuffer(options.data);
        return buff.toBuffer();
      }
      /**
       * Parses a SOCKS UDP frame.
       * @param data
       */
      static parseUDPFrame(data) {
        const buff = smart_buffer_1.SmartBuffer.fromBuffer(data);
        buff.readOffset = 2;
        const frameNumber = buff.readUInt8();
        const hostType = buff.readUInt8();
        let remoteHost;
        if (hostType === constants_1.Socks5HostType.IPv4) {
          remoteHost = (0, helpers_1.int32ToIpv4)(buff.readUInt32BE());
        } else if (hostType === constants_1.Socks5HostType.IPv6) {
          remoteHost = ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm();
        } else {
          remoteHost = buff.readString(buff.readUInt8());
        }
        const remotePort = buff.readUInt16BE();
        return {
          frameNumber,
          remoteHost: {
            host: remoteHost,
            port: remotePort
          },
          data: buff.readBuffer()
        };
      }
      /**
       * Internal state setter. If the SocksClient is in an error state, it cannot be changed to a non error state.
       */
      setState(newState) {
        if (this.state !== constants_1.SocksClientState.Error) {
          this.state = newState;
        }
      }
      /**
       * Starts the connection establishment to the proxy and destination.
       * @param existingSocket Connected socket to use instead of creating a new one (internal use).
       */
      connect(existingSocket) {
        this.onDataReceived = (data) => this.onDataReceivedHandler(data);
        this.onClose = () => this.onCloseHandler();
        this.onError = (err) => this.onErrorHandler(err);
        this.onConnect = () => this.onConnectHandler();
        const timer = setTimeout(() => this.onEstablishedTimeout(), this.options.timeout || constants_1.DEFAULT_TIMEOUT);
        if (timer.unref && typeof timer.unref === "function") {
          timer.unref();
        }
        if (existingSocket) {
          this.socket = existingSocket;
        } else {
          this.socket = new net3.Socket();
        }
        this.socket.once("close", this.onClose);
        this.socket.once("error", this.onError);
        this.socket.once("connect", this.onConnect);
        this.socket.on("data", this.onDataReceived);
        this.setState(constants_1.SocksClientState.Connecting);
        this.receiveBuffer = new receivebuffer_1.ReceiveBuffer();
        if (existingSocket) {
          this.socket.emit("connect");
        } else {
          this.socket.connect(this.getSocketOptions());
          if (this.options.set_tcp_nodelay !== void 0 && this.options.set_tcp_nodelay !== null) {
            this.socket.setNoDelay(!!this.options.set_tcp_nodelay);
          }
        }
        this.prependOnceListener("established", (info) => {
          setImmediate(() => {
            if (this.receiveBuffer.length > 0) {
              const excessData = this.receiveBuffer.get(this.receiveBuffer.length);
              info.socket.emit("data", excessData);
            }
            info.socket.resume();
          });
        });
      }
      // Socket options (defaults host/port to options.proxy.host/options.proxy.port)
      getSocketOptions() {
        return Object.assign(Object.assign({}, this.options.socket_options), { host: this.options.proxy.host || this.options.proxy.ipaddress, port: this.options.proxy.port });
      }
      /**
       * Handles internal Socks timeout callback.
       * Note: If the Socks client is not BoundWaitingForConnection or Established, the connection will be closed.
       */
      onEstablishedTimeout() {
        if (this.state !== constants_1.SocksClientState.Established && this.state !== constants_1.SocksClientState.BoundWaitingForConnection) {
          this.closeSocket(constants_1.ERRORS.ProxyConnectionTimedOut);
        }
      }
      /**
       * Handles Socket connect event.
       */
      onConnectHandler() {
        this.setState(constants_1.SocksClientState.Connected);
        if (this.options.proxy.type === 4) {
          this.sendSocks4InitialHandshake();
        } else {
          this.sendSocks5InitialHandshake();
        }
        this.setState(constants_1.SocksClientState.SentInitialHandshake);
      }
      /**
       * Handles Socket data event.
       * @param data
       */
      onDataReceivedHandler(data) {
        this.receiveBuffer.append(data);
        this.processData();
      }
      /**
       * Handles processing of the data we have received.
       */
      processData() {
        while (this.state !== constants_1.SocksClientState.Established && this.state !== constants_1.SocksClientState.Error && this.receiveBuffer.length >= this.nextRequiredPacketBufferSize) {
          if (this.state === constants_1.SocksClientState.SentInitialHandshake) {
            if (this.options.proxy.type === 4) {
              this.handleSocks4FinalHandshakeResponse();
            } else {
              this.handleInitialSocks5HandshakeResponse();
            }
          } else if (this.state === constants_1.SocksClientState.SentAuthentication) {
            this.handleInitialSocks5AuthenticationHandshakeResponse();
          } else if (this.state === constants_1.SocksClientState.SentFinalHandshake) {
            this.handleSocks5FinalHandshakeResponse();
          } else if (this.state === constants_1.SocksClientState.BoundWaitingForConnection) {
            if (this.options.proxy.type === 4) {
              this.handleSocks4IncomingConnectionResponse();
            } else {
              this.handleSocks5IncomingConnectionResponse();
            }
          } else {
            this.closeSocket(constants_1.ERRORS.InternalError);
            break;
          }
        }
      }
      /**
       * Handles Socket close event.
       * @param had_error
       */
      onCloseHandler() {
        this.closeSocket(constants_1.ERRORS.SocketClosed);
      }
      /**
       * Handles Socket error event.
       * @param err
       */
      onErrorHandler(err) {
        this.closeSocket(err.message);
      }
      /**
       * Removes internal event listeners on the underlying Socket.
       */
      removeInternalSocketHandlers() {
        this.socket.pause();
        this.socket.removeListener("data", this.onDataReceived);
        this.socket.removeListener("close", this.onClose);
        this.socket.removeListener("error", this.onError);
        this.socket.removeListener("connect", this.onConnect);
      }
      /**
       * Closes and destroys the underlying Socket. Emits an error event.
       * @param err { String } An error string to include in error event.
       */
      closeSocket(err) {
        if (this.state !== constants_1.SocksClientState.Error) {
          this.setState(constants_1.SocksClientState.Error);
          this.socket.destroy();
          this.removeInternalSocketHandlers();
          this.emit("error", new util_1.SocksClientError(err, this.options));
        }
      }
      /**
       * Sends initial Socks v4 handshake request.
       */
      sendSocks4InitialHandshake() {
        const userId = this.options.proxy.userId || "";
        const buff = new smart_buffer_1.SmartBuffer();
        buff.writeUInt8(4);
        buff.writeUInt8(constants_1.SocksCommand[this.options.command]);
        buff.writeUInt16BE(this.options.destination.port);
        if (net3.isIPv4(this.options.destination.host)) {
          buff.writeBuffer((0, helpers_1.ipToBuffer)(this.options.destination.host));
          buff.writeStringNT(userId);
        } else {
          buff.writeUInt8(0);
          buff.writeUInt8(0);
          buff.writeUInt8(0);
          buff.writeUInt8(1);
          buff.writeStringNT(userId);
          buff.writeStringNT(this.options.destination.host);
        }
        this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks4Response;
        this.socket.write(buff.toBuffer());
      }
      /**
       * Handles Socks v4 handshake response.
       * @param data
       */
      handleSocks4FinalHandshakeResponse() {
        const data = this.receiveBuffer.get(8);
        if (data[1] !== constants_1.Socks4Response.Granted) {
          this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedConnection} - (${constants_1.Socks4Response[data[1]]})`);
        } else {
          if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.bind) {
            const buff = smart_buffer_1.SmartBuffer.fromBuffer(data);
            buff.readOffset = 2;
            const remoteHost = {
              port: buff.readUInt16BE(),
              host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE())
            };
            if (remoteHost.host === "0.0.0.0") {
              remoteHost.host = this.options.proxy.ipaddress;
            }
            this.setState(constants_1.SocksClientState.BoundWaitingForConnection);
            this.emit("bound", { remoteHost, socket: this.socket });
          } else {
            this.setState(constants_1.SocksClientState.Established);
            this.removeInternalSocketHandlers();
            this.emit("established", { socket: this.socket });
          }
        }
      }
      /**
       * Handles Socks v4 incoming connection request (BIND)
       * @param data
       */
      handleSocks4IncomingConnectionResponse() {
        const data = this.receiveBuffer.get(8);
        if (data[1] !== constants_1.Socks4Response.Granted) {
          this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedIncomingBoundConnection} - (${constants_1.Socks4Response[data[1]]})`);
        } else {
          const buff = smart_buffer_1.SmartBuffer.fromBuffer(data);
          buff.readOffset = 2;
          const remoteHost = {
            port: buff.readUInt16BE(),
            host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE())
          };
          this.setState(constants_1.SocksClientState.Established);
          this.removeInternalSocketHandlers();
          this.emit("established", { remoteHost, socket: this.socket });
        }
      }
      /**
       * Sends initial Socks v5 handshake request.
       */
      sendSocks5InitialHandshake() {
        const buff = new smart_buffer_1.SmartBuffer();
        const supportedAuthMethods = [constants_1.Socks5Auth.NoAuth];
        if (this.options.proxy.userId || this.options.proxy.password) {
          supportedAuthMethods.push(constants_1.Socks5Auth.UserPass);
        }
        if (this.options.proxy.custom_auth_method !== void 0) {
          supportedAuthMethods.push(this.options.proxy.custom_auth_method);
        }
        buff.writeUInt8(5);
        buff.writeUInt8(supportedAuthMethods.length);
        for (const authMethod of supportedAuthMethods) {
          buff.writeUInt8(authMethod);
        }
        this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5InitialHandshakeResponse;
        this.socket.write(buff.toBuffer());
        this.setState(constants_1.SocksClientState.SentInitialHandshake);
      }
      /**
       * Handles initial Socks v5 handshake response.
       * @param data
       */
      handleInitialSocks5HandshakeResponse() {
        const data = this.receiveBuffer.get(2);
        if (data[0] !== 5) {
          this.closeSocket(constants_1.ERRORS.InvalidSocks5IntiailHandshakeSocksVersion);
        } else if (data[1] === constants_1.SOCKS5_NO_ACCEPTABLE_AUTH) {
          this.closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeNoAcceptedAuthType);
        } else {
          if (data[1] === constants_1.Socks5Auth.NoAuth) {
            this.socks5ChosenAuthType = constants_1.Socks5Auth.NoAuth;
            this.sendSocks5CommandRequest();
          } else if (data[1] === constants_1.Socks5Auth.UserPass) {
            this.socks5ChosenAuthType = constants_1.Socks5Auth.UserPass;
            this.sendSocks5UserPassAuthentication();
          } else if (data[1] === this.options.proxy.custom_auth_method) {
            this.socks5ChosenAuthType = this.options.proxy.custom_auth_method;
            this.sendSocks5CustomAuthentication();
          } else {
            this.closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeUnknownAuthType);
          }
        }
      }
      /**
       * Sends Socks v5 user & password auth handshake.
       *
       * Note: No auth and user/pass are currently supported.
       */
      sendSocks5UserPassAuthentication() {
        const userId = this.options.proxy.userId || "";
        const password = this.options.proxy.password || "";
        const buff = new smart_buffer_1.SmartBuffer();
        buff.writeUInt8(1);
        buff.writeUInt8(Buffer.byteLength(userId));
        buff.writeString(userId);
        buff.writeUInt8(Buffer.byteLength(password));
        buff.writeString(password);
        this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5UserPassAuthenticationResponse;
        this.socket.write(buff.toBuffer());
        this.setState(constants_1.SocksClientState.SentAuthentication);
      }
      sendSocks5CustomAuthentication() {
        return __awaiter2(this, void 0, void 0, function* () {
          this.nextRequiredPacketBufferSize = this.options.proxy.custom_auth_response_size;
          this.socket.write(yield this.options.proxy.custom_auth_request_handler());
          this.setState(constants_1.SocksClientState.SentAuthentication);
        });
      }
      handleSocks5CustomAuthHandshakeResponse(data) {
        return __awaiter2(this, void 0, void 0, function* () {
          return yield this.options.proxy.custom_auth_response_handler(data);
        });
      }
      handleSocks5AuthenticationNoAuthHandshakeResponse(data) {
        return __awaiter2(this, void 0, void 0, function* () {
          return data[1] === 0;
        });
      }
      handleSocks5AuthenticationUserPassHandshakeResponse(data) {
        return __awaiter2(this, void 0, void 0, function* () {
          return data[1] === 0;
        });
      }
      /**
       * Handles Socks v5 auth handshake response.
       * @param data
       */
      handleInitialSocks5AuthenticationHandshakeResponse() {
        return __awaiter2(this, void 0, void 0, function* () {
          this.setState(constants_1.SocksClientState.ReceivedAuthenticationResponse);
          let authResult = false;
          if (this.socks5ChosenAuthType === constants_1.Socks5Auth.NoAuth) {
            authResult = yield this.handleSocks5AuthenticationNoAuthHandshakeResponse(this.receiveBuffer.get(2));
          } else if (this.socks5ChosenAuthType === constants_1.Socks5Auth.UserPass) {
            authResult = yield this.handleSocks5AuthenticationUserPassHandshakeResponse(this.receiveBuffer.get(2));
          } else if (this.socks5ChosenAuthType === this.options.proxy.custom_auth_method) {
            authResult = yield this.handleSocks5CustomAuthHandshakeResponse(this.receiveBuffer.get(this.options.proxy.custom_auth_response_size));
          }
          if (!authResult) {
            this.closeSocket(constants_1.ERRORS.Socks5AuthenticationFailed);
          } else {
            this.sendSocks5CommandRequest();
          }
        });
      }
      /**
       * Sends Socks v5 final handshake request.
       */
      sendSocks5CommandRequest() {
        const buff = new smart_buffer_1.SmartBuffer();
        buff.writeUInt8(5);
        buff.writeUInt8(constants_1.SocksCommand[this.options.command]);
        buff.writeUInt8(0);
        if (net3.isIPv4(this.options.destination.host)) {
          buff.writeUInt8(constants_1.Socks5HostType.IPv4);
          buff.writeBuffer((0, helpers_1.ipToBuffer)(this.options.destination.host));
        } else if (net3.isIPv6(this.options.destination.host)) {
          buff.writeUInt8(constants_1.Socks5HostType.IPv6);
          buff.writeBuffer((0, helpers_1.ipToBuffer)(this.options.destination.host));
        } else {
          buff.writeUInt8(constants_1.Socks5HostType.Hostname);
          buff.writeUInt8(this.options.destination.host.length);
          buff.writeString(this.options.destination.host);
        }
        buff.writeUInt16BE(this.options.destination.port);
        this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader;
        this.socket.write(buff.toBuffer());
        this.setState(constants_1.SocksClientState.SentFinalHandshake);
      }
      /**
       * Handles Socks v5 final handshake response.
       * @param data
       */
      handleSocks5FinalHandshakeResponse() {
        const header = this.receiveBuffer.peek(5);
        if (header[0] !== 5 || header[1] !== constants_1.Socks5Response.Granted) {
          this.closeSocket(`${constants_1.ERRORS.InvalidSocks5FinalHandshakeRejected} - ${constants_1.Socks5Response[header[1]]}`);
        } else {
          const addressType = header[3];
          let remoteHost;
          let buff;
          if (addressType === constants_1.Socks5HostType.IPv4) {
            const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;
            if (this.receiveBuffer.length < dataNeeded) {
              this.nextRequiredPacketBufferSize = dataNeeded;
              return;
            }
            buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4));
            remoteHost = {
              host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()),
              port: buff.readUInt16BE()
            };
            if (remoteHost.host === "0.0.0.0") {
              remoteHost.host = this.options.proxy.ipaddress;
            }
          } else if (addressType === constants_1.Socks5HostType.Hostname) {
            const hostLength = header[4];
            const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength);
            if (this.receiveBuffer.length < dataNeeded) {
              this.nextRequiredPacketBufferSize = dataNeeded;
              return;
            }
            buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(5));
            remoteHost = {
              host: buff.readString(hostLength),
              port: buff.readUInt16BE()
            };
          } else if (addressType === constants_1.Socks5HostType.IPv6) {
            const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;
            if (this.receiveBuffer.length < dataNeeded) {
              this.nextRequiredPacketBufferSize = dataNeeded;
              return;
            }
            buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4));
            remoteHost = {
              host: ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm(),
              port: buff.readUInt16BE()
            };
          }
          this.setState(constants_1.SocksClientState.ReceivedFinalResponse);
          if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.connect) {
            this.setState(constants_1.SocksClientState.Established);
            this.removeInternalSocketHandlers();
            this.emit("established", { remoteHost, socket: this.socket });
          } else if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.bind) {
            this.setState(constants_1.SocksClientState.BoundWaitingForConnection);
            this.nextRequiredPacketBufferSize = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader;
            this.emit("bound", { remoteHost, socket: this.socket });
          } else if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.associate) {
            this.setState(constants_1.SocksClientState.Established);
            this.removeInternalSocketHandlers();
            this.emit("established", {
              remoteHost,
              socket: this.socket
            });
          }
        }
      }
      /**
       * Handles Socks v5 incoming connection request (BIND).
       */
      handleSocks5IncomingConnectionResponse() {
        const header = this.receiveBuffer.peek(5);
        if (header[0] !== 5 || header[1] !== constants_1.Socks5Response.Granted) {
          this.closeSocket(`${constants_1.ERRORS.Socks5ProxyRejectedIncomingBoundConnection} - ${constants_1.Socks5Response[header[1]]}`);
        } else {
          const addressType = header[3];
          let remoteHost;
          let buff;
          if (addressType === constants_1.Socks5HostType.IPv4) {
            const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;
            if (this.receiveBuffer.length < dataNeeded) {
              this.nextRequiredPacketBufferSize = dataNeeded;
              return;
            }
            buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4));
            remoteHost = {
              host: (0, helpers_1.int32ToIpv4)(buff.readUInt32BE()),
              port: buff.readUInt16BE()
            };
            if (remoteHost.host === "0.0.0.0") {
              remoteHost.host = this.options.proxy.ipaddress;
            }
          } else if (addressType === constants_1.Socks5HostType.Hostname) {
            const hostLength = header[4];
            const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength);
            if (this.receiveBuffer.length < dataNeeded) {
              this.nextRequiredPacketBufferSize = dataNeeded;
              return;
            }
            buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(5));
            remoteHost = {
              host: buff.readString(hostLength),
              port: buff.readUInt16BE()
            };
          } else if (addressType === constants_1.Socks5HostType.IPv6) {
            const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;
            if (this.receiveBuffer.length < dataNeeded) {
              this.nextRequiredPacketBufferSize = dataNeeded;
              return;
            }
            buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4));
            remoteHost = {
              host: ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm(),
              port: buff.readUInt16BE()
            };
          }
          this.setState(constants_1.SocksClientState.Established);
          this.removeInternalSocketHandlers();
          this.emit("established", { remoteHost, socket: this.socket });
        }
      }
      get socksClientOptions() {
        return Object.assign({}, this.options);
      }
    };
    exports2.SocksClient = SocksClient;
  }
});

// ../../node_modules/.pnpm/socks@2.8.5/node_modules/socks/build/index.js
var require_build = __commonJS({
  "../../node_modules/.pnpm/socks@2.8.5/node_modules/socks/build/index.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __exportStar2 = exports2 && exports2.__exportStar || function(m, exports3) {
      for (var p2 in m) if (p2 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p2)) __createBinding2(exports3, m, p2);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    __exportStar2(require_socksclient(), exports2);
  }
});

// ../../node_modules/.pnpm/socks-proxy-agent@8.0.5/node_modules/socks-proxy-agent/dist/index.js
var require_dist5 = __commonJS({
  "../../node_modules/.pnpm/socks-proxy-agent@8.0.5/node_modules/socks-proxy-agent/dist/index.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding2(result, mod, k);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.SocksProxyAgent = void 0;
    var socks_1 = require_build();
    var agent_base_1 = require_dist2();
    var debug_1 = __importDefault2(require_src2());
    var dns = __importStar2(require("dns"));
    var net3 = __importStar2(require("net"));
    var tls3 = __importStar2(require("tls"));
    var url_1 = require("url");
    var debug4 = (0, debug_1.default)("socks-proxy-agent");
    var setServernameFromNonIpHost = (options) => {
      if (options.servername === void 0 && options.host && !net3.isIP(options.host)) {
        return {
          ...options,
          servername: options.host
        };
      }
      return options;
    };
    function parseSocksURL(url46) {
      let lookup = false;
      let type = 5;
      const host = url46.hostname;
      const port = parseInt(url46.port, 10) || 1080;
      switch (url46.protocol.replace(":", "")) {
        case "socks4":
          lookup = true;
          type = 4;
          break;
        // pass through
        case "socks4a":
          type = 4;
          break;
        case "socks5":
          lookup = true;
          type = 5;
          break;
        // pass through
        case "socks":
          type = 5;
          break;
        case "socks5h":
          type = 5;
          break;
        default:
          throw new TypeError(`A "socks" protocol must be specified! Got: ${String(url46.protocol)}`);
      }
      const proxy = {
        host,
        port,
        type
      };
      if (url46.username) {
        Object.defineProperty(proxy, "userId", {
          value: decodeURIComponent(url46.username),
          enumerable: false
        });
      }
      if (url46.password != null) {
        Object.defineProperty(proxy, "password", {
          value: decodeURIComponent(url46.password),
          enumerable: false
        });
      }
      return { lookup, proxy };
    }
    var SocksProxyAgent = class extends agent_base_1.Agent {
      constructor(uri, opts) {
        super(opts);
        const url46 = typeof uri === "string" ? new url_1.URL(uri) : uri;
        const { proxy, lookup } = parseSocksURL(url46);
        this.shouldLookup = lookup;
        this.proxy = proxy;
        this.timeout = opts?.timeout ?? null;
        this.socketOptions = opts?.socketOptions ?? null;
      }
      /**
       * Initiates a SOCKS connection to the specified SOCKS proxy server,
       * which in turn connects to the specified remote host and port.
       */
      async connect(req, opts) {
        const { shouldLookup, proxy, timeout } = this;
        if (!opts.host) {
          throw new Error("No `host` defined!");
        }
        let { host } = opts;
        const { port, lookup: lookupFn = dns.lookup } = opts;
        if (shouldLookup) {
          host = await new Promise((resolve8, reject) => {
            lookupFn(host, {}, (err, res) => {
              if (err) {
                reject(err);
              } else {
                resolve8(res);
              }
            });
          });
        }
        const socksOpts = {
          proxy,
          destination: {
            host,
            port: typeof port === "number" ? port : parseInt(port, 10)
          },
          command: "connect",
          timeout: timeout ?? void 0,
          // @ts-expect-error the type supplied by socks for socket_options is wider
          // than necessary since socks will always override the host and port
          socket_options: this.socketOptions ?? void 0
        };
        const cleanup = (tlsSocket) => {
          req.destroy();
          socket.destroy();
          if (tlsSocket)
            tlsSocket.destroy();
        };
        debug4("Creating socks proxy connection: %o", socksOpts);
        const { socket } = await socks_1.SocksClient.createConnection(socksOpts);
        debug4("Successfully created socks proxy connection");
        if (timeout !== null) {
          socket.setTimeout(timeout);
          socket.on("timeout", () => cleanup());
        }
        if (opts.secureEndpoint) {
          debug4("Upgrading socket connection to TLS");
          const tlsSocket = tls3.connect({
            ...omit3(setServernameFromNonIpHost(opts), "host", "path", "port"),
            socket
          });
          tlsSocket.once("error", (error101) => {
            debug4("Socket TLS error", error101.message);
            cleanup(tlsSocket);
          });
          return tlsSocket;
        }
        return socket;
      }
    };
    SocksProxyAgent.protocols = [
      "socks",
      "socks4",
      "socks4a",
      "socks5",
      "socks5h"
    ];
    exports2.SocksProxyAgent = SocksProxyAgent;
    function omit3(obj, ...keys) {
      const ret = {};
      let key;
      for (key in obj) {
        if (!keys.includes(key)) {
          ret[key] = obj[key];
        }
      }
      return ret;
    }
  }
});

// ../../node_modules/.pnpm/data-uri-to-buffer@6.0.2/node_modules/data-uri-to-buffer/dist/common.js
var require_common3 = __commonJS({
  "../../node_modules/.pnpm/data-uri-to-buffer@6.0.2/node_modules/data-uri-to-buffer/dist/common.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.makeDataUriToBuffer = void 0;
    var makeDataUriToBuffer = (convert) => (uri) => {
      uri = String(uri);
      if (!/^data:/i.test(uri)) {
        throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');
      }
      uri = uri.replace(/\r?\n/g, "");
      const firstComma = uri.indexOf(",");
      if (firstComma === -1 || firstComma <= 4) {
        throw new TypeError("malformed data: URI");
      }
      const meta5 = uri.substring(5, firstComma).split(";");
      let charset = "";
      let base645 = false;
      const type = meta5[0] || "text/plain";
      let typeFull = type;
      for (let i = 1; i < meta5.length; i++) {
        if (meta5[i] === "base64") {
          base645 = true;
        } else if (meta5[i]) {
          typeFull += `;${meta5[i]}`;
          if (meta5[i].indexOf("charset=") === 0) {
            charset = meta5[i].substring(8);
          }
        }
      }
      if (!meta5[0] && !charset.length) {
        typeFull += ";charset=US-ASCII";
        charset = "US-ASCII";
      }
      const data = unescape(uri.substring(firstComma + 1));
      const buffer = base645 ? convert.base64ToArrayBuffer(data) : convert.stringToBuffer(data);
      return {
        type,
        typeFull,
        charset,
        buffer
      };
    };
    exports2.makeDataUriToBuffer = makeDataUriToBuffer;
  }
});

// ../../node_modules/.pnpm/data-uri-to-buffer@6.0.2/node_modules/data-uri-to-buffer/dist/node.js
var require_node2 = __commonJS({
  "../../node_modules/.pnpm/data-uri-to-buffer@6.0.2/node_modules/data-uri-to-buffer/dist/node.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.dataUriToBuffer = void 0;
    var common_1 = require_common3();
    function nodeBuffertoArrayBuffer(nodeBuf) {
      if (nodeBuf.byteLength === nodeBuf.buffer.byteLength) {
        return nodeBuf.buffer;
      }
      const buffer = new ArrayBuffer(nodeBuf.byteLength);
      const view = new Uint8Array(buffer);
      view.set(nodeBuf);
      return buffer;
    }
    function base64ToArrayBuffer(base645) {
      return nodeBuffertoArrayBuffer(Buffer.from(base645, "base64"));
    }
    function stringToBuffer(str) {
      return nodeBuffertoArrayBuffer(Buffer.from(str, "ascii"));
    }
    exports2.dataUriToBuffer = (0, common_1.makeDataUriToBuffer)({ stringToBuffer, base64ToArrayBuffer });
  }
});

// ../../node_modules/.pnpm/get-uri@6.0.4/node_modules/get-uri/dist/notmodified.js
var require_notmodified = __commonJS({
  "../../node_modules/.pnpm/get-uri@6.0.4/node_modules/get-uri/dist/notmodified.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var NotModifiedError = class extends Error {
      constructor(message) {
        super(message || 'Source has not been modified since the provied "cache", re-use previous results');
        this.code = "ENOTMODIFIED";
      }
    };
    exports2.default = NotModifiedError;
  }
});

// ../../node_modules/.pnpm/get-uri@6.0.4/node_modules/get-uri/dist/data.js
var require_data = __commonJS({
  "../../node_modules/.pnpm/get-uri@6.0.4/node_modules/get-uri/dist/data.js"(exports2) {
    "use strict";
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.data = void 0;
    var debug_1 = __importDefault2(require_src2());
    var stream_1 = require("stream");
    var crypto_1 = require("crypto");
    var data_uri_to_buffer_1 = require_node2();
    var notmodified_1 = __importDefault2(require_notmodified());
    var debug4 = (0, debug_1.default)("get-uri:data");
    var DataReadable = class extends stream_1.Readable {
      constructor(hash3, buf) {
        super();
        this.push(buf);
        this.push(null);
        this.hash = hash3;
      }
    };
    var data = async ({ href: uri }, { cache } = {}) => {
      const shasum = (0, crypto_1.createHash)("sha1");
      shasum.update(uri);
      const hash3 = shasum.digest("hex");
      debug4('generated SHA1 hash for "data:" URI: %o', hash3);
      if (cache?.hash === hash3) {
        debug4("got matching cache SHA1 hash: %o", hash3);
        throw new notmodified_1.default();
      } else {
        debug4('creating Readable stream from "data:" URI buffer');
        const { buffer } = (0, data_uri_to_buffer_1.dataUriToBuffer)(uri);
        return new DataReadable(hash3, Buffer.from(buffer));
      }
    };
    exports2.data = data;
  }
});

// ../../node_modules/.pnpm/get-uri@6.0.4/node_modules/get-uri/dist/notfound.js
var require_notfound = __commonJS({
  "../../node_modules/.pnpm/get-uri@6.0.4/node_modules/get-uri/dist/notfound.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var NotFoundError = class extends Error {
      constructor(message) {
        super(message || "File does not exist at the specified endpoint");
        this.code = "ENOTFOUND";
      }
    };
    exports2.default = NotFoundError;
  }
});

// ../../node_modules/.pnpm/get-uri@6.0.4/node_modules/get-uri/dist/file.js
var require_file = __commonJS({
  "../../node_modules/.pnpm/get-uri@6.0.4/node_modules/get-uri/dist/file.js"(exports2) {
    "use strict";
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.file = void 0;
    var debug_1 = __importDefault2(require_src2());
    var fs_1 = require("fs");
    var notfound_1 = __importDefault2(require_notfound());
    var notmodified_1 = __importDefault2(require_notmodified());
    var url_1 = require("url");
    var debug4 = (0, debug_1.default)("get-uri:file");
    var file5 = async ({ href: uri }, opts = {}) => {
      const {
        cache,
        flags = "r",
        mode = 438
        // =0666
      } = opts;
      try {
        const filepath = (0, url_1.fileURLToPath)(uri);
        debug4("Normalized pathname: %o", filepath);
        const fdHandle = await fs_1.promises.open(filepath, flags, mode);
        const fd = fdHandle.fd;
        const stat4 = await fdHandle.stat();
        if (cache && cache.stat && stat4 && isNotModified(cache.stat, stat4)) {
          throw new notmodified_1.default();
        }
        const rs = (0, fs_1.createReadStream)(filepath, {
          autoClose: true,
          ...opts,
          fd
        });
        rs.stat = stat4;
        return rs;
      } catch (err) {
        if (err.code === "ENOENT") {
          throw new notfound_1.default();
        }
        throw err;
      }
    };
    exports2.file = file5;
    function isNotModified(prev, curr) {
      return +prev.mtime === +curr.mtime;
    }
  }
});

// ../../node_modules/.pnpm/basic-ftp@5.0.5/node_modules/basic-ftp/dist/parseControlResponse.js
var require_parseControlResponse = __commonJS({
  "../../node_modules/.pnpm/basic-ftp@5.0.5/node_modules/basic-ftp/dist/parseControlResponse.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.positiveIntermediate = exports2.positiveCompletion = exports2.isMultiline = exports2.isSingleLine = exports2.parseControlResponse = void 0;
    var LF = "\n";
    function parseControlResponse(text) {
      const lines = text.split(/\r?\n/).filter(isNotBlank);
      const messages = [];
      let startAt = 0;
      let tokenRegex;
      for (let i = 0; i < lines.length; i++) {
        const line = lines[i];
        if (!tokenRegex) {
          if (isMultiline(line)) {
            const token = line.substr(0, 3);
            tokenRegex = new RegExp(`^${token}(?:$| )`);
            startAt = i;
          } else if (isSingleLine(line)) {
            messages.push(line);
          }
        } else if (tokenRegex.test(line)) {
          tokenRegex = void 0;
          messages.push(lines.slice(startAt, i + 1).join(LF));
        }
      }
      const rest = tokenRegex ? lines.slice(startAt).join(LF) + LF : "";
      return { messages, rest };
    }
    exports2.parseControlResponse = parseControlResponse;
    function isSingleLine(line) {
      return /^\d\d\d(?:$| )/.test(line);
    }
    exports2.isSingleLine = isSingleLine;
    function isMultiline(line) {
      return /^\d\d\d-/.test(line);
    }
    exports2.isMultiline = isMultiline;
    function positiveCompletion(code) {
      return code >= 200 && code < 300;
    }
    exports2.positiveCompletion = positiveCompletion;
    function positiveIntermediate(code) {
      return code >= 300 && code < 400;
    }
    exports2.positiveIntermediate = positiveIntermediate;
    function isNotBlank(str) {
      return str.trim() !== "";
    }
  }
});

// ../../node_modules/.pnpm/basic-ftp@5.0.5/node_modules/basic-ftp/dist/FtpContext.js
var require_FtpContext = __commonJS({
  "../../node_modules/.pnpm/basic-ftp@5.0.5/node_modules/basic-ftp/dist/FtpContext.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.FTPContext = exports2.FTPError = void 0;
    var net_1 = require("net");
    var parseControlResponse_1 = require_parseControlResponse();
    var FTPError = class extends Error {
      constructor(res) {
        super(res.message);
        this.name = this.constructor.name;
        this.code = res.code;
      }
    };
    exports2.FTPError = FTPError;
    function doNothing() {
    }
    var FTPContext = class {
      /**
       * Instantiate an FTP context.
       *
       * @param timeout - Timeout in milliseconds to apply to control and data connections. Use 0 for no timeout.
       * @param encoding - Encoding to use for control connection. UTF-8 by default. Use "latin1" for older servers.
       */
      constructor(timeout = 0, encoding = "utf8") {
        this.timeout = timeout;
        this.verbose = false;
        this.ipFamily = void 0;
        this.tlsOptions = {};
        this._partialResponse = "";
        this._encoding = encoding;
        this._socket = this.socket = this._newSocket();
        this._dataSocket = void 0;
      }
      /**
       * Close the context.
       */
      close() {
        const message = this._task ? "User closed client during task" : "User closed client";
        const err = new Error(message);
        this.closeWithError(err);
      }
      /**
       * Close the context with an error.
       */
      closeWithError(err) {
        if (this._closingError) {
          return;
        }
        this._closingError = err;
        this._closeControlSocket();
        this._closeSocket(this._dataSocket);
        this._passToHandler(err);
        this._stopTrackingTask();
      }
      /**
       * Returns true if this context has been closed or hasn't been connected yet. You can reopen it with `access`.
       */
      get closed() {
        return this.socket.remoteAddress === void 0 || this._closingError !== void 0;
      }
      /**
       * Reset this contex and all of its state.
       */
      reset() {
        this.socket = this._newSocket();
      }
      /**
       * Get the FTP control socket.
       */
      get socket() {
        return this._socket;
      }
      /**
       * Set the socket for the control connection. This will only close the current control socket
       * if the new one is not an upgrade to the current one.
       */
      set socket(socket) {
        this.dataSocket = void 0;
        this.tlsOptions = {};
        this._partialResponse = "";
        if (this._socket) {
          const newSocketUpgradesExisting = socket.localPort === this._socket.localPort;
          if (newSocketUpgradesExisting) {
            this._removeSocketListeners(this.socket);
          } else {
            this._closeControlSocket();
          }
        }
        if (socket) {
          this._closingError = void 0;
          socket.setTimeout(0);
          socket.setEncoding(this._encoding);
          socket.setKeepAlive(true);
          socket.on("data", (data) => this._onControlSocketData(data));
          socket.on("end", () => this.closeWithError(new Error("Server sent FIN packet unexpectedly, closing connection.")));
          socket.on("close", (hadError) => {
            if (!hadError)
              this.closeWithError(new Error("Server closed connection unexpectedly."));
          });
          this._setupDefaultErrorHandlers(socket, "control socket");
        }
        this._socket = socket;
      }
      /**
       * Get the current FTP data connection if present.
       */
      get dataSocket() {
        return this._dataSocket;
      }
      /**
       * Set the socket for the data connection. This will automatically close the former data socket.
       */
      set dataSocket(socket) {
        this._closeSocket(this._dataSocket);
        if (socket) {
          socket.setTimeout(0);
          this._setupDefaultErrorHandlers(socket, "data socket");
        }
        this._dataSocket = socket;
      }
      /**
       * Get the currently used encoding.
       */
      get encoding() {
        return this._encoding;
      }
      /**
       * Set the encoding used for the control socket.
       *
       * See https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings for what encodings
       * are supported by Node.
       */
      set encoding(encoding) {
        this._encoding = encoding;
        if (this.socket) {
          this.socket.setEncoding(encoding);
        }
      }
      /**
       * Send an FTP command without waiting for or handling the result.
       */
      send(command) {
        const containsPassword = command.startsWith("PASS");
        const message = containsPassword ? "> PASS ###" : `> ${command}`;
        this.log(message);
        this._socket.write(command + "\r\n", this.encoding);
      }
      /**
       * Send an FTP command and handle the first response. Use this if you have a simple
       * request-response situation.
       */
      request(command) {
        return this.handle(command, (res, task) => {
          if (res instanceof Error) {
            task.reject(res);
          } else {
            task.resolve(res);
          }
        });
      }
      /**
       * Send an FTP command and handle any response until you resolve/reject. Use this if you expect multiple responses
       * to a request. This returns a Promise that will hold whatever the response handler passed on when resolving/rejecting its task.
       */
      handle(command, responseHandler) {
        if (this._task) {
          const err = new Error("User launched a task while another one is still running. Forgot to use 'await' or '.then()'?");
          err.stack += `
Running task launched at: ${this._task.stack}`;
          this.closeWithError(err);
        }
        return new Promise((resolveTask, rejectTask) => {
          this._task = {
            stack: new Error().stack || "Unknown call stack",
            responseHandler,
            resolver: {
              resolve: (arg) => {
                this._stopTrackingTask();
                resolveTask(arg);
              },
              reject: (err) => {
                this._stopTrackingTask();
                rejectTask(err);
              }
            }
          };
          if (this._closingError) {
            const err = new Error(`Client is closed because ${this._closingError.message}`);
            err.stack += `
Closing reason: ${this._closingError.stack}`;
            err.code = this._closingError.code !== void 0 ? this._closingError.code : "0";
            this._passToHandler(err);
            return;
          }
          this.socket.setTimeout(this.timeout);
          if (command) {
            this.send(command);
          }
        });
      }
      /**
       * Log message if set to be verbose.
       */
      log(message) {
        if (this.verbose) {
          console.log(message);
        }
      }
      /**
       * Return true if the control socket is using TLS. This does not mean that a session
       * has already been negotiated.
       */
      get hasTLS() {
        return "encrypted" in this._socket;
      }
      /**
       * Removes reference to current task and handler. This won't resolve or reject the task.
       * @protected
       */
      _stopTrackingTask() {
        this.socket.setTimeout(0);
        this._task = void 0;
      }
      /**
       * Handle incoming data on the control socket. The chunk is going to be of type `string`
       * because we let `socket` handle encoding with `setEncoding`.
       * @protected
       */
      _onControlSocketData(chunk) {
        this.log(`< ${chunk}`);
        const completeResponse = this._partialResponse + chunk;
        const parsed = (0, parseControlResponse_1.parseControlResponse)(completeResponse);
        this._partialResponse = parsed.rest;
        for (const message of parsed.messages) {
          const code = parseInt(message.substr(0, 3), 10);
          const response = { code, message };
          const err = code >= 400 ? new FTPError(response) : void 0;
          this._passToHandler(err ? err : response);
        }
      }
      /**
       * Send the current handler a response. This is usually a control socket response
       * or a socket event, like an error or timeout.
       * @protected
       */
      _passToHandler(response) {
        if (this._task) {
          this._task.responseHandler(response, this._task.resolver);
        }
      }
      /**
       * Setup all error handlers for a socket.
       * @protected
       */
      _setupDefaultErrorHandlers(socket, identifier) {
        socket.once("error", (error101) => {
          error101.message += ` (${identifier})`;
          this.closeWithError(error101);
        });
        socket.once("close", (hadError) => {
          if (hadError) {
            this.closeWithError(new Error(`Socket closed due to transmission error (${identifier})`));
          }
        });
        socket.once("timeout", () => {
          socket.destroy();
          this.closeWithError(new Error(`Timeout (${identifier})`));
        });
      }
      /**
       * Close the control socket. Sends QUIT, then FIN, and ignores any response or error.
       */
      _closeControlSocket() {
        this._removeSocketListeners(this._socket);
        this._socket.on("error", doNothing);
        this.send("QUIT");
        this._closeSocket(this._socket);
      }
      /**
       * Close a socket, ignores any error.
       * @protected
       */
      _closeSocket(socket) {
        if (socket) {
          this._removeSocketListeners(socket);
          socket.on("error", doNothing);
          socket.destroy();
        }
      }
      /**
       * Remove all default listeners for socket.
       * @protected
       */
      _removeSocketListeners(socket) {
        socket.removeAllListeners();
        socket.removeAllListeners("timeout");
        socket.removeAllListeners("data");
        socket.removeAllListeners("end");
        socket.removeAllListeners("error");
        socket.removeAllListeners("close");
        socket.removeAllListeners("connect");
      }
      /**
       * Provide a new socket instance.
       *
       * Internal use only, replaced for unit tests.
       */
      _newSocket() {
        return new net_1.Socket();
      }
    };
    exports2.FTPContext = FTPContext;
  }
});

// ../../node_modules/.pnpm/basic-ftp@5.0.5/node_modules/basic-ftp/dist/FileInfo.js
var require_FileInfo = __commonJS({
  "../../node_modules/.pnpm/basic-ftp@5.0.5/node_modules/basic-ftp/dist/FileInfo.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.FileInfo = exports2.FileType = void 0;
    var FileType;
    (function(FileType2) {
      FileType2[FileType2["Unknown"] = 0] = "Unknown";
      FileType2[FileType2["File"] = 1] = "File";
      FileType2[FileType2["Directory"] = 2] = "Directory";
      FileType2[FileType2["SymbolicLink"] = 3] = "SymbolicLink";
    })(FileType || (exports2.FileType = FileType = {}));
    var FileInfo = class {
      constructor(name) {
        this.name = name;
        this.type = FileType.Unknown;
        this.size = 0;
        this.rawModifiedAt = "";
        this.modifiedAt = void 0;
        this.permissions = void 0;
        this.hardLinkCount = void 0;
        this.link = void 0;
        this.group = void 0;
        this.user = void 0;
        this.uniqueID = void 0;
        this.name = name;
      }
      get isDirectory() {
        return this.type === FileType.Directory;
      }
      get isSymbolicLink() {
        return this.type === FileType.SymbolicLink;
      }
      get isFile() {
        return this.type === FileType.File;
      }
      /**
       * Deprecated, legacy API. Use `rawModifiedAt` instead.
       * @deprecated
       */
      get date() {
        return this.rawModifiedAt;
      }
      set date(rawModifiedAt) {
        this.rawModifiedAt = rawModifiedAt;
      }
    };
    exports2.FileInfo = FileInfo;
    FileInfo.UnixPermission = {
      Read: 4,
      Write: 2,
      Execute: 1
    };
  }
});

// ../../node_modules/.pnpm/basic-ftp@5.0.5/node_modules/basic-ftp/dist/parseListDOS.js
var require_parseListDOS = __commonJS({
  "../../node_modules/.pnpm/basic-ftp@5.0.5/node_modules/basic-ftp/dist/parseListDOS.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.transformList = exports2.parseLine = exports2.testLine = void 0;
    var FileInfo_1 = require_FileInfo();
    var RE_LINE = new RegExp(
      "(\\S+)\\s+(\\S+)\\s+(?:(<DIR>)|([0-9]+))\\s+(\\S.*)"
      // First non-space followed by rest of line (name)
    );
    function testLine(line) {
      return /^\d{2}/.test(line) && RE_LINE.test(line);
    }
    exports2.testLine = testLine;
    function parseLine(line) {
      const groups = line.match(RE_LINE);
      if (groups === null) {
        return void 0;
      }
      const name = groups[5];
      if (name === "." || name === "..") {
        return void 0;
      }
      const file5 = new FileInfo_1.FileInfo(name);
      const fileType = groups[3];
      if (fileType === "<DIR>") {
        file5.type = FileInfo_1.FileType.Directory;
        file5.size = 0;
      } else {
        file5.type = FileInfo_1.FileType.File;
        file5.size = parseInt(groups[4], 10);
      }
      file5.rawModifiedAt = groups[1] + " " + groups[2];
      return file5;
    }
    exports2.parseLine = parseLine;
    function transformList(files) {
      return files;
    }
    exports2.transformList = transformList;
  }
});

// ../../node_modules/.pnpm/basic-ftp@5.0.5/node_modules/basic-ftp/dist/parseListUnix.js
var require_parseListUnix = __commonJS({
  "../../node_modules/.pnpm/basic-ftp@5.0.5/node_modules/basic-ftp/dist/parseListUnix.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.transformList = exports2.parseLine = exports2.testLine = void 0;
    var FileInfo_1 = require_FileInfo();
    var JA_MONTH = "\u6708";
    var JA_DAY = "\u65E5";
    var JA_YEAR = "\u5E74";
    var RE_LINE = new RegExp("([bcdelfmpSs-])(((r|-)(w|-)([xsStTL-]))((r|-)(w|-)([xsStTL-]))((r|-)(w|-)([xsStTL-]?)))\\+?\\s*(\\d+)\\s+(?:(\\S+(?:\\s\\S+)*?)\\s+)?(?:(\\S+(?:\\s\\S+)*)\\s+)?(\\d+(?:,\\s*\\d+)?)\\s+((?:\\d+[-/]\\d+[-/]\\d+)|(?:\\S{3}\\s+\\d{1,2})|(?:\\d{1,2}\\s+\\S{3})|(?:\\d{1,2}" + JA_MONTH + "\\s+\\d{1,2}" + JA_DAY + "))\\s+((?:\\d+(?::\\d+)?)|(?:\\d{4}" + JA_YEAR + "))\\s(.*)");
    function testLine(line) {
      return RE_LINE.test(line);
    }
    exports2.testLine = testLine;
    function parseLine(line) {
      const groups = line.match(RE_LINE);
      if (groups === null) {
        return void 0;
      }
      const name = groups[21];
      if (name === "." || name === "..") {
        return void 0;
      }
      const file5 = new FileInfo_1.FileInfo(name);
      file5.size = parseInt(groups[18], 10);
      file5.user = groups[16];
      file5.group = groups[17];
      file5.hardLinkCount = parseInt(groups[15], 10);
      file5.rawModifiedAt = groups[19] + " " + groups[20];
      file5.permissions = {
        user: parseMode(groups[4], groups[5], groups[6]),
        group: parseMode(groups[8], groups[9], groups[10]),
        world: parseMode(groups[12], groups[13], groups[14])
      };
      switch (groups[1].charAt(0)) {
        case "d":
          file5.type = FileInfo_1.FileType.Directory;
          break;
        case "e":
          file5.type = FileInfo_1.FileType.SymbolicLink;
          break;
        case "l":
          file5.type = FileInfo_1.FileType.SymbolicLink;
          break;
        case "b":
        case "c":
          file5.type = FileInfo_1.FileType.File;
          break;
        case "f":
        case "-":
          file5.type = FileInfo_1.FileType.File;
          break;
        default:
          file5.type = FileInfo_1.FileType.Unknown;
      }
      if (file5.isSymbolicLink) {
        const end = name.indexOf(" -> ");
        if (end !== -1) {
          file5.name = name.substring(0, end);
          file5.link = name.substring(end + 4);
        }
      }
      return file5;
    }
    exports2.parseLine = parseLine;
    function transformList(files) {
      return files;
    }
    exports2.transformList = transformList;
    function parseMode(r, w, x) {
      let value = 0;
      if (r !== "-") {
        value += FileInfo_1.FileInfo.UnixPermission.Read;
      }
      if (w !== "-") {
        value += FileInfo_1.FileInfo.UnixPermission.Write;
      }
      const execToken = x.charAt(0);
      if (execToken !== "-" && execToken.toUpperCase() !== execToken) {
        value += FileInfo_1.FileInfo.UnixPermission.Execute;
      }
      return value;
    }
  }
});

// ../../node_modules/.pnpm/basic-ftp@5.0.5/node_modules/basic-ftp/dist/parseListMLSD.js
var require_parseListMLSD = __commonJS({
  "../../node_modules/.pnpm/basic-ftp@5.0.5/node_modules/basic-ftp/dist/parseListMLSD.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.parseMLSxDate = exports2.transformList = exports2.parseLine = exports2.testLine = void 0;
    var FileInfo_1 = require_FileInfo();
    function parseSize(value, info) {
      info.size = parseInt(value, 10);
    }
    var factHandlersByName = {
      "size": parseSize,
      // File size
      "sizd": parseSize,
      // Directory size
      "unique": (value, info) => {
        info.uniqueID = value;
      },
      "modify": (value, info) => {
        info.modifiedAt = parseMLSxDate(value);
        info.rawModifiedAt = info.modifiedAt.toISOString();
      },
      "type": (value, info) => {
        if (value.startsWith("OS.unix=slink")) {
          info.type = FileInfo_1.FileType.SymbolicLink;
          info.link = value.substr(value.indexOf(":") + 1);
          return 1;
        }
        switch (value) {
          case "file":
            info.type = FileInfo_1.FileType.File;
            break;
          case "dir":
            info.type = FileInfo_1.FileType.Directory;
            break;
          case "OS.unix=symlink":
            info.type = FileInfo_1.FileType.SymbolicLink;
            break;
          case "cdir":
          // Current directory being listed
          case "pdir":
            return 2;
          // Don't include these entries in the listing
          default:
            info.type = FileInfo_1.FileType.Unknown;
        }
        return 1;
      },
      "unix.mode": (value, info) => {
        const digits = value.substr(-3);
        info.permissions = {
          user: parseInt(digits[0], 10),
          group: parseInt(digits[1], 10),
          world: parseInt(digits[2], 10)
        };
      },
      "unix.ownername": (value, info) => {
        info.user = value;
      },
      "unix.owner": (value, info) => {
        if (info.user === void 0)
          info.user = value;
      },
      get "unix.uid"() {
        return this["unix.owner"];
      },
      "unix.groupname": (value, info) => {
        info.group = value;
      },
      "unix.group": (value, info) => {
        if (info.group === void 0)
          info.group = value;
      },
      get "unix.gid"() {
        return this["unix.group"];
      }
      // Regarding the fact "perm":
      // We don't handle permission information stored in "perm" because its information is conceptually
      // different from what users of FTP clients usually associate with "permissions". Those that have
      // some expectations (and probably want to edit them with a SITE command) often unknowingly expect
      // the Unix permission system. The information passed by "perm" describes what FTP commands can be
      // executed with a file/directory. But even this can be either incomplete or just meant as a "guide"
      // as the spec mentions. From https://tools.ietf.org/html/rfc3659#section-7.5.5: "The permissions are
      // described here as they apply to FTP commands. They may not map easily into particular permissions
      // available on the server's operating system." The parser by Apache Commons tries to translate these
      // to Unix permissions – this is misleading users and might not even be correct.
    };
    function splitStringOnce(str, delimiter) {
      const pos = str.indexOf(delimiter);
      const a = str.substr(0, pos);
      const b = str.substr(pos + delimiter.length);
      return [a, b];
    }
    function testLine(line) {
      return /^\S+=\S+;/.test(line) || line.startsWith(" ");
    }
    exports2.testLine = testLine;
    function parseLine(line) {
      const [packedFacts, name] = splitStringOnce(line, " ");
      if (name === "" || name === "." || name === "..") {
        return void 0;
      }
      const info = new FileInfo_1.FileInfo(name);
      const facts = packedFacts.split(";");
      for (const fact of facts) {
        const [factName, factValue] = splitStringOnce(fact, "=");
        if (!factValue) {
          continue;
        }
        const factHandler = factHandlersByName[factName.toLowerCase()];
        if (!factHandler) {
          continue;
        }
        const result = factHandler(factValue, info);
        if (result === 2) {
          return void 0;
        }
      }
      return info;
    }
    exports2.parseLine = parseLine;
    function transformList(files) {
      const nonLinksByID = /* @__PURE__ */ new Map();
      for (const file5 of files) {
        if (!file5.isSymbolicLink && file5.uniqueID !== void 0) {
          nonLinksByID.set(file5.uniqueID, file5);
        }
      }
      const resolvedFiles = [];
      for (const file5 of files) {
        if (file5.isSymbolicLink && file5.uniqueID !== void 0 && file5.link === void 0) {
          const target = nonLinksByID.get(file5.uniqueID);
          if (target !== void 0) {
            file5.link = target.name;
          }
        }
        const isPartOfDirectory = !file5.name.includes("/");
        if (isPartOfDirectory) {
          resolvedFiles.push(file5);
        }
      }
      return resolvedFiles;
    }
    exports2.transformList = transformList;
    function parseMLSxDate(fact) {
      return new Date(Date.UTC(
        +fact.slice(0, 4),
        // Year
        +fact.slice(4, 6) - 1,
        // Month
        +fact.slice(6, 8),
        // Date
        +fact.slice(8, 10),
        // Hours
        +fact.slice(10, 12),
        // Minutes
        +fact.slice(12, 14),
        // Seconds
        +fact.slice(15, 18)
        // Milliseconds
      ));
    }
    exports2.parseMLSxDate = parseMLSxDate;
  }
});

// ../../node_modules/.pnpm/basic-ftp@5.0.5/node_modules/basic-ftp/dist/parseList.js
var require_parseList = __commonJS({
  "../../node_modules/.pnpm/basic-ftp@5.0.5/node_modules/basic-ftp/dist/parseList.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding2(result, mod, k);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.parseList = void 0;
    var dosParser = __importStar2(require_parseListDOS());
    var unixParser = __importStar2(require_parseListUnix());
    var mlsdParser = __importStar2(require_parseListMLSD());
    var availableParsers = [
      dosParser,
      unixParser,
      mlsdParser
      // Keep MLSD last, may accept filename only
    ];
    function firstCompatibleParser(line, parsers) {
      return parsers.find((parser) => parser.testLine(line) === true);
    }
    function isNotBlank(str) {
      return str.trim() !== "";
    }
    function isNotMeta(str) {
      return !str.startsWith("total");
    }
    var REGEX_NEWLINE = /\r?\n/;
    function parseList(rawList) {
      const lines = rawList.split(REGEX_NEWLINE).filter(isNotBlank).filter(isNotMeta);
      if (lines.length === 0) {
        return [];
      }
      const testLine = lines[lines.length - 1];
      const parser = firstCompatibleParser(testLine, availableParsers);
      if (!parser) {
        throw new Error("This library only supports MLSD, Unix- or DOS-style directory listing. Your FTP server seems to be using another format. You can see the transmitted listing when setting `client.ftp.verbose = true`. You can then provide a custom parser to `client.parseList`, see the documentation for details.");
      }
      const files = lines.map(parser.parseLine).filter((info) => info !== void 0);
      return parser.transformList(files);
    }
    exports2.parseList = parseList;
  }
});

// ../../node_modules/.pnpm/basic-ftp@5.0.5/node_modules/basic-ftp/dist/ProgressTracker.js
var require_ProgressTracker = __commonJS({
  "../../node_modules/.pnpm/basic-ftp@5.0.5/node_modules/basic-ftp/dist/ProgressTracker.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ProgressTracker = void 0;
    var ProgressTracker = class {
      constructor() {
        this.bytesOverall = 0;
        this.intervalMs = 500;
        this.onStop = noop;
        this.onHandle = noop;
      }
      /**
       * Register a new handler for progress info. Use `undefined` to disable reporting.
       */
      reportTo(onHandle = noop) {
        this.onHandle = onHandle;
      }
      /**
       * Start tracking transfer progress of a socket.
       *
       * @param socket  The socket to observe.
       * @param name  A name associated with this progress tracking, e.g. a filename.
       * @param type  The type of the transfer, typically "upload" or "download".
       */
      start(socket, name, type) {
        let lastBytes = 0;
        this.onStop = poll(this.intervalMs, () => {
          const bytes = socket.bytesRead + socket.bytesWritten;
          this.bytesOverall += bytes - lastBytes;
          lastBytes = bytes;
          this.onHandle({
            name,
            type,
            bytes,
            bytesOverall: this.bytesOverall
          });
        });
      }
      /**
       * Stop tracking transfer progress.
       */
      stop() {
        this.onStop(false);
      }
      /**
       * Call the progress handler one more time, then stop tracking.
       */
      updateAndStop() {
        this.onStop(true);
      }
    };
    exports2.ProgressTracker = ProgressTracker;
    function poll(intervalMs, updateFunc) {
      const id = setInterval(updateFunc, intervalMs);
      const stopFunc = (stopWithUpdate) => {
        clearInterval(id);
        if (stopWithUpdate) {
          updateFunc();
        }
        updateFunc = noop;
      };
      updateFunc();
      return stopFunc;
    }
    function noop() {
    }
  }
});

// ../../node_modules/.pnpm/basic-ftp@5.0.5/node_modules/basic-ftp/dist/StringWriter.js
var require_StringWriter = __commonJS({
  "../../node_modules/.pnpm/basic-ftp@5.0.5/node_modules/basic-ftp/dist/StringWriter.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.StringWriter = void 0;
    var stream_1 = require("stream");
    var StringWriter = class extends stream_1.Writable {
      constructor() {
        super(...arguments);
        this.buf = Buffer.alloc(0);
      }
      _write(chunk, _, callback) {
        if (chunk instanceof Buffer) {
          this.buf = Buffer.concat([this.buf, chunk]);
          callback(null);
        } else {
          callback(new Error("StringWriter expects chunks of type 'Buffer'."));
        }
      }
      getText(encoding) {
        return this.buf.toString(encoding);
      }
    };
    exports2.StringWriter = StringWriter;
  }
});

// ../../node_modules/.pnpm/basic-ftp@5.0.5/node_modules/basic-ftp/dist/netUtils.js
var require_netUtils = __commonJS({
  "../../node_modules/.pnpm/basic-ftp@5.0.5/node_modules/basic-ftp/dist/netUtils.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ipIsPrivateV4Address = exports2.upgradeSocket = exports2.describeAddress = exports2.describeTLS = void 0;
    var tls_1 = require("tls");
    function describeTLS(socket) {
      if (socket instanceof tls_1.TLSSocket) {
        const protocol = socket.getProtocol();
        return protocol ? protocol : "Server socket or disconnected client socket";
      }
      return "No encryption";
    }
    exports2.describeTLS = describeTLS;
    function describeAddress(socket) {
      if (socket.remoteFamily === "IPv6") {
        return `[${socket.remoteAddress}]:${socket.remotePort}`;
      }
      return `${socket.remoteAddress}:${socket.remotePort}`;
    }
    exports2.describeAddress = describeAddress;
    function upgradeSocket(socket, options) {
      return new Promise((resolve8, reject) => {
        const tlsOptions = Object.assign({}, options, {
          socket
        });
        const tlsSocket = (0, tls_1.connect)(tlsOptions, () => {
          const expectCertificate = tlsOptions.rejectUnauthorized !== false;
          if (expectCertificate && !tlsSocket.authorized) {
            reject(tlsSocket.authorizationError);
          } else {
            tlsSocket.removeAllListeners("error");
            resolve8(tlsSocket);
          }
        }).once("error", (error101) => {
          reject(error101);
        });
      });
    }
    exports2.upgradeSocket = upgradeSocket;
    function ipIsPrivateV4Address(ip = "") {
      if (ip.startsWith("::ffff:")) {
        ip = ip.substr(7);
      }
      const octets = ip.split(".").map((o) => parseInt(o, 10));
      return octets[0] === 10 || octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31 || octets[0] === 192 && octets[1] === 168 || ip === "127.0.0.1";
    }
    exports2.ipIsPrivateV4Address = ipIsPrivateV4Address;
  }
});

// ../../node_modules/.pnpm/basic-ftp@5.0.5/node_modules/basic-ftp/dist/transfer.js
var require_transfer = __commonJS({
  "../../node_modules/.pnpm/basic-ftp@5.0.5/node_modules/basic-ftp/dist/transfer.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.downloadTo = exports2.uploadFrom = exports2.connectForPassiveTransfer = exports2.parsePasvResponse = exports2.enterPassiveModeIPv4 = exports2.parseEpsvResponse = exports2.enterPassiveModeIPv6 = void 0;
    var netUtils_1 = require_netUtils();
    var stream_1 = require("stream");
    var tls_1 = require("tls");
    var parseControlResponse_1 = require_parseControlResponse();
    async function enterPassiveModeIPv6(ftp) {
      const res = await ftp.request("EPSV");
      const port = parseEpsvResponse(res.message);
      if (!port) {
        throw new Error("Can't parse EPSV response: " + res.message);
      }
      const controlHost = ftp.socket.remoteAddress;
      if (controlHost === void 0) {
        throw new Error("Control socket is disconnected, can't get remote address.");
      }
      await connectForPassiveTransfer(controlHost, port, ftp);
      return res;
    }
    exports2.enterPassiveModeIPv6 = enterPassiveModeIPv6;
    function parseEpsvResponse(message) {
      const groups = message.match(/[|!]{3}(.+)[|!]/);
      if (groups === null || groups[1] === void 0) {
        throw new Error(`Can't parse response to 'EPSV': ${message}`);
      }
      const port = parseInt(groups[1], 10);
      if (Number.isNaN(port)) {
        throw new Error(`Can't parse response to 'EPSV', port is not a number: ${message}`);
      }
      return port;
    }
    exports2.parseEpsvResponse = parseEpsvResponse;
    async function enterPassiveModeIPv4(ftp) {
      const res = await ftp.request("PASV");
      const target = parsePasvResponse(res.message);
      if (!target) {
        throw new Error("Can't parse PASV response: " + res.message);
      }
      const controlHost = ftp.socket.remoteAddress;
      if ((0, netUtils_1.ipIsPrivateV4Address)(target.host) && controlHost && !(0, netUtils_1.ipIsPrivateV4Address)(controlHost)) {
        target.host = controlHost;
      }
      await connectForPassiveTransfer(target.host, target.port, ftp);
      return res;
    }
    exports2.enterPassiveModeIPv4 = enterPassiveModeIPv4;
    function parsePasvResponse(message) {
      const groups = message.match(/([-\d]+,[-\d]+,[-\d]+,[-\d]+),([-\d]+),([-\d]+)/);
      if (groups === null || groups.length !== 4) {
        throw new Error(`Can't parse response to 'PASV': ${message}`);
      }
      return {
        host: groups[1].replace(/,/g, "."),
        port: (parseInt(groups[2], 10) & 255) * 256 + (parseInt(groups[3], 10) & 255)
      };
    }
    exports2.parsePasvResponse = parsePasvResponse;
    function connectForPassiveTransfer(host, port, ftp) {
      return new Promise((resolve8, reject) => {
        let socket = ftp._newSocket();
        const handleConnErr = function(err) {
          err.message = "Can't open data connection in passive mode: " + err.message;
          reject(err);
        };
        const handleTimeout = function() {
          socket.destroy();
          reject(new Error(`Timeout when trying to open data connection to ${host}:${port}`));
        };
        socket.setTimeout(ftp.timeout);
        socket.on("error", handleConnErr);
        socket.on("timeout", handleTimeout);
        socket.connect({ port, host, family: ftp.ipFamily }, () => {
          if (ftp.socket instanceof tls_1.TLSSocket) {
            socket = (0, tls_1.connect)(Object.assign({}, ftp.tlsOptions, {
              socket,
              // Reuse the TLS session negotiated earlier when the control connection
              // was upgraded. Servers expect this because it provides additional
              // security: If a completely new session would be negotiated, a hacker
              // could guess the port and connect to the new data connection before we do
              // by just starting his/her own TLS session.
              session: ftp.socket.getSession()
            }));
          }
          socket.removeListener("error", handleConnErr);
          socket.removeListener("timeout", handleTimeout);
          ftp.dataSocket = socket;
          resolve8();
        });
      });
    }
    exports2.connectForPassiveTransfer = connectForPassiveTransfer;
    var TransferResolver = class {
      /**
       * Instantiate a TransferResolver
       */
      constructor(ftp, progress) {
        this.ftp = ftp;
        this.progress = progress;
        this.response = void 0;
        this.dataTransferDone = false;
      }
      /**
       * Mark the beginning of a transfer.
       *
       * @param name - Name of the transfer, usually the filename.
       * @param type - Type of transfer, usually "upload" or "download".
       */
      onDataStart(name, type) {
        if (this.ftp.dataSocket === void 0) {
          throw new Error("Data transfer should start but there is no data connection.");
        }
        this.ftp.socket.setTimeout(0);
        this.ftp.dataSocket.setTimeout(this.ftp.timeout);
        this.progress.start(this.ftp.dataSocket, name, type);
      }
      /**
       * The data connection has finished the transfer.
       */
      onDataDone(task) {
        this.progress.updateAndStop();
        this.ftp.socket.setTimeout(this.ftp.timeout);
        if (this.ftp.dataSocket) {
          this.ftp.dataSocket.setTimeout(0);
        }
        this.dataTransferDone = true;
        this.tryResolve(task);
      }
      /**
       * The control connection reports the transfer as finished.
       */
      onControlDone(task, response) {
        this.response = response;
        this.tryResolve(task);
      }
      /**
       * An error has been reported and the task should be rejected.
       */
      onError(task, err) {
        this.progress.updateAndStop();
        this.ftp.socket.setTimeout(this.ftp.timeout);
        this.ftp.dataSocket = void 0;
        task.reject(err);
      }
      /**
       * Control connection sent an unexpected request requiring a response from our part. We
       * can't provide that (because unknown) and have to close the contrext with an error because
       * the FTP server is now caught up in a state we can't resolve.
       */
      onUnexpectedRequest(response) {
        const err = new Error(`Unexpected FTP response is requesting an answer: ${response.message}`);
        this.ftp.closeWithError(err);
      }
      tryResolve(task) {
        const canResolve = this.dataTransferDone && this.response !== void 0;
        if (canResolve) {
          this.ftp.dataSocket = void 0;
          task.resolve(this.response);
        }
      }
    };
    function uploadFrom(source, config3) {
      const resolver = new TransferResolver(config3.ftp, config3.tracker);
      const fullCommand = `${config3.command} ${config3.remotePath}`;
      return config3.ftp.handle(fullCommand, (res, task) => {
        if (res instanceof Error) {
          resolver.onError(task, res);
        } else if (res.code === 150 || res.code === 125) {
          const dataSocket = config3.ftp.dataSocket;
          if (!dataSocket) {
            resolver.onError(task, new Error("Upload should begin but no data connection is available."));
            return;
          }
          const canUpload = "getCipher" in dataSocket ? dataSocket.getCipher() !== void 0 : true;
          onConditionOrEvent(canUpload, dataSocket, "secureConnect", () => {
            config3.ftp.log(`Uploading to ${(0, netUtils_1.describeAddress)(dataSocket)} (${(0, netUtils_1.describeTLS)(dataSocket)})`);
            resolver.onDataStart(config3.remotePath, config3.type);
            (0, stream_1.pipeline)(source, dataSocket, (err) => {
              if (err) {
                resolver.onError(task, err);
              } else {
                resolver.onDataDone(task);
              }
            });
          });
        } else if ((0, parseControlResponse_1.positiveCompletion)(res.code)) {
          resolver.onControlDone(task, res);
        } else if ((0, parseControlResponse_1.positiveIntermediate)(res.code)) {
          resolver.onUnexpectedRequest(res);
        }
      });
    }
    exports2.uploadFrom = uploadFrom;
    function downloadTo(destination, config3) {
      if (!config3.ftp.dataSocket) {
        throw new Error("Download will be initiated but no data connection is available.");
      }
      const resolver = new TransferResolver(config3.ftp, config3.tracker);
      return config3.ftp.handle(config3.command, (res, task) => {
        if (res instanceof Error) {
          resolver.onError(task, res);
        } else if (res.code === 150 || res.code === 125) {
          const dataSocket = config3.ftp.dataSocket;
          if (!dataSocket) {
            resolver.onError(task, new Error("Download should begin but no data connection is available."));
            return;
          }
          config3.ftp.log(`Downloading from ${(0, netUtils_1.describeAddress)(dataSocket)} (${(0, netUtils_1.describeTLS)(dataSocket)})`);
          resolver.onDataStart(config3.remotePath, config3.type);
          (0, stream_1.pipeline)(dataSocket, destination, (err) => {
            if (err) {
              resolver.onError(task, err);
            } else {
              resolver.onDataDone(task);
            }
          });
        } else if (res.code === 350) {
          config3.ftp.send("RETR " + config3.remotePath);
        } else if ((0, parseControlResponse_1.positiveCompletion)(res.code)) {
          resolver.onControlDone(task, res);
        } else if ((0, parseControlResponse_1.positiveIntermediate)(res.code)) {
          resolver.onUnexpectedRequest(res);
        }
      });
    }
    exports2.downloadTo = downloadTo;
    function onConditionOrEvent(condition, emitter, eventName, action) {
      if (condition === true) {
        action();
      } else {
        emitter.once(eventName, () => action());
      }
    }
  }
});

// ../../node_modules/.pnpm/basic-ftp@5.0.5/node_modules/basic-ftp/dist/Client.js
var require_Client = __commonJS({
  "../../node_modules/.pnpm/basic-ftp@5.0.5/node_modules/basic-ftp/dist/Client.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Client = void 0;
    var fs_1 = require("fs");
    var path_1 = require("path");
    var tls_1 = require("tls");
    var util_1 = require("util");
    var FtpContext_1 = require_FtpContext();
    var parseList_1 = require_parseList();
    var ProgressTracker_1 = require_ProgressTracker();
    var StringWriter_1 = require_StringWriter();
    var parseListMLSD_1 = require_parseListMLSD();
    var netUtils_1 = require_netUtils();
    var transfer_1 = require_transfer();
    var parseControlResponse_1 = require_parseControlResponse();
    var fsReadDir = (0, util_1.promisify)(fs_1.readdir);
    var fsMkDir = (0, util_1.promisify)(fs_1.mkdir);
    var fsStat = (0, util_1.promisify)(fs_1.stat);
    var fsOpen = (0, util_1.promisify)(fs_1.open);
    var fsClose = (0, util_1.promisify)(fs_1.close);
    var fsUnlink = (0, util_1.promisify)(fs_1.unlink);
    var LIST_COMMANDS_DEFAULT = () => ["LIST -a", "LIST"];
    var LIST_COMMANDS_MLSD = () => ["MLSD", "LIST -a", "LIST"];
    var Client = class {
      /**
       * Instantiate an FTP client.
       *
       * @param timeout  Timeout in milliseconds, use 0 for no timeout. Optional, default is 30 seconds.
       */
      constructor(timeout = 3e4) {
        this.availableListCommands = LIST_COMMANDS_DEFAULT();
        this.ftp = new FtpContext_1.FTPContext(timeout);
        this.prepareTransfer = this._enterFirstCompatibleMode([transfer_1.enterPassiveModeIPv6, transfer_1.enterPassiveModeIPv4]);
        this.parseList = parseList_1.parseList;
        this._progressTracker = new ProgressTracker_1.ProgressTracker();
      }
      /**
       * Close the client and all open socket connections.
       *
       * Close the client and all open socket connections. The client can’t be used anymore after calling this method,
       * you have to either reconnect with `access` or `connect` or instantiate a new instance to continue any work.
       * A client is also closed automatically if any timeout or connection error occurs.
       */
      close() {
        this.ftp.close();
        this._progressTracker.stop();
      }
      /**
       * Returns true if the client is closed and can't be used anymore.
       */
      get closed() {
        return this.ftp.closed;
      }
      /**
       * Connect (or reconnect) to an FTP server.
       *
       * This is an instance method and thus can be called multiple times during the lifecycle of a `Client`
       * instance. Whenever you do, the client is reset with a new control connection. This also implies that
       * you can reopen a `Client` instance that has been closed due to an error when reconnecting with this
       * method. In fact, reconnecting is the only way to continue using a closed `Client`.
       *
       * @param host  Host the client should connect to. Optional, default is "localhost".
       * @param port  Port the client should connect to. Optional, default is 21.
       */
      connect(host = "localhost", port = 21) {
        this.ftp.reset();
        this.ftp.socket.connect({
          host,
          port,
          family: this.ftp.ipFamily
        }, () => this.ftp.log(`Connected to ${(0, netUtils_1.describeAddress)(this.ftp.socket)} (${(0, netUtils_1.describeTLS)(this.ftp.socket)})`));
        return this._handleConnectResponse();
      }
      /**
       * As `connect` but using implicit TLS. Implicit TLS is not an FTP standard and has been replaced by
       * explicit TLS. There are still FTP servers that support only implicit TLS, though.
       */
      connectImplicitTLS(host = "localhost", port = 21, tlsOptions = {}) {
        this.ftp.reset();
        this.ftp.socket = (0, tls_1.connect)(port, host, tlsOptions, () => this.ftp.log(`Connected to ${(0, netUtils_1.describeAddress)(this.ftp.socket)} (${(0, netUtils_1.describeTLS)(this.ftp.socket)})`));
        this.ftp.tlsOptions = tlsOptions;
        return this._handleConnectResponse();
      }
      /**
       * Handles the first reponse by an FTP server after the socket connection has been established.
       */
      _handleConnectResponse() {
        return this.ftp.handle(void 0, (res, task) => {
          if (res instanceof Error) {
            task.reject(res);
          } else if ((0, parseControlResponse_1.positiveCompletion)(res.code)) {
            task.resolve(res);
          } else {
            task.reject(new FtpContext_1.FTPError(res));
          }
        });
      }
      /**
       * Send an FTP command and handle the first response.
       */
      send(command, ignoreErrorCodesDEPRECATED = false) {
        if (ignoreErrorCodesDEPRECATED) {
          this.ftp.log("Deprecated call using send(command, flag) with boolean flag to ignore errors. Use sendIgnoringError(command).");
          return this.sendIgnoringError(command);
        }
        return this.ftp.request(command);
      }
      /**
       * Send an FTP command and ignore an FTP error response. Any other kind of error or timeout will still reject the Promise.
       *
       * @param command
       */
      sendIgnoringError(command) {
        return this.ftp.handle(command, (res, task) => {
          if (res instanceof FtpContext_1.FTPError) {
            task.resolve({ code: res.code, message: res.message });
          } else if (res instanceof Error) {
            task.reject(res);
          } else {
            task.resolve(res);
          }
        });
      }
      /**
       * Upgrade the current socket connection to TLS.
       *
       * @param options  TLS options as in `tls.connect(options)`, optional.
       * @param command  Set the authentication command. Optional, default is "AUTH TLS".
       */
      async useTLS(options = {}, command = "AUTH TLS") {
        const ret = await this.send(command);
        this.ftp.socket = await (0, netUtils_1.upgradeSocket)(this.ftp.socket, options);
        this.ftp.tlsOptions = options;
        this.ftp.log(`Control socket is using: ${(0, netUtils_1.describeTLS)(this.ftp.socket)}`);
        return ret;
      }
      /**
       * Login a user with a password.
       *
       * @param user  Username to use for login. Optional, default is "anonymous".
       * @param password  Password to use for login. Optional, default is "guest".
       */
      login(user = "anonymous", password = "guest") {
        this.ftp.log(`Login security: ${(0, netUtils_1.describeTLS)(this.ftp.socket)}`);
        return this.ftp.handle("USER " + user, (res, task) => {
          if (res instanceof Error) {
            task.reject(res);
          } else if ((0, parseControlResponse_1.positiveCompletion)(res.code)) {
            task.resolve(res);
          } else if (res.code === 331) {
            this.ftp.send("PASS " + password);
          } else {
            task.reject(new FtpContext_1.FTPError(res));
          }
        });
      }
      /**
       * Set the usual default settings.
       *
       * Settings used:
       * * Binary mode (TYPE I)
       * * File structure (STRU F)
       * * Additional settings for FTPS (PBSZ 0, PROT P)
       */
      async useDefaultSettings() {
        const features = await this.features();
        const supportsMLSD = features.has("MLST");
        this.availableListCommands = supportsMLSD ? LIST_COMMANDS_MLSD() : LIST_COMMANDS_DEFAULT();
        await this.send("TYPE I");
        await this.sendIgnoringError("STRU F");
        await this.sendIgnoringError("OPTS UTF8 ON");
        if (supportsMLSD) {
          await this.sendIgnoringError("OPTS MLST type;size;modify;unique;unix.mode;unix.owner;unix.group;unix.ownername;unix.groupname;");
        }
        if (this.ftp.hasTLS) {
          await this.sendIgnoringError("PBSZ 0");
          await this.sendIgnoringError("PROT P");
        }
      }
      /**
       * Convenience method that calls `connect`, `useTLS`, `login` and `useDefaultSettings`.
       *
       * This is an instance method and thus can be called multiple times during the lifecycle of a `Client`
       * instance. Whenever you do, the client is reset with a new control connection. This also implies that
       * you can reopen a `Client` instance that has been closed due to an error when reconnecting with this
       * method. In fact, reconnecting is the only way to continue using a closed `Client`.
       */
      async access(options = {}) {
        var _a5, _b;
        const useExplicitTLS = options.secure === true;
        const useImplicitTLS = options.secure === "implicit";
        let welcome;
        if (useImplicitTLS) {
          welcome = await this.connectImplicitTLS(options.host, options.port, options.secureOptions);
        } else {
          welcome = await this.connect(options.host, options.port);
        }
        if (useExplicitTLS) {
          const secureOptions = (_a5 = options.secureOptions) !== null && _a5 !== void 0 ? _a5 : {};
          secureOptions.host = (_b = secureOptions.host) !== null && _b !== void 0 ? _b : options.host;
          await this.useTLS(secureOptions);
        }
        await this.sendIgnoringError("OPTS UTF8 ON");
        await this.login(options.user, options.password);
        await this.useDefaultSettings();
        return welcome;
      }
      /**
       * Get the current working directory.
       */
      async pwd() {
        const res = await this.send("PWD");
        const parsed = res.message.match(/"(.+)"/);
        if (parsed === null || parsed[1] === void 0) {
          throw new Error(`Can't parse response to command 'PWD': ${res.message}`);
        }
        return parsed[1];
      }
      /**
       * Get a description of supported features.
       *
       * This sends the FEAT command and parses the result into a Map where keys correspond to available commands
       * and values hold further information. Be aware that your FTP servers might not support this
       * command in which case this method will not throw an exception but just return an empty Map.
       */
      async features() {
        const res = await this.sendIgnoringError("FEAT");
        const features = /* @__PURE__ */ new Map();
        if (res.code < 400 && (0, parseControlResponse_1.isMultiline)(res.message)) {
          res.message.split("\n").slice(1, -1).forEach((line) => {
            const entry = line.trim().split(" ");
            features.set(entry[0], entry[1] || "");
          });
        }
        return features;
      }
      /**
       * Set the working directory.
       */
      async cd(path73) {
        const validPath = await this.protectWhitespace(path73);
        return this.send("CWD " + validPath);
      }
      /**
       * Switch to the parent directory of the working directory.
       */
      async cdup() {
        return this.send("CDUP");
      }
      /**
       * Get the last modified time of a file. This is not supported by every FTP server, in which case
       * calling this method will throw an exception.
       */
      async lastMod(path73) {
        const validPath = await this.protectWhitespace(path73);
        const res = await this.send(`MDTM ${validPath}`);
        const date9 = res.message.slice(4);
        return (0, parseListMLSD_1.parseMLSxDate)(date9);
      }
      /**
       * Get the size of a file.
       */
      async size(path73) {
        const validPath = await this.protectWhitespace(path73);
        const command = `SIZE ${validPath}`;
        const res = await this.send(command);
        const size = parseInt(res.message.slice(4), 10);
        if (Number.isNaN(size)) {
          throw new Error(`Can't parse response to command '${command}' as a numerical value: ${res.message}`);
        }
        return size;
      }
      /**
       * Rename a file.
       *
       * Depending on the FTP server this might also be used to move a file from one
       * directory to another by providing full paths.
       */
      async rename(srcPath, destPath) {
        const validSrc = await this.protectWhitespace(srcPath);
        const validDest = await this.protectWhitespace(destPath);
        await this.send("RNFR " + validSrc);
        return this.send("RNTO " + validDest);
      }
      /**
       * Remove a file from the current working directory.
       *
       * You can ignore FTP error return codes which won't throw an exception if e.g.
       * the file doesn't exist.
       */
      async remove(path73, ignoreErrorCodes = false) {
        const validPath = await this.protectWhitespace(path73);
        if (ignoreErrorCodes) {
          return this.sendIgnoringError(`DELE ${validPath}`);
        }
        return this.send(`DELE ${validPath}`);
      }
      /**
       * Report transfer progress for any upload or download to a given handler.
       *
       * This will also reset the overall transfer counter that can be used for multiple transfers. You can
       * also call the function without a handler to stop reporting to an earlier one.
       *
       * @param handler  Handler function to call on transfer progress.
       */
      trackProgress(handler) {
        this._progressTracker.bytesOverall = 0;
        this._progressTracker.reportTo(handler);
      }
      /**
       * Upload data from a readable stream or a local file to a remote file.
       *
       * @param source  Readable stream or path to a local file.
       * @param toRemotePath  Path to a remote file to write to.
       */
      async uploadFrom(source, toRemotePath, options = {}) {
        return this._uploadWithCommand(source, toRemotePath, "STOR", options);
      }
      /**
       * Upload data from a readable stream or a local file by appending it to an existing file. If the file doesn't
       * exist the FTP server should create it.
       *
       * @param source  Readable stream or path to a local file.
       * @param toRemotePath  Path to a remote file to write to.
       */
      async appendFrom(source, toRemotePath, options = {}) {
        return this._uploadWithCommand(source, toRemotePath, "APPE", options);
      }
      /**
       * @protected
       */
      async _uploadWithCommand(source, remotePath, command, options) {
        if (typeof source === "string") {
          return this._uploadLocalFile(source, remotePath, command, options);
        }
        return this._uploadFromStream(source, remotePath, command);
      }
      /**
       * @protected
       */
      async _uploadLocalFile(localPath, remotePath, command, options) {
        const fd = await fsOpen(localPath, "r");
        const source = (0, fs_1.createReadStream)("", {
          fd,
          start: options.localStart,
          end: options.localEndInclusive,
          autoClose: false
        });
        try {
          return await this._uploadFromStream(source, remotePath, command);
        } finally {
          await ignoreError(() => fsClose(fd));
        }
      }
      /**
       * @protected
       */
      async _uploadFromStream(source, remotePath, command) {
        const onError = (err) => this.ftp.closeWithError(err);
        source.once("error", onError);
        try {
          const validPath = await this.protectWhitespace(remotePath);
          await this.prepareTransfer(this.ftp);
          return await (0, transfer_1.uploadFrom)(source, {
            ftp: this.ftp,
            tracker: this._progressTracker,
            command,
            remotePath: validPath,
            type: "upload"
          });
        } finally {
          source.removeListener("error", onError);
        }
      }
      /**
       * Download a remote file and pipe its data to a writable stream or to a local file.
       *
       * You can optionally define at which position of the remote file you'd like to start
       * downloading. If the destination you provide is a file, the offset will be applied
       * to it as well. For example: To resume a failed download, you'd request the size of
       * the local, partially downloaded file and use that as the offset. Assuming the size
       * is 23, you'd download the rest using `downloadTo("local.txt", "remote.txt", 23)`.
       *
       * @param destination  Stream or path for a local file to write to.
       * @param fromRemotePath  Path of the remote file to read from.
       * @param startAt  Position within the remote file to start downloading at. If the destination is a file, this offset is also applied to it.
       */
      async downloadTo(destination, fromRemotePath, startAt = 0) {
        if (typeof destination === "string") {
          return this._downloadToFile(destination, fromRemotePath, startAt);
        }
        return this._downloadToStream(destination, fromRemotePath, startAt);
      }
      /**
       * @protected
       */
      async _downloadToFile(localPath, remotePath, startAt) {
        const appendingToLocalFile = startAt > 0;
        const fileSystemFlags = appendingToLocalFile ? "r+" : "w";
        const fd = await fsOpen(localPath, fileSystemFlags);
        const destination = (0, fs_1.createWriteStream)("", {
          fd,
          start: startAt,
          autoClose: false
        });
        try {
          return await this._downloadToStream(destination, remotePath, startAt);
        } catch (err) {
          const localFileStats = await ignoreError(() => fsStat(localPath));
          const hasDownloadedData = localFileStats && localFileStats.size > 0;
          const shouldRemoveLocalFile = !appendingToLocalFile && !hasDownloadedData;
          if (shouldRemoveLocalFile) {
            await ignoreError(() => fsUnlink(localPath));
          }
          throw err;
        } finally {
          await ignoreError(() => fsClose(fd));
        }
      }
      /**
       * @protected
       */
      async _downloadToStream(destination, remotePath, startAt) {
        const onError = (err) => this.ftp.closeWithError(err);
        destination.once("error", onError);
        try {
          const validPath = await this.protectWhitespace(remotePath);
          await this.prepareTransfer(this.ftp);
          return await (0, transfer_1.downloadTo)(destination, {
            ftp: this.ftp,
            tracker: this._progressTracker,
            command: startAt > 0 ? `REST ${startAt}` : `RETR ${validPath}`,
            remotePath: validPath,
            type: "download"
          });
        } finally {
          destination.removeListener("error", onError);
          destination.end();
        }
      }
      /**
       * List files and directories in the current working directory, or from `path` if specified.
       *
       * @param [path]  Path to remote file or directory.
       */
      async list(path73 = "") {
        const validPath = await this.protectWhitespace(path73);
        let lastError;
        for (const candidate of this.availableListCommands) {
          const command = validPath === "" ? candidate : `${candidate} ${validPath}`;
          await this.prepareTransfer(this.ftp);
          try {
            const parsedList = await this._requestListWithCommand(command);
            this.availableListCommands = [candidate];
            return parsedList;
          } catch (err) {
            const shouldTryNext = err instanceof FtpContext_1.FTPError;
            if (!shouldTryNext) {
              throw err;
            }
            lastError = err;
          }
        }
        throw lastError;
      }
      /**
       * @protected
       */
      async _requestListWithCommand(command) {
        const buffer = new StringWriter_1.StringWriter();
        await (0, transfer_1.downloadTo)(buffer, {
          ftp: this.ftp,
          tracker: this._progressTracker,
          command,
          remotePath: "",
          type: "list"
        });
        const text = buffer.getText(this.ftp.encoding);
        this.ftp.log(text);
        return this.parseList(text);
      }
      /**
       * Remove a directory and all of its content.
       *
       * @param remoteDirPath  The path of the remote directory to delete.
       * @example client.removeDir("foo") // Remove directory 'foo' using a relative path.
       * @example client.removeDir("foo/bar") // Remove directory 'bar' using a relative path.
       * @example client.removeDir("/foo/bar") // Remove directory 'bar' using an absolute path.
       * @example client.removeDir("/") // Remove everything.
       */
      async removeDir(remoteDirPath) {
        return this._exitAtCurrentDirectory(async () => {
          await this.cd(remoteDirPath);
          const absoluteDirPath = await this.pwd();
          await this.clearWorkingDir();
          const dirIsRoot = absoluteDirPath === "/";
          if (!dirIsRoot) {
            await this.cdup();
            await this.removeEmptyDir(absoluteDirPath);
          }
        });
      }
      /**
       * Remove all files and directories in the working directory without removing
       * the working directory itself.
       */
      async clearWorkingDir() {
        for (const file5 of await this.list()) {
          if (file5.isDirectory) {
            await this.cd(file5.name);
            await this.clearWorkingDir();
            await this.cdup();
            await this.removeEmptyDir(file5.name);
          } else {
            await this.remove(file5.name);
          }
        }
      }
      /**
       * Upload the contents of a local directory to the remote working directory.
       *
       * This will overwrite existing files with the same names and reuse existing directories.
       * Unrelated files and directories will remain untouched. You can optionally provide a `remoteDirPath`
       * to put the contents inside a directory which will be created if necessary including all
       * intermediate directories. If you did provide a remoteDirPath the working directory will stay
       * the same as before calling this method.
       *
       * @param localDirPath  Local path, e.g. "foo/bar" or "../test"
       * @param [remoteDirPath]  Remote path of a directory to upload to. Working directory if undefined.
       */
      async uploadFromDir(localDirPath, remoteDirPath) {
        return this._exitAtCurrentDirectory(async () => {
          if (remoteDirPath) {
            await this.ensureDir(remoteDirPath);
          }
          return await this._uploadToWorkingDir(localDirPath);
        });
      }
      /**
       * @protected
       */
      async _uploadToWorkingDir(localDirPath) {
        const files = await fsReadDir(localDirPath);
        for (const file5 of files) {
          const fullPath = (0, path_1.join)(localDirPath, file5);
          const stats = await fsStat(fullPath);
          if (stats.isFile()) {
            await this.uploadFrom(fullPath, file5);
          } else if (stats.isDirectory()) {
            await this._openDir(file5);
            await this._uploadToWorkingDir(fullPath);
            await this.cdup();
          }
        }
      }
      /**
       * Download all files and directories of the working directory to a local directory.
       *
       * @param localDirPath  The local directory to download to.
       * @param remoteDirPath  Remote directory to download. Current working directory if not specified.
       */
      async downloadToDir(localDirPath, remoteDirPath) {
        return this._exitAtCurrentDirectory(async () => {
          if (remoteDirPath) {
            await this.cd(remoteDirPath);
          }
          return await this._downloadFromWorkingDir(localDirPath);
        });
      }
      /**
       * @protected
       */
      async _downloadFromWorkingDir(localDirPath) {
        await ensureLocalDirectory(localDirPath);
        for (const file5 of await this.list()) {
          const localPath = (0, path_1.join)(localDirPath, file5.name);
          if (file5.isDirectory) {
            await this.cd(file5.name);
            await this._downloadFromWorkingDir(localPath);
            await this.cdup();
          } else if (file5.isFile) {
            await this.downloadTo(localPath, file5.name);
          }
        }
      }
      /**
       * Make sure a given remote path exists, creating all directories as necessary.
       * This function also changes the current working directory to the given path.
       */
      async ensureDir(remoteDirPath) {
        if (remoteDirPath.startsWith("/")) {
          await this.cd("/");
        }
        const names = remoteDirPath.split("/").filter((name) => name !== "");
        for (const name of names) {
          await this._openDir(name);
        }
      }
      /**
       * Try to create a directory and enter it. This will not raise an exception if the directory
       * couldn't be created if for example it already exists.
       * @protected
       */
      async _openDir(dirName) {
        await this.sendIgnoringError("MKD " + dirName);
        await this.cd(dirName);
      }
      /**
       * Remove an empty directory, will fail if not empty.
       */
      async removeEmptyDir(path73) {
        const validPath = await this.protectWhitespace(path73);
        return this.send(`RMD ${validPath}`);
      }
      /**
       * FTP servers can't handle filenames that have leading whitespace. This method transforms
       * a given path to fix that issue for most cases.
       */
      async protectWhitespace(path73) {
        if (!path73.startsWith(" ")) {
          return path73;
        }
        const pwd = await this.pwd();
        const absolutePathPrefix = pwd.endsWith("/") ? pwd : pwd + "/";
        return absolutePathPrefix + path73;
      }
      async _exitAtCurrentDirectory(func) {
        const userDir = await this.pwd();
        try {
          return await func();
        } finally {
          if (!this.closed) {
            await ignoreError(() => this.cd(userDir));
          }
        }
      }
      /**
       * Try all available transfer strategies and pick the first one that works. Update `client` to
       * use the working strategy for all successive transfer requests.
       *
       * @returns a function that will try the provided strategies.
       */
      _enterFirstCompatibleMode(strategies) {
        return async (ftp) => {
          ftp.log("Trying to find optimal transfer strategy...");
          let lastError = void 0;
          for (const strategy of strategies) {
            try {
              const res = await strategy(ftp);
              ftp.log("Optimal transfer strategy found.");
              this.prepareTransfer = strategy;
              return res;
            } catch (err) {
              lastError = err;
            }
          }
          throw new Error(`None of the available transfer strategies work. Last error response was '${lastError}'.`);
        };
      }
      /**
       * DEPRECATED, use `uploadFrom`.
       * @deprecated
       */
      async upload(source, toRemotePath, options = {}) {
        this.ftp.log("Warning: upload() has been deprecated, use uploadFrom().");
        return this.uploadFrom(source, toRemotePath, options);
      }
      /**
       * DEPRECATED, use `appendFrom`.
       * @deprecated
       */
      async append(source, toRemotePath, options = {}) {
        this.ftp.log("Warning: append() has been deprecated, use appendFrom().");
        return this.appendFrom(source, toRemotePath, options);
      }
      /**
       * DEPRECATED, use `downloadTo`.
       * @deprecated
       */
      async download(destination, fromRemotePath, startAt = 0) {
        this.ftp.log("Warning: download() has been deprecated, use downloadTo().");
        return this.downloadTo(destination, fromRemotePath, startAt);
      }
      /**
       * DEPRECATED, use `uploadFromDir`.
       * @deprecated
       */
      async uploadDir(localDirPath, remoteDirPath) {
        this.ftp.log("Warning: uploadDir() has been deprecated, use uploadFromDir().");
        return this.uploadFromDir(localDirPath, remoteDirPath);
      }
      /**
       * DEPRECATED, use `downloadToDir`.
       * @deprecated
       */
      async downloadDir(localDirPath) {
        this.ftp.log("Warning: downloadDir() has been deprecated, use downloadToDir().");
        return this.downloadToDir(localDirPath);
      }
    };
    exports2.Client = Client;
    async function ensureLocalDirectory(path73) {
      try {
        await fsStat(path73);
      } catch (err) {
        await fsMkDir(path73, { recursive: true });
      }
    }
    async function ignoreError(func) {
      try {
        return await func();
      } catch (err) {
        return void 0;
      }
    }
  }
});

// ../../node_modules/.pnpm/basic-ftp@5.0.5/node_modules/basic-ftp/dist/StringEncoding.js
var require_StringEncoding = __commonJS({
  "../../node_modules/.pnpm/basic-ftp@5.0.5/node_modules/basic-ftp/dist/StringEncoding.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
  }
});

// ../../node_modules/.pnpm/basic-ftp@5.0.5/node_modules/basic-ftp/dist/index.js
var require_dist6 = __commonJS({
  "../../node_modules/.pnpm/basic-ftp@5.0.5/node_modules/basic-ftp/dist/index.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __exportStar2 = exports2 && exports2.__exportStar || function(m, exports3) {
      for (var p2 in m) if (p2 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p2)) __createBinding2(exports3, m, p2);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.enterPassiveModeIPv6 = exports2.enterPassiveModeIPv4 = void 0;
    __exportStar2(require_Client(), exports2);
    __exportStar2(require_FtpContext(), exports2);
    __exportStar2(require_FileInfo(), exports2);
    __exportStar2(require_parseList(), exports2);
    __exportStar2(require_StringEncoding(), exports2);
    var transfer_1 = require_transfer();
    Object.defineProperty(exports2, "enterPassiveModeIPv4", { enumerable: true, get: function() {
      return transfer_1.enterPassiveModeIPv4;
    } });
    Object.defineProperty(exports2, "enterPassiveModeIPv6", { enumerable: true, get: function() {
      return transfer_1.enterPassiveModeIPv6;
    } });
  }
});

// ../../node_modules/.pnpm/get-uri@6.0.4/node_modules/get-uri/dist/ftp.js
var require_ftp = __commonJS({
  "../../node_modules/.pnpm/get-uri@6.0.4/node_modules/get-uri/dist/ftp.js"(exports2) {
    "use strict";
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ftp = void 0;
    var basic_ftp_1 = require_dist6();
    var stream_1 = require("stream");
    var path_1 = require("path");
    var debug_1 = __importDefault2(require_src2());
    var notfound_1 = __importDefault2(require_notfound());
    var notmodified_1 = __importDefault2(require_notmodified());
    var debug4 = (0, debug_1.default)("get-uri:ftp");
    var ftp = async (url46, opts = {}) => {
      const { cache } = opts;
      const filepath = decodeURIComponent(url46.pathname);
      let lastModified;
      if (!filepath) {
        throw new TypeError('No "pathname"!');
      }
      const client = new basic_ftp_1.Client();
      try {
        const host = url46.hostname || url46.host || "localhost";
        const port = parseInt(url46.port || "0", 10) || 21;
        const user = url46.username ? decodeURIComponent(url46.username) : void 0;
        const password = url46.password ? decodeURIComponent(url46.password) : void 0;
        await client.access({
          host,
          port,
          user,
          password,
          ...opts
        });
        try {
          lastModified = await client.lastMod(filepath);
        } catch (err) {
          if (err.code === 550) {
            throw new notfound_1.default();
          }
        }
        if (!lastModified) {
          const list = await client.list((0, path_1.dirname)(filepath));
          const name = (0, path_1.basename)(filepath);
          const entry = list.find((e) => e.name === name);
          if (entry) {
            lastModified = entry.modifiedAt;
          }
        }
        if (lastModified) {
          if (isNotModified()) {
            throw new notmodified_1.default();
          }
        } else {
          throw new notfound_1.default();
        }
        const stream = new stream_1.PassThrough();
        const rs = stream;
        client.downloadTo(stream, filepath).then((result) => {
          debug4(result.message);
          client.close();
        });
        rs.lastModified = lastModified;
        return rs;
      } catch (err) {
        client.close();
        throw err;
      }
      function isNotModified() {
        if (cache?.lastModified && lastModified) {
          return +cache.lastModified === +lastModified;
        }
        return false;
      }
    };
    exports2.ftp = ftp;
  }
});

// ../../node_modules/.pnpm/get-uri@6.0.4/node_modules/get-uri/dist/http-error.js
var require_http_error = __commonJS({
  "../../node_modules/.pnpm/get-uri@6.0.4/node_modules/get-uri/dist/http-error.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var http_1 = require("http");
    var HTTPError = class extends Error {
      constructor(statusCode, message = http_1.STATUS_CODES[statusCode]) {
        super(message);
        this.statusCode = statusCode;
        this.code = `E${String(message).toUpperCase().replace(/\s+/g, "")}`;
      }
    };
    exports2.default = HTTPError;
  }
});

// ../../node_modules/.pnpm/get-uri@6.0.4/node_modules/get-uri/dist/http.js
var require_http = __commonJS({
  "../../node_modules/.pnpm/get-uri@6.0.4/node_modules/get-uri/dist/http.js"(exports2) {
    "use strict";
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.http = void 0;
    var http_1 = __importDefault2(require("http"));
    var https_1 = __importDefault2(require("https"));
    var events_1 = require("events");
    var debug_1 = __importDefault2(require_src2());
    var http_error_1 = __importDefault2(require_http_error());
    var notfound_1 = __importDefault2(require_notfound());
    var notmodified_1 = __importDefault2(require_notmodified());
    var debug4 = (0, debug_1.default)("get-uri:http");
    var http3 = async (url46, opts = {}) => {
      debug4("GET %o", url46.href);
      const cache = getCache(url46, opts.cache);
      if (cache && isFresh(cache) && typeof cache.statusCode === "number") {
        const type2 = cache.statusCode / 100 | 0;
        if (type2 === 3 && cache.headers.location) {
          debug4("cached redirect");
          throw new Error("TODO: implement cached redirects!");
        }
        throw new notmodified_1.default();
      }
      const maxRedirects = typeof opts.maxRedirects === "number" ? opts.maxRedirects : 5;
      debug4("allowing %o max redirects", maxRedirects);
      let mod;
      if (opts.http) {
        mod = opts.http;
        debug4("using secure `https` core module");
      } else {
        mod = http_1.default;
        debug4("using `http` core module");
      }
      const options = { ...opts };
      if (cache) {
        if (!options.headers) {
          options.headers = {};
        }
        const lastModified = cache.headers["last-modified"];
        if (lastModified) {
          options.headers["If-Modified-Since"] = lastModified;
          debug4('added "If-Modified-Since" request header: %o', lastModified);
        }
        const etag = cache.headers.etag;
        if (etag) {
          options.headers["If-None-Match"] = etag;
          debug4('added "If-None-Match" request header: %o', etag);
        }
      }
      const req = mod.get(url46, options);
      const [res] = await (0, events_1.once)(req, "response");
      const code = res.statusCode || 0;
      res.date = Date.now();
      res.parsed = url46;
      debug4("got %o response status code", code);
      const type = code / 100 | 0;
      const location = res.headers.location;
      if (type === 3 && location) {
        if (!opts.redirects)
          opts.redirects = [];
        const redirects = opts.redirects;
        if (redirects.length < maxRedirects) {
          debug4('got a "redirect" status code with Location: %o', location);
          res.resume();
          redirects.push(res);
          const newUri = new URL(location, url46.href);
          debug4("resolved redirect URL: %o", newUri.href);
          const left = maxRedirects - redirects.length;
          debug4("%o more redirects allowed after this one", left);
          if (newUri.protocol !== url46.protocol) {
            opts.http = newUri.protocol === "https:" ? https_1.default : void 0;
          }
          return (0, exports2.http)(newUri, opts);
        }
      }
      if (type !== 2) {
        res.resume();
        if (code === 304) {
          throw new notmodified_1.default();
        } else if (code === 404) {
          throw new notfound_1.default();
        }
        throw new http_error_1.default(code);
      }
      if (opts.redirects) {
        res.redirects = opts.redirects;
      }
      return res;
    };
    exports2.http = http3;
    function isFresh(cache) {
      let fresh = false;
      let expires = parseInt(cache.headers.expires || "", 10);
      const cacheControl = cache.headers["cache-control"];
      if (cacheControl) {
        debug4("Cache-Control: %o", cacheControl);
        const parts = cacheControl.split(/,\s*?\b/);
        for (let i = 0; i < parts.length; i++) {
          const part = parts[i];
          const subparts = part.split("=");
          const name = subparts[0];
          switch (name) {
            case "max-age":
              expires = (cache.date || 0) + parseInt(subparts[1], 10) * 1e3;
              fresh = Date.now() < expires;
              if (fresh) {
                debug4('cache is "fresh" due to previous %o Cache-Control param', part);
              }
              return fresh;
            case "must-revalidate":
              break;
            case "no-cache":
            case "no-store":
              debug4('cache is "stale" due to explicit %o Cache-Control param', name);
              return false;
            default:
              break;
          }
        }
      } else if (expires) {
        debug4("Expires: %o", expires);
        fresh = Date.now() < expires;
        if (fresh) {
          debug4('cache is "fresh" due to previous Expires response header');
        }
        return fresh;
      }
      return false;
    }
    function getCache(url46, cache) {
      if (cache) {
        if (cache.parsed && cache.parsed.href === url46.href) {
          return cache;
        }
        if (cache.redirects) {
          for (let i = 0; i < cache.redirects.length; i++) {
            const c2 = getCache(url46, cache.redirects[i]);
            if (c2) {
              return c2;
            }
          }
        }
      }
      return null;
    }
  }
});

// ../../node_modules/.pnpm/get-uri@6.0.4/node_modules/get-uri/dist/https.js
var require_https = __commonJS({
  "../../node_modules/.pnpm/get-uri@6.0.4/node_modules/get-uri/dist/https.js"(exports2) {
    "use strict";
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.https = void 0;
    var https_1 = __importDefault2(require("https"));
    var http_1 = require_http();
    var https2 = (url46, opts) => {
      return (0, http_1.http)(url46, { ...opts, http: https_1.default });
    };
    exports2.https = https2;
  }
});

// ../../node_modules/.pnpm/get-uri@6.0.4/node_modules/get-uri/dist/index.js
var require_dist7 = __commonJS({
  "../../node_modules/.pnpm/get-uri@6.0.4/node_modules/get-uri/dist/index.js"(exports2) {
    "use strict";
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.getUri = exports2.isValidProtocol = exports2.protocols = void 0;
    var debug_1 = __importDefault2(require_src2());
    var data_1 = require_data();
    var file_1 = require_file();
    var ftp_1 = require_ftp();
    var http_1 = require_http();
    var https_1 = require_https();
    var debug4 = (0, debug_1.default)("get-uri");
    exports2.protocols = {
      data: data_1.data,
      file: file_1.file,
      ftp: ftp_1.ftp,
      http: http_1.http,
      https: https_1.https
    };
    var VALID_PROTOCOLS = new Set(Object.keys(exports2.protocols));
    function isValidProtocol(p2) {
      return VALID_PROTOCOLS.has(p2);
    }
    exports2.isValidProtocol = isValidProtocol;
    async function getUri(uri, opts) {
      debug4("getUri(%o)", uri);
      if (!uri) {
        throw new TypeError('Must pass in a URI to "getUri()"');
      }
      const url46 = typeof uri === "string" ? new URL(uri) : uri;
      const protocol = url46.protocol.replace(/:$/, "");
      if (!isValidProtocol(protocol)) {
        throw new TypeError(`Unsupported protocol "${protocol}" specified in URI: "${uri}"`);
      }
      const getter = exports2.protocols[protocol];
      return getter(url46, opts);
    }
    exports2.getUri = getUri;
  }
});

// ../../node_modules/.pnpm/estraverse@5.3.0/node_modules/estraverse/estraverse.js
var require_estraverse = __commonJS({
  "../../node_modules/.pnpm/estraverse@5.3.0/node_modules/estraverse/estraverse.js"(exports2) {
    "use strict";
    (function clone3(exports3) {
      "use strict";
      var Syntax, VisitorOption, VisitorKeys, BREAK, SKIP, REMOVE;
      function deepCopy(obj) {
        var ret = {}, key, val;
        for (key in obj) {
          if (obj.hasOwnProperty(key)) {
            val = obj[key];
            if (typeof val === "object" && val !== null) {
              ret[key] = deepCopy(val);
            } else {
              ret[key] = val;
            }
          }
        }
        return ret;
      }
      function upperBound(array3, func) {
        var diff, len, i, current;
        len = array3.length;
        i = 0;
        while (len) {
          diff = len >>> 1;
          current = i + diff;
          if (func(array3[current])) {
            len = diff;
          } else {
            i = current + 1;
            len -= diff + 1;
          }
        }
        return i;
      }
      Syntax = {
        AssignmentExpression: "AssignmentExpression",
        AssignmentPattern: "AssignmentPattern",
        ArrayExpression: "ArrayExpression",
        ArrayPattern: "ArrayPattern",
        ArrowFunctionExpression: "ArrowFunctionExpression",
        AwaitExpression: "AwaitExpression",
        // CAUTION: It's deferred to ES7.
        BlockStatement: "BlockStatement",
        BinaryExpression: "BinaryExpression",
        BreakStatement: "BreakStatement",
        CallExpression: "CallExpression",
        CatchClause: "CatchClause",
        ChainExpression: "ChainExpression",
        ClassBody: "ClassBody",
        ClassDeclaration: "ClassDeclaration",
        ClassExpression: "ClassExpression",
        ComprehensionBlock: "ComprehensionBlock",
        // CAUTION: It's deferred to ES7.
        ComprehensionExpression: "ComprehensionExpression",
        // CAUTION: It's deferred to ES7.
        ConditionalExpression: "ConditionalExpression",
        ContinueStatement: "ContinueStatement",
        DebuggerStatement: "DebuggerStatement",
        DirectiveStatement: "DirectiveStatement",
        DoWhileStatement: "DoWhileStatement",
        EmptyStatement: "EmptyStatement",
        ExportAllDeclaration: "ExportAllDeclaration",
        ExportDefaultDeclaration: "ExportDefaultDeclaration",
        ExportNamedDeclaration: "ExportNamedDeclaration",
        ExportSpecifier: "ExportSpecifier",
        ExpressionStatement: "ExpressionStatement",
        ForStatement: "ForStatement",
        ForInStatement: "ForInStatement",
        ForOfStatement: "ForOfStatement",
        FunctionDeclaration: "FunctionDeclaration",
        FunctionExpression: "FunctionExpression",
        GeneratorExpression: "GeneratorExpression",
        // CAUTION: It's deferred to ES7.
        Identifier: "Identifier",
        IfStatement: "IfStatement",
        ImportExpression: "ImportExpression",
        ImportDeclaration: "ImportDeclaration",
        ImportDefaultSpecifier: "ImportDefaultSpecifier",
        ImportNamespaceSpecifier: "ImportNamespaceSpecifier",
        ImportSpecifier: "ImportSpecifier",
        Literal: "Literal",
        LabeledStatement: "LabeledStatement",
        LogicalExpression: "LogicalExpression",
        MemberExpression: "MemberExpression",
        MetaProperty: "MetaProperty",
        MethodDefinition: "MethodDefinition",
        ModuleSpecifier: "ModuleSpecifier",
        NewExpression: "NewExpression",
        ObjectExpression: "ObjectExpression",
        ObjectPattern: "ObjectPattern",
        PrivateIdentifier: "PrivateIdentifier",
        Program: "Program",
        Property: "Property",
        PropertyDefinition: "PropertyDefinition",
        RestElement: "RestElement",
        ReturnStatement: "ReturnStatement",
        SequenceExpression: "SequenceExpression",
        SpreadElement: "SpreadElement",
        Super: "Super",
        SwitchStatement: "SwitchStatement",
        SwitchCase: "SwitchCase",
        TaggedTemplateExpression: "TaggedTemplateExpression",
        TemplateElement: "TemplateElement",
        TemplateLiteral: "TemplateLiteral",
        ThisExpression: "ThisExpression",
        ThrowStatement: "ThrowStatement",
        TryStatement: "TryStatement",
        UnaryExpression: "UnaryExpression",
        UpdateExpression: "UpdateExpression",
        VariableDeclaration: "VariableDeclaration",
        VariableDeclarator: "VariableDeclarator",
        WhileStatement: "WhileStatement",
        WithStatement: "WithStatement",
        YieldExpression: "YieldExpression"
      };
      VisitorKeys = {
        AssignmentExpression: ["left", "right"],
        AssignmentPattern: ["left", "right"],
        ArrayExpression: ["elements"],
        ArrayPattern: ["elements"],
        ArrowFunctionExpression: ["params", "body"],
        AwaitExpression: ["argument"],
        // CAUTION: It's deferred to ES7.
        BlockStatement: ["body"],
        BinaryExpression: ["left", "right"],
        BreakStatement: ["label"],
        CallExpression: ["callee", "arguments"],
        CatchClause: ["param", "body"],
        ChainExpression: ["expression"],
        ClassBody: ["body"],
        ClassDeclaration: ["id", "superClass", "body"],
        ClassExpression: ["id", "superClass", "body"],
        ComprehensionBlock: ["left", "right"],
        // CAUTION: It's deferred to ES7.
        ComprehensionExpression: ["blocks", "filter", "body"],
        // CAUTION: It's deferred to ES7.
        ConditionalExpression: ["test", "consequent", "alternate"],
        ContinueStatement: ["label"],
        DebuggerStatement: [],
        DirectiveStatement: [],
        DoWhileStatement: ["body", "test"],
        EmptyStatement: [],
        ExportAllDeclaration: ["source"],
        ExportDefaultDeclaration: ["declaration"],
        ExportNamedDeclaration: ["declaration", "specifiers", "source"],
        ExportSpecifier: ["exported", "local"],
        ExpressionStatement: ["expression"],
        ForStatement: ["init", "test", "update", "body"],
        ForInStatement: ["left", "right", "body"],
        ForOfStatement: ["left", "right", "body"],
        FunctionDeclaration: ["id", "params", "body"],
        FunctionExpression: ["id", "params", "body"],
        GeneratorExpression: ["blocks", "filter", "body"],
        // CAUTION: It's deferred to ES7.
        Identifier: [],
        IfStatement: ["test", "consequent", "alternate"],
        ImportExpression: ["source"],
        ImportDeclaration: ["specifiers", "source"],
        ImportDefaultSpecifier: ["local"],
        ImportNamespaceSpecifier: ["local"],
        ImportSpecifier: ["imported", "local"],
        Literal: [],
        LabeledStatement: ["label", "body"],
        LogicalExpression: ["left", "right"],
        MemberExpression: ["object", "property"],
        MetaProperty: ["meta", "property"],
        MethodDefinition: ["key", "value"],
        ModuleSpecifier: [],
        NewExpression: ["callee", "arguments"],
        ObjectExpression: ["properties"],
        ObjectPattern: ["properties"],
        PrivateIdentifier: [],
        Program: ["body"],
        Property: ["key", "value"],
        PropertyDefinition: ["key", "value"],
        RestElement: ["argument"],
        ReturnStatement: ["argument"],
        SequenceExpression: ["expressions"],
        SpreadElement: ["argument"],
        Super: [],
        SwitchStatement: ["discriminant", "cases"],
        SwitchCase: ["test", "consequent"],
        TaggedTemplateExpression: ["tag", "quasi"],
        TemplateElement: [],
        TemplateLiteral: ["quasis", "expressions"],
        ThisExpression: [],
        ThrowStatement: ["argument"],
        TryStatement: ["block", "handler", "finalizer"],
        UnaryExpression: ["argument"],
        UpdateExpression: ["argument"],
        VariableDeclaration: ["declarations"],
        VariableDeclarator: ["id", "init"],
        WhileStatement: ["test", "body"],
        WithStatement: ["object", "body"],
        YieldExpression: ["argument"]
      };
      BREAK = {};
      SKIP = {};
      REMOVE = {};
      VisitorOption = {
        Break: BREAK,
        Skip: SKIP,
        Remove: REMOVE
      };
      function Reference(parent, key) {
        this.parent = parent;
        this.key = key;
      }
      Reference.prototype.replace = function replace2(node) {
        this.parent[this.key] = node;
      };
      Reference.prototype.remove = function remove() {
        if (Array.isArray(this.parent)) {
          this.parent.splice(this.key, 1);
          return true;
        } else {
          this.replace(null);
          return false;
        }
      };
      function Element(node, path73, wrap, ref) {
        this.node = node;
        this.path = path73;
        this.wrap = wrap;
        this.ref = ref;
      }
      function Controller() {
      }
      Controller.prototype.path = function path73() {
        var i, iz, j, jz, result, element;
        function addToPath(result2, path74) {
          if (Array.isArray(path74)) {
            for (j = 0, jz = path74.length; j < jz; ++j) {
              result2.push(path74[j]);
            }
          } else {
            result2.push(path74);
          }
        }
        if (!this.__current.path) {
          return null;
        }
        result = [];
        for (i = 2, iz = this.__leavelist.length; i < iz; ++i) {
          element = this.__leavelist[i];
          addToPath(result, element.path);
        }
        addToPath(result, this.__current.path);
        return result;
      };
      Controller.prototype.type = function() {
        var node = this.current();
        return node.type || this.__current.wrap;
      };
      Controller.prototype.parents = function parents() {
        var i, iz, result;
        result = [];
        for (i = 1, iz = this.__leavelist.length; i < iz; ++i) {
          result.push(this.__leavelist[i].node);
        }
        return result;
      };
      Controller.prototype.current = function current() {
        return this.__current.node;
      };
      Controller.prototype.__execute = function __execute(callback, element) {
        var previous, result;
        result = void 0;
        previous = this.__current;
        this.__current = element;
        this.__state = null;
        if (callback) {
          result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node);
        }
        this.__current = previous;
        return result;
      };
      Controller.prototype.notify = function notify(flag) {
        this.__state = flag;
      };
      Controller.prototype.skip = function() {
        this.notify(SKIP);
      };
      Controller.prototype["break"] = function() {
        this.notify(BREAK);
      };
      Controller.prototype.remove = function() {
        this.notify(REMOVE);
      };
      Controller.prototype.__initialize = function(root, visitor) {
        this.visitor = visitor;
        this.root = root;
        this.__worklist = [];
        this.__leavelist = [];
        this.__current = null;
        this.__state = null;
        this.__fallback = null;
        if (visitor.fallback === "iteration") {
          this.__fallback = Object.keys;
        } else if (typeof visitor.fallback === "function") {
          this.__fallback = visitor.fallback;
        }
        this.__keys = VisitorKeys;
        if (visitor.keys) {
          this.__keys = Object.assign(Object.create(this.__keys), visitor.keys);
        }
      };
      function isNode(node) {
        if (node == null) {
          return false;
        }
        return typeof node === "object" && typeof node.type === "string";
      }
      function isProperty(nodeType, key) {
        return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && "properties" === key;
      }
      function candidateExistsInLeaveList(leavelist, candidate) {
        for (var i = leavelist.length - 1; i >= 0; --i) {
          if (leavelist[i].node === candidate) {
            return true;
          }
        }
        return false;
      }
      Controller.prototype.traverse = function traverse2(root, visitor) {
        var worklist, leavelist, element, node, nodeType, ret, key, current, current2, candidates, candidate, sentinel;
        this.__initialize(root, visitor);
        sentinel = {};
        worklist = this.__worklist;
        leavelist = this.__leavelist;
        worklist.push(new Element(root, null, null, null));
        leavelist.push(new Element(null, null, null, null));
        while (worklist.length) {
          element = worklist.pop();
          if (element === sentinel) {
            element = leavelist.pop();
            ret = this.__execute(visitor.leave, element);
            if (this.__state === BREAK || ret === BREAK) {
              return;
            }
            continue;
          }
          if (element.node) {
            ret = this.__execute(visitor.enter, element);
            if (this.__state === BREAK || ret === BREAK) {
              return;
            }
            worklist.push(sentinel);
            leavelist.push(element);
            if (this.__state === SKIP || ret === SKIP) {
              continue;
            }
            node = element.node;
            nodeType = node.type || element.wrap;
            candidates = this.__keys[nodeType];
            if (!candidates) {
              if (this.__fallback) {
                candidates = this.__fallback(node);
              } else {
                throw new Error("Unknown node type " + nodeType + ".");
              }
            }
            current = candidates.length;
            while ((current -= 1) >= 0) {
              key = candidates[current];
              candidate = node[key];
              if (!candidate) {
                continue;
              }
              if (Array.isArray(candidate)) {
                current2 = candidate.length;
                while ((current2 -= 1) >= 0) {
                  if (!candidate[current2]) {
                    continue;
                  }
                  if (candidateExistsInLeaveList(leavelist, candidate[current2])) {
                    continue;
                  }
                  if (isProperty(nodeType, candidates[current])) {
                    element = new Element(candidate[current2], [key, current2], "Property", null);
                  } else if (isNode(candidate[current2])) {
                    element = new Element(candidate[current2], [key, current2], null, null);
                  } else {
                    continue;
                  }
                  worklist.push(element);
                }
              } else if (isNode(candidate)) {
                if (candidateExistsInLeaveList(leavelist, candidate)) {
                  continue;
                }
                worklist.push(new Element(candidate, key, null, null));
              }
            }
          }
        }
      };
      Controller.prototype.replace = function replace2(root, visitor) {
        var worklist, leavelist, node, nodeType, target, element, current, current2, candidates, candidate, sentinel, outer, key;
        function removeElem(element2) {
          var i, key2, nextElem, parent;
          if (element2.ref.remove()) {
            key2 = element2.ref.key;
            parent = element2.ref.parent;
            i = worklist.length;
            while (i--) {
              nextElem = worklist[i];
              if (nextElem.ref && nextElem.ref.parent === parent) {
                if (nextElem.ref.key < key2) {
                  break;
                }
                --nextElem.ref.key;
              }
            }
          }
        }
        this.__initialize(root, visitor);
        sentinel = {};
        worklist = this.__worklist;
        leavelist = this.__leavelist;
        outer = {
          root
        };
        element = new Element(root, null, null, new Reference(outer, "root"));
        worklist.push(element);
        leavelist.push(element);
        while (worklist.length) {
          element = worklist.pop();
          if (element === sentinel) {
            element = leavelist.pop();
            target = this.__execute(visitor.leave, element);
            if (target !== void 0 && target !== BREAK && target !== SKIP && target !== REMOVE) {
              element.ref.replace(target);
            }
            if (this.__state === REMOVE || target === REMOVE) {
              removeElem(element);
            }
            if (this.__state === BREAK || target === BREAK) {
              return outer.root;
            }
            continue;
          }
          target = this.__execute(visitor.enter, element);
          if (target !== void 0 && target !== BREAK && target !== SKIP && target !== REMOVE) {
            element.ref.replace(target);
            element.node = target;
          }
          if (this.__state === REMOVE || target === REMOVE) {
            removeElem(element);
            element.node = null;
          }
          if (this.__state === BREAK || target === BREAK) {
            return outer.root;
          }
          node = element.node;
          if (!node) {
            continue;
          }
          worklist.push(sentinel);
          leavelist.push(element);
          if (this.__state === SKIP || target === SKIP) {
            continue;
          }
          nodeType = node.type || element.wrap;
          candidates = this.__keys[nodeType];
          if (!candidates) {
            if (this.__fallback) {
              candidates = this.__fallback(node);
            } else {
              throw new Error("Unknown node type " + nodeType + ".");
            }
          }
          current = candidates.length;
          while ((current -= 1) >= 0) {
            key = candidates[current];
            candidate = node[key];
            if (!candidate) {
              continue;
            }
            if (Array.isArray(candidate)) {
              current2 = candidate.length;
              while ((current2 -= 1) >= 0) {
                if (!candidate[current2]) {
                  continue;
                }
                if (isProperty(nodeType, candidates[current])) {
                  element = new Element(candidate[current2], [key, current2], "Property", new Reference(candidate, current2));
                } else if (isNode(candidate[current2])) {
                  element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2));
                } else {
                  continue;
                }
                worklist.push(element);
              }
            } else if (isNode(candidate)) {
              worklist.push(new Element(candidate, key, null, new Reference(node, key)));
            }
          }
        }
        return outer.root;
      };
      function traverse(root, visitor) {
        var controller = new Controller();
        return controller.traverse(root, visitor);
      }
      function replace(root, visitor) {
        var controller = new Controller();
        return controller.replace(root, visitor);
      }
      function extendCommentRange(comment, tokens) {
        var target;
        target = upperBound(tokens, function search(token) {
          return token.range[0] > comment.range[0];
        });
        comment.extendedRange = [comment.range[0], comment.range[1]];
        if (target !== tokens.length) {
          comment.extendedRange[1] = tokens[target].range[0];
        }
        target -= 1;
        if (target >= 0) {
          comment.extendedRange[0] = tokens[target].range[1];
        }
        return comment;
      }
      function attachComments(tree, providedComments, tokens) {
        var comments = [], comment, len, i, cursor;
        if (!tree.range) {
          throw new Error("attachComments needs range information");
        }
        if (!tokens.length) {
          if (providedComments.length) {
            for (i = 0, len = providedComments.length; i < len; i += 1) {
              comment = deepCopy(providedComments[i]);
              comment.extendedRange = [0, tree.range[0]];
              comments.push(comment);
            }
            tree.leadingComments = comments;
          }
          return tree;
        }
        for (i = 0, len = providedComments.length; i < len; i += 1) {
          comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens));
        }
        cursor = 0;
        traverse(tree, {
          enter: function(node) {
            var comment2;
            while (cursor < comments.length) {
              comment2 = comments[cursor];
              if (comment2.extendedRange[1] > node.range[0]) {
                break;
              }
              if (comment2.extendedRange[1] === node.range[0]) {
                if (!node.leadingComments) {
                  node.leadingComments = [];
                }
                node.leadingComments.push(comment2);
                comments.splice(cursor, 1);
              } else {
                cursor += 1;
              }
            }
            if (cursor === comments.length) {
              return VisitorOption.Break;
            }
            if (comments[cursor].extendedRange[0] > node.range[1]) {
              return VisitorOption.Skip;
            }
          }
        });
        cursor = 0;
        traverse(tree, {
          leave: function(node) {
            var comment2;
            while (cursor < comments.length) {
              comment2 = comments[cursor];
              if (node.range[1] < comment2.extendedRange[0]) {
                break;
              }
              if (node.range[1] === comment2.extendedRange[0]) {
                if (!node.trailingComments) {
                  node.trailingComments = [];
                }
                node.trailingComments.push(comment2);
                comments.splice(cursor, 1);
              } else {
                cursor += 1;
              }
            }
            if (cursor === comments.length) {
              return VisitorOption.Break;
            }
            if (comments[cursor].extendedRange[0] > node.range[1]) {
              return VisitorOption.Skip;
            }
          }
        });
        return tree;
      }
      exports3.Syntax = Syntax;
      exports3.traverse = traverse;
      exports3.replace = replace;
      exports3.attachComments = attachComments;
      exports3.VisitorKeys = VisitorKeys;
      exports3.VisitorOption = VisitorOption;
      exports3.Controller = Controller;
      exports3.cloneEnvironment = function() {
        return clone3({});
      };
      return exports3;
    })(exports2);
  }
});

// ../../node_modules/.pnpm/esutils@2.0.3/node_modules/esutils/lib/ast.js
var require_ast = __commonJS({
  "../../node_modules/.pnpm/esutils@2.0.3/node_modules/esutils/lib/ast.js"(exports2, module2) {
    "use strict";
    (function() {
      "use strict";
      function isExpression(node) {
        if (node == null) {
          return false;
        }
        switch (node.type) {
          case "ArrayExpression":
          case "AssignmentExpression":
          case "BinaryExpression":
          case "CallExpression":
          case "ConditionalExpression":
          case "FunctionExpression":
          case "Identifier":
          case "Literal":
          case "LogicalExpression":
          case "MemberExpression":
          case "NewExpression":
          case "ObjectExpression":
          case "SequenceExpression":
          case "ThisExpression":
          case "UnaryExpression":
          case "UpdateExpression":
            return true;
        }
        return false;
      }
      function isIterationStatement(node) {
        if (node == null) {
          return false;
        }
        switch (node.type) {
          case "DoWhileStatement":
          case "ForInStatement":
          case "ForStatement":
          case "WhileStatement":
            return true;
        }
        return false;
      }
      function isStatement(node) {
        if (node == null) {
          return false;
        }
        switch (node.type) {
          case "BlockStatement":
          case "BreakStatement":
          case "ContinueStatement":
          case "DebuggerStatement":
          case "DoWhileStatement":
          case "EmptyStatement":
          case "ExpressionStatement":
          case "ForInStatement":
          case "ForStatement":
          case "IfStatement":
          case "LabeledStatement":
          case "ReturnStatement":
          case "SwitchStatement":
          case "ThrowStatement":
          case "TryStatement":
          case "VariableDeclaration":
          case "WhileStatement":
          case "WithStatement":
            return true;
        }
        return false;
      }
      function isSourceElement(node) {
        return isStatement(node) || node != null && node.type === "FunctionDeclaration";
      }
      function trailingStatement(node) {
        switch (node.type) {
          case "IfStatement":
            if (node.alternate != null) {
              return node.alternate;
            }
            return node.consequent;
          case "LabeledStatement":
          case "ForStatement":
          case "ForInStatement":
          case "WhileStatement":
          case "WithStatement":
            return node.body;
        }
        return null;
      }
      function isProblematicIfStatement(node) {
        var current;
        if (node.type !== "IfStatement") {
          return false;
        }
        if (node.alternate == null) {
          return false;
        }
        current = node.consequent;
        do {
          if (current.type === "IfStatement") {
            if (current.alternate == null) {
              return true;
            }
          }
          current = trailingStatement(current);
        } while (current);
        return false;
      }
      module2.exports = {
        isExpression,
        isStatement,
        isIterationStatement,
        isSourceElement,
        isProblematicIfStatement,
        trailingStatement
      };
    })();
  }
});

// ../../node_modules/.pnpm/esutils@2.0.3/node_modules/esutils/lib/code.js
var require_code = __commonJS({
  "../../node_modules/.pnpm/esutils@2.0.3/node_modules/esutils/lib/code.js"(exports2, module2) {
    "use strict";
    (function() {
      "use strict";
      var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START, IDENTIFIER_PART, ch;
      ES5Regex = {
        // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierStart:
        NonAsciiIdentifierStart: /[\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\u0561-\u0587\u05D0-\u05EA\u05F0-\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\u08A0-\u08B4\u08B6-\u08BD\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\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\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\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\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\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-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\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\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\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\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\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-\uAB65\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]/,
        // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierPart:
        NonAsciiIdentifierPart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\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\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\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\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/
      };
      ES6Regex = {
        // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierStart:
        NonAsciiIdentifierStart: /[\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\u0561-\u0587\u05D0-\u05EA\u05F0-\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\u08A0-\u08B4\u08B6-\u08BD\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\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\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\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\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\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-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\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-\u2C2E\u2C30-\u2C5E\u2C60-\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-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\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-\uAB65\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]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/,
        // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierPart:
        NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\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\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\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\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/
      };
      function isDecimalDigit(ch2) {
        return 48 <= ch2 && ch2 <= 57;
      }
      function isHexDigit(ch2) {
        return 48 <= ch2 && ch2 <= 57 || // 0..9
        97 <= ch2 && ch2 <= 102 || // a..f
        65 <= ch2 && ch2 <= 70;
      }
      function isOctalDigit(ch2) {
        return ch2 >= 48 && ch2 <= 55;
      }
      NON_ASCII_WHITESPACES = [
        5760,
        8192,
        8193,
        8194,
        8195,
        8196,
        8197,
        8198,
        8199,
        8200,
        8201,
        8202,
        8239,
        8287,
        12288,
        65279
      ];
      function isWhiteSpace3(ch2) {
        return ch2 === 32 || ch2 === 9 || ch2 === 11 || ch2 === 12 || ch2 === 160 || ch2 >= 5760 && NON_ASCII_WHITESPACES.indexOf(ch2) >= 0;
      }
      function isLineTerminator(ch2) {
        return ch2 === 10 || ch2 === 13 || ch2 === 8232 || ch2 === 8233;
      }
      function fromCodePoint(cp) {
        if (cp <= 65535) {
          return String.fromCharCode(cp);
        }
        var cu1 = String.fromCharCode(Math.floor((cp - 65536) / 1024) + 55296);
        var cu2 = String.fromCharCode((cp - 65536) % 1024 + 56320);
        return cu1 + cu2;
      }
      IDENTIFIER_START = new Array(128);
      for (ch = 0; ch < 128; ++ch) {
        IDENTIFIER_START[ch] = ch >= 97 && ch <= 122 || // a..z
        ch >= 65 && ch <= 90 || // A..Z
        ch === 36 || ch === 95;
      }
      IDENTIFIER_PART = new Array(128);
      for (ch = 0; ch < 128; ++ch) {
        IDENTIFIER_PART[ch] = ch >= 97 && ch <= 122 || // a..z
        ch >= 65 && ch <= 90 || // A..Z
        ch >= 48 && ch <= 57 || // 0..9
        ch === 36 || ch === 95;
      }
      function isIdentifierStartES5(ch2) {
        return ch2 < 128 ? IDENTIFIER_START[ch2] : ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch2));
      }
      function isIdentifierPartES5(ch2) {
        return ch2 < 128 ? IDENTIFIER_PART[ch2] : ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch2));
      }
      function isIdentifierStartES6(ch2) {
        return ch2 < 128 ? IDENTIFIER_START[ch2] : ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch2));
      }
      function isIdentifierPartES6(ch2) {
        return ch2 < 128 ? IDENTIFIER_PART[ch2] : ES6Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch2));
      }
      module2.exports = {
        isDecimalDigit,
        isHexDigit,
        isOctalDigit,
        isWhiteSpace: isWhiteSpace3,
        isLineTerminator,
        isIdentifierStartES5,
        isIdentifierPartES5,
        isIdentifierStartES6,
        isIdentifierPartES6
      };
    })();
  }
});

// ../../node_modules/.pnpm/esutils@2.0.3/node_modules/esutils/lib/keyword.js
var require_keyword = __commonJS({
  "../../node_modules/.pnpm/esutils@2.0.3/node_modules/esutils/lib/keyword.js"(exports2, module2) {
    "use strict";
    (function() {
      "use strict";
      var code = require_code();
      function isStrictModeReservedWordES6(id) {
        switch (id) {
          case "implements":
          case "interface":
          case "package":
          case "private":
          case "protected":
          case "public":
          case "static":
          case "let":
            return true;
          default:
            return false;
        }
      }
      function isKeywordES5(id, strict) {
        if (!strict && id === "yield") {
          return false;
        }
        return isKeywordES6(id, strict);
      }
      function isKeywordES6(id, strict) {
        if (strict && isStrictModeReservedWordES6(id)) {
          return true;
        }
        switch (id.length) {
          case 2:
            return id === "if" || id === "in" || id === "do";
          case 3:
            return id === "var" || id === "for" || id === "new" || id === "try";
          case 4:
            return id === "this" || id === "else" || id === "case" || id === "void" || id === "with" || id === "enum";
          case 5:
            return id === "while" || id === "break" || id === "catch" || id === "throw" || id === "const" || id === "yield" || id === "class" || id === "super";
          case 6:
            return id === "return" || id === "typeof" || id === "delete" || id === "switch" || id === "export" || id === "import";
          case 7:
            return id === "default" || id === "finally" || id === "extends";
          case 8:
            return id === "function" || id === "continue" || id === "debugger";
          case 10:
            return id === "instanceof";
          default:
            return false;
        }
      }
      function isReservedWordES5(id, strict) {
        return id === "null" || id === "true" || id === "false" || isKeywordES5(id, strict);
      }
      function isReservedWordES6(id, strict) {
        return id === "null" || id === "true" || id === "false" || isKeywordES6(id, strict);
      }
      function isRestrictedWord(id) {
        return id === "eval" || id === "arguments";
      }
      function isIdentifierNameES5(id) {
        var i, iz, ch;
        if (id.length === 0) {
          return false;
        }
        ch = id.charCodeAt(0);
        if (!code.isIdentifierStartES5(ch)) {
          return false;
        }
        for (i = 1, iz = id.length; i < iz; ++i) {
          ch = id.charCodeAt(i);
          if (!code.isIdentifierPartES5(ch)) {
            return false;
          }
        }
        return true;
      }
      function decodeUtf16(lead, trail) {
        return (lead - 55296) * 1024 + (trail - 56320) + 65536;
      }
      function isIdentifierNameES6(id) {
        var i, iz, ch, lowCh, check3;
        if (id.length === 0) {
          return false;
        }
        check3 = code.isIdentifierStartES6;
        for (i = 0, iz = id.length; i < iz; ++i) {
          ch = id.charCodeAt(i);
          if (55296 <= ch && ch <= 56319) {
            ++i;
            if (i >= iz) {
              return false;
            }
            lowCh = id.charCodeAt(i);
            if (!(56320 <= lowCh && lowCh <= 57343)) {
              return false;
            }
            ch = decodeUtf16(ch, lowCh);
          }
          if (!check3(ch)) {
            return false;
          }
          check3 = code.isIdentifierPartES6;
        }
        return true;
      }
      function isIdentifierES5(id, strict) {
        return isIdentifierNameES5(id) && !isReservedWordES5(id, strict);
      }
      function isIdentifierES6(id, strict) {
        return isIdentifierNameES6(id) && !isReservedWordES6(id, strict);
      }
      module2.exports = {
        isKeywordES5,
        isKeywordES6,
        isReservedWordES5,
        isReservedWordES6,
        isRestrictedWord,
        isIdentifierNameES5,
        isIdentifierNameES6,
        isIdentifierES5,
        isIdentifierES6
      };
    })();
  }
});

// ../../node_modules/.pnpm/esutils@2.0.3/node_modules/esutils/lib/utils.js
var require_utils3 = __commonJS({
  "../../node_modules/.pnpm/esutils@2.0.3/node_modules/esutils/lib/utils.js"(exports2) {
    "use strict";
    (function() {
      "use strict";
      exports2.ast = require_ast();
      exports2.code = require_code();
      exports2.keyword = require_keyword();
    })();
  }
});

// ../../node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/base64.js
var require_base642 = __commonJS({
  "../../node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/base64.js"(exports2) {
    "use strict";
    var intToCharMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
    exports2.encode = function(number7) {
      if (0 <= number7 && number7 < intToCharMap.length) {
        return intToCharMap[number7];
      }
      throw new TypeError("Must be between 0 and 63: " + number7);
    };
    exports2.decode = function(charCode) {
      var bigA = 65;
      var bigZ = 90;
      var littleA = 97;
      var littleZ = 122;
      var zero = 48;
      var nine = 57;
      var plus = 43;
      var slash = 47;
      var littleOffset = 26;
      var numberOffset = 52;
      if (bigA <= charCode && charCode <= bigZ) {
        return charCode - bigA;
      }
      if (littleA <= charCode && charCode <= littleZ) {
        return charCode - littleA + littleOffset;
      }
      if (zero <= charCode && charCode <= nine) {
        return charCode - zero + numberOffset;
      }
      if (charCode == plus) {
        return 62;
      }
      if (charCode == slash) {
        return 63;
      }
      return -1;
    };
  }
});

// ../../node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/base64-vlq.js
var require_base64_vlq = __commonJS({
  "../../node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/base64-vlq.js"(exports2) {
    "use strict";
    var base645 = require_base642();
    var VLQ_BASE_SHIFT = 5;
    var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
    var VLQ_BASE_MASK = VLQ_BASE - 1;
    var VLQ_CONTINUATION_BIT = VLQ_BASE;
    function toVLQSigned(aValue) {
      return aValue < 0 ? (-aValue << 1) + 1 : (aValue << 1) + 0;
    }
    function fromVLQSigned(aValue) {
      var isNegative = (aValue & 1) === 1;
      var shifted = aValue >> 1;
      return isNegative ? -shifted : shifted;
    }
    exports2.encode = function base64VLQ_encode(aValue) {
      var encoded = "";
      var digit;
      var vlq = toVLQSigned(aValue);
      do {
        digit = vlq & VLQ_BASE_MASK;
        vlq >>>= VLQ_BASE_SHIFT;
        if (vlq > 0) {
          digit |= VLQ_CONTINUATION_BIT;
        }
        encoded += base645.encode(digit);
      } while (vlq > 0);
      return encoded;
    };
    exports2.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
      var strLen = aStr.length;
      var result = 0;
      var shift = 0;
      var continuation, digit;
      do {
        if (aIndex >= strLen) {
          throw new Error("Expected more digits in base 64 VLQ value.");
        }
        digit = base645.decode(aStr.charCodeAt(aIndex++));
        if (digit === -1) {
          throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
        }
        continuation = !!(digit & VLQ_CONTINUATION_BIT);
        digit &= VLQ_BASE_MASK;
        result = result + (digit << shift);
        shift += VLQ_BASE_SHIFT;
      } while (continuation);
      aOutParam.value = fromVLQSigned(result);
      aOutParam.rest = aIndex;
    };
  }
});

// ../../node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/util.js
var require_util2 = __commonJS({
  "../../node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/util.js"(exports2) {
    "use strict";
    function getArg(aArgs, aName, aDefaultValue) {
      if (aName in aArgs) {
        return aArgs[aName];
      } else if (arguments.length === 3) {
        return aDefaultValue;
      } else {
        throw new Error('"' + aName + '" is a required argument.');
      }
    }
    exports2.getArg = getArg;
    var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
    var dataUrlRegexp = /^data:.+\,.+$/;
    function urlParse(aUrl) {
      var match = aUrl.match(urlRegexp);
      if (!match) {
        return null;
      }
      return {
        scheme: match[1],
        auth: match[2],
        host: match[3],
        port: match[4],
        path: match[5]
      };
    }
    exports2.urlParse = urlParse;
    function urlGenerate(aParsedUrl) {
      var url46 = "";
      if (aParsedUrl.scheme) {
        url46 += aParsedUrl.scheme + ":";
      }
      url46 += "//";
      if (aParsedUrl.auth) {
        url46 += aParsedUrl.auth + "@";
      }
      if (aParsedUrl.host) {
        url46 += aParsedUrl.host;
      }
      if (aParsedUrl.port) {
        url46 += ":" + aParsedUrl.port;
      }
      if (aParsedUrl.path) {
        url46 += aParsedUrl.path;
      }
      return url46;
    }
    exports2.urlGenerate = urlGenerate;
    function normalize2(aPath) {
      var path73 = aPath;
      var url46 = urlParse(aPath);
      if (url46) {
        if (!url46.path) {
          return aPath;
        }
        path73 = url46.path;
      }
      var isAbsolute6 = exports2.isAbsolute(path73);
      var parts = path73.split(/\/+/);
      for (var part, up3 = 0, i = parts.length - 1; i >= 0; i--) {
        part = parts[i];
        if (part === ".") {
          parts.splice(i, 1);
        } else if (part === "..") {
          up3++;
        } else if (up3 > 0) {
          if (part === "") {
            parts.splice(i + 1, up3);
            up3 = 0;
          } else {
            parts.splice(i, 2);
            up3--;
          }
        }
      }
      path73 = parts.join("/");
      if (path73 === "") {
        path73 = isAbsolute6 ? "/" : ".";
      }
      if (url46) {
        url46.path = path73;
        return urlGenerate(url46);
      }
      return path73;
    }
    exports2.normalize = normalize2;
    function join9(aRoot, aPath) {
      if (aRoot === "") {
        aRoot = ".";
      }
      if (aPath === "") {
        aPath = ".";
      }
      var aPathUrl = urlParse(aPath);
      var aRootUrl = urlParse(aRoot);
      if (aRootUrl) {
        aRoot = aRootUrl.path || "/";
      }
      if (aPathUrl && !aPathUrl.scheme) {
        if (aRootUrl) {
          aPathUrl.scheme = aRootUrl.scheme;
        }
        return urlGenerate(aPathUrl);
      }
      if (aPathUrl || aPath.match(dataUrlRegexp)) {
        return aPath;
      }
      if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
        aRootUrl.host = aPath;
        return urlGenerate(aRootUrl);
      }
      var joined = aPath.charAt(0) === "/" ? aPath : normalize2(aRoot.replace(/\/+$/, "") + "/" + aPath);
      if (aRootUrl) {
        aRootUrl.path = joined;
        return urlGenerate(aRootUrl);
      }
      return joined;
    }
    exports2.join = join9;
    exports2.isAbsolute = function(aPath) {
      return aPath.charAt(0) === "/" || urlRegexp.test(aPath);
    };
    function relative5(aRoot, aPath) {
      if (aRoot === "") {
        aRoot = ".";
      }
      aRoot = aRoot.replace(/\/$/, "");
      var level = 0;
      while (aPath.indexOf(aRoot + "/") !== 0) {
        var index = aRoot.lastIndexOf("/");
        if (index < 0) {
          return aPath;
        }
        aRoot = aRoot.slice(0, index);
        if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
          return aPath;
        }
        ++level;
      }
      return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
    }
    exports2.relative = relative5;
    var supportsNullProto = (function() {
      var obj = /* @__PURE__ */ Object.create(null);
      return !("__proto__" in obj);
    })();
    function identity(s) {
      return s;
    }
    function toSetString(aStr) {
      if (isProtoString(aStr)) {
        return "$" + aStr;
      }
      return aStr;
    }
    exports2.toSetString = supportsNullProto ? identity : toSetString;
    function fromSetString(aStr) {
      if (isProtoString(aStr)) {
        return aStr.slice(1);
      }
      return aStr;
    }
    exports2.fromSetString = supportsNullProto ? identity : fromSetString;
    function isProtoString(s) {
      if (!s) {
        return false;
      }
      var length = s.length;
      if (length < 9) {
        return false;
      }
      if (s.charCodeAt(length - 1) !== 95 || s.charCodeAt(length - 2) !== 95 || s.charCodeAt(length - 3) !== 111 || s.charCodeAt(length - 4) !== 116 || s.charCodeAt(length - 5) !== 111 || s.charCodeAt(length - 6) !== 114 || s.charCodeAt(length - 7) !== 112 || s.charCodeAt(length - 8) !== 95 || s.charCodeAt(length - 9) !== 95) {
        return false;
      }
      for (var i = length - 10; i >= 0; i--) {
        if (s.charCodeAt(i) !== 36) {
          return false;
        }
      }
      return true;
    }
    function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
      var cmp = strcmp(mappingA.source, mappingB.source);
      if (cmp !== 0) {
        return cmp;
      }
      cmp = mappingA.originalLine - mappingB.originalLine;
      if (cmp !== 0) {
        return cmp;
      }
      cmp = mappingA.originalColumn - mappingB.originalColumn;
      if (cmp !== 0 || onlyCompareOriginal) {
        return cmp;
      }
      cmp = mappingA.generatedColumn - mappingB.generatedColumn;
      if (cmp !== 0) {
        return cmp;
      }
      cmp = mappingA.generatedLine - mappingB.generatedLine;
      if (cmp !== 0) {
        return cmp;
      }
      return strcmp(mappingA.name, mappingB.name);
    }
    exports2.compareByOriginalPositions = compareByOriginalPositions;
    function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
      var cmp = mappingA.generatedLine - mappingB.generatedLine;
      if (cmp !== 0) {
        return cmp;
      }
      cmp = mappingA.generatedColumn - mappingB.generatedColumn;
      if (cmp !== 0 || onlyCompareGenerated) {
        return cmp;
      }
      cmp = strcmp(mappingA.source, mappingB.source);
      if (cmp !== 0) {
        return cmp;
      }
      cmp = mappingA.originalLine - mappingB.originalLine;
      if (cmp !== 0) {
        return cmp;
      }
      cmp = mappingA.originalColumn - mappingB.originalColumn;
      if (cmp !== 0) {
        return cmp;
      }
      return strcmp(mappingA.name, mappingB.name);
    }
    exports2.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
    function strcmp(aStr1, aStr2) {
      if (aStr1 === aStr2) {
        return 0;
      }
      if (aStr1 === null) {
        return 1;
      }
      if (aStr2 === null) {
        return -1;
      }
      if (aStr1 > aStr2) {
        return 1;
      }
      return -1;
    }
    function compareByGeneratedPositionsInflated(mappingA, mappingB) {
      var cmp = mappingA.generatedLine - mappingB.generatedLine;
      if (cmp !== 0) {
        return cmp;
      }
      cmp = mappingA.generatedColumn - mappingB.generatedColumn;
      if (cmp !== 0) {
        return cmp;
      }
      cmp = strcmp(mappingA.source, mappingB.source);
      if (cmp !== 0) {
        return cmp;
      }
      cmp = mappingA.originalLine - mappingB.originalLine;
      if (cmp !== 0) {
        return cmp;
      }
      cmp = mappingA.originalColumn - mappingB.originalColumn;
      if (cmp !== 0) {
        return cmp;
      }
      return strcmp(mappingA.name, mappingB.name);
    }
    exports2.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
    function parseSourceMapInput(str) {
      return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ""));
    }
    exports2.parseSourceMapInput = parseSourceMapInput;
    function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
      sourceURL = sourceURL || "";
      if (sourceRoot) {
        if (sourceRoot[sourceRoot.length - 1] !== "/" && sourceURL[0] !== "/") {
          sourceRoot += "/";
        }
        sourceURL = sourceRoot + sourceURL;
      }
      if (sourceMapURL) {
        var parsed = urlParse(sourceMapURL);
        if (!parsed) {
          throw new Error("sourceMapURL could not be parsed");
        }
        if (parsed.path) {
          var index = parsed.path.lastIndexOf("/");
          if (index >= 0) {
            parsed.path = parsed.path.substring(0, index + 1);
          }
        }
        sourceURL = join9(urlGenerate(parsed), sourceURL);
      }
      return normalize2(sourceURL);
    }
    exports2.computeSourceURL = computeSourceURL;
  }
});

// ../../node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/array-set.js
var require_array_set = __commonJS({
  "../../node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/array-set.js"(exports2) {
    "use strict";
    var util4 = require_util2();
    var has = Object.prototype.hasOwnProperty;
    var hasNativeMap = typeof Map !== "undefined";
    function ArraySet() {
      this._array = [];
      this._set = hasNativeMap ? /* @__PURE__ */ new Map() : /* @__PURE__ */ Object.create(null);
    }
    ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
      var set3 = new ArraySet();
      for (var i = 0, len = aArray.length; i < len; i++) {
        set3.add(aArray[i], aAllowDuplicates);
      }
      return set3;
    };
    ArraySet.prototype.size = function ArraySet_size() {
      return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
    };
    ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
      var sStr = hasNativeMap ? aStr : util4.toSetString(aStr);
      var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
      var idx = this._array.length;
      if (!isDuplicate || aAllowDuplicates) {
        this._array.push(aStr);
      }
      if (!isDuplicate) {
        if (hasNativeMap) {
          this._set.set(aStr, idx);
        } else {
          this._set[sStr] = idx;
        }
      }
    };
    ArraySet.prototype.has = function ArraySet_has(aStr) {
      if (hasNativeMap) {
        return this._set.has(aStr);
      } else {
        var sStr = util4.toSetString(aStr);
        return has.call(this._set, sStr);
      }
    };
    ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
      if (hasNativeMap) {
        var idx = this._set.get(aStr);
        if (idx >= 0) {
          return idx;
        }
      } else {
        var sStr = util4.toSetString(aStr);
        if (has.call(this._set, sStr)) {
          return this._set[sStr];
        }
      }
      throw new Error('"' + aStr + '" is not in the set.');
    };
    ArraySet.prototype.at = function ArraySet_at(aIdx) {
      if (aIdx >= 0 && aIdx < this._array.length) {
        return this._array[aIdx];
      }
      throw new Error("No element indexed by " + aIdx);
    };
    ArraySet.prototype.toArray = function ArraySet_toArray() {
      return this._array.slice();
    };
    exports2.ArraySet = ArraySet;
  }
});

// ../../node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/mapping-list.js
var require_mapping_list = __commonJS({
  "../../node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/mapping-list.js"(exports2) {
    "use strict";
    var util4 = require_util2();
    function generatedPositionAfter(mappingA, mappingB) {
      var lineA = mappingA.generatedLine;
      var lineB = mappingB.generatedLine;
      var columnA = mappingA.generatedColumn;
      var columnB = mappingB.generatedColumn;
      return lineB > lineA || lineB == lineA && columnB >= columnA || util4.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
    }
    function MappingList() {
      this._array = [];
      this._sorted = true;
      this._last = { generatedLine: -1, generatedColumn: 0 };
    }
    MappingList.prototype.unsortedForEach = function MappingList_forEach(aCallback, aThisArg) {
      this._array.forEach(aCallback, aThisArg);
    };
    MappingList.prototype.add = function MappingList_add(aMapping) {
      if (generatedPositionAfter(this._last, aMapping)) {
        this._last = aMapping;
        this._array.push(aMapping);
      } else {
        this._sorted = false;
        this._array.push(aMapping);
      }
    };
    MappingList.prototype.toArray = function MappingList_toArray() {
      if (!this._sorted) {
        this._array.sort(util4.compareByGeneratedPositionsInflated);
        this._sorted = true;
      }
      return this._array;
    };
    exports2.MappingList = MappingList;
  }
});

// ../../node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/source-map-generator.js
var require_source_map_generator = __commonJS({
  "../../node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/source-map-generator.js"(exports2) {
    "use strict";
    var base64VLQ = require_base64_vlq();
    var util4 = require_util2();
    var ArraySet = require_array_set().ArraySet;
    var MappingList = require_mapping_list().MappingList;
    function SourceMapGenerator(aArgs) {
      if (!aArgs) {
        aArgs = {};
      }
      this._file = util4.getArg(aArgs, "file", null);
      this._sourceRoot = util4.getArg(aArgs, "sourceRoot", null);
      this._skipValidation = util4.getArg(aArgs, "skipValidation", false);
      this._sources = new ArraySet();
      this._names = new ArraySet();
      this._mappings = new MappingList();
      this._sourcesContents = null;
    }
    SourceMapGenerator.prototype._version = 3;
    SourceMapGenerator.fromSourceMap = function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
      var sourceRoot = aSourceMapConsumer.sourceRoot;
      var generator = new SourceMapGenerator({
        file: aSourceMapConsumer.file,
        sourceRoot
      });
      aSourceMapConsumer.eachMapping(function(mapping) {
        var newMapping = {
          generated: {
            line: mapping.generatedLine,
            column: mapping.generatedColumn
          }
        };
        if (mapping.source != null) {
          newMapping.source = mapping.source;
          if (sourceRoot != null) {
            newMapping.source = util4.relative(sourceRoot, newMapping.source);
          }
          newMapping.original = {
            line: mapping.originalLine,
            column: mapping.originalColumn
          };
          if (mapping.name != null) {
            newMapping.name = mapping.name;
          }
        }
        generator.addMapping(newMapping);
      });
      aSourceMapConsumer.sources.forEach(function(sourceFile) {
        var sourceRelative = sourceFile;
        if (sourceRoot !== null) {
          sourceRelative = util4.relative(sourceRoot, sourceFile);
        }
        if (!generator._sources.has(sourceRelative)) {
          generator._sources.add(sourceRelative);
        }
        var content = aSourceMapConsumer.sourceContentFor(sourceFile);
        if (content != null) {
          generator.setSourceContent(sourceFile, content);
        }
      });
      return generator;
    };
    SourceMapGenerator.prototype.addMapping = function SourceMapGenerator_addMapping(aArgs) {
      var generated = util4.getArg(aArgs, "generated");
      var original = util4.getArg(aArgs, "original", null);
      var source = util4.getArg(aArgs, "source", null);
      var name = util4.getArg(aArgs, "name", null);
      if (!this._skipValidation) {
        this._validateMapping(generated, original, source, name);
      }
      if (source != null) {
        source = String(source);
        if (!this._sources.has(source)) {
          this._sources.add(source);
        }
      }
      if (name != null) {
        name = String(name);
        if (!this._names.has(name)) {
          this._names.add(name);
        }
      }
      this._mappings.add({
        generatedLine: generated.line,
        generatedColumn: generated.column,
        originalLine: original != null && original.line,
        originalColumn: original != null && original.column,
        source,
        name
      });
    };
    SourceMapGenerator.prototype.setSourceContent = function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
      var source = aSourceFile;
      if (this._sourceRoot != null) {
        source = util4.relative(this._sourceRoot, source);
      }
      if (aSourceContent != null) {
        if (!this._sourcesContents) {
          this._sourcesContents = /* @__PURE__ */ Object.create(null);
        }
        this._sourcesContents[util4.toSetString(source)] = aSourceContent;
      } else if (this._sourcesContents) {
        delete this._sourcesContents[util4.toSetString(source)];
        if (Object.keys(this._sourcesContents).length === 0) {
          this._sourcesContents = null;
        }
      }
    };
    SourceMapGenerator.prototype.applySourceMap = function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
      var sourceFile = aSourceFile;
      if (aSourceFile == null) {
        if (aSourceMapConsumer.file == null) {
          throw new Error(
            `SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.`
          );
        }
        sourceFile = aSourceMapConsumer.file;
      }
      var sourceRoot = this._sourceRoot;
      if (sourceRoot != null) {
        sourceFile = util4.relative(sourceRoot, sourceFile);
      }
      var newSources = new ArraySet();
      var newNames = new ArraySet();
      this._mappings.unsortedForEach(function(mapping) {
        if (mapping.source === sourceFile && mapping.originalLine != null) {
          var original = aSourceMapConsumer.originalPositionFor({
            line: mapping.originalLine,
            column: mapping.originalColumn
          });
          if (original.source != null) {
            mapping.source = original.source;
            if (aSourceMapPath != null) {
              mapping.source = util4.join(aSourceMapPath, mapping.source);
            }
            if (sourceRoot != null) {
              mapping.source = util4.relative(sourceRoot, mapping.source);
            }
            mapping.originalLine = original.line;
            mapping.originalColumn = original.column;
            if (original.name != null) {
              mapping.name = original.name;
            }
          }
        }
        var source = mapping.source;
        if (source != null && !newSources.has(source)) {
          newSources.add(source);
        }
        var name = mapping.name;
        if (name != null && !newNames.has(name)) {
          newNames.add(name);
        }
      }, this);
      this._sources = newSources;
      this._names = newNames;
      aSourceMapConsumer.sources.forEach(function(sourceFile2) {
        var content = aSourceMapConsumer.sourceContentFor(sourceFile2);
        if (content != null) {
          if (aSourceMapPath != null) {
            sourceFile2 = util4.join(aSourceMapPath, sourceFile2);
          }
          if (sourceRoot != null) {
            sourceFile2 = util4.relative(sourceRoot, sourceFile2);
          }
          this.setSourceContent(sourceFile2, content);
        }
      }, this);
    };
    SourceMapGenerator.prototype._validateMapping = function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) {
      if (aOriginal && typeof aOriginal.line !== "number" && typeof aOriginal.column !== "number") {
        throw new Error(
          "original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values."
        );
      }
      if (aGenerated && "line" in aGenerated && "column" in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) {
        return;
      } else if (aGenerated && "line" in aGenerated && "column" in aGenerated && aOriginal && "line" in aOriginal && "column" in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) {
        return;
      } else {
        throw new Error("Invalid mapping: " + JSON.stringify({
          generated: aGenerated,
          source: aSource,
          original: aOriginal,
          name: aName
        }));
      }
    };
    SourceMapGenerator.prototype._serializeMappings = function SourceMapGenerator_serializeMappings() {
      var previousGeneratedColumn = 0;
      var previousGeneratedLine = 1;
      var previousOriginalColumn = 0;
      var previousOriginalLine = 0;
      var previousName = 0;
      var previousSource = 0;
      var result = "";
      var next;
      var mapping;
      var nameIdx;
      var sourceIdx;
      var mappings = this._mappings.toArray();
      for (var i = 0, len = mappings.length; i < len; i++) {
        mapping = mappings[i];
        next = "";
        if (mapping.generatedLine !== previousGeneratedLine) {
          previousGeneratedColumn = 0;
          while (mapping.generatedLine !== previousGeneratedLine) {
            next += ";";
            previousGeneratedLine++;
          }
        } else {
          if (i > 0) {
            if (!util4.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
              continue;
            }
            next += ",";
          }
        }
        next += base64VLQ.encode(mapping.generatedColumn - previousGeneratedColumn);
        previousGeneratedColumn = mapping.generatedColumn;
        if (mapping.source != null) {
          sourceIdx = this._sources.indexOf(mapping.source);
          next += base64VLQ.encode(sourceIdx - previousSource);
          previousSource = sourceIdx;
          next += base64VLQ.encode(mapping.originalLine - 1 - previousOriginalLine);
          previousOriginalLine = mapping.originalLine - 1;
          next += base64VLQ.encode(mapping.originalColumn - previousOriginalColumn);
          previousOriginalColumn = mapping.originalColumn;
          if (mapping.name != null) {
            nameIdx = this._names.indexOf(mapping.name);
            next += base64VLQ.encode(nameIdx - previousName);
            previousName = nameIdx;
          }
        }
        result += next;
      }
      return result;
    };
    SourceMapGenerator.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
      return aSources.map(function(source) {
        if (!this._sourcesContents) {
          return null;
        }
        if (aSourceRoot != null) {
          source = util4.relative(aSourceRoot, source);
        }
        var key = util4.toSetString(source);
        return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null;
      }, this);
    };
    SourceMapGenerator.prototype.toJSON = function SourceMapGenerator_toJSON() {
      var map3 = {
        version: this._version,
        sources: this._sources.toArray(),
        names: this._names.toArray(),
        mappings: this._serializeMappings()
      };
      if (this._file != null) {
        map3.file = this._file;
      }
      if (this._sourceRoot != null) {
        map3.sourceRoot = this._sourceRoot;
      }
      if (this._sourcesContents) {
        map3.sourcesContent = this._generateSourcesContent(map3.sources, map3.sourceRoot);
      }
      return map3;
    };
    SourceMapGenerator.prototype.toString = function SourceMapGenerator_toString() {
      return JSON.stringify(this.toJSON());
    };
    exports2.SourceMapGenerator = SourceMapGenerator;
  }
});

// ../../node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/binary-search.js
var require_binary_search = __commonJS({
  "../../node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/binary-search.js"(exports2) {
    "use strict";
    exports2.GREATEST_LOWER_BOUND = 1;
    exports2.LEAST_UPPER_BOUND = 2;
    function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
      var mid = Math.floor((aHigh - aLow) / 2) + aLow;
      var cmp = aCompare(aNeedle, aHaystack[mid], true);
      if (cmp === 0) {
        return mid;
      } else if (cmp > 0) {
        if (aHigh - mid > 1) {
          return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
        }
        if (aBias == exports2.LEAST_UPPER_BOUND) {
          return aHigh < aHaystack.length ? aHigh : -1;
        } else {
          return mid;
        }
      } else {
        if (mid - aLow > 1) {
          return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
        }
        if (aBias == exports2.LEAST_UPPER_BOUND) {
          return mid;
        } else {
          return aLow < 0 ? -1 : aLow;
        }
      }
    }
    exports2.search = function search(aNeedle, aHaystack, aCompare, aBias) {
      if (aHaystack.length === 0) {
        return -1;
      }
      var index = recursiveSearch(
        -1,
        aHaystack.length,
        aNeedle,
        aHaystack,
        aCompare,
        aBias || exports2.GREATEST_LOWER_BOUND
      );
      if (index < 0) {
        return -1;
      }
      while (index - 1 >= 0) {
        if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
          break;
        }
        --index;
      }
      return index;
    };
  }
});

// ../../node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/quick-sort.js
var require_quick_sort = __commonJS({
  "../../node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/quick-sort.js"(exports2) {
    "use strict";
    function swap(ary, x, y) {
      var temp = ary[x];
      ary[x] = ary[y];
      ary[y] = temp;
    }
    function randomIntInRange(low, high) {
      return Math.round(low + Math.random() * (high - low));
    }
    function doQuickSort(ary, comparator, p2, r) {
      if (p2 < r) {
        var pivotIndex = randomIntInRange(p2, r);
        var i = p2 - 1;
        swap(ary, pivotIndex, r);
        var pivot = ary[r];
        for (var j = p2; j < r; j++) {
          if (comparator(ary[j], pivot) <= 0) {
            i += 1;
            swap(ary, i, j);
          }
        }
        swap(ary, i + 1, j);
        var q2 = i + 1;
        doQuickSort(ary, comparator, p2, q2 - 1);
        doQuickSort(ary, comparator, q2 + 1, r);
      }
    }
    exports2.quickSort = function(ary, comparator) {
      doQuickSort(ary, comparator, 0, ary.length - 1);
    };
  }
});

// ../../node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/source-map-consumer.js
var require_source_map_consumer = __commonJS({
  "../../node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/source-map-consumer.js"(exports2) {
    "use strict";
    var util4 = require_util2();
    var binarySearch = require_binary_search();
    var ArraySet = require_array_set().ArraySet;
    var base64VLQ = require_base64_vlq();
    var quickSort = require_quick_sort().quickSort;
    function SourceMapConsumer(aSourceMap, aSourceMapURL) {
      var sourceMap = aSourceMap;
      if (typeof aSourceMap === "string") {
        sourceMap = util4.parseSourceMapInput(aSourceMap);
      }
      return sourceMap.sections != null ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
    }
    SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
      return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
    };
    SourceMapConsumer.prototype._version = 3;
    SourceMapConsumer.prototype.__generatedMappings = null;
    Object.defineProperty(SourceMapConsumer.prototype, "_generatedMappings", {
      configurable: true,
      enumerable: true,
      get: function() {
        if (!this.__generatedMappings) {
          this._parseMappings(this._mappings, this.sourceRoot);
        }
        return this.__generatedMappings;
      }
    });
    SourceMapConsumer.prototype.__originalMappings = null;
    Object.defineProperty(SourceMapConsumer.prototype, "_originalMappings", {
      configurable: true,
      enumerable: true,
      get: function() {
        if (!this.__originalMappings) {
          this._parseMappings(this._mappings, this.sourceRoot);
        }
        return this.__originalMappings;
      }
    });
    SourceMapConsumer.prototype._charIsMappingSeparator = function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
      var c2 = aStr.charAt(index);
      return c2 === ";" || c2 === ",";
    };
    SourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
      throw new Error("Subclasses must implement _parseMappings");
    };
    SourceMapConsumer.GENERATED_ORDER = 1;
    SourceMapConsumer.ORIGINAL_ORDER = 2;
    SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
    SourceMapConsumer.LEAST_UPPER_BOUND = 2;
    SourceMapConsumer.prototype.eachMapping = function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
      var context = aContext || null;
      var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
      var mappings;
      switch (order) {
        case SourceMapConsumer.GENERATED_ORDER:
          mappings = this._generatedMappings;
          break;
        case SourceMapConsumer.ORIGINAL_ORDER:
          mappings = this._originalMappings;
          break;
        default:
          throw new Error("Unknown order of iteration.");
      }
      var sourceRoot = this.sourceRoot;
      mappings.map(function(mapping) {
        var source = mapping.source === null ? null : this._sources.at(mapping.source);
        source = util4.computeSourceURL(sourceRoot, source, this._sourceMapURL);
        return {
          source,
          generatedLine: mapping.generatedLine,
          generatedColumn: mapping.generatedColumn,
          originalLine: mapping.originalLine,
          originalColumn: mapping.originalColumn,
          name: mapping.name === null ? null : this._names.at(mapping.name)
        };
      }, this).forEach(aCallback, context);
    };
    SourceMapConsumer.prototype.allGeneratedPositionsFor = function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
      var line = util4.getArg(aArgs, "line");
      var needle = {
        source: util4.getArg(aArgs, "source"),
        originalLine: line,
        originalColumn: util4.getArg(aArgs, "column", 0)
      };
      needle.source = this._findSourceIndex(needle.source);
      if (needle.source < 0) {
        return [];
      }
      var mappings = [];
      var index = this._findMapping(
        needle,
        this._originalMappings,
        "originalLine",
        "originalColumn",
        util4.compareByOriginalPositions,
        binarySearch.LEAST_UPPER_BOUND
      );
      if (index >= 0) {
        var mapping = this._originalMappings[index];
        if (aArgs.column === void 0) {
          var originalLine = mapping.originalLine;
          while (mapping && mapping.originalLine === originalLine) {
            mappings.push({
              line: util4.getArg(mapping, "generatedLine", null),
              column: util4.getArg(mapping, "generatedColumn", null),
              lastColumn: util4.getArg(mapping, "lastGeneratedColumn", null)
            });
            mapping = this._originalMappings[++index];
          }
        } else {
          var originalColumn = mapping.originalColumn;
          while (mapping && mapping.originalLine === line && mapping.originalColumn == originalColumn) {
            mappings.push({
              line: util4.getArg(mapping, "generatedLine", null),
              column: util4.getArg(mapping, "generatedColumn", null),
              lastColumn: util4.getArg(mapping, "lastGeneratedColumn", null)
            });
            mapping = this._originalMappings[++index];
          }
        }
      }
      return mappings;
    };
    exports2.SourceMapConsumer = SourceMapConsumer;
    function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
      var sourceMap = aSourceMap;
      if (typeof aSourceMap === "string") {
        sourceMap = util4.parseSourceMapInput(aSourceMap);
      }
      var version4 = util4.getArg(sourceMap, "version");
      var sources = util4.getArg(sourceMap, "sources");
      var names = util4.getArg(sourceMap, "names", []);
      var sourceRoot = util4.getArg(sourceMap, "sourceRoot", null);
      var sourcesContent = util4.getArg(sourceMap, "sourcesContent", null);
      var mappings = util4.getArg(sourceMap, "mappings");
      var file5 = util4.getArg(sourceMap, "file", null);
      if (version4 != this._version) {
        throw new Error("Unsupported version: " + version4);
      }
      if (sourceRoot) {
        sourceRoot = util4.normalize(sourceRoot);
      }
      sources = sources.map(String).map(util4.normalize).map(function(source) {
        return sourceRoot && util4.isAbsolute(sourceRoot) && util4.isAbsolute(source) ? util4.relative(sourceRoot, source) : source;
      });
      this._names = ArraySet.fromArray(names.map(String), true);
      this._sources = ArraySet.fromArray(sources, true);
      this._absoluteSources = this._sources.toArray().map(function(s) {
        return util4.computeSourceURL(sourceRoot, s, aSourceMapURL);
      });
      this.sourceRoot = sourceRoot;
      this.sourcesContent = sourcesContent;
      this._mappings = mappings;
      this._sourceMapURL = aSourceMapURL;
      this.file = file5;
    }
    BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
    BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
    BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
      var relativeSource = aSource;
      if (this.sourceRoot != null) {
        relativeSource = util4.relative(this.sourceRoot, relativeSource);
      }
      if (this._sources.has(relativeSource)) {
        return this._sources.indexOf(relativeSource);
      }
      var i;
      for (i = 0; i < this._absoluteSources.length; ++i) {
        if (this._absoluteSources[i] == aSource) {
          return i;
        }
      }
      return -1;
    };
    BasicSourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
      var smc = Object.create(BasicSourceMapConsumer.prototype);
      var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
      var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
      smc.sourceRoot = aSourceMap._sourceRoot;
      smc.sourcesContent = aSourceMap._generateSourcesContent(
        smc._sources.toArray(),
        smc.sourceRoot
      );
      smc.file = aSourceMap._file;
      smc._sourceMapURL = aSourceMapURL;
      smc._absoluteSources = smc._sources.toArray().map(function(s) {
        return util4.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
      });
      var generatedMappings = aSourceMap._mappings.toArray().slice();
      var destGeneratedMappings = smc.__generatedMappings = [];
      var destOriginalMappings = smc.__originalMappings = [];
      for (var i = 0, length = generatedMappings.length; i < length; i++) {
        var srcMapping = generatedMappings[i];
        var destMapping = new Mapping();
        destMapping.generatedLine = srcMapping.generatedLine;
        destMapping.generatedColumn = srcMapping.generatedColumn;
        if (srcMapping.source) {
          destMapping.source = sources.indexOf(srcMapping.source);
          destMapping.originalLine = srcMapping.originalLine;
          destMapping.originalColumn = srcMapping.originalColumn;
          if (srcMapping.name) {
            destMapping.name = names.indexOf(srcMapping.name);
          }
          destOriginalMappings.push(destMapping);
        }
        destGeneratedMappings.push(destMapping);
      }
      quickSort(smc.__originalMappings, util4.compareByOriginalPositions);
      return smc;
    };
    BasicSourceMapConsumer.prototype._version = 3;
    Object.defineProperty(BasicSourceMapConsumer.prototype, "sources", {
      get: function() {
        return this._absoluteSources.slice();
      }
    });
    function Mapping() {
      this.generatedLine = 0;
      this.generatedColumn = 0;
      this.source = null;
      this.originalLine = null;
      this.originalColumn = null;
      this.name = null;
    }
    BasicSourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
      var generatedLine = 1;
      var previousGeneratedColumn = 0;
      var previousOriginalLine = 0;
      var previousOriginalColumn = 0;
      var previousSource = 0;
      var previousName = 0;
      var length = aStr.length;
      var index = 0;
      var cachedSegments = {};
      var temp = {};
      var originalMappings = [];
      var generatedMappings = [];
      var mapping, str, segment, end, value;
      while (index < length) {
        if (aStr.charAt(index) === ";") {
          generatedLine++;
          index++;
          previousGeneratedColumn = 0;
        } else if (aStr.charAt(index) === ",") {
          index++;
        } else {
          mapping = new Mapping();
          mapping.generatedLine = generatedLine;
          for (end = index; end < length; end++) {
            if (this._charIsMappingSeparator(aStr, end)) {
              break;
            }
          }
          str = aStr.slice(index, end);
          segment = cachedSegments[str];
          if (segment) {
            index += str.length;
          } else {
            segment = [];
            while (index < end) {
              base64VLQ.decode(aStr, index, temp);
              value = temp.value;
              index = temp.rest;
              segment.push(value);
            }
            if (segment.length === 2) {
              throw new Error("Found a source, but no line and column");
            }
            if (segment.length === 3) {
              throw new Error("Found a source and line, but no column");
            }
            cachedSegments[str] = segment;
          }
          mapping.generatedColumn = previousGeneratedColumn + segment[0];
          previousGeneratedColumn = mapping.generatedColumn;
          if (segment.length > 1) {
            mapping.source = previousSource + segment[1];
            previousSource += segment[1];
            mapping.originalLine = previousOriginalLine + segment[2];
            previousOriginalLine = mapping.originalLine;
            mapping.originalLine += 1;
            mapping.originalColumn = previousOriginalColumn + segment[3];
            previousOriginalColumn = mapping.originalColumn;
            if (segment.length > 4) {
              mapping.name = previousName + segment[4];
              previousName += segment[4];
            }
          }
          generatedMappings.push(mapping);
          if (typeof mapping.originalLine === "number") {
            originalMappings.push(mapping);
          }
        }
      }
      quickSort(generatedMappings, util4.compareByGeneratedPositionsDeflated);
      this.__generatedMappings = generatedMappings;
      quickSort(originalMappings, util4.compareByOriginalPositions);
      this.__originalMappings = originalMappings;
    };
    BasicSourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator, aBias) {
      if (aNeedle[aLineName] <= 0) {
        throw new TypeError("Line must be greater than or equal to 1, got " + aNeedle[aLineName]);
      }
      if (aNeedle[aColumnName] < 0) {
        throw new TypeError("Column must be greater than or equal to 0, got " + aNeedle[aColumnName]);
      }
      return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
    };
    BasicSourceMapConsumer.prototype.computeColumnSpans = function SourceMapConsumer_computeColumnSpans() {
      for (var index = 0; index < this._generatedMappings.length; ++index) {
        var mapping = this._generatedMappings[index];
        if (index + 1 < this._generatedMappings.length) {
          var nextMapping = this._generatedMappings[index + 1];
          if (mapping.generatedLine === nextMapping.generatedLine) {
            mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
            continue;
          }
        }
        mapping.lastGeneratedColumn = Infinity;
      }
    };
    BasicSourceMapConsumer.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor(aArgs) {
      var needle = {
        generatedLine: util4.getArg(aArgs, "line"),
        generatedColumn: util4.getArg(aArgs, "column")
      };
      var index = this._findMapping(
        needle,
        this._generatedMappings,
        "generatedLine",
        "generatedColumn",
        util4.compareByGeneratedPositionsDeflated,
        util4.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND)
      );
      if (index >= 0) {
        var mapping = this._generatedMappings[index];
        if (mapping.generatedLine === needle.generatedLine) {
          var source = util4.getArg(mapping, "source", null);
          if (source !== null) {
            source = this._sources.at(source);
            source = util4.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
          }
          var name = util4.getArg(mapping, "name", null);
          if (name !== null) {
            name = this._names.at(name);
          }
          return {
            source,
            line: util4.getArg(mapping, "originalLine", null),
            column: util4.getArg(mapping, "originalColumn", null),
            name
          };
        }
      }
      return {
        source: null,
        line: null,
        column: null,
        name: null
      };
    };
    BasicSourceMapConsumer.prototype.hasContentsOfAllSources = function BasicSourceMapConsumer_hasContentsOfAllSources() {
      if (!this.sourcesContent) {
        return false;
      }
      return this.sourcesContent.length >= this._sources.size() && !this.sourcesContent.some(function(sc) {
        return sc == null;
      });
    };
    BasicSourceMapConsumer.prototype.sourceContentFor = function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
      if (!this.sourcesContent) {
        return null;
      }
      var index = this._findSourceIndex(aSource);
      if (index >= 0) {
        return this.sourcesContent[index];
      }
      var relativeSource = aSource;
      if (this.sourceRoot != null) {
        relativeSource = util4.relative(this.sourceRoot, relativeSource);
      }
      var url46;
      if (this.sourceRoot != null && (url46 = util4.urlParse(this.sourceRoot))) {
        var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
        if (url46.scheme == "file" && this._sources.has(fileUriAbsPath)) {
          return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)];
        }
        if ((!url46.path || url46.path == "/") && this._sources.has("/" + relativeSource)) {
          return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
        }
      }
      if (nullOnMissing) {
        return null;
      } else {
        throw new Error('"' + relativeSource + '" is not in the SourceMap.');
      }
    };
    BasicSourceMapConsumer.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor(aArgs) {
      var source = util4.getArg(aArgs, "source");
      source = this._findSourceIndex(source);
      if (source < 0) {
        return {
          line: null,
          column: null,
          lastColumn: null
        };
      }
      var needle = {
        source,
        originalLine: util4.getArg(aArgs, "line"),
        originalColumn: util4.getArg(aArgs, "column")
      };
      var index = this._findMapping(
        needle,
        this._originalMappings,
        "originalLine",
        "originalColumn",
        util4.compareByOriginalPositions,
        util4.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND)
      );
      if (index >= 0) {
        var mapping = this._originalMappings[index];
        if (mapping.source === needle.source) {
          return {
            line: util4.getArg(mapping, "generatedLine", null),
            column: util4.getArg(mapping, "generatedColumn", null),
            lastColumn: util4.getArg(mapping, "lastGeneratedColumn", null)
          };
        }
      }
      return {
        line: null,
        column: null,
        lastColumn: null
      };
    };
    exports2.BasicSourceMapConsumer = BasicSourceMapConsumer;
    function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
      var sourceMap = aSourceMap;
      if (typeof aSourceMap === "string") {
        sourceMap = util4.parseSourceMapInput(aSourceMap);
      }
      var version4 = util4.getArg(sourceMap, "version");
      var sections = util4.getArg(sourceMap, "sections");
      if (version4 != this._version) {
        throw new Error("Unsupported version: " + version4);
      }
      this._sources = new ArraySet();
      this._names = new ArraySet();
      var lastOffset = {
        line: -1,
        column: 0
      };
      this._sections = sections.map(function(s) {
        if (s.url) {
          throw new Error("Support for url field in sections not implemented.");
        }
        var offset = util4.getArg(s, "offset");
        var offsetLine = util4.getArg(offset, "line");
        var offsetColumn = util4.getArg(offset, "column");
        if (offsetLine < lastOffset.line || offsetLine === lastOffset.line && offsetColumn < lastOffset.column) {
          throw new Error("Section offsets must be ordered and non-overlapping.");
        }
        lastOffset = offset;
        return {
          generatedOffset: {
            // The offset fields are 0-based, but we use 1-based indices when
            // encoding/decoding from VLQ.
            generatedLine: offsetLine + 1,
            generatedColumn: offsetColumn + 1
          },
          consumer: new SourceMapConsumer(util4.getArg(s, "map"), aSourceMapURL)
        };
      });
    }
    IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
    IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
    IndexedSourceMapConsumer.prototype._version = 3;
    Object.defineProperty(IndexedSourceMapConsumer.prototype, "sources", {
      get: function() {
        var sources = [];
        for (var i = 0; i < this._sections.length; i++) {
          for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
            sources.push(this._sections[i].consumer.sources[j]);
          }
        }
        return sources;
      }
    });
    IndexedSourceMapConsumer.prototype.originalPositionFor = function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
      var needle = {
        generatedLine: util4.getArg(aArgs, "line"),
        generatedColumn: util4.getArg(aArgs, "column")
      };
      var sectionIndex = binarySearch.search(
        needle,
        this._sections,
        function(needle2, section2) {
          var cmp = needle2.generatedLine - section2.generatedOffset.generatedLine;
          if (cmp) {
            return cmp;
          }
          return needle2.generatedColumn - section2.generatedOffset.generatedColumn;
        }
      );
      var section = this._sections[sectionIndex];
      if (!section) {
        return {
          source: null,
          line: null,
          column: null,
          name: null
        };
      }
      return section.consumer.originalPositionFor({
        line: needle.generatedLine - (section.generatedOffset.generatedLine - 1),
        column: needle.generatedColumn - (section.generatedOffset.generatedLine === needle.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0),
        bias: aArgs.bias
      });
    };
    IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = function IndexedSourceMapConsumer_hasContentsOfAllSources() {
      return this._sections.every(function(s) {
        return s.consumer.hasContentsOfAllSources();
      });
    };
    IndexedSourceMapConsumer.prototype.sourceContentFor = function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
      for (var i = 0; i < this._sections.length; i++) {
        var section = this._sections[i];
        var content = section.consumer.sourceContentFor(aSource, true);
        if (content) {
          return content;
        }
      }
      if (nullOnMissing) {
        return null;
      } else {
        throw new Error('"' + aSource + '" is not in the SourceMap.');
      }
    };
    IndexedSourceMapConsumer.prototype.generatedPositionFor = function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
      for (var i = 0; i < this._sections.length; i++) {
        var section = this._sections[i];
        if (section.consumer._findSourceIndex(util4.getArg(aArgs, "source")) === -1) {
          continue;
        }
        var generatedPosition = section.consumer.generatedPositionFor(aArgs);
        if (generatedPosition) {
          var ret = {
            line: generatedPosition.line + (section.generatedOffset.generatedLine - 1),
            column: generatedPosition.column + (section.generatedOffset.generatedLine === generatedPosition.line ? section.generatedOffset.generatedColumn - 1 : 0)
          };
          return ret;
        }
      }
      return {
        line: null,
        column: null
      };
    };
    IndexedSourceMapConsumer.prototype._parseMappings = function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
      this.__generatedMappings = [];
      this.__originalMappings = [];
      for (var i = 0; i < this._sections.length; i++) {
        var section = this._sections[i];
        var sectionMappings = section.consumer._generatedMappings;
        for (var j = 0; j < sectionMappings.length; j++) {
          var mapping = sectionMappings[j];
          var source = section.consumer._sources.at(mapping.source);
          source = util4.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
          this._sources.add(source);
          source = this._sources.indexOf(source);
          var name = null;
          if (mapping.name) {
            name = section.consumer._names.at(mapping.name);
            this._names.add(name);
            name = this._names.indexOf(name);
          }
          var adjustedMapping = {
            source,
            generatedLine: mapping.generatedLine + (section.generatedOffset.generatedLine - 1),
            generatedColumn: mapping.generatedColumn + (section.generatedOffset.generatedLine === mapping.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0),
            originalLine: mapping.originalLine,
            originalColumn: mapping.originalColumn,
            name
          };
          this.__generatedMappings.push(adjustedMapping);
          if (typeof adjustedMapping.originalLine === "number") {
            this.__originalMappings.push(adjustedMapping);
          }
        }
      }
      quickSort(this.__generatedMappings, util4.compareByGeneratedPositionsDeflated);
      quickSort(this.__originalMappings, util4.compareByOriginalPositions);
    };
    exports2.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
  }
});

// ../../node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/source-node.js
var require_source_node = __commonJS({
  "../../node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/lib/source-node.js"(exports2) {
    "use strict";
    var SourceMapGenerator = require_source_map_generator().SourceMapGenerator;
    var util4 = require_util2();
    var REGEX_NEWLINE = /(\r?\n)/;
    var NEWLINE_CODE = 10;
    var isSourceNode = "$$$isSourceNode$$$";
    function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
      this.children = [];
      this.sourceContents = {};
      this.line = aLine == null ? null : aLine;
      this.column = aColumn == null ? null : aColumn;
      this.source = aSource == null ? null : aSource;
      this.name = aName == null ? null : aName;
      this[isSourceNode] = true;
      if (aChunks != null) this.add(aChunks);
    }
    SourceNode.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
      var node = new SourceNode();
      var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
      var remainingLinesIndex = 0;
      var shiftNextLine = function() {
        var lineContents = getNextLine();
        var newLine = getNextLine() || "";
        return lineContents + newLine;
        function getNextLine() {
          return remainingLinesIndex < remainingLines.length ? remainingLines[remainingLinesIndex++] : void 0;
        }
      };
      var lastGeneratedLine = 1, lastGeneratedColumn = 0;
      var lastMapping = null;
      aSourceMapConsumer.eachMapping(function(mapping) {
        if (lastMapping !== null) {
          if (lastGeneratedLine < mapping.generatedLine) {
            addMappingWithCode(lastMapping, shiftNextLine());
            lastGeneratedLine++;
            lastGeneratedColumn = 0;
          } else {
            var nextLine = remainingLines[remainingLinesIndex] || "";
            var code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn);
            remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn);
            lastGeneratedColumn = mapping.generatedColumn;
            addMappingWithCode(lastMapping, code);
            lastMapping = mapping;
            return;
          }
        }
        while (lastGeneratedLine < mapping.generatedLine) {
          node.add(shiftNextLine());
          lastGeneratedLine++;
        }
        if (lastGeneratedColumn < mapping.generatedColumn) {
          var nextLine = remainingLines[remainingLinesIndex] || "";
          node.add(nextLine.substr(0, mapping.generatedColumn));
          remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
          lastGeneratedColumn = mapping.generatedColumn;
        }
        lastMapping = mapping;
      }, this);
      if (remainingLinesIndex < remainingLines.length) {
        if (lastMapping) {
          addMappingWithCode(lastMapping, shiftNextLine());
        }
        node.add(remainingLines.splice(remainingLinesIndex).join(""));
      }
      aSourceMapConsumer.sources.forEach(function(sourceFile) {
        var content = aSourceMapConsumer.sourceContentFor(sourceFile);
        if (content != null) {
          if (aRelativePath != null) {
            sourceFile = util4.join(aRelativePath, sourceFile);
          }
          node.setSourceContent(sourceFile, content);
        }
      });
      return node;
      function addMappingWithCode(mapping, code) {
        if (mapping === null || mapping.source === void 0) {
          node.add(code);
        } else {
          var source = aRelativePath ? util4.join(aRelativePath, mapping.source) : mapping.source;
          node.add(new SourceNode(
            mapping.originalLine,
            mapping.originalColumn,
            source,
            code,
            mapping.name
          ));
        }
      }
    };
    SourceNode.prototype.add = function SourceNode_add(aChunk) {
      if (Array.isArray(aChunk)) {
        aChunk.forEach(function(chunk) {
          this.add(chunk);
        }, this);
      } else if (aChunk[isSourceNode] || typeof aChunk === "string") {
        if (aChunk) {
          this.children.push(aChunk);
        }
      } else {
        throw new TypeError(
          "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
        );
      }
      return this;
    };
    SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
      if (Array.isArray(aChunk)) {
        for (var i = aChunk.length - 1; i >= 0; i--) {
          this.prepend(aChunk[i]);
        }
      } else if (aChunk[isSourceNode] || typeof aChunk === "string") {
        this.children.unshift(aChunk);
      } else {
        throw new TypeError(
          "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
        );
      }
      return this;
    };
    SourceNode.prototype.walk = function SourceNode_walk(aFn) {
      var chunk;
      for (var i = 0, len = this.children.length; i < len; i++) {
        chunk = this.children[i];
        if (chunk[isSourceNode]) {
          chunk.walk(aFn);
        } else {
          if (chunk !== "") {
            aFn(chunk, {
              source: this.source,
              line: this.line,
              column: this.column,
              name: this.name
            });
          }
        }
      }
    };
    SourceNode.prototype.join = function SourceNode_join(aSep) {
      var newChildren;
      var i;
      var len = this.children.length;
      if (len > 0) {
        newChildren = [];
        for (i = 0; i < len - 1; i++) {
          newChildren.push(this.children[i]);
          newChildren.push(aSep);
        }
        newChildren.push(this.children[i]);
        this.children = newChildren;
      }
      return this;
    };
    SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
      var lastChild = this.children[this.children.length - 1];
      if (lastChild[isSourceNode]) {
        lastChild.replaceRight(aPattern, aReplacement);
      } else if (typeof lastChild === "string") {
        this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
      } else {
        this.children.push("".replace(aPattern, aReplacement));
      }
      return this;
    };
    SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
      this.sourceContents[util4.toSetString(aSourceFile)] = aSourceContent;
    };
    SourceNode.prototype.walkSourceContents = function SourceNode_walkSourceContents(aFn) {
      for (var i = 0, len = this.children.length; i < len; i++) {
        if (this.children[i][isSourceNode]) {
          this.children[i].walkSourceContents(aFn);
        }
      }
      var sources = Object.keys(this.sourceContents);
      for (var i = 0, len = sources.length; i < len; i++) {
        aFn(util4.fromSetString(sources[i]), this.sourceContents[sources[i]]);
      }
    };
    SourceNode.prototype.toString = function SourceNode_toString() {
      var str = "";
      this.walk(function(chunk) {
        str += chunk;
      });
      return str;
    };
    SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
      var generated = {
        code: "",
        line: 1,
        column: 0
      };
      var map3 = new SourceMapGenerator(aArgs);
      var sourceMappingActive = false;
      var lastOriginalSource = null;
      var lastOriginalLine = null;
      var lastOriginalColumn = null;
      var lastOriginalName = null;
      this.walk(function(chunk, original) {
        generated.code += chunk;
        if (original.source !== null && original.line !== null && original.column !== null) {
          if (lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) {
            map3.addMapping({
              source: original.source,
              original: {
                line: original.line,
                column: original.column
              },
              generated: {
                line: generated.line,
                column: generated.column
              },
              name: original.name
            });
          }
          lastOriginalSource = original.source;
          lastOriginalLine = original.line;
          lastOriginalColumn = original.column;
          lastOriginalName = original.name;
          sourceMappingActive = true;
        } else if (sourceMappingActive) {
          map3.addMapping({
            generated: {
              line: generated.line,
              column: generated.column
            }
          });
          lastOriginalSource = null;
          sourceMappingActive = false;
        }
        for (var idx = 0, length = chunk.length; idx < length; idx++) {
          if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
            generated.line++;
            generated.column = 0;
            if (idx + 1 === length) {
              lastOriginalSource = null;
              sourceMappingActive = false;
            } else if (sourceMappingActive) {
              map3.addMapping({
                source: original.source,
                original: {
                  line: original.line,
                  column: original.column
                },
                generated: {
                  line: generated.line,
                  column: generated.column
                },
                name: original.name
              });
            }
          } else {
            generated.column++;
          }
        }
      });
      this.walkSourceContents(function(sourceFile, sourceContent) {
        map3.setSourceContent(sourceFile, sourceContent);
      });
      return { code: generated.code, map: map3 };
    };
    exports2.SourceNode = SourceNode;
  }
});

// ../../node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/source-map.js
var require_source_map = __commonJS({
  "../../node_modules/.pnpm/source-map@0.6.1/node_modules/source-map/source-map.js"(exports2) {
    "use strict";
    exports2.SourceMapGenerator = require_source_map_generator().SourceMapGenerator;
    exports2.SourceMapConsumer = require_source_map_consumer().SourceMapConsumer;
    exports2.SourceNode = require_source_node().SourceNode;
  }
});

// ../../node_modules/.pnpm/escodegen@2.1.0/node_modules/escodegen/package.json
var require_package = __commonJS({
  "../../node_modules/.pnpm/escodegen@2.1.0/node_modules/escodegen/package.json"(exports2, module2) {
    module2.exports = {
      name: "escodegen",
      description: "ECMAScript code generator",
      homepage: "http://github.com/estools/escodegen",
      main: "escodegen.js",
      bin: {
        esgenerate: "./bin/esgenerate.js",
        escodegen: "./bin/escodegen.js"
      },
      files: [
        "LICENSE.BSD",
        "README.md",
        "bin",
        "escodegen.js",
        "package.json"
      ],
      version: "2.1.0",
      engines: {
        node: ">=6.0"
      },
      maintainers: [
        {
          name: "Yusuke Suzuki",
          email: "utatane.tea@gmail.com",
          web: "http://github.com/Constellation"
        }
      ],
      repository: {
        type: "git",
        url: "http://github.com/estools/escodegen.git"
      },
      dependencies: {
        estraverse: "^5.2.0",
        esutils: "^2.0.2",
        esprima: "^4.0.1"
      },
      optionalDependencies: {
        "source-map": "~0.6.1"
      },
      devDependencies: {
        acorn: "^8.0.4",
        bluebird: "^3.4.7",
        "bower-registry-client": "^1.0.0",
        chai: "^4.2.0",
        "chai-exclude": "^2.0.2",
        "commonjs-everywhere": "^0.9.7",
        gulp: "^4.0.2",
        "gulp-eslint": "^6.0.0",
        "gulp-mocha": "^7.0.2",
        minimist: "^1.2.5",
        optionator: "^0.9.1",
        semver: "^7.3.4"
      },
      license: "BSD-2-Clause",
      scripts: {
        test: "gulp travis",
        "unit-test": "gulp test",
        lint: "gulp lint",
        release: "node tools/release.js",
        "build-min": "./node_modules/.bin/cjsify -ma path: tools/entry-point.js > escodegen.browser.min.js",
        build: "./node_modules/.bin/cjsify -a path: tools/entry-point.js > escodegen.browser.js"
      }
    };
  }
});

// ../../node_modules/.pnpm/escodegen@2.1.0/node_modules/escodegen/escodegen.js
var require_escodegen = __commonJS({
  "../../node_modules/.pnpm/escodegen@2.1.0/node_modules/escodegen/escodegen.js"(exports2) {
    "use strict";
    (function() {
      "use strict";
      var Syntax, Precedence, BinaryPrecedence, SourceNode, estraverse, esutils, base, indent, json3, renumber, hexadecimal, quotes, escapeless, newline2, space2, parentheses, semicolons, safeConcatenation, directive, extra, parse9, sourceMap, sourceCode, preserveBlankLines, FORMAT_MINIFY, FORMAT_DEFAULTS;
      estraverse = require_estraverse();
      esutils = require_utils3();
      Syntax = estraverse.Syntax;
      function isExpression(node) {
        return CodeGenerator.Expression.hasOwnProperty(node.type);
      }
      function isStatement(node) {
        return CodeGenerator.Statement.hasOwnProperty(node.type);
      }
      Precedence = {
        Sequence: 0,
        Yield: 1,
        Assignment: 1,
        Conditional: 2,
        ArrowFunction: 2,
        Coalesce: 3,
        LogicalOR: 4,
        LogicalAND: 5,
        BitwiseOR: 6,
        BitwiseXOR: 7,
        BitwiseAND: 8,
        Equality: 9,
        Relational: 10,
        BitwiseSHIFT: 11,
        Additive: 12,
        Multiplicative: 13,
        Exponentiation: 14,
        Await: 15,
        Unary: 15,
        Postfix: 16,
        OptionalChaining: 17,
        Call: 18,
        New: 19,
        TaggedTemplate: 20,
        Member: 21,
        Primary: 22
      };
      BinaryPrecedence = {
        "??": Precedence.Coalesce,
        "||": Precedence.LogicalOR,
        "&&": Precedence.LogicalAND,
        "|": Precedence.BitwiseOR,
        "^": Precedence.BitwiseXOR,
        "&": Precedence.BitwiseAND,
        "==": Precedence.Equality,
        "!=": Precedence.Equality,
        "===": Precedence.Equality,
        "!==": Precedence.Equality,
        "is": Precedence.Equality,
        "isnt": Precedence.Equality,
        "<": Precedence.Relational,
        ">": Precedence.Relational,
        "<=": Precedence.Relational,
        ">=": Precedence.Relational,
        "in": Precedence.Relational,
        "instanceof": Precedence.Relational,
        "<<": Precedence.BitwiseSHIFT,
        ">>": Precedence.BitwiseSHIFT,
        ">>>": Precedence.BitwiseSHIFT,
        "+": Precedence.Additive,
        "-": Precedence.Additive,
        "*": Precedence.Multiplicative,
        "%": Precedence.Multiplicative,
        "/": Precedence.Multiplicative,
        "**": Precedence.Exponentiation
      };
      var F_ALLOW_IN = 1, F_ALLOW_CALL = 1 << 1, F_ALLOW_UNPARATH_NEW = 1 << 2, F_FUNC_BODY = 1 << 3, F_DIRECTIVE_CTX = 1 << 4, F_SEMICOLON_OPT = 1 << 5, F_FOUND_COALESCE = 1 << 6;
      var E_FTT = F_ALLOW_CALL | F_ALLOW_UNPARATH_NEW, E_TTF = F_ALLOW_IN | F_ALLOW_CALL, E_TTT = F_ALLOW_IN | F_ALLOW_CALL | F_ALLOW_UNPARATH_NEW, E_TFF = F_ALLOW_IN, E_FFT = F_ALLOW_UNPARATH_NEW, E_TFT = F_ALLOW_IN | F_ALLOW_UNPARATH_NEW;
      var S_TFFF = F_ALLOW_IN, S_TFFT = F_ALLOW_IN | F_SEMICOLON_OPT, S_FFFF = 0, S_TFTF = F_ALLOW_IN | F_DIRECTIVE_CTX, S_TTFF = F_ALLOW_IN | F_FUNC_BODY;
      function getDefaultOptions() {
        return {
          indent: null,
          base: null,
          parse: null,
          comment: false,
          format: {
            indent: {
              style: "    ",
              base: 0,
              adjustMultilineComment: false
            },
            newline: "\n",
            space: " ",
            json: false,
            renumber: false,
            hexadecimal: false,
            quotes: "single",
            escapeless: false,
            compact: false,
            parentheses: true,
            semicolons: true,
            safeConcatenation: false,
            preserveBlankLines: false
          },
          moz: {
            comprehensionExpressionStartsWithAssignment: false,
            starlessGenerator: false
          },
          sourceMap: null,
          sourceMapRoot: null,
          sourceMapWithCode: false,
          directive: false,
          raw: true,
          verbatim: null,
          sourceCode: null
        };
      }
      function stringRepeat(str, num) {
        var result = "";
        for (num |= 0; num > 0; num >>>= 1, str += str) {
          if (num & 1) {
            result += str;
          }
        }
        return result;
      }
      function hasLineTerminator(str) {
        return /[\r\n]/g.test(str);
      }
      function endsWithLineTerminator(str) {
        var len = str.length;
        return len && esutils.code.isLineTerminator(str.charCodeAt(len - 1));
      }
      function merge3(target, override) {
        var key;
        for (key in override) {
          if (override.hasOwnProperty(key)) {
            target[key] = override[key];
          }
        }
        return target;
      }
      function updateDeeply(target, override) {
        var key, val;
        function isHashObject(target2) {
          return typeof target2 === "object" && target2 instanceof Object && !(target2 instanceof RegExp);
        }
        for (key in override) {
          if (override.hasOwnProperty(key)) {
            val = override[key];
            if (isHashObject(val)) {
              if (isHashObject(target[key])) {
                updateDeeply(target[key], val);
              } else {
                target[key] = updateDeeply({}, val);
              }
            } else {
              target[key] = val;
            }
          }
        }
        return target;
      }
      function generateNumber(value) {
        var result, point, temp, exponent, pos;
        if (value !== value) {
          throw new Error("Numeric literal whose value is NaN");
        }
        if (value < 0 || value === 0 && 1 / value < 0) {
          throw new Error("Numeric literal whose value is negative");
        }
        if (value === 1 / 0) {
          return json3 ? "null" : renumber ? "1e400" : "1e+400";
        }
        result = "" + value;
        if (!renumber || result.length < 3) {
          return result;
        }
        point = result.indexOf(".");
        if (!json3 && result.charCodeAt(0) === 48 && point === 1) {
          point = 0;
          result = result.slice(1);
        }
        temp = result;
        result = result.replace("e+", "e");
        exponent = 0;
        if ((pos = temp.indexOf("e")) > 0) {
          exponent = +temp.slice(pos + 1);
          temp = temp.slice(0, pos);
        }
        if (point >= 0) {
          exponent -= temp.length - point - 1;
          temp = +(temp.slice(0, point) + temp.slice(point + 1)) + "";
        }
        pos = 0;
        while (temp.charCodeAt(temp.length + pos - 1) === 48) {
          --pos;
        }
        if (pos !== 0) {
          exponent -= pos;
          temp = temp.slice(0, pos);
        }
        if (exponent !== 0) {
          temp += "e" + exponent;
        }
        if ((temp.length < result.length || hexadecimal && value > 1e12 && Math.floor(value) === value && (temp = "0x" + value.toString(16)).length < result.length) && +temp === value) {
          result = temp;
        }
        return result;
      }
      function escapeRegExpCharacter(ch, previousIsBackslash) {
        if ((ch & ~1) === 8232) {
          return (previousIsBackslash ? "u" : "\\u") + (ch === 8232 ? "2028" : "2029");
        } else if (ch === 10 || ch === 13) {
          return (previousIsBackslash ? "" : "\\") + (ch === 10 ? "n" : "r");
        }
        return String.fromCharCode(ch);
      }
      function generateRegExp(reg) {
        var match, result, flags, i, iz, ch, characterInBrack, previousIsBackslash;
        result = reg.toString();
        if (reg.source) {
          match = result.match(/\/([^/]*)$/);
          if (!match) {
            return result;
          }
          flags = match[1];
          result = "";
          characterInBrack = false;
          previousIsBackslash = false;
          for (i = 0, iz = reg.source.length; i < iz; ++i) {
            ch = reg.source.charCodeAt(i);
            if (!previousIsBackslash) {
              if (characterInBrack) {
                if (ch === 93) {
                  characterInBrack = false;
                }
              } else {
                if (ch === 47) {
                  result += "\\";
                } else if (ch === 91) {
                  characterInBrack = true;
                }
              }
              result += escapeRegExpCharacter(ch, previousIsBackslash);
              previousIsBackslash = ch === 92;
            } else {
              result += escapeRegExpCharacter(ch, previousIsBackslash);
              previousIsBackslash = false;
            }
          }
          return "/" + result + "/" + flags;
        }
        return result;
      }
      function escapeAllowedCharacter(code, next) {
        var hex5;
        if (code === 8) {
          return "\\b";
        }
        if (code === 12) {
          return "\\f";
        }
        if (code === 9) {
          return "\\t";
        }
        hex5 = code.toString(16).toUpperCase();
        if (json3 || code > 255) {
          return "\\u" + "0000".slice(hex5.length) + hex5;
        } else if (code === 0 && !esutils.code.isDecimalDigit(next)) {
          return "\\0";
        } else if (code === 11) {
          return "\\x0B";
        } else {
          return "\\x" + "00".slice(hex5.length) + hex5;
        }
      }
      function escapeDisallowedCharacter(code) {
        if (code === 92) {
          return "\\\\";
        }
        if (code === 10) {
          return "\\n";
        }
        if (code === 13) {
          return "\\r";
        }
        if (code === 8232) {
          return "\\u2028";
        }
        if (code === 8233) {
          return "\\u2029";
        }
        throw new Error("Incorrectly classified character");
      }
      function escapeDirective(str) {
        var i, iz, code, quote;
        quote = quotes === "double" ? '"' : "'";
        for (i = 0, iz = str.length; i < iz; ++i) {
          code = str.charCodeAt(i);
          if (code === 39) {
            quote = '"';
            break;
          } else if (code === 34) {
            quote = "'";
            break;
          } else if (code === 92) {
            ++i;
          }
        }
        return quote + str + quote;
      }
      function escapeString(str) {
        var result = "", i, len, code, singleQuotes = 0, doubleQuotes = 0, single, quote;
        for (i = 0, len = str.length; i < len; ++i) {
          code = str.charCodeAt(i);
          if (code === 39) {
            ++singleQuotes;
          } else if (code === 34) {
            ++doubleQuotes;
          } else if (code === 47 && json3) {
            result += "\\";
          } else if (esutils.code.isLineTerminator(code) || code === 92) {
            result += escapeDisallowedCharacter(code);
            continue;
          } else if (!esutils.code.isIdentifierPartES5(code) && (json3 && code < 32 || !json3 && !escapeless && (code < 32 || code > 126))) {
            result += escapeAllowedCharacter(code, str.charCodeAt(i + 1));
            continue;
          }
          result += String.fromCharCode(code);
        }
        single = !(quotes === "double" || quotes === "auto" && doubleQuotes < singleQuotes);
        quote = single ? "'" : '"';
        if (!(single ? singleQuotes : doubleQuotes)) {
          return quote + result + quote;
        }
        str = result;
        result = quote;
        for (i = 0, len = str.length; i < len; ++i) {
          code = str.charCodeAt(i);
          if (code === 39 && single || code === 34 && !single) {
            result += "\\";
          }
          result += String.fromCharCode(code);
        }
        return result + quote;
      }
      function flattenToString(arr) {
        var i, iz, elem, result = "";
        for (i = 0, iz = arr.length; i < iz; ++i) {
          elem = arr[i];
          result += Array.isArray(elem) ? flattenToString(elem) : elem;
        }
        return result;
      }
      function toSourceNodeWhenNeeded(generated, node) {
        if (!sourceMap) {
          if (Array.isArray(generated)) {
            return flattenToString(generated);
          } else {
            return generated;
          }
        }
        if (node == null) {
          if (generated instanceof SourceNode) {
            return generated;
          } else {
            node = {};
          }
        }
        if (node.loc == null) {
          return new SourceNode(null, null, sourceMap, generated, node.name || null);
        }
        return new SourceNode(node.loc.start.line, node.loc.start.column, sourceMap === true ? node.loc.source || null : sourceMap, generated, node.name || null);
      }
      function noEmptySpace() {
        return space2 ? space2 : " ";
      }
      function join9(left, right) {
        var leftSource, rightSource, leftCharCode, rightCharCode;
        leftSource = toSourceNodeWhenNeeded(left).toString();
        if (leftSource.length === 0) {
          return [right];
        }
        rightSource = toSourceNodeWhenNeeded(right).toString();
        if (rightSource.length === 0) {
          return [left];
        }
        leftCharCode = leftSource.charCodeAt(leftSource.length - 1);
        rightCharCode = rightSource.charCodeAt(0);
        if ((leftCharCode === 43 || leftCharCode === 45) && leftCharCode === rightCharCode || esutils.code.isIdentifierPartES5(leftCharCode) && esutils.code.isIdentifierPartES5(rightCharCode) || leftCharCode === 47 && rightCharCode === 105) {
          return [left, noEmptySpace(), right];
        } else if (esutils.code.isWhiteSpace(leftCharCode) || esutils.code.isLineTerminator(leftCharCode) || esutils.code.isWhiteSpace(rightCharCode) || esutils.code.isLineTerminator(rightCharCode)) {
          return [left, right];
        }
        return [left, space2, right];
      }
      function addIndent(stmt) {
        return [base, stmt];
      }
      function withIndent(fn) {
        var previousBase;
        previousBase = base;
        base += indent;
        fn(base);
        base = previousBase;
      }
      function calculateSpaces(str) {
        var i;
        for (i = str.length - 1; i >= 0; --i) {
          if (esutils.code.isLineTerminator(str.charCodeAt(i))) {
            break;
          }
        }
        return str.length - 1 - i;
      }
      function adjustMultilineComment(value, specialBase) {
        var array3, i, len, line, j, spaces, previousBase, sn;
        array3 = value.split(/\r\n|[\r\n]/);
        spaces = Number.MAX_VALUE;
        for (i = 1, len = array3.length; i < len; ++i) {
          line = array3[i];
          j = 0;
          while (j < line.length && esutils.code.isWhiteSpace(line.charCodeAt(j))) {
            ++j;
          }
          if (spaces > j) {
            spaces = j;
          }
        }
        if (typeof specialBase !== "undefined") {
          previousBase = base;
          if (array3[1][spaces] === "*") {
            specialBase += " ";
          }
          base = specialBase;
        } else {
          if (spaces & 1) {
            --spaces;
          }
          previousBase = base;
        }
        for (i = 1, len = array3.length; i < len; ++i) {
          sn = toSourceNodeWhenNeeded(addIndent(array3[i].slice(spaces)));
          array3[i] = sourceMap ? sn.join("") : sn;
        }
        base = previousBase;
        return array3.join("\n");
      }
      function generateComment(comment, specialBase) {
        if (comment.type === "Line") {
          if (endsWithLineTerminator(comment.value)) {
            return "//" + comment.value;
          } else {
            var result = "//" + comment.value;
            if (!preserveBlankLines) {
              result += "\n";
            }
            return result;
          }
        }
        if (extra.format.indent.adjustMultilineComment && /[\n\r]/.test(comment.value)) {
          return adjustMultilineComment("/*" + comment.value + "*/", specialBase);
        }
        return "/*" + comment.value + "*/";
      }
      function addComments(stmt, result) {
        var i, len, comment, save, tailingToStatement, specialBase, fragment, extRange, range, prevRange, prefix, infix, suffix, count;
        if (stmt.leadingComments && stmt.leadingComments.length > 0) {
          save = result;
          if (preserveBlankLines) {
            comment = stmt.leadingComments[0];
            result = [];
            extRange = comment.extendedRange;
            range = comment.range;
            prefix = sourceCode.substring(extRange[0], range[0]);
            count = (prefix.match(/\n/g) || []).length;
            if (count > 0) {
              result.push(stringRepeat("\n", count));
              result.push(addIndent(generateComment(comment)));
            } else {
              result.push(prefix);
              result.push(generateComment(comment));
            }
            prevRange = range;
            for (i = 1, len = stmt.leadingComments.length; i < len; i++) {
              comment = stmt.leadingComments[i];
              range = comment.range;
              infix = sourceCode.substring(prevRange[1], range[0]);
              count = (infix.match(/\n/g) || []).length;
              result.push(stringRepeat("\n", count));
              result.push(addIndent(generateComment(comment)));
              prevRange = range;
            }
            suffix = sourceCode.substring(range[1], extRange[1]);
            count = (suffix.match(/\n/g) || []).length;
            result.push(stringRepeat("\n", count));
          } else {
            comment = stmt.leadingComments[0];
            result = [];
            if (safeConcatenation && stmt.type === Syntax.Program && stmt.body.length === 0) {
              result.push("\n");
            }
            result.push(generateComment(comment));
            if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
              result.push("\n");
            }
            for (i = 1, len = stmt.leadingComments.length; i < len; ++i) {
              comment = stmt.leadingComments[i];
              fragment = [generateComment(comment)];
              if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
                fragment.push("\n");
              }
              result.push(addIndent(fragment));
            }
          }
          result.push(addIndent(save));
        }
        if (stmt.trailingComments) {
          if (preserveBlankLines) {
            comment = stmt.trailingComments[0];
            extRange = comment.extendedRange;
            range = comment.range;
            prefix = sourceCode.substring(extRange[0], range[0]);
            count = (prefix.match(/\n/g) || []).length;
            if (count > 0) {
              result.push(stringRepeat("\n", count));
              result.push(addIndent(generateComment(comment)));
            } else {
              result.push(prefix);
              result.push(generateComment(comment));
            }
          } else {
            tailingToStatement = !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString());
            specialBase = stringRepeat(" ", calculateSpaces(toSourceNodeWhenNeeded([base, result, indent]).toString()));
            for (i = 0, len = stmt.trailingComments.length; i < len; ++i) {
              comment = stmt.trailingComments[i];
              if (tailingToStatement) {
                if (i === 0) {
                  result = [result, indent];
                } else {
                  result = [result, specialBase];
                }
                result.push(generateComment(comment, specialBase));
              } else {
                result = [result, addIndent(generateComment(comment))];
              }
              if (i !== len - 1 && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
                result = [result, "\n"];
              }
            }
          }
        }
        return result;
      }
      function generateBlankLines(start, end, result) {
        var j, newlineCount = 0;
        for (j = start; j < end; j++) {
          if (sourceCode[j] === "\n") {
            newlineCount++;
          }
        }
        for (j = 1; j < newlineCount; j++) {
          result.push(newline2);
        }
      }
      function parenthesize(text, current, should) {
        if (current < should) {
          return ["(", text, ")"];
        }
        return text;
      }
      function generateVerbatimString(string7) {
        var i, iz, result;
        result = string7.split(/\r\n|\n/);
        for (i = 1, iz = result.length; i < iz; i++) {
          result[i] = newline2 + base + result[i];
        }
        return result;
      }
      function generateVerbatim(expr, precedence) {
        var verbatim, result, prec;
        verbatim = expr[extra.verbatim];
        if (typeof verbatim === "string") {
          result = parenthesize(generateVerbatimString(verbatim), Precedence.Sequence, precedence);
        } else {
          result = generateVerbatimString(verbatim.content);
          prec = verbatim.precedence != null ? verbatim.precedence : Precedence.Sequence;
          result = parenthesize(result, prec, precedence);
        }
        return toSourceNodeWhenNeeded(result, expr);
      }
      function CodeGenerator() {
      }
      CodeGenerator.prototype.maybeBlock = function(stmt, flags) {
        var result, noLeadingComment, that = this;
        noLeadingComment = !extra.comment || !stmt.leadingComments;
        if (stmt.type === Syntax.BlockStatement && noLeadingComment) {
          return [space2, this.generateStatement(stmt, flags)];
        }
        if (stmt.type === Syntax.EmptyStatement && noLeadingComment) {
          return ";";
        }
        withIndent(function() {
          result = [
            newline2,
            addIndent(that.generateStatement(stmt, flags))
          ];
        });
        return result;
      };
      CodeGenerator.prototype.maybeBlockSuffix = function(stmt, result) {
        var ends = endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString());
        if (stmt.type === Syntax.BlockStatement && (!extra.comment || !stmt.leadingComments) && !ends) {
          return [result, space2];
        }
        if (ends) {
          return [result, base];
        }
        return [result, newline2, base];
      };
      function generateIdentifier(node) {
        return toSourceNodeWhenNeeded(node.name, node);
      }
      function generateAsyncPrefix(node, spaceRequired) {
        return node.async ? "async" + (spaceRequired ? noEmptySpace() : space2) : "";
      }
      function generateStarSuffix(node) {
        var isGenerator = node.generator && !extra.moz.starlessGenerator;
        return isGenerator ? "*" + space2 : "";
      }
      function generateMethodPrefix(prop) {
        var func = prop.value, prefix = "";
        if (func.async) {
          prefix += generateAsyncPrefix(func, !prop.computed);
        }
        if (func.generator) {
          prefix += generateStarSuffix(func) ? "*" : "";
        }
        return prefix;
      }
      CodeGenerator.prototype.generatePattern = function(node, precedence, flags) {
        if (node.type === Syntax.Identifier) {
          return generateIdentifier(node);
        }
        return this.generateExpression(node, precedence, flags);
      };
      CodeGenerator.prototype.generateFunctionParams = function(node) {
        var i, iz, result, hasDefault;
        hasDefault = false;
        if (node.type === Syntax.ArrowFunctionExpression && !node.rest && (!node.defaults || node.defaults.length === 0) && node.params.length === 1 && node.params[0].type === Syntax.Identifier) {
          result = [generateAsyncPrefix(node, true), generateIdentifier(node.params[0])];
        } else {
          result = node.type === Syntax.ArrowFunctionExpression ? [generateAsyncPrefix(node, false)] : [];
          result.push("(");
          if (node.defaults) {
            hasDefault = true;
          }
          for (i = 0, iz = node.params.length; i < iz; ++i) {
            if (hasDefault && node.defaults[i]) {
              result.push(this.generateAssignment(node.params[i], node.defaults[i], "=", Precedence.Assignment, E_TTT));
            } else {
              result.push(this.generatePattern(node.params[i], Precedence.Assignment, E_TTT));
            }
            if (i + 1 < iz) {
              result.push("," + space2);
            }
          }
          if (node.rest) {
            if (node.params.length) {
              result.push("," + space2);
            }
            result.push("...");
            result.push(generateIdentifier(node.rest));
          }
          result.push(")");
        }
        return result;
      };
      CodeGenerator.prototype.generateFunctionBody = function(node) {
        var result, expr;
        result = this.generateFunctionParams(node);
        if (node.type === Syntax.ArrowFunctionExpression) {
          result.push(space2);
          result.push("=>");
        }
        if (node.expression) {
          result.push(space2);
          expr = this.generateExpression(node.body, Precedence.Assignment, E_TTT);
          if (expr.toString().charAt(0) === "{") {
            expr = ["(", expr, ")"];
          }
          result.push(expr);
        } else {
          result.push(this.maybeBlock(node.body, S_TTFF));
        }
        return result;
      };
      CodeGenerator.prototype.generateIterationForStatement = function(operator, stmt, flags) {
        var result = ["for" + (stmt.await ? noEmptySpace() + "await" : "") + space2 + "("], that = this;
        withIndent(function() {
          if (stmt.left.type === Syntax.VariableDeclaration) {
            withIndent(function() {
              result.push(stmt.left.kind + noEmptySpace());
              result.push(that.generateStatement(stmt.left.declarations[0], S_FFFF));
            });
          } else {
            result.push(that.generateExpression(stmt.left, Precedence.Call, E_TTT));
          }
          result = join9(result, operator);
          result = [join9(
            result,
            that.generateExpression(stmt.right, Precedence.Assignment, E_TTT)
          ), ")"];
        });
        result.push(this.maybeBlock(stmt.body, flags));
        return result;
      };
      CodeGenerator.prototype.generatePropertyKey = function(expr, computed) {
        var result = [];
        if (computed) {
          result.push("[");
        }
        result.push(this.generateExpression(expr, Precedence.Assignment, E_TTT));
        if (computed) {
          result.push("]");
        }
        return result;
      };
      CodeGenerator.prototype.generateAssignment = function(left, right, operator, precedence, flags) {
        if (Precedence.Assignment < precedence) {
          flags |= F_ALLOW_IN;
        }
        return parenthesize(
          [
            this.generateExpression(left, Precedence.Call, flags),
            space2 + operator + space2,
            this.generateExpression(right, Precedence.Assignment, flags)
          ],
          Precedence.Assignment,
          precedence
        );
      };
      CodeGenerator.prototype.semicolon = function(flags) {
        if (!semicolons && flags & F_SEMICOLON_OPT) {
          return "";
        }
        return ";";
      };
      CodeGenerator.Statement = {
        BlockStatement: function(stmt, flags) {
          var range, content, result = ["{", newline2], that = this;
          withIndent(function() {
            if (stmt.body.length === 0 && preserveBlankLines) {
              range = stmt.range;
              if (range[1] - range[0] > 2) {
                content = sourceCode.substring(range[0] + 1, range[1] - 1);
                if (content[0] === "\n") {
                  result = ["{"];
                }
                result.push(content);
              }
            }
            var i, iz, fragment, bodyFlags;
            bodyFlags = S_TFFF;
            if (flags & F_FUNC_BODY) {
              bodyFlags |= F_DIRECTIVE_CTX;
            }
            for (i = 0, iz = stmt.body.length; i < iz; ++i) {
              if (preserveBlankLines) {
                if (i === 0) {
                  if (stmt.body[0].leadingComments) {
                    range = stmt.body[0].leadingComments[0].extendedRange;
                    content = sourceCode.substring(range[0], range[1]);
                    if (content[0] === "\n") {
                      result = ["{"];
                    }
                  }
                  if (!stmt.body[0].leadingComments) {
                    generateBlankLines(stmt.range[0], stmt.body[0].range[0], result);
                  }
                }
                if (i > 0) {
                  if (!stmt.body[i - 1].trailingComments && !stmt.body[i].leadingComments) {
                    generateBlankLines(stmt.body[i - 1].range[1], stmt.body[i].range[0], result);
                  }
                }
              }
              if (i === iz - 1) {
                bodyFlags |= F_SEMICOLON_OPT;
              }
              if (stmt.body[i].leadingComments && preserveBlankLines) {
                fragment = that.generateStatement(stmt.body[i], bodyFlags);
              } else {
                fragment = addIndent(that.generateStatement(stmt.body[i], bodyFlags));
              }
              result.push(fragment);
              if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
                if (preserveBlankLines && i < iz - 1) {
                  if (!stmt.body[i + 1].leadingComments) {
                    result.push(newline2);
                  }
                } else {
                  result.push(newline2);
                }
              }
              if (preserveBlankLines) {
                if (i === iz - 1) {
                  if (!stmt.body[i].trailingComments) {
                    generateBlankLines(stmt.body[i].range[1], stmt.range[1], result);
                  }
                }
              }
            }
          });
          result.push(addIndent("}"));
          return result;
        },
        BreakStatement: function(stmt, flags) {
          if (stmt.label) {
            return "break " + stmt.label.name + this.semicolon(flags);
          }
          return "break" + this.semicolon(flags);
        },
        ContinueStatement: function(stmt, flags) {
          if (stmt.label) {
            return "continue " + stmt.label.name + this.semicolon(flags);
          }
          return "continue" + this.semicolon(flags);
        },
        ClassBody: function(stmt, flags) {
          var result = ["{", newline2], that = this;
          withIndent(function(indent2) {
            var i, iz;
            for (i = 0, iz = stmt.body.length; i < iz; ++i) {
              result.push(indent2);
              result.push(that.generateExpression(stmt.body[i], Precedence.Sequence, E_TTT));
              if (i + 1 < iz) {
                result.push(newline2);
              }
            }
          });
          if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
            result.push(newline2);
          }
          result.push(base);
          result.push("}");
          return result;
        },
        ClassDeclaration: function(stmt, flags) {
          var result, fragment;
          result = ["class"];
          if (stmt.id) {
            result = join9(result, this.generateExpression(stmt.id, Precedence.Sequence, E_TTT));
          }
          if (stmt.superClass) {
            fragment = join9("extends", this.generateExpression(stmt.superClass, Precedence.Unary, E_TTT));
            result = join9(result, fragment);
          }
          result.push(space2);
          result.push(this.generateStatement(stmt.body, S_TFFT));
          return result;
        },
        DirectiveStatement: function(stmt, flags) {
          if (extra.raw && stmt.raw) {
            return stmt.raw + this.semicolon(flags);
          }
          return escapeDirective(stmt.directive) + this.semicolon(flags);
        },
        DoWhileStatement: function(stmt, flags) {
          var result = join9("do", this.maybeBlock(stmt.body, S_TFFF));
          result = this.maybeBlockSuffix(stmt.body, result);
          return join9(result, [
            "while" + space2 + "(",
            this.generateExpression(stmt.test, Precedence.Sequence, E_TTT),
            ")" + this.semicolon(flags)
          ]);
        },
        CatchClause: function(stmt, flags) {
          var result, that = this;
          withIndent(function() {
            var guard;
            if (stmt.param) {
              result = [
                "catch" + space2 + "(",
                that.generateExpression(stmt.param, Precedence.Sequence, E_TTT),
                ")"
              ];
              if (stmt.guard) {
                guard = that.generateExpression(stmt.guard, Precedence.Sequence, E_TTT);
                result.splice(2, 0, " if ", guard);
              }
            } else {
              result = ["catch"];
            }
          });
          result.push(this.maybeBlock(stmt.body, S_TFFF));
          return result;
        },
        DebuggerStatement: function(stmt, flags) {
          return "debugger" + this.semicolon(flags);
        },
        EmptyStatement: function(stmt, flags) {
          return ";";
        },
        ExportDefaultDeclaration: function(stmt, flags) {
          var result = ["export"], bodyFlags;
          bodyFlags = flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF;
          result = join9(result, "default");
          if (isStatement(stmt.declaration)) {
            result = join9(result, this.generateStatement(stmt.declaration, bodyFlags));
          } else {
            result = join9(result, this.generateExpression(stmt.declaration, Precedence.Assignment, E_TTT) + this.semicolon(flags));
          }
          return result;
        },
        ExportNamedDeclaration: function(stmt, flags) {
          var result = ["export"], bodyFlags, that = this;
          bodyFlags = flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF;
          if (stmt.declaration) {
            return join9(result, this.generateStatement(stmt.declaration, bodyFlags));
          }
          if (stmt.specifiers) {
            if (stmt.specifiers.length === 0) {
              result = join9(result, "{" + space2 + "}");
            } else if (stmt.specifiers[0].type === Syntax.ExportBatchSpecifier) {
              result = join9(result, this.generateExpression(stmt.specifiers[0], Precedence.Sequence, E_TTT));
            } else {
              result = join9(result, "{");
              withIndent(function(indent2) {
                var i, iz;
                result.push(newline2);
                for (i = 0, iz = stmt.specifiers.length; i < iz; ++i) {
                  result.push(indent2);
                  result.push(that.generateExpression(stmt.specifiers[i], Precedence.Sequence, E_TTT));
                  if (i + 1 < iz) {
                    result.push("," + newline2);
                  }
                }
              });
              if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
                result.push(newline2);
              }
              result.push(base + "}");
            }
            if (stmt.source) {
              result = join9(result, [
                "from" + space2,
                // ModuleSpecifier
                this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
                this.semicolon(flags)
              ]);
            } else {
              result.push(this.semicolon(flags));
            }
          }
          return result;
        },
        ExportAllDeclaration: function(stmt, flags) {
          return [
            "export" + space2,
            "*" + space2,
            "from" + space2,
            // ModuleSpecifier
            this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
            this.semicolon(flags)
          ];
        },
        ExpressionStatement: function(stmt, flags) {
          var result, fragment;
          function isClassPrefixed(fragment2) {
            var code;
            if (fragment2.slice(0, 5) !== "class") {
              return false;
            }
            code = fragment2.charCodeAt(5);
            return code === 123 || esutils.code.isWhiteSpace(code) || esutils.code.isLineTerminator(code);
          }
          function isFunctionPrefixed(fragment2) {
            var code;
            if (fragment2.slice(0, 8) !== "function") {
              return false;
            }
            code = fragment2.charCodeAt(8);
            return code === 40 || esutils.code.isWhiteSpace(code) || code === 42 || esutils.code.isLineTerminator(code);
          }
          function isAsyncPrefixed(fragment2) {
            var code, i, iz;
            if (fragment2.slice(0, 5) !== "async") {
              return false;
            }
            if (!esutils.code.isWhiteSpace(fragment2.charCodeAt(5))) {
              return false;
            }
            for (i = 6, iz = fragment2.length; i < iz; ++i) {
              if (!esutils.code.isWhiteSpace(fragment2.charCodeAt(i))) {
                break;
              }
            }
            if (i === iz) {
              return false;
            }
            if (fragment2.slice(i, i + 8) !== "function") {
              return false;
            }
            code = fragment2.charCodeAt(i + 8);
            return code === 40 || esutils.code.isWhiteSpace(code) || code === 42 || esutils.code.isLineTerminator(code);
          }
          result = [this.generateExpression(stmt.expression, Precedence.Sequence, E_TTT)];
          fragment = toSourceNodeWhenNeeded(result).toString();
          if (fragment.charCodeAt(0) === 123 || // ObjectExpression
          isClassPrefixed(fragment) || isFunctionPrefixed(fragment) || isAsyncPrefixed(fragment) || directive && flags & F_DIRECTIVE_CTX && stmt.expression.type === Syntax.Literal && typeof stmt.expression.value === "string") {
            result = ["(", result, ")" + this.semicolon(flags)];
          } else {
            result.push(this.semicolon(flags));
          }
          return result;
        },
        ImportDeclaration: function(stmt, flags) {
          var result, cursor, that = this;
          if (stmt.specifiers.length === 0) {
            return [
              "import",
              space2,
              // ModuleSpecifier
              this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
              this.semicolon(flags)
            ];
          }
          result = [
            "import"
          ];
          cursor = 0;
          if (stmt.specifiers[cursor].type === Syntax.ImportDefaultSpecifier) {
            result = join9(result, [
              this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT)
            ]);
            ++cursor;
          }
          if (stmt.specifiers[cursor]) {
            if (cursor !== 0) {
              result.push(",");
            }
            if (stmt.specifiers[cursor].type === Syntax.ImportNamespaceSpecifier) {
              result = join9(result, [
                space2,
                this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT)
              ]);
            } else {
              result.push(space2 + "{");
              if (stmt.specifiers.length - cursor === 1) {
                result.push(space2);
                result.push(this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT));
                result.push(space2 + "}" + space2);
              } else {
                withIndent(function(indent2) {
                  var i, iz;
                  result.push(newline2);
                  for (i = cursor, iz = stmt.specifiers.length; i < iz; ++i) {
                    result.push(indent2);
                    result.push(that.generateExpression(stmt.specifiers[i], Precedence.Sequence, E_TTT));
                    if (i + 1 < iz) {
                      result.push("," + newline2);
                    }
                  }
                });
                if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
                  result.push(newline2);
                }
                result.push(base + "}" + space2);
              }
            }
          }
          result = join9(result, [
            "from" + space2,
            // ModuleSpecifier
            this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
            this.semicolon(flags)
          ]);
          return result;
        },
        VariableDeclarator: function(stmt, flags) {
          var itemFlags = flags & F_ALLOW_IN ? E_TTT : E_FTT;
          if (stmt.init) {
            return [
              this.generateExpression(stmt.id, Precedence.Assignment, itemFlags),
              space2,
              "=",
              space2,
              this.generateExpression(stmt.init, Precedence.Assignment, itemFlags)
            ];
          }
          return this.generatePattern(stmt.id, Precedence.Assignment, itemFlags);
        },
        VariableDeclaration: function(stmt, flags) {
          var result, i, iz, node, bodyFlags, that = this;
          result = [stmt.kind];
          bodyFlags = flags & F_ALLOW_IN ? S_TFFF : S_FFFF;
          function block() {
            node = stmt.declarations[0];
            if (extra.comment && node.leadingComments) {
              result.push("\n");
              result.push(addIndent(that.generateStatement(node, bodyFlags)));
            } else {
              result.push(noEmptySpace());
              result.push(that.generateStatement(node, bodyFlags));
            }
            for (i = 1, iz = stmt.declarations.length; i < iz; ++i) {
              node = stmt.declarations[i];
              if (extra.comment && node.leadingComments) {
                result.push("," + newline2);
                result.push(addIndent(that.generateStatement(node, bodyFlags)));
              } else {
                result.push("," + space2);
                result.push(that.generateStatement(node, bodyFlags));
              }
            }
          }
          if (stmt.declarations.length > 1) {
            withIndent(block);
          } else {
            block();
          }
          result.push(this.semicolon(flags));
          return result;
        },
        ThrowStatement: function(stmt, flags) {
          return [join9(
            "throw",
            this.generateExpression(stmt.argument, Precedence.Sequence, E_TTT)
          ), this.semicolon(flags)];
        },
        TryStatement: function(stmt, flags) {
          var result, i, iz, guardedHandlers;
          result = ["try", this.maybeBlock(stmt.block, S_TFFF)];
          result = this.maybeBlockSuffix(stmt.block, result);
          if (stmt.handlers) {
            for (i = 0, iz = stmt.handlers.length; i < iz; ++i) {
              result = join9(result, this.generateStatement(stmt.handlers[i], S_TFFF));
              if (stmt.finalizer || i + 1 !== iz) {
                result = this.maybeBlockSuffix(stmt.handlers[i].body, result);
              }
            }
          } else {
            guardedHandlers = stmt.guardedHandlers || [];
            for (i = 0, iz = guardedHandlers.length; i < iz; ++i) {
              result = join9(result, this.generateStatement(guardedHandlers[i], S_TFFF));
              if (stmt.finalizer || i + 1 !== iz) {
                result = this.maybeBlockSuffix(guardedHandlers[i].body, result);
              }
            }
            if (stmt.handler) {
              if (Array.isArray(stmt.handler)) {
                for (i = 0, iz = stmt.handler.length; i < iz; ++i) {
                  result = join9(result, this.generateStatement(stmt.handler[i], S_TFFF));
                  if (stmt.finalizer || i + 1 !== iz) {
                    result = this.maybeBlockSuffix(stmt.handler[i].body, result);
                  }
                }
              } else {
                result = join9(result, this.generateStatement(stmt.handler, S_TFFF));
                if (stmt.finalizer) {
                  result = this.maybeBlockSuffix(stmt.handler.body, result);
                }
              }
            }
          }
          if (stmt.finalizer) {
            result = join9(result, ["finally", this.maybeBlock(stmt.finalizer, S_TFFF)]);
          }
          return result;
        },
        SwitchStatement: function(stmt, flags) {
          var result, fragment, i, iz, bodyFlags, that = this;
          withIndent(function() {
            result = [
              "switch" + space2 + "(",
              that.generateExpression(stmt.discriminant, Precedence.Sequence, E_TTT),
              ")" + space2 + "{" + newline2
            ];
          });
          if (stmt.cases) {
            bodyFlags = S_TFFF;
            for (i = 0, iz = stmt.cases.length; i < iz; ++i) {
              if (i === iz - 1) {
                bodyFlags |= F_SEMICOLON_OPT;
              }
              fragment = addIndent(this.generateStatement(stmt.cases[i], bodyFlags));
              result.push(fragment);
              if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
                result.push(newline2);
              }
            }
          }
          result.push(addIndent("}"));
          return result;
        },
        SwitchCase: function(stmt, flags) {
          var result, fragment, i, iz, bodyFlags, that = this;
          withIndent(function() {
            if (stmt.test) {
              result = [
                join9("case", that.generateExpression(stmt.test, Precedence.Sequence, E_TTT)),
                ":"
              ];
            } else {
              result = ["default:"];
            }
            i = 0;
            iz = stmt.consequent.length;
            if (iz && stmt.consequent[0].type === Syntax.BlockStatement) {
              fragment = that.maybeBlock(stmt.consequent[0], S_TFFF);
              result.push(fragment);
              i = 1;
            }
            if (i !== iz && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
              result.push(newline2);
            }
            bodyFlags = S_TFFF;
            for (; i < iz; ++i) {
              if (i === iz - 1 && flags & F_SEMICOLON_OPT) {
                bodyFlags |= F_SEMICOLON_OPT;
              }
              fragment = addIndent(that.generateStatement(stmt.consequent[i], bodyFlags));
              result.push(fragment);
              if (i + 1 !== iz && !endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
                result.push(newline2);
              }
            }
          });
          return result;
        },
        IfStatement: function(stmt, flags) {
          var result, bodyFlags, semicolonOptional, that = this;
          withIndent(function() {
            result = [
              "if" + space2 + "(",
              that.generateExpression(stmt.test, Precedence.Sequence, E_TTT),
              ")"
            ];
          });
          semicolonOptional = flags & F_SEMICOLON_OPT;
          bodyFlags = S_TFFF;
          if (semicolonOptional) {
            bodyFlags |= F_SEMICOLON_OPT;
          }
          if (stmt.alternate) {
            result.push(this.maybeBlock(stmt.consequent, S_TFFF));
            result = this.maybeBlockSuffix(stmt.consequent, result);
            if (stmt.alternate.type === Syntax.IfStatement) {
              result = join9(result, ["else ", this.generateStatement(stmt.alternate, bodyFlags)]);
            } else {
              result = join9(result, join9("else", this.maybeBlock(stmt.alternate, bodyFlags)));
            }
          } else {
            result.push(this.maybeBlock(stmt.consequent, bodyFlags));
          }
          return result;
        },
        ForStatement: function(stmt, flags) {
          var result, that = this;
          withIndent(function() {
            result = ["for" + space2 + "("];
            if (stmt.init) {
              if (stmt.init.type === Syntax.VariableDeclaration) {
                result.push(that.generateStatement(stmt.init, S_FFFF));
              } else {
                result.push(that.generateExpression(stmt.init, Precedence.Sequence, E_FTT));
                result.push(";");
              }
            } else {
              result.push(";");
            }
            if (stmt.test) {
              result.push(space2);
              result.push(that.generateExpression(stmt.test, Precedence.Sequence, E_TTT));
              result.push(";");
            } else {
              result.push(";");
            }
            if (stmt.update) {
              result.push(space2);
              result.push(that.generateExpression(stmt.update, Precedence.Sequence, E_TTT));
              result.push(")");
            } else {
              result.push(")");
            }
          });
          result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF));
          return result;
        },
        ForInStatement: function(stmt, flags) {
          return this.generateIterationForStatement("in", stmt, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF);
        },
        ForOfStatement: function(stmt, flags) {
          return this.generateIterationForStatement("of", stmt, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF);
        },
        LabeledStatement: function(stmt, flags) {
          return [stmt.label.name + ":", this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF)];
        },
        Program: function(stmt, flags) {
          var result, fragment, i, iz, bodyFlags;
          iz = stmt.body.length;
          result = [safeConcatenation && iz > 0 ? "\n" : ""];
          bodyFlags = S_TFTF;
          for (i = 0; i < iz; ++i) {
            if (!safeConcatenation && i === iz - 1) {
              bodyFlags |= F_SEMICOLON_OPT;
            }
            if (preserveBlankLines) {
              if (i === 0) {
                if (!stmt.body[0].leadingComments) {
                  generateBlankLines(stmt.range[0], stmt.body[i].range[0], result);
                }
              }
              if (i > 0) {
                if (!stmt.body[i - 1].trailingComments && !stmt.body[i].leadingComments) {
                  generateBlankLines(stmt.body[i - 1].range[1], stmt.body[i].range[0], result);
                }
              }
            }
            fragment = addIndent(this.generateStatement(stmt.body[i], bodyFlags));
            result.push(fragment);
            if (i + 1 < iz && !endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
              if (preserveBlankLines) {
                if (!stmt.body[i + 1].leadingComments) {
                  result.push(newline2);
                }
              } else {
                result.push(newline2);
              }
            }
            if (preserveBlankLines) {
              if (i === iz - 1) {
                if (!stmt.body[i].trailingComments) {
                  generateBlankLines(stmt.body[i].range[1], stmt.range[1], result);
                }
              }
            }
          }
          return result;
        },
        FunctionDeclaration: function(stmt, flags) {
          return [
            generateAsyncPrefix(stmt, true),
            "function",
            generateStarSuffix(stmt) || noEmptySpace(),
            stmt.id ? generateIdentifier(stmt.id) : "",
            this.generateFunctionBody(stmt)
          ];
        },
        ReturnStatement: function(stmt, flags) {
          if (stmt.argument) {
            return [join9(
              "return",
              this.generateExpression(stmt.argument, Precedence.Sequence, E_TTT)
            ), this.semicolon(flags)];
          }
          return ["return" + this.semicolon(flags)];
        },
        WhileStatement: function(stmt, flags) {
          var result, that = this;
          withIndent(function() {
            result = [
              "while" + space2 + "(",
              that.generateExpression(stmt.test, Precedence.Sequence, E_TTT),
              ")"
            ];
          });
          result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF));
          return result;
        },
        WithStatement: function(stmt, flags) {
          var result, that = this;
          withIndent(function() {
            result = [
              "with" + space2 + "(",
              that.generateExpression(stmt.object, Precedence.Sequence, E_TTT),
              ")"
            ];
          });
          result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF));
          return result;
        }
      };
      merge3(CodeGenerator.prototype, CodeGenerator.Statement);
      CodeGenerator.Expression = {
        SequenceExpression: function(expr, precedence, flags) {
          var result, i, iz;
          if (Precedence.Sequence < precedence) {
            flags |= F_ALLOW_IN;
          }
          result = [];
          for (i = 0, iz = expr.expressions.length; i < iz; ++i) {
            result.push(this.generateExpression(expr.expressions[i], Precedence.Assignment, flags));
            if (i + 1 < iz) {
              result.push("," + space2);
            }
          }
          return parenthesize(result, Precedence.Sequence, precedence);
        },
        AssignmentExpression: function(expr, precedence, flags) {
          return this.generateAssignment(expr.left, expr.right, expr.operator, precedence, flags);
        },
        ArrowFunctionExpression: function(expr, precedence, flags) {
          return parenthesize(this.generateFunctionBody(expr), Precedence.ArrowFunction, precedence);
        },
        ConditionalExpression: function(expr, precedence, flags) {
          if (Precedence.Conditional < precedence) {
            flags |= F_ALLOW_IN;
          }
          return parenthesize(
            [
              this.generateExpression(expr.test, Precedence.Coalesce, flags),
              space2 + "?" + space2,
              this.generateExpression(expr.consequent, Precedence.Assignment, flags),
              space2 + ":" + space2,
              this.generateExpression(expr.alternate, Precedence.Assignment, flags)
            ],
            Precedence.Conditional,
            precedence
          );
        },
        LogicalExpression: function(expr, precedence, flags) {
          if (expr.operator === "??") {
            flags |= F_FOUND_COALESCE;
          }
          return this.BinaryExpression(expr, precedence, flags);
        },
        BinaryExpression: function(expr, precedence, flags) {
          var result, leftPrecedence, rightPrecedence, currentPrecedence, fragment, leftSource;
          currentPrecedence = BinaryPrecedence[expr.operator];
          leftPrecedence = expr.operator === "**" ? Precedence.Postfix : currentPrecedence;
          rightPrecedence = expr.operator === "**" ? currentPrecedence : currentPrecedence + 1;
          if (currentPrecedence < precedence) {
            flags |= F_ALLOW_IN;
          }
          fragment = this.generateExpression(expr.left, leftPrecedence, flags);
          leftSource = fragment.toString();
          if (leftSource.charCodeAt(leftSource.length - 1) === 47 && esutils.code.isIdentifierPartES5(expr.operator.charCodeAt(0))) {
            result = [fragment, noEmptySpace(), expr.operator];
          } else {
            result = join9(fragment, expr.operator);
          }
          fragment = this.generateExpression(expr.right, rightPrecedence, flags);
          if (expr.operator === "/" && fragment.toString().charAt(0) === "/" || expr.operator.slice(-1) === "<" && fragment.toString().slice(0, 3) === "!--") {
            result.push(noEmptySpace());
            result.push(fragment);
          } else {
            result = join9(result, fragment);
          }
          if (expr.operator === "in" && !(flags & F_ALLOW_IN)) {
            return ["(", result, ")"];
          }
          if ((expr.operator === "||" || expr.operator === "&&") && flags & F_FOUND_COALESCE) {
            return ["(", result, ")"];
          }
          return parenthesize(result, currentPrecedence, precedence);
        },
        CallExpression: function(expr, precedence, flags) {
          var result, i, iz;
          result = [this.generateExpression(expr.callee, Precedence.Call, E_TTF)];
          if (expr.optional) {
            result.push("?.");
          }
          result.push("(");
          for (i = 0, iz = expr["arguments"].length; i < iz; ++i) {
            result.push(this.generateExpression(expr["arguments"][i], Precedence.Assignment, E_TTT));
            if (i + 1 < iz) {
              result.push("," + space2);
            }
          }
          result.push(")");
          if (!(flags & F_ALLOW_CALL)) {
            return ["(", result, ")"];
          }
          return parenthesize(result, Precedence.Call, precedence);
        },
        ChainExpression: function(expr, precedence, flags) {
          if (Precedence.OptionalChaining < precedence) {
            flags |= F_ALLOW_CALL;
          }
          var result = this.generateExpression(expr.expression, Precedence.OptionalChaining, flags);
          return parenthesize(result, Precedence.OptionalChaining, precedence);
        },
        NewExpression: function(expr, precedence, flags) {
          var result, length, i, iz, itemFlags;
          length = expr["arguments"].length;
          itemFlags = flags & F_ALLOW_UNPARATH_NEW && !parentheses && length === 0 ? E_TFT : E_TFF;
          result = join9(
            "new",
            this.generateExpression(expr.callee, Precedence.New, itemFlags)
          );
          if (!(flags & F_ALLOW_UNPARATH_NEW) || parentheses || length > 0) {
            result.push("(");
            for (i = 0, iz = length; i < iz; ++i) {
              result.push(this.generateExpression(expr["arguments"][i], Precedence.Assignment, E_TTT));
              if (i + 1 < iz) {
                result.push("," + space2);
              }
            }
            result.push(")");
          }
          return parenthesize(result, Precedence.New, precedence);
        },
        MemberExpression: function(expr, precedence, flags) {
          var result, fragment;
          result = [this.generateExpression(expr.object, Precedence.Call, flags & F_ALLOW_CALL ? E_TTF : E_TFF)];
          if (expr.computed) {
            if (expr.optional) {
              result.push("?.");
            }
            result.push("[");
            result.push(this.generateExpression(expr.property, Precedence.Sequence, flags & F_ALLOW_CALL ? E_TTT : E_TFT));
            result.push("]");
          } else {
            if (!expr.optional && expr.object.type === Syntax.Literal && typeof expr.object.value === "number") {
              fragment = toSourceNodeWhenNeeded(result).toString();
              if (fragment.indexOf(".") < 0 && !/[eExX]/.test(fragment) && esutils.code.isDecimalDigit(fragment.charCodeAt(fragment.length - 1)) && !(fragment.length >= 2 && fragment.charCodeAt(0) === 48)) {
                result.push(" ");
              }
            }
            result.push(expr.optional ? "?." : ".");
            result.push(generateIdentifier(expr.property));
          }
          return parenthesize(result, Precedence.Member, precedence);
        },
        MetaProperty: function(expr, precedence, flags) {
          var result;
          result = [];
          result.push(typeof expr.meta === "string" ? expr.meta : generateIdentifier(expr.meta));
          result.push(".");
          result.push(typeof expr.property === "string" ? expr.property : generateIdentifier(expr.property));
          return parenthesize(result, Precedence.Member, precedence);
        },
        UnaryExpression: function(expr, precedence, flags) {
          var result, fragment, rightCharCode, leftSource, leftCharCode;
          fragment = this.generateExpression(expr.argument, Precedence.Unary, E_TTT);
          if (space2 === "") {
            result = join9(expr.operator, fragment);
          } else {
            result = [expr.operator];
            if (expr.operator.length > 2) {
              result = join9(result, fragment);
            } else {
              leftSource = toSourceNodeWhenNeeded(result).toString();
              leftCharCode = leftSource.charCodeAt(leftSource.length - 1);
              rightCharCode = fragment.toString().charCodeAt(0);
              if ((leftCharCode === 43 || leftCharCode === 45) && leftCharCode === rightCharCode || esutils.code.isIdentifierPartES5(leftCharCode) && esutils.code.isIdentifierPartES5(rightCharCode)) {
                result.push(noEmptySpace());
                result.push(fragment);
              } else {
                result.push(fragment);
              }
            }
          }
          return parenthesize(result, Precedence.Unary, precedence);
        },
        YieldExpression: function(expr, precedence, flags) {
          var result;
          if (expr.delegate) {
            result = "yield*";
          } else {
            result = "yield";
          }
          if (expr.argument) {
            result = join9(
              result,
              this.generateExpression(expr.argument, Precedence.Yield, E_TTT)
            );
          }
          return parenthesize(result, Precedence.Yield, precedence);
        },
        AwaitExpression: function(expr, precedence, flags) {
          var result = join9(
            expr.all ? "await*" : "await",
            this.generateExpression(expr.argument, Precedence.Await, E_TTT)
          );
          return parenthesize(result, Precedence.Await, precedence);
        },
        UpdateExpression: function(expr, precedence, flags) {
          if (expr.prefix) {
            return parenthesize(
              [
                expr.operator,
                this.generateExpression(expr.argument, Precedence.Unary, E_TTT)
              ],
              Precedence.Unary,
              precedence
            );
          }
          return parenthesize(
            [
              this.generateExpression(expr.argument, Precedence.Postfix, E_TTT),
              expr.operator
            ],
            Precedence.Postfix,
            precedence
          );
        },
        FunctionExpression: function(expr, precedence, flags) {
          var result = [
            generateAsyncPrefix(expr, true),
            "function"
          ];
          if (expr.id) {
            result.push(generateStarSuffix(expr) || noEmptySpace());
            result.push(generateIdentifier(expr.id));
          } else {
            result.push(generateStarSuffix(expr) || space2);
          }
          result.push(this.generateFunctionBody(expr));
          return result;
        },
        ArrayPattern: function(expr, precedence, flags) {
          return this.ArrayExpression(expr, precedence, flags, true);
        },
        ArrayExpression: function(expr, precedence, flags, isPattern) {
          var result, multiline, that = this;
          if (!expr.elements.length) {
            return "[]";
          }
          multiline = isPattern ? false : expr.elements.length > 1;
          result = ["[", multiline ? newline2 : ""];
          withIndent(function(indent2) {
            var i, iz;
            for (i = 0, iz = expr.elements.length; i < iz; ++i) {
              if (!expr.elements[i]) {
                if (multiline) {
                  result.push(indent2);
                }
                if (i + 1 === iz) {
                  result.push(",");
                }
              } else {
                result.push(multiline ? indent2 : "");
                result.push(that.generateExpression(expr.elements[i], Precedence.Assignment, E_TTT));
              }
              if (i + 1 < iz) {
                result.push("," + (multiline ? newline2 : space2));
              }
            }
          });
          if (multiline && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
            result.push(newline2);
          }
          result.push(multiline ? base : "");
          result.push("]");
          return result;
        },
        RestElement: function(expr, precedence, flags) {
          return "..." + this.generatePattern(expr.argument);
        },
        ClassExpression: function(expr, precedence, flags) {
          var result, fragment;
          result = ["class"];
          if (expr.id) {
            result = join9(result, this.generateExpression(expr.id, Precedence.Sequence, E_TTT));
          }
          if (expr.superClass) {
            fragment = join9("extends", this.generateExpression(expr.superClass, Precedence.Unary, E_TTT));
            result = join9(result, fragment);
          }
          result.push(space2);
          result.push(this.generateStatement(expr.body, S_TFFT));
          return result;
        },
        MethodDefinition: function(expr, precedence, flags) {
          var result, fragment;
          if (expr["static"]) {
            result = ["static" + space2];
          } else {
            result = [];
          }
          if (expr.kind === "get" || expr.kind === "set") {
            fragment = [
              join9(expr.kind, this.generatePropertyKey(expr.key, expr.computed)),
              this.generateFunctionBody(expr.value)
            ];
          } else {
            fragment = [
              generateMethodPrefix(expr),
              this.generatePropertyKey(expr.key, expr.computed),
              this.generateFunctionBody(expr.value)
            ];
          }
          return join9(result, fragment);
        },
        Property: function(expr, precedence, flags) {
          if (expr.kind === "get" || expr.kind === "set") {
            return [
              expr.kind,
              noEmptySpace(),
              this.generatePropertyKey(expr.key, expr.computed),
              this.generateFunctionBody(expr.value)
            ];
          }
          if (expr.shorthand) {
            if (expr.value.type === "AssignmentPattern") {
              return this.AssignmentPattern(expr.value, Precedence.Sequence, E_TTT);
            }
            return this.generatePropertyKey(expr.key, expr.computed);
          }
          if (expr.method) {
            return [
              generateMethodPrefix(expr),
              this.generatePropertyKey(expr.key, expr.computed),
              this.generateFunctionBody(expr.value)
            ];
          }
          return [
            this.generatePropertyKey(expr.key, expr.computed),
            ":" + space2,
            this.generateExpression(expr.value, Precedence.Assignment, E_TTT)
          ];
        },
        ObjectExpression: function(expr, precedence, flags) {
          var multiline, result, fragment, that = this;
          if (!expr.properties.length) {
            return "{}";
          }
          multiline = expr.properties.length > 1;
          withIndent(function() {
            fragment = that.generateExpression(expr.properties[0], Precedence.Sequence, E_TTT);
          });
          if (!multiline) {
            if (!hasLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
              return ["{", space2, fragment, space2, "}"];
            }
          }
          withIndent(function(indent2) {
            var i, iz;
            result = ["{", newline2, indent2, fragment];
            if (multiline) {
              result.push("," + newline2);
              for (i = 1, iz = expr.properties.length; i < iz; ++i) {
                result.push(indent2);
                result.push(that.generateExpression(expr.properties[i], Precedence.Sequence, E_TTT));
                if (i + 1 < iz) {
                  result.push("," + newline2);
                }
              }
            }
          });
          if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
            result.push(newline2);
          }
          result.push(base);
          result.push("}");
          return result;
        },
        AssignmentPattern: function(expr, precedence, flags) {
          return this.generateAssignment(expr.left, expr.right, "=", precedence, flags);
        },
        ObjectPattern: function(expr, precedence, flags) {
          var result, i, iz, multiline, property, that = this;
          if (!expr.properties.length) {
            return "{}";
          }
          multiline = false;
          if (expr.properties.length === 1) {
            property = expr.properties[0];
            if (property.type === Syntax.Property && property.value.type !== Syntax.Identifier) {
              multiline = true;
            }
          } else {
            for (i = 0, iz = expr.properties.length; i < iz; ++i) {
              property = expr.properties[i];
              if (property.type === Syntax.Property && !property.shorthand) {
                multiline = true;
                break;
              }
            }
          }
          result = ["{", multiline ? newline2 : ""];
          withIndent(function(indent2) {
            var i2, iz2;
            for (i2 = 0, iz2 = expr.properties.length; i2 < iz2; ++i2) {
              result.push(multiline ? indent2 : "");
              result.push(that.generateExpression(expr.properties[i2], Precedence.Sequence, E_TTT));
              if (i2 + 1 < iz2) {
                result.push("," + (multiline ? newline2 : space2));
              }
            }
          });
          if (multiline && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
            result.push(newline2);
          }
          result.push(multiline ? base : "");
          result.push("}");
          return result;
        },
        ThisExpression: function(expr, precedence, flags) {
          return "this";
        },
        Super: function(expr, precedence, flags) {
          return "super";
        },
        Identifier: function(expr, precedence, flags) {
          return generateIdentifier(expr);
        },
        ImportDefaultSpecifier: function(expr, precedence, flags) {
          return generateIdentifier(expr.id || expr.local);
        },
        ImportNamespaceSpecifier: function(expr, precedence, flags) {
          var result = ["*"];
          var id = expr.id || expr.local;
          if (id) {
            result.push(space2 + "as" + noEmptySpace() + generateIdentifier(id));
          }
          return result;
        },
        ImportSpecifier: function(expr, precedence, flags) {
          var imported = expr.imported;
          var result = [imported.name];
          var local = expr.local;
          if (local && local.name !== imported.name) {
            result.push(noEmptySpace() + "as" + noEmptySpace() + generateIdentifier(local));
          }
          return result;
        },
        ExportSpecifier: function(expr, precedence, flags) {
          var local = expr.local;
          var result = [local.name];
          var exported = expr.exported;
          if (exported && exported.name !== local.name) {
            result.push(noEmptySpace() + "as" + noEmptySpace() + generateIdentifier(exported));
          }
          return result;
        },
        Literal: function(expr, precedence, flags) {
          var raw;
          if (expr.hasOwnProperty("raw") && parse9 && extra.raw) {
            try {
              raw = parse9(expr.raw).body[0].expression;
              if (raw.type === Syntax.Literal) {
                if (raw.value === expr.value) {
                  return expr.raw;
                }
              }
            } catch (e) {
            }
          }
          if (expr.regex) {
            return "/" + expr.regex.pattern + "/" + expr.regex.flags;
          }
          if (typeof expr.value === "bigint") {
            return expr.value.toString() + "n";
          }
          if (expr.bigint) {
            return expr.bigint + "n";
          }
          if (expr.value === null) {
            return "null";
          }
          if (typeof expr.value === "string") {
            return escapeString(expr.value);
          }
          if (typeof expr.value === "number") {
            return generateNumber(expr.value);
          }
          if (typeof expr.value === "boolean") {
            return expr.value ? "true" : "false";
          }
          return generateRegExp(expr.value);
        },
        GeneratorExpression: function(expr, precedence, flags) {
          return this.ComprehensionExpression(expr, precedence, flags);
        },
        ComprehensionExpression: function(expr, precedence, flags) {
          var result, i, iz, fragment, that = this;
          result = expr.type === Syntax.GeneratorExpression ? ["("] : ["["];
          if (extra.moz.comprehensionExpressionStartsWithAssignment) {
            fragment = this.generateExpression(expr.body, Precedence.Assignment, E_TTT);
            result.push(fragment);
          }
          if (expr.blocks) {
            withIndent(function() {
              for (i = 0, iz = expr.blocks.length; i < iz; ++i) {
                fragment = that.generateExpression(expr.blocks[i], Precedence.Sequence, E_TTT);
                if (i > 0 || extra.moz.comprehensionExpressionStartsWithAssignment) {
                  result = join9(result, fragment);
                } else {
                  result.push(fragment);
                }
              }
            });
          }
          if (expr.filter) {
            result = join9(result, "if" + space2);
            fragment = this.generateExpression(expr.filter, Precedence.Sequence, E_TTT);
            result = join9(result, ["(", fragment, ")"]);
          }
          if (!extra.moz.comprehensionExpressionStartsWithAssignment) {
            fragment = this.generateExpression(expr.body, Precedence.Assignment, E_TTT);
            result = join9(result, fragment);
          }
          result.push(expr.type === Syntax.GeneratorExpression ? ")" : "]");
          return result;
        },
        ComprehensionBlock: function(expr, precedence, flags) {
          var fragment;
          if (expr.left.type === Syntax.VariableDeclaration) {
            fragment = [
              expr.left.kind,
              noEmptySpace(),
              this.generateStatement(expr.left.declarations[0], S_FFFF)
            ];
          } else {
            fragment = this.generateExpression(expr.left, Precedence.Call, E_TTT);
          }
          fragment = join9(fragment, expr.of ? "of" : "in");
          fragment = join9(fragment, this.generateExpression(expr.right, Precedence.Sequence, E_TTT));
          return ["for" + space2 + "(", fragment, ")"];
        },
        SpreadElement: function(expr, precedence, flags) {
          return [
            "...",
            this.generateExpression(expr.argument, Precedence.Assignment, E_TTT)
          ];
        },
        TaggedTemplateExpression: function(expr, precedence, flags) {
          var itemFlags = E_TTF;
          if (!(flags & F_ALLOW_CALL)) {
            itemFlags = E_TFF;
          }
          var result = [
            this.generateExpression(expr.tag, Precedence.Call, itemFlags),
            this.generateExpression(expr.quasi, Precedence.Primary, E_FFT)
          ];
          return parenthesize(result, Precedence.TaggedTemplate, precedence);
        },
        TemplateElement: function(expr, precedence, flags) {
          return expr.value.raw;
        },
        TemplateLiteral: function(expr, precedence, flags) {
          var result, i, iz;
          result = ["`"];
          for (i = 0, iz = expr.quasis.length; i < iz; ++i) {
            result.push(this.generateExpression(expr.quasis[i], Precedence.Primary, E_TTT));
            if (i + 1 < iz) {
              result.push("${" + space2);
              result.push(this.generateExpression(expr.expressions[i], Precedence.Sequence, E_TTT));
              result.push(space2 + "}");
            }
          }
          result.push("`");
          return result;
        },
        ModuleSpecifier: function(expr, precedence, flags) {
          return this.Literal(expr, precedence, flags);
        },
        ImportExpression: function(expr, precedence, flag) {
          return parenthesize([
            "import(",
            this.generateExpression(expr.source, Precedence.Assignment, E_TTT),
            ")"
          ], Precedence.Call, precedence);
        }
      };
      merge3(CodeGenerator.prototype, CodeGenerator.Expression);
      CodeGenerator.prototype.generateExpression = function(expr, precedence, flags) {
        var result, type;
        type = expr.type || Syntax.Property;
        if (extra.verbatim && expr.hasOwnProperty(extra.verbatim)) {
          return generateVerbatim(expr, precedence);
        }
        result = this[type](expr, precedence, flags);
        if (extra.comment) {
          result = addComments(expr, result);
        }
        return toSourceNodeWhenNeeded(result, expr);
      };
      CodeGenerator.prototype.generateStatement = function(stmt, flags) {
        var result, fragment;
        result = this[stmt.type](stmt, flags);
        if (extra.comment) {
          result = addComments(stmt, result);
        }
        fragment = toSourceNodeWhenNeeded(result).toString();
        if (stmt.type === Syntax.Program && !safeConcatenation && newline2 === "" && fragment.charAt(fragment.length - 1) === "\n") {
          result = sourceMap ? toSourceNodeWhenNeeded(result).replaceRight(/\s+$/, "") : fragment.replace(/\s+$/, "");
        }
        return toSourceNodeWhenNeeded(result, stmt);
      };
      function generateInternal(node) {
        var codegen;
        codegen = new CodeGenerator();
        if (isStatement(node)) {
          return codegen.generateStatement(node, S_TFFF);
        }
        if (isExpression(node)) {
          return codegen.generateExpression(node, Precedence.Sequence, E_TTT);
        }
        throw new Error("Unknown node type: " + node.type);
      }
      function generate(node, options) {
        var defaultOptions2 = getDefaultOptions(), result, pair;
        if (options != null) {
          if (typeof options.indent === "string") {
            defaultOptions2.format.indent.style = options.indent;
          }
          if (typeof options.base === "number") {
            defaultOptions2.format.indent.base = options.base;
          }
          options = updateDeeply(defaultOptions2, options);
          indent = options.format.indent.style;
          if (typeof options.base === "string") {
            base = options.base;
          } else {
            base = stringRepeat(indent, options.format.indent.base);
          }
        } else {
          options = defaultOptions2;
          indent = options.format.indent.style;
          base = stringRepeat(indent, options.format.indent.base);
        }
        json3 = options.format.json;
        renumber = options.format.renumber;
        hexadecimal = json3 ? false : options.format.hexadecimal;
        quotes = json3 ? "double" : options.format.quotes;
        escapeless = options.format.escapeless;
        newline2 = options.format.newline;
        space2 = options.format.space;
        if (options.format.compact) {
          newline2 = space2 = indent = base = "";
        }
        parentheses = options.format.parentheses;
        semicolons = options.format.semicolons;
        safeConcatenation = options.format.safeConcatenation;
        directive = options.directive;
        parse9 = json3 ? null : options.parse;
        sourceMap = options.sourceMap;
        sourceCode = options.sourceCode;
        preserveBlankLines = options.format.preserveBlankLines && sourceCode !== null;
        extra = options;
        if (sourceMap) {
          if (!exports2.browser) {
            SourceNode = require_source_map().SourceNode;
          } else {
            SourceNode = global.sourceMap.SourceNode;
          }
        }
        result = generateInternal(node);
        if (!sourceMap) {
          pair = { code: result.toString(), map: null };
          return options.sourceMapWithCode ? pair : pair.code;
        }
        pair = result.toStringWithSourceMap({
          file: options.file,
          sourceRoot: options.sourceMapRoot
        });
        if (options.sourceContent) {
          pair.map.setSourceContent(
            options.sourceMap,
            options.sourceContent
          );
        }
        if (options.sourceMapWithCode) {
          return pair;
        }
        return pair.map.toString();
      }
      FORMAT_MINIFY = {
        indent: {
          style: "",
          base: 0
        },
        renumber: true,
        hexadecimal: true,
        quotes: "auto",
        escapeless: true,
        compact: true,
        parentheses: false,
        semicolons: false
      };
      FORMAT_DEFAULTS = getDefaultOptions().format;
      exports2.version = require_package().version;
      exports2.generate = generate;
      exports2.attachComments = estraverse.attachComments;
      exports2.Precedence = updateDeeply({}, Precedence);
      exports2.browser = false;
      exports2.FORMAT_MINIFY = FORMAT_MINIFY;
      exports2.FORMAT_DEFAULTS = FORMAT_DEFAULTS;
    })();
  }
});

// ../../node_modules/.pnpm/esprima@4.0.1/node_modules/esprima/dist/esprima.js
var require_esprima = __commonJS({
  "../../node_modules/.pnpm/esprima@4.0.1/node_modules/esprima/dist/esprima.js"(exports2, module2) {
    "use strict";
    (function webpackUniversalModuleDefinition(root, factory) {
      if (typeof exports2 === "object" && typeof module2 === "object")
        module2.exports = factory();
      else if (typeof define === "function" && define.amd)
        define([], factory);
      else if (typeof exports2 === "object")
        exports2["esprima"] = factory();
      else
        root["esprima"] = factory();
    })(exports2, function() {
      return (
        /******/
        (function(modules) {
          var installedModules = {};
          function __webpack_require__(moduleId) {
            if (installedModules[moduleId])
              return installedModules[moduleId].exports;
            var module3 = installedModules[moduleId] = {
              /******/
              exports: {},
              /******/
              id: moduleId,
              /******/
              loaded: false
              /******/
            };
            modules[moduleId].call(module3.exports, module3, module3.exports, __webpack_require__);
            module3.loaded = true;
            return module3.exports;
          }
          __webpack_require__.m = modules;
          __webpack_require__.c = installedModules;
          __webpack_require__.p = "";
          return __webpack_require__(0);
        })([
          /* 0 */
          /***/
          function(module3, exports3, __webpack_require__) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            var comment_handler_1 = __webpack_require__(1);
            var jsx_parser_1 = __webpack_require__(3);
            var parser_1 = __webpack_require__(8);
            var tokenizer_1 = __webpack_require__(15);
            function parse9(code, options, delegate) {
              var commentHandler = null;
              var proxyDelegate = function(node, metadata) {
                if (delegate) {
                  delegate(node, metadata);
                }
                if (commentHandler) {
                  commentHandler.visit(node, metadata);
                }
              };
              var parserDelegate = typeof delegate === "function" ? proxyDelegate : null;
              var collectComment = false;
              if (options) {
                collectComment = typeof options.comment === "boolean" && options.comment;
                var attachComment = typeof options.attachComment === "boolean" && options.attachComment;
                if (collectComment || attachComment) {
                  commentHandler = new comment_handler_1.CommentHandler();
                  commentHandler.attach = attachComment;
                  options.comment = true;
                  parserDelegate = proxyDelegate;
                }
              }
              var isModule = false;
              if (options && typeof options.sourceType === "string") {
                isModule = options.sourceType === "module";
              }
              var parser;
              if (options && typeof options.jsx === "boolean" && options.jsx) {
                parser = new jsx_parser_1.JSXParser(code, options, parserDelegate);
              } else {
                parser = new parser_1.Parser(code, options, parserDelegate);
              }
              var program = isModule ? parser.parseModule() : parser.parseScript();
              var ast = program;
              if (collectComment && commentHandler) {
                ast.comments = commentHandler.comments;
              }
              if (parser.config.tokens) {
                ast.tokens = parser.tokens;
              }
              if (parser.config.tolerant) {
                ast.errors = parser.errorHandler.errors;
              }
              return ast;
            }
            exports3.parse = parse9;
            function parseModule(code, options, delegate) {
              var parsingOptions = options || {};
              parsingOptions.sourceType = "module";
              return parse9(code, parsingOptions, delegate);
            }
            exports3.parseModule = parseModule;
            function parseScript(code, options, delegate) {
              var parsingOptions = options || {};
              parsingOptions.sourceType = "script";
              return parse9(code, parsingOptions, delegate);
            }
            exports3.parseScript = parseScript;
            function tokenize(code, options, delegate) {
              var tokenizer = new tokenizer_1.Tokenizer(code, options);
              var tokens;
              tokens = [];
              try {
                while (true) {
                  var token = tokenizer.getNextToken();
                  if (!token) {
                    break;
                  }
                  if (delegate) {
                    token = delegate(token);
                  }
                  tokens.push(token);
                }
              } catch (e) {
                tokenizer.errorHandler.tolerate(e);
              }
              if (tokenizer.errorHandler.tolerant) {
                tokens.errors = tokenizer.errors();
              }
              return tokens;
            }
            exports3.tokenize = tokenize;
            var syntax_1 = __webpack_require__(2);
            exports3.Syntax = syntax_1.Syntax;
            exports3.version = "4.0.1";
          },
          /* 1 */
          /***/
          function(module3, exports3, __webpack_require__) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            var syntax_1 = __webpack_require__(2);
            var CommentHandler = (function() {
              function CommentHandler2() {
                this.attach = false;
                this.comments = [];
                this.stack = [];
                this.leading = [];
                this.trailing = [];
              }
              CommentHandler2.prototype.insertInnerComments = function(node, metadata) {
                if (node.type === syntax_1.Syntax.BlockStatement && node.body.length === 0) {
                  var innerComments = [];
                  for (var i = this.leading.length - 1; i >= 0; --i) {
                    var entry = this.leading[i];
                    if (metadata.end.offset >= entry.start) {
                      innerComments.unshift(entry.comment);
                      this.leading.splice(i, 1);
                      this.trailing.splice(i, 1);
                    }
                  }
                  if (innerComments.length) {
                    node.innerComments = innerComments;
                  }
                }
              };
              CommentHandler2.prototype.findTrailingComments = function(metadata) {
                var trailingComments = [];
                if (this.trailing.length > 0) {
                  for (var i = this.trailing.length - 1; i >= 0; --i) {
                    var entry_1 = this.trailing[i];
                    if (entry_1.start >= metadata.end.offset) {
                      trailingComments.unshift(entry_1.comment);
                    }
                  }
                  this.trailing.length = 0;
                  return trailingComments;
                }
                var entry = this.stack[this.stack.length - 1];
                if (entry && entry.node.trailingComments) {
                  var firstComment = entry.node.trailingComments[0];
                  if (firstComment && firstComment.range[0] >= metadata.end.offset) {
                    trailingComments = entry.node.trailingComments;
                    delete entry.node.trailingComments;
                  }
                }
                return trailingComments;
              };
              CommentHandler2.prototype.findLeadingComments = function(metadata) {
                var leadingComments = [];
                var target;
                while (this.stack.length > 0) {
                  var entry = this.stack[this.stack.length - 1];
                  if (entry && entry.start >= metadata.start.offset) {
                    target = entry.node;
                    this.stack.pop();
                  } else {
                    break;
                  }
                }
                if (target) {
                  var count = target.leadingComments ? target.leadingComments.length : 0;
                  for (var i = count - 1; i >= 0; --i) {
                    var comment = target.leadingComments[i];
                    if (comment.range[1] <= metadata.start.offset) {
                      leadingComments.unshift(comment);
                      target.leadingComments.splice(i, 1);
                    }
                  }
                  if (target.leadingComments && target.leadingComments.length === 0) {
                    delete target.leadingComments;
                  }
                  return leadingComments;
                }
                for (var i = this.leading.length - 1; i >= 0; --i) {
                  var entry = this.leading[i];
                  if (entry.start <= metadata.start.offset) {
                    leadingComments.unshift(entry.comment);
                    this.leading.splice(i, 1);
                  }
                }
                return leadingComments;
              };
              CommentHandler2.prototype.visitNode = function(node, metadata) {
                if (node.type === syntax_1.Syntax.Program && node.body.length > 0) {
                  return;
                }
                this.insertInnerComments(node, metadata);
                var trailingComments = this.findTrailingComments(metadata);
                var leadingComments = this.findLeadingComments(metadata);
                if (leadingComments.length > 0) {
                  node.leadingComments = leadingComments;
                }
                if (trailingComments.length > 0) {
                  node.trailingComments = trailingComments;
                }
                this.stack.push({
                  node,
                  start: metadata.start.offset
                });
              };
              CommentHandler2.prototype.visitComment = function(node, metadata) {
                var type = node.type[0] === "L" ? "Line" : "Block";
                var comment = {
                  type,
                  value: node.value
                };
                if (node.range) {
                  comment.range = node.range;
                }
                if (node.loc) {
                  comment.loc = node.loc;
                }
                this.comments.push(comment);
                if (this.attach) {
                  var entry = {
                    comment: {
                      type,
                      value: node.value,
                      range: [metadata.start.offset, metadata.end.offset]
                    },
                    start: metadata.start.offset
                  };
                  if (node.loc) {
                    entry.comment.loc = node.loc;
                  }
                  node.type = type;
                  this.leading.push(entry);
                  this.trailing.push(entry);
                }
              };
              CommentHandler2.prototype.visit = function(node, metadata) {
                if (node.type === "LineComment") {
                  this.visitComment(node, metadata);
                } else if (node.type === "BlockComment") {
                  this.visitComment(node, metadata);
                } else if (this.attach) {
                  this.visitNode(node, metadata);
                }
              };
              return CommentHandler2;
            })();
            exports3.CommentHandler = CommentHandler;
          },
          /* 2 */
          /***/
          function(module3, exports3) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            exports3.Syntax = {
              AssignmentExpression: "AssignmentExpression",
              AssignmentPattern: "AssignmentPattern",
              ArrayExpression: "ArrayExpression",
              ArrayPattern: "ArrayPattern",
              ArrowFunctionExpression: "ArrowFunctionExpression",
              AwaitExpression: "AwaitExpression",
              BlockStatement: "BlockStatement",
              BinaryExpression: "BinaryExpression",
              BreakStatement: "BreakStatement",
              CallExpression: "CallExpression",
              CatchClause: "CatchClause",
              ClassBody: "ClassBody",
              ClassDeclaration: "ClassDeclaration",
              ClassExpression: "ClassExpression",
              ConditionalExpression: "ConditionalExpression",
              ContinueStatement: "ContinueStatement",
              DoWhileStatement: "DoWhileStatement",
              DebuggerStatement: "DebuggerStatement",
              EmptyStatement: "EmptyStatement",
              ExportAllDeclaration: "ExportAllDeclaration",
              ExportDefaultDeclaration: "ExportDefaultDeclaration",
              ExportNamedDeclaration: "ExportNamedDeclaration",
              ExportSpecifier: "ExportSpecifier",
              ExpressionStatement: "ExpressionStatement",
              ForStatement: "ForStatement",
              ForOfStatement: "ForOfStatement",
              ForInStatement: "ForInStatement",
              FunctionDeclaration: "FunctionDeclaration",
              FunctionExpression: "FunctionExpression",
              Identifier: "Identifier",
              IfStatement: "IfStatement",
              ImportDeclaration: "ImportDeclaration",
              ImportDefaultSpecifier: "ImportDefaultSpecifier",
              ImportNamespaceSpecifier: "ImportNamespaceSpecifier",
              ImportSpecifier: "ImportSpecifier",
              Literal: "Literal",
              LabeledStatement: "LabeledStatement",
              LogicalExpression: "LogicalExpression",
              MemberExpression: "MemberExpression",
              MetaProperty: "MetaProperty",
              MethodDefinition: "MethodDefinition",
              NewExpression: "NewExpression",
              ObjectExpression: "ObjectExpression",
              ObjectPattern: "ObjectPattern",
              Program: "Program",
              Property: "Property",
              RestElement: "RestElement",
              ReturnStatement: "ReturnStatement",
              SequenceExpression: "SequenceExpression",
              SpreadElement: "SpreadElement",
              Super: "Super",
              SwitchCase: "SwitchCase",
              SwitchStatement: "SwitchStatement",
              TaggedTemplateExpression: "TaggedTemplateExpression",
              TemplateElement: "TemplateElement",
              TemplateLiteral: "TemplateLiteral",
              ThisExpression: "ThisExpression",
              ThrowStatement: "ThrowStatement",
              TryStatement: "TryStatement",
              UnaryExpression: "UnaryExpression",
              UpdateExpression: "UpdateExpression",
              VariableDeclaration: "VariableDeclaration",
              VariableDeclarator: "VariableDeclarator",
              WhileStatement: "WhileStatement",
              WithStatement: "WithStatement",
              YieldExpression: "YieldExpression"
            };
          },
          /* 3 */
          /***/
          function(module3, exports3, __webpack_require__) {
            "use strict";
            var __extends2 = this && this.__extends || (function() {
              var extendStatics2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d, b) {
                d.__proto__ = b;
              } || function(d, b) {
                for (var p2 in b) if (b.hasOwnProperty(p2)) d[p2] = b[p2];
              };
              return function(d, b) {
                extendStatics2(d, b);
                function __() {
                  this.constructor = d;
                }
                d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
              };
            })();
            Object.defineProperty(exports3, "__esModule", { value: true });
            var character_1 = __webpack_require__(4);
            var JSXNode = __webpack_require__(5);
            var jsx_syntax_1 = __webpack_require__(6);
            var Node = __webpack_require__(7);
            var parser_1 = __webpack_require__(8);
            var token_1 = __webpack_require__(13);
            var xhtml_entities_1 = __webpack_require__(14);
            token_1.TokenName[
              100
              /* Identifier */
            ] = "JSXIdentifier";
            token_1.TokenName[
              101
              /* Text */
            ] = "JSXText";
            function getQualifiedElementName(elementName) {
              var qualifiedName;
              switch (elementName.type) {
                case jsx_syntax_1.JSXSyntax.JSXIdentifier:
                  var id = elementName;
                  qualifiedName = id.name;
                  break;
                case jsx_syntax_1.JSXSyntax.JSXNamespacedName:
                  var ns = elementName;
                  qualifiedName = getQualifiedElementName(ns.namespace) + ":" + getQualifiedElementName(ns.name);
                  break;
                case jsx_syntax_1.JSXSyntax.JSXMemberExpression:
                  var expr = elementName;
                  qualifiedName = getQualifiedElementName(expr.object) + "." + getQualifiedElementName(expr.property);
                  break;
                /* istanbul ignore next */
                default:
                  break;
              }
              return qualifiedName;
            }
            var JSXParser = (function(_super) {
              __extends2(JSXParser2, _super);
              function JSXParser2(code, options, delegate) {
                return _super.call(this, code, options, delegate) || this;
              }
              JSXParser2.prototype.parsePrimaryExpression = function() {
                return this.match("<") ? this.parseJSXRoot() : _super.prototype.parsePrimaryExpression.call(this);
              };
              JSXParser2.prototype.startJSX = function() {
                this.scanner.index = this.startMarker.index;
                this.scanner.lineNumber = this.startMarker.line;
                this.scanner.lineStart = this.startMarker.index - this.startMarker.column;
              };
              JSXParser2.prototype.finishJSX = function() {
                this.nextToken();
              };
              JSXParser2.prototype.reenterJSX = function() {
                this.startJSX();
                this.expectJSX("}");
                if (this.config.tokens) {
                  this.tokens.pop();
                }
              };
              JSXParser2.prototype.createJSXNode = function() {
                this.collectComments();
                return {
                  index: this.scanner.index,
                  line: this.scanner.lineNumber,
                  column: this.scanner.index - this.scanner.lineStart
                };
              };
              JSXParser2.prototype.createJSXChildNode = function() {
                return {
                  index: this.scanner.index,
                  line: this.scanner.lineNumber,
                  column: this.scanner.index - this.scanner.lineStart
                };
              };
              JSXParser2.prototype.scanXHTMLEntity = function(quote) {
                var result = "&";
                var valid = true;
                var terminated = false;
                var numeric = false;
                var hex5 = false;
                while (!this.scanner.eof() && valid && !terminated) {
                  var ch = this.scanner.source[this.scanner.index];
                  if (ch === quote) {
                    break;
                  }
                  terminated = ch === ";";
                  result += ch;
                  ++this.scanner.index;
                  if (!terminated) {
                    switch (result.length) {
                      case 2:
                        numeric = ch === "#";
                        break;
                      case 3:
                        if (numeric) {
                          hex5 = ch === "x";
                          valid = hex5 || character_1.Character.isDecimalDigit(ch.charCodeAt(0));
                          numeric = numeric && !hex5;
                        }
                        break;
                      default:
                        valid = valid && !(numeric && !character_1.Character.isDecimalDigit(ch.charCodeAt(0)));
                        valid = valid && !(hex5 && !character_1.Character.isHexDigit(ch.charCodeAt(0)));
                        break;
                    }
                  }
                }
                if (valid && terminated && result.length > 2) {
                  var str = result.substr(1, result.length - 2);
                  if (numeric && str.length > 1) {
                    result = String.fromCharCode(parseInt(str.substr(1), 10));
                  } else if (hex5 && str.length > 2) {
                    result = String.fromCharCode(parseInt("0" + str.substr(1), 16));
                  } else if (!numeric && !hex5 && xhtml_entities_1.XHTMLEntities[str]) {
                    result = xhtml_entities_1.XHTMLEntities[str];
                  }
                }
                return result;
              };
              JSXParser2.prototype.lexJSX = function() {
                var cp = this.scanner.source.charCodeAt(this.scanner.index);
                if (cp === 60 || cp === 62 || cp === 47 || cp === 58 || cp === 61 || cp === 123 || cp === 125) {
                  var value = this.scanner.source[this.scanner.index++];
                  return {
                    type: 7,
                    value,
                    lineNumber: this.scanner.lineNumber,
                    lineStart: this.scanner.lineStart,
                    start: this.scanner.index - 1,
                    end: this.scanner.index
                  };
                }
                if (cp === 34 || cp === 39) {
                  var start = this.scanner.index;
                  var quote = this.scanner.source[this.scanner.index++];
                  var str = "";
                  while (!this.scanner.eof()) {
                    var ch = this.scanner.source[this.scanner.index++];
                    if (ch === quote) {
                      break;
                    } else if (ch === "&") {
                      str += this.scanXHTMLEntity(quote);
                    } else {
                      str += ch;
                    }
                  }
                  return {
                    type: 8,
                    value: str,
                    lineNumber: this.scanner.lineNumber,
                    lineStart: this.scanner.lineStart,
                    start,
                    end: this.scanner.index
                  };
                }
                if (cp === 46) {
                  var n1 = this.scanner.source.charCodeAt(this.scanner.index + 1);
                  var n2 = this.scanner.source.charCodeAt(this.scanner.index + 2);
                  var value = n1 === 46 && n2 === 46 ? "..." : ".";
                  var start = this.scanner.index;
                  this.scanner.index += value.length;
                  return {
                    type: 7,
                    value,
                    lineNumber: this.scanner.lineNumber,
                    lineStart: this.scanner.lineStart,
                    start,
                    end: this.scanner.index
                  };
                }
                if (cp === 96) {
                  return {
                    type: 10,
                    value: "",
                    lineNumber: this.scanner.lineNumber,
                    lineStart: this.scanner.lineStart,
                    start: this.scanner.index,
                    end: this.scanner.index
                  };
                }
                if (character_1.Character.isIdentifierStart(cp) && cp !== 92) {
                  var start = this.scanner.index;
                  ++this.scanner.index;
                  while (!this.scanner.eof()) {
                    var ch = this.scanner.source.charCodeAt(this.scanner.index);
                    if (character_1.Character.isIdentifierPart(ch) && ch !== 92) {
                      ++this.scanner.index;
                    } else if (ch === 45) {
                      ++this.scanner.index;
                    } else {
                      break;
                    }
                  }
                  var id = this.scanner.source.slice(start, this.scanner.index);
                  return {
                    type: 100,
                    value: id,
                    lineNumber: this.scanner.lineNumber,
                    lineStart: this.scanner.lineStart,
                    start,
                    end: this.scanner.index
                  };
                }
                return this.scanner.lex();
              };
              JSXParser2.prototype.nextJSXToken = function() {
                this.collectComments();
                this.startMarker.index = this.scanner.index;
                this.startMarker.line = this.scanner.lineNumber;
                this.startMarker.column = this.scanner.index - this.scanner.lineStart;
                var token = this.lexJSX();
                this.lastMarker.index = this.scanner.index;
                this.lastMarker.line = this.scanner.lineNumber;
                this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
                if (this.config.tokens) {
                  this.tokens.push(this.convertToken(token));
                }
                return token;
              };
              JSXParser2.prototype.nextJSXText = function() {
                this.startMarker.index = this.scanner.index;
                this.startMarker.line = this.scanner.lineNumber;
                this.startMarker.column = this.scanner.index - this.scanner.lineStart;
                var start = this.scanner.index;
                var text = "";
                while (!this.scanner.eof()) {
                  var ch = this.scanner.source[this.scanner.index];
                  if (ch === "{" || ch === "<") {
                    break;
                  }
                  ++this.scanner.index;
                  text += ch;
                  if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
                    ++this.scanner.lineNumber;
                    if (ch === "\r" && this.scanner.source[this.scanner.index] === "\n") {
                      ++this.scanner.index;
                    }
                    this.scanner.lineStart = this.scanner.index;
                  }
                }
                this.lastMarker.index = this.scanner.index;
                this.lastMarker.line = this.scanner.lineNumber;
                this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
                var token = {
                  type: 101,
                  value: text,
                  lineNumber: this.scanner.lineNumber,
                  lineStart: this.scanner.lineStart,
                  start,
                  end: this.scanner.index
                };
                if (text.length > 0 && this.config.tokens) {
                  this.tokens.push(this.convertToken(token));
                }
                return token;
              };
              JSXParser2.prototype.peekJSXToken = function() {
                var state = this.scanner.saveState();
                this.scanner.scanComments();
                var next = this.lexJSX();
                this.scanner.restoreState(state);
                return next;
              };
              JSXParser2.prototype.expectJSX = function(value) {
                var token = this.nextJSXToken();
                if (token.type !== 7 || token.value !== value) {
                  this.throwUnexpectedToken(token);
                }
              };
              JSXParser2.prototype.matchJSX = function(value) {
                var next = this.peekJSXToken();
                return next.type === 7 && next.value === value;
              };
              JSXParser2.prototype.parseJSXIdentifier = function() {
                var node = this.createJSXNode();
                var token = this.nextJSXToken();
                if (token.type !== 100) {
                  this.throwUnexpectedToken(token);
                }
                return this.finalize(node, new JSXNode.JSXIdentifier(token.value));
              };
              JSXParser2.prototype.parseJSXElementName = function() {
                var node = this.createJSXNode();
                var elementName = this.parseJSXIdentifier();
                if (this.matchJSX(":")) {
                  var namespace = elementName;
                  this.expectJSX(":");
                  var name_1 = this.parseJSXIdentifier();
                  elementName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_1));
                } else if (this.matchJSX(".")) {
                  while (this.matchJSX(".")) {
                    var object3 = elementName;
                    this.expectJSX(".");
                    var property = this.parseJSXIdentifier();
                    elementName = this.finalize(node, new JSXNode.JSXMemberExpression(object3, property));
                  }
                }
                return elementName;
              };
              JSXParser2.prototype.parseJSXAttributeName = function() {
                var node = this.createJSXNode();
                var attributeName;
                var identifier = this.parseJSXIdentifier();
                if (this.matchJSX(":")) {
                  var namespace = identifier;
                  this.expectJSX(":");
                  var name_2 = this.parseJSXIdentifier();
                  attributeName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_2));
                } else {
                  attributeName = identifier;
                }
                return attributeName;
              };
              JSXParser2.prototype.parseJSXStringLiteralAttribute = function() {
                var node = this.createJSXNode();
                var token = this.nextJSXToken();
                if (token.type !== 8) {
                  this.throwUnexpectedToken(token);
                }
                var raw = this.getTokenRaw(token);
                return this.finalize(node, new Node.Literal(token.value, raw));
              };
              JSXParser2.prototype.parseJSXExpressionAttribute = function() {
                var node = this.createJSXNode();
                this.expectJSX("{");
                this.finishJSX();
                if (this.match("}")) {
                  this.tolerateError("JSX attributes must only be assigned a non-empty expression");
                }
                var expression = this.parseAssignmentExpression();
                this.reenterJSX();
                return this.finalize(node, new JSXNode.JSXExpressionContainer(expression));
              };
              JSXParser2.prototype.parseJSXAttributeValue = function() {
                return this.matchJSX("{") ? this.parseJSXExpressionAttribute() : this.matchJSX("<") ? this.parseJSXElement() : this.parseJSXStringLiteralAttribute();
              };
              JSXParser2.prototype.parseJSXNameValueAttribute = function() {
                var node = this.createJSXNode();
                var name = this.parseJSXAttributeName();
                var value = null;
                if (this.matchJSX("=")) {
                  this.expectJSX("=");
                  value = this.parseJSXAttributeValue();
                }
                return this.finalize(node, new JSXNode.JSXAttribute(name, value));
              };
              JSXParser2.prototype.parseJSXSpreadAttribute = function() {
                var node = this.createJSXNode();
                this.expectJSX("{");
                this.expectJSX("...");
                this.finishJSX();
                var argument = this.parseAssignmentExpression();
                this.reenterJSX();
                return this.finalize(node, new JSXNode.JSXSpreadAttribute(argument));
              };
              JSXParser2.prototype.parseJSXAttributes = function() {
                var attributes = [];
                while (!this.matchJSX("/") && !this.matchJSX(">")) {
                  var attribute = this.matchJSX("{") ? this.parseJSXSpreadAttribute() : this.parseJSXNameValueAttribute();
                  attributes.push(attribute);
                }
                return attributes;
              };
              JSXParser2.prototype.parseJSXOpeningElement = function() {
                var node = this.createJSXNode();
                this.expectJSX("<");
                var name = this.parseJSXElementName();
                var attributes = this.parseJSXAttributes();
                var selfClosing = this.matchJSX("/");
                if (selfClosing) {
                  this.expectJSX("/");
                }
                this.expectJSX(">");
                return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes));
              };
              JSXParser2.prototype.parseJSXBoundaryElement = function() {
                var node = this.createJSXNode();
                this.expectJSX("<");
                if (this.matchJSX("/")) {
                  this.expectJSX("/");
                  var name_3 = this.parseJSXElementName();
                  this.expectJSX(">");
                  return this.finalize(node, new JSXNode.JSXClosingElement(name_3));
                }
                var name = this.parseJSXElementName();
                var attributes = this.parseJSXAttributes();
                var selfClosing = this.matchJSX("/");
                if (selfClosing) {
                  this.expectJSX("/");
                }
                this.expectJSX(">");
                return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes));
              };
              JSXParser2.prototype.parseJSXEmptyExpression = function() {
                var node = this.createJSXChildNode();
                this.collectComments();
                this.lastMarker.index = this.scanner.index;
                this.lastMarker.line = this.scanner.lineNumber;
                this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
                return this.finalize(node, new JSXNode.JSXEmptyExpression());
              };
              JSXParser2.prototype.parseJSXExpressionContainer = function() {
                var node = this.createJSXNode();
                this.expectJSX("{");
                var expression;
                if (this.matchJSX("}")) {
                  expression = this.parseJSXEmptyExpression();
                  this.expectJSX("}");
                } else {
                  this.finishJSX();
                  expression = this.parseAssignmentExpression();
                  this.reenterJSX();
                }
                return this.finalize(node, new JSXNode.JSXExpressionContainer(expression));
              };
              JSXParser2.prototype.parseJSXChildren = function() {
                var children = [];
                while (!this.scanner.eof()) {
                  var node = this.createJSXChildNode();
                  var token = this.nextJSXText();
                  if (token.start < token.end) {
                    var raw = this.getTokenRaw(token);
                    var child = this.finalize(node, new JSXNode.JSXText(token.value, raw));
                    children.push(child);
                  }
                  if (this.scanner.source[this.scanner.index] === "{") {
                    var container = this.parseJSXExpressionContainer();
                    children.push(container);
                  } else {
                    break;
                  }
                }
                return children;
              };
              JSXParser2.prototype.parseComplexJSXElement = function(el) {
                var stack = [];
                while (!this.scanner.eof()) {
                  el.children = el.children.concat(this.parseJSXChildren());
                  var node = this.createJSXChildNode();
                  var element = this.parseJSXBoundaryElement();
                  if (element.type === jsx_syntax_1.JSXSyntax.JSXOpeningElement) {
                    var opening = element;
                    if (opening.selfClosing) {
                      var child = this.finalize(node, new JSXNode.JSXElement(opening, [], null));
                      el.children.push(child);
                    } else {
                      stack.push(el);
                      el = { node, opening, closing: null, children: [] };
                    }
                  }
                  if (element.type === jsx_syntax_1.JSXSyntax.JSXClosingElement) {
                    el.closing = element;
                    var open_1 = getQualifiedElementName(el.opening.name);
                    var close_1 = getQualifiedElementName(el.closing.name);
                    if (open_1 !== close_1) {
                      this.tolerateError("Expected corresponding JSX closing tag for %0", open_1);
                    }
                    if (stack.length > 0) {
                      var child = this.finalize(el.node, new JSXNode.JSXElement(el.opening, el.children, el.closing));
                      el = stack[stack.length - 1];
                      el.children.push(child);
                      stack.pop();
                    } else {
                      break;
                    }
                  }
                }
                return el;
              };
              JSXParser2.prototype.parseJSXElement = function() {
                var node = this.createJSXNode();
                var opening = this.parseJSXOpeningElement();
                var children = [];
                var closing = null;
                if (!opening.selfClosing) {
                  var el = this.parseComplexJSXElement({ node, opening, closing, children });
                  children = el.children;
                  closing = el.closing;
                }
                return this.finalize(node, new JSXNode.JSXElement(opening, children, closing));
              };
              JSXParser2.prototype.parseJSXRoot = function() {
                if (this.config.tokens) {
                  this.tokens.pop();
                }
                this.startJSX();
                var element = this.parseJSXElement();
                this.finishJSX();
                return element;
              };
              JSXParser2.prototype.isStartOfExpression = function() {
                return _super.prototype.isStartOfExpression.call(this) || this.match("<");
              };
              return JSXParser2;
            })(parser_1.Parser);
            exports3.JSXParser = JSXParser;
          },
          /* 4 */
          /***/
          function(module3, exports3) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            var Regex = {
              // Unicode v8.0.0 NonAsciiIdentifierStart:
              NonAsciiIdentifierStart: /[\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\u0561-\u0587\u05D0-\u05EA\u05F0-\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\u08A0-\u08B4\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\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\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\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-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\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-\u2C2E\u2C30-\u2C5E\u2C60-\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-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\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-\uAB65\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]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/,
              // Unicode v8.0.0 NonAsciiIdentifierPart:
              NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\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\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\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\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/
            };
            exports3.Character = {
              /* tslint:disable:no-bitwise */
              fromCodePoint: function(cp) {
                return cp < 65536 ? String.fromCharCode(cp) : String.fromCharCode(55296 + (cp - 65536 >> 10)) + String.fromCharCode(56320 + (cp - 65536 & 1023));
              },
              // https://tc39.github.io/ecma262/#sec-white-space
              isWhiteSpace: function(cp) {
                return cp === 32 || cp === 9 || cp === 11 || cp === 12 || cp === 160 || cp >= 5760 && [5760, 8192, 8193, 8194, 8195, 8196, 8197, 8198, 8199, 8200, 8201, 8202, 8239, 8287, 12288, 65279].indexOf(cp) >= 0;
              },
              // https://tc39.github.io/ecma262/#sec-line-terminators
              isLineTerminator: function(cp) {
                return cp === 10 || cp === 13 || cp === 8232 || cp === 8233;
              },
              // https://tc39.github.io/ecma262/#sec-names-and-keywords
              isIdentifierStart: function(cp) {
                return cp === 36 || cp === 95 || cp >= 65 && cp <= 90 || cp >= 97 && cp <= 122 || cp === 92 || cp >= 128 && Regex.NonAsciiIdentifierStart.test(exports3.Character.fromCodePoint(cp));
              },
              isIdentifierPart: function(cp) {
                return cp === 36 || cp === 95 || cp >= 65 && cp <= 90 || cp >= 97 && cp <= 122 || cp >= 48 && cp <= 57 || cp === 92 || cp >= 128 && Regex.NonAsciiIdentifierPart.test(exports3.Character.fromCodePoint(cp));
              },
              // https://tc39.github.io/ecma262/#sec-literals-numeric-literals
              isDecimalDigit: function(cp) {
                return cp >= 48 && cp <= 57;
              },
              isHexDigit: function(cp) {
                return cp >= 48 && cp <= 57 || cp >= 65 && cp <= 70 || cp >= 97 && cp <= 102;
              },
              isOctalDigit: function(cp) {
                return cp >= 48 && cp <= 55;
              }
            };
          },
          /* 5 */
          /***/
          function(module3, exports3, __webpack_require__) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            var jsx_syntax_1 = __webpack_require__(6);
            var JSXClosingElement = /* @__PURE__ */ (function() {
              function JSXClosingElement2(name) {
                this.type = jsx_syntax_1.JSXSyntax.JSXClosingElement;
                this.name = name;
              }
              return JSXClosingElement2;
            })();
            exports3.JSXClosingElement = JSXClosingElement;
            var JSXElement = /* @__PURE__ */ (function() {
              function JSXElement2(openingElement, children, closingElement) {
                this.type = jsx_syntax_1.JSXSyntax.JSXElement;
                this.openingElement = openingElement;
                this.children = children;
                this.closingElement = closingElement;
              }
              return JSXElement2;
            })();
            exports3.JSXElement = JSXElement;
            var JSXEmptyExpression = /* @__PURE__ */ (function() {
              function JSXEmptyExpression2() {
                this.type = jsx_syntax_1.JSXSyntax.JSXEmptyExpression;
              }
              return JSXEmptyExpression2;
            })();
            exports3.JSXEmptyExpression = JSXEmptyExpression;
            var JSXExpressionContainer = /* @__PURE__ */ (function() {
              function JSXExpressionContainer2(expression) {
                this.type = jsx_syntax_1.JSXSyntax.JSXExpressionContainer;
                this.expression = expression;
              }
              return JSXExpressionContainer2;
            })();
            exports3.JSXExpressionContainer = JSXExpressionContainer;
            var JSXIdentifier = /* @__PURE__ */ (function() {
              function JSXIdentifier2(name) {
                this.type = jsx_syntax_1.JSXSyntax.JSXIdentifier;
                this.name = name;
              }
              return JSXIdentifier2;
            })();
            exports3.JSXIdentifier = JSXIdentifier;
            var JSXMemberExpression = /* @__PURE__ */ (function() {
              function JSXMemberExpression2(object3, property) {
                this.type = jsx_syntax_1.JSXSyntax.JSXMemberExpression;
                this.object = object3;
                this.property = property;
              }
              return JSXMemberExpression2;
            })();
            exports3.JSXMemberExpression = JSXMemberExpression;
            var JSXAttribute = /* @__PURE__ */ (function() {
              function JSXAttribute2(name, value) {
                this.type = jsx_syntax_1.JSXSyntax.JSXAttribute;
                this.name = name;
                this.value = value;
              }
              return JSXAttribute2;
            })();
            exports3.JSXAttribute = JSXAttribute;
            var JSXNamespacedName = /* @__PURE__ */ (function() {
              function JSXNamespacedName2(namespace, name) {
                this.type = jsx_syntax_1.JSXSyntax.JSXNamespacedName;
                this.namespace = namespace;
                this.name = name;
              }
              return JSXNamespacedName2;
            })();
            exports3.JSXNamespacedName = JSXNamespacedName;
            var JSXOpeningElement = /* @__PURE__ */ (function() {
              function JSXOpeningElement2(name, selfClosing, attributes) {
                this.type = jsx_syntax_1.JSXSyntax.JSXOpeningElement;
                this.name = name;
                this.selfClosing = selfClosing;
                this.attributes = attributes;
              }
              return JSXOpeningElement2;
            })();
            exports3.JSXOpeningElement = JSXOpeningElement;
            var JSXSpreadAttribute = /* @__PURE__ */ (function() {
              function JSXSpreadAttribute2(argument) {
                this.type = jsx_syntax_1.JSXSyntax.JSXSpreadAttribute;
                this.argument = argument;
              }
              return JSXSpreadAttribute2;
            })();
            exports3.JSXSpreadAttribute = JSXSpreadAttribute;
            var JSXText = /* @__PURE__ */ (function() {
              function JSXText2(value, raw) {
                this.type = jsx_syntax_1.JSXSyntax.JSXText;
                this.value = value;
                this.raw = raw;
              }
              return JSXText2;
            })();
            exports3.JSXText = JSXText;
          },
          /* 6 */
          /***/
          function(module3, exports3) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            exports3.JSXSyntax = {
              JSXAttribute: "JSXAttribute",
              JSXClosingElement: "JSXClosingElement",
              JSXElement: "JSXElement",
              JSXEmptyExpression: "JSXEmptyExpression",
              JSXExpressionContainer: "JSXExpressionContainer",
              JSXIdentifier: "JSXIdentifier",
              JSXMemberExpression: "JSXMemberExpression",
              JSXNamespacedName: "JSXNamespacedName",
              JSXOpeningElement: "JSXOpeningElement",
              JSXSpreadAttribute: "JSXSpreadAttribute",
              JSXText: "JSXText"
            };
          },
          /* 7 */
          /***/
          function(module3, exports3, __webpack_require__) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            var syntax_1 = __webpack_require__(2);
            var ArrayExpression = /* @__PURE__ */ (function() {
              function ArrayExpression2(elements) {
                this.type = syntax_1.Syntax.ArrayExpression;
                this.elements = elements;
              }
              return ArrayExpression2;
            })();
            exports3.ArrayExpression = ArrayExpression;
            var ArrayPattern = /* @__PURE__ */ (function() {
              function ArrayPattern2(elements) {
                this.type = syntax_1.Syntax.ArrayPattern;
                this.elements = elements;
              }
              return ArrayPattern2;
            })();
            exports3.ArrayPattern = ArrayPattern;
            var ArrowFunctionExpression = /* @__PURE__ */ (function() {
              function ArrowFunctionExpression2(params, body, expression) {
                this.type = syntax_1.Syntax.ArrowFunctionExpression;
                this.id = null;
                this.params = params;
                this.body = body;
                this.generator = false;
                this.expression = expression;
                this.async = false;
              }
              return ArrowFunctionExpression2;
            })();
            exports3.ArrowFunctionExpression = ArrowFunctionExpression;
            var AssignmentExpression = /* @__PURE__ */ (function() {
              function AssignmentExpression2(operator, left, right) {
                this.type = syntax_1.Syntax.AssignmentExpression;
                this.operator = operator;
                this.left = left;
                this.right = right;
              }
              return AssignmentExpression2;
            })();
            exports3.AssignmentExpression = AssignmentExpression;
            var AssignmentPattern = /* @__PURE__ */ (function() {
              function AssignmentPattern2(left, right) {
                this.type = syntax_1.Syntax.AssignmentPattern;
                this.left = left;
                this.right = right;
              }
              return AssignmentPattern2;
            })();
            exports3.AssignmentPattern = AssignmentPattern;
            var AsyncArrowFunctionExpression = /* @__PURE__ */ (function() {
              function AsyncArrowFunctionExpression2(params, body, expression) {
                this.type = syntax_1.Syntax.ArrowFunctionExpression;
                this.id = null;
                this.params = params;
                this.body = body;
                this.generator = false;
                this.expression = expression;
                this.async = true;
              }
              return AsyncArrowFunctionExpression2;
            })();
            exports3.AsyncArrowFunctionExpression = AsyncArrowFunctionExpression;
            var AsyncFunctionDeclaration = /* @__PURE__ */ (function() {
              function AsyncFunctionDeclaration2(id, params, body) {
                this.type = syntax_1.Syntax.FunctionDeclaration;
                this.id = id;
                this.params = params;
                this.body = body;
                this.generator = false;
                this.expression = false;
                this.async = true;
              }
              return AsyncFunctionDeclaration2;
            })();
            exports3.AsyncFunctionDeclaration = AsyncFunctionDeclaration;
            var AsyncFunctionExpression = /* @__PURE__ */ (function() {
              function AsyncFunctionExpression2(id, params, body) {
                this.type = syntax_1.Syntax.FunctionExpression;
                this.id = id;
                this.params = params;
                this.body = body;
                this.generator = false;
                this.expression = false;
                this.async = true;
              }
              return AsyncFunctionExpression2;
            })();
            exports3.AsyncFunctionExpression = AsyncFunctionExpression;
            var AwaitExpression = /* @__PURE__ */ (function() {
              function AwaitExpression2(argument) {
                this.type = syntax_1.Syntax.AwaitExpression;
                this.argument = argument;
              }
              return AwaitExpression2;
            })();
            exports3.AwaitExpression = AwaitExpression;
            var BinaryExpression = /* @__PURE__ */ (function() {
              function BinaryExpression2(operator, left, right) {
                var logical = operator === "||" || operator === "&&";
                this.type = logical ? syntax_1.Syntax.LogicalExpression : syntax_1.Syntax.BinaryExpression;
                this.operator = operator;
                this.left = left;
                this.right = right;
              }
              return BinaryExpression2;
            })();
            exports3.BinaryExpression = BinaryExpression;
            var BlockStatement = /* @__PURE__ */ (function() {
              function BlockStatement2(body) {
                this.type = syntax_1.Syntax.BlockStatement;
                this.body = body;
              }
              return BlockStatement2;
            })();
            exports3.BlockStatement = BlockStatement;
            var BreakStatement = /* @__PURE__ */ (function() {
              function BreakStatement2(label) {
                this.type = syntax_1.Syntax.BreakStatement;
                this.label = label;
              }
              return BreakStatement2;
            })();
            exports3.BreakStatement = BreakStatement;
            var CallExpression = /* @__PURE__ */ (function() {
              function CallExpression2(callee, args) {
                this.type = syntax_1.Syntax.CallExpression;
                this.callee = callee;
                this.arguments = args;
              }
              return CallExpression2;
            })();
            exports3.CallExpression = CallExpression;
            var CatchClause = /* @__PURE__ */ (function() {
              function CatchClause2(param, body) {
                this.type = syntax_1.Syntax.CatchClause;
                this.param = param;
                this.body = body;
              }
              return CatchClause2;
            })();
            exports3.CatchClause = CatchClause;
            var ClassBody = /* @__PURE__ */ (function() {
              function ClassBody2(body) {
                this.type = syntax_1.Syntax.ClassBody;
                this.body = body;
              }
              return ClassBody2;
            })();
            exports3.ClassBody = ClassBody;
            var ClassDeclaration = /* @__PURE__ */ (function() {
              function ClassDeclaration2(id, superClass, body) {
                this.type = syntax_1.Syntax.ClassDeclaration;
                this.id = id;
                this.superClass = superClass;
                this.body = body;
              }
              return ClassDeclaration2;
            })();
            exports3.ClassDeclaration = ClassDeclaration;
            var ClassExpression = /* @__PURE__ */ (function() {
              function ClassExpression2(id, superClass, body) {
                this.type = syntax_1.Syntax.ClassExpression;
                this.id = id;
                this.superClass = superClass;
                this.body = body;
              }
              return ClassExpression2;
            })();
            exports3.ClassExpression = ClassExpression;
            var ComputedMemberExpression = /* @__PURE__ */ (function() {
              function ComputedMemberExpression2(object3, property) {
                this.type = syntax_1.Syntax.MemberExpression;
                this.computed = true;
                this.object = object3;
                this.property = property;
              }
              return ComputedMemberExpression2;
            })();
            exports3.ComputedMemberExpression = ComputedMemberExpression;
            var ConditionalExpression = /* @__PURE__ */ (function() {
              function ConditionalExpression2(test, consequent, alternate) {
                this.type = syntax_1.Syntax.ConditionalExpression;
                this.test = test;
                this.consequent = consequent;
                this.alternate = alternate;
              }
              return ConditionalExpression2;
            })();
            exports3.ConditionalExpression = ConditionalExpression;
            var ContinueStatement = /* @__PURE__ */ (function() {
              function ContinueStatement2(label) {
                this.type = syntax_1.Syntax.ContinueStatement;
                this.label = label;
              }
              return ContinueStatement2;
            })();
            exports3.ContinueStatement = ContinueStatement;
            var DebuggerStatement = /* @__PURE__ */ (function() {
              function DebuggerStatement2() {
                this.type = syntax_1.Syntax.DebuggerStatement;
              }
              return DebuggerStatement2;
            })();
            exports3.DebuggerStatement = DebuggerStatement;
            var Directive = /* @__PURE__ */ (function() {
              function Directive2(expression, directive) {
                this.type = syntax_1.Syntax.ExpressionStatement;
                this.expression = expression;
                this.directive = directive;
              }
              return Directive2;
            })();
            exports3.Directive = Directive;
            var DoWhileStatement = /* @__PURE__ */ (function() {
              function DoWhileStatement2(body, test) {
                this.type = syntax_1.Syntax.DoWhileStatement;
                this.body = body;
                this.test = test;
              }
              return DoWhileStatement2;
            })();
            exports3.DoWhileStatement = DoWhileStatement;
            var EmptyStatement = /* @__PURE__ */ (function() {
              function EmptyStatement2() {
                this.type = syntax_1.Syntax.EmptyStatement;
              }
              return EmptyStatement2;
            })();
            exports3.EmptyStatement = EmptyStatement;
            var ExportAllDeclaration = /* @__PURE__ */ (function() {
              function ExportAllDeclaration2(source) {
                this.type = syntax_1.Syntax.ExportAllDeclaration;
                this.source = source;
              }
              return ExportAllDeclaration2;
            })();
            exports3.ExportAllDeclaration = ExportAllDeclaration;
            var ExportDefaultDeclaration = /* @__PURE__ */ (function() {
              function ExportDefaultDeclaration2(declaration) {
                this.type = syntax_1.Syntax.ExportDefaultDeclaration;
                this.declaration = declaration;
              }
              return ExportDefaultDeclaration2;
            })();
            exports3.ExportDefaultDeclaration = ExportDefaultDeclaration;
            var ExportNamedDeclaration = /* @__PURE__ */ (function() {
              function ExportNamedDeclaration2(declaration, specifiers, source) {
                this.type = syntax_1.Syntax.ExportNamedDeclaration;
                this.declaration = declaration;
                this.specifiers = specifiers;
                this.source = source;
              }
              return ExportNamedDeclaration2;
            })();
            exports3.ExportNamedDeclaration = ExportNamedDeclaration;
            var ExportSpecifier = /* @__PURE__ */ (function() {
              function ExportSpecifier2(local, exported) {
                this.type = syntax_1.Syntax.ExportSpecifier;
                this.exported = exported;
                this.local = local;
              }
              return ExportSpecifier2;
            })();
            exports3.ExportSpecifier = ExportSpecifier;
            var ExpressionStatement = /* @__PURE__ */ (function() {
              function ExpressionStatement2(expression) {
                this.type = syntax_1.Syntax.ExpressionStatement;
                this.expression = expression;
              }
              return ExpressionStatement2;
            })();
            exports3.ExpressionStatement = ExpressionStatement;
            var ForInStatement = /* @__PURE__ */ (function() {
              function ForInStatement2(left, right, body) {
                this.type = syntax_1.Syntax.ForInStatement;
                this.left = left;
                this.right = right;
                this.body = body;
                this.each = false;
              }
              return ForInStatement2;
            })();
            exports3.ForInStatement = ForInStatement;
            var ForOfStatement = /* @__PURE__ */ (function() {
              function ForOfStatement2(left, right, body) {
                this.type = syntax_1.Syntax.ForOfStatement;
                this.left = left;
                this.right = right;
                this.body = body;
              }
              return ForOfStatement2;
            })();
            exports3.ForOfStatement = ForOfStatement;
            var ForStatement = /* @__PURE__ */ (function() {
              function ForStatement2(init3, test, update, body) {
                this.type = syntax_1.Syntax.ForStatement;
                this.init = init3;
                this.test = test;
                this.update = update;
                this.body = body;
              }
              return ForStatement2;
            })();
            exports3.ForStatement = ForStatement;
            var FunctionDeclaration = /* @__PURE__ */ (function() {
              function FunctionDeclaration2(id, params, body, generator) {
                this.type = syntax_1.Syntax.FunctionDeclaration;
                this.id = id;
                this.params = params;
                this.body = body;
                this.generator = generator;
                this.expression = false;
                this.async = false;
              }
              return FunctionDeclaration2;
            })();
            exports3.FunctionDeclaration = FunctionDeclaration;
            var FunctionExpression = /* @__PURE__ */ (function() {
              function FunctionExpression2(id, params, body, generator) {
                this.type = syntax_1.Syntax.FunctionExpression;
                this.id = id;
                this.params = params;
                this.body = body;
                this.generator = generator;
                this.expression = false;
                this.async = false;
              }
              return FunctionExpression2;
            })();
            exports3.FunctionExpression = FunctionExpression;
            var Identifier = /* @__PURE__ */ (function() {
              function Identifier2(name) {
                this.type = syntax_1.Syntax.Identifier;
                this.name = name;
              }
              return Identifier2;
            })();
            exports3.Identifier = Identifier;
            var IfStatement = /* @__PURE__ */ (function() {
              function IfStatement2(test, consequent, alternate) {
                this.type = syntax_1.Syntax.IfStatement;
                this.test = test;
                this.consequent = consequent;
                this.alternate = alternate;
              }
              return IfStatement2;
            })();
            exports3.IfStatement = IfStatement;
            var ImportDeclaration = /* @__PURE__ */ (function() {
              function ImportDeclaration2(specifiers, source) {
                this.type = syntax_1.Syntax.ImportDeclaration;
                this.specifiers = specifiers;
                this.source = source;
              }
              return ImportDeclaration2;
            })();
            exports3.ImportDeclaration = ImportDeclaration;
            var ImportDefaultSpecifier = /* @__PURE__ */ (function() {
              function ImportDefaultSpecifier2(local) {
                this.type = syntax_1.Syntax.ImportDefaultSpecifier;
                this.local = local;
              }
              return ImportDefaultSpecifier2;
            })();
            exports3.ImportDefaultSpecifier = ImportDefaultSpecifier;
            var ImportNamespaceSpecifier = /* @__PURE__ */ (function() {
              function ImportNamespaceSpecifier2(local) {
                this.type = syntax_1.Syntax.ImportNamespaceSpecifier;
                this.local = local;
              }
              return ImportNamespaceSpecifier2;
            })();
            exports3.ImportNamespaceSpecifier = ImportNamespaceSpecifier;
            var ImportSpecifier = /* @__PURE__ */ (function() {
              function ImportSpecifier2(local, imported) {
                this.type = syntax_1.Syntax.ImportSpecifier;
                this.local = local;
                this.imported = imported;
              }
              return ImportSpecifier2;
            })();
            exports3.ImportSpecifier = ImportSpecifier;
            var LabeledStatement = /* @__PURE__ */ (function() {
              function LabeledStatement2(label, body) {
                this.type = syntax_1.Syntax.LabeledStatement;
                this.label = label;
                this.body = body;
              }
              return LabeledStatement2;
            })();
            exports3.LabeledStatement = LabeledStatement;
            var Literal = /* @__PURE__ */ (function() {
              function Literal2(value, raw) {
                this.type = syntax_1.Syntax.Literal;
                this.value = value;
                this.raw = raw;
              }
              return Literal2;
            })();
            exports3.Literal = Literal;
            var MetaProperty = /* @__PURE__ */ (function() {
              function MetaProperty2(meta5, property) {
                this.type = syntax_1.Syntax.MetaProperty;
                this.meta = meta5;
                this.property = property;
              }
              return MetaProperty2;
            })();
            exports3.MetaProperty = MetaProperty;
            var MethodDefinition = /* @__PURE__ */ (function() {
              function MethodDefinition2(key, computed, value, kind, isStatic) {
                this.type = syntax_1.Syntax.MethodDefinition;
                this.key = key;
                this.computed = computed;
                this.value = value;
                this.kind = kind;
                this.static = isStatic;
              }
              return MethodDefinition2;
            })();
            exports3.MethodDefinition = MethodDefinition;
            var Module = /* @__PURE__ */ (function() {
              function Module2(body) {
                this.type = syntax_1.Syntax.Program;
                this.body = body;
                this.sourceType = "module";
              }
              return Module2;
            })();
            exports3.Module = Module;
            var NewExpression = /* @__PURE__ */ (function() {
              function NewExpression2(callee, args) {
                this.type = syntax_1.Syntax.NewExpression;
                this.callee = callee;
                this.arguments = args;
              }
              return NewExpression2;
            })();
            exports3.NewExpression = NewExpression;
            var ObjectExpression = /* @__PURE__ */ (function() {
              function ObjectExpression2(properties) {
                this.type = syntax_1.Syntax.ObjectExpression;
                this.properties = properties;
              }
              return ObjectExpression2;
            })();
            exports3.ObjectExpression = ObjectExpression;
            var ObjectPattern = /* @__PURE__ */ (function() {
              function ObjectPattern2(properties) {
                this.type = syntax_1.Syntax.ObjectPattern;
                this.properties = properties;
              }
              return ObjectPattern2;
            })();
            exports3.ObjectPattern = ObjectPattern;
            var Property = /* @__PURE__ */ (function() {
              function Property2(kind, key, computed, value, method, shorthand) {
                this.type = syntax_1.Syntax.Property;
                this.key = key;
                this.computed = computed;
                this.value = value;
                this.kind = kind;
                this.method = method;
                this.shorthand = shorthand;
              }
              return Property2;
            })();
            exports3.Property = Property;
            var RegexLiteral = /* @__PURE__ */ (function() {
              function RegexLiteral2(value, raw, pattern, flags) {
                this.type = syntax_1.Syntax.Literal;
                this.value = value;
                this.raw = raw;
                this.regex = { pattern, flags };
              }
              return RegexLiteral2;
            })();
            exports3.RegexLiteral = RegexLiteral;
            var RestElement = /* @__PURE__ */ (function() {
              function RestElement2(argument) {
                this.type = syntax_1.Syntax.RestElement;
                this.argument = argument;
              }
              return RestElement2;
            })();
            exports3.RestElement = RestElement;
            var ReturnStatement = /* @__PURE__ */ (function() {
              function ReturnStatement2(argument) {
                this.type = syntax_1.Syntax.ReturnStatement;
                this.argument = argument;
              }
              return ReturnStatement2;
            })();
            exports3.ReturnStatement = ReturnStatement;
            var Script = /* @__PURE__ */ (function() {
              function Script2(body) {
                this.type = syntax_1.Syntax.Program;
                this.body = body;
                this.sourceType = "script";
              }
              return Script2;
            })();
            exports3.Script = Script;
            var SequenceExpression = /* @__PURE__ */ (function() {
              function SequenceExpression2(expressions) {
                this.type = syntax_1.Syntax.SequenceExpression;
                this.expressions = expressions;
              }
              return SequenceExpression2;
            })();
            exports3.SequenceExpression = SequenceExpression;
            var SpreadElement = /* @__PURE__ */ (function() {
              function SpreadElement2(argument) {
                this.type = syntax_1.Syntax.SpreadElement;
                this.argument = argument;
              }
              return SpreadElement2;
            })();
            exports3.SpreadElement = SpreadElement;
            var StaticMemberExpression = /* @__PURE__ */ (function() {
              function StaticMemberExpression2(object3, property) {
                this.type = syntax_1.Syntax.MemberExpression;
                this.computed = false;
                this.object = object3;
                this.property = property;
              }
              return StaticMemberExpression2;
            })();
            exports3.StaticMemberExpression = StaticMemberExpression;
            var Super = /* @__PURE__ */ (function() {
              function Super2() {
                this.type = syntax_1.Syntax.Super;
              }
              return Super2;
            })();
            exports3.Super = Super;
            var SwitchCase = /* @__PURE__ */ (function() {
              function SwitchCase2(test, consequent) {
                this.type = syntax_1.Syntax.SwitchCase;
                this.test = test;
                this.consequent = consequent;
              }
              return SwitchCase2;
            })();
            exports3.SwitchCase = SwitchCase;
            var SwitchStatement = /* @__PURE__ */ (function() {
              function SwitchStatement2(discriminant, cases) {
                this.type = syntax_1.Syntax.SwitchStatement;
                this.discriminant = discriminant;
                this.cases = cases;
              }
              return SwitchStatement2;
            })();
            exports3.SwitchStatement = SwitchStatement;
            var TaggedTemplateExpression = /* @__PURE__ */ (function() {
              function TaggedTemplateExpression2(tag, quasi) {
                this.type = syntax_1.Syntax.TaggedTemplateExpression;
                this.tag = tag;
                this.quasi = quasi;
              }
              return TaggedTemplateExpression2;
            })();
            exports3.TaggedTemplateExpression = TaggedTemplateExpression;
            var TemplateElement = /* @__PURE__ */ (function() {
              function TemplateElement2(value, tail) {
                this.type = syntax_1.Syntax.TemplateElement;
                this.value = value;
                this.tail = tail;
              }
              return TemplateElement2;
            })();
            exports3.TemplateElement = TemplateElement;
            var TemplateLiteral = /* @__PURE__ */ (function() {
              function TemplateLiteral2(quasis, expressions) {
                this.type = syntax_1.Syntax.TemplateLiteral;
                this.quasis = quasis;
                this.expressions = expressions;
              }
              return TemplateLiteral2;
            })();
            exports3.TemplateLiteral = TemplateLiteral;
            var ThisExpression = /* @__PURE__ */ (function() {
              function ThisExpression2() {
                this.type = syntax_1.Syntax.ThisExpression;
              }
              return ThisExpression2;
            })();
            exports3.ThisExpression = ThisExpression;
            var ThrowStatement = /* @__PURE__ */ (function() {
              function ThrowStatement2(argument) {
                this.type = syntax_1.Syntax.ThrowStatement;
                this.argument = argument;
              }
              return ThrowStatement2;
            })();
            exports3.ThrowStatement = ThrowStatement;
            var TryStatement = /* @__PURE__ */ (function() {
              function TryStatement2(block, handler, finalizer) {
                this.type = syntax_1.Syntax.TryStatement;
                this.block = block;
                this.handler = handler;
                this.finalizer = finalizer;
              }
              return TryStatement2;
            })();
            exports3.TryStatement = TryStatement;
            var UnaryExpression = /* @__PURE__ */ (function() {
              function UnaryExpression2(operator, argument) {
                this.type = syntax_1.Syntax.UnaryExpression;
                this.operator = operator;
                this.argument = argument;
                this.prefix = true;
              }
              return UnaryExpression2;
            })();
            exports3.UnaryExpression = UnaryExpression;
            var UpdateExpression = /* @__PURE__ */ (function() {
              function UpdateExpression2(operator, argument, prefix) {
                this.type = syntax_1.Syntax.UpdateExpression;
                this.operator = operator;
                this.argument = argument;
                this.prefix = prefix;
              }
              return UpdateExpression2;
            })();
            exports3.UpdateExpression = UpdateExpression;
            var VariableDeclaration = /* @__PURE__ */ (function() {
              function VariableDeclaration2(declarations, kind) {
                this.type = syntax_1.Syntax.VariableDeclaration;
                this.declarations = declarations;
                this.kind = kind;
              }
              return VariableDeclaration2;
            })();
            exports3.VariableDeclaration = VariableDeclaration;
            var VariableDeclarator = /* @__PURE__ */ (function() {
              function VariableDeclarator2(id, init3) {
                this.type = syntax_1.Syntax.VariableDeclarator;
                this.id = id;
                this.init = init3;
              }
              return VariableDeclarator2;
            })();
            exports3.VariableDeclarator = VariableDeclarator;
            var WhileStatement = /* @__PURE__ */ (function() {
              function WhileStatement2(test, body) {
                this.type = syntax_1.Syntax.WhileStatement;
                this.test = test;
                this.body = body;
              }
              return WhileStatement2;
            })();
            exports3.WhileStatement = WhileStatement;
            var WithStatement = /* @__PURE__ */ (function() {
              function WithStatement2(object3, body) {
                this.type = syntax_1.Syntax.WithStatement;
                this.object = object3;
                this.body = body;
              }
              return WithStatement2;
            })();
            exports3.WithStatement = WithStatement;
            var YieldExpression = /* @__PURE__ */ (function() {
              function YieldExpression2(argument, delegate) {
                this.type = syntax_1.Syntax.YieldExpression;
                this.argument = argument;
                this.delegate = delegate;
              }
              return YieldExpression2;
            })();
            exports3.YieldExpression = YieldExpression;
          },
          /* 8 */
          /***/
          function(module3, exports3, __webpack_require__) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            var assert_1 = __webpack_require__(9);
            var error_handler_1 = __webpack_require__(10);
            var messages_1 = __webpack_require__(11);
            var Node = __webpack_require__(7);
            var scanner_1 = __webpack_require__(12);
            var syntax_1 = __webpack_require__(2);
            var token_1 = __webpack_require__(13);
            var ArrowParameterPlaceHolder = "ArrowParameterPlaceHolder";
            var Parser = (function() {
              function Parser2(code, options, delegate) {
                if (options === void 0) {
                  options = {};
                }
                this.config = {
                  range: typeof options.range === "boolean" && options.range,
                  loc: typeof options.loc === "boolean" && options.loc,
                  source: null,
                  tokens: typeof options.tokens === "boolean" && options.tokens,
                  comment: typeof options.comment === "boolean" && options.comment,
                  tolerant: typeof options.tolerant === "boolean" && options.tolerant
                };
                if (this.config.loc && options.source && options.source !== null) {
                  this.config.source = String(options.source);
                }
                this.delegate = delegate;
                this.errorHandler = new error_handler_1.ErrorHandler();
                this.errorHandler.tolerant = this.config.tolerant;
                this.scanner = new scanner_1.Scanner(code, this.errorHandler);
                this.scanner.trackComment = this.config.comment;
                this.operatorPrecedence = {
                  ")": 0,
                  ";": 0,
                  ",": 0,
                  "=": 0,
                  "]": 0,
                  "||": 1,
                  "&&": 2,
                  "|": 3,
                  "^": 4,
                  "&": 5,
                  "==": 6,
                  "!=": 6,
                  "===": 6,
                  "!==": 6,
                  "<": 7,
                  ">": 7,
                  "<=": 7,
                  ">=": 7,
                  "<<": 8,
                  ">>": 8,
                  ">>>": 8,
                  "+": 9,
                  "-": 9,
                  "*": 11,
                  "/": 11,
                  "%": 11
                };
                this.lookahead = {
                  type: 2,
                  value: "",
                  lineNumber: this.scanner.lineNumber,
                  lineStart: 0,
                  start: 0,
                  end: 0
                };
                this.hasLineTerminator = false;
                this.context = {
                  isModule: false,
                  await: false,
                  allowIn: true,
                  allowStrictDirective: true,
                  allowYield: true,
                  firstCoverInitializedNameError: null,
                  isAssignmentTarget: false,
                  isBindingElement: false,
                  inFunctionBody: false,
                  inIteration: false,
                  inSwitch: false,
                  labelSet: {},
                  strict: false
                };
                this.tokens = [];
                this.startMarker = {
                  index: 0,
                  line: this.scanner.lineNumber,
                  column: 0
                };
                this.lastMarker = {
                  index: 0,
                  line: this.scanner.lineNumber,
                  column: 0
                };
                this.nextToken();
                this.lastMarker = {
                  index: this.scanner.index,
                  line: this.scanner.lineNumber,
                  column: this.scanner.index - this.scanner.lineStart
                };
              }
              Parser2.prototype.throwError = function(messageFormat) {
                var values = [];
                for (var _i = 1; _i < arguments.length; _i++) {
                  values[_i - 1] = arguments[_i];
                }
                var args = Array.prototype.slice.call(arguments, 1);
                var msg = messageFormat.replace(/%(\d)/g, function(whole, idx) {
                  assert_1.assert(idx < args.length, "Message reference must be in range");
                  return args[idx];
                });
                var index = this.lastMarker.index;
                var line = this.lastMarker.line;
                var column = this.lastMarker.column + 1;
                throw this.errorHandler.createError(index, line, column, msg);
              };
              Parser2.prototype.tolerateError = function(messageFormat) {
                var values = [];
                for (var _i = 1; _i < arguments.length; _i++) {
                  values[_i - 1] = arguments[_i];
                }
                var args = Array.prototype.slice.call(arguments, 1);
                var msg = messageFormat.replace(/%(\d)/g, function(whole, idx) {
                  assert_1.assert(idx < args.length, "Message reference must be in range");
                  return args[idx];
                });
                var index = this.lastMarker.index;
                var line = this.scanner.lineNumber;
                var column = this.lastMarker.column + 1;
                this.errorHandler.tolerateError(index, line, column, msg);
              };
              Parser2.prototype.unexpectedTokenError = function(token, message) {
                var msg = message || messages_1.Messages.UnexpectedToken;
                var value;
                if (token) {
                  if (!message) {
                    msg = token.type === 2 ? messages_1.Messages.UnexpectedEOS : token.type === 3 ? messages_1.Messages.UnexpectedIdentifier : token.type === 6 ? messages_1.Messages.UnexpectedNumber : token.type === 8 ? messages_1.Messages.UnexpectedString : token.type === 10 ? messages_1.Messages.UnexpectedTemplate : messages_1.Messages.UnexpectedToken;
                    if (token.type === 4) {
                      if (this.scanner.isFutureReservedWord(token.value)) {
                        msg = messages_1.Messages.UnexpectedReserved;
                      } else if (this.context.strict && this.scanner.isStrictModeReservedWord(token.value)) {
                        msg = messages_1.Messages.StrictReservedWord;
                      }
                    }
                  }
                  value = token.value;
                } else {
                  value = "ILLEGAL";
                }
                msg = msg.replace("%0", value);
                if (token && typeof token.lineNumber === "number") {
                  var index = token.start;
                  var line = token.lineNumber;
                  var lastMarkerLineStart = this.lastMarker.index - this.lastMarker.column;
                  var column = token.start - lastMarkerLineStart + 1;
                  return this.errorHandler.createError(index, line, column, msg);
                } else {
                  var index = this.lastMarker.index;
                  var line = this.lastMarker.line;
                  var column = this.lastMarker.column + 1;
                  return this.errorHandler.createError(index, line, column, msg);
                }
              };
              Parser2.prototype.throwUnexpectedToken = function(token, message) {
                throw this.unexpectedTokenError(token, message);
              };
              Parser2.prototype.tolerateUnexpectedToken = function(token, message) {
                this.errorHandler.tolerate(this.unexpectedTokenError(token, message));
              };
              Parser2.prototype.collectComments = function() {
                if (!this.config.comment) {
                  this.scanner.scanComments();
                } else {
                  var comments = this.scanner.scanComments();
                  if (comments.length > 0 && this.delegate) {
                    for (var i = 0; i < comments.length; ++i) {
                      var e = comments[i];
                      var node = void 0;
                      node = {
                        type: e.multiLine ? "BlockComment" : "LineComment",
                        value: this.scanner.source.slice(e.slice[0], e.slice[1])
                      };
                      if (this.config.range) {
                        node.range = e.range;
                      }
                      if (this.config.loc) {
                        node.loc = e.loc;
                      }
                      var metadata = {
                        start: {
                          line: e.loc.start.line,
                          column: e.loc.start.column,
                          offset: e.range[0]
                        },
                        end: {
                          line: e.loc.end.line,
                          column: e.loc.end.column,
                          offset: e.range[1]
                        }
                      };
                      this.delegate(node, metadata);
                    }
                  }
                }
              };
              Parser2.prototype.getTokenRaw = function(token) {
                return this.scanner.source.slice(token.start, token.end);
              };
              Parser2.prototype.convertToken = function(token) {
                var t = {
                  type: token_1.TokenName[token.type],
                  value: this.getTokenRaw(token)
                };
                if (this.config.range) {
                  t.range = [token.start, token.end];
                }
                if (this.config.loc) {
                  t.loc = {
                    start: {
                      line: this.startMarker.line,
                      column: this.startMarker.column
                    },
                    end: {
                      line: this.scanner.lineNumber,
                      column: this.scanner.index - this.scanner.lineStart
                    }
                  };
                }
                if (token.type === 9) {
                  var pattern = token.pattern;
                  var flags = token.flags;
                  t.regex = { pattern, flags };
                }
                return t;
              };
              Parser2.prototype.nextToken = function() {
                var token = this.lookahead;
                this.lastMarker.index = this.scanner.index;
                this.lastMarker.line = this.scanner.lineNumber;
                this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
                this.collectComments();
                if (this.scanner.index !== this.startMarker.index) {
                  this.startMarker.index = this.scanner.index;
                  this.startMarker.line = this.scanner.lineNumber;
                  this.startMarker.column = this.scanner.index - this.scanner.lineStart;
                }
                var next = this.scanner.lex();
                this.hasLineTerminator = token.lineNumber !== next.lineNumber;
                if (next && this.context.strict && next.type === 3) {
                  if (this.scanner.isStrictModeReservedWord(next.value)) {
                    next.type = 4;
                  }
                }
                this.lookahead = next;
                if (this.config.tokens && next.type !== 2) {
                  this.tokens.push(this.convertToken(next));
                }
                return token;
              };
              Parser2.prototype.nextRegexToken = function() {
                this.collectComments();
                var token = this.scanner.scanRegExp();
                if (this.config.tokens) {
                  this.tokens.pop();
                  this.tokens.push(this.convertToken(token));
                }
                this.lookahead = token;
                this.nextToken();
                return token;
              };
              Parser2.prototype.createNode = function() {
                return {
                  index: this.startMarker.index,
                  line: this.startMarker.line,
                  column: this.startMarker.column
                };
              };
              Parser2.prototype.startNode = function(token, lastLineStart) {
                if (lastLineStart === void 0) {
                  lastLineStart = 0;
                }
                var column = token.start - token.lineStart;
                var line = token.lineNumber;
                if (column < 0) {
                  column += lastLineStart;
                  line--;
                }
                return {
                  index: token.start,
                  line,
                  column
                };
              };
              Parser2.prototype.finalize = function(marker, node) {
                if (this.config.range) {
                  node.range = [marker.index, this.lastMarker.index];
                }
                if (this.config.loc) {
                  node.loc = {
                    start: {
                      line: marker.line,
                      column: marker.column
                    },
                    end: {
                      line: this.lastMarker.line,
                      column: this.lastMarker.column
                    }
                  };
                  if (this.config.source) {
                    node.loc.source = this.config.source;
                  }
                }
                if (this.delegate) {
                  var metadata = {
                    start: {
                      line: marker.line,
                      column: marker.column,
                      offset: marker.index
                    },
                    end: {
                      line: this.lastMarker.line,
                      column: this.lastMarker.column,
                      offset: this.lastMarker.index
                    }
                  };
                  this.delegate(node, metadata);
                }
                return node;
              };
              Parser2.prototype.expect = function(value) {
                var token = this.nextToken();
                if (token.type !== 7 || token.value !== value) {
                  this.throwUnexpectedToken(token);
                }
              };
              Parser2.prototype.expectCommaSeparator = function() {
                if (this.config.tolerant) {
                  var token = this.lookahead;
                  if (token.type === 7 && token.value === ",") {
                    this.nextToken();
                  } else if (token.type === 7 && token.value === ";") {
                    this.nextToken();
                    this.tolerateUnexpectedToken(token);
                  } else {
                    this.tolerateUnexpectedToken(token, messages_1.Messages.UnexpectedToken);
                  }
                } else {
                  this.expect(",");
                }
              };
              Parser2.prototype.expectKeyword = function(keyword) {
                var token = this.nextToken();
                if (token.type !== 4 || token.value !== keyword) {
                  this.throwUnexpectedToken(token);
                }
              };
              Parser2.prototype.match = function(value) {
                return this.lookahead.type === 7 && this.lookahead.value === value;
              };
              Parser2.prototype.matchKeyword = function(keyword) {
                return this.lookahead.type === 4 && this.lookahead.value === keyword;
              };
              Parser2.prototype.matchContextualKeyword = function(keyword) {
                return this.lookahead.type === 3 && this.lookahead.value === keyword;
              };
              Parser2.prototype.matchAssign = function() {
                if (this.lookahead.type !== 7) {
                  return false;
                }
                var op = this.lookahead.value;
                return op === "=" || op === "*=" || op === "**=" || op === "/=" || op === "%=" || op === "+=" || op === "-=" || op === "<<=" || op === ">>=" || op === ">>>=" || op === "&=" || op === "^=" || op === "|=";
              };
              Parser2.prototype.isolateCoverGrammar = function(parseFunction) {
                var previousIsBindingElement = this.context.isBindingElement;
                var previousIsAssignmentTarget = this.context.isAssignmentTarget;
                var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError;
                this.context.isBindingElement = true;
                this.context.isAssignmentTarget = true;
                this.context.firstCoverInitializedNameError = null;
                var result = parseFunction.call(this);
                if (this.context.firstCoverInitializedNameError !== null) {
                  this.throwUnexpectedToken(this.context.firstCoverInitializedNameError);
                }
                this.context.isBindingElement = previousIsBindingElement;
                this.context.isAssignmentTarget = previousIsAssignmentTarget;
                this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError;
                return result;
              };
              Parser2.prototype.inheritCoverGrammar = function(parseFunction) {
                var previousIsBindingElement = this.context.isBindingElement;
                var previousIsAssignmentTarget = this.context.isAssignmentTarget;
                var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError;
                this.context.isBindingElement = true;
                this.context.isAssignmentTarget = true;
                this.context.firstCoverInitializedNameError = null;
                var result = parseFunction.call(this);
                this.context.isBindingElement = this.context.isBindingElement && previousIsBindingElement;
                this.context.isAssignmentTarget = this.context.isAssignmentTarget && previousIsAssignmentTarget;
                this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError || this.context.firstCoverInitializedNameError;
                return result;
              };
              Parser2.prototype.consumeSemicolon = function() {
                if (this.match(";")) {
                  this.nextToken();
                } else if (!this.hasLineTerminator) {
                  if (this.lookahead.type !== 2 && !this.match("}")) {
                    this.throwUnexpectedToken(this.lookahead);
                  }
                  this.lastMarker.index = this.startMarker.index;
                  this.lastMarker.line = this.startMarker.line;
                  this.lastMarker.column = this.startMarker.column;
                }
              };
              Parser2.prototype.parsePrimaryExpression = function() {
                var node = this.createNode();
                var expr;
                var token, raw;
                switch (this.lookahead.type) {
                  case 3:
                    if ((this.context.isModule || this.context.await) && this.lookahead.value === "await") {
                      this.tolerateUnexpectedToken(this.lookahead);
                    }
                    expr = this.matchAsyncFunction() ? this.parseFunctionExpression() : this.finalize(node, new Node.Identifier(this.nextToken().value));
                    break;
                  case 6:
                  case 8:
                    if (this.context.strict && this.lookahead.octal) {
                      this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.StrictOctalLiteral);
                    }
                    this.context.isAssignmentTarget = false;
                    this.context.isBindingElement = false;
                    token = this.nextToken();
                    raw = this.getTokenRaw(token);
                    expr = this.finalize(node, new Node.Literal(token.value, raw));
                    break;
                  case 1:
                    this.context.isAssignmentTarget = false;
                    this.context.isBindingElement = false;
                    token = this.nextToken();
                    raw = this.getTokenRaw(token);
                    expr = this.finalize(node, new Node.Literal(token.value === "true", raw));
                    break;
                  case 5:
                    this.context.isAssignmentTarget = false;
                    this.context.isBindingElement = false;
                    token = this.nextToken();
                    raw = this.getTokenRaw(token);
                    expr = this.finalize(node, new Node.Literal(null, raw));
                    break;
                  case 10:
                    expr = this.parseTemplateLiteral();
                    break;
                  case 7:
                    switch (this.lookahead.value) {
                      case "(":
                        this.context.isBindingElement = false;
                        expr = this.inheritCoverGrammar(this.parseGroupExpression);
                        break;
                      case "[":
                        expr = this.inheritCoverGrammar(this.parseArrayInitializer);
                        break;
                      case "{":
                        expr = this.inheritCoverGrammar(this.parseObjectInitializer);
                        break;
                      case "/":
                      case "/=":
                        this.context.isAssignmentTarget = false;
                        this.context.isBindingElement = false;
                        this.scanner.index = this.startMarker.index;
                        token = this.nextRegexToken();
                        raw = this.getTokenRaw(token);
                        expr = this.finalize(node, new Node.RegexLiteral(token.regex, raw, token.pattern, token.flags));
                        break;
                      default:
                        expr = this.throwUnexpectedToken(this.nextToken());
                    }
                    break;
                  case 4:
                    if (!this.context.strict && this.context.allowYield && this.matchKeyword("yield")) {
                      expr = this.parseIdentifierName();
                    } else if (!this.context.strict && this.matchKeyword("let")) {
                      expr = this.finalize(node, new Node.Identifier(this.nextToken().value));
                    } else {
                      this.context.isAssignmentTarget = false;
                      this.context.isBindingElement = false;
                      if (this.matchKeyword("function")) {
                        expr = this.parseFunctionExpression();
                      } else if (this.matchKeyword("this")) {
                        this.nextToken();
                        expr = this.finalize(node, new Node.ThisExpression());
                      } else if (this.matchKeyword("class")) {
                        expr = this.parseClassExpression();
                      } else {
                        expr = this.throwUnexpectedToken(this.nextToken());
                      }
                    }
                    break;
                  default:
                    expr = this.throwUnexpectedToken(this.nextToken());
                }
                return expr;
              };
              Parser2.prototype.parseSpreadElement = function() {
                var node = this.createNode();
                this.expect("...");
                var arg = this.inheritCoverGrammar(this.parseAssignmentExpression);
                return this.finalize(node, new Node.SpreadElement(arg));
              };
              Parser2.prototype.parseArrayInitializer = function() {
                var node = this.createNode();
                var elements = [];
                this.expect("[");
                while (!this.match("]")) {
                  if (this.match(",")) {
                    this.nextToken();
                    elements.push(null);
                  } else if (this.match("...")) {
                    var element = this.parseSpreadElement();
                    if (!this.match("]")) {
                      this.context.isAssignmentTarget = false;
                      this.context.isBindingElement = false;
                      this.expect(",");
                    }
                    elements.push(element);
                  } else {
                    elements.push(this.inheritCoverGrammar(this.parseAssignmentExpression));
                    if (!this.match("]")) {
                      this.expect(",");
                    }
                  }
                }
                this.expect("]");
                return this.finalize(node, new Node.ArrayExpression(elements));
              };
              Parser2.prototype.parsePropertyMethod = function(params) {
                this.context.isAssignmentTarget = false;
                this.context.isBindingElement = false;
                var previousStrict = this.context.strict;
                var previousAllowStrictDirective = this.context.allowStrictDirective;
                this.context.allowStrictDirective = params.simple;
                var body = this.isolateCoverGrammar(this.parseFunctionSourceElements);
                if (this.context.strict && params.firstRestricted) {
                  this.tolerateUnexpectedToken(params.firstRestricted, params.message);
                }
                if (this.context.strict && params.stricted) {
                  this.tolerateUnexpectedToken(params.stricted, params.message);
                }
                this.context.strict = previousStrict;
                this.context.allowStrictDirective = previousAllowStrictDirective;
                return body;
              };
              Parser2.prototype.parsePropertyMethodFunction = function() {
                var isGenerator = false;
                var node = this.createNode();
                var previousAllowYield = this.context.allowYield;
                this.context.allowYield = true;
                var params = this.parseFormalParameters();
                var method = this.parsePropertyMethod(params);
                this.context.allowYield = previousAllowYield;
                return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator));
              };
              Parser2.prototype.parsePropertyMethodAsyncFunction = function() {
                var node = this.createNode();
                var previousAllowYield = this.context.allowYield;
                var previousAwait = this.context.await;
                this.context.allowYield = false;
                this.context.await = true;
                var params = this.parseFormalParameters();
                var method = this.parsePropertyMethod(params);
                this.context.allowYield = previousAllowYield;
                this.context.await = previousAwait;
                return this.finalize(node, new Node.AsyncFunctionExpression(null, params.params, method));
              };
              Parser2.prototype.parseObjectPropertyKey = function() {
                var node = this.createNode();
                var token = this.nextToken();
                var key;
                switch (token.type) {
                  case 8:
                  case 6:
                    if (this.context.strict && token.octal) {
                      this.tolerateUnexpectedToken(token, messages_1.Messages.StrictOctalLiteral);
                    }
                    var raw = this.getTokenRaw(token);
                    key = this.finalize(node, new Node.Literal(token.value, raw));
                    break;
                  case 3:
                  case 1:
                  case 5:
                  case 4:
                    key = this.finalize(node, new Node.Identifier(token.value));
                    break;
                  case 7:
                    if (token.value === "[") {
                      key = this.isolateCoverGrammar(this.parseAssignmentExpression);
                      this.expect("]");
                    } else {
                      key = this.throwUnexpectedToken(token);
                    }
                    break;
                  default:
                    key = this.throwUnexpectedToken(token);
                }
                return key;
              };
              Parser2.prototype.isPropertyKey = function(key, value) {
                return key.type === syntax_1.Syntax.Identifier && key.name === value || key.type === syntax_1.Syntax.Literal && key.value === value;
              };
              Parser2.prototype.parseObjectProperty = function(hasProto) {
                var node = this.createNode();
                var token = this.lookahead;
                var kind;
                var key = null;
                var value = null;
                var computed = false;
                var method = false;
                var shorthand = false;
                var isAsync = false;
                if (token.type === 3) {
                  var id = token.value;
                  this.nextToken();
                  computed = this.match("[");
                  isAsync = !this.hasLineTerminator && id === "async" && !this.match(":") && !this.match("(") && !this.match("*") && !this.match(",");
                  key = isAsync ? this.parseObjectPropertyKey() : this.finalize(node, new Node.Identifier(id));
                } else if (this.match("*")) {
                  this.nextToken();
                } else {
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                }
                var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead);
                if (token.type === 3 && !isAsync && token.value === "get" && lookaheadPropertyKey) {
                  kind = "get";
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                  this.context.allowYield = false;
                  value = this.parseGetterMethod();
                } else if (token.type === 3 && !isAsync && token.value === "set" && lookaheadPropertyKey) {
                  kind = "set";
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                  value = this.parseSetterMethod();
                } else if (token.type === 7 && token.value === "*" && lookaheadPropertyKey) {
                  kind = "init";
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                  value = this.parseGeneratorMethod();
                  method = true;
                } else {
                  if (!key) {
                    this.throwUnexpectedToken(this.lookahead);
                  }
                  kind = "init";
                  if (this.match(":") && !isAsync) {
                    if (!computed && this.isPropertyKey(key, "__proto__")) {
                      if (hasProto.value) {
                        this.tolerateError(messages_1.Messages.DuplicateProtoProperty);
                      }
                      hasProto.value = true;
                    }
                    this.nextToken();
                    value = this.inheritCoverGrammar(this.parseAssignmentExpression);
                  } else if (this.match("(")) {
                    value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction();
                    method = true;
                  } else if (token.type === 3) {
                    var id = this.finalize(node, new Node.Identifier(token.value));
                    if (this.match("=")) {
                      this.context.firstCoverInitializedNameError = this.lookahead;
                      this.nextToken();
                      shorthand = true;
                      var init3 = this.isolateCoverGrammar(this.parseAssignmentExpression);
                      value = this.finalize(node, new Node.AssignmentPattern(id, init3));
                    } else {
                      shorthand = true;
                      value = id;
                    }
                  } else {
                    this.throwUnexpectedToken(this.nextToken());
                  }
                }
                return this.finalize(node, new Node.Property(kind, key, computed, value, method, shorthand));
              };
              Parser2.prototype.parseObjectInitializer = function() {
                var node = this.createNode();
                this.expect("{");
                var properties = [];
                var hasProto = { value: false };
                while (!this.match("}")) {
                  properties.push(this.parseObjectProperty(hasProto));
                  if (!this.match("}")) {
                    this.expectCommaSeparator();
                  }
                }
                this.expect("}");
                return this.finalize(node, new Node.ObjectExpression(properties));
              };
              Parser2.prototype.parseTemplateHead = function() {
                assert_1.assert(this.lookahead.head, "Template literal must start with a template head");
                var node = this.createNode();
                var token = this.nextToken();
                var raw = token.value;
                var cooked = token.cooked;
                return this.finalize(node, new Node.TemplateElement({ raw, cooked }, token.tail));
              };
              Parser2.prototype.parseTemplateElement = function() {
                if (this.lookahead.type !== 10) {
                  this.throwUnexpectedToken();
                }
                var node = this.createNode();
                var token = this.nextToken();
                var raw = token.value;
                var cooked = token.cooked;
                return this.finalize(node, new Node.TemplateElement({ raw, cooked }, token.tail));
              };
              Parser2.prototype.parseTemplateLiteral = function() {
                var node = this.createNode();
                var expressions = [];
                var quasis = [];
                var quasi = this.parseTemplateHead();
                quasis.push(quasi);
                while (!quasi.tail) {
                  expressions.push(this.parseExpression());
                  quasi = this.parseTemplateElement();
                  quasis.push(quasi);
                }
                return this.finalize(node, new Node.TemplateLiteral(quasis, expressions));
              };
              Parser2.prototype.reinterpretExpressionAsPattern = function(expr) {
                switch (expr.type) {
                  case syntax_1.Syntax.Identifier:
                  case syntax_1.Syntax.MemberExpression:
                  case syntax_1.Syntax.RestElement:
                  case syntax_1.Syntax.AssignmentPattern:
                    break;
                  case syntax_1.Syntax.SpreadElement:
                    expr.type = syntax_1.Syntax.RestElement;
                    this.reinterpretExpressionAsPattern(expr.argument);
                    break;
                  case syntax_1.Syntax.ArrayExpression:
                    expr.type = syntax_1.Syntax.ArrayPattern;
                    for (var i = 0; i < expr.elements.length; i++) {
                      if (expr.elements[i] !== null) {
                        this.reinterpretExpressionAsPattern(expr.elements[i]);
                      }
                    }
                    break;
                  case syntax_1.Syntax.ObjectExpression:
                    expr.type = syntax_1.Syntax.ObjectPattern;
                    for (var i = 0; i < expr.properties.length; i++) {
                      this.reinterpretExpressionAsPattern(expr.properties[i].value);
                    }
                    break;
                  case syntax_1.Syntax.AssignmentExpression:
                    expr.type = syntax_1.Syntax.AssignmentPattern;
                    delete expr.operator;
                    this.reinterpretExpressionAsPattern(expr.left);
                    break;
                  default:
                    break;
                }
              };
              Parser2.prototype.parseGroupExpression = function() {
                var expr;
                this.expect("(");
                if (this.match(")")) {
                  this.nextToken();
                  if (!this.match("=>")) {
                    this.expect("=>");
                  }
                  expr = {
                    type: ArrowParameterPlaceHolder,
                    params: [],
                    async: false
                  };
                } else {
                  var startToken = this.lookahead;
                  var params = [];
                  if (this.match("...")) {
                    expr = this.parseRestElement(params);
                    this.expect(")");
                    if (!this.match("=>")) {
                      this.expect("=>");
                    }
                    expr = {
                      type: ArrowParameterPlaceHolder,
                      params: [expr],
                      async: false
                    };
                  } else {
                    var arrow = false;
                    this.context.isBindingElement = true;
                    expr = this.inheritCoverGrammar(this.parseAssignmentExpression);
                    if (this.match(",")) {
                      var expressions = [];
                      this.context.isAssignmentTarget = false;
                      expressions.push(expr);
                      while (this.lookahead.type !== 2) {
                        if (!this.match(",")) {
                          break;
                        }
                        this.nextToken();
                        if (this.match(")")) {
                          this.nextToken();
                          for (var i = 0; i < expressions.length; i++) {
                            this.reinterpretExpressionAsPattern(expressions[i]);
                          }
                          arrow = true;
                          expr = {
                            type: ArrowParameterPlaceHolder,
                            params: expressions,
                            async: false
                          };
                        } else if (this.match("...")) {
                          if (!this.context.isBindingElement) {
                            this.throwUnexpectedToken(this.lookahead);
                          }
                          expressions.push(this.parseRestElement(params));
                          this.expect(")");
                          if (!this.match("=>")) {
                            this.expect("=>");
                          }
                          this.context.isBindingElement = false;
                          for (var i = 0; i < expressions.length; i++) {
                            this.reinterpretExpressionAsPattern(expressions[i]);
                          }
                          arrow = true;
                          expr = {
                            type: ArrowParameterPlaceHolder,
                            params: expressions,
                            async: false
                          };
                        } else {
                          expressions.push(this.inheritCoverGrammar(this.parseAssignmentExpression));
                        }
                        if (arrow) {
                          break;
                        }
                      }
                      if (!arrow) {
                        expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions));
                      }
                    }
                    if (!arrow) {
                      this.expect(")");
                      if (this.match("=>")) {
                        if (expr.type === syntax_1.Syntax.Identifier && expr.name === "yield") {
                          arrow = true;
                          expr = {
                            type: ArrowParameterPlaceHolder,
                            params: [expr],
                            async: false
                          };
                        }
                        if (!arrow) {
                          if (!this.context.isBindingElement) {
                            this.throwUnexpectedToken(this.lookahead);
                          }
                          if (expr.type === syntax_1.Syntax.SequenceExpression) {
                            for (var i = 0; i < expr.expressions.length; i++) {
                              this.reinterpretExpressionAsPattern(expr.expressions[i]);
                            }
                          } else {
                            this.reinterpretExpressionAsPattern(expr);
                          }
                          var parameters = expr.type === syntax_1.Syntax.SequenceExpression ? expr.expressions : [expr];
                          expr = {
                            type: ArrowParameterPlaceHolder,
                            params: parameters,
                            async: false
                          };
                        }
                      }
                      this.context.isBindingElement = false;
                    }
                  }
                }
                return expr;
              };
              Parser2.prototype.parseArguments = function() {
                this.expect("(");
                var args = [];
                if (!this.match(")")) {
                  while (true) {
                    var expr = this.match("...") ? this.parseSpreadElement() : this.isolateCoverGrammar(this.parseAssignmentExpression);
                    args.push(expr);
                    if (this.match(")")) {
                      break;
                    }
                    this.expectCommaSeparator();
                    if (this.match(")")) {
                      break;
                    }
                  }
                }
                this.expect(")");
                return args;
              };
              Parser2.prototype.isIdentifierName = function(token) {
                return token.type === 3 || token.type === 4 || token.type === 1 || token.type === 5;
              };
              Parser2.prototype.parseIdentifierName = function() {
                var node = this.createNode();
                var token = this.nextToken();
                if (!this.isIdentifierName(token)) {
                  this.throwUnexpectedToken(token);
                }
                return this.finalize(node, new Node.Identifier(token.value));
              };
              Parser2.prototype.parseNewExpression = function() {
                var node = this.createNode();
                var id = this.parseIdentifierName();
                assert_1.assert(id.name === "new", "New expression must start with `new`");
                var expr;
                if (this.match(".")) {
                  this.nextToken();
                  if (this.lookahead.type === 3 && this.context.inFunctionBody && this.lookahead.value === "target") {
                    var property = this.parseIdentifierName();
                    expr = new Node.MetaProperty(id, property);
                  } else {
                    this.throwUnexpectedToken(this.lookahead);
                  }
                } else {
                  var callee = this.isolateCoverGrammar(this.parseLeftHandSideExpression);
                  var args = this.match("(") ? this.parseArguments() : [];
                  expr = new Node.NewExpression(callee, args);
                  this.context.isAssignmentTarget = false;
                  this.context.isBindingElement = false;
                }
                return this.finalize(node, expr);
              };
              Parser2.prototype.parseAsyncArgument = function() {
                var arg = this.parseAssignmentExpression();
                this.context.firstCoverInitializedNameError = null;
                return arg;
              };
              Parser2.prototype.parseAsyncArguments = function() {
                this.expect("(");
                var args = [];
                if (!this.match(")")) {
                  while (true) {
                    var expr = this.match("...") ? this.parseSpreadElement() : this.isolateCoverGrammar(this.parseAsyncArgument);
                    args.push(expr);
                    if (this.match(")")) {
                      break;
                    }
                    this.expectCommaSeparator();
                    if (this.match(")")) {
                      break;
                    }
                  }
                }
                this.expect(")");
                return args;
              };
              Parser2.prototype.parseLeftHandSideExpressionAllowCall = function() {
                var startToken = this.lookahead;
                var maybeAsync = this.matchContextualKeyword("async");
                var previousAllowIn = this.context.allowIn;
                this.context.allowIn = true;
                var expr;
                if (this.matchKeyword("super") && this.context.inFunctionBody) {
                  expr = this.createNode();
                  this.nextToken();
                  expr = this.finalize(expr, new Node.Super());
                  if (!this.match("(") && !this.match(".") && !this.match("[")) {
                    this.throwUnexpectedToken(this.lookahead);
                  }
                } else {
                  expr = this.inheritCoverGrammar(this.matchKeyword("new") ? this.parseNewExpression : this.parsePrimaryExpression);
                }
                while (true) {
                  if (this.match(".")) {
                    this.context.isBindingElement = false;
                    this.context.isAssignmentTarget = true;
                    this.expect(".");
                    var property = this.parseIdentifierName();
                    expr = this.finalize(this.startNode(startToken), new Node.StaticMemberExpression(expr, property));
                  } else if (this.match("(")) {
                    var asyncArrow = maybeAsync && startToken.lineNumber === this.lookahead.lineNumber;
                    this.context.isBindingElement = false;
                    this.context.isAssignmentTarget = false;
                    var args = asyncArrow ? this.parseAsyncArguments() : this.parseArguments();
                    expr = this.finalize(this.startNode(startToken), new Node.CallExpression(expr, args));
                    if (asyncArrow && this.match("=>")) {
                      for (var i = 0; i < args.length; ++i) {
                        this.reinterpretExpressionAsPattern(args[i]);
                      }
                      expr = {
                        type: ArrowParameterPlaceHolder,
                        params: args,
                        async: true
                      };
                    }
                  } else if (this.match("[")) {
                    this.context.isBindingElement = false;
                    this.context.isAssignmentTarget = true;
                    this.expect("[");
                    var property = this.isolateCoverGrammar(this.parseExpression);
                    this.expect("]");
                    expr = this.finalize(this.startNode(startToken), new Node.ComputedMemberExpression(expr, property));
                  } else if (this.lookahead.type === 10 && this.lookahead.head) {
                    var quasi = this.parseTemplateLiteral();
                    expr = this.finalize(this.startNode(startToken), new Node.TaggedTemplateExpression(expr, quasi));
                  } else {
                    break;
                  }
                }
                this.context.allowIn = previousAllowIn;
                return expr;
              };
              Parser2.prototype.parseSuper = function() {
                var node = this.createNode();
                this.expectKeyword("super");
                if (!this.match("[") && !this.match(".")) {
                  this.throwUnexpectedToken(this.lookahead);
                }
                return this.finalize(node, new Node.Super());
              };
              Parser2.prototype.parseLeftHandSideExpression = function() {
                assert_1.assert(this.context.allowIn, "callee of new expression always allow in keyword.");
                var node = this.startNode(this.lookahead);
                var expr = this.matchKeyword("super") && this.context.inFunctionBody ? this.parseSuper() : this.inheritCoverGrammar(this.matchKeyword("new") ? this.parseNewExpression : this.parsePrimaryExpression);
                while (true) {
                  if (this.match("[")) {
                    this.context.isBindingElement = false;
                    this.context.isAssignmentTarget = true;
                    this.expect("[");
                    var property = this.isolateCoverGrammar(this.parseExpression);
                    this.expect("]");
                    expr = this.finalize(node, new Node.ComputedMemberExpression(expr, property));
                  } else if (this.match(".")) {
                    this.context.isBindingElement = false;
                    this.context.isAssignmentTarget = true;
                    this.expect(".");
                    var property = this.parseIdentifierName();
                    expr = this.finalize(node, new Node.StaticMemberExpression(expr, property));
                  } else if (this.lookahead.type === 10 && this.lookahead.head) {
                    var quasi = this.parseTemplateLiteral();
                    expr = this.finalize(node, new Node.TaggedTemplateExpression(expr, quasi));
                  } else {
                    break;
                  }
                }
                return expr;
              };
              Parser2.prototype.parseUpdateExpression = function() {
                var expr;
                var startToken = this.lookahead;
                if (this.match("++") || this.match("--")) {
                  var node = this.startNode(startToken);
                  var token = this.nextToken();
                  expr = this.inheritCoverGrammar(this.parseUnaryExpression);
                  if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) {
                    this.tolerateError(messages_1.Messages.StrictLHSPrefix);
                  }
                  if (!this.context.isAssignmentTarget) {
                    this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
                  }
                  var prefix = true;
                  expr = this.finalize(node, new Node.UpdateExpression(token.value, expr, prefix));
                  this.context.isAssignmentTarget = false;
                  this.context.isBindingElement = false;
                } else {
                  expr = this.inheritCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
                  if (!this.hasLineTerminator && this.lookahead.type === 7) {
                    if (this.match("++") || this.match("--")) {
                      if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) {
                        this.tolerateError(messages_1.Messages.StrictLHSPostfix);
                      }
                      if (!this.context.isAssignmentTarget) {
                        this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
                      }
                      this.context.isAssignmentTarget = false;
                      this.context.isBindingElement = false;
                      var operator = this.nextToken().value;
                      var prefix = false;
                      expr = this.finalize(this.startNode(startToken), new Node.UpdateExpression(operator, expr, prefix));
                    }
                  }
                }
                return expr;
              };
              Parser2.prototype.parseAwaitExpression = function() {
                var node = this.createNode();
                this.nextToken();
                var argument = this.parseUnaryExpression();
                return this.finalize(node, new Node.AwaitExpression(argument));
              };
              Parser2.prototype.parseUnaryExpression = function() {
                var expr;
                if (this.match("+") || this.match("-") || this.match("~") || this.match("!") || this.matchKeyword("delete") || this.matchKeyword("void") || this.matchKeyword("typeof")) {
                  var node = this.startNode(this.lookahead);
                  var token = this.nextToken();
                  expr = this.inheritCoverGrammar(this.parseUnaryExpression);
                  expr = this.finalize(node, new Node.UnaryExpression(token.value, expr));
                  if (this.context.strict && expr.operator === "delete" && expr.argument.type === syntax_1.Syntax.Identifier) {
                    this.tolerateError(messages_1.Messages.StrictDelete);
                  }
                  this.context.isAssignmentTarget = false;
                  this.context.isBindingElement = false;
                } else if (this.context.await && this.matchContextualKeyword("await")) {
                  expr = this.parseAwaitExpression();
                } else {
                  expr = this.parseUpdateExpression();
                }
                return expr;
              };
              Parser2.prototype.parseExponentiationExpression = function() {
                var startToken = this.lookahead;
                var expr = this.inheritCoverGrammar(this.parseUnaryExpression);
                if (expr.type !== syntax_1.Syntax.UnaryExpression && this.match("**")) {
                  this.nextToken();
                  this.context.isAssignmentTarget = false;
                  this.context.isBindingElement = false;
                  var left = expr;
                  var right = this.isolateCoverGrammar(this.parseExponentiationExpression);
                  expr = this.finalize(this.startNode(startToken), new Node.BinaryExpression("**", left, right));
                }
                return expr;
              };
              Parser2.prototype.binaryPrecedence = function(token) {
                var op = token.value;
                var precedence;
                if (token.type === 7) {
                  precedence = this.operatorPrecedence[op] || 0;
                } else if (token.type === 4) {
                  precedence = op === "instanceof" || this.context.allowIn && op === "in" ? 7 : 0;
                } else {
                  precedence = 0;
                }
                return precedence;
              };
              Parser2.prototype.parseBinaryExpression = function() {
                var startToken = this.lookahead;
                var expr = this.inheritCoverGrammar(this.parseExponentiationExpression);
                var token = this.lookahead;
                var prec = this.binaryPrecedence(token);
                if (prec > 0) {
                  this.nextToken();
                  this.context.isAssignmentTarget = false;
                  this.context.isBindingElement = false;
                  var markers = [startToken, this.lookahead];
                  var left = expr;
                  var right = this.isolateCoverGrammar(this.parseExponentiationExpression);
                  var stack = [left, token.value, right];
                  var precedences = [prec];
                  while (true) {
                    prec = this.binaryPrecedence(this.lookahead);
                    if (prec <= 0) {
                      break;
                    }
                    while (stack.length > 2 && prec <= precedences[precedences.length - 1]) {
                      right = stack.pop();
                      var operator = stack.pop();
                      precedences.pop();
                      left = stack.pop();
                      markers.pop();
                      var node = this.startNode(markers[markers.length - 1]);
                      stack.push(this.finalize(node, new Node.BinaryExpression(operator, left, right)));
                    }
                    stack.push(this.nextToken().value);
                    precedences.push(prec);
                    markers.push(this.lookahead);
                    stack.push(this.isolateCoverGrammar(this.parseExponentiationExpression));
                  }
                  var i = stack.length - 1;
                  expr = stack[i];
                  var lastMarker = markers.pop();
                  while (i > 1) {
                    var marker = markers.pop();
                    var lastLineStart = lastMarker && lastMarker.lineStart;
                    var node = this.startNode(marker, lastLineStart);
                    var operator = stack[i - 1];
                    expr = this.finalize(node, new Node.BinaryExpression(operator, stack[i - 2], expr));
                    i -= 2;
                    lastMarker = marker;
                  }
                }
                return expr;
              };
              Parser2.prototype.parseConditionalExpression = function() {
                var startToken = this.lookahead;
                var expr = this.inheritCoverGrammar(this.parseBinaryExpression);
                if (this.match("?")) {
                  this.nextToken();
                  var previousAllowIn = this.context.allowIn;
                  this.context.allowIn = true;
                  var consequent = this.isolateCoverGrammar(this.parseAssignmentExpression);
                  this.context.allowIn = previousAllowIn;
                  this.expect(":");
                  var alternate = this.isolateCoverGrammar(this.parseAssignmentExpression);
                  expr = this.finalize(this.startNode(startToken), new Node.ConditionalExpression(expr, consequent, alternate));
                  this.context.isAssignmentTarget = false;
                  this.context.isBindingElement = false;
                }
                return expr;
              };
              Parser2.prototype.checkPatternParam = function(options, param) {
                switch (param.type) {
                  case syntax_1.Syntax.Identifier:
                    this.validateParam(options, param, param.name);
                    break;
                  case syntax_1.Syntax.RestElement:
                    this.checkPatternParam(options, param.argument);
                    break;
                  case syntax_1.Syntax.AssignmentPattern:
                    this.checkPatternParam(options, param.left);
                    break;
                  case syntax_1.Syntax.ArrayPattern:
                    for (var i = 0; i < param.elements.length; i++) {
                      if (param.elements[i] !== null) {
                        this.checkPatternParam(options, param.elements[i]);
                      }
                    }
                    break;
                  case syntax_1.Syntax.ObjectPattern:
                    for (var i = 0; i < param.properties.length; i++) {
                      this.checkPatternParam(options, param.properties[i].value);
                    }
                    break;
                  default:
                    break;
                }
                options.simple = options.simple && param instanceof Node.Identifier;
              };
              Parser2.prototype.reinterpretAsCoverFormalsList = function(expr) {
                var params = [expr];
                var options;
                var asyncArrow = false;
                switch (expr.type) {
                  case syntax_1.Syntax.Identifier:
                    break;
                  case ArrowParameterPlaceHolder:
                    params = expr.params;
                    asyncArrow = expr.async;
                    break;
                  default:
                    return null;
                }
                options = {
                  simple: true,
                  paramSet: {}
                };
                for (var i = 0; i < params.length; ++i) {
                  var param = params[i];
                  if (param.type === syntax_1.Syntax.AssignmentPattern) {
                    if (param.right.type === syntax_1.Syntax.YieldExpression) {
                      if (param.right.argument) {
                        this.throwUnexpectedToken(this.lookahead);
                      }
                      param.right.type = syntax_1.Syntax.Identifier;
                      param.right.name = "yield";
                      delete param.right.argument;
                      delete param.right.delegate;
                    }
                  } else if (asyncArrow && param.type === syntax_1.Syntax.Identifier && param.name === "await") {
                    this.throwUnexpectedToken(this.lookahead);
                  }
                  this.checkPatternParam(options, param);
                  params[i] = param;
                }
                if (this.context.strict || !this.context.allowYield) {
                  for (var i = 0; i < params.length; ++i) {
                    var param = params[i];
                    if (param.type === syntax_1.Syntax.YieldExpression) {
                      this.throwUnexpectedToken(this.lookahead);
                    }
                  }
                }
                if (options.message === messages_1.Messages.StrictParamDupe) {
                  var token = this.context.strict ? options.stricted : options.firstRestricted;
                  this.throwUnexpectedToken(token, options.message);
                }
                return {
                  simple: options.simple,
                  params,
                  stricted: options.stricted,
                  firstRestricted: options.firstRestricted,
                  message: options.message
                };
              };
              Parser2.prototype.parseAssignmentExpression = function() {
                var expr;
                if (!this.context.allowYield && this.matchKeyword("yield")) {
                  expr = this.parseYieldExpression();
                } else {
                  var startToken = this.lookahead;
                  var token = startToken;
                  expr = this.parseConditionalExpression();
                  if (token.type === 3 && token.lineNumber === this.lookahead.lineNumber && token.value === "async") {
                    if (this.lookahead.type === 3 || this.matchKeyword("yield")) {
                      var arg = this.parsePrimaryExpression();
                      this.reinterpretExpressionAsPattern(arg);
                      expr = {
                        type: ArrowParameterPlaceHolder,
                        params: [arg],
                        async: true
                      };
                    }
                  }
                  if (expr.type === ArrowParameterPlaceHolder || this.match("=>")) {
                    this.context.isAssignmentTarget = false;
                    this.context.isBindingElement = false;
                    var isAsync = expr.async;
                    var list = this.reinterpretAsCoverFormalsList(expr);
                    if (list) {
                      if (this.hasLineTerminator) {
                        this.tolerateUnexpectedToken(this.lookahead);
                      }
                      this.context.firstCoverInitializedNameError = null;
                      var previousStrict = this.context.strict;
                      var previousAllowStrictDirective = this.context.allowStrictDirective;
                      this.context.allowStrictDirective = list.simple;
                      var previousAllowYield = this.context.allowYield;
                      var previousAwait = this.context.await;
                      this.context.allowYield = true;
                      this.context.await = isAsync;
                      var node = this.startNode(startToken);
                      this.expect("=>");
                      var body = void 0;
                      if (this.match("{")) {
                        var previousAllowIn = this.context.allowIn;
                        this.context.allowIn = true;
                        body = this.parseFunctionSourceElements();
                        this.context.allowIn = previousAllowIn;
                      } else {
                        body = this.isolateCoverGrammar(this.parseAssignmentExpression);
                      }
                      var expression = body.type !== syntax_1.Syntax.BlockStatement;
                      if (this.context.strict && list.firstRestricted) {
                        this.throwUnexpectedToken(list.firstRestricted, list.message);
                      }
                      if (this.context.strict && list.stricted) {
                        this.tolerateUnexpectedToken(list.stricted, list.message);
                      }
                      expr = isAsync ? this.finalize(node, new Node.AsyncArrowFunctionExpression(list.params, body, expression)) : this.finalize(node, new Node.ArrowFunctionExpression(list.params, body, expression));
                      this.context.strict = previousStrict;
                      this.context.allowStrictDirective = previousAllowStrictDirective;
                      this.context.allowYield = previousAllowYield;
                      this.context.await = previousAwait;
                    }
                  } else {
                    if (this.matchAssign()) {
                      if (!this.context.isAssignmentTarget) {
                        this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
                      }
                      if (this.context.strict && expr.type === syntax_1.Syntax.Identifier) {
                        var id = expr;
                        if (this.scanner.isRestrictedWord(id.name)) {
                          this.tolerateUnexpectedToken(token, messages_1.Messages.StrictLHSAssignment);
                        }
                        if (this.scanner.isStrictModeReservedWord(id.name)) {
                          this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord);
                        }
                      }
                      if (!this.match("=")) {
                        this.context.isAssignmentTarget = false;
                        this.context.isBindingElement = false;
                      } else {
                        this.reinterpretExpressionAsPattern(expr);
                      }
                      token = this.nextToken();
                      var operator = token.value;
                      var right = this.isolateCoverGrammar(this.parseAssignmentExpression);
                      expr = this.finalize(this.startNode(startToken), new Node.AssignmentExpression(operator, expr, right));
                      this.context.firstCoverInitializedNameError = null;
                    }
                  }
                }
                return expr;
              };
              Parser2.prototype.parseExpression = function() {
                var startToken = this.lookahead;
                var expr = this.isolateCoverGrammar(this.parseAssignmentExpression);
                if (this.match(",")) {
                  var expressions = [];
                  expressions.push(expr);
                  while (this.lookahead.type !== 2) {
                    if (!this.match(",")) {
                      break;
                    }
                    this.nextToken();
                    expressions.push(this.isolateCoverGrammar(this.parseAssignmentExpression));
                  }
                  expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions));
                }
                return expr;
              };
              Parser2.prototype.parseStatementListItem = function() {
                var statement;
                this.context.isAssignmentTarget = true;
                this.context.isBindingElement = true;
                if (this.lookahead.type === 4) {
                  switch (this.lookahead.value) {
                    case "export":
                      if (!this.context.isModule) {
                        this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalExportDeclaration);
                      }
                      statement = this.parseExportDeclaration();
                      break;
                    case "import":
                      if (!this.context.isModule) {
                        this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalImportDeclaration);
                      }
                      statement = this.parseImportDeclaration();
                      break;
                    case "const":
                      statement = this.parseLexicalDeclaration({ inFor: false });
                      break;
                    case "function":
                      statement = this.parseFunctionDeclaration();
                      break;
                    case "class":
                      statement = this.parseClassDeclaration();
                      break;
                    case "let":
                      statement = this.isLexicalDeclaration() ? this.parseLexicalDeclaration({ inFor: false }) : this.parseStatement();
                      break;
                    default:
                      statement = this.parseStatement();
                      break;
                  }
                } else {
                  statement = this.parseStatement();
                }
                return statement;
              };
              Parser2.prototype.parseBlock = function() {
                var node = this.createNode();
                this.expect("{");
                var block = [];
                while (true) {
                  if (this.match("}")) {
                    break;
                  }
                  block.push(this.parseStatementListItem());
                }
                this.expect("}");
                return this.finalize(node, new Node.BlockStatement(block));
              };
              Parser2.prototype.parseLexicalBinding = function(kind, options) {
                var node = this.createNode();
                var params = [];
                var id = this.parsePattern(params, kind);
                if (this.context.strict && id.type === syntax_1.Syntax.Identifier) {
                  if (this.scanner.isRestrictedWord(id.name)) {
                    this.tolerateError(messages_1.Messages.StrictVarName);
                  }
                }
                var init3 = null;
                if (kind === "const") {
                  if (!this.matchKeyword("in") && !this.matchContextualKeyword("of")) {
                    if (this.match("=")) {
                      this.nextToken();
                      init3 = this.isolateCoverGrammar(this.parseAssignmentExpression);
                    } else {
                      this.throwError(messages_1.Messages.DeclarationMissingInitializer, "const");
                    }
                  }
                } else if (!options.inFor && id.type !== syntax_1.Syntax.Identifier || this.match("=")) {
                  this.expect("=");
                  init3 = this.isolateCoverGrammar(this.parseAssignmentExpression);
                }
                return this.finalize(node, new Node.VariableDeclarator(id, init3));
              };
              Parser2.prototype.parseBindingList = function(kind, options) {
                var list = [this.parseLexicalBinding(kind, options)];
                while (this.match(",")) {
                  this.nextToken();
                  list.push(this.parseLexicalBinding(kind, options));
                }
                return list;
              };
              Parser2.prototype.isLexicalDeclaration = function() {
                var state = this.scanner.saveState();
                this.scanner.scanComments();
                var next = this.scanner.lex();
                this.scanner.restoreState(state);
                return next.type === 3 || next.type === 7 && next.value === "[" || next.type === 7 && next.value === "{" || next.type === 4 && next.value === "let" || next.type === 4 && next.value === "yield";
              };
              Parser2.prototype.parseLexicalDeclaration = function(options) {
                var node = this.createNode();
                var kind = this.nextToken().value;
                assert_1.assert(kind === "let" || kind === "const", "Lexical declaration must be either let or const");
                var declarations = this.parseBindingList(kind, options);
                this.consumeSemicolon();
                return this.finalize(node, new Node.VariableDeclaration(declarations, kind));
              };
              Parser2.prototype.parseBindingRestElement = function(params, kind) {
                var node = this.createNode();
                this.expect("...");
                var arg = this.parsePattern(params, kind);
                return this.finalize(node, new Node.RestElement(arg));
              };
              Parser2.prototype.parseArrayPattern = function(params, kind) {
                var node = this.createNode();
                this.expect("[");
                var elements = [];
                while (!this.match("]")) {
                  if (this.match(",")) {
                    this.nextToken();
                    elements.push(null);
                  } else {
                    if (this.match("...")) {
                      elements.push(this.parseBindingRestElement(params, kind));
                      break;
                    } else {
                      elements.push(this.parsePatternWithDefault(params, kind));
                    }
                    if (!this.match("]")) {
                      this.expect(",");
                    }
                  }
                }
                this.expect("]");
                return this.finalize(node, new Node.ArrayPattern(elements));
              };
              Parser2.prototype.parsePropertyPattern = function(params, kind) {
                var node = this.createNode();
                var computed = false;
                var shorthand = false;
                var method = false;
                var key;
                var value;
                if (this.lookahead.type === 3) {
                  var keyToken = this.lookahead;
                  key = this.parseVariableIdentifier();
                  var init3 = this.finalize(node, new Node.Identifier(keyToken.value));
                  if (this.match("=")) {
                    params.push(keyToken);
                    shorthand = true;
                    this.nextToken();
                    var expr = this.parseAssignmentExpression();
                    value = this.finalize(this.startNode(keyToken), new Node.AssignmentPattern(init3, expr));
                  } else if (!this.match(":")) {
                    params.push(keyToken);
                    shorthand = true;
                    value = init3;
                  } else {
                    this.expect(":");
                    value = this.parsePatternWithDefault(params, kind);
                  }
                } else {
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                  this.expect(":");
                  value = this.parsePatternWithDefault(params, kind);
                }
                return this.finalize(node, new Node.Property("init", key, computed, value, method, shorthand));
              };
              Parser2.prototype.parseObjectPattern = function(params, kind) {
                var node = this.createNode();
                var properties = [];
                this.expect("{");
                while (!this.match("}")) {
                  properties.push(this.parsePropertyPattern(params, kind));
                  if (!this.match("}")) {
                    this.expect(",");
                  }
                }
                this.expect("}");
                return this.finalize(node, new Node.ObjectPattern(properties));
              };
              Parser2.prototype.parsePattern = function(params, kind) {
                var pattern;
                if (this.match("[")) {
                  pattern = this.parseArrayPattern(params, kind);
                } else if (this.match("{")) {
                  pattern = this.parseObjectPattern(params, kind);
                } else {
                  if (this.matchKeyword("let") && (kind === "const" || kind === "let")) {
                    this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.LetInLexicalBinding);
                  }
                  params.push(this.lookahead);
                  pattern = this.parseVariableIdentifier(kind);
                }
                return pattern;
              };
              Parser2.prototype.parsePatternWithDefault = function(params, kind) {
                var startToken = this.lookahead;
                var pattern = this.parsePattern(params, kind);
                if (this.match("=")) {
                  this.nextToken();
                  var previousAllowYield = this.context.allowYield;
                  this.context.allowYield = true;
                  var right = this.isolateCoverGrammar(this.parseAssignmentExpression);
                  this.context.allowYield = previousAllowYield;
                  pattern = this.finalize(this.startNode(startToken), new Node.AssignmentPattern(pattern, right));
                }
                return pattern;
              };
              Parser2.prototype.parseVariableIdentifier = function(kind) {
                var node = this.createNode();
                var token = this.nextToken();
                if (token.type === 4 && token.value === "yield") {
                  if (this.context.strict) {
                    this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord);
                  } else if (!this.context.allowYield) {
                    this.throwUnexpectedToken(token);
                  }
                } else if (token.type !== 3) {
                  if (this.context.strict && token.type === 4 && this.scanner.isStrictModeReservedWord(token.value)) {
                    this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord);
                  } else {
                    if (this.context.strict || token.value !== "let" || kind !== "var") {
                      this.throwUnexpectedToken(token);
                    }
                  }
                } else if ((this.context.isModule || this.context.await) && token.type === 3 && token.value === "await") {
                  this.tolerateUnexpectedToken(token);
                }
                return this.finalize(node, new Node.Identifier(token.value));
              };
              Parser2.prototype.parseVariableDeclaration = function(options) {
                var node = this.createNode();
                var params = [];
                var id = this.parsePattern(params, "var");
                if (this.context.strict && id.type === syntax_1.Syntax.Identifier) {
                  if (this.scanner.isRestrictedWord(id.name)) {
                    this.tolerateError(messages_1.Messages.StrictVarName);
                  }
                }
                var init3 = null;
                if (this.match("=")) {
                  this.nextToken();
                  init3 = this.isolateCoverGrammar(this.parseAssignmentExpression);
                } else if (id.type !== syntax_1.Syntax.Identifier && !options.inFor) {
                  this.expect("=");
                }
                return this.finalize(node, new Node.VariableDeclarator(id, init3));
              };
              Parser2.prototype.parseVariableDeclarationList = function(options) {
                var opt = { inFor: options.inFor };
                var list = [];
                list.push(this.parseVariableDeclaration(opt));
                while (this.match(",")) {
                  this.nextToken();
                  list.push(this.parseVariableDeclaration(opt));
                }
                return list;
              };
              Parser2.prototype.parseVariableStatement = function() {
                var node = this.createNode();
                this.expectKeyword("var");
                var declarations = this.parseVariableDeclarationList({ inFor: false });
                this.consumeSemicolon();
                return this.finalize(node, new Node.VariableDeclaration(declarations, "var"));
              };
              Parser2.prototype.parseEmptyStatement = function() {
                var node = this.createNode();
                this.expect(";");
                return this.finalize(node, new Node.EmptyStatement());
              };
              Parser2.prototype.parseExpressionStatement = function() {
                var node = this.createNode();
                var expr = this.parseExpression();
                this.consumeSemicolon();
                return this.finalize(node, new Node.ExpressionStatement(expr));
              };
              Parser2.prototype.parseIfClause = function() {
                if (this.context.strict && this.matchKeyword("function")) {
                  this.tolerateError(messages_1.Messages.StrictFunction);
                }
                return this.parseStatement();
              };
              Parser2.prototype.parseIfStatement = function() {
                var node = this.createNode();
                var consequent;
                var alternate = null;
                this.expectKeyword("if");
                this.expect("(");
                var test = this.parseExpression();
                if (!this.match(")") && this.config.tolerant) {
                  this.tolerateUnexpectedToken(this.nextToken());
                  consequent = this.finalize(this.createNode(), new Node.EmptyStatement());
                } else {
                  this.expect(")");
                  consequent = this.parseIfClause();
                  if (this.matchKeyword("else")) {
                    this.nextToken();
                    alternate = this.parseIfClause();
                  }
                }
                return this.finalize(node, new Node.IfStatement(test, consequent, alternate));
              };
              Parser2.prototype.parseDoWhileStatement = function() {
                var node = this.createNode();
                this.expectKeyword("do");
                var previousInIteration = this.context.inIteration;
                this.context.inIteration = true;
                var body = this.parseStatement();
                this.context.inIteration = previousInIteration;
                this.expectKeyword("while");
                this.expect("(");
                var test = this.parseExpression();
                if (!this.match(")") && this.config.tolerant) {
                  this.tolerateUnexpectedToken(this.nextToken());
                } else {
                  this.expect(")");
                  if (this.match(";")) {
                    this.nextToken();
                  }
                }
                return this.finalize(node, new Node.DoWhileStatement(body, test));
              };
              Parser2.prototype.parseWhileStatement = function() {
                var node = this.createNode();
                var body;
                this.expectKeyword("while");
                this.expect("(");
                var test = this.parseExpression();
                if (!this.match(")") && this.config.tolerant) {
                  this.tolerateUnexpectedToken(this.nextToken());
                  body = this.finalize(this.createNode(), new Node.EmptyStatement());
                } else {
                  this.expect(")");
                  var previousInIteration = this.context.inIteration;
                  this.context.inIteration = true;
                  body = this.parseStatement();
                  this.context.inIteration = previousInIteration;
                }
                return this.finalize(node, new Node.WhileStatement(test, body));
              };
              Parser2.prototype.parseForStatement = function() {
                var init3 = null;
                var test = null;
                var update = null;
                var forIn = true;
                var left, right;
                var node = this.createNode();
                this.expectKeyword("for");
                this.expect("(");
                if (this.match(";")) {
                  this.nextToken();
                } else {
                  if (this.matchKeyword("var")) {
                    init3 = this.createNode();
                    this.nextToken();
                    var previousAllowIn = this.context.allowIn;
                    this.context.allowIn = false;
                    var declarations = this.parseVariableDeclarationList({ inFor: true });
                    this.context.allowIn = previousAllowIn;
                    if (declarations.length === 1 && this.matchKeyword("in")) {
                      var decl = declarations[0];
                      if (decl.init && (decl.id.type === syntax_1.Syntax.ArrayPattern || decl.id.type === syntax_1.Syntax.ObjectPattern || this.context.strict)) {
                        this.tolerateError(messages_1.Messages.ForInOfLoopInitializer, "for-in");
                      }
                      init3 = this.finalize(init3, new Node.VariableDeclaration(declarations, "var"));
                      this.nextToken();
                      left = init3;
                      right = this.parseExpression();
                      init3 = null;
                    } else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword("of")) {
                      init3 = this.finalize(init3, new Node.VariableDeclaration(declarations, "var"));
                      this.nextToken();
                      left = init3;
                      right = this.parseAssignmentExpression();
                      init3 = null;
                      forIn = false;
                    } else {
                      init3 = this.finalize(init3, new Node.VariableDeclaration(declarations, "var"));
                      this.expect(";");
                    }
                  } else if (this.matchKeyword("const") || this.matchKeyword("let")) {
                    init3 = this.createNode();
                    var kind = this.nextToken().value;
                    if (!this.context.strict && this.lookahead.value === "in") {
                      init3 = this.finalize(init3, new Node.Identifier(kind));
                      this.nextToken();
                      left = init3;
                      right = this.parseExpression();
                      init3 = null;
                    } else {
                      var previousAllowIn = this.context.allowIn;
                      this.context.allowIn = false;
                      var declarations = this.parseBindingList(kind, { inFor: true });
                      this.context.allowIn = previousAllowIn;
                      if (declarations.length === 1 && declarations[0].init === null && this.matchKeyword("in")) {
                        init3 = this.finalize(init3, new Node.VariableDeclaration(declarations, kind));
                        this.nextToken();
                        left = init3;
                        right = this.parseExpression();
                        init3 = null;
                      } else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword("of")) {
                        init3 = this.finalize(init3, new Node.VariableDeclaration(declarations, kind));
                        this.nextToken();
                        left = init3;
                        right = this.parseAssignmentExpression();
                        init3 = null;
                        forIn = false;
                      } else {
                        this.consumeSemicolon();
                        init3 = this.finalize(init3, new Node.VariableDeclaration(declarations, kind));
                      }
                    }
                  } else {
                    var initStartToken = this.lookahead;
                    var previousAllowIn = this.context.allowIn;
                    this.context.allowIn = false;
                    init3 = this.inheritCoverGrammar(this.parseAssignmentExpression);
                    this.context.allowIn = previousAllowIn;
                    if (this.matchKeyword("in")) {
                      if (!this.context.isAssignmentTarget || init3.type === syntax_1.Syntax.AssignmentExpression) {
                        this.tolerateError(messages_1.Messages.InvalidLHSInForIn);
                      }
                      this.nextToken();
                      this.reinterpretExpressionAsPattern(init3);
                      left = init3;
                      right = this.parseExpression();
                      init3 = null;
                    } else if (this.matchContextualKeyword("of")) {
                      if (!this.context.isAssignmentTarget || init3.type === syntax_1.Syntax.AssignmentExpression) {
                        this.tolerateError(messages_1.Messages.InvalidLHSInForLoop);
                      }
                      this.nextToken();
                      this.reinterpretExpressionAsPattern(init3);
                      left = init3;
                      right = this.parseAssignmentExpression();
                      init3 = null;
                      forIn = false;
                    } else {
                      if (this.match(",")) {
                        var initSeq = [init3];
                        while (this.match(",")) {
                          this.nextToken();
                          initSeq.push(this.isolateCoverGrammar(this.parseAssignmentExpression));
                        }
                        init3 = this.finalize(this.startNode(initStartToken), new Node.SequenceExpression(initSeq));
                      }
                      this.expect(";");
                    }
                  }
                }
                if (typeof left === "undefined") {
                  if (!this.match(";")) {
                    test = this.parseExpression();
                  }
                  this.expect(";");
                  if (!this.match(")")) {
                    update = this.parseExpression();
                  }
                }
                var body;
                if (!this.match(")") && this.config.tolerant) {
                  this.tolerateUnexpectedToken(this.nextToken());
                  body = this.finalize(this.createNode(), new Node.EmptyStatement());
                } else {
                  this.expect(")");
                  var previousInIteration = this.context.inIteration;
                  this.context.inIteration = true;
                  body = this.isolateCoverGrammar(this.parseStatement);
                  this.context.inIteration = previousInIteration;
                }
                return typeof left === "undefined" ? this.finalize(node, new Node.ForStatement(init3, test, update, body)) : forIn ? this.finalize(node, new Node.ForInStatement(left, right, body)) : this.finalize(node, new Node.ForOfStatement(left, right, body));
              };
              Parser2.prototype.parseContinueStatement = function() {
                var node = this.createNode();
                this.expectKeyword("continue");
                var label = null;
                if (this.lookahead.type === 3 && !this.hasLineTerminator) {
                  var id = this.parseVariableIdentifier();
                  label = id;
                  var key = "$" + id.name;
                  if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
                    this.throwError(messages_1.Messages.UnknownLabel, id.name);
                  }
                }
                this.consumeSemicolon();
                if (label === null && !this.context.inIteration) {
                  this.throwError(messages_1.Messages.IllegalContinue);
                }
                return this.finalize(node, new Node.ContinueStatement(label));
              };
              Parser2.prototype.parseBreakStatement = function() {
                var node = this.createNode();
                this.expectKeyword("break");
                var label = null;
                if (this.lookahead.type === 3 && !this.hasLineTerminator) {
                  var id = this.parseVariableIdentifier();
                  var key = "$" + id.name;
                  if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
                    this.throwError(messages_1.Messages.UnknownLabel, id.name);
                  }
                  label = id;
                }
                this.consumeSemicolon();
                if (label === null && !this.context.inIteration && !this.context.inSwitch) {
                  this.throwError(messages_1.Messages.IllegalBreak);
                }
                return this.finalize(node, new Node.BreakStatement(label));
              };
              Parser2.prototype.parseReturnStatement = function() {
                if (!this.context.inFunctionBody) {
                  this.tolerateError(messages_1.Messages.IllegalReturn);
                }
                var node = this.createNode();
                this.expectKeyword("return");
                var hasArgument = !this.match(";") && !this.match("}") && !this.hasLineTerminator && this.lookahead.type !== 2 || this.lookahead.type === 8 || this.lookahead.type === 10;
                var argument = hasArgument ? this.parseExpression() : null;
                this.consumeSemicolon();
                return this.finalize(node, new Node.ReturnStatement(argument));
              };
              Parser2.prototype.parseWithStatement = function() {
                if (this.context.strict) {
                  this.tolerateError(messages_1.Messages.StrictModeWith);
                }
                var node = this.createNode();
                var body;
                this.expectKeyword("with");
                this.expect("(");
                var object3 = this.parseExpression();
                if (!this.match(")") && this.config.tolerant) {
                  this.tolerateUnexpectedToken(this.nextToken());
                  body = this.finalize(this.createNode(), new Node.EmptyStatement());
                } else {
                  this.expect(")");
                  body = this.parseStatement();
                }
                return this.finalize(node, new Node.WithStatement(object3, body));
              };
              Parser2.prototype.parseSwitchCase = function() {
                var node = this.createNode();
                var test;
                if (this.matchKeyword("default")) {
                  this.nextToken();
                  test = null;
                } else {
                  this.expectKeyword("case");
                  test = this.parseExpression();
                }
                this.expect(":");
                var consequent = [];
                while (true) {
                  if (this.match("}") || this.matchKeyword("default") || this.matchKeyword("case")) {
                    break;
                  }
                  consequent.push(this.parseStatementListItem());
                }
                return this.finalize(node, new Node.SwitchCase(test, consequent));
              };
              Parser2.prototype.parseSwitchStatement = function() {
                var node = this.createNode();
                this.expectKeyword("switch");
                this.expect("(");
                var discriminant = this.parseExpression();
                this.expect(")");
                var previousInSwitch = this.context.inSwitch;
                this.context.inSwitch = true;
                var cases = [];
                var defaultFound = false;
                this.expect("{");
                while (true) {
                  if (this.match("}")) {
                    break;
                  }
                  var clause = this.parseSwitchCase();
                  if (clause.test === null) {
                    if (defaultFound) {
                      this.throwError(messages_1.Messages.MultipleDefaultsInSwitch);
                    }
                    defaultFound = true;
                  }
                  cases.push(clause);
                }
                this.expect("}");
                this.context.inSwitch = previousInSwitch;
                return this.finalize(node, new Node.SwitchStatement(discriminant, cases));
              };
              Parser2.prototype.parseLabelledStatement = function() {
                var node = this.createNode();
                var expr = this.parseExpression();
                var statement;
                if (expr.type === syntax_1.Syntax.Identifier && this.match(":")) {
                  this.nextToken();
                  var id = expr;
                  var key = "$" + id.name;
                  if (Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
                    this.throwError(messages_1.Messages.Redeclaration, "Label", id.name);
                  }
                  this.context.labelSet[key] = true;
                  var body = void 0;
                  if (this.matchKeyword("class")) {
                    this.tolerateUnexpectedToken(this.lookahead);
                    body = this.parseClassDeclaration();
                  } else if (this.matchKeyword("function")) {
                    var token = this.lookahead;
                    var declaration = this.parseFunctionDeclaration();
                    if (this.context.strict) {
                      this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunction);
                    } else if (declaration.generator) {
                      this.tolerateUnexpectedToken(token, messages_1.Messages.GeneratorInLegacyContext);
                    }
                    body = declaration;
                  } else {
                    body = this.parseStatement();
                  }
                  delete this.context.labelSet[key];
                  statement = new Node.LabeledStatement(id, body);
                } else {
                  this.consumeSemicolon();
                  statement = new Node.ExpressionStatement(expr);
                }
                return this.finalize(node, statement);
              };
              Parser2.prototype.parseThrowStatement = function() {
                var node = this.createNode();
                this.expectKeyword("throw");
                if (this.hasLineTerminator) {
                  this.throwError(messages_1.Messages.NewlineAfterThrow);
                }
                var argument = this.parseExpression();
                this.consumeSemicolon();
                return this.finalize(node, new Node.ThrowStatement(argument));
              };
              Parser2.prototype.parseCatchClause = function() {
                var node = this.createNode();
                this.expectKeyword("catch");
                this.expect("(");
                if (this.match(")")) {
                  this.throwUnexpectedToken(this.lookahead);
                }
                var params = [];
                var param = this.parsePattern(params);
                var paramMap = {};
                for (var i = 0; i < params.length; i++) {
                  var key = "$" + params[i].value;
                  if (Object.prototype.hasOwnProperty.call(paramMap, key)) {
                    this.tolerateError(messages_1.Messages.DuplicateBinding, params[i].value);
                  }
                  paramMap[key] = true;
                }
                if (this.context.strict && param.type === syntax_1.Syntax.Identifier) {
                  if (this.scanner.isRestrictedWord(param.name)) {
                    this.tolerateError(messages_1.Messages.StrictCatchVariable);
                  }
                }
                this.expect(")");
                var body = this.parseBlock();
                return this.finalize(node, new Node.CatchClause(param, body));
              };
              Parser2.prototype.parseFinallyClause = function() {
                this.expectKeyword("finally");
                return this.parseBlock();
              };
              Parser2.prototype.parseTryStatement = function() {
                var node = this.createNode();
                this.expectKeyword("try");
                var block = this.parseBlock();
                var handler = this.matchKeyword("catch") ? this.parseCatchClause() : null;
                var finalizer = this.matchKeyword("finally") ? this.parseFinallyClause() : null;
                if (!handler && !finalizer) {
                  this.throwError(messages_1.Messages.NoCatchOrFinally);
                }
                return this.finalize(node, new Node.TryStatement(block, handler, finalizer));
              };
              Parser2.prototype.parseDebuggerStatement = function() {
                var node = this.createNode();
                this.expectKeyword("debugger");
                this.consumeSemicolon();
                return this.finalize(node, new Node.DebuggerStatement());
              };
              Parser2.prototype.parseStatement = function() {
                var statement;
                switch (this.lookahead.type) {
                  case 1:
                  case 5:
                  case 6:
                  case 8:
                  case 10:
                  case 9:
                    statement = this.parseExpressionStatement();
                    break;
                  case 7:
                    var value = this.lookahead.value;
                    if (value === "{") {
                      statement = this.parseBlock();
                    } else if (value === "(") {
                      statement = this.parseExpressionStatement();
                    } else if (value === ";") {
                      statement = this.parseEmptyStatement();
                    } else {
                      statement = this.parseExpressionStatement();
                    }
                    break;
                  case 3:
                    statement = this.matchAsyncFunction() ? this.parseFunctionDeclaration() : this.parseLabelledStatement();
                    break;
                  case 4:
                    switch (this.lookahead.value) {
                      case "break":
                        statement = this.parseBreakStatement();
                        break;
                      case "continue":
                        statement = this.parseContinueStatement();
                        break;
                      case "debugger":
                        statement = this.parseDebuggerStatement();
                        break;
                      case "do":
                        statement = this.parseDoWhileStatement();
                        break;
                      case "for":
                        statement = this.parseForStatement();
                        break;
                      case "function":
                        statement = this.parseFunctionDeclaration();
                        break;
                      case "if":
                        statement = this.parseIfStatement();
                        break;
                      case "return":
                        statement = this.parseReturnStatement();
                        break;
                      case "switch":
                        statement = this.parseSwitchStatement();
                        break;
                      case "throw":
                        statement = this.parseThrowStatement();
                        break;
                      case "try":
                        statement = this.parseTryStatement();
                        break;
                      case "var":
                        statement = this.parseVariableStatement();
                        break;
                      case "while":
                        statement = this.parseWhileStatement();
                        break;
                      case "with":
                        statement = this.parseWithStatement();
                        break;
                      default:
                        statement = this.parseExpressionStatement();
                        break;
                    }
                    break;
                  default:
                    statement = this.throwUnexpectedToken(this.lookahead);
                }
                return statement;
              };
              Parser2.prototype.parseFunctionSourceElements = function() {
                var node = this.createNode();
                this.expect("{");
                var body = this.parseDirectivePrologues();
                var previousLabelSet = this.context.labelSet;
                var previousInIteration = this.context.inIteration;
                var previousInSwitch = this.context.inSwitch;
                var previousInFunctionBody = this.context.inFunctionBody;
                this.context.labelSet = {};
                this.context.inIteration = false;
                this.context.inSwitch = false;
                this.context.inFunctionBody = true;
                while (this.lookahead.type !== 2) {
                  if (this.match("}")) {
                    break;
                  }
                  body.push(this.parseStatementListItem());
                }
                this.expect("}");
                this.context.labelSet = previousLabelSet;
                this.context.inIteration = previousInIteration;
                this.context.inSwitch = previousInSwitch;
                this.context.inFunctionBody = previousInFunctionBody;
                return this.finalize(node, new Node.BlockStatement(body));
              };
              Parser2.prototype.validateParam = function(options, param, name) {
                var key = "$" + name;
                if (this.context.strict) {
                  if (this.scanner.isRestrictedWord(name)) {
                    options.stricted = param;
                    options.message = messages_1.Messages.StrictParamName;
                  }
                  if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
                    options.stricted = param;
                    options.message = messages_1.Messages.StrictParamDupe;
                  }
                } else if (!options.firstRestricted) {
                  if (this.scanner.isRestrictedWord(name)) {
                    options.firstRestricted = param;
                    options.message = messages_1.Messages.StrictParamName;
                  } else if (this.scanner.isStrictModeReservedWord(name)) {
                    options.firstRestricted = param;
                    options.message = messages_1.Messages.StrictReservedWord;
                  } else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
                    options.stricted = param;
                    options.message = messages_1.Messages.StrictParamDupe;
                  }
                }
                if (typeof Object.defineProperty === "function") {
                  Object.defineProperty(options.paramSet, key, { value: true, enumerable: true, writable: true, configurable: true });
                } else {
                  options.paramSet[key] = true;
                }
              };
              Parser2.prototype.parseRestElement = function(params) {
                var node = this.createNode();
                this.expect("...");
                var arg = this.parsePattern(params);
                if (this.match("=")) {
                  this.throwError(messages_1.Messages.DefaultRestParameter);
                }
                if (!this.match(")")) {
                  this.throwError(messages_1.Messages.ParameterAfterRestParameter);
                }
                return this.finalize(node, new Node.RestElement(arg));
              };
              Parser2.prototype.parseFormalParameter = function(options) {
                var params = [];
                var param = this.match("...") ? this.parseRestElement(params) : this.parsePatternWithDefault(params);
                for (var i = 0; i < params.length; i++) {
                  this.validateParam(options, params[i], params[i].value);
                }
                options.simple = options.simple && param instanceof Node.Identifier;
                options.params.push(param);
              };
              Parser2.prototype.parseFormalParameters = function(firstRestricted) {
                var options;
                options = {
                  simple: true,
                  params: [],
                  firstRestricted
                };
                this.expect("(");
                if (!this.match(")")) {
                  options.paramSet = {};
                  while (this.lookahead.type !== 2) {
                    this.parseFormalParameter(options);
                    if (this.match(")")) {
                      break;
                    }
                    this.expect(",");
                    if (this.match(")")) {
                      break;
                    }
                  }
                }
                this.expect(")");
                return {
                  simple: options.simple,
                  params: options.params,
                  stricted: options.stricted,
                  firstRestricted: options.firstRestricted,
                  message: options.message
                };
              };
              Parser2.prototype.matchAsyncFunction = function() {
                var match = this.matchContextualKeyword("async");
                if (match) {
                  var state = this.scanner.saveState();
                  this.scanner.scanComments();
                  var next = this.scanner.lex();
                  this.scanner.restoreState(state);
                  match = state.lineNumber === next.lineNumber && next.type === 4 && next.value === "function";
                }
                return match;
              };
              Parser2.prototype.parseFunctionDeclaration = function(identifierIsOptional) {
                var node = this.createNode();
                var isAsync = this.matchContextualKeyword("async");
                if (isAsync) {
                  this.nextToken();
                }
                this.expectKeyword("function");
                var isGenerator = isAsync ? false : this.match("*");
                if (isGenerator) {
                  this.nextToken();
                }
                var message;
                var id = null;
                var firstRestricted = null;
                if (!identifierIsOptional || !this.match("(")) {
                  var token = this.lookahead;
                  id = this.parseVariableIdentifier();
                  if (this.context.strict) {
                    if (this.scanner.isRestrictedWord(token.value)) {
                      this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName);
                    }
                  } else {
                    if (this.scanner.isRestrictedWord(token.value)) {
                      firstRestricted = token;
                      message = messages_1.Messages.StrictFunctionName;
                    } else if (this.scanner.isStrictModeReservedWord(token.value)) {
                      firstRestricted = token;
                      message = messages_1.Messages.StrictReservedWord;
                    }
                  }
                }
                var previousAllowAwait = this.context.await;
                var previousAllowYield = this.context.allowYield;
                this.context.await = isAsync;
                this.context.allowYield = !isGenerator;
                var formalParameters = this.parseFormalParameters(firstRestricted);
                var params = formalParameters.params;
                var stricted = formalParameters.stricted;
                firstRestricted = formalParameters.firstRestricted;
                if (formalParameters.message) {
                  message = formalParameters.message;
                }
                var previousStrict = this.context.strict;
                var previousAllowStrictDirective = this.context.allowStrictDirective;
                this.context.allowStrictDirective = formalParameters.simple;
                var body = this.parseFunctionSourceElements();
                if (this.context.strict && firstRestricted) {
                  this.throwUnexpectedToken(firstRestricted, message);
                }
                if (this.context.strict && stricted) {
                  this.tolerateUnexpectedToken(stricted, message);
                }
                this.context.strict = previousStrict;
                this.context.allowStrictDirective = previousAllowStrictDirective;
                this.context.await = previousAllowAwait;
                this.context.allowYield = previousAllowYield;
                return isAsync ? this.finalize(node, new Node.AsyncFunctionDeclaration(id, params, body)) : this.finalize(node, new Node.FunctionDeclaration(id, params, body, isGenerator));
              };
              Parser2.prototype.parseFunctionExpression = function() {
                var node = this.createNode();
                var isAsync = this.matchContextualKeyword("async");
                if (isAsync) {
                  this.nextToken();
                }
                this.expectKeyword("function");
                var isGenerator = isAsync ? false : this.match("*");
                if (isGenerator) {
                  this.nextToken();
                }
                var message;
                var id = null;
                var firstRestricted;
                var previousAllowAwait = this.context.await;
                var previousAllowYield = this.context.allowYield;
                this.context.await = isAsync;
                this.context.allowYield = !isGenerator;
                if (!this.match("(")) {
                  var token = this.lookahead;
                  id = !this.context.strict && !isGenerator && this.matchKeyword("yield") ? this.parseIdentifierName() : this.parseVariableIdentifier();
                  if (this.context.strict) {
                    if (this.scanner.isRestrictedWord(token.value)) {
                      this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName);
                    }
                  } else {
                    if (this.scanner.isRestrictedWord(token.value)) {
                      firstRestricted = token;
                      message = messages_1.Messages.StrictFunctionName;
                    } else if (this.scanner.isStrictModeReservedWord(token.value)) {
                      firstRestricted = token;
                      message = messages_1.Messages.StrictReservedWord;
                    }
                  }
                }
                var formalParameters = this.parseFormalParameters(firstRestricted);
                var params = formalParameters.params;
                var stricted = formalParameters.stricted;
                firstRestricted = formalParameters.firstRestricted;
                if (formalParameters.message) {
                  message = formalParameters.message;
                }
                var previousStrict = this.context.strict;
                var previousAllowStrictDirective = this.context.allowStrictDirective;
                this.context.allowStrictDirective = formalParameters.simple;
                var body = this.parseFunctionSourceElements();
                if (this.context.strict && firstRestricted) {
                  this.throwUnexpectedToken(firstRestricted, message);
                }
                if (this.context.strict && stricted) {
                  this.tolerateUnexpectedToken(stricted, message);
                }
                this.context.strict = previousStrict;
                this.context.allowStrictDirective = previousAllowStrictDirective;
                this.context.await = previousAllowAwait;
                this.context.allowYield = previousAllowYield;
                return isAsync ? this.finalize(node, new Node.AsyncFunctionExpression(id, params, body)) : this.finalize(node, new Node.FunctionExpression(id, params, body, isGenerator));
              };
              Parser2.prototype.parseDirective = function() {
                var token = this.lookahead;
                var node = this.createNode();
                var expr = this.parseExpression();
                var directive = expr.type === syntax_1.Syntax.Literal ? this.getTokenRaw(token).slice(1, -1) : null;
                this.consumeSemicolon();
                return this.finalize(node, directive ? new Node.Directive(expr, directive) : new Node.ExpressionStatement(expr));
              };
              Parser2.prototype.parseDirectivePrologues = function() {
                var firstRestricted = null;
                var body = [];
                while (true) {
                  var token = this.lookahead;
                  if (token.type !== 8) {
                    break;
                  }
                  var statement = this.parseDirective();
                  body.push(statement);
                  var directive = statement.directive;
                  if (typeof directive !== "string") {
                    break;
                  }
                  if (directive === "use strict") {
                    this.context.strict = true;
                    if (firstRestricted) {
                      this.tolerateUnexpectedToken(firstRestricted, messages_1.Messages.StrictOctalLiteral);
                    }
                    if (!this.context.allowStrictDirective) {
                      this.tolerateUnexpectedToken(token, messages_1.Messages.IllegalLanguageModeDirective);
                    }
                  } else {
                    if (!firstRestricted && token.octal) {
                      firstRestricted = token;
                    }
                  }
                }
                return body;
              };
              Parser2.prototype.qualifiedPropertyName = function(token) {
                switch (token.type) {
                  case 3:
                  case 8:
                  case 1:
                  case 5:
                  case 6:
                  case 4:
                    return true;
                  case 7:
                    return token.value === "[";
                  default:
                    break;
                }
                return false;
              };
              Parser2.prototype.parseGetterMethod = function() {
                var node = this.createNode();
                var isGenerator = false;
                var previousAllowYield = this.context.allowYield;
                this.context.allowYield = !isGenerator;
                var formalParameters = this.parseFormalParameters();
                if (formalParameters.params.length > 0) {
                  this.tolerateError(messages_1.Messages.BadGetterArity);
                }
                var method = this.parsePropertyMethod(formalParameters);
                this.context.allowYield = previousAllowYield;
                return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator));
              };
              Parser2.prototype.parseSetterMethod = function() {
                var node = this.createNode();
                var isGenerator = false;
                var previousAllowYield = this.context.allowYield;
                this.context.allowYield = !isGenerator;
                var formalParameters = this.parseFormalParameters();
                if (formalParameters.params.length !== 1) {
                  this.tolerateError(messages_1.Messages.BadSetterArity);
                } else if (formalParameters.params[0] instanceof Node.RestElement) {
                  this.tolerateError(messages_1.Messages.BadSetterRestParameter);
                }
                var method = this.parsePropertyMethod(formalParameters);
                this.context.allowYield = previousAllowYield;
                return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator));
              };
              Parser2.prototype.parseGeneratorMethod = function() {
                var node = this.createNode();
                var isGenerator = true;
                var previousAllowYield = this.context.allowYield;
                this.context.allowYield = true;
                var params = this.parseFormalParameters();
                this.context.allowYield = false;
                var method = this.parsePropertyMethod(params);
                this.context.allowYield = previousAllowYield;
                return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator));
              };
              Parser2.prototype.isStartOfExpression = function() {
                var start = true;
                var value = this.lookahead.value;
                switch (this.lookahead.type) {
                  case 7:
                    start = value === "[" || value === "(" || value === "{" || value === "+" || value === "-" || value === "!" || value === "~" || value === "++" || value === "--" || value === "/" || value === "/=";
                    break;
                  case 4:
                    start = value === "class" || value === "delete" || value === "function" || value === "let" || value === "new" || value === "super" || value === "this" || value === "typeof" || value === "void" || value === "yield";
                    break;
                  default:
                    break;
                }
                return start;
              };
              Parser2.prototype.parseYieldExpression = function() {
                var node = this.createNode();
                this.expectKeyword("yield");
                var argument = null;
                var delegate = false;
                if (!this.hasLineTerminator) {
                  var previousAllowYield = this.context.allowYield;
                  this.context.allowYield = false;
                  delegate = this.match("*");
                  if (delegate) {
                    this.nextToken();
                    argument = this.parseAssignmentExpression();
                  } else if (this.isStartOfExpression()) {
                    argument = this.parseAssignmentExpression();
                  }
                  this.context.allowYield = previousAllowYield;
                }
                return this.finalize(node, new Node.YieldExpression(argument, delegate));
              };
              Parser2.prototype.parseClassElement = function(hasConstructor) {
                var token = this.lookahead;
                var node = this.createNode();
                var kind = "";
                var key = null;
                var value = null;
                var computed = false;
                var method = false;
                var isStatic = false;
                var isAsync = false;
                if (this.match("*")) {
                  this.nextToken();
                } else {
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                  var id = key;
                  if (id.name === "static" && (this.qualifiedPropertyName(this.lookahead) || this.match("*"))) {
                    token = this.lookahead;
                    isStatic = true;
                    computed = this.match("[");
                    if (this.match("*")) {
                      this.nextToken();
                    } else {
                      key = this.parseObjectPropertyKey();
                    }
                  }
                  if (token.type === 3 && !this.hasLineTerminator && token.value === "async") {
                    var punctuator = this.lookahead.value;
                    if (punctuator !== ":" && punctuator !== "(" && punctuator !== "*") {
                      isAsync = true;
                      token = this.lookahead;
                      key = this.parseObjectPropertyKey();
                      if (token.type === 3 && token.value === "constructor") {
                        this.tolerateUnexpectedToken(token, messages_1.Messages.ConstructorIsAsync);
                      }
                    }
                  }
                }
                var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead);
                if (token.type === 3) {
                  if (token.value === "get" && lookaheadPropertyKey) {
                    kind = "get";
                    computed = this.match("[");
                    key = this.parseObjectPropertyKey();
                    this.context.allowYield = false;
                    value = this.parseGetterMethod();
                  } else if (token.value === "set" && lookaheadPropertyKey) {
                    kind = "set";
                    computed = this.match("[");
                    key = this.parseObjectPropertyKey();
                    value = this.parseSetterMethod();
                  }
                } else if (token.type === 7 && token.value === "*" && lookaheadPropertyKey) {
                  kind = "init";
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                  value = this.parseGeneratorMethod();
                  method = true;
                }
                if (!kind && key && this.match("(")) {
                  kind = "init";
                  value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction();
                  method = true;
                }
                if (!kind) {
                  this.throwUnexpectedToken(this.lookahead);
                }
                if (kind === "init") {
                  kind = "method";
                }
                if (!computed) {
                  if (isStatic && this.isPropertyKey(key, "prototype")) {
                    this.throwUnexpectedToken(token, messages_1.Messages.StaticPrototype);
                  }
                  if (!isStatic && this.isPropertyKey(key, "constructor")) {
                    if (kind !== "method" || !method || value && value.generator) {
                      this.throwUnexpectedToken(token, messages_1.Messages.ConstructorSpecialMethod);
                    }
                    if (hasConstructor.value) {
                      this.throwUnexpectedToken(token, messages_1.Messages.DuplicateConstructor);
                    } else {
                      hasConstructor.value = true;
                    }
                    kind = "constructor";
                  }
                }
                return this.finalize(node, new Node.MethodDefinition(key, computed, value, kind, isStatic));
              };
              Parser2.prototype.parseClassElementList = function() {
                var body = [];
                var hasConstructor = { value: false };
                this.expect("{");
                while (!this.match("}")) {
                  if (this.match(";")) {
                    this.nextToken();
                  } else {
                    body.push(this.parseClassElement(hasConstructor));
                  }
                }
                this.expect("}");
                return body;
              };
              Parser2.prototype.parseClassBody = function() {
                var node = this.createNode();
                var elementList = this.parseClassElementList();
                return this.finalize(node, new Node.ClassBody(elementList));
              };
              Parser2.prototype.parseClassDeclaration = function(identifierIsOptional) {
                var node = this.createNode();
                var previousStrict = this.context.strict;
                this.context.strict = true;
                this.expectKeyword("class");
                var id = identifierIsOptional && this.lookahead.type !== 3 ? null : this.parseVariableIdentifier();
                var superClass = null;
                if (this.matchKeyword("extends")) {
                  this.nextToken();
                  superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
                }
                var classBody = this.parseClassBody();
                this.context.strict = previousStrict;
                return this.finalize(node, new Node.ClassDeclaration(id, superClass, classBody));
              };
              Parser2.prototype.parseClassExpression = function() {
                var node = this.createNode();
                var previousStrict = this.context.strict;
                this.context.strict = true;
                this.expectKeyword("class");
                var id = this.lookahead.type === 3 ? this.parseVariableIdentifier() : null;
                var superClass = null;
                if (this.matchKeyword("extends")) {
                  this.nextToken();
                  superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
                }
                var classBody = this.parseClassBody();
                this.context.strict = previousStrict;
                return this.finalize(node, new Node.ClassExpression(id, superClass, classBody));
              };
              Parser2.prototype.parseModule = function() {
                this.context.strict = true;
                this.context.isModule = true;
                this.scanner.isModule = true;
                var node = this.createNode();
                var body = this.parseDirectivePrologues();
                while (this.lookahead.type !== 2) {
                  body.push(this.parseStatementListItem());
                }
                return this.finalize(node, new Node.Module(body));
              };
              Parser2.prototype.parseScript = function() {
                var node = this.createNode();
                var body = this.parseDirectivePrologues();
                while (this.lookahead.type !== 2) {
                  body.push(this.parseStatementListItem());
                }
                return this.finalize(node, new Node.Script(body));
              };
              Parser2.prototype.parseModuleSpecifier = function() {
                var node = this.createNode();
                if (this.lookahead.type !== 8) {
                  this.throwError(messages_1.Messages.InvalidModuleSpecifier);
                }
                var token = this.nextToken();
                var raw = this.getTokenRaw(token);
                return this.finalize(node, new Node.Literal(token.value, raw));
              };
              Parser2.prototype.parseImportSpecifier = function() {
                var node = this.createNode();
                var imported;
                var local;
                if (this.lookahead.type === 3) {
                  imported = this.parseVariableIdentifier();
                  local = imported;
                  if (this.matchContextualKeyword("as")) {
                    this.nextToken();
                    local = this.parseVariableIdentifier();
                  }
                } else {
                  imported = this.parseIdentifierName();
                  local = imported;
                  if (this.matchContextualKeyword("as")) {
                    this.nextToken();
                    local = this.parseVariableIdentifier();
                  } else {
                    this.throwUnexpectedToken(this.nextToken());
                  }
                }
                return this.finalize(node, new Node.ImportSpecifier(local, imported));
              };
              Parser2.prototype.parseNamedImports = function() {
                this.expect("{");
                var specifiers = [];
                while (!this.match("}")) {
                  specifiers.push(this.parseImportSpecifier());
                  if (!this.match("}")) {
                    this.expect(",");
                  }
                }
                this.expect("}");
                return specifiers;
              };
              Parser2.prototype.parseImportDefaultSpecifier = function() {
                var node = this.createNode();
                var local = this.parseIdentifierName();
                return this.finalize(node, new Node.ImportDefaultSpecifier(local));
              };
              Parser2.prototype.parseImportNamespaceSpecifier = function() {
                var node = this.createNode();
                this.expect("*");
                if (!this.matchContextualKeyword("as")) {
                  this.throwError(messages_1.Messages.NoAsAfterImportNamespace);
                }
                this.nextToken();
                var local = this.parseIdentifierName();
                return this.finalize(node, new Node.ImportNamespaceSpecifier(local));
              };
              Parser2.prototype.parseImportDeclaration = function() {
                if (this.context.inFunctionBody) {
                  this.throwError(messages_1.Messages.IllegalImportDeclaration);
                }
                var node = this.createNode();
                this.expectKeyword("import");
                var src;
                var specifiers = [];
                if (this.lookahead.type === 8) {
                  src = this.parseModuleSpecifier();
                } else {
                  if (this.match("{")) {
                    specifiers = specifiers.concat(this.parseNamedImports());
                  } else if (this.match("*")) {
                    specifiers.push(this.parseImportNamespaceSpecifier());
                  } else if (this.isIdentifierName(this.lookahead) && !this.matchKeyword("default")) {
                    specifiers.push(this.parseImportDefaultSpecifier());
                    if (this.match(",")) {
                      this.nextToken();
                      if (this.match("*")) {
                        specifiers.push(this.parseImportNamespaceSpecifier());
                      } else if (this.match("{")) {
                        specifiers = specifiers.concat(this.parseNamedImports());
                      } else {
                        this.throwUnexpectedToken(this.lookahead);
                      }
                    }
                  } else {
                    this.throwUnexpectedToken(this.nextToken());
                  }
                  if (!this.matchContextualKeyword("from")) {
                    var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
                    this.throwError(message, this.lookahead.value);
                  }
                  this.nextToken();
                  src = this.parseModuleSpecifier();
                }
                this.consumeSemicolon();
                return this.finalize(node, new Node.ImportDeclaration(specifiers, src));
              };
              Parser2.prototype.parseExportSpecifier = function() {
                var node = this.createNode();
                var local = this.parseIdentifierName();
                var exported = local;
                if (this.matchContextualKeyword("as")) {
                  this.nextToken();
                  exported = this.parseIdentifierName();
                }
                return this.finalize(node, new Node.ExportSpecifier(local, exported));
              };
              Parser2.prototype.parseExportDeclaration = function() {
                if (this.context.inFunctionBody) {
                  this.throwError(messages_1.Messages.IllegalExportDeclaration);
                }
                var node = this.createNode();
                this.expectKeyword("export");
                var exportDeclaration;
                if (this.matchKeyword("default")) {
                  this.nextToken();
                  if (this.matchKeyword("function")) {
                    var declaration = this.parseFunctionDeclaration(true);
                    exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration));
                  } else if (this.matchKeyword("class")) {
                    var declaration = this.parseClassDeclaration(true);
                    exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration));
                  } else if (this.matchContextualKeyword("async")) {
                    var declaration = this.matchAsyncFunction() ? this.parseFunctionDeclaration(true) : this.parseAssignmentExpression();
                    exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration));
                  } else {
                    if (this.matchContextualKeyword("from")) {
                      this.throwError(messages_1.Messages.UnexpectedToken, this.lookahead.value);
                    }
                    var declaration = this.match("{") ? this.parseObjectInitializer() : this.match("[") ? this.parseArrayInitializer() : this.parseAssignmentExpression();
                    this.consumeSemicolon();
                    exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration));
                  }
                } else if (this.match("*")) {
                  this.nextToken();
                  if (!this.matchContextualKeyword("from")) {
                    var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
                    this.throwError(message, this.lookahead.value);
                  }
                  this.nextToken();
                  var src = this.parseModuleSpecifier();
                  this.consumeSemicolon();
                  exportDeclaration = this.finalize(node, new Node.ExportAllDeclaration(src));
                } else if (this.lookahead.type === 4) {
                  var declaration = void 0;
                  switch (this.lookahead.value) {
                    case "let":
                    case "const":
                      declaration = this.parseLexicalDeclaration({ inFor: false });
                      break;
                    case "var":
                    case "class":
                    case "function":
                      declaration = this.parseStatementListItem();
                      break;
                    default:
                      this.throwUnexpectedToken(this.lookahead);
                  }
                  exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null));
                } else if (this.matchAsyncFunction()) {
                  var declaration = this.parseFunctionDeclaration();
                  exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null));
                } else {
                  var specifiers = [];
                  var source = null;
                  var isExportFromIdentifier = false;
                  this.expect("{");
                  while (!this.match("}")) {
                    isExportFromIdentifier = isExportFromIdentifier || this.matchKeyword("default");
                    specifiers.push(this.parseExportSpecifier());
                    if (!this.match("}")) {
                      this.expect(",");
                    }
                  }
                  this.expect("}");
                  if (this.matchContextualKeyword("from")) {
                    this.nextToken();
                    source = this.parseModuleSpecifier();
                    this.consumeSemicolon();
                  } else if (isExportFromIdentifier) {
                    var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
                    this.throwError(message, this.lookahead.value);
                  } else {
                    this.consumeSemicolon();
                  }
                  exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(null, specifiers, source));
                }
                return exportDeclaration;
              };
              return Parser2;
            })();
            exports3.Parser = Parser;
          },
          /* 9 */
          /***/
          function(module3, exports3) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            function assert24(condition, message) {
              if (!condition) {
                throw new Error("ASSERT: " + message);
              }
            }
            exports3.assert = assert24;
          },
          /* 10 */
          /***/
          function(module3, exports3) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            var ErrorHandler = (function() {
              function ErrorHandler2() {
                this.errors = [];
                this.tolerant = false;
              }
              ErrorHandler2.prototype.recordError = function(error101) {
                this.errors.push(error101);
              };
              ErrorHandler2.prototype.tolerate = function(error101) {
                if (this.tolerant) {
                  this.recordError(error101);
                } else {
                  throw error101;
                }
              };
              ErrorHandler2.prototype.constructError = function(msg, column) {
                var error101 = new Error(msg);
                try {
                  throw error101;
                } catch (base) {
                  if (Object.create && Object.defineProperty) {
                    error101 = Object.create(base);
                    Object.defineProperty(error101, "column", { value: column });
                  }
                }
                return error101;
              };
              ErrorHandler2.prototype.createError = function(index, line, col, description) {
                var msg = "Line " + line + ": " + description;
                var error101 = this.constructError(msg, col);
                error101.index = index;
                error101.lineNumber = line;
                error101.description = description;
                return error101;
              };
              ErrorHandler2.prototype.throwError = function(index, line, col, description) {
                throw this.createError(index, line, col, description);
              };
              ErrorHandler2.prototype.tolerateError = function(index, line, col, description) {
                var error101 = this.createError(index, line, col, description);
                if (this.tolerant) {
                  this.recordError(error101);
                } else {
                  throw error101;
                }
              };
              return ErrorHandler2;
            })();
            exports3.ErrorHandler = ErrorHandler;
          },
          /* 11 */
          /***/
          function(module3, exports3) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            exports3.Messages = {
              BadGetterArity: "Getter must not have any formal parameters",
              BadSetterArity: "Setter must have exactly one formal parameter",
              BadSetterRestParameter: "Setter function argument must not be a rest parameter",
              ConstructorIsAsync: "Class constructor may not be an async method",
              ConstructorSpecialMethod: "Class constructor may not be an accessor",
              DeclarationMissingInitializer: "Missing initializer in %0 declaration",
              DefaultRestParameter: "Unexpected token =",
              DuplicateBinding: "Duplicate binding %0",
              DuplicateConstructor: "A class may only have one constructor",
              DuplicateProtoProperty: "Duplicate __proto__ fields are not allowed in object literals",
              ForInOfLoopInitializer: "%0 loop variable declaration may not have an initializer",
              GeneratorInLegacyContext: "Generator declarations are not allowed in legacy contexts",
              IllegalBreak: "Illegal break statement",
              IllegalContinue: "Illegal continue statement",
              IllegalExportDeclaration: "Unexpected token",
              IllegalImportDeclaration: "Unexpected token",
              IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list",
              IllegalReturn: "Illegal return statement",
              InvalidEscapedReservedWord: "Keyword must not contain escaped characters",
              InvalidHexEscapeSequence: "Invalid hexadecimal escape sequence",
              InvalidLHSInAssignment: "Invalid left-hand side in assignment",
              InvalidLHSInForIn: "Invalid left-hand side in for-in",
              InvalidLHSInForLoop: "Invalid left-hand side in for-loop",
              InvalidModuleSpecifier: "Unexpected token",
              InvalidRegExp: "Invalid regular expression",
              LetInLexicalBinding: "let is disallowed as a lexically bound name",
              MissingFromClause: "Unexpected token",
              MultipleDefaultsInSwitch: "More than one default clause in switch statement",
              NewlineAfterThrow: "Illegal newline after throw",
              NoAsAfterImportNamespace: "Unexpected token",
              NoCatchOrFinally: "Missing catch or finally after try",
              ParameterAfterRestParameter: "Rest parameter must be last formal parameter",
              Redeclaration: "%0 '%1' has already been declared",
              StaticPrototype: "Classes may not have static property named prototype",
              StrictCatchVariable: "Catch variable may not be eval or arguments in strict mode",
              StrictDelete: "Delete of an unqualified identifier in strict mode.",
              StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block",
              StrictFunctionName: "Function name may not be eval or arguments in strict mode",
              StrictLHSAssignment: "Assignment to eval or arguments is not allowed in strict mode",
              StrictLHSPostfix: "Postfix increment/decrement may not have eval or arguments operand in strict mode",
              StrictLHSPrefix: "Prefix increment/decrement may not have eval or arguments operand in strict mode",
              StrictModeWith: "Strict mode code may not include a with statement",
              StrictOctalLiteral: "Octal literals are not allowed in strict mode.",
              StrictParamDupe: "Strict mode function may not have duplicate parameter names",
              StrictParamName: "Parameter name eval or arguments is not allowed in strict mode",
              StrictReservedWord: "Use of future reserved word in strict mode",
              StrictVarName: "Variable name may not be eval or arguments in strict mode",
              TemplateOctalLiteral: "Octal literals are not allowed in template strings.",
              UnexpectedEOS: "Unexpected end of input",
              UnexpectedIdentifier: "Unexpected identifier",
              UnexpectedNumber: "Unexpected number",
              UnexpectedReserved: "Unexpected reserved word",
              UnexpectedString: "Unexpected string",
              UnexpectedTemplate: "Unexpected quasi %0",
              UnexpectedToken: "Unexpected token %0",
              UnexpectedTokenIllegal: "Unexpected token ILLEGAL",
              UnknownLabel: "Undefined label '%0'",
              UnterminatedRegExp: "Invalid regular expression: missing /"
            };
          },
          /* 12 */
          /***/
          function(module3, exports3, __webpack_require__) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            var assert_1 = __webpack_require__(9);
            var character_1 = __webpack_require__(4);
            var messages_1 = __webpack_require__(11);
            function hexValue(ch) {
              return "0123456789abcdef".indexOf(ch.toLowerCase());
            }
            function octalValue(ch) {
              return "01234567".indexOf(ch);
            }
            var Scanner = (function() {
              function Scanner2(code, handler) {
                this.source = code;
                this.errorHandler = handler;
                this.trackComment = false;
                this.isModule = false;
                this.length = code.length;
                this.index = 0;
                this.lineNumber = code.length > 0 ? 1 : 0;
                this.lineStart = 0;
                this.curlyStack = [];
              }
              Scanner2.prototype.saveState = function() {
                return {
                  index: this.index,
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart
                };
              };
              Scanner2.prototype.restoreState = function(state) {
                this.index = state.index;
                this.lineNumber = state.lineNumber;
                this.lineStart = state.lineStart;
              };
              Scanner2.prototype.eof = function() {
                return this.index >= this.length;
              };
              Scanner2.prototype.throwUnexpectedToken = function(message) {
                if (message === void 0) {
                  message = messages_1.Messages.UnexpectedTokenIllegal;
                }
                return this.errorHandler.throwError(this.index, this.lineNumber, this.index - this.lineStart + 1, message);
              };
              Scanner2.prototype.tolerateUnexpectedToken = function(message) {
                if (message === void 0) {
                  message = messages_1.Messages.UnexpectedTokenIllegal;
                }
                this.errorHandler.tolerateError(this.index, this.lineNumber, this.index - this.lineStart + 1, message);
              };
              Scanner2.prototype.skipSingleLineComment = function(offset) {
                var comments = [];
                var start, loc;
                if (this.trackComment) {
                  comments = [];
                  start = this.index - offset;
                  loc = {
                    start: {
                      line: this.lineNumber,
                      column: this.index - this.lineStart - offset
                    },
                    end: {}
                  };
                }
                while (!this.eof()) {
                  var ch = this.source.charCodeAt(this.index);
                  ++this.index;
                  if (character_1.Character.isLineTerminator(ch)) {
                    if (this.trackComment) {
                      loc.end = {
                        line: this.lineNumber,
                        column: this.index - this.lineStart - 1
                      };
                      var entry = {
                        multiLine: false,
                        slice: [start + offset, this.index - 1],
                        range: [start, this.index - 1],
                        loc
                      };
                      comments.push(entry);
                    }
                    if (ch === 13 && this.source.charCodeAt(this.index) === 10) {
                      ++this.index;
                    }
                    ++this.lineNumber;
                    this.lineStart = this.index;
                    return comments;
                  }
                }
                if (this.trackComment) {
                  loc.end = {
                    line: this.lineNumber,
                    column: this.index - this.lineStart
                  };
                  var entry = {
                    multiLine: false,
                    slice: [start + offset, this.index],
                    range: [start, this.index],
                    loc
                  };
                  comments.push(entry);
                }
                return comments;
              };
              Scanner2.prototype.skipMultiLineComment = function() {
                var comments = [];
                var start, loc;
                if (this.trackComment) {
                  comments = [];
                  start = this.index - 2;
                  loc = {
                    start: {
                      line: this.lineNumber,
                      column: this.index - this.lineStart - 2
                    },
                    end: {}
                  };
                }
                while (!this.eof()) {
                  var ch = this.source.charCodeAt(this.index);
                  if (character_1.Character.isLineTerminator(ch)) {
                    if (ch === 13 && this.source.charCodeAt(this.index + 1) === 10) {
                      ++this.index;
                    }
                    ++this.lineNumber;
                    ++this.index;
                    this.lineStart = this.index;
                  } else if (ch === 42) {
                    if (this.source.charCodeAt(this.index + 1) === 47) {
                      this.index += 2;
                      if (this.trackComment) {
                        loc.end = {
                          line: this.lineNumber,
                          column: this.index - this.lineStart
                        };
                        var entry = {
                          multiLine: true,
                          slice: [start + 2, this.index - 2],
                          range: [start, this.index],
                          loc
                        };
                        comments.push(entry);
                      }
                      return comments;
                    }
                    ++this.index;
                  } else {
                    ++this.index;
                  }
                }
                if (this.trackComment) {
                  loc.end = {
                    line: this.lineNumber,
                    column: this.index - this.lineStart
                  };
                  var entry = {
                    multiLine: true,
                    slice: [start + 2, this.index],
                    range: [start, this.index],
                    loc
                  };
                  comments.push(entry);
                }
                this.tolerateUnexpectedToken();
                return comments;
              };
              Scanner2.prototype.scanComments = function() {
                var comments;
                if (this.trackComment) {
                  comments = [];
                }
                var start = this.index === 0;
                while (!this.eof()) {
                  var ch = this.source.charCodeAt(this.index);
                  if (character_1.Character.isWhiteSpace(ch)) {
                    ++this.index;
                  } else if (character_1.Character.isLineTerminator(ch)) {
                    ++this.index;
                    if (ch === 13 && this.source.charCodeAt(this.index) === 10) {
                      ++this.index;
                    }
                    ++this.lineNumber;
                    this.lineStart = this.index;
                    start = true;
                  } else if (ch === 47) {
                    ch = this.source.charCodeAt(this.index + 1);
                    if (ch === 47) {
                      this.index += 2;
                      var comment = this.skipSingleLineComment(2);
                      if (this.trackComment) {
                        comments = comments.concat(comment);
                      }
                      start = true;
                    } else if (ch === 42) {
                      this.index += 2;
                      var comment = this.skipMultiLineComment();
                      if (this.trackComment) {
                        comments = comments.concat(comment);
                      }
                    } else {
                      break;
                    }
                  } else if (start && ch === 45) {
                    if (this.source.charCodeAt(this.index + 1) === 45 && this.source.charCodeAt(this.index + 2) === 62) {
                      this.index += 3;
                      var comment = this.skipSingleLineComment(3);
                      if (this.trackComment) {
                        comments = comments.concat(comment);
                      }
                    } else {
                      break;
                    }
                  } else if (ch === 60 && !this.isModule) {
                    if (this.source.slice(this.index + 1, this.index + 4) === "!--") {
                      this.index += 4;
                      var comment = this.skipSingleLineComment(4);
                      if (this.trackComment) {
                        comments = comments.concat(comment);
                      }
                    } else {
                      break;
                    }
                  } else {
                    break;
                  }
                }
                return comments;
              };
              Scanner2.prototype.isFutureReservedWord = function(id) {
                switch (id) {
                  case "enum":
                  case "export":
                  case "import":
                  case "super":
                    return true;
                  default:
                    return false;
                }
              };
              Scanner2.prototype.isStrictModeReservedWord = function(id) {
                switch (id) {
                  case "implements":
                  case "interface":
                  case "package":
                  case "private":
                  case "protected":
                  case "public":
                  case "static":
                  case "yield":
                  case "let":
                    return true;
                  default:
                    return false;
                }
              };
              Scanner2.prototype.isRestrictedWord = function(id) {
                return id === "eval" || id === "arguments";
              };
              Scanner2.prototype.isKeyword = function(id) {
                switch (id.length) {
                  case 2:
                    return id === "if" || id === "in" || id === "do";
                  case 3:
                    return id === "var" || id === "for" || id === "new" || id === "try" || id === "let";
                  case 4:
                    return id === "this" || id === "else" || id === "case" || id === "void" || id === "with" || id === "enum";
                  case 5:
                    return id === "while" || id === "break" || id === "catch" || id === "throw" || id === "const" || id === "yield" || id === "class" || id === "super";
                  case 6:
                    return id === "return" || id === "typeof" || id === "delete" || id === "switch" || id === "export" || id === "import";
                  case 7:
                    return id === "default" || id === "finally" || id === "extends";
                  case 8:
                    return id === "function" || id === "continue" || id === "debugger";
                  case 10:
                    return id === "instanceof";
                  default:
                    return false;
                }
              };
              Scanner2.prototype.codePointAt = function(i) {
                var cp = this.source.charCodeAt(i);
                if (cp >= 55296 && cp <= 56319) {
                  var second = this.source.charCodeAt(i + 1);
                  if (second >= 56320 && second <= 57343) {
                    var first = cp;
                    cp = (first - 55296) * 1024 + second - 56320 + 65536;
                  }
                }
                return cp;
              };
              Scanner2.prototype.scanHexEscape = function(prefix) {
                var len = prefix === "u" ? 4 : 2;
                var code = 0;
                for (var i = 0; i < len; ++i) {
                  if (!this.eof() && character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) {
                    code = code * 16 + hexValue(this.source[this.index++]);
                  } else {
                    return null;
                  }
                }
                return String.fromCharCode(code);
              };
              Scanner2.prototype.scanUnicodeCodePointEscape = function() {
                var ch = this.source[this.index];
                var code = 0;
                if (ch === "}") {
                  this.throwUnexpectedToken();
                }
                while (!this.eof()) {
                  ch = this.source[this.index++];
                  if (!character_1.Character.isHexDigit(ch.charCodeAt(0))) {
                    break;
                  }
                  code = code * 16 + hexValue(ch);
                }
                if (code > 1114111 || ch !== "}") {
                  this.throwUnexpectedToken();
                }
                return character_1.Character.fromCodePoint(code);
              };
              Scanner2.prototype.getIdentifier = function() {
                var start = this.index++;
                while (!this.eof()) {
                  var ch = this.source.charCodeAt(this.index);
                  if (ch === 92) {
                    this.index = start;
                    return this.getComplexIdentifier();
                  } else if (ch >= 55296 && ch < 57343) {
                    this.index = start;
                    return this.getComplexIdentifier();
                  }
                  if (character_1.Character.isIdentifierPart(ch)) {
                    ++this.index;
                  } else {
                    break;
                  }
                }
                return this.source.slice(start, this.index);
              };
              Scanner2.prototype.getComplexIdentifier = function() {
                var cp = this.codePointAt(this.index);
                var id = character_1.Character.fromCodePoint(cp);
                this.index += id.length;
                var ch;
                if (cp === 92) {
                  if (this.source.charCodeAt(this.index) !== 117) {
                    this.throwUnexpectedToken();
                  }
                  ++this.index;
                  if (this.source[this.index] === "{") {
                    ++this.index;
                    ch = this.scanUnicodeCodePointEscape();
                  } else {
                    ch = this.scanHexEscape("u");
                    if (ch === null || ch === "\\" || !character_1.Character.isIdentifierStart(ch.charCodeAt(0))) {
                      this.throwUnexpectedToken();
                    }
                  }
                  id = ch;
                }
                while (!this.eof()) {
                  cp = this.codePointAt(this.index);
                  if (!character_1.Character.isIdentifierPart(cp)) {
                    break;
                  }
                  ch = character_1.Character.fromCodePoint(cp);
                  id += ch;
                  this.index += ch.length;
                  if (cp === 92) {
                    id = id.substr(0, id.length - 1);
                    if (this.source.charCodeAt(this.index) !== 117) {
                      this.throwUnexpectedToken();
                    }
                    ++this.index;
                    if (this.source[this.index] === "{") {
                      ++this.index;
                      ch = this.scanUnicodeCodePointEscape();
                    } else {
                      ch = this.scanHexEscape("u");
                      if (ch === null || ch === "\\" || !character_1.Character.isIdentifierPart(ch.charCodeAt(0))) {
                        this.throwUnexpectedToken();
                      }
                    }
                    id += ch;
                  }
                }
                return id;
              };
              Scanner2.prototype.octalToDecimal = function(ch) {
                var octal = ch !== "0";
                var code = octalValue(ch);
                if (!this.eof() && character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
                  octal = true;
                  code = code * 8 + octalValue(this.source[this.index++]);
                  if ("0123".indexOf(ch) >= 0 && !this.eof() && character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
                    code = code * 8 + octalValue(this.source[this.index++]);
                  }
                }
                return {
                  code,
                  octal
                };
              };
              Scanner2.prototype.scanIdentifier = function() {
                var type;
                var start = this.index;
                var id = this.source.charCodeAt(start) === 92 ? this.getComplexIdentifier() : this.getIdentifier();
                if (id.length === 1) {
                  type = 3;
                } else if (this.isKeyword(id)) {
                  type = 4;
                } else if (id === "null") {
                  type = 5;
                } else if (id === "true" || id === "false") {
                  type = 1;
                } else {
                  type = 3;
                }
                if (type !== 3 && start + id.length !== this.index) {
                  var restore = this.index;
                  this.index = start;
                  this.tolerateUnexpectedToken(messages_1.Messages.InvalidEscapedReservedWord);
                  this.index = restore;
                }
                return {
                  type,
                  value: id,
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.scanPunctuator = function() {
                var start = this.index;
                var str = this.source[this.index];
                switch (str) {
                  case "(":
                  case "{":
                    if (str === "{") {
                      this.curlyStack.push("{");
                    }
                    ++this.index;
                    break;
                  case ".":
                    ++this.index;
                    if (this.source[this.index] === "." && this.source[this.index + 1] === ".") {
                      this.index += 2;
                      str = "...";
                    }
                    break;
                  case "}":
                    ++this.index;
                    this.curlyStack.pop();
                    break;
                  case ")":
                  case ";":
                  case ",":
                  case "[":
                  case "]":
                  case ":":
                  case "?":
                  case "~":
                    ++this.index;
                    break;
                  default:
                    str = this.source.substr(this.index, 4);
                    if (str === ">>>=") {
                      this.index += 4;
                    } else {
                      str = str.substr(0, 3);
                      if (str === "===" || str === "!==" || str === ">>>" || str === "<<=" || str === ">>=" || str === "**=") {
                        this.index += 3;
                      } else {
                        str = str.substr(0, 2);
                        if (str === "&&" || str === "||" || str === "==" || str === "!=" || str === "+=" || str === "-=" || str === "*=" || str === "/=" || str === "++" || str === "--" || str === "<<" || str === ">>" || str === "&=" || str === "|=" || str === "^=" || str === "%=" || str === "<=" || str === ">=" || str === "=>" || str === "**") {
                          this.index += 2;
                        } else {
                          str = this.source[this.index];
                          if ("<>=!+-*%&|^/".indexOf(str) >= 0) {
                            ++this.index;
                          }
                        }
                      }
                    }
                }
                if (this.index === start) {
                  this.throwUnexpectedToken();
                }
                return {
                  type: 7,
                  value: str,
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.scanHexLiteral = function(start) {
                var num = "";
                while (!this.eof()) {
                  if (!character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) {
                    break;
                  }
                  num += this.source[this.index++];
                }
                if (num.length === 0) {
                  this.throwUnexpectedToken();
                }
                if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) {
                  this.throwUnexpectedToken();
                }
                return {
                  type: 6,
                  value: parseInt("0x" + num, 16),
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.scanBinaryLiteral = function(start) {
                var num = "";
                var ch;
                while (!this.eof()) {
                  ch = this.source[this.index];
                  if (ch !== "0" && ch !== "1") {
                    break;
                  }
                  num += this.source[this.index++];
                }
                if (num.length === 0) {
                  this.throwUnexpectedToken();
                }
                if (!this.eof()) {
                  ch = this.source.charCodeAt(this.index);
                  if (character_1.Character.isIdentifierStart(ch) || character_1.Character.isDecimalDigit(ch)) {
                    this.throwUnexpectedToken();
                  }
                }
                return {
                  type: 6,
                  value: parseInt(num, 2),
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.scanOctalLiteral = function(prefix, start) {
                var num = "";
                var octal = false;
                if (character_1.Character.isOctalDigit(prefix.charCodeAt(0))) {
                  octal = true;
                  num = "0" + this.source[this.index++];
                } else {
                  ++this.index;
                }
                while (!this.eof()) {
                  if (!character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
                    break;
                  }
                  num += this.source[this.index++];
                }
                if (!octal && num.length === 0) {
                  this.throwUnexpectedToken();
                }
                if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index)) || character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
                  this.throwUnexpectedToken();
                }
                return {
                  type: 6,
                  value: parseInt(num, 8),
                  octal,
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.isImplicitOctalLiteral = function() {
                for (var i = this.index + 1; i < this.length; ++i) {
                  var ch = this.source[i];
                  if (ch === "8" || ch === "9") {
                    return false;
                  }
                  if (!character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
                    return true;
                  }
                }
                return true;
              };
              Scanner2.prototype.scanNumericLiteral = function() {
                var start = this.index;
                var ch = this.source[start];
                assert_1.assert(character_1.Character.isDecimalDigit(ch.charCodeAt(0)) || ch === ".", "Numeric literal must start with a decimal digit or a decimal point");
                var num = "";
                if (ch !== ".") {
                  num = this.source[this.index++];
                  ch = this.source[this.index];
                  if (num === "0") {
                    if (ch === "x" || ch === "X") {
                      ++this.index;
                      return this.scanHexLiteral(start);
                    }
                    if (ch === "b" || ch === "B") {
                      ++this.index;
                      return this.scanBinaryLiteral(start);
                    }
                    if (ch === "o" || ch === "O") {
                      return this.scanOctalLiteral(ch, start);
                    }
                    if (ch && character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
                      if (this.isImplicitOctalLiteral()) {
                        return this.scanOctalLiteral(ch, start);
                      }
                    }
                  }
                  while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
                    num += this.source[this.index++];
                  }
                  ch = this.source[this.index];
                }
                if (ch === ".") {
                  num += this.source[this.index++];
                  while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
                    num += this.source[this.index++];
                  }
                  ch = this.source[this.index];
                }
                if (ch === "e" || ch === "E") {
                  num += this.source[this.index++];
                  ch = this.source[this.index];
                  if (ch === "+" || ch === "-") {
                    num += this.source[this.index++];
                  }
                  if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
                    while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
                      num += this.source[this.index++];
                    }
                  } else {
                    this.throwUnexpectedToken();
                  }
                }
                if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) {
                  this.throwUnexpectedToken();
                }
                return {
                  type: 6,
                  value: parseFloat(num),
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.scanStringLiteral = function() {
                var start = this.index;
                var quote = this.source[start];
                assert_1.assert(quote === "'" || quote === '"', "String literal must starts with a quote");
                ++this.index;
                var octal = false;
                var str = "";
                while (!this.eof()) {
                  var ch = this.source[this.index++];
                  if (ch === quote) {
                    quote = "";
                    break;
                  } else if (ch === "\\") {
                    ch = this.source[this.index++];
                    if (!ch || !character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
                      switch (ch) {
                        case "u":
                          if (this.source[this.index] === "{") {
                            ++this.index;
                            str += this.scanUnicodeCodePointEscape();
                          } else {
                            var unescaped_1 = this.scanHexEscape(ch);
                            if (unescaped_1 === null) {
                              this.throwUnexpectedToken();
                            }
                            str += unescaped_1;
                          }
                          break;
                        case "x":
                          var unescaped = this.scanHexEscape(ch);
                          if (unescaped === null) {
                            this.throwUnexpectedToken(messages_1.Messages.InvalidHexEscapeSequence);
                          }
                          str += unescaped;
                          break;
                        case "n":
                          str += "\n";
                          break;
                        case "r":
                          str += "\r";
                          break;
                        case "t":
                          str += "	";
                          break;
                        case "b":
                          str += "\b";
                          break;
                        case "f":
                          str += "\f";
                          break;
                        case "v":
                          str += "\v";
                          break;
                        case "8":
                        case "9":
                          str += ch;
                          this.tolerateUnexpectedToken();
                          break;
                        default:
                          if (ch && character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
                            var octToDec = this.octalToDecimal(ch);
                            octal = octToDec.octal || octal;
                            str += String.fromCharCode(octToDec.code);
                          } else {
                            str += ch;
                          }
                          break;
                      }
                    } else {
                      ++this.lineNumber;
                      if (ch === "\r" && this.source[this.index] === "\n") {
                        ++this.index;
                      }
                      this.lineStart = this.index;
                    }
                  } else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
                    break;
                  } else {
                    str += ch;
                  }
                }
                if (quote !== "") {
                  this.index = start;
                  this.throwUnexpectedToken();
                }
                return {
                  type: 8,
                  value: str,
                  octal,
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.scanTemplate = function() {
                var cooked = "";
                var terminated = false;
                var start = this.index;
                var head = this.source[start] === "`";
                var tail = false;
                var rawOffset = 2;
                ++this.index;
                while (!this.eof()) {
                  var ch = this.source[this.index++];
                  if (ch === "`") {
                    rawOffset = 1;
                    tail = true;
                    terminated = true;
                    break;
                  } else if (ch === "$") {
                    if (this.source[this.index] === "{") {
                      this.curlyStack.push("${");
                      ++this.index;
                      terminated = true;
                      break;
                    }
                    cooked += ch;
                  } else if (ch === "\\") {
                    ch = this.source[this.index++];
                    if (!character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
                      switch (ch) {
                        case "n":
                          cooked += "\n";
                          break;
                        case "r":
                          cooked += "\r";
                          break;
                        case "t":
                          cooked += "	";
                          break;
                        case "u":
                          if (this.source[this.index] === "{") {
                            ++this.index;
                            cooked += this.scanUnicodeCodePointEscape();
                          } else {
                            var restore = this.index;
                            var unescaped_2 = this.scanHexEscape(ch);
                            if (unescaped_2 !== null) {
                              cooked += unescaped_2;
                            } else {
                              this.index = restore;
                              cooked += ch;
                            }
                          }
                          break;
                        case "x":
                          var unescaped = this.scanHexEscape(ch);
                          if (unescaped === null) {
                            this.throwUnexpectedToken(messages_1.Messages.InvalidHexEscapeSequence);
                          }
                          cooked += unescaped;
                          break;
                        case "b":
                          cooked += "\b";
                          break;
                        case "f":
                          cooked += "\f";
                          break;
                        case "v":
                          cooked += "\v";
                          break;
                        default:
                          if (ch === "0") {
                            if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
                              this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral);
                            }
                            cooked += "\0";
                          } else if (character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
                            this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral);
                          } else {
                            cooked += ch;
                          }
                          break;
                      }
                    } else {
                      ++this.lineNumber;
                      if (ch === "\r" && this.source[this.index] === "\n") {
                        ++this.index;
                      }
                      this.lineStart = this.index;
                    }
                  } else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
                    ++this.lineNumber;
                    if (ch === "\r" && this.source[this.index] === "\n") {
                      ++this.index;
                    }
                    this.lineStart = this.index;
                    cooked += "\n";
                  } else {
                    cooked += ch;
                  }
                }
                if (!terminated) {
                  this.throwUnexpectedToken();
                }
                if (!head) {
                  this.curlyStack.pop();
                }
                return {
                  type: 10,
                  value: this.source.slice(start + 1, this.index - rawOffset),
                  cooked,
                  head,
                  tail,
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.testRegExp = function(pattern, flags) {
                var astralSubstitute = "\uFFFF";
                var tmp = pattern;
                var self2 = this;
                if (flags.indexOf("u") >= 0) {
                  tmp = tmp.replace(/\\u\{([0-9a-fA-F]+)\}|\\u([a-fA-F0-9]{4})/g, function($0, $1, $22) {
                    var codePoint = parseInt($1 || $22, 16);
                    if (codePoint > 1114111) {
                      self2.throwUnexpectedToken(messages_1.Messages.InvalidRegExp);
                    }
                    if (codePoint <= 65535) {
                      return String.fromCharCode(codePoint);
                    }
                    return astralSubstitute;
                  }).replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, astralSubstitute);
                }
                try {
                  RegExp(tmp);
                } catch (e) {
                  this.throwUnexpectedToken(messages_1.Messages.InvalidRegExp);
                }
                try {
                  return new RegExp(pattern, flags);
                } catch (exception) {
                  return null;
                }
              };
              Scanner2.prototype.scanRegExpBody = function() {
                var ch = this.source[this.index];
                assert_1.assert(ch === "/", "Regular expression literal must start with a slash");
                var str = this.source[this.index++];
                var classMarker = false;
                var terminated = false;
                while (!this.eof()) {
                  ch = this.source[this.index++];
                  str += ch;
                  if (ch === "\\") {
                    ch = this.source[this.index++];
                    if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
                      this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
                    }
                    str += ch;
                  } else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
                    this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
                  } else if (classMarker) {
                    if (ch === "]") {
                      classMarker = false;
                    }
                  } else {
                    if (ch === "/") {
                      terminated = true;
                      break;
                    } else if (ch === "[") {
                      classMarker = true;
                    }
                  }
                }
                if (!terminated) {
                  this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
                }
                return str.substr(1, str.length - 2);
              };
              Scanner2.prototype.scanRegExpFlags = function() {
                var str = "";
                var flags = "";
                while (!this.eof()) {
                  var ch = this.source[this.index];
                  if (!character_1.Character.isIdentifierPart(ch.charCodeAt(0))) {
                    break;
                  }
                  ++this.index;
                  if (ch === "\\" && !this.eof()) {
                    ch = this.source[this.index];
                    if (ch === "u") {
                      ++this.index;
                      var restore = this.index;
                      var char = this.scanHexEscape("u");
                      if (char !== null) {
                        flags += char;
                        for (str += "\\u"; restore < this.index; ++restore) {
                          str += this.source[restore];
                        }
                      } else {
                        this.index = restore;
                        flags += "u";
                        str += "\\u";
                      }
                      this.tolerateUnexpectedToken();
                    } else {
                      str += "\\";
                      this.tolerateUnexpectedToken();
                    }
                  } else {
                    flags += ch;
                    str += ch;
                  }
                }
                return flags;
              };
              Scanner2.prototype.scanRegExp = function() {
                var start = this.index;
                var pattern = this.scanRegExpBody();
                var flags = this.scanRegExpFlags();
                var value = this.testRegExp(pattern, flags);
                return {
                  type: 9,
                  value: "",
                  pattern,
                  flags,
                  regex: value,
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.lex = function() {
                if (this.eof()) {
                  return {
                    type: 2,
                    value: "",
                    lineNumber: this.lineNumber,
                    lineStart: this.lineStart,
                    start: this.index,
                    end: this.index
                  };
                }
                var cp = this.source.charCodeAt(this.index);
                if (character_1.Character.isIdentifierStart(cp)) {
                  return this.scanIdentifier();
                }
                if (cp === 40 || cp === 41 || cp === 59) {
                  return this.scanPunctuator();
                }
                if (cp === 39 || cp === 34) {
                  return this.scanStringLiteral();
                }
                if (cp === 46) {
                  if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index + 1))) {
                    return this.scanNumericLiteral();
                  }
                  return this.scanPunctuator();
                }
                if (character_1.Character.isDecimalDigit(cp)) {
                  return this.scanNumericLiteral();
                }
                if (cp === 96 || cp === 125 && this.curlyStack[this.curlyStack.length - 1] === "${") {
                  return this.scanTemplate();
                }
                if (cp >= 55296 && cp < 57343) {
                  if (character_1.Character.isIdentifierStart(this.codePointAt(this.index))) {
                    return this.scanIdentifier();
                  }
                }
                return this.scanPunctuator();
              };
              return Scanner2;
            })();
            exports3.Scanner = Scanner;
          },
          /* 13 */
          /***/
          function(module3, exports3) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            exports3.TokenName = {};
            exports3.TokenName[
              1
              /* BooleanLiteral */
            ] = "Boolean";
            exports3.TokenName[
              2
              /* EOF */
            ] = "<end>";
            exports3.TokenName[
              3
              /* Identifier */
            ] = "Identifier";
            exports3.TokenName[
              4
              /* Keyword */
            ] = "Keyword";
            exports3.TokenName[
              5
              /* NullLiteral */
            ] = "Null";
            exports3.TokenName[
              6
              /* NumericLiteral */
            ] = "Numeric";
            exports3.TokenName[
              7
              /* Punctuator */
            ] = "Punctuator";
            exports3.TokenName[
              8
              /* StringLiteral */
            ] = "String";
            exports3.TokenName[
              9
              /* RegularExpression */
            ] = "RegularExpression";
            exports3.TokenName[
              10
              /* Template */
            ] = "Template";
          },
          /* 14 */
          /***/
          function(module3, exports3) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            exports3.XHTMLEntities = {
              quot: '"',
              amp: "&",
              apos: "'",
              gt: ">",
              nbsp: "\xA0",
              iexcl: "\xA1",
              cent: "\xA2",
              pound: "\xA3",
              curren: "\xA4",
              yen: "\xA5",
              brvbar: "\xA6",
              sect: "\xA7",
              uml: "\xA8",
              copy: "\xA9",
              ordf: "\xAA",
              laquo: "\xAB",
              not: "\xAC",
              shy: "\xAD",
              reg: "\xAE",
              macr: "\xAF",
              deg: "\xB0",
              plusmn: "\xB1",
              sup2: "\xB2",
              sup3: "\xB3",
              acute: "\xB4",
              micro: "\xB5",
              para: "\xB6",
              middot: "\xB7",
              cedil: "\xB8",
              sup1: "\xB9",
              ordm: "\xBA",
              raquo: "\xBB",
              frac14: "\xBC",
              frac12: "\xBD",
              frac34: "\xBE",
              iquest: "\xBF",
              Agrave: "\xC0",
              Aacute: "\xC1",
              Acirc: "\xC2",
              Atilde: "\xC3",
              Auml: "\xC4",
              Aring: "\xC5",
              AElig: "\xC6",
              Ccedil: "\xC7",
              Egrave: "\xC8",
              Eacute: "\xC9",
              Ecirc: "\xCA",
              Euml: "\xCB",
              Igrave: "\xCC",
              Iacute: "\xCD",
              Icirc: "\xCE",
              Iuml: "\xCF",
              ETH: "\xD0",
              Ntilde: "\xD1",
              Ograve: "\xD2",
              Oacute: "\xD3",
              Ocirc: "\xD4",
              Otilde: "\xD5",
              Ouml: "\xD6",
              times: "\xD7",
              Oslash: "\xD8",
              Ugrave: "\xD9",
              Uacute: "\xDA",
              Ucirc: "\xDB",
              Uuml: "\xDC",
              Yacute: "\xDD",
              THORN: "\xDE",
              szlig: "\xDF",
              agrave: "\xE0",
              aacute: "\xE1",
              acirc: "\xE2",
              atilde: "\xE3",
              auml: "\xE4",
              aring: "\xE5",
              aelig: "\xE6",
              ccedil: "\xE7",
              egrave: "\xE8",
              eacute: "\xE9",
              ecirc: "\xEA",
              euml: "\xEB",
              igrave: "\xEC",
              iacute: "\xED",
              icirc: "\xEE",
              iuml: "\xEF",
              eth: "\xF0",
              ntilde: "\xF1",
              ograve: "\xF2",
              oacute: "\xF3",
              ocirc: "\xF4",
              otilde: "\xF5",
              ouml: "\xF6",
              divide: "\xF7",
              oslash: "\xF8",
              ugrave: "\xF9",
              uacute: "\xFA",
              ucirc: "\xFB",
              uuml: "\xFC",
              yacute: "\xFD",
              thorn: "\xFE",
              yuml: "\xFF",
              OElig: "\u0152",
              oelig: "\u0153",
              Scaron: "\u0160",
              scaron: "\u0161",
              Yuml: "\u0178",
              fnof: "\u0192",
              circ: "\u02C6",
              tilde: "\u02DC",
              Alpha: "\u0391",
              Beta: "\u0392",
              Gamma: "\u0393",
              Delta: "\u0394",
              Epsilon: "\u0395",
              Zeta: "\u0396",
              Eta: "\u0397",
              Theta: "\u0398",
              Iota: "\u0399",
              Kappa: "\u039A",
              Lambda: "\u039B",
              Mu: "\u039C",
              Nu: "\u039D",
              Xi: "\u039E",
              Omicron: "\u039F",
              Pi: "\u03A0",
              Rho: "\u03A1",
              Sigma: "\u03A3",
              Tau: "\u03A4",
              Upsilon: "\u03A5",
              Phi: "\u03A6",
              Chi: "\u03A7",
              Psi: "\u03A8",
              Omega: "\u03A9",
              alpha: "\u03B1",
              beta: "\u03B2",
              gamma: "\u03B3",
              delta: "\u03B4",
              epsilon: "\u03B5",
              zeta: "\u03B6",
              eta: "\u03B7",
              theta: "\u03B8",
              iota: "\u03B9",
              kappa: "\u03BA",
              lambda: "\u03BB",
              mu: "\u03BC",
              nu: "\u03BD",
              xi: "\u03BE",
              omicron: "\u03BF",
              pi: "\u03C0",
              rho: "\u03C1",
              sigmaf: "\u03C2",
              sigma: "\u03C3",
              tau: "\u03C4",
              upsilon: "\u03C5",
              phi: "\u03C6",
              chi: "\u03C7",
              psi: "\u03C8",
              omega: "\u03C9",
              thetasym: "\u03D1",
              upsih: "\u03D2",
              piv: "\u03D6",
              ensp: "\u2002",
              emsp: "\u2003",
              thinsp: "\u2009",
              zwnj: "\u200C",
              zwj: "\u200D",
              lrm: "\u200E",
              rlm: "\u200F",
              ndash: "\u2013",
              mdash: "\u2014",
              lsquo: "\u2018",
              rsquo: "\u2019",
              sbquo: "\u201A",
              ldquo: "\u201C",
              rdquo: "\u201D",
              bdquo: "\u201E",
              dagger: "\u2020",
              Dagger: "\u2021",
              bull: "\u2022",
              hellip: "\u2026",
              permil: "\u2030",
              prime: "\u2032",
              Prime: "\u2033",
              lsaquo: "\u2039",
              rsaquo: "\u203A",
              oline: "\u203E",
              frasl: "\u2044",
              euro: "\u20AC",
              image: "\u2111",
              weierp: "\u2118",
              real: "\u211C",
              trade: "\u2122",
              alefsym: "\u2135",
              larr: "\u2190",
              uarr: "\u2191",
              rarr: "\u2192",
              darr: "\u2193",
              harr: "\u2194",
              crarr: "\u21B5",
              lArr: "\u21D0",
              uArr: "\u21D1",
              rArr: "\u21D2",
              dArr: "\u21D3",
              hArr: "\u21D4",
              forall: "\u2200",
              part: "\u2202",
              exist: "\u2203",
              empty: "\u2205",
              nabla: "\u2207",
              isin: "\u2208",
              notin: "\u2209",
              ni: "\u220B",
              prod: "\u220F",
              sum: "\u2211",
              minus: "\u2212",
              lowast: "\u2217",
              radic: "\u221A",
              prop: "\u221D",
              infin: "\u221E",
              ang: "\u2220",
              and: "\u2227",
              or: "\u2228",
              cap: "\u2229",
              cup: "\u222A",
              int: "\u222B",
              there4: "\u2234",
              sim: "\u223C",
              cong: "\u2245",
              asymp: "\u2248",
              ne: "\u2260",
              equiv: "\u2261",
              le: "\u2264",
              ge: "\u2265",
              sub: "\u2282",
              sup: "\u2283",
              nsub: "\u2284",
              sube: "\u2286",
              supe: "\u2287",
              oplus: "\u2295",
              otimes: "\u2297",
              perp: "\u22A5",
              sdot: "\u22C5",
              lceil: "\u2308",
              rceil: "\u2309",
              lfloor: "\u230A",
              rfloor: "\u230B",
              loz: "\u25CA",
              spades: "\u2660",
              clubs: "\u2663",
              hearts: "\u2665",
              diams: "\u2666",
              lang: "\u27E8",
              rang: "\u27E9"
            };
          },
          /* 15 */
          /***/
          function(module3, exports3, __webpack_require__) {
            "use strict";
            Object.defineProperty(exports3, "__esModule", { value: true });
            var error_handler_1 = __webpack_require__(10);
            var scanner_1 = __webpack_require__(12);
            var token_1 = __webpack_require__(13);
            var Reader = (function() {
              function Reader2() {
                this.values = [];
                this.curly = this.paren = -1;
              }
              Reader2.prototype.beforeFunctionExpression = function(t) {
                return [
                  "(",
                  "{",
                  "[",
                  "in",
                  "typeof",
                  "instanceof",
                  "new",
                  "return",
                  "case",
                  "delete",
                  "throw",
                  "void",
                  // assignment operators
                  "=",
                  "+=",
                  "-=",
                  "*=",
                  "**=",
                  "/=",
                  "%=",
                  "<<=",
                  ">>=",
                  ">>>=",
                  "&=",
                  "|=",
                  "^=",
                  ",",
                  // binary/unary operators
                  "+",
                  "-",
                  "*",
                  "**",
                  "/",
                  "%",
                  "++",
                  "--",
                  "<<",
                  ">>",
                  ">>>",
                  "&",
                  "|",
                  "^",
                  "!",
                  "~",
                  "&&",
                  "||",
                  "?",
                  ":",
                  "===",
                  "==",
                  ">=",
                  "<=",
                  "<",
                  ">",
                  "!=",
                  "!=="
                ].indexOf(t) >= 0;
              };
              Reader2.prototype.isRegexStart = function() {
                var previous = this.values[this.values.length - 1];
                var regex3 = previous !== null;
                switch (previous) {
                  case "this":
                  case "]":
                    regex3 = false;
                    break;
                  case ")":
                    var keyword = this.values[this.paren - 1];
                    regex3 = keyword === "if" || keyword === "while" || keyword === "for" || keyword === "with";
                    break;
                  case "}":
                    regex3 = false;
                    if (this.values[this.curly - 3] === "function") {
                      var check3 = this.values[this.curly - 4];
                      regex3 = check3 ? !this.beforeFunctionExpression(check3) : false;
                    } else if (this.values[this.curly - 4] === "function") {
                      var check3 = this.values[this.curly - 5];
                      regex3 = check3 ? !this.beforeFunctionExpression(check3) : true;
                    }
                    break;
                  default:
                    break;
                }
                return regex3;
              };
              Reader2.prototype.push = function(token) {
                if (token.type === 7 || token.type === 4) {
                  if (token.value === "{") {
                    this.curly = this.values.length;
                  } else if (token.value === "(") {
                    this.paren = this.values.length;
                  }
                  this.values.push(token.value);
                } else {
                  this.values.push(null);
                }
              };
              return Reader2;
            })();
            var Tokenizer = (function() {
              function Tokenizer2(code, config3) {
                this.errorHandler = new error_handler_1.ErrorHandler();
                this.errorHandler.tolerant = config3 ? typeof config3.tolerant === "boolean" && config3.tolerant : false;
                this.scanner = new scanner_1.Scanner(code, this.errorHandler);
                this.scanner.trackComment = config3 ? typeof config3.comment === "boolean" && config3.comment : false;
                this.trackRange = config3 ? typeof config3.range === "boolean" && config3.range : false;
                this.trackLoc = config3 ? typeof config3.loc === "boolean" && config3.loc : false;
                this.buffer = [];
                this.reader = new Reader();
              }
              Tokenizer2.prototype.errors = function() {
                return this.errorHandler.errors;
              };
              Tokenizer2.prototype.getNextToken = function() {
                if (this.buffer.length === 0) {
                  var comments = this.scanner.scanComments();
                  if (this.scanner.trackComment) {
                    for (var i = 0; i < comments.length; ++i) {
                      var e = comments[i];
                      var value = this.scanner.source.slice(e.slice[0], e.slice[1]);
                      var comment = {
                        type: e.multiLine ? "BlockComment" : "LineComment",
                        value
                      };
                      if (this.trackRange) {
                        comment.range = e.range;
                      }
                      if (this.trackLoc) {
                        comment.loc = e.loc;
                      }
                      this.buffer.push(comment);
                    }
                  }
                  if (!this.scanner.eof()) {
                    var loc = void 0;
                    if (this.trackLoc) {
                      loc = {
                        start: {
                          line: this.scanner.lineNumber,
                          column: this.scanner.index - this.scanner.lineStart
                        },
                        end: {}
                      };
                    }
                    var startRegex = this.scanner.source[this.scanner.index] === "/" && this.reader.isRegexStart();
                    var token = startRegex ? this.scanner.scanRegExp() : this.scanner.lex();
                    this.reader.push(token);
                    var entry = {
                      type: token_1.TokenName[token.type],
                      value: this.scanner.source.slice(token.start, token.end)
                    };
                    if (this.trackRange) {
                      entry.range = [token.start, token.end];
                    }
                    if (this.trackLoc) {
                      loc.end = {
                        line: this.scanner.lineNumber,
                        column: this.scanner.index - this.scanner.lineStart
                      };
                      entry.loc = loc;
                    }
                    if (token.type === 9) {
                      var pattern = token.pattern;
                      var flags = token.flags;
                      entry.regex = { pattern, flags };
                    }
                    this.buffer.push(entry);
                  }
                }
                return this.buffer.shift();
              };
              return Tokenizer2;
            })();
            exports3.Tokenizer = Tokenizer;
          }
          /******/
        ])
      );
    });
  }
});

// ../../node_modules/.pnpm/tslib@2.8.1/node_modules/tslib/tslib.es6.mjs
var tslib_es6_exports = {};
__export(tslib_es6_exports, {
  __addDisposableResource: () => __addDisposableResource,
  __assign: () => __assign,
  __asyncDelegator: () => __asyncDelegator,
  __asyncGenerator: () => __asyncGenerator,
  __asyncValues: () => __asyncValues,
  __await: () => __await,
  __awaiter: () => __awaiter,
  __classPrivateFieldGet: () => __classPrivateFieldGet2,
  __classPrivateFieldIn: () => __classPrivateFieldIn,
  __classPrivateFieldSet: () => __classPrivateFieldSet,
  __createBinding: () => __createBinding,
  __decorate: () => __decorate,
  __disposeResources: () => __disposeResources,
  __esDecorate: () => __esDecorate,
  __exportStar: () => __exportStar,
  __extends: () => __extends,
  __generator: () => __generator,
  __importDefault: () => __importDefault,
  __importStar: () => __importStar,
  __makeTemplateObject: () => __makeTemplateObject,
  __metadata: () => __metadata,
  __param: () => __param,
  __propKey: () => __propKey,
  __read: () => __read,
  __rest: () => __rest,
  __rewriteRelativeImportExtension: () => __rewriteRelativeImportExtension,
  __runInitializers: () => __runInitializers,
  __setFunctionName: () => __setFunctionName,
  __spread: () => __spread,
  __spreadArray: () => __spreadArray,
  __spreadArrays: () => __spreadArrays,
  __values: () => __values,
  default: () => tslib_es6_default
});
function __extends(d, b) {
  if (typeof b !== "function" && b !== null)
    throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  extendStatics(d, b);
  function __() {
    this.constructor = d;
  }
  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
function __rest(s, e) {
  var t = {};
  for (var p2 in s) if (Object.prototype.hasOwnProperty.call(s, p2) && e.indexOf(p2) < 0)
    t[p2] = s[p2];
  if (s != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i = 0, p2 = Object.getOwnPropertySymbols(s); i < p2.length; i++) {
      if (e.indexOf(p2[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p2[i]))
        t[p2[i]] = s[p2[i]];
    }
  return t;
}
function __decorate(decorators, target, key, desc) {
  var c2 = arguments.length, r = c2 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c2 < 3 ? d(r) : c2 > 3 ? d(target, key, r) : d(target, key)) || r;
  return c2 > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
}
function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
  function accept(f) {
    if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
    return f;
  }
  var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
  var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
  var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
  var _, done = false;
  for (var i = decorators.length - 1; i >= 0; i--) {
    var context = {};
    for (var p2 in contextIn) context[p2] = p2 === "access" ? {} : contextIn[p2];
    for (var p2 in contextIn.access) context.access[p2] = contextIn.access[p2];
    context.addInitializer = function(f) {
      if (done) throw new TypeError("Cannot add initializers after decoration has completed");
      extraInitializers.push(accept(f || null));
    };
    var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
    if (kind === "accessor") {
      if (result === void 0) continue;
      if (result === null || typeof result !== "object") throw new TypeError("Object expected");
      if (_ = accept(result.get)) descriptor.get = _;
      if (_ = accept(result.set)) descriptor.set = _;
      if (_ = accept(result.init)) initializers.unshift(_);
    } else if (_ = accept(result)) {
      if (kind === "field") initializers.unshift(_);
      else descriptor[key] = _;
    }
  }
  if (target) Object.defineProperty(target, contextIn.name, descriptor);
  done = true;
}
function __runInitializers(thisArg, initializers, value) {
  var useValue = arguments.length > 2;
  for (var i = 0; i < initializers.length; i++) {
    value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
  }
  return useValue ? value : void 0;
}
function __propKey(x) {
  return typeof x === "symbol" ? x : "".concat(x);
}
function __setFunctionName(f, name, prefix) {
  if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
  return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
}
function __metadata(metadataKey, metadataValue) {
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
  function adopt2(value) {
    return value instanceof P ? value : new P(function(resolve8) {
      resolve8(value);
    });
  }
  return new (P || (P = Promise))(function(resolve8, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e) {
        reject(e);
      }
    }
    function step(result) {
      result.done ? resolve8(result.value) : adopt2(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}
function __generator(thisArg, body) {
  var _ = { label: 0, sent: function() {
    if (t[0] & 1) throw t[1];
    return t[1];
  }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
  return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
    return this;
  }), g;
  function verb(n) {
    return function(v) {
      return step([n, v]);
    };
  }
  function step(op) {
    if (f) throw new TypeError("Generator is already executing.");
    while (g && (g = 0, op[0] && (_ = 0)), _) try {
      if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
      if (y = 0, t) op = [op[0] & 2, t.value];
      switch (op[0]) {
        case 0:
        case 1:
          t = op;
          break;
        case 4:
          _.label++;
          return { value: op[1], done: false };
        case 5:
          _.label++;
          y = op[1];
          op = [0];
          continue;
        case 7:
          op = _.ops.pop();
          _.trys.pop();
          continue;
        default:
          if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
            _ = 0;
            continue;
          }
          if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
            _.label = op[1];
            break;
          }
          if (op[0] === 6 && _.label < t[1]) {
            _.label = t[1];
            t = op;
            break;
          }
          if (t && _.label < t[2]) {
            _.label = t[2];
            _.ops.push(op);
            break;
          }
          if (t[2]) _.ops.pop();
          _.trys.pop();
          continue;
      }
      op = body.call(thisArg, _);
    } catch (e) {
      op = [6, e];
      y = 0;
    } finally {
      f = t = 0;
    }
    if (op[0] & 5) throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
}
function __exportStar(m, o) {
  for (var p2 in m) if (p2 !== "default" && !Object.prototype.hasOwnProperty.call(o, p2)) __createBinding(o, m, p2);
}
function __values(o) {
  var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
  if (m) return m.call(o);
  if (o && typeof o.length === "number") return {
    next: function() {
      if (o && i >= o.length) o = void 0;
      return { value: o && o[i++], done: !o };
    }
  };
  throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
  var m = typeof Symbol === "function" && o[Symbol.iterator];
  if (!m) return o;
  var i = m.call(o), r, ar = [], e;
  try {
    while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
  } catch (error101) {
    e = { error: error101 };
  } finally {
    try {
      if (r && !r.done && (m = i["return"])) m.call(i);
    } finally {
      if (e) throw e.error;
    }
  }
  return ar;
}
function __spread() {
  for (var ar = [], i = 0; i < arguments.length; i++)
    ar = ar.concat(__read(arguments[i]));
  return ar;
}
function __spreadArrays() {
  for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
  for (var r = Array(s), k = 0, i = 0; i < il; i++)
    for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
      r[k] = a[j];
  return r;
}
function __spreadArray(to, from, pack2) {
  if (pack2 || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
    if (ar || !(i in from)) {
      if (!ar) ar = Array.prototype.slice.call(from, 0, i);
      ar[i] = from[i];
    }
  }
  return to.concat(ar || Array.prototype.slice.call(from));
}
function __await(v) {
  return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var g = generator.apply(thisArg, _arguments || []), i, q2 = [];
  return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() {
    return this;
  }, i;
  function awaitReturn(f) {
    return function(v) {
      return Promise.resolve(v).then(f, reject);
    };
  }
  function verb(n, f) {
    if (g[n]) {
      i[n] = function(v) {
        return new Promise(function(a, b) {
          q2.push([n, v, a, b]) > 1 || resume(n, v);
        });
      };
      if (f) i[n] = f(i[n]);
    }
  }
  function resume(n, v) {
    try {
      step(g[n](v));
    } catch (e) {
      settle(q2[0][3], e);
    }
  }
  function step(r) {
    r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q2[0][2], r);
  }
  function fulfill(value) {
    resume("next", value);
  }
  function reject(value) {
    resume("throw", value);
  }
  function settle(f, v) {
    if (f(v), q2.shift(), q2.length) resume(q2[0][0], q2[0][1]);
  }
}
function __asyncDelegator(o) {
  var i, p2;
  return i = {}, verb("next"), verb("throw", function(e) {
    throw e;
  }), verb("return"), i[Symbol.iterator] = function() {
    return this;
  }, i;
  function verb(n, f) {
    i[n] = o[n] ? function(v) {
      return (p2 = !p2) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v;
    } : f;
  }
}
function __asyncValues(o) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var m = o[Symbol.asyncIterator], i;
  return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
    return this;
  }, i);
  function verb(n) {
    i[n] = o[n] && function(v) {
      return new Promise(function(resolve8, reject) {
        v = o[n](v), settle(resolve8, reject, v.done, v.value);
      });
    };
  }
  function settle(resolve8, reject, d, v) {
    Promise.resolve(v).then(function(v2) {
      resolve8({ value: v2, done: d });
    }, reject);
  }
}
function __makeTemplateObject(cooked, raw) {
  if (Object.defineProperty) {
    Object.defineProperty(cooked, "raw", { value: raw });
  } else {
    cooked.raw = raw;
  }
  return cooked;
}
function __importStar(mod) {
  if (mod && mod.__esModule) return mod;
  var result = {};
  if (mod != null) {
    for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
  }
  __setModuleDefault(result, mod);
  return result;
}
function __importDefault(mod) {
  return mod && mod.__esModule ? mod : { default: mod };
}
function __classPrivateFieldGet2(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);
}
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;
}
function __classPrivateFieldIn(state, receiver) {
  if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object");
  return typeof state === "function" ? receiver === state : state.has(receiver);
}
function __addDisposableResource(env3, value, async) {
  if (value !== null && value !== void 0) {
    if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
    var dispose, inner;
    if (async) {
      if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
      dispose = value[Symbol.asyncDispose];
    }
    if (dispose === void 0) {
      if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
      dispose = value[Symbol.dispose];
      if (async) inner = dispose;
    }
    if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
    if (inner) dispose = function() {
      try {
        inner.call(this);
      } catch (e) {
        return Promise.reject(e);
      }
    };
    env3.stack.push({ value, dispose, async });
  } else if (async) {
    env3.stack.push({ async: true });
  }
  return value;
}
function __disposeResources(env3) {
  function fail(e) {
    env3.error = env3.hasError ? new _SuppressedError(e, env3.error, "An error was suppressed during disposal.") : e;
    env3.hasError = true;
  }
  var r, s = 0;
  function next() {
    while (r = env3.stack.pop()) {
      try {
        if (!r.async && s === 1) return s = 0, env3.stack.push(r), Promise.resolve().then(next);
        if (r.dispose) {
          var result = r.dispose.call(r.value);
          if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
            fail(e);
            return next();
          });
        } else s |= 1;
      } catch (e) {
        fail(e);
      }
    }
    if (s === 1) return env3.hasError ? Promise.reject(env3.error) : Promise.resolve();
    if (env3.hasError) throw env3.error;
  }
  return next();
}
function __rewriteRelativeImportExtension(path73, preserveJsx) {
  if (typeof path73 === "string" && /^\.\.?\//.test(path73)) {
    return path73.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m, tsx, d, ext, cm) {
      return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : d + ext + "." + cm.toLowerCase() + "js";
    });
  }
  return path73;
}
var extendStatics, __assign, __createBinding, __setModuleDefault, ownKeys, _SuppressedError, tslib_es6_default;
var init_tslib_es6 = __esm({
  "../../node_modules/.pnpm/tslib@2.8.1/node_modules/tslib/tslib.es6.mjs"() {
    "use strict";
    extendStatics = function(d, b) {
      extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
        d2.__proto__ = b2;
      } || function(d2, b2) {
        for (var p2 in b2) if (Object.prototype.hasOwnProperty.call(b2, p2)) d2[p2] = b2[p2];
      };
      return extendStatics(d, b);
    };
    __assign = function() {
      __assign = Object.assign || function __assign2(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
          s = arguments[i];
          for (var p2 in s) if (Object.prototype.hasOwnProperty.call(s, p2)) t[p2] = s[p2];
        }
        return t;
      };
      return __assign.apply(this, arguments);
    };
    __createBinding = Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    __setModuleDefault = Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    };
    ownKeys = function(o) {
      ownKeys = Object.getOwnPropertyNames || function(o2) {
        var ar = [];
        for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
        return ar;
      };
      return ownKeys(o);
    };
    _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error101, suppressed, message) {
      var e = new Error(message);
      return e.name = "SuppressedError", e.error = error101, e.suppressed = suppressed, e;
    };
    tslib_es6_default = {
      __extends,
      __assign,
      __rest,
      __decorate,
      __param,
      __esDecorate,
      __runInitializers,
      __propKey,
      __setFunctionName,
      __metadata,
      __awaiter,
      __generator,
      __createBinding,
      __exportStar,
      __values,
      __read,
      __spread,
      __spreadArrays,
      __spreadArray,
      __await,
      __asyncGenerator,
      __asyncDelegator,
      __asyncValues,
      __makeTemplateObject,
      __importStar,
      __importDefault,
      __classPrivateFieldGet: __classPrivateFieldGet2,
      __classPrivateFieldSet,
      __classPrivateFieldIn,
      __addDisposableResource,
      __disposeResources,
      __rewriteRelativeImportExtension
    };
  }
});

// ../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/lib/types.js
var require_types = __commonJS({
  "../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/lib/types.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Def = void 0;
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var Op = Object.prototype;
    var objToStr = Op.toString;
    var hasOwn = Op.hasOwnProperty;
    var BaseType = (
      /** @class */
      (function() {
        function BaseType2() {
        }
        BaseType2.prototype.assert = function(value, deep) {
          if (!this.check(value, deep)) {
            var str = shallowStringify(value);
            throw new Error(str + " does not match type " + this);
          }
          return true;
        };
        BaseType2.prototype.arrayOf = function() {
          var elemType = this;
          return new ArrayType(elemType);
        };
        return BaseType2;
      })()
    );
    var ArrayType = (
      /** @class */
      (function(_super) {
        tslib_1.__extends(ArrayType2, _super);
        function ArrayType2(elemType) {
          var _this = _super.call(this) || this;
          _this.elemType = elemType;
          _this.kind = "ArrayType";
          return _this;
        }
        ArrayType2.prototype.toString = function() {
          return "[" + this.elemType + "]";
        };
        ArrayType2.prototype.check = function(value, deep) {
          var _this = this;
          return Array.isArray(value) && value.every(function(elem) {
            return _this.elemType.check(elem, deep);
          });
        };
        return ArrayType2;
      })(BaseType)
    );
    var IdentityType = (
      /** @class */
      (function(_super) {
        tslib_1.__extends(IdentityType2, _super);
        function IdentityType2(value) {
          var _this = _super.call(this) || this;
          _this.value = value;
          _this.kind = "IdentityType";
          return _this;
        }
        IdentityType2.prototype.toString = function() {
          return String(this.value);
        };
        IdentityType2.prototype.check = function(value, deep) {
          var result = value === this.value;
          if (!result && typeof deep === "function") {
            deep(this, value);
          }
          return result;
        };
        return IdentityType2;
      })(BaseType)
    );
    var ObjectType = (
      /** @class */
      (function(_super) {
        tslib_1.__extends(ObjectType2, _super);
        function ObjectType2(fields) {
          var _this = _super.call(this) || this;
          _this.fields = fields;
          _this.kind = "ObjectType";
          return _this;
        }
        ObjectType2.prototype.toString = function() {
          return "{ " + this.fields.join(", ") + " }";
        };
        ObjectType2.prototype.check = function(value, deep) {
          return objToStr.call(value) === objToStr.call({}) && this.fields.every(function(field) {
            return field.type.check(value[field.name], deep);
          });
        };
        return ObjectType2;
      })(BaseType)
    );
    var OrType = (
      /** @class */
      (function(_super) {
        tslib_1.__extends(OrType2, _super);
        function OrType2(types3) {
          var _this = _super.call(this) || this;
          _this.types = types3;
          _this.kind = "OrType";
          return _this;
        }
        OrType2.prototype.toString = function() {
          return this.types.join(" | ");
        };
        OrType2.prototype.check = function(value, deep) {
          return this.types.some(function(type) {
            return type.check(value, deep);
          });
        };
        return OrType2;
      })(BaseType)
    );
    var PredicateType = (
      /** @class */
      (function(_super) {
        tslib_1.__extends(PredicateType2, _super);
        function PredicateType2(name, predicate) {
          var _this = _super.call(this) || this;
          _this.name = name;
          _this.predicate = predicate;
          _this.kind = "PredicateType";
          return _this;
        }
        PredicateType2.prototype.toString = function() {
          return this.name;
        };
        PredicateType2.prototype.check = function(value, deep) {
          var result = this.predicate(value, deep);
          if (!result && typeof deep === "function") {
            deep(this, value);
          }
          return result;
        };
        return PredicateType2;
      })(BaseType)
    );
    var Def = (
      /** @class */
      (function() {
        function Def2(type, typeName) {
          this.type = type;
          this.typeName = typeName;
          this.baseNames = [];
          this.ownFields = /* @__PURE__ */ Object.create(null);
          this.allSupertypes = /* @__PURE__ */ Object.create(null);
          this.supertypeList = [];
          this.allFields = /* @__PURE__ */ Object.create(null);
          this.fieldNames = [];
          this.finalized = false;
          this.buildable = false;
          this.buildParams = [];
        }
        Def2.prototype.isSupertypeOf = function(that) {
          if (that instanceof Def2) {
            if (this.finalized !== true || that.finalized !== true) {
              throw new Error("");
            }
            return hasOwn.call(that.allSupertypes, this.typeName);
          } else {
            throw new Error(that + " is not a Def");
          }
        };
        Def2.prototype.checkAllFields = function(value, deep) {
          var allFields = this.allFields;
          if (this.finalized !== true) {
            throw new Error("" + this.typeName);
          }
          function checkFieldByName(name) {
            var field = allFields[name];
            var type = field.type;
            var child = field.getValue(value);
            return type.check(child, deep);
          }
          return value !== null && typeof value === "object" && Object.keys(allFields).every(checkFieldByName);
        };
        Def2.prototype.bases = function() {
          var supertypeNames = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            supertypeNames[_i] = arguments[_i];
          }
          var bases = this.baseNames;
          if (this.finalized) {
            if (supertypeNames.length !== bases.length) {
              throw new Error("");
            }
            for (var i = 0; i < supertypeNames.length; i++) {
              if (supertypeNames[i] !== bases[i]) {
                throw new Error("");
              }
            }
            return this;
          }
          supertypeNames.forEach(function(baseName) {
            if (bases.indexOf(baseName) < 0) {
              bases.push(baseName);
            }
          });
          return this;
        };
        return Def2;
      })()
    );
    exports2.Def = Def;
    var Field = (
      /** @class */
      (function() {
        function Field2(name, type, defaultFn, hidden3) {
          this.name = name;
          this.type = type;
          this.defaultFn = defaultFn;
          this.hidden = !!hidden3;
        }
        Field2.prototype.toString = function() {
          return JSON.stringify(this.name) + ": " + this.type;
        };
        Field2.prototype.getValue = function(obj) {
          var value = obj[this.name];
          if (typeof value !== "undefined") {
            return value;
          }
          if (typeof this.defaultFn === "function") {
            value = this.defaultFn.call(obj);
          }
          return value;
        };
        return Field2;
      })()
    );
    function shallowStringify(value) {
      if (Array.isArray(value)) {
        return "[" + value.map(shallowStringify).join(", ") + "]";
      }
      if (value && typeof value === "object") {
        return "{ " + Object.keys(value).map(function(key) {
          return key + ": " + value[key];
        }).join(", ") + " }";
      }
      return JSON.stringify(value);
    }
    function typesPlugin(_fork) {
      var Type = {
        or: function() {
          var types3 = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            types3[_i] = arguments[_i];
          }
          return new OrType(types3.map(function(type) {
            return Type.from(type);
          }));
        },
        from: function(value, name) {
          if (value instanceof ArrayType || value instanceof IdentityType || value instanceof ObjectType || value instanceof OrType || value instanceof PredicateType) {
            return value;
          }
          if (value instanceof Def) {
            return value.type;
          }
          if (isArray.check(value)) {
            if (value.length !== 1) {
              throw new Error("only one element type is permitted for typed arrays");
            }
            return new ArrayType(Type.from(value[0]));
          }
          if (isObject3.check(value)) {
            return new ObjectType(Object.keys(value).map(function(name2) {
              return new Field(name2, Type.from(value[name2], name2));
            }));
          }
          if (typeof value === "function") {
            var bicfIndex = builtInCtorFns.indexOf(value);
            if (bicfIndex >= 0) {
              return builtInCtorTypes[bicfIndex];
            }
            if (typeof name !== "string") {
              throw new Error("missing name");
            }
            return new PredicateType(name, value);
          }
          return new IdentityType(value);
        },
        // Define a type whose name is registered in a namespace (the defCache) so
        // that future definitions will return the same type given the same name.
        // In particular, this system allows for circular and forward definitions.
        // The Def object d returned from Type.def may be used to configure the
        // type d.type by calling methods such as d.bases, d.build, and d.field.
        def: function(typeName) {
          return hasOwn.call(defCache, typeName) ? defCache[typeName] : defCache[typeName] = new DefImpl(typeName);
        },
        hasDef: function(typeName) {
          return hasOwn.call(defCache, typeName);
        }
      };
      var builtInCtorFns = [];
      var builtInCtorTypes = [];
      function defBuiltInType(name, example) {
        var objStr = objToStr.call(example);
        var type = new PredicateType(name, function(value) {
          return objToStr.call(value) === objStr;
        });
        if (example && typeof example.constructor === "function") {
          builtInCtorFns.push(example.constructor);
          builtInCtorTypes.push(type);
        }
        return type;
      }
      var isString2 = defBuiltInType("string", "truthy");
      var isFunction = defBuiltInType("function", function() {
      });
      var isArray = defBuiltInType("array", []);
      var isObject3 = defBuiltInType("object", {});
      var isRegExp = defBuiltInType("RegExp", /./);
      var isDate = defBuiltInType("Date", /* @__PURE__ */ new Date());
      var isNumber = defBuiltInType("number", 3);
      var isBoolean2 = defBuiltInType("boolean", true);
      var isNull2 = defBuiltInType("null", null);
      var isUndefined = defBuiltInType("undefined", void 0);
      var builtInTypes = {
        string: isString2,
        function: isFunction,
        array: isArray,
        object: isObject3,
        RegExp: isRegExp,
        Date: isDate,
        number: isNumber,
        boolean: isBoolean2,
        null: isNull2,
        undefined: isUndefined
      };
      var defCache = /* @__PURE__ */ Object.create(null);
      function defFromValue(value) {
        if (value && typeof value === "object") {
          var type = value.type;
          if (typeof type === "string" && hasOwn.call(defCache, type)) {
            var d = defCache[type];
            if (d.finalized) {
              return d;
            }
          }
        }
        return null;
      }
      var DefImpl = (
        /** @class */
        (function(_super) {
          tslib_1.__extends(DefImpl2, _super);
          function DefImpl2(typeName) {
            var _this = _super.call(this, new PredicateType(typeName, function(value, deep) {
              return _this.check(value, deep);
            }), typeName) || this;
            return _this;
          }
          DefImpl2.prototype.check = function(value, deep) {
            if (this.finalized !== true) {
              throw new Error("prematurely checking unfinalized type " + this.typeName);
            }
            if (value === null || typeof value !== "object") {
              return false;
            }
            var vDef = defFromValue(value);
            if (!vDef) {
              if (this.typeName === "SourceLocation" || this.typeName === "Position") {
                return this.checkAllFields(value, deep);
              }
              return false;
            }
            if (deep && vDef === this) {
              return this.checkAllFields(value, deep);
            }
            if (!this.isSupertypeOf(vDef)) {
              return false;
            }
            if (!deep) {
              return true;
            }
            return vDef.checkAllFields(value, deep) && this.checkAllFields(value, false);
          };
          DefImpl2.prototype.build = function() {
            var _this = this;
            var buildParams = [];
            for (var _i = 0; _i < arguments.length; _i++) {
              buildParams[_i] = arguments[_i];
            }
            this.buildParams = buildParams;
            if (this.buildable) {
              return this;
            }
            this.field("type", String, function() {
              return _this.typeName;
            });
            this.buildable = true;
            var addParam = function(built, param, arg, isArgAvailable) {
              if (hasOwn.call(built, param))
                return;
              var all2 = _this.allFields;
              if (!hasOwn.call(all2, param)) {
                throw new Error("" + param);
              }
              var field = all2[param];
              var type = field.type;
              var value;
              if (isArgAvailable) {
                value = arg;
              } else if (field.defaultFn) {
                value = field.defaultFn.call(built);
              } else {
                var message = "no value or default function given for field " + JSON.stringify(param) + " of " + _this.typeName + "(" + _this.buildParams.map(function(name) {
                  return all2[name];
                }).join(", ") + ")";
                throw new Error(message);
              }
              if (!type.check(value)) {
                throw new Error(shallowStringify(value) + " does not match field " + field + " of type " + _this.typeName);
              }
              built[param] = value;
            };
            var builder = function() {
              var args = [];
              for (var _i2 = 0; _i2 < arguments.length; _i2++) {
                args[_i2] = arguments[_i2];
              }
              var argc = args.length;
              if (!_this.finalized) {
                throw new Error("attempting to instantiate unfinalized type " + _this.typeName);
              }
              var built = Object.create(nodePrototype);
              _this.buildParams.forEach(function(param, i) {
                if (i < argc) {
                  addParam(built, param, args[i], true);
                } else {
                  addParam(built, param, null, false);
                }
              });
              Object.keys(_this.allFields).forEach(function(param) {
                addParam(built, param, null, false);
              });
              if (built.type !== _this.typeName) {
                throw new Error("");
              }
              return built;
            };
            builder.from = function(obj) {
              if (!_this.finalized) {
                throw new Error("attempting to instantiate unfinalized type " + _this.typeName);
              }
              var built = Object.create(nodePrototype);
              Object.keys(_this.allFields).forEach(function(param) {
                if (hasOwn.call(obj, param)) {
                  addParam(built, param, obj[param], true);
                } else {
                  addParam(built, param, null, false);
                }
              });
              if (built.type !== _this.typeName) {
                throw new Error("");
              }
              return built;
            };
            Object.defineProperty(builders, getBuilderName(this.typeName), {
              enumerable: true,
              value: builder
            });
            return this;
          };
          DefImpl2.prototype.field = function(name, type, defaultFn, hidden3) {
            if (this.finalized) {
              console.error("Ignoring attempt to redefine field " + JSON.stringify(name) + " of finalized type " + JSON.stringify(this.typeName));
              return this;
            }
            this.ownFields[name] = new Field(name, Type.from(type), defaultFn, hidden3);
            return this;
          };
          DefImpl2.prototype.finalize = function() {
            var _this = this;
            if (!this.finalized) {
              var allFields = this.allFields;
              var allSupertypes = this.allSupertypes;
              this.baseNames.forEach(function(name) {
                var def = defCache[name];
                if (def instanceof Def) {
                  def.finalize();
                  extend3(allFields, def.allFields);
                  extend3(allSupertypes, def.allSupertypes);
                } else {
                  var message = "unknown supertype name " + JSON.stringify(name) + " for subtype " + JSON.stringify(_this.typeName);
                  throw new Error(message);
                }
              });
              extend3(allFields, this.ownFields);
              allSupertypes[this.typeName] = this;
              this.fieldNames.length = 0;
              for (var fieldName in allFields) {
                if (hasOwn.call(allFields, fieldName) && !allFields[fieldName].hidden) {
                  this.fieldNames.push(fieldName);
                }
              }
              Object.defineProperty(namedTypes, this.typeName, {
                enumerable: true,
                value: this.type
              });
              this.finalized = true;
              populateSupertypeList(this.typeName, this.supertypeList);
              if (this.buildable && this.supertypeList.lastIndexOf("Expression") >= 0) {
                wrapExpressionBuilderWithStatement(this.typeName);
              }
            }
          };
          return DefImpl2;
        })(Def)
      );
      function getSupertypeNames(typeName) {
        if (!hasOwn.call(defCache, typeName)) {
          throw new Error("");
        }
        var d = defCache[typeName];
        if (d.finalized !== true) {
          throw new Error("");
        }
        return d.supertypeList.slice(1);
      }
      function computeSupertypeLookupTable(candidates) {
        var table = {};
        var typeNames = Object.keys(defCache);
        var typeNameCount = typeNames.length;
        for (var i = 0; i < typeNameCount; ++i) {
          var typeName = typeNames[i];
          var d = defCache[typeName];
          if (d.finalized !== true) {
            throw new Error("" + typeName);
          }
          for (var j = 0; j < d.supertypeList.length; ++j) {
            var superTypeName = d.supertypeList[j];
            if (hasOwn.call(candidates, superTypeName)) {
              table[typeName] = superTypeName;
              break;
            }
          }
        }
        return table;
      }
      var builders = /* @__PURE__ */ Object.create(null);
      var nodePrototype = {};
      function defineMethod(name, func) {
        var old = nodePrototype[name];
        if (isUndefined.check(func)) {
          delete nodePrototype[name];
        } else {
          isFunction.assert(func);
          Object.defineProperty(nodePrototype, name, {
            enumerable: true,
            configurable: true,
            value: func
          });
        }
        return old;
      }
      function getBuilderName(typeName) {
        return typeName.replace(/^[A-Z]+/, function(upperCasePrefix) {
          var len = upperCasePrefix.length;
          switch (len) {
            case 0:
              return "";
            // If there's only one initial capital letter, just lower-case it.
            case 1:
              return upperCasePrefix.toLowerCase();
            default:
              return upperCasePrefix.slice(0, len - 1).toLowerCase() + upperCasePrefix.charAt(len - 1);
          }
        });
      }
      function getStatementBuilderName(typeName) {
        typeName = getBuilderName(typeName);
        return typeName.replace(/(Expression)?$/, "Statement");
      }
      var namedTypes = {};
      function getFieldNames(object3) {
        var d = defFromValue(object3);
        if (d) {
          return d.fieldNames.slice(0);
        }
        if ("type" in object3) {
          throw new Error("did not recognize object of type " + JSON.stringify(object3.type));
        }
        return Object.keys(object3);
      }
      function getFieldValue(object3, fieldName) {
        var d = defFromValue(object3);
        if (d) {
          var field = d.allFields[fieldName];
          if (field) {
            return field.getValue(object3);
          }
        }
        return object3 && object3[fieldName];
      }
      function eachField(object3, callback, context) {
        getFieldNames(object3).forEach(function(name) {
          callback.call(this, name, getFieldValue(object3, name));
        }, context);
      }
      function someField(object3, callback, context) {
        return getFieldNames(object3).some(function(name) {
          return callback.call(this, name, getFieldValue(object3, name));
        }, context);
      }
      function wrapExpressionBuilderWithStatement(typeName) {
        var wrapperName = getStatementBuilderName(typeName);
        if (builders[wrapperName])
          return;
        var wrapped = builders[getBuilderName(typeName)];
        if (!wrapped)
          return;
        var builder = function() {
          var args = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
          }
          return builders.expressionStatement(wrapped.apply(builders, args));
        };
        builder.from = function() {
          var args = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
          }
          return builders.expressionStatement(wrapped.from.apply(builders, args));
        };
        builders[wrapperName] = builder;
      }
      function populateSupertypeList(typeName, list) {
        list.length = 0;
        list.push(typeName);
        var lastSeen = /* @__PURE__ */ Object.create(null);
        for (var pos = 0; pos < list.length; ++pos) {
          typeName = list[pos];
          var d = defCache[typeName];
          if (d.finalized !== true) {
            throw new Error("");
          }
          if (hasOwn.call(lastSeen, typeName)) {
            delete list[lastSeen[typeName]];
          }
          lastSeen[typeName] = pos;
          list.push.apply(list, d.baseNames);
        }
        for (var to = 0, from = to, len = list.length; from < len; ++from) {
          if (hasOwn.call(list, from)) {
            list[to++] = list[from];
          }
        }
        list.length = to;
      }
      function extend3(into, from) {
        Object.keys(from).forEach(function(name) {
          into[name] = from[name];
        });
        return into;
      }
      function finalize3() {
        Object.keys(defCache).forEach(function(name) {
          defCache[name].finalize();
        });
      }
      return {
        Type,
        builtInTypes,
        getSupertypeNames,
        computeSupertypeLookupTable,
        builders,
        defineMethod,
        getBuilderName,
        getStatementBuilderName,
        namedTypes,
        getFieldNames,
        getFieldValue,
        eachField,
        someField,
        finalize: finalize3
      };
    }
    exports2.default = typesPlugin;
  }
});

// ../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/lib/path.js
var require_path = __commonJS({
  "../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/lib/path.js"(exports2, module2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var types_1 = tslib_1.__importDefault(require_types());
    var Op = Object.prototype;
    var hasOwn = Op.hasOwnProperty;
    function pathPlugin(fork) {
      var types3 = fork.use(types_1.default);
      var isArray = types3.builtInTypes.array;
      var isNumber = types3.builtInTypes.number;
      var Path = function Path2(value, parentPath, name) {
        if (!(this instanceof Path2)) {
          throw new Error("Path constructor cannot be invoked without 'new'");
        }
        if (parentPath) {
          if (!(parentPath instanceof Path2)) {
            throw new Error("");
          }
        } else {
          parentPath = null;
          name = null;
        }
        this.value = value;
        this.parentPath = parentPath;
        this.name = name;
        this.__childCache = null;
      };
      var Pp = Path.prototype;
      function getChildCache(path73) {
        return path73.__childCache || (path73.__childCache = /* @__PURE__ */ Object.create(null));
      }
      function getChildPath(path73, name) {
        var cache = getChildCache(path73);
        var actualChildValue = path73.getValueProperty(name);
        var childPath = cache[name];
        if (!hasOwn.call(cache, name) || // Ensure consistency between cache and reality.
        childPath.value !== actualChildValue) {
          childPath = cache[name] = new path73.constructor(actualChildValue, path73, name);
        }
        return childPath;
      }
      Pp.getValueProperty = function getValueProperty(name) {
        return this.value[name];
      };
      Pp.get = function get() {
        var names = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          names[_i] = arguments[_i];
        }
        var path73 = this;
        var count = names.length;
        for (var i = 0; i < count; ++i) {
          path73 = getChildPath(path73, names[i]);
        }
        return path73;
      };
      Pp.each = function each(callback, context) {
        var childPaths = [];
        var len = this.value.length;
        var i = 0;
        for (var i = 0; i < len; ++i) {
          if (hasOwn.call(this.value, i)) {
            childPaths[i] = this.get(i);
          }
        }
        context = context || this;
        for (i = 0; i < len; ++i) {
          if (hasOwn.call(childPaths, i)) {
            callback.call(context, childPaths[i]);
          }
        }
      };
      Pp.map = function map3(callback, context) {
        var result = [];
        this.each(function(childPath) {
          result.push(callback.call(this, childPath));
        }, context);
        return result;
      };
      Pp.filter = function filter(callback, context) {
        var result = [];
        this.each(function(childPath) {
          if (callback.call(this, childPath)) {
            result.push(childPath);
          }
        }, context);
        return result;
      };
      function emptyMoves() {
      }
      function getMoves(path73, offset, start, end) {
        isArray.assert(path73.value);
        if (offset === 0) {
          return emptyMoves;
        }
        var length = path73.value.length;
        if (length < 1) {
          return emptyMoves;
        }
        var argc = arguments.length;
        if (argc === 2) {
          start = 0;
          end = length;
        } else if (argc === 3) {
          start = Math.max(start, 0);
          end = length;
        } else {
          start = Math.max(start, 0);
          end = Math.min(end, length);
        }
        isNumber.assert(start);
        isNumber.assert(end);
        var moves = /* @__PURE__ */ Object.create(null);
        var cache = getChildCache(path73);
        for (var i = start; i < end; ++i) {
          if (hasOwn.call(path73.value, i)) {
            var childPath = path73.get(i);
            if (childPath.name !== i) {
              throw new Error("");
            }
            var newIndex = i + offset;
            childPath.name = newIndex;
            moves[newIndex] = childPath;
            delete cache[i];
          }
        }
        delete cache.length;
        return function() {
          for (var newIndex2 in moves) {
            var childPath2 = moves[newIndex2];
            if (childPath2.name !== +newIndex2) {
              throw new Error("");
            }
            cache[newIndex2] = childPath2;
            path73.value[newIndex2] = childPath2.value;
          }
        };
      }
      Pp.shift = function shift() {
        var move = getMoves(this, -1);
        var result = this.value.shift();
        move();
        return result;
      };
      Pp.unshift = function unshift() {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          args[_i] = arguments[_i];
        }
        var move = getMoves(this, args.length);
        var result = this.value.unshift.apply(this.value, args);
        move();
        return result;
      };
      Pp.push = function push() {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          args[_i] = arguments[_i];
        }
        isArray.assert(this.value);
        delete getChildCache(this).length;
        return this.value.push.apply(this.value, args);
      };
      Pp.pop = function pop() {
        isArray.assert(this.value);
        var cache = getChildCache(this);
        delete cache[this.value.length - 1];
        delete cache.length;
        return this.value.pop();
      };
      Pp.insertAt = function insertAt(index) {
        var argc = arguments.length;
        var move = getMoves(this, argc - 1, index);
        if (move === emptyMoves && argc <= 1) {
          return this;
        }
        index = Math.max(index, 0);
        for (var i = 1; i < argc; ++i) {
          this.value[index + i - 1] = arguments[i];
        }
        move();
        return this;
      };
      Pp.insertBefore = function insertBefore() {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          args[_i] = arguments[_i];
        }
        var pp = this.parentPath;
        var argc = args.length;
        var insertAtArgs = [this.name];
        for (var i = 0; i < argc; ++i) {
          insertAtArgs.push(args[i]);
        }
        return pp.insertAt.apply(pp, insertAtArgs);
      };
      Pp.insertAfter = function insertAfter() {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          args[_i] = arguments[_i];
        }
        var pp = this.parentPath;
        var argc = args.length;
        var insertAtArgs = [this.name + 1];
        for (var i = 0; i < argc; ++i) {
          insertAtArgs.push(args[i]);
        }
        return pp.insertAt.apply(pp, insertAtArgs);
      };
      function repairRelationshipWithParent(path73) {
        if (!(path73 instanceof Path)) {
          throw new Error("");
        }
        var pp = path73.parentPath;
        if (!pp) {
          return path73;
        }
        var parentValue = pp.value;
        var parentCache = getChildCache(pp);
        if (parentValue[path73.name] === path73.value) {
          parentCache[path73.name] = path73;
        } else if (isArray.check(parentValue)) {
          var i = parentValue.indexOf(path73.value);
          if (i >= 0) {
            parentCache[path73.name = i] = path73;
          }
        } else {
          parentValue[path73.name] = path73.value;
          parentCache[path73.name] = path73;
        }
        if (parentValue[path73.name] !== path73.value) {
          throw new Error("");
        }
        if (path73.parentPath.get(path73.name) !== path73) {
          throw new Error("");
        }
        return path73;
      }
      Pp.replace = function replace(replacement) {
        var results = [];
        var parentValue = this.parentPath.value;
        var parentCache = getChildCache(this.parentPath);
        var count = arguments.length;
        repairRelationshipWithParent(this);
        if (isArray.check(parentValue)) {
          var originalLength = parentValue.length;
          var move = getMoves(this.parentPath, count - 1, this.name + 1);
          var spliceArgs = [this.name, 1];
          for (var i = 0; i < count; ++i) {
            spliceArgs.push(arguments[i]);
          }
          var splicedOut = parentValue.splice.apply(parentValue, spliceArgs);
          if (splicedOut[0] !== this.value) {
            throw new Error("");
          }
          if (parentValue.length !== originalLength - 1 + count) {
            throw new Error("");
          }
          move();
          if (count === 0) {
            delete this.value;
            delete parentCache[this.name];
            this.__childCache = null;
          } else {
            if (parentValue[this.name] !== replacement) {
              throw new Error("");
            }
            if (this.value !== replacement) {
              this.value = replacement;
              this.__childCache = null;
            }
            for (i = 0; i < count; ++i) {
              results.push(this.parentPath.get(this.name + i));
            }
            if (results[0] !== this) {
              throw new Error("");
            }
          }
        } else if (count === 1) {
          if (this.value !== replacement) {
            this.__childCache = null;
          }
          this.value = parentValue[this.name] = replacement;
          results.push(this);
        } else if (count === 0) {
          delete parentValue[this.name];
          delete this.value;
          this.__childCache = null;
        } else {
          throw new Error("Could not replace path");
        }
        return results;
      };
      return Path;
    }
    exports2.default = pathPlugin;
    module2.exports = exports2["default"];
  }
});

// ../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/lib/scope.js
var require_scope = __commonJS({
  "../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/lib/scope.js"(exports2, module2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var types_1 = tslib_1.__importDefault(require_types());
    var hasOwn = Object.prototype.hasOwnProperty;
    function scopePlugin(fork) {
      var types3 = fork.use(types_1.default);
      var Type = types3.Type;
      var namedTypes = types3.namedTypes;
      var Node = namedTypes.Node;
      var Expression = namedTypes.Expression;
      var isArray = types3.builtInTypes.array;
      var b = types3.builders;
      var Scope = function Scope2(path73, parentScope) {
        if (!(this instanceof Scope2)) {
          throw new Error("Scope constructor cannot be invoked without 'new'");
        }
        ScopeType.assert(path73.value);
        var depth;
        if (parentScope) {
          if (!(parentScope instanceof Scope2)) {
            throw new Error("");
          }
          depth = parentScope.depth + 1;
        } else {
          parentScope = null;
          depth = 0;
        }
        Object.defineProperties(this, {
          path: { value: path73 },
          node: { value: path73.value },
          isGlobal: { value: !parentScope, enumerable: true },
          depth: { value: depth },
          parent: { value: parentScope },
          bindings: { value: {} },
          types: { value: {} }
        });
      };
      var scopeTypes = [
        // Program nodes introduce global scopes.
        namedTypes.Program,
        // Function is the supertype of FunctionExpression,
        // FunctionDeclaration, ArrowExpression, etc.
        namedTypes.Function,
        // In case you didn't know, the caught parameter shadows any variable
        // of the same name in an outer scope.
        namedTypes.CatchClause
      ];
      var ScopeType = Type.or.apply(Type, scopeTypes);
      Scope.isEstablishedBy = function(node) {
        return ScopeType.check(node);
      };
      var Sp = Scope.prototype;
      Sp.didScan = false;
      Sp.declares = function(name) {
        this.scan();
        return hasOwn.call(this.bindings, name);
      };
      Sp.declaresType = function(name) {
        this.scan();
        return hasOwn.call(this.types, name);
      };
      Sp.declareTemporary = function(prefix) {
        if (prefix) {
          if (!/^[a-z$_]/i.test(prefix)) {
            throw new Error("");
          }
        } else {
          prefix = "t$";
        }
        prefix += this.depth.toString(36) + "$";
        this.scan();
        var index = 0;
        while (this.declares(prefix + index)) {
          ++index;
        }
        var name = prefix + index;
        return this.bindings[name] = types3.builders.identifier(name);
      };
      Sp.injectTemporary = function(identifier, init3) {
        identifier || (identifier = this.declareTemporary());
        var bodyPath = this.path.get("body");
        if (namedTypes.BlockStatement.check(bodyPath.value)) {
          bodyPath = bodyPath.get("body");
        }
        bodyPath.unshift(b.variableDeclaration("var", [b.variableDeclarator(identifier, init3 || null)]));
        return identifier;
      };
      Sp.scan = function(force) {
        if (force || !this.didScan) {
          for (var name in this.bindings) {
            delete this.bindings[name];
          }
          scanScope(this.path, this.bindings, this.types);
          this.didScan = true;
        }
      };
      Sp.getBindings = function() {
        this.scan();
        return this.bindings;
      };
      Sp.getTypes = function() {
        this.scan();
        return this.types;
      };
      function scanScope(path73, bindings, scopeTypes2) {
        var node = path73.value;
        ScopeType.assert(node);
        if (namedTypes.CatchClause.check(node)) {
          var param = path73.get("param");
          if (param.value) {
            addPattern(param, bindings);
          }
        } else {
          recursiveScanScope(path73, bindings, scopeTypes2);
        }
      }
      function recursiveScanScope(path73, bindings, scopeTypes2) {
        var node = path73.value;
        if (path73.parent && namedTypes.FunctionExpression.check(path73.parent.node) && path73.parent.node.id) {
          addPattern(path73.parent.get("id"), bindings);
        }
        if (!node) {
        } else if (isArray.check(node)) {
          path73.each(function(childPath) {
            recursiveScanChild(childPath, bindings, scopeTypes2);
          });
        } else if (namedTypes.Function.check(node)) {
          path73.get("params").each(function(paramPath) {
            addPattern(paramPath, bindings);
          });
          recursiveScanChild(path73.get("body"), bindings, scopeTypes2);
        } else if (namedTypes.TypeAlias && namedTypes.TypeAlias.check(node) || namedTypes.InterfaceDeclaration && namedTypes.InterfaceDeclaration.check(node) || namedTypes.TSTypeAliasDeclaration && namedTypes.TSTypeAliasDeclaration.check(node) || namedTypes.TSInterfaceDeclaration && namedTypes.TSInterfaceDeclaration.check(node)) {
          addTypePattern(path73.get("id"), scopeTypes2);
        } else if (namedTypes.VariableDeclarator.check(node)) {
          addPattern(path73.get("id"), bindings);
          recursiveScanChild(path73.get("init"), bindings, scopeTypes2);
        } else if (node.type === "ImportSpecifier" || node.type === "ImportNamespaceSpecifier" || node.type === "ImportDefaultSpecifier") {
          addPattern(
            // Esprima used to use the .name field to refer to the local
            // binding identifier for ImportSpecifier nodes, but .id for
            // ImportNamespaceSpecifier and ImportDefaultSpecifier nodes.
            // ESTree/Acorn/ESpree use .local for all three node types.
            path73.get(node.local ? "local" : node.name ? "name" : "id"),
            bindings
          );
        } else if (Node.check(node) && !Expression.check(node)) {
          types3.eachField(node, function(name, child) {
            var childPath = path73.get(name);
            if (!pathHasValue(childPath, child)) {
              throw new Error("");
            }
            recursiveScanChild(childPath, bindings, scopeTypes2);
          });
        }
      }
      function pathHasValue(path73, value) {
        if (path73.value === value) {
          return true;
        }
        if (Array.isArray(path73.value) && path73.value.length === 0 && Array.isArray(value) && value.length === 0) {
          return true;
        }
        return false;
      }
      function recursiveScanChild(path73, bindings, scopeTypes2) {
        var node = path73.value;
        if (!node || Expression.check(node)) {
        } else if (namedTypes.FunctionDeclaration.check(node) && node.id !== null) {
          addPattern(path73.get("id"), bindings);
        } else if (namedTypes.ClassDeclaration && namedTypes.ClassDeclaration.check(node)) {
          addPattern(path73.get("id"), bindings);
        } else if (ScopeType.check(node)) {
          if (namedTypes.CatchClause.check(node) && // TODO Broaden this to accept any pattern.
          namedTypes.Identifier.check(node.param)) {
            var catchParamName = node.param.name;
            var hadBinding = hasOwn.call(bindings, catchParamName);
            recursiveScanScope(path73.get("body"), bindings, scopeTypes2);
            if (!hadBinding) {
              delete bindings[catchParamName];
            }
          }
        } else {
          recursiveScanScope(path73, bindings, scopeTypes2);
        }
      }
      function addPattern(patternPath, bindings) {
        var pattern = patternPath.value;
        namedTypes.Pattern.assert(pattern);
        if (namedTypes.Identifier.check(pattern)) {
          if (hasOwn.call(bindings, pattern.name)) {
            bindings[pattern.name].push(patternPath);
          } else {
            bindings[pattern.name] = [patternPath];
          }
        } else if (namedTypes.AssignmentPattern && namedTypes.AssignmentPattern.check(pattern)) {
          addPattern(patternPath.get("left"), bindings);
        } else if (namedTypes.ObjectPattern && namedTypes.ObjectPattern.check(pattern)) {
          patternPath.get("properties").each(function(propertyPath) {
            var property = propertyPath.value;
            if (namedTypes.Pattern.check(property)) {
              addPattern(propertyPath, bindings);
            } else if (namedTypes.Property.check(property)) {
              addPattern(propertyPath.get("value"), bindings);
            } else if (namedTypes.SpreadProperty && namedTypes.SpreadProperty.check(property)) {
              addPattern(propertyPath.get("argument"), bindings);
            }
          });
        } else if (namedTypes.ArrayPattern && namedTypes.ArrayPattern.check(pattern)) {
          patternPath.get("elements").each(function(elementPath) {
            var element = elementPath.value;
            if (namedTypes.Pattern.check(element)) {
              addPattern(elementPath, bindings);
            } else if (namedTypes.SpreadElement && namedTypes.SpreadElement.check(element)) {
              addPattern(elementPath.get("argument"), bindings);
            }
          });
        } else if (namedTypes.PropertyPattern && namedTypes.PropertyPattern.check(pattern)) {
          addPattern(patternPath.get("pattern"), bindings);
        } else if (namedTypes.SpreadElementPattern && namedTypes.SpreadElementPattern.check(pattern) || namedTypes.SpreadPropertyPattern && namedTypes.SpreadPropertyPattern.check(pattern)) {
          addPattern(patternPath.get("argument"), bindings);
        }
      }
      function addTypePattern(patternPath, types4) {
        var pattern = patternPath.value;
        namedTypes.Pattern.assert(pattern);
        if (namedTypes.Identifier.check(pattern)) {
          if (hasOwn.call(types4, pattern.name)) {
            types4[pattern.name].push(patternPath);
          } else {
            types4[pattern.name] = [patternPath];
          }
        }
      }
      Sp.lookup = function(name) {
        for (var scope = this; scope; scope = scope.parent)
          if (scope.declares(name))
            break;
        return scope;
      };
      Sp.lookupType = function(name) {
        for (var scope = this; scope; scope = scope.parent)
          if (scope.declaresType(name))
            break;
        return scope;
      };
      Sp.getGlobalScope = function() {
        var scope = this;
        while (!scope.isGlobal)
          scope = scope.parent;
        return scope;
      };
      return Scope;
    }
    exports2.default = scopePlugin;
    module2.exports = exports2["default"];
  }
});

// ../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/lib/node-path.js
var require_node_path = __commonJS({
  "../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/lib/node-path.js"(exports2, module2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var types_1 = tslib_1.__importDefault(require_types());
    var path_1 = tslib_1.__importDefault(require_path());
    var scope_1 = tslib_1.__importDefault(require_scope());
    function nodePathPlugin(fork) {
      var types3 = fork.use(types_1.default);
      var n = types3.namedTypes;
      var b = types3.builders;
      var isNumber = types3.builtInTypes.number;
      var isArray = types3.builtInTypes.array;
      var Path = fork.use(path_1.default);
      var Scope = fork.use(scope_1.default);
      var NodePath = function NodePath2(value, parentPath, name) {
        if (!(this instanceof NodePath2)) {
          throw new Error("NodePath constructor cannot be invoked without 'new'");
        }
        Path.call(this, value, parentPath, name);
      };
      var NPp = NodePath.prototype = Object.create(Path.prototype, {
        constructor: {
          value: NodePath,
          enumerable: false,
          writable: true,
          configurable: true
        }
      });
      Object.defineProperties(NPp, {
        node: {
          get: function() {
            Object.defineProperty(this, "node", {
              configurable: true,
              value: this._computeNode()
            });
            return this.node;
          }
        },
        parent: {
          get: function() {
            Object.defineProperty(this, "parent", {
              configurable: true,
              value: this._computeParent()
            });
            return this.parent;
          }
        },
        scope: {
          get: function() {
            Object.defineProperty(this, "scope", {
              configurable: true,
              value: this._computeScope()
            });
            return this.scope;
          }
        }
      });
      NPp.replace = function() {
        delete this.node;
        delete this.parent;
        delete this.scope;
        return Path.prototype.replace.apply(this, arguments);
      };
      NPp.prune = function() {
        var remainingNodePath = this.parent;
        this.replace();
        return cleanUpNodesAfterPrune(remainingNodePath);
      };
      NPp._computeNode = function() {
        var value = this.value;
        if (n.Node.check(value)) {
          return value;
        }
        var pp = this.parentPath;
        return pp && pp.node || null;
      };
      NPp._computeParent = function() {
        var value = this.value;
        var pp = this.parentPath;
        if (!n.Node.check(value)) {
          while (pp && !n.Node.check(pp.value)) {
            pp = pp.parentPath;
          }
          if (pp) {
            pp = pp.parentPath;
          }
        }
        while (pp && !n.Node.check(pp.value)) {
          pp = pp.parentPath;
        }
        return pp || null;
      };
      NPp._computeScope = function() {
        var value = this.value;
        var pp = this.parentPath;
        var scope = pp && pp.scope;
        if (n.Node.check(value) && Scope.isEstablishedBy(value)) {
          scope = new Scope(this, scope);
        }
        return scope || null;
      };
      NPp.getValueProperty = function(name) {
        return types3.getFieldValue(this.value, name);
      };
      NPp.needsParens = function(assumeExpressionContext) {
        var pp = this.parentPath;
        if (!pp) {
          return false;
        }
        var node = this.value;
        if (!n.Expression.check(node)) {
          return false;
        }
        if (node.type === "Identifier") {
          return false;
        }
        while (!n.Node.check(pp.value)) {
          pp = pp.parentPath;
          if (!pp) {
            return false;
          }
        }
        var parent = pp.value;
        switch (node.type) {
          case "UnaryExpression":
          case "SpreadElement":
          case "SpreadProperty":
            return parent.type === "MemberExpression" && this.name === "object" && parent.object === node;
          case "BinaryExpression":
          case "LogicalExpression":
            switch (parent.type) {
              case "CallExpression":
                return this.name === "callee" && parent.callee === node;
              case "UnaryExpression":
              case "SpreadElement":
              case "SpreadProperty":
                return true;
              case "MemberExpression":
                return this.name === "object" && parent.object === node;
              case "BinaryExpression":
              case "LogicalExpression": {
                var n_1 = node;
                var po = parent.operator;
                var pp_1 = PRECEDENCE[po];
                var no = n_1.operator;
                var np = PRECEDENCE[no];
                if (pp_1 > np) {
                  return true;
                }
                if (pp_1 === np && this.name === "right") {
                  if (parent.right !== n_1) {
                    throw new Error("Nodes must be equal");
                  }
                  return true;
                }
              }
              default:
                return false;
            }
          case "SequenceExpression":
            switch (parent.type) {
              case "ForStatement":
                return false;
              case "ExpressionStatement":
                return this.name !== "expression";
              default:
                return true;
            }
          case "YieldExpression":
            switch (parent.type) {
              case "BinaryExpression":
              case "LogicalExpression":
              case "UnaryExpression":
              case "SpreadElement":
              case "SpreadProperty":
              case "CallExpression":
              case "MemberExpression":
              case "NewExpression":
              case "ConditionalExpression":
              case "YieldExpression":
                return true;
              default:
                return false;
            }
          case "Literal":
            return parent.type === "MemberExpression" && isNumber.check(node.value) && this.name === "object" && parent.object === node;
          case "AssignmentExpression":
          case "ConditionalExpression":
            switch (parent.type) {
              case "UnaryExpression":
              case "SpreadElement":
              case "SpreadProperty":
              case "BinaryExpression":
              case "LogicalExpression":
                return true;
              case "CallExpression":
                return this.name === "callee" && parent.callee === node;
              case "ConditionalExpression":
                return this.name === "test" && parent.test === node;
              case "MemberExpression":
                return this.name === "object" && parent.object === node;
              default:
                return false;
            }
          default:
            if (parent.type === "NewExpression" && this.name === "callee" && parent.callee === node) {
              return containsCallExpression(node);
            }
        }
        if (assumeExpressionContext !== true && !this.canBeFirstInStatement() && this.firstInStatement())
          return true;
        return false;
      };
      function isBinary(node) {
        return n.BinaryExpression.check(node) || n.LogicalExpression.check(node);
      }
      function isUnaryLike(node) {
        return n.UnaryExpression.check(node) || n.SpreadElement && n.SpreadElement.check(node) || n.SpreadProperty && n.SpreadProperty.check(node);
      }
      var PRECEDENCE = {};
      [
        ["||"],
        ["&&"],
        ["|"],
        ["^"],
        ["&"],
        ["==", "===", "!=", "!=="],
        ["<", ">", "<=", ">=", "in", "instanceof"],
        [">>", "<<", ">>>"],
        ["+", "-"],
        ["*", "/", "%"]
      ].forEach(function(tier, i) {
        tier.forEach(function(op) {
          PRECEDENCE[op] = i;
        });
      });
      function containsCallExpression(node) {
        if (n.CallExpression.check(node)) {
          return true;
        }
        if (isArray.check(node)) {
          return node.some(containsCallExpression);
        }
        if (n.Node.check(node)) {
          return types3.someField(node, function(_name, child) {
            return containsCallExpression(child);
          });
        }
        return false;
      }
      NPp.canBeFirstInStatement = function() {
        var node = this.node;
        return !n.FunctionExpression.check(node) && !n.ObjectExpression.check(node);
      };
      NPp.firstInStatement = function() {
        return firstInStatement(this);
      };
      function firstInStatement(path73) {
        for (var node, parent; path73.parent; path73 = path73.parent) {
          node = path73.node;
          parent = path73.parent.node;
          if (n.BlockStatement.check(parent) && path73.parent.name === "body" && path73.name === 0) {
            if (parent.body[0] !== node) {
              throw new Error("Nodes must be equal");
            }
            return true;
          }
          if (n.ExpressionStatement.check(parent) && path73.name === "expression") {
            if (parent.expression !== node) {
              throw new Error("Nodes must be equal");
            }
            return true;
          }
          if (n.SequenceExpression.check(parent) && path73.parent.name === "expressions" && path73.name === 0) {
            if (parent.expressions[0] !== node) {
              throw new Error("Nodes must be equal");
            }
            continue;
          }
          if (n.CallExpression.check(parent) && path73.name === "callee") {
            if (parent.callee !== node) {
              throw new Error("Nodes must be equal");
            }
            continue;
          }
          if (n.MemberExpression.check(parent) && path73.name === "object") {
            if (parent.object !== node) {
              throw new Error("Nodes must be equal");
            }
            continue;
          }
          if (n.ConditionalExpression.check(parent) && path73.name === "test") {
            if (parent.test !== node) {
              throw new Error("Nodes must be equal");
            }
            continue;
          }
          if (isBinary(parent) && path73.name === "left") {
            if (parent.left !== node) {
              throw new Error("Nodes must be equal");
            }
            continue;
          }
          if (n.UnaryExpression.check(parent) && !parent.prefix && path73.name === "argument") {
            if (parent.argument !== node) {
              throw new Error("Nodes must be equal");
            }
            continue;
          }
          return false;
        }
        return true;
      }
      function cleanUpNodesAfterPrune(remainingNodePath) {
        if (n.VariableDeclaration.check(remainingNodePath.node)) {
          var declarations = remainingNodePath.get("declarations").value;
          if (!declarations || declarations.length === 0) {
            return remainingNodePath.prune();
          }
        } else if (n.ExpressionStatement.check(remainingNodePath.node)) {
          if (!remainingNodePath.get("expression").value) {
            return remainingNodePath.prune();
          }
        } else if (n.IfStatement.check(remainingNodePath.node)) {
          cleanUpIfStatementAfterPrune(remainingNodePath);
        }
        return remainingNodePath;
      }
      function cleanUpIfStatementAfterPrune(ifStatement) {
        var testExpression = ifStatement.get("test").value;
        var alternate = ifStatement.get("alternate").value;
        var consequent = ifStatement.get("consequent").value;
        if (!consequent && !alternate) {
          var testExpressionStatement = b.expressionStatement(testExpression);
          ifStatement.replace(testExpressionStatement);
        } else if (!consequent && alternate) {
          var negatedTestExpression = b.unaryExpression("!", testExpression, true);
          if (n.UnaryExpression.check(testExpression) && testExpression.operator === "!") {
            negatedTestExpression = testExpression.argument;
          }
          ifStatement.get("test").replace(negatedTestExpression);
          ifStatement.get("consequent").replace(alternate);
          ifStatement.get("alternate").replace();
        }
      }
      return NodePath;
    }
    exports2.default = nodePathPlugin;
    module2.exports = exports2["default"];
  }
});

// ../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/lib/path-visitor.js
var require_path_visitor = __commonJS({
  "../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/lib/path-visitor.js"(exports2, module2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var types_1 = tslib_1.__importDefault(require_types());
    var node_path_1 = tslib_1.__importDefault(require_node_path());
    var hasOwn = Object.prototype.hasOwnProperty;
    function pathVisitorPlugin(fork) {
      var types3 = fork.use(types_1.default);
      var NodePath = fork.use(node_path_1.default);
      var isArray = types3.builtInTypes.array;
      var isObject3 = types3.builtInTypes.object;
      var isFunction = types3.builtInTypes.function;
      var undefined2;
      var PathVisitor = function PathVisitor2() {
        if (!(this instanceof PathVisitor2)) {
          throw new Error("PathVisitor constructor cannot be invoked without 'new'");
        }
        this._reusableContextStack = [];
        this._methodNameTable = computeMethodNameTable(this);
        this._shouldVisitComments = hasOwn.call(this._methodNameTable, "Block") || hasOwn.call(this._methodNameTable, "Line");
        this.Context = makeContextConstructor(this);
        this._visiting = false;
        this._changeReported = false;
      };
      function computeMethodNameTable(visitor) {
        var typeNames = /* @__PURE__ */ Object.create(null);
        for (var methodName in visitor) {
          if (/^visit[A-Z]/.test(methodName)) {
            typeNames[methodName.slice("visit".length)] = true;
          }
        }
        var supertypeTable = types3.computeSupertypeLookupTable(typeNames);
        var methodNameTable = /* @__PURE__ */ Object.create(null);
        var typeNameKeys = Object.keys(supertypeTable);
        var typeNameCount = typeNameKeys.length;
        for (var i = 0; i < typeNameCount; ++i) {
          var typeName = typeNameKeys[i];
          methodName = "visit" + supertypeTable[typeName];
          if (isFunction.check(visitor[methodName])) {
            methodNameTable[typeName] = methodName;
          }
        }
        return methodNameTable;
      }
      PathVisitor.fromMethodsObject = function fromMethodsObject(methods) {
        if (methods instanceof PathVisitor) {
          return methods;
        }
        if (!isObject3.check(methods)) {
          return new PathVisitor();
        }
        var Visitor = function Visitor2() {
          if (!(this instanceof Visitor2)) {
            throw new Error("Visitor constructor cannot be invoked without 'new'");
          }
          PathVisitor.call(this);
        };
        var Vp = Visitor.prototype = Object.create(PVp);
        Vp.constructor = Visitor;
        extend3(Vp, methods);
        extend3(Visitor, PathVisitor);
        isFunction.assert(Visitor.fromMethodsObject);
        isFunction.assert(Visitor.visit);
        return new Visitor();
      };
      function extend3(target, source) {
        for (var property in source) {
          if (hasOwn.call(source, property)) {
            target[property] = source[property];
          }
        }
        return target;
      }
      PathVisitor.visit = function visit3(node, methods) {
        return PathVisitor.fromMethodsObject(methods).visit(node);
      };
      var PVp = PathVisitor.prototype;
      PVp.visit = function() {
        if (this._visiting) {
          throw new Error("Recursively calling visitor.visit(path) resets visitor state. Try this.visit(path) or this.traverse(path) instead.");
        }
        this._visiting = true;
        this._changeReported = false;
        this._abortRequested = false;
        var argc = arguments.length;
        var args = new Array(argc);
        for (var i = 0; i < argc; ++i) {
          args[i] = arguments[i];
        }
        if (!(args[0] instanceof NodePath)) {
          args[0] = new NodePath({ root: args[0] }).get("root");
        }
        this.reset.apply(this, args);
        var didNotThrow;
        try {
          var root = this.visitWithoutReset(args[0]);
          didNotThrow = true;
        } finally {
          this._visiting = false;
          if (!didNotThrow && this._abortRequested) {
            return args[0].value;
          }
        }
        return root;
      };
      PVp.AbortRequest = function AbortRequest() {
      };
      PVp.abort = function() {
        var visitor = this;
        visitor._abortRequested = true;
        var request4 = new visitor.AbortRequest();
        request4.cancel = function() {
          visitor._abortRequested = false;
        };
        throw request4;
      };
      PVp.reset = function(_path) {
      };
      PVp.visitWithoutReset = function(path73) {
        if (this instanceof this.Context) {
          return this.visitor.visitWithoutReset(path73);
        }
        if (!(path73 instanceof NodePath)) {
          throw new Error("");
        }
        var value = path73.value;
        var methodName = value && typeof value === "object" && typeof value.type === "string" && this._methodNameTable[value.type];
        if (methodName) {
          var context = this.acquireContext(path73);
          try {
            return context.invokeVisitorMethod(methodName);
          } finally {
            this.releaseContext(context);
          }
        } else {
          return visitChildren(path73, this);
        }
      };
      function visitChildren(path73, visitor) {
        if (!(path73 instanceof NodePath)) {
          throw new Error("");
        }
        if (!(visitor instanceof PathVisitor)) {
          throw new Error("");
        }
        var value = path73.value;
        if (isArray.check(value)) {
          path73.each(visitor.visitWithoutReset, visitor);
        } else if (!isObject3.check(value)) {
        } else {
          var childNames = types3.getFieldNames(value);
          if (visitor._shouldVisitComments && value.comments && childNames.indexOf("comments") < 0) {
            childNames.push("comments");
          }
          var childCount = childNames.length;
          var childPaths = [];
          for (var i = 0; i < childCount; ++i) {
            var childName = childNames[i];
            if (!hasOwn.call(value, childName)) {
              value[childName] = types3.getFieldValue(value, childName);
            }
            childPaths.push(path73.get(childName));
          }
          for (var i = 0; i < childCount; ++i) {
            visitor.visitWithoutReset(childPaths[i]);
          }
        }
        return path73.value;
      }
      PVp.acquireContext = function(path73) {
        if (this._reusableContextStack.length === 0) {
          return new this.Context(path73);
        }
        return this._reusableContextStack.pop().reset(path73);
      };
      PVp.releaseContext = function(context) {
        if (!(context instanceof this.Context)) {
          throw new Error("");
        }
        this._reusableContextStack.push(context);
        context.currentPath = null;
      };
      PVp.reportChanged = function() {
        this._changeReported = true;
      };
      PVp.wasChangeReported = function() {
        return this._changeReported;
      };
      function makeContextConstructor(visitor) {
        function Context(path73) {
          if (!(this instanceof Context)) {
            throw new Error("");
          }
          if (!(this instanceof PathVisitor)) {
            throw new Error("");
          }
          if (!(path73 instanceof NodePath)) {
            throw new Error("");
          }
          Object.defineProperty(this, "visitor", {
            value: visitor,
            writable: false,
            enumerable: true,
            configurable: false
          });
          this.currentPath = path73;
          this.needToCallTraverse = true;
          Object.seal(this);
        }
        if (!(visitor instanceof PathVisitor)) {
          throw new Error("");
        }
        var Cp = Context.prototype = Object.create(visitor);
        Cp.constructor = Context;
        extend3(Cp, sharedContextProtoMethods);
        return Context;
      }
      var sharedContextProtoMethods = /* @__PURE__ */ Object.create(null);
      sharedContextProtoMethods.reset = function reset2(path73) {
        if (!(this instanceof this.Context)) {
          throw new Error("");
        }
        if (!(path73 instanceof NodePath)) {
          throw new Error("");
        }
        this.currentPath = path73;
        this.needToCallTraverse = true;
        return this;
      };
      sharedContextProtoMethods.invokeVisitorMethod = function invokeVisitorMethod(methodName) {
        if (!(this instanceof this.Context)) {
          throw new Error("");
        }
        if (!(this.currentPath instanceof NodePath)) {
          throw new Error("");
        }
        var result = this.visitor[methodName].call(this, this.currentPath);
        if (result === false) {
          this.needToCallTraverse = false;
        } else if (result !== undefined2) {
          this.currentPath = this.currentPath.replace(result)[0];
          if (this.needToCallTraverse) {
            this.traverse(this.currentPath);
          }
        }
        if (this.needToCallTraverse !== false) {
          throw new Error("Must either call this.traverse or return false in " + methodName);
        }
        var path73 = this.currentPath;
        return path73 && path73.value;
      };
      sharedContextProtoMethods.traverse = function traverse(path73, newVisitor) {
        if (!(this instanceof this.Context)) {
          throw new Error("");
        }
        if (!(path73 instanceof NodePath)) {
          throw new Error("");
        }
        if (!(this.currentPath instanceof NodePath)) {
          throw new Error("");
        }
        this.needToCallTraverse = false;
        return visitChildren(path73, PathVisitor.fromMethodsObject(newVisitor || this.visitor));
      };
      sharedContextProtoMethods.visit = function visit3(path73, newVisitor) {
        if (!(this instanceof this.Context)) {
          throw new Error("");
        }
        if (!(path73 instanceof NodePath)) {
          throw new Error("");
        }
        if (!(this.currentPath instanceof NodePath)) {
          throw new Error("");
        }
        this.needToCallTraverse = false;
        return PathVisitor.fromMethodsObject(newVisitor || this.visitor).visitWithoutReset(path73);
      };
      sharedContextProtoMethods.reportChanged = function reportChanged() {
        this.visitor.reportChanged();
      };
      sharedContextProtoMethods.abort = function abort() {
        this.needToCallTraverse = false;
        this.visitor.abort();
      };
      return PathVisitor;
    }
    exports2.default = pathVisitorPlugin;
    module2.exports = exports2["default"];
  }
});

// ../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/lib/equiv.js
var require_equiv = __commonJS({
  "../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/lib/equiv.js"(exports2, module2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var types_1 = tslib_1.__importDefault(require_types());
    function default_1(fork) {
      var types3 = fork.use(types_1.default);
      var getFieldNames = types3.getFieldNames;
      var getFieldValue = types3.getFieldValue;
      var isArray = types3.builtInTypes.array;
      var isObject3 = types3.builtInTypes.object;
      var isDate = types3.builtInTypes.Date;
      var isRegExp = types3.builtInTypes.RegExp;
      var hasOwn = Object.prototype.hasOwnProperty;
      function astNodesAreEquivalent(a, b, problemPath) {
        if (isArray.check(problemPath)) {
          problemPath.length = 0;
        } else {
          problemPath = null;
        }
        return areEquivalent(a, b, problemPath);
      }
      astNodesAreEquivalent.assert = function(a, b) {
        var problemPath = [];
        if (!astNodesAreEquivalent(a, b, problemPath)) {
          if (problemPath.length === 0) {
            if (a !== b) {
              throw new Error("Nodes must be equal");
            }
          } else {
            throw new Error("Nodes differ in the following path: " + problemPath.map(subscriptForProperty).join(""));
          }
        }
      };
      function subscriptForProperty(property) {
        if (/[_$a-z][_$a-z0-9]*/i.test(property)) {
          return "." + property;
        }
        return "[" + JSON.stringify(property) + "]";
      }
      function areEquivalent(a, b, problemPath) {
        if (a === b) {
          return true;
        }
        if (isArray.check(a)) {
          return arraysAreEquivalent(a, b, problemPath);
        }
        if (isObject3.check(a)) {
          return objectsAreEquivalent(a, b, problemPath);
        }
        if (isDate.check(a)) {
          return isDate.check(b) && +a === +b;
        }
        if (isRegExp.check(a)) {
          return isRegExp.check(b) && (a.source === b.source && a.global === b.global && a.multiline === b.multiline && a.ignoreCase === b.ignoreCase);
        }
        return a == b;
      }
      function arraysAreEquivalent(a, b, problemPath) {
        isArray.assert(a);
        var aLength = a.length;
        if (!isArray.check(b) || b.length !== aLength) {
          if (problemPath) {
            problemPath.push("length");
          }
          return false;
        }
        for (var i = 0; i < aLength; ++i) {
          if (problemPath) {
            problemPath.push(i);
          }
          if (i in a !== i in b) {
            return false;
          }
          if (!areEquivalent(a[i], b[i], problemPath)) {
            return false;
          }
          if (problemPath) {
            var problemPathTail = problemPath.pop();
            if (problemPathTail !== i) {
              throw new Error("" + problemPathTail);
            }
          }
        }
        return true;
      }
      function objectsAreEquivalent(a, b, problemPath) {
        isObject3.assert(a);
        if (!isObject3.check(b)) {
          return false;
        }
        if (a.type !== b.type) {
          if (problemPath) {
            problemPath.push("type");
          }
          return false;
        }
        var aNames = getFieldNames(a);
        var aNameCount = aNames.length;
        var bNames = getFieldNames(b);
        var bNameCount = bNames.length;
        if (aNameCount === bNameCount) {
          for (var i = 0; i < aNameCount; ++i) {
            var name = aNames[i];
            var aChild = getFieldValue(a, name);
            var bChild = getFieldValue(b, name);
            if (problemPath) {
              problemPath.push(name);
            }
            if (!areEquivalent(aChild, bChild, problemPath)) {
              return false;
            }
            if (problemPath) {
              var problemPathTail = problemPath.pop();
              if (problemPathTail !== name) {
                throw new Error("" + problemPathTail);
              }
            }
          }
          return true;
        }
        if (!problemPath) {
          return false;
        }
        var seenNames = /* @__PURE__ */ Object.create(null);
        for (i = 0; i < aNameCount; ++i) {
          seenNames[aNames[i]] = true;
        }
        for (i = 0; i < bNameCount; ++i) {
          name = bNames[i];
          if (!hasOwn.call(seenNames, name)) {
            problemPath.push(name);
            return false;
          }
          delete seenNames[name];
        }
        for (name in seenNames) {
          problemPath.push(name);
          break;
        }
        return false;
      }
      return astNodesAreEquivalent;
    }
    exports2.default = default_1;
    module2.exports = exports2["default"];
  }
});

// ../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/fork.js
var require_fork = __commonJS({
  "../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/fork.js"(exports2, module2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var types_1 = tslib_1.__importDefault(require_types());
    var path_visitor_1 = tslib_1.__importDefault(require_path_visitor());
    var equiv_1 = tslib_1.__importDefault(require_equiv());
    var path_1 = tslib_1.__importDefault(require_path());
    var node_path_1 = tslib_1.__importDefault(require_node_path());
    function default_1(defs) {
      var fork = createFork();
      var types3 = fork.use(types_1.default);
      defs.forEach(fork.use);
      types3.finalize();
      var PathVisitor = fork.use(path_visitor_1.default);
      return {
        Type: types3.Type,
        builtInTypes: types3.builtInTypes,
        namedTypes: types3.namedTypes,
        builders: types3.builders,
        defineMethod: types3.defineMethod,
        getFieldNames: types3.getFieldNames,
        getFieldValue: types3.getFieldValue,
        eachField: types3.eachField,
        someField: types3.someField,
        getSupertypeNames: types3.getSupertypeNames,
        getBuilderName: types3.getBuilderName,
        astNodesAreEquivalent: fork.use(equiv_1.default),
        finalize: types3.finalize,
        Path: fork.use(path_1.default),
        NodePath: fork.use(node_path_1.default),
        PathVisitor,
        use: fork.use,
        visit: PathVisitor.visit
      };
    }
    exports2.default = default_1;
    function createFork() {
      var used = [];
      var usedResult = [];
      function use(plugin) {
        var idx = used.indexOf(plugin);
        if (idx === -1) {
          idx = used.length;
          used.push(plugin);
          usedResult[idx] = plugin(fork);
        }
        return usedResult[idx];
      }
      var fork = { use };
      return fork;
    }
    module2.exports = exports2["default"];
  }
});

// ../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/lib/shared.js
var require_shared = __commonJS({
  "../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/lib/shared.js"(exports2, module2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var types_1 = tslib_1.__importDefault(require_types());
    function default_1(fork) {
      var types3 = fork.use(types_1.default);
      var Type = types3.Type;
      var builtin = types3.builtInTypes;
      var isNumber = builtin.number;
      function geq(than) {
        return Type.from(function(value) {
          return isNumber.check(value) && value >= than;
        }, isNumber + " >= " + than);
      }
      ;
      var defaults = {
        // Functions were used because (among other reasons) that's the most
        // elegant way to allow for the emptyArray one always to give a new
        // array instance.
        "null": function() {
          return null;
        },
        "emptyArray": function() {
          return [];
        },
        "false": function() {
          return false;
        },
        "true": function() {
          return true;
        },
        "undefined": function() {
        },
        "use strict": function() {
          return "use strict";
        }
      };
      var naiveIsPrimitive = Type.or(builtin.string, builtin.number, builtin.boolean, builtin.null, builtin.undefined);
      var isPrimitive = Type.from(function(value) {
        if (value === null)
          return true;
        var type = typeof value;
        if (type === "object" || type === "function") {
          return false;
        }
        return true;
      }, naiveIsPrimitive.toString());
      return {
        geq,
        defaults,
        isPrimitive
      };
    }
    exports2.default = default_1;
    module2.exports = exports2["default"];
  }
});

// ../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/def/core.js
var require_core = __commonJS({
  "../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/def/core.js"(exports2, module2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var types_1 = tslib_1.__importDefault(require_types());
    var shared_1 = tslib_1.__importDefault(require_shared());
    function default_1(fork) {
      var types3 = fork.use(types_1.default);
      var Type = types3.Type;
      var def = Type.def;
      var or = Type.or;
      var shared = fork.use(shared_1.default);
      var defaults = shared.defaults;
      var geq = shared.geq;
      def("Printable").field("loc", or(def("SourceLocation"), null), defaults["null"], true);
      def("Node").bases("Printable").field("type", String).field("comments", or([def("Comment")], null), defaults["null"], true);
      def("SourceLocation").field("start", def("Position")).field("end", def("Position")).field("source", or(String, null), defaults["null"]);
      def("Position").field("line", geq(1)).field("column", geq(0));
      def("File").bases("Node").build("program", "name").field("program", def("Program")).field("name", or(String, null), defaults["null"]);
      def("Program").bases("Node").build("body").field("body", [def("Statement")]);
      def("Function").bases("Node").field("id", or(def("Identifier"), null), defaults["null"]).field("params", [def("Pattern")]).field("body", def("BlockStatement")).field("generator", Boolean, defaults["false"]).field("async", Boolean, defaults["false"]);
      def("Statement").bases("Node");
      def("EmptyStatement").bases("Statement").build();
      def("BlockStatement").bases("Statement").build("body").field("body", [def("Statement")]);
      def("ExpressionStatement").bases("Statement").build("expression").field("expression", def("Expression"));
      def("IfStatement").bases("Statement").build("test", "consequent", "alternate").field("test", def("Expression")).field("consequent", def("Statement")).field("alternate", or(def("Statement"), null), defaults["null"]);
      def("LabeledStatement").bases("Statement").build("label", "body").field("label", def("Identifier")).field("body", def("Statement"));
      def("BreakStatement").bases("Statement").build("label").field("label", or(def("Identifier"), null), defaults["null"]);
      def("ContinueStatement").bases("Statement").build("label").field("label", or(def("Identifier"), null), defaults["null"]);
      def("WithStatement").bases("Statement").build("object", "body").field("object", def("Expression")).field("body", def("Statement"));
      def("SwitchStatement").bases("Statement").build("discriminant", "cases", "lexical").field("discriminant", def("Expression")).field("cases", [def("SwitchCase")]).field("lexical", Boolean, defaults["false"]);
      def("ReturnStatement").bases("Statement").build("argument").field("argument", or(def("Expression"), null));
      def("ThrowStatement").bases("Statement").build("argument").field("argument", def("Expression"));
      def("TryStatement").bases("Statement").build("block", "handler", "finalizer").field("block", def("BlockStatement")).field("handler", or(def("CatchClause"), null), function() {
        return this.handlers && this.handlers[0] || null;
      }).field("handlers", [def("CatchClause")], function() {
        return this.handler ? [this.handler] : [];
      }, true).field("guardedHandlers", [def("CatchClause")], defaults.emptyArray).field("finalizer", or(def("BlockStatement"), null), defaults["null"]);
      def("CatchClause").bases("Node").build("param", "guard", "body").field("param", or(def("Pattern"), null), defaults["null"]).field("guard", or(def("Expression"), null), defaults["null"]).field("body", def("BlockStatement"));
      def("WhileStatement").bases("Statement").build("test", "body").field("test", def("Expression")).field("body", def("Statement"));
      def("DoWhileStatement").bases("Statement").build("body", "test").field("body", def("Statement")).field("test", def("Expression"));
      def("ForStatement").bases("Statement").build("init", "test", "update", "body").field("init", or(def("VariableDeclaration"), def("Expression"), null)).field("test", or(def("Expression"), null)).field("update", or(def("Expression"), null)).field("body", def("Statement"));
      def("ForInStatement").bases("Statement").build("left", "right", "body").field("left", or(def("VariableDeclaration"), def("Expression"))).field("right", def("Expression")).field("body", def("Statement"));
      def("DebuggerStatement").bases("Statement").build();
      def("Declaration").bases("Statement");
      def("FunctionDeclaration").bases("Function", "Declaration").build("id", "params", "body").field("id", def("Identifier"));
      def("FunctionExpression").bases("Function", "Expression").build("id", "params", "body");
      def("VariableDeclaration").bases("Declaration").build("kind", "declarations").field("kind", or("var", "let", "const")).field("declarations", [def("VariableDeclarator")]);
      def("VariableDeclarator").bases("Node").build("id", "init").field("id", def("Pattern")).field("init", or(def("Expression"), null), defaults["null"]);
      def("Expression").bases("Node");
      def("ThisExpression").bases("Expression").build();
      def("ArrayExpression").bases("Expression").build("elements").field("elements", [or(def("Expression"), null)]);
      def("ObjectExpression").bases("Expression").build("properties").field("properties", [def("Property")]);
      def("Property").bases("Node").build("kind", "key", "value").field("kind", or("init", "get", "set")).field("key", or(def("Literal"), def("Identifier"))).field("value", def("Expression"));
      def("SequenceExpression").bases("Expression").build("expressions").field("expressions", [def("Expression")]);
      var UnaryOperator = or("-", "+", "!", "~", "typeof", "void", "delete");
      def("UnaryExpression").bases("Expression").build("operator", "argument", "prefix").field("operator", UnaryOperator).field("argument", def("Expression")).field("prefix", Boolean, defaults["true"]);
      var BinaryOperator = or(
        "==",
        "!=",
        "===",
        "!==",
        "<",
        "<=",
        ">",
        ">=",
        "<<",
        ">>",
        ">>>",
        "+",
        "-",
        "*",
        "/",
        "%",
        "**",
        "&",
        // TODO Missing from the Parser API.
        "|",
        "^",
        "in",
        "instanceof"
      );
      def("BinaryExpression").bases("Expression").build("operator", "left", "right").field("operator", BinaryOperator).field("left", def("Expression")).field("right", def("Expression"));
      var AssignmentOperator = or("=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "|=", "^=", "&=");
      def("AssignmentExpression").bases("Expression").build("operator", "left", "right").field("operator", AssignmentOperator).field("left", or(def("Pattern"), def("MemberExpression"))).field("right", def("Expression"));
      var UpdateOperator = or("++", "--");
      def("UpdateExpression").bases("Expression").build("operator", "argument", "prefix").field("operator", UpdateOperator).field("argument", def("Expression")).field("prefix", Boolean);
      var LogicalOperator = or("||", "&&");
      def("LogicalExpression").bases("Expression").build("operator", "left", "right").field("operator", LogicalOperator).field("left", def("Expression")).field("right", def("Expression"));
      def("ConditionalExpression").bases("Expression").build("test", "consequent", "alternate").field("test", def("Expression")).field("consequent", def("Expression")).field("alternate", def("Expression"));
      def("NewExpression").bases("Expression").build("callee", "arguments").field("callee", def("Expression")).field("arguments", [def("Expression")]);
      def("CallExpression").bases("Expression").build("callee", "arguments").field("callee", def("Expression")).field("arguments", [def("Expression")]);
      def("MemberExpression").bases("Expression").build("object", "property", "computed").field("object", def("Expression")).field("property", or(def("Identifier"), def("Expression"))).field("computed", Boolean, function() {
        var type = this.property.type;
        if (type === "Literal" || type === "MemberExpression" || type === "BinaryExpression") {
          return true;
        }
        return false;
      });
      def("Pattern").bases("Node");
      def("SwitchCase").bases("Node").build("test", "consequent").field("test", or(def("Expression"), null)).field("consequent", [def("Statement")]);
      def("Identifier").bases("Expression", "Pattern").build("name").field("name", String).field("optional", Boolean, defaults["false"]);
      def("Literal").bases("Expression").build("value").field("value", or(String, Boolean, null, Number, RegExp)).field("regex", or({
        pattern: String,
        flags: String
      }, null), function() {
        if (this.value instanceof RegExp) {
          var flags = "";
          if (this.value.ignoreCase)
            flags += "i";
          if (this.value.multiline)
            flags += "m";
          if (this.value.global)
            flags += "g";
          return {
            pattern: this.value.source,
            flags
          };
        }
        return null;
      });
      def("Comment").bases("Printable").field("value", String).field("leading", Boolean, defaults["true"]).field("trailing", Boolean, defaults["false"]);
    }
    exports2.default = default_1;
    module2.exports = exports2["default"];
  }
});

// ../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/def/es6.js
var require_es6 = __commonJS({
  "../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/def/es6.js"(exports2, module2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var core_1 = tslib_1.__importDefault(require_core());
    var types_1 = tslib_1.__importDefault(require_types());
    var shared_1 = tslib_1.__importDefault(require_shared());
    function default_1(fork) {
      fork.use(core_1.default);
      var types3 = fork.use(types_1.default);
      var def = types3.Type.def;
      var or = types3.Type.or;
      var defaults = fork.use(shared_1.default).defaults;
      def("Function").field("generator", Boolean, defaults["false"]).field("expression", Boolean, defaults["false"]).field("defaults", [or(def("Expression"), null)], defaults.emptyArray).field("rest", or(def("Identifier"), null), defaults["null"]);
      def("RestElement").bases("Pattern").build("argument").field("argument", def("Pattern")).field(
        "typeAnnotation",
        // for Babylon. Flow parser puts it on the identifier
        or(def("TypeAnnotation"), def("TSTypeAnnotation"), null),
        defaults["null"]
      );
      def("SpreadElementPattern").bases("Pattern").build("argument").field("argument", def("Pattern"));
      def("FunctionDeclaration").build("id", "params", "body", "generator", "expression");
      def("FunctionExpression").build("id", "params", "body", "generator", "expression");
      def("ArrowFunctionExpression").bases("Function", "Expression").build("params", "body", "expression").field("id", null, defaults["null"]).field("body", or(def("BlockStatement"), def("Expression"))).field("generator", false, defaults["false"]);
      def("ForOfStatement").bases("Statement").build("left", "right", "body").field("left", or(def("VariableDeclaration"), def("Pattern"))).field("right", def("Expression")).field("body", def("Statement"));
      def("YieldExpression").bases("Expression").build("argument", "delegate").field("argument", or(def("Expression"), null)).field("delegate", Boolean, defaults["false"]);
      def("GeneratorExpression").bases("Expression").build("body", "blocks", "filter").field("body", def("Expression")).field("blocks", [def("ComprehensionBlock")]).field("filter", or(def("Expression"), null));
      def("ComprehensionExpression").bases("Expression").build("body", "blocks", "filter").field("body", def("Expression")).field("blocks", [def("ComprehensionBlock")]).field("filter", or(def("Expression"), null));
      def("ComprehensionBlock").bases("Node").build("left", "right", "each").field("left", def("Pattern")).field("right", def("Expression")).field("each", Boolean);
      def("Property").field("key", or(def("Literal"), def("Identifier"), def("Expression"))).field("value", or(def("Expression"), def("Pattern"))).field("method", Boolean, defaults["false"]).field("shorthand", Boolean, defaults["false"]).field("computed", Boolean, defaults["false"]);
      def("ObjectProperty").field("shorthand", Boolean, defaults["false"]);
      def("PropertyPattern").bases("Pattern").build("key", "pattern").field("key", or(def("Literal"), def("Identifier"), def("Expression"))).field("pattern", def("Pattern")).field("computed", Boolean, defaults["false"]);
      def("ObjectPattern").bases("Pattern").build("properties").field("properties", [or(def("PropertyPattern"), def("Property"))]);
      def("ArrayPattern").bases("Pattern").build("elements").field("elements", [or(def("Pattern"), null)]);
      def("MethodDefinition").bases("Declaration").build("kind", "key", "value", "static").field("kind", or("constructor", "method", "get", "set")).field("key", def("Expression")).field("value", def("Function")).field("computed", Boolean, defaults["false"]).field("static", Boolean, defaults["false"]);
      def("SpreadElement").bases("Node").build("argument").field("argument", def("Expression"));
      def("ArrayExpression").field("elements", [or(def("Expression"), def("SpreadElement"), def("RestElement"), null)]);
      def("NewExpression").field("arguments", [or(def("Expression"), def("SpreadElement"))]);
      def("CallExpression").field("arguments", [or(def("Expression"), def("SpreadElement"))]);
      def("AssignmentPattern").bases("Pattern").build("left", "right").field("left", def("Pattern")).field("right", def("Expression"));
      var ClassBodyElement = or(def("MethodDefinition"), def("VariableDeclarator"), def("ClassPropertyDefinition"), def("ClassProperty"));
      def("ClassProperty").bases("Declaration").build("key").field("key", or(def("Literal"), def("Identifier"), def("Expression"))).field("computed", Boolean, defaults["false"]);
      def("ClassPropertyDefinition").bases("Declaration").build("definition").field("definition", ClassBodyElement);
      def("ClassBody").bases("Declaration").build("body").field("body", [ClassBodyElement]);
      def("ClassDeclaration").bases("Declaration").build("id", "body", "superClass").field("id", or(def("Identifier"), null)).field("body", def("ClassBody")).field("superClass", or(def("Expression"), null), defaults["null"]);
      def("ClassExpression").bases("Expression").build("id", "body", "superClass").field("id", or(def("Identifier"), null), defaults["null"]).field("body", def("ClassBody")).field("superClass", or(def("Expression"), null), defaults["null"]);
      def("Specifier").bases("Node");
      def("ModuleSpecifier").bases("Specifier").field("local", or(def("Identifier"), null), defaults["null"]).field("id", or(def("Identifier"), null), defaults["null"]).field("name", or(def("Identifier"), null), defaults["null"]);
      def("ImportSpecifier").bases("ModuleSpecifier").build("id", "name");
      def("ImportNamespaceSpecifier").bases("ModuleSpecifier").build("id");
      def("ImportDefaultSpecifier").bases("ModuleSpecifier").build("id");
      def("ImportDeclaration").bases("Declaration").build("specifiers", "source", "importKind").field("specifiers", [or(def("ImportSpecifier"), def("ImportNamespaceSpecifier"), def("ImportDefaultSpecifier"))], defaults.emptyArray).field("source", def("Literal")).field("importKind", or("value", "type"), function() {
        return "value";
      });
      def("TaggedTemplateExpression").bases("Expression").build("tag", "quasi").field("tag", def("Expression")).field("quasi", def("TemplateLiteral"));
      def("TemplateLiteral").bases("Expression").build("quasis", "expressions").field("quasis", [def("TemplateElement")]).field("expressions", [def("Expression")]);
      def("TemplateElement").bases("Node").build("value", "tail").field("value", { "cooked": String, "raw": String }).field("tail", Boolean);
    }
    exports2.default = default_1;
    module2.exports = exports2["default"];
  }
});

// ../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/def/es7.js
var require_es7 = __commonJS({
  "../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/def/es7.js"(exports2, module2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var es6_1 = tslib_1.__importDefault(require_es6());
    var types_1 = tslib_1.__importDefault(require_types());
    var shared_1 = tslib_1.__importDefault(require_shared());
    function default_1(fork) {
      fork.use(es6_1.default);
      var types3 = fork.use(types_1.default);
      var def = types3.Type.def;
      var or = types3.Type.or;
      var defaults = fork.use(shared_1.default).defaults;
      def("Function").field("async", Boolean, defaults["false"]);
      def("SpreadProperty").bases("Node").build("argument").field("argument", def("Expression"));
      def("ObjectExpression").field("properties", [or(def("Property"), def("SpreadProperty"), def("SpreadElement"))]);
      def("SpreadPropertyPattern").bases("Pattern").build("argument").field("argument", def("Pattern"));
      def("ObjectPattern").field("properties", [or(def("Property"), def("PropertyPattern"), def("SpreadPropertyPattern"))]);
      def("AwaitExpression").bases("Expression").build("argument", "all").field("argument", or(def("Expression"), null)).field("all", Boolean, defaults["false"]);
    }
    exports2.default = default_1;
    module2.exports = exports2["default"];
  }
});

// ../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/def/es2020.js
var require_es2020 = __commonJS({
  "../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/def/es2020.js"(exports2, module2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var es7_1 = tslib_1.__importDefault(require_es7());
    var types_1 = tslib_1.__importDefault(require_types());
    function default_1(fork) {
      fork.use(es7_1.default);
      var types3 = fork.use(types_1.default);
      var def = types3.Type.def;
      def("ImportExpression").bases("Expression").build("source").field("source", def("Expression"));
    }
    exports2.default = default_1;
    module2.exports = exports2["default"];
  }
});

// ../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/def/jsx.js
var require_jsx = __commonJS({
  "../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/def/jsx.js"(exports2, module2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var es7_1 = tslib_1.__importDefault(require_es7());
    var types_1 = tslib_1.__importDefault(require_types());
    var shared_1 = tslib_1.__importDefault(require_shared());
    function default_1(fork) {
      fork.use(es7_1.default);
      var types3 = fork.use(types_1.default);
      var def = types3.Type.def;
      var or = types3.Type.or;
      var defaults = fork.use(shared_1.default).defaults;
      def("JSXAttribute").bases("Node").build("name", "value").field("name", or(def("JSXIdentifier"), def("JSXNamespacedName"))).field("value", or(
        def("Literal"),
        // attr="value"
        def("JSXExpressionContainer"),
        // attr={value}
        null
        // attr= or just attr
      ), defaults["null"]);
      def("JSXIdentifier").bases("Identifier").build("name").field("name", String);
      def("JSXNamespacedName").bases("Node").build("namespace", "name").field("namespace", def("JSXIdentifier")).field("name", def("JSXIdentifier"));
      def("JSXMemberExpression").bases("MemberExpression").build("object", "property").field("object", or(def("JSXIdentifier"), def("JSXMemberExpression"))).field("property", def("JSXIdentifier")).field("computed", Boolean, defaults.false);
      var JSXElementName = or(def("JSXIdentifier"), def("JSXNamespacedName"), def("JSXMemberExpression"));
      def("JSXSpreadAttribute").bases("Node").build("argument").field("argument", def("Expression"));
      var JSXAttributes = [or(def("JSXAttribute"), def("JSXSpreadAttribute"))];
      def("JSXExpressionContainer").bases("Expression").build("expression").field("expression", def("Expression"));
      def("JSXElement").bases("Expression").build("openingElement", "closingElement", "children").field("openingElement", def("JSXOpeningElement")).field("closingElement", or(def("JSXClosingElement"), null), defaults["null"]).field("children", [or(
        def("JSXElement"),
        def("JSXExpressionContainer"),
        def("JSXFragment"),
        def("JSXText"),
        def("Literal")
        // TODO Esprima should return JSXText instead.
      )], defaults.emptyArray).field("name", JSXElementName, function() {
        return this.openingElement.name;
      }, true).field("selfClosing", Boolean, function() {
        return this.openingElement.selfClosing;
      }, true).field("attributes", JSXAttributes, function() {
        return this.openingElement.attributes;
      }, true);
      def("JSXOpeningElement").bases("Node").build("name", "attributes", "selfClosing").field("name", JSXElementName).field("attributes", JSXAttributes, defaults.emptyArray).field("selfClosing", Boolean, defaults["false"]);
      def("JSXClosingElement").bases("Node").build("name").field("name", JSXElementName);
      def("JSXFragment").bases("Expression").build("openingElement", "closingElement", "children").field("openingElement", def("JSXOpeningFragment")).field("closingElement", def("JSXClosingFragment")).field("children", [or(
        def("JSXElement"),
        def("JSXExpressionContainer"),
        def("JSXFragment"),
        def("JSXText"),
        def("Literal")
        // TODO Esprima should return JSXText instead.
      )], defaults.emptyArray);
      def("JSXOpeningFragment").bases("Node").build();
      def("JSXClosingFragment").bases("Node").build();
      def("JSXText").bases("Literal").build("value").field("value", String);
      def("JSXEmptyExpression").bases("Expression").build();
      def("JSXSpreadChild").bases("Expression").build("expression").field("expression", def("Expression"));
    }
    exports2.default = default_1;
    module2.exports = exports2["default"];
  }
});

// ../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/def/type-annotations.js
var require_type_annotations = __commonJS({
  "../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/def/type-annotations.js"(exports2, module2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var types_1 = tslib_1.__importDefault(require_types());
    var shared_1 = tslib_1.__importDefault(require_shared());
    function default_1(fork) {
      var types3 = fork.use(types_1.default);
      var def = types3.Type.def;
      var or = types3.Type.or;
      var defaults = fork.use(shared_1.default).defaults;
      var TypeAnnotation = or(def("TypeAnnotation"), def("TSTypeAnnotation"), null);
      var TypeParamDecl = or(def("TypeParameterDeclaration"), def("TSTypeParameterDeclaration"), null);
      def("Identifier").field("typeAnnotation", TypeAnnotation, defaults["null"]);
      def("ObjectPattern").field("typeAnnotation", TypeAnnotation, defaults["null"]);
      def("Function").field("returnType", TypeAnnotation, defaults["null"]).field("typeParameters", TypeParamDecl, defaults["null"]);
      def("ClassProperty").build("key", "value", "typeAnnotation", "static").field("value", or(def("Expression"), null)).field("static", Boolean, defaults["false"]).field("typeAnnotation", TypeAnnotation, defaults["null"]);
      [
        "ClassDeclaration",
        "ClassExpression"
      ].forEach(function(typeName) {
        def(typeName).field("typeParameters", TypeParamDecl, defaults["null"]).field("superTypeParameters", or(def("TypeParameterInstantiation"), def("TSTypeParameterInstantiation"), null), defaults["null"]).field("implements", or([def("ClassImplements")], [def("TSExpressionWithTypeArguments")]), defaults.emptyArray);
      });
    }
    exports2.default = default_1;
    module2.exports = exports2["default"];
  }
});

// ../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/def/flow.js
var require_flow = __commonJS({
  "../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/def/flow.js"(exports2, module2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var es7_1 = tslib_1.__importDefault(require_es7());
    var type_annotations_1 = tslib_1.__importDefault(require_type_annotations());
    var types_1 = tslib_1.__importDefault(require_types());
    var shared_1 = tslib_1.__importDefault(require_shared());
    function default_1(fork) {
      fork.use(es7_1.default);
      fork.use(type_annotations_1.default);
      var types3 = fork.use(types_1.default);
      var def = types3.Type.def;
      var or = types3.Type.or;
      var defaults = fork.use(shared_1.default).defaults;
      def("Flow").bases("Node");
      def("FlowType").bases("Flow");
      def("AnyTypeAnnotation").bases("FlowType").build();
      def("EmptyTypeAnnotation").bases("FlowType").build();
      def("MixedTypeAnnotation").bases("FlowType").build();
      def("VoidTypeAnnotation").bases("FlowType").build();
      def("NumberTypeAnnotation").bases("FlowType").build();
      def("NumberLiteralTypeAnnotation").bases("FlowType").build("value", "raw").field("value", Number).field("raw", String);
      def("NumericLiteralTypeAnnotation").bases("FlowType").build("value", "raw").field("value", Number).field("raw", String);
      def("StringTypeAnnotation").bases("FlowType").build();
      def("StringLiteralTypeAnnotation").bases("FlowType").build("value", "raw").field("value", String).field("raw", String);
      def("BooleanTypeAnnotation").bases("FlowType").build();
      def("BooleanLiteralTypeAnnotation").bases("FlowType").build("value", "raw").field("value", Boolean).field("raw", String);
      def("TypeAnnotation").bases("Node").build("typeAnnotation").field("typeAnnotation", def("FlowType"));
      def("NullableTypeAnnotation").bases("FlowType").build("typeAnnotation").field("typeAnnotation", def("FlowType"));
      def("NullLiteralTypeAnnotation").bases("FlowType").build();
      def("NullTypeAnnotation").bases("FlowType").build();
      def("ThisTypeAnnotation").bases("FlowType").build();
      def("ExistsTypeAnnotation").bases("FlowType").build();
      def("ExistentialTypeParam").bases("FlowType").build();
      def("FunctionTypeAnnotation").bases("FlowType").build("params", "returnType", "rest", "typeParameters").field("params", [def("FunctionTypeParam")]).field("returnType", def("FlowType")).field("rest", or(def("FunctionTypeParam"), null)).field("typeParameters", or(def("TypeParameterDeclaration"), null));
      def("FunctionTypeParam").bases("Node").build("name", "typeAnnotation", "optional").field("name", def("Identifier")).field("typeAnnotation", def("FlowType")).field("optional", Boolean);
      def("ArrayTypeAnnotation").bases("FlowType").build("elementType").field("elementType", def("FlowType"));
      def("ObjectTypeAnnotation").bases("FlowType").build("properties", "indexers", "callProperties").field("properties", [
        or(def("ObjectTypeProperty"), def("ObjectTypeSpreadProperty"))
      ]).field("indexers", [def("ObjectTypeIndexer")], defaults.emptyArray).field("callProperties", [def("ObjectTypeCallProperty")], defaults.emptyArray).field("inexact", or(Boolean, void 0), defaults["undefined"]).field("exact", Boolean, defaults["false"]).field("internalSlots", [def("ObjectTypeInternalSlot")], defaults.emptyArray);
      def("Variance").bases("Node").build("kind").field("kind", or("plus", "minus"));
      var LegacyVariance = or(def("Variance"), "plus", "minus", null);
      def("ObjectTypeProperty").bases("Node").build("key", "value", "optional").field("key", or(def("Literal"), def("Identifier"))).field("value", def("FlowType")).field("optional", Boolean).field("variance", LegacyVariance, defaults["null"]);
      def("ObjectTypeIndexer").bases("Node").build("id", "key", "value").field("id", def("Identifier")).field("key", def("FlowType")).field("value", def("FlowType")).field("variance", LegacyVariance, defaults["null"]);
      def("ObjectTypeCallProperty").bases("Node").build("value").field("value", def("FunctionTypeAnnotation")).field("static", Boolean, defaults["false"]);
      def("QualifiedTypeIdentifier").bases("Node").build("qualification", "id").field("qualification", or(def("Identifier"), def("QualifiedTypeIdentifier"))).field("id", def("Identifier"));
      def("GenericTypeAnnotation").bases("FlowType").build("id", "typeParameters").field("id", or(def("Identifier"), def("QualifiedTypeIdentifier"))).field("typeParameters", or(def("TypeParameterInstantiation"), null));
      def("MemberTypeAnnotation").bases("FlowType").build("object", "property").field("object", def("Identifier")).field("property", or(def("MemberTypeAnnotation"), def("GenericTypeAnnotation")));
      def("UnionTypeAnnotation").bases("FlowType").build("types").field("types", [def("FlowType")]);
      def("IntersectionTypeAnnotation").bases("FlowType").build("types").field("types", [def("FlowType")]);
      def("TypeofTypeAnnotation").bases("FlowType").build("argument").field("argument", def("FlowType"));
      def("ObjectTypeSpreadProperty").bases("Node").build("argument").field("argument", def("FlowType"));
      def("ObjectTypeInternalSlot").bases("Node").build("id", "value", "optional", "static", "method").field("id", def("Identifier")).field("value", def("FlowType")).field("optional", Boolean).field("static", Boolean).field("method", Boolean);
      def("TypeParameterDeclaration").bases("Node").build("params").field("params", [def("TypeParameter")]);
      def("TypeParameterInstantiation").bases("Node").build("params").field("params", [def("FlowType")]);
      def("TypeParameter").bases("FlowType").build("name", "variance", "bound").field("name", String).field("variance", LegacyVariance, defaults["null"]).field("bound", or(def("TypeAnnotation"), null), defaults["null"]);
      def("ClassProperty").field("variance", LegacyVariance, defaults["null"]);
      def("ClassImplements").bases("Node").build("id").field("id", def("Identifier")).field("superClass", or(def("Expression"), null), defaults["null"]).field("typeParameters", or(def("TypeParameterInstantiation"), null), defaults["null"]);
      def("InterfaceTypeAnnotation").bases("FlowType").build("body", "extends").field("body", def("ObjectTypeAnnotation")).field("extends", or([def("InterfaceExtends")], null), defaults["null"]);
      def("InterfaceDeclaration").bases("Declaration").build("id", "body", "extends").field("id", def("Identifier")).field("typeParameters", or(def("TypeParameterDeclaration"), null), defaults["null"]).field("body", def("ObjectTypeAnnotation")).field("extends", [def("InterfaceExtends")]);
      def("DeclareInterface").bases("InterfaceDeclaration").build("id", "body", "extends");
      def("InterfaceExtends").bases("Node").build("id").field("id", def("Identifier")).field("typeParameters", or(def("TypeParameterInstantiation"), null), defaults["null"]);
      def("TypeAlias").bases("Declaration").build("id", "typeParameters", "right").field("id", def("Identifier")).field("typeParameters", or(def("TypeParameterDeclaration"), null)).field("right", def("FlowType"));
      def("OpaqueType").bases("Declaration").build("id", "typeParameters", "impltype", "supertype").field("id", def("Identifier")).field("typeParameters", or(def("TypeParameterDeclaration"), null)).field("impltype", def("FlowType")).field("supertype", def("FlowType"));
      def("DeclareTypeAlias").bases("TypeAlias").build("id", "typeParameters", "right");
      def("DeclareOpaqueType").bases("TypeAlias").build("id", "typeParameters", "supertype");
      def("TypeCastExpression").bases("Expression").build("expression", "typeAnnotation").field("expression", def("Expression")).field("typeAnnotation", def("TypeAnnotation"));
      def("TupleTypeAnnotation").bases("FlowType").build("types").field("types", [def("FlowType")]);
      def("DeclareVariable").bases("Statement").build("id").field("id", def("Identifier"));
      def("DeclareFunction").bases("Statement").build("id").field("id", def("Identifier"));
      def("DeclareClass").bases("InterfaceDeclaration").build("id");
      def("DeclareModule").bases("Statement").build("id", "body").field("id", or(def("Identifier"), def("Literal"))).field("body", def("BlockStatement"));
      def("DeclareModuleExports").bases("Statement").build("typeAnnotation").field("typeAnnotation", def("TypeAnnotation"));
      def("DeclareExportDeclaration").bases("Declaration").build("default", "declaration", "specifiers", "source").field("default", Boolean).field("declaration", or(
        def("DeclareVariable"),
        def("DeclareFunction"),
        def("DeclareClass"),
        def("FlowType"),
        // Implies default.
        null
      )).field("specifiers", [or(def("ExportSpecifier"), def("ExportBatchSpecifier"))], defaults.emptyArray).field("source", or(def("Literal"), null), defaults["null"]);
      def("DeclareExportAllDeclaration").bases("Declaration").build("source").field("source", or(def("Literal"), null), defaults["null"]);
      def("FlowPredicate").bases("Flow");
      def("InferredPredicate").bases("FlowPredicate").build();
      def("DeclaredPredicate").bases("FlowPredicate").build("value").field("value", def("Expression"));
      def("CallExpression").field("typeArguments", or(null, def("TypeParameterInstantiation")), defaults["null"]);
      def("NewExpression").field("typeArguments", or(null, def("TypeParameterInstantiation")), defaults["null"]);
    }
    exports2.default = default_1;
    module2.exports = exports2["default"];
  }
});

// ../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/def/esprima.js
var require_esprima2 = __commonJS({
  "../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/def/esprima.js"(exports2, module2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var es7_1 = tslib_1.__importDefault(require_es7());
    var types_1 = tslib_1.__importDefault(require_types());
    var shared_1 = tslib_1.__importDefault(require_shared());
    function default_1(fork) {
      fork.use(es7_1.default);
      var types3 = fork.use(types_1.default);
      var defaults = fork.use(shared_1.default).defaults;
      var def = types3.Type.def;
      var or = types3.Type.or;
      def("VariableDeclaration").field("declarations", [or(
        def("VariableDeclarator"),
        def("Identifier")
        // Esprima deviation.
      )]);
      def("Property").field("value", or(
        def("Expression"),
        def("Pattern")
        // Esprima deviation.
      ));
      def("ArrayPattern").field("elements", [or(def("Pattern"), def("SpreadElement"), null)]);
      def("ObjectPattern").field("properties", [or(
        def("Property"),
        def("PropertyPattern"),
        def("SpreadPropertyPattern"),
        def("SpreadProperty")
        // Used by Esprima.
      )]);
      def("ExportSpecifier").bases("ModuleSpecifier").build("id", "name");
      def("ExportBatchSpecifier").bases("Specifier").build();
      def("ExportDeclaration").bases("Declaration").build("default", "declaration", "specifiers", "source").field("default", Boolean).field("declaration", or(
        def("Declaration"),
        def("Expression"),
        // Implies default.
        null
      )).field("specifiers", [or(def("ExportSpecifier"), def("ExportBatchSpecifier"))], defaults.emptyArray).field("source", or(def("Literal"), null), defaults["null"]);
      def("Block").bases("Comment").build(
        "value",
        /*optional:*/
        "leading",
        "trailing"
      );
      def("Line").bases("Comment").build(
        "value",
        /*optional:*/
        "leading",
        "trailing"
      );
    }
    exports2.default = default_1;
    module2.exports = exports2["default"];
  }
});

// ../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/def/babel-core.js
var require_babel_core = __commonJS({
  "../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/def/babel-core.js"(exports2, module2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var types_1 = tslib_1.__importDefault(require_types());
    var shared_1 = tslib_1.__importDefault(require_shared());
    var es7_1 = tslib_1.__importDefault(require_es7());
    function default_1(fork) {
      fork.use(es7_1.default);
      var types3 = fork.use(types_1.default);
      var defaults = fork.use(shared_1.default).defaults;
      var def = types3.Type.def;
      var or = types3.Type.or;
      def("Noop").bases("Statement").build();
      def("DoExpression").bases("Expression").build("body").field("body", [def("Statement")]);
      def("Super").bases("Expression").build();
      def("BindExpression").bases("Expression").build("object", "callee").field("object", or(def("Expression"), null)).field("callee", def("Expression"));
      def("Decorator").bases("Node").build("expression").field("expression", def("Expression"));
      def("Property").field("decorators", or([def("Decorator")], null), defaults["null"]);
      def("MethodDefinition").field("decorators", or([def("Decorator")], null), defaults["null"]);
      def("MetaProperty").bases("Expression").build("meta", "property").field("meta", def("Identifier")).field("property", def("Identifier"));
      def("ParenthesizedExpression").bases("Expression").build("expression").field("expression", def("Expression"));
      def("ImportSpecifier").bases("ModuleSpecifier").build("imported", "local").field("imported", def("Identifier"));
      def("ImportDefaultSpecifier").bases("ModuleSpecifier").build("local");
      def("ImportNamespaceSpecifier").bases("ModuleSpecifier").build("local");
      def("ExportDefaultDeclaration").bases("Declaration").build("declaration").field("declaration", or(def("Declaration"), def("Expression")));
      def("ExportNamedDeclaration").bases("Declaration").build("declaration", "specifiers", "source").field("declaration", or(def("Declaration"), null)).field("specifiers", [def("ExportSpecifier")], defaults.emptyArray).field("source", or(def("Literal"), null), defaults["null"]);
      def("ExportSpecifier").bases("ModuleSpecifier").build("local", "exported").field("exported", def("Identifier"));
      def("ExportNamespaceSpecifier").bases("Specifier").build("exported").field("exported", def("Identifier"));
      def("ExportDefaultSpecifier").bases("Specifier").build("exported").field("exported", def("Identifier"));
      def("ExportAllDeclaration").bases("Declaration").build("exported", "source").field("exported", or(def("Identifier"), null)).field("source", def("Literal"));
      def("CommentBlock").bases("Comment").build(
        "value",
        /*optional:*/
        "leading",
        "trailing"
      );
      def("CommentLine").bases("Comment").build(
        "value",
        /*optional:*/
        "leading",
        "trailing"
      );
      def("Directive").bases("Node").build("value").field("value", def("DirectiveLiteral"));
      def("DirectiveLiteral").bases("Node", "Expression").build("value").field("value", String, defaults["use strict"]);
      def("InterpreterDirective").bases("Node").build("value").field("value", String);
      def("BlockStatement").bases("Statement").build("body").field("body", [def("Statement")]).field("directives", [def("Directive")], defaults.emptyArray);
      def("Program").bases("Node").build("body").field("body", [def("Statement")]).field("directives", [def("Directive")], defaults.emptyArray).field("interpreter", or(def("InterpreterDirective"), null), defaults["null"]);
      def("StringLiteral").bases("Literal").build("value").field("value", String);
      def("NumericLiteral").bases("Literal").build("value").field("value", Number).field("raw", or(String, null), defaults["null"]).field("extra", {
        rawValue: Number,
        raw: String
      }, function getDefault() {
        return {
          rawValue: this.value,
          raw: this.value + ""
        };
      });
      def("BigIntLiteral").bases("Literal").build("value").field("value", or(String, Number)).field("extra", {
        rawValue: String,
        raw: String
      }, function getDefault() {
        return {
          rawValue: String(this.value),
          raw: this.value + "n"
        };
      });
      def("NullLiteral").bases("Literal").build().field("value", null, defaults["null"]);
      def("BooleanLiteral").bases("Literal").build("value").field("value", Boolean);
      def("RegExpLiteral").bases("Literal").build("pattern", "flags").field("pattern", String).field("flags", String).field("value", RegExp, function() {
        return new RegExp(this.pattern, this.flags);
      });
      var ObjectExpressionProperty = or(def("Property"), def("ObjectMethod"), def("ObjectProperty"), def("SpreadProperty"), def("SpreadElement"));
      def("ObjectExpression").bases("Expression").build("properties").field("properties", [ObjectExpressionProperty]);
      def("ObjectMethod").bases("Node", "Function").build("kind", "key", "params", "body", "computed").field("kind", or("method", "get", "set")).field("key", or(def("Literal"), def("Identifier"), def("Expression"))).field("params", [def("Pattern")]).field("body", def("BlockStatement")).field("computed", Boolean, defaults["false"]).field("generator", Boolean, defaults["false"]).field("async", Boolean, defaults["false"]).field(
        "accessibility",
        // TypeScript
        or(def("Literal"), null),
        defaults["null"]
      ).field("decorators", or([def("Decorator")], null), defaults["null"]);
      def("ObjectProperty").bases("Node").build("key", "value").field("key", or(def("Literal"), def("Identifier"), def("Expression"))).field("value", or(def("Expression"), def("Pattern"))).field(
        "accessibility",
        // TypeScript
        or(def("Literal"), null),
        defaults["null"]
      ).field("computed", Boolean, defaults["false"]);
      var ClassBodyElement = or(def("MethodDefinition"), def("VariableDeclarator"), def("ClassPropertyDefinition"), def("ClassProperty"), def("ClassPrivateProperty"), def("ClassMethod"), def("ClassPrivateMethod"));
      def("ClassBody").bases("Declaration").build("body").field("body", [ClassBodyElement]);
      def("ClassMethod").bases("Declaration", "Function").build("kind", "key", "params", "body", "computed", "static").field("key", or(def("Literal"), def("Identifier"), def("Expression")));
      def("ClassPrivateMethod").bases("Declaration", "Function").build("key", "params", "body", "kind", "computed", "static").field("key", def("PrivateName"));
      [
        "ClassMethod",
        "ClassPrivateMethod"
      ].forEach(function(typeName) {
        def(typeName).field("kind", or("get", "set", "method", "constructor"), function() {
          return "method";
        }).field("body", def("BlockStatement")).field("computed", Boolean, defaults["false"]).field("static", or(Boolean, null), defaults["null"]).field("abstract", or(Boolean, null), defaults["null"]).field("access", or("public", "private", "protected", null), defaults["null"]).field("accessibility", or("public", "private", "protected", null), defaults["null"]).field("decorators", or([def("Decorator")], null), defaults["null"]).field("optional", or(Boolean, null), defaults["null"]);
      });
      def("ClassPrivateProperty").bases("ClassProperty").build("key", "value").field("key", def("PrivateName")).field("value", or(def("Expression"), null), defaults["null"]);
      def("PrivateName").bases("Expression", "Pattern").build("id").field("id", def("Identifier"));
      var ObjectPatternProperty = or(
        def("Property"),
        def("PropertyPattern"),
        def("SpreadPropertyPattern"),
        def("SpreadProperty"),
        // Used by Esprima
        def("ObjectProperty"),
        // Babel 6
        def("RestProperty")
        // Babel 6
      );
      def("ObjectPattern").bases("Pattern").build("properties").field("properties", [ObjectPatternProperty]).field("decorators", or([def("Decorator")], null), defaults["null"]);
      def("SpreadProperty").bases("Node").build("argument").field("argument", def("Expression"));
      def("RestProperty").bases("Node").build("argument").field("argument", def("Expression"));
      def("ForAwaitStatement").bases("Statement").build("left", "right", "body").field("left", or(def("VariableDeclaration"), def("Expression"))).field("right", def("Expression")).field("body", def("Statement"));
      def("Import").bases("Expression").build();
    }
    exports2.default = default_1;
    module2.exports = exports2["default"];
  }
});

// ../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/def/babel.js
var require_babel = __commonJS({
  "../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/def/babel.js"(exports2, module2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var babel_core_1 = tslib_1.__importDefault(require_babel_core());
    var flow_1 = tslib_1.__importDefault(require_flow());
    function default_1(fork) {
      fork.use(babel_core_1.default);
      fork.use(flow_1.default);
    }
    exports2.default = default_1;
    module2.exports = exports2["default"];
  }
});

// ../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/def/typescript.js
var require_typescript = __commonJS({
  "../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/def/typescript.js"(exports2, module2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var babel_core_1 = tslib_1.__importDefault(require_babel_core());
    var type_annotations_1 = tslib_1.__importDefault(require_type_annotations());
    var types_1 = tslib_1.__importDefault(require_types());
    var shared_1 = tslib_1.__importDefault(require_shared());
    function default_1(fork) {
      fork.use(babel_core_1.default);
      fork.use(type_annotations_1.default);
      var types3 = fork.use(types_1.default);
      var n = types3.namedTypes;
      var def = types3.Type.def;
      var or = types3.Type.or;
      var defaults = fork.use(shared_1.default).defaults;
      var StringLiteral = types3.Type.from(function(value, deep) {
        if (n.StringLiteral && n.StringLiteral.check(value, deep)) {
          return true;
        }
        if (n.Literal && n.Literal.check(value, deep) && typeof value.value === "string") {
          return true;
        }
        return false;
      }, "StringLiteral");
      def("TSType").bases("Node");
      var TSEntityName = or(def("Identifier"), def("TSQualifiedName"));
      def("TSTypeReference").bases("TSType", "TSHasOptionalTypeParameterInstantiation").build("typeName", "typeParameters").field("typeName", TSEntityName);
      def("TSHasOptionalTypeParameterInstantiation").field("typeParameters", or(def("TSTypeParameterInstantiation"), null), defaults["null"]);
      def("TSHasOptionalTypeParameters").field("typeParameters", or(def("TSTypeParameterDeclaration"), null, void 0), defaults["null"]);
      def("TSHasOptionalTypeAnnotation").field("typeAnnotation", or(def("TSTypeAnnotation"), null), defaults["null"]);
      def("TSQualifiedName").bases("Node").build("left", "right").field("left", TSEntityName).field("right", TSEntityName);
      def("TSAsExpression").bases("Expression", "Pattern").build("expression", "typeAnnotation").field("expression", def("Expression")).field("typeAnnotation", def("TSType")).field("extra", or({ parenthesized: Boolean }, null), defaults["null"]);
      def("TSNonNullExpression").bases("Expression", "Pattern").build("expression").field("expression", def("Expression"));
      [
        "TSAnyKeyword",
        "TSBigIntKeyword",
        "TSBooleanKeyword",
        "TSNeverKeyword",
        "TSNullKeyword",
        "TSNumberKeyword",
        "TSObjectKeyword",
        "TSStringKeyword",
        "TSSymbolKeyword",
        "TSUndefinedKeyword",
        "TSUnknownKeyword",
        "TSVoidKeyword",
        "TSThisType"
      ].forEach(function(keywordType) {
        def(keywordType).bases("TSType").build();
      });
      def("TSArrayType").bases("TSType").build("elementType").field("elementType", def("TSType"));
      def("TSLiteralType").bases("TSType").build("literal").field("literal", or(def("NumericLiteral"), def("StringLiteral"), def("BooleanLiteral"), def("TemplateLiteral"), def("UnaryExpression")));
      [
        "TSUnionType",
        "TSIntersectionType"
      ].forEach(function(typeName) {
        def(typeName).bases("TSType").build("types").field("types", [def("TSType")]);
      });
      def("TSConditionalType").bases("TSType").build("checkType", "extendsType", "trueType", "falseType").field("checkType", def("TSType")).field("extendsType", def("TSType")).field("trueType", def("TSType")).field("falseType", def("TSType"));
      def("TSInferType").bases("TSType").build("typeParameter").field("typeParameter", def("TSTypeParameter"));
      def("TSParenthesizedType").bases("TSType").build("typeAnnotation").field("typeAnnotation", def("TSType"));
      var ParametersType = [or(def("Identifier"), def("RestElement"), def("ArrayPattern"), def("ObjectPattern"))];
      [
        "TSFunctionType",
        "TSConstructorType"
      ].forEach(function(typeName) {
        def(typeName).bases("TSType", "TSHasOptionalTypeParameters", "TSHasOptionalTypeAnnotation").build("parameters").field("parameters", ParametersType);
      });
      def("TSDeclareFunction").bases("Declaration", "TSHasOptionalTypeParameters").build("id", "params", "returnType").field("declare", Boolean, defaults["false"]).field("async", Boolean, defaults["false"]).field("generator", Boolean, defaults["false"]).field("id", or(def("Identifier"), null), defaults["null"]).field("params", [def("Pattern")]).field("returnType", or(
        def("TSTypeAnnotation"),
        def("Noop"),
        // Still used?
        null
      ), defaults["null"]);
      def("TSDeclareMethod").bases("Declaration", "TSHasOptionalTypeParameters").build("key", "params", "returnType").field("async", Boolean, defaults["false"]).field("generator", Boolean, defaults["false"]).field("params", [def("Pattern")]).field("abstract", Boolean, defaults["false"]).field("accessibility", or("public", "private", "protected", void 0), defaults["undefined"]).field("static", Boolean, defaults["false"]).field("computed", Boolean, defaults["false"]).field("optional", Boolean, defaults["false"]).field("key", or(
        def("Identifier"),
        def("StringLiteral"),
        def("NumericLiteral"),
        // Only allowed if .computed is true.
        def("Expression")
      )).field("kind", or("get", "set", "method", "constructor"), function getDefault() {
        return "method";
      }).field(
        "access",
        // Not "accessibility"?
        or("public", "private", "protected", void 0),
        defaults["undefined"]
      ).field("decorators", or([def("Decorator")], null), defaults["null"]).field("returnType", or(
        def("TSTypeAnnotation"),
        def("Noop"),
        // Still used?
        null
      ), defaults["null"]);
      def("TSMappedType").bases("TSType").build("typeParameter", "typeAnnotation").field("readonly", or(Boolean, "+", "-"), defaults["false"]).field("typeParameter", def("TSTypeParameter")).field("optional", or(Boolean, "+", "-"), defaults["false"]).field("typeAnnotation", or(def("TSType"), null), defaults["null"]);
      def("TSTupleType").bases("TSType").build("elementTypes").field("elementTypes", [or(def("TSType"), def("TSNamedTupleMember"))]);
      def("TSNamedTupleMember").bases("TSType").build("label", "elementType", "optional").field("label", def("Identifier")).field("optional", Boolean, defaults["false"]).field("elementType", def("TSType"));
      def("TSRestType").bases("TSType").build("typeAnnotation").field("typeAnnotation", def("TSType"));
      def("TSOptionalType").bases("TSType").build("typeAnnotation").field("typeAnnotation", def("TSType"));
      def("TSIndexedAccessType").bases("TSType").build("objectType", "indexType").field("objectType", def("TSType")).field("indexType", def("TSType"));
      def("TSTypeOperator").bases("TSType").build("operator").field("operator", String).field("typeAnnotation", def("TSType"));
      def("TSTypeAnnotation").bases("Node").build("typeAnnotation").field("typeAnnotation", or(def("TSType"), def("TSTypeAnnotation")));
      def("TSIndexSignature").bases("Declaration", "TSHasOptionalTypeAnnotation").build("parameters", "typeAnnotation").field("parameters", [def("Identifier")]).field("readonly", Boolean, defaults["false"]);
      def("TSPropertySignature").bases("Declaration", "TSHasOptionalTypeAnnotation").build("key", "typeAnnotation", "optional").field("key", def("Expression")).field("computed", Boolean, defaults["false"]).field("readonly", Boolean, defaults["false"]).field("optional", Boolean, defaults["false"]).field("initializer", or(def("Expression"), null), defaults["null"]);
      def("TSMethodSignature").bases("Declaration", "TSHasOptionalTypeParameters", "TSHasOptionalTypeAnnotation").build("key", "parameters", "typeAnnotation").field("key", def("Expression")).field("computed", Boolean, defaults["false"]).field("optional", Boolean, defaults["false"]).field("parameters", ParametersType);
      def("TSTypePredicate").bases("TSTypeAnnotation", "TSType").build("parameterName", "typeAnnotation", "asserts").field("parameterName", or(def("Identifier"), def("TSThisType"))).field("typeAnnotation", or(def("TSTypeAnnotation"), null), defaults["null"]).field("asserts", Boolean, defaults["false"]);
      [
        "TSCallSignatureDeclaration",
        "TSConstructSignatureDeclaration"
      ].forEach(function(typeName) {
        def(typeName).bases("Declaration", "TSHasOptionalTypeParameters", "TSHasOptionalTypeAnnotation").build("parameters", "typeAnnotation").field("parameters", ParametersType);
      });
      def("TSEnumMember").bases("Node").build("id", "initializer").field("id", or(def("Identifier"), StringLiteral)).field("initializer", or(def("Expression"), null), defaults["null"]);
      def("TSTypeQuery").bases("TSType").build("exprName").field("exprName", or(TSEntityName, def("TSImportType")));
      var TSTypeMember = or(def("TSCallSignatureDeclaration"), def("TSConstructSignatureDeclaration"), def("TSIndexSignature"), def("TSMethodSignature"), def("TSPropertySignature"));
      def("TSTypeLiteral").bases("TSType").build("members").field("members", [TSTypeMember]);
      def("TSTypeParameter").bases("Identifier").build("name", "constraint", "default").field("name", String).field("constraint", or(def("TSType"), void 0), defaults["undefined"]).field("default", or(def("TSType"), void 0), defaults["undefined"]);
      def("TSTypeAssertion").bases("Expression", "Pattern").build("typeAnnotation", "expression").field("typeAnnotation", def("TSType")).field("expression", def("Expression")).field("extra", or({ parenthesized: Boolean }, null), defaults["null"]);
      def("TSTypeParameterDeclaration").bases("Declaration").build("params").field("params", [def("TSTypeParameter")]);
      def("TSTypeParameterInstantiation").bases("Node").build("params").field("params", [def("TSType")]);
      def("TSEnumDeclaration").bases("Declaration").build("id", "members").field("id", def("Identifier")).field("const", Boolean, defaults["false"]).field("declare", Boolean, defaults["false"]).field("members", [def("TSEnumMember")]).field("initializer", or(def("Expression"), null), defaults["null"]);
      def("TSTypeAliasDeclaration").bases("Declaration", "TSHasOptionalTypeParameters").build("id", "typeAnnotation").field("id", def("Identifier")).field("declare", Boolean, defaults["false"]).field("typeAnnotation", def("TSType"));
      def("TSModuleBlock").bases("Node").build("body").field("body", [def("Statement")]);
      def("TSModuleDeclaration").bases("Declaration").build("id", "body").field("id", or(StringLiteral, TSEntityName)).field("declare", Boolean, defaults["false"]).field("global", Boolean, defaults["false"]).field("body", or(def("TSModuleBlock"), def("TSModuleDeclaration"), null), defaults["null"]);
      def("TSImportType").bases("TSType", "TSHasOptionalTypeParameterInstantiation").build("argument", "qualifier", "typeParameters").field("argument", StringLiteral).field("qualifier", or(TSEntityName, void 0), defaults["undefined"]);
      def("TSImportEqualsDeclaration").bases("Declaration").build("id", "moduleReference").field("id", def("Identifier")).field("isExport", Boolean, defaults["false"]).field("moduleReference", or(TSEntityName, def("TSExternalModuleReference")));
      def("TSExternalModuleReference").bases("Declaration").build("expression").field("expression", StringLiteral);
      def("TSExportAssignment").bases("Statement").build("expression").field("expression", def("Expression"));
      def("TSNamespaceExportDeclaration").bases("Declaration").build("id").field("id", def("Identifier"));
      def("TSInterfaceBody").bases("Node").build("body").field("body", [TSTypeMember]);
      def("TSExpressionWithTypeArguments").bases("TSType", "TSHasOptionalTypeParameterInstantiation").build("expression", "typeParameters").field("expression", TSEntityName);
      def("TSInterfaceDeclaration").bases("Declaration", "TSHasOptionalTypeParameters").build("id", "body").field("id", TSEntityName).field("declare", Boolean, defaults["false"]).field("extends", or([def("TSExpressionWithTypeArguments")], null), defaults["null"]).field("body", def("TSInterfaceBody"));
      def("TSParameterProperty").bases("Pattern").build("parameter").field("accessibility", or("public", "private", "protected", void 0), defaults["undefined"]).field("readonly", Boolean, defaults["false"]).field("parameter", or(def("Identifier"), def("AssignmentPattern")));
      def("ClassProperty").field(
        "access",
        // Not "accessibility"?
        or("public", "private", "protected", void 0),
        defaults["undefined"]
      );
      def("ClassBody").field("body", [or(
        def("MethodDefinition"),
        def("VariableDeclarator"),
        def("ClassPropertyDefinition"),
        def("ClassProperty"),
        def("ClassPrivateProperty"),
        def("ClassMethod"),
        def("ClassPrivateMethod"),
        // Just need to add these types:
        def("TSDeclareMethod"),
        TSTypeMember
      )]);
    }
    exports2.default = default_1;
    module2.exports = exports2["default"];
  }
});

// ../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/def/es-proposals.js
var require_es_proposals = __commonJS({
  "../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/def/es-proposals.js"(exports2, module2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var types_1 = tslib_1.__importDefault(require_types());
    var shared_1 = tslib_1.__importDefault(require_shared());
    var core_1 = tslib_1.__importDefault(require_core());
    function default_1(fork) {
      fork.use(core_1.default);
      var types3 = fork.use(types_1.default);
      var Type = types3.Type;
      var def = types3.Type.def;
      var or = Type.or;
      var shared = fork.use(shared_1.default);
      var defaults = shared.defaults;
      def("OptionalMemberExpression").bases("MemberExpression").build("object", "property", "computed", "optional").field("optional", Boolean, defaults["true"]);
      def("OptionalCallExpression").bases("CallExpression").build("callee", "arguments", "optional").field("optional", Boolean, defaults["true"]);
      var LogicalOperator = or("||", "&&", "??");
      def("LogicalExpression").field("operator", LogicalOperator);
    }
    exports2.default = default_1;
    module2.exports = exports2["default"];
  }
});

// ../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/gen/namedTypes.js
var require_namedTypes = __commonJS({
  "../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/gen/namedTypes.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.namedTypes = void 0;
    var namedTypes;
    /* @__PURE__ */ (function(namedTypes2) {
    })(namedTypes = exports2.namedTypes || (exports2.namedTypes = {}));
  }
});

// ../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/main.js
var require_main = __commonJS({
  "../../node_modules/.pnpm/ast-types@0.13.4/node_modules/ast-types/main.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.visit = exports2.use = exports2.Type = exports2.someField = exports2.PathVisitor = exports2.Path = exports2.NodePath = exports2.namedTypes = exports2.getSupertypeNames = exports2.getFieldValue = exports2.getFieldNames = exports2.getBuilderName = exports2.finalize = exports2.eachField = exports2.defineMethod = exports2.builtInTypes = exports2.builders = exports2.astNodesAreEquivalent = void 0;
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var fork_1 = tslib_1.__importDefault(require_fork());
    var core_1 = tslib_1.__importDefault(require_core());
    var es6_1 = tslib_1.__importDefault(require_es6());
    var es7_1 = tslib_1.__importDefault(require_es7());
    var es2020_1 = tslib_1.__importDefault(require_es2020());
    var jsx_1 = tslib_1.__importDefault(require_jsx());
    var flow_1 = tslib_1.__importDefault(require_flow());
    var esprima_1 = tslib_1.__importDefault(require_esprima2());
    var babel_1 = tslib_1.__importDefault(require_babel());
    var typescript_1 = tslib_1.__importDefault(require_typescript());
    var es_proposals_1 = tslib_1.__importDefault(require_es_proposals());
    var namedTypes_1 = require_namedTypes();
    Object.defineProperty(exports2, "namedTypes", { enumerable: true, get: function() {
      return namedTypes_1.namedTypes;
    } });
    var _a5 = fork_1.default([
      // This core module of AST types captures ES5 as it is parsed today by
      // git://github.com/ariya/esprima.git#master.
      core_1.default,
      // Feel free to add to or remove from this list of extension modules to
      // configure the precise type hierarchy that you need.
      es6_1.default,
      es7_1.default,
      es2020_1.default,
      jsx_1.default,
      flow_1.default,
      esprima_1.default,
      babel_1.default,
      typescript_1.default,
      es_proposals_1.default
    ]);
    var astNodesAreEquivalent = _a5.astNodesAreEquivalent;
    var builders = _a5.builders;
    var builtInTypes = _a5.builtInTypes;
    var defineMethod = _a5.defineMethod;
    var eachField = _a5.eachField;
    var finalize3 = _a5.finalize;
    var getBuilderName = _a5.getBuilderName;
    var getFieldNames = _a5.getFieldNames;
    var getFieldValue = _a5.getFieldValue;
    var getSupertypeNames = _a5.getSupertypeNames;
    var n = _a5.namedTypes;
    var NodePath = _a5.NodePath;
    var Path = _a5.Path;
    var PathVisitor = _a5.PathVisitor;
    var someField = _a5.someField;
    var Type = _a5.Type;
    var use = _a5.use;
    var visit3 = _a5.visit;
    exports2.astNodesAreEquivalent = astNodesAreEquivalent;
    exports2.builders = builders;
    exports2.builtInTypes = builtInTypes;
    exports2.defineMethod = defineMethod;
    exports2.eachField = eachField;
    exports2.finalize = finalize3;
    exports2.getBuilderName = getBuilderName;
    exports2.getFieldNames = getFieldNames;
    exports2.getFieldValue = getFieldValue;
    exports2.getSupertypeNames = getSupertypeNames;
    exports2.NodePath = NodePath;
    exports2.Path = Path;
    exports2.PathVisitor = PathVisitor;
    exports2.someField = someField;
    exports2.Type = Type;
    exports2.use = use;
    exports2.visit = visit3;
    Object.assign(namedTypes_1.namedTypes, n);
  }
});

// ../../node_modules/.pnpm/degenerator@5.0.1/node_modules/degenerator/dist/degenerator.js
var require_degenerator = __commonJS({
  "../../node_modules/.pnpm/degenerator@5.0.1/node_modules/degenerator/dist/degenerator.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.degenerator = void 0;
    var util_1 = require("util");
    var escodegen_1 = require_escodegen();
    var esprima_1 = require_esprima();
    var ast_types_1 = require_main();
    function degenerator(code, _names) {
      if (!Array.isArray(_names)) {
        throw new TypeError('an array of async function "names" is required');
      }
      const names = _names.slice(0);
      const ast = (0, esprima_1.parseScript)(code);
      let lastNamesLength = 0;
      do {
        lastNamesLength = names.length;
        (0, ast_types_1.visit)(ast, {
          visitVariableDeclaration(path73) {
            if (path73.node.declarations) {
              for (let i = 0; i < path73.node.declarations.length; i++) {
                const declaration = path73.node.declarations[i];
                if (ast_types_1.namedTypes.VariableDeclarator.check(declaration) && ast_types_1.namedTypes.Identifier.check(declaration.init) && ast_types_1.namedTypes.Identifier.check(declaration.id) && checkName(declaration.init.name, names) && !checkName(declaration.id.name, names)) {
                  names.push(declaration.id.name);
                }
              }
            }
            return false;
          },
          visitAssignmentExpression(path73) {
            if (ast_types_1.namedTypes.Identifier.check(path73.node.left) && ast_types_1.namedTypes.Identifier.check(path73.node.right) && checkName(path73.node.right.name, names) && !checkName(path73.node.left.name, names)) {
              names.push(path73.node.left.name);
            }
            return false;
          },
          visitFunction(path73) {
            if (path73.node.id) {
              let shouldDegenerate = false;
              (0, ast_types_1.visit)(path73.node, {
                visitCallExpression(path74) {
                  if (checkNames(path74.node, names)) {
                    shouldDegenerate = true;
                  }
                  return false;
                }
              });
              if (!shouldDegenerate) {
                return false;
              }
              path73.node.async = true;
              if (!checkName(path73.node.id.name, names)) {
                names.push(path73.node.id.name);
              }
            }
            this.traverse(path73);
          }
        });
      } while (lastNamesLength !== names.length);
      (0, ast_types_1.visit)(ast, {
        visitCallExpression(path73) {
          if (checkNames(path73.node, names)) {
            const delegate = false;
            const { name, parent: { node: pNode } } = path73;
            const expr = ast_types_1.builders.awaitExpression(path73.node, delegate);
            if (ast_types_1.namedTypes.CallExpression.check(pNode)) {
              pNode.arguments[name] = expr;
            } else {
              pNode[name] = expr;
            }
          }
          this.traverse(path73);
        }
      });
      return (0, escodegen_1.generate)(ast);
    }
    exports2.degenerator = degenerator;
    function checkNames({ callee }, names) {
      let name;
      if (ast_types_1.namedTypes.Identifier.check(callee)) {
        name = callee.name;
      } else if (ast_types_1.namedTypes.MemberExpression.check(callee)) {
        if (ast_types_1.namedTypes.Identifier.check(callee.object) && ast_types_1.namedTypes.Identifier.check(callee.property)) {
          name = `${callee.object.name}.${callee.property.name}`;
        } else {
          return false;
        }
      } else if (ast_types_1.namedTypes.FunctionExpression.check(callee)) {
        if (callee.id) {
          name = callee.id.name;
        } else {
          return false;
        }
      } else {
        throw new Error(`Don't know how to get name for: ${callee.type}`);
      }
      return checkName(name, names);
    }
    function checkName(name, names) {
      for (let i = 0; i < names.length; i++) {
        const n = names[i];
        if (util_1.types.isRegExp(n)) {
          if (n.test(name)) {
            return true;
          }
        } else if (name === n) {
          return true;
        }
      }
      return false;
    }
  }
});

// ../../node_modules/.pnpm/degenerator@5.0.1/node_modules/degenerator/dist/compile.js
var require_compile = __commonJS({
  "../../node_modules/.pnpm/degenerator@5.0.1/node_modules/degenerator/dist/compile.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.compile = void 0;
    var util_1 = require("util");
    var degenerator_1 = require_degenerator();
    function compile(qjs, code, returnName, options = {}) {
      const compiled = (0, degenerator_1.degenerator)(code, options.names ?? []);
      const vm = qjs.newContext();
      if (options.sandbox) {
        for (const [name, value] of Object.entries(options.sandbox)) {
          if (typeof value !== "function") {
            throw new Error(`Expected a "function" for sandbox property \`${name}\`, but got "${typeof value}"`);
          }
          const fnHandle = vm.newFunction(name, (...args) => {
            const result = value(...args.map((arg) => quickJSHandleToHost(vm, arg)));
            vm.runtime.executePendingJobs();
            return hostToQuickJSHandle(vm, result);
          });
          fnHandle.consume((handle) => vm.setProp(vm.global, name, handle));
        }
      }
      const fnResult = vm.evalCode(`${compiled};${returnName}`, options.filename);
      const fn = vm.unwrapResult(fnResult);
      const t = vm.typeof(fn);
      if (t !== "function") {
        throw new Error(`Expected a "function" named \`${returnName}\` to be defined, but got "${t}"`);
      }
      const r = async function(...args) {
        let promiseHandle;
        let resolvedHandle;
        try {
          const result = vm.callFunction(fn, vm.undefined, ...args.map((arg) => hostToQuickJSHandle(vm, arg)));
          promiseHandle = vm.unwrapResult(result);
          const resolvedResultP = vm.resolvePromise(promiseHandle);
          vm.runtime.executePendingJobs();
          const resolvedResult = await resolvedResultP;
          resolvedHandle = vm.unwrapResult(resolvedResult);
          return quickJSHandleToHost(vm, resolvedHandle);
        } catch (err) {
          if (err && typeof err === "object" && "cause" in err && err.cause) {
            if (typeof err.cause === "object" && "stack" in err.cause && "name" in err.cause && "message" in err.cause && typeof err.cause.stack === "string" && typeof err.cause.name === "string" && typeof err.cause.message === "string") {
              err.cause.stack = `${err.cause.name}: ${err.cause.message}
${err.cause.stack}`;
            }
            throw err.cause;
          }
          throw err;
        } finally {
          promiseHandle?.dispose();
          resolvedHandle?.dispose();
        }
      };
      Object.defineProperty(r, "toString", {
        value: () => compiled,
        enumerable: false
      });
      return r;
    }
    exports2.compile = compile;
    function quickJSHandleToHost(vm, val) {
      return vm.dump(val);
    }
    function hostToQuickJSHandle(vm, val) {
      if (typeof val === "undefined") {
        return vm.undefined;
      } else if (val === null) {
        return vm.null;
      } else if (typeof val === "string") {
        return vm.newString(val);
      } else if (typeof val === "number") {
        return vm.newNumber(val);
      } else if (typeof val === "bigint") {
        return vm.newBigInt(val);
      } else if (typeof val === "boolean") {
        return val ? vm.true : vm.false;
      } else if (util_1.types.isPromise(val)) {
        const promise3 = vm.newPromise();
        promise3.settled.then(vm.runtime.executePendingJobs);
        val.then((r) => {
          promise3.resolve(hostToQuickJSHandle(vm, r));
        }, (err) => {
          promise3.reject(hostToQuickJSHandle(vm, err));
        });
        return promise3.handle;
      } else if (util_1.types.isNativeError(val)) {
        return vm.newError(val);
      }
      throw new Error(`Unsupported value: ${val}`);
    }
  }
});

// ../../node_modules/.pnpm/degenerator@5.0.1/node_modules/degenerator/dist/index.js
var require_dist8 = __commonJS({
  "../../node_modules/.pnpm/degenerator@5.0.1/node_modules/degenerator/dist/index.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __exportStar2 = exports2 && exports2.__exportStar || function(m, exports3) {
      for (var p2 in m) if (p2 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p2)) __createBinding2(exports3, m, p2);
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    __exportStar2(require_degenerator(), exports2);
    __exportStar2(require_compile(), exports2);
  }
});

// ../../node_modules/.pnpm/pac-resolver@7.0.1/node_modules/pac-resolver/dist/dateRange.js
var require_dateRange = __commonJS({
  "../../node_modules/.pnpm/pac-resolver@7.0.1/node_modules/pac-resolver/dist/dateRange.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    function dateRange() {
      return false;
    }
    exports2.default = dateRange;
  }
});

// ../../node_modules/.pnpm/pac-resolver@7.0.1/node_modules/pac-resolver/dist/dnsDomainIs.js
var require_dnsDomainIs = __commonJS({
  "../../node_modules/.pnpm/pac-resolver@7.0.1/node_modules/pac-resolver/dist/dnsDomainIs.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    function dnsDomainIs(host, domain3) {
      host = String(host);
      domain3 = String(domain3);
      return host.substr(domain3.length * -1) === domain3;
    }
    exports2.default = dnsDomainIs;
  }
});

// ../../node_modules/.pnpm/pac-resolver@7.0.1/node_modules/pac-resolver/dist/dnsDomainLevels.js
var require_dnsDomainLevels = __commonJS({
  "../../node_modules/.pnpm/pac-resolver@7.0.1/node_modules/pac-resolver/dist/dnsDomainLevels.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    function dnsDomainLevels(host) {
      const match = String(host).match(/\./g);
      let levels = 0;
      if (match) {
        levels = match.length;
      }
      return levels;
    }
    exports2.default = dnsDomainLevels;
  }
});

// ../../node_modules/.pnpm/pac-resolver@7.0.1/node_modules/pac-resolver/dist/util.js
var require_util3 = __commonJS({
  "../../node_modules/.pnpm/pac-resolver@7.0.1/node_modules/pac-resolver/dist/util.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.isGMT = exports2.dnsLookup = void 0;
    var dns_1 = require("dns");
    function dnsLookup(host, opts) {
      return new Promise((resolve8, reject) => {
        (0, dns_1.lookup)(host, opts, (err, res) => {
          if (err) {
            reject(err);
          } else {
            resolve8(res);
          }
        });
      });
    }
    exports2.dnsLookup = dnsLookup;
    function isGMT(v) {
      return v === "GMT";
    }
    exports2.isGMT = isGMT;
  }
});

// ../../node_modules/.pnpm/pac-resolver@7.0.1/node_modules/pac-resolver/dist/dnsResolve.js
var require_dnsResolve = __commonJS({
  "../../node_modules/.pnpm/pac-resolver@7.0.1/node_modules/pac-resolver/dist/dnsResolve.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var util_1 = require_util3();
    async function dnsResolve(host) {
      const family = 4;
      try {
        const r = await (0, util_1.dnsLookup)(host, { family });
        if (typeof r === "string") {
          return r;
        }
      } catch (err) {
      }
      return null;
    }
    exports2.default = dnsResolve;
  }
});

// ../../node_modules/.pnpm/netmask@2.0.2/node_modules/netmask/lib/netmask.js
var require_netmask = __commonJS({
  "../../node_modules/.pnpm/netmask@2.0.2/node_modules/netmask/lib/netmask.js"(exports2) {
    "use strict";
    (function() {
      var Netmask, atob2, chr, chr0, chrA, chra, ip2long, long2ip;
      long2ip = function(long) {
        var a, b, c2, d;
        a = (long & 255 << 24) >>> 24;
        b = (long & 255 << 16) >>> 16;
        c2 = (long & 255 << 8) >>> 8;
        d = long & 255;
        return [a, b, c2, d].join(".");
      };
      ip2long = function(ip) {
        var b, c2, i, j, n, ref;
        b = [];
        for (i = j = 0; j <= 3; i = ++j) {
          if (ip.length === 0) {
            break;
          }
          if (i > 0) {
            if (ip[0] !== ".") {
              throw new Error("Invalid IP");
            }
            ip = ip.substring(1);
          }
          ref = atob2(ip), n = ref[0], c2 = ref[1];
          ip = ip.substring(c2);
          b.push(n);
        }
        if (ip.length !== 0) {
          throw new Error("Invalid IP");
        }
        switch (b.length) {
          case 1:
            if (b[0] > 4294967295) {
              throw new Error("Invalid IP");
            }
            return b[0] >>> 0;
          case 2:
            if (b[0] > 255 || b[1] > 16777215) {
              throw new Error("Invalid IP");
            }
            return (b[0] << 24 | b[1]) >>> 0;
          case 3:
            if (b[0] > 255 || b[1] > 255 || b[2] > 65535) {
              throw new Error("Invalid IP");
            }
            return (b[0] << 24 | b[1] << 16 | b[2]) >>> 0;
          case 4:
            if (b[0] > 255 || b[1] > 255 || b[2] > 255 || b[3] > 255) {
              throw new Error("Invalid IP");
            }
            return (b[0] << 24 | b[1] << 16 | b[2] << 8 | b[3]) >>> 0;
          default:
            throw new Error("Invalid IP");
        }
      };
      chr = function(b) {
        return b.charCodeAt(0);
      };
      chr0 = chr("0");
      chra = chr("a");
      chrA = chr("A");
      atob2 = function(s) {
        var base, dmax, i, n, start;
        n = 0;
        base = 10;
        dmax = "9";
        i = 0;
        if (s.length > 1 && s[i] === "0") {
          if (s[i + 1] === "x" || s[i + 1] === "X") {
            i += 2;
            base = 16;
          } else if ("0" <= s[i + 1] && s[i + 1] <= "9") {
            i++;
            base = 8;
            dmax = "7";
          }
        }
        start = i;
        while (i < s.length) {
          if ("0" <= s[i] && s[i] <= dmax) {
            n = n * base + (chr(s[i]) - chr0) >>> 0;
          } else if (base === 16) {
            if ("a" <= s[i] && s[i] <= "f") {
              n = n * base + (10 + chr(s[i]) - chra) >>> 0;
            } else if ("A" <= s[i] && s[i] <= "F") {
              n = n * base + (10 + chr(s[i]) - chrA) >>> 0;
            } else {
              break;
            }
          } else {
            break;
          }
          if (n > 4294967295) {
            throw new Error("too large");
          }
          i++;
        }
        if (i === start) {
          throw new Error("empty octet");
        }
        return [n, i];
      };
      Netmask = (function() {
        function Netmask2(net3, mask) {
          var error101, i, j, ref;
          if (typeof net3 !== "string") {
            throw new Error("Missing `net' parameter");
          }
          if (!mask) {
            ref = net3.split("/", 2), net3 = ref[0], mask = ref[1];
          }
          if (!mask) {
            mask = 32;
          }
          if (typeof mask === "string" && mask.indexOf(".") > -1) {
            try {
              this.maskLong = ip2long(mask);
            } catch (error1) {
              error101 = error1;
              throw new Error("Invalid mask: " + mask);
            }
            for (i = j = 32; j >= 0; i = --j) {
              if (this.maskLong === 4294967295 << 32 - i >>> 0) {
                this.bitmask = i;
                break;
              }
            }
          } else if (mask || mask === 0) {
            this.bitmask = parseInt(mask, 10);
            this.maskLong = 0;
            if (this.bitmask > 0) {
              this.maskLong = 4294967295 << 32 - this.bitmask >>> 0;
            }
          } else {
            throw new Error("Invalid mask: empty");
          }
          try {
            this.netLong = (ip2long(net3) & this.maskLong) >>> 0;
          } catch (error1) {
            error101 = error1;
            throw new Error("Invalid net address: " + net3);
          }
          if (!(this.bitmask <= 32)) {
            throw new Error("Invalid mask for ip4: " + mask);
          }
          this.size = Math.pow(2, 32 - this.bitmask);
          this.base = long2ip(this.netLong);
          this.mask = long2ip(this.maskLong);
          this.hostmask = long2ip(~this.maskLong);
          this.first = this.bitmask <= 30 ? long2ip(this.netLong + 1) : this.base;
          this.last = this.bitmask <= 30 ? long2ip(this.netLong + this.size - 2) : long2ip(this.netLong + this.size - 1);
          this.broadcast = this.bitmask <= 30 ? long2ip(this.netLong + this.size - 1) : void 0;
        }
        Netmask2.prototype.contains = function(ip) {
          if (typeof ip === "string" && (ip.indexOf("/") > 0 || ip.split(".").length !== 4)) {
            ip = new Netmask2(ip);
          }
          if (ip instanceof Netmask2) {
            return this.contains(ip.base) && this.contains(ip.broadcast || ip.last);
          } else {
            return (ip2long(ip) & this.maskLong) >>> 0 === (this.netLong & this.maskLong) >>> 0;
          }
        };
        Netmask2.prototype.next = function(count) {
          if (count == null) {
            count = 1;
          }
          return new Netmask2(long2ip(this.netLong + this.size * count), this.mask);
        };
        Netmask2.prototype.forEach = function(fn) {
          var index, lastLong, long;
          long = ip2long(this.first);
          lastLong = ip2long(this.last);
          index = 0;
          while (long <= lastLong) {
            fn(long2ip(long), long, index);
            index++;
            long++;
          }
        };
        Netmask2.prototype.toString = function() {
          return this.base + "/" + this.bitmask;
        };
        return Netmask2;
      })();
      exports2.ip2long = ip2long;
      exports2.long2ip = long2ip;
      exports2.Netmask = Netmask;
    }).call(exports2);
  }
});

// ../../node_modules/.pnpm/pac-resolver@7.0.1/node_modules/pac-resolver/dist/isInNet.js
var require_isInNet = __commonJS({
  "../../node_modules/.pnpm/pac-resolver@7.0.1/node_modules/pac-resolver/dist/isInNet.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var netmask_1 = require_netmask();
    var util_1 = require_util3();
    async function isInNet(host, pattern, mask) {
      const family = 4;
      try {
        const ip = await (0, util_1.dnsLookup)(host, { family });
        if (typeof ip === "string") {
          const netmask = new netmask_1.Netmask(pattern, mask);
          return netmask.contains(ip);
        }
      } catch (err) {
      }
      return false;
    }
    exports2.default = isInNet;
  }
});

// ../../node_modules/.pnpm/pac-resolver@7.0.1/node_modules/pac-resolver/dist/isPlainHostName.js
var require_isPlainHostName = __commonJS({
  "../../node_modules/.pnpm/pac-resolver@7.0.1/node_modules/pac-resolver/dist/isPlainHostName.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    function isPlainHostName(host) {
      return !/\./.test(host);
    }
    exports2.default = isPlainHostName;
  }
});

// ../../node_modules/.pnpm/pac-resolver@7.0.1/node_modules/pac-resolver/dist/isResolvable.js
var require_isResolvable = __commonJS({
  "../../node_modules/.pnpm/pac-resolver@7.0.1/node_modules/pac-resolver/dist/isResolvable.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var util_1 = require_util3();
    async function isResolvable(host) {
      const family = 4;
      try {
        if (await (0, util_1.dnsLookup)(host, { family })) {
          return true;
        }
      } catch (err) {
      }
      return false;
    }
    exports2.default = isResolvable;
  }
});

// ../../node_modules/.pnpm/pac-resolver@7.0.1/node_modules/pac-resolver/dist/localHostOrDomainIs.js
var require_localHostOrDomainIs = __commonJS({
  "../../node_modules/.pnpm/pac-resolver@7.0.1/node_modules/pac-resolver/dist/localHostOrDomainIs.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    function localHostOrDomainIs(host, hostdom) {
      const parts = host.split(".");
      const domparts = hostdom.split(".");
      let matches = true;
      for (let i = 0; i < parts.length; i++) {
        if (parts[i] !== domparts[i]) {
          matches = false;
          break;
        }
      }
      return matches;
    }
    exports2.default = localHostOrDomainIs;
  }
});

// ../../node_modules/.pnpm/pac-resolver@7.0.1/node_modules/pac-resolver/dist/ip.js
var require_ip = __commonJS({
  "../../node_modules/.pnpm/pac-resolver@7.0.1/node_modules/pac-resolver/dist/ip.js"(exports2) {
    "use strict";
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ip = void 0;
    var os_1 = __importDefault2(require("os"));
    exports2.ip = {
      address() {
        const interfaces = os_1.default.networkInterfaces();
        const family = normalizeFamily();
        const all2 = Object.values(interfaces).map((addrs = []) => {
          const addresses = addrs.filter((details) => {
            const detailsFamily = normalizeFamily(details.family);
            if (detailsFamily !== family || exports2.ip.isLoopback(details.address)) {
              return false;
            }
            return true;
          });
          return addresses.length ? addresses[0].address : void 0;
        }).filter(Boolean);
        return !all2.length ? exports2.ip.loopback(family) : all2[0];
      },
      isLoopback(addr) {
        return /^(::f{4}:)?127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/.test(addr) || /^fe80::1$/.test(addr) || /^::1$/.test(addr) || /^::$/.test(addr);
      },
      loopback(family) {
        family = normalizeFamily(family);
        if (family !== "ipv4" && family !== "ipv6") {
          throw new Error("family must be ipv4 or ipv6");
        }
        return family === "ipv4" ? "127.0.0.1" : "fe80::1";
      }
    };
    function normalizeFamily(family) {
      if (family === 4) {
        return "ipv4";
      }
      if (family === 6) {
        return "ipv6";
      }
      return family ? family.toLowerCase() : "ipv4";
    }
  }
});

// ../../node_modules/.pnpm/pac-resolver@7.0.1/node_modules/pac-resolver/dist/myIpAddress.js
var require_myIpAddress = __commonJS({
  "../../node_modules/.pnpm/pac-resolver@7.0.1/node_modules/pac-resolver/dist/myIpAddress.js"(exports2) {
    "use strict";
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    var ip_1 = require_ip();
    var net_1 = __importDefault2(require("net"));
    async function myIpAddress() {
      return new Promise((resolve8, reject) => {
        const socket = net_1.default.connect({ host: "8.8.8.8", port: 53 });
        const onError = () => {
          resolve8(ip_1.ip.address());
        };
        socket.once("error", onError);
        socket.once("connect", () => {
          socket.removeListener("error", onError);
          const addr = socket.address();
          socket.destroy();
          if (typeof addr === "string") {
            resolve8(addr);
          } else if (addr.address) {
            resolve8(addr.address);
          } else {
            reject(new Error("Expected a `string`"));
          }
        });
      });
    }
    exports2.default = myIpAddress;
  }
});

// ../../node_modules/.pnpm/pac-resolver@7.0.1/node_modules/pac-resolver/dist/shExpMatch.js
var require_shExpMatch = __commonJS({
  "../../node_modules/.pnpm/pac-resolver@7.0.1/node_modules/pac-resolver/dist/shExpMatch.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    function shExpMatch(str, shexp) {
      const re = toRegExp(shexp);
      return re.test(str);
    }
    exports2.default = shExpMatch;
    function toRegExp(str) {
      str = String(str).replace(/\./g, "\\.").replace(/\?/g, ".").replace(/\*/g, ".*");
      return new RegExp(`^${str}$`);
    }
  }
});

// ../../node_modules/.pnpm/pac-resolver@7.0.1/node_modules/pac-resolver/dist/timeRange.js
var require_timeRange = __commonJS({
  "../../node_modules/.pnpm/pac-resolver@7.0.1/node_modules/pac-resolver/dist/timeRange.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    function timeRange() {
      const args = Array.prototype.slice.call(arguments);
      const lastArg = args.pop();
      const useGMTzone = lastArg === "GMT";
      const currentDate = /* @__PURE__ */ new Date();
      if (!useGMTzone) {
        args.push(lastArg);
      }
      let result = false;
      const noOfArgs = args.length;
      const numericArgs = args.map((n) => parseInt(n, 10));
      if (noOfArgs === 1) {
        result = getCurrentHour(useGMTzone, currentDate) === numericArgs[0];
      } else if (noOfArgs === 2) {
        const currentHour = getCurrentHour(useGMTzone, currentDate);
        result = numericArgs[0] <= currentHour && currentHour < numericArgs[1];
      } else if (noOfArgs === 4) {
        result = valueInRange(secondsElapsedToday(numericArgs[0], numericArgs[1], 0), secondsElapsedToday(getCurrentHour(useGMTzone, currentDate), getCurrentMinute(useGMTzone, currentDate), 0), secondsElapsedToday(numericArgs[2], numericArgs[3], 59));
      } else if (noOfArgs === 6) {
        result = valueInRange(secondsElapsedToday(numericArgs[0], numericArgs[1], numericArgs[2]), secondsElapsedToday(getCurrentHour(useGMTzone, currentDate), getCurrentMinute(useGMTzone, currentDate), getCurrentSecond(useGMTzone, currentDate)), secondsElapsedToday(numericArgs[3], numericArgs[4], numericArgs[5]));
      }
      return result;
    }
    exports2.default = timeRange;
    function secondsElapsedToday(hh, mm, ss) {
      return hh * 3600 + mm * 60 + ss;
    }
    function getCurrentHour(gmt, currentDate) {
      return gmt ? currentDate.getUTCHours() : currentDate.getHours();
    }
    function getCurrentMinute(gmt, currentDate) {
      return gmt ? currentDate.getUTCMinutes() : currentDate.getMinutes();
    }
    function getCurrentSecond(gmt, currentDate) {
      return gmt ? currentDate.getUTCSeconds() : currentDate.getSeconds();
    }
    function valueInRange(start, value, finish) {
      return start <= value && value <= finish;
    }
  }
});

// ../../node_modules/.pnpm/pac-resolver@7.0.1/node_modules/pac-resolver/dist/weekdayRange.js
var require_weekdayRange = __commonJS({
  "../../node_modules/.pnpm/pac-resolver@7.0.1/node_modules/pac-resolver/dist/weekdayRange.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var util_1 = require_util3();
    var weekdays = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
    function weekdayRange(wd1, wd2, gmt) {
      let useGMTzone = false;
      let wd1Index = -1;
      let wd2Index = -1;
      let wd2IsGmt = false;
      if ((0, util_1.isGMT)(gmt)) {
        useGMTzone = true;
      } else if ((0, util_1.isGMT)(wd2)) {
        useGMTzone = true;
        wd2IsGmt = true;
      }
      wd1Index = weekdays.indexOf(wd1);
      if (!wd2IsGmt && isWeekday(wd2)) {
        wd2Index = weekdays.indexOf(wd2);
      }
      const todaysDay = getTodaysDay(useGMTzone);
      let result;
      if (wd2Index < 0) {
        result = todaysDay === wd1Index;
      } else if (wd1Index <= wd2Index) {
        result = valueInRange(wd1Index, todaysDay, wd2Index);
      } else {
        result = valueInRange(wd1Index, todaysDay, 6) || valueInRange(0, todaysDay, wd2Index);
      }
      return result;
    }
    exports2.default = weekdayRange;
    function getTodaysDay(gmt) {
      return gmt ? (/* @__PURE__ */ new Date()).getUTCDay() : (/* @__PURE__ */ new Date()).getDay();
    }
    function valueInRange(start, value, finish) {
      return start <= value && value <= finish;
    }
    function isWeekday(v) {
      if (!v)
        return false;
      return weekdays.includes(v);
    }
  }
});

// ../../node_modules/.pnpm/pac-resolver@7.0.1/node_modules/pac-resolver/dist/index.js
var require_dist9 = __commonJS({
  "../../node_modules/.pnpm/pac-resolver@7.0.1/node_modules/pac-resolver/dist/index.js"(exports2) {
    "use strict";
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.sandbox = exports2.createPacResolver = void 0;
    var degenerator_1 = require_dist8();
    var dateRange_1 = __importDefault2(require_dateRange());
    var dnsDomainIs_1 = __importDefault2(require_dnsDomainIs());
    var dnsDomainLevels_1 = __importDefault2(require_dnsDomainLevels());
    var dnsResolve_1 = __importDefault2(require_dnsResolve());
    var isInNet_1 = __importDefault2(require_isInNet());
    var isPlainHostName_1 = __importDefault2(require_isPlainHostName());
    var isResolvable_1 = __importDefault2(require_isResolvable());
    var localHostOrDomainIs_1 = __importDefault2(require_localHostOrDomainIs());
    var myIpAddress_1 = __importDefault2(require_myIpAddress());
    var shExpMatch_1 = __importDefault2(require_shExpMatch());
    var timeRange_1 = __importDefault2(require_timeRange());
    var weekdayRange_1 = __importDefault2(require_weekdayRange());
    function createPacResolver(qjs, _str, _opts = {}) {
      const str = Buffer.isBuffer(_str) ? _str.toString("utf8") : _str;
      const context = {
        ...exports2.sandbox,
        ..._opts.sandbox
      };
      const names = Object.keys(context).filter((k) => isAsyncFunction(context[k]));
      const opts = {
        filename: "proxy.pac",
        names,
        ..._opts,
        sandbox: context
      };
      const resolver = (0, degenerator_1.compile)(qjs, str, "FindProxyForURL", opts);
      function FindProxyForURL(url46, _host) {
        const urlObj = typeof url46 === "string" ? new URL(url46) : url46;
        const host = _host || urlObj.hostname;
        if (!host) {
          throw new TypeError("Could not determine `host`");
        }
        return resolver(urlObj.href, host);
      }
      Object.defineProperty(FindProxyForURL, "toString", {
        value: () => resolver.toString(),
        enumerable: false
      });
      return FindProxyForURL;
    }
    exports2.createPacResolver = createPacResolver;
    exports2.sandbox = Object.freeze({
      alert: (message = "") => console.log("%s", message),
      dateRange: dateRange_1.default,
      dnsDomainIs: dnsDomainIs_1.default,
      dnsDomainLevels: dnsDomainLevels_1.default,
      dnsResolve: dnsResolve_1.default,
      isInNet: isInNet_1.default,
      isPlainHostName: isPlainHostName_1.default,
      isResolvable: isResolvable_1.default,
      localHostOrDomainIs: localHostOrDomainIs_1.default,
      myIpAddress: myIpAddress_1.default,
      shExpMatch: shExpMatch_1.default,
      timeRange: timeRange_1.default,
      weekdayRange: weekdayRange_1.default
    });
    function isAsyncFunction(v) {
      if (typeof v !== "function")
        return false;
      if (v.constructor.name === "AsyncFunction")
        return true;
      if (String(v).indexOf("__awaiter(") !== -1)
        return true;
      return Boolean(v.async);
    }
  }
});

// ../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/esmHelpers.js
var require_esmHelpers = __commonJS({
  "../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/esmHelpers.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.unwrapJavascript = exports2.unwrapTypescript = void 0;
    function fakeUnwrapDefault(mod) {
      return mod.default;
    }
    function actualUnwrapDefault(mod) {
      const maybeUnwrap = mod.default;
      return maybeUnwrap ?? mod;
    }
    exports2.unwrapTypescript = actualUnwrapDefault;
    exports2.unwrapJavascript = fakeUnwrapDefault;
  }
});

// ../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/debug.js
var require_debug2 = __commonJS({
  "../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/debug.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.debugLog = exports2.QTS_DEBUG = void 0;
    exports2.QTS_DEBUG = Boolean(typeof process === "object" && process.env.QTS_DEBUG);
    exports2.debugLog = exports2.QTS_DEBUG ? console.log.bind(console) : () => {
    };
  }
});

// ../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/errors.js
var require_errors = __commonJS({
  "../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/errors.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.QuickJSMemoryLeakDetected = exports2.QuickJSAsyncifySuspended = exports2.QuickJSAsyncifyError = exports2.QuickJSNotImplemented = exports2.QuickJSUseAfterFree = exports2.QuickJSWrongOwner = exports2.QuickJSUnwrapError = void 0;
    var QuickJSUnwrapError = class extends Error {
      constructor(cause, context) {
        super(String(cause));
        this.cause = cause;
        this.context = context;
        this.name = "QuickJSUnwrapError";
      }
    };
    exports2.QuickJSUnwrapError = QuickJSUnwrapError;
    var QuickJSWrongOwner = class extends Error {
      constructor() {
        super(...arguments);
        this.name = "QuickJSWrongOwner";
      }
    };
    exports2.QuickJSWrongOwner = QuickJSWrongOwner;
    var QuickJSUseAfterFree = class extends Error {
      constructor() {
        super(...arguments);
        this.name = "QuickJSUseAfterFree";
      }
    };
    exports2.QuickJSUseAfterFree = QuickJSUseAfterFree;
    var QuickJSNotImplemented = class extends Error {
      constructor() {
        super(...arguments);
        this.name = "QuickJSNotImplemented";
      }
    };
    exports2.QuickJSNotImplemented = QuickJSNotImplemented;
    var QuickJSAsyncifyError = class extends Error {
      constructor() {
        super(...arguments);
        this.name = "QuickJSAsyncifyError";
      }
    };
    exports2.QuickJSAsyncifyError = QuickJSAsyncifyError;
    var QuickJSAsyncifySuspended = class extends Error {
      constructor() {
        super(...arguments);
        this.name = "QuickJSAsyncifySuspended";
      }
    };
    exports2.QuickJSAsyncifySuspended = QuickJSAsyncifySuspended;
    var QuickJSMemoryLeakDetected = class extends Error {
      constructor() {
        super(...arguments);
        this.name = "QuickJSMemoryLeakDetected";
      }
    };
    exports2.QuickJSMemoryLeakDetected = QuickJSMemoryLeakDetected;
  }
});

// ../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/asyncify-helpers.js
var require_asyncify_helpers = __commonJS({
  "../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/asyncify-helpers.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.awaitEachYieldedPromise = exports2.maybeAsync = exports2.maybeAsyncFn = void 0;
    function* awaitYield(value) {
      return yield value;
    }
    function awaitYieldOf(generator) {
      return awaitYield(awaitEachYieldedPromise(generator));
    }
    var AwaitYield = awaitYield;
    AwaitYield.of = awaitYieldOf;
    function maybeAsyncFn(that, fn) {
      return (...args) => {
        const generator = fn.call(that, AwaitYield, ...args);
        return awaitEachYieldedPromise(generator);
      };
    }
    exports2.maybeAsyncFn = maybeAsyncFn;
    function maybeAsync(that, startGenerator) {
      const generator = startGenerator.call(that, AwaitYield);
      return awaitEachYieldedPromise(generator);
    }
    exports2.maybeAsync = maybeAsync;
    function awaitEachYieldedPromise(gen) {
      function handleNextStep(step) {
        if (step.done) {
          return step.value;
        }
        if (step.value instanceof Promise) {
          return step.value.then((value) => handleNextStep(gen.next(value)), (error101) => handleNextStep(gen.throw(error101)));
        }
        return handleNextStep(gen.next(step.value));
      }
      return handleNextStep(gen.next());
    }
    exports2.awaitEachYieldedPromise = awaitEachYieldedPromise;
  }
});

// ../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/lifetime.js
var require_lifetime = __commonJS({
  "../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/lifetime.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.Scope = exports2.WeakLifetime = exports2.StaticLifetime = exports2.Lifetime = void 0;
    var asyncify_helpers_1 = require_asyncify_helpers();
    var debug_1 = require_debug2();
    var errors_1 = require_errors();
    var Lifetime = class _Lifetime {
      /**
       * When the Lifetime is disposed, it will call `disposer(_value)`. Use the
       * disposer function to implement whatever cleanup needs to happen at the end
       * of `value`'s lifetime.
       *
       * `_owner` is not used or controlled by the lifetime. It's just metadata for
       * the creator.
       */
      constructor(_value, copier, disposer, _owner) {
        this._value = _value;
        this.copier = copier;
        this.disposer = disposer;
        this._owner = _owner;
        this._alive = true;
        this._constructorStack = debug_1.QTS_DEBUG ? new Error("Lifetime constructed").stack : void 0;
      }
      get alive() {
        return this._alive;
      }
      /**
       * The value this Lifetime protects. You must never retain the value - it
       * may become invalid, leading to memory errors.
       *
       * @throws If the lifetime has been [[dispose]]d already.
       */
      get value() {
        this.assertAlive();
        return this._value;
      }
      get owner() {
        return this._owner;
      }
      get dupable() {
        return !!this.copier;
      }
      /**
       * Create a new handle pointing to the same [[value]].
       */
      dup() {
        this.assertAlive();
        if (!this.copier) {
          throw new Error("Non-dupable lifetime");
        }
        return new _Lifetime(this.copier(this._value), this.copier, this.disposer, this._owner);
      }
      consume(map3) {
        this.assertAlive();
        const result = map3(this);
        this.dispose();
        return result;
      }
      /**
       * Dispose of [[value]] and perform cleanup.
       */
      dispose() {
        this.assertAlive();
        if (this.disposer) {
          this.disposer(this._value);
        }
        this._alive = false;
      }
      assertAlive() {
        if (!this.alive) {
          if (this._constructorStack) {
            throw new errors_1.QuickJSUseAfterFree(`Lifetime not alive
${this._constructorStack}
Lifetime used`);
          }
          throw new errors_1.QuickJSUseAfterFree("Lifetime not alive");
        }
      }
    };
    exports2.Lifetime = Lifetime;
    var StaticLifetime = class extends Lifetime {
      constructor(value, owner) {
        super(value, void 0, void 0, owner);
      }
      // Static lifetime doesn't need a copier to be copiable
      get dupable() {
        return true;
      }
      // Copy returns the same instance.
      dup() {
        return this;
      }
      // Dispose does nothing.
      dispose() {
      }
    };
    exports2.StaticLifetime = StaticLifetime;
    var WeakLifetime = class extends Lifetime {
      constructor(value, copier, disposer, owner) {
        super(value, copier, disposer, owner);
      }
      dispose() {
        this._alive = false;
      }
    };
    exports2.WeakLifetime = WeakLifetime;
    function scopeFinally(scope, blockError) {
      let disposeError;
      try {
        scope.dispose();
      } catch (error101) {
        disposeError = error101;
      }
      if (blockError && disposeError) {
        Object.assign(blockError, {
          message: `${blockError.message}
 Then, failed to dispose scope: ${disposeError.message}`,
          disposeError
        });
        throw blockError;
      }
      if (blockError || disposeError) {
        throw blockError || disposeError;
      }
    }
    var Scope = class _Scope {
      constructor() {
        this._disposables = new Lifetime(/* @__PURE__ */ new Set());
      }
      /**
       * Run `block` with a new Scope instance that will be disposed after the block returns.
       * Inside `block`, call `scope.manage` on each lifetime you create to have the lifetime
       * automatically disposed after the block returns.
       *
       * @warning Do not use with async functions. Instead, use [[withScopeAsync]].
       */
      static withScope(block) {
        const scope = new _Scope();
        let blockError;
        try {
          return block(scope);
        } catch (error101) {
          blockError = error101;
          throw error101;
        } finally {
          scopeFinally(scope, blockError);
        }
      }
      static withScopeMaybeAsync(_this, block) {
        return (0, asyncify_helpers_1.maybeAsync)(void 0, function* (awaited) {
          const scope = new _Scope();
          let blockError;
          try {
            return yield* awaited.of(block.call(_this, awaited, scope));
          } catch (error101) {
            blockError = error101;
            throw error101;
          } finally {
            scopeFinally(scope, blockError);
          }
        });
      }
      /**
       * Run `block` with a new Scope instance that will be disposed after the
       * block's returned promise settles. Inside `block`, call `scope.manage` on each
       * lifetime you create to have the lifetime automatically disposed after the
       * block returns.
       */
      static async withScopeAsync(block) {
        const scope = new _Scope();
        let blockError;
        try {
          return await block(scope);
        } catch (error101) {
          blockError = error101;
          throw error101;
        } finally {
          scopeFinally(scope, blockError);
        }
      }
      /**
       * Track `lifetime` so that it is disposed when this scope is disposed.
       */
      manage(lifetime) {
        this._disposables.value.add(lifetime);
        return lifetime;
      }
      get alive() {
        return this._disposables.alive;
      }
      dispose() {
        const lifetimes = Array.from(this._disposables.value.values()).reverse();
        for (const lifetime of lifetimes) {
          if (lifetime.alive) {
            lifetime.dispose();
          }
        }
        this._disposables.dispose();
      }
    };
    exports2.Scope = Scope;
  }
});

// ../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/deferred-promise.js
var require_deferred_promise = __commonJS({
  "../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/deferred-promise.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.QuickJSDeferredPromise = void 0;
    var QuickJSDeferredPromise = class {
      /**
       * Use [[QuickJSContext.newPromise]] to create a new promise instead of calling
       * this constructor directly.
       * @unstable
       */
      constructor(args) {
        this.resolve = (value) => {
          if (!this.resolveHandle.alive) {
            return;
          }
          this.context.unwrapResult(this.context.callFunction(this.resolveHandle, this.context.undefined, value || this.context.undefined)).dispose();
          this.disposeResolvers();
          this.onSettled();
        };
        this.reject = (value) => {
          if (!this.rejectHandle.alive) {
            return;
          }
          this.context.unwrapResult(this.context.callFunction(this.rejectHandle, this.context.undefined, value || this.context.undefined)).dispose();
          this.disposeResolvers();
          this.onSettled();
        };
        this.dispose = () => {
          if (this.handle.alive) {
            this.handle.dispose();
          }
          this.disposeResolvers();
        };
        this.context = args.context;
        this.owner = args.context.runtime;
        this.handle = args.promiseHandle;
        this.settled = new Promise((resolve8) => {
          this.onSettled = resolve8;
        });
        this.resolveHandle = args.resolveHandle;
        this.rejectHandle = args.rejectHandle;
      }
      get alive() {
        return this.handle.alive || this.resolveHandle.alive || this.rejectHandle.alive;
      }
      disposeResolvers() {
        if (this.resolveHandle.alive) {
          this.resolveHandle.dispose();
        }
        if (this.rejectHandle.alive) {
          this.rejectHandle.dispose();
        }
      }
    };
    exports2.QuickJSDeferredPromise = QuickJSDeferredPromise;
  }
});

// ../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/memory.js
var require_memory = __commonJS({
  "../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/memory.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ModuleMemory = void 0;
    var lifetime_1 = require_lifetime();
    var ModuleMemory = class {
      constructor(module3) {
        this.module = module3;
      }
      toPointerArray(handleArray) {
        const typedArray = new Int32Array(handleArray.map((handle) => handle.value));
        const numBytes = typedArray.length * typedArray.BYTES_PER_ELEMENT;
        const ptr = this.module._malloc(numBytes);
        var heapBytes = new Uint8Array(this.module.HEAPU8.buffer, ptr, numBytes);
        heapBytes.set(new Uint8Array(typedArray.buffer));
        return new lifetime_1.Lifetime(ptr, void 0, (ptr2) => this.module._free(ptr2));
      }
      newMutablePointerArray(length) {
        const zeros = new Int32Array(new Array(length).fill(0));
        const numBytes = zeros.length * zeros.BYTES_PER_ELEMENT;
        const ptr = this.module._malloc(numBytes);
        const typedArray = new Int32Array(this.module.HEAPU8.buffer, ptr, length);
        typedArray.set(zeros);
        return new lifetime_1.Lifetime({ typedArray, ptr }, void 0, (value) => this.module._free(value.ptr));
      }
      newHeapCharPointer(string7) {
        const numBytes = this.module.lengthBytesUTF8(string7) + 1;
        const ptr = this.module._malloc(numBytes);
        this.module.stringToUTF8(string7, ptr, numBytes);
        return new lifetime_1.Lifetime(ptr, void 0, (value) => this.module._free(value));
      }
      consumeHeapCharPointer(ptr) {
        const str = this.module.UTF8ToString(ptr);
        this.module._free(ptr);
        return str;
      }
    };
    exports2.ModuleMemory = ModuleMemory;
  }
});

// ../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/types-ffi.js
var require_types_ffi = __commonJS({
  "../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/types-ffi.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.EvalFlags = exports2.assertSync = void 0;
    function assertSync(fn) {
      return function mustBeSync(...args) {
        const result = fn(...args);
        if (result && typeof result === "object" && result instanceof Promise) {
          throw new Error("Function unexpectedly returned a Promise");
        }
        return result;
      };
    }
    exports2.assertSync = assertSync;
    exports2.EvalFlags = {
      /** global code (default) */
      JS_EVAL_TYPE_GLOBAL: 0 << 0,
      /** module code */
      JS_EVAL_TYPE_MODULE: 1 << 0,
      /** direct call (internal use) */
      JS_EVAL_TYPE_DIRECT: 2 << 0,
      /** indirect call (internal use) */
      JS_EVAL_TYPE_INDIRECT: 3 << 0,
      JS_EVAL_TYPE_MASK: 3 << 0,
      /** force 'strict' mode */
      JS_EVAL_FLAG_STRICT: 1 << 3,
      /** force 'strip' mode */
      JS_EVAL_FLAG_STRIP: 1 << 4,
      /**
       * compile but do not run. The result is an object with a
       * JS_TAG_FUNCTION_BYTECODE or JS_TAG_MODULE tag. It can be executed
       * with JS_EvalFunction().
       */
      JS_EVAL_FLAG_COMPILE_ONLY: 1 << 5,
      /** don't include the stack frames before this eval in the Error() backtraces */
      JS_EVAL_FLAG_BACKTRACE_BARRIER: 1 << 6
    };
  }
});

// ../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/types.js
var require_types2 = __commonJS({
  "../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/types.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.concat = exports2.evalOptionsToFlags = exports2.DefaultIntrinsics = void 0;
    var types_ffi_1 = require_types_ffi();
    exports2.DefaultIntrinsics = /* @__PURE__ */ Symbol("DefaultIntrinsics");
    function evalOptionsToFlags(evalOptions) {
      if (typeof evalOptions === "number") {
        return evalOptions;
      }
      if (evalOptions === void 0) {
        return 0;
      }
      const { type, strict, strip, compileOnly, backtraceBarrier } = evalOptions;
      let flags = 0;
      if (type === "global")
        flags |= types_ffi_1.EvalFlags.JS_EVAL_TYPE_GLOBAL;
      if (type === "module")
        flags |= types_ffi_1.EvalFlags.JS_EVAL_TYPE_MODULE;
      if (strict)
        flags |= types_ffi_1.EvalFlags.JS_EVAL_FLAG_STRICT;
      if (strip)
        flags |= types_ffi_1.EvalFlags.JS_EVAL_FLAG_STRIP;
      if (compileOnly)
        flags |= types_ffi_1.EvalFlags.JS_EVAL_FLAG_COMPILE_ONLY;
      if (backtraceBarrier)
        flags |= types_ffi_1.EvalFlags.JS_EVAL_FLAG_BACKTRACE_BARRIER;
      return flags;
    }
    exports2.evalOptionsToFlags = evalOptionsToFlags;
    function concat(...values) {
      let result = [];
      for (const value of values) {
        if (value !== void 0) {
          result = result.concat(value);
        }
      }
      return result;
    }
    exports2.concat = concat;
  }
});

// ../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/context.js
var require_context = __commonJS({
  "../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/context.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.QuickJSContext = void 0;
    var debug_1 = require_debug2();
    var deferred_promise_1 = require_deferred_promise();
    var errors_1 = require_errors();
    var lifetime_1 = require_lifetime();
    var memory_1 = require_memory();
    var types_1 = require_types2();
    var ContextMemory = class extends memory_1.ModuleMemory {
      /** @private */
      constructor(args) {
        super(args.module);
        this.scope = new lifetime_1.Scope();
        this.copyJSValue = (ptr) => {
          return this.ffi.QTS_DupValuePointer(this.ctx.value, ptr);
        };
        this.freeJSValue = (ptr) => {
          this.ffi.QTS_FreeValuePointer(this.ctx.value, ptr);
        };
        args.ownedLifetimes?.forEach((lifetime) => this.scope.manage(lifetime));
        this.owner = args.owner;
        this.module = args.module;
        this.ffi = args.ffi;
        this.rt = args.rt;
        this.ctx = this.scope.manage(args.ctx);
      }
      get alive() {
        return this.scope.alive;
      }
      dispose() {
        return this.scope.dispose();
      }
      /**
       * Track `lifetime` so that it is disposed when this scope is disposed.
       */
      manage(lifetime) {
        return this.scope.manage(lifetime);
      }
      consumeJSCharPointer(ptr) {
        const str = this.module.UTF8ToString(ptr);
        this.ffi.QTS_FreeCString(this.ctx.value, ptr);
        return str;
      }
      heapValueHandle(ptr) {
        return new lifetime_1.Lifetime(ptr, this.copyJSValue, this.freeJSValue, this.owner);
      }
    };
    var QuickJSContext = class {
      /**
       * Use {@link QuickJS.createVm} to create a QuickJSContext instance.
       */
      constructor(args) {
        this._undefined = void 0;
        this._null = void 0;
        this._false = void 0;
        this._true = void 0;
        this._global = void 0;
        this._BigInt = void 0;
        this.fnNextId = -32768;
        this.fnMaps = /* @__PURE__ */ new Map();
        this.cToHostCallbacks = {
          callFunction: (ctx, this_ptr, argc, argv, fn_id) => {
            if (ctx !== this.ctx.value) {
              throw new Error("QuickJSContext instance received C -> JS call with mismatched ctx");
            }
            const fn = this.getFunction(fn_id);
            if (!fn) {
              throw new Error(`QuickJSContext had no callback with id ${fn_id}`);
            }
            return lifetime_1.Scope.withScopeMaybeAsync(this, function* (awaited, scope) {
              const thisHandle = scope.manage(new lifetime_1.WeakLifetime(this_ptr, this.memory.copyJSValue, this.memory.freeJSValue, this.runtime));
              const argHandles = new Array(argc);
              for (let i = 0; i < argc; i++) {
                const ptr = this.ffi.QTS_ArgvGetJSValueConstPointer(argv, i);
                argHandles[i] = scope.manage(new lifetime_1.WeakLifetime(ptr, this.memory.copyJSValue, this.memory.freeJSValue, this.runtime));
              }
              try {
                const result = yield* awaited(fn.apply(thisHandle, argHandles));
                if (result) {
                  if ("error" in result && result.error) {
                    (0, debug_1.debugLog)("throw error", result.error);
                    throw result.error;
                  }
                  const handle = scope.manage(result instanceof lifetime_1.Lifetime ? result : result.value);
                  return this.ffi.QTS_DupValuePointer(this.ctx.value, handle.value);
                }
                return 0;
              } catch (error101) {
                return this.errorToHandle(error101).consume((errorHandle) => this.ffi.QTS_Throw(this.ctx.value, errorHandle.value));
              }
            });
          }
        };
        this.runtime = args.runtime;
        this.module = args.module;
        this.ffi = args.ffi;
        this.rt = args.rt;
        this.ctx = args.ctx;
        this.memory = new ContextMemory({
          ...args,
          owner: this.runtime
        });
        args.callbacks.setContextCallbacks(this.ctx.value, this.cToHostCallbacks);
        this.dump = this.dump.bind(this);
        this.getString = this.getString.bind(this);
        this.getNumber = this.getNumber.bind(this);
        this.resolvePromise = this.resolvePromise.bind(this);
      }
      // @implement Disposable ----------------------------------------------------
      get alive() {
        return this.memory.alive;
      }
      /**
       * Dispose of this VM's underlying resources.
       *
       * @throws Calling this method without disposing of all created handles
       * will result in an error.
       */
      dispose() {
        this.memory.dispose();
      }
      // Globals ------------------------------------------------------------------
      /**
       * [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined).
       */
      get undefined() {
        if (this._undefined) {
          return this._undefined;
        }
        const ptr = this.ffi.QTS_GetUndefined();
        return this._undefined = new lifetime_1.StaticLifetime(ptr);
      }
      /**
       * [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null).
       */
      get null() {
        if (this._null) {
          return this._null;
        }
        const ptr = this.ffi.QTS_GetNull();
        return this._null = new lifetime_1.StaticLifetime(ptr);
      }
      /**
       * [`true`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/true).
       */
      get true() {
        if (this._true) {
          return this._true;
        }
        const ptr = this.ffi.QTS_GetTrue();
        return this._true = new lifetime_1.StaticLifetime(ptr);
      }
      /**
       * [`false`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/false).
       */
      get false() {
        if (this._false) {
          return this._false;
        }
        const ptr = this.ffi.QTS_GetFalse();
        return this._false = new lifetime_1.StaticLifetime(ptr);
      }
      /**
       * [`global`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects).
       * A handle to the global object inside the interpreter.
       * You can set properties to create global variables.
       */
      get global() {
        if (this._global) {
          return this._global;
        }
        const ptr = this.ffi.QTS_GetGlobalObject(this.ctx.value);
        this.memory.manage(this.memory.heapValueHandle(ptr));
        this._global = new lifetime_1.StaticLifetime(ptr, this.runtime);
        return this._global;
      }
      // New values ---------------------------------------------------------------
      /**
       * Converts a Javascript number into a QuickJS value.
       */
      newNumber(num) {
        return this.memory.heapValueHandle(this.ffi.QTS_NewFloat64(this.ctx.value, num));
      }
      /**
       * Create a QuickJS [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) value.
       */
      newString(str) {
        const ptr = this.memory.newHeapCharPointer(str).consume((charHandle) => this.ffi.QTS_NewString(this.ctx.value, charHandle.value));
        return this.memory.heapValueHandle(ptr);
      }
      /**
       * Create a QuickJS [symbol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) value.
       * No two symbols created with this function will be the same value.
       */
      newUniqueSymbol(description) {
        const key = (typeof description === "symbol" ? description.description : description) ?? "";
        const ptr = this.memory.newHeapCharPointer(key).consume((charHandle) => this.ffi.QTS_NewSymbol(this.ctx.value, charHandle.value, 0));
        return this.memory.heapValueHandle(ptr);
      }
      /**
       * Get a symbol from the [global registry](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry) for the given key.
       * All symbols created with the same key will be the same value.
       */
      newSymbolFor(key) {
        const description = (typeof key === "symbol" ? key.description : key) ?? "";
        const ptr = this.memory.newHeapCharPointer(description).consume((charHandle) => this.ffi.QTS_NewSymbol(this.ctx.value, charHandle.value, 1));
        return this.memory.heapValueHandle(ptr);
      }
      /**
       * Create a QuickJS [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) value.
       */
      newBigInt(num) {
        if (!this._BigInt) {
          const bigIntHandle2 = this.getProp(this.global, "BigInt");
          this.memory.manage(bigIntHandle2);
          this._BigInt = new lifetime_1.StaticLifetime(bigIntHandle2.value, this.runtime);
        }
        const bigIntHandle = this._BigInt;
        const asString = String(num);
        return this.newString(asString).consume((handle) => this.unwrapResult(this.callFunction(bigIntHandle, this.undefined, handle)));
      }
      /**
       * `{}`.
       * Create a new QuickJS [object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer).
       *
       * @param prototype - Like [`Object.create`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create).
       */
      newObject(prototype) {
        if (prototype) {
          this.runtime.assertOwned(prototype);
        }
        const ptr = prototype ? this.ffi.QTS_NewObjectProto(this.ctx.value, prototype.value) : this.ffi.QTS_NewObject(this.ctx.value);
        return this.memory.heapValueHandle(ptr);
      }
      /**
       * `[]`.
       * Create a new QuickJS [array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array).
       */
      newArray() {
        const ptr = this.ffi.QTS_NewArray(this.ctx.value);
        return this.memory.heapValueHandle(ptr);
      }
      newPromise(value) {
        const deferredPromise = lifetime_1.Scope.withScope((scope) => {
          const mutablePointerArray = scope.manage(this.memory.newMutablePointerArray(2));
          const promisePtr = this.ffi.QTS_NewPromiseCapability(this.ctx.value, mutablePointerArray.value.ptr);
          const promiseHandle = this.memory.heapValueHandle(promisePtr);
          const [resolveHandle, rejectHandle] = Array.from(mutablePointerArray.value.typedArray).map((jsvaluePtr) => this.memory.heapValueHandle(jsvaluePtr));
          return new deferred_promise_1.QuickJSDeferredPromise({
            context: this,
            promiseHandle,
            resolveHandle,
            rejectHandle
          });
        });
        if (value && typeof value === "function") {
          value = new Promise(value);
        }
        if (value) {
          Promise.resolve(value).then(deferredPromise.resolve, (error101) => error101 instanceof lifetime_1.Lifetime ? deferredPromise.reject(error101) : this.newError(error101).consume(deferredPromise.reject));
        }
        return deferredPromise;
      }
      /**
       * Convert a Javascript function into a QuickJS function value.
       * See [[VmFunctionImplementation]] for more details.
       *
       * A [[VmFunctionImplementation]] should not free its arguments or its return
       * value. A VmFunctionImplementation should also not retain any references to
       * its return value.
       *
       * To implement an async function, create a promise with [[newPromise]], then
       * return the deferred promise handle from `deferred.handle` from your
       * function implementation:
       *
       * ```
       * const deferred = vm.newPromise()
       * someNativeAsyncFunction().then(deferred.resolve)
       * return deferred.handle
       * ```
       */
      newFunction(name, fn) {
        const fnId = ++this.fnNextId;
        this.setFunction(fnId, fn);
        return this.memory.heapValueHandle(this.ffi.QTS_NewFunction(this.ctx.value, fnId, name));
      }
      newError(error101) {
        const errorHandle = this.memory.heapValueHandle(this.ffi.QTS_NewError(this.ctx.value));
        if (error101 && typeof error101 === "object") {
          if (error101.name !== void 0) {
            this.newString(error101.name).consume((handle) => this.setProp(errorHandle, "name", handle));
          }
          if (error101.message !== void 0) {
            this.newString(error101.message).consume((handle) => this.setProp(errorHandle, "message", handle));
          }
        } else if (typeof error101 === "string") {
          this.newString(error101).consume((handle) => this.setProp(errorHandle, "message", handle));
        } else if (error101 !== void 0) {
          this.newString(String(error101)).consume((handle) => this.setProp(errorHandle, "message", handle));
        }
        return errorHandle;
      }
      // Read values --------------------------------------------------------------
      /**
       * `typeof` operator. **Not** [standards compliant](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof).
       *
       * @remarks
       * Does not support BigInt values correctly.
       */
      typeof(handle) {
        this.runtime.assertOwned(handle);
        return this.memory.consumeHeapCharPointer(this.ffi.QTS_Typeof(this.ctx.value, handle.value));
      }
      /**
       * Converts `handle` into a Javascript number.
       * @returns `NaN` on error, otherwise a `number`.
       */
      getNumber(handle) {
        this.runtime.assertOwned(handle);
        return this.ffi.QTS_GetFloat64(this.ctx.value, handle.value);
      }
      /**
       * Converts `handle` to a Javascript string.
       */
      getString(handle) {
        this.runtime.assertOwned(handle);
        return this.memory.consumeJSCharPointer(this.ffi.QTS_GetString(this.ctx.value, handle.value));
      }
      /**
       * Converts `handle` into a Javascript symbol. If the symbol is in the global
       * registry in the guest, it will be created with Symbol.for on the host.
       */
      getSymbol(handle) {
        this.runtime.assertOwned(handle);
        const key = this.memory.consumeJSCharPointer(this.ffi.QTS_GetSymbolDescriptionOrKey(this.ctx.value, handle.value));
        const isGlobal = this.ffi.QTS_IsGlobalSymbol(this.ctx.value, handle.value);
        return isGlobal ? Symbol.for(key) : Symbol(key);
      }
      /**
       * Converts `handle` to a Javascript bigint.
       */
      getBigInt(handle) {
        this.runtime.assertOwned(handle);
        const asString = this.getString(handle);
        return BigInt(asString);
      }
      /**
       * `Promise.resolve(value)`.
       * Convert a handle containing a Promise-like value inside the VM into an
       * actual promise on the host.
       *
       * @remarks
       * You may need to call [[executePendingJobs]] to ensure that the promise is resolved.
       *
       * @param promiseLikeHandle - A handle to a Promise-like value with a `.then(onSuccess, onError)` method.
       */
      resolvePromise(promiseLikeHandle) {
        this.runtime.assertOwned(promiseLikeHandle);
        const vmResolveResult = lifetime_1.Scope.withScope((scope) => {
          const vmPromise = scope.manage(this.getProp(this.global, "Promise"));
          const vmPromiseResolve = scope.manage(this.getProp(vmPromise, "resolve"));
          return this.callFunction(vmPromiseResolve, vmPromise, promiseLikeHandle);
        });
        if (vmResolveResult.error) {
          return Promise.resolve(vmResolveResult);
        }
        return new Promise((resolve8) => {
          lifetime_1.Scope.withScope((scope) => {
            const resolveHandle = scope.manage(this.newFunction("resolve", (value) => {
              resolve8({ value: value && value.dup() });
            }));
            const rejectHandle = scope.manage(this.newFunction("reject", (error101) => {
              resolve8({ error: error101 && error101.dup() });
            }));
            const promiseHandle = scope.manage(vmResolveResult.value);
            const promiseThenHandle = scope.manage(this.getProp(promiseHandle, "then"));
            this.unwrapResult(this.callFunction(promiseThenHandle, promiseHandle, resolveHandle, rejectHandle)).dispose();
          });
        });
      }
      // Properties ---------------------------------------------------------------
      /**
       * `handle[key]`.
       * Get a property from a JSValue.
       *
       * @param key - The property may be specified as a JSValue handle, or as a
       * Javascript string (which will be converted automatically).
       */
      getProp(handle, key) {
        this.runtime.assertOwned(handle);
        const ptr = this.borrowPropertyKey(key).consume((quickJSKey) => this.ffi.QTS_GetProp(this.ctx.value, handle.value, quickJSKey.value));
        const result = this.memory.heapValueHandle(ptr);
        return result;
      }
      /**
       * `handle[key] = value`.
       * Set a property on a JSValue.
       *
       * @remarks
       * Note that the QuickJS authors recommend using [[defineProp]] to define new
       * properties.
       *
       * @param key - The property may be specified as a JSValue handle, or as a
       * Javascript string or number (which will be converted automatically to a JSValue).
       */
      setProp(handle, key, value) {
        this.runtime.assertOwned(handle);
        this.borrowPropertyKey(key).consume((quickJSKey) => this.ffi.QTS_SetProp(this.ctx.value, handle.value, quickJSKey.value, value.value));
      }
      /**
       * [`Object.defineProperty(handle, key, descriptor)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty).
       *
       * @param key - The property may be specified as a JSValue handle, or as a
       * Javascript string or number (which will be converted automatically to a JSValue).
       */
      defineProp(handle, key, descriptor) {
        this.runtime.assertOwned(handle);
        lifetime_1.Scope.withScope((scope) => {
          const quickJSKey = scope.manage(this.borrowPropertyKey(key));
          const value = descriptor.value || this.undefined;
          const configurable = Boolean(descriptor.configurable);
          const enumerable = Boolean(descriptor.enumerable);
          const hasValue = Boolean(descriptor.value);
          const get = descriptor.get ? scope.manage(this.newFunction(descriptor.get.name, descriptor.get)) : this.undefined;
          const set3 = descriptor.set ? scope.manage(this.newFunction(descriptor.set.name, descriptor.set)) : this.undefined;
          this.ffi.QTS_DefineProp(this.ctx.value, handle.value, quickJSKey.value, value.value, get.value, set3.value, configurable, enumerable, hasValue);
        });
      }
      // Evaluation ---------------------------------------------------------------
      /**
       * [`func.call(thisVal, ...args)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call).
       * Call a JSValue as a function.
       *
       * See [[unwrapResult]], which will throw if the function returned an error, or
       * return the result handle directly. If evaluation returned a handle containing
       * a promise, use [[resolvePromise]] to convert it to a native promise and
       * [[executePendingJobs]] to finish evaluating the promise.
       *
       * @returns A result. If the function threw synchronously, `result.error` be a
       * handle to the exception. Otherwise `result.value` will be a handle to the
       * value.
       */
      callFunction(func, thisVal, ...args) {
        this.runtime.assertOwned(func);
        const resultPtr = this.memory.toPointerArray(args).consume((argsArrayPtr) => this.ffi.QTS_Call(this.ctx.value, func.value, thisVal.value, args.length, argsArrayPtr.value));
        const errorPtr = this.ffi.QTS_ResolveException(this.ctx.value, resultPtr);
        if (errorPtr) {
          this.ffi.QTS_FreeValuePointer(this.ctx.value, resultPtr);
          return { error: this.memory.heapValueHandle(errorPtr) };
        }
        return { value: this.memory.heapValueHandle(resultPtr) };
      }
      /**
       * Like [`eval(code)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Description).
       * Evaluates the Javascript source `code` in the global scope of this VM.
       * When working with async code, you many need to call [[executePendingJobs]]
       * to execute callbacks pending after synchronous evaluation returns.
       *
       * See [[unwrapResult]], which will throw if the function returned an error, or
       * return the result handle directly. If evaluation returned a handle containing
       * a promise, use [[resolvePromise]] to convert it to a native promise and
       * [[executePendingJobs]] to finish evaluating the promise.
       *
       * *Note*: to protect against infinite loops, provide an interrupt handler to
       * [[setInterruptHandler]]. You can use [[shouldInterruptAfterDeadline]] to
       * create a time-based deadline.
       *
       * @returns The last statement's value. If the code threw synchronously,
       * `result.error` will be a handle to the exception. If execution was
       * interrupted, the error will have name `InternalError` and message
       * `interrupted`.
       */
      evalCode(code, filename = "eval.js", options) {
        const detectModule = options === void 0 ? 1 : 0;
        const flags = (0, types_1.evalOptionsToFlags)(options);
        const resultPtr = this.memory.newHeapCharPointer(code).consume((charHandle) => this.ffi.QTS_Eval(this.ctx.value, charHandle.value, filename, detectModule, flags));
        const errorPtr = this.ffi.QTS_ResolveException(this.ctx.value, resultPtr);
        if (errorPtr) {
          this.ffi.QTS_FreeValuePointer(this.ctx.value, resultPtr);
          return { error: this.memory.heapValueHandle(errorPtr) };
        }
        return { value: this.memory.heapValueHandle(resultPtr) };
      }
      /**
       * Throw an error in the VM, interrupted whatever current execution is in progress when execution resumes.
       * @experimental
       */
      throw(error101) {
        return this.errorToHandle(error101).consume((handle) => this.ffi.QTS_Throw(this.ctx.value, handle.value));
      }
      /**
       * @private
       */
      borrowPropertyKey(key) {
        if (typeof key === "number") {
          return this.newNumber(key);
        }
        if (typeof key === "string") {
          return this.newString(key);
        }
        return new lifetime_1.StaticLifetime(key.value, this.runtime);
      }
      /**
       * @private
       */
      getMemory(rt) {
        if (rt === this.rt.value) {
          return this.memory;
        } else {
          throw new Error("Private API. Cannot get memory from a different runtime");
        }
      }
      // Utilities ----------------------------------------------------------------
      /**
       * Dump a JSValue to Javascript in a best-effort fashion.
       * Returns `handle.toString()` if it cannot be serialized to JSON.
       */
      dump(handle) {
        this.runtime.assertOwned(handle);
        const type = this.typeof(handle);
        if (type === "string") {
          return this.getString(handle);
        } else if (type === "number") {
          return this.getNumber(handle);
        } else if (type === "bigint") {
          return this.getBigInt(handle);
        } else if (type === "undefined") {
          return void 0;
        } else if (type === "symbol") {
          return this.getSymbol(handle);
        }
        const str = this.memory.consumeJSCharPointer(this.ffi.QTS_Dump(this.ctx.value, handle.value));
        try {
          return JSON.parse(str);
        } catch (err) {
          return str;
        }
      }
      /**
       * Unwrap a SuccessOrFail result such as a [[VmCallResult]] or a
       * [[ExecutePendingJobsResult]], where the fail branch contains a handle to a QuickJS error value.
       * If the result is a success, returns the value.
       * If the result is an error, converts the error to a native object and throws the error.
       */
      unwrapResult(result) {
        if (result.error) {
          const context = "context" in result.error ? result.error.context : this;
          const cause = result.error.consume((error101) => this.dump(error101));
          if (cause && typeof cause === "object" && typeof cause.message === "string") {
            const { message, name, stack } = cause;
            const exception = new errors_1.QuickJSUnwrapError("");
            const hostStack = exception.stack;
            if (typeof name === "string") {
              exception.name = cause.name;
            }
            if (typeof stack === "string") {
              exception.stack = `${name}: ${message}
${cause.stack}Host: ${hostStack}`;
            }
            Object.assign(exception, { cause, context, message });
            throw exception;
          }
          throw new errors_1.QuickJSUnwrapError(cause, context);
        }
        return result.value;
      }
      /** @private */
      getFunction(fn_id) {
        const map_id = fn_id >> 8;
        const fnMap = this.fnMaps.get(map_id);
        if (!fnMap) {
          return void 0;
        }
        return fnMap.get(fn_id);
      }
      /** @private */
      setFunction(fn_id, handle) {
        const map_id = fn_id >> 8;
        let fnMap = this.fnMaps.get(map_id);
        if (!fnMap) {
          fnMap = /* @__PURE__ */ new Map();
          this.fnMaps.set(map_id, fnMap);
        }
        return fnMap.set(fn_id, handle);
      }
      errorToHandle(error101) {
        if (error101 instanceof lifetime_1.Lifetime) {
          return error101;
        }
        return this.newError(error101);
      }
    };
    exports2.QuickJSContext = QuickJSContext;
  }
});

// ../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/runtime.js
var require_runtime = __commonJS({
  "../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/runtime.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.QuickJSRuntime = void 0;
    var asyncify_helpers_1 = require_asyncify_helpers();
    var context_1 = require_context();
    var debug_1 = require_debug2();
    var errors_1 = require_errors();
    var lifetime_1 = require_lifetime();
    var memory_1 = require_memory();
    var types_1 = require_types2();
    var QuickJSRuntime = class {
      /** @private */
      constructor(args) {
        this.scope = new lifetime_1.Scope();
        this.contextMap = /* @__PURE__ */ new Map();
        this.cToHostCallbacks = {
          shouldInterrupt: (rt) => {
            if (rt !== this.rt.value) {
              throw new Error("QuickJSContext instance received C -> JS interrupt with mismatched rt");
            }
            const fn = this.interruptHandler;
            if (!fn) {
              throw new Error("QuickJSContext had no interrupt handler");
            }
            return fn(this) ? 1 : 0;
          },
          loadModuleSource: (0, asyncify_helpers_1.maybeAsyncFn)(this, function* (awaited, rt, ctx, moduleName) {
            const moduleLoader = this.moduleLoader;
            if (!moduleLoader) {
              throw new Error("Runtime has no module loader");
            }
            if (rt !== this.rt.value) {
              throw new Error("Runtime pointer mismatch");
            }
            const context = this.contextMap.get(ctx) ?? this.newContext({
              contextPointer: ctx
            });
            try {
              const result = yield* awaited(moduleLoader(moduleName, context));
              if (typeof result === "object" && "error" in result && result.error) {
                (0, debug_1.debugLog)("cToHostLoadModule: loader returned error", result.error);
                throw result.error;
              }
              const moduleSource = typeof result === "string" ? result : "value" in result ? result.value : result;
              return this.memory.newHeapCharPointer(moduleSource).value;
            } catch (error101) {
              (0, debug_1.debugLog)("cToHostLoadModule: caught error", error101);
              context.throw(error101);
              return 0;
            }
          }),
          normalizeModule: (0, asyncify_helpers_1.maybeAsyncFn)(this, function* (awaited, rt, ctx, baseModuleName, moduleNameRequest) {
            const moduleNormalizer = this.moduleNormalizer;
            if (!moduleNormalizer) {
              throw new Error("Runtime has no module normalizer");
            }
            if (rt !== this.rt.value) {
              throw new Error("Runtime pointer mismatch");
            }
            const context = this.contextMap.get(ctx) ?? this.newContext({
              /* TODO: Does this happen? Are we responsible for disposing? I don't think so */
              contextPointer: ctx
            });
            try {
              const result = yield* awaited(moduleNormalizer(baseModuleName, moduleNameRequest, context));
              if (typeof result === "object" && "error" in result && result.error) {
                (0, debug_1.debugLog)("cToHostNormalizeModule: normalizer returned error", result.error);
                throw result.error;
              }
              const name = typeof result === "string" ? result : result.value;
              return context.getMemory(this.rt.value).newHeapCharPointer(name).value;
            } catch (error101) {
              (0, debug_1.debugLog)("normalizeModule: caught error", error101);
              context.throw(error101);
              return 0;
            }
          })
        };
        args.ownedLifetimes?.forEach((lifetime) => this.scope.manage(lifetime));
        this.module = args.module;
        this.memory = new memory_1.ModuleMemory(this.module);
        this.ffi = args.ffi;
        this.rt = args.rt;
        this.callbacks = args.callbacks;
        this.scope.manage(this.rt);
        this.callbacks.setRuntimeCallbacks(this.rt.value, this.cToHostCallbacks);
        this.executePendingJobs = this.executePendingJobs.bind(this);
      }
      get alive() {
        return this.scope.alive;
      }
      dispose() {
        return this.scope.dispose();
      }
      newContext(options = {}) {
        if (options.intrinsics && options.intrinsics !== types_1.DefaultIntrinsics) {
          throw new Error("TODO: Custom intrinsics are not supported yet");
        }
        const ctx = new lifetime_1.Lifetime(options.contextPointer || this.ffi.QTS_NewContext(this.rt.value), void 0, (ctx_ptr) => {
          this.contextMap.delete(ctx_ptr);
          this.callbacks.deleteContext(ctx_ptr);
          this.ffi.QTS_FreeContext(ctx_ptr);
        });
        const context = new context_1.QuickJSContext({
          module: this.module,
          ctx,
          ffi: this.ffi,
          rt: this.rt,
          ownedLifetimes: options.ownedLifetimes,
          runtime: this,
          callbacks: this.callbacks
        });
        this.contextMap.set(ctx.value, context);
        return context;
      }
      /**
       * Set the loader for EcmaScript modules requested by any context in this
       * runtime.
       *
       * The loader can be removed with [[removeModuleLoader]].
       */
      setModuleLoader(moduleLoader, moduleNormalizer) {
        this.moduleLoader = moduleLoader;
        this.moduleNormalizer = moduleNormalizer;
        this.ffi.QTS_RuntimeEnableModuleLoader(this.rt.value, this.moduleNormalizer ? 1 : 0);
      }
      /**
       * Remove the the loader set by [[setModuleLoader]]. This disables module loading.
       */
      removeModuleLoader() {
        this.moduleLoader = void 0;
        this.ffi.QTS_RuntimeDisableModuleLoader(this.rt.value);
      }
      // Runtime management -------------------------------------------------------
      /**
       * In QuickJS, promises and async functions create pendingJobs. These do not execute
       * immediately and need to be run by calling [[executePendingJobs]].
       *
       * @return true if there is at least one pendingJob queued up.
       */
      hasPendingJob() {
        return Boolean(this.ffi.QTS_IsJobPending(this.rt.value));
      }
      /**
       * Set a callback which is regularly called by the QuickJS engine when it is
       * executing code. This callback can be used to implement an execution
       * timeout.
       *
       * The interrupt handler can be removed with [[removeInterruptHandler]].
       */
      setInterruptHandler(cb) {
        const prevInterruptHandler = this.interruptHandler;
        this.interruptHandler = cb;
        if (!prevInterruptHandler) {
          this.ffi.QTS_RuntimeEnableInterruptHandler(this.rt.value);
        }
      }
      /**
       * Remove the interrupt handler, if any.
       * See [[setInterruptHandler]].
       */
      removeInterruptHandler() {
        if (this.interruptHandler) {
          this.ffi.QTS_RuntimeDisableInterruptHandler(this.rt.value);
          this.interruptHandler = void 0;
        }
      }
      /**
       * Execute pendingJobs on the runtime until `maxJobsToExecute` jobs are
       * executed (default all pendingJobs), the queue is exhausted, or the runtime
       * encounters an exception.
       *
       * In QuickJS, promises and async functions *inside the runtime* create
       * pendingJobs. These do not execute immediately and need to triggered to run.
       *
       * @param maxJobsToExecute - When negative, run all pending jobs. Otherwise execute
       * at most `maxJobsToExecute` before returning.
       *
       * @return On success, the number of executed jobs. On error, the exception
       * that stopped execution, and the context it occurred in. Note that
       * executePendingJobs will not normally return errors thrown inside async
       * functions or rejected promises. Those errors are available by calling
       * [[resolvePromise]] on the promise handle returned by the async function.
       */
      executePendingJobs(maxJobsToExecute = -1) {
        const ctxPtrOut = this.memory.newMutablePointerArray(1);
        const valuePtr = this.ffi.QTS_ExecutePendingJob(this.rt.value, maxJobsToExecute ?? -1, ctxPtrOut.value.ptr);
        const ctxPtr = ctxPtrOut.value.typedArray[0];
        ctxPtrOut.dispose();
        if (ctxPtr === 0) {
          this.ffi.QTS_FreeValuePointerRuntime(this.rt.value, valuePtr);
          return { value: 0 };
        }
        const context = this.contextMap.get(ctxPtr) ?? this.newContext({
          contextPointer: ctxPtr
        });
        const resultValue = context.getMemory(this.rt.value).heapValueHandle(valuePtr);
        const typeOfRet = context.typeof(resultValue);
        if (typeOfRet === "number") {
          const executedJobs = context.getNumber(resultValue);
          resultValue.dispose();
          return { value: executedJobs };
        } else {
          const error101 = Object.assign(resultValue, { context });
          return {
            error: error101
          };
        }
      }
      /**
       * Set the max memory this runtime can allocate.
       * To remove the limit, set to `-1`.
       */
      setMemoryLimit(limitBytes) {
        if (limitBytes < 0 && limitBytes !== -1) {
          throw new Error("Cannot set memory limit to negative number. To unset, pass -1");
        }
        this.ffi.QTS_RuntimeSetMemoryLimit(this.rt.value, limitBytes);
      }
      /**
       * Compute memory usage for this runtime. Returns the result as a handle to a
       * JSValue object. Use [[QuickJSContext.dump]] to convert to a native object.
       * Calling this method will allocate more memory inside the runtime. The information
       * is accurate as of just before the call to `computeMemoryUsage`.
       * For a human-digestible representation, see [[dumpMemoryUsage]].
       */
      computeMemoryUsage() {
        const serviceContextMemory = this.getSystemContext().getMemory(this.rt.value);
        return serviceContextMemory.heapValueHandle(this.ffi.QTS_RuntimeComputeMemoryUsage(this.rt.value, serviceContextMemory.ctx.value));
      }
      /**
       * @returns a human-readable description of memory usage in this runtime.
       * For programmatic access to this information, see [[computeMemoryUsage]].
       */
      dumpMemoryUsage() {
        return this.memory.consumeHeapCharPointer(this.ffi.QTS_RuntimeDumpMemoryUsage(this.rt.value));
      }
      /**
       * Set the max stack size for this runtime, in bytes.
       * To remove the limit, set to `0`.
       */
      setMaxStackSize(stackSize) {
        if (stackSize < 0) {
          throw new Error("Cannot set memory limit to negative number. To unset, pass 0.");
        }
        this.ffi.QTS_RuntimeSetMaxStackSize(this.rt.value, stackSize);
      }
      /**
       * Assert that `handle` is owned by this runtime.
       * @throws QuickJSWrongOwner if owned by a different runtime.
       */
      assertOwned(handle) {
        if (handle.owner && handle.owner.rt !== this.rt) {
          throw new errors_1.QuickJSWrongOwner(`Handle is not owned by this runtime: ${handle.owner.rt.value} != ${this.rt.value}`);
        }
      }
      getSystemContext() {
        if (!this.context) {
          this.context = this.scope.manage(this.newContext());
        }
        return this.context;
      }
    };
    exports2.QuickJSRuntime = QuickJSRuntime;
  }
});

// ../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/module.js
var require_module = __commonJS({
  "../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/module.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.QuickJSWASMModule = exports2.applyModuleEvalRuntimeOptions = exports2.applyBaseRuntimeOptions = exports2.QuickJSModuleCallbacks = void 0;
    var debug_1 = require_debug2();
    var errors_1 = require_errors();
    var lifetime_1 = require_lifetime();
    var runtime_1 = require_runtime();
    var types_1 = require_types2();
    var QuickJSEmscriptenModuleCallbacks = class {
      constructor(args) {
        this.callFunction = args.callFunction;
        this.shouldInterrupt = args.shouldInterrupt;
        this.loadModuleSource = args.loadModuleSource;
        this.normalizeModule = args.normalizeModule;
      }
    };
    var QuickJSModuleCallbacks = class {
      constructor(module3) {
        this.contextCallbacks = /* @__PURE__ */ new Map();
        this.runtimeCallbacks = /* @__PURE__ */ new Map();
        this.suspendedCount = 0;
        this.cToHostCallbacks = new QuickJSEmscriptenModuleCallbacks({
          callFunction: (asyncify, ctx, this_ptr, argc, argv, fn_id) => this.handleAsyncify(asyncify, () => {
            try {
              const vm = this.contextCallbacks.get(ctx);
              if (!vm) {
                throw new Error(`QuickJSContext(ctx = ${ctx}) not found for C function call "${fn_id}"`);
              }
              return vm.callFunction(ctx, this_ptr, argc, argv, fn_id);
            } catch (error101) {
              console.error("[C to host error: returning null]", error101);
              return 0;
            }
          }),
          shouldInterrupt: (asyncify, rt) => this.handleAsyncify(asyncify, () => {
            try {
              const vm = this.runtimeCallbacks.get(rt);
              if (!vm) {
                throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C interrupt`);
              }
              return vm.shouldInterrupt(rt);
            } catch (error101) {
              console.error("[C to host interrupt: returning error]", error101);
              return 1;
            }
          }),
          loadModuleSource: (asyncify, rt, ctx, moduleName) => this.handleAsyncify(asyncify, () => {
            try {
              const runtimeCallbacks = this.runtimeCallbacks.get(rt);
              if (!runtimeCallbacks) {
                throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C module loader`);
              }
              const loadModule = runtimeCallbacks.loadModuleSource;
              if (!loadModule) {
                throw new Error(`QuickJSRuntime(rt = ${rt}) does not support module loading`);
              }
              return loadModule(rt, ctx, moduleName);
            } catch (error101) {
              console.error("[C to host module loader error: returning null]", error101);
              return 0;
            }
          }),
          normalizeModule: (asyncify, rt, ctx, moduleBaseName, moduleName) => this.handleAsyncify(asyncify, () => {
            try {
              const runtimeCallbacks = this.runtimeCallbacks.get(rt);
              if (!runtimeCallbacks) {
                throw new Error(`QuickJSRuntime(rt = ${rt}) not found for C module loader`);
              }
              const normalizeModule = runtimeCallbacks.normalizeModule;
              if (!normalizeModule) {
                throw new Error(`QuickJSRuntime(rt = ${rt}) does not support module loading`);
              }
              return normalizeModule(rt, ctx, moduleBaseName, moduleName);
            } catch (error101) {
              console.error("[C to host module loader error: returning null]", error101);
              return 0;
            }
          })
        });
        this.module = module3;
        this.module.callbacks = this.cToHostCallbacks;
      }
      setRuntimeCallbacks(rt, callbacks2) {
        this.runtimeCallbacks.set(rt, callbacks2);
      }
      deleteRuntime(rt) {
        this.runtimeCallbacks.delete(rt);
      }
      setContextCallbacks(ctx, callbacks2) {
        this.contextCallbacks.set(ctx, callbacks2);
      }
      deleteContext(ctx) {
        this.contextCallbacks.delete(ctx);
      }
      handleAsyncify(asyncify, fn) {
        if (asyncify) {
          return asyncify.handleSleep((done) => {
            try {
              const result = fn();
              if (!(result instanceof Promise)) {
                (0, debug_1.debugLog)("asyncify.handleSleep: not suspending:", result);
                done(result);
                return;
              }
              if (this.suspended) {
                throw new errors_1.QuickJSAsyncifyError(`Already suspended at: ${this.suspended.stack}
Attempted to suspend at:`);
              } else {
                this.suspended = new errors_1.QuickJSAsyncifySuspended(`(${this.suspendedCount++})`);
                (0, debug_1.debugLog)("asyncify.handleSleep: suspending:", this.suspended);
              }
              result.then((resolvedResult) => {
                this.suspended = void 0;
                (0, debug_1.debugLog)("asyncify.handleSleep: resolved:", resolvedResult);
                done(resolvedResult);
              }, (error101) => {
                (0, debug_1.debugLog)("asyncify.handleSleep: rejected:", error101);
                console.error("QuickJS: cannot handle error in suspended function", error101);
                this.suspended = void 0;
              });
            } catch (error101) {
              (0, debug_1.debugLog)("asyncify.handleSleep: error:", error101);
              this.suspended = void 0;
              throw error101;
            }
          });
        }
        const value = fn();
        if (value instanceof Promise) {
          throw new Error("Promise return value not supported in non-asyncify context.");
        }
        return value;
      }
    };
    exports2.QuickJSModuleCallbacks = QuickJSModuleCallbacks;
    function applyBaseRuntimeOptions(runtime, options) {
      if (options.interruptHandler) {
        runtime.setInterruptHandler(options.interruptHandler);
      }
      if (options.maxStackSizeBytes !== void 0) {
        runtime.setMaxStackSize(options.maxStackSizeBytes);
      }
      if (options.memoryLimitBytes !== void 0) {
        runtime.setMemoryLimit(options.memoryLimitBytes);
      }
    }
    exports2.applyBaseRuntimeOptions = applyBaseRuntimeOptions;
    function applyModuleEvalRuntimeOptions(runtime, options) {
      if (options.moduleLoader) {
        runtime.setModuleLoader(options.moduleLoader);
      }
      if (options.shouldInterrupt) {
        runtime.setInterruptHandler(options.shouldInterrupt);
      }
      if (options.memoryLimitBytes !== void 0) {
        runtime.setMemoryLimit(options.memoryLimitBytes);
      }
      if (options.maxStackSizeBytes !== void 0) {
        runtime.setMaxStackSize(options.maxStackSizeBytes);
      }
    }
    exports2.applyModuleEvalRuntimeOptions = applyModuleEvalRuntimeOptions;
    var QuickJSWASMModule = class {
      /** @private */
      constructor(module3, ffi) {
        this.module = module3;
        this.ffi = ffi;
        this.callbacks = new QuickJSModuleCallbacks(module3);
      }
      /**
       * Create a runtime.
       * Use the runtime to set limits on CPU and memory usage and configure module
       * loading for one or more [[QuickJSContext]]s inside the runtime.
       */
      newRuntime(options = {}) {
        const rt = new lifetime_1.Lifetime(this.ffi.QTS_NewRuntime(), void 0, (rt_ptr) => {
          this.callbacks.deleteRuntime(rt_ptr);
          this.ffi.QTS_FreeRuntime(rt_ptr);
        });
        const runtime = new runtime_1.QuickJSRuntime({
          module: this.module,
          callbacks: this.callbacks,
          ffi: this.ffi,
          rt
        });
        applyBaseRuntimeOptions(runtime, options);
        if (options.moduleLoader) {
          runtime.setModuleLoader(options.moduleLoader);
        }
        return runtime;
      }
      /**
       * A simplified API to create a new [[QuickJSRuntime]] and a
       * [[QuickJSContext]] inside that runtime at the same time. The runtime will
       * be disposed when the context is disposed.
       */
      newContext(options = {}) {
        const runtime = this.newRuntime();
        const context = runtime.newContext({
          ...options,
          ownedLifetimes: (0, types_1.concat)(runtime, options.ownedLifetimes)
        });
        runtime.context = context;
        return context;
      }
      /**
       * One-off evaluate code without needing to create a [[QuickJSRuntime]] or
       * [[QuickJSContext]] explicitly.
       *
       * To protect against infinite loops, use the `shouldInterrupt` option. The
       * [[shouldInterruptAfterDeadline]] function will create a time-based deadline.
       *
       * If you need more control over how the code executes, create a
       * [[QuickJSRuntime]] (with [[newRuntime]]) or a [[QuickJSContext]] (with
       * [[newContext]] or [[QuickJSRuntime.newContext]]), and use its
       * [[QuickJSContext.evalCode]] method.
       *
       * Asynchronous callbacks may not run during the first call to `evalCode`. If
       * you need to work with async code inside QuickJS, create a runtime and use
       * [[QuickJSRuntime.executePendingJobs]].
       *
       * @returns The result is coerced to a native Javascript value using JSON
       * serialization, so properties and values unsupported by JSON will be dropped.
       *
       * @throws If `code` throws during evaluation, the exception will be
       * converted into a native Javascript value and thrown.
       *
       * @throws if `options.shouldInterrupt` interrupted execution, will throw a Error
       * with name `"InternalError"` and  message `"interrupted"`.
       */
      evalCode(code, options = {}) {
        return lifetime_1.Scope.withScope((scope) => {
          const vm = scope.manage(this.newContext());
          applyModuleEvalRuntimeOptions(vm.runtime, options);
          const result = vm.evalCode(code, "eval.js");
          if (options.memoryLimitBytes !== void 0) {
            vm.runtime.setMemoryLimit(-1);
          }
          if (result.error) {
            const error101 = vm.dump(scope.manage(result.error));
            throw error101;
          }
          const value = vm.dump(scope.manage(result.value));
          return value;
        });
      }
      /**
       * Get a low-level interface to the QuickJS functions in this WebAssembly
       * module.
       * @experimental
       * @unstable No warranty is provided with this API. It could change at any time.
       * @private
       */
      getFFI() {
        return this.ffi;
      }
    };
    exports2.QuickJSWASMModule = QuickJSWASMModule;
  }
});

// ../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/context-asyncify.js
var require_context_asyncify = __commonJS({
  "../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/context-asyncify.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.QuickJSAsyncContext = void 0;
    var context_1 = require_context();
    var debug_1 = require_debug2();
    var types_1 = require_types2();
    var QuickJSAsyncContext = class extends context_1.QuickJSContext {
      /**
       * Asyncified version of [[evalCode]].
       */
      async evalCodeAsync(code, filename = "eval.js", options) {
        const detectModule = options === void 0 ? 1 : 0;
        const flags = (0, types_1.evalOptionsToFlags)(options);
        let resultPtr = 0;
        try {
          resultPtr = await this.memory.newHeapCharPointer(code).consume((charHandle) => this.ffi.QTS_Eval_MaybeAsync(this.ctx.value, charHandle.value, filename, detectModule, flags));
        } catch (error101) {
          (0, debug_1.debugLog)("QTS_Eval_MaybeAsync threw", error101);
          throw error101;
        }
        const errorPtr = this.ffi.QTS_ResolveException(this.ctx.value, resultPtr);
        if (errorPtr) {
          this.ffi.QTS_FreeValuePointer(this.ctx.value, resultPtr);
          return { error: this.memory.heapValueHandle(errorPtr) };
        }
        return { value: this.memory.heapValueHandle(resultPtr) };
      }
      /**
       * Similar to [[newFunction]].
       * Convert an async host Javascript function into a synchronous QuickJS function value.
       *
       * Whenever QuickJS calls this function, the VM's stack will be unwound while
       * waiting the async function to complete, and then restored when the returned
       * promise resolves.
       *
       * Asyncified functions must never call other asyncified functions or
       * `import`, even indirectly, because the stack cannot be unwound twice.
       *
       * See [Emscripten's docs on Asyncify](https://emscripten.org/docs/porting/asyncify.html).
       */
      newAsyncifiedFunction(name, fn) {
        return this.newFunction(name, fn);
      }
    };
    exports2.QuickJSAsyncContext = QuickJSAsyncContext;
  }
});

// ../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/runtime-asyncify.js
var require_runtime_asyncify = __commonJS({
  "../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/runtime-asyncify.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.QuickJSAsyncRuntime = void 0;
    var _1 = require_dist10();
    var context_asyncify_1 = require_context_asyncify();
    var runtime_1 = require_runtime();
    var types_1 = require_types2();
    var QuickJSAsyncRuntime = class extends runtime_1.QuickJSRuntime {
      /** @private */
      constructor(args) {
        super(args);
      }
      newContext(options = {}) {
        if (options.intrinsics && options.intrinsics !== types_1.DefaultIntrinsics) {
          throw new Error("TODO: Custom intrinsics are not supported yet");
        }
        const ctx = new _1.Lifetime(this.ffi.QTS_NewContext(this.rt.value), void 0, (ctx_ptr) => {
          this.contextMap.delete(ctx_ptr);
          this.callbacks.deleteContext(ctx_ptr);
          this.ffi.QTS_FreeContext(ctx_ptr);
        });
        const context = new context_asyncify_1.QuickJSAsyncContext({
          module: this.module,
          ctx,
          ffi: this.ffi,
          rt: this.rt,
          ownedLifetimes: [],
          runtime: this,
          callbacks: this.callbacks
        });
        this.contextMap.set(ctx.value, context);
        return context;
      }
      setModuleLoader(moduleLoader, moduleNormalizer) {
        super.setModuleLoader(moduleLoader, moduleNormalizer);
      }
      /**
       * Set the max stack size for this runtime in bytes.
       * To remove the limit, set to `0`.
       *
       * Setting this limit also adjusts the global `ASYNCIFY_STACK_SIZE` for the entire {@link QuickJSAsyncWASMModule}.
       * See the [pull request](https://github.com/justjake/quickjs-emscripten/pull/114) for more details.
       */
      setMaxStackSize(stackSize) {
        return super.setMaxStackSize(stackSize);
      }
    };
    exports2.QuickJSAsyncRuntime = QuickJSAsyncRuntime;
  }
});

// ../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/module-asyncify.js
var require_module_asyncify = __commonJS({
  "../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/module-asyncify.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.QuickJSAsyncWASMModule = void 0;
    var errors_1 = require_errors();
    var lifetime_1 = require_lifetime();
    var module_1 = require_module();
    var runtime_asyncify_1 = require_runtime_asyncify();
    var QuickJSAsyncWASMModule = class extends module_1.QuickJSWASMModule {
      /** @private */
      constructor(module3, ffi) {
        super(module3, ffi);
        this.ffi = ffi;
        this.module = module3;
      }
      /**
       * Create a new async runtime inside this WebAssembly module. All runtimes inside a
       * module are limited to a single async call at a time. For multiple
       * concurrent async actions, create multiple WebAssembly modules.
       */
      newRuntime(options = {}) {
        const rt = new lifetime_1.Lifetime(this.ffi.QTS_NewRuntime(), void 0, (rt_ptr) => {
          this.callbacks.deleteRuntime(rt_ptr);
          this.ffi.QTS_FreeRuntime(rt_ptr);
        });
        const runtime = new runtime_asyncify_1.QuickJSAsyncRuntime({
          module: this.module,
          ffi: this.ffi,
          rt,
          callbacks: this.callbacks
        });
        (0, module_1.applyBaseRuntimeOptions)(runtime, options);
        if (options.moduleLoader) {
          runtime.setModuleLoader(options.moduleLoader);
        }
        return runtime;
      }
      /**
       * A simplified API to create a new [[QuickJSRuntime]] and a
       * [[QuickJSContext]] inside that runtime at the same time. The runtime will
       * be disposed when the context is disposed.
       */
      newContext(options = {}) {
        const runtime = this.newRuntime();
        const lifetimes = options.ownedLifetimes ? options.ownedLifetimes.concat([runtime]) : [runtime];
        const context = runtime.newContext({ ...options, ownedLifetimes: lifetimes });
        runtime.context = context;
        return context;
      }
      /** Synchronous evalCode is not supported. */
      evalCode() {
        throw new errors_1.QuickJSNotImplemented("QuickJSWASMModuleAsyncify.evalCode: use evalCodeAsync instead");
      }
      /**
       * One-off evaluate code without needing to create a [[QuickJSRuntimeAsync]] or
       * [[QuickJSContextSync]] explicitly.
       *
       * This version allows for asynchronous Ecmascript module loading.
       *
       * Note that only a single async action can occur at a time inside the entire WebAssembly module.
       * **Multiple concurrent async actions is an error.**
       *
       * See the documentation for [[QuickJSWASMModule.evalCode]] for more details.
       */
      evalCodeAsync(code, options) {
        return lifetime_1.Scope.withScopeAsync(async (scope) => {
          const vm = scope.manage(this.newContext());
          (0, module_1.applyModuleEvalRuntimeOptions)(vm.runtime, options);
          const result = await vm.evalCodeAsync(code, "eval.js");
          if (options.memoryLimitBytes !== void 0) {
            vm.runtime.setMemoryLimit(-1);
          }
          if (result.error) {
            const error101 = vm.dump(scope.manage(result.error));
            throw error101;
          }
          const value = vm.dump(scope.manage(result.value));
          return value;
        });
      }
    };
    exports2.QuickJSAsyncWASMModule = QuickJSAsyncWASMModule;
  }
});

// ../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/generated/ffi.WASM_RELEASE_SYNC.js
var require_ffi_WASM_RELEASE_SYNC = __commonJS({
  "../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/generated/ffi.WASM_RELEASE_SYNC.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.QuickJSFFI = void 0;
    var QuickJSFFI = class {
      constructor(module3) {
        this.module = module3;
        this.DEBUG = false;
        this.QTS_Throw = this.module.cwrap("QTS_Throw", "number", ["number", "number"]);
        this.QTS_NewError = this.module.cwrap("QTS_NewError", "number", ["number"]);
        this.QTS_RuntimeSetMemoryLimit = this.module.cwrap("QTS_RuntimeSetMemoryLimit", null, ["number", "number"]);
        this.QTS_RuntimeComputeMemoryUsage = this.module.cwrap("QTS_RuntimeComputeMemoryUsage", "number", ["number", "number"]);
        this.QTS_RuntimeDumpMemoryUsage = this.module.cwrap("QTS_RuntimeDumpMemoryUsage", "number", ["number"]);
        this.QTS_RecoverableLeakCheck = this.module.cwrap("QTS_RecoverableLeakCheck", "number", []);
        this.QTS_BuildIsSanitizeLeak = this.module.cwrap("QTS_BuildIsSanitizeLeak", "number", []);
        this.QTS_RuntimeSetMaxStackSize = this.module.cwrap("QTS_RuntimeSetMaxStackSize", null, ["number", "number"]);
        this.QTS_GetUndefined = this.module.cwrap("QTS_GetUndefined", "number", []);
        this.QTS_GetNull = this.module.cwrap("QTS_GetNull", "number", []);
        this.QTS_GetFalse = this.module.cwrap("QTS_GetFalse", "number", []);
        this.QTS_GetTrue = this.module.cwrap("QTS_GetTrue", "number", []);
        this.QTS_NewRuntime = this.module.cwrap("QTS_NewRuntime", "number", []);
        this.QTS_FreeRuntime = this.module.cwrap("QTS_FreeRuntime", null, ["number"]);
        this.QTS_NewContext = this.module.cwrap("QTS_NewContext", "number", ["number"]);
        this.QTS_FreeContext = this.module.cwrap("QTS_FreeContext", null, ["number"]);
        this.QTS_FreeValuePointer = this.module.cwrap("QTS_FreeValuePointer", null, ["number", "number"]);
        this.QTS_FreeValuePointerRuntime = this.module.cwrap("QTS_FreeValuePointerRuntime", null, ["number", "number"]);
        this.QTS_FreeVoidPointer = this.module.cwrap("QTS_FreeVoidPointer", null, ["number", "number"]);
        this.QTS_FreeCString = this.module.cwrap("QTS_FreeCString", null, ["number", "number"]);
        this.QTS_DupValuePointer = this.module.cwrap("QTS_DupValuePointer", "number", ["number", "number"]);
        this.QTS_NewObject = this.module.cwrap("QTS_NewObject", "number", ["number"]);
        this.QTS_NewObjectProto = this.module.cwrap("QTS_NewObjectProto", "number", ["number", "number"]);
        this.QTS_NewArray = this.module.cwrap("QTS_NewArray", "number", ["number"]);
        this.QTS_NewFloat64 = this.module.cwrap("QTS_NewFloat64", "number", ["number", "number"]);
        this.QTS_GetFloat64 = this.module.cwrap("QTS_GetFloat64", "number", ["number", "number"]);
        this.QTS_NewString = this.module.cwrap("QTS_NewString", "number", ["number", "number"]);
        this.QTS_GetString = this.module.cwrap("QTS_GetString", "number", ["number", "number"]);
        this.QTS_NewSymbol = this.module.cwrap("QTS_NewSymbol", "number", ["number", "number", "number"]);
        this.QTS_GetSymbolDescriptionOrKey = this.module.cwrap("QTS_GetSymbolDescriptionOrKey", "number", ["number", "number"]);
        this.QTS_IsGlobalSymbol = this.module.cwrap("QTS_IsGlobalSymbol", "number", ["number", "number"]);
        this.QTS_IsJobPending = this.module.cwrap("QTS_IsJobPending", "number", ["number"]);
        this.QTS_ExecutePendingJob = this.module.cwrap("QTS_ExecutePendingJob", "number", ["number", "number", "number"]);
        this.QTS_GetProp = this.module.cwrap("QTS_GetProp", "number", ["number", "number", "number"]);
        this.QTS_SetProp = this.module.cwrap("QTS_SetProp", null, ["number", "number", "number", "number"]);
        this.QTS_DefineProp = this.module.cwrap("QTS_DefineProp", null, ["number", "number", "number", "number", "number", "number", "boolean", "boolean", "boolean"]);
        this.QTS_Call = this.module.cwrap("QTS_Call", "number", ["number", "number", "number", "number", "number"]);
        this.QTS_ResolveException = this.module.cwrap("QTS_ResolveException", "number", ["number", "number"]);
        this.QTS_Dump = this.module.cwrap("QTS_Dump", "number", ["number", "number"]);
        this.QTS_Eval = this.module.cwrap("QTS_Eval", "number", ["number", "number", "string", "number", "number"]);
        this.QTS_Typeof = this.module.cwrap("QTS_Typeof", "number", ["number", "number"]);
        this.QTS_GetGlobalObject = this.module.cwrap("QTS_GetGlobalObject", "number", ["number"]);
        this.QTS_NewPromiseCapability = this.module.cwrap("QTS_NewPromiseCapability", "number", ["number", "number"]);
        this.QTS_TestStringArg = this.module.cwrap("QTS_TestStringArg", null, ["string"]);
        this.QTS_BuildIsDebug = this.module.cwrap("QTS_BuildIsDebug", "number", []);
        this.QTS_BuildIsAsyncify = this.module.cwrap("QTS_BuildIsAsyncify", "number", []);
        this.QTS_NewFunction = this.module.cwrap("QTS_NewFunction", "number", ["number", "number", "string"]);
        this.QTS_ArgvGetJSValueConstPointer = this.module.cwrap("QTS_ArgvGetJSValueConstPointer", "number", ["number", "number"]);
        this.QTS_RuntimeEnableInterruptHandler = this.module.cwrap("QTS_RuntimeEnableInterruptHandler", null, ["number"]);
        this.QTS_RuntimeDisableInterruptHandler = this.module.cwrap("QTS_RuntimeDisableInterruptHandler", null, ["number"]);
        this.QTS_RuntimeEnableModuleLoader = this.module.cwrap("QTS_RuntimeEnableModuleLoader", null, ["number", "number"]);
        this.QTS_RuntimeDisableModuleLoader = this.module.cwrap("QTS_RuntimeDisableModuleLoader", null, ["number"]);
      }
    };
    exports2.QuickJSFFI = QuickJSFFI;
  }
});

// ../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/generated/emscripten-module.WASM_RELEASE_SYNC.js
var require_emscripten_module_WASM_RELEASE_SYNC = __commonJS({
  "../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/generated/emscripten-module.WASM_RELEASE_SYNC.js"(exports2, module2) {
    "use strict";
    var QuickJSRaw = (() => {
      var _scriptDir = typeof document !== "undefined" && document.currentScript ? document.currentScript.src : void 0;
      if (typeof __filename !== "undefined")
        _scriptDir = _scriptDir || __filename;
      return (function(QuickJSRaw2 = {}) {
        var a;
        a || (a = typeof QuickJSRaw2 !== "undefined" ? QuickJSRaw2 : {});
        var m, n;
        a.ready = new Promise(function(b, c2) {
          m = b;
          n = c2;
        });
        var p2 = Object.assign({}, a), t = "./this.program", u2 = "object" == typeof window, v = "function" == typeof importScripts, w = "object" == typeof process && "object" == typeof process.versions && "string" == typeof process.versions.node, x = "", y, z3, A;
        if (w) {
          var fs68 = require("fs"), B = require("path");
          x = v ? B.dirname(x) + "/" : __dirname + "/";
          y = (b, c2) => {
            var d = C(b);
            if (d)
              return c2 ? d : d.toString();
            b = b.startsWith("file://") ? new URL(b) : B.normalize(b);
            return fs68.readFileSync(b, c2 ? void 0 : "utf8");
          };
          A = (b) => {
            b = y(b, true);
            b.buffer || (b = new Uint8Array(b));
            return b;
          };
          z3 = (b, c2, d) => {
            var e = C(b);
            e && c2(e);
            b = b.startsWith("file://") ? new URL(b) : B.normalize(b);
            fs68.readFile(b, function(f, g) {
              f ? d(f) : c2(g.buffer);
            });
          };
          !a.thisProgram && 1 < process.argv.length && (t = process.argv[1].replace(/\\/g, "/"));
          process.argv.slice(2);
          a.inspect = function() {
            return "[Emscripten Module object]";
          };
        } else if (u2 || v)
          v ? x = self.location.href : "undefined" != typeof document && document.currentScript && (x = document.currentScript.src), _scriptDir && (x = _scriptDir), 0 !== x.indexOf("blob:") ? x = x.substr(0, x.replace(/[?#].*/, "").lastIndexOf("/") + 1) : x = "", y = (b) => {
            try {
              var c2 = new XMLHttpRequest();
              c2.open("GET", b, false);
              c2.send(null);
              return c2.responseText;
            } catch (f) {
              if (b = C(b)) {
                c2 = [];
                for (var d = 0; d < b.length; d++) {
                  var e = b[d];
                  255 < e && (e &= 255);
                  c2.push(String.fromCharCode(e));
                }
                return c2.join("");
              }
              throw f;
            }
          }, v && (A = (b) => {
            try {
              var c2 = new XMLHttpRequest();
              c2.open("GET", b, false);
              c2.responseType = "arraybuffer";
              c2.send(null);
              return new Uint8Array(c2.response);
            } catch (d) {
              if (b = C(b))
                return b;
              throw d;
            }
          }), z3 = (b, c2, d) => {
            var e = new XMLHttpRequest();
            e.open("GET", b, true);
            e.responseType = "arraybuffer";
            e.onload = () => {
              if (200 == e.status || 0 == e.status && e.response)
                c2(e.response);
              else {
                var f = C(b);
                f ? c2(f.buffer) : d();
              }
            };
            e.onerror = d;
            e.send(null);
          };
        var aa = a.print || console.log.bind(console), D = a.printErr || console.warn.bind(console);
        Object.assign(a, p2);
        p2 = null;
        a.thisProgram && (t = a.thisProgram);
        var E2;
        a.wasmBinary && (E2 = a.wasmBinary);
        var noExitRuntime = a.noExitRuntime || true;
        "object" != typeof WebAssembly && F("no native wasm support detected");
        var G2, H = false, I, J, K, L;
        function M2() {
          var b = G2.buffer;
          a.HEAP8 = I = new Int8Array(b);
          a.HEAP16 = new Int16Array(b);
          a.HEAP32 = K = new Int32Array(b);
          a.HEAPU8 = J = new Uint8Array(b);
          a.HEAPU16 = new Uint16Array(b);
          a.HEAPU32 = L = new Uint32Array(b);
          a.HEAPF32 = new Float32Array(b);
          a.HEAPF64 = new Float64Array(b);
        }
        var ba = [], ca = [], da = [];
        function ea() {
          var b = a.preRun.shift();
          ba.unshift(b);
        }
        var N = 0, O = null, P = null;
        function F(b) {
          if (a.onAbort)
            a.onAbort(b);
          b = "Aborted(" + b + ")";
          D(b);
          H = true;
          b = new WebAssembly.RuntimeError(b + ". Build with -sASSERTIONS for more info.");
          n(b);
          throw b;
        }
        var Q2 = "data:application/octet-stream;base64,", R;
        R = "data:application/octet-stream;base64, ";
        if (!R.startsWith(Q2)) {
          var fa = R;
          R = a.locateFile ? a.locateFile(fa, x) : x + fa;
        }
        function ha(b) {
          try {
            if (b == R && E2)
              return new Uint8Array(E2);
            var c2 = C(b);
            if (c2)
              return c2;
            if (A)
              return A(b);
            throw "both async and sync fetching of the wasm failed";
          } catch (d) {
            F(d);
          }
        }
        function ia(b) {
          if (!E2 && (u2 || v)) {
            if ("function" == typeof fetch && !b.startsWith("file://"))
              return fetch(b, { credentials: "same-origin" }).then(function(c2) {
                if (!c2.ok)
                  throw "failed to load wasm binary file at '" + b + "'";
                return c2.arrayBuffer();
              }).catch(function() {
                return ha(b);
              });
            if (z3)
              return new Promise(function(c2, d) {
                z3(b, function(e) {
                  c2(new Uint8Array(e));
                }, d);
              });
          }
          return Promise.resolve().then(function() {
            return ha(b);
          });
        }
        function ja(b, c2, d) {
          return ia(b).then(function(e) {
            return WebAssembly.instantiate(e, c2);
          }).then(function(e) {
            return e;
          }).then(d, function(e) {
            D("failed to asynchronously prepare wasm: " + e);
            F(e);
          });
        }
        function ka(b, c2) {
          var d = R;
          return E2 || "function" != typeof WebAssembly.instantiateStreaming || d.startsWith(Q2) || d.startsWith("file://") || w || "function" != typeof fetch ? ja(d, b, c2) : fetch(d, { credentials: "same-origin" }).then(function(e) {
            return WebAssembly.instantiateStreaming(e, b).then(c2, function(f) {
              D("wasm streaming compile failed: " + f);
              D("falling back to ArrayBuffer instantiation");
              return ja(d, b, c2);
            });
          });
        }
        function S(b) {
          for (; 0 < b.length; )
            b.shift()(a);
        }
        var la = "undefined" != typeof TextDecoder ? new TextDecoder("utf8") : void 0;
        function na(b, c2, d) {
          var e = c2 + d;
          for (d = c2; b[d] && !(d >= e); )
            ++d;
          if (16 < d - c2 && b.buffer && la)
            return la.decode(b.subarray(c2, d));
          for (e = ""; c2 < d; ) {
            var f = b[c2++];
            if (f & 128) {
              var g = b[c2++] & 63;
              if (192 == (f & 224))
                e += String.fromCharCode((f & 31) << 6 | g);
              else {
                var h = b[c2++] & 63;
                f = 224 == (f & 240) ? (f & 15) << 12 | g << 6 | h : (f & 7) << 18 | g << 12 | h << 6 | b[c2++] & 63;
                65536 > f ? e += String.fromCharCode(f) : (f -= 65536, e += String.fromCharCode(55296 | f >> 10, 56320 | f & 1023));
              }
            } else
              e += String.fromCharCode(f);
          }
          return e;
        }
        function T(b, c2) {
          return b ? na(J, b, c2) : "";
        }
        var oa = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335], pa = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
        function U(b) {
          for (var c2 = 0, d = 0; d < b.length; ++d) {
            var e = b.charCodeAt(d);
            127 >= e ? c2++ : 2047 >= e ? c2 += 2 : 55296 <= e && 57343 >= e ? (c2 += 4, ++d) : c2 += 3;
          }
          return c2;
        }
        function V(b, c2, d) {
          var e = J;
          if (!(0 < d))
            return 0;
          var f = c2;
          d = c2 + d - 1;
          for (var g = 0; g < b.length; ++g) {
            var h = b.charCodeAt(g);
            if (55296 <= h && 57343 >= h) {
              var k = b.charCodeAt(++g);
              h = 65536 + ((h & 1023) << 10) | k & 1023;
            }
            if (127 >= h) {
              if (c2 >= d)
                break;
              e[c2++] = h;
            } else {
              if (2047 >= h) {
                if (c2 + 1 >= d)
                  break;
                e[c2++] = 192 | h >> 6;
              } else {
                if (65535 >= h) {
                  if (c2 + 2 >= d)
                    break;
                  e[c2++] = 224 | h >> 12;
                } else {
                  if (c2 + 3 >= d)
                    break;
                  e[c2++] = 240 | h >> 18;
                  e[c2++] = 128 | h >> 12 & 63;
                }
                e[c2++] = 128 | h >> 6 & 63;
              }
              e[c2++] = 128 | h & 63;
            }
          }
          e[c2] = 0;
          return c2 - f;
        }
        function qa(b) {
          var c2 = U(b) + 1, d = ra(c2);
          d && V(b, d, c2);
          return d;
        }
        var W = {};
        function sa() {
          if (!X) {
            var b = { USER: "web_user", LOGNAME: "web_user", PATH: "/", PWD: "/", HOME: "/home/web_user", LANG: ("object" == typeof navigator && navigator.languages && navigator.languages[0] || "C").replace("-", "_") + ".UTF-8", _: t || "./this.program" }, c2;
            for (c2 in W)
              void 0 === W[c2] ? delete b[c2] : b[c2] = W[c2];
            var d = [];
            for (c2 in b)
              d.push(c2 + "=" + b[c2]);
            X = d;
          }
          return X;
        }
        var X, ta = [null, [], []];
        function ua(b, c2, d, e) {
          var f = { string: (l) => {
            var q2 = 0;
            if (null !== l && void 0 !== l && 0 !== l) {
              q2 = U(l) + 1;
              var ma = Y2(q2);
              V(l, ma, q2);
              q2 = ma;
            }
            return q2;
          }, array: (l) => {
            var q2 = Y2(l.length);
            I.set(l, q2);
            return q2;
          } };
          b = a["_" + b];
          var g = [], h = 0;
          if (e)
            for (var k = 0; k < e.length; k++) {
              var r = f[d[k]];
              r ? (0 === h && (h = va()), g[k] = r(e[k])) : g[k] = e[k];
            }
          d = b.apply(null, g);
          return d = (function(l) {
            0 !== h && wa(h);
            return "string" === c2 ? T(l) : "boolean" === c2 ? !!l : l;
          })(d);
        }
        var xa = "function" == typeof atob ? atob : function(b) {
          var c2 = "", d = 0;
          b = b.replace(/[^A-Za-z0-9\+\/=]/g, "");
          do {
            var e = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(b.charAt(d++));
            var f = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(b.charAt(d++));
            var g = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(b.charAt(d++));
            var h = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(b.charAt(d++));
            e = e << 2 | f >> 4;
            f = (f & 15) << 4 | g >> 2;
            var k = (g & 3) << 6 | h;
            c2 += String.fromCharCode(e);
            64 !== g && (c2 += String.fromCharCode(f));
            64 !== h && (c2 += String.fromCharCode(k));
          } while (d < b.length);
          return c2;
        };
        function C(b) {
          if (b.startsWith(Q2)) {
            b = b.slice(Q2.length);
            if ("boolean" == typeof w && w) {
              var c2 = Buffer.from(b, "base64");
              c2 = new Uint8Array(c2.buffer, c2.byteOffset, c2.byteLength);
            } else
              try {
                var d = xa(b), e = new Uint8Array(d.length);
                for (b = 0; b < d.length; ++b)
                  e[b] = d.charCodeAt(b);
                c2 = e;
              } catch (f) {
                throw Error("Converting base64 string to bytes failed.");
              }
            return c2;
          }
        }
        var ya = {
          a: function(b, c2, d, e) {
            F("Assertion failed: " + T(b) + ", at: " + [c2 ? T(c2) : "unknown filename", d, e ? T(e) : "unknown function"]);
          },
          l: function(b, c2) {
            b = new Date(1e3 * (L[b >> 2] + 4294967296 * K[b + 4 >> 2]));
            K[c2 >> 2] = b.getSeconds();
            K[c2 + 4 >> 2] = b.getMinutes();
            K[c2 + 8 >> 2] = b.getHours();
            K[c2 + 12 >> 2] = b.getDate();
            K[c2 + 16 >> 2] = b.getMonth();
            K[c2 + 20 >> 2] = b.getFullYear() - 1900;
            K[c2 + 24 >> 2] = b.getDay();
            var d = b.getFullYear();
            K[c2 + 28 >> 2] = (0 !== d % 4 || 0 === d % 100 && 0 !== d % 400 ? pa : oa)[b.getMonth()] + b.getDate() - 1 | 0;
            K[c2 + 36 >> 2] = -(60 * b.getTimezoneOffset());
            d = new Date(b.getFullYear(), 6, 1).getTimezoneOffset();
            var e = new Date(b.getFullYear(), 0, 1).getTimezoneOffset();
            K[c2 + 32 >> 2] = (d != e && b.getTimezoneOffset() == Math.min(e, d)) | 0;
          },
          k: function(b, c2, d) {
            function e(r) {
              return (r = r.toTimeString().match(/\(([A-Za-z ]+)\)$/)) ? r[1] : "GMT";
            }
            var f = (/* @__PURE__ */ new Date()).getFullYear(), g = new Date(f, 0, 1), h = new Date(f, 6, 1);
            f = g.getTimezoneOffset();
            var k = h.getTimezoneOffset();
            L[b >> 2] = 60 * Math.max(f, k);
            K[c2 >> 2] = Number(f != k);
            b = e(g);
            c2 = e(h);
            b = qa(b);
            c2 = qa(c2);
            k < f ? (L[d >> 2] = b, L[d + 4 >> 2] = c2) : (L[d >> 2] = c2, L[d + 4 >> 2] = b);
          },
          b: function() {
            F("");
          },
          m: function() {
            return Date.now();
          },
          j: function(b) {
            var c2 = J.length;
            b >>>= 0;
            if (2147483648 < b)
              return false;
            for (var d = 1; 4 >= d; d *= 2) {
              var e = c2 * (1 + 0.2 / d);
              e = Math.min(e, b + 100663296);
              var f = Math, g = f.min;
              e = Math.max(b, e);
              e += (65536 - e % 65536) % 65536;
              a: {
                var h = G2.buffer;
                try {
                  G2.grow(g.call(f, 2147483648, e) - h.byteLength + 65535 >>> 16);
                  M2();
                  var k = 1;
                  break a;
                } catch (r) {
                }
                k = void 0;
              }
              if (k)
                return true;
            }
            return false;
          },
          e: function(b, c2) {
            var d = 0;
            sa().forEach(function(e, f) {
              var g = c2 + d;
              f = L[b + 4 * f >> 2] = g;
              for (g = 0; g < e.length; ++g)
                I[f++ >> 0] = e.charCodeAt(g);
              I[f >> 0] = 0;
              d += e.length + 1;
            });
            return 0;
          },
          f: function(b, c2) {
            var d = sa();
            L[b >> 2] = d.length;
            var e = 0;
            d.forEach(function(f) {
              e += f.length + 1;
            });
            L[c2 >> 2] = e;
            return 0;
          },
          d: function() {
            return 52;
          },
          i: function() {
            return 70;
          },
          c: function(b, c2, d, e) {
            for (var f = 0, g = 0; g < d; g++) {
              var h = L[c2 >> 2], k = L[c2 + 4 >> 2];
              c2 += 8;
              for (var r = 0; r < k; r++) {
                var l = J[h + r], q2 = ta[b];
                0 === l || 10 === l ? ((1 === b ? aa : D)(na(q2, 0)), q2.length = 0) : q2.push(l);
              }
              f += k;
            }
            L[e >> 2] = f;
            return 0;
          },
          o: function(b, c2, d, e, f) {
            return a.callbacks.callFunction(void 0, b, c2, d, e, f);
          },
          n: function(b) {
            return a.callbacks.shouldInterrupt(void 0, b);
          },
          h: function(b, c2, d) {
            d = T(d);
            return a.callbacks.loadModuleSource(void 0, b, c2, d);
          },
          g: function(b, c2, d, e) {
            d = T(d);
            e = T(e);
            return a.callbacks.normalizeModule(void 0, b, c2, d, e);
          }
        };
        (function() {
          function b(d) {
            d = d.exports;
            a.asm = d;
            G2 = a.asm.p;
            M2();
            ca.unshift(a.asm.q);
            N--;
            a.monitorRunDependencies && a.monitorRunDependencies(N);
            if (0 == N && (null !== O && (clearInterval(O), O = null), P)) {
              var e = P;
              P = null;
              e();
            }
            return d;
          }
          var c2 = { a: ya };
          N++;
          a.monitorRunDependencies && a.monitorRunDependencies(N);
          if (a.instantiateWasm)
            try {
              return a.instantiateWasm(c2, b);
            } catch (d) {
              D("Module.instantiateWasm callback failed with error: " + d), n(d);
            }
          ka(c2, function(d) {
            b(d.instance);
          }).catch(n);
          return {};
        })();
        var ra = a._malloc = function() {
          return (ra = a._malloc = a.asm.r).apply(null, arguments);
        };
        a._QTS_Throw = function() {
          return (a._QTS_Throw = a.asm.s).apply(null, arguments);
        };
        a._QTS_NewError = function() {
          return (a._QTS_NewError = a.asm.t).apply(null, arguments);
        };
        a._QTS_RuntimeSetMemoryLimit = function() {
          return (a._QTS_RuntimeSetMemoryLimit = a.asm.u).apply(null, arguments);
        };
        a._QTS_RuntimeComputeMemoryUsage = function() {
          return (a._QTS_RuntimeComputeMemoryUsage = a.asm.v).apply(null, arguments);
        };
        a._QTS_RuntimeDumpMemoryUsage = function() {
          return (a._QTS_RuntimeDumpMemoryUsage = a.asm.w).apply(null, arguments);
        };
        a._QTS_RecoverableLeakCheck = function() {
          return (a._QTS_RecoverableLeakCheck = a.asm.x).apply(null, arguments);
        };
        a._QTS_BuildIsSanitizeLeak = function() {
          return (a._QTS_BuildIsSanitizeLeak = a.asm.y).apply(null, arguments);
        };
        a._QTS_RuntimeSetMaxStackSize = function() {
          return (a._QTS_RuntimeSetMaxStackSize = a.asm.z).apply(null, arguments);
        };
        a._QTS_GetUndefined = function() {
          return (a._QTS_GetUndefined = a.asm.A).apply(null, arguments);
        };
        a._QTS_GetNull = function() {
          return (a._QTS_GetNull = a.asm.B).apply(null, arguments);
        };
        a._QTS_GetFalse = function() {
          return (a._QTS_GetFalse = a.asm.C).apply(null, arguments);
        };
        a._QTS_GetTrue = function() {
          return (a._QTS_GetTrue = a.asm.D).apply(null, arguments);
        };
        a._QTS_NewRuntime = function() {
          return (a._QTS_NewRuntime = a.asm.E).apply(null, arguments);
        };
        a._QTS_FreeRuntime = function() {
          return (a._QTS_FreeRuntime = a.asm.F).apply(null, arguments);
        };
        a._QTS_NewContext = function() {
          return (a._QTS_NewContext = a.asm.G).apply(null, arguments);
        };
        a._QTS_FreeContext = function() {
          return (a._QTS_FreeContext = a.asm.H).apply(null, arguments);
        };
        a._QTS_FreeValuePointer = function() {
          return (a._QTS_FreeValuePointer = a.asm.I).apply(null, arguments);
        };
        a._free = function() {
          return (a._free = a.asm.J).apply(null, arguments);
        };
        a._QTS_FreeValuePointerRuntime = function() {
          return (a._QTS_FreeValuePointerRuntime = a.asm.K).apply(null, arguments);
        };
        a._QTS_FreeVoidPointer = function() {
          return (a._QTS_FreeVoidPointer = a.asm.L).apply(null, arguments);
        };
        a._QTS_FreeCString = function() {
          return (a._QTS_FreeCString = a.asm.M).apply(null, arguments);
        };
        a._QTS_DupValuePointer = function() {
          return (a._QTS_DupValuePointer = a.asm.N).apply(null, arguments);
        };
        a._QTS_NewObject = function() {
          return (a._QTS_NewObject = a.asm.O).apply(null, arguments);
        };
        a._QTS_NewObjectProto = function() {
          return (a._QTS_NewObjectProto = a.asm.P).apply(null, arguments);
        };
        a._QTS_NewArray = function() {
          return (a._QTS_NewArray = a.asm.Q).apply(null, arguments);
        };
        a._QTS_NewFloat64 = function() {
          return (a._QTS_NewFloat64 = a.asm.R).apply(null, arguments);
        };
        a._QTS_GetFloat64 = function() {
          return (a._QTS_GetFloat64 = a.asm.S).apply(null, arguments);
        };
        a._QTS_NewString = function() {
          return (a._QTS_NewString = a.asm.T).apply(null, arguments);
        };
        a._QTS_GetString = function() {
          return (a._QTS_GetString = a.asm.U).apply(null, arguments);
        };
        a._QTS_NewSymbol = function() {
          return (a._QTS_NewSymbol = a.asm.V).apply(null, arguments);
        };
        a._QTS_GetSymbolDescriptionOrKey = function() {
          return (a._QTS_GetSymbolDescriptionOrKey = a.asm.W).apply(null, arguments);
        };
        a._QTS_IsGlobalSymbol = function() {
          return (a._QTS_IsGlobalSymbol = a.asm.X).apply(null, arguments);
        };
        a._QTS_IsJobPending = function() {
          return (a._QTS_IsJobPending = a.asm.Y).apply(null, arguments);
        };
        a._QTS_ExecutePendingJob = function() {
          return (a._QTS_ExecutePendingJob = a.asm.Z).apply(null, arguments);
        };
        a._QTS_GetProp = function() {
          return (a._QTS_GetProp = a.asm._).apply(null, arguments);
        };
        a._QTS_SetProp = function() {
          return (a._QTS_SetProp = a.asm.$).apply(null, arguments);
        };
        a._QTS_DefineProp = function() {
          return (a._QTS_DefineProp = a.asm.aa).apply(null, arguments);
        };
        a._QTS_Call = function() {
          return (a._QTS_Call = a.asm.ba).apply(null, arguments);
        };
        a._QTS_ResolveException = function() {
          return (a._QTS_ResolveException = a.asm.ca).apply(null, arguments);
        };
        a._QTS_Dump = function() {
          return (a._QTS_Dump = a.asm.da).apply(null, arguments);
        };
        a._QTS_Eval = function() {
          return (a._QTS_Eval = a.asm.ea).apply(null, arguments);
        };
        a._QTS_Typeof = function() {
          return (a._QTS_Typeof = a.asm.fa).apply(null, arguments);
        };
        a._QTS_GetGlobalObject = function() {
          return (a._QTS_GetGlobalObject = a.asm.ga).apply(null, arguments);
        };
        a._QTS_NewPromiseCapability = function() {
          return (a._QTS_NewPromiseCapability = a.asm.ha).apply(null, arguments);
        };
        a._QTS_TestStringArg = function() {
          return (a._QTS_TestStringArg = a.asm.ia).apply(null, arguments);
        };
        a._QTS_BuildIsDebug = function() {
          return (a._QTS_BuildIsDebug = a.asm.ja).apply(null, arguments);
        };
        a._QTS_BuildIsAsyncify = function() {
          return (a._QTS_BuildIsAsyncify = a.asm.ka).apply(null, arguments);
        };
        a._QTS_NewFunction = function() {
          return (a._QTS_NewFunction = a.asm.la).apply(null, arguments);
        };
        a._QTS_ArgvGetJSValueConstPointer = function() {
          return (a._QTS_ArgvGetJSValueConstPointer = a.asm.ma).apply(null, arguments);
        };
        a._QTS_RuntimeEnableInterruptHandler = function() {
          return (a._QTS_RuntimeEnableInterruptHandler = a.asm.na).apply(null, arguments);
        };
        a._QTS_RuntimeDisableInterruptHandler = function() {
          return (a._QTS_RuntimeDisableInterruptHandler = a.asm.oa).apply(null, arguments);
        };
        a._QTS_RuntimeEnableModuleLoader = function() {
          return (a._QTS_RuntimeEnableModuleLoader = a.asm.pa).apply(null, arguments);
        };
        a._QTS_RuntimeDisableModuleLoader = function() {
          return (a._QTS_RuntimeDisableModuleLoader = a.asm.qa).apply(null, arguments);
        };
        function va() {
          return (va = a.asm.sa).apply(null, arguments);
        }
        function wa() {
          return (wa = a.asm.ta).apply(null, arguments);
        }
        function Y2() {
          return (Y2 = a.asm.ua).apply(null, arguments);
        }
        a.___start_em_js = 74916;
        a.___stop_em_js = 75818;
        a.cwrap = function(b, c2, d, e) {
          var f = !d || d.every((g) => "number" === g || "boolean" === g);
          return "string" !== c2 && f && !e ? a["_" + b] : function() {
            return ua(b, c2, d, arguments);
          };
        };
        a.UTF8ToString = T;
        a.stringToUTF8 = function(b, c2, d) {
          return V(b, c2, d);
        };
        a.lengthBytesUTF8 = U;
        var Z;
        P = function za() {
          Z || Aa();
          Z || (P = za);
        };
        function Aa() {
          function b() {
            if (!Z && (Z = true, a.calledRun = true, !H)) {
              S(ca);
              m(a);
              if (a.onRuntimeInitialized)
                a.onRuntimeInitialized();
              if (a.postRun)
                for ("function" == typeof a.postRun && (a.postRun = [a.postRun]); a.postRun.length; ) {
                  var c2 = a.postRun.shift();
                  da.unshift(c2);
                }
              S(da);
            }
          }
          if (!(0 < N)) {
            if (a.preRun)
              for ("function" == typeof a.preRun && (a.preRun = [a.preRun]); a.preRun.length; )
                ea();
            S(ba);
            0 < N || (a.setStatus ? (a.setStatus("Running..."), setTimeout(function() {
              setTimeout(function() {
                a.setStatus("");
              }, 1);
              b();
            }, 1)) : b());
          }
        }
        if (a.preInit)
          for ("function" == typeof a.preInit && (a.preInit = [a.preInit]); 0 < a.preInit.length; )
            a.preInit.pop()();
        Aa();
        return QuickJSRaw2.ready;
      });
    })();
    if (typeof exports2 === "object" && typeof module2 === "object")
      module2.exports = QuickJSRaw;
    else if (typeof define === "function" && define["amd"])
      define([], function() {
        return QuickJSRaw;
      });
    else if (typeof exports2 === "object")
      exports2["QuickJSRaw"] = QuickJSRaw;
  }
});

// ../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/variants.js
var require_variants = __commonJS({
  "../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/variants.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding2(result, mod, k);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.RELEASE_ASYNC = exports2.DEBUG_ASYNC = exports2.RELEASE_SYNC = exports2.DEBUG_SYNC = exports2.memoizePromiseFactory = exports2.newQuickJSAsyncWASMModule = exports2.newQuickJSWASMModule = void 0;
    var esmHelpers_1 = require_esmHelpers();
    async function newQuickJSWASMModule(variant = exports2.RELEASE_SYNC) {
      const [wasmModuleLoader, QuickJSFFI, { QuickJSWASMModule }] = await Promise.all([
        variant.importModuleLoader(),
        variant.importFFI(),
        Promise.resolve().then(() => __importStar2(require_module())).then(esmHelpers_1.unwrapTypescript)
      ]);
      const wasmModule = await wasmModuleLoader();
      wasmModule.type = "sync";
      const ffi = new QuickJSFFI(wasmModule);
      return new QuickJSWASMModule(wasmModule, ffi);
    }
    exports2.newQuickJSWASMModule = newQuickJSWASMModule;
    async function newQuickJSAsyncWASMModule(variant = exports2.RELEASE_ASYNC) {
      const [wasmModuleLoader, QuickJSAsyncFFI, { QuickJSAsyncWASMModule }] = await Promise.all([
        variant.importModuleLoader(),
        variant.importFFI(),
        Promise.resolve().then(() => __importStar2(require_module_asyncify())).then(esmHelpers_1.unwrapTypescript)
      ]);
      const wasmModule = await wasmModuleLoader();
      wasmModule.type = "async";
      const ffi = new QuickJSAsyncFFI(wasmModule);
      return new QuickJSAsyncWASMModule(wasmModule, ffi);
    }
    exports2.newQuickJSAsyncWASMModule = newQuickJSAsyncWASMModule;
    function memoizePromiseFactory(fn) {
      let promise3;
      return () => {
        return promise3 ?? (promise3 = fn());
      };
    }
    exports2.memoizePromiseFactory = memoizePromiseFactory;
    exports2.DEBUG_SYNC = {
      type: "sync",
      async importFFI() {
        throw new Error("not implemented");
      },
      async importModuleLoader() {
        throw new Error("not implemented");
      }
    };
    exports2.RELEASE_SYNC = {
      type: "sync",
      async importFFI() {
        const mod = await Promise.resolve().then(() => __importStar2(require_ffi_WASM_RELEASE_SYNC()));
        return (0, esmHelpers_1.unwrapTypescript)(mod).QuickJSFFI;
      },
      async importModuleLoader() {
        const mod = await Promise.resolve().then(() => __importStar2(require_emscripten_module_WASM_RELEASE_SYNC()));
        return (0, esmHelpers_1.unwrapJavascript)(mod);
      }
    };
    exports2.DEBUG_ASYNC = {
      type: "async",
      async importFFI() {
        throw new Error("not implemented");
      },
      async importModuleLoader() {
        throw new Error("not implemented");
      }
    };
    exports2.RELEASE_ASYNC = {
      type: "async",
      async importFFI() {
        throw new Error("not implemented");
      },
      async importModuleLoader() {
        throw new Error("not implemented");
      }
    };
  }
});

// ../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/vm-interface.js
var require_vm_interface = __commonJS({
  "../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/vm-interface.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.isFail = exports2.isSuccess = void 0;
    function isSuccess(successOrFail) {
      return "error" in successOrFail === false;
    }
    exports2.isSuccess = isSuccess;
    function isFail(successOrFail) {
      return "error" in successOrFail === true;
    }
    exports2.isFail = isFail;
  }
});

// ../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/module-test.js
var require_module_test = __commonJS({
  "../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/module-test.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.TestQuickJSWASMModule = void 0;
    var errors_1 = require_errors();
    var lifetime_1 = require_lifetime();
    var TestQuickJSWASMModule = class {
      constructor(parent) {
        this.parent = parent;
        this.contexts = /* @__PURE__ */ new Set();
        this.runtimes = /* @__PURE__ */ new Set();
      }
      newRuntime(options) {
        const runtime = this.parent.newRuntime({
          ...options,
          ownedLifetimes: [
            new lifetime_1.Lifetime(void 0, void 0, () => this.runtimes.delete(runtime)),
            ...options?.ownedLifetimes ?? []
          ]
        });
        this.runtimes.add(runtime);
        return runtime;
      }
      newContext(options) {
        const context = this.parent.newContext({
          ...options,
          ownedLifetimes: [
            new lifetime_1.Lifetime(void 0, void 0, () => this.contexts.delete(context)),
            ...options?.ownedLifetimes ?? []
          ]
        });
        this.contexts.add(context);
        return context;
      }
      evalCode(code, options) {
        return this.parent.evalCode(code, options);
      }
      disposeAll() {
        const allDisposables = [...this.contexts, ...this.runtimes];
        this.runtimes.clear();
        this.contexts.clear();
        allDisposables.forEach((d) => {
          if (d.alive) {
            d.dispose();
          }
        });
      }
      assertNoMemoryAllocated() {
        const leaksDetected = this.getFFI().QTS_RecoverableLeakCheck();
        if (leaksDetected) {
          throw new errors_1.QuickJSMemoryLeakDetected("Leak sanitizer detected un-freed memory");
        }
        if (this.contexts.size > 0) {
          throw new errors_1.QuickJSMemoryLeakDetected(`${this.contexts.size} contexts leaked`);
        }
        if (this.runtimes.size > 0) {
          throw new errors_1.QuickJSMemoryLeakDetected(`${this.runtimes.size} runtimes leaked`);
        }
      }
      /** @private */
      getFFI() {
        return this.parent.getFFI();
      }
    };
    exports2.TestQuickJSWASMModule = TestQuickJSWASMModule;
  }
});

// ../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/index.js
var require_dist10 = __commonJS({
  "../../node_modules/.pnpm/@tootallnate+quickjs-emscripten@0.23.0/node_modules/@tootallnate/quickjs-emscripten/dist/index.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __exportStar2 = exports2 && exports2.__exportStar || function(m, exports3) {
      for (var p2 in m) if (p2 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p2)) __createBinding2(exports3, m, p2);
    };
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding2(result, mod, k);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.shouldInterruptAfterDeadline = exports2.newAsyncContext = exports2.newAsyncRuntime = exports2.getQuickJSSync = exports2.getQuickJS = exports2.errors = exports2.RELEASE_SYNC = exports2.RELEASE_ASYNC = exports2.DEBUG_SYNC = exports2.DEBUG_ASYNC = exports2.newQuickJSAsyncWASMModule = exports2.newQuickJSWASMModule = void 0;
    var variants_1 = require_variants();
    Object.defineProperty(exports2, "newQuickJSWASMModule", { enumerable: true, get: function() {
      return variants_1.newQuickJSWASMModule;
    } });
    Object.defineProperty(exports2, "newQuickJSAsyncWASMModule", { enumerable: true, get: function() {
      return variants_1.newQuickJSAsyncWASMModule;
    } });
    Object.defineProperty(exports2, "DEBUG_ASYNC", { enumerable: true, get: function() {
      return variants_1.DEBUG_ASYNC;
    } });
    Object.defineProperty(exports2, "DEBUG_SYNC", { enumerable: true, get: function() {
      return variants_1.DEBUG_SYNC;
    } });
    Object.defineProperty(exports2, "RELEASE_ASYNC", { enumerable: true, get: function() {
      return variants_1.RELEASE_ASYNC;
    } });
    Object.defineProperty(exports2, "RELEASE_SYNC", { enumerable: true, get: function() {
      return variants_1.RELEASE_SYNC;
    } });
    __exportStar2(require_vm_interface(), exports2);
    __exportStar2(require_lifetime(), exports2);
    exports2.errors = __importStar2(require_errors());
    __exportStar2(require_deferred_promise(), exports2);
    __exportStar2(require_module_test(), exports2);
    var singleton = void 0;
    var singletonPromise = void 0;
    async function getQuickJS() {
      singletonPromise ?? (singletonPromise = (0, variants_1.newQuickJSWASMModule)().then((instance) => {
        singleton = instance;
        return instance;
      }));
      return await singletonPromise;
    }
    exports2.getQuickJS = getQuickJS;
    function getQuickJSSync() {
      if (!singleton) {
        throw new Error("QuickJS not initialized. Await getQuickJS() at least once.");
      }
      return singleton;
    }
    exports2.getQuickJSSync = getQuickJSSync;
    async function newAsyncRuntime(options) {
      const module3 = await (0, variants_1.newQuickJSAsyncWASMModule)();
      return module3.newRuntime(options);
    }
    exports2.newAsyncRuntime = newAsyncRuntime;
    async function newAsyncContext(options) {
      const module3 = await (0, variants_1.newQuickJSAsyncWASMModule)();
      return module3.newContext(options);
    }
    exports2.newAsyncContext = newAsyncContext;
    function shouldInterruptAfterDeadline(deadline) {
      const deadlineAsNumber = typeof deadline === "number" ? deadline : deadline.getTime();
      return function() {
        return Date.now() > deadlineAsNumber;
      };
    }
    exports2.shouldInterruptAfterDeadline = shouldInterruptAfterDeadline;
  }
});

// ../../node_modules/.pnpm/pac-proxy-agent@7.2.0/node_modules/pac-proxy-agent/dist/index.js
var require_dist11 = __commonJS({
  "../../node_modules/.pnpm/pac-proxy-agent@7.2.0/node_modules/pac-proxy-agent/dist/index.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding2(result, mod, k);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.PacProxyAgent = void 0;
    var net3 = __importStar2(require("net"));
    var tls3 = __importStar2(require("tls"));
    var crypto6 = __importStar2(require("crypto"));
    var events_1 = require("events");
    var debug_1 = __importDefault2(require_src2());
    var url_1 = require("url");
    var agent_base_1 = require_dist2();
    var get_uri_1 = require_dist7();
    var pac_resolver_1 = require_dist9();
    var quickjs_emscripten_1 = require_dist10();
    var debug4 = (0, debug_1.default)("pac-proxy-agent");
    var setServernameFromNonIpHost = (options) => {
      if (options.servername === void 0 && options.host && !net3.isIP(options.host)) {
        return {
          ...options,
          servername: options.host
        };
      }
      return options;
    };
    var PacProxyAgent = class extends agent_base_1.Agent {
      constructor(uri, opts) {
        super(opts);
        this.clearResolverPromise = () => {
          this.resolverPromise = void 0;
        };
        const uriStr = typeof uri === "string" ? uri : uri.href;
        this.uri = new url_1.URL(uriStr.replace(/^pac\+/i, ""));
        debug4("Creating PacProxyAgent with URI %o", this.uri.href);
        this.opts = { ...opts };
        this.cache = void 0;
        this.resolver = void 0;
        this.resolverHash = "";
        this.resolverPromise = void 0;
        if (!this.opts.filename) {
          this.opts.filename = this.uri.href;
        }
      }
      /**
       * Loads the PAC proxy file from the source if necessary, and returns
       * a generated `FindProxyForURL()` resolver function to use.
       */
      getResolver() {
        if (!this.resolverPromise) {
          this.resolverPromise = this.loadResolver();
          this.resolverPromise.then(this.clearResolverPromise, this.clearResolverPromise);
        }
        return this.resolverPromise;
      }
      async loadResolver() {
        try {
          const [qjs, code] = await Promise.all([
            (0, quickjs_emscripten_1.getQuickJS)(),
            this.loadPacFile()
          ]);
          const hash3 = crypto6.createHash("sha1").update(code).digest("hex");
          if (this.resolver && this.resolverHash === hash3) {
            debug4("Same sha1 hash for code - contents have not changed, reusing previous proxy resolver");
            return this.resolver;
          }
          debug4("Creating new proxy resolver instance");
          this.resolver = (0, pac_resolver_1.createPacResolver)(qjs, code, this.opts);
          this.resolverHash = hash3;
          return this.resolver;
        } catch (err) {
          if (this.resolver && err.code === "ENOTMODIFIED") {
            debug4("Got ENOTMODIFIED response, reusing previous proxy resolver");
            return this.resolver;
          }
          throw err;
        }
      }
      /**
       * Loads the contents of the PAC proxy file.
       *
       * @api private
       */
      async loadPacFile() {
        debug4("Loading PAC file: %o", this.uri);
        const rs = await (0, get_uri_1.getUri)(this.uri, { ...this.opts, cache: this.cache });
        debug4("Got `Readable` instance for URI");
        this.cache = rs;
        const buf = await (0, agent_base_1.toBuffer)(rs);
        debug4("Read %o byte PAC file from URI", buf.length);
        return buf.toString("utf8");
      }
      /**
       * Called when the node-core HTTP client library is creating a new HTTP request.
       */
      async connect(req, opts) {
        const { secureEndpoint } = opts;
        const isWebSocket = req.getHeader("upgrade") === "websocket";
        const resolver = await this.getResolver();
        const protocol = secureEndpoint ? "https:" : "http:";
        const host = opts.host && net3.isIPv6(opts.host) ? `[${opts.host}]` : opts.host;
        const defaultPort = secureEndpoint ? 443 : 80;
        const url46 = Object.assign(new url_1.URL(req.path, `${protocol}//${host}`), defaultPort ? void 0 : { port: opts.port });
        debug4("url: %s", url46);
        let result = await resolver(url46);
        if (!result) {
          result = "DIRECT";
        }
        const proxies = String(result).trim().split(/\s*;\s*/g).filter(Boolean);
        if (this.opts.fallbackToDirect && !proxies.includes("DIRECT")) {
          proxies.push("DIRECT");
        }
        for (const proxy of proxies) {
          let agent = null;
          let socket = null;
          const [type, target] = proxy.split(/\s+/);
          debug4("Attempting to use proxy: %o", proxy);
          if (type === "DIRECT") {
            if (secureEndpoint) {
              socket = tls3.connect(setServernameFromNonIpHost(opts));
            } else {
              socket = net3.connect(opts);
            }
          } else if (type === "SOCKS" || type === "SOCKS5") {
            const { SocksProxyAgent } = await Promise.resolve().then(() => __importStar2(require_dist5()));
            agent = new SocksProxyAgent(`socks://${target}`, this.opts);
          } else if (type === "SOCKS4") {
            const { SocksProxyAgent } = await Promise.resolve().then(() => __importStar2(require_dist5()));
            agent = new SocksProxyAgent(`socks4a://${target}`, this.opts);
          } else if (type === "PROXY" || type === "HTTP" || type === "HTTPS") {
            const proxyURL = `${type === "HTTPS" ? "https" : "http"}://${target}`;
            if (secureEndpoint || isWebSocket) {
              const { HttpsProxyAgent } = await Promise.resolve().then(() => __importStar2(require_dist4()));
              agent = new HttpsProxyAgent(proxyURL, this.opts);
            } else {
              const { HttpProxyAgent } = await Promise.resolve().then(() => __importStar2(require_dist3()));
              agent = new HttpProxyAgent(proxyURL, this.opts);
            }
          }
          try {
            if (socket) {
              await (0, events_1.once)(socket, "connect");
              req.emit("proxy", { proxy, socket });
              return socket;
            }
            if (agent) {
              const s = await agent.connect(req, opts);
              if (!(s instanceof net3.Socket)) {
                throw new Error("Expected a `net.Socket` to be returned from agent");
              }
              req.emit("proxy", { proxy, socket: s });
              return s;
            }
            throw new Error(`Could not determine proxy type for: ${proxy}`);
          } catch (err) {
            debug4("Got error for proxy %o: %o", proxy, err);
            req.emit("proxy", { proxy, error: err });
          }
        }
        throw new Error(`Failed to establish a socket connection to proxies: ${JSON.stringify(proxies)}`);
      }
    };
    PacProxyAgent.protocols = [
      "pac+data",
      "pac+file",
      "pac+ftp",
      "pac+http",
      "pac+https"
    ];
    exports2.PacProxyAgent = PacProxyAgent;
  }
});

// ../../node_modules/.pnpm/proxy-agent@6.5.0/node_modules/proxy-agent/dist/index.js
var require_dist12 = __commonJS({
  "../../node_modules/.pnpm/proxy-agent@6.5.0/node_modules/proxy-agent/dist/index.js"(exports2) {
    "use strict";
    var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() {
          return m[k];
        } };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault2 = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar2 = exports2 && exports2.__importStar || function(mod) {
      if (mod && mod.__esModule) return mod;
      var result = {};
      if (mod != null) {
        for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding2(result, mod, k);
      }
      __setModuleDefault2(result, mod);
      return result;
    };
    var __importDefault2 = exports2 && exports2.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports2, "__esModule", { value: true });
    exports2.ProxyAgent = exports2.proxies = void 0;
    var http3 = __importStar2(require("http"));
    var https2 = __importStar2(require("https"));
    var url_1 = require("url");
    var lru_cache_1 = __importDefault2(require_lru_cache());
    var agent_base_1 = require_dist2();
    var debug_1 = __importDefault2(require_src2());
    var proxy_from_env_1 = require_proxy_from_env();
    var debug4 = (0, debug_1.default)("proxy-agent");
    var wellKnownAgents = {
      http: async () => (await Promise.resolve().then(() => __importStar2(require_dist3()))).HttpProxyAgent,
      https: async () => (await Promise.resolve().then(() => __importStar2(require_dist4()))).HttpsProxyAgent,
      socks: async () => (await Promise.resolve().then(() => __importStar2(require_dist5()))).SocksProxyAgent,
      pac: async () => (await Promise.resolve().then(() => __importStar2(require_dist11()))).PacProxyAgent
    };
    exports2.proxies = {
      http: [wellKnownAgents.http, wellKnownAgents.https],
      https: [wellKnownAgents.http, wellKnownAgents.https],
      socks: [wellKnownAgents.socks, wellKnownAgents.socks],
      socks4: [wellKnownAgents.socks, wellKnownAgents.socks],
      socks4a: [wellKnownAgents.socks, wellKnownAgents.socks],
      socks5: [wellKnownAgents.socks, wellKnownAgents.socks],
      socks5h: [wellKnownAgents.socks, wellKnownAgents.socks],
      "pac+data": [wellKnownAgents.pac, wellKnownAgents.pac],
      "pac+file": [wellKnownAgents.pac, wellKnownAgents.pac],
      "pac+ftp": [wellKnownAgents.pac, wellKnownAgents.pac],
      "pac+http": [wellKnownAgents.pac, wellKnownAgents.pac],
      "pac+https": [wellKnownAgents.pac, wellKnownAgents.pac]
    };
    function isValidProtocol(v) {
      return Object.keys(exports2.proxies).includes(v);
    }
    var ProxyAgent2 = class extends agent_base_1.Agent {
      constructor(opts) {
        super(opts);
        this.cache = new lru_cache_1.default({
          max: 20,
          dispose: (agent) => agent.destroy()
        });
        debug4("Creating new ProxyAgent instance: %o", opts);
        this.connectOpts = opts;
        this.httpAgent = opts?.httpAgent || new http3.Agent(opts);
        this.httpsAgent = opts?.httpsAgent || new https2.Agent(opts);
        this.getProxyForUrl = opts?.getProxyForUrl || proxy_from_env_1.getProxyForUrl;
      }
      async connect(req, opts) {
        const { secureEndpoint } = opts;
        const isWebSocket = req.getHeader("upgrade") === "websocket";
        const protocol = secureEndpoint ? isWebSocket ? "wss:" : "https:" : isWebSocket ? "ws:" : "http:";
        const host = req.getHeader("host");
        const url46 = new url_1.URL(req.path, `${protocol}//${host}`).href;
        const proxy = await this.getProxyForUrl(url46, req);
        if (!proxy) {
          debug4("Proxy not enabled for URL: %o", url46);
          return secureEndpoint ? this.httpsAgent : this.httpAgent;
        }
        debug4("Request URL: %o", url46);
        debug4("Proxy URL: %o", proxy);
        const cacheKey = `${protocol}+${proxy}`;
        let agent = this.cache.get(cacheKey);
        if (!agent) {
          const proxyUrl = new url_1.URL(proxy);
          const proxyProto = proxyUrl.protocol.replace(":", "");
          if (!isValidProtocol(proxyProto)) {
            throw new Error(`Unsupported protocol for proxy URL: ${proxy}`);
          }
          const ctor = await exports2.proxies[proxyProto][secureEndpoint || isWebSocket ? 1 : 0]();
          agent = new ctor(proxy, this.connectOpts);
          this.cache.set(cacheKey, agent);
        } else {
          debug4("Cache hit for proxy URL: %o", proxy);
        }
        return agent;
      }
      destroy() {
        for (const agent of this.cache.values()) {
          agent.destroy();
        }
        super.destroy();
      }
    };
    exports2.ProxyAgent = ProxyAgent2;
  }
});

// ../../node_modules/.pnpm/progress@2.0.3/node_modules/progress/lib/node-progress.js
var require_node_progress = __commonJS({
  "../../node_modules/.pnpm/progress@2.0.3/node_modules/progress/lib/node-progress.js"(exports2, module2) {
    "use strict";
    exports2 = module2.exports = ProgressBar;
    function ProgressBar(fmt, options) {
      this.stream = options.stream || process.stderr;
      if (typeof options == "number") {
        var total = options;
        options = {};
        options.total = total;
      } else {
        options = options || {};
        if ("string" != typeof fmt) throw new Error("format required");
        if ("number" != typeof options.total) throw new Error("total required");
      }
      this.fmt = fmt;
      this.curr = options.curr || 0;
      this.total = options.total;
      this.width = options.width || this.total;
      this.clear = options.clear;
      this.chars = {
        complete: options.complete || "=",
        incomplete: options.incomplete || "-",
        head: options.head || (options.complete || "=")
      };
      this.renderThrottle = options.renderThrottle !== 0 ? options.renderThrottle || 16 : 0;
      this.lastRender = -Infinity;
      this.callback = options.callback || function() {
      };
      this.tokens = {};
      this.lastDraw = "";
    }
    ProgressBar.prototype.tick = function(len, tokens) {
      if (len !== 0)
        len = len || 1;
      if ("object" == typeof len) tokens = len, len = 1;
      if (tokens) this.tokens = tokens;
      if (0 == this.curr) this.start = /* @__PURE__ */ new Date();
      this.curr += len;
      this.render();
      if (this.curr >= this.total) {
        this.render(void 0, true);
        this.complete = true;
        this.terminate();
        this.callback(this);
        return;
      }
    };
    ProgressBar.prototype.render = function(tokens, force) {
      force = force !== void 0 ? force : false;
      if (tokens) this.tokens = tokens;
      if (!this.stream.isTTY) return;
      var now = Date.now();
      var delta = now - this.lastRender;
      if (!force && delta < this.renderThrottle) {
        return;
      } else {
        this.lastRender = now;
      }
      var ratio = this.curr / this.total;
      ratio = Math.min(Math.max(ratio, 0), 1);
      var percent = Math.floor(ratio * 100);
      var incomplete, complete, completeLength;
      var elapsed = /* @__PURE__ */ new Date() - this.start;
      var eta = percent == 100 ? 0 : elapsed * (this.total / this.curr - 1);
      var rate = this.curr / (elapsed / 1e3);
      var str = this.fmt.replace(":current", this.curr).replace(":total", this.total).replace(":elapsed", isNaN(elapsed) ? "0.0" : (elapsed / 1e3).toFixed(1)).replace(":eta", isNaN(eta) || !isFinite(eta) ? "0.0" : (eta / 1e3).toFixed(1)).replace(":percent", percent.toFixed(0) + "%").replace(":rate", Math.round(rate));
      var availableSpace = Math.max(0, this.stream.columns - str.replace(":bar", "").length);
      if (availableSpace && process.platform === "win32") {
        availableSpace = availableSpace - 1;
      }
      var width = Math.min(this.width, availableSpace);
      completeLength = Math.round(width * ratio);
      complete = Array(Math.max(0, completeLength + 1)).join(this.chars.complete);
      incomplete = Array(Math.max(0, width - completeLength + 1)).join(this.chars.incomplete);
      if (completeLength > 0)
        complete = complete.slice(0, -1) + this.chars.head;
      str = str.replace(":bar", complete + incomplete);
      if (this.tokens) for (var key in this.tokens) str = str.replace(":" + key, this.tokens[key]);
      if (this.lastDraw !== str) {
        this.stream.cursorTo(0);
        this.stream.write(str);
        this.stream.clearLine(1);
        this.lastDraw = str;
      }
    };
    ProgressBar.prototype.update = function(ratio, tokens) {
      var goal = Math.floor(ratio * this.total);
      var delta = goal - this.curr;
      this.tick(delta, tokens);
    };
    ProgressBar.prototype.interrupt = function(message) {
      this.stream.clearLine();
      this.stream.cursorTo(0);
      this.stream.write(message);
      this.stream.write("\n");
      this.stream.write(this.lastDraw);
    };
    ProgressBar.prototype.terminate = function() {
      if (this.clear) {
        if (this.stream.clearLine) {
          this.stream.clearLine();
          this.stream.cursorTo(0);
        }
      } else {
        this.stream.write("\n");
      }
    };
  }
});

// ../../node_modules/.pnpm/progress@2.0.3/node_modules/progress/index.js
var require_progress = __commonJS({
  "../../node_modules/.pnpm/progress@2.0.3/node_modules/progress/index.js"(exports2, module2) {
    "use strict";
    module2.exports = require_node_progress();
  }
});

// ../../node_modules/.pnpm/wrappy@1.0.2/node_modules/wrappy/wrappy.js
var require_wrappy = __commonJS({
  "../../node_modules/.pnpm/wrappy@1.0.2/node_modules/wrappy/wrappy.js"(exports2, module2) {
    "use strict";
    module2.exports = wrappy;
    function wrappy(fn, cb) {
      if (fn && cb) return wrappy(fn)(cb);
      if (typeof fn !== "function")
        throw new TypeError("need wrapper function");
      Object.keys(fn).forEach(function(k) {
        wrapper[k] = fn[k];
      });
      return wrapper;
      function wrapper() {
        var args = new Array(arguments.length);
        for (var i = 0; i < args.length; i++) {
          args[i] = arguments[i];
        }
        var ret = fn.apply(this, args);
        var cb2 = args[args.length - 1];
        if (typeof ret === "function" && ret !== cb2) {
          Object.keys(cb2).forEach(function(k) {
            ret[k] = cb2[k];
          });
        }
        return ret;
      }
    }
  }
});

// ../../node_modules/.pnpm/once@1.4.0/node_modules/once/once.js
var require_once = __commonJS({
  "../../node_modules/.pnpm/once@1.4.0/node_modules/once/once.js"(exports2, module2) {
    "use strict";
    var wrappy = require_wrappy();
    module2.exports = wrappy(once3);
    module2.exports.strict = wrappy(onceStrict);
    once3.proto = once3(function() {
      Object.defineProperty(Function.prototype, "once", {
        value: function() {
          return once3(this);
        },
        configurable: true
      });
      Object.defineProperty(Function.prototype, "onceStrict", {
        value: function() {
          return onceStrict(this);
        },
        configurable: true
      });
    });
    function once3(fn) {
      var f = function() {
        if (f.called) return f.value;
        f.called = true;
        return f.value = fn.apply(this, arguments);
      };
      f.called = false;
      return f;
    }
    function onceStrict(fn) {
      var f = function() {
        if (f.called)
          throw new Error(f.onceError);
        f.called = true;
        return f.value = fn.apply(this, arguments);
      };
      var name = fn.name || "Function wrapped with `once`";
      f.onceError = name + " shouldn't be called more than once";
      f.called = false;
      return f;
    }
  }
});

// ../../node_modules/.pnpm/end-of-stream@1.4.4/node_modules/end-of-stream/index.js
var require_end_of_stream = __commonJS({
  "../../node_modules/.pnpm/end-of-stream@1.4.4/node_modules/end-of-stream/index.js"(exports2, module2) {
    "use strict";
    var once3 = require_once();
    var noop = function() {
    };
    var isRequest = function(stream) {
      return stream.setHeader && typeof stream.abort === "function";
    };
    var isChildProcess = function(stream) {
      return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3;
    };
    var eos = function(stream, opts, callback) {
      if (typeof opts === "function") return eos(stream, null, opts);
      if (!opts) opts = {};
      callback = once3(callback || noop);
      var ws = stream._writableState;
      var rs = stream._readableState;
      var readable = opts.readable || opts.readable !== false && stream.readable;
      var writable = opts.writable || opts.writable !== false && stream.writable;
      var cancelled = false;
      var onlegacyfinish = function() {
        if (!stream.writable) onfinish();
      };
      var onfinish = function() {
        writable = false;
        if (!readable) callback.call(stream);
      };
      var onend = function() {
        readable = false;
        if (!writable) callback.call(stream);
      };
      var onexit = function(exitCode) {
        callback.call(stream, exitCode ? new Error("exited with error code: " + exitCode) : null);
      };
      var onerror = function(err) {
        callback.call(stream, err);
      };
      var onclose = function() {
        process.nextTick(onclosenexttick);
      };
      var onclosenexttick = function() {
        if (cancelled) return;
        if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error("premature close"));
        if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error("premature close"));
      };
      var onrequest = function() {
        stream.req.on("finish", onfinish);
      };
      if (isRequest(stream)) {
        stream.on("complete", onfinish);
        stream.on("abort", onclose);
        if (stream.req) onrequest();
        else stream.on("request", onrequest);
      } else if (writable && !ws) {
        stream.on("end", onlegacyfinish);
        stream.on("close", onlegacyfinish);
      }
      if (isChildProcess(stream)) stream.on("exit", onexit);
      stream.on("end", onend);
      stream.on("finish", onfinish);
      if (opts.error !== false) stream.on("error", onerror);
      stream.on("close", onclose);
      return function() {
        cancelled = true;
        stream.removeListener("complete", onfinish);
        stream.removeListener("abort", onclose);
        stream.removeListener("request", onrequest);
        if (stream.req) stream.req.removeListener("finish", onfinish);
        stream.removeListener("end", onlegacyfinish);
        stream.removeListener("close", onlegacyfinish);
        stream.removeListener("finish", onfinish);
        stream.removeListener("exit", onexit);
        stream.removeListener("end", onend);
        stream.removeListener("error", onerror);
        stream.removeListener("close", onclose);
      };
    };
    module2.exports = eos;
  }
});

// ../../node_modules/.pnpm/pump@3.0.0/node_modules/pump/index.js
var require_pump = __commonJS({
  "../../node_modules/.pnpm/pump@3.0.0/node_modules/pump/index.js"(exports2, module2) {
    "use strict";
    var once3 = require_once();
    var eos = require_end_of_stream();
    var fs68 = require("fs");
    var noop = function() {
    };
    var ancient = /^v?\.0/.test(process.version);
    var isFn = function(fn) {
      return typeof fn === "function";
    };
    var isFS = function(stream) {
      if (!ancient) return false;
      if (!fs68) return false;
      return (stream instanceof (fs68.ReadStream || noop) || stream instanceof (fs68.WriteStream || noop)) && isFn(stream.close);
    };
    var isRequest = function(stream) {
      return stream.setHeader && isFn(stream.abort);
    };
    var destroyer = function(stream, reading, writing, callback) {
      callback = once3(callback);
      var closed = false;
      stream.on("close", function() {
        closed = true;
      });
      eos(stream, { readable: reading, writable: writing }, function(err) {
        if (err) return callback(err);
        closed = true;
        callback();
      });
      var destroyed = false;
      return function(err) {
        if (closed) return;
        if (destroyed) return;
        destroyed = true;
        if (isFS(stream)) return stream.close(noop);
        if (isRequest(stream)) return stream.abort();
        if (isFn(stream.destroy)) return stream.destroy();
        callback(err || new Error("stream was destroyed"));
      };
    };
    var call = function(fn) {
      fn();
    };
    var pipe3 = function(from, to) {
      return from.pipe(to);
    };
    var pump = function() {
      var streams = Array.prototype.slice.call(arguments);
      var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop;
      if (Array.isArray(streams[0])) streams = streams[0];
      if (streams.length < 2) throw new Error("pump requires two streams per minimum");
      var error101;
      var destroys = streams.map(function(stream, i) {
        var reading = i < streams.length - 1;
        var writing = i > 0;
        return destroyer(stream, reading, writing, function(err) {
          if (!error101) error101 = err;
          if (err) destroys.forEach(call);
          if (reading) return;
          destroys.forEach(call);
          callback(error101);
        });
      });
      return streams.reduce(pipe3);
    };
    module2.exports = pump;
  }
});

// ../../node_modules/.pnpm/get-stream@5.2.0/node_modules/get-stream/buffer-stream.js
var require_buffer_stream = __commonJS({
  "../../node_modules/.pnpm/get-stream@5.2.0/node_modules/get-stream/buffer-stream.js"(exports2, module2) {
    "use strict";
    var { PassThrough: PassThroughStream } = require("stream");
    module2.exports = (options) => {
      options = { ...options };
      const { array: array3 } = options;
      let { encoding } = options;
      const isBuffer = encoding === "buffer";
      let objectMode = false;
      if (array3) {
        objectMode = !(encoding || isBuffer);
      } else {
        encoding = encoding || "utf8";
      }
      if (isBuffer) {
        encoding = null;
      }
      const stream = new PassThroughStream({ objectMode });
      if (encoding) {
        stream.setEncoding(encoding);
      }
      let length = 0;
      const chunks = [];
      stream.on("data", (chunk) => {
        chunks.push(chunk);
        if (objectMode) {
          length = chunks.length;
        } else {
          length += chunk.length;
        }
      });
      stream.getBufferedValue = () => {
        if (array3) {
          return chunks;
        }
        return isBuffer ? Buffer.concat(chunks, length) : chunks.join("");
      };
      stream.getBufferedLength = () => length;
      return stream;
    };
  }
});

// ../../node_modules/.pnpm/get-stream@5.2.0/node_modules/get-stream/index.js
var require_get_stream = __commonJS({
  "../../node_modules/.pnpm/get-stream@5.2.0/node_modules/get-stream/index.js"(exports2, module2) {
    "use strict";
    var { constants: BufferConstants } = require("buffer");
    var pump = require_pump();
    var bufferStream = require_buffer_stream();
    var MaxBufferError = class extends Error {
      constructor() {
        super("maxBuffer exceeded");
        this.name = "MaxBufferError";
      }
    };
    async function getStream(inputStream, options) {
      if (!inputStream) {
        return Promise.reject(new Error("Expected a stream"));
      }
      options = {
        maxBuffer: Infinity,
        ...options
      };
      const { maxBuffer } = options;
      let stream;
      await new Promise((resolve8, reject) => {
        const rejectPromise = (error101) => {
          if (error101 && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) {
            error101.bufferedData = stream.getBufferedValue();
          }
          reject(error101);
        };
        stream = pump(inputStream, bufferStream(options), (error101) => {
          if (error101) {
            rejectPromise(error101);
            return;
          }
          resolve8();
        });
        stream.on("data", () => {
          if (stream.getBufferedLength() > maxBuffer) {
            rejectPromise(new MaxBufferError());
          }
        });
      });
      return stream.getBufferedValue();
    }
    module2.exports = getStream;
    module2.exports.default = getStream;
    module2.exports.buffer = (stream, options) => getStream(stream, { ...options, encoding: "buffer" });
    module2.exports.array = (stream, options) => getStream(stream, { ...options, array: true });
    module2.exports.MaxBufferError = MaxBufferError;
  }
});

// ../../node_modules/.pnpm/pend@1.2.0/node_modules/pend/index.js
var require_pend = __commonJS({
  "../../node_modules/.pnpm/pend@1.2.0/node_modules/pend/index.js"(exports2, module2) {
    "use strict";
    module2.exports = Pend;
    function Pend() {
      this.pending = 0;
      this.max = Infinity;
      this.listeners = [];
      this.waiting = [];
      this.error = null;
    }
    Pend.prototype.go = function(fn) {
      if (this.pending < this.max) {
        pendGo(this, fn);
      } else {
        this.waiting.push(fn);
      }
    };
    Pend.prototype.wait = function(cb) {
      if (this.pending === 0) {
        cb(this.error);
      } else {
        this.listeners.push(cb);
      }
    };
    Pend.prototype.hold = function() {
      return pendHold(this);
    };
    function pendHold(self2) {
      self2.pending += 1;
      var called2 = false;
      return onCb;
      function onCb(err) {
        if (called2) throw new Error("callback called twice");
        called2 = true;
        self2.error = self2.error || err;
        self2.pending -= 1;
        if (self2.waiting.length > 0 && self2.pending < self2.max) {
          pendGo(self2, self2.waiting.shift());
        } else if (self2.pending === 0) {
          var listeners = self2.listeners;
          self2.listeners = [];
          listeners.forEach(cbListener);
        }
      }
      function cbListener(listener) {
        listener(self2.error);
      }
    }
    function pendGo(self2, fn) {
      fn(pendHold(self2));
    }
  }
});

// ../../node_modules/.pnpm/fd-slicer@1.1.0/node_modules/fd-slicer/index.js
var require_fd_slicer = __commonJS({
  "../../node_modules/.pnpm/fd-slicer@1.1.0/node_modules/fd-slicer/index.js"(exports2) {
    "use strict";
    var fs68 = require("fs");
    var util4 = require("util");
    var stream = require("stream");
    var Readable3 = stream.Readable;
    var Writable = stream.Writable;
    var PassThrough = stream.PassThrough;
    var Pend = require_pend();
    var EventEmitter2 = require("events").EventEmitter;
    exports2.createFromBuffer = createFromBuffer;
    exports2.createFromFd = createFromFd;
    exports2.BufferSlicer = BufferSlicer;
    exports2.FdSlicer = FdSlicer;
    util4.inherits(FdSlicer, EventEmitter2);
    function FdSlicer(fd, options) {
      options = options || {};
      EventEmitter2.call(this);
      this.fd = fd;
      this.pend = new Pend();
      this.pend.max = 1;
      this.refCount = 0;
      this.autoClose = !!options.autoClose;
    }
    FdSlicer.prototype.read = function(buffer, offset, length, position, callback) {
      var self2 = this;
      self2.pend.go(function(cb) {
        fs68.read(self2.fd, buffer, offset, length, position, function(err, bytesRead, buffer2) {
          cb();
          callback(err, bytesRead, buffer2);
        });
      });
    };
    FdSlicer.prototype.write = function(buffer, offset, length, position, callback) {
      var self2 = this;
      self2.pend.go(function(cb) {
        fs68.write(self2.fd, buffer, offset, length, position, function(err, written, buffer2) {
          cb();
          callback(err, written, buffer2);
        });
      });
    };
    FdSlicer.prototype.createReadStream = function(options) {
      return new ReadStream(this, options);
    };
    FdSlicer.prototype.createWriteStream = function(options) {
      return new WriteStream(this, options);
    };
    FdSlicer.prototype.ref = function() {
      this.refCount += 1;
    };
    FdSlicer.prototype.unref = function() {
      var self2 = this;
      self2.refCount -= 1;
      if (self2.refCount > 0) return;
      if (self2.refCount < 0) throw new Error("invalid unref");
      if (self2.autoClose) {
        fs68.close(self2.fd, onCloseDone);
      }
      function onCloseDone(err) {
        if (err) {
          self2.emit("error", err);
        } else {
          self2.emit("close");
        }
      }
    };
    util4.inherits(ReadStream, Readable3);
    function ReadStream(context, options) {
      options = options || {};
      Readable3.call(this, options);
      this.context = context;
      this.context.ref();
      this.start = options.start || 0;
      this.endOffset = options.end;
      this.pos = this.start;
      this.destroyed = false;
    }
    ReadStream.prototype._read = function(n) {
      var self2 = this;
      if (self2.destroyed) return;
      var toRead = Math.min(self2._readableState.highWaterMark, n);
      if (self2.endOffset != null) {
        toRead = Math.min(toRead, self2.endOffset - self2.pos);
      }
      if (toRead <= 0) {
        self2.destroyed = true;
        self2.push(null);
        self2.context.unref();
        return;
      }
      self2.context.pend.go(function(cb) {
        if (self2.destroyed) return cb();
        var buffer = new Buffer(toRead);
        fs68.read(self2.context.fd, buffer, 0, toRead, self2.pos, function(err, bytesRead) {
          if (err) {
            self2.destroy(err);
          } else if (bytesRead === 0) {
            self2.destroyed = true;
            self2.push(null);
            self2.context.unref();
          } else {
            self2.pos += bytesRead;
            self2.push(buffer.slice(0, bytesRead));
          }
          cb();
        });
      });
    };
    ReadStream.prototype.destroy = function(err) {
      if (this.destroyed) return;
      err = err || new Error("stream destroyed");
      this.destroyed = true;
      this.emit("error", err);
      this.context.unref();
    };
    util4.inherits(WriteStream, Writable);
    function WriteStream(context, options) {
      options = options || {};
      Writable.call(this, options);
      this.context = context;
      this.context.ref();
      this.start = options.start || 0;
      this.endOffset = options.end == null ? Infinity : +options.end;
      this.bytesWritten = 0;
      this.pos = this.start;
      this.destroyed = false;
      this.on("finish", this.destroy.bind(this));
    }
    WriteStream.prototype._write = function(buffer, encoding, callback) {
      var self2 = this;
      if (self2.destroyed) return;
      if (self2.pos + buffer.length > self2.endOffset) {
        var err = new Error("maximum file length exceeded");
        err.code = "ETOOBIG";
        self2.destroy();
        callback(err);
        return;
      }
      self2.context.pend.go(function(cb) {
        if (self2.destroyed) return cb();
        fs68.write(self2.context.fd, buffer, 0, buffer.length, self2.pos, function(err2, bytes) {
          if (err2) {
            self2.destroy();
            cb();
            callback(err2);
          } else {
            self2.bytesWritten += bytes;
            self2.pos += bytes;
            self2.emit("progress");
            cb();
            callback();
          }
        });
      });
    };
    WriteStream.prototype.destroy = function() {
      if (this.destroyed) return;
      this.destroyed = true;
      this.context.unref();
    };
    util4.inherits(BufferSlicer, EventEmitter2);
    function BufferSlicer(buffer, options) {
      EventEmitter2.call(this);
      options = options || {};
      this.refCount = 0;
      this.buffer = buffer;
      this.maxChunkSize = options.maxChunkSize || Number.MAX_SAFE_INTEGER;
    }
    BufferSlicer.prototype.read = function(buffer, offset, length, position, callback) {
      var end = position + length;
      var delta = end - this.buffer.length;
      var written = delta > 0 ? delta : length;
      this.buffer.copy(buffer, offset, position, end);
      setImmediate(function() {
        callback(null, written);
      });
    };
    BufferSlicer.prototype.write = function(buffer, offset, length, position, callback) {
      buffer.copy(this.buffer, position, offset, offset + length);
      setImmediate(function() {
        callback(null, length, buffer);
      });
    };
    BufferSlicer.prototype.createReadStream = function(options) {
      options = options || {};
      var readStream = new PassThrough(options);
      readStream.destroyed = false;
      readStream.start = options.start || 0;
      readStream.endOffset = options.end;
      readStream.pos = readStream.endOffset || this.buffer.length;
      var entireSlice = this.buffer.slice(readStream.start, readStream.pos);
      var offset = 0;
      while (true) {
        var nextOffset = offset + this.maxChunkSize;
        if (nextOffset >= entireSlice.length) {
          if (offset < entireSlice.length) {
            readStream.write(entireSlice.slice(offset, entireSlice.length));
          }
          break;
        }
        readStream.write(entireSlice.slice(offset, nextOffset));
        offset = nextOffset;
      }
      readStream.end();
      readStream.destroy = function() {
        readStream.destroyed = true;
      };
      return readStream;
    };
    BufferSlicer.prototype.createWriteStream = function(options) {
      var bufferSlicer = this;
      options = options || {};
      var writeStream = new Writable(options);
      writeStream.start = options.start || 0;
      writeStream.endOffset = options.end == null ? this.buffer.length : +options.end;
      writeStream.bytesWritten = 0;
      writeStream.pos = writeStream.start;
      writeStream.destroyed = false;
      writeStream._write = function(buffer, encoding, callback) {
        if (writeStream.destroyed) return;
        var end = writeStream.pos + buffer.length;
        if (end > writeStream.endOffset) {
          var err = new Error("maximum file length exceeded");
          err.code = "ETOOBIG";
          writeStream.destroyed = true;
          callback(err);
          return;
        }
        buffer.copy(bufferSlicer.buffer, writeStream.pos, 0, buffer.length);
        writeStream.bytesWritten += buffer.length;
        writeStream.pos = end;
        writeStream.emit("progress");
        callback();
      };
      writeStream.destroy = function() {
        writeStream.destroyed = true;
      };
      return writeStream;
    };
    BufferSlicer.prototype.ref = function() {
      this.refCount += 1;
    };
    BufferSlicer.prototype.unref = function() {
      this.refCount -= 1;
      if (this.refCount < 0) {
        throw new Error("invalid unref");
      }
    };
    function createFromBuffer(buffer, options) {
      return new BufferSlicer(buffer, options);
    }
    function createFromFd(fd, options) {
      return new FdSlicer(fd, options);
    }
  }
});

// ../../node_modules/.pnpm/buffer-crc32@0.2.13/node_modules/buffer-crc32/index.js
var require_buffer_crc32 = __commonJS({
  "../../node_modules/.pnpm/buffer-crc32@0.2.13/node_modules/buffer-crc32/index.js"(exports2, module2) {
    "use strict";
    var Buffer6 = require("buffer").Buffer;
    var CRC_TABLE = [
      0,
      1996959894,
      3993919788,
      2567524794,
      124634137,
      1886057615,
      3915621685,
      2657392035,
      249268274,
      2044508324,
      3772115230,
      2547177864,
      162941995,
      2125561021,
      3887607047,
      2428444049,
      498536548,
      1789927666,
      4089016648,
      2227061214,
      450548861,
      1843258603,
      4107580753,
      2211677639,
      325883990,
      1684777152,
      4251122042,
      2321926636,
      335633487,
      1661365465,
      4195302755,
      2366115317,
      997073096,
      1281953886,
      3579855332,
      2724688242,
      1006888145,
      1258607687,
      3524101629,
      2768942443,
      901097722,
      1119000684,
      3686517206,
      2898065728,
      853044451,
      1172266101,
      3705015759,
      2882616665,
      651767980,
      1373503546,
      3369554304,
      3218104598,
      565507253,
      1454621731,
      3485111705,
      3099436303,
      671266974,
      1594198024,
      3322730930,
      2970347812,
      795835527,
      1483230225,
      3244367275,
      3060149565,
      1994146192,
      31158534,
      2563907772,
      4023717930,
      1907459465,
      112637215,
      2680153253,
      3904427059,
      2013776290,
      251722036,
      2517215374,
      3775830040,
      2137656763,
      141376813,
      2439277719,
      3865271297,
      1802195444,
      476864866,
      2238001368,
      4066508878,
      1812370925,
      453092731,
      2181625025,
      4111451223,
      1706088902,
      314042704,
      2344532202,
      4240017532,
      1658658271,
      366619977,
      2362670323,
      4224994405,
      1303535960,
      984961486,
      2747007092,
      3569037538,
      1256170817,
      1037604311,
      2765210733,
      3554079995,
      1131014506,
      879679996,
      2909243462,
      3663771856,
      1141124467,
      855842277,
      2852801631,
      3708648649,
      1342533948,
      654459306,
      3188396048,
      3373015174,
      1466479909,
      544179635,
      3110523913,
      3462522015,
      1591671054,
      702138776,
      2966460450,
      3352799412,
      1504918807,
      783551873,
      3082640443,
      3233442989,
      3988292384,
      2596254646,
      62317068,
      1957810842,
      3939845945,
      2647816111,
      81470997,
      1943803523,
      3814918930,
      2489596804,
      225274430,
      2053790376,
      3826175755,
      2466906013,
      167816743,
      2097651377,
      4027552580,
      2265490386,
      503444072,
      1762050814,
      4150417245,
      2154129355,
      426522225,
      1852507879,
      4275313526,
      2312317920,
      282753626,
      1742555852,
      4189708143,
      2394877945,
      397917763,
      1622183637,
      3604390888,
      2714866558,
      953729732,
      1340076626,
      3518719985,
      2797360999,
      1068828381,
      1219638859,
      3624741850,
      2936675148,
      906185462,
      1090812512,
      3747672003,
      2825379669,
      829329135,
      1181335161,
      3412177804,
      3160834842,
      628085408,
      1382605366,
      3423369109,
      3138078467,
      570562233,
      1426400815,
      3317316542,
      2998733608,
      733239954,
      1555261956,
      3268935591,
      3050360625,
      752459403,
      1541320221,
      2607071920,
      3965973030,
      1969922972,
      40735498,
      2617837225,
      3943577151,
      1913087877,
      83908371,
      2512341634,
      3803740692,
      2075208622,
      213261112,
      2463272603,
      3855990285,
      2094854071,
      198958881,
      2262029012,
      4057260610,
      1759359992,
      534414190,
      2176718541,
      4139329115,
      1873836001,
      414664567,
      2282248934,
      4279200368,
      1711684554,
      285281116,
      2405801727,
      4167216745,
      1634467795,
      376229701,
      2685067896,
      3608007406,
      1308918612,
      956543938,
      2808555105,
      3495958263,
      1231636301,
      1047427035,
      2932959818,
      3654703836,
      1088359270,
      936918e3,
      2847714899,
      3736837829,
      1202900863,
      817233897,
      3183342108,
      3401237130,
      1404277552,
      615818150,
      3134207493,
      3453421203,
      1423857449,
      601450431,
      3009837614,
      3294710456,
      1567103746,
      711928724,
      3020668471,
      3272380065,
      1510334235,
      755167117
    ];
    if (typeof Int32Array !== "undefined") {
      CRC_TABLE = new Int32Array(CRC_TABLE);
    }
    function ensureBuffer(input) {
      if (Buffer6.isBuffer(input)) {
        return input;
      }
      var hasNewBufferAPI = typeof Buffer6.alloc === "function" && typeof Buffer6.from === "function";
      if (typeof input === "number") {
        return hasNewBufferAPI ? Buffer6.alloc(input) : new Buffer6(input);
      } else if (typeof input === "string") {
        return hasNewBufferAPI ? Buffer6.from(input) : new Buffer6(input);
      } else {
        throw new Error("input must be buffer, number, or string, received " + typeof input);
      }
    }
    function bufferizeInt(num) {
      var tmp = ensureBuffer(4);
      tmp.writeInt32BE(num, 0);
      return tmp;
    }
    function _crc32(buf, previous) {
      buf = ensureBuffer(buf);
      if (Buffer6.isBuffer(previous)) {
        previous = previous.readUInt32BE(0);
      }
      var crc = ~~previous ^ -1;
      for (var n = 0; n < buf.length; n++) {
        crc = CRC_TABLE[(crc ^ buf[n]) & 255] ^ crc >>> 8;
      }
      return crc ^ -1;
    }
    function crc32() {
      return bufferizeInt(_crc32.apply(null, arguments));
    }
    crc32.signed = function() {
      return _crc32.apply(null, arguments);
    };
    crc32.unsigned = function() {
      return _crc32.apply(null, arguments) >>> 0;
    };
    module2.exports = crc32;
  }
});

// ../../node_modules/.pnpm/yauzl@2.10.0/node_modules/yauzl/index.js
var require_yauzl = __commonJS({
  "../../node_modules/.pnpm/yauzl@2.10.0/node_modules/yauzl/index.js"(exports2) {
    "use strict";
    var fs68 = require("fs");
    var zlib2 = require("zlib");
    var fd_slicer = require_fd_slicer();
    var crc32 = require_buffer_crc32();
    var util4 = require("util");
    var EventEmitter2 = require("events").EventEmitter;
    var Transform2 = require("stream").Transform;
    var PassThrough = require("stream").PassThrough;
    var Writable = require("stream").Writable;
    exports2.open = open3;
    exports2.fromFd = fromFd;
    exports2.fromBuffer = fromBuffer;
    exports2.fromRandomAccessReader = fromRandomAccessReader;
    exports2.dosDateTimeToDate = dosDateTimeToDate;
    exports2.validateFileName = validateFileName;
    exports2.ZipFile = ZipFile;
    exports2.Entry = Entry;
    exports2.RandomAccessReader = RandomAccessReader;
    function open3(path73, options, callback) {
      if (typeof options === "function") {
        callback = options;
        options = null;
      }
      if (options == null) options = {};
      if (options.autoClose == null) options.autoClose = true;
      if (options.lazyEntries == null) options.lazyEntries = false;
      if (options.decodeStrings == null) options.decodeStrings = true;
      if (options.validateEntrySizes == null) options.validateEntrySizes = true;
      if (options.strictFileNames == null) options.strictFileNames = false;
      if (callback == null) callback = defaultCallback;
      fs68.open(path73, "r", function(err, fd) {
        if (err) return callback(err);
        fromFd(fd, options, function(err2, zipfile) {
          if (err2) fs68.close(fd, defaultCallback);
          callback(err2, zipfile);
        });
      });
    }
    function fromFd(fd, options, callback) {
      if (typeof options === "function") {
        callback = options;
        options = null;
      }
      if (options == null) options = {};
      if (options.autoClose == null) options.autoClose = false;
      if (options.lazyEntries == null) options.lazyEntries = false;
      if (options.decodeStrings == null) options.decodeStrings = true;
      if (options.validateEntrySizes == null) options.validateEntrySizes = true;
      if (options.strictFileNames == null) options.strictFileNames = false;
      if (callback == null) callback = defaultCallback;
      fs68.fstat(fd, function(err, stats) {
        if (err) return callback(err);
        var reader = fd_slicer.createFromFd(fd, { autoClose: true });
        fromRandomAccessReader(reader, stats.size, options, callback);
      });
    }
    function fromBuffer(buffer, options, callback) {
      if (typeof options === "function") {
        callback = options;
        options = null;
      }
      if (options == null) options = {};
      options.autoClose = false;
      if (options.lazyEntries == null) options.lazyEntries = false;
      if (options.decodeStrings == null) options.decodeStrings = true;
      if (options.validateEntrySizes == null) options.validateEntrySizes = true;
      if (options.strictFileNames == null) options.strictFileNames = false;
      var reader = fd_slicer.createFromBuffer(buffer, { maxChunkSize: 65536 });
      fromRandomAccessReader(reader, buffer.length, options, callback);
    }
    function fromRandomAccessReader(reader, totalSize, options, callback) {
      if (typeof options === "function") {
        callback = options;
        options = null;
      }
      if (options == null) options = {};
      if (options.autoClose == null) options.autoClose = true;
      if (options.lazyEntries == null) options.lazyEntries = false;
      if (options.decodeStrings == null) options.decodeStrings = true;
      var decodeStrings = !!options.decodeStrings;
      if (options.validateEntrySizes == null) options.validateEntrySizes = true;
      if (options.strictFileNames == null) options.strictFileNames = false;
      if (callback == null) callback = defaultCallback;
      if (typeof totalSize !== "number") throw new Error("expected totalSize parameter to be a number");
      if (totalSize > Number.MAX_SAFE_INTEGER) {
        throw new Error("zip file too large. only file sizes up to 2^52 are supported due to JavaScript's Number type being an IEEE 754 double.");
      }
      reader.ref();
      var eocdrWithoutCommentSize = 22;
      var maxCommentSize = 65535;
      var bufferSize = Math.min(eocdrWithoutCommentSize + maxCommentSize, totalSize);
      var buffer = newBuffer(bufferSize);
      var bufferReadStart = totalSize - buffer.length;
      readAndAssertNoEof(reader, buffer, 0, bufferSize, bufferReadStart, function(err) {
        if (err) return callback(err);
        for (var i = bufferSize - eocdrWithoutCommentSize; i >= 0; i -= 1) {
          if (buffer.readUInt32LE(i) !== 101010256) continue;
          var eocdrBuffer = buffer.slice(i);
          var diskNumber = eocdrBuffer.readUInt16LE(4);
          if (diskNumber !== 0) {
            return callback(new Error("multi-disk zip files are not supported: found disk number: " + diskNumber));
          }
          var entryCount = eocdrBuffer.readUInt16LE(10);
          var centralDirectoryOffset = eocdrBuffer.readUInt32LE(16);
          var commentLength = eocdrBuffer.readUInt16LE(20);
          var expectedCommentLength = eocdrBuffer.length - eocdrWithoutCommentSize;
          if (commentLength !== expectedCommentLength) {
            return callback(new Error("invalid comment length. expected: " + expectedCommentLength + ". found: " + commentLength));
          }
          var comment = decodeStrings ? decodeBuffer(eocdrBuffer, 22, eocdrBuffer.length, false) : eocdrBuffer.slice(22);
          if (!(entryCount === 65535 || centralDirectoryOffset === 4294967295)) {
            return callback(null, new ZipFile(reader, centralDirectoryOffset, totalSize, entryCount, comment, options.autoClose, options.lazyEntries, decodeStrings, options.validateEntrySizes, options.strictFileNames));
          }
          var zip64EocdlBuffer = newBuffer(20);
          var zip64EocdlOffset = bufferReadStart + i - zip64EocdlBuffer.length;
          readAndAssertNoEof(reader, zip64EocdlBuffer, 0, zip64EocdlBuffer.length, zip64EocdlOffset, function(err2) {
            if (err2) return callback(err2);
            if (zip64EocdlBuffer.readUInt32LE(0) !== 117853008) {
              return callback(new Error("invalid zip64 end of central directory locator signature"));
            }
            var zip64EocdrOffset = readUInt64LE(zip64EocdlBuffer, 8);
            var zip64EocdrBuffer = newBuffer(56);
            readAndAssertNoEof(reader, zip64EocdrBuffer, 0, zip64EocdrBuffer.length, zip64EocdrOffset, function(err3) {
              if (err3) return callback(err3);
              if (zip64EocdrBuffer.readUInt32LE(0) !== 101075792) {
                return callback(new Error("invalid zip64 end of central directory record signature"));
              }
              entryCount = readUInt64LE(zip64EocdrBuffer, 32);
              centralDirectoryOffset = readUInt64LE(zip64EocdrBuffer, 48);
              return callback(null, new ZipFile(reader, centralDirectoryOffset, totalSize, entryCount, comment, options.autoClose, options.lazyEntries, decodeStrings, options.validateEntrySizes, options.strictFileNames));
            });
          });
          return;
        }
        callback(new Error("end of central directory record signature not found"));
      });
    }
    util4.inherits(ZipFile, EventEmitter2);
    function ZipFile(reader, centralDirectoryOffset, fileSize, entryCount, comment, autoClose, lazyEntries, decodeStrings, validateEntrySizes, strictFileNames) {
      var self2 = this;
      EventEmitter2.call(self2);
      self2.reader = reader;
      self2.reader.on("error", function(err) {
        emitError(self2, err);
      });
      self2.reader.once("close", function() {
        self2.emit("close");
      });
      self2.readEntryCursor = centralDirectoryOffset;
      self2.fileSize = fileSize;
      self2.entryCount = entryCount;
      self2.comment = comment;
      self2.entriesRead = 0;
      self2.autoClose = !!autoClose;
      self2.lazyEntries = !!lazyEntries;
      self2.decodeStrings = !!decodeStrings;
      self2.validateEntrySizes = !!validateEntrySizes;
      self2.strictFileNames = !!strictFileNames;
      self2.isOpen = true;
      self2.emittedError = false;
      if (!self2.lazyEntries) self2._readEntry();
    }
    ZipFile.prototype.close = function() {
      if (!this.isOpen) return;
      this.isOpen = false;
      this.reader.unref();
    };
    function emitErrorAndAutoClose(self2, err) {
      if (self2.autoClose) self2.close();
      emitError(self2, err);
    }
    function emitError(self2, err) {
      if (self2.emittedError) return;
      self2.emittedError = true;
      self2.emit("error", err);
    }
    ZipFile.prototype.readEntry = function() {
      if (!this.lazyEntries) throw new Error("readEntry() called without lazyEntries:true");
      this._readEntry();
    };
    ZipFile.prototype._readEntry = function() {
      var self2 = this;
      if (self2.entryCount === self2.entriesRead) {
        setImmediate(function() {
          if (self2.autoClose) self2.close();
          if (self2.emittedError) return;
          self2.emit("end");
        });
        return;
      }
      if (self2.emittedError) return;
      var buffer = newBuffer(46);
      readAndAssertNoEof(self2.reader, buffer, 0, buffer.length, self2.readEntryCursor, function(err) {
        if (err) return emitErrorAndAutoClose(self2, err);
        if (self2.emittedError) return;
        var entry = new Entry();
        var signature = buffer.readUInt32LE(0);
        if (signature !== 33639248) return emitErrorAndAutoClose(self2, new Error("invalid central directory file header signature: 0x" + signature.toString(16)));
        entry.versionMadeBy = buffer.readUInt16LE(4);
        entry.versionNeededToExtract = buffer.readUInt16LE(6);
        entry.generalPurposeBitFlag = buffer.readUInt16LE(8);
        entry.compressionMethod = buffer.readUInt16LE(10);
        entry.lastModFileTime = buffer.readUInt16LE(12);
        entry.lastModFileDate = buffer.readUInt16LE(14);
        entry.crc32 = buffer.readUInt32LE(16);
        entry.compressedSize = buffer.readUInt32LE(20);
        entry.uncompressedSize = buffer.readUInt32LE(24);
        entry.fileNameLength = buffer.readUInt16LE(28);
        entry.extraFieldLength = buffer.readUInt16LE(30);
        entry.fileCommentLength = buffer.readUInt16LE(32);
        entry.internalFileAttributes = buffer.readUInt16LE(36);
        entry.externalFileAttributes = buffer.readUInt32LE(38);
        entry.relativeOffsetOfLocalHeader = buffer.readUInt32LE(42);
        if (entry.generalPurposeBitFlag & 64) return emitErrorAndAutoClose(self2, new Error("strong encryption is not supported"));
        self2.readEntryCursor += 46;
        buffer = newBuffer(entry.fileNameLength + entry.extraFieldLength + entry.fileCommentLength);
        readAndAssertNoEof(self2.reader, buffer, 0, buffer.length, self2.readEntryCursor, function(err2) {
          if (err2) return emitErrorAndAutoClose(self2, err2);
          if (self2.emittedError) return;
          var isUtf8 = (entry.generalPurposeBitFlag & 2048) !== 0;
          entry.fileName = self2.decodeStrings ? decodeBuffer(buffer, 0, entry.fileNameLength, isUtf8) : buffer.slice(0, entry.fileNameLength);
          var fileCommentStart = entry.fileNameLength + entry.extraFieldLength;
          var extraFieldBuffer = buffer.slice(entry.fileNameLength, fileCommentStart);
          entry.extraFields = [];
          var i = 0;
          while (i < extraFieldBuffer.length - 3) {
            var headerId = extraFieldBuffer.readUInt16LE(i + 0);
            var dataSize = extraFieldBuffer.readUInt16LE(i + 2);
            var dataStart = i + 4;
            var dataEnd = dataStart + dataSize;
            if (dataEnd > extraFieldBuffer.length) return emitErrorAndAutoClose(self2, new Error("extra field length exceeds extra field buffer size"));
            var dataBuffer = newBuffer(dataSize);
            extraFieldBuffer.copy(dataBuffer, 0, dataStart, dataEnd);
            entry.extraFields.push({
              id: headerId,
              data: dataBuffer
            });
            i = dataEnd;
          }
          entry.fileComment = self2.decodeStrings ? decodeBuffer(buffer, fileCommentStart, fileCommentStart + entry.fileCommentLength, isUtf8) : buffer.slice(fileCommentStart, fileCommentStart + entry.fileCommentLength);
          entry.comment = entry.fileComment;
          self2.readEntryCursor += buffer.length;
          self2.entriesRead += 1;
          if (entry.uncompressedSize === 4294967295 || entry.compressedSize === 4294967295 || entry.relativeOffsetOfLocalHeader === 4294967295) {
            var zip64EiefBuffer = null;
            for (var i = 0; i < entry.extraFields.length; i++) {
              var extraField = entry.extraFields[i];
              if (extraField.id === 1) {
                zip64EiefBuffer = extraField.data;
                break;
              }
            }
            if (zip64EiefBuffer == null) {
              return emitErrorAndAutoClose(self2, new Error("expected zip64 extended information extra field"));
            }
            var index = 0;
            if (entry.uncompressedSize === 4294967295) {
              if (index + 8 > zip64EiefBuffer.length) {
                return emitErrorAndAutoClose(self2, new Error("zip64 extended information extra field does not include uncompressed size"));
              }
              entry.uncompressedSize = readUInt64LE(zip64EiefBuffer, index);
              index += 8;
            }
            if (entry.compressedSize === 4294967295) {
              if (index + 8 > zip64EiefBuffer.length) {
                return emitErrorAndAutoClose(self2, new Error("zip64 extended information extra field does not include compressed size"));
              }
              entry.compressedSize = readUInt64LE(zip64EiefBuffer, index);
              index += 8;
            }
            if (entry.relativeOffsetOfLocalHeader === 4294967295) {
              if (index + 8 > zip64EiefBuffer.length) {
                return emitErrorAndAutoClose(self2, new Error("zip64 extended information extra field does not include relative header offset"));
              }
              entry.relativeOffsetOfLocalHeader = readUInt64LE(zip64EiefBuffer, index);
              index += 8;
            }
          }
          if (self2.decodeStrings) {
            for (var i = 0; i < entry.extraFields.length; i++) {
              var extraField = entry.extraFields[i];
              if (extraField.id === 28789) {
                if (extraField.data.length < 6) {
                  continue;
                }
                if (extraField.data.readUInt8(0) !== 1) {
                  continue;
                }
                var oldNameCrc32 = extraField.data.readUInt32LE(1);
                if (crc32.unsigned(buffer.slice(0, entry.fileNameLength)) !== oldNameCrc32) {
                  continue;
                }
                entry.fileName = decodeBuffer(extraField.data, 5, extraField.data.length, true);
                break;
              }
            }
          }
          if (self2.validateEntrySizes && entry.compressionMethod === 0) {
            var expectedCompressedSize = entry.uncompressedSize;
            if (entry.isEncrypted()) {
              expectedCompressedSize += 12;
            }
            if (entry.compressedSize !== expectedCompressedSize) {
              var msg = "compressed/uncompressed size mismatch for stored file: " + entry.compressedSize + " != " + entry.uncompressedSize;
              return emitErrorAndAutoClose(self2, new Error(msg));
            }
          }
          if (self2.decodeStrings) {
            if (!self2.strictFileNames) {
              entry.fileName = entry.fileName.replace(/\\/g, "/");
            }
            var errorMessage = validateFileName(entry.fileName, self2.validateFileNameOptions);
            if (errorMessage != null) return emitErrorAndAutoClose(self2, new Error(errorMessage));
          }
          self2.emit("entry", entry);
          if (!self2.lazyEntries) self2._readEntry();
        });
      });
    };
    ZipFile.prototype.openReadStream = function(entry, options, callback) {
      var self2 = this;
      var relativeStart = 0;
      var relativeEnd = entry.compressedSize;
      if (callback == null) {
        callback = options;
        options = {};
      } else {
        if (options.decrypt != null) {
          if (!entry.isEncrypted()) {
            throw new Error("options.decrypt can only be specified for encrypted entries");
          }
          if (options.decrypt !== false) throw new Error("invalid options.decrypt value: " + options.decrypt);
          if (entry.isCompressed()) {
            if (options.decompress !== false) throw new Error("entry is encrypted and compressed, and options.decompress !== false");
          }
        }
        if (options.decompress != null) {
          if (!entry.isCompressed()) {
            throw new Error("options.decompress can only be specified for compressed entries");
          }
          if (!(options.decompress === false || options.decompress === true)) {
            throw new Error("invalid options.decompress value: " + options.decompress);
          }
        }
        if (options.start != null || options.end != null) {
          if (entry.isCompressed() && options.decompress !== false) {
            throw new Error("start/end range not allowed for compressed entry without options.decompress === false");
          }
          if (entry.isEncrypted() && options.decrypt !== false) {
            throw new Error("start/end range not allowed for encrypted entry without options.decrypt === false");
          }
        }
        if (options.start != null) {
          relativeStart = options.start;
          if (relativeStart < 0) throw new Error("options.start < 0");
          if (relativeStart > entry.compressedSize) throw new Error("options.start > entry.compressedSize");
        }
        if (options.end != null) {
          relativeEnd = options.end;
          if (relativeEnd < 0) throw new Error("options.end < 0");
          if (relativeEnd > entry.compressedSize) throw new Error("options.end > entry.compressedSize");
          if (relativeEnd < relativeStart) throw new Error("options.end < options.start");
        }
      }
      if (!self2.isOpen) return callback(new Error("closed"));
      if (entry.isEncrypted()) {
        if (options.decrypt !== false) return callback(new Error("entry is encrypted, and options.decrypt !== false"));
      }
      self2.reader.ref();
      var buffer = newBuffer(30);
      readAndAssertNoEof(self2.reader, buffer, 0, buffer.length, entry.relativeOffsetOfLocalHeader, function(err) {
        try {
          if (err) return callback(err);
          var signature = buffer.readUInt32LE(0);
          if (signature !== 67324752) {
            return callback(new Error("invalid local file header signature: 0x" + signature.toString(16)));
          }
          var fileNameLength = buffer.readUInt16LE(26);
          var extraFieldLength = buffer.readUInt16LE(28);
          var localFileHeaderEnd = entry.relativeOffsetOfLocalHeader + buffer.length + fileNameLength + extraFieldLength;
          var decompress;
          if (entry.compressionMethod === 0) {
            decompress = false;
          } else if (entry.compressionMethod === 8) {
            decompress = options.decompress != null ? options.decompress : true;
          } else {
            return callback(new Error("unsupported compression method: " + entry.compressionMethod));
          }
          var fileDataStart = localFileHeaderEnd;
          var fileDataEnd = fileDataStart + entry.compressedSize;
          if (entry.compressedSize !== 0) {
            if (fileDataEnd > self2.fileSize) {
              return callback(new Error("file data overflows file bounds: " + fileDataStart + " + " + entry.compressedSize + " > " + self2.fileSize));
            }
          }
          var readStream = self2.reader.createReadStream({
            start: fileDataStart + relativeStart,
            end: fileDataStart + relativeEnd
          });
          var endpointStream = readStream;
          if (decompress) {
            var destroyed = false;
            var inflateFilter = zlib2.createInflateRaw();
            readStream.on("error", function(err2) {
              setImmediate(function() {
                if (!destroyed) inflateFilter.emit("error", err2);
              });
            });
            readStream.pipe(inflateFilter);
            if (self2.validateEntrySizes) {
              endpointStream = new AssertByteCountStream(entry.uncompressedSize);
              inflateFilter.on("error", function(err2) {
                setImmediate(function() {
                  if (!destroyed) endpointStream.emit("error", err2);
                });
              });
              inflateFilter.pipe(endpointStream);
            } else {
              endpointStream = inflateFilter;
            }
            endpointStream.destroy = function() {
              destroyed = true;
              if (inflateFilter !== endpointStream) inflateFilter.unpipe(endpointStream);
              readStream.unpipe(inflateFilter);
              readStream.destroy();
            };
          }
          callback(null, endpointStream);
        } finally {
          self2.reader.unref();
        }
      });
    };
    function Entry() {
    }
    Entry.prototype.getLastModDate = function() {
      return dosDateTimeToDate(this.lastModFileDate, this.lastModFileTime);
    };
    Entry.prototype.isEncrypted = function() {
      return (this.generalPurposeBitFlag & 1) !== 0;
    };
    Entry.prototype.isCompressed = function() {
      return this.compressionMethod === 8;
    };
    function dosDateTimeToDate(date9, time5) {
      var day = date9 & 31;
      var month = (date9 >> 5 & 15) - 1;
      var year = (date9 >> 9 & 127) + 1980;
      var millisecond = 0;
      var second = (time5 & 31) * 2;
      var minute = time5 >> 5 & 63;
      var hour = time5 >> 11 & 31;
      return new Date(year, month, day, hour, minute, second, millisecond);
    }
    function validateFileName(fileName) {
      if (fileName.indexOf("\\") !== -1) {
        return "invalid characters in fileName: " + fileName;
      }
      if (/^[a-zA-Z]:/.test(fileName) || /^\//.test(fileName)) {
        return "absolute path: " + fileName;
      }
      if (fileName.split("/").indexOf("..") !== -1) {
        return "invalid relative path: " + fileName;
      }
      return null;
    }
    function readAndAssertNoEof(reader, buffer, offset, length, position, callback) {
      if (length === 0) {
        return setImmediate(function() {
          callback(null, newBuffer(0));
        });
      }
      reader.read(buffer, offset, length, position, function(err, bytesRead) {
        if (err) return callback(err);
        if (bytesRead < length) {
          return callback(new Error("unexpected EOF"));
        }
        callback();
      });
    }
    util4.inherits(AssertByteCountStream, Transform2);
    function AssertByteCountStream(byteCount) {
      Transform2.call(this);
      this.actualByteCount = 0;
      this.expectedByteCount = byteCount;
    }
    AssertByteCountStream.prototype._transform = function(chunk, encoding, cb) {
      this.actualByteCount += chunk.length;
      if (this.actualByteCount > this.expectedByteCount) {
        var msg = "too many bytes in the stream. expected " + this.expectedByteCount + ". got at least " + this.actualByteCount;
        return cb(new Error(msg));
      }
      cb(null, chunk);
    };
    AssertByteCountStream.prototype._flush = function(cb) {
      if (this.actualByteCount < this.expectedByteCount) {
        var msg = "not enough bytes in the stream. expected " + this.expectedByteCount + ". got only " + this.actualByteCount;
        return cb(new Error(msg));
      }
      cb();
    };
    util4.inherits(RandomAccessReader, EventEmitter2);
    function RandomAccessReader() {
      EventEmitter2.call(this);
      this.refCount = 0;
    }
    RandomAccessReader.prototype.ref = function() {
      this.refCount += 1;
    };
    RandomAccessReader.prototype.unref = function() {
      var self2 = this;
      self2.refCount -= 1;
      if (self2.refCount > 0) return;
      if (self2.refCount < 0) throw new Error("invalid unref");
      self2.close(onCloseDone);
      function onCloseDone(err) {
        if (err) return self2.emit("error", err);
        self2.emit("close");
      }
    };
    RandomAccessReader.prototype.createReadStream = function(options) {
      var start = options.start;
      var end = options.end;
      if (start === end) {
        var emptyStream = new PassThrough();
        setImmediate(function() {
          emptyStream.end();
        });
        return emptyStream;
      }
      var stream = this._readStreamForRange(start, end);
      var destroyed = false;
      var refUnrefFilter = new RefUnrefFilter(this);
      stream.on("error", function(err) {
        setImmediate(function() {
          if (!destroyed) refUnrefFilter.emit("error", err);
        });
      });
      refUnrefFilter.destroy = function() {
        stream.unpipe(refUnrefFilter);
        refUnrefFilter.unref();
        stream.destroy();
      };
      var byteCounter = new AssertByteCountStream(end - start);
      refUnrefFilter.on("error", function(err) {
        setImmediate(function() {
          if (!destroyed) byteCounter.emit("error", err);
        });
      });
      byteCounter.destroy = function() {
        destroyed = true;
        refUnrefFilter.unpipe(byteCounter);
        refUnrefFilter.destroy();
      };
      return stream.pipe(refUnrefFilter).pipe(byteCounter);
    };
    RandomAccessReader.prototype._readStreamForRange = function(start, end) {
      throw new Error("not implemented");
    };
    RandomAccessReader.prototype.read = function(buffer, offset, length, position, callback) {
      var readStream = this.createReadStream({ start: position, end: position + length });
      var writeStream = new Writable();
      var written = 0;
      writeStream._write = function(chunk, encoding, cb) {
        chunk.copy(buffer, offset + written, 0, chunk.length);
        written += chunk.length;
        cb();
      };
      writeStream.on("finish", callback);
      readStream.on("error", function(error101) {
        callback(error101);
      });
      readStream.pipe(writeStream);
    };
    RandomAccessReader.prototype.close = function(callback) {
      setImmediate(callback);
    };
    util4.inherits(RefUnrefFilter, PassThrough);
    function RefUnrefFilter(context) {
      PassThrough.call(this);
      this.context = context;
      this.context.ref();
      this.unreffedYet = false;
    }
    RefUnrefFilter.prototype._flush = function(cb) {
      this.unref();
      cb();
    };
    RefUnrefFilter.prototype.unref = function(cb) {
      if (this.unreffedYet) return;
      this.unreffedYet = true;
      this.context.unref();
    };
    var cp437 = "\0\u263A\u263B\u2665\u2666\u2663\u2660\u2022\u25D8\u25CB\u25D9\u2642\u2640\u266A\u266B\u263C\u25BA\u25C4\u2195\u203C\xB6\xA7\u25AC\u21A8\u2191\u2193\u2192\u2190\u221F\u2194\u25B2\u25BC !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u2302\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xA2\xA3\xA5\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0";
    function decodeBuffer(buffer, start, end, isUtf8) {
      if (isUtf8) {
        return buffer.toString("utf8", start, end);
      } else {
        var result = "";
        for (var i = start; i < end; i++) {
          result += cp437[buffer[i]];
        }
        return result;
      }
    }
    function readUInt64LE(buffer, offset) {
      var lower32 = buffer.readUInt32LE(offset);
      var upper32 = buffer.readUInt32LE(offset + 4);
      return upper32 * 4294967296 + lower32;
    }
    var newBuffer;
    if (typeof Buffer.allocUnsafe === "function") {
      newBuffer = function(len) {
        return Buffer.allocUnsafe(len);
      };
    } else {
      newBuffer = function(len) {
        return new Buffer(len);
      };
    }
    function defaultCallback(err) {
      if (err) throw err;
    }
  }
});

// ../../node_modules/.pnpm/extract-zip@2.0.1/node_modules/extract-zip/index.js
var require_extract_zip = __commonJS({
  "../../node_modules/.pnpm/extract-zip@2.0.1/node_modules/extract-zip/index.js"(exports2, module2) {
    "use strict";
    var debug4 = require_src2()("extract-zip");
    var { createWriteStream: createWriteStream2, promises: fs68 } = require("fs");
    var getStream = require_get_stream();
    var path73 = require("path");
    var { promisify: promisify2 } = require("util");
    var stream = require("stream");
    var yauzl = require_yauzl();
    var openZip = promisify2(yauzl.open);
    var pipeline = promisify2(stream.pipeline);
    var Extractor = class {
      constructor(zipPath, opts) {
        this.zipPath = zipPath;
        this.opts = opts;
      }
      async extract() {
        debug4("opening", this.zipPath, "with opts", this.opts);
        this.zipfile = await openZip(this.zipPath, { lazyEntries: true });
        this.canceled = false;
        return new Promise((resolve8, reject) => {
          this.zipfile.on("error", (err) => {
            this.canceled = true;
            reject(err);
          });
          this.zipfile.readEntry();
          this.zipfile.on("close", () => {
            if (!this.canceled) {
              debug4("zip extraction complete");
              resolve8();
            }
          });
          this.zipfile.on("entry", async (entry) => {
            if (this.canceled) {
              debug4("skipping entry", entry.fileName, { cancelled: this.canceled });
              return;
            }
            debug4("zipfile entry", entry.fileName);
            if (entry.fileName.startsWith("__MACOSX/")) {
              this.zipfile.readEntry();
              return;
            }
            const destDir = path73.dirname(path73.join(this.opts.dir, entry.fileName));
            try {
              await fs68.mkdir(destDir, { recursive: true });
              const canonicalDestDir = await fs68.realpath(destDir);
              const relativeDestDir = path73.relative(this.opts.dir, canonicalDestDir);
              if (relativeDestDir.split(path73.sep).includes("..")) {
                throw new Error(`Out of bound path "${canonicalDestDir}" found while processing file ${entry.fileName}`);
              }
              await this.extractEntry(entry);
              debug4("finished processing", entry.fileName);
              this.zipfile.readEntry();
            } catch (err) {
              this.canceled = true;
              this.zipfile.close();
              reject(err);
            }
          });
        });
      }
      async extractEntry(entry) {
        if (this.canceled) {
          debug4("skipping entry extraction", entry.fileName, { cancelled: this.canceled });
          return;
        }
        if (this.opts.onEntry) {
          this.opts.onEntry(entry, this.zipfile);
        }
        const dest = path73.join(this.opts.dir, entry.fileName);
        const mode = entry.externalFileAttributes >> 16 & 65535;
        const IFMT = 61440;
        const IFDIR = 16384;
        const IFLNK = 40960;
        const symlink = (mode & IFMT) === IFLNK;
        let isDir = (mode & IFMT) === IFDIR;
        if (!isDir && entry.fileName.endsWith("/")) {
          isDir = true;
        }
        const madeBy = entry.versionMadeBy >> 8;
        if (!isDir) isDir = madeBy === 0 && entry.externalFileAttributes === 16;
        debug4("extracting entry", { filename: entry.fileName, isDir, isSymlink: symlink });
        const procMode = this.getExtractedMode(mode, isDir) & 511;
        const destDir = isDir ? dest : path73.dirname(dest);
        const mkdirOptions = { recursive: true };
        if (isDir) {
          mkdirOptions.mode = procMode;
        }
        debug4("mkdir", { dir: destDir, ...mkdirOptions });
        await fs68.mkdir(destDir, mkdirOptions);
        if (isDir) return;
        debug4("opening read stream", dest);
        const readStream = await promisify2(this.zipfile.openReadStream.bind(this.zipfile))(entry);
        if (symlink) {
          const link = await getStream(readStream);
          debug4("creating symlink", link, dest);
          await fs68.symlink(link, dest);
        } else {
          await pipeline(readStream, createWriteStream2(dest, { mode: procMode }));
        }
      }
      getExtractedMode(entryMode, isDir) {
        let mode = entryMode;
        if (mode === 0) {
          if (isDir) {
            if (this.opts.defaultDirMode) {
              mode = parseInt(this.opts.defaultDirMode, 10);
            }
            if (!mode) {
              mode = 493;
            }
          } else {
            if (this.opts.defaultFileMode) {
              mode = parseInt(this.opts.defaultFileMode, 10);
            }
            if (!mode) {
              mode = 420;
            }
          }
        }
        return mode;
      }
    };
    module2.exports = async function(zipPath, opts) {
      debug4("creating target directory", opts.dir);
      if (!path73.isAbsolute(opts.dir)) {
        throw new Error("Target directory is expected to be absolute");
      }
      await fs68.mkdir(opts.dir, { recursive: true });
      opts.dir = await fs68.realpath(opts.dir);
      return new Extractor(zipPath, opts).extract();
    };
  }
});

// ../../node_modules/.pnpm/queue-tick@1.0.1/node_modules/queue-tick/queue-microtask.js
var require_queue_microtask = __commonJS({
  "../../node_modules/.pnpm/queue-tick@1.0.1/node_modules/queue-tick/queue-microtask.js"(exports2, module2) {
    "use strict";
    module2.exports = typeof queueMicrotask === "function" ? queueMicrotask : (fn) => Promise.resolve().then(fn);
  }
});

// ../../node_modules/.pnpm/queue-tick@1.0.1/node_modules/queue-tick/process-next-tick.js
var require_process_next_tick = __commonJS({
  "../../node_modules/.pnpm/queue-tick@1.0.1/node_modules/queue-tick/process-next-tick.js"(exports2, module2) {
    "use strict";
    module2.exports = typeof process !== "undefined" && typeof process.nextTick === "function" ? process.nextTick.bind(process) : require_queue_microtask();
  }
});

// ../../node_modules/.pnpm/fast-fifo@1.3.2/node_modules/fast-fifo/fixed-size.js
var require_fixed_size = __commonJS({
  "../../node_modules/.pnpm/fast-fifo@1.3.2/node_modules/fast-fifo/fixed-size.js"(exports2, module2) {
    "use strict";
    module2.exports = class FixedFIFO {
      constructor(hwm) {
        if (!(hwm > 0) || (hwm - 1 & hwm) !== 0) throw new Error("Max size for a FixedFIFO should be a power of two");
        this.buffer = new Array(hwm);
        this.mask = hwm - 1;
        this.top = 0;
        this.btm = 0;
        this.next = null;
      }
      clear() {
        this.top = this.btm = 0;
        this.next = null;
        this.buffer.fill(void 0);
      }
      push(data) {
        if (this.buffer[this.top] !== void 0) return false;
        this.buffer[this.top] = data;
        this.top = this.top + 1 & this.mask;
        return true;
      }
      shift() {
        const last = this.buffer[this.btm];
        if (last === void 0) return void 0;
        this.buffer[this.btm] = void 0;
        this.btm = this.btm + 1 & this.mask;
        return last;
      }
      peek() {
        return this.buffer[this.btm];
      }
      isEmpty() {
        return this.buffer[this.btm] === void 0;
      }
    };
  }
});

// ../../node_modules/.pnpm/fast-fifo@1.3.2/node_modules/fast-fifo/index.js
var require_fast_fifo = __commonJS({
  "../../node_modules/.pnpm/fast-fifo@1.3.2/node_modules/fast-fifo/index.js"(exports2, module2) {
    "use strict";
    var FixedFIFO = require_fixed_size();
    module2.exports = class FastFIFO {
      constructor(hwm) {
        this.hwm = hwm || 16;
        this.head = new FixedFIFO(this.hwm);
        this.tail = this.head;
        this.length = 0;
      }
      clear() {
        this.head = this.tail;
        this.head.clear();
        this.length = 0;
      }
      push(val) {
        this.length++;
        if (!this.head.push(val)) {
          const prev = this.head;
          this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length);
          this.head.push(val);
        }
      }
      shift() {
        if (this.length !== 0) this.length--;
        const val = this.tail.shift();
        if (val === void 0 && this.tail.next) {
          const next = this.tail.next;
          this.tail.next = null;
          this.tail = next;
          return this.tail.shift();
        }
        return val;
      }
      peek() {
        const val = this.tail.peek();
        if (val === void 0 && this.tail.next) return this.tail.next.peek();
        return val;
      }
      isEmpty() {
        return this.length === 0;
      }
    };
  }
});

// ../../node_modules/.pnpm/b4a@1.6.7/node_modules/b4a/index.js
var require_b4a = __commonJS({
  "../../node_modules/.pnpm/b4a@1.6.7/node_modules/b4a/index.js"(exports2, module2) {
    "use strict";
    function isBuffer(value) {
      return Buffer.isBuffer(value) || value instanceof Uint8Array;
    }
    function isEncoding(encoding) {
      return Buffer.isEncoding(encoding);
    }
    function alloc(size, fill2, encoding) {
      return Buffer.alloc(size, fill2, encoding);
    }
    function allocUnsafe(size) {
      return Buffer.allocUnsafe(size);
    }
    function allocUnsafeSlow(size) {
      return Buffer.allocUnsafeSlow(size);
    }
    function byteLength(string7, encoding) {
      return Buffer.byteLength(string7, encoding);
    }
    function compare(a, b) {
      return Buffer.compare(a, b);
    }
    function concat(buffers, totalLength) {
      return Buffer.concat(buffers, totalLength);
    }
    function copy2(source, target, targetStart, start, end) {
      return toBuffer(source).copy(target, targetStart, start, end);
    }
    function equals(a, b) {
      return toBuffer(a).equals(b);
    }
    function fill(buffer, value, offset, end, encoding) {
      return toBuffer(buffer).fill(value, offset, end, encoding);
    }
    function from(value, encodingOrOffset, length) {
      return Buffer.from(value, encodingOrOffset, length);
    }
    function includes(buffer, value, byteOffset, encoding) {
      return toBuffer(buffer).includes(value, byteOffset, encoding);
    }
    function indexOf(buffer, value, byfeOffset, encoding) {
      return toBuffer(buffer).indexOf(value, byfeOffset, encoding);
    }
    function lastIndexOf(buffer, value, byteOffset, encoding) {
      return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding);
    }
    function swap16(buffer) {
      return toBuffer(buffer).swap16();
    }
    function swap32(buffer) {
      return toBuffer(buffer).swap32();
    }
    function swap64(buffer) {
      return toBuffer(buffer).swap64();
    }
    function toBuffer(buffer) {
      if (Buffer.isBuffer(buffer)) return buffer;
      return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength);
    }
    function toString(buffer, encoding, start, end) {
      return toBuffer(buffer).toString(encoding, start, end);
    }
    function write(buffer, string7, offset, length, encoding) {
      return toBuffer(buffer).write(string7, offset, length, encoding);
    }
    function writeDoubleLE(buffer, value, offset) {
      return toBuffer(buffer).writeDoubleLE(value, offset);
    }
    function writeFloatLE(buffer, value, offset) {
      return toBuffer(buffer).writeFloatLE(value, offset);
    }
    function writeUInt32LE(buffer, value, offset) {
      return toBuffer(buffer).writeUInt32LE(value, offset);
    }
    function writeInt32LE(buffer, value, offset) {
      return toBuffer(buffer).writeInt32LE(value, offset);
    }
    function readDoubleLE(buffer, offset) {
      return toBuffer(buffer).readDoubleLE(offset);
    }
    function readFloatLE(buffer, offset) {
      return toBuffer(buffer).readFloatLE(offset);
    }
    function readUInt32LE(buffer, offset) {
      return toBuffer(buffer).readUInt32LE(offset);
    }
    function readInt32LE(buffer, offset) {
      return toBuffer(buffer).readInt32LE(offset);
    }
    function writeDoubleBE(buffer, value, offset) {
      return toBuffer(buffer).writeDoubleBE(value, offset);
    }
    function writeFloatBE(buffer, value, offset) {
      return toBuffer(buffer).writeFloatBE(value, offset);
    }
    function writeUInt32BE(buffer, value, offset) {
      return toBuffer(buffer).writeUInt32BE(value, offset);
    }
    function writeInt32BE(buffer, value, offset) {
      return toBuffer(buffer).writeInt32BE(value, offset);
    }
    function readDoubleBE(buffer, offset) {
      return toBuffer(buffer).readDoubleBE(offset);
    }
    function readFloatBE(buffer, offset) {
      return toBuffer(buffer).readFloatBE(offset);
    }
    function readUInt32BE(buffer, offset) {
      return toBuffer(buffer).readUInt32BE(offset);
    }
    function readInt32BE(buffer, offset) {
      return toBuffer(buffer).readInt32BE(offset);
    }
    module2.exports = {
      isBuffer,
      isEncoding,
      alloc,
      allocUnsafe,
      allocUnsafeSlow,
      byteLength,
      compare,
      concat,
      copy: copy2,
      equals,
      fill,
      from,
      includes,
      indexOf,
      lastIndexOf,
      swap16,
      swap32,
      swap64,
      toBuffer,
      toString,
      write,
      writeDoubleLE,
      writeFloatLE,
      writeUInt32LE,
      writeInt32LE,
      readDoubleLE,
      readFloatLE,
      readUInt32LE,
      readInt32LE,
      writeDoubleBE,
      writeFloatBE,
      writeUInt32BE,
      writeInt32BE,
      readDoubleBE,
      readFloatBE,
      readUInt32BE,
      readInt32BE
    };
  }
});

// ../../node_modules/.pnpm/text-decoder@1.2.3/node_modules/text-decoder/lib/pass-through-decoder.js
var require_pass_through_decoder = __commonJS({
  "../../node_modules/.pnpm/text-decoder@1.2.3/node_modules/text-decoder/lib/pass-through-decoder.js"(exports2, module2) {
    "use strict";
    var b4a = require_b4a();
    module2.exports = class PassThroughDecoder {
      constructor(encoding) {
        this.encoding = encoding;
      }
      get remaining() {
        return 0;
      }
      decode(tail) {
        return b4a.toString(tail, this.encoding);
      }
      flush() {
        return "";
      }
    };
  }
});

// ../../node_modules/.pnpm/text-decoder@1.2.3/node_modules/text-decoder/lib/utf8-decoder.js
var require_utf8_decoder = __commonJS({
  "../../node_modules/.pnpm/text-decoder@1.2.3/node_modules/text-decoder/lib/utf8-decoder.js"(exports2, module2) {
    "use strict";
    var b4a = require_b4a();
    module2.exports = class UTF8Decoder {
      constructor() {
        this.codePoint = 0;
        this.bytesSeen = 0;
        this.bytesNeeded = 0;
        this.lowerBoundary = 128;
        this.upperBoundary = 191;
      }
      get remaining() {
        return this.bytesSeen;
      }
      decode(data) {
        if (this.bytesNeeded === 0) {
          let isBoundary = true;
          for (let i = Math.max(0, data.byteLength - 4), n = data.byteLength; i < n && isBoundary; i++) {
            isBoundary = data[i] <= 127;
          }
          if (isBoundary) return b4a.toString(data, "utf8");
        }
        let result = "";
        for (let i = 0, n = data.byteLength; i < n; i++) {
          const byte = data[i];
          if (this.bytesNeeded === 0) {
            if (byte <= 127) {
              result += String.fromCharCode(byte);
            } else {
              this.bytesSeen = 1;
              if (byte >= 194 && byte <= 223) {
                this.bytesNeeded = 2;
                this.codePoint = byte & 31;
              } else if (byte >= 224 && byte <= 239) {
                if (byte === 224) this.lowerBoundary = 160;
                else if (byte === 237) this.upperBoundary = 159;
                this.bytesNeeded = 3;
                this.codePoint = byte & 15;
              } else if (byte >= 240 && byte <= 244) {
                if (byte === 240) this.lowerBoundary = 144;
                if (byte === 244) this.upperBoundary = 143;
                this.bytesNeeded = 4;
                this.codePoint = byte & 7;
              } else {
                result += "\uFFFD";
              }
            }
            continue;
          }
          if (byte < this.lowerBoundary || byte > this.upperBoundary) {
            this.codePoint = 0;
            this.bytesNeeded = 0;
            this.bytesSeen = 0;
            this.lowerBoundary = 128;
            this.upperBoundary = 191;
            result += "\uFFFD";
            continue;
          }
          this.lowerBoundary = 128;
          this.upperBoundary = 191;
          this.codePoint = this.codePoint << 6 | byte & 63;
          this.bytesSeen++;
          if (this.bytesSeen !== this.bytesNeeded) continue;
          result += String.fromCodePoint(this.codePoint);
          this.codePoint = 0;
          this.bytesNeeded = 0;
          this.bytesSeen = 0;
        }
        return result;
      }
      flush() {
        const result = this.bytesNeeded > 0 ? "\uFFFD" : "";
        this.codePoint = 0;
        this.bytesNeeded = 0;
        this.bytesSeen = 0;
        this.lowerBoundary = 128;
        this.upperBoundary = 191;
        return result;
      }
    };
  }
});

// ../../node_modules/.pnpm/text-decoder@1.2.3/node_modules/text-decoder/index.js
var require_text_decoder = __commonJS({
  "../../node_modules/.pnpm/text-decoder@1.2.3/node_modules/text-decoder/index.js"(exports2, module2) {
    "use strict";
    var PassThroughDecoder = require_pass_through_decoder();
    var UTF8Decoder = require_utf8_decoder();
    module2.exports = class TextDecoder {
      constructor(encoding = "utf8") {
        this.encoding = normalizeEncoding(encoding);
        switch (this.encoding) {
          case "utf8":
            this.decoder = new UTF8Decoder();
            break;
          case "utf16le":
          case "base64":
            throw new Error("Unsupported encoding: " + this.encoding);
          default:
            this.decoder = new PassThroughDecoder(this.encoding);
        }
      }
      get remaining() {
        return this.decoder.remaining;
      }
      push(data) {
        if (typeof data === "string") return data;
        return this.decoder.decode(data);
      }
      // For Node.js compatibility
      write(data) {
        return this.push(data);
      }
      end(data) {
        let result = "";
        if (data) result = this.push(data);
        result += this.decoder.flush();
        return result;
      }
    };
    function normalizeEncoding(encoding) {
      encoding = encoding.toLowerCase();
      switch (encoding) {
        case "utf8":
        case "utf-8":
          return "utf8";
        case "ucs2":
        case "ucs-2":
        case "utf16le":
        case "utf-16le":
          return "utf16le";
        case "latin1":
        case "binary":
          return "latin1";
        case "base64":
        case "ascii":
        case "hex":
          return encoding;
        default:
          throw new Error("Unknown encoding: " + encoding);
      }
    }
  }
});

// ../../node_modules/.pnpm/streamx@2.21.1/node_modules/streamx/index.js
var require_streamx = __commonJS({
  "../../node_modules/.pnpm/streamx@2.21.1/node_modules/streamx/index.js"(exports2, module2) {
    "use strict";
    var { EventEmitter: EventEmitter2 } = require("events");
    var STREAM_DESTROYED = new Error("Stream was destroyed");
    var PREMATURE_CLOSE = new Error("Premature close");
    var queueTick = require_process_next_tick();
    var FIFO = require_fast_fifo();
    var TextDecoder3 = require_text_decoder();
    var MAX = (1 << 29) - 1;
    var OPENING = 1;
    var PREDESTROYING = 2;
    var DESTROYING = 4;
    var DESTROYED = 8;
    var NOT_OPENING = MAX ^ OPENING;
    var NOT_PREDESTROYING = MAX ^ PREDESTROYING;
    var READ_ACTIVE = 1 << 4;
    var READ_UPDATING = 2 << 4;
    var READ_PRIMARY = 4 << 4;
    var READ_QUEUED = 8 << 4;
    var READ_RESUMED = 16 << 4;
    var READ_PIPE_DRAINED = 32 << 4;
    var READ_ENDING = 64 << 4;
    var READ_EMIT_DATA = 128 << 4;
    var READ_EMIT_READABLE = 256 << 4;
    var READ_EMITTED_READABLE = 512 << 4;
    var READ_DONE = 1024 << 4;
    var READ_NEXT_TICK = 2048 << 4;
    var READ_NEEDS_PUSH = 4096 << 4;
    var READ_READ_AHEAD = 8192 << 4;
    var READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED;
    var READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH;
    var READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE;
    var READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED;
    var READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD;
    var READ_NOT_ACTIVE = MAX ^ READ_ACTIVE;
    var READ_NON_PRIMARY = MAX ^ READ_PRIMARY;
    var READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH);
    var READ_PUSHED = MAX ^ READ_NEEDS_PUSH;
    var READ_PAUSED = MAX ^ READ_RESUMED;
    var READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE);
    var READ_NOT_ENDING = MAX ^ READ_ENDING;
    var READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING;
    var READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK;
    var READ_NOT_UPDATING = MAX ^ READ_UPDATING;
    var READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD;
    var READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD;
    var WRITE_ACTIVE = 1 << 18;
    var WRITE_UPDATING = 2 << 18;
    var WRITE_PRIMARY = 4 << 18;
    var WRITE_QUEUED = 8 << 18;
    var WRITE_UNDRAINED = 16 << 18;
    var WRITE_DONE = 32 << 18;
    var WRITE_EMIT_DRAIN = 64 << 18;
    var WRITE_NEXT_TICK = 128 << 18;
    var WRITE_WRITING = 256 << 18;
    var WRITE_FINISHING = 512 << 18;
    var WRITE_CORKED = 1024 << 18;
    var WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING);
    var WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY;
    var WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING);
    var WRITE_DRAINED = MAX ^ WRITE_UNDRAINED;
    var WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED;
    var WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK;
    var WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING;
    var WRITE_NOT_CORKED = MAX ^ WRITE_CORKED;
    var ACTIVE = READ_ACTIVE | WRITE_ACTIVE;
    var NOT_ACTIVE = MAX ^ ACTIVE;
    var DONE = READ_DONE | WRITE_DONE;
    var DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING;
    var OPEN_STATUS = DESTROY_STATUS | OPENING;
    var AUTO_DESTROY = DESTROY_STATUS | DONE;
    var NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY;
    var ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK;
    var TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE;
    var IS_OPENING = OPEN_STATUS | TICKING;
    var READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE;
    var READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED;
    var READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED;
    var READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE;
    var SHOULD_NOT_READ = OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD;
    var READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE;
    var READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY;
    var READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING;
    var WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE;
    var WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED;
    var WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE;
    var WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE;
    var WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED;
    var WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE;
    var WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING;
    var WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE;
    var WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE;
    var WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY;
    var WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS;
    var asyncIterator = Symbol.asyncIterator || /* @__PURE__ */ Symbol("asyncIterator");
    var WritableState = class {
      constructor(stream, { highWaterMark = 16384, map: map3 = null, mapWritable, byteLength, byteLengthWritable } = {}) {
        this.stream = stream;
        this.queue = new FIFO();
        this.highWaterMark = highWaterMark;
        this.buffered = 0;
        this.error = null;
        this.pipeline = null;
        this.drains = null;
        this.byteLength = byteLengthWritable || byteLength || defaultByteLength;
        this.map = mapWritable || map3;
        this.afterWrite = afterWrite.bind(this);
        this.afterUpdateNextTick = updateWriteNT.bind(this);
      }
      get ended() {
        return (this.stream._duplexState & WRITE_DONE) !== 0;
      }
      push(data) {
        if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false;
        if (this.map !== null) data = this.map(data);
        this.buffered += this.byteLength(data);
        this.queue.push(data);
        if (this.buffered < this.highWaterMark) {
          this.stream._duplexState |= WRITE_QUEUED;
          return true;
        }
        this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED;
        return false;
      }
      shift() {
        const data = this.queue.shift();
        this.buffered -= this.byteLength(data);
        if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED;
        return data;
      }
      end(data) {
        if (typeof data === "function") this.stream.once("finish", data);
        else if (data !== void 0 && data !== null) this.push(data);
        this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY;
      }
      autoBatch(data, cb) {
        const buffer = [];
        const stream = this.stream;
        buffer.push(data);
        while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {
          buffer.push(stream._writableState.shift());
        }
        if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null);
        stream._writev(buffer, cb);
      }
      update() {
        const stream = this.stream;
        stream._duplexState |= WRITE_UPDATING;
        do {
          while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
            const data = this.shift();
            stream._duplexState |= WRITE_ACTIVE_AND_WRITING;
            stream._write(data, this.afterWrite);
          }
          if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary();
        } while (this.continueUpdate() === true);
        stream._duplexState &= WRITE_NOT_UPDATING;
      }
      updateNonPrimary() {
        const stream = this.stream;
        if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
          stream._duplexState = stream._duplexState | WRITE_ACTIVE;
          stream._final(afterFinal.bind(this));
          return;
        }
        if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
          if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
            stream._duplexState |= ACTIVE;
            stream._destroy(afterDestroy.bind(this));
          }
          return;
        }
        if ((stream._duplexState & IS_OPENING) === OPENING) {
          stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING;
          stream._open(afterOpen.bind(this));
        }
      }
      continueUpdate() {
        if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false;
        this.stream._duplexState &= WRITE_NOT_NEXT_TICK;
        return true;
      }
      updateCallback() {
        if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) this.update();
        else this.updateNextTick();
      }
      updateNextTick() {
        if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return;
        this.stream._duplexState |= WRITE_NEXT_TICK;
        if ((this.stream._duplexState & WRITE_UPDATING) === 0) queueTick(this.afterUpdateNextTick);
      }
    };
    var ReadableState = class {
      constructor(stream, { highWaterMark = 16384, map: map3 = null, mapReadable, byteLength, byteLengthReadable } = {}) {
        this.stream = stream;
        this.queue = new FIFO();
        this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark;
        this.buffered = 0;
        this.readAhead = highWaterMark > 0;
        this.error = null;
        this.pipeline = null;
        this.byteLength = byteLengthReadable || byteLength || defaultByteLength;
        this.map = mapReadable || map3;
        this.pipeTo = null;
        this.afterRead = afterRead.bind(this);
        this.afterUpdateNextTick = updateReadNT.bind(this);
      }
      get ended() {
        return (this.stream._duplexState & READ_DONE) !== 0;
      }
      pipe(pipeTo, cb) {
        if (this.pipeTo !== null) throw new Error("Can only pipe to one destination");
        if (typeof cb !== "function") cb = null;
        this.stream._duplexState |= READ_PIPE_DRAINED;
        this.pipeTo = pipeTo;
        this.pipeline = new Pipeline2(this.stream, pipeTo, cb);
        if (cb) this.stream.on("error", noop);
        if (isStreamx(pipeTo)) {
          pipeTo._writableState.pipeline = this.pipeline;
          if (cb) pipeTo.on("error", noop);
          pipeTo.on("finish", this.pipeline.finished.bind(this.pipeline));
        } else {
          const onerror = this.pipeline.done.bind(this.pipeline, pipeTo);
          const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null);
          pipeTo.on("error", onerror);
          pipeTo.on("close", onclose);
          pipeTo.on("finish", this.pipeline.finished.bind(this.pipeline));
        }
        pipeTo.on("drain", afterDrain.bind(this));
        this.stream.emit("piping", pipeTo);
        pipeTo.emit("pipe", this.stream);
      }
      push(data) {
        const stream = this.stream;
        if (data === null) {
          this.highWaterMark = 0;
          stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED;
          return false;
        }
        if (this.map !== null) {
          data = this.map(data);
          if (data === null) {
            stream._duplexState &= READ_PUSHED;
            return this.buffered < this.highWaterMark;
          }
        }
        this.buffered += this.byteLength(data);
        this.queue.push(data);
        stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED;
        return this.buffered < this.highWaterMark;
      }
      shift() {
        const data = this.queue.shift();
        this.buffered -= this.byteLength(data);
        if (this.buffered === 0) this.stream._duplexState &= READ_NOT_QUEUED;
        return data;
      }
      unshift(data) {
        const pending = [this.map !== null ? this.map(data) : data];
        while (this.buffered > 0) pending.push(this.shift());
        for (let i = 0; i < pending.length - 1; i++) {
          const data2 = pending[i];
          this.buffered += this.byteLength(data2);
          this.queue.push(data2);
        }
        this.push(pending[pending.length - 1]);
      }
      read() {
        const stream = this.stream;
        if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
          const data = this.shift();
          if (this.pipeTo !== null && this.pipeTo.write(data) === false) stream._duplexState &= READ_PIPE_NOT_DRAINED;
          if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit("data", data);
          return data;
        }
        if (this.readAhead === false) {
          stream._duplexState |= READ_READ_AHEAD;
          this.updateNextTick();
        }
        return null;
      }
      drain() {
        const stream = this.stream;
        while ((stream._duplexState & READ_STATUS) === READ_QUEUED && (stream._duplexState & READ_FLOWING) !== 0) {
          const data = this.shift();
          if (this.pipeTo !== null && this.pipeTo.write(data) === false) stream._duplexState &= READ_PIPE_NOT_DRAINED;
          if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit("data", data);
        }
      }
      update() {
        const stream = this.stream;
        stream._duplexState |= READ_UPDATING;
        do {
          this.drain();
          while (this.buffered < this.highWaterMark && (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD) {
            stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH;
            stream._read(this.afterRead);
            this.drain();
          }
          if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
            stream._duplexState |= READ_EMITTED_READABLE;
            stream.emit("readable");
          }
          if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary();
        } while (this.continueUpdate() === true);
        stream._duplexState &= READ_NOT_UPDATING;
      }
      updateNonPrimary() {
        const stream = this.stream;
        if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
          stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING;
          stream.emit("end");
          if ((stream._duplexState & AUTO_DESTROY) === DONE) stream._duplexState |= DESTROYING;
          if (this.pipeTo !== null) this.pipeTo.end();
        }
        if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
          if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
            stream._duplexState |= ACTIVE;
            stream._destroy(afterDestroy.bind(this));
          }
          return;
        }
        if ((stream._duplexState & IS_OPENING) === OPENING) {
          stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING;
          stream._open(afterOpen.bind(this));
        }
      }
      continueUpdate() {
        if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false;
        this.stream._duplexState &= READ_NOT_NEXT_TICK;
        return true;
      }
      updateCallback() {
        if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) this.update();
        else this.updateNextTick();
      }
      updateNextTickIfOpen() {
        if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return;
        this.stream._duplexState |= READ_NEXT_TICK;
        if ((this.stream._duplexState & READ_UPDATING) === 0) queueTick(this.afterUpdateNextTick);
      }
      updateNextTick() {
        if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return;
        this.stream._duplexState |= READ_NEXT_TICK;
        if ((this.stream._duplexState & READ_UPDATING) === 0) queueTick(this.afterUpdateNextTick);
      }
    };
    var TransformState = class {
      constructor(stream) {
        this.data = null;
        this.afterTransform = afterTransform.bind(stream);
        this.afterFinal = null;
      }
    };
    var Pipeline2 = class {
      constructor(src, dst, cb) {
        this.from = src;
        this.to = dst;
        this.afterPipe = cb;
        this.error = null;
        this.pipeToFinished = false;
      }
      finished() {
        this.pipeToFinished = true;
      }
      done(stream, err) {
        if (err) this.error = err;
        if (stream === this.to) {
          this.to = null;
          if (this.from !== null) {
            if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {
              this.from.destroy(this.error || new Error("Writable stream closed prematurely"));
            }
            return;
          }
        }
        if (stream === this.from) {
          this.from = null;
          if (this.to !== null) {
            if ((stream._duplexState & READ_DONE) === 0) {
              this.to.destroy(this.error || new Error("Readable stream closed before ending"));
            }
            return;
          }
        }
        if (this.afterPipe !== null) this.afterPipe(this.error);
        this.to = this.from = this.afterPipe = null;
      }
    };
    function afterDrain() {
      this.stream._duplexState |= READ_PIPE_DRAINED;
      this.updateCallback();
    }
    function afterFinal(err) {
      const stream = this.stream;
      if (err) stream.destroy(err);
      if ((stream._duplexState & DESTROY_STATUS) === 0) {
        stream._duplexState |= WRITE_DONE;
        stream.emit("finish");
      }
      if ((stream._duplexState & AUTO_DESTROY) === DONE) {
        stream._duplexState |= DESTROYING;
      }
      stream._duplexState &= WRITE_NOT_FINISHING;
      if ((stream._duplexState & WRITE_UPDATING) === 0) this.update();
      else this.updateNextTick();
    }
    function afterDestroy(err) {
      const stream = this.stream;
      if (!err && this.error !== STREAM_DESTROYED) err = this.error;
      if (err) stream.emit("error", err);
      stream._duplexState |= DESTROYED;
      stream.emit("close");
      const rs = stream._readableState;
      const ws = stream._writableState;
      if (rs !== null && rs.pipeline !== null) rs.pipeline.done(stream, err);
      if (ws !== null) {
        while (ws.drains !== null && ws.drains.length > 0) ws.drains.shift().resolve(false);
        if (ws.pipeline !== null) ws.pipeline.done(stream, err);
      }
    }
    function afterWrite(err) {
      const stream = this.stream;
      if (err) stream.destroy(err);
      stream._duplexState &= WRITE_NOT_ACTIVE;
      if (this.drains !== null) tickDrains(this.drains);
      if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
        stream._duplexState &= WRITE_DRAINED;
        if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {
          stream.emit("drain");
        }
      }
      this.updateCallback();
    }
    function afterRead(err) {
      if (err) this.stream.destroy(err);
      this.stream._duplexState &= READ_NOT_ACTIVE;
      if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0) this.stream._duplexState &= READ_NO_READ_AHEAD;
      this.updateCallback();
    }
    function updateReadNT() {
      if ((this.stream._duplexState & READ_UPDATING) === 0) {
        this.stream._duplexState &= READ_NOT_NEXT_TICK;
        this.update();
      }
    }
    function updateWriteNT() {
      if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
        this.stream._duplexState &= WRITE_NOT_NEXT_TICK;
        this.update();
      }
    }
    function tickDrains(drains) {
      for (let i = 0; i < drains.length; i++) {
        if (--drains[i].writes === 0) {
          drains.shift().resolve(true);
          i--;
        }
      }
    }
    function afterOpen(err) {
      const stream = this.stream;
      if (err) stream.destroy(err);
      if ((stream._duplexState & DESTROYING) === 0) {
        if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) stream._duplexState |= READ_PRIMARY;
        if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) stream._duplexState |= WRITE_PRIMARY;
        stream.emit("open");
      }
      stream._duplexState &= NOT_ACTIVE;
      if (stream._writableState !== null) {
        stream._writableState.updateCallback();
      }
      if (stream._readableState !== null) {
        stream._readableState.updateCallback();
      }
    }
    function afterTransform(err, data) {
      if (data !== void 0 && data !== null) this.push(data);
      this._writableState.afterWrite(err);
    }
    function newListener(name) {
      if (this._readableState !== null) {
        if (name === "data") {
          this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD;
          this._readableState.updateNextTick();
        }
        if (name === "readable") {
          this._duplexState |= READ_EMIT_READABLE;
          this._readableState.updateNextTick();
        }
      }
      if (this._writableState !== null) {
        if (name === "drain") {
          this._duplexState |= WRITE_EMIT_DRAIN;
          this._writableState.updateNextTick();
        }
      }
    }
    var Stream2 = class extends EventEmitter2 {
      constructor(opts) {
        super();
        this._duplexState = 0;
        this._readableState = null;
        this._writableState = null;
        if (opts) {
          if (opts.open) this._open = opts.open;
          if (opts.destroy) this._destroy = opts.destroy;
          if (opts.predestroy) this._predestroy = opts.predestroy;
          if (opts.signal) {
            opts.signal.addEventListener("abort", abort.bind(this));
          }
        }
        this.on("newListener", newListener);
      }
      _open(cb) {
        cb(null);
      }
      _destroy(cb) {
        cb(null);
      }
      _predestroy() {
      }
      get readable() {
        return this._readableState !== null ? true : void 0;
      }
      get writable() {
        return this._writableState !== null ? true : void 0;
      }
      get destroyed() {
        return (this._duplexState & DESTROYED) !== 0;
      }
      get destroying() {
        return (this._duplexState & DESTROY_STATUS) !== 0;
      }
      destroy(err) {
        if ((this._duplexState & DESTROY_STATUS) === 0) {
          if (!err) err = STREAM_DESTROYED;
          this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY;
          if (this._readableState !== null) {
            this._readableState.highWaterMark = 0;
            this._readableState.error = err;
          }
          if (this._writableState !== null) {
            this._writableState.highWaterMark = 0;
            this._writableState.error = err;
          }
          this._duplexState |= PREDESTROYING;
          this._predestroy();
          this._duplexState &= NOT_PREDESTROYING;
          if (this._readableState !== null) this._readableState.updateNextTick();
          if (this._writableState !== null) this._writableState.updateNextTick();
        }
      }
    };
    var Readable3 = class _Readable extends Stream2 {
      constructor(opts) {
        super(opts);
        this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD;
        this._readableState = new ReadableState(this, opts);
        if (opts) {
          if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD;
          if (opts.read) this._read = opts.read;
          if (opts.eagerOpen) this._readableState.updateNextTick();
          if (opts.encoding) this.setEncoding(opts.encoding);
        }
      }
      setEncoding(encoding) {
        const dec = new TextDecoder3(encoding);
        const map3 = this._readableState.map || echo;
        this._readableState.map = mapOrSkip;
        return this;
        function mapOrSkip(data) {
          const next = dec.push(data);
          return next === "" && (data.byteLength !== 0 || dec.remaining > 0) ? null : map3(next);
        }
      }
      _read(cb) {
        cb(null);
      }
      pipe(dest, cb) {
        this._readableState.updateNextTick();
        this._readableState.pipe(dest, cb);
        return dest;
      }
      read() {
        this._readableState.updateNextTick();
        return this._readableState.read();
      }
      push(data) {
        this._readableState.updateNextTickIfOpen();
        return this._readableState.push(data);
      }
      unshift(data) {
        this._readableState.updateNextTickIfOpen();
        return this._readableState.unshift(data);
      }
      resume() {
        this._duplexState |= READ_RESUMED_READ_AHEAD;
        this._readableState.updateNextTick();
        return this;
      }
      pause() {
        this._duplexState &= this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED;
        return this;
      }
      static _fromAsyncIterator(ite, opts) {
        let destroy;
        const rs = new _Readable({
          ...opts,
          read(cb) {
            ite.next().then(push).then(cb.bind(null, null)).catch(cb);
          },
          predestroy() {
            destroy = ite.return();
          },
          destroy(cb) {
            if (!destroy) return cb(null);
            destroy.then(cb.bind(null, null)).catch(cb);
          }
        });
        return rs;
        function push(data) {
          if (data.done) rs.push(null);
          else rs.push(data.value);
        }
      }
      static from(data, opts) {
        if (isReadStreamx(data)) return data;
        if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts);
        if (!Array.isArray(data)) data = data === void 0 ? [] : [data];
        let i = 0;
        return new _Readable({
          ...opts,
          read(cb) {
            this.push(i === data.length ? null : data[i++]);
            cb(null);
          }
        });
      }
      static isBackpressured(rs) {
        return (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 || rs._readableState.buffered >= rs._readableState.highWaterMark;
      }
      static isPaused(rs) {
        return (rs._duplexState & READ_RESUMED) === 0;
      }
      [asyncIterator]() {
        const stream = this;
        let error101 = null;
        let promiseResolve = null;
        let promiseReject = null;
        this.on("error", (err) => {
          error101 = err;
        });
        this.on("readable", onreadable);
        this.on("close", onclose);
        return {
          [asyncIterator]() {
            return this;
          },
          next() {
            return new Promise(function(resolve8, reject) {
              promiseResolve = resolve8;
              promiseReject = reject;
              const data = stream.read();
              if (data !== null) ondata(data);
              else if ((stream._duplexState & DESTROYED) !== 0) ondata(null);
            });
          },
          return() {
            return destroy(null);
          },
          throw(err) {
            return destroy(err);
          }
        };
        function onreadable() {
          if (promiseResolve !== null) ondata(stream.read());
        }
        function onclose() {
          if (promiseResolve !== null) ondata(null);
        }
        function ondata(data) {
          if (promiseReject === null) return;
          if (error101) promiseReject(error101);
          else if (data === null && (stream._duplexState & READ_DONE) === 0) promiseReject(STREAM_DESTROYED);
          else promiseResolve({ value: data, done: data === null });
          promiseReject = promiseResolve = null;
        }
        function destroy(err) {
          stream.destroy(err);
          return new Promise((resolve8, reject) => {
            if (stream._duplexState & DESTROYED) return resolve8({ value: void 0, done: true });
            stream.once("close", function() {
              if (err) reject(err);
              else resolve8({ value: void 0, done: true });
            });
          });
        }
      }
    };
    var Writable = class extends Stream2 {
      constructor(opts) {
        super(opts);
        this._duplexState |= OPENING | READ_DONE;
        this._writableState = new WritableState(this, opts);
        if (opts) {
          if (opts.writev) this._writev = opts.writev;
          if (opts.write) this._write = opts.write;
          if (opts.final) this._final = opts.final;
          if (opts.eagerOpen) this._writableState.updateNextTick();
        }
      }
      cork() {
        this._duplexState |= WRITE_CORKED;
      }
      uncork() {
        this._duplexState &= WRITE_NOT_CORKED;
        this._writableState.updateNextTick();
      }
      _writev(batch, cb) {
        cb(null);
      }
      _write(data, cb) {
        this._writableState.autoBatch(data, cb);
      }
      _final(cb) {
        cb(null);
      }
      static isBackpressured(ws) {
        return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0;
      }
      static drained(ws) {
        if (ws.destroyed) return Promise.resolve(false);
        const state = ws._writableState;
        const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length;
        const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0);
        if (writes === 0) return Promise.resolve(true);
        if (state.drains === null) state.drains = [];
        return new Promise((resolve8) => {
          state.drains.push({ writes, resolve: resolve8 });
        });
      }
      write(data) {
        this._writableState.updateNextTick();
        return this._writableState.push(data);
      }
      end(data) {
        this._writableState.updateNextTick();
        this._writableState.end(data);
        return this;
      }
    };
    var Duplex = class extends Readable3 {
      // and Writable
      constructor(opts) {
        super(opts);
        this._duplexState = OPENING | this._duplexState & READ_READ_AHEAD;
        this._writableState = new WritableState(this, opts);
        if (opts) {
          if (opts.writev) this._writev = opts.writev;
          if (opts.write) this._write = opts.write;
          if (opts.final) this._final = opts.final;
        }
      }
      cork() {
        this._duplexState |= WRITE_CORKED;
      }
      uncork() {
        this._duplexState &= WRITE_NOT_CORKED;
        this._writableState.updateNextTick();
      }
      _writev(batch, cb) {
        cb(null);
      }
      _write(data, cb) {
        this._writableState.autoBatch(data, cb);
      }
      _final(cb) {
        cb(null);
      }
      write(data) {
        this._writableState.updateNextTick();
        return this._writableState.push(data);
      }
      end(data) {
        this._writableState.updateNextTick();
        this._writableState.end(data);
        return this;
      }
    };
    var Transform2 = class extends Duplex {
      constructor(opts) {
        super(opts);
        this._transformState = new TransformState(this);
        if (opts) {
          if (opts.transform) this._transform = opts.transform;
          if (opts.flush) this._flush = opts.flush;
        }
      }
      _write(data, cb) {
        if (this._readableState.buffered >= this._readableState.highWaterMark) {
          this._transformState.data = data;
        } else {
          this._transform(data, this._transformState.afterTransform);
        }
      }
      _read(cb) {
        if (this._transformState.data !== null) {
          const data = this._transformState.data;
          this._transformState.data = null;
          cb(null);
          this._transform(data, this._transformState.afterTransform);
        } else {
          cb(null);
        }
      }
      destroy(err) {
        super.destroy(err);
        if (this._transformState.data !== null) {
          this._transformState.data = null;
          this._transformState.afterTransform();
        }
      }
      _transform(data, cb) {
        cb(null, data);
      }
      _flush(cb) {
        cb(null);
      }
      _final(cb) {
        this._transformState.afterFinal = cb;
        this._flush(transformAfterFlush.bind(this));
      }
    };
    var PassThrough = class extends Transform2 {
    };
    function transformAfterFlush(err, data) {
      const cb = this._transformState.afterFinal;
      if (err) return cb(err);
      if (data !== null && data !== void 0) this.push(data);
      this.push(null);
      cb(null);
    }
    function pipelinePromise(...streams) {
      return new Promise((resolve8, reject) => {
        return pipeline(...streams, (err) => {
          if (err) return reject(err);
          resolve8();
        });
      });
    }
    function pipeline(stream, ...streams) {
      const all2 = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams];
      const done = all2.length && typeof all2[all2.length - 1] === "function" ? all2.pop() : null;
      if (all2.length < 2) throw new Error("Pipeline requires at least 2 streams");
      let src = all2[0];
      let dest = null;
      let error101 = null;
      for (let i = 1; i < all2.length; i++) {
        dest = all2[i];
        if (isStreamx(src)) {
          src.pipe(dest, onerror);
        } else {
          errorHandle(src, true, i > 1, onerror);
          src.pipe(dest);
        }
        src = dest;
      }
      if (done) {
        let fin = false;
        const autoDestroy = isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy);
        dest.on("error", (err) => {
          if (error101 === null) error101 = err;
        });
        dest.on("finish", () => {
          fin = true;
          if (!autoDestroy) done(error101);
        });
        if (autoDestroy) {
          dest.on("close", () => done(error101 || (fin ? null : PREMATURE_CLOSE)));
        }
      }
      return dest;
      function errorHandle(s, rd, wr, onerror2) {
        s.on("error", onerror2);
        s.on("close", onclose);
        function onclose() {
          if (rd && s._readableState && !s._readableState.ended) return onerror2(PREMATURE_CLOSE);
          if (wr && s._writableState && !s._writableState.ended) return onerror2(PREMATURE_CLOSE);
        }
      }
      function onerror(err) {
        if (!err || error101) return;
        error101 = err;
        for (const s of all2) {
          s.destroy(err);
        }
      }
    }
    function echo(s) {
      return s;
    }
    function isStream(stream) {
      return !!stream._readableState || !!stream._writableState;
    }
    function isStreamx(stream) {
      return typeof stream._duplexState === "number" && isStream(stream);
    }
    function isEnded(stream) {
      return !!stream._readableState && stream._readableState.ended;
    }
    function isFinished(stream) {
      return !!stream._writableState && stream._writableState.ended;
    }
    function getStreamError(stream, opts = {}) {
      const err = stream._readableState && stream._readableState.error || stream._writableState && stream._writableState.error;
      return !opts.all && err === STREAM_DESTROYED ? null : err;
    }
    function isReadStreamx(stream) {
      return isStreamx(stream) && stream.readable;
    }
    function isDisturbed(stream) {
      return (stream._duplexState & OPENING) !== OPENING || (stream._duplexState & ACTIVE_OR_TICKING) !== 0;
    }
    function isTypedArray(data) {
      return typeof data === "object" && data !== null && typeof data.byteLength === "number";
    }
    function defaultByteLength(data) {
      return isTypedArray(data) ? data.byteLength : 1024;
    }
    function noop() {
    }
    function abort() {
      this.destroy(new Error("Stream aborted."));
    }
    function isWritev(s) {
      return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev;
    }
    module2.exports = {
      pipeline,
      pipelinePromise,
      isStream,
      isStreamx,
      isEnded,
      isFinished,
      isDisturbed,
      getStreamError,
      Stream: Stream2,
      Writable,
      Readable: Readable3,
      Duplex,
      Transform: Transform2,
      // Export PassThrough for compatibility with Node.js core's stream module
      PassThrough
    };
  }
});

// ../../node_modules/.pnpm/tar-stream@3.1.7/node_modules/tar-stream/headers.js
var require_headers = __commonJS({
  "../../node_modules/.pnpm/tar-stream@3.1.7/node_modules/tar-stream/headers.js"(exports2) {
    "use strict";
    var b4a = require_b4a();
    var ZEROS = "0000000000000000000";
    var SEVENS = "7777777777777777777";
    var ZERO_OFFSET = "0".charCodeAt(0);
    var USTAR_MAGIC = b4a.from([117, 115, 116, 97, 114, 0]);
    var USTAR_VER = b4a.from([ZERO_OFFSET, ZERO_OFFSET]);
    var GNU_MAGIC = b4a.from([117, 115, 116, 97, 114, 32]);
    var GNU_VER = b4a.from([32, 0]);
    var MASK = 4095;
    var MAGIC_OFFSET = 257;
    var VERSION_OFFSET = 263;
    exports2.decodeLongPath = function decodeLongPath(buf, encoding) {
      return decodeStr(buf, 0, buf.length, encoding);
    };
    exports2.encodePax = function encodePax(opts) {
      let result = "";
      if (opts.name) result += addLength(" path=" + opts.name + "\n");
      if (opts.linkname) result += addLength(" linkpath=" + opts.linkname + "\n");
      const pax = opts.pax;
      if (pax) {
        for (const key in pax) {
          result += addLength(" " + key + "=" + pax[key] + "\n");
        }
      }
      return b4a.from(result);
    };
    exports2.decodePax = function decodePax(buf) {
      const result = {};
      while (buf.length) {
        let i = 0;
        while (i < buf.length && buf[i] !== 32) i++;
        const len = parseInt(b4a.toString(buf.subarray(0, i)), 10);
        if (!len) return result;
        const b = b4a.toString(buf.subarray(i + 1, len - 1));
        const keyIndex = b.indexOf("=");
        if (keyIndex === -1) return result;
        result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1);
        buf = buf.subarray(len);
      }
      return result;
    };
    exports2.encode = function encode5(opts) {
      const buf = b4a.alloc(512);
      let name = opts.name;
      let prefix = "";
      if (opts.typeflag === 5 && name[name.length - 1] !== "/") name += "/";
      if (b4a.byteLength(name) !== name.length) return null;
      while (b4a.byteLength(name) > 100) {
        const i = name.indexOf("/");
        if (i === -1) return null;
        prefix += prefix ? "/" + name.slice(0, i) : name.slice(0, i);
        name = name.slice(i + 1);
      }
      if (b4a.byteLength(name) > 100 || b4a.byteLength(prefix) > 155) return null;
      if (opts.linkname && b4a.byteLength(opts.linkname) > 100) return null;
      b4a.write(buf, name);
      b4a.write(buf, encodeOct(opts.mode & MASK, 6), 100);
      b4a.write(buf, encodeOct(opts.uid, 6), 108);
      b4a.write(buf, encodeOct(opts.gid, 6), 116);
      encodeSize(opts.size, buf, 124);
      b4a.write(buf, encodeOct(opts.mtime.getTime() / 1e3 | 0, 11), 136);
      buf[156] = ZERO_OFFSET + toTypeflag(opts.type);
      if (opts.linkname) b4a.write(buf, opts.linkname, 157);
      b4a.copy(USTAR_MAGIC, buf, MAGIC_OFFSET);
      b4a.copy(USTAR_VER, buf, VERSION_OFFSET);
      if (opts.uname) b4a.write(buf, opts.uname, 265);
      if (opts.gname) b4a.write(buf, opts.gname, 297);
      b4a.write(buf, encodeOct(opts.devmajor || 0, 6), 329);
      b4a.write(buf, encodeOct(opts.devminor || 0, 6), 337);
      if (prefix) b4a.write(buf, prefix, 345);
      b4a.write(buf, encodeOct(cksum(buf), 6), 148);
      return buf;
    };
    exports2.decode = function decode5(buf, filenameEncoding, allowUnknownFormat) {
      let typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET;
      let name = decodeStr(buf, 0, 100, filenameEncoding);
      const mode = decodeOct(buf, 100, 8);
      const uid = decodeOct(buf, 108, 8);
      const gid = decodeOct(buf, 116, 8);
      const size = decodeOct(buf, 124, 12);
      const mtime = decodeOct(buf, 136, 12);
      const type = toType(typeflag);
      const linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100, filenameEncoding);
      const uname = decodeStr(buf, 265, 32);
      const gname = decodeStr(buf, 297, 32);
      const devmajor = decodeOct(buf, 329, 8);
      const devminor = decodeOct(buf, 337, 8);
      const c2 = cksum(buf);
      if (c2 === 8 * 32) return null;
      if (c2 !== decodeOct(buf, 148, 8)) throw new Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");
      if (isUSTAR(buf)) {
        if (buf[345]) name = decodeStr(buf, 345, 155, filenameEncoding) + "/" + name;
      } else if (isGNU(buf)) {
      } else {
        if (!allowUnknownFormat) {
          throw new Error("Invalid tar header: unknown format.");
        }
      }
      if (typeflag === 0 && name && name[name.length - 1] === "/") typeflag = 5;
      return {
        name,
        mode,
        uid,
        gid,
        size,
        mtime: new Date(1e3 * mtime),
        type,
        linkname,
        uname,
        gname,
        devmajor,
        devminor,
        pax: null
      };
    };
    function isUSTAR(buf) {
      return b4a.equals(USTAR_MAGIC, buf.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6));
    }
    function isGNU(buf) {
      return b4a.equals(GNU_MAGIC, buf.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6)) && b4a.equals(GNU_VER, buf.subarray(VERSION_OFFSET, VERSION_OFFSET + 2));
    }
    function clamp(index, len, defaultValue) {
      if (typeof index !== "number") return defaultValue;
      index = ~~index;
      if (index >= len) return len;
      if (index >= 0) return index;
      index += len;
      if (index >= 0) return index;
      return 0;
    }
    function toType(flag) {
      switch (flag) {
        case 0:
          return "file";
        case 1:
          return "link";
        case 2:
          return "symlink";
        case 3:
          return "character-device";
        case 4:
          return "block-device";
        case 5:
          return "directory";
        case 6:
          return "fifo";
        case 7:
          return "contiguous-file";
        case 72:
          return "pax-header";
        case 55:
          return "pax-global-header";
        case 27:
          return "gnu-long-link-path";
        case 28:
        case 30:
          return "gnu-long-path";
      }
      return null;
    }
    function toTypeflag(flag) {
      switch (flag) {
        case "file":
          return 0;
        case "link":
          return 1;
        case "symlink":
          return 2;
        case "character-device":
          return 3;
        case "block-device":
          return 4;
        case "directory":
          return 5;
        case "fifo":
          return 6;
        case "contiguous-file":
          return 7;
        case "pax-header":
          return 72;
      }
      return 0;
    }
    function indexOf(block, num, offset, end) {
      for (; offset < end; offset++) {
        if (block[offset] === num) return offset;
      }
      return end;
    }
    function cksum(block) {
      let sum = 8 * 32;
      for (let i = 0; i < 148; i++) sum += block[i];
      for (let j = 156; j < 512; j++) sum += block[j];
      return sum;
    }
    function encodeOct(val, n) {
      val = val.toString(8);
      if (val.length > n) return SEVENS.slice(0, n) + " ";
      return ZEROS.slice(0, n - val.length) + val + " ";
    }
    function encodeSizeBin(num, buf, off) {
      buf[off] = 128;
      for (let i = 11; i > 0; i--) {
        buf[off + i] = num & 255;
        num = Math.floor(num / 256);
      }
    }
    function encodeSize(num, buf, off) {
      if (num.toString(8).length > 11) {
        encodeSizeBin(num, buf, off);
      } else {
        b4a.write(buf, encodeOct(num, 11), off);
      }
    }
    function parse256(buf) {
      let positive;
      if (buf[0] === 128) positive = true;
      else if (buf[0] === 255) positive = false;
      else return null;
      const tuple3 = [];
      let i;
      for (i = buf.length - 1; i > 0; i--) {
        const byte = buf[i];
        if (positive) tuple3.push(byte);
        else tuple3.push(255 - byte);
      }
      let sum = 0;
      const l = tuple3.length;
      for (i = 0; i < l; i++) {
        sum += tuple3[i] * Math.pow(256, i);
      }
      return positive ? sum : -1 * sum;
    }
    function decodeOct(val, offset, length) {
      val = val.subarray(offset, offset + length);
      offset = 0;
      if (val[offset] & 128) {
        return parse256(val);
      } else {
        while (offset < val.length && val[offset] === 32) offset++;
        const end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length);
        while (offset < end && val[offset] === 0) offset++;
        if (end === offset) return 0;
        return parseInt(b4a.toString(val.subarray(offset, end)), 8);
      }
    }
    function decodeStr(val, offset, length, encoding) {
      return b4a.toString(val.subarray(offset, indexOf(val, 0, offset, offset + length)), encoding);
    }
    function addLength(str) {
      const len = b4a.byteLength(str);
      let digits = Math.floor(Math.log(len) / Math.log(10)) + 1;
      if (len + digits >= Math.pow(10, digits)) digits++;
      return len + digits + str;
    }
  }
});

// ../../node_modules/.pnpm/tar-stream@3.1.7/node_modules/tar-stream/extract.js
var require_extract = __commonJS({
  "../../node_modules/.pnpm/tar-stream@3.1.7/node_modules/tar-stream/extract.js"(exports2, module2) {
    "use strict";
    var { Writable, Readable: Readable3, getStreamError } = require_streamx();
    var FIFO = require_fast_fifo();
    var b4a = require_b4a();
    var headers = require_headers();
    var EMPTY = b4a.alloc(0);
    var BufferList = class {
      constructor() {
        this.buffered = 0;
        this.shifted = 0;
        this.queue = new FIFO();
        this._offset = 0;
      }
      push(buffer) {
        this.buffered += buffer.byteLength;
        this.queue.push(buffer);
      }
      shiftFirst(size) {
        return this._buffered === 0 ? null : this._next(size);
      }
      shift(size) {
        if (size > this.buffered) return null;
        if (size === 0) return EMPTY;
        let chunk = this._next(size);
        if (size === chunk.byteLength) return chunk;
        const chunks = [chunk];
        while ((size -= chunk.byteLength) > 0) {
          chunk = this._next(size);
          chunks.push(chunk);
        }
        return b4a.concat(chunks);
      }
      _next(size) {
        const buf = this.queue.peek();
        const rem = buf.byteLength - this._offset;
        if (size >= rem) {
          const sub = this._offset ? buf.subarray(this._offset, buf.byteLength) : buf;
          this.queue.shift();
          this._offset = 0;
          this.buffered -= rem;
          this.shifted += rem;
          return sub;
        }
        this.buffered -= size;
        this.shifted += size;
        return buf.subarray(this._offset, this._offset += size);
      }
    };
    var Source = class extends Readable3 {
      constructor(self2, header, offset) {
        super();
        this.header = header;
        this.offset = offset;
        this._parent = self2;
      }
      _read(cb) {
        if (this.header.size === 0) {
          this.push(null);
        }
        if (this._parent._stream === this) {
          this._parent._update();
        }
        cb(null);
      }
      _predestroy() {
        this._parent.destroy(getStreamError(this));
      }
      _detach() {
        if (this._parent._stream === this) {
          this._parent._stream = null;
          this._parent._missing = overflow(this.header.size);
          this._parent._update();
        }
      }
      _destroy(cb) {
        this._detach();
        cb(null);
      }
    };
    var Extract = class extends Writable {
      constructor(opts) {
        super(opts);
        if (!opts) opts = {};
        this._buffer = new BufferList();
        this._offset = 0;
        this._header = null;
        this._stream = null;
        this._missing = 0;
        this._longHeader = false;
        this._callback = noop;
        this._locked = false;
        this._finished = false;
        this._pax = null;
        this._paxGlobal = null;
        this._gnuLongPath = null;
        this._gnuLongLinkPath = null;
        this._filenameEncoding = opts.filenameEncoding || "utf-8";
        this._allowUnknownFormat = !!opts.allowUnknownFormat;
        this._unlockBound = this._unlock.bind(this);
      }
      _unlock(err) {
        this._locked = false;
        if (err) {
          this.destroy(err);
          this._continueWrite(err);
          return;
        }
        this._update();
      }
      _consumeHeader() {
        if (this._locked) return false;
        this._offset = this._buffer.shifted;
        try {
          this._header = headers.decode(this._buffer.shift(512), this._filenameEncoding, this._allowUnknownFormat);
        } catch (err) {
          this._continueWrite(err);
          return false;
        }
        if (!this._header) return true;
        switch (this._header.type) {
          case "gnu-long-path":
          case "gnu-long-link-path":
          case "pax-global-header":
          case "pax-header":
            this._longHeader = true;
            this._missing = this._header.size;
            return true;
        }
        this._locked = true;
        this._applyLongHeaders();
        if (this._header.size === 0 || this._header.type === "directory") {
          this.emit("entry", this._header, this._createStream(), this._unlockBound);
          return true;
        }
        this._stream = this._createStream();
        this._missing = this._header.size;
        this.emit("entry", this._header, this._stream, this._unlockBound);
        return true;
      }
      _applyLongHeaders() {
        if (this._gnuLongPath) {
          this._header.name = this._gnuLongPath;
          this._gnuLongPath = null;
        }
        if (this._gnuLongLinkPath) {
          this._header.linkname = this._gnuLongLinkPath;
          this._gnuLongLinkPath = null;
        }
        if (this._pax) {
          if (this._pax.path) this._header.name = this._pax.path;
          if (this._pax.linkpath) this._header.linkname = this._pax.linkpath;
          if (this._pax.size) this._header.size = parseInt(this._pax.size, 10);
          this._header.pax = this._pax;
          this._pax = null;
        }
      }
      _decodeLongHeader(buf) {
        switch (this._header.type) {
          case "gnu-long-path":
            this._gnuLongPath = headers.decodeLongPath(buf, this._filenameEncoding);
            break;
          case "gnu-long-link-path":
            this._gnuLongLinkPath = headers.decodeLongPath(buf, this._filenameEncoding);
            break;
          case "pax-global-header":
            this._paxGlobal = headers.decodePax(buf);
            break;
          case "pax-header":
            this._pax = this._paxGlobal === null ? headers.decodePax(buf) : Object.assign({}, this._paxGlobal, headers.decodePax(buf));
            break;
        }
      }
      _consumeLongHeader() {
        this._longHeader = false;
        this._missing = overflow(this._header.size);
        const buf = this._buffer.shift(this._header.size);
        try {
          this._decodeLongHeader(buf);
        } catch (err) {
          this._continueWrite(err);
          return false;
        }
        return true;
      }
      _consumeStream() {
        const buf = this._buffer.shiftFirst(this._missing);
        if (buf === null) return false;
        this._missing -= buf.byteLength;
        const drained = this._stream.push(buf);
        if (this._missing === 0) {
          this._stream.push(null);
          if (drained) this._stream._detach();
          return drained && this._locked === false;
        }
        return drained;
      }
      _createStream() {
        return new Source(this, this._header, this._offset);
      }
      _update() {
        while (this._buffer.buffered > 0 && !this.destroying) {
          if (this._missing > 0) {
            if (this._stream !== null) {
              if (this._consumeStream() === false) return;
              continue;
            }
            if (this._longHeader === true) {
              if (this._missing > this._buffer.buffered) break;
              if (this._consumeLongHeader() === false) return false;
              continue;
            }
            const ignore2 = this._buffer.shiftFirst(this._missing);
            if (ignore2 !== null) this._missing -= ignore2.byteLength;
            continue;
          }
          if (this._buffer.buffered < 512) break;
          if (this._stream !== null || this._consumeHeader() === false) return;
        }
        this._continueWrite(null);
      }
      _continueWrite(err) {
        const cb = this._callback;
        this._callback = noop;
        cb(err);
      }
      _write(data, cb) {
        this._callback = cb;
        this._buffer.push(data);
        this._update();
      }
      _final(cb) {
        this._finished = this._missing === 0 && this._buffer.buffered === 0;
        cb(this._finished ? null : new Error("Unexpected end of data"));
      }
      _predestroy() {
        this._continueWrite(null);
      }
      _destroy(cb) {
        if (this._stream) this._stream.destroy(getStreamError(this));
        cb(null);
      }
      [Symbol.asyncIterator]() {
        let error101 = null;
        let promiseResolve = null;
        let promiseReject = null;
        let entryStream = null;
        let entryCallback = null;
        const extract = this;
        this.on("entry", onentry);
        this.on("error", (err) => {
          error101 = err;
        });
        this.on("close", onclose);
        return {
          [Symbol.asyncIterator]() {
            return this;
          },
          next() {
            return new Promise(onnext);
          },
          return() {
            return destroy(null);
          },
          throw(err) {
            return destroy(err);
          }
        };
        function consumeCallback(err) {
          if (!entryCallback) return;
          const cb = entryCallback;
          entryCallback = null;
          cb(err);
        }
        function onnext(resolve8, reject) {
          if (error101) {
            return reject(error101);
          }
          if (entryStream) {
            resolve8({ value: entryStream, done: false });
            entryStream = null;
            return;
          }
          promiseResolve = resolve8;
          promiseReject = reject;
          consumeCallback(null);
          if (extract._finished && promiseResolve) {
            promiseResolve({ value: void 0, done: true });
            promiseResolve = promiseReject = null;
          }
        }
        function onentry(header, stream, callback) {
          entryCallback = callback;
          stream.on("error", noop);
          if (promiseResolve) {
            promiseResolve({ value: stream, done: false });
            promiseResolve = promiseReject = null;
          } else {
            entryStream = stream;
          }
        }
        function onclose() {
          consumeCallback(error101);
          if (!promiseResolve) return;
          if (error101) promiseReject(error101);
          else promiseResolve({ value: void 0, done: true });
          promiseResolve = promiseReject = null;
        }
        function destroy(err) {
          extract.destroy(err);
          consumeCallback(err);
          return new Promise((resolve8, reject) => {
            if (extract.destroyed) return resolve8({ value: void 0, done: true });
            extract.once("close", function() {
              if (err) reject(err);
              else resolve8({ value: void 0, done: true });
            });
          });
        }
      }
    };
    module2.exports = function extract(opts) {
      return new Extract(opts);
    };
    function noop() {
    }
    function overflow(size) {
      size &= 511;
      return size && 512 - size;
    }
  }
});

// ../../node_modules/.pnpm/tar-stream@3.1.7/node_modules/tar-stream/constants.js
var require_constants5 = __commonJS({
  "../../node_modules/.pnpm/tar-stream@3.1.7/node_modules/tar-stream/constants.js"(exports2, module2) {
    "use strict";
    var constants3 = {
      // just for envs without fs
      S_IFMT: 61440,
      S_IFDIR: 16384,
      S_IFCHR: 8192,
      S_IFBLK: 24576,
      S_IFIFO: 4096,
      S_IFLNK: 40960
    };
    try {
      module2.exports = require("fs").constants || constants3;
    } catch {
      module2.exports = constants3;
    }
  }
});

// ../../node_modules/.pnpm/tar-stream@3.1.7/node_modules/tar-stream/pack.js
var require_pack = __commonJS({
  "../../node_modules/.pnpm/tar-stream@3.1.7/node_modules/tar-stream/pack.js"(exports2, module2) {
    "use strict";
    var { Readable: Readable3, Writable, getStreamError } = require_streamx();
    var b4a = require_b4a();
    var constants3 = require_constants5();
    var headers = require_headers();
    var DMODE = 493;
    var FMODE = 420;
    var END_OF_TAR = b4a.alloc(1024);
    var Sink = class extends Writable {
      constructor(pack2, header, callback) {
        super({ mapWritable, eagerOpen: true });
        this.written = 0;
        this.header = header;
        this._callback = callback;
        this._linkname = null;
        this._isLinkname = header.type === "symlink" && !header.linkname;
        this._isVoid = header.type !== "file" && header.type !== "contiguous-file";
        this._finished = false;
        this._pack = pack2;
        this._openCallback = null;
        if (this._pack._stream === null) this._pack._stream = this;
        else this._pack._pending.push(this);
      }
      _open(cb) {
        this._openCallback = cb;
        if (this._pack._stream === this) this._continueOpen();
      }
      _continuePack(err) {
        if (this._callback === null) return;
        const callback = this._callback;
        this._callback = null;
        callback(err);
      }
      _continueOpen() {
        if (this._pack._stream === null) this._pack._stream = this;
        const cb = this._openCallback;
        this._openCallback = null;
        if (cb === null) return;
        if (this._pack.destroying) return cb(new Error("pack stream destroyed"));
        if (this._pack._finalized) return cb(new Error("pack stream is already finalized"));
        this._pack._stream = this;
        if (!this._isLinkname) {
          this._pack._encode(this.header);
        }
        if (this._isVoid) {
          this._finish();
          this._continuePack(null);
        }
        cb(null);
      }
      _write(data, cb) {
        if (this._isLinkname) {
          this._linkname = this._linkname ? b4a.concat([this._linkname, data]) : data;
          return cb(null);
        }
        if (this._isVoid) {
          if (data.byteLength > 0) {
            return cb(new Error("No body allowed for this entry"));
          }
          return cb();
        }
        this.written += data.byteLength;
        if (this._pack.push(data)) return cb();
        this._pack._drain = cb;
      }
      _finish() {
        if (this._finished) return;
        this._finished = true;
        if (this._isLinkname) {
          this.header.linkname = this._linkname ? b4a.toString(this._linkname, "utf-8") : "";
          this._pack._encode(this.header);
        }
        overflow(this._pack, this.header.size);
        this._pack._done(this);
      }
      _final(cb) {
        if (this.written !== this.header.size) {
          return cb(new Error("Size mismatch"));
        }
        this._finish();
        cb(null);
      }
      _getError() {
        return getStreamError(this) || new Error("tar entry destroyed");
      }
      _predestroy() {
        this._pack.destroy(this._getError());
      }
      _destroy(cb) {
        this._pack._done(this);
        this._continuePack(this._finished ? null : this._getError());
        cb();
      }
    };
    var Pack = class extends Readable3 {
      constructor(opts) {
        super(opts);
        this._drain = noop;
        this._finalized = false;
        this._finalizing = false;
        this._pending = [];
        this._stream = null;
      }
      entry(header, buffer, callback) {
        if (this._finalized || this.destroying) throw new Error("already finalized or destroyed");
        if (typeof buffer === "function") {
          callback = buffer;
          buffer = null;
        }
        if (!callback) callback = noop;
        if (!header.size || header.type === "symlink") header.size = 0;
        if (!header.type) header.type = modeToType(header.mode);
        if (!header.mode) header.mode = header.type === "directory" ? DMODE : FMODE;
        if (!header.uid) header.uid = 0;
        if (!header.gid) header.gid = 0;
        if (!header.mtime) header.mtime = /* @__PURE__ */ new Date();
        if (typeof buffer === "string") buffer = b4a.from(buffer);
        const sink = new Sink(this, header, callback);
        if (b4a.isBuffer(buffer)) {
          header.size = buffer.byteLength;
          sink.write(buffer);
          sink.end();
          return sink;
        }
        if (sink._isVoid) {
          return sink;
        }
        return sink;
      }
      finalize() {
        if (this._stream || this._pending.length > 0) {
          this._finalizing = true;
          return;
        }
        if (this._finalized) return;
        this._finalized = true;
        this.push(END_OF_TAR);
        this.push(null);
      }
      _done(stream) {
        if (stream !== this._stream) return;
        this._stream = null;
        if (this._finalizing) this.finalize();
        if (this._pending.length) this._pending.shift()._continueOpen();
      }
      _encode(header) {
        if (!header.pax) {
          const buf = headers.encode(header);
          if (buf) {
            this.push(buf);
            return;
          }
        }
        this._encodePax(header);
      }
      _encodePax(header) {
        const paxHeader = headers.encodePax({
          name: header.name,
          linkname: header.linkname,
          pax: header.pax
        });
        const newHeader = {
          name: "PaxHeader",
          mode: header.mode,
          uid: header.uid,
          gid: header.gid,
          size: paxHeader.byteLength,
          mtime: header.mtime,
          type: "pax-header",
          linkname: header.linkname && "PaxHeader",
          uname: header.uname,
          gname: header.gname,
          devmajor: header.devmajor,
          devminor: header.devminor
        };
        this.push(headers.encode(newHeader));
        this.push(paxHeader);
        overflow(this, paxHeader.byteLength);
        newHeader.size = header.size;
        newHeader.type = header.type;
        this.push(headers.encode(newHeader));
      }
      _doDrain() {
        const drain = this._drain;
        this._drain = noop;
        drain();
      }
      _predestroy() {
        const err = getStreamError(this);
        if (this._stream) this._stream.destroy(err);
        while (this._pending.length) {
          const stream = this._pending.shift();
          stream.destroy(err);
          stream._continueOpen();
        }
        this._doDrain();
      }
      _read(cb) {
        this._doDrain();
        cb();
      }
    };
    module2.exports = function pack2(opts) {
      return new Pack(opts);
    };
    function modeToType(mode) {
      switch (mode & constants3.S_IFMT) {
        case constants3.S_IFBLK:
          return "block-device";
        case constants3.S_IFCHR:
          return "character-device";
        case constants3.S_IFDIR:
          return "directory";
        case constants3.S_IFIFO:
          return "fifo";
        case constants3.S_IFLNK:
          return "symlink";
      }
      return "file";
    }
    function noop() {
    }
    function overflow(self2, size) {
      size &= 511;
      if (size) self2.push(END_OF_TAR.subarray(0, 512 - size));
    }
    function mapWritable(buf) {
      return b4a.isBuffer(buf) ? buf : b4a.from(buf);
    }
  }
});

// ../../node_modules/.pnpm/tar-stream@3.1.7/node_modules/tar-stream/index.js
var require_tar_stream = __commonJS({
  "../../node_modules/.pnpm/tar-stream@3.1.7/node_modules/tar-stream/index.js"(exports2) {
    "use strict";
    exports2.extract = require_extract();
    exports2.pack = require_pack();
  }
});

// ../../node_modules/.pnpm/tar-fs@3.1.0/node_modules/tar-fs/index.js
var require_tar_fs = __commonJS({
  "../../node_modules/.pnpm/tar-fs@3.1.0/node_modules/tar-fs/index.js"(exports2) {
    "use strict";
    var tar = require_tar_stream();
    var pump = require_pump();
    var fs68 = require("fs");
    var path73 = require("path");
    var win32 = (global.Bare ? global.Bare.platform : process.platform) === "win32";
    exports2.pack = function pack2(cwd2, opts) {
      if (!cwd2) cwd2 = ".";
      if (!opts) opts = {};
      const xfs = opts.fs || fs68;
      const ignore2 = opts.ignore || opts.filter || noop;
      const mapStream = opts.mapStream || echo;
      const statNext = statAll(xfs, opts.dereference ? xfs.stat : xfs.lstat, cwd2, ignore2, opts.entries, opts.sort);
      const strict = opts.strict !== false;
      const umask = typeof opts.umask === "number" ? ~opts.umask : ~processUmask();
      const pack3 = opts.pack || tar.pack();
      const finish = opts.finish || noop;
      let map3 = opts.map || noop;
      let dmode = typeof opts.dmode === "number" ? opts.dmode : 0;
      let fmode = typeof opts.fmode === "number" ? opts.fmode : 0;
      if (opts.strip) map3 = strip(map3, opts.strip);
      if (opts.readable) {
        dmode |= parseInt(555, 8);
        fmode |= parseInt(444, 8);
      }
      if (opts.writable) {
        dmode |= parseInt(333, 8);
        fmode |= parseInt(222, 8);
      }
      onnextentry();
      function onsymlink(filename, header) {
        xfs.readlink(path73.join(cwd2, filename), function(err, linkname) {
          if (err) return pack3.destroy(err);
          header.linkname = normalize2(linkname);
          pack3.entry(header, onnextentry);
        });
      }
      function onstat(err, filename, stat4) {
        if (pack3.destroyed) return;
        if (err) return pack3.destroy(err);
        if (!filename) {
          if (opts.finalize !== false) pack3.finalize();
          return finish(pack3);
        }
        if (stat4.isSocket()) return onnextentry();
        let header = {
          name: normalize2(filename),
          mode: (stat4.mode | (stat4.isDirectory() ? dmode : fmode)) & umask,
          mtime: stat4.mtime,
          size: stat4.size,
          type: "file",
          uid: stat4.uid,
          gid: stat4.gid
        };
        if (stat4.isDirectory()) {
          header.size = 0;
          header.type = "directory";
          header = map3(header) || header;
          return pack3.entry(header, onnextentry);
        }
        if (stat4.isSymbolicLink()) {
          header.size = 0;
          header.type = "symlink";
          header = map3(header) || header;
          return onsymlink(filename, header);
        }
        header = map3(header) || header;
        if (!stat4.isFile()) {
          if (strict) return pack3.destroy(new Error("unsupported type for " + filename));
          return onnextentry();
        }
        const entry = pack3.entry(header, onnextentry);
        const rs = mapStream(xfs.createReadStream(path73.join(cwd2, filename), { start: 0, end: header.size > 0 ? header.size - 1 : header.size }), header);
        rs.on("error", function(err2) {
          entry.destroy(err2);
        });
        pump(rs, entry);
      }
      function onnextentry(err) {
        if (err) return pack3.destroy(err);
        statNext(onstat);
      }
      return pack3;
    };
    function head(list) {
      return list.length ? list[list.length - 1] : null;
    }
    function processGetuid() {
      return !global.Bare && process.getuid ? process.getuid() : -1;
    }
    function processUmask() {
      return !global.Bare && process.umask ? process.umask() : 0;
    }
    exports2.extract = function extract(cwd2, opts) {
      if (!cwd2) cwd2 = ".";
      if (!opts) opts = {};
      cwd2 = path73.resolve(cwd2);
      const xfs = opts.fs || fs68;
      const ignore2 = opts.ignore || opts.filter || noop;
      const mapStream = opts.mapStream || echo;
      const own = opts.chown !== false && !win32 && processGetuid() === 0;
      const extract2 = opts.extract || tar.extract();
      const stack = [];
      const now = /* @__PURE__ */ new Date();
      const umask = typeof opts.umask === "number" ? ~opts.umask : ~processUmask();
      const strict = opts.strict !== false;
      const validateSymLinks = opts.validateSymlinks !== false;
      let map3 = opts.map || noop;
      let dmode = typeof opts.dmode === "number" ? opts.dmode : 0;
      let fmode = typeof opts.fmode === "number" ? opts.fmode : 0;
      if (opts.strip) map3 = strip(map3, opts.strip);
      if (opts.readable) {
        dmode |= parseInt(555, 8);
        fmode |= parseInt(444, 8);
      }
      if (opts.writable) {
        dmode |= parseInt(333, 8);
        fmode |= parseInt(222, 8);
      }
      extract2.on("entry", onentry);
      if (opts.finish) extract2.on("finish", opts.finish);
      return extract2;
      function onentry(header, stream, next) {
        header = map3(header) || header;
        header.name = normalize2(header.name);
        const name = path73.join(cwd2, path73.join("/", header.name));
        if (ignore2(name, header)) {
          stream.resume();
          return next();
        }
        const dir3 = path73.join(name, ".") === path73.join(cwd2, ".") ? cwd2 : path73.dirname(name);
        validate2(xfs, dir3, path73.join(cwd2, "."), function(err, valid) {
          if (err) return next(err);
          if (!valid) return next(new Error(dir3 + " is not a valid path"));
          if (header.type === "directory") {
            stack.push([name, header.mtime]);
            return mkdirfix(name, {
              fs: xfs,
              own,
              uid: header.uid,
              gid: header.gid,
              mode: header.mode
            }, stat4);
          }
          mkdirfix(dir3, {
            fs: xfs,
            own,
            uid: header.uid,
            gid: header.gid,
            // normally, the folders with rights and owner should be part of the TAR file
            // if this is not the case, create folder for same user as file and with
            // standard permissions of 0o755 (rwxr-xr-x)
            mode: 493
          }, function(err2) {
            if (err2) return next(err2);
            switch (header.type) {
              case "file":
                return onfile();
              case "link":
                return onlink();
              case "symlink":
                return onsymlink();
            }
            if (strict) return next(new Error("unsupported type for " + name + " (" + header.type + ")"));
            stream.resume();
            next();
          });
        });
        function stat4(err) {
          if (err) return next(err);
          utimes(name, header, function(err2) {
            if (err2) return next(err2);
            if (win32) return next();
            chperm(name, header, next);
          });
        }
        function onsymlink() {
          if (win32) return next();
          xfs.unlink(name, function() {
            const dst = path73.resolve(path73.dirname(name), header.linkname);
            if (!inCwd(dst) && validateSymLinks) return next(new Error(name + " is not a valid symlink"));
            xfs.symlink(header.linkname, name, stat4);
          });
        }
        function onlink() {
          if (win32) return next();
          xfs.unlink(name, function() {
            const link = path73.join(cwd2, path73.join("/", header.linkname));
            fs68.realpath(link, function(err, dst) {
              if (err || !inCwd(dst)) return next(new Error(name + " is not a valid hardlink"));
              xfs.link(dst, name, function(err2) {
                if (err2 && err2.code === "EPERM" && opts.hardlinkAsFilesFallback) {
                  stream = xfs.createReadStream(dst);
                  return onfile();
                }
                stat4(err2);
              });
            });
          });
        }
        function inCwd(dst) {
          return dst.startsWith(cwd2);
        }
        function onfile() {
          const ws = xfs.createWriteStream(name);
          const rs = mapStream(stream, header);
          ws.on("error", function(err) {
            rs.destroy(err);
          });
          pump(rs, ws, function(err) {
            if (err) return next(err);
            ws.on("close", stat4);
          });
        }
      }
      function utimesParent(name, cb) {
        let top;
        while ((top = head(stack)) && name.slice(0, top[0].length) !== top[0]) stack.pop();
        if (!top) return cb();
        xfs.utimes(top[0], now, top[1], cb);
      }
      function utimes(name, header, cb) {
        if (opts.utimes === false) return cb();
        if (header.type === "directory") return xfs.utimes(name, now, header.mtime, cb);
        if (header.type === "symlink") return utimesParent(name, cb);
        xfs.utimes(name, now, header.mtime, function(err) {
          if (err) return cb(err);
          utimesParent(name, cb);
        });
      }
      function chperm(name, header, cb) {
        const link = header.type === "symlink";
        const chmod = link ? xfs.lchmod : xfs.chmod;
        const chown = link ? xfs.lchown : xfs.chown;
        if (!chmod) return cb();
        const mode = (header.mode | (header.type === "directory" ? dmode : fmode)) & umask;
        if (chown && own) chown.call(xfs, name, header.uid, header.gid, onchown);
        else onchown(null);
        function onchown(err) {
          if (err) return cb(err);
          if (!chmod) return cb();
          chmod.call(xfs, name, mode, cb);
        }
      }
      function mkdirfix(name, opts2, cb) {
        xfs.stat(name, function(err) {
          if (!err) return cb(null);
          if (err.code !== "ENOENT") return cb(err);
          xfs.mkdir(name, { mode: opts2.mode, recursive: true }, function(err2, made) {
            if (err2) return cb(err2);
            chperm(name, opts2, cb);
          });
        });
      }
    };
    function validate2(fs69, name, root, cb) {
      if (name === root) return cb(null, true);
      fs69.lstat(name, function(err, st) {
        if (err && err.code !== "ENOENT" && err.code !== "EPERM") return cb(err);
        if (err || st.isDirectory()) return validate2(fs69, path73.join(name, ".."), root, cb);
        cb(null, false);
      });
    }
    function noop() {
    }
    function echo(name) {
      return name;
    }
    function normalize2(name) {
      return win32 ? name.replace(/\\/g, "/").replace(/[:?<>|]/g, "_") : name;
    }
    function statAll(fs69, stat4, cwd2, ignore2, entries, sort) {
      if (!entries) entries = ["."];
      const queue = entries.slice(0);
      return function loop(callback) {
        if (!queue.length) return callback(null);
        const next = queue.shift();
        const nextAbs = path73.join(cwd2, next);
        stat4.call(fs69, nextAbs, function(err, stat5) {
          if (err) return callback(entries.indexOf(next) === -1 && err.code === "ENOENT" ? null : err);
          if (!stat5.isDirectory()) return callback(null, next, stat5);
          fs69.readdir(nextAbs, function(err2, files) {
            if (err2) return callback(err2);
            if (sort) files.sort();
            for (let i = 0; i < files.length; i++) {
              if (!ignore2(path73.join(cwd2, next, files[i]))) queue.push(path73.join(next, files[i]));
            }
            callback(null, next, stat5);
          });
        });
      };
    }
    function strip(map3, level) {
      return function(header) {
        header.name = header.name.split("/").slice(level).join("/");
        const linkname = header.linkname;
        if (linkname && (header.type === "link" || path73.isAbsolute(linkname))) {
          header.linkname = linkname.split("/").slice(level).join("/");
        }
        return map3(header);
      };
    }
  }
});

// src/index.ts
var src_exports = {};
__export(src_exports, {
  AGENT_MEMORY_PLUGIN: () => AGENT_MEMORY_PLUGIN,
  AGENT_MEMORY_PLUGIN_NAME: () => AGENT_MEMORY_PLUGIN_NAME,
  AI_PLUGIN: () => AI_PLUGIN,
  AI_PLUGIN_NAME: () => AI_PLUGIN_NAME,
  AI_SEARCH_PLUGIN: () => AI_SEARCH_PLUGIN,
  AI_SEARCH_PLUGIN_NAME: () => AI_SEARCH_PLUGIN_NAME,
  ANALYTICS_ENGINE_PLUGIN: () => ANALYTICS_ENGINE_PLUGIN,
  ANALYTICS_ENGINE_PLUGIN_NAME: () => ANALYTICS_ENGINE_PLUGIN_NAME,
  ARTIFACTS_PLUGIN: () => ARTIFACTS_PLUGIN,
  ARTIFACTS_PLUGIN_NAME: () => ARTIFACTS_PLUGIN_NAME,
  ASSETS_PLUGIN: () => ASSETS_PLUGIN,
  BROWSER_RENDERING_PLUGIN: () => BROWSER_RENDERING_PLUGIN,
  BROWSER_RENDERING_PLUGIN_NAME: () => BROWSER_RENDERING_PLUGIN_NAME,
  CACHE_PLUGIN: () => CACHE_PLUGIN,
  CACHE_PLUGIN_NAME: () => CACHE_PLUGIN_NAME,
  CORE_PLUGIN: () => CORE_PLUGIN,
  CORE_PLUGIN_NAME: () => CORE_PLUGIN_NAME2,
  CacheHeaders: () => CacheHeaders,
  CloseEvent: () => CloseEvent,
  CoreBindings: () => CoreBindings,
  CoreHeaders: () => CoreHeaders,
  CorePaths: () => CorePaths,
  D1_PLUGIN: () => D1_PLUGIN,
  D1_PLUGIN_NAME: () => D1_PLUGIN_NAME,
  DISPATCH_NAMESPACE_PLUGIN: () => DISPATCH_NAMESPACE_PLUGIN,
  DISPATCH_NAMESPACE_PLUGIN_NAME: () => DISPATCH_NAMESPACE_PLUGIN_NAME,
  DOContainerOptionsSchema: () => DOContainerOptionsSchema,
  DURABLE_OBJECTS_PLUGIN: () => DURABLE_OBJECTS_PLUGIN,
  DURABLE_OBJECTS_PLUGIN_NAME: () => DURABLE_OBJECTS_PLUGIN_NAME,
  DURABLE_OBJECTS_STORAGE_SERVICE_NAME: () => DURABLE_OBJECTS_STORAGE_SERVICE_NAME,
  DeferredPromise: () => DeferredPromise,
  DevConfigSchema: () => DevConfigSchema,
  DispatchFetchDispatcher: () => DispatchFetchDispatcher,
  EMAIL_PLUGIN: () => EMAIL_PLUGIN,
  EMAIL_PLUGIN_NAME: () => EMAIL_PLUGIN_NAME,
  ErrorEvent: () => ErrorEvent,
  FLAGSHIP_PLUGIN: () => FLAGSHIP_PLUGIN,
  FLAGSHIP_PLUGIN_NAME: () => FLAGSHIP_PLUGIN_NAME,
  FormData: () => import_undici5.FormData,
  HEADER_QUEUE_NAME: () => HEADER_QUEUE_NAME,
  HELLO_WORLD_PLUGIN: () => HELLO_WORLD_PLUGIN,
  HELLO_WORLD_PLUGIN_NAME: () => HELLO_WORLD_PLUGIN_NAME,
  HOST_CAPNP_CONNECT: () => HOST_CAPNP_CONNECT,
  HYPERDRIVE_PLUGIN: () => HYPERDRIVE_PLUGIN,
  HYPERDRIVE_PLUGIN_NAME: () => HYPERDRIVE_PLUGIN_NAME,
  Headers: () => import_undici5.Headers,
  HttpOptions_Style: () => HttpOptions_Style,
  HyperdriveSchema: () => HyperdriveSchema,
  IMAGES_PLUGIN: () => IMAGES_PLUGIN,
  IMAGES_PLUGIN_NAME: () => IMAGES_PLUGIN_NAME,
  INTROSPECT_SQLITE_METHOD: () => INTROSPECT_SQLITE_METHOD,
  InstanceOptionsSchema: () => InstanceOptionsSchema,
  JsonSchema: () => JsonSchema,
  KVHeaders: () => KVHeaders,
  KVLimits: () => KVLimits,
  KVParams: () => KVParams,
  KV_NAMESPACE_OBJECT_CLASS_NAME: () => KV_NAMESPACE_OBJECT_CLASS_NAME,
  KV_PLUGIN: () => KV_PLUGIN,
  KV_PLUGIN_NAME: () => KV_PLUGIN_NAME,
  LegacyConfigSchema: () => LegacyConfigSchema,
  LiteralSchema: () => LiteralSchema,
  Log: () => Log,
  LogLevel: () => LogLevel,
  MAX_BULK_GET_KEYS: () => MAX_BULK_GET_KEYS,
  MEDIA_PLUGIN: () => MEDIA_PLUGIN,
  MEDIA_PLUGIN_NAME: () => MEDIA_PLUGIN_NAME,
  MTLS_PLUGIN: () => MTLS_PLUGIN,
  MTLS_PLUGIN_NAME: () => MTLS_PLUGIN_NAME,
  MessageEvent: () => MessageEvent,
  Miniflare: () => Miniflare,
  MiniflareCoreError: () => MiniflareCoreError,
  MiniflareDurableObjectExportSchema: () => MiniflareDurableObjectExportSchema,
  MiniflareError: () => MiniflareError,
  MiniflareOptionsSchema: () => MiniflareOptionsSchema,
  MiniflareWorkerConfigBaseSchema: () => MiniflareWorkerConfigBaseSchema,
  MiniflareWorkerConfigSchema: () => MiniflareWorkerConfigSchema,
  Mutex: () => Mutex,
  NoOpLog: () => NoOpLog,
  PIPELINES_PLUGIN_NAME: () => PIPELINES_PLUGIN_NAME,
  PIPELINE_PLUGIN: () => PIPELINE_PLUGIN,
  PLUGINS: () => PLUGINS,
  PLUGIN_ENTRIES: () => PLUGIN_ENTRIES,
  ParsedMiniflareKnownBindingSchema: () => ParsedMiniflareKnownBindingSchema,
  PathSchema: () => PathSchema,
  PeriodType: () => PeriodType,
  ProxyAddresses: () => ProxyAddresses,
  ProxyClient: () => ProxyClient,
  ProxyNodeBinding: () => ProxyNodeBinding,
  ProxyOps: () => ProxyOps,
  QUEUES_PLUGIN: () => QUEUES_PLUGIN,
  QUEUES_PLUGIN_NAME: () => QUEUES_PLUGIN_NAME,
  QueueBindings: () => QueueBindings,
  QueueConsumerOptionsSchema: () => QueueConsumerOptionsSchema,
  QueueConsumerSchema: () => QueueConsumerSchema,
  QueueConsumersSchema: () => QueueConsumersSchema,
  QueueContentTypeSchema: () => QueueContentTypeSchema,
  QueueIncomingMessageSchema: () => QueueIncomingMessageSchema,
  QueueMessageDelaySchema: () => QueueMessageDelaySchema,
  QueueProducerOptionsSchema: () => QueueProducerOptionsSchema,
  QueueProducerSchema: () => QueueProducerSchema,
  QueueProducersSchema: () => QueueProducersSchema,
  QueuesBatchRequestSchema: () => QueuesBatchRequestSchema,
  QueuesError: () => QueuesError,
  R2_PLUGIN: () => R2_PLUGIN,
  R2_PLUGIN_NAME: () => R2_PLUGIN_NAME,
  R2_PUBLIC_SERVICE_NAME: () => R2_PUBLIC_SERVICE_NAME,
  R2_S3_SERVICE_NAME: () => R2_S3_SERVICE_NAME,
  RATELIMIT_PLUGIN: () => RATELIMIT_PLUGIN,
  RATELIMIT_PLUGIN_NAME: () => RATELIMIT_PLUGIN_NAME,
  Request: () => Request,
  Response: () => Response3,
  RouterError: () => RouterError,
  Runtime: () => Runtime,
  SECRET_STORE_PLUGIN: () => SECRET_STORE_PLUGIN,
  SECRET_STORE_PLUGIN_NAME: () => SECRET_STORE_PLUGIN_NAME,
  SERVICE_DEV_REGISTRY_PROXY: () => SERVICE_DEV_REGISTRY_PROXY,
  SERVICE_ENTRY: () => SERVICE_ENTRY,
  SERVICE_LOOPBACK: () => SERVICE_LOOPBACK,
  SERVICE_QUEUE_PREFIX: () => SERVICE_QUEUE_PREFIX,
  SITES_NO_CACHE_PREFIX: () => SITES_NO_CACHE_PREFIX,
  SOCKET_DEBUG_PORT: () => SOCKET_DEBUG_PORT,
  SOCKET_DEV_REGISTRY: () => SOCKET_DEV_REGISTRY,
  SOCKET_ENTRY: () => SOCKET_ENTRY,
  SOCKET_ENTRY_LOCAL: () => SOCKET_ENTRY_LOCAL,
  STREAM_COMPAT_DATE: () => STREAM_COMPAT_DATE,
  STREAM_OBJECT_CLASS_NAME: () => STREAM_OBJECT_CLASS_NAME,
  STREAM_PLUGIN: () => STREAM_PLUGIN,
  STREAM_PLUGIN_NAME: () => STREAM_PLUGIN_NAME,
  SYSTEM_ERROR_CODES: () => SYSTEM_ERROR_CODES,
  SharedBindings: () => SharedBindings,
  SharedHeaders: () => SharedHeaders,
  SiteBindings: () => SiteBindings,
  TlsOptions_Version: () => TlsOptions_Version,
  TypedEventTarget: () => TypedEventTarget,
  USER_ERROR_CODES: () => USER_ERROR_CODES,
  V4MiniflareOptionsSchema: () => V4MiniflareOptionsSchema,
  V4WorkerOptionsSchema: () => V4WorkerOptionsSchema,
  VECTORIZE_PLUGIN: () => VECTORIZE_PLUGIN,
  VECTORIZE_PLUGIN_NAME: () => VECTORIZE_PLUGIN_NAME,
  VERSION_METADATA_PLUGIN: () => VERSION_METADATA_PLUGIN,
  VERSION_METADATA_PLUGIN_NAME: () => VERSION_METADATA_PLUGIN_NAME,
  VPC_NETWORKS_PLUGIN: () => VPC_NETWORKS_PLUGIN,
  VPC_NETWORKS_PLUGIN_NAME: () => VPC_NETWORKS_PLUGIN_NAME,
  VPC_SERVICES_PLUGIN: () => VPC_SERVICES_PLUGIN,
  VPC_SERVICES_PLUGIN_NAME: () => VPC_SERVICES_PLUGIN_NAME,
  WEBSEARCH_PLUGIN: () => WEBSEARCH_PLUGIN,
  WEBSEARCH_PLUGIN_NAME: () => WEBSEARCH_PLUGIN_NAME,
  WORKER_BINDING_SERVICE_LOOPBACK: () => WORKER_BINDING_SERVICE_LOOPBACK,
  WORKER_LOADER_PLUGIN: () => WORKER_LOADER_PLUGIN,
  WORKER_LOADER_PLUGIN_NAME: () => WORKER_LOADER_PLUGIN_NAME,
  WORKFLOWS_PLUGIN: () => WORKFLOWS_PLUGIN,
  WORKFLOWS_PLUGIN_NAME: () => WORKFLOWS_PLUGIN_NAME,
  WORKFLOWS_STORAGE_SERVICE_NAME: () => WORKFLOWS_STORAGE_SERVICE_NAME,
  WaitGroup: () => WaitGroup,
  WebSocket: () => WebSocket,
  WebSocketPair: () => WebSocketPair,
  WorkerOptionsSchema: () => WorkerOptionsSchema,
  Worker_Binding_CryptoKey_Usage: () => Worker_Binding_CryptoKey_Usage,
  __MiniflareFunctionWrapper: () => __MiniflareFunctionWrapper,
  _enableControlEndpoints: () => _enableControlEndpoints,
  _initialiseInstanceRegistry: () => _initialiseInstanceRegistry,
  _isCyclic: () => _isCyclic,
  _transformsForContentEncodingAndContentType: () => _transformsForContentEncodingAndContentType,
  base64Decode: () => base64Decode,
  base64Encode: () => base64Encode,
  buildAssetManifest: () => buildAssetManifest,
  buildObjectEntryProps: () => buildObjectEntryProps,
  buildPublicUrl: () => buildPublicUrl,
  buildRemoteProxyProps: () => buildRemoteProxyProps,
  compileModuleRules: () => compileModuleRules,
  convertV4MiniflareOptions: () => convertV4MiniflareOptions,
  coupleWebSocket: () => coupleWebSocket,
  createHTTPReducers: () => createHTTPReducers,
  createHTTPRevivers: () => createHTTPRevivers,
  decodeErrorPayload: () => decodeErrorPayload,
  decodeSitesKey: () => decodeSitesKey,
  deserialiseRegExps: () => deserialiseRegExps,
  deserialiseSiteRegExps: () => deserialiseSiteRegExps,
  encodeSitesKey: () => encodeSitesKey,
  extractObjectEntryId: () => extractObjectEntryId,
  fetch: () => fetch5,
  formatError: () => formatError3,
  getAccessibleHosts: () => getAccessibleHosts,
  getAssetsBindingsNames: () => getAssetsBindingsNames,
  getCacheServiceName: () => getCacheServiceName,
  getDefaultDevRegistryPath: () => getDefaultDevRegistryPath,
  getDirectSocketName: () => getDirectSocketName,
  getDurableObjectUniqueKey: () => getDurableObjectUniqueKey,
  getEmailPathsToClean: () => getEmailPathsToClean,
  getEntrySocketHttpOptions: () => getEntrySocketHttpOptions,
  getEnvBindingsOfType: () => getEnvBindingsOfType,
  getExportsOfType: () => getExportsOfType,
  getFreshSourceMapSupport: () => getFreshSourceMapSupport,
  getGlobalServices: () => getGlobalServices,
  getLocallyAccessibleHost: () => getLocallyAccessibleHost,
  getMiniflareObjectBindings: () => getMiniflareObjectBindings,
  getNodeCompat: () => getNodeCompat,
  getPersistPath: () => getPersistPath,
  getQueueServiceName: () => getQueueServiceName,
  getR2PublicService: () => getR2PublicService,
  getR2S3Service: () => getR2S3Service,
  getRemoteProxyConnectionString: () => getRemoteProxyConnectionString,
  getTriggersOfType: () => getTriggersOfType,
  getUserBindingServiceName: () => getUserBindingServiceName,
  getWorkerRegistry: () => getWorkerRegistry,
  globsToRegExps: () => globsToRegExps,
  isDurableObjectStub: () => isDurableObjectStub,
  isFetcherFetch: () => isFetcherFetch,
  isFileNotFoundError: () => isFileNotFoundError,
  isImagesInput: () => isImagesInput,
  isR2ObjectWriteHttpMetadata: () => isR2ObjectWriteHttpMetadata,
  isSitesRequest: () => isSitesRequest,
  kCurrentWorker: () => kCurrentWorker,
  kInspectorSocket: () => kInspectorSocket,
  kUnsafeEphemeralUniqueKey: () => kUnsafeEphemeralUniqueKey,
  kVoid: () => kVoid,
  launchBrowser: () => launchBrowser,
  loadExternalPlugins: () => loadExternalPlugins,
  matchRoutes: () => matchRoutes,
  maybeApply: () => maybeApply,
  maybeParseURL: () => maybeParseURL,
  mergeWorkerOptions: () => mergeWorkerOptions,
  namespaceEntries: () => namespaceEntries,
  objectEntryWorker: () => objectEntryWorker,
  parseModuleFallbackRequest: () => parseModuleFallbackRequest,
  parseRanges: () => parseRanges,
  parseRoutes: () => parseRoutes,
  parseWithReadableStreams: () => parseWithReadableStreams,
  parseWithRootPath: () => parseWithRootPath,
  prefixError: () => prefixError,
  prefixStream: () => prefixStream,
  processStackTrace: () => processStackTrace,
  readPrefix: () => readPrefix,
  reduceError: () => reduceError,
  remoteProxyClientWorker: () => remoteProxyClientWorker,
  sanitisePath: () => sanitisePath,
  serialiseRegExps: () => serialiseRegExps,
  serialiseSiteRegExps: () => serialiseSiteRegExps,
  serializeConfig: () => serializeConfig,
  stringifyWithStreams: () => stringifyWithStreams,
  stripAnsi: () => stripAnsi,
  structuredSerializableReducers: () => structuredSerializableReducers,
  structuredSerializableRevivers: () => structuredSerializableRevivers,
  testRegExps: () => testRegExps,
  testSiteRegExps: () => testSiteRegExps,
  viewToBuffer: () => viewToBuffer,
  workerdStructuredLogSchema: () => WorkerdStructuredLogSchema,
  zAwaitable: () => zAwaitable
});
module.exports = __toCommonJS(src_exports);
var import_node_assert21 = __toESM(require("node:assert"));
var import_node_crypto8 = __toESM(require("node:crypto"));
var import_node_fs21 = __toESM(require("node:fs"));
var import_promises24 = require("node:fs/promises");
var import_node_http2 = __toESM(require("node:http"));
var import_node_net2 = __toESM(require("node:net"));
var import_node_os12 = __toESM(require("node:os"));
var import_node_path31 = __toESM(require("node:path"));
var import_web5 = require("node:stream/web");
var import_node_util7 = __toESM(require("node:util"));
var import_node_zlib = __toESM(require("node:zlib"));

// ../../node_modules/.pnpm/chalk@5.3.0/node_modules/chalk/source/vendor/ansi-styles/index.js
var ANSI_BACKGROUND_OFFSET = 10;
var wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
var wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
var wrapAnsi16m = (offset = 0) => (red4, green4, blue4) => `\x1B[${38 + offset};2;${red4};${green4};${blue4}m`;
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(red4, green4, blue4) {
        if (red4 === green4 && green4 === blue4) {
          if (red4 < 8) {
            return 16;
          }
          if (red4 > 248) {
            return 231;
          }
          return Math.round((red4 - 8) / 247 * 24) + 232;
        }
        return 16 + 36 * Math.round(red4 / 255 * 5) + 6 * Math.round(green4 / 255 * 5) + Math.round(blue4 / 255 * 5);
      },
      enumerable: false
    },
    hexToRgb: {
      value(hex5) {
        const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex5.toString(16));
        if (!matches) {
          return [0, 0, 0];
        }
        let [colorString] = matches;
        if (colorString.length === 3) {
          colorString = [...colorString].map((character) => character + character).join("");
        }
        const integer3 = Number.parseInt(colorString, 16);
        return [
          /* eslint-disable no-bitwise */
          integer3 >> 16 & 255,
          integer3 >> 8 & 255,
          integer3 & 255
          /* eslint-enable no-bitwise */
        ];
      },
      enumerable: false
    },
    hexToAnsi256: {
      value: (hex5) => styles.rgbToAnsi256(...styles.hexToRgb(hex5)),
      enumerable: false
    },
    ansi256ToAnsi: {
      value(code) {
        if (code < 8) {
          return 30 + code;
        }
        if (code < 16) {
          return 90 + (code - 8);
        }
        let red4;
        let green4;
        let blue4;
        if (code >= 232) {
          red4 = ((code - 232) * 10 + 8) / 255;
          green4 = red4;
          blue4 = red4;
        } else {
          code -= 16;
          const remainder = code % 36;
          red4 = Math.floor(code / 36) / 5;
          green4 = Math.floor(remainder / 6) / 5;
          blue4 = remainder % 6 / 5;
        }
        const value = Math.max(red4, green4, blue4) * 2;
        if (value === 0) {
          return 30;
        }
        let result = 30 + (Math.round(blue4) << 2 | Math.round(green4) << 1 | Math.round(red4));
        if (value === 2) {
          result += 60;
        }
        return result;
      },
      enumerable: false
    },
    rgbToAnsi: {
      value: (red4, green4, blue4) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red4, green4, blue4)),
      enumerable: false
    },
    hexToAnsi: {
      value: (hex5) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex5)),
      enumerable: false
    }
  });
  return styles;
}
var ansiStyles = assembleStyles();
var ansi_styles_default = ansiStyles;

// ../../node_modules/.pnpm/chalk@5.3.0/node_modules/chalk/source/vendor/supports-color/index.js
var import_node_process = __toESM(require("node:process"), 1);
var import_node_os = __toESM(require("node:os"), 1);
var import_node_tty = __toESM(require("node:tty"), 1);
function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : import_node_process.default.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);
}
var { env } = import_node_process.default;
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 env) {
    if (env.FORCE_COLOR === "true") {
      return 1;
    }
    if (env.FORCE_COLOR === "false") {
      return 0;
    }
    return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
  }
}
function translateLevel(level) {
  if (level === 0) {
    return false;
  }
  return {
    level,
    hasBasic: true,
    has256: level >= 2,
    has16m: level >= 3
  };
}
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 env && "AGENT_NAME" in env) {
    return 1;
  }
  if (haveStream && !streamIsTTY && forceColor === void 0) {
    return 0;
  }
  const min = forceColor || 0;
  if (env.TERM === "dumb") {
    return min;
  }
  if (import_node_process.default.platform === "win32") {
    const osRelease = import_node_os.default.release().split(".");
    if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
      return Number(osRelease[2]) >= 14931 ? 3 : 2;
    }
    return 1;
  }
  if ("CI" in env) {
    if ("GITHUB_ACTIONS" in env || "GITEA_ACTIONS" in env) {
      return 3;
    }
    if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
      return 1;
    }
    return min;
  }
  if ("TEAMCITY_VERSION" in env) {
    return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
  }
  if (env.COLORTERM === "truecolor") {
    return 3;
  }
  if (env.TERM === "xterm-kitty") {
    return 3;
  }
  if ("TERM_PROGRAM" in env) {
    const version4 = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
    switch (env.TERM_PROGRAM) {
      case "iTerm.app": {
        return version4 >= 3 ? 3 : 2;
      }
      case "Apple_Terminal": {
        return 2;
      }
    }
  }
  if (/-256(color)?$/i.test(env.TERM)) {
    return 2;
  }
  if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
    return 1;
  }
  if ("COLORTERM" in env) {
    return 1;
  }
  return min;
}
function createSupportsColor(stream, options = {}) {
  const level = _supportsColor(stream, {
    streamIsTTY: stream && stream.isTTY,
    ...options
  });
  return translateLevel(level);
}
var supportsColor = {
  stdout: createSupportsColor({ isTTY: import_node_tty.default.isatty(1) }),
  stderr: createSupportsColor({ isTTY: import_node_tty.default.isatty(2) })
};
var supports_color_default = supportsColor;

// ../../node_modules/.pnpm/chalk@5.3.0/node_modules/chalk/source/utilities.js
function stringReplaceAll(string7, substring, replacer) {
  let index = string7.indexOf(substring);
  if (index === -1) {
    return string7;
  }
  const substringLength = substring.length;
  let endIndex = 0;
  let returnValue = "";
  do {
    returnValue += string7.slice(endIndex, index) + substring + replacer;
    endIndex = index + substringLength;
    index = string7.indexOf(substring, endIndex);
  } while (index !== -1);
  returnValue += string7.slice(endIndex);
  return returnValue;
}
function stringEncaseCRLFWithFirstIndex(string7, prefix, postfix, index) {
  let endIndex = 0;
  let returnValue = "";
  do {
    const gotCR = string7[index - 1] === "\r";
    returnValue += string7.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
    endIndex = index + 1;
    index = string7.indexOf("\n", endIndex);
  } while (index !== -1);
  returnValue += string7.slice(endIndex);
  return returnValue;
}

// ../../node_modules/.pnpm/chalk@5.3.0/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 styles2 = /* @__PURE__ */ Object.create(null);
var applyOptions = (object3, options = {}) => {
  if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
    throw new Error("The `level` option should be an integer from 0 to 3");
  }
  const colorLevel = stdoutColor ? stdoutColor.level : 0;
  object3.level = options.level === void 0 ? colorLevel : options.level;
};
var chalkFactory = (options) => {
  const chalk2 = (...strings) => strings.join(" ");
  applyOptions(chalk2, options);
  Object.setPrototypeOf(chalk2, createChalk.prototype);
  return chalk2;
};
function createChalk(options) {
  return chalkFactory(options);
}
Object.setPrototypeOf(createChalk.prototype, Function.prototype);
for (const [styleName, style] of Object.entries(ansi_styles_default)) {
  styles2[styleName] = {
    get() {
      const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
      Object.defineProperty(this, styleName, { value: builder });
      return builder;
    }
  };
}
styles2.visible = {
  get() {
    const builder = createBuilder(this, this[STYLER], true);
    Object.defineProperty(this, "visible", { value: builder });
    return builder;
  }
};
var getModelAnsi = (model, level, type, ...arguments_) => {
  if (model === "rgb") {
    if (level === "ansi16m") {
      return ansi_styles_default[type].ansi16m(...arguments_);
    }
    if (level === "ansi256") {
      return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
    }
    return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
  }
  if (model === "hex") {
    return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
  }
  return ansi_styles_default[type][model](...arguments_);
};
var usedModels = ["rgb", "hex", "ansi256"];
for (const model of usedModels) {
  styles2[model] = {
    get() {
      const { level } = this;
      return function(...arguments_) {
        const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
        return createBuilder(this, styler, this[IS_EMPTY]);
      };
    }
  };
  const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
  styles2[bgModel] = {
    get() {
      const { level } = this;
      return function(...arguments_) {
        const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
        return createBuilder(this, styler, this[IS_EMPTY]);
      };
    }
  };
}
var proto = Object.defineProperties(() => {
}, {
  ...styles2,
  level: {
    enumerable: true,
    get() {
      return this[GENERATOR].level;
    },
    set(level) {
      this[GENERATOR].level = level;
    }
  }
});
var createStyler = (open3, close, parent) => {
  let openAll;
  let closeAll;
  if (parent === void 0) {
    openAll = open3;
    closeAll = close;
  } else {
    openAll = parent.openAll + open3;
    closeAll = close + parent.closeAll;
  }
  return {
    open: open3,
    close,
    openAll,
    closeAll,
    parent
  };
};
var createBuilder = (self2, _styler, _isEmpty) => {
  const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
  Object.setPrototypeOf(builder, proto);
  builder[GENERATOR] = self2;
  builder[STYLER] = _styler;
  builder[IS_EMPTY] = _isEmpty;
  return builder;
};
var applyStyle = (self2, string7) => {
  if (self2.level <= 0 || !string7) {
    return self2[IS_EMPTY] ? "" : string7;
  }
  let styler = self2[STYLER];
  if (styler === void 0) {
    return string7;
  }
  const { openAll, closeAll } = styler;
  if (string7.includes("\x1B")) {
    while (styler !== void 0) {
      string7 = stringReplaceAll(string7, styler.close, styler.open);
      styler = styler.parent;
    }
  }
  const lfIndex = string7.indexOf("\n");
  if (lfIndex !== -1) {
    string7 = stringEncaseCRLFWithFirstIndex(string7, closeAll, openAll, lfIndex);
  }
  return openAll + string7 + closeAll;
};
Object.defineProperties(createChalk.prototype, styles2);
var chalk = createChalk();
var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
var source_default = chalk;

// ../cli/dist/colors.mjs
var { white, gray, dim, hidden, bold, cyanBright, bgCyan } = source_default;
var brandColor = source_default.hex("#BD5B08");
var black = source_default.hex("#111");
var blue = source_default.hex("#0E838F");
var bgBlue = black.bgHex("#0E838F");
var red = source_default.hex("#AB2526");
var bgRed = black.bgHex("#AB2526");
var green = source_default.hex("#218529");
var bgGreen = black.bgHex("#218529");
var yellow = source_default.hex("#7F7322");
var bgYellow = black.bgHex("#7F7322");

// ../cli/dist/streams.mjs
var stdout = process.stdout;
var stderr = process.stderr;

// ../cli/dist/check-macos-version.mjs
var import_node_os5 = __toESM(require("node:os"), 1);

// ../workers-utils/dist/chunk-53IMCORZ.mjs
init_chunk_Q72B4Q5Z();
var import_node_fs = __toESM(require("node:fs"), 1);
function isDirectory(path73) {
  return import_node_fs.default.statSync(path73, { throwIfNoEntry: false })?.isDirectory() ?? false;
}
__name(isDirectory, "isDirectory");
function removeDir(dirPath, { fireAndForget = false } = {}) {
  const result = import_node_fs.default.promises.rm(dirPath, {
    recursive: true,
    force: true,
    maxRetries: 5,
    retryDelay: 100
  });
  if (fireAndForget) {
    void result.catch(() => {
    });
  } else {
    return result;
  }
}
__name(removeDir, "removeDir");
function removeDirSync(dirPath) {
  import_node_fs.default.rmSync(dirPath, {
    recursive: true,
    force: true,
    maxRetries: 5,
    retryDelay: 100
  });
}
__name(removeDirSync, "removeDirSync");

// ../workers-utils/dist/chunk-34VZWBGB.mjs
init_chunk_Q72B4Q5Z();
var import_node_os2 = __toESM(require("node:os"), 1);
var import_node_path = __toESM(require("node:path"), 1);
function isWindows() {
  return /^win/i.test(process.platform);
}
__name(isWindows, "isWindows");
function isMacOS() {
  return /^darwin$/i.test(process.platform);
}
__name(isMacOS, "isMacOS");
function isNonEmpty(value) {
  return !!value;
}
__name(isNonEmpty, "isNonEmpty");
function getEnv(name) {
  return process.env[name];
}
__name(getEnv, "getEnv");
function normalizePath(p2) {
  return p2 ? import_node_path.default.normalize(import_node_path.default.join(p2, ".")) : void 0;
}
__name(normalizePath, "normalizePath");
function homeDir() {
  if (isWindows()) {
    const priorityList = [
      import_node_os2.default.homedir(),
      getEnv("USERPROFILE"),
      getEnv("HOME"),
      // NOTE: `os-paths@7` uses `||` here (not `&&`), so a home directory is
      // derived even when only one of HOMEDRIVE/HOMEPATH is set. This is
      // preserved deliberately for byte-for-byte parity — see the parity
      // tests, which compare this branch against the real package.
      getEnv("HOMEDRIVE") || getEnv("HOMEPATH") ? import_node_path.default.join(getEnv("HOMEDRIVE") ?? "", getEnv("HOMEPATH") ?? "") : void 0
    ];
    return normalizePath(priorityList.find(isNonEmpty));
  }
  return normalizePath(import_node_os2.default.homedir() || getEnv("HOME"));
}
__name(homeDir, "homeDir");
function joinToBase(base, segments) {
  return base ? import_node_path.default.join(base, ...segments) : void 0;
}
__name(joinToBase, "joinToBase");
function tempDir() {
  if (isWindows()) {
    const fallback2 = "C:\\Temp";
    const priorityListLazy = [
      () => import_node_os2.default.tmpdir(),
      () => getEnv("TEMP"),
      () => getEnv("TMP"),
      () => joinToBase(getEnv("LOCALAPPDATA"), ["Temp"]),
      () => joinToBase(homeDir(), ["AppData", "Local", "Temp"]),
      () => joinToBase(getEnv("ALLUSERSPROFILE"), ["Temp"]),
      () => joinToBase(getEnv("SystemRoot"), ["Temp"]),
      () => joinToBase(getEnv("windir"), ["Temp"]),
      () => joinToBase(getEnv("SystemDrive"), ["\\", "Temp"])
    ];
    const found = priorityListLazy.find((fn) => isNonEmpty(fn()));
    return found && normalizePath(found()) || fallback2;
  }
  const fallback = "/tmp";
  const priorityList = [
    import_node_os2.default.tmpdir(),
    getEnv("TMPDIR"),
    getEnv("TEMP"),
    getEnv("TMP")
  ];
  return normalizePath(priorityList.find(isNonEmpty)) || fallback;
}
__name(tempDir, "tempDir");
function baseDir() {
  return homeDir() || tempDir();
}
__name(baseDir, "baseDir");
function valOrPath(value, segments) {
  return value || import_node_path.default.join(...segments);
}
__name(valOrPath, "valOrPath");
function windowsAppData() {
  return valOrPath(getEnv("APPDATA"), [baseDir(), "AppData", "Roaming"]);
}
__name(windowsAppData, "windowsAppData");
function windowsLocalAppData() {
  return valOrPath(getEnv("LOCALAPPDATA"), [baseDir(), "AppData", "Local"]);
}
__name(windowsLocalAppData, "windowsLocalAppData");
function xdgConfig() {
  if (isMacOS()) {
    return valOrPath(getEnv("XDG_CONFIG_HOME"), [
      baseDir(),
      "Library",
      "Preferences"
    ]);
  }
  if (isWindows()) {
    return valOrPath(getEnv("XDG_CONFIG_HOME"), [
      windowsAppData(),
      "xdg.config"
    ]);
  }
  return valOrPath(getEnv("XDG_CONFIG_HOME"), [baseDir(), ".config"]);
}
__name(xdgConfig, "xdgConfig");
function xdgCache() {
  if (isMacOS()) {
    return valOrPath(getEnv("XDG_CACHE_HOME"), [
      baseDir(),
      "Library",
      "Caches"
    ]);
  }
  if (isWindows()) {
    return valOrPath(getEnv("XDG_CACHE_HOME"), [
      windowsLocalAppData(),
      "xdg.cache"
    ]);
  }
  return valOrPath(getEnv("XDG_CACHE_HOME"), [baseDir(), ".cache"]);
}
__name(xdgCache, "xdgCache");
function xdgAppPaths(name) {
  const segment = import_node_path.default.parse(name).name;
  return {
    config: /* @__PURE__ */ __name(() => import_node_path.default.join(xdgConfig(), segment), "config"),
    cache: /* @__PURE__ */ __name(() => import_node_path.default.join(xdgCache(), segment), "cache")
  };
}
__name(xdgAppPaths, "xdgAppPaths");
function getGlobalConfigPath({
  appName = "wrangler",
  leadingDot = true,
  useLegacyHomeDir = true
} = {}) {
  const dirName = `${leadingDot ? "." : ""}${appName}`;
  const configDir = xdgAppPaths(dirName).config();
  if (useLegacyHomeDir) {
    const legacyConfigDir = import_node_path.default.join(import_node_os2.default.homedir(), dirName);
    if (isDirectory(legacyConfigDir)) {
      return legacyConfigDir;
    }
  }
  return configDir;
}
__name(getGlobalConfigPath, "getGlobalConfigPath");
function getGlobalWranglerCachePath() {
  return xdgAppPaths(".wrangler").cache();
}
__name(getGlobalWranglerCachePath, "getGlobalWranglerCachePath");

// ../workers-utils/dist/chunk-QFKPUV4H.mjs
init_chunk_Q72B4Q5Z();
var import_node_fs2 = require("node:fs");
var import_node_path2 = __toESM(require("node:path"), 1);
function hasKnownExportType(entry) {
  const type = entry?.type;
  return type === "durable-object" || type === "worker";
}
__name(hasKnownExportType, "hasKnownExportType");
function partitionExports(exports2) {
  const partitioned = {
    "durable-object": {},
    worker: {}
  };
  if (exports2 === void 0) {
    return partitioned;
  }
  for (const [name, entry] of Object.entries(exports2)) {
    if (!hasKnownExportType(entry)) {
      continue;
    }
    partitioned[entry.type][name] = entry;
  }
  return partitioned;
}
__name(partitionExports, "partitionExports");
function getDurableObjectExports(exports2) {
  return partitionExports(exports2)["durable-object"];
}
__name(getDurableObjectExports, "getDurableObjectExports");
function hasDurableObjectExports(exports2) {
  return Object.keys(getDurableObjectExports(exports2)).length > 0;
}
__name(hasDurableObjectExports, "hasDurableObjectExports");
function getContainerNameToClassNameMap(exports2) {
  const containerNameToClassName = /* @__PURE__ */ new Map();
  for (const [className, entry] of Object.entries(
    getDurableObjectExports(exports2)
  )) {
    if ("container" in entry && typeof entry.container === "string" && !containerNameToClassName.has(entry.container)) {
      containerNameToClassName.set(entry.container, className);
    }
  }
  return containerNameToClassName;
}
__name(getContainerNameToClassNameMap, "getContainerNameToClassNameMap");
function resolveContainerClassName(container, exports2) {
  if (container.class_name !== void 0) {
    return container.class_name;
  }
  if (container.name === void 0) {
    return void 0;
  }
  return getContainerNameToClassNameMap(exports2).get(container.name);
}
__name(resolveContainerClassName, "resolveContainerClassName");
function getContainerDurableObjectClassNames(containers, exports2) {
  const classNames = /* @__PURE__ */ new Set();
  for (const container of containers ?? []) {
    const className = resolveContainerClassName(container, exports2);
    if (className !== void 0) {
      classNames.add(className);
    }
  }
  return classNames;
}
__name(getContainerDurableObjectClassNames, "getContainerDurableObjectClassNames");
var UserError = class extends Error {
  static {
    __name(this, "UserError");
  }
  telemetryMessage;
  constructor(message, options) {
    super(message, options);
    Object.setPrototypeOf(this, new.target.prototype);
    this.telemetryMessage = typeof options?.telemetryMessage === "string" ? options.telemetryMessage : options?.telemetryMessage ? message : void 0;
  }
};
var DeprecationError = class extends UserError {
  static {
    __name(this, "DeprecationError");
  }
  constructor(message, options) {
    super(`Deprecation:
${message}`, options);
  }
};
var FatalError = class extends UserError {
  static {
    __name(this, "FatalError");
  }
  code;
  constructor(message, options) {
    super(message, options);
    this.code = options.code;
  }
};
var CommandLineArgsError = class extends UserError {
  static {
    __name(this, "CommandLineArgsError");
  }
};
var JsonFriendlyFatalError = class extends FatalError {
  static {
    __name(this, "JsonFriendlyFatalError");
  }
};
var MissingConfigError = class extends Error {
  static {
    __name(this, "MissingConfigError");
  }
  telemetryMessage;
  constructor(key) {
    super(`Missing config value for ${key}`);
    this.telemetryMessage = `Missing config value for ${key}`;
  }
};
function createFatalError(message, isJson, options) {
  if (isJson) {
    return new JsonFriendlyFatalError(JSON.stringify(message), options);
  }
  return new FatalError(`${message}`, options);
}
__name(createFatalError, "createFatalError");
function createScanner(text, ignoreTrivia = false) {
  const len = text.length;
  let pos = 0, value = "", tokenOffset = 0, token = 16, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0;
  function scanHexDigits(count, exact) {
    let digits = 0;
    let value2 = 0;
    while (digits < count || !exact) {
      let ch = text.charCodeAt(pos);
      if (ch >= 48 && ch <= 57) {
        value2 = value2 * 16 + ch - 48;
      } else if (ch >= 65 && ch <= 70) {
        value2 = value2 * 16 + ch - 65 + 10;
      } else if (ch >= 97 && ch <= 102) {
        value2 = value2 * 16 + ch - 97 + 10;
      } else {
        break;
      }
      pos++;
      digits++;
    }
    if (digits < count) {
      value2 = -1;
    }
    return value2;
  }
  __name(scanHexDigits, "scanHexDigits");
  function setPosition(newPosition) {
    pos = newPosition;
    value = "";
    tokenOffset = 0;
    token = 16;
    scanError = 0;
  }
  __name(setPosition, "setPosition");
  function scanNumber() {
    let start = pos;
    if (text.charCodeAt(pos) === 48) {
      pos++;
    } else {
      pos++;
      while (pos < text.length && isDigit(text.charCodeAt(pos))) {
        pos++;
      }
    }
    if (pos < text.length && text.charCodeAt(pos) === 46) {
      pos++;
      if (pos < text.length && isDigit(text.charCodeAt(pos))) {
        pos++;
        while (pos < text.length && isDigit(text.charCodeAt(pos))) {
          pos++;
        }
      } else {
        scanError = 3;
        return text.substring(start, pos);
      }
    }
    let end = pos;
    if (pos < text.length && (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101)) {
      pos++;
      if (pos < text.length && text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) {
        pos++;
      }
      if (pos < text.length && isDigit(text.charCodeAt(pos))) {
        pos++;
        while (pos < text.length && isDigit(text.charCodeAt(pos))) {
          pos++;
        }
        end = pos;
      } else {
        scanError = 3;
      }
    }
    return text.substring(start, end);
  }
  __name(scanNumber, "scanNumber");
  function scanString() {
    let result = "", start = pos;
    while (true) {
      if (pos >= len) {
        result += text.substring(start, pos);
        scanError = 2;
        break;
      }
      const ch = text.charCodeAt(pos);
      if (ch === 34) {
        result += text.substring(start, pos);
        pos++;
        break;
      }
      if (ch === 92) {
        result += text.substring(start, pos);
        pos++;
        if (pos >= len) {
          scanError = 2;
          break;
        }
        const ch2 = text.charCodeAt(pos++);
        switch (ch2) {
          case 34:
            result += '"';
            break;
          case 92:
            result += "\\";
            break;
          case 47:
            result += "/";
            break;
          case 98:
            result += "\b";
            break;
          case 102:
            result += "\f";
            break;
          case 110:
            result += "\n";
            break;
          case 114:
            result += "\r";
            break;
          case 116:
            result += "	";
            break;
          case 117:
            const ch3 = scanHexDigits(4, true);
            if (ch3 >= 0) {
              result += String.fromCharCode(ch3);
            } else {
              scanError = 4;
            }
            break;
          default:
            scanError = 5;
        }
        start = pos;
        continue;
      }
      if (ch >= 0 && ch <= 31) {
        if (isLineBreak(ch)) {
          result += text.substring(start, pos);
          scanError = 2;
          break;
        } else {
          scanError = 6;
        }
      }
      pos++;
    }
    return result;
  }
  __name(scanString, "scanString");
  function scanNext() {
    value = "";
    scanError = 0;
    tokenOffset = pos;
    lineStartOffset = lineNumber;
    prevTokenLineStartOffset = tokenLineStartOffset;
    if (pos >= len) {
      tokenOffset = len;
      return token = 17;
    }
    let code = text.charCodeAt(pos);
    if (isWhiteSpace(code)) {
      do {
        pos++;
        value += String.fromCharCode(code);
        code = text.charCodeAt(pos);
      } while (isWhiteSpace(code));
      return token = 15;
    }
    if (isLineBreak(code)) {
      pos++;
      value += String.fromCharCode(code);
      if (code === 13 && text.charCodeAt(pos) === 10) {
        pos++;
        value += "\n";
      }
      lineNumber++;
      tokenLineStartOffset = pos;
      return token = 14;
    }
    switch (code) {
      // tokens: []{}:,
      case 123:
        pos++;
        return token = 1;
      case 125:
        pos++;
        return token = 2;
      case 91:
        pos++;
        return token = 3;
      case 93:
        pos++;
        return token = 4;
      case 58:
        pos++;
        return token = 6;
      case 44:
        pos++;
        return token = 5;
      // strings
      case 34:
        pos++;
        value = scanString();
        return token = 10;
      // comments
      case 47:
        const start = pos - 1;
        if (text.charCodeAt(pos + 1) === 47) {
          pos += 2;
          while (pos < len) {
            if (isLineBreak(text.charCodeAt(pos))) {
              break;
            }
            pos++;
          }
          value = text.substring(start, pos);
          return token = 12;
        }
        if (text.charCodeAt(pos + 1) === 42) {
          pos += 2;
          const safeLength = len - 1;
          let commentClosed = false;
          while (pos < safeLength) {
            const ch = text.charCodeAt(pos);
            if (ch === 42 && text.charCodeAt(pos + 1) === 47) {
              pos += 2;
              commentClosed = true;
              break;
            }
            pos++;
            if (isLineBreak(ch)) {
              if (ch === 13 && text.charCodeAt(pos) === 10) {
                pos++;
              }
              lineNumber++;
              tokenLineStartOffset = pos;
            }
          }
          if (!commentClosed) {
            pos++;
            scanError = 1;
          }
          value = text.substring(start, pos);
          return token = 13;
        }
        value += String.fromCharCode(code);
        pos++;
        return token = 16;
      // numbers
      case 45:
        value += String.fromCharCode(code);
        pos++;
        if (pos === len || !isDigit(text.charCodeAt(pos))) {
          return token = 16;
        }
      // found a minus, followed by a number so
      // we fall through to proceed with scanning
      // numbers
      case 48:
      case 49:
      case 50:
      case 51:
      case 52:
      case 53:
      case 54:
      case 55:
      case 56:
      case 57:
        value += scanNumber();
        return token = 11;
      // literals and unknown symbols
      default:
        while (pos < len && isUnknownContentCharacter(code)) {
          pos++;
          code = text.charCodeAt(pos);
        }
        if (tokenOffset !== pos) {
          value = text.substring(tokenOffset, pos);
          switch (value) {
            case "true":
              return token = 8;
            case "false":
              return token = 9;
            case "null":
              return token = 7;
          }
          return token = 16;
        }
        value += String.fromCharCode(code);
        pos++;
        return token = 16;
    }
  }
  __name(scanNext, "scanNext");
  function isUnknownContentCharacter(code) {
    if (isWhiteSpace(code) || isLineBreak(code)) {
      return false;
    }
    switch (code) {
      case 125:
      case 93:
      case 123:
      case 91:
      case 34:
      case 58:
      case 44:
      case 47:
        return false;
    }
    return true;
  }
  __name(isUnknownContentCharacter, "isUnknownContentCharacter");
  function scanNextNonTrivia() {
    let result;
    do {
      result = scanNext();
    } while (result >= 12 && result <= 15);
    return result;
  }
  __name(scanNextNonTrivia, "scanNextNonTrivia");
  return {
    setPosition,
    getPosition: /* @__PURE__ */ __name(() => pos, "getPosition"),
    scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
    getToken: /* @__PURE__ */ __name(() => token, "getToken"),
    getTokenValue: /* @__PURE__ */ __name(() => value, "getTokenValue"),
    getTokenOffset: /* @__PURE__ */ __name(() => tokenOffset, "getTokenOffset"),
    getTokenLength: /* @__PURE__ */ __name(() => pos - tokenOffset, "getTokenLength"),
    getTokenStartLine: /* @__PURE__ */ __name(() => lineStartOffset, "getTokenStartLine"),
    getTokenStartCharacter: /* @__PURE__ */ __name(() => tokenOffset - prevTokenLineStartOffset, "getTokenStartCharacter"),
    getTokenError: /* @__PURE__ */ __name(() => scanError, "getTokenError")
  };
}
__name(createScanner, "createScanner");
function isWhiteSpace(ch) {
  return ch === 32 || ch === 9;
}
__name(isWhiteSpace, "isWhiteSpace");
function isLineBreak(ch) {
  return ch === 10 || ch === 13;
}
__name(isLineBreak, "isLineBreak");
function isDigit(ch) {
  return ch >= 48 && ch <= 57;
}
__name(isDigit, "isDigit");
var CharacterCodes;
(function(CharacterCodes22) {
  CharacterCodes22[CharacterCodes22["lineFeed"] = 10] = "lineFeed";
  CharacterCodes22[CharacterCodes22["carriageReturn"] = 13] = "carriageReturn";
  CharacterCodes22[CharacterCodes22["space"] = 32] = "space";
  CharacterCodes22[CharacterCodes22["_0"] = 48] = "_0";
  CharacterCodes22[CharacterCodes22["_1"] = 49] = "_1";
  CharacterCodes22[CharacterCodes22["_2"] = 50] = "_2";
  CharacterCodes22[CharacterCodes22["_3"] = 51] = "_3";
  CharacterCodes22[CharacterCodes22["_4"] = 52] = "_4";
  CharacterCodes22[CharacterCodes22["_5"] = 53] = "_5";
  CharacterCodes22[CharacterCodes22["_6"] = 54] = "_6";
  CharacterCodes22[CharacterCodes22["_7"] = 55] = "_7";
  CharacterCodes22[CharacterCodes22["_8"] = 56] = "_8";
  CharacterCodes22[CharacterCodes22["_9"] = 57] = "_9";
  CharacterCodes22[CharacterCodes22["a"] = 97] = "a";
  CharacterCodes22[CharacterCodes22["b"] = 98] = "b";
  CharacterCodes22[CharacterCodes22["c"] = 99] = "c";
  CharacterCodes22[CharacterCodes22["d"] = 100] = "d";
  CharacterCodes22[CharacterCodes22["e"] = 101] = "e";
  CharacterCodes22[CharacterCodes22["f"] = 102] = "f";
  CharacterCodes22[CharacterCodes22["g"] = 103] = "g";
  CharacterCodes22[CharacterCodes22["h"] = 104] = "h";
  CharacterCodes22[CharacterCodes22["i"] = 105] = "i";
  CharacterCodes22[CharacterCodes22["j"] = 106] = "j";
  CharacterCodes22[CharacterCodes22["k"] = 107] = "k";
  CharacterCodes22[CharacterCodes22["l"] = 108] = "l";
  CharacterCodes22[CharacterCodes22["m"] = 109] = "m";
  CharacterCodes22[CharacterCodes22["n"] = 110] = "n";
  CharacterCodes22[CharacterCodes22["o"] = 111] = "o";
  CharacterCodes22[CharacterCodes22["p"] = 112] = "p";
  CharacterCodes22[CharacterCodes22["q"] = 113] = "q";
  CharacterCodes22[CharacterCodes22["r"] = 114] = "r";
  CharacterCodes22[CharacterCodes22["s"] = 115] = "s";
  CharacterCodes22[CharacterCodes22["t"] = 116] = "t";
  CharacterCodes22[CharacterCodes22["u"] = 117] = "u";
  CharacterCodes22[CharacterCodes22["v"] = 118] = "v";
  CharacterCodes22[CharacterCodes22["w"] = 119] = "w";
  CharacterCodes22[CharacterCodes22["x"] = 120] = "x";
  CharacterCodes22[CharacterCodes22["y"] = 121] = "y";
  CharacterCodes22[CharacterCodes22["z"] = 122] = "z";
  CharacterCodes22[CharacterCodes22["A"] = 65] = "A";
  CharacterCodes22[CharacterCodes22["B"] = 66] = "B";
  CharacterCodes22[CharacterCodes22["C"] = 67] = "C";
  CharacterCodes22[CharacterCodes22["D"] = 68] = "D";
  CharacterCodes22[CharacterCodes22["E"] = 69] = "E";
  CharacterCodes22[CharacterCodes22["F"] = 70] = "F";
  CharacterCodes22[CharacterCodes22["G"] = 71] = "G";
  CharacterCodes22[CharacterCodes22["H"] = 72] = "H";
  CharacterCodes22[CharacterCodes22["I"] = 73] = "I";
  CharacterCodes22[CharacterCodes22["J"] = 74] = "J";
  CharacterCodes22[CharacterCodes22["K"] = 75] = "K";
  CharacterCodes22[CharacterCodes22["L"] = 76] = "L";
  CharacterCodes22[CharacterCodes22["M"] = 77] = "M";
  CharacterCodes22[CharacterCodes22["N"] = 78] = "N";
  CharacterCodes22[CharacterCodes22["O"] = 79] = "O";
  CharacterCodes22[CharacterCodes22["P"] = 80] = "P";
  CharacterCodes22[CharacterCodes22["Q"] = 81] = "Q";
  CharacterCodes22[CharacterCodes22["R"] = 82] = "R";
  CharacterCodes22[CharacterCodes22["S"] = 83] = "S";
  CharacterCodes22[CharacterCodes22["T"] = 84] = "T";
  CharacterCodes22[CharacterCodes22["U"] = 85] = "U";
  CharacterCodes22[CharacterCodes22["V"] = 86] = "V";
  CharacterCodes22[CharacterCodes22["W"] = 87] = "W";
  CharacterCodes22[CharacterCodes22["X"] = 88] = "X";
  CharacterCodes22[CharacterCodes22["Y"] = 89] = "Y";
  CharacterCodes22[CharacterCodes22["Z"] = 90] = "Z";
  CharacterCodes22[CharacterCodes22["asterisk"] = 42] = "asterisk";
  CharacterCodes22[CharacterCodes22["backslash"] = 92] = "backslash";
  CharacterCodes22[CharacterCodes22["closeBrace"] = 125] = "closeBrace";
  CharacterCodes22[CharacterCodes22["closeBracket"] = 93] = "closeBracket";
  CharacterCodes22[CharacterCodes22["colon"] = 58] = "colon";
  CharacterCodes22[CharacterCodes22["comma"] = 44] = "comma";
  CharacterCodes22[CharacterCodes22["dot"] = 46] = "dot";
  CharacterCodes22[CharacterCodes22["doubleQuote"] = 34] = "doubleQuote";
  CharacterCodes22[CharacterCodes22["minus"] = 45] = "minus";
  CharacterCodes22[CharacterCodes22["openBrace"] = 123] = "openBrace";
  CharacterCodes22[CharacterCodes22["openBracket"] = 91] = "openBracket";
  CharacterCodes22[CharacterCodes22["plus"] = 43] = "plus";
  CharacterCodes22[CharacterCodes22["slash"] = 47] = "slash";
  CharacterCodes22[CharacterCodes22["formFeed"] = 12] = "formFeed";
  CharacterCodes22[CharacterCodes22["tab"] = 9] = "tab";
})(CharacterCodes || (CharacterCodes = {}));
function format(documentText, range, options) {
  let initialIndentLevel;
  let formatText;
  let formatTextStart;
  let rangeStart;
  let rangeEnd;
  if (range) {
    rangeStart = range.offset;
    rangeEnd = rangeStart + range.length;
    formatTextStart = rangeStart;
    while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) {
      formatTextStart--;
    }
    let endOffset = rangeEnd;
    while (endOffset < documentText.length && !isEOL(documentText, endOffset)) {
      endOffset++;
    }
    formatText = documentText.substring(formatTextStart, endOffset);
    initialIndentLevel = computeIndentLevel(formatText, options);
  } else {
    formatText = documentText;
    initialIndentLevel = 0;
    formatTextStart = 0;
    rangeStart = 0;
    rangeEnd = documentText.length;
  }
  const eol = getEOL(options, documentText);
  let numberLineBreaks = 0;
  let indentLevel = 0;
  let indentValue;
  if (options.insertSpaces) {
    indentValue = repeat(" ", options.tabSize || 4);
  } else {
    indentValue = "	";
  }
  let scanner = createScanner(formatText, false);
  let hasError = false;
  function newLinesAndIndent() {
    if (numberLineBreaks > 1) {
      return repeat(eol, numberLineBreaks) + repeat(indentValue, initialIndentLevel + indentLevel);
    } else {
      return eol + repeat(indentValue, initialIndentLevel + indentLevel);
    }
  }
  __name(newLinesAndIndent, "newLinesAndIndent");
  function scanNext() {
    let token = scanner.scan();
    numberLineBreaks = 0;
    while (token === 15 || token === 14) {
      if (token === 14 && options.keepLines) {
        numberLineBreaks += 1;
      } else if (token === 14) {
        numberLineBreaks = 1;
      }
      token = scanner.scan();
    }
    hasError = token === 16 || scanner.getTokenError() !== 0;
    return token;
  }
  __name(scanNext, "scanNext");
  const editOperations = [];
  function addEdit(text, startOffset, endOffset) {
    if (!hasError && (!range || startOffset < rangeEnd && endOffset > rangeStart) && documentText.substring(startOffset, endOffset) !== text) {
      editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text });
    }
  }
  __name(addEdit, "addEdit");
  let firstToken = scanNext();
  if (options.keepLines && numberLineBreaks > 0) {
    addEdit(repeat(eol, numberLineBreaks), 0, 0);
  }
  if (firstToken !== 17) {
    let firstTokenStart = scanner.getTokenOffset() + formatTextStart;
    let initialIndent = repeat(indentValue, initialIndentLevel);
    addEdit(initialIndent, formatTextStart, firstTokenStart);
  }
  while (firstToken !== 17) {
    let firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
    let secondToken = scanNext();
    let replaceContent = "";
    let needsLineBreak = false;
    while (numberLineBreaks === 0 && (secondToken === 12 || secondToken === 13)) {
      let commentTokenStart = scanner.getTokenOffset() + formatTextStart;
      addEdit(" ", firstTokenEnd, commentTokenStart);
      firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
      needsLineBreak = secondToken === 12;
      replaceContent = needsLineBreak ? newLinesAndIndent() : "";
      secondToken = scanNext();
    }
    if (secondToken === 2) {
      if (firstToken !== 1) {
        indentLevel--;
      }
      if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 1) {
        replaceContent = newLinesAndIndent();
      } else if (options.keepLines) {
        replaceContent = " ";
      }
    } else if (secondToken === 4) {
      if (firstToken !== 3) {
        indentLevel--;
      }
      if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 3) {
        replaceContent = newLinesAndIndent();
      } else if (options.keepLines) {
        replaceContent = " ";
      }
    } else {
      switch (firstToken) {
        case 3:
        case 1:
          indentLevel++;
          if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) {
            replaceContent = newLinesAndIndent();
          } else {
            replaceContent = " ";
          }
          break;
        case 5:
          if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) {
            replaceContent = newLinesAndIndent();
          } else {
            replaceContent = " ";
          }
          break;
        case 12:
          replaceContent = newLinesAndIndent();
          break;
        case 13:
          if (numberLineBreaks > 0) {
            replaceContent = newLinesAndIndent();
          } else if (!needsLineBreak) {
            replaceContent = " ";
          }
          break;
        case 6:
          if (options.keepLines && numberLineBreaks > 0) {
            replaceContent = newLinesAndIndent();
          } else if (!needsLineBreak) {
            replaceContent = " ";
          }
          break;
        case 10:
          if (options.keepLines && numberLineBreaks > 0) {
            replaceContent = newLinesAndIndent();
          } else if (secondToken === 6 && !needsLineBreak) {
            replaceContent = "";
          }
          break;
        case 7:
        case 8:
        case 9:
        case 11:
        case 2:
        case 4:
          if (options.keepLines && numberLineBreaks > 0) {
            replaceContent = newLinesAndIndent();
          } else {
            if ((secondToken === 12 || secondToken === 13) && !needsLineBreak) {
              replaceContent = " ";
            } else if (secondToken !== 5 && secondToken !== 17) {
              hasError = true;
            }
          }
          break;
        case 16:
          hasError = true;
          break;
      }
      if (numberLineBreaks > 0 && (secondToken === 12 || secondToken === 13)) {
        replaceContent = newLinesAndIndent();
      }
    }
    if (secondToken === 17) {
      if (options.keepLines && numberLineBreaks > 0) {
        replaceContent = newLinesAndIndent();
      } else {
        replaceContent = options.insertFinalNewline ? eol : "";
      }
    }
    const secondTokenStart = scanner.getTokenOffset() + formatTextStart;
    addEdit(replaceContent, firstTokenEnd, secondTokenStart);
    firstToken = secondToken;
  }
  return editOperations;
}
__name(format, "format");
function repeat(s, count) {
  let result = "";
  for (let i = 0; i < count; i++) {
    result += s;
  }
  return result;
}
__name(repeat, "repeat");
function computeIndentLevel(content, options) {
  let i = 0;
  let nChars = 0;
  const tabSize = options.tabSize || 4;
  while (i < content.length) {
    let ch = content.charAt(i);
    if (ch === " ") {
      nChars++;
    } else if (ch === "	") {
      nChars += tabSize;
    } else {
      break;
    }
    i++;
  }
  return Math.floor(nChars / tabSize);
}
__name(computeIndentLevel, "computeIndentLevel");
function getEOL(options, text) {
  for (let i = 0; i < text.length; i++) {
    const ch = text.charAt(i);
    if (ch === "\r") {
      if (i + 1 < text.length && text.charAt(i + 1) === "\n") {
        return "\r\n";
      }
      return "\r";
    } else if (ch === "\n") {
      return "\n";
    }
  }
  return options && options.eol || "\n";
}
__name(getEOL, "getEOL");
function isEOL(text, offset) {
  return "\r\n".indexOf(text.charAt(offset)) !== -1;
}
__name(isEOL, "isEOL");
var ParseOptions;
(function(ParseOptions22) {
  ParseOptions22.DEFAULT = {
    allowTrailingComma: false
  };
})(ParseOptions || (ParseOptions = {}));
function parse(text, errors = [], options = ParseOptions.DEFAULT) {
  let currentProperty = null;
  let currentParent = [];
  const previousParents = [];
  function onValue(value) {
    if (Array.isArray(currentParent)) {
      currentParent.push(value);
    } else if (currentProperty !== null) {
      currentParent[currentProperty] = value;
    }
  }
  __name(onValue, "onValue");
  const visitor = {
    onObjectBegin: /* @__PURE__ */ __name(() => {
      const object3 = {};
      onValue(object3);
      previousParents.push(currentParent);
      currentParent = object3;
      currentProperty = null;
    }, "onObjectBegin"),
    onObjectProperty: /* @__PURE__ */ __name((name) => {
      currentProperty = name;
    }, "onObjectProperty"),
    onObjectEnd: /* @__PURE__ */ __name(() => {
      currentParent = previousParents.pop();
    }, "onObjectEnd"),
    onArrayBegin: /* @__PURE__ */ __name(() => {
      const array3 = [];
      onValue(array3);
      previousParents.push(currentParent);
      currentParent = array3;
      currentProperty = null;
    }, "onArrayBegin"),
    onArrayEnd: /* @__PURE__ */ __name(() => {
      currentParent = previousParents.pop();
    }, "onArrayEnd"),
    onLiteralValue: onValue,
    onError: /* @__PURE__ */ __name((error101, offset, length) => {
      errors.push({ error: error101, offset, length });
    }, "onError")
  };
  visit(text, visitor, options);
  return currentParent[0];
}
__name(parse, "parse");
function parseTree(text, errors = [], options = ParseOptions.DEFAULT) {
  let currentParent = { type: "array", offset: -1, length: -1, children: [], parent: void 0 };
  function ensurePropertyComplete(endOffset) {
    if (currentParent.type === "property") {
      currentParent.length = endOffset - currentParent.offset;
      currentParent = currentParent.parent;
    }
  }
  __name(ensurePropertyComplete, "ensurePropertyComplete");
  function onValue(valueNode) {
    currentParent.children.push(valueNode);
    return valueNode;
  }
  __name(onValue, "onValue");
  const visitor = {
    onObjectBegin: /* @__PURE__ */ __name((offset) => {
      currentParent = onValue({ type: "object", offset, length: -1, parent: currentParent, children: [] });
    }, "onObjectBegin"),
    onObjectProperty: /* @__PURE__ */ __name((name, offset, length) => {
      currentParent = onValue({ type: "property", offset, length: -1, parent: currentParent, children: [] });
      currentParent.children.push({ type: "string", value: name, offset, length, parent: currentParent });
    }, "onObjectProperty"),
    onObjectEnd: /* @__PURE__ */ __name((offset, length) => {
      ensurePropertyComplete(offset + length);
      currentParent.length = offset + length - currentParent.offset;
      currentParent = currentParent.parent;
      ensurePropertyComplete(offset + length);
    }, "onObjectEnd"),
    onArrayBegin: /* @__PURE__ */ __name((offset, length) => {
      currentParent = onValue({ type: "array", offset, length: -1, parent: currentParent, children: [] });
    }, "onArrayBegin"),
    onArrayEnd: /* @__PURE__ */ __name((offset, length) => {
      currentParent.length = offset + length - currentParent.offset;
      currentParent = currentParent.parent;
      ensurePropertyComplete(offset + length);
    }, "onArrayEnd"),
    onLiteralValue: /* @__PURE__ */ __name((value, offset, length) => {
      onValue({ type: getNodeType(value), offset, length, parent: currentParent, value });
      ensurePropertyComplete(offset + length);
    }, "onLiteralValue"),
    onSeparator: /* @__PURE__ */ __name((sep2, offset, length) => {
      if (currentParent.type === "property") {
        if (sep2 === ":") {
          currentParent.colonOffset = offset;
        } else if (sep2 === ",") {
          ensurePropertyComplete(offset);
        }
      }
    }, "onSeparator"),
    onError: /* @__PURE__ */ __name((error101, offset, length) => {
      errors.push({ error: error101, offset, length });
    }, "onError")
  };
  visit(text, visitor, options);
  const result = currentParent.children[0];
  if (result) {
    delete result.parent;
  }
  return result;
}
__name(parseTree, "parseTree");
function findNodeAtLocation(root, path210) {
  if (!root) {
    return void 0;
  }
  let node = root;
  for (let segment of path210) {
    if (typeof segment === "string") {
      if (node.type !== "object" || !Array.isArray(node.children)) {
        return void 0;
      }
      let found = false;
      for (const propertyNode of node.children) {
        if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) {
          node = propertyNode.children[1];
          found = true;
          break;
        }
      }
      if (!found) {
        return void 0;
      }
    } else {
      const index = segment;
      if (node.type !== "array" || index < 0 || !Array.isArray(node.children) || index >= node.children.length) {
        return void 0;
      }
      node = node.children[index];
    }
  }
  return node;
}
__name(findNodeAtLocation, "findNodeAtLocation");
function visit(text, visitor, options = ParseOptions.DEFAULT) {
  const _scanner = createScanner(text, false);
  const _jsonPath = [];
  function toNoArgVisit(visitFunction) {
    return visitFunction ? () => visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
  }
  __name(toNoArgVisit, "toNoArgVisit");
  function toNoArgVisitWithPath(visitFunction) {
    return visitFunction ? () => visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;
  }
  __name(toNoArgVisitWithPath, "toNoArgVisitWithPath");
  function toOneArgVisit(visitFunction) {
    return visitFunction ? (arg) => visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
  }
  __name(toOneArgVisit, "toOneArgVisit");
  function toOneArgVisitWithPath(visitFunction) {
    return visitFunction ? (arg) => visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;
  }
  __name(toOneArgVisitWithPath, "toOneArgVisitWithPath");
  const onObjectBegin = toNoArgVisitWithPath(visitor.onObjectBegin), onObjectProperty = toOneArgVisitWithPath(visitor.onObjectProperty), onObjectEnd = toNoArgVisit(visitor.onObjectEnd), onArrayBegin = toNoArgVisitWithPath(visitor.onArrayBegin), onArrayEnd = toNoArgVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisitWithPath(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError);
  const disallowComments = options && options.disallowComments;
  const allowTrailingComma = options && options.allowTrailingComma;
  function scanNext() {
    while (true) {
      const token = _scanner.scan();
      switch (_scanner.getTokenError()) {
        case 4:
          handleError(
            14
            /* ParseErrorCode.InvalidUnicode */
          );
          break;
        case 5:
          handleError(
            15
            /* ParseErrorCode.InvalidEscapeCharacter */
          );
          break;
        case 3:
          handleError(
            13
            /* ParseErrorCode.UnexpectedEndOfNumber */
          );
          break;
        case 1:
          if (!disallowComments) {
            handleError(
              11
              /* ParseErrorCode.UnexpectedEndOfComment */
            );
          }
          break;
        case 2:
          handleError(
            12
            /* ParseErrorCode.UnexpectedEndOfString */
          );
          break;
        case 6:
          handleError(
            16
            /* ParseErrorCode.InvalidCharacter */
          );
          break;
      }
      switch (token) {
        case 12:
        case 13:
          if (disallowComments) {
            handleError(
              10
              /* ParseErrorCode.InvalidCommentToken */
            );
          } else {
            onComment();
          }
          break;
        case 16:
          handleError(
            1
            /* ParseErrorCode.InvalidSymbol */
          );
          break;
        case 15:
        case 14:
          break;
        default:
          return token;
      }
    }
  }
  __name(scanNext, "scanNext");
  function handleError(error101, skipUntilAfter = [], skipUntil22 = []) {
    onError(error101);
    if (skipUntilAfter.length + skipUntil22.length > 0) {
      let token = _scanner.getToken();
      while (token !== 17) {
        if (skipUntilAfter.indexOf(token) !== -1) {
          scanNext();
          break;
        } else if (skipUntil22.indexOf(token) !== -1) {
          break;
        }
        token = scanNext();
      }
    }
  }
  __name(handleError, "handleError");
  function parseString22(isValue) {
    const value = _scanner.getTokenValue();
    if (isValue) {
      onLiteralValue(value);
    } else {
      onObjectProperty(value);
      _jsonPath.push(value);
    }
    scanNext();
    return true;
  }
  __name(parseString22, "parseString");
  function parseLiteral() {
    switch (_scanner.getToken()) {
      case 11:
        const tokenValue = _scanner.getTokenValue();
        let value = Number(tokenValue);
        if (isNaN(value)) {
          handleError(
            2
            /* ParseErrorCode.InvalidNumberFormat */
          );
          value = 0;
        }
        onLiteralValue(value);
        break;
      case 7:
        onLiteralValue(null);
        break;
      case 8:
        onLiteralValue(true);
        break;
      case 9:
        onLiteralValue(false);
        break;
      default:
        return false;
    }
    scanNext();
    return true;
  }
  __name(parseLiteral, "parseLiteral");
  function parseProperty() {
    if (_scanner.getToken() !== 10) {
      handleError(3, [], [
        2,
        5
        /* SyntaxKind.CommaToken */
      ]);
      return false;
    }
    parseString22(false);
    if (_scanner.getToken() === 6) {
      onSeparator(":");
      scanNext();
      if (!parseValue22()) {
        handleError(4, [], [
          2,
          5
          /* SyntaxKind.CommaToken */
        ]);
      }
    } else {
      handleError(5, [], [
        2,
        5
        /* SyntaxKind.CommaToken */
      ]);
    }
    _jsonPath.pop();
    return true;
  }
  __name(parseProperty, "parseProperty");
  function parseObject() {
    onObjectBegin();
    scanNext();
    let needsComma = false;
    while (_scanner.getToken() !== 2 && _scanner.getToken() !== 17) {
      if (_scanner.getToken() === 5) {
        if (!needsComma) {
          handleError(4, [], []);
        }
        onSeparator(",");
        scanNext();
        if (_scanner.getToken() === 2 && allowTrailingComma) {
          break;
        }
      } else if (needsComma) {
        handleError(6, [], []);
      }
      if (!parseProperty()) {
        handleError(4, [], [
          2,
          5
          /* SyntaxKind.CommaToken */
        ]);
      }
      needsComma = true;
    }
    onObjectEnd();
    if (_scanner.getToken() !== 2) {
      handleError(7, [
        2
        /* SyntaxKind.CloseBraceToken */
      ], []);
    } else {
      scanNext();
    }
    return true;
  }
  __name(parseObject, "parseObject");
  function parseArray22() {
    onArrayBegin();
    scanNext();
    let isFirstElement = true;
    let needsComma = false;
    while (_scanner.getToken() !== 4 && _scanner.getToken() !== 17) {
      if (_scanner.getToken() === 5) {
        if (!needsComma) {
          handleError(4, [], []);
        }
        onSeparator(",");
        scanNext();
        if (_scanner.getToken() === 4 && allowTrailingComma) {
          break;
        }
      } else if (needsComma) {
        handleError(6, [], []);
      }
      if (isFirstElement) {
        _jsonPath.push(0);
        isFirstElement = false;
      } else {
        _jsonPath[_jsonPath.length - 1]++;
      }
      if (!parseValue22()) {
        handleError(4, [], [
          4,
          5
          /* SyntaxKind.CommaToken */
        ]);
      }
      needsComma = true;
    }
    onArrayEnd();
    if (!isFirstElement) {
      _jsonPath.pop();
    }
    if (_scanner.getToken() !== 4) {
      handleError(8, [
        4
        /* SyntaxKind.CloseBracketToken */
      ], []);
    } else {
      scanNext();
    }
    return true;
  }
  __name(parseArray22, "parseArray");
  function parseValue22() {
    switch (_scanner.getToken()) {
      case 3:
        return parseArray22();
      case 1:
        return parseObject();
      case 10:
        return parseString22(true);
      default:
        return parseLiteral();
    }
  }
  __name(parseValue22, "parseValue");
  scanNext();
  if (_scanner.getToken() === 17) {
    if (options.allowEmptyContent) {
      return true;
    }
    handleError(4, [], []);
    return false;
  }
  if (!parseValue22()) {
    handleError(4, [], []);
    return false;
  }
  if (_scanner.getToken() !== 17) {
    handleError(9, [], []);
  }
  return true;
}
__name(visit, "visit");
function getNodeType(value) {
  switch (typeof value) {
    case "boolean":
      return "boolean";
    case "number":
      return "number";
    case "string":
      return "string";
    case "object": {
      if (!value) {
        return "null";
      } else if (Array.isArray(value)) {
        return "array";
      }
      return "object";
    }
    default:
      return "null";
  }
}
__name(getNodeType, "getNodeType");
function setProperty(text, originalPath, value, options) {
  const path210 = originalPath.slice();
  const errors = [];
  const root = parseTree(text, errors);
  let parent = void 0;
  let lastSegment = void 0;
  while (path210.length > 0) {
    lastSegment = path210.pop();
    parent = findNodeAtLocation(root, path210);
    if (parent === void 0 && value !== void 0) {
      if (typeof lastSegment === "string") {
        value = { [lastSegment]: value };
      } else {
        value = [value];
      }
    } else {
      break;
    }
  }
  if (!parent) {
    if (value === void 0) {
      throw new Error("Can not delete in empty document");
    }
    return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, options);
  } else if (parent.type === "object" && typeof lastSegment === "string" && Array.isArray(parent.children)) {
    const existing = findNodeAtLocation(parent, [lastSegment]);
    if (existing !== void 0) {
      if (value === void 0) {
        if (!existing.parent) {
          throw new Error("Malformed AST");
        }
        const propertyIndex = parent.children.indexOf(existing.parent);
        let removeBegin;
        let removeEnd = existing.parent.offset + existing.parent.length;
        if (propertyIndex > 0) {
          let previous = parent.children[propertyIndex - 1];
          removeBegin = previous.offset + previous.length;
        } else {
          removeBegin = parent.offset + 1;
          if (parent.children.length > 1) {
            let next = parent.children[1];
            removeEnd = next.offset;
          }
        }
        return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: "" }, options);
      } else {
        return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, options);
      }
    } else {
      if (value === void 0) {
        return [];
      }
      const newProperty = `${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`;
      const index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map((p2) => p2.children[0].value)) : parent.children.length;
      let edit;
      if (index > 0) {
        let previous = parent.children[index - 1];
        edit = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
      } else if (parent.children.length === 0) {
        edit = { offset: parent.offset + 1, length: 0, content: newProperty };
      } else {
        edit = { offset: parent.offset + 1, length: 0, content: newProperty + "," };
      }
      return withFormatting(text, edit, options);
    }
  } else if (parent.type === "array" && typeof lastSegment === "number" && Array.isArray(parent.children)) {
    const insertIndex = lastSegment;
    if (insertIndex === -1) {
      const newProperty = `${JSON.stringify(value)}`;
      let edit;
      if (parent.children.length === 0) {
        edit = { offset: parent.offset + 1, length: 0, content: newProperty };
      } else {
        const previous = parent.children[parent.children.length - 1];
        edit = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
      }
      return withFormatting(text, edit, options);
    } else if (value === void 0 && parent.children.length >= 0) {
      const removalIndex = lastSegment;
      const toRemove = parent.children[removalIndex];
      let edit;
      if (parent.children.length === 1) {
        edit = { offset: parent.offset + 1, length: parent.length - 2, content: "" };
      } else if (parent.children.length - 1 === removalIndex) {
        let previous = parent.children[removalIndex - 1];
        let offset = previous.offset + previous.length;
        let parentEndOffset = parent.offset + parent.length;
        edit = { offset, length: parentEndOffset - 2 - offset, content: "" };
      } else {
        edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: "" };
      }
      return withFormatting(text, edit, options);
    } else if (value !== void 0) {
      let edit;
      const newProperty = `${JSON.stringify(value)}`;
      if (!options.isArrayInsertion && parent.children.length > lastSegment) {
        const toModify = parent.children[lastSegment];
        edit = { offset: toModify.offset, length: toModify.length, content: newProperty };
      } else if (parent.children.length === 0 || lastSegment === 0) {
        edit = { offset: parent.offset + 1, length: 0, content: parent.children.length === 0 ? newProperty : newProperty + "," };
      } else {
        const index = lastSegment > parent.children.length ? parent.children.length : lastSegment;
        const previous = parent.children[index - 1];
        edit = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
      }
      return withFormatting(text, edit, options);
    } else {
      throw new Error(`Can not ${value === void 0 ? "remove" : options.isArrayInsertion ? "insert" : "modify"} Array index ${insertIndex} as length is not sufficient`);
    }
  } else {
    throw new Error(`Can not add ${typeof lastSegment !== "number" ? "index" : "property"} to parent of type ${parent.type}`);
  }
}
__name(setProperty, "setProperty");
function withFormatting(text, edit, options) {
  if (!options.formattingOptions) {
    return [edit];
  }
  let newText = applyEdit(text, edit);
  let begin = edit.offset;
  let end = edit.offset + edit.content.length;
  if (edit.length === 0 || edit.content.length === 0) {
    while (begin > 0 && !isEOL(newText, begin - 1)) {
      begin--;
    }
    while (end < newText.length && !isEOL(newText, end)) {
      end++;
    }
  }
  const edits = format(newText, { offset: begin, length: end - begin }, { ...options.formattingOptions, keepLines: false });
  for (let i = edits.length - 1; i >= 0; i--) {
    const edit2 = edits[i];
    newText = applyEdit(newText, edit2);
    begin = Math.min(begin, edit2.offset);
    end = Math.max(end, edit2.offset + edit2.length);
    end += edit2.content.length - edit2.length;
  }
  const editLength = text.length - (newText.length - end) - begin;
  return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }];
}
__name(withFormatting, "withFormatting");
function applyEdit(text, edit) {
  return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);
}
__name(applyEdit, "applyEdit");
var ScanError;
(function(ScanError22) {
  ScanError22[ScanError22["None"] = 0] = "None";
  ScanError22[ScanError22["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment";
  ScanError22[ScanError22["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString";
  ScanError22[ScanError22["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber";
  ScanError22[ScanError22["InvalidUnicode"] = 4] = "InvalidUnicode";
  ScanError22[ScanError22["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter";
  ScanError22[ScanError22["InvalidCharacter"] = 6] = "InvalidCharacter";
})(ScanError || (ScanError = {}));
var SyntaxKind;
(function(SyntaxKind22) {
  SyntaxKind22[SyntaxKind22["OpenBraceToken"] = 1] = "OpenBraceToken";
  SyntaxKind22[SyntaxKind22["CloseBraceToken"] = 2] = "CloseBraceToken";
  SyntaxKind22[SyntaxKind22["OpenBracketToken"] = 3] = "OpenBracketToken";
  SyntaxKind22[SyntaxKind22["CloseBracketToken"] = 4] = "CloseBracketToken";
  SyntaxKind22[SyntaxKind22["CommaToken"] = 5] = "CommaToken";
  SyntaxKind22[SyntaxKind22["ColonToken"] = 6] = "ColonToken";
  SyntaxKind22[SyntaxKind22["NullKeyword"] = 7] = "NullKeyword";
  SyntaxKind22[SyntaxKind22["TrueKeyword"] = 8] = "TrueKeyword";
  SyntaxKind22[SyntaxKind22["FalseKeyword"] = 9] = "FalseKeyword";
  SyntaxKind22[SyntaxKind22["StringLiteral"] = 10] = "StringLiteral";
  SyntaxKind22[SyntaxKind22["NumericLiteral"] = 11] = "NumericLiteral";
  SyntaxKind22[SyntaxKind22["LineCommentTrivia"] = 12] = "LineCommentTrivia";
  SyntaxKind22[SyntaxKind22["BlockCommentTrivia"] = 13] = "BlockCommentTrivia";
  SyntaxKind22[SyntaxKind22["LineBreakTrivia"] = 14] = "LineBreakTrivia";
  SyntaxKind22[SyntaxKind22["Trivia"] = 15] = "Trivia";
  SyntaxKind22[SyntaxKind22["Unknown"] = 16] = "Unknown";
  SyntaxKind22[SyntaxKind22["EOF"] = 17] = "EOF";
})(SyntaxKind || (SyntaxKind = {}));
var parse2 = parse;
var ParseErrorCode;
(function(ParseErrorCode22) {
  ParseErrorCode22[ParseErrorCode22["InvalidSymbol"] = 1] = "InvalidSymbol";
  ParseErrorCode22[ParseErrorCode22["InvalidNumberFormat"] = 2] = "InvalidNumberFormat";
  ParseErrorCode22[ParseErrorCode22["PropertyNameExpected"] = 3] = "PropertyNameExpected";
  ParseErrorCode22[ParseErrorCode22["ValueExpected"] = 4] = "ValueExpected";
  ParseErrorCode22[ParseErrorCode22["ColonExpected"] = 5] = "ColonExpected";
  ParseErrorCode22[ParseErrorCode22["CommaExpected"] = 6] = "CommaExpected";
  ParseErrorCode22[ParseErrorCode22["CloseBraceExpected"] = 7] = "CloseBraceExpected";
  ParseErrorCode22[ParseErrorCode22["CloseBracketExpected"] = 8] = "CloseBracketExpected";
  ParseErrorCode22[ParseErrorCode22["EndOfFileExpected"] = 9] = "EndOfFileExpected";
  ParseErrorCode22[ParseErrorCode22["InvalidCommentToken"] = 10] = "InvalidCommentToken";
  ParseErrorCode22[ParseErrorCode22["UnexpectedEndOfComment"] = 11] = "UnexpectedEndOfComment";
  ParseErrorCode22[ParseErrorCode22["UnexpectedEndOfString"] = 12] = "UnexpectedEndOfString";
  ParseErrorCode22[ParseErrorCode22["UnexpectedEndOfNumber"] = 13] = "UnexpectedEndOfNumber";
  ParseErrorCode22[ParseErrorCode22["InvalidUnicode"] = 14] = "InvalidUnicode";
  ParseErrorCode22[ParseErrorCode22["InvalidEscapeCharacter"] = 15] = "InvalidEscapeCharacter";
  ParseErrorCode22[ParseErrorCode22["InvalidCharacter"] = 16] = "InvalidCharacter";
})(ParseErrorCode || (ParseErrorCode = {}));
function printParseErrorCode(code) {
  switch (code) {
    case 1:
      return "InvalidSymbol";
    case 2:
      return "InvalidNumberFormat";
    case 3:
      return "PropertyNameExpected";
    case 4:
      return "ValueExpected";
    case 5:
      return "ColonExpected";
    case 6:
      return "CommaExpected";
    case 7:
      return "CloseBraceExpected";
    case 8:
      return "CloseBracketExpected";
    case 9:
      return "EndOfFileExpected";
    case 10:
      return "InvalidCommentToken";
    case 11:
      return "UnexpectedEndOfComment";
    case 12:
      return "UnexpectedEndOfString";
    case 13:
      return "UnexpectedEndOfNumber";
    case 14:
      return "InvalidUnicode";
    case 15:
      return "InvalidEscapeCharacter";
    case 16:
      return "InvalidCharacter";
  }
  return "<unknown ParseErrorCode>";
}
__name(printParseErrorCode, "printParseErrorCode");
function format2(documentText, range, options) {
  return format(documentText, range, options);
}
__name(format2, "format");
function modify(text, path210, value, options) {
  return setProperty(text, path210, value, options);
}
__name(modify, "modify");
function applyEdits(text, edits) {
  let sortedEdits = edits.slice(0).sort((a, b) => {
    const diff = a.offset - b.offset;
    if (diff === 0) {
      return a.length - b.length;
    }
    return diff;
  });
  let lastModifiedOffset = text.length;
  for (let i = sortedEdits.length - 1; i >= 0; i--) {
    let e = sortedEdits[i];
    if (e.offset + e.length <= lastModifiedOffset) {
      text = applyEdit(text, e);
    } else {
      throw new Error("Overlapping edit");
    }
    lastModifiedOffset = e.offset;
  }
  return text;
}
__name(applyEdits, "applyEdits");
function getLineColFromPtr(string7, ptr) {
  let lines = string7.slice(0, ptr).split(/\r\n|\n|\r/g);
  return [lines.length, lines.pop().length + 1];
}
__name(getLineColFromPtr, "getLineColFromPtr");
function makeCodeBlock(string7, line, column) {
  let lines = string7.split(/\r\n|\n|\r/g);
  let codeblock = "";
  let numberLen = (Math.log10(line + 1) | 0) + 1;
  for (let i = line - 1; i <= line + 1; i++) {
    let l = lines[i - 1];
    if (!l)
      continue;
    codeblock += i.toString().padEnd(numberLen, " ");
    codeblock += ":  ";
    codeblock += l;
    codeblock += "\n";
    if (i === line) {
      codeblock += " ".repeat(numberLen + column + 2);
      codeblock += "^\n";
    }
  }
  return codeblock;
}
__name(makeCodeBlock, "makeCodeBlock");
var TomlError = class extends Error {
  static {
    __name(this, "TomlError");
  }
  line;
  column;
  codeblock;
  constructor(message, options) {
    const [line, column] = getLineColFromPtr(options.toml, options.ptr);
    const codeblock = makeCodeBlock(options.toml, line, column);
    super(`Invalid TOML document: ${message}

${codeblock}`, options);
    this.line = line;
    this.column = column;
    this.codeblock = codeblock;
  }
};
function isEscaped(str, ptr) {
  let i = 0;
  while (str[ptr - ++i] === "\\")
    ;
  return --i && i % 2;
}
__name(isEscaped, "isEscaped");
function indexOfNewline(str, start = 0, end = str.length) {
  let idx = str.indexOf("\n", start);
  if (str[idx - 1] === "\r")
    idx--;
  return idx <= end ? idx : -1;
}
__name(indexOfNewline, "indexOfNewline");
function skipComment(str, ptr) {
  for (let i = ptr; i < str.length; i++) {
    let c2 = str[i];
    if (c2 === "\n")
      return i;
    if (c2 === "\r" && str[i + 1] === "\n")
      return i + 1;
    if (c2 < " " && c2 !== "	" || c2 === "\x7F") {
      throw new TomlError("control characters are not allowed in comments", {
        toml: str,
        ptr
      });
    }
  }
  return str.length;
}
__name(skipComment, "skipComment");
function skipVoid(str, ptr, banNewLines, banComments) {
  let c2;
  while ((c2 = str[ptr]) === " " || c2 === "	" || !banNewLines && (c2 === "\n" || c2 === "\r" && str[ptr + 1] === "\n"))
    ptr++;
  return banComments || c2 !== "#" ? ptr : skipVoid(str, skipComment(str, ptr), banNewLines);
}
__name(skipVoid, "skipVoid");
function skipUntil(str, ptr, sep2, end, banNewLines = false) {
  if (!end) {
    ptr = indexOfNewline(str, ptr);
    return ptr < 0 ? str.length : ptr;
  }
  for (let i = ptr; i < str.length; i++) {
    let c2 = str[i];
    if (c2 === "#") {
      i = indexOfNewline(str, i);
    } else if (c2 === sep2) {
      return i + 1;
    } else if (c2 === end || banNewLines && (c2 === "\n" || c2 === "\r" && str[i + 1] === "\n")) {
      return i;
    }
  }
  throw new TomlError("cannot find end of structure", {
    toml: str,
    ptr
  });
}
__name(skipUntil, "skipUntil");
function getStringEnd(str, seek) {
  let first = str[seek];
  let target = first === str[seek + 1] && str[seek + 1] === str[seek + 2] ? str.slice(seek, seek + 3) : first;
  seek += target.length - 1;
  do
    seek = str.indexOf(target, ++seek);
  while (seek > -1 && first !== "'" && isEscaped(str, seek));
  if (seek > -1) {
    seek += target.length;
    if (target.length > 1) {
      if (str[seek] === first)
        seek++;
      if (str[seek] === first)
        seek++;
    }
  }
  return seek;
}
__name(getStringEnd, "getStringEnd");
var DATE_TIME_RE = /^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}:\d{2}(?:\.\d+)?)?(Z|[-+]\d{2}:\d{2})?$/i;
var TomlDate = class _TomlDate extends Date {
  static {
    __name(this, "TomlDate");
  }
  #hasDate = false;
  #hasTime = false;
  #offset = null;
  constructor(date9) {
    let hasDate = true;
    let hasTime = true;
    let offset = "Z";
    if (typeof date9 === "string") {
      let match = date9.match(DATE_TIME_RE);
      if (match) {
        if (!match[1]) {
          hasDate = false;
          date9 = `0000-01-01T${date9}`;
        }
        hasTime = !!match[2];
        hasTime && date9[10] === " " && (date9 = date9.replace(" ", "T"));
        if (match[2] && +match[2] > 23) {
          date9 = "";
        } else {
          offset = match[3] || null;
          date9 = date9.toUpperCase();
          if (!offset && hasTime)
            date9 += "Z";
        }
      } else {
        date9 = "";
      }
    }
    super(date9);
    if (!isNaN(this.getTime())) {
      this.#hasDate = hasDate;
      this.#hasTime = hasTime;
      this.#offset = offset;
    }
  }
  isDateTime() {
    return this.#hasDate && this.#hasTime;
  }
  isLocal() {
    return !this.#hasDate || !this.#hasTime || !this.#offset;
  }
  isDate() {
    return this.#hasDate && !this.#hasTime;
  }
  isTime() {
    return this.#hasTime && !this.#hasDate;
  }
  isValid() {
    return this.#hasDate || this.#hasTime;
  }
  toISOString() {
    let iso = super.toISOString();
    if (this.isDate())
      return iso.slice(0, 10);
    if (this.isTime())
      return iso.slice(11, 23);
    if (this.#offset === null)
      return iso.slice(0, -1);
    if (this.#offset === "Z")
      return iso;
    let offset = +this.#offset.slice(1, 3) * 60 + +this.#offset.slice(4, 6);
    offset = this.#offset[0] === "-" ? offset : -offset;
    let offsetDate = new Date(this.getTime() - offset * 6e4);
    return offsetDate.toISOString().slice(0, -1) + this.#offset;
  }
  static wrapAsOffsetDateTime(jsDate, offset = "Z") {
    let date9 = new _TomlDate(jsDate);
    date9.#offset = offset;
    return date9;
  }
  static wrapAsLocalDateTime(jsDate) {
    let date9 = new _TomlDate(jsDate);
    date9.#offset = null;
    return date9;
  }
  static wrapAsLocalDate(jsDate) {
    let date9 = new _TomlDate(jsDate);
    date9.#hasTime = false;
    date9.#offset = null;
    return date9;
  }
  static wrapAsLocalTime(jsDate) {
    let date9 = new _TomlDate(jsDate);
    date9.#hasDate = false;
    date9.#offset = null;
    return date9;
  }
};
var INT_REGEX = /^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/;
var FLOAT_REGEX = /^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/;
var LEADING_ZERO = /^[+-]?0[0-9_]/;
var ESCAPE_REGEX = /^[0-9a-f]{4,8}$/i;
var ESC_MAP = {
  b: "\b",
  t: "	",
  n: "\n",
  f: "\f",
  r: "\r",
  '"': '"',
  "\\": "\\"
};
function parseString(str, ptr = 0, endPtr = str.length) {
  let isLiteral = str[ptr] === "'";
  let isMultiline = str[ptr++] === str[ptr] && str[ptr] === str[ptr + 1];
  if (isMultiline) {
    endPtr -= 2;
    if (str[ptr += 2] === "\r")
      ptr++;
    if (str[ptr] === "\n")
      ptr++;
  }
  let tmp = 0;
  let isEscape;
  let parsed = "";
  let sliceStart = ptr;
  while (ptr < endPtr - 1) {
    let c2 = str[ptr++];
    if (c2 === "\n" || c2 === "\r" && str[ptr] === "\n") {
      if (!isMultiline) {
        throw new TomlError("newlines are not allowed in strings", {
          toml: str,
          ptr: ptr - 1
        });
      }
    } else if (c2 < " " && c2 !== "	" || c2 === "\x7F") {
      throw new TomlError("control characters are not allowed in strings", {
        toml: str,
        ptr: ptr - 1
      });
    }
    if (isEscape) {
      isEscape = false;
      if (c2 === "u" || c2 === "U") {
        let code = str.slice(ptr, ptr += c2 === "u" ? 4 : 8);
        if (!ESCAPE_REGEX.test(code)) {
          throw new TomlError("invalid unicode escape", {
            toml: str,
            ptr: tmp
          });
        }
        try {
          parsed += String.fromCodePoint(parseInt(code, 16));
        } catch {
          throw new TomlError("invalid unicode escape", {
            toml: str,
            ptr: tmp
          });
        }
      } else if (isMultiline && (c2 === "\n" || c2 === " " || c2 === "	" || c2 === "\r")) {
        ptr = skipVoid(str, ptr - 1, true);
        if (str[ptr] !== "\n" && str[ptr] !== "\r") {
          throw new TomlError("invalid escape: only line-ending whitespace may be escaped", {
            toml: str,
            ptr: tmp
          });
        }
        ptr = skipVoid(str, ptr);
      } else if (c2 in ESC_MAP) {
        parsed += ESC_MAP[c2];
      } else {
        throw new TomlError("unrecognized escape sequence", {
          toml: str,
          ptr: tmp
        });
      }
      sliceStart = ptr;
    } else if (!isLiteral && c2 === "\\") {
      tmp = ptr - 1;
      isEscape = true;
      parsed += str.slice(sliceStart, tmp);
    }
  }
  return parsed + str.slice(sliceStart, endPtr - 1);
}
__name(parseString, "parseString");
function parseValue(value, toml, ptr, integersAsBigInt) {
  if (value === "true")
    return true;
  if (value === "false")
    return false;
  if (value === "-inf")
    return -Infinity;
  if (value === "inf" || value === "+inf")
    return Infinity;
  if (value === "nan" || value === "+nan" || value === "-nan")
    return NaN;
  if (value === "-0")
    return integersAsBigInt ? 0n : 0;
  let isInt = INT_REGEX.test(value);
  if (isInt || FLOAT_REGEX.test(value)) {
    if (LEADING_ZERO.test(value)) {
      throw new TomlError("leading zeroes are not allowed", {
        toml,
        ptr
      });
    }
    value = value.replace(/_/g, "");
    let numeric = +value;
    if (isNaN(numeric)) {
      throw new TomlError("invalid number", {
        toml,
        ptr
      });
    }
    if (isInt) {
      if ((isInt = !Number.isSafeInteger(numeric)) && !integersAsBigInt) {
        throw new TomlError("integer value cannot be represented losslessly", {
          toml,
          ptr
        });
      }
      if (isInt || integersAsBigInt === true)
        numeric = BigInt(value);
    }
    return numeric;
  }
  const date9 = new TomlDate(value);
  if (!date9.isValid()) {
    throw new TomlError("invalid value", {
      toml,
      ptr
    });
  }
  return date9;
}
__name(parseValue, "parseValue");
function sliceAndTrimEndOf(str, startPtr, endPtr, allowNewLines) {
  let value = str.slice(startPtr, endPtr);
  let commentIdx = value.indexOf("#");
  if (commentIdx > -1) {
    skipComment(str, commentIdx);
    value = value.slice(0, commentIdx);
  }
  let trimmed = value.trimEnd();
  if (!allowNewLines) {
    let newlineIdx = value.indexOf("\n", trimmed.length);
    if (newlineIdx > -1) {
      throw new TomlError("newlines are not allowed in inline tables", {
        toml: str,
        ptr: startPtr + newlineIdx
      });
    }
  }
  return [trimmed, commentIdx];
}
__name(sliceAndTrimEndOf, "sliceAndTrimEndOf");
function extractValue(str, ptr, end, depth, integersAsBigInt) {
  if (depth === 0) {
    throw new TomlError("document contains excessively nested structures. aborting.", {
      toml: str,
      ptr
    });
  }
  let c2 = str[ptr];
  if (c2 === "[" || c2 === "{") {
    let [value, endPtr2] = c2 === "[" ? parseArray(str, ptr, depth, integersAsBigInt) : parseInlineTable(str, ptr, depth, integersAsBigInt);
    let newPtr = end ? skipUntil(str, endPtr2, ",", end) : endPtr2;
    if (endPtr2 - newPtr && end === "}") {
      let nextNewLine = indexOfNewline(str, endPtr2, newPtr);
      if (nextNewLine > -1) {
        throw new TomlError("newlines are not allowed in inline tables", {
          toml: str,
          ptr: nextNewLine
        });
      }
    }
    return [value, newPtr];
  }
  let endPtr;
  if (c2 === '"' || c2 === "'") {
    endPtr = getStringEnd(str, ptr);
    let parsed = parseString(str, ptr, endPtr);
    if (end) {
      endPtr = skipVoid(str, endPtr, end !== "]");
      if (str[endPtr] && str[endPtr] !== "," && str[endPtr] !== end && str[endPtr] !== "\n" && str[endPtr] !== "\r") {
        throw new TomlError("unexpected character encountered", {
          toml: str,
          ptr: endPtr
        });
      }
      endPtr += +(str[endPtr] === ",");
    }
    return [parsed, endPtr];
  }
  endPtr = skipUntil(str, ptr, ",", end);
  let slice = sliceAndTrimEndOf(str, ptr, endPtr - +(str[endPtr - 1] === ","), end === "]");
  if (!slice[0]) {
    throw new TomlError("incomplete key-value declaration: no value specified", {
      toml: str,
      ptr
    });
  }
  if (end && slice[1] > -1) {
    endPtr = skipVoid(str, ptr + slice[1]);
    endPtr += +(str[endPtr] === ",");
  }
  return [
    parseValue(slice[0], str, ptr, integersAsBigInt),
    endPtr
  ];
}
__name(extractValue, "extractValue");
var KEY_PART_RE = /^[a-zA-Z0-9-_]+[ \t]*$/;
function parseKey(str, ptr, end = "=") {
  let dot = ptr - 1;
  let parsed = [];
  let endPtr = str.indexOf(end, ptr);
  if (endPtr < 0) {
    throw new TomlError("incomplete key-value: cannot find end of key", {
      toml: str,
      ptr
    });
  }
  do {
    let c2 = str[ptr = ++dot];
    if (c2 !== " " && c2 !== "	") {
      if (c2 === '"' || c2 === "'") {
        if (c2 === str[ptr + 1] && c2 === str[ptr + 2]) {
          throw new TomlError("multiline strings are not allowed in keys", {
            toml: str,
            ptr
          });
        }
        let eos = getStringEnd(str, ptr);
        if (eos < 0) {
          throw new TomlError("unfinished string encountered", {
            toml: str,
            ptr
          });
        }
        dot = str.indexOf(".", eos);
        let strEnd = str.slice(eos, dot < 0 || dot > endPtr ? endPtr : dot);
        let newLine = indexOfNewline(strEnd);
        if (newLine > -1) {
          throw new TomlError("newlines are not allowed in keys", {
            toml: str,
            ptr: ptr + dot + newLine
          });
        }
        if (strEnd.trimStart()) {
          throw new TomlError("found extra tokens after the string part", {
            toml: str,
            ptr: eos
          });
        }
        if (endPtr < eos) {
          endPtr = str.indexOf(end, eos);
          if (endPtr < 0) {
            throw new TomlError("incomplete key-value: cannot find end of key", {
              toml: str,
              ptr
            });
          }
        }
        parsed.push(parseString(str, ptr, eos));
      } else {
        dot = str.indexOf(".", ptr);
        let part = str.slice(ptr, dot < 0 || dot > endPtr ? endPtr : dot);
        if (!KEY_PART_RE.test(part)) {
          throw new TomlError("only letter, numbers, dashes and underscores are allowed in keys", {
            toml: str,
            ptr
          });
        }
        parsed.push(part.trimEnd());
      }
    }
  } while (dot + 1 && dot < endPtr);
  return [parsed, skipVoid(str, endPtr + 1, true, true)];
}
__name(parseKey, "parseKey");
function parseInlineTable(str, ptr, depth, integersAsBigInt) {
  let res = {};
  let seen = /* @__PURE__ */ new Set();
  let c2;
  let comma = 0;
  ptr++;
  while ((c2 = str[ptr++]) !== "}" && c2) {
    let err = { toml: str, ptr: ptr - 1 };
    if (c2 === "\n") {
      throw new TomlError("newlines are not allowed in inline tables", err);
    } else if (c2 === "#") {
      throw new TomlError("inline tables cannot contain comments", err);
    } else if (c2 === ",") {
      throw new TomlError("expected key-value, found comma", err);
    } else if (c2 !== " " && c2 !== "	") {
      let k;
      let t = res;
      let hasOwn = false;
      let [key, keyEndPtr] = parseKey(str, ptr - 1);
      for (let i = 0; i < key.length; i++) {
        if (i)
          t = hasOwn ? t[k] : t[k] = {};
        k = key[i];
        if ((hasOwn = Object.hasOwn(t, k)) && (typeof t[k] !== "object" || seen.has(t[k]))) {
          throw new TomlError("trying to redefine an already defined value", {
            toml: str,
            ptr
          });
        }
        if (!hasOwn && k === "__proto__") {
          Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
        }
      }
      if (hasOwn) {
        throw new TomlError("trying to redefine an already defined value", {
          toml: str,
          ptr
        });
      }
      let [value, valueEndPtr] = extractValue(str, keyEndPtr, "}", depth - 1, integersAsBigInt);
      seen.add(value);
      t[k] = value;
      ptr = valueEndPtr;
      comma = str[ptr - 1] === "," ? ptr - 1 : 0;
    }
  }
  if (comma) {
    throw new TomlError("trailing commas are not allowed in inline tables", {
      toml: str,
      ptr: comma
    });
  }
  if (!c2) {
    throw new TomlError("unfinished table encountered", {
      toml: str,
      ptr
    });
  }
  return [res, ptr];
}
__name(parseInlineTable, "parseInlineTable");
function parseArray(str, ptr, depth, integersAsBigInt) {
  let res = [];
  let c2;
  ptr++;
  while ((c2 = str[ptr++]) !== "]" && c2) {
    if (c2 === ",") {
      throw new TomlError("expected value, found comma", {
        toml: str,
        ptr: ptr - 1
      });
    } else if (c2 === "#")
      ptr = skipComment(str, ptr);
    else if (c2 !== " " && c2 !== "	" && c2 !== "\n" && c2 !== "\r") {
      let e = extractValue(str, ptr - 1, "]", depth - 1, integersAsBigInt);
      res.push(e[0]);
      ptr = e[1];
    }
  }
  if (!c2) {
    throw new TomlError("unfinished array encountered", {
      toml: str,
      ptr
    });
  }
  return [res, ptr];
}
__name(parseArray, "parseArray");
function peekTable(key, table, meta5, type) {
  let t = table;
  let m = meta5;
  let k;
  let hasOwn = false;
  let state;
  for (let i = 0; i < key.length; i++) {
    if (i) {
      t = hasOwn ? t[k] : t[k] = {};
      m = (state = m[k]).c;
      if (type === 0 && (state.t === 1 || state.t === 2)) {
        return null;
      }
      if (state.t === 2) {
        let l = t.length - 1;
        t = t[l];
        m = m[l].c;
      }
    }
    k = key[i];
    if ((hasOwn = Object.hasOwn(t, k)) && m[k]?.t === 0 && m[k]?.d) {
      return null;
    }
    if (!hasOwn) {
      if (k === "__proto__") {
        Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
        Object.defineProperty(m, k, { enumerable: true, configurable: true, writable: true });
      }
      m[k] = {
        t: i < key.length - 1 && type === 2 ? 3 : type,
        d: false,
        i: 0,
        c: {}
      };
    }
  }
  state = m[k];
  if (state.t !== type && !(type === 1 && state.t === 3)) {
    return null;
  }
  if (type === 2) {
    if (!state.d) {
      state.d = true;
      t[k] = [];
    }
    t[k].push(t = {});
    state.c[state.i++] = state = { t: 1, d: false, i: 0, c: {} };
  }
  if (state.d) {
    return null;
  }
  state.d = true;
  if (type === 1) {
    t = hasOwn ? t[k] : t[k] = {};
  } else if (type === 0 && hasOwn) {
    return null;
  }
  return [k, t, state.c];
}
__name(peekTable, "peekTable");
function parse3(toml, { maxDepth = 1e3, integersAsBigInt } = {}) {
  let res = {};
  let meta5 = {};
  let tbl = res;
  let m = meta5;
  for (let ptr = skipVoid(toml, 0); ptr < toml.length; ) {
    if (toml[ptr] === "[") {
      let isTableArray = toml[++ptr] === "[";
      let k = parseKey(toml, ptr += +isTableArray, "]");
      if (isTableArray) {
        if (toml[k[1] - 1] !== "]") {
          throw new TomlError("expected end of table declaration", {
            toml,
            ptr: k[1] - 1
          });
        }
        k[1]++;
      }
      let p2 = peekTable(
        k[0],
        res,
        meta5,
        isTableArray ? 2 : 1
        /* Type.EXPLICIT */
      );
      if (!p2) {
        throw new TomlError("trying to redefine an already defined table or value", {
          toml,
          ptr
        });
      }
      m = p2[2];
      tbl = p2[1];
      ptr = k[1];
    } else {
      let k = parseKey(toml, ptr);
      let p2 = peekTable(
        k[0],
        tbl,
        m,
        0
        /* Type.DOTTED */
      );
      if (!p2) {
        throw new TomlError("trying to redefine an already defined table or value", {
          toml,
          ptr
        });
      }
      let v = extractValue(toml, k[1], void 0, maxDepth, integersAsBigInt);
      p2[1][p2[0]] = v[0];
      ptr = v[1];
    }
    ptr = skipVoid(toml, ptr, true);
    if (toml[ptr] && toml[ptr] !== "\n" && toml[ptr] !== "\r") {
      throw new TomlError("each key-value declaration must be followed by an end-of-line", {
        toml,
        ptr
      });
    }
    ptr = skipVoid(toml, ptr);
  }
  return res;
}
__name(parse3, "parse");
var BARE_KEY = /^[a-z0-9-_]+$/i;
function extendedTypeOf(obj) {
  let type = typeof obj;
  if (type === "object") {
    if (Array.isArray(obj))
      return "array";
    if (obj instanceof Date)
      return "date";
  }
  return type;
}
__name(extendedTypeOf, "extendedTypeOf");
function isArrayOfTables(obj) {
  for (let i = 0; i < obj.length; i++) {
    if (extendedTypeOf(obj[i]) !== "object")
      return false;
  }
  return obj.length != 0;
}
__name(isArrayOfTables, "isArrayOfTables");
function formatString(s) {
  return JSON.stringify(s).replace(/\x7f/g, "\\u007f");
}
__name(formatString, "formatString");
function stringifyValue(val, type, depth, numberAsFloat) {
  if (depth === 0) {
    throw new Error("Could not stringify the object: maximum object depth exceeded");
  }
  if (type === "number") {
    if (isNaN(val))
      return "nan";
    if (val === Infinity)
      return "inf";
    if (val === -Infinity)
      return "-inf";
    if (numberAsFloat && Number.isInteger(val))
      return val.toFixed(1);
    return val.toString();
  }
  if (type === "bigint" || type === "boolean") {
    return val.toString();
  }
  if (type === "string") {
    return formatString(val);
  }
  if (type === "date") {
    if (isNaN(val.getTime())) {
      throw new TypeError("cannot serialize invalid date");
    }
    return val.toISOString();
  }
  if (type === "object") {
    return stringifyInlineTable(val, depth, numberAsFloat);
  }
  if (type === "array") {
    return stringifyArray(val, depth, numberAsFloat);
  }
}
__name(stringifyValue, "stringifyValue");
function stringifyInlineTable(obj, depth, numberAsFloat) {
  let keys = Object.keys(obj);
  if (keys.length === 0)
    return "{}";
  let res = "{ ";
  for (let i = 0; i < keys.length; i++) {
    let k = keys[i];
    if (i)
      res += ", ";
    res += BARE_KEY.test(k) ? k : formatString(k);
    res += " = ";
    res += stringifyValue(obj[k], extendedTypeOf(obj[k]), depth - 1, numberAsFloat);
  }
  return res + " }";
}
__name(stringifyInlineTable, "stringifyInlineTable");
function stringifyArray(array3, depth, numberAsFloat) {
  if (array3.length === 0)
    return "[]";
  let res = "[ ";
  for (let i = 0; i < array3.length; i++) {
    if (i)
      res += ", ";
    if (array3[i] === null || array3[i] === void 0) {
      throw new TypeError("arrays cannot contain null or undefined values");
    }
    res += stringifyValue(array3[i], extendedTypeOf(array3[i]), depth - 1, numberAsFloat);
  }
  return res + " ]";
}
__name(stringifyArray, "stringifyArray");
function stringifyArrayTable(array3, key, depth, numberAsFloat) {
  if (depth === 0) {
    throw new Error("Could not stringify the object: maximum object depth exceeded");
  }
  let res = "";
  for (let i = 0; i < array3.length; i++) {
    res += `${res && "\n"}[[${key}]]
`;
    res += stringifyTable(0, array3[i], key, depth, numberAsFloat);
  }
  return res;
}
__name(stringifyArrayTable, "stringifyArrayTable");
function stringifyTable(tableKey, obj, prefix, depth, numberAsFloat) {
  if (depth === 0) {
    throw new Error("Could not stringify the object: maximum object depth exceeded");
  }
  let preamble = "";
  let tables = "";
  let keys = Object.keys(obj);
  for (let i = 0; i < keys.length; i++) {
    let k = keys[i];
    if (obj[k] !== null && obj[k] !== void 0) {
      let type = extendedTypeOf(obj[k]);
      if (type === "symbol" || type === "function") {
        throw new TypeError(`cannot serialize values of type '${type}'`);
      }
      let key = BARE_KEY.test(k) ? k : formatString(k);
      if (type === "array" && isArrayOfTables(obj[k])) {
        tables += (tables && "\n") + stringifyArrayTable(obj[k], prefix ? `${prefix}.${key}` : key, depth - 1, numberAsFloat);
      } else if (type === "object") {
        let tblKey = prefix ? `${prefix}.${key}` : key;
        tables += (tables && "\n") + stringifyTable(tblKey, obj[k], tblKey, depth - 1, numberAsFloat);
      } else {
        preamble += key;
        preamble += " = ";
        preamble += stringifyValue(obj[k], type, depth, numberAsFloat);
        preamble += "\n";
      }
    }
  }
  if (tableKey && (preamble || !tables))
    preamble = preamble ? `[${tableKey}]
${preamble}` : `[${tableKey}]`;
  return preamble && tables ? `${preamble}
${tables}` : preamble || tables;
}
__name(stringifyTable, "stringifyTable");
function stringify(obj, { maxDepth = 1e3, numbersAsFloat = false } = {}) {
  if (extendedTypeOf(obj) !== "object") {
    throw new TypeError("stringify can only be called with an object");
  }
  let str = stringifyTable(0, obj, "", maxDepth, numbersAsFloat);
  if (str[str.length - 1] !== "\n")
    return str + "\n";
  return str;
}
__name(stringify, "stringify");
var dist_default = { parse: parse3, stringify, TomlDate, TomlError };
var ParseError = class extends UserError {
  static {
    __name(this, "ParseError");
  }
  text;
  notes;
  location;
  kind;
  constructor({ text, notes, location, kind, telemetryMessage }) {
    super(text, { telemetryMessage });
    this.name = this.constructor.name;
    this.text = text;
    this.notes = notes ?? [];
    this.location = location;
    this.kind = kind ?? "error";
  }
};
var APIError = class extends ParseError {
  static {
    __name(this, "APIError");
  }
  #status;
  code;
  accountTag;
  /**
   * Optional structured metadata hoisted from the first `FetchError.meta`
   * on the v4 response envelope. Consumers can inspect this to render
   * endpoint-specific structured error payloads.
   */
  meta;
  /**
   * Optional number of milliseconds the API asked us to wait before retrying,
   * derived from the response's `Retry-After` header (if present).
   */
  retryAfterMs;
  constructor({
    status: status2,
    retryAfterMs,
    ...rest
  }) {
    super(rest);
    this.name = this.constructor.name;
    this.#status = status2;
    this.retryAfterMs = retryAfterMs;
  }
  get status() {
    return this.#status;
  }
  isGatewayError() {
    if (this.#status !== void 0) {
      return [524].includes(this.#status);
    }
    return false;
  }
  isRetryable() {
    return String(this.#status).startsWith("5");
  }
  // Allow `APIError`s to be marked as handled.
  #reportable = true;
  get reportable() {
    return this.#reportable;
  }
  preventReport() {
    this.#reportable = false;
  }
};
function parseTOML(tomlContent, filePath) {
  try {
    return dist_default.parse(tomlContent);
  } catch (err) {
    if (!(err instanceof TomlError)) {
      throw err;
    }
    const location = {
      lineText: tomlContent.split("\n")[err.line - 1],
      line: err.line,
      column: err.column - 1,
      file: filePath,
      fileText: tomlContent
    };
    throw new ParseError({
      text: err.message.substring(0, err.message.indexOf("\n")),
      location,
      telemetryMessage: "TOML parse error"
    });
  }
}
__name(parseTOML, "parseTOML");
function parsePackageJSON(input, file22) {
  return parseJSON(input, file22);
}
__name(parsePackageJSON, "parsePackageJSON");
function parseJSON(input, file22) {
  return parseJSONC(input, file22, {
    allowEmptyContent: false,
    allowTrailingComma: false,
    disallowComments: true
  });
}
__name(parseJSON, "parseJSON");
function parseJSONC(input, file22, options = { allowTrailingComma: true }) {
  const errors = [];
  const data = parse2(input, errors, options);
  if (errors.length) {
    throw new ParseError({
      text: printParseErrorCode(errors[0].error),
      location: {
        ...indexLocation({ file: file22, fileText: input }, errors[0].offset + 1),
        length: errors[0].length
      },
      telemetryMessage: "JSON(C) parse error"
    });
  }
  return data;
}
__name(parseJSONC, "parseJSONC");
function readFileSyncToBuffer(file22) {
  try {
    return (0, import_node_fs2.readFileSync)(file22);
  } catch (err) {
    const { message } = err;
    throw new ParseError({
      text: `Could not read file: ${file22}`,
      notes: [
        {
          text: message.replace(file22, (0, import_node_path2.resolve)(file22))
        }
      ],
      telemetryMessage: false
    });
  }
}
__name(readFileSyncToBuffer, "readFileSyncToBuffer");
function readFileSync(file22) {
  try {
    const buffer = (0, import_node_fs2.readFileSync)(file22);
    return removeBOMAndValidate(buffer, file22);
  } catch (err) {
    if (err instanceof ParseError) {
      throw err;
    }
    const { message } = err;
    throw new ParseError({
      text: `Could not read file: ${file22}`,
      notes: [
        {
          text: message.replace(file22, (0, import_node_path2.resolve)(file22))
        }
      ],
      telemetryMessage: "Could not read file"
    });
  }
}
__name(readFileSync, "readFileSync");
function indexLocation(file22, index) {
  let lineText, line = 0, column = 0, cursor = 0;
  const { fileText = "" } = file22;
  for (const row of fileText.split("\n")) {
    line++;
    cursor += row.length + 1;
    if (cursor >= index) {
      lineText = row;
      column = row.length - (cursor - index);
      break;
    }
  }
  return { lineText, line, column, ...file22 };
}
__name(indexLocation, "indexLocation");
function searchLocation(file22, query) {
  let lineText, length, line = 0, column = 0;
  const queryText = String(query);
  const { fileText = "" } = file22;
  for (const content of fileText.split("\n")) {
    line++;
    const index = content.indexOf(queryText);
    if (index >= 0) {
      lineText = content;
      column = index;
      length = queryText.length;
      break;
    }
  }
  return { lineText, line, column, length, ...file22 };
}
__name(searchLocation, "searchLocation");
var units = {
  nanoseconds: 1e-9,
  nanosecond: 1e-9,
  microseconds: 1e-6,
  microsecond: 1e-6,
  milliseconds: 1e-3,
  millisecond: 1e-3,
  seconds: 1,
  second: 1,
  minutes: 60,
  minute: 60,
  hours: 3600,
  hour: 3600,
  days: 86400,
  day: 86400,
  weeks: 604800,
  week: 604800,
  month: 18144e3,
  year: 220752e3,
  nsecs: 1e-9,
  nsec: 1e-9,
  usecs: 1e-6,
  usec: 1e-6,
  msecs: 1e-3,
  msec: 1e-3,
  secs: 1,
  sec: 1,
  mins: 60,
  min: 60,
  ns: 1e-9,
  us: 1e-6,
  ms: 1e-3,
  mo: 18144e3,
  yr: 220752e3,
  s: 1,
  m: 60,
  h: 3600,
  d: 86400,
  w: 604800,
  y: 220752e3
};
function parseHumanDuration(s) {
  const unitsMap = new Map(Object.entries(units));
  s = s.trim().toLowerCase();
  let base = 1;
  for (const [name, _] of unitsMap) {
    if (s.endsWith(name)) {
      s = s.substring(0, s.length - name.length);
      base = unitsMap.get(name) || 1;
      break;
    }
  }
  return Number(s) * base;
}
__name(parseHumanDuration, "parseHumanDuration");
function parseNonHyphenedUuid(uuid8) {
  if (uuid8 == null || uuid8.includes("-")) {
    return uuid8;
  }
  if (uuid8.length != 32) {
    return null;
  }
  const uuid_parts = [];
  uuid_parts.push(uuid8.slice(0, 8));
  uuid_parts.push(uuid8.slice(8, 12));
  uuid_parts.push(uuid8.slice(12, 16));
  uuid_parts.push(uuid8.slice(16, 20));
  uuid_parts.push(uuid8.slice(20));
  let hyphenated = "";
  uuid_parts.forEach((part) => hyphenated += part + "-");
  return hyphenated.slice(0, 36);
}
__name(parseNonHyphenedUuid, "parseNonHyphenedUuid");
function parseByteSize(s, base = void 0) {
  const match = s.match(
    /^(\d*\.*\d*)\s*([kKmMgGtTpP]{0,1})([i]{0,1}[bB]{0,1})$/
  );
  if (!match) {
    return NaN;
  }
  const size = match[1];
  if (size.length === 0 || isNaN(Number(size))) {
    return NaN;
  }
  const unit = match[2].toLowerCase();
  const sizeUnits = {
    k: 1,
    m: 2,
    g: 3,
    t: 4,
    p: 5
  };
  if (unit.length !== 0 && !(unit in sizeUnits)) {
    return NaN;
  }
  const binary = match[3].toLowerCase() == "ib";
  if (binary && unit.length === 0) {
    return NaN;
  }
  const pow = sizeUnits[unit] || 0;
  return Math.floor(
    Number(size) * Math.pow(base ?? (binary ? 1024 : 1e3), pow)
  );
}
__name(parseByteSize, "parseByteSize");
var UNSUPPORTED_BOMS = [
  {
    buffer: Buffer.from([0, 0, 254, 255]),
    encoding: "UTF-32 BE"
  },
  {
    buffer: Buffer.from([255, 254, 0, 0]),
    encoding: "UTF-32 LE"
  },
  {
    buffer: Buffer.from([254, 255]),
    encoding: "UTF-16 BE"
  },
  {
    buffer: Buffer.from([255, 254]),
    encoding: "UTF-16 LE"
  }
];
function removeBOMAndValidate(buffer, file22) {
  for (const bom of UNSUPPORTED_BOMS) {
    if (buffer.length >= bom.buffer.length && buffer.subarray(0, bom.buffer.length).equals(bom.buffer)) {
      throw new ParseError({
        text: `Configuration file contains ${bom.encoding} byte order marker`,
        notes: [
          {
            text: `The file "${file22}" appears to be encoded as ${bom.encoding}. Please save the file as UTF-8 without BOM.`
          }
        ],
        location: { file: file22, line: 1, column: 0 },
        telemetryMessage: `${bom.encoding} BOM detected`
      });
    }
  }
  const content = buffer.toString("utf-8");
  if (content.charCodeAt(0) === 65279) {
    return content.slice(1);
  }
  return content;
}
__name(removeBOMAndValidate, "removeBOMAndValidate");
var PATH_TO_DEPLOY_CONFIG = ".wrangler/deploy/config.json";
function absolute(input, root) {
  return (0, import_node_path2.isAbsolute)(input) ? input : (0, import_node_path2.resolve)(root || ".", input);
}
__name(absolute, "absolute");
function up(base, options) {
  let { last, cwd: cwd2 } = options || {};
  let tmp = absolute(base, cwd2);
  let root = absolute(last || "/", cwd2);
  let prev, arr = [];
  while (prev !== root) {
    arr.push(tmp);
    tmp = (0, import_node_path2.dirname)(prev = tmp);
    if (tmp === prev) break;
  }
  return arr;
}
__name(up, "up");
function file(name, options) {
  let dir22, tmp;
  let start = options && options.cwd || "";
  for (dir22 of up(start, options)) {
    try {
      tmp = (0, import_node_path2.join)(dir22, name);
      if ((0, import_node_fs2.statSync)(tmp).isFile()) return tmp;
    } catch {
    }
  }
}
__name(file, "file");
function dir(name, options) {
  let dir22, tmp;
  let start = options && options.cwd || "";
  for (dir22 of up(start, options)) {
    try {
      tmp = (0, import_node_path2.join)(dir22, name);
      if ((0, import_node_fs2.statSync)(tmp).isDirectory()) return tmp;
    } catch {
    }
  }
}
__name(dir, "dir");
function dedent(templ) {
  var values = [];
  for (var _i = 1; _i < arguments.length; _i++) {
    values[_i - 1] = arguments[_i];
  }
  var strings = Array.from(typeof templ === "string" ? [templ] : templ);
  strings[strings.length - 1] = strings[strings.length - 1].replace(/\r?\n([\t ]*)$/, "");
  var indentLengths = strings.reduce(function(arr, str) {
    var matches = str.match(/\n([\t ]+|(?!\s).)/g);
    if (matches) {
      return arr.concat(matches.map(function(match) {
        var _a5, _b;
        return (_b = (_a5 = match.match(/[\t ]/g)) === null || _a5 === void 0 ? void 0 : _a5.length) !== null && _b !== void 0 ? _b : 0;
      }));
    }
    return arr;
  }, []);
  if (indentLengths.length) {
    var pattern_1 = new RegExp("\n[	 ]{" + Math.min.apply(Math, indentLengths) + "}", "g");
    strings = strings.map(function(str) {
      return str.replace(pattern_1, "\n");
    });
  }
  strings[0] = strings[0].replace(/^\r?\n/, "");
  var string7 = strings[0];
  values.forEach(function(value, i) {
    var endentations = string7.match(/(?:^|\n)( *)$/);
    var endentation = endentations ? endentations[1] : "";
    var indentedValue = value;
    if (typeof value === "string" && value.includes("\n")) {
      indentedValue = String(value).split("\n").map(function(str, i2) {
        return i2 === 0 ? str : "" + endentation + str;
      }).join("\n");
    }
    string7 += indentedValue + strings[i + 1];
  });
  return string7;
}
__name(dedent, "dedent");
var esm_default = dedent;
function resolveWranglerConfigPath({
  config: config3,
  script
}, options) {
  if (config3 !== void 0) {
    return {
      userConfigPath: config3,
      configPath: config3,
      deployConfigPath: void 0,
      redirected: false
    };
  }
  const leafPath = script !== void 0 ? import_node_path2.default.dirname(script) : process.cwd();
  return findWranglerConfig(leafPath, options);
}
__name(resolveWranglerConfigPath, "resolveWranglerConfigPath");
function findWranglerConfig(referencePath = process.cwd(), { useRedirectIfAvailable = false } = {}) {
  const userConfigPath = file(`wrangler.json`, { cwd: referencePath }) ?? file(`wrangler.jsonc`, { cwd: referencePath }) ?? file(`wrangler.toml`, { cwd: referencePath });
  if (!useRedirectIfAvailable) {
    return {
      userConfigPath,
      configPath: userConfigPath,
      deployConfigPath: void 0,
      redirected: false
    };
  }
  const { configPath, deployConfigPath, redirected } = findRedirectedWranglerConfig(referencePath, userConfigPath);
  return {
    userConfigPath,
    configPath,
    deployConfigPath,
    redirected
  };
}
__name(findWranglerConfig, "findWranglerConfig");
function findRedirectedWranglerConfig(cwd2, userConfigPath) {
  const deployConfigPath = file(PATH_TO_DEPLOY_CONFIG, { cwd: cwd2 });
  if (deployConfigPath === void 0) {
    return { configPath: userConfigPath, deployConfigPath, redirected: false };
  }
  let redirectedConfigPath;
  const deployConfigFile = readFileSync(deployConfigPath);
  try {
    const deployConfig = parseJSONC(deployConfigFile, deployConfigPath);
    redirectedConfigPath = deployConfig.configPath && import_node_path2.default.resolve(import_node_path2.default.dirname(deployConfigPath), deployConfig.configPath);
  } catch (e) {
    throw new UserError(
      `Failed to parse the deploy configuration file at ${import_node_path2.default.relative(".", deployConfigPath)}`,
      { cause: e, telemetryMessage: false }
    );
  }
  if (!redirectedConfigPath) {
    throw new UserError(
      esm_default`
			A deploy configuration file was found at "${import_node_path2.default.relative(".", deployConfigPath)}".
			But this is not valid - the required "configPath" property was not found.
			Instead this file contains:
			\`\`\`
			${deployConfigFile}
			\`\`\`
		`,
      { telemetryMessage: false }
    );
  }
  if (!(0, import_node_fs2.existsSync)(redirectedConfigPath)) {
    throw new UserError(
      esm_default`
				There is a deploy configuration at "${import_node_path2.default.relative(".", deployConfigPath)}".
				But the redirected configuration path it points to, "${import_node_path2.default.relative(".", redirectedConfigPath)}", does not exist.
			`,
      { telemetryMessage: false }
    );
  }
  if (userConfigPath) {
    if (import_node_path2.default.join(import_node_path2.default.dirname(userConfigPath), PATH_TO_DEPLOY_CONFIG) !== deployConfigPath) {
      throw new UserError(
        esm_default`
					Found both a user configuration file at "${import_node_path2.default.relative(".", userConfigPath)}"
					and a deploy configuration file at "${import_node_path2.default.relative(".", deployConfigPath)}".
					But these do not share the same base path so it is not clear which should be used.
				`,
        { telemetryMessage: false }
      );
    }
  }
  return {
    configPath: redirectedConfigPath,
    deployConfigPath,
    redirected: true
  };
}
__name(findRedirectedWranglerConfig, "findRedirectedWranglerConfig");
function isRedirectedConfig(config3) {
  return config3.configPath !== void 0 && config3.configPath !== config3.userConfigPath;
}
__name(isRedirectedConfig, "isRedirectedConfig");
function isRedirectedRawConfig(rawConfig, configPath, userConfigPath) {
  return isRedirectedConfig({ configPath, userConfigPath });
}
__name(isRedirectedRawConfig, "isRedirectedRawConfig");
function configFormat(configPath) {
  if (configPath?.endsWith("toml")) {
    return "toml";
  }
  if (configPath?.endsWith("jsonc")) {
    return "jsonc";
  }
  if (configPath?.endsWith("json")) {
    return "json";
  }
  return "none";
}
__name(configFormat, "configFormat");
function configFileName(configPath) {
  const format32 = configFormat(configPath);
  switch (format32) {
    case "toml":
      return "wrangler.toml";
    case "json":
      return "wrangler.json";
    case "jsonc":
      return "wrangler.jsonc";
    default:
      return "Wrangler configuration";
  }
}
__name(configFileName, "configFileName");
function formatConfigSnippet(snippet, configPath, formatted = true) {
  const format32 = configFormat(configPath);
  if (format32 === "toml") {
    return dist_default.stringify(snippet);
  } else {
    return formatted ? JSON.stringify(snippet, null, 2) : JSON.stringify(snippet);
  }
}
__name(formatConfigSnippet, "formatConfigSnippet");

// ../workers-utils/dist/index.mjs
init_chunk_Q72B4Q5Z();
var import_node_fs4 = __toESM(require("node:fs"), 1);
var import_node_assert = __toESM(require("node:assert"), 1);
var path22 = __toESM(require("node:path"), 1);
var import_node_path4 = __toESM(require("node:path"), 1);
var import_node_child_process2 = require("node:child_process");
var import_node_crypto = require("node:crypto");
var import_node_os4 = require("node:os");
var import_undici = require("undici");
var import_node_url2 = require("node:url");
var timersPromises = __toESM(require("node:timers/promises"), 1);
var import_promises2 = require("node:timers/promises");
var import_node_util2 = __toESM(require("node:util"), 1);
var import_node_console = require("node:console");
var require_vendors = __commonJS2({
  "../../node_modules/.pnpm/ci-info@4.4.0/node_modules/ci-info/vendors.json"(exports2, module2) {
    module2.exports = [
      {
        name: "Agola CI",
        constant: "AGOLA",
        env: "AGOLA_GIT_REF",
        pr: "AGOLA_PULL_REQUEST_ID"
      },
      {
        name: "Alpic",
        constant: "ALPIC",
        env: "ALPIC_HOST"
      },
      {
        name: "Appcircle",
        constant: "APPCIRCLE",
        env: "AC_APPCIRCLE",
        pr: {
          env: "AC_GIT_PR",
          ne: "false"
        }
      },
      {
        name: "AppVeyor",
        constant: "APPVEYOR",
        env: "APPVEYOR",
        pr: "APPVEYOR_PULL_REQUEST_NUMBER"
      },
      {
        name: "AWS CodeBuild",
        constant: "CODEBUILD",
        env: "CODEBUILD_BUILD_ARN",
        pr: {
          env: "CODEBUILD_WEBHOOK_EVENT",
          any: [
            "PULL_REQUEST_CREATED",
            "PULL_REQUEST_UPDATED",
            "PULL_REQUEST_REOPENED"
          ]
        }
      },
      {
        name: "Azure Pipelines",
        constant: "AZURE_PIPELINES",
        env: "TF_BUILD",
        pr: {
          BUILD_REASON: "PullRequest"
        }
      },
      {
        name: "Bamboo",
        constant: "BAMBOO",
        env: "bamboo_planKey"
      },
      {
        name: "Bitbucket Pipelines",
        constant: "BITBUCKET",
        env: "BITBUCKET_COMMIT",
        pr: "BITBUCKET_PR_ID"
      },
      {
        name: "Bitrise",
        constant: "BITRISE",
        env: "BITRISE_IO",
        pr: "BITRISE_PULL_REQUEST"
      },
      {
        name: "Buddy",
        constant: "BUDDY",
        env: "BUDDY_WORKSPACE_ID",
        pr: "BUDDY_EXECUTION_PULL_REQUEST_ID"
      },
      {
        name: "Buildkite",
        constant: "BUILDKITE",
        env: "BUILDKITE",
        pr: {
          env: "BUILDKITE_PULL_REQUEST",
          ne: "false"
        }
      },
      {
        name: "CircleCI",
        constant: "CIRCLE",
        env: "CIRCLECI",
        pr: "CIRCLE_PULL_REQUEST"
      },
      {
        name: "Cirrus CI",
        constant: "CIRRUS",
        env: "CIRRUS_CI",
        pr: "CIRRUS_PR"
      },
      {
        name: "Cloudflare Pages",
        constant: "CLOUDFLARE_PAGES",
        env: "CF_PAGES"
      },
      {
        name: "Cloudflare Workers",
        constant: "CLOUDFLARE_WORKERS",
        env: "WORKERS_CI"
      },
      {
        name: "Codefresh",
        constant: "CODEFRESH",
        env: "CF_BUILD_ID",
        pr: {
          any: [
            "CF_PULL_REQUEST_NUMBER",
            "CF_PULL_REQUEST_ID"
          ]
        }
      },
      {
        name: "Codemagic",
        constant: "CODEMAGIC",
        env: "CM_BUILD_ID",
        pr: "CM_PULL_REQUEST"
      },
      {
        name: "Codeship",
        constant: "CODESHIP",
        env: {
          CI_NAME: "codeship"
        }
      },
      {
        name: "Drone",
        constant: "DRONE",
        env: "DRONE",
        pr: {
          DRONE_BUILD_EVENT: "pull_request"
        }
      },
      {
        name: "dsari",
        constant: "DSARI",
        env: "DSARI"
      },
      {
        name: "Earthly",
        constant: "EARTHLY",
        env: "EARTHLY_CI"
      },
      {
        name: "Expo Application Services",
        constant: "EAS",
        env: "EAS_BUILD"
      },
      {
        name: "Gerrit",
        constant: "GERRIT",
        env: "GERRIT_PROJECT"
      },
      {
        name: "Gitea Actions",
        constant: "GITEA_ACTIONS",
        env: "GITEA_ACTIONS"
      },
      {
        name: "GitHub Actions",
        constant: "GITHUB_ACTIONS",
        env: "GITHUB_ACTIONS",
        pr: {
          GITHUB_EVENT_NAME: "pull_request"
        }
      },
      {
        name: "GitLab CI",
        constant: "GITLAB",
        env: "GITLAB_CI",
        pr: "CI_MERGE_REQUEST_ID"
      },
      {
        name: "GoCD",
        constant: "GOCD",
        env: "GO_PIPELINE_LABEL"
      },
      {
        name: "Google Cloud Build",
        constant: "GOOGLE_CLOUD_BUILD",
        env: "BUILDER_OUTPUT"
      },
      {
        name: "Harness CI",
        constant: "HARNESS",
        env: "HARNESS_BUILD_ID"
      },
      {
        name: "Heroku",
        constant: "HEROKU",
        env: {
          env: "NODE",
          includes: "/app/.heroku/node/bin/node"
        }
      },
      {
        name: "Hudson",
        constant: "HUDSON",
        env: "HUDSON_URL"
      },
      {
        name: "Jenkins",
        constant: "JENKINS",
        env: [
          "JENKINS_URL",
          "BUILD_ID"
        ],
        pr: {
          any: [
            "ghprbPullId",
            "CHANGE_ID"
          ]
        }
      },
      {
        name: "LayerCI",
        constant: "LAYERCI",
        env: "LAYERCI",
        pr: "LAYERCI_PULL_REQUEST"
      },
      {
        name: "Magnum CI",
        constant: "MAGNUM",
        env: "MAGNUM"
      },
      {
        name: "Netlify CI",
        constant: "NETLIFY",
        env: "NETLIFY",
        pr: {
          env: "PULL_REQUEST",
          ne: "false"
        }
      },
      {
        name: "Nevercode",
        constant: "NEVERCODE",
        env: "NEVERCODE",
        pr: {
          env: "NEVERCODE_PULL_REQUEST",
          ne: "false"
        }
      },
      {
        name: "Prow",
        constant: "PROW",
        env: "PROW_JOB_ID"
      },
      {
        name: "ReleaseHub",
        constant: "RELEASEHUB",
        env: "RELEASE_BUILD_ID"
      },
      {
        name: "Render",
        constant: "RENDER",
        env: "RENDER",
        pr: {
          IS_PULL_REQUEST: "true"
        }
      },
      {
        name: "Sail CI",
        constant: "SAIL",
        env: "SAILCI",
        pr: "SAIL_PULL_REQUEST_NUMBER"
      },
      {
        name: "Screwdriver",
        constant: "SCREWDRIVER",
        env: "SCREWDRIVER",
        pr: {
          env: "SD_PULL_REQUEST",
          ne: "false"
        }
      },
      {
        name: "Semaphore",
        constant: "SEMAPHORE",
        env: "SEMAPHORE",
        pr: "PULL_REQUEST_NUMBER"
      },
      {
        name: "Sourcehut",
        constant: "SOURCEHUT",
        env: {
          CI_NAME: "sourcehut"
        }
      },
      {
        name: "Strider CD",
        constant: "STRIDER",
        env: "STRIDER"
      },
      {
        name: "TaskCluster",
        constant: "TASKCLUSTER",
        env: [
          "TASK_ID",
          "RUN_ID"
        ]
      },
      {
        name: "TeamCity",
        constant: "TEAMCITY",
        env: "TEAMCITY_VERSION"
      },
      {
        name: "Travis CI",
        constant: "TRAVIS",
        env: "TRAVIS",
        pr: {
          env: "TRAVIS_PULL_REQUEST",
          ne: "false"
        }
      },
      {
        name: "Vela",
        constant: "VELA",
        env: "VELA",
        pr: {
          VELA_PULL_REQUEST: "1"
        }
      },
      {
        name: "Vercel",
        constant: "VERCEL",
        env: {
          any: [
            "NOW_BUILDER",
            "VERCEL"
          ]
        },
        pr: "VERCEL_GIT_PULL_REQUEST_ID"
      },
      {
        name: "Visual Studio App Center",
        constant: "APPCENTER",
        env: "APPCENTER_BUILD_ID"
      },
      {
        name: "Woodpecker",
        constant: "WOODPECKER",
        env: {
          CI: "woodpecker"
        },
        pr: {
          CI_BUILD_EVENT: "pull_request"
        }
      },
      {
        name: "Xcode Cloud",
        constant: "XCODE_CLOUD",
        env: "CI_XCODE_PROJECT",
        pr: "CI_PULL_REQUEST_NUMBER"
      },
      {
        name: "Xcode Server",
        constant: "XCODE_SERVER",
        env: "XCS"
      }
    ];
  }
});
var require_ci_info = __commonJS2({
  "../../node_modules/.pnpm/ci-info@4.4.0/node_modules/ci-info/index.js"(exports2) {
    var vendors = require_vendors();
    var env3 = process.env;
    Object.defineProperty(exports2, "_vendors", {
      value: vendors.map(function(v) {
        return v.constant;
      })
    });
    exports2.name = null;
    exports2.isPR = null;
    exports2.id = null;
    if (env3.CI !== "false") {
      vendors.forEach(function(vendor) {
        const envs = Array.isArray(vendor.env) ? vendor.env : [vendor.env];
        const isCI2 = envs.every(function(obj) {
          return checkEnv(obj);
        });
        exports2[vendor.constant] = isCI2;
        if (!isCI2) {
          return;
        }
        exports2.name = vendor.name;
        exports2.isPR = checkPR(vendor);
        exports2.id = vendor.constant;
      });
    }
    exports2.isCI = !!(env3.CI !== "false" && // Bypass all checks if CI env is explicitly set to 'false'
    (env3.BUILD_ID || // Jenkins, Cloudbees
    env3.BUILD_NUMBER || // Jenkins, TeamCity
    env3.CI || // Travis CI, CircleCI, Cirrus CI, Gitlab CI, Appveyor, CodeShip, dsari, Cloudflare Pages/Workers
    env3.CI_APP_ID || // Appflow
    env3.CI_BUILD_ID || // Appflow
    env3.CI_BUILD_NUMBER || // Appflow
    env3.CI_NAME || // Codeship and others
    env3.CONTINUOUS_INTEGRATION || // Travis CI, Cirrus CI
    env3.RUN_ID || // TaskCluster, dsari
    exports2.name || false));
    function checkEnv(obj) {
      if (typeof obj === "string") return !!env3[obj];
      if ("env" in obj) {
        return env3[obj.env] && env3[obj.env].includes(obj.includes);
      }
      if ("any" in obj) {
        return obj.any.some(function(k) {
          return !!env3[k];
        });
      }
      return Object.keys(obj).every(function(k) {
        return env3[k] === obj[k];
      });
    }
    __name(checkEnv, "checkEnv");
    function checkPR(vendor) {
      switch (typeof vendor.pr) {
        case "string":
          return !!env3[vendor.pr];
        case "object":
          if ("env" in vendor.pr) {
            if ("any" in vendor.pr) {
              return vendor.pr.any.some(function(key) {
                return env3[vendor.pr.env] === key;
              });
            } else {
              return vendor.pr.env in env3 && env3[vendor.pr.env] !== vendor.pr.ne;
            }
          } else if ("any" in vendor.pr) {
            return vendor.pr.any.some(function(key) {
              return !!env3[key];
            });
          } else {
            return checkEnv(vendor.pr);
          }
        default:
          return null;
      }
    }
    __name(checkPR, "checkPR");
  }
});
var require_command_exists = __commonJS2({
  "../../node_modules/.pnpm/command-exists@1.2.9/node_modules/command-exists/lib/command-exists.js"(exports2, module2) {
    var exec2 = __require("child_process").exec;
    var execSync = __require("child_process").execSync;
    var fs310 = __require("fs");
    var path610 = __require("path");
    var access = fs310.access;
    var accessSync2 = fs310.accessSync;
    var constants22 = fs310.constants || fs310;
    var isUsingWindows = process.platform == "win32";
    var fileNotExists = /* @__PURE__ */ __name(function(commandName, callback) {
      access(
        commandName,
        constants22.F_OK,
        function(err) {
          callback(!err);
        }
      );
    }, "fileNotExists");
    var fileNotExistsSync = /* @__PURE__ */ __name(function(commandName) {
      try {
        accessSync2(commandName, constants22.F_OK);
        return false;
      } catch (e2) {
        return true;
      }
    }, "fileNotExistsSync");
    var localExecutable = /* @__PURE__ */ __name(function(commandName, callback) {
      access(
        commandName,
        constants22.F_OK | constants22.X_OK,
        function(err) {
          callback(null, !err);
        }
      );
    }, "localExecutable");
    var localExecutableSync = /* @__PURE__ */ __name(function(commandName) {
      try {
        accessSync2(commandName, constants22.F_OK | constants22.X_OK);
        return true;
      } catch (e2) {
        return false;
      }
    }, "localExecutableSync");
    var commandExistsUnix = /* @__PURE__ */ __name(function(commandName, cleanedCommandName, callback) {
      fileNotExists(commandName, function(isFile) {
        if (!isFile) {
          exec2(
            "command -v " + cleanedCommandName + " 2>/dev/null && { echo >&1 " + cleanedCommandName + "; exit 0; }",
            function(error512, stdout2, stderr2) {
              callback(null, !!stdout2);
            }
          );
          return;
        }
        localExecutable(commandName, callback);
      });
    }, "commandExistsUnix");
    var commandExistsWindows = /* @__PURE__ */ __name(function(commandName, cleanedCommandName, callback) {
      if (!/^(?!(?:.*\s|.*\.|\W+)$)(?:[a-zA-Z]:)?(?:(?:[^<>:"\|\?\*\n])+(?:\/\/|\/|\\\\|\\)?)+$/m.test(commandName)) {
        callback(null, false);
        return;
      }
      exec2(
        "where " + cleanedCommandName,
        function(error512) {
          if (error512 !== null) {
            callback(null, false);
          } else {
            callback(null, true);
          }
        }
      );
    }, "commandExistsWindows");
    var commandExistsUnixSync = /* @__PURE__ */ __name(function(commandName, cleanedCommandName) {
      if (fileNotExistsSync(commandName)) {
        try {
          var stdout2 = execSync(
            "command -v " + cleanedCommandName + " 2>/dev/null && { echo >&1 " + cleanedCommandName + "; exit 0; }"
          );
          return !!stdout2;
        } catch (error512) {
          return false;
        }
      }
      return localExecutableSync(commandName);
    }, "commandExistsUnixSync");
    var commandExistsWindowsSync = /* @__PURE__ */ __name(function(commandName, cleanedCommandName, callback) {
      if (!/^(?!(?:.*\s|.*\.|\W+)$)(?:[a-zA-Z]:)?(?:(?:[^<>:"\|\?\*\n])+(?:\/\/|\/|\\\\|\\)?)+$/m.test(commandName)) {
        return false;
      }
      try {
        var stdout2 = execSync("where " + cleanedCommandName, { stdio: [] });
        return !!stdout2;
      } catch (error512) {
        return false;
      }
    }, "commandExistsWindowsSync");
    var cleanInput = /* @__PURE__ */ __name(function(s) {
      if (/[^A-Za-z0-9_\/:=-]/.test(s)) {
        s = "'" + s.replace(/'/g, "'\\''") + "'";
        s = s.replace(/^(?:'')+/g, "").replace(/\\'''/g, "\\'");
      }
      return s;
    }, "cleanInput");
    if (isUsingWindows) {
      cleanInput = /* @__PURE__ */ __name(function(s) {
        var isPathName = /[\\]/.test(s);
        if (isPathName) {
          var dirname32 = '"' + path610.dirname(s) + '"';
          var basename22 = '"' + path610.basename(s) + '"';
          return dirname32 + ":" + basename22;
        }
        return '"' + s + '"';
      }, "cleanInput");
    }
    module2.exports = /* @__PURE__ */ __name(function commandExists(commandName, callback) {
      var cleanedCommandName = cleanInput(commandName);
      if (!callback && typeof Promise !== "undefined") {
        return new Promise(function(resolve22, reject) {
          commandExists(commandName, function(error512, output) {
            if (output) {
              resolve22(commandName);
            } else {
              reject(error512);
            }
          });
        });
      }
      if (isUsingWindows) {
        commandExistsWindows(commandName, cleanedCommandName, callback);
      } else {
        commandExistsUnix(commandName, cleanedCommandName, callback);
      }
    }, "commandExists");
    module2.exports.sync = function(commandName) {
      var cleanedCommandName = cleanInput(commandName);
      if (isUsingWindows) {
        return commandExistsWindowsSync(commandName, cleanedCommandName);
      } else {
        return commandExistsUnixSync(commandName, cleanedCommandName);
      }
    };
  }
});
var require_command_exists2 = __commonJS2({
  "../../node_modules/.pnpm/command-exists@1.2.9/node_modules/command-exists/index.js"(exports2, module2) {
    module2.exports = require_command_exists();
  }
});
var require_ini = __commonJS2({
  "../../node_modules/.pnpm/ini@1.3.8/node_modules/ini/ini.js"(exports2) {
    exports2.parse = exports2.decode = decode32;
    exports2.stringify = exports2.encode = encode32;
    exports2.safe = safe;
    exports2.unsafe = unsafe;
    var eol = typeof process !== "undefined" && process.platform === "win32" ? "\r\n" : "\n";
    function encode32(obj, opt) {
      var children = [];
      var out = "";
      if (typeof opt === "string") {
        opt = {
          section: opt,
          whitespace: false
        };
      } else {
        opt = opt || {};
        opt.whitespace = opt.whitespace === true;
      }
      var separator = opt.whitespace ? " = " : "=";
      Object.keys(obj).forEach(function(k, _, __) {
        var val = obj[k];
        if (val && Array.isArray(val)) {
          val.forEach(function(item) {
            out += safe(k + "[]") + separator + safe(item) + "\n";
          });
        } else if (val && typeof val === "object")
          children.push(k);
        else
          out += safe(k) + separator + safe(val) + eol;
      });
      if (opt.section && out.length)
        out = "[" + safe(opt.section) + "]" + eol + out;
      children.forEach(function(k, _, __) {
        var nk = dotSplit(k).join("\\.");
        var section = (opt.section ? opt.section + "." : "") + nk;
        var child = encode32(obj[k], {
          section,
          whitespace: opt.whitespace
        });
        if (out.length && child.length)
          out += eol;
        out += child;
      });
      return out;
    }
    __name(encode32, "encode");
    function dotSplit(str) {
      return str.replace(/\1/g, "LITERAL\\1LITERAL").replace(/\\\./g, "").split(/\./).map(function(part) {
        return part.replace(/\1/g, "\\.").replace(/\2LITERAL\\1LITERAL\2/g, "");
      });
    }
    __name(dotSplit, "dotSplit");
    function decode32(str) {
      var out = {};
      var p2 = out;
      var section = null;
      var re = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i;
      var lines = str.split(/[\r\n]+/g);
      lines.forEach(function(line, _, __) {
        if (!line || line.match(/^\s*[;#]/))
          return;
        var match = line.match(re);
        if (!match)
          return;
        if (match[1] !== void 0) {
          section = unsafe(match[1]);
          if (section === "__proto__") {
            p2 = {};
            return;
          }
          p2 = out[section] = out[section] || {};
          return;
        }
        var key = unsafe(match[2]);
        if (key === "__proto__")
          return;
        var value = match[3] ? unsafe(match[4]) : true;
        switch (value) {
          case "true":
          case "false":
          case "null":
            value = JSON.parse(value);
        }
        if (key.length > 2 && key.slice(-2) === "[]") {
          key = key.substring(0, key.length - 2);
          if (key === "__proto__")
            return;
          if (!p2[key])
            p2[key] = [];
          else if (!Array.isArray(p2[key]))
            p2[key] = [p2[key]];
        }
        if (Array.isArray(p2[key]))
          p2[key].push(value);
        else
          p2[key] = value;
      });
      Object.keys(out).filter(function(k, _, __) {
        if (!out[k] || typeof out[k] !== "object" || Array.isArray(out[k]))
          return false;
        var parts = dotSplit(k);
        var p22 = out;
        var l = parts.pop();
        var nl = l.replace(/\\\./g, ".");
        parts.forEach(function(part, _2, __2) {
          if (part === "__proto__")
            return;
          if (!p22[part] || typeof p22[part] !== "object")
            p22[part] = {};
          p22 = p22[part];
        });
        if (p22 === out && nl === l)
          return false;
        p22[nl] = out[k];
        return true;
      }).forEach(function(del, _, __) {
        delete out[del];
      });
      return out;
    }
    __name(decode32, "decode");
    function isQuoted(val) {
      return val.charAt(0) === '"' && val.slice(-1) === '"' || val.charAt(0) === "'" && val.slice(-1) === "'";
    }
    __name(isQuoted, "isQuoted");
    function safe(val) {
      return typeof val !== "string" || val.match(/[=\r\n]/) || val.match(/^\[/) || val.length > 1 && isQuoted(val) || val !== val.trim() ? JSON.stringify(val) : val.replace(/;/g, "\\;").replace(/#/g, "\\#");
    }
    __name(safe, "safe");
    function unsafe(val, doUnesc) {
      val = (val || "").trim();
      if (isQuoted(val)) {
        if (val.charAt(0) === "'")
          val = val.substr(1, val.length - 2);
        try {
          val = JSON.parse(val);
        } catch (_) {
        }
      } else {
        var esc22 = false;
        var unesc = "";
        for (var i = 0, l = val.length; i < l; i++) {
          var c2 = val.charAt(i);
          if (esc22) {
            if ("\\;#".indexOf(c2) !== -1)
              unesc += c2;
            else
              unesc += "\\" + c2;
            esc22 = false;
          } else if (";#".indexOf(c2) !== -1)
            break;
          else if (c2 === "\\")
            esc22 = true;
          else
            unesc += c2;
        }
        if (esc22)
          unesc += "\\";
        return unesc.trim();
      }
      return val;
    }
    __name(unsafe, "unsafe");
  }
});
var require_strip_json_comments = __commonJS2({
  "../../node_modules/.pnpm/strip-json-comments@2.0.1/node_modules/strip-json-comments/index.js"(exports2, module2) {
    var singleComment = 1;
    var multiComment = 2;
    function stripWithoutWhitespace() {
      return "";
    }
    __name(stripWithoutWhitespace, "stripWithoutWhitespace");
    function stripWithWhitespace(str, start, end) {
      return str.slice(start, end).replace(/\S/g, " ");
    }
    __name(stripWithWhitespace, "stripWithWhitespace");
    module2.exports = function(str, opts) {
      opts = opts || {};
      var currentChar;
      var nextChar;
      var insideString = false;
      var insideComment = false;
      var offset = 0;
      var ret = "";
      var strip = opts.whitespace === false ? stripWithoutWhitespace : stripWithWhitespace;
      for (var i = 0; i < str.length; i++) {
        currentChar = str[i];
        nextChar = str[i + 1];
        if (!insideComment && currentChar === '"') {
          var escaped = str[i - 1] === "\\" && str[i - 2] !== "\\";
          if (!escaped) {
            insideString = !insideString;
          }
        }
        if (insideString) {
          continue;
        }
        if (!insideComment && currentChar + nextChar === "//") {
          ret += str.slice(offset, i);
          offset = i;
          insideComment = singleComment;
          i++;
        } else if (insideComment === singleComment && currentChar + nextChar === "\r\n") {
          i++;
          insideComment = false;
          ret += strip(str, offset, i);
          offset = i;
          continue;
        } else if (insideComment === singleComment && currentChar === "\n") {
          insideComment = false;
          ret += strip(str, offset, i);
          offset = i;
        } else if (!insideComment && currentChar + nextChar === "/*") {
          ret += str.slice(offset, i);
          offset = i;
          insideComment = multiComment;
          i++;
          continue;
        } else if (insideComment === multiComment && currentChar + nextChar === "*/") {
          i++;
          insideComment = false;
          ret += strip(str, offset, i + 1);
          offset = i + 1;
          continue;
        }
      }
      return ret + (insideComment ? strip(str.substr(offset)) : str.substr(offset));
    };
  }
});
var require_utils = __commonJS2({
  "../../node_modules/.pnpm/rc@1.2.8/node_modules/rc/lib/utils.js"(exports2) {
    var fs310 = __require("fs");
    var ini = require_ini();
    var path610 = __require("path");
    var stripJsonComments = require_strip_json_comments();
    var parse33 = exports2.parse = function(content) {
      if (/^\s*{/.test(content))
        return JSON.parse(stripJsonComments(content));
      return ini.parse(content);
    };
    var file22 = exports2.file = function() {
      var args = [].slice.call(arguments).filter(function(arg) {
        return arg != null;
      });
      for (var i in args)
        if ("string" !== typeof args[i])
          return;
      var file32 = path610.join.apply(null, args);
      try {
        return fs310.readFileSync(file32, "utf-8");
      } catch (err) {
        return;
      }
    };
    exports2.json = function() {
      var content = file22.apply(null, arguments);
      return content ? parse33(content) : null;
    };
    exports2.env = function(prefix, env22) {
      env22 = env22 || process.env;
      var obj = {};
      var l = prefix.length;
      for (var k in env22) {
        if (k.toLowerCase().indexOf(prefix.toLowerCase()) === 0) {
          var keypath = k.substring(l).split("__");
          var _emptyStringIndex;
          while ((_emptyStringIndex = keypath.indexOf("")) > -1) {
            keypath.splice(_emptyStringIndex, 1);
          }
          var cursor = obj;
          keypath.forEach(/* @__PURE__ */ __name(function _buildSubObj(_subkey, i) {
            if (!_subkey || typeof cursor !== "object")
              return;
            if (i === keypath.length - 1)
              cursor[_subkey] = env22[k];
            if (cursor[_subkey] === void 0)
              cursor[_subkey] = {};
            cursor = cursor[_subkey];
          }, "_buildSubObj"));
        }
      }
      return obj;
    };
    exports2.find = function() {
      var rel = path610.join.apply(null, [].slice.call(arguments));
      function find2(start, rel2) {
        var file32 = path610.join(start, rel2);
        try {
          fs310.statSync(file32);
          return file32;
        } catch (err) {
          if (path610.dirname(start) !== start)
            return find2(path610.dirname(start), rel2);
        }
      }
      __name(find2, "find");
      return find2(process.cwd(), rel);
    };
  }
});
var require_deep_extend = __commonJS2({
  "../../node_modules/.pnpm/deep-extend@0.6.0/node_modules/deep-extend/lib/deep-extend.js"(exports2, module2) {
    function isSpecificValue(val) {
      return val instanceof Buffer || val instanceof Date || val instanceof RegExp ? true : false;
    }
    __name(isSpecificValue, "isSpecificValue");
    function cloneSpecificValue(val) {
      if (val instanceof Buffer) {
        var x = Buffer.alloc ? Buffer.alloc(val.length) : new Buffer(val.length);
        val.copy(x);
        return x;
      } else if (val instanceof Date) {
        return new Date(val.getTime());
      } else if (val instanceof RegExp) {
        return new RegExp(val);
      } else {
        throw new Error("Unexpected situation");
      }
    }
    __name(cloneSpecificValue, "cloneSpecificValue");
    function deepCloneArray(arr) {
      var clone22 = [];
      arr.forEach(function(item, index) {
        if (typeof item === "object" && item !== null) {
          if (Array.isArray(item)) {
            clone22[index] = deepCloneArray(item);
          } else if (isSpecificValue(item)) {
            clone22[index] = cloneSpecificValue(item);
          } else {
            clone22[index] = deepExtend({}, item);
          }
        } else {
          clone22[index] = item;
        }
      });
      return clone22;
    }
    __name(deepCloneArray, "deepCloneArray");
    function safeGetProperty(object22, property) {
      return property === "__proto__" ? void 0 : object22[property];
    }
    __name(safeGetProperty, "safeGetProperty");
    var deepExtend = module2.exports = function() {
      if (arguments.length < 1 || typeof arguments[0] !== "object") {
        return false;
      }
      if (arguments.length < 2) {
        return arguments[0];
      }
      var target = arguments[0];
      var args = Array.prototype.slice.call(arguments, 1);
      var val, src;
      args.forEach(function(obj) {
        if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
          return;
        }
        Object.keys(obj).forEach(function(key) {
          src = safeGetProperty(target, key);
          val = safeGetProperty(obj, key);
          if (val === target) {
            return;
          } else if (typeof val !== "object" || val === null) {
            target[key] = val;
            return;
          } else if (Array.isArray(val)) {
            target[key] = deepCloneArray(val);
            return;
          } else if (isSpecificValue(val)) {
            target[key] = cloneSpecificValue(val);
            return;
          } else if (typeof src !== "object" || src === null || Array.isArray(src)) {
            target[key] = deepExtend({}, val);
            return;
          } else {
            target[key] = deepExtend(src, val);
            return;
          }
        });
      });
      return target;
    };
  }
});
var require_minimist = __commonJS2({
  "../../node_modules/.pnpm/minimist@1.2.6/node_modules/minimist/index.js"(exports2, module2) {
    module2.exports = function(args, opts) {
      if (!opts) opts = {};
      var flags = { bools: {}, strings: {}, unknownFn: null };
      if (typeof opts["unknown"] === "function") {
        flags.unknownFn = opts["unknown"];
      }
      if (typeof opts["boolean"] === "boolean" && opts["boolean"]) {
        flags.allBools = true;
      } else {
        [].concat(opts["boolean"]).filter(Boolean).forEach(function(key2) {
          flags.bools[key2] = true;
        });
      }
      var aliases = {};
      Object.keys(opts.alias || {}).forEach(function(key2) {
        aliases[key2] = [].concat(opts.alias[key2]);
        aliases[key2].forEach(function(x) {
          aliases[x] = [key2].concat(aliases[key2].filter(function(y) {
            return x !== y;
          }));
        });
      });
      [].concat(opts.string).filter(Boolean).forEach(function(key2) {
        flags.strings[key2] = true;
        if (aliases[key2]) {
          flags.strings[aliases[key2]] = true;
        }
      });
      var defaults = opts["default"] || {};
      var argv = { _: [] };
      Object.keys(flags.bools).forEach(function(key2) {
        setArg(key2, defaults[key2] === void 0 ? false : defaults[key2]);
      });
      var notFlags = [];
      if (args.indexOf("--") !== -1) {
        notFlags = args.slice(args.indexOf("--") + 1);
        args = args.slice(0, args.indexOf("--"));
      }
      function argDefined(key2, arg2) {
        return flags.allBools && /^--[^=]+$/.test(arg2) || flags.strings[key2] || flags.bools[key2] || aliases[key2];
      }
      __name(argDefined, "argDefined");
      function setArg(key2, val, arg2) {
        if (arg2 && flags.unknownFn && !argDefined(key2, arg2)) {
          if (flags.unknownFn(arg2) === false) return;
        }
        var value2 = !flags.strings[key2] && isNumber(val) ? Number(val) : val;
        setKey(argv, key2.split("."), value2);
        (aliases[key2] || []).forEach(function(x) {
          setKey(argv, x.split("."), value2);
        });
      }
      __name(setArg, "setArg");
      function setKey(obj, keys, value2) {
        var o = obj;
        for (var i2 = 0; i2 < keys.length - 1; i2++) {
          var key2 = keys[i2];
          if (isConstructorOrProto(o, key2)) return;
          if (o[key2] === void 0) o[key2] = {};
          if (o[key2] === Object.prototype || o[key2] === Number.prototype || o[key2] === String.prototype) o[key2] = {};
          if (o[key2] === Array.prototype) o[key2] = [];
          o = o[key2];
        }
        var key2 = keys[keys.length - 1];
        if (isConstructorOrProto(o, key2)) return;
        if (o === Object.prototype || o === Number.prototype || o === String.prototype) o = {};
        if (o === Array.prototype) o = [];
        if (o[key2] === void 0 || flags.bools[key2] || typeof o[key2] === "boolean") {
          o[key2] = value2;
        } else if (Array.isArray(o[key2])) {
          o[key2].push(value2);
        } else {
          o[key2] = [o[key2], value2];
        }
      }
      __name(setKey, "setKey");
      function aliasIsBoolean(key2) {
        return aliases[key2].some(function(x) {
          return flags.bools[x];
        });
      }
      __name(aliasIsBoolean, "aliasIsBoolean");
      for (var i = 0; i < args.length; i++) {
        var arg = args[i];
        if (/^--.+=/.test(arg)) {
          var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
          var key = m[1];
          var value = m[2];
          if (flags.bools[key]) {
            value = value !== "false";
          }
          setArg(key, value, arg);
        } else if (/^--no-.+/.test(arg)) {
          var key = arg.match(/^--no-(.+)/)[1];
          setArg(key, false, arg);
        } else if (/^--.+/.test(arg)) {
          var key = arg.match(/^--(.+)/)[1];
          var next = args[i + 1];
          if (next !== void 0 && !/^-/.test(next) && !flags.bools[key] && !flags.allBools && (aliases[key] ? !aliasIsBoolean(key) : true)) {
            setArg(key, next, arg);
            i++;
          } else if (/^(true|false)$/.test(next)) {
            setArg(key, next === "true", arg);
            i++;
          } else {
            setArg(key, flags.strings[key] ? "" : true, arg);
          }
        } else if (/^-[^-]+/.test(arg)) {
          var letters = arg.slice(1, -1).split("");
          var broken = false;
          for (var j = 0; j < letters.length; j++) {
            var next = arg.slice(j + 2);
            if (next === "-") {
              setArg(letters[j], next, arg);
              continue;
            }
            if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
              setArg(letters[j], next.split("=")[1], arg);
              broken = true;
              break;
            }
            if (/[A-Za-z]/.test(letters[j]) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
              setArg(letters[j], next, arg);
              broken = true;
              break;
            }
            if (letters[j + 1] && letters[j + 1].match(/\W/)) {
              setArg(letters[j], arg.slice(j + 2), arg);
              broken = true;
              break;
            } else {
              setArg(letters[j], flags.strings[letters[j]] ? "" : true, arg);
            }
          }
          var key = arg.slice(-1)[0];
          if (!broken && key !== "-") {
            if (args[i + 1] && !/^(-|--)[^-]/.test(args[i + 1]) && !flags.bools[key] && (aliases[key] ? !aliasIsBoolean(key) : true)) {
              setArg(key, args[i + 1], arg);
              i++;
            } else if (args[i + 1] && /^(true|false)$/.test(args[i + 1])) {
              setArg(key, args[i + 1] === "true", arg);
              i++;
            } else {
              setArg(key, flags.strings[key] ? "" : true, arg);
            }
          }
        } else {
          if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
            argv._.push(
              flags.strings["_"] || !isNumber(arg) ? arg : Number(arg)
            );
          }
          if (opts.stopEarly) {
            argv._.push.apply(argv._, args.slice(i + 1));
            break;
          }
        }
      }
      Object.keys(defaults).forEach(function(key2) {
        if (!hasKey(argv, key2.split("."))) {
          setKey(argv, key2.split("."), defaults[key2]);
          (aliases[key2] || []).forEach(function(x) {
            setKey(argv, x.split("."), defaults[key2]);
          });
        }
      });
      if (opts["--"]) {
        argv["--"] = new Array();
        notFlags.forEach(function(key2) {
          argv["--"].push(key2);
        });
      } else {
        notFlags.forEach(function(key2) {
          argv._.push(key2);
        });
      }
      return argv;
    };
    function hasKey(obj, keys) {
      var o = obj;
      keys.slice(0, -1).forEach(function(key2) {
        o = o[key2] || {};
      });
      var key = keys[keys.length - 1];
      return key in o;
    }
    __name(hasKey, "hasKey");
    function isNumber(x) {
      if (typeof x === "number") return true;
      if (/^0x[0-9a-f]+$/i.test(x)) return true;
      return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
    }
    __name(isNumber, "isNumber");
    function isConstructorOrProto(obj, key) {
      return key === "constructor" && typeof obj[key] === "function" || key === "__proto__";
    }
    __name(isConstructorOrProto, "isConstructorOrProto");
  }
});
var require_rc = __commonJS2({
  "../../node_modules/.pnpm/rc@1.2.8/node_modules/rc/index.js"(exports2, module2) {
    var cc = require_utils();
    var join32 = __require("path").join;
    var deepExtend = require_deep_extend();
    var etc = "/etc";
    var win = process.platform === "win32";
    var home = win ? process.env.USERPROFILE : process.env.HOME;
    module2.exports = function(name, defaults, argv, parse33) {
      if ("string" !== typeof name)
        throw new Error("rc(name): name *must* be string");
      if (!argv)
        argv = require_minimist()(process.argv.slice(2));
      defaults = ("string" === typeof defaults ? cc.json(defaults) : defaults) || {};
      parse33 = parse33 || cc.parse;
      var env3 = cc.env(name + "_");
      var configs = [defaults];
      var configFiles = [];
      function addConfigFile(file22) {
        if (configFiles.indexOf(file22) >= 0) return;
        var fileConfig = cc.file(file22);
        if (fileConfig) {
          configs.push(parse33(fileConfig));
          configFiles.push(file22);
        }
      }
      __name(addConfigFile, "addConfigFile");
      if (!win)
        [
          join32(etc, name, "config"),
          join32(etc, name + "rc")
        ].forEach(addConfigFile);
      if (home)
        [
          join32(home, ".config", name, "config"),
          join32(home, ".config", name),
          join32(home, "." + name, "config"),
          join32(home, "." + name + "rc")
        ].forEach(addConfigFile);
      addConfigFile(cc.find("." + name + "rc"));
      if (env3.config) addConfigFile(env3.config);
      if (argv.config) addConfigFile(argv.config);
      return deepExtend.apply(null, configs.concat([
        env3,
        argv,
        configFiles.length ? { configs: configFiles, config: configFiles[configFiles.length - 1] } : void 0
      ]));
    };
  }
});
var require_registry_url = __commonJS2({
  "../../node_modules/.pnpm/registry-url@3.1.0/node_modules/registry-url/index.js"(exports2, module2) {
    module2.exports = function(scope) {
      var rc = require_rc()("npm", { registry: "https://registry.npmjs.org/" });
      var url210 = rc[scope + ":registry"] || rc.registry;
      return url210.slice(-1) === "/" ? url210 : url210 + "/";
    };
  }
});
var require_safe_buffer = __commonJS2({
  "../../node_modules/.pnpm/safe-buffer@5.2.1/node_modules/safe-buffer/index.js"(exports2, module2) {
    var buffer = __require("buffer");
    var Buffer22 = buffer.Buffer;
    function copyProps(src, dst) {
      for (var key in src) {
        dst[key] = src[key];
      }
    }
    __name(copyProps, "copyProps");
    if (Buffer22.from && Buffer22.alloc && Buffer22.allocUnsafe && Buffer22.allocUnsafeSlow) {
      module2.exports = buffer;
    } else {
      copyProps(buffer, exports2);
      exports2.Buffer = SafeBuffer;
    }
    function SafeBuffer(arg, encodingOrOffset, length) {
      return Buffer22(arg, encodingOrOffset, length);
    }
    __name(SafeBuffer, "SafeBuffer");
    SafeBuffer.prototype = Object.create(Buffer22.prototype);
    copyProps(Buffer22, SafeBuffer);
    SafeBuffer.from = function(arg, encodingOrOffset, length) {
      if (typeof arg === "number") {
        throw new TypeError("Argument must not be a number");
      }
      return Buffer22(arg, encodingOrOffset, length);
    };
    SafeBuffer.alloc = function(size, fill, encoding) {
      if (typeof size !== "number") {
        throw new TypeError("Argument must be a number");
      }
      var buf = Buffer22(size);
      if (fill !== void 0) {
        if (typeof encoding === "string") {
          buf.fill(fill, encoding);
        } else {
          buf.fill(fill);
        }
      } else {
        buf.fill(0);
      }
      return buf;
    };
    SafeBuffer.allocUnsafe = function(size) {
      if (typeof size !== "number") {
        throw new TypeError("Argument must be a number");
      }
      return Buffer22(size);
    };
    SafeBuffer.allocUnsafeSlow = function(size) {
      if (typeof size !== "number") {
        throw new TypeError("Argument must be a number");
      }
      return buffer.SlowBuffer(size);
    };
  }
});
var require_base64 = __commonJS2({
  "../../node_modules/.pnpm/registry-auth-token@3.3.2/node_modules/registry-auth-token/base64.js"(exports2, module2) {
    var safeBuffer = require_safe_buffer().Buffer;
    function decodeBase64(base6432) {
      return safeBuffer.from(base6432, "base64").toString("utf8");
    }
    __name(decodeBase64, "decodeBase64");
    function encodeBase64(string42) {
      return safeBuffer.from(string42, "utf8").toString("base64");
    }
    __name(encodeBase64, "encodeBase64");
    module2.exports = {
      decodeBase64,
      encodeBase64
    };
  }
});
var require_registry_auth_token = __commonJS2({
  "../../node_modules/.pnpm/registry-auth-token@3.3.2/node_modules/registry-auth-token/index.js"(exports2, module2) {
    var url210 = __require("url");
    var base6432 = require_base64();
    var decodeBase64 = base6432.decodeBase64;
    var encodeBase64 = base6432.encodeBase64;
    var tokenKey = ":_authToken";
    var userKey = ":username";
    var passwordKey = ":_password";
    module2.exports = function() {
      var checkUrl;
      var options;
      if (arguments.length >= 2) {
        checkUrl = arguments[0];
        options = arguments[1];
      } else if (typeof arguments[0] === "string") {
        checkUrl = arguments[0];
      } else {
        options = arguments[0];
      }
      options = options || {};
      options.npmrc = options.npmrc || require_rc()("npm", { registry: "https://registry.npmjs.org/" });
      checkUrl = checkUrl || options.npmrc.registry;
      return getRegistryAuthInfo(checkUrl, options) || getLegacyAuthInfo(options.npmrc);
    };
    function getRegistryAuthInfo(checkUrl, options) {
      var parsed = url210.parse(checkUrl, false, true);
      var pathname;
      while (pathname !== "/" && parsed.pathname !== pathname) {
        pathname = parsed.pathname || "/";
        var regUrl = "//" + parsed.host + pathname.replace(/\/$/, "");
        var authInfo = getAuthInfoForUrl(regUrl, options.npmrc);
        if (authInfo) {
          return authInfo;
        }
        if (!options.recursive) {
          return /\/$/.test(checkUrl) ? void 0 : getRegistryAuthInfo(url210.resolve(checkUrl, "."), options);
        }
        parsed.pathname = url210.resolve(normalizePath3(pathname), "..") || "/";
      }
      return void 0;
    }
    __name(getRegistryAuthInfo, "getRegistryAuthInfo");
    function getLegacyAuthInfo(npmrc) {
      if (npmrc._auth) {
        return { token: npmrc._auth, type: "Basic" };
      }
      return void 0;
    }
    __name(getLegacyAuthInfo, "getLegacyAuthInfo");
    function normalizePath3(path610) {
      return path610[path610.length - 1] === "/" ? path610 : path610 + "/";
    }
    __name(normalizePath3, "normalizePath");
    function getAuthInfoForUrl(regUrl, npmrc) {
      var bearerAuth = getBearerToken(npmrc[regUrl + tokenKey] || npmrc[regUrl + "/" + tokenKey]);
      if (bearerAuth) {
        return bearerAuth;
      }
      var username = npmrc[regUrl + userKey] || npmrc[regUrl + "/" + userKey];
      var password = npmrc[regUrl + passwordKey] || npmrc[regUrl + "/" + passwordKey];
      var basicAuth = getTokenForUsernameAndPassword(username, password);
      if (basicAuth) {
        return basicAuth;
      }
      return void 0;
    }
    __name(getAuthInfoForUrl, "getAuthInfoForUrl");
    function getBearerToken(tok) {
      if (!tok) {
        return void 0;
      }
      var token = tok.replace(/^\$\{?([^}]*)\}?$/, function(fullMatch, envVar) {
        return process.env[envVar];
      });
      return { token, type: "Bearer" };
    }
    __name(getBearerToken, "getBearerToken");
    function getTokenForUsernameAndPassword(username, password) {
      if (!username || !password) {
        return void 0;
      }
      var pass = decodeBase64(password.replace(/^\$\{?([^}]*)\}?$/, function(fullMatch, envVar) {
        return process.env[envVar];
      }));
      var token = encodeBase64(username + ":" + pass);
      return {
        token,
        type: "Basic",
        password: pass,
        username
      };
    }
    __name(getTokenForUsernameAndPassword, "getTokenForUsernameAndPassword");
  }
});
var require_update_check = __commonJS2({
  "../../node_modules/.pnpm/update-check@1.5.4/node_modules/update-check/index.js"(exports2, module2) {
    var { URL: URL22 } = __require("url");
    var { join: join32 } = __require("path");
    var fs310 = __require("fs");
    var { promisify: promisify2 } = __require("util");
    var { tmpdir } = __require("os");
    var registryUrl = require_registry_url();
    var writeFile3 = promisify2(fs310.writeFile);
    var mkdir6 = promisify2(fs310.mkdir);
    var readFile2 = promisify2(fs310.readFile);
    var compareVersions4 = /* @__PURE__ */ __name((a, b) => a.localeCompare(b, "en-US", { numeric: true }), "compareVersions");
    var encode32 = /* @__PURE__ */ __name((value) => encodeURIComponent(value).replace(/^%40/, "@"), "encode");
    var getFile = /* @__PURE__ */ __name(async (details, distTag) => {
      const rootDir = tmpdir();
      const subDir = join32(rootDir, "update-check");
      if (!fs310.existsSync(subDir)) {
        await mkdir6(subDir);
      }
      let name = `${details.name}-${distTag}.json`;
      if (details.scope) {
        name = `${details.scope}-${name}`;
      }
      return join32(subDir, name);
    }, "getFile");
    var evaluateCache = /* @__PURE__ */ __name(async (file22, time32, interval) => {
      if (fs310.existsSync(file22)) {
        const content = await readFile2(file22, "utf8");
        const { lastUpdate, latest } = JSON.parse(content);
        const nextCheck = lastUpdate + interval;
        if (nextCheck > time32) {
          return {
            shouldCheck: false,
            latest
          };
        }
      }
      return {
        shouldCheck: true,
        latest: null
      };
    }, "evaluateCache");
    var updateCache = /* @__PURE__ */ __name(async (file22, latest, lastUpdate) => {
      const content = JSON.stringify({
        latest,
        lastUpdate
      });
      await writeFile3(file22, content, "utf8");
    }, "updateCache");
    var loadPackage = /* @__PURE__ */ __name((url210, authInfo) => new Promise((resolve22, reject) => {
      const options = {
        host: url210.hostname,
        path: url210.pathname,
        port: url210.port,
        headers: {
          accept: "application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"
        },
        timeout: 2e3
      };
      if (authInfo) {
        options.headers.authorization = `${authInfo.type} ${authInfo.token}`;
      }
      const { get } = url210.protocol === "https:" ? __require("https") : __require("http");
      get(options, (response) => {
        const { statusCode } = response;
        if (statusCode !== 200) {
          const error512 = new Error(`Request failed with code ${statusCode}`);
          error512.code = statusCode;
          reject(error512);
          response.resume();
          return;
        }
        let rawData = "";
        response.setEncoding("utf8");
        response.on("data", (chunk) => {
          rawData += chunk;
        });
        response.on("end", () => {
          try {
            const parsedData = JSON.parse(rawData);
            resolve22(parsedData);
          } catch (e2) {
            reject(e2);
          }
        });
      }).on("error", reject).on("timeout", reject);
    }), "loadPackage");
    var getMostRecent = /* @__PURE__ */ __name(async ({ full, scope }, distTag) => {
      const regURL = registryUrl(scope);
      const url210 = new URL22(full, regURL);
      let spec = null;
      try {
        spec = await loadPackage(url210);
      } catch (err) {
        if (err.code && String(err.code).startsWith(4)) {
          const registryAuthToken = require_registry_auth_token();
          const authInfo = registryAuthToken(regURL, { recursive: true });
          spec = await loadPackage(url210, authInfo);
        } else {
          throw err;
        }
      }
      const version22 = spec["dist-tags"][distTag];
      if (!version22) {
        throw new Error(`Distribution tag ${distTag} is not available`);
      }
      return version22;
    }, "getMostRecent");
    var defaultConfig = {
      interval: 36e5,
      distTag: "latest"
    };
    var getDetails = /* @__PURE__ */ __name((name) => {
      const spec = {
        full: encode32(name)
      };
      if (name.includes("/")) {
        const parts = name.split("/");
        spec.scope = parts[0];
        spec.name = parts[1];
      } else {
        spec.scope = null;
        spec.name = name;
      }
      return spec;
    }, "getDetails");
    module2.exports = async (pkg, config22) => {
      if (typeof pkg !== "object") {
        throw new Error("The first parameter should be your package.json file content");
      }
      const details = getDetails(pkg.name);
      const time32 = Date.now();
      const { distTag, interval } = Object.assign({}, defaultConfig, config22);
      const file22 = await getFile(details, distTag);
      let latest = null;
      let shouldCheck = true;
      ({ shouldCheck, latest } = await evaluateCache(file22, time32, interval));
      if (shouldCheck) {
        latest = await getMostRecent(details, distTag);
        await updateCache(file22, latest, time32);
      }
      const comparision = compareVersions4(pkg.version, latest);
      if (comparision === -1) {
        return {
          latest,
          fromCache: !shouldCheck
        };
      }
      return null;
    };
  }
});
var ARTIFACTS_EVENT_TYPES = [
  "cf.artifacts.repo.created",
  "cf.artifacts.repo.deleted",
  "cf.artifacts.repo.forked",
  "cf.artifacts.repo.imported",
  "cf.artifacts.repo.pushed",
  "cf.artifacts.repo.cloned",
  "cf.artifacts.repo.fetched",
  "cf.artifacts.repo.token.created",
  "cf.artifacts.repo.token.revoked"
];
var defaultWranglerConfig = {
  /* COMPUTED_FIELDS */
  configPath: void 0,
  userConfigPath: void 0,
  topLevelName: void 0,
  definedEnvironments: void 0,
  targetEnvironment: void 0,
  /*====================================================*/
  /*      Fields supported by both Workers & Pages      */
  /*====================================================*/
  /* TOP-LEVEL ONLY FIELDS */
  pages_build_output_dir: void 0,
  send_metrics: void 0,
  dependencies_instrumentation: void 0,
  dev: {
    ip: process.platform === "win32" ? "127.0.0.1" : "localhost",
    port: void 0,
    // the default of 8787 is set at runtime
    inspector_port: void 0,
    // the default of 9229 is set at runtime
    inspector_ip: void 0,
    // the default of 127.0.0.1 is set at runtime
    local_protocol: "http",
    upstream_protocol: "http",
    host: void 0,
    // Note this one is also workers only
    enable_containers: true,
    container_engine: void 0,
    generate_types: false
  },
  /** INHERITABLE ENVIRONMENT FIELDS **/
  name: void 0,
  compatibility_date: void 0,
  compatibility_flags: [],
  limits: void 0,
  placement: void 0,
  /** NON-INHERITABLE ENVIRONMENT FIELDS **/
  vars: {},
  durable_objects: { bindings: [] },
  kv_namespaces: [],
  queues: {
    producers: [],
    consumers: []
    // WORKERS SUPPORT ONLY!!
  },
  r2_buckets: [],
  d1_databases: [],
  vectorize: [],
  ai_search_namespaces: [],
  ai_search: [],
  websearch: void 0,
  agent_memory: [],
  hyperdrive: [],
  workflows: [],
  secrets_store_secrets: [],
  artifacts: [],
  services: [],
  analytics_engine_datasets: [],
  ai: void 0,
  images: void 0,
  stream: void 0,
  media: void 0,
  version_metadata: void 0,
  unsafe_hello_world: [],
  flagship: [],
  ratelimits: [],
  worker_loaders: [],
  /*====================================================*/
  /*           Fields supported by Workers only         */
  /*====================================================*/
  /* TOP-LEVEL ONLY FIELDS */
  site: void 0,
  wasm_modules: void 0,
  text_blobs: void 0,
  data_blobs: void 0,
  keep_vars: void 0,
  alias: void 0,
  addresses: void 0,
  /** INHERITABLE ENVIRONMENT FIELDS **/
  account_id: void 0,
  main: void 0,
  find_additional_modules: void 0,
  preserve_file_names: void 0,
  base_dir: void 0,
  workers_dev: void 0,
  preview_urls: void 0,
  route: void 0,
  routes: void 0,
  tsconfig: void 0,
  jsx_factory: "React.createElement",
  jsx_fragment: "React.Fragment",
  migrations: [],
  exports: {},
  triggers: {
    crons: void 0
  },
  rules: [],
  build: { command: void 0, watch_dir: "./src", cwd: void 0 },
  no_bundle: void 0,
  minify: void 0,
  keep_names: void 0,
  dispatch_namespaces: [],
  first_party_worker: void 0,
  logfwdr: { bindings: [] },
  logpush: void 0,
  upload_source_maps: void 0,
  assets: void 0,
  observability: { enabled: true },
  access: void 0,
  cache: void 0,
  /** The default here is undefined so that we can delegate to the CLOUDFLARE_COMPLIANCE_REGION environment variable. */
  compliance_region: void 0,
  python_modules: { exclude: ["**/*.pyc"] },
  previews: void 0,
  /** NON-INHERITABLE ENVIRONMENT FIELDS **/
  define: {},
  cloudchamber: {},
  containers: void 0,
  send_email: [],
  browser: void 0,
  unsafe: {},
  mtls_certificates: [],
  tail_consumers: void 0,
  streaming_tail_consumers: void 0,
  pipelines: [],
  vpc_services: [],
  vpc_networks: []
};
var PatchConfigError = class extends Error {
  static {
    __name(this, "PatchConfigError");
  }
};
var external_exports = {};
__export2(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: () => check,
  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: () => file2,
  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: () => parse22,
  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
});
var core_exports2 = {};
__export2(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: () => parse4,
  parseAsync: () => parseAsync,
  prettifyError: () => prettifyError,
  process: () => process22,
  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
});
var _a;
var NEVER = /* @__PURE__ */ Object.freeze({
  status: "aborted"
});
// @__NO_SIDE_EFFECTS__
function $constructor(name, initializer32, params) {
  function init22(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);
    initializer32(inst, def);
    const proto2 = _.prototype;
    const keys = Object.keys(proto2);
    for (let i = 0; i < keys.length; i++) {
      const k = keys[i];
      if (!(k in inst)) {
        inst[k] = proto2[k].bind(inst);
      }
    }
  }
  __name(init22, "init");
  const Parent = params?.Parent ?? Object;
  class Definition extends Parent {
    static {
      __name(this, "Definition");
    }
  }
  Object.defineProperty(Definition, "name", { value: name });
  function _(def) {
    var _a32;
    const inst = params?.Parent ? new Definition() : this;
    init22(inst, def);
    (_a32 = inst._zod).deferred ?? (_a32.deferred = []);
    for (const fn of inst._zod.deferred) {
      fn();
    }
    return inst;
  }
  __name(_, "_");
  Object.defineProperty(_, "init", { value: init22 });
  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");
var util_exports = {};
__export2(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: () => assertNever2,
  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: () => isPlainObject,
  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
});
function assertEqual(val) {
  return val;
}
__name(assertEqual, "assertEqual");
function assertNotEqual(val) {
  return val;
}
__name(assertNotEqual, "assertNotEqual");
function assertIs(_arg) {
}
__name(assertIs, "assertIs");
function assertNever2(_x) {
  throw new Error("Unexpected value in exhaustive check");
}
__name(assertNever2, "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(array22, separator = "|") {
  return array22.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) {
  return {
    get value() {
      {
        const value = getter();
        Object.defineProperty(this, "value", { value });
        return value;
      }
    }
  };
}
__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(object22, key, getter) {
  let value = void 0;
  Object.defineProperty(object22, key, {
    get() {
      if (value === EVALUATING) {
        return void 0;
      }
      if (value === void 0) {
        value = EVALUATING;
        value = getter();
      }
      return value;
    },
    set(v) {
      Object.defineProperty(object22, 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, path610) {
  if (!path610)
    return obj;
  return path610.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 str = "";
  for (let i = 0; i < length; i++) {
    str += chars[Math.floor(Math.random() * chars.length)];
  }
  return str;
}
__name(randomString, "randomString");
function esc(str) {
  return JSON.stringify(str);
}
__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 isPlainObject(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(isPlainObject, "isPlainObject");
function shallowClone(o) {
  if (isPlainObject(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 t2 = typeof data;
  switch (t2) {
    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: ${t2}`);
  }
}, "getParsedType");
var propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]);
var primitiveTypes = /* @__PURE__ */ new Set([
  "string",
  "number",
  "bigint",
  "boolean",
  "symbol",
  "undefined"
]);
function escapeRegex(str) {
  return str.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 (!isPlainObject(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 (!isPlainObject(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(Class22, 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] = Class22 ? new Class22({
            type: "optional",
            innerType: oldShape[key]
          }) : oldShape[key];
        }
      } else {
        for (const key in oldShape) {
          shape[key] = Class22 ? new Class22({
            type: "optional",
            innerType: oldShape[key]
          }) : oldShape[key];
        }
      }
      assignProp(this, "shape", shape);
      return shape;
    },
    checks: []
  });
  return clone(schema, def);
}
__name(partial, "partial");
function required(Class22, 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 Class22({
            type: "nonoptional",
            innerType: oldShape[key]
          });
        }
      } else {
        for (const key in oldShape) {
          shape[key] = new Class22({
            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(path610, issues) {
  return issues.map((iss) => {
    var _a32;
    (_a32 = iss).path ?? (_a32.path = []);
    iss.path.unshift(path610);
    return iss;
  });
}
__name(prefixIssues, "prefixIssues");
function unwrapMessage(message) {
  return typeof message === "string" ? message : message?.message;
}
__name(unwrapMessage, "unwrapMessage");
function finalizeIssue(iss, ctx, config22) {
  const message = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config22.customError?.(iss)) ?? unwrapMessage(config22.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 t2 = typeof data;
  switch (t2) {
    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 t2;
}
__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(base6432) {
  const binaryString = atob(base6432);
  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(base64url32) {
  const base6432 = base64url32.replace(/-/g, "+").replace(/_/g, "/");
  const padding = "=".repeat((4 - base6432.length % 4) % 4);
  return base64ToUint8Array(base6432 + padding);
}
__name(base64urlToUint8Array, "base64urlToUint8Array");
function uint8ArrayToBase64url(bytes) {
  return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
}
__name(uint8ArrayToBase64url, "uint8ArrayToBase64url");
function hexToUint8Array(hex32) {
  const cleanHex = hex32.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) {
  }
};
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 = /* @__PURE__ */ $constructor("$ZodError", initializer);
var $ZodRealError = /* @__PURE__ */ $constructor("$ZodError", initializer, { Parent: Error });
function flattenError(error512, mapper = (issue22) => issue22.message) {
  const fieldErrors = {};
  const formErrors = [];
  for (const sub of error512.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(error512, mapper = (issue22) => issue22.message) {
  const fieldErrors = { _errors: [] };
  const processError = /* @__PURE__ */ __name((error522, path610 = []) => {
    for (const issue22 of error522.issues) {
      if (issue22.code === "invalid_union" && issue22.errors.length) {
        issue22.errors.map((issues) => processError({ issues }, [...path610, ...issue22.path]));
      } else if (issue22.code === "invalid_key") {
        processError({ issues: issue22.issues }, [...path610, ...issue22.path]);
      } else if (issue22.code === "invalid_element") {
        processError({ issues: issue22.issues }, [...path610, ...issue22.path]);
      } else {
        const fullpath = [...path610, ...issue22.path];
        if (fullpath.length === 0) {
          fieldErrors._errors.push(mapper(issue22));
        } 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(issue22));
            }
            curr = curr[el];
            i++;
          }
        }
      }
    }
  }, "processError");
  processError(error512);
  return fieldErrors;
}
__name(formatError, "formatError");
function treeifyError(error512, mapper = (issue22) => issue22.message) {
  const result = { errors: [] };
  const processError = /* @__PURE__ */ __name((error522, path610 = []) => {
    var _a32, _b;
    for (const issue22 of error522.issues) {
      if (issue22.code === "invalid_union" && issue22.errors.length) {
        issue22.errors.map((issues) => processError({ issues }, [...path610, ...issue22.path]));
      } else if (issue22.code === "invalid_key") {
        processError({ issues: issue22.issues }, [...path610, ...issue22.path]);
      } else if (issue22.code === "invalid_element") {
        processError({ issues: issue22.issues }, [...path610, ...issue22.path]);
      } else {
        const fullpath = [...path610, ...issue22.path];
        if (fullpath.length === 0) {
          result.errors.push(mapper(issue22));
          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 = {});
            (_a32 = curr.properties)[el] ?? (_a32[el] = { errors: [] });
            curr = curr.properties[el];
          } else {
            curr.items ?? (curr.items = []);
            (_b = curr.items)[el] ?? (_b[el] = { errors: [] });
            curr = curr.items[el];
          }
          if (terminal) {
            curr.errors.push(mapper(issue22));
          }
          i++;
        }
      }
    }
  }, "processError");
  processError(error512);
  return result;
}
__name(treeifyError, "treeifyError");
function toDotPath(_path) {
  const segs = [];
  const path610 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
  for (const seg of path610) {
    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(error512) {
  const lines = [];
  const issues = [...error512.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);
  for (const issue22 of issues) {
    lines.push(`\u2716 ${issue22.message}`);
    if (issue22.path?.length)
      lines.push(`  \u2192 at ${toDotPath(issue22.path)}`);
  }
  return lines.join("\n");
}
__name(prettifyError, "prettifyError");
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 e2 = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
    captureStackTrace(e2, _params?.callee);
    throw e2;
  }
  return result.value;
}, "_parse");
var parse4 = /* @__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 e2 = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
    captureStackTrace(e2, params?.callee);
    throw e2;
  }
  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);
var regexes_exports = {};
__export2(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
});
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((version22) => {
  if (!version22)
    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}-${version22}[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 regex3 = 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 regex3;
}
__name(timeSource, "timeSource");
function time(args) {
  return new RegExp(`^${timeSource(args)}$`);
}
__name(time, "time");
function datetime(args) {
  const time32 = 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 = `${time32}(?:${opts.join("|")})`;
  return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
}
__name(datetime, "datetime");
var string = /* @__PURE__ */ __name((params) => {
  const regex3 = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
  return new RegExp(`^${regex3}$`);
}, "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);
var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
  var _a32;
  inst._zod ?? (inst._zod = {});
  inst._zod.def = def;
  (_a32 = inst._zod).onattach ?? (_a32.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 _a32;
    (_a32 = inst2._zod.bag).multipleOf ?? (_a32.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 _a32;
  $ZodCheck.init(inst, def);
  (_a32 = inst._zod.def).when ?? (_a32.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 _a32;
  $ZodCheck.init(inst, def);
  (_a32 = inst._zod.def).when ?? (_a32.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 _a32;
  $ZodCheck.init(inst, def);
  (_a32 = inst._zod.def).when ?? (_a32.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 _a32;
  $ZodCheck.init(inst, def);
  (_a32 = inst._zod.def).when ?? (_a32.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 _a32;
  $ZodCheck.init(inst, def);
  (_a32 = inst._zod.def).when ?? (_a32.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 _a32;
  $ZodCheck.init(inst, def);
  (_a32 = inst._zod.def).when ?? (_a32.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 _a32, _b;
  $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)
    (_a32 = inst._zod).check ?? (_a32.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
    (_b = inst._zod).check ?? (_b.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);
  };
});
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"));
  }
};
var version = {
  major: 4,
  minor: 4,
  patch: 3
};
var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
  var _a32;
  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) {
    (_a32 = inst._zod).deferred ?? (_a32.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 r2 = safeParse(inst, value);
        return r2.success ? { value: r2.data } : { issues: r2.error?.issues };
      } catch (_) {
        return safeParseAsync(inst, value).then((r2) => r2.success ? { value: r2.data } : { issues: r2.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 url210 = new URL(trimmed);
      if (def.hostname) {
        def.hostname.lastIndex = 0;
        if (!def.hostname.test(url210.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(url210.protocol.endsWith(":") ? url210.protocol.slice(0, -1) : url210.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 = url210.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 base6432 = data.replace(/[-_]/g, (c2) => c2 === "-" ? "+" : "/");
  const padded = base6432.padEnd(Math.ceil(base6432.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 t2 = _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 (t2 === "never") {
      unrecognized.push(key);
      continue;
    }
    const r2 = _catchall.run({ value: input[key], issues: [] }, ctx);
    if (r2 instanceof Promise) {
      proms.push(r2.then((r3) => handlePropertyResult(r3, payload, key, input, isOptionalIn, isOptionalOut)));
    } else {
      handlePropertyResult(r2, 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 isObject22 = isObject;
  const catchall = def.catchall;
  let value;
  inst._zod.parse = (payload, ctx) => {
    value ?? (value = _normalized.value);
    const input = payload.value;
    if (!isObject22(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 r2 = el._zod.run({ value: input[key], issues: [] }, ctx);
      if (r2 instanceof Promise) {
        proms.push(r2.then((r3) => handlePropertyResult(r3, payload, key, input, isOptionalIn, isOptionalOut)));
      } else {
        handlePropertyResult(r2, 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 isObject22 = isObject;
  const jit = !globalConfig.jitless;
  const allowsEval22 = allowsEval;
  const fastEnabled = jit && allowsEval22.value;
  const catchall = def.catchall;
  let value;
  inst._zod.parse = (payload, ctx) => {
    value ?? (value = _normalized.value);
    const input = payload.value;
    if (!isObject22(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((r2) => !aborted(r2));
  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((p2) => cleanRegex(p2.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((r2) => r2.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 map22 = /* @__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 (map22.has(v)) {
          throw new Error(`Duplicate discriminator value "${String(v)}"`);
        }
        map22.set(v, o);
      }
    }
    return map22;
  });
  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 left = def.left._zod.run({ value: input, issues: [] }, ctx);
    const right = def.right._zod.run({ value: input, issues: [] }, ctx);
    const async = left instanceof Promise || right instanceof Promise;
    if (async) {
      return Promise.all([left, right]).then(([left2, right2]) => {
        return handleIntersectionResults(payload, left2, right2);
      });
    }
    return handleIntersectionResults(payload, left, right);
  };
});
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 (isPlainObject(a) && isPlainObject(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, left, right) {
  const unrecKeys = /* @__PURE__ */ new Map();
  let unrecIssue;
  for (const iss of left.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 right.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(left.value, right.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 r2 = items[i]._zod.run({ value: input[i], issues: [] }, ctx);
      if (r2 instanceof Promise) {
        proms.push(r2.then((rr) => {
          itemResults[i] = rr;
        }));
      } else {
        itemResults[i] = r2;
      }
    }
    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((r2) => handleTupleResult(r2, 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 r2 = itemResults[i];
    const isPresent = i < input.length;
    if (r2.issues.length) {
      if (!isPresent && i >= optoutStart) {
        final.value.length = i;
        break;
      }
      final.issues.push(...prefixIssues(i, r2.issues));
    }
    final.value[i] = r2.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 (!isPlainObject(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((r2) => handleOptionalResult(r2, 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 right = def.out._zod.run(payload, ctx);
      if (right instanceof Promise) {
        return right.then((right2) => handlePipeResult(right2, def.in, ctx));
      }
      return handlePipeResult(right, def.in, ctx);
    }
    const left = def.in._zod.run(payload, ctx);
    if (left instanceof Promise) {
      return left.then((left2) => handlePipeResult(left2, def.out, ctx));
    }
    return handlePipeResult(left, def.out, ctx);
  };
});
function handlePipeResult(left, next, ctx) {
  if (left.issues.length) {
    left.aborted = true;
    return left;
  }
  return next._zod.run({ value: left.value, issues: left.issues, fallback: left.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 left = def.in._zod.run(payload, ctx);
      if (left instanceof Promise) {
        return left.then((left2) => handleCodecAResult(left2, def, ctx));
      }
      return handleCodecAResult(left, def, ctx);
    } else {
      const right = def.out._zod.run(payload, ctx);
      if (right instanceof Promise) {
        return right.then((right2) => handleCodecAResult(right2, def, ctx));
      }
      return handleCodecAResult(right, 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(left, value, nextSchema, ctx) {
  if (left.issues.length) {
    left.aborted = true;
    return left;
  }
  return nextSchema._zod.run({ value, issues: left.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 ? parse4(inst._def.input, args) : args;
      const result = Reflect.apply(func, this, parsedArgs);
      if (inst._def.output) {
        return parse4(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 r2 = def.fn(input);
    if (r2 instanceof Promise) {
      return r2.then((r3) => handleRefineResult(r3, payload, input, inst));
    }
    handleRefineResult(r2, 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");
var locales_exports = {};
__export2(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
});
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.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 ${issue22.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 (issue22.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(issue22.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(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.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 ${issue22.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue22.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 ${issue22.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue22.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue22.minimum.toString()} ${sizing.unit}`;
        }
        return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue22.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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 "${issue22.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] ?? issue22.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 ${issue22.divisor}`;
      case "unrecognized_keys":
        return `\u0645\u0639\u0631\u0641${issue22.keys.length > 1 ? "\u0627\u062A" : ""} \u063A\u0631\u064A\u0628${issue22.keys.length > 1 ? "\u0629" : ""}: ${joinValues(issue22.keys, "\u060C ")}`;
      case "invalid_key":
        return `\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue22.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 ${issue22.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");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n instanceof ${issue22.expected}, daxil olan ${received}`;
        }
        return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${expected}, daxil olan ${received}`;
      }
      case "invalid_value":
        if (issue22.values.length === 1)
          return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${stringifyPrimitive(issue22.values[0])}`;
        return `Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${joinValues(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue22.origin ?? "d\u0259y\u0259r"} ${adj}${issue22.maximum.toString()} ${sizing.unit ?? "element"}`;
        return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue22.origin ?? "d\u0259y\u0259r"} ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue22.origin} ${adj}${issue22.minimum.toString()} ${sizing.unit}`;
        return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue22.origin} ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format}`;
      }
      case "not_multiple_of":
        return `Yanl\u0131\u015F \u0259d\u0259d: ${issue22.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;
      case "unrecognized_keys":
        return `Tan\u0131nmayan a\xE7ar${issue22.keys.length > 1 ? "lar" : ""}: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `${issue22.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;
      case "invalid_union":
        return "Yanl\u0131\u015F d\u0259y\u0259r";
      case "invalid_element":
        return `${issue22.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");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.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 ${issue22.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 (issue22.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(issue22.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(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          const maxValue = Number(issue22.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 ${issue22.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue22.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 ${issue22.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          const minValue = Number(issue22.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 ${issue22.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue22.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 ${issue22.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.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 ${issue22.divisor}`;
      case "unrecognized_keys":
        return `\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${issue22.keys.length > 1 ? "\u043A\u043B\u044E\u0447\u044B" : "\u043A\u043B\u044E\u0447"}: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${issue22.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 ${issue22.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");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${issue22.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 (issue22.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(issue22.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(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue22.origin ?? "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue22.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 ${issue22.origin ?? "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue22.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue22.minimum.toString()} ${sizing.unit}`;
        }
        return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue22.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.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 ${issue22.divisor}`;
      case "unrecognized_keys":
        return `\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${issue22.keys.length > 1 ? "\u0438" : ""} \u043A\u043B\u044E\u0447${issue22.keys.length > 1 ? "\u043E\u0432\u0435" : ""}: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${issue22.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 ${issue22.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");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `Tipus inv\xE0lid: s'esperava instanceof ${issue22.expected}, s'ha rebut ${received}`;
        }
        return `Tipus inv\xE0lid: s'esperava ${expected}, s'ha rebut ${received}`;
      }
      case "invalid_value":
        if (issue22.values.length === 1)
          return `Valor inv\xE0lid: s'esperava ${stringifyPrimitive(issue22.values[0])}`;
        return `Opci\xF3 inv\xE0lida: s'esperava una de ${joinValues(issue22.values, " o ")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "com a m\xE0xim" : "menys de";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `Massa gran: s'esperava que ${issue22.origin ?? "el valor"} contingu\xE9s ${adj} ${issue22.maximum.toString()} ${sizing.unit ?? "elements"}`;
        return `Massa gran: s'esperava que ${issue22.origin ?? "el valor"} fos ${adj} ${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? "com a m\xEDnim" : "m\xE9s de";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `Massa petit: s'esperava que ${issue22.origin} contingu\xE9s ${adj} ${issue22.minimum.toString()} ${sizing.unit}`;
        }
        return `Massa petit: s'esperava que ${issue22.origin} fos ${adj} ${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format}`;
      }
      case "not_multiple_of":
        return `N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${issue22.divisor}`;
      case "unrecognized_keys":
        return `Clau${issue22.keys.length > 1 ? "s" : ""} no reconeguda${issue22.keys.length > 1 ? "s" : ""}: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `Clau inv\xE0lida a ${issue22.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 ${issue22.origin}`;
      default:
        return `Entrada inv\xE0lida`;
    }
  };
}, "error");
function ca_default() {
  return {
    localeError: error5()
  };
}
__name(ca_default, "default");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no instanceof ${issue22.expected}, obdr\u017Eeno ${received}`;
        }
        return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${expected}, obdr\u017Eeno ${received}`;
      }
      case "invalid_value":
        if (issue22.values.length === 1)
          return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${stringifyPrimitive(issue22.values[0])}`;
        return `Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${joinValues(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue22.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue22.maximum.toString()} ${sizing.unit ?? "prvk\u016F"}`;
        }
        return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue22.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue22.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue22.minimum.toString()} ${sizing.unit ?? "prvk\u016F"}`;
        }
        return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue22.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format}`;
      }
      case "not_multiple_of":
        return `Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${issue22.divisor}`;
      case "unrecognized_keys":
        return `Nezn\xE1m\xE9 kl\xED\u010De: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `Neplatn\xFD kl\xED\u010D v ${issue22.origin}`;
      case "invalid_union":
        return "Neplatn\xFD vstup";
      case "invalid_element":
        return `Neplatn\xE1 hodnota v ${issue22.origin}`;
      default:
        return `Neplatn\xFD vstup`;
    }
  };
}, "error");
function cs_default() {
  return {
    localeError: error6()
  };
}
__name(cs_default, "default");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `Ugyldigt input: forventede instanceof ${issue22.expected}, fik ${received}`;
        }
        return `Ugyldigt input: forventede ${expected}, fik ${received}`;
      }
      case "invalid_value":
        if (issue22.values.length === 1)
          return `Ugyldig v\xE6rdi: forventede ${stringifyPrimitive(issue22.values[0])}`;
        return `Ugyldigt valg: forventede en af f\xF8lgende ${joinValues(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        const origin = TypeDictionary[issue22.origin] ?? issue22.origin;
        if (sizing)
          return `For stor: forventede ${origin ?? "value"} ${sizing.verb} ${adj} ${issue22.maximum.toString()} ${sizing.unit ?? "elementer"}`;
        return `For stor: forventede ${origin ?? "value"} havde ${adj} ${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        const origin = TypeDictionary[issue22.origin] ?? issue22.origin;
        if (sizing) {
          return `For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue22.minimum.toString()} ${sizing.unit}`;
        }
        return `For lille: forventede ${origin} havde ${adj} ${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format}`;
      }
      case "not_multiple_of":
        return `Ugyldigt tal: skal v\xE6re deleligt med ${issue22.divisor}`;
      case "unrecognized_keys":
        return `${issue22.keys.length > 1 ? "Ukendte n\xF8gler" : "Ukendt n\xF8gle"}: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `Ugyldig n\xF8gle i ${issue22.origin}`;
      case "invalid_union":
        return "Ugyldigt input: matcher ingen af de tilladte typer";
      case "invalid_element":
        return `Ugyldig v\xE6rdi i ${issue22.origin}`;
      default:
        return `Ugyldigt input`;
    }
  };
}, "error");
function da_default() {
  return {
    localeError: error7()
  };
}
__name(da_default, "default");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `Ung\xFCltige Eingabe: erwartet instanceof ${issue22.expected}, erhalten ${received}`;
        }
        return `Ung\xFCltige Eingabe: erwartet ${expected}, erhalten ${received}`;
      }
      case "invalid_value":
        if (issue22.values.length === 1)
          return `Ung\xFCltige Eingabe: erwartet ${stringifyPrimitive(issue22.values[0])}`;
        return `Ung\xFCltige Option: erwartet eine von ${joinValues(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `Zu gro\xDF: erwartet, dass ${issue22.origin ?? "Wert"} ${adj}${issue22.maximum.toString()} ${sizing.unit ?? "Elemente"} hat`;
        return `Zu gro\xDF: erwartet, dass ${issue22.origin ?? "Wert"} ${adj}${issue22.maximum.toString()} ist`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `Zu klein: erwartet, dass ${issue22.origin} ${adj}${issue22.minimum.toString()} ${sizing.unit} hat`;
        }
        return `Zu klein: erwartet, dass ${issue22.origin} ${adj}${issue22.minimum.toString()} ist`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format}`;
      }
      case "not_multiple_of":
        return `Ung\xFCltige Zahl: muss ein Vielfaches von ${issue22.divisor} sein`;
      case "unrecognized_keys":
        return `${issue22.keys.length > 1 ? "Unbekannte Schl\xFCssel" : "Unbekannter Schl\xFCssel"}: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `Ung\xFCltiger Schl\xFCssel in ${issue22.origin}`;
      case "invalid_union":
        return "Ung\xFCltige Eingabe";
      case "invalid_element":
        return `Ung\xFCltiger Wert in ${issue22.origin}`;
      default:
        return `Ung\xFCltige Eingabe`;
    }
  };
}, "error");
function de_default() {
  return {
    localeError: error8()
  };
}
__name(de_default, "default");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (typeof issue22.expected === "string" && /^[A-Z]/.test(issue22.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 ${issue22.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 (issue22.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(issue22.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(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue22.origin ?? "\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${adj}${issue22.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 ${issue22.origin ?? "\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue22.origin} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${adj}${issue22.minimum.toString()} ${sizing.unit}`;
        }
        return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue22.origin} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.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 ${issue22.divisor}`;
      case "unrecognized_keys":
        return `\u0386\u03B3\u03BD\u03C9\u03C3\u03C4${issue22.keys.length > 1 ? "\u03B1" : "\u03BF"} \u03BA\u03BB\u03B5\u03B9\u03B4${issue22.keys.length > 1 ? "\u03B9\u03AC" : "\u03AF"}: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF \u03BA\u03BB\u03B5\u03B9\u03B4\u03AF \u03C3\u03C4\u03BF ${issue22.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 ${issue22.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");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        return `Invalid input: expected ${expected}, received ${received}`;
      }
      case "invalid_value":
        if (issue22.values.length === 1)
          return `Invalid input: expected ${stringifyPrimitive(issue22.values[0])}`;
        return `Invalid option: expected one of ${joinValues(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `Too big: expected ${issue22.origin ?? "value"} to have ${adj}${issue22.maximum.toString()} ${sizing.unit ?? "elements"}`;
        return `Too big: expected ${issue22.origin ?? "value"} to be ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `Too small: expected ${issue22.origin} to have ${adj}${issue22.minimum.toString()} ${sizing.unit}`;
        }
        return `Too small: expected ${issue22.origin} to be ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format}`;
      }
      case "not_multiple_of":
        return `Invalid number: must be a multiple of ${issue22.divisor}`;
      case "unrecognized_keys":
        return `Unrecognized key${issue22.keys.length > 1 ? "s" : ""}: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `Invalid key in ${issue22.origin}`;
      case "invalid_union":
        if (issue22.options && Array.isArray(issue22.options) && issue22.options.length > 0) {
          const opts = issue22.options.map((o) => `'${o}'`).join(" | ");
          return `Invalid discriminator value. Expected ${opts}`;
        }
        return "Invalid input";
      case "invalid_element":
        return `Invalid value in ${issue22.origin}`;
      default:
        return `Invalid input`;
    }
  };
}, "error");
function en_default() {
  return {
    localeError: error10()
  };
}
__name(en_default, "default");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `Nevalida enigo: atendi\u011Dis instanceof ${issue22.expected}, ricevi\u011Dis ${received}`;
        }
        return `Nevalida enigo: atendi\u011Dis ${expected}, ricevi\u011Dis ${received}`;
      }
      case "invalid_value":
        if (issue22.values.length === 1)
          return `Nevalida enigo: atendi\u011Dis ${stringifyPrimitive(issue22.values[0])}`;
        return `Nevalida opcio: atendi\u011Dis unu el ${joinValues(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `Tro granda: atendi\u011Dis ke ${issue22.origin ?? "valoro"} havu ${adj}${issue22.maximum.toString()} ${sizing.unit ?? "elementojn"}`;
        return `Tro granda: atendi\u011Dis ke ${issue22.origin ?? "valoro"} havu ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `Tro malgranda: atendi\u011Dis ke ${issue22.origin} havu ${adj}${issue22.minimum.toString()} ${sizing.unit}`;
        }
        return `Tro malgranda: atendi\u011Dis ke ${issue22.origin} estu ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format}`;
      }
      case "not_multiple_of":
        return `Nevalida nombro: devas esti oblo de ${issue22.divisor}`;
      case "unrecognized_keys":
        return `Nekonata${issue22.keys.length > 1 ? "j" : ""} \u015Dlosilo${issue22.keys.length > 1 ? "j" : ""}: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `Nevalida \u015Dlosilo en ${issue22.origin}`;
      case "invalid_union":
        return "Nevalida enigo";
      case "invalid_element":
        return `Nevalida valoro en ${issue22.origin}`;
      default:
        return `Nevalida enigo`;
    }
  };
}, "error");
function eo_default() {
  return {
    localeError: error11()
  };
}
__name(eo_default, "default");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `Entrada inv\xE1lida: se esperaba instanceof ${issue22.expected}, recibido ${received}`;
        }
        return `Entrada inv\xE1lida: se esperaba ${expected}, recibido ${received}`;
      }
      case "invalid_value":
        if (issue22.values.length === 1)
          return `Entrada inv\xE1lida: se esperaba ${stringifyPrimitive(issue22.values[0])}`;
        return `Opci\xF3n inv\xE1lida: se esperaba una de ${joinValues(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        const origin = TypeDictionary[issue22.origin] ?? issue22.origin;
        if (sizing)
          return `Demasiado grande: se esperaba que ${origin ?? "valor"} tuviera ${adj}${issue22.maximum.toString()} ${sizing.unit ?? "elementos"}`;
        return `Demasiado grande: se esperaba que ${origin ?? "valor"} fuera ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        const origin = TypeDictionary[issue22.origin] ?? issue22.origin;
        if (sizing) {
          return `Demasiado peque\xF1o: se esperaba que ${origin} tuviera ${adj}${issue22.minimum.toString()} ${sizing.unit}`;
        }
        return `Demasiado peque\xF1o: se esperaba que ${origin} fuera ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format}`;
      }
      case "not_multiple_of":
        return `N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${issue22.divisor}`;
      case "unrecognized_keys":
        return `Llave${issue22.keys.length > 1 ? "s" : ""} desconocida${issue22.keys.length > 1 ? "s" : ""}: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `Llave inv\xE1lida en ${TypeDictionary[issue22.origin] ?? issue22.origin}`;
      case "invalid_union":
        return "Entrada inv\xE1lida";
      case "invalid_element":
        return `Valor inv\xE1lido en ${TypeDictionary[issue22.origin] ?? issue22.origin}`;
      default:
        return `Entrada inv\xE1lida`;
    }
  };
}, "error");
function es_default() {
  return {
    localeError: error12()
  };
}
__name(es_default, "default");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${issue22.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 (issue22.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(issue22.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(issue22.values, "|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue22.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue22.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`;
        }
        return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue22.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue22.maximum.toString()} \u0628\u0627\u0634\u062F`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue22.origin} \u0628\u0627\u06CC\u062F ${adj}${issue22.minimum.toString()} ${sizing.unit} \u0628\u0627\u0634\u062F`;
        }
        return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue22.origin} \u0628\u0627\u06CC\u062F ${adj}${issue22.minimum.toString()} \u0628\u0627\u0634\u062F`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.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 ${issue22.divisor} \u0628\u0627\u0634\u062F`;
      case "unrecognized_keys":
        return `\u06A9\u0644\u06CC\u062F${issue22.keys.length > 1 ? "\u0647\u0627\u06CC" : ""} \u0646\u0627\u0634\u0646\u0627\u0633: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${issue22.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 ${issue22.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");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `Virheellinen tyyppi: odotettiin instanceof ${issue22.expected}, oli ${received}`;
        }
        return `Virheellinen tyyppi: odotettiin ${expected}, oli ${received}`;
      }
      case "invalid_value":
        if (issue22.values.length === 1)
          return `Virheellinen sy\xF6te: t\xE4ytyy olla ${stringifyPrimitive(issue22.values[0])}`;
        return `Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${joinValues(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `Liian suuri: ${sizing.subject} t\xE4ytyy olla ${adj}${issue22.maximum.toString()} ${sizing.unit}`.trim();
        }
        return `Liian suuri: arvon t\xE4ytyy olla ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `Liian pieni: ${sizing.subject} t\xE4ytyy olla ${adj}${issue22.minimum.toString()} ${sizing.unit}`.trim();
        }
        return `Liian pieni: arvon t\xE4ytyy olla ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format}`;
      }
      case "not_multiple_of":
        return `Virheellinen luku: t\xE4ytyy olla luvun ${issue22.divisor} monikerta`;
      case "unrecognized_keys":
        return `${issue22.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${joinValues(issue22.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");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `Entr\xE9e invalide : instanceof ${issue22.expected} attendu, ${received} re\xE7u`;
        }
        return `Entr\xE9e invalide : ${expected} attendu, ${received} re\xE7u`;
      }
      case "invalid_value":
        if (issue22.values.length === 1)
          return `Entr\xE9e invalide : ${stringifyPrimitive(issue22.values[0])} attendu`;
        return `Option invalide : une valeur parmi ${joinValues(issue22.values, "|")} attendue`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `Trop grand : ${TypeDictionary[issue22.origin] ?? "valeur"} doit ${sizing.verb} ${adj}${issue22.maximum.toString()} ${sizing.unit ?? "\xE9l\xE9ment(s)"}`;
        return `Trop grand : ${TypeDictionary[issue22.origin] ?? "valeur"} doit \xEAtre ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `Trop petit : ${TypeDictionary[issue22.origin] ?? "valeur"} doit ${sizing.verb} ${adj}${issue22.minimum.toString()} ${sizing.unit}`;
        return `Trop petit : ${TypeDictionary[issue22.origin] ?? "valeur"} doit \xEAtre ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format} invalide`;
      }
      case "not_multiple_of":
        return `Nombre invalide : doit \xEAtre un multiple de ${issue22.divisor}`;
      case "unrecognized_keys":
        return `Cl\xE9${issue22.keys.length > 1 ? "s" : ""} non reconnue${issue22.keys.length > 1 ? "s" : ""} : ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `Cl\xE9 invalide dans ${issue22.origin}`;
      case "invalid_union":
        return "Entr\xE9e invalide";
      case "invalid_element":
        return `Valeur invalide dans ${issue22.origin}`;
      default:
        return `Entr\xE9e invalide`;
    }
  };
}, "error");
function fr_default() {
  return {
    localeError: error15()
  };
}
__name(fr_default, "default");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `Entr\xE9e invalide : attendu instanceof ${issue22.expected}, re\xE7u ${received}`;
        }
        return `Entr\xE9e invalide : attendu ${expected}, re\xE7u ${received}`;
      }
      case "invalid_value":
        if (issue22.values.length === 1)
          return `Entr\xE9e invalide : attendu ${stringifyPrimitive(issue22.values[0])}`;
        return `Option invalide : attendu l'une des valeurs suivantes ${joinValues(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "\u2264" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `Trop grand : attendu que ${issue22.origin ?? "la valeur"} ait ${adj}${issue22.maximum.toString()} ${sizing.unit}`;
        return `Trop grand : attendu que ${issue22.origin ?? "la valeur"} soit ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? "\u2265" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `Trop petit : attendu que ${issue22.origin} ait ${adj}${issue22.minimum.toString()} ${sizing.unit}`;
        }
        return `Trop petit : attendu que ${issue22.origin} soit ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format} invalide`;
      }
      case "not_multiple_of":
        return `Nombre invalide : doit \xEAtre un multiple de ${issue22.divisor}`;
      case "unrecognized_keys":
        return `Cl\xE9${issue22.keys.length > 1 ? "s" : ""} non reconnue${issue22.keys.length > 1 ? "s" : ""} : ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `Cl\xE9 invalide dans ${issue22.origin}`;
      case "invalid_union":
        return "Entr\xE9e invalide";
      case "invalid_element":
        return `Valeur invalide dans ${issue22.origin}`;
      default:
        return `Entr\xE9e invalide`;
    }
  };
}, "error");
function fr_CA_default() {
  return {
    localeError: error16()
  };
}
__name(fr_CA_default, "default");
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((t2) => t2 ? TypeNames[t2] : void 0, "typeEntry");
  const typeLabel = /* @__PURE__ */ __name((t2) => {
    const e2 = typeEntry(t2);
    if (e2)
      return e2.label;
    return t2 ?? TypeNames.unknown.label;
  }, "typeLabel");
  const withDefinite = /* @__PURE__ */ __name((t2) => `\u05D4${typeLabel(t2)}`, "withDefinite");
  const verbFor = /* @__PURE__ */ __name((t2) => {
    const e2 = typeEntry(t2);
    const gender = e2?.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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expectedKey = issue22.expected;
        const expected = TypeDictionary[expectedKey ?? ""] ?? typeLabel(expectedKey);
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? TypeNames[receivedType]?.label ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${issue22.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 (issue22.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(issue22.values[0])}`;
        }
        const stringified = issue22.values.map((v) => stringifyPrimitive(v));
        if (issue22.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(issue22.origin);
        const subject = withDefinite(issue22.origin ?? "value");
        if (issue22.origin === "string") {
          return `${sizing?.longLabel ?? "\u05D0\u05E8\u05D5\u05DA"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue22.maximum.toString()} ${sizing?.unit ?? ""} ${issue22.inclusive ? "\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA" : "\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8"}`.trim();
        }
        if (issue22.origin === "number") {
          const comparison = issue22.inclusive ? `\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue22.maximum}` : `\u05E7\u05D8\u05DF \u05DE-${issue22.maximum}`;
          return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`;
        }
        if (issue22.origin === "array" || issue22.origin === "set") {
          const verb = issue22.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA";
          const comparison = issue22.inclusive ? `${issue22.maximum} ${sizing?.unit ?? ""} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA` : `\u05E4\u05D7\u05D5\u05EA \u05DE-${issue22.maximum} ${sizing?.unit ?? ""}`;
          return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim();
        }
        const adj = issue22.inclusive ? "<=" : "<";
        const be = verbFor(issue22.origin ?? "value");
        if (sizing?.unit) {
          return `${sizing.longLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue22.maximum.toString()} ${sizing.unit}`;
        }
        return `${sizing?.longLabel ?? "\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const sizing = getSizing(issue22.origin);
        const subject = withDefinite(issue22.origin ?? "value");
        if (issue22.origin === "string") {
          return `${sizing?.shortLabel ?? "\u05E7\u05E6\u05E8"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue22.minimum.toString()} ${sizing?.unit ?? ""} ${issue22.inclusive ? "\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8" : "\u05DC\u05E4\u05D7\u05D5\u05EA"}`.trim();
        }
        if (issue22.origin === "number") {
          const comparison = issue22.inclusive ? `\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue22.minimum}` : `\u05D2\u05D3\u05D5\u05DC \u05DE-${issue22.minimum}`;
          return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`;
        }
        if (issue22.origin === "array" || issue22.origin === "set") {
          const verb = issue22.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA";
          if (issue22.minimum === 1 && issue22.inclusive) {
            const singularPhrase = issue22.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 = issue22.inclusive ? `${issue22.minimum} ${sizing?.unit ?? ""} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8` : `\u05D9\u05D5\u05EA\u05E8 \u05DE-${issue22.minimum} ${sizing?.unit ?? ""}`;
          return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim();
        }
        const adj = issue22.inclusive ? ">=" : ">";
        const be = verbFor(issue22.origin ?? "value");
        if (sizing?.unit) {
          return `${sizing.shortLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue22.minimum.toString()} ${sizing.unit}`;
        }
        return `${sizing?.shortLabel ?? "\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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 ${issue22.divisor}`;
      case "unrecognized_keys":
        return `\u05DE\u05E4\u05EA\u05D7${issue22.keys.length > 1 ? "\u05D5\u05EA" : ""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${issue22.keys.length > 1 ? "\u05D9\u05DD" : "\u05D4"}: ${joinValues(issue22.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(issue22.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");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `Neispravan unos: o\u010Dekuje se instanceof ${issue22.expected}, a primljeno je ${received}`;
        }
        return `Neispravan unos: o\u010Dekuje se ${expected}, a primljeno je ${received}`;
      }
      case "invalid_value":
        if (issue22.values.length === 1)
          return `Neispravna vrijednost: o\u010Dekivano ${stringifyPrimitive(issue22.values[0])}`;
        return `Neispravna opcija: o\u010Dekivano jedno od ${joinValues(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        const origin = TypeDictionary[issue22.origin] ?? issue22.origin;
        if (sizing)
          return `Preveliko: o\u010Dekivano da ${origin ?? "vrijednost"} ima ${adj}${issue22.maximum.toString()} ${sizing.unit ?? "elemenata"}`;
        return `Preveliko: o\u010Dekivano da ${origin ?? "vrijednost"} bude ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        const origin = TypeDictionary[issue22.origin] ?? issue22.origin;
        if (sizing) {
          return `Premalo: o\u010Dekivano da ${origin} ima ${adj}${issue22.minimum.toString()} ${sizing.unit}`;
        }
        return `Premalo: o\u010Dekivano da ${origin} bude ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format}`;
      }
      case "not_multiple_of":
        return `Neispravan broj: mora biti vi\u0161ekratnik od ${issue22.divisor}`;
      case "unrecognized_keys":
        return `Neprepoznat${issue22.keys.length > 1 ? "i klju\u010Devi" : " klju\u010D"}: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `Neispravan klju\u010D u ${TypeDictionary[issue22.origin] ?? issue22.origin}`;
      case "invalid_union":
        return "Neispravan unos";
      case "invalid_element":
        return `Neispravna vrijednost u ${TypeDictionary[issue22.origin] ?? issue22.origin}`;
      default:
        return `Neispravan unos`;
    }
  };
}, "error");
function hr_default() {
  return {
    localeError: error18()
  };
}
__name(hr_default, "default");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k instanceof ${issue22.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 (issue22.values.length === 1)
          return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${stringifyPrimitive(issue22.values[0])}`;
        return `\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${joinValues(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `T\xFAl nagy: ${issue22.origin ?? "\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${adj}${issue22.maximum.toString()} ${sizing.unit ?? "elem"}`;
        return `T\xFAl nagy: a bemeneti \xE9rt\xE9k ${issue22.origin ?? "\xE9rt\xE9k"} t\xFAl nagy: ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue22.origin} m\xE9rete t\xFAl kicsi ${adj}${issue22.minimum.toString()} ${sizing.unit}`;
        }
        return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue22.origin} t\xFAl kicsi ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format}`;
      }
      case "not_multiple_of":
        return `\xC9rv\xE9nytelen sz\xE1m: ${issue22.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;
      case "unrecognized_keys":
        return `Ismeretlen kulcs${issue22.keys.length > 1 ? "s" : ""}: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `\xC9rv\xE9nytelen kulcs ${issue22.origin}`;
      case "invalid_union":
        return "\xC9rv\xE9nytelen bemenet";
      case "invalid_element":
        return `\xC9rv\xE9nytelen \xE9rt\xE9k: ${issue22.origin}`;
      default:
        return `\xC9rv\xE9nytelen bemenet`;
    }
  };
}, "error");
function hu_default() {
  return {
    localeError: error19()
  };
}
__name(hu_default, "default");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.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 ${issue22.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 (issue22.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(issue22.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(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          const maxValue = Number(issue22.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(issue22.origin ?? "\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue22.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(issue22.origin ?? "\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          const minValue = Number(issue22.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(issue22.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue22.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(issue22.origin)} \u056C\u056B\u0576\u056B ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.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 ${issue22.divisor}-\u056B`;
      case "unrecognized_keys":
        return `\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${issue22.keys.length > 1 ? "\u0576\u0565\u0580" : ""}. ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${withDefiniteArticle(issue22.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(issue22.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");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `Input tidak valid: diharapkan instanceof ${issue22.expected}, diterima ${received}`;
        }
        return `Input tidak valid: diharapkan ${expected}, diterima ${received}`;
      }
      case "invalid_value":
        if (issue22.values.length === 1)
          return `Input tidak valid: diharapkan ${stringifyPrimitive(issue22.values[0])}`;
        return `Pilihan tidak valid: diharapkan salah satu dari ${joinValues(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `Terlalu besar: diharapkan ${issue22.origin ?? "value"} memiliki ${adj}${issue22.maximum.toString()} ${sizing.unit ?? "elemen"}`;
        return `Terlalu besar: diharapkan ${issue22.origin ?? "value"} menjadi ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `Terlalu kecil: diharapkan ${issue22.origin} memiliki ${adj}${issue22.minimum.toString()} ${sizing.unit}`;
        }
        return `Terlalu kecil: diharapkan ${issue22.origin} menjadi ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format} tidak valid`;
      }
      case "not_multiple_of":
        return `Angka tidak valid: harus kelipatan dari ${issue22.divisor}`;
      case "unrecognized_keys":
        return `Kunci tidak dikenali ${issue22.keys.length > 1 ? "s" : ""}: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `Kunci tidak valid di ${issue22.origin}`;
      case "invalid_union":
        return "Input tidak valid";
      case "invalid_element":
        return `Nilai tidak valid di ${issue22.origin}`;
      default:
        return `Input tidak valid`;
    }
  };
}, "error");
function id_default() {
  return {
    localeError: error21()
  };
}
__name(id_default, "default");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera instanceof ${issue22.expected}`;
        }
        return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera ${expected}`;
      }
      case "invalid_value":
        if (issue22.values.length === 1)
          return `Rangt gildi: gert r\xE1\xF0 fyrir ${stringifyPrimitive(issue22.values[0])}`;
        return `\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${joinValues(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue22.origin ?? "gildi"} hafi ${adj}${issue22.maximum.toString()} ${sizing.unit ?? "hluti"}`;
        return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue22.origin ?? "gildi"} s\xE9 ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue22.origin} hafi ${adj}${issue22.minimum.toString()} ${sizing.unit}`;
        }
        return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue22.origin} s\xE9 ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format}`;
      }
      case "not_multiple_of":
        return `R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${issue22.divisor}`;
      case "unrecognized_keys":
        return `\xD3\xFEekkt ${issue22.keys.length > 1 ? "ir lyklar" : "ur lykill"}: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `Rangur lykill \xED ${issue22.origin}`;
      case "invalid_union":
        return "Rangt gildi";
      case "invalid_element":
        return `Rangt gildi \xED ${issue22.origin}`;
      default:
        return `Rangt gildi`;
    }
  };
}, "error");
function is_default() {
  return {
    localeError: error22()
  };
}
__name(is_default, "default");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `Input non valido: atteso instanceof ${issue22.expected}, ricevuto ${received}`;
        }
        return `Input non valido: atteso ${expected}, ricevuto ${received}`;
      }
      case "invalid_value":
        if (issue22.values.length === 1)
          return `Input non valido: atteso ${stringifyPrimitive(issue22.values[0])}`;
        return `Opzione non valida: atteso uno tra ${joinValues(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `Troppo grande: ${issue22.origin ?? "valore"} deve avere ${adj}${issue22.maximum.toString()} ${sizing.unit ?? "elementi"}`;
        return `Troppo grande: ${issue22.origin ?? "valore"} deve essere ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `Troppo piccolo: ${issue22.origin} deve avere ${adj}${issue22.minimum.toString()} ${sizing.unit}`;
        }
        return `Troppo piccolo: ${issue22.origin} deve essere ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format}`;
      }
      case "not_multiple_of":
        return `Numero non valido: deve essere un multiplo di ${issue22.divisor}`;
      case "unrecognized_keys":
        return `Chiav${issue22.keys.length > 1 ? "i" : "e"} non riconosciut${issue22.keys.length > 1 ? "e" : "a"}: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `Chiave non valida in ${issue22.origin}`;
      case "invalid_union":
        return "Input non valido";
      case "invalid_element":
        return `Valore non valido in ${issue22.origin}`;
      default:
        return `Input non valido`;
    }
  };
}, "error");
function it_default() {
  return {
    localeError: error23()
  };
}
__name(it_default, "default");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `\u7121\u52B9\u306A\u5165\u529B: instanceof ${issue22.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 (issue22.values.length === 1)
          return `\u7121\u52B9\u306A\u5165\u529B: ${stringifyPrimitive(issue22.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`;
        return `\u7121\u52B9\u306A\u9078\u629E: ${joinValues(issue22.values, "\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
      case "too_big": {
        const adj = issue22.inclusive ? "\u4EE5\u4E0B\u3067\u3042\u308B" : "\u3088\u308A\u5C0F\u3055\u3044";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue22.origin ?? "\u5024"}\u306F${issue22.maximum.toString()}${sizing.unit ?? "\u8981\u7D20"}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
        return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue22.origin ?? "\u5024"}\u306F${issue22.maximum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? "\u4EE5\u4E0A\u3067\u3042\u308B" : "\u3088\u308A\u5927\u304D\u3044";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue22.origin}\u306F${issue22.minimum.toString()}${sizing.unit}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
        return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue22.origin}\u306F${issue22.minimum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format}`;
      }
      case "not_multiple_of":
        return `\u7121\u52B9\u306A\u6570\u5024: ${issue22.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${issue22.keys.length > 1 ? "\u7FA4" : ""}: ${joinValues(issue22.keys, "\u3001")}`;
      case "invalid_key":
        return `${issue22.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;
      case "invalid_union":
        return "\u7121\u52B9\u306A\u5165\u529B";
      case "invalid_element":
        return `${issue22.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");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.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 ${issue22.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 (issue22.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(issue22.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(issue22.values, "|")}-\u10D3\u10D0\u10DC`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.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 ${issue22.origin ?? "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${sizing.verb} ${adj}${issue22.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 ${issue22.origin ?? "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.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 ${issue22.origin} ${sizing.verb} ${adj}${issue22.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 ${issue22.origin} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.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 ${issue22.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${issue22.keys.length > 1 ? "\u10D4\u10D1\u10D8" : "\u10D8"}: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${issue22.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 ${issue22.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");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.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 ${issue22.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 (issue22.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(issue22.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(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue22.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue22.maximum.toString()} ${sizing.unit ?? "\u1792\u17B6\u178F\u17BB"}`;
        return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue22.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue22.origin} ${adj} ${issue22.minimum.toString()} ${sizing.unit}`;
        }
        return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue22.origin} ${adj} ${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.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 ${issue22.divisor}`;
      case "unrecognized_keys":
        return `\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${joinValues(issue22.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 ${issue22.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 ${issue22.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");
function kh_default() {
  return km_default();
}
__name(kh_default, "default");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${issue22.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 (issue22.values.length === 1)
          return `\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${stringifyPrimitive(issue22.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`;
        return `\uC798\uBABB\uB41C \uC635\uC158: ${joinValues(issue22.values, "\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;
      case "too_big": {
        const adj = issue22.inclusive ? "\uC774\uD558" : "\uBBF8\uB9CC";
        const suffix = adj === "\uBBF8\uB9CC" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4";
        const sizing = getSizing(issue22.origin);
        const unit = sizing?.unit ?? "\uC694\uC18C";
        if (sizing)
          return `${issue22.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue22.maximum.toString()}${unit} ${adj}${suffix}`;
        return `${issue22.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue22.maximum.toString()} ${adj}${suffix}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? "\uC774\uC0C1" : "\uCD08\uACFC";
        const suffix = adj === "\uC774\uC0C1" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4";
        const sizing = getSizing(issue22.origin);
        const unit = sizing?.unit ?? "\uC694\uC18C";
        if (sizing) {
          return `${issue22.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue22.minimum.toString()}${unit} ${adj}${suffix}`;
        }
        return `${issue22.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue22.minimum.toString()} ${adj}${suffix}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format}`;
      }
      case "not_multiple_of":
        return `\uC798\uBABB\uB41C \uC22B\uC790: ${issue22.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;
      case "unrecognized_keys":
        return `\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `\uC798\uBABB\uB41C \uD0A4: ${issue22.origin}`;
      case "invalid_union":
        return `\uC798\uBABB\uB41C \uC785\uB825`;
      case "invalid_element":
        return `\uC798\uBABB\uB41C \uAC12: ${issue22.origin}`;
      default:
        return `\uC798\uBABB\uB41C \uC785\uB825`;
    }
  };
}, "error");
function ko_default() {
  return {
    localeError: error27()
  };
}
__name(ko_default, "default");
var capitalizeFirstCharacter = /* @__PURE__ */ __name((text) => {
  return text.charAt(0).toUpperCase() + text.slice(1);
}, "capitalizeFirstCharacter");
function getUnitTypeFromNumber(number42) {
  const abs = Math.abs(number42);
  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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `Gautas tipas ${received}, o tik\u0117tasi - instanceof ${issue22.expected}`;
        }
        return `Gautas tipas ${received}, o tik\u0117tasi - ${expected}`;
      }
      case "invalid_value":
        if (issue22.values.length === 1)
          return `Privalo b\u016Bti ${stringifyPrimitive(issue22.values[0])}`;
        return `Privalo b\u016Bti vienas i\u0161 ${joinValues(issue22.values, "|")} pasirinkim\u0173`;
      case "too_big": {
        const origin = TypeDictionary[issue22.origin] ?? issue22.origin;
        const sizing = getSizing(issue22.origin, getUnitTypeFromNumber(Number(issue22.maximum)), issue22.inclusive ?? false, "smaller");
        if (sizing?.verb)
          return `${capitalizeFirstCharacter(origin ?? issue22.origin ?? "reik\u0161m\u0117")} ${sizing.verb} ${issue22.maximum.toString()} ${sizing.unit ?? "element\u0173"}`;
        const adj = issue22.inclusive ? "ne didesnis kaip" : "ma\u017Eesnis kaip";
        return `${capitalizeFirstCharacter(origin ?? issue22.origin ?? "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue22.maximum.toString()} ${sizing?.unit}`;
      }
      case "too_small": {
        const origin = TypeDictionary[issue22.origin] ?? issue22.origin;
        const sizing = getSizing(issue22.origin, getUnitTypeFromNumber(Number(issue22.minimum)), issue22.inclusive ?? false, "bigger");
        if (sizing?.verb)
          return `${capitalizeFirstCharacter(origin ?? issue22.origin ?? "reik\u0161m\u0117")} ${sizing.verb} ${issue22.minimum.toString()} ${sizing.unit ?? "element\u0173"}`;
        const adj = issue22.inclusive ? "ne ma\u017Eesnis kaip" : "didesnis kaip";
        return `${capitalizeFirstCharacter(origin ?? issue22.origin ?? "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue22.minimum.toString()} ${sizing?.unit}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format}`;
      }
      case "not_multiple_of":
        return `Skai\u010Dius privalo b\u016Bti ${issue22.divisor} kartotinis.`;
      case "unrecognized_keys":
        return `Neatpa\u017Eint${issue22.keys.length > 1 ? "i" : "as"} rakt${issue22.keys.length > 1 ? "ai" : "as"}: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return "Rastas klaidingas raktas";
      case "invalid_union":
        return "Klaidinga \u012Fvestis";
      case "invalid_element": {
        const origin = TypeDictionary[issue22.origin] ?? issue22.origin;
        return `${capitalizeFirstCharacter(origin ?? issue22.origin ?? "reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`;
      }
      default:
        return "Klaidinga \u012Fvestis";
    }
  };
}, "error");
function lt_default() {
  return {
    localeError: error28()
  };
}
__name(lt_default, "default");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${issue22.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 (issue22.values.length === 1)
          return `Invalid input: expected ${stringifyPrimitive(issue22.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(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.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 ${issue22.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue22.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 ${issue22.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue22.origin} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue22.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 ${issue22.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.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 ${issue22.divisor}`;
      case "unrecognized_keys":
        return `${issue22.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(issue22.keys, ", ")}`;
      case "invalid_key":
        return `\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${issue22.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 ${issue22.origin}`;
      default:
        return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441`;
    }
  };
}, "error");
function mk_default() {
  return {
    localeError: error29()
  };
}
__name(mk_default, "default");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `Input tidak sah: dijangka instanceof ${issue22.expected}, diterima ${received}`;
        }
        return `Input tidak sah: dijangka ${expected}, diterima ${received}`;
      }
      case "invalid_value":
        if (issue22.values.length === 1)
          return `Input tidak sah: dijangka ${stringifyPrimitive(issue22.values[0])}`;
        return `Pilihan tidak sah: dijangka salah satu daripada ${joinValues(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `Terlalu besar: dijangka ${issue22.origin ?? "nilai"} ${sizing.verb} ${adj}${issue22.maximum.toString()} ${sizing.unit ?? "elemen"}`;
        return `Terlalu besar: dijangka ${issue22.origin ?? "nilai"} adalah ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `Terlalu kecil: dijangka ${issue22.origin} ${sizing.verb} ${adj}${issue22.minimum.toString()} ${sizing.unit}`;
        }
        return `Terlalu kecil: dijangka ${issue22.origin} adalah ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format} tidak sah`;
      }
      case "not_multiple_of":
        return `Nombor tidak sah: perlu gandaan ${issue22.divisor}`;
      case "unrecognized_keys":
        return `Kunci tidak dikenali: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `Kunci tidak sah dalam ${issue22.origin}`;
      case "invalid_union":
        return "Input tidak sah";
      case "invalid_element":
        return `Nilai tidak sah dalam ${issue22.origin}`;
      default:
        return `Input tidak sah`;
    }
  };
}, "error");
function ms_default() {
  return {
    localeError: error30()
  };
}
__name(ms_default, "default");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `Ongeldige invoer: verwacht instanceof ${issue22.expected}, ontving ${received}`;
        }
        return `Ongeldige invoer: verwacht ${expected}, ontving ${received}`;
      }
      case "invalid_value":
        if (issue22.values.length === 1)
          return `Ongeldige invoer: verwacht ${stringifyPrimitive(issue22.values[0])}`;
        return `Ongeldige optie: verwacht \xE9\xE9n van ${joinValues(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        const longName = issue22.origin === "date" ? "laat" : issue22.origin === "string" ? "lang" : "groot";
        if (sizing)
          return `Te ${longName}: verwacht dat ${issue22.origin ?? "waarde"} ${adj}${issue22.maximum.toString()} ${sizing.unit ?? "elementen"} ${sizing.verb}`;
        return `Te ${longName}: verwacht dat ${issue22.origin ?? "waarde"} ${adj}${issue22.maximum.toString()} is`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        const shortName = issue22.origin === "date" ? "vroeg" : issue22.origin === "string" ? "kort" : "klein";
        if (sizing) {
          return `Te ${shortName}: verwacht dat ${issue22.origin} ${adj}${issue22.minimum.toString()} ${sizing.unit} ${sizing.verb}`;
        }
        return `Te ${shortName}: verwacht dat ${issue22.origin} ${adj}${issue22.minimum.toString()} is`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format}`;
      }
      case "not_multiple_of":
        return `Ongeldig getal: moet een veelvoud van ${issue22.divisor} zijn`;
      case "unrecognized_keys":
        return `Onbekende key${issue22.keys.length > 1 ? "s" : ""}: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `Ongeldige key in ${issue22.origin}`;
      case "invalid_union":
        return "Ongeldige invoer";
      case "invalid_element":
        return `Ongeldige waarde in ${issue22.origin}`;
      default:
        return `Ongeldige invoer`;
    }
  };
}, "error");
function nl_default() {
  return {
    localeError: error31()
  };
}
__name(nl_default, "default");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `Ugyldig input: forventet instanceof ${issue22.expected}, fikk ${received}`;
        }
        return `Ugyldig input: forventet ${expected}, fikk ${received}`;
      }
      case "invalid_value":
        if (issue22.values.length === 1)
          return `Ugyldig verdi: forventet ${stringifyPrimitive(issue22.values[0])}`;
        return `Ugyldig valg: forventet en av ${joinValues(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `For stor(t): forventet ${issue22.origin ?? "value"} til \xE5 ha ${adj}${issue22.maximum.toString()} ${sizing.unit ?? "elementer"}`;
        return `For stor(t): forventet ${issue22.origin ?? "value"} til \xE5 ha ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `For lite(n): forventet ${issue22.origin} til \xE5 ha ${adj}${issue22.minimum.toString()} ${sizing.unit}`;
        }
        return `For lite(n): forventet ${issue22.origin} til \xE5 ha ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format}`;
      }
      case "not_multiple_of":
        return `Ugyldig tall: m\xE5 v\xE6re et multiplum av ${issue22.divisor}`;
      case "unrecognized_keys":
        return `${issue22.keys.length > 1 ? "Ukjente n\xF8kler" : "Ukjent n\xF8kkel"}: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `Ugyldig n\xF8kkel i ${issue22.origin}`;
      case "invalid_union":
        return "Ugyldig input";
      case "invalid_element":
        return `Ugyldig verdi i ${issue22.origin}`;
      default:
        return `Ugyldig input`;
    }
  };
}, "error");
function no_default() {
  return {
    localeError: error32()
  };
}
__name(no_default, "default");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `F\xE2sit giren: umulan instanceof ${issue22.expected}, al\u0131nan ${received}`;
        }
        return `F\xE2sit giren: umulan ${expected}, al\u0131nan ${received}`;
      }
      case "invalid_value":
        if (issue22.values.length === 1)
          return `F\xE2sit giren: umulan ${stringifyPrimitive(issue22.values[0])}`;
        return `F\xE2sit tercih: m\xFBteberler ${joinValues(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `Fazla b\xFCy\xFCk: ${issue22.origin ?? "value"}, ${adj}${issue22.maximum.toString()} ${sizing.unit ?? "elements"} sahip olmal\u0131yd\u0131.`;
        return `Fazla b\xFCy\xFCk: ${issue22.origin ?? "value"}, ${adj}${issue22.maximum.toString()} olmal\u0131yd\u0131.`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `Fazla k\xFC\xE7\xFCk: ${issue22.origin}, ${adj}${issue22.minimum.toString()} ${sizing.unit} sahip olmal\u0131yd\u0131.`;
        }
        return `Fazla k\xFC\xE7\xFCk: ${issue22.origin}, ${adj}${issue22.minimum.toString()} olmal\u0131yd\u0131.`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format}`;
      }
      case "not_multiple_of":
        return `F\xE2sit say\u0131: ${issue22.divisor} kat\u0131 olmal\u0131yd\u0131.`;
      case "unrecognized_keys":
        return `Tan\u0131nmayan anahtar ${issue22.keys.length > 1 ? "s" : ""}: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `${issue22.origin} i\xE7in tan\u0131nmayan anahtar var.`;
      case "invalid_union":
        return "Giren tan\u0131namad\u0131.";
      case "invalid_element":
        return `${issue22.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");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${issue22.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 (issue22.values.length === 1) {
          return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${stringifyPrimitive(issue22.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(issue22.values, "|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue22.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue22.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`;
        }
        return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue22.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue22.maximum.toString()} \u0648\u064A`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue22.origin} \u0628\u0627\u06CC\u062F ${adj}${issue22.minimum.toString()} ${sizing.unit} \u0648\u0644\u0631\u064A`;
        }
        return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue22.origin} \u0628\u0627\u06CC\u062F ${adj}${issue22.minimum.toString()} \u0648\u064A`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`;
      }
      case "not_multiple_of":
        return `\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${issue22.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;
      case "unrecognized_keys":
        return `\u0646\u0627\u0633\u0645 ${issue22.keys.length > 1 ? "\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647" : "\u06A9\u0644\u06CC\u0689"}: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${issue22.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 ${issue22.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");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${issue22.expected}, otrzymano ${received}`;
        }
        return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${expected}, otrzymano ${received}`;
      }
      case "invalid_value":
        if (issue22.values.length === 1)
          return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${stringifyPrimitive(issue22.values[0])}`;
        return `Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${joinValues(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${issue22.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue22.maximum.toString()} ${sizing.unit ?? "element\xF3w"}`;
        }
        return `Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${issue22.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${issue22.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue22.minimum.toString()} ${sizing.unit ?? "element\xF3w"}`;
        }
        return `Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${issue22.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format}`;
      }
      case "not_multiple_of":
        return `Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${issue22.divisor}`;
      case "unrecognized_keys":
        return `Nierozpoznane klucze${issue22.keys.length > 1 ? "s" : ""}: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `Nieprawid\u0142owy klucz w ${issue22.origin}`;
      case "invalid_union":
        return "Nieprawid\u0142owe dane wej\u015Bciowe";
      case "invalid_element":
        return `Nieprawid\u0142owa warto\u015B\u0107 w ${issue22.origin}`;
      default:
        return `Nieprawid\u0142owe dane wej\u015Bciowe`;
    }
  };
}, "error");
function pl_default() {
  return {
    localeError: error35()
  };
}
__name(pl_default, "default");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `Tipo inv\xE1lido: esperado instanceof ${issue22.expected}, recebido ${received}`;
        }
        return `Tipo inv\xE1lido: esperado ${expected}, recebido ${received}`;
      }
      case "invalid_value":
        if (issue22.values.length === 1)
          return `Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue22.values[0])}`;
        return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `Muito grande: esperado que ${issue22.origin ?? "valor"} tivesse ${adj}${issue22.maximum.toString()} ${sizing.unit ?? "elementos"}`;
        return `Muito grande: esperado que ${issue22.origin ?? "valor"} fosse ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `Muito pequeno: esperado que ${issue22.origin} tivesse ${adj}${issue22.minimum.toString()} ${sizing.unit}`;
        }
        return `Muito pequeno: esperado que ${issue22.origin} fosse ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format} inv\xE1lido`;
      }
      case "not_multiple_of":
        return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue22.divisor}`;
      case "unrecognized_keys":
        return `Chave${issue22.keys.length > 1 ? "s" : ""} desconhecida${issue22.keys.length > 1 ? "s" : ""}: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `Chave inv\xE1lida em ${issue22.origin}`;
      case "invalid_union":
        return "Entrada inv\xE1lida";
      case "invalid_element":
        return `Valor inv\xE1lido em ${issue22.origin}`;
      default:
        return `Campo inv\xE1lido`;
    }
  };
}, "error");
function pt_default() {
  return {
    localeError: error36()
  };
}
__name(pt_default, "default");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        return `Intrare invalid\u0103: a\u0219teptat ${expected}, primit ${received}`;
      }
      case "invalid_value":
        if (issue22.values.length === 1)
          return `Intrare invalid\u0103: a\u0219teptat ${stringifyPrimitive(issue22.values[0])}`;
        return `Op\u021Biune invalid\u0103: a\u0219teptat una dintre ${joinValues(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `Prea mare: a\u0219teptat ca ${issue22.origin ?? "valoarea"} ${sizing.verb} ${adj}${issue22.maximum.toString()} ${sizing.unit ?? "elemente"}`;
        return `Prea mare: a\u0219teptat ca ${issue22.origin ?? "valoarea"} s\u0103 fie ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `Prea mic: a\u0219teptat ca ${issue22.origin} ${sizing.verb} ${adj}${issue22.minimum.toString()} ${sizing.unit}`;
        }
        return `Prea mic: a\u0219teptat ca ${issue22.origin} s\u0103 fie ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format}`;
      }
      case "not_multiple_of":
        return `Num\u0103r invalid: trebuie s\u0103 fie multiplu de ${issue22.divisor}`;
      case "unrecognized_keys":
        return `Chei nerecunoscute: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `Cheie invalid\u0103 \xEEn ${issue22.origin}`;
      case "invalid_union":
        return "Intrare invalid\u0103";
      case "invalid_element":
        return `Valoare invalid\u0103 \xEEn ${issue22.origin}`;
      default:
        return `Intrare invalid\u0103`;
    }
  };
}, "error");
function ro_default() {
  return {
    localeError: error37()
  };
}
__name(ro_default, "default");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${issue22.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 (issue22.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(issue22.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(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          const maxValue = Number(issue22.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 ${issue22.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue22.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 ${issue22.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          const minValue = Number(issue22.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 ${issue22.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue22.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 ${issue22.origin} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.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 ${issue22.divisor}`;
      case "unrecognized_keys":
        return `\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${issue22.keys.length > 1 ? "\u044B\u0435" : "\u044B\u0439"} \u043A\u043B\u044E\u0447${issue22.keys.length > 1 ? "\u0438" : ""}: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${issue22.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 ${issue22.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");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `Neveljaven vnos: pri\u010Dakovano instanceof ${issue22.expected}, prejeto ${received}`;
        }
        return `Neveljaven vnos: pri\u010Dakovano ${expected}, prejeto ${received}`;
      }
      case "invalid_value":
        if (issue22.values.length === 1)
          return `Neveljaven vnos: pri\u010Dakovano ${stringifyPrimitive(issue22.values[0])}`;
        return `Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${joinValues(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `Preveliko: pri\u010Dakovano, da bo ${issue22.origin ?? "vrednost"} imelo ${adj}${issue22.maximum.toString()} ${sizing.unit ?? "elementov"}`;
        return `Preveliko: pri\u010Dakovano, da bo ${issue22.origin ?? "vrednost"} ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `Premajhno: pri\u010Dakovano, da bo ${issue22.origin} imelo ${adj}${issue22.minimum.toString()} ${sizing.unit}`;
        }
        return `Premajhno: pri\u010Dakovano, da bo ${issue22.origin} ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format}`;
      }
      case "not_multiple_of":
        return `Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${issue22.divisor}`;
      case "unrecognized_keys":
        return `Neprepoznan${issue22.keys.length > 1 ? "i klju\u010Di" : " klju\u010D"}: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `Neveljaven klju\u010D v ${issue22.origin}`;
      case "invalid_union":
        return "Neveljaven vnos";
      case "invalid_element":
        return `Neveljavna vrednost v ${issue22.origin}`;
      default:
        return "Neveljaven vnos";
    }
  };
}, "error");
function sl_default() {
  return {
    localeError: error39()
  };
}
__name(sl_default, "default");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `Ogiltig inmatning: f\xF6rv\xE4ntat instanceof ${issue22.expected}, fick ${received}`;
        }
        return `Ogiltig inmatning: f\xF6rv\xE4ntat ${expected}, fick ${received}`;
      }
      case "invalid_value":
        if (issue22.values.length === 1)
          return `Ogiltig inmatning: f\xF6rv\xE4ntat ${stringifyPrimitive(issue22.values[0])}`;
        return `Ogiltigt val: f\xF6rv\xE4ntade en av ${joinValues(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `F\xF6r stor(t): f\xF6rv\xE4ntade ${issue22.origin ?? "v\xE4rdet"} att ha ${adj}${issue22.maximum.toString()} ${sizing.unit ?? "element"}`;
        }
        return `F\xF6r stor(t): f\xF6rv\xE4ntat ${issue22.origin ?? "v\xE4rdet"} att ha ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue22.origin ?? "v\xE4rdet"} att ha ${adj}${issue22.minimum.toString()} ${sizing.unit}`;
        }
        return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue22.origin ?? "v\xE4rdet"} att ha ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format}`;
      }
      case "not_multiple_of":
        return `Ogiltigt tal: m\xE5ste vara en multipel av ${issue22.divisor}`;
      case "unrecognized_keys":
        return `${issue22.keys.length > 1 ? "Ok\xE4nda nycklar" : "Ok\xE4nd nyckel"}: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `Ogiltig nyckel i ${issue22.origin ?? "v\xE4rdet"}`;
      case "invalid_union":
        return "Ogiltig input";
      case "invalid_element":
        return `Ogiltigt v\xE4rde i ${issue22.origin ?? "v\xE4rdet"}`;
      default:
        return `Ogiltig input`;
    }
  };
}, "error");
function sv_default() {
  return {
    localeError: error40()
  };
}
__name(sv_default, "default");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.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 ${issue22.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 (issue22.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(issue22.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(issue22.values, "|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.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 ${issue22.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue22.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 ${issue22.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue22.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.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 ${issue22.origin} ${adj}${issue22.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 ${issue22.origin} ${adj}${issue22.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format}`;
      }
      case "not_multiple_of":
        return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${issue22.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${issue22.keys.length > 1 ? "\u0B95\u0BB3\u0BCD" : ""}: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `${issue22.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 `${issue22.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");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.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 ${issue22.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 (issue22.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(issue22.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(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19" : "\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue22.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue22.maximum.toString()} ${sizing.unit ?? "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`;
        return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue22.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? "\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22" : "\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue22.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue22.minimum.toString()} ${sizing.unit}`;
        }
        return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue22.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.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 ${issue22.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(issue22.keys, ", ")}`;
      case "invalid_key":
        return `\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue22.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 ${issue22.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");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `Ge\xE7ersiz de\u011Fer: beklenen instanceof ${issue22.expected}, al\u0131nan ${received}`;
        }
        return `Ge\xE7ersiz de\u011Fer: beklenen ${expected}, al\u0131nan ${received}`;
      }
      case "invalid_value":
        if (issue22.values.length === 1)
          return `Ge\xE7ersiz de\u011Fer: beklenen ${stringifyPrimitive(issue22.values[0])}`;
        return `Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${joinValues(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `\xC7ok b\xFCy\xFCk: beklenen ${issue22.origin ?? "de\u011Fer"} ${adj}${issue22.maximum.toString()} ${sizing.unit ?? "\xF6\u011Fe"}`;
        return `\xC7ok b\xFCy\xFCk: beklenen ${issue22.origin ?? "de\u011Fer"} ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue22.origin} ${adj}${issue22.minimum.toString()} ${sizing.unit}`;
        return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue22.origin} ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format}`;
      }
      case "not_multiple_of":
        return `Ge\xE7ersiz say\u0131: ${issue22.divisor} ile tam b\xF6l\xFCnebilmeli`;
      case "unrecognized_keys":
        return `Tan\u0131nmayan anahtar${issue22.keys.length > 1 ? "lar" : ""}: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `${issue22.origin} i\xE7inde ge\xE7ersiz anahtar`;
      case "invalid_union":
        return "Ge\xE7ersiz de\u011Fer";
      case "invalid_element":
        return `${issue22.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;
      default:
        return `Ge\xE7ersiz de\u011Fer`;
    }
  };
}, "error");
function tr_default() {
  return {
    localeError: error43()
  };
}
__name(tr_default, "default");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.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 ${issue22.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 (issue22.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(issue22.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(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.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 ${issue22.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${sizing.verb} ${adj}${issue22.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 ${issue22.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.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 ${issue22.origin} ${sizing.verb} ${adj}${issue22.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 ${issue22.origin} \u0431\u0443\u0434\u0435 ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.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 ${issue22.divisor}`;
      case "unrecognized_keys":
        return `\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${issue22.keys.length > 1 ? "\u0456" : ""}: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${issue22.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 ${issue22.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");
function ua_default() {
  return uk_default();
}
__name(ua_default, "default");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${issue22.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 (issue22.values.length === 1)
          return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${stringifyPrimitive(issue22.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
        return `\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${joinValues(issue22.values, "|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue22.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${adj}${issue22.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: ${issue22.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${adj}${issue22.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue22.origin} \u06A9\u06D2 ${adj}${issue22.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: ${issue22.origin} \u06A9\u0627 ${adj}${issue22.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format}`;
      }
      case "not_multiple_of":
        return `\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${issue22.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${issue22.keys.length > 1 ? "\u0632" : ""}: ${joinValues(issue22.keys, "\u060C ")}`;
      case "invalid_key":
        return `${issue22.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;
      case "invalid_union":
        return "\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";
      case "invalid_element":
        return `${issue22.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");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `Noto\u2018g\u2018ri kirish: kutilgan instanceof ${issue22.expected}, qabul qilingan ${received}`;
        }
        return `Noto\u2018g\u2018ri kirish: kutilgan ${expected}, qabul qilingan ${received}`;
      }
      case "invalid_value":
        if (issue22.values.length === 1)
          return `Noto\u2018g\u2018ri kirish: kutilgan ${stringifyPrimitive(issue22.values[0])}`;
        return `Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${joinValues(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `Juda katta: kutilgan ${issue22.origin ?? "qiymat"} ${adj}${issue22.maximum.toString()} ${sizing.unit} ${sizing.verb}`;
        return `Juda katta: kutilgan ${issue22.origin ?? "qiymat"} ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `Juda kichik: kutilgan ${issue22.origin} ${adj}${issue22.minimum.toString()} ${sizing.unit} ${sizing.verb}`;
        }
        return `Juda kichik: kutilgan ${issue22.origin} ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format}`;
      }
      case "not_multiple_of":
        return `Noto\u2018g\u2018ri raqam: ${issue22.divisor} ning karralisi bo\u2018lishi kerak`;
      case "unrecognized_keys":
        return `Noma\u2019lum kalit${issue22.keys.length > 1 ? "lar" : ""}: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `${issue22.origin} dagi kalit noto\u2018g\u2018ri`;
      case "invalid_union":
        return "Noto\u2018g\u2018ri kirish";
      case "invalid_element":
        return `${issue22.origin} da noto\u2018g\u2018ri qiymat`;
      default:
        return `Noto\u2018g\u2018ri kirish`;
    }
  };
}, "error");
function uz_default() {
  return {
    localeError: error46()
  };
}
__name(uz_default, "default");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${issue22.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 (issue22.values.length === 1)
          return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${stringifyPrimitive(issue22.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(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue22.origin ?? "gi\xE1 tr\u1ECB"} ${sizing.verb} ${adj}${issue22.maximum.toString()} ${sizing.unit ?? "ph\u1EA7n t\u1EED"}`;
        return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue22.origin ?? "gi\xE1 tr\u1ECB"} ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue22.origin} ${sizing.verb} ${adj}${issue22.minimum.toString()} ${sizing.unit}`;
        }
        return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue22.origin} ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.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 ${issue22.divisor}`;
      case "unrecognized_keys":
        return `Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue22.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 ${issue22.origin}`;
      default:
        return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7`;
    }
  };
}, "error");
function vi_default() {
  return {
    localeError: error47()
  };
}
__name(vi_default, "default");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${issue22.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 (issue22.values.length === 1)
          return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${stringifyPrimitive(issue22.values[0])}`;
        return `\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${joinValues(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue22.origin ?? "\u503C"} ${adj}${issue22.maximum.toString()} ${sizing.unit ?? "\u4E2A\u5143\u7D20"}`;
        return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue22.origin ?? "\u503C"} ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue22.origin} ${adj}${issue22.minimum.toString()} ${sizing.unit}`;
        }
        return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue22.origin} ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format}`;
      }
      case "not_multiple_of":
        return `\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${issue22.divisor} \u7684\u500D\u6570`;
      case "unrecognized_keys":
        return `\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `${issue22.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;
      case "invalid_union":
        return "\u65E0\u6548\u8F93\u5165";
      case "invalid_element":
        return `${issue22.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");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${issue22.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 (issue22.values.length === 1)
          return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${stringifyPrimitive(issue22.values[0])}`;
        return `\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${joinValues(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue22.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue22.maximum.toString()} ${sizing.unit ?? "\u500B\u5143\u7D20"}`;
        return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue22.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue22.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing) {
          return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue22.origin} \u61C9\u70BA ${adj}${issue22.minimum.toString()} ${sizing.unit}`;
        }
        return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue22.origin} \u61C9\u70BA ${adj}${issue22.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.format}`;
      }
      case "not_multiple_of":
        return `\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${issue22.divisor} \u7684\u500D\u6578`;
      case "unrecognized_keys":
        return `\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${issue22.keys.length > 1 ? "\u5011" : ""}\uFF1A${joinValues(issue22.keys, "\u3001")}`;
      case "invalid_key":
        return `${issue22.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;
      case "invalid_union":
        return "\u7121\u6548\u7684\u8F38\u5165\u503C";
      case "invalid_element":
        return `${issue22.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");
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 (issue22) => {
    switch (issue22.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue22.expected] ?? issue22.expected;
        const receivedType = parsedType(issue22.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue22.expected)) {
          return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi instanceof ${issue22.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 (issue22.values.length === 1)
          return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${stringifyPrimitive(issue22.values[0])}`;
        return `\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${joinValues(issue22.values, "|")}`;
      case "too_big": {
        const adj = issue22.inclusive ? "<=" : "<";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue22.origin ?? "iye"} ${sizing.verb} ${adj}${issue22.maximum} ${sizing.unit}`;
        return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue22.maximum}`;
      }
      case "too_small": {
        const adj = issue22.inclusive ? ">=" : ">";
        const sizing = getSizing(issue22.origin);
        if (sizing)
          return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue22.origin} ${sizing.verb} ${adj}${issue22.minimum} ${sizing.unit}`;
        return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue22.minimum}`;
      }
      case "invalid_format": {
        const _issue = issue22;
        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] ?? issue22.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 ${issue22.divisor}`;
      case "unrecognized_keys":
        return `B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${joinValues(issue22.keys, ", ")}`;
      case "invalid_key":
        return `B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue22.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 ${issue22.origin}`;
      default:
        return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e";
    }
  };
}, "error");
function yo_default() {
  return {
    localeError: error50()
  };
}
__name(yo_default, "default");
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 meta32 = _meta[0];
    this._map.set(schema, meta32);
    if (meta32 && typeof meta32 === "object" && "id" in meta32) {
      this._idmap.set(meta32.id, schema);
    }
    return this;
  }
  clear() {
    this._map = /* @__PURE__ */ new WeakMap();
    this._idmap = /* @__PURE__ */ new Map();
    return this;
  }
  remove(schema) {
    const meta32 = this._map.get(schema);
    if (meta32 && typeof meta32 === "object" && "id" in meta32) {
      this._idmap.delete(meta32.id);
    }
    this._map.delete(schema);
    return this;
  }
  get(schema) {
    const p2 = schema._zod.parent;
    if (p2) {
      const pm = { ...this.get(p2) ?? {} };
      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;
// @__NO_SIDE_EFFECTS__
function _string(Class22, params) {
  return new Class22({
    type: "string",
    ...normalizeParams(params)
  });
}
__name(_string, "_string");
// @__NO_SIDE_EFFECTS__
function _coercedString(Class22, params) {
  return new Class22({
    type: "string",
    coerce: true,
    ...normalizeParams(params)
  });
}
__name(_coercedString, "_coercedString");
// @__NO_SIDE_EFFECTS__
function _email(Class22, params) {
  return new Class22({
    type: "string",
    format: "email",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
__name(_email, "_email");
// @__NO_SIDE_EFFECTS__
function _guid(Class22, params) {
  return new Class22({
    type: "string",
    format: "guid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
__name(_guid, "_guid");
// @__NO_SIDE_EFFECTS__
function _uuid(Class22, params) {
  return new Class22({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
__name(_uuid, "_uuid");
// @__NO_SIDE_EFFECTS__
function _uuidv4(Class22, params) {
  return new Class22({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    version: "v4",
    ...normalizeParams(params)
  });
}
__name(_uuidv4, "_uuidv4");
// @__NO_SIDE_EFFECTS__
function _uuidv6(Class22, params) {
  return new Class22({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    version: "v6",
    ...normalizeParams(params)
  });
}
__name(_uuidv6, "_uuidv6");
// @__NO_SIDE_EFFECTS__
function _uuidv7(Class22, params) {
  return new Class22({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    version: "v7",
    ...normalizeParams(params)
  });
}
__name(_uuidv7, "_uuidv7");
// @__NO_SIDE_EFFECTS__
function _url(Class22, params) {
  return new Class22({
    type: "string",
    format: "url",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
__name(_url, "_url");
// @__NO_SIDE_EFFECTS__
function _emoji2(Class22, params) {
  return new Class22({
    type: "string",
    format: "emoji",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
__name(_emoji2, "_emoji");
// @__NO_SIDE_EFFECTS__
function _nanoid(Class22, params) {
  return new Class22({
    type: "string",
    format: "nanoid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
__name(_nanoid, "_nanoid");
// @__NO_SIDE_EFFECTS__
function _cuid(Class22, params) {
  return new Class22({
    type: "string",
    format: "cuid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
__name(_cuid, "_cuid");
// @__NO_SIDE_EFFECTS__
function _cuid2(Class22, params) {
  return new Class22({
    type: "string",
    format: "cuid2",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
__name(_cuid2, "_cuid2");
// @__NO_SIDE_EFFECTS__
function _ulid(Class22, params) {
  return new Class22({
    type: "string",
    format: "ulid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
__name(_ulid, "_ulid");
// @__NO_SIDE_EFFECTS__
function _xid(Class22, params) {
  return new Class22({
    type: "string",
    format: "xid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
__name(_xid, "_xid");
// @__NO_SIDE_EFFECTS__
function _ksuid(Class22, params) {
  return new Class22({
    type: "string",
    format: "ksuid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
__name(_ksuid, "_ksuid");
// @__NO_SIDE_EFFECTS__
function _ipv4(Class22, params) {
  return new Class22({
    type: "string",
    format: "ipv4",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
__name(_ipv4, "_ipv4");
// @__NO_SIDE_EFFECTS__
function _ipv6(Class22, params) {
  return new Class22({
    type: "string",
    format: "ipv6",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
__name(_ipv6, "_ipv6");
// @__NO_SIDE_EFFECTS__
function _mac(Class22, params) {
  return new Class22({
    type: "string",
    format: "mac",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
__name(_mac, "_mac");
// @__NO_SIDE_EFFECTS__
function _cidrv4(Class22, params) {
  return new Class22({
    type: "string",
    format: "cidrv4",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
__name(_cidrv4, "_cidrv4");
// @__NO_SIDE_EFFECTS__
function _cidrv6(Class22, params) {
  return new Class22({
    type: "string",
    format: "cidrv6",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
__name(_cidrv6, "_cidrv6");
// @__NO_SIDE_EFFECTS__
function _base64(Class22, params) {
  return new Class22({
    type: "string",
    format: "base64",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
__name(_base64, "_base64");
// @__NO_SIDE_EFFECTS__
function _base64url(Class22, params) {
  return new Class22({
    type: "string",
    format: "base64url",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
__name(_base64url, "_base64url");
// @__NO_SIDE_EFFECTS__
function _e164(Class22, params) {
  return new Class22({
    type: "string",
    format: "e164",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
__name(_e164, "_e164");
// @__NO_SIDE_EFFECTS__
function _jwt(Class22, params) {
  return new Class22({
    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(Class22, params) {
  return new Class22({
    type: "string",
    format: "datetime",
    check: "string_format",
    offset: false,
    local: false,
    precision: null,
    ...normalizeParams(params)
  });
}
__name(_isoDateTime, "_isoDateTime");
// @__NO_SIDE_EFFECTS__
function _isoDate(Class22, params) {
  return new Class22({
    type: "string",
    format: "date",
    check: "string_format",
    ...normalizeParams(params)
  });
}
__name(_isoDate, "_isoDate");
// @__NO_SIDE_EFFECTS__
function _isoTime(Class22, params) {
  return new Class22({
    type: "string",
    format: "time",
    check: "string_format",
    precision: null,
    ...normalizeParams(params)
  });
}
__name(_isoTime, "_isoTime");
// @__NO_SIDE_EFFECTS__
function _isoDuration(Class22, params) {
  return new Class22({
    type: "string",
    format: "duration",
    check: "string_format",
    ...normalizeParams(params)
  });
}
__name(_isoDuration, "_isoDuration");
// @__NO_SIDE_EFFECTS__
function _number(Class22, params) {
  return new Class22({
    type: "number",
    checks: [],
    ...normalizeParams(params)
  });
}
__name(_number, "_number");
// @__NO_SIDE_EFFECTS__
function _coercedNumber(Class22, params) {
  return new Class22({
    type: "number",
    coerce: true,
    checks: [],
    ...normalizeParams(params)
  });
}
__name(_coercedNumber, "_coercedNumber");
// @__NO_SIDE_EFFECTS__
function _int(Class22, params) {
  return new Class22({
    type: "number",
    check: "number_format",
    abort: false,
    format: "safeint",
    ...normalizeParams(params)
  });
}
__name(_int, "_int");
// @__NO_SIDE_EFFECTS__
function _float32(Class22, params) {
  return new Class22({
    type: "number",
    check: "number_format",
    abort: false,
    format: "float32",
    ...normalizeParams(params)
  });
}
__name(_float32, "_float32");
// @__NO_SIDE_EFFECTS__
function _float64(Class22, params) {
  return new Class22({
    type: "number",
    check: "number_format",
    abort: false,
    format: "float64",
    ...normalizeParams(params)
  });
}
__name(_float64, "_float64");
// @__NO_SIDE_EFFECTS__
function _int32(Class22, params) {
  return new Class22({
    type: "number",
    check: "number_format",
    abort: false,
    format: "int32",
    ...normalizeParams(params)
  });
}
__name(_int32, "_int32");
// @__NO_SIDE_EFFECTS__
function _uint32(Class22, params) {
  return new Class22({
    type: "number",
    check: "number_format",
    abort: false,
    format: "uint32",
    ...normalizeParams(params)
  });
}
__name(_uint32, "_uint32");
// @__NO_SIDE_EFFECTS__
function _boolean(Class22, params) {
  return new Class22({
    type: "boolean",
    ...normalizeParams(params)
  });
}
__name(_boolean, "_boolean");
// @__NO_SIDE_EFFECTS__
function _coercedBoolean(Class22, params) {
  return new Class22({
    type: "boolean",
    coerce: true,
    ...normalizeParams(params)
  });
}
__name(_coercedBoolean, "_coercedBoolean");
// @__NO_SIDE_EFFECTS__
function _bigint(Class22, params) {
  return new Class22({
    type: "bigint",
    ...normalizeParams(params)
  });
}
__name(_bigint, "_bigint");
// @__NO_SIDE_EFFECTS__
function _coercedBigint(Class22, params) {
  return new Class22({
    type: "bigint",
    coerce: true,
    ...normalizeParams(params)
  });
}
__name(_coercedBigint, "_coercedBigint");
// @__NO_SIDE_EFFECTS__
function _int64(Class22, params) {
  return new Class22({
    type: "bigint",
    check: "bigint_format",
    abort: false,
    format: "int64",
    ...normalizeParams(params)
  });
}
__name(_int64, "_int64");
// @__NO_SIDE_EFFECTS__
function _uint64(Class22, params) {
  return new Class22({
    type: "bigint",
    check: "bigint_format",
    abort: false,
    format: "uint64",
    ...normalizeParams(params)
  });
}
__name(_uint64, "_uint64");
// @__NO_SIDE_EFFECTS__
function _symbol(Class22, params) {
  return new Class22({
    type: "symbol",
    ...normalizeParams(params)
  });
}
__name(_symbol, "_symbol");
// @__NO_SIDE_EFFECTS__
function _undefined2(Class22, params) {
  return new Class22({
    type: "undefined",
    ...normalizeParams(params)
  });
}
__name(_undefined2, "_undefined");
// @__NO_SIDE_EFFECTS__
function _null2(Class22, params) {
  return new Class22({
    type: "null",
    ...normalizeParams(params)
  });
}
__name(_null2, "_null");
// @__NO_SIDE_EFFECTS__
function _any(Class22) {
  return new Class22({
    type: "any"
  });
}
__name(_any, "_any");
// @__NO_SIDE_EFFECTS__
function _unknown(Class22) {
  return new Class22({
    type: "unknown"
  });
}
__name(_unknown, "_unknown");
// @__NO_SIDE_EFFECTS__
function _never(Class22, params) {
  return new Class22({
    type: "never",
    ...normalizeParams(params)
  });
}
__name(_never, "_never");
// @__NO_SIDE_EFFECTS__
function _void(Class22, params) {
  return new Class22({
    type: "void",
    ...normalizeParams(params)
  });
}
__name(_void, "_void");
// @__NO_SIDE_EFFECTS__
function _date(Class22, params) {
  return new Class22({
    type: "date",
    ...normalizeParams(params)
  });
}
__name(_date, "_date");
// @__NO_SIDE_EFFECTS__
function _coercedDate(Class22, params) {
  return new Class22({
    type: "date",
    coerce: true,
    ...normalizeParams(params)
  });
}
__name(_coercedDate, "_coercedDate");
// @__NO_SIDE_EFFECTS__
function _nan(Class22, params) {
  return new Class22({
    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(types3, params) {
  return new $ZodCheckMimeType({
    check: "mime_type",
    mime: types3,
    ...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(Class22, element, params) {
  return new Class22({
    type: "array",
    element,
    // get element() {
    //   return element;
    // },
    ...normalizeParams(params)
  });
}
__name(_array, "_array");
// @__NO_SIDE_EFFECTS__
function _union(Class22, options, params) {
  return new Class22({
    type: "union",
    options,
    ...normalizeParams(params)
  });
}
__name(_union, "_union");
function _xor(Class22, options, params) {
  return new Class22({
    type: "union",
    options,
    inclusive: false,
    ...normalizeParams(params)
  });
}
__name(_xor, "_xor");
// @__NO_SIDE_EFFECTS__
function _discriminatedUnion(Class22, discriminator, options, params) {
  return new Class22({
    type: "union",
    options,
    discriminator,
    ...normalizeParams(params)
  });
}
__name(_discriminatedUnion, "_discriminatedUnion");
// @__NO_SIDE_EFFECTS__
function _intersection(Class22, left, right) {
  return new Class22({
    type: "intersection",
    left,
    right
  });
}
__name(_intersection, "_intersection");
// @__NO_SIDE_EFFECTS__
function _tuple(Class22, items, _paramsOrRest, _params) {
  const hasRest = _paramsOrRest instanceof $ZodType;
  const params = hasRest ? _params : _paramsOrRest;
  const rest = hasRest ? _paramsOrRest : null;
  return new Class22({
    type: "tuple",
    items,
    rest,
    ...normalizeParams(params)
  });
}
__name(_tuple, "_tuple");
// @__NO_SIDE_EFFECTS__
function _record(Class22, keyType, valueType, params) {
  return new Class22({
    type: "record",
    keyType,
    valueType,
    ...normalizeParams(params)
  });
}
__name(_record, "_record");
// @__NO_SIDE_EFFECTS__
function _map(Class22, keyType, valueType, params) {
  return new Class22({
    type: "map",
    keyType,
    valueType,
    ...normalizeParams(params)
  });
}
__name(_map, "_map");
// @__NO_SIDE_EFFECTS__
function _set(Class22, valueType, params) {
  return new Class22({
    type: "set",
    valueType,
    ...normalizeParams(params)
  });
}
__name(_set, "_set");
// @__NO_SIDE_EFFECTS__
function _enum(Class22, values, params) {
  const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
  return new Class22({
    type: "enum",
    entries,
    ...normalizeParams(params)
  });
}
__name(_enum, "_enum");
// @__NO_SIDE_EFFECTS__
function _nativeEnum(Class22, entries, params) {
  return new Class22({
    type: "enum",
    entries,
    ...normalizeParams(params)
  });
}
__name(_nativeEnum, "_nativeEnum");
// @__NO_SIDE_EFFECTS__
function _literal(Class22, value, params) {
  return new Class22({
    type: "literal",
    values: Array.isArray(value) ? value : [value],
    ...normalizeParams(params)
  });
}
__name(_literal, "_literal");
// @__NO_SIDE_EFFECTS__
function _file(Class22, params) {
  return new Class22({
    type: "file",
    ...normalizeParams(params)
  });
}
__name(_file, "_file");
// @__NO_SIDE_EFFECTS__
function _transform(Class22, fn) {
  return new Class22({
    type: "transform",
    transform: fn
  });
}
__name(_transform, "_transform");
// @__NO_SIDE_EFFECTS__
function _optional(Class22, innerType) {
  return new Class22({
    type: "optional",
    innerType
  });
}
__name(_optional, "_optional");
// @__NO_SIDE_EFFECTS__
function _nullable(Class22, innerType) {
  return new Class22({
    type: "nullable",
    innerType
  });
}
__name(_nullable, "_nullable");
// @__NO_SIDE_EFFECTS__
function _default(Class22, innerType, defaultValue) {
  return new Class22({
    type: "default",
    innerType,
    get defaultValue() {
      return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
    }
  });
}
__name(_default, "_default");
// @__NO_SIDE_EFFECTS__
function _nonoptional(Class22, innerType, params) {
  return new Class22({
    type: "nonoptional",
    innerType,
    ...normalizeParams(params)
  });
}
__name(_nonoptional, "_nonoptional");
// @__NO_SIDE_EFFECTS__
function _success(Class22, innerType) {
  return new Class22({
    type: "success",
    innerType
  });
}
__name(_success, "_success");
// @__NO_SIDE_EFFECTS__
function _catch(Class22, innerType, catchValue) {
  return new Class22({
    type: "catch",
    innerType,
    catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
  });
}
__name(_catch, "_catch");
// @__NO_SIDE_EFFECTS__
function _pipe(Class22, in_, out) {
  return new Class22({
    type: "pipe",
    in: in_,
    out
  });
}
__name(_pipe, "_pipe");
// @__NO_SIDE_EFFECTS__
function _readonly(Class22, innerType) {
  return new Class22({
    type: "readonly",
    innerType
  });
}
__name(_readonly, "_readonly");
// @__NO_SIDE_EFFECTS__
function _templateLiteral(Class22, parts, params) {
  return new Class22({
    type: "template_literal",
    parts,
    ...normalizeParams(params)
  });
}
__name(_templateLiteral, "_templateLiteral");
// @__NO_SIDE_EFFECTS__
function _lazy(Class22, getter) {
  return new Class22({
    type: "lazy",
    getter
  });
}
__name(_lazy, "_lazy");
// @__NO_SIDE_EFFECTS__
function _promise(Class22, innerType) {
  return new Class22({
    type: "promise",
    innerType
  });
}
__name(_promise, "_promise");
// @__NO_SIDE_EFFECTS__
function _custom(Class22, fn, _params) {
  const norm = normalizeParams(_params);
  norm.abort ?? (norm.abort = true);
  const schema = new Class22({
    type: "custom",
    check: "custom",
    fn,
    ...norm
  });
  return schema;
}
__name(_custom, "_custom");
// @__NO_SIDE_EFFECTS__
function _refine(Class22, fn, _params) {
  const schema = new Class22({
    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 = (issue22) => {
      if (typeof issue22 === "string") {
        payload.issues.push(issue(issue22, payload.value, ch._zod.def));
      } else {
        const _issue = issue22;
        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 codec22 = 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: codec22,
          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 codec22;
}
__name(_stringbool, "_stringbool");
// @__NO_SIDE_EFFECTS__
function _stringFormat(Class22, format23, fnOrRegex, _params = {}) {
  const params = normalizeParams(_params);
  const def = {
    ...normalizeParams(_params),
    check: "string_format",
    type: "string",
    format: format23,
    fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val),
    ...params
  };
  if (fnOrRegex instanceof RegExp) {
    def.pattern = fnOrRegex;
  }
  const inst = new Class22(def);
  return inst;
}
__name(_stringFormat, "_stringFormat");
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 process22(schema, ctx, _params = { path: [], schemaPath: [] }) {
  var _a32;
  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;
      process22(parent, ctx, params);
      ctx.seen.get(parent).isParent = true;
    }
  }
  const meta32 = ctx.metadataRegistry.get(schema);
  if (meta32)
    Object.assign(result.schema, meta32);
  if (ctx.io === "input" && isTransforming(schema)) {
    delete result.schema.examples;
    delete result.schema.default;
  }
  if (ctx.io === "input" && "_prefault" in result.schema)
    (_a32 = result.schema).default ?? (_a32.default = result.schema._prefault);
  delete result.schema._prefault;
  const _result = ctx.seen.get(schema);
  return _result.schema;
}
__name(process22, "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("/")}/<root>

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 });
  process22(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 });
  process22(schema, ctx);
  extractDefs(ctx, schema);
  return finalize(ctx, schema);
}, "createStandardJSONSchemaMethod");
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 json22 = _json;
  json22.type = "string";
  const { minimum, maximum, format: format23, patterns, contentEncoding } = schema._zod.bag;
  if (typeof minimum === "number")
    json22.minLength = minimum;
  if (typeof maximum === "number")
    json22.maxLength = maximum;
  if (format23) {
    json22.format = formatMap[format23] ?? format23;
    if (json22.format === "")
      delete json22.format;
    if (format23 === "time") {
      delete json22.format;
    }
  }
  if (contentEncoding)
    json22.contentEncoding = contentEncoding;
  if (patterns && patterns.size > 0) {
    const regexes = [...patterns];
    if (regexes.length === 1)
      json22.pattern = regexes[0].source;
    else if (regexes.length > 1) {
      json22.allOf = [
        ...regexes.map((regex3) => ({
          ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {},
          pattern: regex3.source
        }))
      ];
    }
  }
}, "stringProcessor");
var numberProcessor = /* @__PURE__ */ __name((schema, ctx, _json, _params) => {
  const json22 = _json;
  const { minimum, maximum, format: format23, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;
  if (typeof format23 === "string" && format23.includes("int"))
    json22.type = "integer";
  else
    json22.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) {
      json22.minimum = exclusiveMinimum;
      json22.exclusiveMinimum = true;
    } else {
      json22.exclusiveMinimum = exclusiveMinimum;
    }
  } else if (typeof minimum === "number") {
    json22.minimum = minimum;
  }
  if (exMax) {
    if (legacy) {
      json22.maximum = exclusiveMaximum;
      json22.exclusiveMaximum = true;
    } else {
      json22.exclusiveMaximum = exclusiveMaximum;
    }
  } else if (typeof maximum === "number") {
    json22.maximum = maximum;
  }
  if (typeof multipleOf === "number")
    json22.multipleOf = multipleOf;
}, "numberProcessor");
var booleanProcessor = /* @__PURE__ */ __name((_schema, _ctx, json22, _params) => {
  json22.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, json22, _params) => {
  if (ctx.target === "openapi-3.0") {
    json22.type = "string";
    json22.nullable = true;
    json22.enum = [null];
  } else {
    json22.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, json22, _params) => {
  json22.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, json22, _params) => {
  const def = schema._zod.def;
  const values = getEnumValues(def.entries);
  if (values.every((v) => typeof v === "number"))
    json22.type = "number";
  if (values.every((v) => typeof v === "string"))
    json22.type = "string";
  json22.enum = values;
}, "enumProcessor");
var literalProcessor = /* @__PURE__ */ __name((schema, ctx, json22, _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 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];
    json22.type = val === null ? "null" : typeof val;
    if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
      json22.enum = [val];
    } else {
      json22.const = val;
    }
  } else {
    if (vals.every((v) => typeof v === "number"))
      json22.type = "number";
    if (vals.every((v) => typeof v === "string"))
      json22.type = "string";
    if (vals.every((v) => typeof v === "boolean"))
      json22.type = "boolean";
    if (vals.every((v) => v === null))
      json22.type = "null";
    json22.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, json22, _params) => {
  const _json = json22;
  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, json22, _params) => {
  const _json = json22;
  const file22 = {
    type: "string",
    format: "binary",
    contentEncoding: "binary"
  };
  const { minimum, maximum, mime } = schema._zod.bag;
  if (minimum !== void 0)
    file22.minLength = minimum;
  if (maximum !== void 0)
    file22.maxLength = maximum;
  if (mime) {
    if (mime.length === 1) {
      file22.contentMediaType = mime[0];
      Object.assign(_json, file22);
    } else {
      Object.assign(_json, file22);
      _json.anyOf = mime.map((m) => ({ contentMediaType: m }));
    }
  } else {
    Object.assign(_json, file22);
  }
}, "fileProcessor");
var successProcessor = /* @__PURE__ */ __name((_schema, _ctx, json22, _params) => {
  json22.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 json22 = _json;
  const def = schema._zod.def;
  const { minimum, maximum } = schema._zod.bag;
  if (typeof minimum === "number")
    json22.minItems = minimum;
  if (typeof maximum === "number")
    json22.maxItems = maximum;
  json22.type = "array";
  json22.items = process22(def.element, ctx, {
    ...params,
    path: [...params.path, "items"]
  });
}, "arrayProcessor");
var objectProcessor = /* @__PURE__ */ __name((schema, ctx, _json, params) => {
  const json22 = _json;
  const def = schema._zod.def;
  json22.type = "object";
  json22.properties = {};
  const shape = def.shape;
  for (const key in shape) {
    json22.properties[key] = process22(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) {
    json22.required = Array.from(requiredKeys);
  }
  if (def.catchall?._zod.def.type === "never") {
    json22.additionalProperties = false;
  } else if (!def.catchall) {
    if (ctx.io === "output")
      json22.additionalProperties = false;
  } else if (def.catchall) {
    json22.additionalProperties = process22(def.catchall, ctx, {
      ...params,
      path: [...params.path, "additionalProperties"]
    });
  }
}, "objectProcessor");
var unionProcessor = /* @__PURE__ */ __name((schema, ctx, json22, params) => {
  const def = schema._zod.def;
  const isExclusive = def.inclusive === false;
  const options = def.options.map((x, i) => process22(x, ctx, {
    ...params,
    path: [...params.path, isExclusive ? "oneOf" : "anyOf", i]
  }));
  if (isExclusive) {
    json22.oneOf = options;
  } else {
    json22.anyOf = options;
  }
}, "unionProcessor");
var intersectionProcessor = /* @__PURE__ */ __name((schema, ctx, json22, params) => {
  const def = schema._zod.def;
  const a = process22(def.left, ctx, {
    ...params,
    path: [...params.path, "allOf", 0]
  });
  const b = process22(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]
  ];
  json22.allOf = allOf;
}, "intersectionProcessor");
var tupleProcessor = /* @__PURE__ */ __name((schema, ctx, _json, params) => {
  const json22 = _json;
  const def = schema._zod.def;
  json22.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) => process22(x, ctx, {
    ...params,
    path: [...params.path, prefixPath, i]
  }));
  const rest = def.rest ? process22(def.rest, ctx, {
    ...params,
    path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []]
  }) : null;
  if (ctx.target === "draft-2020-12") {
    json22.prefixItems = prefixItems;
    if (rest) {
      json22.items = rest;
    }
  } else if (ctx.target === "openapi-3.0") {
    json22.items = {
      anyOf: prefixItems
    };
    if (rest) {
      json22.items.anyOf.push(rest);
    }
    json22.minItems = prefixItems.length;
    if (!rest) {
      json22.maxItems = prefixItems.length;
    }
  } else {
    json22.items = prefixItems;
    if (rest) {
      json22.additionalItems = rest;
    }
  }
  const { minimum, maximum } = schema._zod.bag;
  if (typeof minimum === "number")
    json22.minItems = minimum;
  if (typeof maximum === "number")
    json22.maxItems = maximum;
}, "tupleProcessor");
var recordProcessor = /* @__PURE__ */ __name((schema, ctx, _json, params) => {
  const json22 = _json;
  const def = schema._zod.def;
  json22.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 = process22(def.valueType, ctx, {
      ...params,
      path: [...params.path, "patternProperties", "*"]
    });
    json22.patternProperties = {};
    for (const pattern of patterns) {
      json22.patternProperties[pattern.source] = valueSchema;
    }
  } else {
    if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") {
      json22.propertyNames = process22(def.keyType, ctx, {
        ...params,
        path: [...params.path, "propertyNames"]
      });
    }
    json22.additionalProperties = process22(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) {
      json22.required = validKeyValues;
    }
  }
}, "recordProcessor");
var nullableProcessor = /* @__PURE__ */ __name((schema, ctx, json22, params) => {
  const def = schema._zod.def;
  const inner = process22(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  if (ctx.target === "openapi-3.0") {
    seen.ref = def.innerType;
    json22.nullable = true;
  } else {
    json22.anyOf = [inner, { type: "null" }];
  }
}, "nullableProcessor");
var nonoptionalProcessor = /* @__PURE__ */ __name((schema, ctx, _json, params) => {
  const def = schema._zod.def;
  process22(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
}, "nonoptionalProcessor");
var defaultProcessor = /* @__PURE__ */ __name((schema, ctx, json22, params) => {
  const def = schema._zod.def;
  process22(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
  json22.default = JSON.parse(JSON.stringify(def.defaultValue));
}, "defaultProcessor");
var prefaultProcessor = /* @__PURE__ */ __name((schema, ctx, json22, params) => {
  const def = schema._zod.def;
  process22(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
  if (ctx.io === "input")
    json22._prefault = JSON.parse(JSON.stringify(def.defaultValue));
}, "prefaultProcessor");
var catchProcessor = /* @__PURE__ */ __name((schema, ctx, json22, params) => {
  const def = schema._zod.def;
  process22(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");
  }
  json22.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;
  process22(innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = innerType;
}, "pipeProcessor");
var readonlyProcessor = /* @__PURE__ */ __name((schema, ctx, json22, params) => {
  const def = schema._zod.def;
  process22(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
  json22.readOnly = true;
}, "readonlyProcessor");
var promiseProcessor = /* @__PURE__ */ __name((schema, ctx, _json, params) => {
  const def = schema._zod.def;
  process22(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;
  process22(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;
  process22(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 registry22 = input;
    const ctx2 = initializeContext({ ...params, processors: allProcessors });
    const defs = {};
    for (const entry of registry22._idmap.entries()) {
      const [_, schema] = entry;
      process22(schema, ctx2);
    }
    const schemas = {};
    const external = {
      registry: registry22,
      uri: params?.uri,
      defs
    };
    ctx2.external = external;
    for (const entry of registry22._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 });
  process22(input, ctx);
  extractDefs(ctx, input);
  return finalize(ctx, input);
}
__name(toJSONSchema, "toJSONSchema");
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 process22(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;
  }
};
var json_schema_exports = {};
var schemas_exports2 = {};
__export2(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: () => check,
  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: () => file2,
  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
});
var checks_exports2 = {};
__export2(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
});
var iso_exports = {};
__export2(iso_exports, {
  ZodISODate: () => ZodISODate,
  ZodISODateTime: () => ZodISODateTime,
  ZodISODuration: () => ZodISODuration,
  ZodISOTime: () => ZodISOTime,
  date: () => date2,
  datetime: () => datetime2,
  duration: () => duration2,
  time: () => time2
});
var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => {
  $ZodISODateTime.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function datetime2(params) {
  return /* @__PURE__ */ _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 /* @__PURE__ */ _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 /* @__PURE__ */ _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 /* @__PURE__ */ _isoDuration(ZodISODuration, params);
}
__name(duration2, "duration");
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((issue22) => {
        inst.issues.push(issue22);
        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
});
var parse22 = /* @__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);
var _installedGroups = /* @__PURE__ */ new WeakMap();
function _installLazyMethods(inst, group, methods) {
  const proto2 = Object.getPrototypeOf(inst);
  let installed = _installedGroups.get(proto2);
  if (!installed) {
    installed = /* @__PURE__ */ new Set();
    _installedGroups.set(proto2, installed);
  }
  if (installed.has(group))
    return;
  installed.add(group);
  for (const key in methods) {
    const fn = methods[key];
    Object.defineProperty(proto2, 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) => parse22(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, meta32) {
      reg.add(this, meta32);
      return this;
    },
    refine(check22, params) {
      return this.check(refine(check22, params));
    },
    superRefine(refinement, params) {
      return this.check(superRefine(refinement, params));
    },
    overwrite(fn) {
      return this.check(/* @__PURE__ */ _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, json22, params) => stringProcessor(inst, ctx, json22, 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(/* @__PURE__ */ _regex(...args));
    },
    includes(...args) {
      return this.check(/* @__PURE__ */ _includes(...args));
    },
    startsWith(...args) {
      return this.check(/* @__PURE__ */ _startsWith(...args));
    },
    endsWith(...args) {
      return this.check(/* @__PURE__ */ _endsWith(...args));
    },
    min(...args) {
      return this.check(/* @__PURE__ */ _minLength(...args));
    },
    max(...args) {
      return this.check(/* @__PURE__ */ _maxLength(...args));
    },
    length(...args) {
      return this.check(/* @__PURE__ */ _length(...args));
    },
    nonempty(...args) {
      return this.check(/* @__PURE__ */ _minLength(1, ...args));
    },
    lowercase(params) {
      return this.check(/* @__PURE__ */ _lowercase(params));
    },
    uppercase(params) {
      return this.check(/* @__PURE__ */ _uppercase(params));
    },
    trim() {
      return this.check(/* @__PURE__ */ _trim());
    },
    normalize(...args) {
      return this.check(/* @__PURE__ */ _normalize(...args));
    },
    toLowerCase() {
      return this.check(/* @__PURE__ */ _toLowerCase());
    },
    toUpperCase() {
      return this.check(/* @__PURE__ */ _toUpperCase());
    },
    slugify() {
      return this.check(/* @__PURE__ */ _slugify());
    }
  });
});
var ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => {
  $ZodString.init(inst, def);
  _ZodString.init(inst, def);
  inst.email = (params) => inst.check(/* @__PURE__ */ _email(ZodEmail, params));
  inst.url = (params) => inst.check(/* @__PURE__ */ _url(ZodURL, params));
  inst.jwt = (params) => inst.check(/* @__PURE__ */ _jwt(ZodJWT, params));
  inst.emoji = (params) => inst.check(/* @__PURE__ */ _emoji2(ZodEmoji, params));
  inst.guid = (params) => inst.check(/* @__PURE__ */ _guid(ZodGUID, params));
  inst.uuid = (params) => inst.check(/* @__PURE__ */ _uuid(ZodUUID, params));
  inst.uuidv4 = (params) => inst.check(/* @__PURE__ */ _uuidv4(ZodUUID, params));
  inst.uuidv6 = (params) => inst.check(/* @__PURE__ */ _uuidv6(ZodUUID, params));
  inst.uuidv7 = (params) => inst.check(/* @__PURE__ */ _uuidv7(ZodUUID, params));
  inst.nanoid = (params) => inst.check(/* @__PURE__ */ _nanoid(ZodNanoID, params));
  inst.guid = (params) => inst.check(/* @__PURE__ */ _guid(ZodGUID, params));
  inst.cuid = (params) => inst.check(/* @__PURE__ */ _cuid(ZodCUID, params));
  inst.cuid2 = (params) => inst.check(/* @__PURE__ */ _cuid2(ZodCUID2, params));
  inst.ulid = (params) => inst.check(/* @__PURE__ */ _ulid(ZodULID, params));
  inst.base64 = (params) => inst.check(/* @__PURE__ */ _base64(ZodBase64, params));
  inst.base64url = (params) => inst.check(/* @__PURE__ */ _base64url(ZodBase64URL, params));
  inst.xid = (params) => inst.check(/* @__PURE__ */ _xid(ZodXID, params));
  inst.ksuid = (params) => inst.check(/* @__PURE__ */ _ksuid(ZodKSUID, params));
  inst.ipv4 = (params) => inst.check(/* @__PURE__ */ _ipv4(ZodIPv4, params));
  inst.ipv6 = (params) => inst.check(/* @__PURE__ */ _ipv6(ZodIPv6, params));
  inst.cidrv4 = (params) => inst.check(/* @__PURE__ */ _cidrv4(ZodCIDRv4, params));
  inst.cidrv6 = (params) => inst.check(/* @__PURE__ */ _cidrv6(ZodCIDRv6, params));
  inst.e164 = (params) => inst.check(/* @__PURE__ */ _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 /* @__PURE__ */ _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 /* @__PURE__ */ _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 /* @__PURE__ */ _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 /* @__PURE__ */ _uuid(ZodUUID, params);
}
__name(uuid2, "uuid");
function uuidv4(params) {
  return /* @__PURE__ */ _uuidv4(ZodUUID, params);
}
__name(uuidv4, "uuidv4");
function uuidv6(params) {
  return /* @__PURE__ */ _uuidv6(ZodUUID, params);
}
__name(uuidv6, "uuidv6");
function uuidv7(params) {
  return /* @__PURE__ */ _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 /* @__PURE__ */ _url(ZodURL, params);
}
__name(url, "url");
function httpUrl(params) {
  return /* @__PURE__ */ _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 /* @__PURE__ */ _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 /* @__PURE__ */ _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 /* @__PURE__ */ _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 /* @__PURE__ */ _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 /* @__PURE__ */ _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 /* @__PURE__ */ _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 /* @__PURE__ */ _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 /* @__PURE__ */ _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 /* @__PURE__ */ _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 /* @__PURE__ */ _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 /* @__PURE__ */ _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 /* @__PURE__ */ _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 /* @__PURE__ */ _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 /* @__PURE__ */ _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 /* @__PURE__ */ _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 /* @__PURE__ */ _jwt(ZodJWT, params);
}
__name(jwt, "jwt");
var ZodCustomStringFormat = /* @__PURE__ */ $constructor("ZodCustomStringFormat", (inst, def) => {
  $ZodCustomStringFormat.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function stringFormat(format23, fnOrRegex, _params = {}) {
  return /* @__PURE__ */ _stringFormat(ZodCustomStringFormat, format23, fnOrRegex, _params);
}
__name(stringFormat, "stringFormat");
function hostname2(_params) {
  return /* @__PURE__ */ _stringFormat(ZodCustomStringFormat, "hostname", regexes_exports.hostname, _params);
}
__name(hostname2, "hostname");
function hex2(_params) {
  return /* @__PURE__ */ _stringFormat(ZodCustomStringFormat, "hex", regexes_exports.hex, _params);
}
__name(hex2, "hex");
function hash(alg, params) {
  const enc = params?.enc ?? "hex";
  const format23 = `${alg}_${enc}`;
  const regex3 = regexes_exports[format23];
  if (!regex3)
    throw new Error(`Unrecognized hash format: ${format23}`);
  return /* @__PURE__ */ _stringFormat(ZodCustomStringFormat, format23, regex3, params);
}
__name(hash, "hash");
var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => {
  $ZodNumber.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json22, params) => numberProcessor(inst, ctx, json22, params);
  _installLazyMethods(inst, "ZodNumber", {
    gt(value, params) {
      return this.check(/* @__PURE__ */ _gt(value, params));
    },
    gte(value, params) {
      return this.check(/* @__PURE__ */ _gte(value, params));
    },
    min(value, params) {
      return this.check(/* @__PURE__ */ _gte(value, params));
    },
    lt(value, params) {
      return this.check(/* @__PURE__ */ _lt(value, params));
    },
    lte(value, params) {
      return this.check(/* @__PURE__ */ _lte(value, params));
    },
    max(value, params) {
      return this.check(/* @__PURE__ */ _lte(value, params));
    },
    int(params) {
      return this.check(int(params));
    },
    safe(params) {
      return this.check(int(params));
    },
    positive(params) {
      return this.check(/* @__PURE__ */ _gt(0, params));
    },
    nonnegative(params) {
      return this.check(/* @__PURE__ */ _gte(0, params));
    },
    negative(params) {
      return this.check(/* @__PURE__ */ _lt(0, params));
    },
    nonpositive(params) {
      return this.check(/* @__PURE__ */ _lte(0, params));
    },
    multipleOf(value, params) {
      return this.check(/* @__PURE__ */ _multipleOf(value, params));
    },
    step(value, params) {
      return this.check(/* @__PURE__ */ _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 /* @__PURE__ */ _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 /* @__PURE__ */ _int(ZodNumberFormat, params);
}
__name(int, "int");
function float32(params) {
  return /* @__PURE__ */ _float32(ZodNumberFormat, params);
}
__name(float32, "float32");
function float64(params) {
  return /* @__PURE__ */ _float64(ZodNumberFormat, params);
}
__name(float64, "float64");
function int32(params) {
  return /* @__PURE__ */ _int32(ZodNumberFormat, params);
}
__name(int32, "int32");
function uint32(params) {
  return /* @__PURE__ */ _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, json22, params) => booleanProcessor(inst, ctx, json22, params);
});
function boolean2(params) {
  return /* @__PURE__ */ _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, json22, params) => bigintProcessor(inst, ctx, json22, params);
  inst.gte = (value, params) => inst.check(/* @__PURE__ */ _gte(value, params));
  inst.min = (value, params) => inst.check(/* @__PURE__ */ _gte(value, params));
  inst.gt = (value, params) => inst.check(/* @__PURE__ */ _gt(value, params));
  inst.gte = (value, params) => inst.check(/* @__PURE__ */ _gte(value, params));
  inst.min = (value, params) => inst.check(/* @__PURE__ */ _gte(value, params));
  inst.lt = (value, params) => inst.check(/* @__PURE__ */ _lt(value, params));
  inst.lte = (value, params) => inst.check(/* @__PURE__ */ _lte(value, params));
  inst.max = (value, params) => inst.check(/* @__PURE__ */ _lte(value, params));
  inst.positive = (params) => inst.check(/* @__PURE__ */ _gt(BigInt(0), params));
  inst.negative = (params) => inst.check(/* @__PURE__ */ _lt(BigInt(0), params));
  inst.nonpositive = (params) => inst.check(/* @__PURE__ */ _lte(BigInt(0), params));
  inst.nonnegative = (params) => inst.check(/* @__PURE__ */ _gte(BigInt(0), params));
  inst.multipleOf = (value, params) => inst.check(/* @__PURE__ */ _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 /* @__PURE__ */ _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 /* @__PURE__ */ _int64(ZodBigIntFormat, params);
}
__name(int64, "int64");
function uint64(params) {
  return /* @__PURE__ */ _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, json22, params) => symbolProcessor(inst, ctx, json22, params);
});
function symbol(params) {
  return /* @__PURE__ */ _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, json22, params) => undefinedProcessor(inst, ctx, json22, params);
});
function _undefined3(params) {
  return /* @__PURE__ */ _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, json22, params) => nullProcessor(inst, ctx, json22, params);
});
function _null3(params) {
  return /* @__PURE__ */ _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, json22, params) => anyProcessor(inst, ctx, json22, params);
});
function any() {
  return /* @__PURE__ */ _any(ZodAny);
}
__name(any, "any");
var ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => {
  $ZodUnknown.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json22, params) => unknownProcessor(inst, ctx, json22, params);
});
function unknown() {
  return /* @__PURE__ */ _unknown(ZodUnknown);
}
__name(unknown, "unknown");
var ZodNever = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => {
  $ZodNever.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json22, params) => neverProcessor(inst, ctx, json22, params);
});
function never(params) {
  return /* @__PURE__ */ _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, json22, params) => voidProcessor(inst, ctx, json22, params);
});
function _void2(params) {
  return /* @__PURE__ */ _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, json22, params) => dateProcessor(inst, ctx, json22, params);
  inst.min = (value, params) => inst.check(/* @__PURE__ */ _gte(value, params));
  inst.max = (value, params) => inst.check(/* @__PURE__ */ _lte(value, params));
  const c2 = inst._zod.bag;
  inst.minDate = c2.minimum ? new Date(c2.minimum) : null;
  inst.maxDate = c2.maximum ? new Date(c2.maximum) : null;
});
function date3(params) {
  return /* @__PURE__ */ _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, json22, params) => arrayProcessor(inst, ctx, json22, params);
  inst.element = def.element;
  _installLazyMethods(inst, "ZodArray", {
    min(n2, params) {
      return this.check(/* @__PURE__ */ _minLength(n2, params));
    },
    nonempty(params) {
      return this.check(/* @__PURE__ */ _minLength(1, params));
    },
    max(n2, params) {
      return this.check(/* @__PURE__ */ _maxLength(n2, params));
    },
    length(n2, params) {
      return this.check(/* @__PURE__ */ _length(n2, params));
    },
    unwrap() {
      return this.element;
    }
  });
});
function array(element, params) {
  return /* @__PURE__ */ _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, json22, params) => objectProcessor(inst, ctx, json22, 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, json22, params) => unionProcessor(inst, ctx, json22, params);
  inst.options = def.options;
});
function union(options, params) {
  return new ZodUnion({
    type: "union",
    options,
    ...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, json22, params) => unionProcessor(inst, ctx, json22, params);
  inst.options = def.options;
});
function xor(options, params) {
  return new ZodXor({
    type: "union",
    options,
    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, options, params) {
  return new ZodDiscriminatedUnion({
    type: "union",
    options,
    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, json22, params) => intersectionProcessor(inst, ctx, json22, params);
});
function intersection(left, right) {
  return new ZodIntersection({
    type: "intersection",
    left,
    right
  });
}
__name(intersection, "intersection");
var ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => {
  $ZodTuple.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json22, params) => tupleProcessor(inst, ctx, json22, 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, json22, params) => recordProcessor(inst, ctx, json22, 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, json22, params) => mapProcessor(inst, ctx, json22, params);
  inst.keyType = def.keyType;
  inst.valueType = def.valueType;
  inst.min = (...args) => inst.check(/* @__PURE__ */ _minSize(...args));
  inst.nonempty = (params) => inst.check(/* @__PURE__ */ _minSize(1, params));
  inst.max = (...args) => inst.check(/* @__PURE__ */ _maxSize(...args));
  inst.size = (...args) => inst.check(/* @__PURE__ */ _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, json22, params) => setProcessor(inst, ctx, json22, params);
  inst.min = (...args) => inst.check(/* @__PURE__ */ _minSize(...args));
  inst.nonempty = (params) => inst.check(/* @__PURE__ */ _minSize(1, params));
  inst.max = (...args) => inst.check(/* @__PURE__ */ _maxSize(...args));
  inst.size = (...args) => inst.check(/* @__PURE__ */ _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, json22, params) => enumProcessor(inst, ctx, json22, 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, json22, params) => literalProcessor(inst, ctx, json22, 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, json22, params) => fileProcessor(inst, ctx, json22, params);
  inst.min = (size, params) => inst.check(/* @__PURE__ */ _minSize(size, params));
  inst.max = (size, params) => inst.check(/* @__PURE__ */ _maxSize(size, params));
  inst.mime = (types3, params) => inst.check(/* @__PURE__ */ _mime(Array.isArray(types3) ? types3 : [types3], params));
});
function file2(params) {
  return /* @__PURE__ */ _file(ZodFile, params);
}
__name(file2, "file");
var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
  $ZodTransform.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json22, params) => transformProcessor(inst, ctx, json22, params);
  inst._zod.parse = (payload, _ctx) => {
    if (_ctx.direction === "backward") {
      throw new $ZodEncodeError(inst.constructor.name);
    }
    payload.addIssue = (issue22) => {
      if (typeof issue22 === "string") {
        payload.issues.push(util_exports.issue(issue22, payload.value, def));
      } else {
        const _issue = issue22;
        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, json22, params) => optionalProcessor(inst, ctx, json22, 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, json22, params) => optionalProcessor(inst, ctx, json22, 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, json22, params) => nullableProcessor(inst, ctx, json22, 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, json22, params) => defaultProcessor(inst, ctx, json22, params);
  inst.unwrap = () => inst._zod.def.innerType;
  inst.removeDefault = inst.unwrap;
});
function _default2(innerType, defaultValue) {
  return new ZodDefault({
    type: "default",
    innerType,
    get defaultValue() {
      return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue);
    }
  });
}
__name(_default2, "_default");
var ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => {
  $ZodPrefault.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json22, params) => prefaultProcessor(inst, ctx, json22, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function prefault(innerType, defaultValue) {
  return new ZodPrefault({
    type: "prefault",
    innerType,
    get defaultValue() {
      return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue);
    }
  });
}
__name(prefault, "prefault");
var ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => {
  $ZodNonOptional.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json22, params) => nonoptionalProcessor(inst, ctx, json22, 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, json22, params) => successProcessor(inst, ctx, json22, 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, json22, params) => catchProcessor(inst, ctx, json22, 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, json22, params) => nanProcessor(inst, ctx, json22, params);
});
function nan(params) {
  return /* @__PURE__ */ _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, json22, params) => pipeProcessor(inst, ctx, json22, 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(codec22) {
  const def = codec22._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, json22, params) => readonlyProcessor(inst, ctx, json22, 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, json22, params) => templateLiteralProcessor(inst, ctx, json22, 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, json22, params) => lazyProcessor(inst, ctx, json22, 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, json22, params) => promiseProcessor(inst, ctx, json22, 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, json22, params) => functionProcessor(inst, ctx, json22, 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, json22, params) => customProcessor(inst, ctx, json22, params);
});
function check(fn) {
  const ch = new $ZodCheck({
    check: "custom"
    // ...util.normalizeParams(params),
  });
  ch._zod.check = fn;
  return ch;
}
__name(check, "check");
function custom(fn, _params) {
  return /* @__PURE__ */ _custom(ZodCustom, fn ?? (() => true), _params);
}
__name(custom, "custom");
function refine(fn, _params = {}) {
  return /* @__PURE__ */ _refine(ZodCustom, fn, _params);
}
__name(refine, "refine");
function superRefine(fn, params) {
  return /* @__PURE__ */ _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) => /* @__PURE__ */ _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");
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(map22) {
  config({
    customError: map22
  });
}
__name(setErrorMap, "setErrorMap");
function getErrorMap() {
  return config().customError;
}
__name(getErrorMap, "getErrorMap");
var ZodFirstPartyTypeKind;
/* @__PURE__ */ (function(ZodFirstPartyTypeKind22) {
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
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 path610 = ref.slice(1).split("/").filter(Boolean);
  if (path610.length === 0) {
    return ctx.rootSchema;
  }
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
  if (path610[0] === defsKey) {
    const key = path610[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 type = schema.type;
  if (Array.isArray(type)) {
    const typeSchemas = type.map((t2) => {
      const typeSchema = { ...schema, type: t2 };
      return convertBaseSchema(typeSchema, ctx);
    });
    if (typeSchemas.length === 0) {
      return z.never();
    }
    if (typeSchemas.length === 1) {
      return typeSchemas[0];
    }
    return z.union(typeSchemas);
  }
  if (!type) {
    return z.any();
  }
  let zodSchema;
  switch (type) {
    case "string": {
      let stringSchema = z.string();
      if (schema.format) {
        const format23 = schema.format;
        if (format23 === "email") {
          stringSchema = stringSchema.check(z.email());
        } else if (format23 === "uri" || format23 === "uri-reference") {
          stringSchema = stringSchema.check(z.url());
        } else if (format23 === "uuid" || format23 === "guid") {
          stringSchema = stringSchema.check(z.uuid());
        } else if (format23 === "date-time") {
          stringSchema = stringSchema.check(z.iso.datetime());
        } else if (format23 === "date") {
          stringSchema = stringSchema.check(z.iso.date());
        } else if (format23 === "time") {
          stringSchema = stringSchema.check(z.iso.time());
        } else if (format23 === "duration") {
          stringSchema = stringSchema.check(z.iso.duration());
        } else if (format23 === "ipv4") {
          stringSchema = stringSchema.check(z.ipv4());
        } else if (format23 === "ipv6") {
          stringSchema = stringSchema.check(z.ipv6());
        } else if (format23 === "mac") {
          stringSchema = stringSchema.check(z.mac());
        } else if (format23 === "cidr") {
          stringSchema = stringSchema.check(z.cidrv4());
        } else if (format23 === "cidr-v6") {
          stringSchema = stringSchema.check(z.cidrv6());
        } else if (format23 === "base64") {
          stringSchema = stringSchema.check(z.base64());
        } else if (format23 === "base64url") {
          stringSchema = stringSchema.check(z.base64url());
        } else if (format23 === "e164") {
          stringSchema = stringSchema.check(z.e164());
        } else if (format23 === "jwt") {
          stringSchema = stringSchema.check(z.jwt());
        } else if (format23 === "emoji") {
          stringSchema = stringSchema.check(z.emoji());
        } else if (format23 === "nanoid") {
          stringSchema = stringSchema.check(z.nanoid());
        } else if (format23 === "cuid") {
          stringSchema = stringSchema.check(z.cuid());
        } else if (format23 === "cuid2") {
          stringSchema = stringSchema.check(z.cuid2());
        } else if (format23 === "ulid") {
          stringSchema = stringSchema.check(z.ulid());
        } else if (format23 === "xid") {
          stringSchema = stringSchema.check(z.xid());
        } else if (format23 === "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 = type === "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: ${type}`);
  }
  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 options = schema.anyOf.map((s) => convertSchema(s, ctx));
    const anyOfUnion = z.union(options);
    baseSchema = hasExplicitType ? z.intersection(baseSchema, anyOfUnion) : anyOfUnion;
  }
  if (schema.oneOf && Array.isArray(schema.oneOf)) {
    const options = schema.oneOf.map((s) => convertSchema(s, ctx));
    const oneOfUnion = z.xor(options);
    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 version22 = detectVersion(normalized, params?.defaultTarget);
  const defs = normalized.$defs || normalized.definitions || {};
  const ctx = {
    version: version22,
    defs,
    refs: /* @__PURE__ */ new Map(),
    processing: /* @__PURE__ */ new Set(),
    rootSchema: normalized,
    registry: params?.registry ?? globalRegistry
  };
  return convertSchema(normalized, ctx);
}
__name(fromJSONSchema, "fromJSONSchema");
var coerce_exports = {};
__export2(coerce_exports, {
  bigint: () => bigint3,
  boolean: () => boolean3,
  date: () => date4,
  number: () => number3,
  string: () => string3
});
function string3(params) {
  return /* @__PURE__ */ _coercedString(ZodString, params);
}
__name(string3, "string");
function number3(params) {
  return /* @__PURE__ */ _coercedNumber(ZodNumber, params);
}
__name(number3, "number");
function boolean3(params) {
  return /* @__PURE__ */ _coercedBoolean(ZodBoolean, params);
}
__name(boolean3, "boolean");
function bigint3(params) {
  return /* @__PURE__ */ _coercedBigint(ZodBigInt, params);
}
__name(bigint3, "bigint");
function date4(params) {
  return /* @__PURE__ */ _coercedDate(ZodDate, params);
}
__name(date4, "date");
config(en_default());
var SENSITIVE_STEP_OUTPUT = "output";
var MAX_WORKFLOW_NAME_LENGTH = 64;
var ALLOWED_STRING_ID_PATTERN = "^[a-zA-Z0-9_][a-zA-Z0-9-_]*$";
var ALLOWED_WORKFLOW_INSTANCE_ID_REGEX = new RegExp(
  ALLOWED_STRING_ID_PATTERN
);
var ALLOWED_WORKFLOW_NAME_REGEX = ALLOWED_WORKFLOW_INSTANCE_ID_REGEX;
function isValidWorkflowName(name) {
  if (typeof name !== "string") {
    return false;
  }
  if (name.length > MAX_WORKFLOW_NAME_LENGTH) {
    return false;
  }
  return ALLOWED_WORKFLOW_NAME_REGEX.test(name);
}
__name(isValidWorkflowName, "isValidWorkflowName");
external_exports.object({
  retries: external_exports.object({
    delay: external_exports.number().gte(0).or(external_exports.string()).or(external_exports.function()),
    limit: external_exports.number().gte(0),
    backoff: external_exports.enum(["constant", "linear", "exponential"]).optional()
  }).strict().optional(),
  timeout: external_exports.number().gte(0).or(external_exports.string()).optional(),
  sensitive: external_exports.literal(SENSITIVE_STEP_OUTPUT).optional()
}).strict();
function getBooleanEnvironmentVariableFactory(options) {
  return () => {
    if (!(options.variableName in process.env) || process.env[options.variableName] === void 0) {
      return typeof options.defaultValue === "function" ? options.defaultValue() : options.defaultValue;
    }
    switch (process.env[options.variableName]?.toLowerCase()) {
      case "true":
        return true;
      case "false":
        return false;
      default:
        throw new UserError(
          `Expected ${options.variableName} to be "true" or "false", but got ${JSON.stringify(
            process.env[options.variableName]
          )}`,
          { telemetryMessage: false }
        );
    }
  };
}
__name(getBooleanEnvironmentVariableFactory, "getBooleanEnvironmentVariableFactory");
function getEnvironmentVariableFactory({
  variableName,
  deprecatedName,
  choices,
  defaultValue
}) {
  let hasWarned = false;
  return () => {
    if (variableName in process.env) {
      return getProcessEnv(variableName, choices);
    }
    if (deprecatedName && deprecatedName in process.env) {
      if (!hasWarned) {
        hasWarned = true;
        console.warn(
          `Using "${deprecatedName}" environment variable. This is deprecated. Please use "${variableName}", instead.`
        );
      }
      return getProcessEnv(deprecatedName, choices);
    }
    return defaultValue?.();
  };
}
__name(getEnvironmentVariableFactory, "getEnvironmentVariableFactory");
function getProcessEnv(variableName, choices) {
  assertOneOf(choices, process.env[variableName]);
  return process.env[variableName];
}
__name(getProcessEnv, "getProcessEnv");
function assertOneOf(choices, value) {
  if (Array.isArray(choices) && !choices.includes(value)) {
    throw new UserError(
      `Expected ${JSON.stringify(value)} to be one of ${JSON.stringify(choices)}`,
      { telemetryMessage: false }
    );
  }
}
__name(assertOneOf, "assertOneOf");
var getC3CommandFromEnv = getEnvironmentVariableFactory({
  variableName: "WRANGLER_C3_COMMAND",
  defaultValue: /* @__PURE__ */ __name(() => "create cloudflare", "defaultValue")
});
var getDoNotTrackFromEnv = getEnvironmentVariableFactory({
  variableName: "DO_NOT_TRACK"
});
function isDoNotTrackEnabled() {
  const value = getDoNotTrackFromEnv()?.toLowerCase();
  return value === "1" || value === "true";
}
__name(isDoNotTrackEnabled, "isDoNotTrackEnabled");
var getWranglerSendMetricsVariableFromEnv = getBooleanEnvironmentVariableFactory({
  variableName: "WRANGLER_SEND_METRICS"
});
function getWranglerSendMetricsFromEnv() {
  if (isDoNotTrackEnabled()) {
    return false;
  }
  return getWranglerSendMetricsVariableFromEnv();
}
__name(getWranglerSendMetricsFromEnv, "getWranglerSendMetricsFromEnv");
var getNoSkillsUpdatePromptsFromEnv = getBooleanEnvironmentVariableFactory({
  variableName: "WRANGLER_NO_SKILLS_UPDATE_PROMPTS"
});
var getWranglerSendErrorReportsFromEnv = getBooleanEnvironmentVariableFactory({
  variableName: "WRANGLER_SEND_ERROR_REPORTS",
  defaultValue: false
});
var getCloudflareApiEnvironmentFromEnv = getEnvironmentVariableFactory(
  {
    variableName: "WRANGLER_API_ENVIRONMENT",
    defaultValue: /* @__PURE__ */ __name(() => "production", "defaultValue"),
    choices: ["production", "staging"]
  }
);
var getCloudflareComplianceRegionFromEnv = getEnvironmentVariableFactory({
  variableName: "CLOUDFLARE_COMPLIANCE_REGION",
  choices: ["public", "fedramp_high"]
});
var getCloudflareComplianceRegion = /* @__PURE__ */ __name((complianceConfig) => {
  const complianceRegionFromEnv = getCloudflareComplianceRegionFromEnv();
  if (complianceRegionFromEnv !== void 0 && complianceConfig?.compliance_region !== void 0 && complianceRegionFromEnv !== complianceConfig.compliance_region) {
    throw new UserError(
      dedent`
			The compliance region has been set to different values in two places:
			 - \`CLOUDFLARE_COMPLIANCE_REGION\` environment variable: \`${complianceRegionFromEnv}\`
			 - \`compliance_region\` configuration property: \`${complianceConfig.compliance_region}\`
			`,
      { telemetryMessage: false }
    );
  }
  return complianceRegionFromEnv || complianceConfig?.compliance_region || "public";
}, "getCloudflareComplianceRegion");
var getCloudflareApiBaseUrlFromEnv = getEnvironmentVariableFactory({
  variableName: "CLOUDFLARE_API_BASE_URL",
  deprecatedName: "CF_API_BASE_URL"
});
var getCloudflareApiBaseUrl = /* @__PURE__ */ __name((complianceConfig) => getCloudflareApiBaseUrlFromEnv() ?? `https://api${getComplianceRegionSubdomain(complianceConfig)}${getStagingSubdomain()}.cloudflare.com/client/v4`, "getCloudflareApiBaseUrl");
function getComplianceRegionSubdomain(complianceConfig) {
  return getCloudflareComplianceRegion(complianceConfig) === "fedramp_high" ? ".fed" : "";
}
__name(getComplianceRegionSubdomain, "getComplianceRegionSubdomain");
function getStagingSubdomain() {
  return getCloudflareApiEnvironmentFromEnv() === "staging" ? ".staging" : "";
}
__name(getStagingSubdomain, "getStagingSubdomain");
var getSanitizeLogs = getBooleanEnvironmentVariableFactory({
  variableName: "WRANGLER_LOG_SANITIZE",
  defaultValue: true
});
var getOutputFileDirectoryFromEnv = getEnvironmentVariableFactory({
  variableName: "WRANGLER_OUTPUT_FILE_DIRECTORY"
});
var getOutputFilePathFromEnv = getEnvironmentVariableFactory({
  variableName: "WRANGLER_OUTPUT_FILE_PATH"
});
var getCIMatchTag = getEnvironmentVariableFactory({
  variableName: "WRANGLER_CI_MATCH_TAG"
});
var getCIOverrideName = getEnvironmentVariableFactory({
  variableName: "WRANGLER_CI_OVERRIDE_NAME"
});
var getCIOverrideNetworkModeHost = getEnvironmentVariableFactory({
  variableName: "WRANGLER_CI_OVERRIDE_NETWORK_MODE_HOST"
});
var getCIGeneratePreviewAlias = getEnvironmentVariableFactory({
  variableName: "WRANGLER_CI_GENERATE_PREVIEW_ALIAS",
  defaultValue: /* @__PURE__ */ __name(() => "false", "defaultValue"),
  choices: ["true", "false"]
});
var getWorkersCIBranchName = getEnvironmentVariableFactory({
  variableName: "WORKERS_CI_BRANCH"
});
var getBuildConditionsFromEnv = getEnvironmentVariableFactory({
  variableName: "WRANGLER_BUILD_CONDITIONS"
});
var getBuildPlatformFromEnv = getEnvironmentVariableFactory({
  variableName: "WRANGLER_BUILD_PLATFORM"
});
var getRegistryPath = getEnvironmentVariableFactory({
  variableName: "WRANGLER_REGISTRY_PATH",
  defaultValue() {
    return import_node_path4.default.join(getGlobalConfigPath(), "registry");
  }
});
var getD1ExtraLocationChoices = getEnvironmentVariableFactory({
  variableName: "WRANGLER_D1_EXTRA_LOCATION_CHOICES"
});
var getDockerPath = getEnvironmentVariableFactory({
  variableName: "WRANGLER_DOCKER_BIN",
  defaultValue() {
    return "docker";
  }
});
var getSubdomainMixedStateCheckDisabled = getBooleanEnvironmentVariableFactory({
  variableName: "WRANGLER_DISABLE_SUBDOMAIN_MIXED_STATE_CHECK",
  defaultValue: false
});
var getCloudflareLoadDevVarsFromDotEnv = getBooleanEnvironmentVariableFactory({
  variableName: "CLOUDFLARE_LOAD_DEV_VARS_FROM_DOT_ENV",
  defaultValue: true
});
var getCloudflareIncludeProcessEnvFromEnv = getBooleanEnvironmentVariableFactory({
  variableName: "CLOUDFLARE_INCLUDE_PROCESS_ENV",
  defaultValue: false
});
var getTraceHeader = getEnvironmentVariableFactory({
  variableName: "WRANGLER_TRACE_ID"
});
var getDisableConfigWatching = getBooleanEnvironmentVariableFactory({
  variableName: "WRANGLER_CI_DISABLE_CONFIG_WATCHING",
  defaultValue: false
});
var getWranglerHideBanner = getBooleanEnvironmentVariableFactory({
  variableName: "WRANGLER_HIDE_BANNER",
  defaultValue: false
});
var getCloudflareEnv = getEnvironmentVariableFactory({
  variableName: "CLOUDFLARE_ENV"
});
var getOpenNextDeployFromEnv = getEnvironmentVariableFactory({
  variableName: "OPEN_NEXT_DEPLOY"
});
var getLocalExplorerEnabledFromEnv = getBooleanEnvironmentVariableFactory({
  variableName: "X_LOCAL_EXPLORER",
  defaultValue: true
});
var getLocalObservabilityEnabledFromEnv = getBooleanEnvironmentVariableFactory({
  variableName: "X_LOCAL_OBSERVABILITY",
  defaultValue: true
});
var getBrowserRenderingHeadfulFromEnv = getBooleanEnvironmentVariableFactory({
  variableName: "X_BROWSER_HEADFUL",
  defaultValue: false
});
var getCfFetchEnabledFromEnv = getBooleanEnvironmentVariableFactory({
  variableName: "CLOUDFLARE_CF_FETCH_ENABLED",
  defaultValue: true
});
var getCfFetchPathFromEnv = getEnvironmentVariableFactory({
  variableName: "CLOUDFLARE_CF_FETCH_PATH"
});
var getWranglerCacheDirFromEnv = getEnvironmentVariableFactory({
  variableName: "WRANGLER_CACHE_DIR"
});
var getCloudflaredPathFromEnv = getEnvironmentVariableFactory({
  variableName: "CLOUDFLARED_PATH"
});
var Diagnostics = class {
  /**
   * Create a new Diagnostics object.
   * @param description A general description of this collection of messages.
   */
  constructor(description) {
    this.description = description;
  }
  static {
    __name(this, "Diagnostics");
  }
  errors = [];
  warnings = [];
  children = [];
  /** Set to true when an unexpected/unknown field is encountered during validation. */
  hasUnexpectedFields = false;
  /**
   * Merge the given `diagnostics` into this as a child.
   */
  addChild(diagnostics) {
    if (diagnostics.hasErrors() || diagnostics.hasWarnings()) {
      this.children.push(diagnostics);
    }
  }
  /** Does this or any of its children have errors. */
  hasErrors() {
    if (this.errors.length > 0) {
      return true;
    } else {
      return this.children.some((child) => child.hasErrors());
    }
  }
  /** Does this or any of its children have unexpected fields. */
  hasUnexpectedFieldsInTree() {
    if (this.hasUnexpectedFields) {
      return true;
    } else {
      return this.children.some((child) => child.hasUnexpectedFieldsInTree());
    }
  }
  /** Render the errors of this and all its children. */
  renderErrors() {
    return this.render("errors");
  }
  /** Does this or any of its children have warnings. */
  hasWarnings() {
    if (this.warnings.length > 0) {
      return true;
    } else {
      return this.children.some((child) => child.hasWarnings());
    }
  }
  /** Render the warnings of this and all its children. */
  renderWarnings() {
    return this.render("warnings");
  }
  render(field) {
    const hasMethod = field === "errors" ? "hasErrors" : "hasWarnings";
    return indentText(
      `${this.description}
` + // Output all the fields (errors or warnings) at this level
      this[field].map((message) => `- ${indentText(message)}`).join("\n") + // Output all the child diagnostics at the next level
      this.children.map(
        (child) => child[hasMethod]() ? "\n- " + child.render(field) : ""
      ).filter((output) => output !== "").join("\n")
    );
  }
};
function indentText(str) {
  return str.split("\n").map(
    (line, index) => (index === 0 ? line : `  ${line}`).replace(/^\s*$/, "")
  ).join("\n");
}
__name(indentText, "indentText");
function deprecated(diagnostics, config22, fieldPath, message, remove, title = "Deprecation", type = "warning") {
  const BOLD = "\x1B[1m";
  const NORMAL = "\x1B[0m";
  const diagnosticMessage = `${BOLD}${title}${NORMAL}: "${fieldPath}":
${message}`;
  const result = unwindPropertyPath(config22, fieldPath);
  if (result !== void 0 && result.field in result.container) {
    diagnostics[`${type}s`].push(diagnosticMessage);
    if (remove) {
      delete result.container[result.field];
    }
  }
}
__name(deprecated, "deprecated");
function experimental(diagnostics, config22, fieldPath) {
  const result = unwindPropertyPath(config22, fieldPath);
  if (result !== void 0 && result.field in result.container && !("WRANGLER_DISABLE_EXPERIMENTAL_WARNING" in process.env)) {
    diagnostics.warnings.push(
      `"${fieldPath}" fields are experimental and may change or break at any time.`
    );
  }
}
__name(experimental, "experimental");
function inheritable(diagnostics, topLevelEnv, rawEnv, field, validate2, defaultValue, transformFn = (v) => v) {
  validate2(diagnostics, field, rawEnv[field], topLevelEnv);
  return (
    // `rawEnv === topLevelEnv` is a special case where the user has provided an environment name
    // but that named environment is not actually defined in the configuration.
    // In that case we have reused the topLevelEnv as the rawEnv,
    // and so we need to process the `transformFn()` anyway rather than just using the field in the `rawEnv`.
    (rawEnv !== topLevelEnv ? rawEnv[field] : void 0) ?? transformFn(topLevelEnv?.[field]) ?? defaultValue
  );
}
__name(inheritable, "inheritable");
var appendEnvName = /* @__PURE__ */ __name((envName) => (fieldValue) => fieldValue ? `${fieldValue}-${envName}` : void 0, "appendEnvName");
function notInheritable(diagnostics, topLevelEnv, rawConfig, rawEnv, envName, field, validate2, defaultValue) {
  if (rawEnv[field] !== void 0) {
    validate2(diagnostics, field, rawEnv[field], topLevelEnv);
  } else {
    if (rawConfig?.[field] !== void 0) {
      diagnostics.warnings.push(
        `"${field}" exists at the top level, but not on "env.${envName}".
This is not what you probably want, since "${field}" is not inherited by environments.
Please add "${field}" to "env.${envName}".`
      );
    }
  }
  return rawEnv[field] ?? defaultValue;
}
__name(notInheritable, "notInheritable");
function unwindPropertyPath(root, path610) {
  let container = root;
  const parts = path610.split(".");
  for (let i = 0; i < parts.length - 1; i++) {
    if (!hasProperty(container, parts[i])) {
      return;
    }
    container = container[parts[i]];
  }
  return { container, field: parts[parts.length - 1] };
}
__name(unwindPropertyPath, "unwindPropertyPath");
var isString = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (value !== void 0 && typeof value !== "string") {
    diagnostics.errors.push(
      `Expected "${field}" to be of type string but got ${JSON.stringify(
        value
      )}.`
    );
    return false;
  }
  return true;
}, "isString");
var isValidName = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (typeof value === "string" && /^$|^[a-z0-9_][a-z0-9-_]*$/.test(value) || value === void 0) {
    return true;
  } else {
    diagnostics.errors.push(
      `Expected "${field}" to be of type string, alphanumeric and lowercase with dashes only but got ${JSON.stringify(
        value
      )}.`
    );
    return false;
  }
}, "isValidName");
var isValidDateTimeStringFormat = /* @__PURE__ */ __name((diagnostics, field, value) => {
  let isValid = true;
  if (value.includes("\u2013") || // en-dash
  value.includes("\u2014")) {
    diagnostics.errors.push(
      `"${field}" field should use ISO-8601 accepted hyphens (-) rather than en-dashes (\u2013) or em-dashes (\u2014).`
    );
    isValid = false;
  }
  const data = new Date(value.replaceAll(/–|—/g, "-"));
  if (isNaN(data.getTime())) {
    diagnostics.errors.push(
      `"${field}" field should be a valid ISO-8601 date (YYYY-MM-DD), but got ${JSON.stringify(value)}.`
    );
    isValid = false;
  }
  return isValid;
}, "isValidDateTimeStringFormat");
var isStringArray = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (value !== void 0 && (!Array.isArray(value) || value.some((item) => typeof item !== "string"))) {
    diagnostics.errors.push(
      `Expected "${field}" to be of type string array but got ${JSON.stringify(
        value
      )}.`
    );
    return false;
  }
  return true;
}, "isStringArray");
var isOneOf = /* @__PURE__ */ __name((...choices) => (diagnostics, field, value) => {
  if (value !== void 0 && !choices.some((choice) => value === choice)) {
    diagnostics.errors.push(
      `Expected "${field}" field to be one of ${JSON.stringify(
        choices
      )} but got ${JSON.stringify(value)}.`
    );
    return false;
  }
  return true;
}, "isOneOf");
var all = /* @__PURE__ */ __name((...validations) => {
  return (diagnostics, field, value, config22) => {
    let passedValidations = true;
    for (const validate2 of validations) {
      if (!validate2(diagnostics, field, value, config22)) {
        passedValidations = false;
      }
    }
    return passedValidations;
  };
}, "all");
var isMutuallyExclusiveWith = /* @__PURE__ */ __name((container, ...fields) => {
  return (diagnostics, field, value) => {
    if (value === void 0) {
      return true;
    }
    for (const exclusiveWith of fields) {
      if (container[exclusiveWith] !== void 0) {
        diagnostics.errors.push(
          `Expected exactly one of the following fields ${JSON.stringify([
            field,
            ...fields
          ])}.`
        );
        return false;
      }
    }
    return true;
  };
}, "isMutuallyExclusiveWith");
var isBoolean = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (value !== void 0 && typeof value !== "boolean") {
    diagnostics.errors.push(
      `Expected "${field}" to be of type boolean but got ${JSON.stringify(
        value
      )}.`
    );
    return false;
  }
  return true;
}, "isBoolean");
var validateRequiredProperty = /* @__PURE__ */ __name((diagnostics, container, key, value, type, choices) => {
  if (container) {
    container += ".";
  }
  if (value === void 0) {
    diagnostics.errors.push(`"${container}${key}" is a required field.`);
    return false;
  } else if (typeof value !== type) {
    diagnostics.errors.push(
      `Expected "${container}${key}" to be of type ${type} but got ${JSON.stringify(
        value
      )}.`
    );
    return false;
  } else if (choices) {
    if (!isOneOf(...choices)(diagnostics, `${container}${key}`, value, void 0)) {
      return false;
    }
  }
  return true;
}, "validateRequiredProperty");
var validateAtLeastOnePropertyRequired = /* @__PURE__ */ __name((diagnostics, container, properties) => {
  const containerPath = container ? `${container}.` : "";
  if (properties.every((property) => property.value === void 0)) {
    diagnostics.errors.push(
      `${properties.map(({ key }) => `"${containerPath}${key}"`).join(" or ")} is required.`
    );
    return false;
  }
  const errors = [];
  for (const prop of properties) {
    if (typeof prop.value === prop.type) {
      return true;
    }
    errors.push(
      `Expected "${containerPath}${prop.key}" to be of type ${prop.type} but got ${JSON.stringify(
        prop.value
      )}.`
    );
  }
  diagnostics.errors.push(...errors);
  return false;
}, "validateAtLeastOnePropertyRequired");
var validateOptionalProperty = /* @__PURE__ */ __name((diagnostics, container, key, value, type, choices) => {
  if (value !== void 0) {
    return validateRequiredProperty(
      diagnostics,
      container,
      key,
      value,
      type,
      choices
    );
  }
  return true;
}, "validateOptionalProperty");
var validateTypedArray = /* @__PURE__ */ __name((diagnostics, container, value, type) => {
  let isValid = true;
  if (!Array.isArray(value)) {
    diagnostics.errors.push(
      `Expected "${container}" to be an array of ${type}s but got ${JSON.stringify(
        value
      )}`
    );
    isValid = false;
  } else {
    for (let i = 0; i < value.length; i++) {
      isValid = validateRequiredProperty(
        diagnostics,
        container,
        `[${i}]`,
        value[i],
        type
      ) && isValid;
    }
  }
  return isValid;
}, "validateTypedArray");
var validateOptionalTypedArray = /* @__PURE__ */ __name((diagnostics, container, value, type) => {
  if (value !== void 0) {
    return validateTypedArray(diagnostics, container, value, type);
  }
  return true;
}, "validateOptionalTypedArray");
var isRequiredProperty = /* @__PURE__ */ __name((target, property, type, choices) => hasProperty(target, property) && typeof target[property] === type && (choices === void 0 || choices.includes(target[property])), "isRequiredProperty");
var isOptionalProperty = /* @__PURE__ */ __name((target, property, type) => !hasProperty(target, property) || typeof target[property] === type, "isOptionalProperty");
var hasProperty = /* @__PURE__ */ __name((target, property) => property in target, "hasProperty");
var validateAdditionalProperties = /* @__PURE__ */ __name((diagnostics, fieldPath, restProps, knownProps) => {
  const restPropSet = new Set(restProps);
  for (const knownProp of knownProps) {
    restPropSet.delete(knownProp);
  }
  if (restPropSet.size > 0) {
    const fields = Array.from(restPropSet.keys()).map((field) => `"${field}"`);
    diagnostics.warnings.push(
      `Unexpected fields found in ${fieldPath} field: ${fields}`
    );
    diagnostics.hasUnexpectedFields = true;
    return false;
  }
  return true;
}, "validateAdditionalProperties");
var getBindingNames = /* @__PURE__ */ __name((value) => {
  if (typeof value !== "object" || value === null) {
    return [];
  }
  if (isBindingList(value)) {
    return value.bindings.map(({ name }) => name);
  } else if (isNamespaceList(value)) {
    return value.map(({ binding }) => binding);
  } else if (isRecord(value)) {
    if (value["binding"] !== void 0) {
      return [value["binding"]];
    }
    return Object.keys(value).filter((k) => value[k] !== void 0);
  } else {
    return [];
  }
}, "getBindingNames");
var isBindingList = /* @__PURE__ */ __name((value) => isRecord(value) && "bindings" in value && Array.isArray(value.bindings) && value.bindings.every(
  (binding) => isRecord(binding) && "name" in binding && typeof binding.name === "string"
), "isBindingList");
var isNamespaceList = /* @__PURE__ */ __name((value) => Array.isArray(value) && value.every(
  (entry) => isRecord(entry) && "binding" in entry && typeof entry.binding === "string"
), "isNamespaceList");
var isRecord = /* @__PURE__ */ __name((value) => typeof value === "object" && value !== null && !Array.isArray(value), "isRecord");
var validateUniqueNameProperty = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (Array.isArray(value)) {
    const nameCount = /* @__PURE__ */ new Map();
    Object.entries(value).forEach(([_, entry]) => {
      nameCount.set(entry.name, (nameCount.get(entry.name) ?? 0) + 1);
    });
    const duplicates = Array.from(nameCount.entries()).filter(([_, count]) => count > 1).map(([name]) => name);
    if (duplicates.length > 0) {
      const list = duplicates.join('", "');
      diagnostics.errors.push(
        `"${field}" bindings must have unique "name" values; duplicate(s) found: "${list}"`
      );
      return false;
    }
  }
  return true;
}, "validateUniqueNameProperty");
function isValidR2BucketName(name) {
  return typeof name === "string" && /^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/.test(name);
}
__name(isValidR2BucketName, "isValidR2BucketName");
var bucketFormatMessage = `Bucket names must begin and end with an alphanumeric character, only contain lowercase letters, numbers, and hyphens, and be between 3 and 63 characters long.`;
var friendlyBindingNames = {
  data_blobs: "Data Blob",
  durable_objects: "Durable Object",
  kv_namespaces: "KV Namespace",
  send_email: "Send Email",
  queues: "Queue",
  d1_databases: "D1 Database",
  vectorize: "Vectorize Index",
  ai_search_namespaces: "AI Search Namespace",
  ai_search: "AI Search Instance",
  websearch: "Web Search",
  agent_memory: "Agent Memory",
  hyperdrive: "Hyperdrive Config",
  r2_buckets: "R2 Bucket",
  logfwdr: "logfwdr",
  services: "Worker",
  analytics_engine_datasets: "Analytics Engine Dataset",
  text_blobs: "Text Blob",
  browser: "Browser Run",
  ai: "AI",
  images: "Images",
  stream: "Stream",
  media: "Media",
  version_metadata: "Worker Version Metadata",
  unsafe: "Unsafe Metadata",
  vars: "Environment Variable",
  wasm_modules: "Wasm Module",
  dispatch_namespaces: "Dispatch Namespace",
  mtls_certificates: "mTLS Certificate",
  workflows: "Workflow",
  pipelines: "Pipeline",
  secrets_store_secrets: "Secrets Store Secret",
  artifacts: "Artifacts",
  ratelimits: "Rate Limit",
  assets: "Assets",
  unsafe_hello_world: "Hello World",
  flagship: "Flagship",
  worker_loaders: "Worker Loader",
  vpc_services: "VPC Service",
  vpc_networks: "VPC Network"
};
var bindingTypeFriendlyNames = {
  // The 3 binding types below are all rendered as "Environment Variable" to preserve existing behaviour (friendlyBindingNames.vars)
  plain_text: "Environment Variable",
  secret_text: "Environment Variable",
  json: "Environment Variable",
  kv_namespace: "KV Namespace",
  send_email: "Send Email",
  wasm_module: "Wasm Module",
  text_blob: "Text Blob",
  browser: "Browser Run",
  ai: "AI",
  images: "Images",
  stream: "Stream",
  version_metadata: "Worker Version Metadata",
  data_blob: "Data Blob",
  durable_object_namespace: "Durable Object",
  workflow: "Workflow",
  queue: "Queue",
  r2_bucket: "R2 Bucket",
  d1: "D1 Database",
  vectorize: "Vectorize Index",
  ai_search_namespace: "AI Search Namespace",
  ai_search: "AI Search Instance",
  websearch: "Web Search",
  agent_memory: "Agent Memory",
  hyperdrive: "Hyperdrive Config",
  service: "Worker",
  fetcher: "Service Binding",
  analytics_engine: "Analytics Engine Dataset",
  dispatch_namespace: "Dispatch Namespace",
  mtls_certificate: "mTLS Certificate",
  pipeline: "Pipeline",
  secrets_store_secret: "Secrets Store Secret",
  artifacts: "Artifacts",
  logfwdr: "logfwdr",
  unsafe_hello_world: "Hello World",
  flagship: "Flagship",
  ratelimit: "Rate Limit",
  worker_loader: "Worker Loader",
  vpc_service: "VPC Service",
  vpc_network: "VPC Network",
  media: "Media",
  assets: "Assets",
  inherit: "Inherited"
};
function getBindingTypeFriendlyName(bindingType) {
  if (bindingType in bindingTypeFriendlyNames) {
    return bindingTypeFriendlyNames[bindingType];
  }
  if (bindingType.startsWith("unsafe_")) {
    return "Unsafe Metadata";
  }
  return bindingType;
}
__name(getBindingTypeFriendlyName, "getBindingTypeFriendlyName");
var ENGLISH = new Intl.ListFormat("en-US");
var ALLOWED_INSTANCE_TYPES = [
  "lite",
  "basic",
  "standard-1",
  "standard-2",
  "standard-3",
  "standard-4",
  "dev",
  // legacy
  "standard"
  // legacy
];
function isPagesConfig(rawConfig) {
  return rawConfig.pages_build_output_dir !== void 0;
}
__name(isPagesConfig, "isPagesConfig");
function normalizeAndValidateConfig(rawConfig, configPath, userConfigPath, args, preserveOriginalMain = false) {
  const diagnostics = new Diagnostics(
    `Processing ${configPath ? import_node_path4.default.relative(process.cwd(), configPath) : "wrangler"} configuration:`
  );
  const isRedirectedConfig22 = isRedirectedRawConfig(
    rawConfig,
    configPath,
    userConfigPath
  );
  if ("legacy_env" in rawConfig) {
    if (!isRedirectedConfig22) {
      diagnostics.errors.push(
        dedent`
					The "legacy_env" field is no longer supported, so please remove it from your configuration file.
					Service environments have been removed, and each environment is now deployed as its own Worker named "<name>-<environment>". This matches the behaviour of "legacy_env = true", which was the default, so removing the field will not change how your Worker is deployed.
					Refer to https://developers.cloudflare.com/workers/wrangler/environments/ for more information.
				`
      );
    }
    delete rawConfig.legacy_env;
  }
  validateOptionalProperty(
    diagnostics,
    "",
    "send_metrics",
    rawConfig.send_metrics,
    "boolean"
  );
  if (validateOptionalProperty(
    diagnostics,
    "",
    "dependencies_instrumentation",
    rawConfig.dependencies_instrumentation,
    "object"
  )) {
    if (typeof rawConfig.dependencies_instrumentation === "object") {
      validateOptionalProperty(
        diagnostics,
        "dependencies_instrumentation",
        "enabled",
        rawConfig.dependencies_instrumentation.enabled,
        "boolean"
      );
      validateOptionalTypedArray(
        diagnostics,
        "dependencies_instrumentation.exclude_packages",
        rawConfig.dependencies_instrumentation.exclude_packages,
        "string"
      );
      validateAdditionalProperties(
        diagnostics,
        "dependencies_instrumentation",
        Object.keys(
          rawConfig.dependencies_instrumentation
        ),
        ["enabled", "exclude_packages"]
      );
    }
  }
  validateOptionalProperty(
    diagnostics,
    "",
    "keep_vars",
    rawConfig.keep_vars,
    "boolean"
  );
  validateOptionalTypedArray(
    diagnostics,
    "addresses",
    rawConfig.addresses,
    "string"
  );
  validateOptionalProperty(
    diagnostics,
    "",
    "pages_build_output_dir",
    rawConfig.pages_build_output_dir,
    "string"
  );
  validateOptionalProperty(
    diagnostics,
    "",
    "$schema",
    rawConfig.$schema,
    "string"
  );
  const isDispatchNamespace = typeof args["dispatch-namespace"] === "string" && args["dispatch-namespace"].trim() !== "";
  const topLevelEnv = normalizeAndValidateEnvironment(
    diagnostics,
    configPath,
    rawConfig,
    isDispatchNamespace,
    preserveOriginalMain
  );
  const definedEnvironments = Object.keys(rawConfig.env ?? {});
  if (isRedirectedConfig22 && definedEnvironments.length > 0) {
    diagnostics.errors.push(
      dedent`
				Redirected configurations cannot include environments but the following have been found:\n${definedEnvironments.map((env3) => `	- ${env3}`).join("\n")}


				Such configurations are generated by tools, meaning that one of the tools
				your application is using is generating the incorrect configuration.
				Report this issue to the tool's author so that this can be fixed there.
				`
    );
  }
  const envName = args.env ?? getCloudflareEnv();
  (0, import_node_assert.default)(envName === void 0 || typeof envName === "string");
  let activeEnv = topLevelEnv;
  if (envName) {
    if (isRedirectedConfig22) {
      if (!isPagesConfig(rawConfig) && rawConfig.targetEnvironment && rawConfig.targetEnvironment !== envName) {
        const via = args.env !== void 0 ? "via the `--env/-e` CLI argument" : "via the CLOUDFLARE_ENV environment variable";
        throw new Error(dedent`
					You have specified the environment "${envName}" ${via}.
					This does not match the target environment "${rawConfig.targetEnvironment}" that was used when building the application.
					Perhaps you need to re-run the custom build of the project with "${envName}" as the selected environment?
				`);
      }
    } else {
      const envDiagnostics = new Diagnostics(
        `"env.${envName}" environment configuration`
      );
      const rawEnv = rawConfig.env?.[envName];
      if (rawEnv !== void 0) {
        activeEnv = normalizeAndValidateEnvironment(
          envDiagnostics,
          configPath,
          rawEnv,
          isDispatchNamespace,
          preserveOriginalMain,
          envName,
          topLevelEnv,
          rawConfig
        );
        diagnostics.addChild(envDiagnostics);
      } else if (!isPagesConfig(rawConfig)) {
        activeEnv = normalizeAndValidateEnvironment(
          envDiagnostics,
          configPath,
          topLevelEnv,
          // in this case reuse the topLevelEnv to ensure that nonInherited fields are not removed
          isDispatchNamespace,
          preserveOriginalMain,
          envName,
          topLevelEnv,
          rawConfig
        );
        const envNames = rawConfig.env ? `The available configured environment names are: ${JSON.stringify(
          Object.keys(rawConfig.env)
        )}
` : "";
        const message = `No environment found in configuration with name "${envName}".
Before using \`--env=${envName}\` there should be an equivalent environment section in the configuration.
${envNames}
Consider adding an environment configuration section to the ${configFileName(configPath)} file:
\`\`\`
[env.` + envName + "]\n```\n";
        if (envNames.length > 0) {
          diagnostics.errors.push(message);
        } else {
          diagnostics.warnings.push(message);
        }
      }
    }
  }
  const config22 = {
    configPath,
    userConfigPath,
    topLevelName: isRedirectedConfig22 ? rawConfig.topLevelName : rawConfig.name,
    definedEnvironments: isRedirectedConfig22 ? rawConfig.definedEnvironments : definedEnvironments,
    targetEnvironment: isRedirectedConfig22 ? rawConfig.targetEnvironment : envName,
    pages_build_output_dir: normalizeAndValidatePagesBuildOutputDir(
      configPath,
      rawConfig.pages_build_output_dir
    ),
    send_metrics: rawConfig.send_metrics,
    dependencies_instrumentation: rawConfig.dependencies_instrumentation,
    keep_vars: rawConfig.keep_vars,
    addresses: rawConfig.addresses,
    ...activeEnv,
    dev: normalizeAndValidateDev(diagnostics, rawConfig.dev ?? {}, args),
    site: normalizeAndValidateSite(
      diagnostics,
      configPath,
      rawConfig,
      activeEnv.main
    ),
    alias: normalizeAndValidateAliases(diagnostics, configPath, rawConfig),
    wasm_modules: normalizeAndValidateModulePaths(
      diagnostics,
      configPath,
      "wasm_modules",
      rawConfig.wasm_modules
    ),
    text_blobs: normalizeAndValidateModulePaths(
      diagnostics,
      configPath,
      "text_blobs",
      rawConfig.text_blobs
    ),
    data_blobs: normalizeAndValidateModulePaths(
      diagnostics,
      configPath,
      "data_blobs",
      rawConfig.data_blobs
    )
  };
  validateBindingsHaveUniqueNames(diagnostics, config22);
  validateAdditionalProperties(
    diagnostics,
    "top-level",
    Object.keys(rawConfig),
    [...Object.keys(config22), "env", "$schema"]
  );
  applyPythonConfig(config22, args);
  return { config: config22, diagnostics };
}
__name(normalizeAndValidateConfig, "normalizeAndValidateConfig");
function applyPythonConfig(config22, args) {
  const mainModule = args.script ?? config22.main;
  if (typeof mainModule === "string" && mainModule.endsWith(".py")) {
    config22.no_bundle = true;
    if (!config22.rules.some((rule) => rule.type === "PythonModule")) {
      config22.rules.push({ type: "PythonModule", globs: ["**/*.py"] });
    }
    if (!config22.compatibility_flags.includes("python_workers")) {
      throw new UserError(
        "The `python_workers` compatibility flag is required to use Python.",
        { telemetryMessage: false }
      );
    }
  }
}
__name(applyPythonConfig, "applyPythonConfig");
function normalizeAndValidateBuild(diagnostics, rawEnv, rawBuild, configPath) {
  const { command, cwd: cwd2, watch_dir = "./src", ...rest } = rawBuild;
  validateAdditionalProperties(diagnostics, "build", Object.keys(rest), []);
  validateOptionalProperty(diagnostics, "build", "command", command, "string");
  validateOptionalProperty(diagnostics, "build", "cwd", cwd2, "string");
  if (Array.isArray(watch_dir)) {
    validateTypedArray(diagnostics, "build.watch_dir", watch_dir, "string");
  } else {
    validateOptionalProperty(
      diagnostics,
      "build",
      "watch_dir",
      watch_dir,
      "string"
    );
  }
  return {
    command,
    watch_dir: (
      // - `watch_dir` only matters when `command` is defined, so we apply
      // a default only when `command` is defined
      // - `configPath` will always be defined since `build` can only
      // be configured in the Wrangler configuration file, but who knows, that may
      // change in the future, so we do a check anyway
      command && configPath ? Array.isArray(watch_dir) ? watch_dir.map(
        (dir22) => import_node_path4.default.relative(
          process.cwd(),
          import_node_path4.default.join(import_node_path4.default.dirname(configPath), `${dir22}`)
        )
      ) : import_node_path4.default.relative(
        process.cwd(),
        import_node_path4.default.join(import_node_path4.default.dirname(configPath), `${watch_dir}`)
      ) : watch_dir
    ),
    cwd: cwd2
  };
}
__name(normalizeAndValidateBuild, "normalizeAndValidateBuild");
function normalizeAndValidateMainField(configPath, rawMain) {
  const configDir = import_node_path4.default.dirname(configPath ?? "wrangler.toml");
  if (rawMain !== void 0) {
    if (typeof rawMain === "string") {
      const directory = import_node_path4.default.resolve(configDir);
      return import_node_path4.default.resolve(directory, rawMain);
    } else {
      return rawMain;
    }
  } else {
    return;
  }
}
__name(normalizeAndValidateMainField, "normalizeAndValidateMainField");
function normalizeAndValidateBaseDirField(configPath, rawDir) {
  const configDir = import_node_path4.default.dirname(configPath ?? "wrangler.toml");
  if (rawDir !== void 0) {
    if (typeof rawDir === "string") {
      const directory = import_node_path4.default.resolve(configDir);
      return import_node_path4.default.resolve(directory, rawDir);
    } else {
      return rawDir;
    }
  } else {
    return;
  }
}
__name(normalizeAndValidateBaseDirField, "normalizeAndValidateBaseDirField");
function normalizeAndValidatePagesBuildOutputDir(configPath, rawPagesDir) {
  const configDir = import_node_path4.default.dirname(configPath ?? "wrangler.toml");
  if (rawPagesDir !== void 0) {
    if (typeof rawPagesDir === "string") {
      const directory = import_node_path4.default.resolve(configDir);
      return import_node_path4.default.resolve(directory, rawPagesDir);
    } else {
      return rawPagesDir;
    }
  } else {
    return;
  }
}
__name(normalizeAndValidatePagesBuildOutputDir, "normalizeAndValidatePagesBuildOutputDir");
function normalizeAndValidateDev(diagnostics, rawDev, args) {
  (0, import_node_assert.default)(typeof args === "object" && args !== null && !Array.isArray(args));
  const {
    localProtocol: localProtocolArg,
    upstreamProtocol: upstreamProtocolArg,
    remote: remoteArg,
    enableContainers: enableContainersArg,
    generateTypes: generateTypesArg
  } = args;
  (0, import_node_assert.default)(
    localProtocolArg === void 0 || localProtocolArg === "http" || localProtocolArg === "https"
  );
  (0, import_node_assert.default)(
    upstreamProtocolArg === void 0 || upstreamProtocolArg === "http" || upstreamProtocolArg === "https"
  );
  (0, import_node_assert.default)(remoteArg === void 0 || typeof remoteArg === "boolean");
  (0, import_node_assert.default)(
    enableContainersArg === void 0 || typeof enableContainersArg === "boolean"
  );
  (0, import_node_assert.default)(
    generateTypesArg === void 0 || typeof generateTypesArg === "boolean"
  );
  const {
    // On Windows, when specifying `localhost` as the socket hostname, `workerd`
    // will only listen on the IPv4 loopback `127.0.0.1`, not the IPv6 `::1`:
    // https://github.com/cloudflare/workerd/issues/1408
    // On Node 17+, `fetch()` will only try to fetch the IPv6 address.
    // For now, on Windows, we default to listening on IPv4 only and using
    // `127.0.0.1` when sending control requests to `workerd` (e.g. with the
    // `ProxyController`).
    ip = process.platform === "win32" ? "127.0.0.1" : "localhost",
    port,
    inspector_port,
    inspector_ip,
    local_protocol = localProtocolArg ?? "http",
    // In remote mode upstream_protocol must be https, otherwise it defaults to local_protocol.
    upstream_protocol = upstreamProtocolArg ?? remoteArg ? "https" : local_protocol,
    host,
    enable_containers = enableContainersArg ?? true,
    container_engine,
    generate_types = generateTypesArg ?? false,
    ...rest
  } = rawDev;
  validateAdditionalProperties(diagnostics, "dev", Object.keys(rest), []);
  validateOptionalProperty(diagnostics, "dev", "ip", ip, "string");
  validateOptionalProperty(diagnostics, "dev", "port", port, "number");
  validateOptionalProperty(
    diagnostics,
    "dev",
    "inspector_port",
    inspector_port,
    "number"
  );
  validateOptionalProperty(
    diagnostics,
    "dev",
    "inspector_ip",
    inspector_ip,
    "string"
  );
  validateOptionalProperty(
    diagnostics,
    "dev",
    "local_protocol",
    local_protocol,
    "string",
    ["http", "https"]
  );
  validateOptionalProperty(
    diagnostics,
    "dev",
    "upstream_protocol",
    upstream_protocol,
    "string",
    ["http", "https"]
  );
  validateOptionalProperty(diagnostics, "dev", "host", host, "string");
  validateOptionalProperty(
    diagnostics,
    "dev",
    "enable_containers",
    enable_containers,
    "boolean"
  );
  validateOptionalProperty(
    diagnostics,
    "dev",
    "container_engine",
    container_engine,
    "string"
  );
  validateOptionalProperty(
    diagnostics,
    "dev",
    "generate_types",
    generate_types,
    "boolean"
  );
  return {
    ip,
    port,
    inspector_port,
    inspector_ip,
    local_protocol,
    upstream_protocol,
    host,
    enable_containers,
    container_engine,
    generate_types
  };
}
__name(normalizeAndValidateDev, "normalizeAndValidateDev");
function normalizeAndValidateAssets(diagnostics, topLevelEnv, rawEnv) {
  return inheritable(
    diagnostics,
    topLevelEnv,
    rawEnv,
    "assets",
    validateAssetsConfig,
    void 0
  );
}
__name(normalizeAndValidateAssets, "normalizeAndValidateAssets");
function normalizeAndValidateSite(diagnostics, configPath, rawConfig, mainEntryPoint) {
  if (rawConfig?.site !== void 0) {
    const { bucket, include = [], exclude = [], ...rest } = rawConfig.site;
    validateAdditionalProperties(diagnostics, "site", Object.keys(rest), [
      "entry-point"
    ]);
    validateRequiredProperty(diagnostics, "site", "bucket", bucket, "string");
    validateTypedArray(diagnostics, "sites.include", include, "string");
    validateTypedArray(diagnostics, "sites.exclude", exclude, "string");
    const legacySiteEntryPoint = rawConfig.site["entry-point"];
    validateOptionalProperty(
      diagnostics,
      "site",
      "entry-point",
      legacySiteEntryPoint,
      "string"
    );
    deprecated(
      diagnostics,
      rawConfig,
      `site.entry-point`,
      `Delete the \`site.entry-point\` field, then add the top level \`main\` field to your configuration file:
\`\`\`
main = "${import_node_path4.default.join(
        String(legacySiteEntryPoint) || "workers-site",
        import_node_path4.default.extname(String(legacySiteEntryPoint) || "workers-site") ? "" : "index.js"
      )}"
\`\`\``,
      false,
      void 0,
      "warning"
    );
    let siteEntryPoint = legacySiteEntryPoint;
    if (!mainEntryPoint && !siteEntryPoint) {
      diagnostics.warnings.push(
        `Because you've defined a [site] configuration, we're defaulting to "workers-site" for the deprecated \`site.entry-point\`field.
Add the top level \`main\` field to your configuration file:
\`\`\`
main = "workers-site/index.js"
\`\`\``
      );
      siteEntryPoint = "workers-site";
    } else if (mainEntryPoint && siteEntryPoint) {
      diagnostics.errors.push(
        `Don't define both the \`main\` and \`site.entry-point\` fields in your configuration.
They serve the same purpose: to point to the entry-point of your worker.
Delete the deprecated \`site.entry-point\` field from your config.`
      );
    }
    if (configPath && siteEntryPoint) {
      siteEntryPoint = import_node_path4.default.relative(
        process.cwd(),
        import_node_path4.default.join(import_node_path4.default.dirname(configPath), siteEntryPoint)
      );
    }
    return {
      bucket,
      "entry-point": siteEntryPoint,
      include,
      exclude
    };
  }
  return void 0;
}
__name(normalizeAndValidateSite, "normalizeAndValidateSite");
function normalizeAndValidateAliases(diagnostics, configPath, rawConfig) {
  if (rawConfig?.alias === void 0) {
    return void 0;
  }
  if (["string", "boolean", "number"].includes(typeof rawConfig?.alias) || typeof rawConfig?.alias !== "object") {
    diagnostics.errors.push(
      `Expected alias to be an object, but got ${typeof rawConfig?.alias}`
    );
    return void 0;
  }
  let isValid = true;
  for (const [key, value] of Object.entries(rawConfig?.alias)) {
    if (typeof value !== "string") {
      diagnostics.errors.push(
        `Expected alias["${key}"] to be a string, but got ${typeof value}`
      );
      isValid = false;
    }
  }
  if (isValid) {
    return rawConfig.alias;
  }
  return;
}
__name(normalizeAndValidateAliases, "normalizeAndValidateAliases");
function normalizeAndValidateModulePaths(diagnostics, configPath, field, rawMapping) {
  if (rawMapping === void 0) {
    return void 0;
  }
  const mapping = {};
  for (const [name, filePath] of Object.entries(rawMapping)) {
    if (isString(diagnostics, `${field}['${name}']`, filePath, void 0)) {
      if (configPath) {
        mapping[name] = configPath ? import_node_path4.default.relative(
          process.cwd(),
          import_node_path4.default.join(import_node_path4.default.dirname(configPath), filePath)
        ) : filePath;
      }
    }
  }
  return mapping;
}
__name(normalizeAndValidateModulePaths, "normalizeAndValidateModulePaths");
function isValidRouteValue(item) {
  if (!item) {
    return false;
  }
  if (typeof item === "string") {
    return true;
  }
  if (typeof item === "object") {
    if (!hasProperty(item, "pattern") || typeof item.pattern !== "string") {
      return false;
    }
    const hasZoneId = hasProperty(item, "zone_id") && typeof item.zone_id === "string";
    const hasZoneName = hasProperty(item, "zone_name") && typeof item.zone_name === "string";
    const hasCustomDomainFlag = hasProperty(item, "custom_domain") && typeof item.custom_domain === "boolean";
    const hasEnabled = hasProperty(item, "enabled") && typeof item.enabled === "boolean";
    const hasPreviewsEnabled = hasProperty(item, "previews_enabled") && typeof item.previews_enabled === "boolean";
    const recognizedKeys = [
      hasZoneId,
      hasZoneName,
      hasCustomDomainFlag,
      hasEnabled,
      hasPreviewsEnabled
    ].filter(Boolean).length;
    const otherKeys = Object.keys(item).length - 1;
    if (recognizedKeys !== otherKeys) {
      return false;
    }
    if (hasZoneId && hasZoneName) {
      return false;
    }
    if ((hasEnabled || hasPreviewsEnabled) && !hasCustomDomainFlag) {
      return false;
    }
    if (hasZoneId || hasZoneName || hasCustomDomainFlag) {
      return true;
    }
  }
  return false;
}
__name(isValidRouteValue, "isValidRouteValue");
function mutateEmptyStringAccountIDValue(diagnostics, rawEnv) {
  if (rawEnv.account_id === "") {
    diagnostics.warnings.push(
      `The "account_id" field in your configuration is an empty string and will be ignored.
Please remove the "account_id" field from your configuration.`
    );
    rawEnv.account_id = void 0;
  }
  return rawEnv;
}
__name(mutateEmptyStringAccountIDValue, "mutateEmptyStringAccountIDValue");
function mutateEmptyStringRouteValue(diagnostics, rawEnv) {
  if (rawEnv["route"] === "") {
    diagnostics.warnings.push(
      `The "route" field in your configuration is an empty string and will be ignored.
Please remove the "route" field from your configuration.`
    );
    rawEnv["route"] = void 0;
  }
  return rawEnv;
}
__name(mutateEmptyStringRouteValue, "mutateEmptyStringRouteValue");
var isRoute = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (value !== void 0 && !isValidRouteValue(value)) {
    diagnostics.errors.push(
      `Expected "${field}" to be either a string, or an object with shape { pattern, custom_domain, zone_id | zone_name, enabled, previews_enabled }, but got ${JSON.stringify(
        value
      )}.`
    );
    return false;
  }
  return true;
}, "isRoute");
var isRouteArray = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (value === void 0) {
    return true;
  }
  if (!Array.isArray(value)) {
    diagnostics.errors.push(
      `Expected "${field}" to be an array but got ${JSON.stringify(value)}.`
    );
    return false;
  }
  const invalidRoutes = [];
  for (const item of value) {
    if (!isValidRouteValue(item)) {
      invalidRoutes.push(item);
    }
  }
  if (invalidRoutes.length > 0) {
    diagnostics.errors.push(
      `Expected "${field}" to be an array of either strings or objects with the shape { pattern, custom_domain, zone_id | zone_name, enabled, previews_enabled }, but these weren't valid: ${JSON.stringify(
        invalidRoutes,
        null,
        2
      )}.`
    );
  }
  return invalidRoutes.length === 0;
}, "isRouteArray");
function normalizeAndValidateRoute(diagnostics, topLevelEnv, rawEnv) {
  return inheritable(
    diagnostics,
    topLevelEnv,
    mutateEmptyStringRouteValue(diagnostics, rawEnv),
    "route",
    isRoute,
    void 0
  );
}
__name(normalizeAndValidateRoute, "normalizeAndValidateRoute");
function validateRoutes(diagnostics, topLevelEnv, rawEnv, envName) {
  const result = inheritable(
    diagnostics,
    topLevelEnv,
    rawEnv,
    "routes",
    all(isRouteArray, isMutuallyExclusiveWith(rawEnv, "route")),
    void 0
  );
  if (topLevelEnv !== void 0 && envName !== void 0 && rawEnv.routes === void 0) {
    const customDomainRoutes = topLevelEnv.routes?.filter(
      (r2) => typeof r2 === "object" && r2 !== null && r2.custom_domain === true
    );
    if (customDomainRoutes && customDomainRoutes.length > 0) {
      const customDomains = customDomainRoutes.map((r2) => r2.pattern).join(", ");
      diagnostics.warnings.push(
        `The "env.${envName}" environment inherits the top-level \`routes\` configuration, which includes the custom domain(s): ${customDomains}. Deploying this environment will reassign these custom domains away from the top-level Worker. Add \`"routes": []\` to "env.${envName}" to prevent inheritance, or copy the route configuration from the top level to hide this warning.`
      );
    }
  }
  return result;
}
__name(validateRoutes, "validateRoutes");
function normalizeAndValidatePlacement(diagnostics, topLevelEnv, rawEnv) {
  if (rawEnv.placement) {
    const placement = rawEnv.placement;
    const hasHint = "hint" in placement;
    const hasRegion = "region" in placement;
    const hasHost = "host" in placement;
    const hasHostname = "hostname" in placement;
    const hasTargetedFields = hasRegion || hasHost || hasHostname;
    if (hasHint && hasTargetedFields) {
      diagnostics.errors.push(
        `"placement" cannot have both "hint" (smart format) and "region"/"host"/"hostname" (targeted format) fields`
      );
      return inheritable(
        diagnostics,
        topLevelEnv,
        rawEnv,
        "placement",
        () => true,
        void 0
      );
    }
    if (hasHint) {
      validateRequiredProperty(
        diagnostics,
        "placement",
        "mode",
        placement.mode,
        "string",
        ["off", "smart"]
      );
      const mode = placement.mode;
      const hint = placement.hint;
      if (hint !== void 0 && typeof hint !== "string") {
        diagnostics.errors.push(
          `"placement.hint" must be a string when "placement.mode" is "${mode}"`
        );
      }
      if (hint && mode !== "smart") {
        diagnostics.errors.push(
          `"placement.hint" can only be set when "placement.mode" is "smart"`
        );
      }
    } else if (hasTargetedFields) {
      validateOptionalProperty(
        diagnostics,
        "placement",
        "mode",
        placement.mode,
        "string",
        ["off", "targeted"]
      );
      if (hasRegion) {
        validateOptionalProperty(
          diagnostics,
          "placement",
          "region",
          placement.region,
          "string"
        );
      }
      if (hasHost) {
        validateOptionalProperty(
          diagnostics,
          "placement",
          "host",
          placement.host,
          "string"
        );
      }
      if (hasHostname) {
        validateOptionalProperty(
          diagnostics,
          "placement",
          "hostname",
          placement.hostname,
          "string"
        );
      }
      const fieldsPresent = [hasRegion, hasHost, hasHostname].filter(Boolean);
      if (fieldsPresent.length > 1) {
        const presentFields = [];
        if (hasRegion) {
          presentFields.push("region");
        }
        if (hasHost) {
          presentFields.push("host");
        }
        if (hasHostname) {
          presentFields.push("hostname");
        }
        diagnostics.errors.push(
          `"placement" fields ${presentFields.map((f) => `"${f}"`).join(", ")} are mutually exclusive. Only one can be specified.`
        );
      }
    } else {
      validateRequiredProperty(
        diagnostics,
        "placement",
        "mode",
        placement.mode,
        "string",
        ["off", "smart", "targeted"]
      );
    }
  }
  return inheritable(
    diagnostics,
    topLevelEnv,
    rawEnv,
    "placement",
    () => true,
    void 0
  );
}
__name(normalizeAndValidatePlacement, "normalizeAndValidatePlacement");
function validateTailConsumer(diagnostics, field, value) {
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"${field}" should be an object but got ${JSON.stringify(value)}.`
    );
    return false;
  }
  let isValid = true;
  isValid = isValid && validateRequiredProperty(
    diagnostics,
    field,
    "service",
    value.service,
    "string"
  );
  isValid = isValid && validateOptionalProperty(
    diagnostics,
    field,
    "environment",
    value.environment,
    "string"
  );
  return isValid;
}
__name(validateTailConsumer, "validateTailConsumer");
var validateTailConsumers = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (!value) {
    return true;
  }
  if (!Array.isArray(value)) {
    diagnostics.errors.push(
      `Expected "${field}" to be an array but got ${JSON.stringify(value)}.`
    );
    return false;
  }
  let isValid = true;
  for (let i = 0; i < value.length; i++) {
    isValid = validateTailConsumer(diagnostics, `${field}[${i}]`, value[i]) && isValid;
  }
  return isValid;
}, "validateTailConsumers");
function validateStreamingTailConsumer(diagnostics, field, value) {
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
    diagnostics.errors.push(
      `"${field}" should be an object but got ${JSON.stringify(value)}.`
    );
    return false;
  }
  return validateRequiredProperty(
    diagnostics,
    field,
    "service",
    value.service,
    "string"
  );
}
__name(validateStreamingTailConsumer, "validateStreamingTailConsumer");
var validateStreamingTailConsumers = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (!value) {
    return true;
  }
  if (!Array.isArray(value)) {
    diagnostics.errors.push(
      `Expected "${field}" to be an array but got ${JSON.stringify(value)}.`
    );
    return false;
  }
  let isValid = true;
  for (let i = 0; i < value.length; i++) {
    isValid = validateStreamingTailConsumer(diagnostics, `${field}[${i}]`, value[i]) && isValid;
  }
  return isValid;
}, "validateStreamingTailConsumers");
function normalizeAndValidateEnvironment(diagnostics, configPath, rawEnv, isDispatchNamespace, preserveOriginalMain, envName = "top level", topLevelEnv, rawConfig) {
  deprecated(
    diagnostics,
    rawEnv,
    // @ts-expect-error Removed from the config type
    "node_compat",
    `The "node_compat" field is no longer supported as of Wrangler v4. Instead, use the \`nodejs_compat\` compatibility flag. This includes the functionality from legacy \`node_compat\` polyfills and natively implemented Node.js APIs. See https://developers.cloudflare.com/workers/runtime-apis/nodejs for more information.`,
    true,
    "Removed",
    "error"
  );
  if (topLevelEnv === void 0 || rawConfig?.unsafe === void 0) {
    experimental(diagnostics, rawEnv, "unsafe");
  }
  const route = normalizeAndValidateRoute(diagnostics, topLevelEnv, rawEnv);
  const account_id = inheritable(
    diagnostics,
    topLevelEnv,
    mutateEmptyStringAccountIDValue(diagnostics, rawEnv),
    "account_id",
    isString,
    void 0
  );
  const routes = validateRoutes(
    diagnostics,
    topLevelEnv,
    rawEnv,
    topLevelEnv === void 0 ? void 0 : envName
  );
  const workers_dev = inheritable(
    diagnostics,
    topLevelEnv,
    rawEnv,
    "workers_dev",
    isBoolean,
    void 0
  );
  const preview_urls = inheritable(
    diagnostics,
    topLevelEnv,
    rawEnv,
    "preview_urls",
    isBoolean,
    void 0
  );
  const build = normalizeAndValidateBuild(
    diagnostics,
    rawEnv,
    rawEnv.build ?? topLevelEnv?.build ?? {},
    configPath
  );
  const environment = {
    // Inherited fields
    account_id,
    compatibility_date: inheritable(
      diagnostics,
      topLevelEnv,
      rawEnv,
      "compatibility_date",
      validateCompatibilityDate,
      void 0
    ),
    compatibility_flags: inheritable(
      diagnostics,
      topLevelEnv,
      rawEnv,
      "compatibility_flags",
      isStringArray,
      []
    ),
    jsx_factory: inheritable(
      diagnostics,
      topLevelEnv,
      rawEnv,
      "jsx_factory",
      isString,
      "React.createElement"
    ),
    jsx_fragment: inheritable(
      diagnostics,
      topLevelEnv,
      rawEnv,
      "jsx_fragment",
      isString,
      "React.Fragment"
    ),
    tsconfig: validateAndNormalizeTsconfig(
      diagnostics,
      topLevelEnv,
      rawEnv,
      configPath
    ),
    rules: validateAndNormalizeRules(diagnostics, topLevelEnv, rawEnv, envName),
    name: inheritable(
      diagnostics,
      topLevelEnv,
      rawEnv,
      "name",
      isDispatchNamespace ? isString : isValidName,
      void 0,
      appendEnvName(envName)
    ),
    main: preserveOriginalMain ? inheritable(
      diagnostics,
      topLevelEnv,
      rawEnv,
      "main",
      isString,
      void 0
    ) : normalizeAndValidateMainField(
      configPath,
      inheritable(
        diagnostics,
        topLevelEnv,
        rawEnv,
        "main",
        isString,
        void 0
      )
    ),
    find_additional_modules: inheritable(
      diagnostics,
      topLevelEnv,
      rawEnv,
      "find_additional_modules",
      isBoolean,
      void 0
    ),
    preserve_file_names: inheritable(
      diagnostics,
      topLevelEnv,
      rawEnv,
      "preserve_file_names",
      isBoolean,
      void 0
    ),
    base_dir: normalizeAndValidateBaseDirField(
      configPath,
      inheritable(
        diagnostics,
        topLevelEnv,
        rawEnv,
        "base_dir",
        isString,
        void 0
      )
    ),
    route,
    routes,
    triggers: inheritable(
      diagnostics,
      topLevelEnv,
      rawEnv,
      "triggers",
      validateTriggers,
      { crons: void 0 }
    ),
    assets: normalizeAndValidateAssets(diagnostics, topLevelEnv, rawEnv),
    limits: normalizeAndValidateLimits(diagnostics, topLevelEnv, rawEnv),
    placement: normalizeAndValidatePlacement(diagnostics, topLevelEnv, rawEnv),
    build,
    workers_dev,
    preview_urls,
    // Not inherited fields
    vars: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "vars",
      validateVars(envName),
      {}
    ),
    secrets: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "secrets",
      validateSecrets(envName),
      void 0
    ),
    define: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "define",
      validateDefines(envName),
      {}
    ),
    durable_objects: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "durable_objects",
      validateBindingsProperty(envName, validateDurableObjectBinding),
      {
        bindings: []
      }
    ),
    workflows: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "workflows",
      all(
        validateBindingArray(envName, validateWorkflowBinding),
        validateUniqueNameProperty
      ),
      []
    ),
    migrations: inheritable(
      diagnostics,
      topLevelEnv,
      rawEnv,
      "migrations",
      validateMigrations,
      []
    ),
    exports: inheritable(
      diagnostics,
      topLevelEnv,
      rawEnv,
      "exports",
      validateExports,
      {}
    ),
    kv_namespaces: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "kv_namespaces",
      validateBindingArray(envName, validateKVBinding),
      []
    ),
    cloudchamber: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "cloudchamber",
      validateCloudchamberConfig,
      {}
    ),
    containers: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "containers",
      // `name` is inheritable, so a named environment that doesn't redeclare it
      // still runs under the top level Worker name — fall back to it so the
      // generated container name isn't built from `undefined`.
      validateContainerApp(envName, rawEnv.name ?? rawConfig?.name, configPath),
      void 0
    ),
    send_email: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "send_email",
      validateBindingArray(envName, validateSendEmailBinding),
      []
    ),
    queues: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "queues",
      validateQueues(envName),
      { producers: [], consumers: [] }
    ),
    r2_buckets: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "r2_buckets",
      validateBindingArray(envName, validateR2Binding),
      []
    ),
    d1_databases: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "d1_databases",
      validateBindingArray(envName, validateD1Binding),
      []
    ),
    vectorize: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "vectorize",
      validateBindingArray(envName, validateVectorizeBinding),
      []
    ),
    ai_search_namespaces: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "ai_search_namespaces",
      validateBindingArray(envName, validateAISearchNamespaceBinding),
      []
    ),
    ai_search: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "ai_search",
      validateBindingArray(envName, validateAISearchBinding),
      []
    ),
    websearch: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "websearch",
      validateNamedSimpleBinding(envName),
      void 0
    ),
    agent_memory: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "agent_memory",
      validateBindingArray(envName, validateAgentMemoryBinding),
      []
    ),
    hyperdrive: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "hyperdrive",
      validateBindingArray(envName, validateHyperdriveBinding),
      []
    ),
    services: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "services",
      validateBindingArray(envName, validateServiceBinding),
      []
    ),
    analytics_engine_datasets: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "analytics_engine_datasets",
      validateBindingArray(envName, validateAnalyticsEngineBinding),
      []
    ),
    dispatch_namespaces: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "dispatch_namespaces",
      validateBindingArray(envName, validateWorkerNamespaceBinding),
      []
    ),
    mtls_certificates: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "mtls_certificates",
      validateBindingArray(envName, validateMTlsCertificateBinding),
      []
    ),
    tail_consumers: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "tail_consumers",
      validateTailConsumers,
      void 0
    ),
    streaming_tail_consumers: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "streaming_tail_consumers",
      validateStreamingTailConsumers,
      void 0
    ),
    unsafe: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "unsafe",
      validateUnsafeSettings(envName),
      {}
    ),
    browser: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "browser",
      validateNamedSimpleBinding(envName),
      void 0
    ),
    ai: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "ai",
      validateAIBinding(envName),
      void 0
    ),
    images: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "images",
      validateNamedSimpleBinding(envName),
      void 0
    ),
    stream: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "stream",
      validateNamedSimpleBinding(envName),
      void 0
    ),
    media: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "media",
      validateNamedSimpleBinding(envName),
      void 0
    ),
    pipelines: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "pipelines",
      validateBindingArray(envName, validatePipelineBinding),
      []
    ),
    secrets_store_secrets: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "secrets_store_secrets",
      validateBindingArray(envName, validateSecretsStoreSecretBinding),
      []
    ),
    artifacts: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "artifacts",
      validateBindingArray(envName, validateArtifactsBinding),
      []
    ),
    unsafe_hello_world: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "unsafe_hello_world",
      validateBindingArray(envName, validateHelloWorldBinding),
      []
    ),
    flagship: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "flagship",
      validateBindingArray(envName, validateFlagshipBinding),
      []
    ),
    worker_loaders: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "worker_loaders",
      validateBindingArray(envName, validateWorkerLoaderBinding),
      []
    ),
    ratelimits: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "ratelimits",
      validateBindingArray(envName, validateRateLimitBinding),
      []
    ),
    vpc_services: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "vpc_services",
      validateBindingArray(envName, validateVpcServiceBinding),
      []
    ),
    vpc_networks: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "vpc_networks",
      validateBindingArray(envName, validateVpcNetworkBinding),
      []
    ),
    version_metadata: notInheritable(
      diagnostics,
      topLevelEnv,
      rawConfig,
      rawEnv,
      envName,
      "version_metadata",
      validateVersionMetadataBinding(envName),
      void 0
    ),
    logfwdr: inheritable(
      diagnostics,
      topLevelEnv,
      rawEnv,
      "logfwdr",
      validateCflogfwdrObject(envName),
      {
        bindings: []
      }
    ),
    no_bundle: inheritable(
      diagnostics,
      topLevelEnv,
      rawEnv,
      "no_bundle",
      isBoolean,
      void 0
    ),
    minify: inheritable(
      diagnostics,
      topLevelEnv,
      rawEnv,
      "minify",
      isBoolean,
      void 0
    ),
    keep_names: inheritable(
      diagnostics,
      topLevelEnv,
      rawEnv,
      "keep_names",
      isBoolean,
      void 0
    ),
    first_party_worker: inheritable(
      diagnostics,
      topLevelEnv,
      rawEnv,
      "first_party_worker",
      isBoolean,
      void 0
    ),
    logpush: inheritable(
      diagnostics,
      topLevelEnv,
      rawEnv,
      "logpush",
      isBoolean,
      void 0
    ),
    upload_source_maps: inheritable(
      diagnostics,
      topLevelEnv,
      rawEnv,
      "upload_source_maps",
      isBoolean,
      void 0
    ),
    observability: inheritable(
      diagnostics,
      topLevelEnv,
      rawEnv,
      "observability",
      validateObservability,
      void 0
    ),
    access: inheritable(
      diagnostics,
      topLevelEnv,
      rawEnv,
      "access",
      validateAccess,
      void 0
    ),
    cache: inheritable(
      diagnostics,
      topLevelEnv,
      rawEnv,
      "cache",
      validateCache,
      void 0
    ),
    compliance_region: inheritable(
      diagnostics,
      topLevelEnv,
      rawEnv,
      "compliance_region",
      isOneOf("public", "fedramp_high"),
      void 0
    ),
    python_modules: inheritable(
      diagnostics,
      topLevelEnv,
      rawEnv,
      "python_modules",
      validatePythonModules,
      { exclude: ["**/*.pyc"] }
    ),
    previews: inheritable(
      diagnostics,
      topLevelEnv,
      rawEnv,
      "previews",
      validatePreviewsConfig(envName),
      void 0
    )
  };
  warnIfDurableObjectsHaveNoLifecycleConfig(
    diagnostics,
    environment.durable_objects,
    environment.migrations,
    environment.exports,
    configPath
  );
  errorIfMigrationsAndExportsBothSet(
    diagnostics,
    environment.migrations,
    environment.exports
  );
  const containersDeclaredElsewhere = rawConfig !== void 0 ? rawConfig.containers !== void 0 : Object.values("env" in rawEnv ? rawEnv.env ?? {} : {}).some(
    (rawNamedEnv) => rawNamedEnv?.containers !== void 0
  );
  validateContainerExportLinks(
    diagnostics,
    environment.containers,
    environment.exports,
    containersDeclaredElsewhere
  );
  if (envName !== "top level") {
    validateAdditionalProperties(
      diagnostics,
      "env." + envName,
      Object.keys(rawEnv),
      Object.keys(environment)
    );
  }
  return environment;
}
__name(normalizeAndValidateEnvironment, "normalizeAndValidateEnvironment");
function validateAndNormalizeTsconfig(diagnostics, topLevelEnv, rawEnv, configPath) {
  const tsconfig = inheritable(
    diagnostics,
    topLevelEnv,
    rawEnv,
    "tsconfig",
    isString,
    void 0
  );
  return configPath && tsconfig ? import_node_path4.default.relative(
    process.cwd(),
    import_node_path4.default.join(import_node_path4.default.dirname(configPath), tsconfig)
  ) : tsconfig;
}
__name(validateAndNormalizeTsconfig, "validateAndNormalizeTsconfig");
var validateAndNormalizeRules = /* @__PURE__ */ __name((diagnostics, topLevelEnv, rawEnv, envName) => {
  return inheritable(
    diagnostics,
    topLevelEnv,
    rawEnv,
    "rules",
    validateRules(envName),
    []
  );
}, "validateAndNormalizeRules");
var ARTIFACTS_EVENT_TYPE_SET = new Set(
  ARTIFACTS_EVENT_TYPES
);
var validateTriggers = /* @__PURE__ */ __name((diagnostics, triggersFieldName, triggersValue) => {
  if (triggersValue === void 0 || triggersValue === null) {
    return true;
  }
  if (typeof triggersValue !== "object" || Array.isArray(triggersValue)) {
    diagnostics.errors.push(
      `Expected "${triggersFieldName}" to be of type object but got ${JSON.stringify(
        triggersValue
      )}.`
    );
    return false;
  }
  let isValid = true;
  if ("crons" in triggersValue && !Array.isArray(triggersValue.crons)) {
    diagnostics.errors.push(
      `Expected "${triggersFieldName}.crons" to be of type array, but got ${JSON.stringify(triggersValue)}.`
    );
    isValid = false;
  }
  if (hasProperty(triggersValue, "events") && !Array.isArray(triggersValue.events)) {
    diagnostics.errors.push(
      `Expected "${triggersFieldName}.events" to be of type array, but got ${JSON.stringify(triggersValue)}.`
    );
    isValid = false;
  } else if (hasProperty(triggersValue, "events") && Array.isArray(triggersValue.events)) {
    for (const [eventIndex, event] of triggersValue.events.entries()) {
      const eventFieldName = `${triggersFieldName}.events[${eventIndex}]`;
      if (typeof event !== "object" || event === null || Array.isArray(event)) {
        diagnostics.errors.push(
          `Expected "${eventFieldName}" to be of type object, but got ${JSON.stringify(event)}.`
        );
        isValid = false;
        continue;
      }
      if (!isRequiredProperty(event, "type", "string") || !ARTIFACTS_EVENT_TYPE_SET.has(event.type)) {
        diagnostics.errors.push(
          `Expected "${eventFieldName}.type" to be a supported Artifacts event type, but got ${JSON.stringify(event.type)}.`
        );
        isValid = false;
      }
      if (hasProperty(event, "filter") && event.filter !== void 0) {
        if (typeof event.filter !== "object" || event.filter === null || Array.isArray(event.filter)) {
          diagnostics.errors.push(
            `Expected "${eventFieldName}.filter" to be of type object, but got ${JSON.stringify(event.filter)}.`
          );
          isValid = false;
        } else {
          for (const [filterName, filterValue] of Object.entries(
            event.filter
          )) {
            if (filterName !== "namespace" && filterName !== "repo_name" || typeof filterValue !== "string") {
              diagnostics.errors.push(
                `Expected "${eventFieldName}.filter" to contain only string "namespace" and "repo_name" fields, but got ${JSON.stringify(event.filter)}.`
              );
              isValid = false;
              break;
            }
          }
        }
      }
      if (!Array.isArray(event.targets) || event.targets.length === 0) {
        diagnostics.errors.push(
          `Expected "${eventFieldName}.targets" to be a non-empty array, but got ${JSON.stringify(event.targets)}.`
        );
        isValid = false;
      } else {
        for (const [targetIndex, target] of event.targets.entries()) {
          const targetFieldName = `${eventFieldName}.targets[${targetIndex}]`;
          if (typeof target !== "object" || target === null || Array.isArray(target) || target.type !== "workflow" || typeof target.workflow_name !== "string" || target.workflow_name.length === 0) {
            diagnostics.errors.push(
              `Expected "${targetFieldName}" to be a workflow target with a non-empty "workflow_name", but got ${JSON.stringify(target)}.`
            );
            isValid = false;
            continue;
          }
          validateAdditionalProperties(
            diagnostics,
            targetFieldName,
            Object.keys(target),
            ["type", "workflow_name"]
          );
        }
      }
      validateAdditionalProperties(
        diagnostics,
        eventFieldName,
        Object.keys(event),
        ["type", "filter", "targets"]
      );
    }
  }
  isValid = validateAdditionalProperties(
    diagnostics,
    triggersFieldName,
    Object.keys(triggersValue),
    ["crons", "events"]
  ) && isValid;
  return isValid;
}, "validateTriggers");
var validateRules = /* @__PURE__ */ __name((envName) => (diagnostics, field, envValue, config22) => {
  if (!envValue) {
    return true;
  }
  const fieldPath = config22 === void 0 ? `${field}` : `env.${envName}.${field}`;
  if (!Array.isArray(envValue)) {
    diagnostics.errors.push(
      `The field "${fieldPath}" should be an array but got ${JSON.stringify(
        envValue
      )}.`
    );
    return false;
  }
  let isValid = true;
  for (let i = 0; i < envValue.length; i++) {
    isValid = validateRule(diagnostics, `${fieldPath}[${i}]`, envValue[i], config22) && isValid;
  }
  return isValid;
}, "validateRules");
var validateRule = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"${field}" should be an object but got ${JSON.stringify(value)}.`
    );
    return false;
  }
  let isValid = true;
  const rule = value;
  if (!isRequiredProperty(rule, "type", "string", [
    "ESModule",
    "CommonJS",
    "CompiledWasm",
    "Text",
    "Data"
  ])) {
    diagnostics.errors.push(
      `bindings should have a string "type" field, which contains one of "ESModule", "CommonJS", "CompiledWasm", "Text", or "Data".`
    );
    isValid = false;
  }
  isValid = validateTypedArray(diagnostics, `${field}.globs`, rule.globs, "string") && isValid;
  if (!isOptionalProperty(rule, "fallthrough", "boolean")) {
    diagnostics.errors.push(
      `the field "fallthrough", when present, should be a boolean.`
    );
    isValid = false;
  }
  return isValid;
}, "validateRule");
var validateDefines = /* @__PURE__ */ __name((envName) => (diagnostics, field, value, config22) => {
  let isValid = true;
  const fieldPath = config22 === void 0 ? `${field}` : `env.${envName}.${field}`;
  if (typeof value === "object" && value !== null) {
    for (const varName in value) {
      if (typeof value[varName] !== "string") {
        diagnostics.errors.push(
          `The field "${fieldPath}.${varName}" should be a string but got ${JSON.stringify(
            value[varName]
          )}.`
        );
        isValid = false;
      }
    }
  } else {
    if (value !== void 0) {
      diagnostics.errors.push(
        `The field "${fieldPath}" should be an object but got ${JSON.stringify(
          value
        )}.
`
      );
      isValid = false;
    }
  }
  const configDefines = Object.keys(config22?.define ?? {});
  if (configDefines.length > 0) {
    if (typeof value === "object" && value !== null) {
      const configEnvDefines = config22 === void 0 ? [] : Object.keys(value);
      const missingDefines = configDefines.filter(
        (varName) => !(varName in value)
      );
      if (missingDefines.length > 0) {
        diagnostics.warnings.push(
          `The following define entries exist at the top level, but not on "${fieldPath}".
This is probably not what you want, since "define" configuration is not inherited by environments.
Please add these entries to "env.${envName}.define":
` + missingDefines.map((varName) => `- ${varName}`).join("\n")
        );
      }
      for (const varName of configEnvDefines) {
        if (!configDefines.includes(varName)) {
          diagnostics.warnings.push(
            `"${varName}" exists on "env.${envName}", but not on the top level.
This is not what you probably want, since "define" configuration within environments can only override existing top level "define" configuration
Please remove "${fieldPath}.${varName}", or add "define.${varName}".`
          );
        }
      }
    }
  }
  return isValid;
}, "validateDefines");
var validateVars = /* @__PURE__ */ __name((envName) => (diagnostics, field, value, config22) => {
  let isValid = true;
  const fieldPath = config22 === void 0 ? `${field}` : `env.${envName}.${field}`;
  if (value !== void 0) {
    if (typeof value !== "object" || value === null) {
      diagnostics.errors.push(
        `The field "${fieldPath}" should be an object but got ${JSON.stringify(
          value
        )}.
`
      );
      isValid = false;
    } else {
      for (const [varName, varValue] of Object.entries(value)) {
        if (varValue instanceof Date) {
          diagnostics.errors.push(
            `The field "${fieldPath}.${varName}" is a TOML date, which is not supported. Please use a string instead, e.g. ${varName} = "2025-12-19".`
          );
          isValid = false;
        }
      }
    }
  }
  const configVars = Object.keys(config22?.vars ?? {});
  if (configVars.length > 0) {
    if (typeof value === "object" && value !== null) {
      const missingVars = configVars.filter((varName) => !(varName in value));
      if (missingVars.length > 0) {
        diagnostics.warnings.push(
          `The following vars exist at the top level, but not on "${fieldPath}".
This is probably not what you want, since "vars" configuration is not inherited by environments.
Please add these vars to "env.${envName}.vars":
` + missingVars.map((varName) => `- ${varName}`).join("\n")
        );
      }
    }
  }
  return isValid;
}, "validateVars");
var validateSecrets = /* @__PURE__ */ __name((envName) => (diagnostics, field, value, config22) => {
  const fieldPath = config22 === void 0 ? `${field}` : `env.${envName}.${field}`;
  if (value === void 0) {
    return true;
  }
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
    diagnostics.errors.push(
      `The field "${fieldPath}" should be an object but got ${JSON.stringify(value)}.`
    );
    return false;
  }
  let isValid = true;
  validateAdditionalProperties(diagnostics, fieldPath, Object.keys(value), [
    "required"
  ]);
  isValid = validateOptionalTypedArray(
    diagnostics,
    `${fieldPath}.required`,
    value.required,
    "string"
  ) && isValid;
  return isValid;
}, "validateSecrets");
var validateBindingsProperty = /* @__PURE__ */ __name((envName, validateBinding) => (diagnostics, field, value, config22) => {
  let isValid = true;
  const fieldPath = config22 === void 0 ? `${field}` : `env.${envName}.${field}`;
  if (value !== void 0) {
    if (typeof value !== "object" || value === null || Array.isArray(value)) {
      diagnostics.errors.push(
        `The field "${fieldPath}" should be an object but got ${JSON.stringify(
          value
        )}.`
      );
      isValid = false;
    } else if (!hasProperty(value, "bindings")) {
      diagnostics.errors.push(
        `The field "${fieldPath}" is missing the required "bindings" property.`
      );
      isValid = false;
    } else if (!Array.isArray(value.bindings)) {
      diagnostics.errors.push(
        `The field "${fieldPath}.bindings" should be an array but got ${JSON.stringify(
          value.bindings
        )}.`
      );
      isValid = false;
    } else {
      for (let i = 0; i < value.bindings.length; i++) {
        const binding = value.bindings[i];
        const bindingDiagnostics = new Diagnostics(
          `"${fieldPath}.bindings[${i}]": ${JSON.stringify(binding)}`
        );
        isValid = validateBinding(
          bindingDiagnostics,
          `${fieldPath}.bindings[${i}]`,
          binding,
          config22
        ) && isValid;
        diagnostics.addChild(bindingDiagnostics);
      }
    }
    const configBindingNames = getBindingNames(
      config22?.[field]
    );
    if (isValid && configBindingNames.length > 0) {
      const envBindingNames = new Set(getBindingNames(value));
      const missingBindings = configBindingNames.filter(
        (name) => !envBindingNames.has(name)
      );
      if (missingBindings.length > 0) {
        diagnostics.warnings.push(
          `The following bindings are at the top level, but not on "env.${envName}".
This is not what you probably want, since "${field}" configuration is not inherited by environments.
Please add a binding for each to "${fieldPath}.bindings":
` + missingBindings.map((name) => `- ${name}`).join("\n")
        );
      }
    }
  }
  return isValid;
}, "validateBindingsProperty");
var validateUnsafeSettings = /* @__PURE__ */ __name((envName) => (diagnostics, field, value, config22) => {
  const fieldPath = config22 === void 0 ? `${field}` : `env.${envName}.${field}`;
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
    diagnostics.errors.push(
      `The field "${fieldPath}" should be an object but got ${JSON.stringify(
        value
      )}.`
    );
    return false;
  }
  if (hasProperty(value, "bindings") && value.bindings !== void 0) {
    const validateBindingsFn = validateBindingsProperty(
      envName,
      validateUnsafeBinding
    );
    const valid = validateBindingsFn(diagnostics, field, value, config22);
    if (!valid) {
      return false;
    }
  }
  if (hasProperty(value, "metadata") && value.metadata !== void 0 && (typeof value.metadata !== "object" || value.metadata === null || Array.isArray(value.metadata))) {
    diagnostics.errors.push(
      `The field "${fieldPath}.metadata" should be an object but got ${JSON.stringify(
        value.metadata
      )}.`
    );
    return false;
  }
  if (hasProperty(value, "capnp") && value.capnp !== void 0) {
    if (typeof value.capnp !== "object" || value.capnp === null || Array.isArray(value.capnp)) {
      diagnostics.errors.push(
        `The field "${fieldPath}.capnp" should be an object but got ${JSON.stringify(
          value.capnp
        )}.`
      );
      return false;
    }
    if (hasProperty(value.capnp, "compiled_schema")) {
      if (hasProperty(value.capnp, "base_path") || hasProperty(value.capnp, "source_schemas")) {
        diagnostics.errors.push(
          `The field "${fieldPath}.capnp" cannot contain both "compiled_schema" and one of "base_path" or "source_schemas".`
        );
        return false;
      }
      if (typeof value.capnp.compiled_schema !== "string") {
        diagnostics.errors.push(
          `The field "${fieldPath}.capnp.compiled_schema", when present, should be a string but got ${JSON.stringify(
            value.capnp.compiled_schema
          )}.`
        );
        return false;
      }
    } else {
      if (!isRequiredProperty(value.capnp, "base_path", "string")) {
        diagnostics.errors.push(
          `The field "${fieldPath}.capnp.base_path", when present, should be a string but got ${JSON.stringify(
            value.capnp.base_path
          )}`
        );
      }
      if (!validateTypedArray(
        diagnostics,
        `${fieldPath}.capnp.source_schemas`,
        value.capnp.source_schemas,
        "string"
      )) {
        return false;
      }
    }
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "bindings",
    "metadata",
    "capnp"
  ]);
  return true;
}, "validateUnsafeSettings");
var validateDurableObjectBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `Expected "${field}" to be an object but got ${JSON.stringify(value)}`
    );
    return false;
  }
  let isValid = true;
  if (!isRequiredProperty(value, "name", "string")) {
    diagnostics.errors.push(`binding should have a string "name" field.`);
    isValid = false;
  }
  if (!isRequiredProperty(value, "class_name", "string")) {
    diagnostics.errors.push(`binding should have a string "class_name" field.`);
    isValid = false;
  }
  if (!isOptionalProperty(value, "script_name", "string")) {
    diagnostics.errors.push(
      `the field "script_name", when present, should be a string.`
    );
    isValid = false;
  }
  if (!isOptionalProperty(value, "environment", "string")) {
    diagnostics.errors.push(
      `the field "environment", when present, should be a string.`
    );
    isValid = false;
  }
  if ("environment" in value && !("script_name" in value)) {
    diagnostics.errors.push(
      `binding should have a "script_name" field if "environment" is present.`
    );
    isValid = false;
  }
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "class_name",
    "environment",
    "name",
    "script_name"
  ]);
  return isValid;
}, "validateDurableObjectBinding");
var workflowNameFormatMessage = `Workflow names must be 1-64 characters long, start with a letter, number, or underscore, and may only contain letters, numbers, underscores, or hyphens.`;
var validateWorkflowBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"workflows" bindings should be objects, but got ${JSON.stringify(value)}`
    );
    return false;
  }
  let isValid = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isRequiredProperty(value, "name", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "name" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  } else if (!isValidWorkflowName(value.name)) {
    diagnostics.errors.push(
      `"${field}" binding "name" field is invalid. ${workflowNameFormatMessage}`
    );
    isValid = false;
  }
  if (!isRequiredProperty(value, "class_name", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "class_name" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isOptionalProperty(value, "script_name", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should, optionally, have a string "script_name" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isOptionalProperty(value, "remote", "boolean")) {
    diagnostics.errors.push(
      `"${field}" bindings should, optionally, have a boolean "remote" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (hasProperty(value, "schedules") && value.schedules !== void 0) {
    if (typeof value.schedules === "string") {
      if (value.schedules.length === 0) {
        diagnostics.errors.push(
          `"${field}" bindings "schedules" field must not be an empty string.`
        );
        isValid = false;
      }
    } else if (Array.isArray(value.schedules)) {
      if (value.schedules.length === 0) {
        diagnostics.errors.push(
          `"${field}" bindings "schedules" field must not be an empty array.`
        );
        isValid = false;
      } else if (!value.schedules.every((s) => typeof s === "string")) {
        diagnostics.errors.push(
          `"${field}" bindings should, optionally, have a string or array of strings "schedules" field but got ${JSON.stringify(
            value
          )}.`
        );
        isValid = false;
      } else if (value.schedules.some((s) => s === "")) {
        diagnostics.errors.push(
          `"${field}" bindings "schedules" field must not contain empty strings.`
        );
        isValid = false;
      }
    } else {
      diagnostics.errors.push(
        `"${field}" bindings should, optionally, have a string or array of strings "schedules" field but got ${JSON.stringify(
          value
        )}.`
      );
      isValid = false;
    }
  }
  if (hasProperty(value, "limits") && value.limits !== void 0) {
    if (typeof value.limits !== "object" || value.limits === null || Array.isArray(value.limits)) {
      diagnostics.errors.push(
        `"${field}" bindings should, optionally, have an object "limits" field but got ${JSON.stringify(
          value
        )}.`
      );
      isValid = false;
    } else {
      const limits = value.limits;
      if (limits.steps !== void 0) {
        if (typeof limits.steps !== "number" || !Number.isInteger(limits.steps) || limits.steps < 1) {
          diagnostics.errors.push(
            `"${field}" bindings "limits.steps" field must be a positive integer but got ${JSON.stringify(
              limits.steps
            )}.`
          );
          isValid = false;
        } else if (limits.steps > 25e3) {
          diagnostics.warnings.push(
            `"${field}" has a step limit of ${limits.steps}, which exceeds the production maximum of 25,000. This configuration may not work when deployed.`
          );
        }
      }
      validateAdditionalProperties(
        diagnostics,
        `${field}.limits`,
        Object.keys(limits),
        ["steps"]
      );
    }
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "name",
    "class_name",
    "script_name",
    "remote",
    "limits",
    "schedules"
  ]);
  return isValid;
}, "validateWorkflowBinding");
var validateCflogfwdrObject = /* @__PURE__ */ __name((envName) => (diagnostics, field, value, topLevelEnv) => {
  const bindingsValidation = validateBindingsProperty(
    envName,
    validateCflogfwdrBinding
  );
  if (!bindingsValidation(diagnostics, field, value, topLevelEnv)) {
    return false;
  }
  const v = value;
  if (v?.schema !== void 0) {
    diagnostics.errors.push(
      `"${field}" binding "schema" property has been replaced with the "unsafe.capnp" object, which expects a "base_path" and an array of "source_schemas" to compile, or a "compiled_schema" property.`
    );
    return false;
  }
  return true;
}, "validateCflogfwdrObject");
var validateCflogfwdrBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `Expected "${field}" to be an object but got ${JSON.stringify(value)}`
    );
    return false;
  }
  let isValid = true;
  if (!isRequiredProperty(value, "name", "string")) {
    diagnostics.errors.push(`binding should have a string "name" field.`);
    isValid = false;
  }
  if (!isRequiredProperty(value, "destination", "string")) {
    diagnostics.errors.push(
      `binding should have a string "destination" field.`
    );
    isValid = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "destination",
    "name"
  ]);
  return isValid;
}, "validateCflogfwdrBinding");
var validateAssetsConfig = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (value === void 0) {
    return true;
  }
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"${field}" should be an object, but got value ${JSON.stringify(
        field
      )} of type ${typeof value}`
    );
    return false;
  }
  let isValid = true;
  isValid = validateOptionalProperty(
    diagnostics,
    field,
    "directory",
    value.directory,
    "string"
  ) && isValid;
  isValid = validateOptionalProperty(
    diagnostics,
    field,
    "binding",
    value.binding,
    "string"
  ) && isValid;
  isValid = validateOptionalProperty(
    diagnostics,
    field,
    "html_handling",
    value.html_handling,
    "string",
    [
      "auto-trailing-slash",
      "force-trailing-slash",
      "drop-trailing-slash",
      "none"
    ]
  ) && isValid;
  isValid = validateOptionalProperty(
    diagnostics,
    field,
    "not_found_handling",
    value.not_found_handling,
    "string",
    ["single-page-application", "404-page", "none"]
  ) && isValid;
  if (value.run_worker_first !== void 0) {
    if (typeof value.run_worker_first === "boolean") {
      isValid = validateOptionalProperty(
        diagnostics,
        field,
        "run_worker_first",
        value.run_worker_first,
        "boolean"
      ) && isValid;
    } else if (Array.isArray(value.run_worker_first)) {
      isValid = validateOptionalTypedArray(
        diagnostics,
        "assets.run_worker_first",
        value.run_worker_first,
        "string"
      ) && isValid;
    } else {
      diagnostics.errors.push(
        `The field "${field}.run_worker_first" should be an array of strings or a boolean, but got ${JSON.stringify(
          value.run_worker_first
        )}.`
      );
      isValid = false;
    }
  }
  isValid = validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "directory",
    "binding",
    "html_handling",
    "not_found_handling",
    "run_worker_first"
  ]) && isValid;
  return isValid;
}, "validateAssetsConfig");
var validateNamedSimpleBinding = /* @__PURE__ */ __name((envName) => (diagnostics, field, value, config22) => {
  const fieldPath = config22 === void 0 ? `${field}` : `env.${envName}.${field}`;
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
    diagnostics.errors.push(
      `The field "${fieldPath}" should be an object but got ${JSON.stringify(
        value
      )}.`
    );
    return false;
  }
  let isValid = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(`binding should have a string "binding" field.`);
    isValid = false;
  }
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "remote"
  ]);
  return isValid;
}, "validateNamedSimpleBinding");
var validateAIBinding = /* @__PURE__ */ __name((envName) => (diagnostics, field, value, config22) => {
  const fieldPath = config22 === void 0 ? `${field}` : `env.${envName}.${field}`;
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
    diagnostics.errors.push(
      `The field "${fieldPath}" should be an object but got ${JSON.stringify(
        value
      )}.`
    );
    return false;
  }
  let isValid = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(`binding should have a string "binding" field.`);
    isValid = false;
  }
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid = false;
  }
  return isValid;
}, "validateAIBinding");
var validateVersionMetadataBinding = /* @__PURE__ */ __name((envName) => (diagnostics, field, value, config22) => {
  const fieldPath = config22 === void 0 ? `${field}` : `env.${envName}.${field}`;
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
    diagnostics.errors.push(
      `The field "${fieldPath}" should be an object but got ${JSON.stringify(
        value
      )}.`
    );
    return false;
  }
  let isValid = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(`binding should have a string "binding" field.`);
    isValid = false;
  }
  return isValid;
}, "validateVersionMetadataBinding");
var validateUnsafeBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `Expected ${field} to be an object but got ${JSON.stringify(value)}.`
    );
    return false;
  }
  let isValid = true;
  if (!isRequiredProperty(value, "name", "string")) {
    diagnostics.errors.push(`binding should have a string "name" field.`);
    isValid = false;
  }
  if (isRequiredProperty(value, "type", "string")) {
    const safeBindings = [
      "plain_text",
      "secret_text",
      "json",
      "wasm_module",
      "data_blob",
      "text_blob",
      "browser",
      "ai",
      "ai_search_namespace",
      "ai_search",
      "websearch",
      "agent_memory",
      "kv_namespace",
      "durable_object_namespace",
      "d1_database",
      "r2_bucket",
      "service",
      "logfwdr",
      "mtls_certificate",
      "pipeline",
      "worker_loader",
      "vpc_service",
      "flagship",
      "vpc_network",
      "stream",
      "media",
      "artifacts"
    ];
    if (safeBindings.includes(value.type)) {
      diagnostics.warnings.push(
        `The binding type "${value.type}" is directly supported by wrangler.
Consider migrating this unsafe binding to a format for '${value.type}' bindings that is supported by wrangler for optimal support.
For more details, see https://developers.cloudflare.com/workers/cli-wrangler/configuration`
      );
    }
    if (value.type === "metadata" && isRequiredProperty(value, "name", "string")) {
      diagnostics.warnings.push(
        "The deployment object in the metadata binding is now deprecated. Please switch using the version_metadata binding for access to version specific fields: https://developers.cloudflare.com/workers/runtime-apis/bindings/version-metadata"
      );
    }
  } else {
    diagnostics.errors.push(`binding should have a string "type" field.`);
    isValid = false;
  }
  return isValid;
}, "validateUnsafeBinding");
var validateBindingArray = /* @__PURE__ */ __name((envName, validateBinding) => (diagnostics, field, envValue, config22) => {
  if (envValue === void 0) {
    return true;
  }
  const fieldPath = config22 === void 0 ? `${field}` : `env.${envName}.${field}`;
  if (!Array.isArray(envValue)) {
    diagnostics.errors.push(
      `The field "${fieldPath}" should be an array but got ${JSON.stringify(
        envValue
      )}.`
    );
    return false;
  }
  let isValid = true;
  for (let i = 0; i < envValue.length; i++) {
    isValid = validateBinding(
      diagnostics,
      `${fieldPath}[${i}]`,
      envValue[i],
      config22
    ) && isValid;
  }
  const configValue = config22?.[field];
  if (Array.isArray(configValue)) {
    const configBindingNames = configValue.map((value) => value.binding);
    if (configBindingNames.length > 0) {
      const envBindingNames = new Set(envValue.map((value) => value.binding));
      for (const configBindingName of configBindingNames) {
        if (!envBindingNames.has(configBindingName)) {
          diagnostics.warnings.push(
            `There is a ${field} binding with name "${configBindingName}" at the top level, but not on "env.${envName}".
This is not what you probably want, since "${field}" configuration is not inherited by environments.
Please add a binding for "${configBindingName}" to "env.${envName}.${field}.bindings".`
          );
        }
      }
    }
  }
  return isValid;
}, "validateBindingArray");
function validateSshPublicKeys(diagnostics, field, value, nameRequired) {
  if (!Array.isArray(value)) {
    diagnostics.errors.push(`${field} must be an array`);
    return;
  }
  for (const [index, key] of value.entries()) {
    const fieldPath = `${field}[${index}]`;
    if (typeof key !== "object" || key === null || Array.isArray(key)) {
      diagnostics.errors.push(`${fieldPath} must be an object`);
      continue;
    }
    const hasValidName = nameRequired ? isRequiredProperty(key, "name", "string") : isOptionalProperty(key, "name", "string");
    if (!hasValidName) {
      diagnostics.errors.push(`${fieldPath}.name must be a string`);
    }
    if (!isRequiredProperty(key, "public_key", "string")) {
      diagnostics.errors.push(`${fieldPath}.public_key must be a string`);
    } else if (!key.public_key.toLowerCase().startsWith("ssh-ed25519")) {
      diagnostics.errors.push(
        `${fieldPath}.public_key is an unsupported key type. Please provide an ED25519 public key.`
      );
    }
  }
}
__name(validateSshPublicKeys, "validateSshPublicKeys");
function validateContainerApp(envName, topLevelName, configPath) {
  return (diagnostics, field, value, config22) => {
    if (!value) {
      return true;
    }
    if (!Array.isArray(value)) {
      diagnostics.errors.push(
        `"containers" field should be an array, but got ${JSON.stringify(value)}`
      );
      return false;
    }
    for (const containerAppOptional of value) {
      validateOptionalProperty(
        diagnostics,
        field,
        "class_name",
        containerAppOptional.class_name,
        "string"
      );
      validateOptionalProperty(
        diagnostics,
        field,
        "name",
        containerAppOptional.name,
        "string"
      );
      if (!containerAppOptional.name) {
        if (containerAppOptional.class_name === void 0) {
          diagnostics.errors.push(
            `"containers.name" is required when "containers.class_name" is not defined, because there is no class name to derive a default name from. Either name this container and reference it from a Durable Object's \`exports\` entry, or set "containers.class_name".`
          );
        } else if (!topLevelName) {
          diagnostics.errors.push(
            `Must have either a top level "name" and "containers.class_name" field defined, or have field "containers.name" defined.`
          );
        } else {
          let name = `${topLevelName}-${containerAppOptional.class_name}`;
          name += config22 === void 0 ? "" : `-${envName}`;
          containerAppOptional.name = name.toLowerCase().replace(/ /g, "-");
        }
      }
      if (!containerAppOptional.configuration?.image && !containerAppOptional.image) {
        diagnostics.errors.push(
          `"containers.image" field must be defined for each container app. This should be the path to your Dockerfile or an image URI pointing to the Cloudflare registry.`
        );
      }
      if ("configuration" in containerAppOptional) {
        diagnostics.warnings.push(
          `"containers.configuration" is deprecated. Use top level "containers" fields instead. "configuration.image" should be "image", limits should be set via "instance_type".`
        );
        if (typeof containerAppOptional.configuration !== "object" || containerAppOptional.configuration === null || Array.isArray(containerAppOptional.configuration)) {
          diagnostics.errors.push(
            `"containers.configuration" should be an object`
          );
        } else if (containerAppOptional.instance_type && (containerAppOptional.configuration.disk !== void 0 || containerAppOptional.configuration.vcpu !== void 0 || containerAppOptional.configuration.memory_mib !== void 0)) {
          diagnostics.errors.push(
            `Cannot set custom limits via "containers.configuration" and use preset "instance_type" limits at the same time.`
          );
        }
      }
      validateOptionalProperty(
        diagnostics,
        field,
        "image_build_context",
        containerAppOptional.image_build_context,
        "string"
      );
      let resolvedImage = containerAppOptional.image ?? containerAppOptional.configuration?.image;
      let resolvedBuildContextPath = void 0;
      try {
        if (isDockerfile(resolvedImage, configPath)) {
          const baseDir2 = configPath ? import_node_path4.default.dirname(configPath) : process.cwd();
          resolvedImage = import_node_path4.default.resolve(baseDir2, resolvedImage);
          resolvedBuildContextPath = containerAppOptional.image_build_context ? import_node_path4.default.resolve(baseDir2, containerAppOptional.image_build_context) : import_node_path4.default.dirname(resolvedImage);
        }
      } catch (err) {
        if (err instanceof Error && err.message) {
          diagnostics.errors.push(err.message);
        } else {
          throw err;
        }
      }
      containerAppOptional.image = resolvedImage;
      containerAppOptional.image_build_context = resolvedBuildContextPath;
      if (containerAppOptional.rollout_step_percentage !== void 0) {
        const rolloutStep = containerAppOptional.rollout_step_percentage;
        if (typeof rolloutStep === "number") {
          const allowedSingleValues = [5, 10, 20, 25, 50, 100];
          if (!allowedSingleValues.includes(rolloutStep)) {
            diagnostics.errors.push(
              `"containers.rollout_step_percentage" must be one of [5, 10, 20, 25, 50, 100], but got ${rolloutStep}`
            );
          }
        } else if (Array.isArray(rolloutStep)) {
          const nonNumber = [];
          const outOfRange = [];
          let index = 0;
          let ascending = true;
          for (const step of rolloutStep) {
            if (typeof step !== "number") {
              nonNumber.push(step);
            } else {
              if (step < 10 || step > 100) {
                outOfRange.push(step);
              }
              if (ascending && index > 0 && step < rolloutStep[index - 1]) {
                diagnostics.errors.push(
                  `"containers.rollout_step_percentage" array elements must be in ascending order, but got "${rolloutStep}"`
                );
                ascending = false;
              }
              if (index === rolloutStep.length - 1 && step !== 100) {
                diagnostics.errors.push(
                  `The final step in "containers.rollout_step_percentage" must be 100, but got "${step}"`
                );
              }
              index++;
            }
          }
          if (nonNumber.length) {
            diagnostics.errors.push(
              `"containers.rollout_step_percentage" array elements must be numbers, but got "${nonNumber.join(", ")}"`
            );
          }
          if (outOfRange.length) {
            diagnostics.errors.push(
              `"containers.rollout_step_percentage" array elements must be between 10 and 100, but got "${outOfRange.join(", ")}"`
            );
          }
        } else {
          diagnostics.errors.push(
            `"containers.rollout_step_percentage" must be a number or array of numbers, but got "${rolloutStep}"`
          );
        }
      }
      validateOptionalProperty(
        diagnostics,
        field,
        "rollout_kind",
        containerAppOptional.rollout_kind,
        "string",
        ["full_auto", "full_manual", "none"]
      );
      if (!isOptionalProperty(
        containerAppOptional,
        "rollout_active_grace_period",
        "number"
      ) || containerAppOptional.rollout_active_grace_period < 0) {
        diagnostics.errors.push(
          `"containers.rollout_active_grace_period" field should be a positive number but got "${containerAppOptional.rollout_active_grace_period}"`
        );
      }
      validateOptionalProperty(
        diagnostics,
        field,
        "max_instances",
        containerAppOptional.max_instances,
        "number"
      );
      if (containerAppOptional.max_instances !== void 0 && containerAppOptional.max_instances < 0) {
        diagnostics.errors.push(
          `"containers.max_instances" field should be a positive number, but got ${containerAppOptional.max_instances}`
        );
      }
      if (containerAppOptional.rollout_step_percentage !== void 0 && containerAppOptional.max_instances !== void 0 && Array.isArray(containerAppOptional.rollout_step_percentage)) {
        const rolloutStepsCount = containerAppOptional.rollout_step_percentage.length;
        if (rolloutStepsCount > containerAppOptional.max_instances) {
          diagnostics.errors.push(
            `"containers.rollout_step_percentage" cannot have more steps (${rolloutStepsCount}) than "max_instances" (${containerAppOptional.max_instances})`
          );
        }
      }
      validateOptionalProperty(
        diagnostics,
        field,
        "image_vars",
        containerAppOptional.image_vars,
        "object"
      );
      validateOptionalProperty(
        diagnostics,
        field,
        "scheduling_policy",
        containerAppOptional.scheduling_policy,
        "string",
        ["regional", "moon", "default"]
      );
      if ("instances" in containerAppOptional) {
        diagnostics.warnings.push(
          `"containers.instances" is deprecated. Use "containers.max_instances" instead.`
        );
      }
      if ("durable_objects" in containerAppOptional) {
        diagnostics.warnings.push(
          `"containers.durable_objects" is deprecated. Use the "class_name" field instead.`
        );
      }
      if ("wrangler_ssh" in containerAppOptional) {
        diagnostics.warnings.push(
          `"containers.wrangler_ssh" is deprecated. Use "containers.ssh" instead.`
        );
      }
      if ("unsafe" in containerAppOptional) {
        if (containerAppOptional.unsafe && typeof containerAppOptional.unsafe !== "object" || Array.isArray(containerAppOptional.unsafe)) {
          diagnostics.errors.push(
            `The field "containers.unsafe" should be an object but got ${JSON.stringify(
              typeof containerAppOptional.unsafe
            )}.`
          );
        }
      }
      validateAdditionalProperties(
        diagnostics,
        field,
        Object.keys(containerAppOptional),
        [
          "name",
          "instances",
          "max_instances",
          "image",
          "image_build_context",
          "image_vars",
          "class_name",
          "scheduling_policy",
          "instance_type",
          "ssh",
          "wrangler_ssh",
          "authorized_keys",
          "trusted_user_ca_keys",
          "configuration",
          "constraints",
          "affinities",
          "rollout_step_percentage",
          "rollout_kind",
          "durable_objects",
          "rollout_active_grace_period",
          "unsafe"
        ]
      );
      if (typeof containerAppOptional.configuration === "object" && containerAppOptional.configuration !== null && !Array.isArray(containerAppOptional.configuration)) {
        validateAdditionalProperties(
          diagnostics,
          `${field}.configuration`,
          Object.keys(containerAppOptional.configuration),
          ["image", "secrets", "labels", "disk", "vcpu", "memory_mib"]
        );
      }
      let sshField;
      let sshConfig;
      if ("ssh" in containerAppOptional) {
        sshField = "ssh";
        sshConfig = containerAppOptional.ssh;
        containerAppOptional.wrangler_ssh = containerAppOptional.ssh;
        delete containerAppOptional.ssh;
      } else if ("wrangler_ssh" in containerAppOptional) {
        sshField = "wrangler_ssh";
        sshConfig = containerAppOptional.wrangler_ssh;
      }
      if (sshField !== void 0) {
        const sshConfigObject = typeof sshConfig === "object" && sshConfig !== null ? sshConfig : {};
        if (!isRequiredProperty(sshConfigObject, "enabled", "boolean")) {
          diagnostics.errors.push(
            `${field}.${sshField}.enabled must be a boolean`
          );
        }
        const sshPort = "port" in sshConfigObject ? sshConfigObject.port : void 0;
        if (!isOptionalProperty(sshConfigObject, "port", "number") || typeof sshPort === "number" && (sshPort < 1 || sshPort > 65535)) {
          diagnostics.errors.push(
            `${field}.${sshField}.port must be a number between 1 and 65535 inclusive`
          );
        }
      }
      if ("authorized_keys" in containerAppOptional) {
        validateSshPublicKeys(
          diagnostics,
          `${field}.authorized_keys`,
          containerAppOptional.authorized_keys,
          true
        );
      }
      if ("trusted_user_ca_keys" in containerAppOptional) {
        validateSshPublicKeys(
          diagnostics,
          `${field}.trusted_user_ca_keys`,
          containerAppOptional.trusted_user_ca_keys,
          false
        );
      }
      if (validateOptionalProperty(
        diagnostics,
        field,
        "constraints",
        containerAppOptional.constraints,
        "object"
      ) && containerAppOptional.constraints) {
        const constraints = containerAppOptional.constraints;
        if ("tier" in constraints) {
          diagnostics.warnings.push(
            `"constraints.tier" has been deprecated in favor of "constraints.tiers". Please update your configuration to use "constraints.tiers" instead.`
          );
          if ("tiers" in constraints) {
            diagnostics.errors.push(
              `${field}.constraints.tier and ${field}.constraints.tiers cannot both be set`
            );
          }
        }
        validateOptionalTypedArray(
          diagnostics,
          `${field}.constraints.tiers`,
          constraints.tiers,
          "number"
        );
        validateOptionalProperty(
          diagnostics,
          `${field}.constraints`,
          "jurisdiction",
          constraints.jurisdiction,
          "string"
        );
        if (constraints.jurisdiction && !["eu", "fedramp"].includes(constraints.jurisdiction)) {
          diagnostics.errors.push(
            `${field}.constraints.jurisdiction must be one of: "eu", "fedramp"`
          );
        }
        if (validateOptionalTypedArray(
          diagnostics,
          `${field}.constraints.regions`,
          constraints.regions,
          "string"
        ) && constraints.regions && Array.isArray(constraints.regions)) {
          const validRegions = [
            "ENAM",
            "WNAM",
            "EEUR",
            "WEUR",
            "APAC",
            "SAM",
            "ME",
            "OC",
            "AFR"
          ];
          for (const region of constraints.regions) {
            if (typeof region === "string" && !validRegions.includes(region.toUpperCase())) {
              diagnostics.errors.push(
                `${field}.constraints.regions contains invalid region "${region}". Valid regions are: ${validRegions.join(", ")}`
              );
            }
          }
        }
      }
      if (typeof containerAppOptional.instance_type === "string") {
        validateOptionalProperty(
          diagnostics,
          field,
          "instance_type",
          containerAppOptional.instance_type,
          "string",
          ALLOWED_INSTANCE_TYPES
        );
        if (containerAppOptional.instance_type === "dev") {
          diagnostics.warnings.push(
            `The "dev" instance_type has been renamed to "lite" and will be removed in a subsequent version. Please update your configuration to use "lite" instead.`
          );
        }
        if (containerAppOptional.instance_type === "standard") {
          diagnostics.warnings.push(
            `The "standard" instance_type has been renamed to "standard-1" and will be removed in a subsequent version. Please update your configuration to use "standard-1" instead.`
          );
        }
      } else if (validateOptionalProperty(
        diagnostics,
        field,
        "instance_type",
        containerAppOptional.instance_type,
        "object"
      ) && containerAppOptional.instance_type) {
        const instanceTypeProperties = ["vcpu", "memory_mib", "disk_mb"];
        instanceTypeProperties.forEach((key) => {
          if (!isOptionalProperty(
            containerAppOptional.instance_type,
            key,
            "number"
          )) {
            diagnostics.errors.push(
              `"containers.instance_type.${key}", when present, should be a number.`
            );
          }
        });
        validateAdditionalProperties(
          diagnostics,
          `${field}.instance_type`,
          Object.keys(containerAppOptional.instance_type),
          instanceTypeProperties
        );
      }
    }
    if (diagnostics.errors.length > 0) {
      return false;
    }
    return true;
  };
}
__name(validateContainerApp, "validateContainerApp");
var validateCloudchamberConfig = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
    diagnostics.errors.push(
      `"cloudchamber" should be an object, but got ${JSON.stringify(value)}`
    );
    return false;
  }
  const optionalAttrsByType = {
    string: ["memory", "image", "location"],
    boolean: ["ipv4"],
    number: ["vcpu"]
  };
  let isValid = true;
  Object.entries(optionalAttrsByType).forEach(([attrType, attrNames]) => {
    attrNames.forEach((key) => {
      if (!isOptionalProperty(value, key, attrType)) {
        diagnostics.errors.push(
          `"${field}" bindings should, optionally, have a ${attrType} "${key}" field but got ${JSON.stringify(
            value
          )}.`
        );
        isValid = false;
      }
    });
  });
  if ("instance_type" in value && value.instance_type !== void 0) {
    if (typeof value.instance_type !== "string" || !ALLOWED_INSTANCE_TYPES.includes(value.instance_type)) {
      diagnostics.errors.push(
        `"instance_type" should be one of 'lite', 'basic', 'standard-1', 'standard-2', 'standard-3', or 'standard-4', but got ${value.instance_type}`
      );
    }
    if ("memory" in value && value.memory !== void 0 || "vcpu" in value && value.vcpu !== void 0) {
      diagnostics.errors.push(
        `"${field}" configuration should not set either "memory" or "vcpu" with "instance_type"`
      );
    }
  }
  return isValid;
}, "validateCloudchamberConfig");
var validateKVBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"kv_namespaces" bindings should be objects, but got ${JSON.stringify(
        value
      )}`
    );
    return false;
  }
  let isValid = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isOptionalProperty(value, "id", "string") || value.id !== void 0 && value.id.length === 0) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "id" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isOptionalProperty(value, "preview_id", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should, optionally, have a string "preview_id" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "id",
    "preview_id",
    "remote"
  ]);
  return isValid;
}, "validateKVBinding");
var validateSendEmailBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"send_email" bindings should be objects, but got ${JSON.stringify(
        value
      )}`
    );
    return false;
  }
  let isValid = true;
  if (!isRequiredProperty(value, "name", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "name" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isOptionalProperty(value, "destination_address", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should, optionally, have a string "destination_address" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isOptionalProperty(value, "allowed_destination_addresses", "object")) {
    diagnostics.errors.push(
      `"${field}" bindings should, optionally, have a []string "allowed_destination_addresses" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isOptionalProperty(value, "allowed_sender_addresses", "object")) {
    diagnostics.errors.push(
      `"${field}" bindings should, optionally, have a []string "allowed_sender_addresses" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if ("destination_address" in value && "allowed_destination_addresses" in value) {
    diagnostics.errors.push(
      `"${field}" bindings should have either a "destination_address" or "allowed_destination_addresses" field, but not both.`
    );
    isValid = false;
  }
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "allowed_sender_addresses",
    "allowed_destination_addresses",
    "destination_address",
    "name",
    "binding",
    "remote"
  ]);
  return isValid;
}, "validateSendEmailBinding");
var validateQueueBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"queue" bindings should be objects, but got ${JSON.stringify(value)}`
    );
    return false;
  }
  if (!validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "queue",
    "delivery_delay",
    "remote"
  ])) {
    return false;
  }
  let isValid = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isOptionalProperty(value, "queue", "string") || hasProperty(value, "queue") && value.queue === "") {
    diagnostics.errors.push(
      `"${field}" bindings should optionally have a non-empty string "queue" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  const options = [{ key: "delivery_delay", type: "number" }];
  for (const optionalOpt of options) {
    if (!isOptionalProperty(value, optionalOpt.key, optionalOpt.type)) {
      diagnostics.errors.push(
        `"${field}" should, optionally, have a ${optionalOpt.type} "${optionalOpt.key}" field but got ${JSON.stringify(value)}.`
      );
      isValid = false;
    }
  }
  if (hasProperty(value, "delivery_delay") && value.delivery_delay !== void 0) {
    diagnostics.warnings.push(
      `The "delivery_delay" field in "${field}" is deprecated and has no effect. Queue-level settings should be configured using "wrangler queues update" instead. This setting will be removed in a future version.`
    );
  }
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid = false;
  }
  return isValid;
}, "validateQueueBinding");
var validateR2Binding = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"r2_buckets" bindings should be objects, but got ${JSON.stringify(
        value
      )}`
    );
    return false;
  }
  let isValid = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isOptionalProperty(value, "bucket_name", "string") || value.bucket_name !== void 0 && value.bucket_name.length === 0) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "bucket_name" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (isValid && hasProperty(value, "bucket_name") && !isValidR2BucketName(value.bucket_name)) {
    diagnostics.errors.push(
      `${field}.bucket_name=${JSON.stringify(value.bucket_name)} is invalid. ${bucketFormatMessage}`
    );
    isValid = false;
  }
  if (!isOptionalProperty(value, "preview_bucket_name", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should, optionally, have a string "preview_bucket_name" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (isValid && hasProperty(value, "preview_bucket_name") && !isValidR2BucketName(value.preview_bucket_name)) {
    diagnostics.errors.push(
      `${field}.preview_bucket_name= ${JSON.stringify(value.preview_bucket_name)} is invalid. ${bucketFormatMessage}`
    );
    isValid = false;
  }
  if (!isOptionalProperty(value, "jurisdiction", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should, optionally, have a string "jurisdiction" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid = false;
  }
  if (hasProperty(value, "local_dev")) {
    const localDev = value.local_dev;
    if (typeof localDev !== "object" || localDev === null) {
      diagnostics.errors.push(
        `"${field}" bindings should, optionally, have an object "local_dev" field but got ${JSON.stringify(
          value
        )}.`
      );
      isValid = false;
    } else {
      experimental(
        diagnostics,
        { local_dev: localDev },
        "local_dev.experimental_s3_credentials"
      );
      if (hasProperty(localDev, "experimental_s3_credentials")) {
        const credentials = localDev.experimental_s3_credentials;
        if (typeof credentials !== "object" || credentials === null || !isRequiredProperty(credentials, "accessKeyId", "string") || !isRequiredProperty(credentials, "secretAccessKey", "string")) {
          diagnostics.errors.push(
            `"${field}" bindings should, optionally, have a "local_dev.experimental_s3_credentials" field with string "accessKeyId" and "secretAccessKey" fields, but got ${JSON.stringify(
              value
            )}.`
          );
          isValid = false;
        }
      }
      validateAdditionalProperties(
        diagnostics,
        `${field}.local_dev`,
        Object.keys(localDev),
        ["experimental_s3_credentials"]
      );
    }
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "bucket_name",
    "preview_bucket_name",
    "jurisdiction",
    "remote",
    "local_dev"
  ]);
  return isValid;
}, "validateR2Binding");
var validateD1Binding = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"d1_databases" bindings should be objects, but got ${JSON.stringify(
        value
      )}`
    );
    return false;
  }
  let isValid = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isOptionalProperty(value, "database_id", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a "database_id" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isOptionalProperty(value, "preview_database_id", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should, optionally, have a string "preview_database_id" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid = false;
  }
  if (!isOptionalProperty(value, "migrations_pattern", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should, optionally, have a string "migrations_pattern" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isOptionalProperty(value, "database_name", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should, optionally, have a string "database_name" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isOptionalProperty(value, "migrations_dir", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should, optionally, have a string "migrations_dir" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isOptionalProperty(value, "migrations_table", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should, optionally, have a string "migrations_table" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isOptionalProperty(value, "database_internal_env", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should, optionally, have a string "database_internal_env" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "database_id",
    "database_internal_env",
    "database_name",
    "migrations_dir",
    "migrations_pattern",
    "migrations_table",
    "preview_database_id",
    "remote"
  ]);
  return isValid;
}, "validateD1Binding");
var validateVectorizeBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"vectorize" bindings should be objects, but got ${JSON.stringify(value)}`
    );
    return false;
  }
  let isValid = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isRequiredProperty(value, "index_name", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have an "index_name" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "index_name",
    "remote"
  ]);
  return isValid;
}, "validateVectorizeBinding");
var validateAISearchNamespaceBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"ai_search_namespaces" bindings should be objects, but got ${JSON.stringify(value)}`
    );
    return false;
  }
  let isValid = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(value)}.`
    );
    isValid = false;
  }
  if (!isRequiredProperty(value, "namespace", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a "namespace" field but got ${JSON.stringify(value)}.`
    );
    isValid = false;
  }
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "namespace",
    "remote"
  ]);
  return isValid;
}, "validateAISearchNamespaceBinding");
var validateAISearchBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"ai_search" bindings should be objects, but got ${JSON.stringify(value)}`
    );
    return false;
  }
  let isValid = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(value)}.`
    );
    isValid = false;
  }
  if (!isRequiredProperty(value, "instance_name", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have an "instance_name" field but got ${JSON.stringify(value)}.`
    );
    isValid = false;
  }
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "instance_name",
    "remote"
  ]);
  return isValid;
}, "validateAISearchBinding");
var validateAgentMemoryBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"agent_memory" bindings should be objects, but got ${JSON.stringify(value)}`
    );
    return false;
  }
  let isValid = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(value)}.`
    );
    isValid = false;
  }
  if (!isRequiredProperty(value, "namespace", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a "namespace" field but got ${JSON.stringify(value)}.`
    );
    isValid = false;
  }
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "namespace",
    "remote"
  ]);
  return isValid;
}, "validateAgentMemoryBinding");
var validateHyperdriveBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"hyperdrive" bindings should be objects, but got ${JSON.stringify(
        value
      )}`
    );
    return false;
  }
  let isValid = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isRequiredProperty(value, "id", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a "id" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "id",
    "localConnectionString"
  ]);
  return isValid;
}, "validateHyperdriveBinding");
var validateVpcServiceBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"vpc_services" bindings should be objects, but got ${JSON.stringify(
        value
      )}`
    );
    return false;
  }
  let isValid = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isRequiredProperty(value, "service_id", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a "service_id" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "service_id",
    "remote"
  ]);
  return isValid;
}, "validateVpcServiceBinding");
var validateVpcNetworkBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"vpc_networks" bindings should be objects, but got ${JSON.stringify(
        value
      )}`
    );
    return false;
  }
  let isValid = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  const hasTunnelId = hasProperty(value, "tunnel_id");
  const hasNetworkId = hasProperty(value, "network_id");
  if (hasTunnelId && hasNetworkId) {
    diagnostics.errors.push(
      `"${field}" bindings must have either a "tunnel_id" or "network_id", but not both.`
    );
    isValid = false;
  } else if (!hasTunnelId && !hasNetworkId) {
    diagnostics.errors.push(
      `"${field}" bindings must have either a "tunnel_id" or "network_id" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  } else if (hasTunnelId && typeof value.tunnel_id !== "string") {
    diagnostics.errors.push(
      `"${field}" bindings must have a string "tunnel_id" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  } else if (hasNetworkId && typeof value.network_id !== "string") {
    diagnostics.errors.push(
      `"${field}" bindings must have a string "network_id" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "tunnel_id",
    "network_id",
    "remote"
  ]);
  return isValid;
}, "validateVpcNetworkBinding");
var validateBindingsHaveUniqueNames = /* @__PURE__ */ __name((diagnostics, config22) => {
  let hasDuplicates = false;
  const bindingNamesArray = Object.entries(friendlyBindingNames);
  const bindingsGroupedByType = Object.fromEntries(
    bindingNamesArray.map(([bindingType, binding]) => [
      binding,
      getBindingNames(
        bindingType === "queues" ? config22[bindingType]?.producers : config22[bindingType]
      )
    ])
  );
  bindingsGroupedByType["Secret"] = config22.secrets?.required ?? [];
  const bindingsGroupedByName = {};
  for (const bindingType in bindingsGroupedByType) {
    const bindingNames = bindingsGroupedByType[bindingType];
    for (const bindingName of bindingNames) {
      if (!(bindingName in bindingsGroupedByName)) {
        bindingsGroupedByName[bindingName] = [];
      }
      if (bindingName === "ASSETS" && isPagesConfig(config22)) {
        diagnostics.errors.push(
          `The name 'ASSETS' is reserved in Pages projects. Please use a different name for your ${bindingType} binding.`
        );
      }
      bindingsGroupedByName[bindingName].push(bindingType);
    }
  }
  for (const bindingName in bindingsGroupedByName) {
    const bindingTypes = bindingsGroupedByName[bindingName];
    if (bindingTypes.length < 2) {
      continue;
    }
    hasDuplicates = true;
    const sameType = bindingTypes.filter((type, i) => bindingTypes.indexOf(type) !== i).filter(
      (type, i, duplicateBindingTypes) => duplicateBindingTypes.indexOf(type) === i
    );
    const differentTypes = bindingTypes.filter(
      (type, i) => bindingTypes.indexOf(type) === i
    );
    if (differentTypes.length > 1) {
      diagnostics.errors.push(
        `${bindingName} assigned to ${ENGLISH.format(differentTypes)} bindings.`
      );
    }
    sameType.forEach((bindingType) => {
      diagnostics.errors.push(
        `${bindingName} assigned to multiple ${bindingType} bindings.`
      );
    });
  }
  if (hasDuplicates) {
    const problem = "Bindings must have unique names, so that they can all be referenced in the worker.";
    const resolution = "Please change your bindings to have unique names.";
    diagnostics.errors.push(`${problem}
${resolution}`);
  }
  return !hasDuplicates;
}, "validateBindingsHaveUniqueNames");
var validateServiceBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"services" bindings should be objects, but got ${JSON.stringify(value)}`
    );
    return false;
  }
  let isValid = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isRequiredProperty(value, "service", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "service" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isOptionalProperty(value, "environment", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "environment" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isOptionalProperty(value, "entrypoint", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "entrypoint" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (hasProperty(value, "dev") && value.dev !== void 0) {
    if (typeof value.dev !== "object" || value.dev === null || Array.isArray(value.dev)) {
      diagnostics.errors.push(
        `"${field}" bindings should have an object "dev" field but got ${JSON.stringify(
          value.dev
        )}.`
      );
      isValid = false;
    } else {
      if (!hasProperty(value.dev, "plugin") || typeof value.dev.plugin !== "object" || value.dev.plugin === null || Array.isArray(value.dev.plugin)) {
        diagnostics.errors.push(
          `"${field}.dev" should have an object "plugin" field but got ${JSON.stringify(
            value.dev.plugin
          )}.`
        );
        isValid = false;
      } else {
        if (!isRequiredProperty(value.dev.plugin, "package", "string")) {
          diagnostics.errors.push(
            `"${field}.dev.plugin" should have a string "package" field but got ${JSON.stringify(
              value.dev.plugin.package
            )}.`
          );
          isValid = false;
        }
        if (!isRequiredProperty(value.dev.plugin, "name", "string")) {
          diagnostics.errors.push(
            `"${field}.dev.plugin" should have a string "name" field but got ${JSON.stringify(
              value.dev.plugin.name
            )}.`
          );
          isValid = false;
        }
      }
      if (hasProperty(value.dev, "options") && value.dev.options !== void 0 && (typeof value.dev.options !== "object" || value.dev.options === null || Array.isArray(value.dev.options))) {
        diagnostics.errors.push(
          `"${field}.dev.options" should be an object but got ${JSON.stringify(
            value.dev.options
          )}.`
        );
        isValid = false;
      }
    }
    if (value.remote === true) {
      diagnostics.warnings.push(
        `"${field}" binding has both "dev" and "remote" set; "remote" is ignored when "dev" is present and the binding is routed through the local Miniflare plugin.`
      );
    }
  }
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid = false;
  }
  return isValid;
}, "validateServiceBinding");
var validateAnalyticsEngineBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"analytics_engine" bindings should be objects, but got ${JSON.stringify(
        value
      )}`
    );
    return false;
  }
  let isValid = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isOptionalProperty(value, "dataset", "string") || value.dataset?.length === 0) {
    diagnostics.errors.push(
      `"${field}" bindings should, optionally, have a string "dataset" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "dataset"
  ]);
  return isValid;
}, "validateAnalyticsEngineBinding");
var validateWorkerNamespaceBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"${field}" binding should be objects, but got ${JSON.stringify(value)}`
    );
    return false;
  }
  let isValid = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" should have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isOptionalProperty(value, "namespace", "string")) {
    diagnostics.errors.push(
      `"${field}" should optionally have a string "namespace" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (hasProperty(value, "outbound")) {
    if (!validateWorkerNamespaceOutbound(
      diagnostics,
      `${field}.outbound`,
      value.outbound ?? {}
    )) {
      diagnostics.errors.push(`"${field}" has an invalid outbound definition.`);
      isValid = false;
    }
  }
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid = false;
  }
  return isValid;
}, "validateWorkerNamespaceBinding");
function validateWorkerNamespaceOutbound(diagnostics, field, value) {
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"${field}" should be an object, but got ${JSON.stringify(value)}`
    );
    return false;
  }
  let isValid = true;
  isValid = isValid && validateRequiredProperty(
    diagnostics,
    field,
    "service",
    value.service,
    "string"
  );
  isValid = isValid && validateOptionalProperty(
    diagnostics,
    field,
    "environment",
    value.environment,
    "string"
  );
  isValid = isValid && validateOptionalTypedArray(
    diagnostics,
    `${field}.parameters`,
    value.parameters,
    "string"
  );
  return isValid;
}
__name(validateWorkerNamespaceOutbound, "validateWorkerNamespaceOutbound");
var validateMTlsCertificateBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"mtls_certificates" bindings should be objects, but got ${JSON.stringify(
        value
      )}`
    );
    return false;
  }
  let isValid = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isRequiredProperty(value, "certificate_id", "string") || value.certificate_id.length === 0) {
    diagnostics.errors.push(
      `"${field}" bindings should have a string "certificate_id" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "certificate_id",
    "remote"
  ]);
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid = false;
  }
  return isValid;
}, "validateMTlsCertificateBinding");
function validateQueues(envName) {
  return (diagnostics, field, value, config22) => {
    if (value === void 0) {
      return true;
    }
    const fieldPath = config22 === void 0 ? `${field}` : `env.${envName}.${field}`;
    if (typeof value !== "object" || Array.isArray(value) || value === null) {
      diagnostics.errors.push(
        `The field "${fieldPath}" should be an object but got ${JSON.stringify(
          value
        )}.`
      );
      return false;
    }
    let isValid = true;
    if (!validateAdditionalProperties(
      diagnostics,
      fieldPath,
      Object.keys(value),
      ["consumers", "producers"]
    )) {
      isValid = false;
    }
    if (hasProperty(value, "consumers")) {
      const consumers = value.consumers;
      if (!Array.isArray(consumers)) {
        diagnostics.errors.push(
          `The field "${fieldPath}.consumers" should be an array but got ${JSON.stringify(
            consumers
          )}.`
        );
        isValid = false;
      } else {
        for (let i = 0; i < consumers.length; i++) {
          const consumer = consumers[i];
          const consumerPath = `${fieldPath}.consumers[${i}]`;
          if (!validateConsumer(diagnostics, consumerPath, consumer, config22)) {
            isValid = false;
          }
        }
      }
    }
    if (hasProperty(value, "producers")) {
      if (!validateBindingArray(envName, validateQueueBinding)(
        diagnostics,
        `${field}.producers`,
        value.producers,
        config22
      )) {
        isValid = false;
      }
    }
    return isValid;
  };
}
__name(validateQueues, "validateQueues");
var validateConsumer = /* @__PURE__ */ __name((diagnostics, field, value, _config) => {
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"${field}" should be a objects, but got ${JSON.stringify(value)}`
    );
    return false;
  }
  let isValid = true;
  if (!validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "queue",
    "type",
    "max_batch_size",
    "max_batch_timeout",
    "max_retries",
    "dead_letter_queue",
    "max_concurrency",
    "visibility_timeout_ms",
    "retry_delay"
  ])) {
    isValid = false;
  }
  if (!isRequiredProperty(value, "queue", "string")) {
    diagnostics.errors.push(
      `"${field}" should have a string "queue" field but got ${JSON.stringify(
        value
      )}.`
    );
  }
  if ("type" in value && value.type !== void 0 && value.type !== "worker") {
    diagnostics.errors.push(
      `"${field}.type" has an invalid value "${value.type}". Only "worker" consumers can be configured in your Wrangler configuration.`
    );
    isValid = false;
  }
  const options = [
    { key: "type", type: "string" },
    { key: "max_batch_size", type: "number" },
    { key: "max_batch_timeout", type: "number" },
    { key: "max_retries", type: "number" },
    { key: "dead_letter_queue", type: "string" },
    { key: "max_concurrency", type: "number" },
    { key: "visibility_timeout_ms", type: "number" },
    { key: "retry_delay", type: "number" }
  ];
  for (const optionalOpt of options) {
    if (!isOptionalProperty(value, optionalOpt.key, optionalOpt.type)) {
      diagnostics.errors.push(
        `"${field}" should, optionally, have a ${optionalOpt.type} "${optionalOpt.key}" field but got ${JSON.stringify(value)}.`
      );
      isValid = false;
    }
  }
  return isValid;
}, "validateConsumer");
var validateCompatibilityDate = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (value === void 0) {
    return true;
  }
  if (typeof value !== "string") {
    diagnostics.errors.push(
      `Expected "${field}" to be of type string but got ${JSON.stringify(value)}.`
    );
    return false;
  }
  return isValidDateTimeStringFormat(diagnostics, field, value);
}, "validateCompatibilityDate");
var validatePipelineBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"pipeline" bindings should be objects, but got ${JSON.stringify(value)}`
    );
    return false;
  }
  let isValid = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  const hasStream = isOptionalProperty(value, "stream", "string");
  const hasPipeline = isOptionalProperty(value, "pipeline", "string");
  const v = value;
  if (hasStream && v.stream) ;
  else if (hasPipeline && v.pipeline) {
    diagnostics.warnings.push(
      `The "pipeline" field in "${field}" bindings is deprecated. Use "stream" instead.`
    );
  } else {
    diagnostics.errors.push(
      `"${field}" bindings must have a string "stream" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "stream",
    "pipeline",
    "remote"
  ]);
  return isValid;
}, "validatePipelineBinding");
var validateSecretsStoreSecretBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"secrets_store_secrets" bindings should be objects, but got ${JSON.stringify(value)}`
    );
    return false;
  }
  let isValid = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isRequiredProperty(value, "store_id", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a string "store_id" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isRequiredProperty(value, "secret_name", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a string "secret_name" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "store_id",
    "secret_name"
  ]);
  return isValid;
}, "validateSecretsStoreSecretBinding");
var validateArtifactsBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"artifacts" bindings should be objects, but got ${JSON.stringify(value)}`
    );
    return false;
  }
  let isValid = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isRequiredProperty(value, "namespace", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a string "namespace" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "namespace",
    "remote"
  ]);
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid = false;
  }
  return isValid;
}, "validateArtifactsBinding");
var validateHelloWorldBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"unsafe_hello_world" bindings should be objects, but got ${JSON.stringify(value)}`
    );
    return false;
  }
  let isValid = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isOptionalProperty(value, "enable_timer", "boolean")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a boolean "enable_timer" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "enable_timer"
  ]);
  return isValid;
}, "validateHelloWorldBinding");
var validateFlagshipBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"flagship" bindings should be objects, but got ${JSON.stringify(value)}`
    );
    return false;
  }
  let isValid = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isOptionalProperty(value, "app_id", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings may have a string "app_id" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding",
    "app_id",
    "remote"
  ]);
  if (!isRemoteValid(value, field, diagnostics)) {
    isValid = false;
  }
  return isValid;
}, "validateFlagshipBinding");
var validateWorkerLoaderBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"worker_loader" bindings should be objects, but got ${JSON.stringify(value)}`
    );
    return false;
  }
  let isValid = true;
  if (!isRequiredProperty(value, "binding", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a string "binding" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "binding"
  ]);
  return isValid;
}, "validateWorkerLoaderBinding");
var validateRateLimitBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"ratelimits" bindings should be objects, but got ${JSON.stringify(value)}`
    );
    return false;
  }
  let isValid = true;
  if (!isRequiredProperty(value, "name", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a string "name" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!isRequiredProperty(value, "namespace_id", "string")) {
    diagnostics.errors.push(
      `"${field}" bindings must have a string "namespace_id" field but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  }
  if (!hasProperty(value, "simple") || typeof value.simple !== "object" || value.simple === null) {
    diagnostics.errors.push(
      `"${field}" bindings must have a "simple" configuration object but got ${JSON.stringify(
        value
      )}.`
    );
    isValid = false;
  } else {
    if (!isRequiredProperty(value.simple, "limit", "number")) {
      diagnostics.errors.push(
        `"${field}" bindings "simple.limit" must be a number but got ${JSON.stringify(
          value.simple
        )}.`
      );
      isValid = false;
    }
    if (!isRequiredProperty(value.simple, "period", "number")) {
      diagnostics.errors.push(
        `"${field}" bindings "simple.period" is required and must be a number but got ${JSON.stringify(
          value.simple
        )}.`
      );
      isValid = false;
    } else if (![10, 60].includes(value.simple.period)) {
      diagnostics.errors.push(
        `"${field}" bindings "simple.period" must be either 10 or 60 but got ${JSON.stringify(
          value.simple.period
        )}.`
      );
      isValid = false;
    }
    validateAdditionalProperties(
      diagnostics,
      `${field}.simple`,
      Object.keys(value.simple),
      ["limit", "period"]
    );
  }
  validateAdditionalProperties(diagnostics, field, Object.keys(value), [
    "name",
    "namespace_id",
    "simple"
  ]);
  return isValid;
}, "validateRateLimitBinding");
function normalizeAndValidateLimits(diagnostics, topLevelEnv, rawEnv) {
  if (rawEnv.limits) {
    validateOptionalProperty(
      diagnostics,
      "limits",
      "cpu_ms",
      rawEnv.limits.cpu_ms,
      "number"
    );
    validateOptionalProperty(
      diagnostics,
      "limits",
      "subrequests",
      rawEnv.limits.subrequests,
      "number"
    );
  }
  return inheritable(
    diagnostics,
    topLevelEnv,
    rawEnv,
    "limits",
    () => true,
    void 0
  );
}
__name(normalizeAndValidateLimits, "normalizeAndValidateLimits");
var validatePreviewsConfig = /* @__PURE__ */ __name((envName) => (diagnostics, field, value) => {
  if (value === void 0) {
    return true;
  }
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
    diagnostics.errors.push(
      `The field "${field}" should be an object but got ${JSON.stringify(
        value
      )}.`
    );
    return false;
  }
  const previews = value;
  let isValid = true;
  isValid = validateAdditionalProperties(diagnostics, field, Object.keys(previews), [
    "vars",
    "define",
    "durable_objects",
    "workflows",
    "kv_namespaces",
    "send_email",
    "queues",
    "d1_databases",
    "r2_buckets",
    "vectorize",
    "hyperdrive",
    "services",
    "analytics_engine_datasets",
    "dispatch_namespaces",
    "mtls_certificates",
    "tail_consumers",
    "streaming_tail_consumers",
    "unsafe",
    "browser",
    "ai",
    "images",
    "stream",
    "media",
    "pipelines",
    "secrets_store_secrets",
    "artifacts",
    "unsafe_hello_world",
    "flagship",
    "worker_loaders",
    "ratelimits",
    "vpc_services",
    "version_metadata",
    "logpush",
    "observability",
    "limits",
    "cache"
  ]) && isValid;
  isValid = validateVars(envName)(
    diagnostics,
    `${field}.vars`,
    previews.vars,
    void 0
  ) && isValid;
  isValid = validateDefines(envName)(
    diagnostics,
    `${field}.define`,
    previews.define,
    void 0
  ) && isValid;
  isValid = validateBindingsProperty(envName, validateDurableObjectBinding)(
    diagnostics,
    `${field}.durable_objects`,
    previews.durable_objects,
    void 0
  ) && isValid;
  isValid = all(
    validateBindingArray(envName, validateWorkflowBinding),
    validateUniqueNameProperty
  )(diagnostics, `${field}.workflows`, previews.workflows, void 0) && isValid;
  isValid = validateBindingArray(envName, validateKVBinding)(
    diagnostics,
    `${field}.kv_namespaces`,
    previews.kv_namespaces,
    void 0
  ) && isValid;
  isValid = validateBindingArray(envName, validateSendEmailBinding)(
    diagnostics,
    `${field}.send_email`,
    previews.send_email,
    void 0
  ) && isValid;
  isValid = validateQueues(envName)(
    diagnostics,
    `${field}.queues`,
    previews.queues,
    void 0
  ) && isValid;
  isValid = validateBindingArray(envName, validateD1Binding)(
    diagnostics,
    `${field}.d1_databases`,
    previews.d1_databases,
    void 0
  ) && isValid;
  isValid = validateBindingArray(envName, validateR2Binding)(
    diagnostics,
    `${field}.r2_buckets`,
    previews.r2_buckets,
    void 0
  ) && isValid;
  isValid = validateBindingArray(envName, validateVectorizeBinding)(
    diagnostics,
    `${field}.vectorize`,
    previews.vectorize,
    void 0
  ) && isValid;
  isValid = validateBindingArray(envName, validateHyperdriveBinding)(
    diagnostics,
    `${field}.hyperdrive`,
    previews.hyperdrive,
    void 0
  ) && isValid;
  isValid = validateBindingArray(envName, validateServiceBinding)(
    diagnostics,
    `${field}.services`,
    previews.services,
    void 0
  ) && isValid;
  isValid = validateBindingArray(envName, validateAnalyticsEngineBinding)(
    diagnostics,
    `${field}.analytics_engine_datasets`,
    previews.analytics_engine_datasets,
    void 0
  ) && isValid;
  isValid = validateBindingArray(envName, validateWorkerNamespaceBinding)(
    diagnostics,
    `${field}.dispatch_namespaces`,
    previews.dispatch_namespaces,
    void 0
  ) && isValid;
  isValid = validateBindingArray(envName, validateMTlsCertificateBinding)(
    diagnostics,
    `${field}.mtls_certificates`,
    previews.mtls_certificates,
    void 0
  ) && isValid;
  isValid = validateTailConsumers(
    diagnostics,
    `${field}.tail_consumers`,
    previews.tail_consumers,
    void 0
  ) && isValid;
  isValid = validateStreamingTailConsumers(
    diagnostics,
    `${field}.streaming_tail_consumers`,
    previews.streaming_tail_consumers,
    void 0
  ) && isValid;
  if (previews.unsafe !== void 0) {
    isValid = validateUnsafeSettings(envName)(
      diagnostics,
      `${field}.unsafe`,
      previews.unsafe,
      void 0
    ) && isValid;
  }
  if (previews.browser !== void 0) {
    isValid = validateNamedSimpleBinding(envName)(
      diagnostics,
      `${field}.browser`,
      previews.browser,
      void 0
    ) && isValid;
  }
  if (previews.ai !== void 0) {
    isValid = validateAIBinding(envName)(
      diagnostics,
      `${field}.ai`,
      previews.ai,
      void 0
    ) && isValid;
  }
  if (previews.images !== void 0) {
    isValid = validateNamedSimpleBinding(envName)(
      diagnostics,
      `${field}.images`,
      previews.images,
      void 0
    ) && isValid;
  }
  if (previews.stream !== void 0) {
    isValid = validateNamedSimpleBinding(envName)(
      diagnostics,
      `${field}.stream`,
      previews.stream,
      void 0
    ) && isValid;
  }
  if (previews.media !== void 0) {
    isValid = validateNamedSimpleBinding(envName)(
      diagnostics,
      `${field}.media`,
      previews.media,
      void 0
    ) && isValid;
  }
  isValid = validateBindingArray(envName, validatePipelineBinding)(
    diagnostics,
    `${field}.pipelines`,
    previews.pipelines,
    void 0
  ) && isValid;
  isValid = validateBindingArray(envName, validateSecretsStoreSecretBinding)(
    diagnostics,
    `${field}.secrets_store_secrets`,
    previews.secrets_store_secrets,
    void 0
  ) && isValid;
  isValid = validateBindingArray(envName, validateArtifactsBinding)(
    diagnostics,
    `${field}.artifacts`,
    previews.artifacts,
    void 0
  ) && isValid;
  isValid = validateBindingArray(envName, validateHelloWorldBinding)(
    diagnostics,
    `${field}.unsafe_hello_world`,
    previews.unsafe_hello_world,
    void 0
  ) && isValid;
  isValid = validateBindingArray(envName, validateFlagshipBinding)(
    diagnostics,
    `${field}.flagship`,
    previews.flagship,
    void 0
  ) && isValid;
  isValid = validateBindingArray(envName, validateWorkerLoaderBinding)(
    diagnostics,
    `${field}.worker_loaders`,
    previews.worker_loaders,
    void 0
  ) && isValid;
  isValid = validateBindingArray(envName, validateRateLimitBinding)(
    diagnostics,
    `${field}.ratelimits`,
    previews.ratelimits,
    void 0
  ) && isValid;
  isValid = validateBindingArray(envName, validateVpcServiceBinding)(
    diagnostics,
    `${field}.vpc_services`,
    previews.vpc_services,
    void 0
  ) && isValid;
  if (previews.version_metadata !== void 0) {
    isValid = validateVersionMetadataBinding(envName)(
      diagnostics,
      `${field}.version_metadata`,
      previews.version_metadata,
      void 0
    ) && isValid;
  }
  isValid = isBoolean(diagnostics, `${field}.logpush`, previews.logpush, void 0) && isValid;
  isValid = validateObservability(
    diagnostics,
    `${field}.observability`,
    previews.observability,
    void 0
  ) && isValid;
  if (previews.limits) {
    isValid = validateOptionalProperty(
      diagnostics,
      `${field}.limits`,
      "cpu_ms",
      previews.limits.cpu_ms,
      "number"
    ) && isValid;
    isValid = validateOptionalProperty(
      diagnostics,
      `${field}.limits`,
      "subrequests",
      previews.limits.subrequests,
      "number"
    ) && isValid;
  }
  isValid = validateCache(diagnostics, `${field}.cache`, previews.cache, void 0) && isValid;
  return isValid;
}, "validatePreviewsConfig");
var validateMigrations = /* @__PURE__ */ __name((diagnostics, field, value) => {
  const rawMigrations = value ?? [];
  if (!Array.isArray(rawMigrations)) {
    diagnostics.errors.push(
      `The optional "${field}" field should be an array, but got ${JSON.stringify(
        rawMigrations
      )}`
    );
    return false;
  }
  let valid = true;
  for (let i = 0; i < rawMigrations.length; i++) {
    const {
      tag,
      new_classes,
      new_sqlite_classes,
      renamed_classes,
      deleted_classes,
      transferred_classes,
      ...rest
    } = rawMigrations[i];
    valid = validateAdditionalProperties(
      diagnostics,
      "migrations",
      Object.keys(rest),
      []
    ) && valid;
    valid = validateRequiredProperty(
      diagnostics,
      `migrations[${i}]`,
      `tag`,
      tag,
      "string"
    ) && valid;
    valid = validateOptionalTypedArray(
      diagnostics,
      `migrations[${i}].new_classes`,
      new_classes,
      "string"
    ) && valid;
    valid = validateOptionalTypedArray(
      diagnostics,
      `migrations[${i}].new_sqlite_classes`,
      new_sqlite_classes,
      "string"
    ) && valid;
    if (renamed_classes !== void 0) {
      if (!Array.isArray(renamed_classes)) {
        diagnostics.errors.push(
          `Expected "migrations[${i}].renamed_classes" to be an array of "{from: string, to: string}" objects but got ${JSON.stringify(
            renamed_classes
          )}.`
        );
        valid = false;
      } else if (renamed_classes.some(
        (c2) => typeof c2 !== "object" || !isRequiredProperty(c2, "from", "string") || !isRequiredProperty(c2, "to", "string")
      )) {
        diagnostics.errors.push(
          `Expected "migrations[${i}].renamed_classes" to be an array of "{from: string, to: string}" objects but got ${JSON.stringify(
            renamed_classes
          )}.`
        );
        valid = false;
      }
    }
    if (transferred_classes !== void 0) {
      if (!Array.isArray(transferred_classes)) {
        diagnostics.errors.push(
          `Expected "migrations[${i}].transferred_classes" to be an array of "{from: string, from_script: string, to: string}" objects but got ${JSON.stringify(
            transferred_classes
          )}.`
        );
        valid = false;
      } else if (transferred_classes.some(
        (c2) => typeof c2 !== "object" || !isRequiredProperty(c2, "from", "string") || !isRequiredProperty(c2, "from_script", "string") || !isRequiredProperty(c2, "to", "string")
      )) {
        diagnostics.errors.push(
          `Expected "migrations[${i}].transferred_classes" to be an array of "{from: string, from_script: string, to: string}" objects but got ${JSON.stringify(
            transferred_classes
          )}.`
        );
        valid = false;
      }
    }
    valid = validateOptionalTypedArray(
      diagnostics,
      `migrations[${i}].deleted_classes`,
      deleted_classes,
      "string"
    ) && valid;
  }
  return valid;
}, "validateMigrations");
var VALID_EXPORT_STORAGES = /* @__PURE__ */ new Set(["sqlite", "legacy-kv"]);
var JS_IDENTIFIER_RE = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
function validateDurableObjectExportProperties(diagnostics, className, durableObjectExport, allowedProperties) {
  let valid = true;
  for (const key of Object.keys(durableObjectExport)) {
    if (!allowedProperties.includes(key)) {
      diagnostics.errors.push(
        `"exports.${className}.${key}" is forbidden on state "${durableObjectExport.state ?? "created"}".`
      );
      valid = false;
    }
  }
  if (!valid) {
    diagnostics.errors.push(
      `Allowed properties are: ${ENGLISH.format(allowedProperties)}.`
    );
  }
  return valid;
}
__name(validateDurableObjectExportProperties, "validateDurableObjectExportProperties");
function validateDurableObjectExportContainer(diagnostics, className, durableObjectExport) {
  if (durableObjectExport.container === void 0) {
    return true;
  }
  if (typeof durableObjectExport.container !== "string" || durableObjectExport.container === "") {
    diagnostics.errors.push(
      `"exports.${className}.container" must be a non-empty string naming a container in the "containers" array, but got ${JSON.stringify(durableObjectExport.container)}.`
    );
    return false;
  }
  if (durableObjectExport.storage === "legacy-kv") {
    diagnostics.errors.push(
      `"exports.${className}.container" requires "storage" to be "sqlite". Containers are not supported on Durable Objects using the "legacy-kv" storage backend.`
    );
    return false;
  }
  return true;
}
__name(validateDurableObjectExportContainer, "validateDurableObjectExportContainer");
function validateDurableObjectExport(diagnostics, className, durableObjectExport) {
  let valid = true;
  if (className === "") {
    diagnostics.errors.push(`"export" keys cannot be the empty string.`);
    valid = false;
  }
  switch (durableObjectExport.state) {
    case void 0:
    case "created": {
      if (typeof durableObjectExport.storage !== "string" || !VALID_EXPORT_STORAGES.has(durableObjectExport.storage)) {
        diagnostics.errors.push(
          `"exports.${className}.storage" is required for state "created" and must be one of ${ENGLISH.format(VALID_EXPORT_STORAGES)}, but got ${JSON.stringify(durableObjectExport.storage)}`
        );
        valid = false;
      }
      valid = validateDurableObjectExportContainer(
        diagnostics,
        className,
        durableObjectExport
      ) && valid;
      valid = validateDurableObjectExportProperties(
        diagnostics,
        className,
        durableObjectExport,
        ["type", "state", "storage", "container"]
      ) && valid;
      break;
    }
    case "deleted": {
      valid = validateDurableObjectExportProperties(
        diagnostics,
        className,
        durableObjectExport,
        ["type", "state"]
      ) && valid;
      break;
    }
    case "renamed": {
      if (typeof durableObjectExport.renamed_to !== "string" || durableObjectExport.renamed_to === "") {
        diagnostics.errors.push(
          `"exports.${className}.renamed_to" is required for state "renamed" and must be a non-empty string.`
        );
        valid = false;
      } else {
        if (!JS_IDENTIFIER_RE.test(durableObjectExport.renamed_to)) {
          diagnostics.errors.push(
            `"exports.${className}.renamed_to" must be a valid JavaScript identifier (got "${durableObjectExport.renamed_to}").`
          );
          valid = false;
        }
        if (durableObjectExport.renamed_to === className) {
          diagnostics.errors.push(
            `"exports.${className}.renamed_to" cannot equal the source class name "${className}".`
          );
          valid = false;
        }
      }
      valid = validateDurableObjectExportProperties(
        diagnostics,
        className,
        durableObjectExport,
        ["type", "state", "renamed_to"]
      ) && valid;
      break;
    }
    case "transferred": {
      if (typeof durableObjectExport.transferred_to !== "string" || durableObjectExport.transferred_to === "") {
        diagnostics.errors.push(
          `"exports.${className}.transferred_to" is required for state "transferred" and must be a non-empty string.`
        );
        valid = false;
      }
      valid = validateDurableObjectExportProperties(
        diagnostics,
        className,
        durableObjectExport,
        ["type", "state", "transferred_to"]
      ) && valid;
      break;
    }
    case "expecting-transfer": {
      if (typeof durableObjectExport.storage !== "string" || !VALID_EXPORT_STORAGES.has(durableObjectExport.storage)) {
        diagnostics.errors.push(
          `"exports.${className}.storage" is required for state "expecting-transfer" and must be one of ${ENGLISH.format(VALID_EXPORT_STORAGES)}, but got ${JSON.stringify(durableObjectExport.storage)}`
        );
        valid = false;
      }
      if (typeof durableObjectExport.transfer_from !== "string" || durableObjectExport.transfer_from === "") {
        diagnostics.errors.push(
          `"exports.${className}.transfer_from" is required for state "expecting-transfer" and must be a non-empty string.`
        );
        valid = false;
      }
      valid = validateDurableObjectExportContainer(
        diagnostics,
        className,
        durableObjectExport
      ) && valid;
      valid = validateDurableObjectExportProperties(
        diagnostics,
        className,
        durableObjectExport,
        ["type", "state", "storage", "transfer_from", "container"]
      ) && valid;
      break;
    }
    default: {
      const state = durableObjectExport.state;
      diagnostics.errors.push(
        `"exports.${className}.state" must be one of "created", "deleted", "renamed", "transferred", or "expecting-transfer" but got ${JSON.stringify(state)}.`
      );
      valid = false;
    }
  }
  return valid;
}
__name(validateDurableObjectExport, "validateDurableObjectExport");
function validateWorkerExport(diagnostics, exportName, workerExport) {
  let valid = true;
  valid = validateAdditionalProperties(
    diagnostics,
    `exports.${exportName}`,
    Object.keys(workerExport),
    ["type", "cache"]
  ) && valid;
  valid = validateWorkerExportCache(
    diagnostics,
    `exports.${exportName}.cache`,
    workerExport.cache
  ) && valid;
  return valid;
}
__name(validateWorkerExport, "validateWorkerExport");
function validateWorkerExportCache(diagnostics, field, value) {
  if (value === void 0) {
    return true;
  }
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
    diagnostics.errors.push(
      `"${field}" should be an object but got ${JSON.stringify(value)}.`
    );
    return false;
  }
  const cache = value;
  let valid = true;
  valid = validateRequiredProperty(
    diagnostics,
    field,
    "enabled",
    cache.enabled,
    "boolean"
  ) && valid;
  valid = validateAdditionalProperties(diagnostics, field, Object.keys(cache), [
    "enabled"
  ]) && valid;
  return valid;
}
__name(validateWorkerExportCache, "validateWorkerExportCache");
var validateExports = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (value === void 0 || value === null) {
    return true;
  }
  if (typeof value !== "object" || Array.isArray(value)) {
    diagnostics.errors.push(
      `The optional "${field}" field should be an object keyed by class name, but got ${JSON.stringify(
        value
      )}`
    );
    return false;
  }
  let valid = true;
  for (const [exportName, exportConfig] of Object.entries(value)) {
    if (typeof exportConfig !== "object" || exportConfig === null) {
      diagnostics.errors.push(
        `"exports.${exportName}" should be an object but got ${JSON.stringify(
          exportConfig
        )}.`
      );
      valid = false;
      continue;
    }
    if (exportConfig.type === "durable-object") {
      valid = validateDurableObjectExport(diagnostics, exportName, exportConfig) && valid;
    } else if (exportConfig.type === "worker") {
      valid = validateWorkerExport(diagnostics, exportName, exportConfig) && valid;
    } else {
      valid = false;
      diagnostics.errors.push(
        `"exports.${exportName}.type" must be "durable-object" or "worker", but got ${JSON.stringify(exportConfig.type)}.`
      );
    }
  }
  return valid;
}, "validateExports");
var validateObservability = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (value === void 0) {
    return true;
  }
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"${field}" should be an object but got ${JSON.stringify(value)}.`
    );
    return false;
  }
  const val = value;
  let isValid = true;
  isValid = validateAtLeastOnePropertyRequired(diagnostics, field, [
    {
      key: "enabled",
      value: val.enabled,
      type: "boolean"
    },
    {
      key: "logs.enabled",
      value: val.logs?.enabled,
      type: "boolean"
    },
    {
      key: "traces.enabled",
      value: val.traces?.enabled,
      type: "boolean"
    }
  ]) && isValid;
  isValid = validateOptionalProperty(
    diagnostics,
    field,
    "head_sampling_rate",
    val.head_sampling_rate,
    "number"
  ) && isValid;
  isValid = validateOptionalProperty(diagnostics, field, "logs", val.logs, "object") && isValid;
  isValid = validateOptionalProperty(
    diagnostics,
    field,
    "traces",
    val.traces,
    "object"
  ) && isValid;
  isValid = validateAdditionalProperties(diagnostics, field, Object.keys(val), [
    "enabled",
    "head_sampling_rate",
    "logs",
    "traces"
  ]) && isValid;
  if (typeof val.logs === "object") {
    isValid = validateOptionalProperty(
      diagnostics,
      field,
      "logs.enabled",
      val.logs.enabled,
      "boolean"
    ) && isValid;
    isValid = validateOptionalProperty(
      diagnostics,
      field,
      "logs.head_sampling_rate",
      val.logs.head_sampling_rate,
      "number"
    ) && isValid;
    isValid = validateOptionalProperty(
      diagnostics,
      field,
      "logs.invocation_logs",
      val.logs.invocation_logs,
      "boolean"
    ) && isValid;
    isValid = validateOptionalTypedArray(
      diagnostics,
      "logs.destinations",
      val.logs?.destinations,
      "string"
    ) && isValid;
    isValid = validateOptionalProperty(
      diagnostics,
      field,
      "logs.persist",
      val.logs.persist,
      "boolean"
    ) && isValid;
    isValid = validateAdditionalProperties(diagnostics, field, Object.keys(val.logs), [
      "enabled",
      "head_sampling_rate",
      "invocation_logs",
      "destinations",
      "persist"
    ]) && isValid;
  }
  if (typeof val.traces === "object") {
    isValid = validateOptionalProperty(
      diagnostics,
      field,
      "traces.enabled",
      val.traces.enabled,
      "boolean"
    ) && isValid;
    isValid = validateOptionalProperty(
      diagnostics,
      field,
      "traces.head_sampling_rate",
      val.traces.head_sampling_rate,
      "number"
    ) && isValid;
    isValid = validateOptionalTypedArray(
      diagnostics,
      "traces.destinations",
      val.traces?.destinations,
      "string"
    ) && isValid;
    isValid = validateOptionalProperty(
      diagnostics,
      field,
      "traces.persist",
      val.traces.persist,
      "boolean"
    ) && isValid;
    isValid = validateAdditionalProperties(
      diagnostics,
      field,
      Object.keys(val.traces),
      ["enabled", "head_sampling_rate", "destinations", "persist"]
    ) && isValid;
  }
  validateHeadSamplingRate(
    diagnostics,
    field,
    "head_sampling_rate",
    val?.head_sampling_rate
  );
  validateHeadSamplingRate(
    diagnostics,
    field,
    "logs.head_sampling_rate",
    val?.logs?.head_sampling_rate
  );
  validateHeadSamplingRate(
    diagnostics,
    field,
    "traces.head_sampling_rate",
    val?.traces?.head_sampling_rate
  );
  return isValid;
}, "validateObservability");
function validateHeadSamplingRate(diagnostics, container, key, samplingRate) {
  if (samplingRate && (samplingRate < 0 || samplingRate > 1)) {
    diagnostics.errors.push(
      `"${container}.${key}" must be a value between 0 and 1.`
    );
  }
}
__name(validateHeadSamplingRate, "validateHeadSamplingRate");
var validateAccess = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (value === void 0) {
    return true;
  }
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"${field}" should be an object but got ${JSON.stringify(value)}.`
    );
    return false;
  }
  const val = value;
  let isValid = true;
  isValid = validateOptionalProperty(diagnostics, field, "dev", val.dev, "object") && isValid;
  isValid = validateAdditionalProperties(diagnostics, field, Object.keys(val), [
    "dev"
  ]) && isValid;
  if (typeof val.dev === "object" && val.dev !== null) {
    isValid = validateRequiredProperty(
      diagnostics,
      `${field}.dev`,
      "aud",
      val.dev.aud,
      "string"
    ) && isValid;
    isValid = validateOptionalProperty(
      diagnostics,
      `${field}.dev`,
      "identity",
      val.dev.identity,
      "object"
    ) && isValid;
    isValid = validateAdditionalProperties(
      diagnostics,
      `${field}.dev`,
      Object.keys(val.dev),
      ["aud", "identity"]
    ) && isValid;
  }
  return isValid;
}, "validateAccess");
var validateCache = /* @__PURE__ */ __name((diagnostics, field, value) => {
  if (value === void 0) {
    return true;
  }
  if (typeof value !== "object" || value === null) {
    diagnostics.errors.push(
      `"${field}" should be an object but got ${JSON.stringify(value)}.`
    );
    return false;
  }
  const val = value;
  let isValid = true;
  isValid = validateRequiredProperty(
    diagnostics,
    field,
    "enabled",
    val.enabled,
    "boolean"
  ) && isValid;
  isValid = validateOptionalProperty(
    diagnostics,
    field,
    "cross_version_cache",
    val.cross_version_cache,
    "boolean"
  ) && isValid;
  isValid = validateAdditionalProperties(diagnostics, field, Object.keys(val), [
    "enabled",
    "cross_version_cache"
  ]) && isValid;
  return isValid;
}, "validateCache");
function warnIfDurableObjectsHaveNoLifecycleConfig(diagnostics, durableObjects, migrations, exports2, configPath) {
  if (!Array.isArray(durableObjects.bindings) || durableObjects.bindings.length === 0) {
    return;
  }
  const exportedDurableObjects = durableObjects.bindings.filter(
    (binding) => !binding.script_name
  );
  const exportsCovers = /* @__PURE__ */ __name((className) => {
    const entry = exports2?.[className];
    if (entry === void 0 || entry.type !== "durable-object") {
      return false;
    }
    const state = entry.state ?? "created";
    return state === "created" || state === "expecting-transfer";
  }, "exportsCovers");
  const uncoveredByExports = exportedDurableObjects.filter(
    (binding) => typeof binding.class_name !== "string" || !exportsCovers(binding.class_name)
  );
  if (uncoveredByExports.length === 0 || migrations.length > 0) {
    return;
  }
  if (uncoveredByExports.some(
    (exportedDurableObject) => typeof exportedDurableObject.class_name !== "string"
  )) {
    return;
  }
  const durableObjectClassnames = uncoveredByExports.map(
    (durable) => durable.class_name
  );
  const suggestedExports = {};
  for (const className of durableObjectClassnames) {
    suggestedExports[className] = {
      type: "durable-object",
      storage: "sqlite"
    };
  }
  diagnostics.warnings.push(dedent`
	In your ${configFileName(configPath)} file, you have configured \`durable_objects\` exported by this Worker (${durableObjectClassnames.join(", ")}), but no live \`exports\` entry for them. This may not work as expected until you add a live \`durable-object\` entry to \`exports\` for each. Add the following configuration:

	\`\`\`
	${formatConfigSnippet({ exports: suggestedExports }, configPath)}
	\`\`\``);
}
__name(warnIfDurableObjectsHaveNoLifecycleConfig, "warnIfDurableObjectsHaveNoLifecycleConfig");
function errorIfMigrationsAndExportsBothSet(diagnostics, migrations, exports2) {
  if (migrations.length > 0 && exports2 !== void 0 && Object.values(exports2).some((entry) => entry.type === "durable-object")) {
    diagnostics.errors.push(
      `\`migrations\` and \`exports\` are mutually exclusive. Choose one or the other to declare your Durable Object lifecycle, but not both.`
    );
  }
}
__name(errorIfMigrationsAndExportsBothSet, "errorIfMigrationsAndExportsBothSet");
function validateContainerExportLinks(diagnostics, containers, exports2, containersDeclaredElsewhere) {
  if (containers !== void 0 && !Array.isArray(containers)) {
    return;
  }
  if (containers === void 0 && containersDeclaredElsewhere) {
    return;
  }
  const containersByName = /* @__PURE__ */ new Map();
  const duplicateNames = /* @__PURE__ */ new Set();
  for (const container of containers ?? []) {
    if (typeof container.name !== "string") {
      continue;
    }
    if (containersByName.has(container.name)) {
      duplicateNames.add(container.name);
    } else {
      containersByName.set(container.name, container);
    }
  }
  for (const name of [...duplicateNames].sort()) {
    diagnostics.errors.push(
      `"containers" contains more than one container named "${name}". Container names must be unique.`
    );
  }
  const containerCountByClassName = /* @__PURE__ */ new Map();
  for (const container of containers ?? []) {
    if (typeof container.class_name !== "string") {
      continue;
    }
    containerCountByClassName.set(
      container.class_name,
      (containerCountByClassName.get(container.class_name) ?? 0) + 1
    );
  }
  const overSubscribedClassNames = new Set(
    [...containerCountByClassName].filter(([, count]) => count > 1).map(([className]) => className)
  );
  for (const className of [...overSubscribedClassNames].sort()) {
    diagnostics.errors.push(
      `More than one container is attached to the Durable Object "${className}". A Durable Object can only have one container attached to it.`
    );
  }
  const durableObjectExports = getDurableObjectExports(exports2);
  const liveExportClassNames = /* @__PURE__ */ new Set();
  const classNamesByContainerName = /* @__PURE__ */ new Map();
  for (const [className, entry] of Object.entries(durableObjectExports)) {
    if (entry.state !== void 0 && entry.state !== "created" && entry.state !== "expecting-transfer") {
      continue;
    }
    liveExportClassNames.add(className);
    if (typeof entry.container !== "string" || entry.container === "") {
      continue;
    }
    if (!containersByName.has(entry.container)) {
      diagnostics.errors.push(
        `"exports.${className}.container" references a container named "${entry.container}", but no container with that name is defined in "containers".`
      );
      continue;
    }
    classNamesByContainerName.set(entry.container, [
      ...classNamesByContainerName.get(entry.container) ?? [],
      className
    ]);
  }
  for (const [containerName, classNames] of classNamesByContainerName) {
    if (classNames.length > 1) {
      diagnostics.errors.push(
        `The container "${containerName}" is referenced by more than one Durable Object export (${classNames.join(", ")}). A container can only back a single Durable Object.`
      );
    }
  }
  const containerNameToClassName = getContainerNameToClassNameMap(exports2);
  const usesDurableObjectExports = Object.keys(durableObjectExports).length > 0;
  for (const container of containers ?? []) {
    if (typeof container.name !== "string") {
      continue;
    }
    if (container.class_name === void 0) {
      if (!containerNameToClassName.has(container.name)) {
        diagnostics.errors.push(
          `The container "${container.name}" is not linked to a Durable Object. Either set "containers.class_name", or reference this container from a Durable Object's \`exports\` entry via its "container" field.`
        );
      }
      continue;
    }
    if (overSubscribedClassNames.has(container.class_name)) {
      continue;
    }
    const exportEntry = durableObjectExports[container.class_name];
    const referencedContainerName = exportEntry !== void 0 && "container" in exportEntry ? exportEntry.container : void 0;
    if (typeof referencedContainerName === "string" && referencedContainerName !== container.name) {
      diagnostics.errors.push(
        `The container "${container.name}" sets "class_name" to "${container.class_name}", but "exports.${container.class_name}.container" is "${referencedContainerName}". A Durable Object and its container must reference each other consistently.`
      );
      continue;
    }
    const claimingClassNames = classNamesByContainerName.get(container.name);
    const claimingClassName = claimingClassNames?.length === 1 ? claimingClassNames[0] : void 0;
    if (claimingClassName !== void 0 && claimingClassName !== container.class_name) {
      diagnostics.errors.push(
        `The container "${container.name}" sets "class_name" to "${container.class_name}", but "exports.${claimingClassName}.container" references it. A Durable Object and its container must reference each other consistently.`
      );
      continue;
    }
    if (usesDurableObjectExports && !liveExportClassNames.has(container.class_name)) {
      diagnostics.errors.push(
        `The container "${container.name}" sets "class_name" to "${container.class_name}", but "exports" has no live "durable-object" entry for "${container.class_name}".`
      );
      continue;
    }
    if (referencedContainerName === void 0 && exportEntry !== void 0 && "storage" in exportEntry && exportEntry.storage === "legacy-kv") {
      diagnostics.errors.push(
        `The container "${container.name}" sets "class_name" to "${container.class_name}", but "exports.${container.class_name}.storage" is "legacy-kv". Containers are not supported on Durable Objects using the "legacy-kv" storage backend.`
      );
    }
  }
}
__name(validateContainerExportLinks, "validateContainerExportLinks");
var validatePythonModules = /* @__PURE__ */ __name((diagnostics, field, value, topLevelEnv) => {
  if (value === void 0) {
    return true;
  }
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
    diagnostics.errors.push(
      `"${field}" should be an object but got ${JSON.stringify(value)}.`
    );
    return false;
  }
  const val = value;
  if (!("exclude" in val)) {
    return false;
  }
  if (!isStringArray(diagnostics, `${field}.exclude`, val.exclude, topLevelEnv)) {
    return false;
  }
  return true;
}, "validatePythonModules");
function isRemoteValid(targetObject, fieldPath, diagnostics) {
  if (!isOptionalProperty(targetObject, "remote", "boolean")) {
    diagnostics.errors.push(
      `"${fieldPath}" should, optionally, have a boolean "remote" field but got ${JSON.stringify(
        targetObject
      )}.`
    );
    return false;
  }
  return true;
}
__name(isRemoteValid, "isRemoteValid");
function isDockerfile(imagePath, configPath) {
  const baseDir2 = configPath ? import_node_path4.default.dirname(configPath) : process.cwd();
  const maybeDockerfile = import_node_path4.default.resolve(baseDir2, imagePath);
  if (import_node_fs4.default.existsSync(maybeDockerfile)) {
    if (isDirectory(maybeDockerfile)) {
      throw new UserError(
        `${imagePath} is a directory, you should specify a path to the Dockerfile`,
        { telemetryMessage: false }
      );
    }
    return true;
  }
  const errorPrefix = `The image "${imagePath}" does not appear to be a valid path to a Dockerfile, or a valid image registry path:
`;
  try {
    new URL(`https://${imagePath}`);
  } catch (e2) {
    if (e2 instanceof Error) {
      throw new UserError(errorPrefix + e2.message, {
        telemetryMessage: false
      });
    }
    throw e2;
  }
  const imageParts = imagePath.split("/");
  if (!imageParts[imageParts.length - 1]?.includes(":")) {
    throw new UserError(
      errorPrefix + `If this is an image registry path, it needs to include at least a tag ':' (e.g: docker.io/httpd:1)`,
      { telemetryMessage: false }
    );
  }
  if (imagePath.includes("://")) {
    throw new UserError(
      errorPrefix + `Image reference should not include the protocol part (e.g: docker.io/httpd:1, not https://docker.io/httpd:1)`,
      { telemetryMessage: false }
    );
  }
  return false;
}
__name(isDockerfile, "isDockerfile");
var BINDING_LOCAL_SUPPORT = {
  plain_text: "local-only",
  secret_text: "local-only",
  json: "local-only",
  wasm_module: "local-only",
  text_blob: "local-only",
  data_blob: "local-only",
  version_metadata: "local-only",
  inherit: "local-only",
  logfwdr: "local-only",
  assets: "local-only",
  unsafe_hello_world: "local-only",
  durable_object_namespace: "local-only",
  hyperdrive: "local-only",
  fetcher: "local-only",
  analytics_engine: "local-only",
  secrets_store_secret: "local-only",
  ratelimit: "local-only",
  worker_loader: "local-only",
  kv_namespace: "local-and-remote",
  r2_bucket: "local-and-remote",
  d1: "local-and-remote",
  workflow: "local-and-remote",
  browser: "local-and-remote",
  images: "local-and-remote",
  stream: "local-and-remote",
  send_email: "local-and-remote",
  pipeline: "local-and-remote",
  service: "local-and-remote",
  // TODO: Miniflare currently ignores `remote: true` on queues, tracked in #13727.
  queue: "local-and-remote",
  vectorize: "remote",
  mtls_certificate: "remote",
  dispatch_namespace: "remote",
  // Reach out to the @cloudflare/wrangler team before adding anything here
  ai: "DO-NOT-USE-this-resource-will-never-have-a-local-simulator",
  ai_search: "DO-NOT-USE-this-resource-will-never-have-a-local-simulator",
  ai_search_namespace: "DO-NOT-USE-this-resource-will-never-have-a-local-simulator",
  media: "DO-NOT-USE-this-resource-will-never-have-a-local-simulator",
  artifacts: "DO-NOT-USE-this-resource-will-never-have-a-local-simulator",
  flagship: "DO-NOT-USE-this-resource-will-never-have-a-local-simulator",
  vpc_service: "DO-NOT-USE-this-resource-will-never-have-a-local-simulator",
  vpc_network: "DO-NOT-USE-this-resource-will-never-have-a-local-simulator",
  websearch: "DO-NOT-USE-this-resource-will-never-have-a-local-simulator",
  agent_memory: "DO-NOT-USE-this-resource-will-never-have-a-local-simulator"
};
function getBindingLocalSupport(type) {
  if (type in BINDING_LOCAL_SUPPORT) {
    return BINDING_LOCAL_SUPPORT[type];
  }
  return "local-only";
}
__name(getBindingLocalSupport, "getBindingLocalSupport");
var supportedPagesConfigFields = [
  "pages_build_output_dir",
  "name",
  "compatibility_date",
  "compatibility_flags",
  "send_metrics",
  "no_bundle",
  "limits",
  "placement",
  "vars",
  "durable_objects",
  "kv_namespaces",
  "queues",
  // `producers` ONLY
  "r2_buckets",
  "d1_databases",
  "vectorize",
  "hyperdrive",
  "services",
  "analytics_engine_datasets",
  "ai",
  "version_metadata",
  "dev",
  "mtls_certificates",
  "browser",
  "upload_source_maps",
  // normalizeAndValidateConfig() sets these values
  "configPath",
  "userConfigPath",
  "topLevelName",
  "definedEnvironments",
  "targetEnvironment"
];
function validatePagesConfig(config22, envNames, projectName) {
  if (!config22.pages_build_output_dir) {
    throw new FatalError(
      `Attempting to validate Pages configuration file, but "pages_build_output_dir" field was not found.
		"pages_build_output_dir" is required for Pages projects.`,
      { telemetryMessage: false }
    );
  }
  const diagnostics = new Diagnostics(
    `Running configuration file validation for Pages:`
  );
  validateMainField(config22, diagnostics);
  validateProjectName(projectName, diagnostics);
  validatePagesEnvironmentNames(envNames, diagnostics);
  validateUnsupportedFields(config22, diagnostics);
  validateDurableObjectBinding2(config22, diagnostics);
  return diagnostics;
}
__name(validatePagesConfig, "validatePagesConfig");
function validateMainField(config22, diagnostics) {
  if (config22.main !== void 0) {
    diagnostics.errors.push(
      `Configuration file cannot contain both both "main" and "pages_build_output_dir" configuration keys.
Please use "main" if you are deploying a Worker, or "pages_build_output_dir" if you are deploying a Pages project.`
    );
  }
}
__name(validateMainField, "validateMainField");
function validateProjectName(name, diagnostics) {
  if (name === void 0 || name.trim() === "") {
    diagnostics.errors.push(
      `Missing top-level field "name" in configuration file.
Pages requires the name of your project to be configured at the top-level of your Wrangler configuration file. This is because, in Pages, environments target the same project.`
    );
  }
}
__name(validateProjectName, "validateProjectName");
function validatePagesEnvironmentNames(envNames, diagnostics) {
  if (!envNames?.length) {
    return;
  }
  const unsupportedPagesEnvNames = envNames.filter(
    (name) => name !== "preview" && name !== "production"
  );
  if (unsupportedPagesEnvNames.length > 0) {
    diagnostics.errors.push(
      `Configuration file contains the following environment names that are not supported by Pages projects:
${unsupportedPagesEnvNames.map((name) => `"${name}"`).join()}.
The supported named-environments for Pages are "preview" and "production".`
    );
  }
}
__name(validatePagesEnvironmentNames, "validatePagesEnvironmentNames");
function validateUnsupportedFields(config22, diagnostics) {
  const unsupportedFields = new Set(Object.keys(config22));
  for (const field of supportedPagesConfigFields) {
    if (field === "queues" && config22.queues?.consumers?.length) {
      continue;
    }
    unsupportedFields.delete(field);
  }
  for (const field of unsupportedFields) {
    if (config22[field] === void 0 || JSON.stringify(config22[field]) === JSON.stringify(defaultWranglerConfig[field])) {
      unsupportedFields.delete(field);
    }
  }
  if (unsupportedFields.size > 0) {
    const fields = Array.from(unsupportedFields.keys());
    fields.forEach((field) => {
      if (field === "queues" && config22.queues?.consumers?.length) {
        diagnostics.errors.push(
          `Configuration file for Pages projects does not support "queues.consumers"`
        );
      } else {
        diagnostics.errors.push(
          `Configuration file for Pages projects does not support "${field}"`
        );
      }
    });
  }
}
__name(validateUnsupportedFields, "validateUnsupportedFields");
function validateDurableObjectBinding2(config22, diagnostics) {
  if (config22.durable_objects.bindings.length > 0) {
    const invalidBindings = config22.durable_objects.bindings.filter(
      (binding) => !isRequiredProperty(binding, "script_name", "string")
    );
    if (invalidBindings.length > 0) {
      diagnostics.errors.push(
        `Durable Objects bindings should specify a "script_name".
Pages requires Durable Object bindings to specify the name of the Worker where the Durable Object is defined.`
      );
    }
  }
}
__name(validateDurableObjectBinding2, "validateDurableObjectBinding");
function getPackagePath(packageName, projectPath) {
  try {
    return import_node_path4.default.dirname(
      __require.resolve(`${packageName}/package.json`, {
        paths: [projectPath]
      })
    );
  } catch {
  }
  try {
    return import_node_path4.default.dirname(
      __require.resolve(packageName, {
        paths: [projectPath]
      })
    );
  } catch {
  }
  return void 0;
}
__name(getPackagePath, "getPackagePath");
function isPackageInstalled(packageName, projectPath) {
  return !!getPackagePath(packageName, projectPath);
}
__name(isPackageInstalled, "isPackageInstalled");
function getInstalledPackageVersion(packageName, projectPath, opts = {}) {
  try {
    const packagePath = getPackagePath(packageName, projectPath);
    if (!packagePath) {
      return void 0;
    }
    const lastDir = opts.stopAtProjectPath === true ? projectPath : void 0;
    const packageJsonPath = findFileUp("package.json", packagePath, lastDir);
    if (!packageJsonPath) {
      return void 0;
    }
    const packageJson = parsePackageJSON(
      readFileSync(packageJsonPath),
      packageJsonPath
    );
    if (packageJson.name !== packageName) {
      const bundledVersion = packageJson.bundledVersions?.[packageName];
      if (bundledVersion !== void 0) {
        return bundledVersion;
      }
    }
    return packageJson.version;
  } catch {
  }
}
__name(getInstalledPackageVersion, "getInstalledPackageVersion");
function findFileUp(name, startDir, lastDir) {
  let dir22 = startDir;
  const root = import_node_path4.default.parse(dir22).root;
  while (true) {
    const candidate = import_node_path4.default.join(dir22, name);
    try {
      if ((0, import_node_fs4.statSync)(candidate).isFile()) {
        return candidate;
      }
    } catch {
    }
    if (lastDir !== void 0 && dir22 === lastDir) {
      break;
    }
    const parent = import_node_path4.default.dirname(dir22);
    if (parent === dir22 || dir22 === root) {
      break;
    }
    dir22 = parent;
  }
  return void 0;
}
__name(findFileUp, "findFileUp");
function isCompatDate(str) {
  return /^\d{4}-\d{2}-\d{2}$/.test(str);
}
__name(isCompatDate, "isCompatDate");
function formatCompatibilityDate(date52) {
  const compatDate = date52.toISOString().slice(0, 10);
  (0, import_node_assert.default)(isCompatDate(compatDate));
  return compatDate;
}
__name(formatCompatibilityDate, "formatCompatibilityDate");
function getTodaysCompatDate() {
  return formatCompatibilityDate(/* @__PURE__ */ new Date());
}
__name(getTodaysCompatDate, "getTodaysCompatDate");
var NODEJS_COMPAT_DEFAULT_ON_DATE = "2026-08-04";
function isNodejsCompatDefaultOn(compatibilityDate) {
  return compatibilityDate !== void 0 && compatibilityDate >= NODEJS_COMPAT_DEFAULT_ON_DATE;
}
__name(isNodejsCompatDefaultOn, "isNodejsCompatDefaultOn");
var NODEJS_COMPAT_V2_SWITCH_OVER_DATE = "2024-09-23";
function resolveNodejsCompat(compatibilityDate, compatibilityFlags) {
  const isDefaultOn = isNodejsCompatDefaultOn(compatibilityDate);
  const isNodejsCompatEnabled = compatibilityFlags.includes("nodejs_compat") || isDefaultOn && !compatibilityFlags.includes("no_nodejs_compat");
  const isNodejsCompatV2Enabled = compatibilityFlags.includes("nodejs_compat_v2") || !compatibilityFlags.includes("no_nodejs_compat_v2") && (isDefaultOn || isNodejsCompatEnabled && compatibilityDate >= NODEJS_COMPAT_V2_SWITCH_OVER_DATE);
  return { isNodejsCompatEnabled, isNodejsCompatV2Enabled };
}
__name(resolveNodejsCompat, "resolveNodejsCompat");
function stripRedundantNodejsCompatFlags(compatibilityDate, compatibilityFlags) {
  if (!isNodejsCompatDefaultOn(compatibilityDate)) {
    return compatibilityFlags;
  }
  const redundantFlags = ["nodejs_compat", "nodejs_compat_v2"].filter(
    (flag) => !compatibilityFlags.includes(`no_${flag}`)
  );
  return compatibilityFlags.filter((flag) => !redundantFlags.includes(flag));
}
__name(stripRedundantNodejsCompatFlags, "stripRedundantNodejsCompatFlags");
var import_ci_info = __toESM2(require_ci_info());
function isTtyInteractive() {
  try {
    return Boolean(process.stdin.isTTY && process.stdout.isTTY);
  } catch {
    return false;
  }
}
__name(isTtyInteractive, "isTtyInteractive");
function isInteractive() {
  if (import_ci_info.default.CLOUDFLARE_PAGES || import_ci_info.default.CLOUDFLARE_WORKERS) {
    return false;
  }
  return isTtyInteractive();
}
__name(isInteractive, "isInteractive");
function isNonInteractiveOrCI() {
  return !isInteractive() || import_ci_info.default.isCI;
}
__name(isNonInteractiveOrCI, "isNonInteractiveOrCI");
function isCI() {
  return import_ci_info.default.isCI;
}
__name(isCI, "isCI");
var arrayFormatter = new Intl.ListFormat("en-US", {
  style: "long",
  type: "conjunction"
});
function createConfigCache(logger, options) {
  let cacheMessageShown = false;
  const namespace = options?.namespace ?? "wrangler";
  function getCacheFolder() {
    if (namespace === "wrangler") {
      const envCacheDir = getWranglerCacheDirFromEnv();
      if (envCacheDir) {
        return envCacheDir;
      }
    }
    const closestNodeModulesDirectory = dir("node_modules");
    const nodeModulesCache = closestNodeModulesDirectory ? path22.join(closestNodeModulesDirectory, ".cache", namespace) : null;
    const localCache = path22.join(process.cwd(), `.${namespace}`, "cache");
    if (nodeModulesCache && (0, import_node_fs4.existsSync)(nodeModulesCache)) {
      return nodeModulesCache;
    }
    if ((0, import_node_fs4.existsSync)(localCache)) {
      return localCache;
    }
    if (nodeModulesCache) {
      return nodeModulesCache;
    }
    return localCache;
  }
  __name(getCacheFolder, "getCacheFolder");
  function showCacheMessage(fields, folder5) {
    if (!cacheMessageShown && !isNonInteractiveOrCI()) {
      if (fields.length > 0) {
        logger.debug(
          `Retrieving cached values for ${arrayFormatter.format(
            fields
          )} from ${path22.relative(process.cwd(), folder5)}`
        );
        cacheMessageShown = true;
      }
    }
  }
  __name(showCacheMessage, "showCacheMessage");
  function getConfigCache(fileName) {
    try {
      const cacheFolder = getCacheFolder();
      const configCacheLocation = path22.join(cacheFolder, fileName);
      const configCache = JSON.parse(
        (0, import_node_fs4.readFileSync)(configCacheLocation, "utf-8")
      );
      showCacheMessage(Object.keys(configCache), cacheFolder);
      return configCache;
    } catch {
      return {};
    }
  }
  __name(getConfigCache, "getConfigCache");
  function saveToConfigCache(fileName, newValues) {
    const cacheFolder = getCacheFolder();
    if (cacheFolder) {
      logger.debug(`Saving to cache: ${JSON.stringify(newValues)}`);
      const configCacheLocation = path22.join(cacheFolder, fileName);
      const existingValues = getConfigCache(fileName);
      (0, import_node_fs4.mkdirSync)(path22.dirname(configCacheLocation), { recursive: true });
      (0, import_node_fs4.writeFileSync)(
        configCacheLocation,
        JSON.stringify({ ...existingValues, ...newValues }, null, 2)
      );
    }
  }
  __name(saveToConfigCache, "saveToConfigCache");
  function purgeConfigCaches() {
    const cacheFolder = getCacheFolder();
    if (cacheFolder) {
      removeDirSync(cacheFolder);
    }
  }
  __name(purgeConfigCaches, "purgeConfigCaches");
  return {
    getCacheFolder,
    getConfigCache,
    saveToConfigCache,
    purgeConfigCaches
  };
}
__name(createConfigCache, "createConfigCache");
var signals = [];
signals.push("SIGHUP", "SIGINT", "SIGTERM");
if (process.platform !== "win32") {
  signals.push(
    "SIGALRM",
    "SIGABRT",
    "SIGVTALRM",
    "SIGXCPU",
    "SIGXFSZ",
    "SIGUSR2",
    "SIGTRAP",
    "SIGSYS",
    "SIGQUIT",
    "SIGIOT"
    // should detect profiler and enable/disable accordingly.
    // see #21
    // 'SIGPROF'
  );
}
if (process.platform === "linux") {
  signals.push("SIGIO", "SIGPOLL", "SIGPWR", "SIGSTKFLT");
}
var processOk = /* @__PURE__ */ __name((process42) => !!process42 && typeof process42 === "object" && typeof process42.removeListener === "function" && typeof process42.emit === "function" && typeof process42.reallyExit === "function" && typeof process42.listeners === "function" && typeof process42.kill === "function" && typeof process42.pid === "number" && typeof process42.on === "function", "processOk");
var kExitEmitter = /* @__PURE__ */ Symbol.for("signal-exit emitter");
var global2 = globalThis;
var ObjectDefineProperty = Object.defineProperty.bind(Object);
var Emitter = class {
  static {
    __name(this, "Emitter");
  }
  emitted = {
    afterExit: false,
    exit: false
  };
  listeners = {
    afterExit: [],
    exit: []
  };
  count = 0;
  id = Math.random();
  constructor() {
    if (global2[kExitEmitter]) {
      return global2[kExitEmitter];
    }
    ObjectDefineProperty(global2, kExitEmitter, {
      value: this,
      writable: false,
      enumerable: false,
      configurable: false
    });
  }
  on(ev, fn) {
    this.listeners[ev].push(fn);
  }
  removeListener(ev, fn) {
    const list = this.listeners[ev];
    const i = list.indexOf(fn);
    if (i === -1) {
      return;
    }
    if (i === 0 && list.length === 1) {
      list.length = 0;
    } else {
      list.splice(i, 1);
    }
  }
  emit(ev, code, signal) {
    if (this.emitted[ev]) {
      return false;
    }
    this.emitted[ev] = true;
    let ret = false;
    for (const fn of this.listeners[ev]) {
      ret = fn(code, signal) === true || ret;
    }
    if (ev === "exit") {
      ret = this.emit("afterExit", code, signal) || ret;
    }
    return ret;
  }
};
var SignalExitBase = class {
  static {
    __name(this, "SignalExitBase");
  }
};
var signalExitWrap = /* @__PURE__ */ __name((handler) => {
  return {
    onExit(cb, opts) {
      return handler.onExit(cb, opts);
    },
    load() {
      return handler.load();
    },
    unload() {
      return handler.unload();
    }
  };
}, "signalExitWrap");
var SignalExitFallback = class extends SignalExitBase {
  static {
    __name(this, "SignalExitFallback");
  }
  onExit() {
    return () => {
    };
  }
  load() {
  }
  unload() {
  }
};
var SignalExit = class extends SignalExitBase {
  static {
    __name(this, "SignalExit");
  }
  // "SIGHUP" throws an `ENOSYS` error on Windows,
  // so use a supported signal instead
  /* c8 ignore start */
  #hupSig = process3.platform === "win32" ? "SIGINT" : "SIGHUP";
  /* c8 ignore stop */
  #emitter = new Emitter();
  #process;
  #originalProcessEmit;
  #originalProcessReallyExit;
  #sigListeners = {};
  #loaded = false;
  constructor(process42) {
    super();
    this.#process = process42;
    this.#sigListeners = {};
    for (const sig of signals) {
      this.#sigListeners[sig] = () => {
        const listeners = this.#process.listeners(sig);
        let { count } = this.#emitter;
        const p2 = process42;
        if (typeof p2.__signal_exit_emitter__ === "object" && typeof p2.__signal_exit_emitter__.count === "number") {
          count += p2.__signal_exit_emitter__.count;
        }
        if (listeners.length === count) {
          this.unload();
          const ret = this.#emitter.emit("exit", null, sig);
          const s = sig === "SIGHUP" ? this.#hupSig : sig;
          if (!ret)
            process42.kill(process42.pid, s);
        }
      };
    }
    this.#originalProcessReallyExit = process42.reallyExit;
    this.#originalProcessEmit = process42.emit;
  }
  onExit(cb, opts) {
    if (!processOk(this.#process)) {
      return () => {
      };
    }
    if (this.#loaded === false) {
      this.load();
    }
    const ev = opts?.alwaysLast ? "afterExit" : "exit";
    this.#emitter.on(ev, cb);
    return () => {
      this.#emitter.removeListener(ev, cb);
      if (this.#emitter.listeners["exit"].length === 0 && this.#emitter.listeners["afterExit"].length === 0) {
        this.unload();
      }
    };
  }
  load() {
    if (this.#loaded) {
      return;
    }
    this.#loaded = true;
    this.#emitter.count += 1;
    for (const sig of signals) {
      try {
        const fn = this.#sigListeners[sig];
        if (fn)
          this.#process.on(sig, fn);
      } catch (_) {
      }
    }
    this.#process.emit = (ev, ...a) => {
      return this.#processEmit(ev, ...a);
    };
    this.#process.reallyExit = (code) => {
      return this.#processReallyExit(code);
    };
  }
  unload() {
    if (!this.#loaded) {
      return;
    }
    this.#loaded = false;
    signals.forEach((sig) => {
      const listener = this.#sigListeners[sig];
      if (!listener) {
        throw new Error("Listener not defined for signal: " + sig);
      }
      try {
        this.#process.removeListener(sig, listener);
      } catch (_) {
      }
    });
    this.#process.emit = this.#originalProcessEmit;
    this.#process.reallyExit = this.#originalProcessReallyExit;
    this.#emitter.count -= 1;
  }
  #processReallyExit(code) {
    if (!processOk(this.#process)) {
      return 0;
    }
    this.#process.exitCode = code || 0;
    this.#emitter.emit("exit", this.#process.exitCode, null);
    return this.#originalProcessReallyExit.call(this.#process, this.#process.exitCode);
  }
  #processEmit(ev, ...args) {
    const og = this.#originalProcessEmit;
    if (ev === "exit" && processOk(this.#process)) {
      if (typeof args[0] === "number") {
        this.#process.exitCode = args[0];
      }
      const ret = og.call(this.#process, ev, ...args);
      this.#emitter.emit("exit", this.#process.exitCode, null);
      return ret;
    } else {
      return og.call(this.#process, ev, ...args);
    }
  }
};
var process3 = globalThis.process;
var {
  /**
   * Called when the process is exiting, whether via signal, explicit
   * exit, or running out of stuff to do.
   *
   * If the global process object is not suitable for instrumentation,
   * then this will be a no-op.
   *
   * Returns a function that may be used to unload signal-exit.
   */
  onExit,
  /**
   * Load the listeners.  Likely you never need to call this, unless
   * doing a rather deep integration with signal-exit functionality.
   * Mostly exposed for the benefit of testing.
   *
   * @internal
   */
  load,
  /**
   * Unload the listeners.  Likely you never need to call this, unless
   * doing a rather deep integration with signal-exit functionality.
   * Mostly exposed for the benefit of testing.
   *
   * @internal
   */
  unload
} = signalExitWrap(processOk(process3) ? new SignalExit(process3) : new SignalExitFallback());
function getWranglerHiddenDirPath(projectRoot) {
  projectRoot ??= process.cwd();
  return import_node_path4.default.join(projectRoot, ".wrangler");
}
__name(getWranglerHiddenDirPath, "getWranglerHiddenDirPath");
var STALE_WRANGLER_TMP_DIR_MS = 24 * 60 * 60 * 1e3;
var sweptTmpRoots = /* @__PURE__ */ new Set();
function sweepStaleWranglerTmpDirs(tmpRoot) {
  if (sweptTmpRoots.has(tmpRoot)) {
    return;
  }
  sweptTmpRoots.add(tmpRoot);
  let entries;
  try {
    entries = import_node_fs4.default.readdirSync(tmpRoot, { withFileTypes: true });
  } catch {
    return;
  }
  const cutoff = Date.now() - STALE_WRANGLER_TMP_DIR_MS;
  for (const entry of entries) {
    if (!entry.isDirectory()) {
      continue;
    }
    const entryPath = import_node_path4.default.join(tmpRoot, entry.name);
    try {
      if (import_node_fs4.default.statSync(entryPath).mtimeMs < cutoff) {
        removeDirSync(entryPath);
      }
    } catch {
    }
  }
}
__name(sweepStaleWranglerTmpDirs, "sweepStaleWranglerTmpDirs");
function getWranglerTmpDir(projectRoot, prefix, cleanup = true) {
  const tmpRoot = import_node_path4.default.join(getWranglerHiddenDirPath(projectRoot), "tmp");
  import_node_fs4.default.mkdirSync(tmpRoot, { recursive: true });
  sweepStaleWranglerTmpDirs(tmpRoot);
  const tmpPrefix = import_node_path4.default.join(tmpRoot, `${prefix}-`);
  const tmpDir = import_node_fs4.default.realpathSync(import_node_fs4.default.mkdtempSync(tmpPrefix));
  const cleanupDir = /* @__PURE__ */ __name(() => {
    if (cleanup) {
      try {
        removeDirSync(tmpDir);
      } catch {
      }
    }
  }, "cleanupDir");
  const removeExitListener = onExit(cleanupDir);
  return {
    path: tmpDir,
    remove() {
      removeExitListener();
      cleanupDir();
    }
  };
}
__name(getWranglerTmpDir, "getWranglerTmpDir");
var import_command_exists = __toESM2(require_command_exists2());
var UPDATE_SERVICE_URL = "https://update.argotunnel.com";
var CLOUDFLARED_VERSION_PATTERN = /^\d{4}\.\d+\.\d+$/;
function sha256Hex(buffer) {
  return (0, import_node_crypto.createHash)("sha256").update(buffer).digest("hex");
}
__name(sha256Hex, "sha256Hex");
function getGoArch() {
  const nodeArch = (0, import_node_os4.arch)();
  switch (nodeArch) {
    case "x64":
      return "amd64";
    case "arm64":
      return "arm64";
    case "arm":
      return "arm";
    default:
      throw new UserError(
        `Unsupported architecture for cloudflared: ${nodeArch}

cloudflared supports: x64 (amd64), arm64, arm

You can manually install cloudflared and set the CLOUDFLARED_PATH environment variable.
Download instructions: https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/downloads/`,
        { telemetryMessage: "tunnel cloudflared unsupported architecture" }
      );
  }
}
__name(getGoArch, "getGoArch");
function getGoOS() {
  switch (process.platform) {
    case "darwin":
      return "darwin";
    case "linux":
      return "linux";
    case "win32":
      return "windows";
    default:
      throw new UserError(
        `Unsupported platform for cloudflared: ${process.platform}

cloudflared supports: darwin (macOS), linux, win32 (Windows)

You can manually install cloudflared and set the CLOUDFLARED_PATH environment variable.
Download instructions: https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/downloads/`,
        { telemetryMessage: "tunnel cloudflared unsupported platform" }
      );
  }
}
__name(getGoOS, "getGoOS");
var GITHUB_RELEASE_BASE = "https://github.com/cloudflare/cloudflared/releases/download";
function getAssetFilename(goOS, goArch) {
  if (goOS === "windows") {
    return `cloudflared-${goOS}-${goArch}.exe`;
  }
  if (goOS === "darwin") {
    return `cloudflared-${goOS}-${goArch}.tgz`;
  }
  return `cloudflared-${goOS}-${goArch}`;
}
__name(getAssetFilename, "getAssetFilename");
async function queryUpdateService(goOS, goArch, options) {
  const { logger } = options ?? {};
  const url210 = new URL(UPDATE_SERVICE_URL);
  url210.searchParams.set("os", goOS);
  url210.searchParams.set("arch", goArch);
  logger?.debug(`Checking for latest cloudflared: ${url210.toString()}`);
  let response;
  try {
    response = await (0, import_undici.fetch)(url210.toString(), {
      headers: { "User-Agent": "wrangler" }
    });
  } catch (e2) {
    logger?.debug(
      `Failed to reach update service: ${e2 instanceof Error ? e2.message : String(e2)}`
    );
    return null;
  }
  if (!response.ok) {
    logger?.debug(
      `Update service returned ${response.status} for ${goOS}/${goArch}`
    );
    return null;
  }
  let data;
  try {
    data = await response.json();
  } catch (e2) {
    logger?.debug(
      `Update service returned non-JSON response: ${e2 instanceof Error ? e2.message : String(e2)}`
    );
    return null;
  }
  if (typeof data.version === "string" && !CLOUDFLARED_VERSION_PATTERN.test(data.version)) {
    throw new Error(
      `[cloudflared] Invalid cloudflared version returned by update service: ${data.version}`
    );
  }
  if (data.error || !data.url || !data.version) {
    return data.version ? data : null;
  }
  return data;
}
__name(queryUpdateService, "queryUpdateService");
async function getLatestVersionInfo(options) {
  const { logger } = options ?? {};
  const goOS = getGoOS();
  const goArch = getGoArch();
  const primary = await queryUpdateService(goOS, goArch, { logger });
  if (primary && primary.url && primary.version) {
    return primary;
  }
  logger?.debug(
    `Update worker had no result for ${goOS}/${goArch}, falling back to GitHub release URL`
  );
  const fallback = await queryUpdateService("linux", "amd64", { logger });
  if (!fallback?.version) {
    throw new UserError(
      `[cloudflared] Failed to determine the latest cloudflared version.

The update service did not return results for ${goOS}/${goArch},
and the fallback query also failed.

You can manually install cloudflared from:
https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/downloads/`,
      { telemetryMessage: "tunnel cloudflared version lookup failed" }
    );
  }
  const version22 = fallback.version;
  const filename = getAssetFilename(goOS, goArch);
  const url210 = `${GITHUB_RELEASE_BASE}/${version22}/${filename}`;
  const compressed = filename.endsWith(".tgz");
  return {
    url: url210,
    version: version22,
    checksum: "",
    // no checksum available for fallback URLs
    compressed,
    shouldUpdate: true,
    userMessage: "",
    error: ""
  };
}
__name(getLatestVersionInfo, "getLatestVersionInfo");
function getCacheDir(version22) {
  return (0, import_node_path4.join)(getGlobalConfigPath(), "cloudflared", version22);
}
__name(getCacheDir, "getCacheDir");
function getCloudflaredBinPath(version22) {
  const binName = process.platform === "win32" ? "cloudflared.exe" : "cloudflared";
  return (0, import_node_path4.join)(getCacheDir(version22), binName);
}
__name(getCloudflaredBinPath, "getCloudflaredBinPath");
function isBinaryExecutable(binPath) {
  try {
    (0, import_node_fs4.accessSync)(binPath, import_node_fs4.constants.X_OK);
    return true;
  } catch {
    return false;
  }
}
__name(isBinaryExecutable, "isBinaryExecutable");
function validateBinary(binPath, options) {
  const { logger } = options ?? {};
  try {
    const output = (0, import_node_child_process2.execFileSync)(binPath, ["--version"], {
      stdio: ["pipe", "pipe", "pipe"],
      timeout: 1e4,
      encoding: "utf8"
    }).trim();
    logger?.debug(`cloudflared version: ${output}`);
  } catch {
    let errorMessage = `[cloudflared] Failed to validate cloudflared binary at ${binPath}

`;
    errorMessage += `This usually means:
`;
    errorMessage += `  - The binary is corrupted or incomplete
`;
    errorMessage += `  - You're missing required system libraries
`;
    if (process.platform === "linux") {
      errorMessage += `
On Linux, make sure you have the required dependencies:
`;
      errorMessage += `  - glibc (GNU C Library)
`;
      errorMessage += `  - For Debian/Ubuntu: sudo apt-get install libc6
`;
    }
    const cacheDir = (0, import_node_path4.join)(getGlobalConfigPath(), "cloudflared");
    errorMessage += `
You can try:
`;
    errorMessage += `  1. Deleting the cache directory: rm -rf ${cacheDir}
`;
    errorMessage += `  2. Running the command again to re-download
`;
    errorMessage += `  3. Manually installing cloudflared: https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/downloads/
`;
    errorMessage += `  4. Setting CLOUDFLARED_PATH to point to your cloudflared binary`;
    throw new UserError(errorMessage, {
      telemetryMessage: "tunnel cloudflared validation failed"
    });
  }
}
__name(validateBinary, "validateBinary");
function redactCloudflaredArgsForLogging(args) {
  const redacted = [...args];
  for (let i = 0; i < redacted.length; i++) {
    const arg = redacted[i];
    if (arg === "--token" && i + 1 < redacted.length) {
      redacted[i + 1] = "[REDACTED]";
    }
    if (arg.startsWith("--token=")) {
      redacted[i] = "--token=[REDACTED]";
    }
  }
  return redacted;
}
__name(redactCloudflaredArgsForLogging, "redactCloudflaredArgsForLogging");
function tryGetCloudflaredFromPath(options) {
  const { logger } = options ?? {};
  if (!(0, import_command_exists.sync)("cloudflared")) {
    return null;
  }
  try {
    validateBinary("cloudflared", { logger });
    return "cloudflared";
  } catch (e2) {
    logger?.debug("cloudflared found in PATH but failed validation", e2);
    return null;
  }
}
__name(tryGetCloudflaredFromPath, "tryGetCloudflaredFromPath");
function getInstalledVersion(binPath) {
  try {
    const output = (0, import_node_child_process2.execFileSync)(binPath, ["--version"], {
      stdio: ["pipe", "pipe", "pipe"],
      timeout: 1e4,
      encoding: "utf8"
    });
    const match = output.match(/(\d+\.\d+\.\d+)/);
    return match ? match[1] : null;
  } catch {
    return null;
  }
}
__name(getInstalledVersion, "getInstalledVersion");
function isVersionOutdated(installed, latest) {
  const parse33 = /* @__PURE__ */ __name((v) => v.split(".").map(Number), "parse");
  const [iYear, iMonth, iPatch] = parse33(installed);
  const [lYear, lMonth, lPatch] = parse33(latest);
  if (iYear !== lYear) {
    return iYear < lYear;
  }
  if (iMonth !== lMonth) {
    return iMonth < lMonth;
  }
  return iPatch < lPatch;
}
__name(isVersionOutdated, "isVersionOutdated");
async function warnIfOutdated(binPath, options) {
  const { logger } = options ?? {};
  try {
    const installed = getInstalledVersion(binPath);
    if (!installed) {
      return;
    }
    const latest = await queryUpdateService(getGoOS(), getGoArch(), { logger }) ?? await queryUpdateService("linux", "amd64", { logger });
    const latestVersion = latest?.version;
    if (!latestVersion) {
      return;
    }
    if (isVersionOutdated(installed, latestVersion)) {
      logger?.warn(
        `Your cloudflared (${installed}) is outdated. Latest version is ${latestVersion}.
Update: https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/downloads/`
      );
    }
  } catch (e2) {
    logger?.debug("Failed to check cloudflared version", e2);
  }
}
__name(warnIfOutdated, "warnIfOutdated");
function writeFileAtomic(filePath, contents44) {
  const dir22 = (0, import_node_path4.dirname)(filePath);
  const tmpPath = (0, import_node_path4.join)(
    dir22,
    `.tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`
  );
  try {
    (0, import_node_fs4.writeFileSync)(tmpPath, contents44);
    (0, import_node_fs4.renameSync)(tmpPath, filePath);
  } finally {
    try {
      if ((0, import_node_fs4.existsSync)(tmpPath)) {
        (0, import_node_fs4.unlinkSync)(tmpPath);
      }
    } catch {
    }
  }
}
__name(writeFileAtomic, "writeFileAtomic");
async function downloadCloudflared(versionInfo, binPath, options) {
  const { logger } = options ?? {};
  const { url: url210, version: version22, checksum, compressed } = versionInfo;
  logger?.log(`Downloading cloudflared ${version22}...`);
  logger?.debug(`Download URL: ${url210}`);
  const cacheDir = (0, import_node_path4.dirname)(binPath);
  (0, import_node_fs4.mkdirSync)(cacheDir, { recursive: true });
  let response;
  try {
    response = await (0, import_undici.fetch)(url210, {
      headers: { "User-Agent": "wrangler" }
    });
  } catch (e2) {
    throw new UserError(
      `[cloudflared] Failed to download cloudflared from ${url210}

Network error: ${e2 instanceof Error ? e2.message : String(e2)}

Please check your internet connection and try again.
If you're behind a proxy, make sure it's configured correctly.`,
      { telemetryMessage: "tunnel cloudflared download network failed" }
    );
  }
  if (!response.ok) {
    throw new UserError(
      `[cloudflared] Failed to download cloudflared from ${url210}

HTTP ${response.status}: ${response.statusText}

You can manually download cloudflared from:
https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/downloads/`,
      { telemetryMessage: "tunnel cloudflared download response failed" }
    );
  }
  try {
    if (compressed) {
      await downloadAndExtractTarball(response, checksum, binPath, cacheDir);
    } else {
      await downloadBinary(response, checksum, binPath);
    }
  } catch (e2) {
    try {
      if ((0, import_node_fs4.existsSync)(binPath)) {
        (0, import_node_fs4.unlinkSync)(binPath);
      }
    } catch {
    }
    if (e2 instanceof UserError) {
      throw e2;
    }
    throw new UserError(
      `[cloudflared] Failed to save cloudflared binary

Error: ${e2 instanceof Error ? e2.message : String(e2)}

Please ensure you have write permissions to: ${cacheDir}`,
      { telemetryMessage: "tunnel cloudflared save failed" }
    );
  }
  if (process.platform !== "win32") {
    (0, import_node_fs4.chmodSync)(binPath, 493);
  }
  logger?.log(`cloudflared ${version22} installed`);
  logger?.debug(`Binary location: ${binPath}`);
}
__name(downloadCloudflared, "downloadCloudflared");
async function downloadAndExtractTarball(response, expectedChecksum, binPath, cacheDir) {
  const tempTarPath = (0, import_node_path4.join)(cacheDir, "cloudflared.tgz");
  const buffer = Buffer.from(await response.arrayBuffer());
  (0, import_node_fs4.writeFileSync)(tempTarPath, buffer);
  try {
    (0, import_node_child_process2.execFileSync)("tar", ["-xzf", tempTarPath, "-C", cacheDir], {
      stdio: "ignore"
    });
    const extractedPath = (0, import_node_path4.join)(cacheDir, "cloudflared");
    if (extractedPath !== binPath && (0, import_node_fs4.existsSync)(extractedPath)) {
      (0, import_node_fs4.renameSync)(extractedPath, binPath);
    }
    if (expectedChecksum) {
      const extractedBinary = (0, import_node_fs4.readFileSync)(binPath);
      const actualSha256 = sha256Hex(extractedBinary);
      if (actualSha256 !== expectedChecksum) {
        throw new UserError(
          `[cloudflared] SHA256 mismatch for downloaded cloudflared binary.

Expected: ${expectedChecksum}
Actual:   ${actualSha256}`,
          {
            telemetryMessage: "tunnel cloudflared extracted binary checksum mismatch"
          }
        );
      }
    }
  } finally {
    try {
      if ((0, import_node_fs4.existsSync)(tempTarPath)) {
        (0, import_node_fs4.unlinkSync)(tempTarPath);
      }
    } catch {
    }
  }
}
__name(downloadAndExtractTarball, "downloadAndExtractTarball");
async function downloadBinary(response, expectedChecksum, binPath) {
  const buffer = Buffer.from(await response.arrayBuffer());
  if (expectedChecksum) {
    const actualSha256 = sha256Hex(buffer);
    if (actualSha256 !== expectedChecksum) {
      throw new UserError(
        `[cloudflared] SHA256 mismatch for downloaded cloudflared binary.

Expected: ${expectedChecksum}
Actual:   ${actualSha256}`,
        { telemetryMessage: "tunnel cloudflared binary checksum mismatch" }
      );
    }
  }
  writeFileAtomic(binPath, buffer);
}
__name(downloadBinary, "downloadBinary");
async function getCloudflaredPath(options) {
  const logger = options?.logger;
  const envPath = getCloudflaredPathFromEnv();
  if (envPath) {
    if (!(0, import_node_fs4.existsSync)(envPath)) {
      throw new UserError(
        `CLOUDFLARED_PATH is set to "${envPath}" but the file does not exist.

Please ensure the path points to a valid cloudflared binary.`,
        { telemetryMessage: "tunnel cloudflared env path missing" }
      );
    }
    logger?.debug(`Using cloudflared from CLOUDFLARED_PATH: ${envPath}`);
    return envPath;
  }
  const pathBin = tryGetCloudflaredFromPath({ logger });
  if (pathBin) {
    logger?.debug("Using cloudflared from PATH");
    if (!options?.skipVersionCheck) {
      await warnIfOutdated(pathBin, { logger });
    }
    return pathBin;
  }
  const versionInfo = await getLatestVersionInfo({ logger });
  const binPath = getCloudflaredBinPath(versionInfo.version);
  let needsDownload = !isBinaryExecutable(binPath);
  if (!needsDownload) {
    try {
      validateBinary(binPath, { logger });
      logger?.debug(
        `Using cached cloudflared ${versionInfo.version}: ${binPath}`
      );
      return binPath;
    } catch (e2) {
      logger?.debug("Cached cloudflared failed validation; re-downloading", e2);
      needsDownload = true;
    }
  }
  const shouldDownload = await options?.confirmDownload?.(
    `cloudflared (${versionInfo.version}) is needed but not installed. Download to ${binPath}?`
  ) ?? true;
  if (!shouldDownload) {
    throw new UserError(
      `cloudflared is required to run this command.

You can install it manually from:
https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/downloads/

Then either add it to your PATH or set CLOUDFLARED_PATH.`,
      { telemetryMessage: "tunnel cloudflared download declined" }
    );
  }
  if ((0, import_node_fs4.existsSync)(binPath)) {
    const cacheDir = removeCloudflaredCache(versionInfo.version);
    if (cacheDir) {
      logger?.log(`Removed cloudflared cache: ${cacheDir}`);
    }
  }
  await downloadCloudflared(versionInfo, binPath, { logger });
  validateBinary(binPath, { logger });
  return binPath;
}
__name(getCloudflaredPath, "getCloudflaredPath");
async function spawnCloudflared(args, options) {
  const logger = options?.logger;
  const binPath = await getCloudflaredPath({
    skipVersionCheck: options?.skipVersionCheck,
    confirmDownload: options?.confirmDownload,
    logger
  });
  logger?.debug(
    `Spawning cloudflared: ${binPath} ${redactCloudflaredArgsForLogging(args).join(" ")}`
  );
  const cloudflared = (0, import_node_child_process2.spawn)(binPath, args, {
    stdio: options?.stdio ?? "inherit",
    env: options?.env ? { ...process.env, ...options.env } : void 0
  });
  return cloudflared;
}
__name(spawnCloudflared, "spawnCloudflared");
function removeCloudflaredCache(version22) {
  const cacheDir = version22 ? getCacheDir(version22) : (0, import_node_path4.join)(getGlobalConfigPath(), "cloudflared");
  if ((0, import_node_fs4.existsSync)(cacheDir)) {
    removeDirSync(cacheDir);
    return cacheDir;
  }
  return null;
}
__name(removeCloudflaredCache, "removeCloudflaredCache");
var TUNNEL_STARTUP_TIMEOUT_MS = 3e4;
var TUNNEL_FORCE_KILL_TIMEOUT_MS = 5e3;
var DEFAULT_TUNNEL_EXPIRY_MS = 60 * 60 * 1e3;
var DEFAULT_TUNNEL_EXTENSION_MS = 60 * 60 * 1e3;
var DEFAULT_TUNNEL_MAX_REMAINING_MS = 3 * 60 * 60 * 1e3;
var DEFAULT_TUNNEL_REMINDER_INTERVAL_MS = 10 * 60 * 1e3;
var QUICK_TUNNEL_URL_REGEX = /https:\/\/[a-z0-9-]+\.trycloudflare\.com/;
function startTunnel(options) {
  let disposed = false;
  let reminderInterval;
  let expiryTimeout;
  let expiresAt = 0;
  let cloudflaredProcess;
  const logger = options.logger;
  const timeoutMs = options.timeoutMs ?? TUNNEL_STARTUP_TIMEOUT_MS;
  const reminderIntervalMs = options.reminderIntervalMs ?? DEFAULT_TUNNEL_REMINDER_INTERVAL_MS;
  const defaultExpiryMs = options.expiryMs ?? DEFAULT_TUNNEL_EXPIRY_MS;
  const isNamedTunnel = options.token !== void 0;
  const timeFormatter = new Intl.DateTimeFormat(void 0, {
    timeStyle: "short"
  });
  const cloudflaredArgs = isNamedTunnel ? ["tunnel", "--no-autoupdate", "run"] : ["tunnel", "--no-autoupdate", "--url", options.origin.href];
  const cloudflaredPromise = spawnCloudflared(cloudflaredArgs, {
    stdio: "pipe",
    env: options.token ? { TUNNEL_TOKEN: options.token } : void 0,
    skipVersionCheck: true,
    logger
  }).then((process42) => {
    cloudflaredProcess = process42;
    if (disposed) {
      terminateCloudflared(process42);
    }
    return process42;
  });
  const readyPromise = cloudflaredPromise.then((process42) => {
    if (isNamedTunnel) {
      return { mode: "named" };
    }
    return waitForQuickTunnelReady(process42, timeoutMs, {
      logger,
      origin: options.origin
    });
  }).then((result) => {
    expiresAt = Date.now() + defaultExpiryMs;
    scheduleExpiryTimeout();
    scheduleReminder(
      result.mode === "quick" ? result.publicUrl.origin : void 0
    );
    return result;
  });
  function disposeTunnel() {
    disposed = true;
    clearTunnelTimers();
    if (cloudflaredProcess) {
      terminateCloudflared(cloudflaredProcess);
    }
  }
  __name(disposeTunnel, "disposeTunnel");
  function clearTunnelTimers() {
    if (expiryTimeout) {
      clearTimeout(expiryTimeout);
      expiryTimeout = void 0;
    }
    if (reminderInterval) {
      clearInterval(reminderInterval);
      reminderInterval = void 0;
    }
  }
  __name(clearTunnelTimers, "clearTunnelTimers");
  function scheduleReminder(publicURL) {
    if (reminderIntervalMs > 0) {
      reminderInterval = setInterval(() => {
        if (disposed) {
          return;
        }
        const remainingMs = expiresAt - Date.now();
        if (remainingMs <= 0) {
          return;
        }
        logger?.log(
          `${publicURL ? `Tunnel still open, expires in ${formatTunnelDuration(remainingMs)}: ${publicURL}` : `The tunnel is still open. It expires in ${formatTunnelDuration(remainingMs)}.`}${options.extendHint ? ` ${options.extendHint}` : ""}`
        );
      }, reminderIntervalMs);
      reminderInterval.unref?.();
    }
  }
  __name(scheduleReminder, "scheduleReminder");
  function scheduleExpiryTimeout() {
    if (disposed) {
      return;
    }
    if (expiryTimeout) {
      clearTimeout(expiryTimeout);
    }
    expiryTimeout = setTimeout(
      () => {
        if (disposed) {
          return;
        }
        logger?.log("Tunnel expired. Closing tunnel.");
        disposeTunnel();
      },
      Math.max(0, expiresAt - Date.now())
    );
    expiryTimeout.unref();
  }
  __name(scheduleExpiryTimeout, "scheduleExpiryTimeout");
  function extendExpiry(ms = DEFAULT_TUNNEL_EXTENSION_MS) {
    if (disposed || !expiryTimeout || ms <= 0) {
      return;
    }
    const now = Date.now();
    const previousExpiresAt = expiresAt;
    expiresAt = Math.min(
      now + DEFAULT_TUNNEL_MAX_REMAINING_MS,
      Math.max(expiresAt, now) + ms
    );
    const extendedByMs = expiresAt - previousExpiresAt;
    if (extendedByMs < ms) {
      logger?.log(
        `Tunnel expiry extended to the ${formatTunnelDuration(DEFAULT_TUNNEL_MAX_REMAINING_MS)} limit. It now expires at ${timeFormatter.format(new Date(expiresAt))}.`
      );
      scheduleExpiryTimeout();
      return;
    }
    logger?.log(
      `Tunnel expiry extended by ${formatTunnelDuration(extendedByMs)}. It now expires at ${timeFormatter.format(new Date(expiresAt))}.`
    );
    scheduleExpiryTimeout();
  }
  __name(extendExpiry, "extendExpiry");
  return {
    ready: /* @__PURE__ */ __name(() => readyPromise, "ready"),
    isOpen: /* @__PURE__ */ __name(() => !disposed, "isOpen"),
    dispose: disposeTunnel,
    extendExpiry
  };
}
__name(startTunnel, "startTunnel");
function formatTunnelDuration(durationMs) {
  const totalMinutes = Math.max(1, Math.ceil(durationMs / 6e4));
  const hours = Math.floor(totalMinutes / 60);
  const minutes = totalMinutes % 60;
  if (hours === 0) {
    return `${minutes}m`;
  }
  if (minutes === 0) {
    return `${hours}h`;
  }
  return `${hours}h ${minutes}m`;
}
__name(formatTunnelDuration, "formatTunnelDuration");
function terminateCloudflared(cloudflared) {
  if (cloudflared.killed) {
    return;
  }
  cloudflared.unref();
  cloudflared.kill("SIGTERM");
  const forceKillTimer = setTimeout(() => {
    if (!cloudflared.killed) {
      cloudflared.kill("SIGKILL");
    }
  }, TUNNEL_FORCE_KILL_TIMEOUT_MS);
  forceKillTimer.unref();
}
__name(terminateCloudflared, "terminateCloudflared");
function waitForQuickTunnelReady(cloudflared, timeoutMs, options) {
  return new Promise((resolve22, reject) => {
    let resolved = false;
    let stderrOutput = "";
    const logger = options?.logger;
    const origin = options?.origin;
    const timeoutId = setTimeout(() => {
      if (!resolved) {
        resolved = true;
        terminateCloudflared(cloudflared);
        reject(
          createTunnelStartupError(
            `Timed out waiting for cloudflared to start (${timeoutMs / 1e3}s).`,
            stderrOutput,
            origin
          )
        );
      }
    }, timeoutMs);
    timeoutId.unref();
    if (cloudflared.stderr) {
      cloudflared.stderr.on("data", (data) => {
        const chunk = data.toString();
        stderrOutput += chunk;
        logger?.debug("[cloudflared]", chunk.trimEnd());
        const match = QUICK_TUNNEL_URL_REGEX.exec(stderrOutput);
        if (match && !resolved) {
          resolved = true;
          clearTimeout(timeoutId);
          resolve22({ mode: "quick", publicUrl: new URL(match[0]) });
        }
      });
    }
    cloudflared.on("error", (error512) => {
      if (!resolved) {
        resolved = true;
        clearTimeout(timeoutId);
        reject(new Error(`Failed to start cloudflared: ${error512.message}`));
      }
    });
    cloudflared.on("exit", (code, signal) => {
      if (!resolved) {
        resolved = true;
        clearTimeout(timeoutId);
        const reason = signal ? `terminated by signal ${signal}` : `exited with code ${code}`;
        reject(
          createTunnelStartupError(
            `cloudflared ${reason} before the tunnel was ready.`,
            stderrOutput,
            origin
          )
        );
      }
    });
  });
}
__name(waitForQuickTunnelReady, "waitForQuickTunnelReady");
function createTunnelStartupError(message, stderrOutput, origin) {
  const isQuickTunnelRateLimited = stderrOutput.includes(
    "429 Too Many Requests"
  );
  const errorMessage = `${message}
cloudflared output:
${stderrOutput || "(no output)"}

The local dev server started at ${origin.href}
` + (isQuickTunnelRateLimited ? "Cloudflare Quick Tunnel creation was rate limited. Try again in a few minutes, or use a named tunnel if you need more reliable access." : `Check the cloudflared output above for more details, and verify that ${origin.href} is reachable from this machine if this keeps happening.`);
  if (isQuickTunnelRateLimited) {
    return new UserError(errorMessage, { telemetryMessage: false });
  }
  return new Error(errorMessage);
}
__name(createTunnelStartupError, "createTunnelStartupError");
function buildDetailedError(message, ...extra) {
  return new ParseError({
    text: message,
    notes: extra.map((text) => ({ text })),
    telemetryMessage: false
  });
}
__name(buildDetailedError, "buildDetailedError");
function maybeThrowFriendlyError(error512) {
  if (error512.message === "workers.api.error.email_verification_required") {
    throw buildDetailedError(
      "Please verify your account's email address and try again.",
      "Check your email for a verification link, or login to https://dash.cloudflare.com and request a new one."
    );
  }
}
__name(maybeThrowFriendlyError, "maybeThrowFriendlyError");
function logHeaders(headers, logger) {
  const clone22 = cloneHeaders(headers);
  clone22.delete("Authorization");
  logger.debugWithSanitization?.(
    "HEADERS:",
    JSON.stringify(Object.fromEntries(clone22), null, 2)
  );
}
__name(logHeaders, "logHeaders");
async function performApiFetchBase(complianceConfig, resource, init22 = {}, userAgent, logger, queryParams, abortSignal, credentials) {
  (0, import_node_assert.default)(credentials, "credentials are required for performApiFetch");
  const method = init22.method ?? "GET";
  (0, import_node_assert.default)(
    resource.startsWith("/"),
    `CF API fetch - resource path must start with a "/" but got "${resource}"`
  );
  const headers = cloneHeaders(new import_undici.Headers(init22.headers));
  addAuthorizationHeader(headers, credentials);
  headers.set("User-Agent", userAgent);
  maybeAddTraceHeader(headers);
  const queryString = queryParams ? `?${queryParams.toString()}` : "";
  logger.debug(
    `-- START CF API REQUEST: ${method} ${getCloudflareApiBaseUrl(complianceConfig)}${resource}`
  );
  logger.debugWithSanitization?.("QUERY STRING:", queryString);
  logHeaders(headers, logger);
  logger.debugWithSanitization?.("INIT:", JSON.stringify({ ...init22 }, null, 2));
  if (init22.body instanceof import_undici.FormData) {
    logger.debugWithSanitization?.(
      "BODY:",
      await new import_undici.Response(init22.body).text(),
      null,
      2
    );
  }
  logger.debug("-- END CF API REQUEST");
  return await (0, import_undici.fetch)(
    `${getCloudflareApiBaseUrl(complianceConfig)}${resource}${queryString}`,
    {
      method,
      ...init22,
      headers,
      signal: abortSignal
    }
  );
}
__name(performApiFetchBase, "performApiFetchBase");
async function fetchInternalBase(complianceConfig, resource, init22 = {}, userAgent, logger, queryParams, abortSignal, credentials) {
  const method = init22.method ?? "GET";
  const response = await performApiFetchBase(
    complianceConfig,
    resource,
    init22,
    userAgent,
    logger,
    queryParams,
    abortSignal,
    credentials
  );
  const jsonText = await response.text();
  logger.debug(
    "-- START CF API RESPONSE:",
    response.statusText,
    response.status
  );
  logHeaders(response.headers, logger);
  logger.debugWithSanitization?.("RESPONSE:", jsonText);
  logger.debug("-- END CF API RESPONSE");
  const retryAfterMs = parseRetryAfterMs(response.headers);
  if (!jsonText && (response.status === 204 || response.status === 205)) {
    return {
      response: {
        result: {},
        success: true,
        errors: [],
        messages: []
      },
      status: response.status,
      retryAfterMs
    };
  }
  if (isWAFBlockResponse(response.headers)) {
    throwWAFBlockError(
      response.headers,
      method,
      resource,
      response.status,
      response.statusText,
      retryAfterMs
    );
  }
  try {
    const json22 = parseJSON(jsonText);
    return { response: json22, status: response.status, retryAfterMs };
  } catch {
    const rayId = extractWAFBlockRayId(response.headers);
    throw new APIError({
      text: "Received a malformed response from the API",
      notes: [
        {
          text: truncate(jsonText, 100)
        },
        {
          text: `${method} ${resource} -> ${response.status} ${response.statusText}`
        },
        ...rayId ? [{ text: `Cloudflare Ray ID: ${rayId}` }] : []
      ],
      status: response.status,
      retryAfterMs,
      telemetryMessage: false
    });
  }
}
__name(fetchInternalBase, "fetchInternalBase");
async function fetchResultBase(complianceConfig, resource, init22 = {}, userAgent, logger, queryParams, abortSignal, credentials) {
  const {
    response: json22,
    status: status2,
    retryAfterMs
  } = await fetchInternalBase(
    complianceConfig,
    resource,
    init22,
    userAgent,
    logger,
    queryParams,
    abortSignal,
    credentials
  );
  if (json22.success) {
    return json22.result;
  } else {
    throwFetchError(resource, json22, status2, retryAfterMs);
  }
}
__name(fetchResultBase, "fetchResultBase");
async function fetchListResultBase(complianceConfig, resource, init22 = {}, userAgent, logger, queryParams, credentials) {
  const results = [];
  let getMoreResults = true;
  let cursor;
  while (getMoreResults) {
    if (cursor) {
      queryParams = new import_node_url2.URLSearchParams(queryParams);
      queryParams.set("cursor", cursor);
    }
    const {
      response: json22,
      status: status2,
      retryAfterMs
    } = await fetchInternalBase(
      complianceConfig,
      resource,
      init22,
      userAgent,
      logger,
      queryParams,
      void 0,
      credentials
    );
    if (json22.success) {
      results.push(...json22.result);
      if (hasCursor(json22.result_info)) {
        cursor = json22.result_info?.cursor;
      } else {
        getMoreResults = false;
      }
    } else {
      throwFetchError(resource, json22, status2, retryAfterMs);
    }
  }
  return results;
}
__name(fetchListResultBase, "fetchListResultBase");
function truncate(text, maxLength) {
  const { length } = text;
  if (length <= maxLength) {
    return text;
  }
  return `${text.substring(0, maxLength)}... (length = ${length})`;
}
__name(truncate, "truncate");
function isWAFBlockResponse(headers) {
  return headers.get("cf-mitigated") === "challenge";
}
__name(isWAFBlockResponse, "isWAFBlockResponse");
function parseRetryAfterValue(retryAfter) {
  if (!retryAfter) {
    return void 0;
  }
  if (/^\d+$/.test(retryAfter.trim())) {
    return Number(retryAfter) * 1e3;
  }
  const retryAfterDate = new Date(retryAfter);
  if (!Number.isNaN(retryAfterDate.getTime())) {
    return Math.max(0, retryAfterDate.getTime() - Date.now());
  }
  return void 0;
}
__name(parseRetryAfterValue, "parseRetryAfterValue");
function parseRetryAfterMs(headers) {
  return parseRetryAfterValue(headers.get("Retry-After"));
}
__name(parseRetryAfterMs, "parseRetryAfterMs");
function extractWAFBlockRayId(headers) {
  return headers.get("cf-ray") ?? void 0;
}
__name(extractWAFBlockRayId, "extractWAFBlockRayId");
function extractAccountTag(resource) {
  const re = new RegExp("/accounts/([a-zA-Z0-9]+)/?");
  const matches = re.exec(resource);
  return matches?.[1];
}
__name(extractAccountTag, "extractAccountTag");
function hasMorePages(result_info) {
  const page = result_info?.page;
  const per_page = result_info?.per_page;
  const total = result_info?.total_count;
  return page !== void 0 && per_page !== void 0 && total !== void 0 && page * per_page < total;
}
__name(hasMorePages, "hasMorePages");
function renderError(err, level = 0) {
  const indent = "  ".repeat(level);
  const message = err.message ?? "";
  const chainedMessages = "error_chain" in err ? err.error_chain?.map(
    (chainedError) => `

${indent}- ${renderError(chainedError, level + 1)}`
  ).join("\n") ?? "" : "";
  return (err.code ? `${message} [code: ${err.code}]` : message) + (err.documentation_url ? `
${indent}To learn more about this error, visit: ${err.documentation_url}` : "") + chainedMessages;
}
__name(renderError, "renderError");
function addAuthorizationHeader(headers, auth, overrideExisting = false) {
  if (!headers.has("Authorization") || overrideExisting) {
    if ("apiToken" in auth) {
      const authorizationHeader = `Bearer ${auth.apiToken}`;
      validateAuthorizationHeaderValue(authorizationHeader);
      headers.set("Authorization", authorizationHeader);
    } else {
      headers.set("X-Auth-Key", auth.authKey);
      headers.set("X-Auth-Email", auth.authEmail);
    }
  }
}
__name(addAuthorizationHeader, "addAuthorizationHeader");
function validateAuthorizationHeaderValue(value) {
  for (const character of value) {
    const codePoint = character.codePointAt(0);
    if (codePoint === void 0 || codePoint > 255) {
      throw new UserError(
        `The configured Cloudflare API token contains a character that cannot be used in an HTTP Authorization header: ${formatAuthorizationHeaderCharacter(character, codePoint)}. Recreate or copy the token again, making sure it does not include characters such as ellipses.`,
        {
          telemetryMessage: "cfetch auth invalid authorization header"
        }
      );
    }
  }
}
__name(validateAuthorizationHeaderValue, "validateAuthorizationHeaderValue");
function formatAuthorizationHeaderCharacter(character, codePoint) {
  if (codePoint === void 0) {
    return '"\\u{unknown}"';
  }
  const codePointLabel = `U+${codePoint.toString(16).toUpperCase().padStart(4, "0")}`;
  const characterLabel = isPrintableCharacter(character) ? `"${character}"` : `"${escapeCharacter(character)}"`;
  return `${characterLabel} (${codePointLabel})`;
}
__name(formatAuthorizationHeaderCharacter, "formatAuthorizationHeaderCharacter");
function isPrintableCharacter(character) {
  return !/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(character);
}
__name(isPrintableCharacter, "isPrintableCharacter");
function escapeCharacter(character) {
  return Array.from(character).map((c2) => {
    const codePoint = c2.codePointAt(0);
    if (codePoint === void 0) {
      return "";
    }
    return codePoint <= 65535 ? `\\u${codePoint.toString(16).toUpperCase().padStart(4, "0")}` : `\\u{${codePoint.toString(16).toUpperCase()}}`;
  }).join("");
}
__name(escapeCharacter, "escapeCharacter");
function throwFetchError(resource, response, status2, retryAfterMs) {
  const errors = response.errors ?? [];
  for (const error522 of errors) {
    maybeThrowFriendlyError(error522);
  }
  const notes = [
    ...errors.map((err) => ({ text: renderError(err) })),
    ...response.messages?.map((msg) => ({
      text: typeof msg === "string" ? msg : msg.message ?? String(msg)
    })) ?? []
  ];
  if (notes.length === 0) {
    const raw = response;
    const fallbackMessage = typeof raw.error === "string" ? `${raw.error}${raw.code ? ` [code: ${raw.code}]` : ""}` : void 0;
    if (fallbackMessage) {
      notes.push({ text: fallbackMessage });
    }
  }
  if (retryAfterMs !== void 0) {
    notes.push({
      text: `The API responded with a "Retry-After" header indicating you should wait ${Math.ceil(retryAfterMs / 1e3)} second(s) before retrying.`
    });
  }
  const error512 = new APIError({
    text: `A request to the Cloudflare API (${resource}) failed.`,
    notes,
    status: status2,
    // hoist the parsed `Retry-After` header (if any) so consumers such as
    // `retryOnAPIFailure()` can back off for the amount of time the API
    // asked us to wait, e.g. when rate limited (HTTP 429).
    retryAfterMs,
    telemetryMessage: false
  });
  const code = errors[0]?.code;
  if (code) {
    error512.code = code;
  }
  const meta32 = errors[0]?.meta;
  if (meta32) {
    error512.meta = meta32;
  }
  error512.accountTag = extractAccountTag(resource);
  throw error512;
}
__name(throwFetchError, "throwFetchError");
function throwWAFBlockError(headers, method, resource, status2, statusText, retryAfterMs) {
  const rayId = extractWAFBlockRayId(headers);
  throw new APIError({
    text: "The Cloudflare API responded with a WAF block page instead of the expected JSON response",
    notes: [
      {
        text: "Cloudflare's firewall (WAF) blocked this API request. This is usually a false positive."
      },
      ...rayId ? [{ text: `Cloudflare Ray ID: ${rayId}` }] : [],
      {
        text: rayId ? "If the issue persists, please open a Cloudflare Support ticket and include the Ray ID above." : "If the issue persists, please open a Cloudflare Support ticket. You can find the Cloudflare Ray ID on the block page in your browser."
      },
      {
        text: `${method} ${resource} -> ${status2} ${statusText}`
      }
    ],
    status: status2,
    retryAfterMs,
    telemetryMessage: false
  });
}
__name(throwWAFBlockError, "throwWAFBlockError");
async function fetchKVGetValueBase(complianceConfig, accountId, namespaceId, key, userAgent, logger, credentials) {
  const headers = new import_undici.Headers();
  addAuthorizationHeader(headers, credentials);
  headers.set("User-Agent", userAgent);
  maybeAddTraceHeader(headers);
  const resource = `${getCloudflareApiBaseUrl(complianceConfig)}/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${key}`;
  logger.debug(`-- START CF API REQUEST: GET ${resource}`);
  logger.debug("-- END CF API REQUEST");
  const response = await (0, import_undici.fetch)(resource, {
    method: "GET",
    headers
  });
  if (response.ok) {
    return await response.arrayBuffer();
  } else {
    throw new Error(
      `Failed to fetch ${resource} - ${response.status}: ${response.statusText}`
    );
  }
}
__name(fetchKVGetValueBase, "fetchKVGetValueBase");
function hasCursor(result_info) {
  const cursor = result_info?.cursor;
  return cursor !== void 0 && cursor !== null && cursor !== "";
}
__name(hasCursor, "hasCursor");
function maybeAddTraceHeader(headers) {
  const traceHeader = getTraceHeader();
  if (traceHeader) {
    headers.set("Cf-Trace-Id", traceHeader);
  }
}
__name(maybeAddTraceHeader, "maybeAddTraceHeader");
function cloneHeaders(headers) {
  return new import_undici.Headers(headers);
}
__name(cloneHeaders, "cloneHeaders");
var import_update_check = __toESM2(require_update_check());
var UPDATE_CHECK_TIMEOUT_MS = 3e3;
var TIMED_OUT = /* @__PURE__ */ Symbol("timed_out");
async function fetchLatestNpmVersion(name, version22) {
  let result = null;
  try {
    result = await Promise.race([
      (0, import_update_check.default)(
        { name, version: version22 },
        {
          distTag: version22.startsWith("0.0.0") ? "beta" : "latest"
        }
      ),
      timersPromises.setTimeout(UPDATE_CHECK_TIMEOUT_MS, TIMED_OUT, {
        ref: false
      })
    ]);
  } catch {
    return { status: "failed" };
  }
  if (result === TIMED_OUT) {
    return { status: "failed" };
  }
  if (result === null) {
    return { status: "up-to-date" };
  }
  return { status: "update-available", latest: result.latest };
}
__name(fetchLatestNpmVersion, "fetchLatestNpmVersion");
async function openInBrowser(url210, logger) {
  try {
    const { default: open3 } = await Promise.resolve().then(() => (init_open_PBXRGS4R(), open_PBXRGS4R_exports));
    const childProcess4 = await open3(url210);
    childProcess4.on("error", (err) => {
      handleBrowserOpenError(url210, err, logger);
    });
  } catch (err) {
    if (err.code === "ENOENT") {
      handleBrowserOpenError(url210, err, logger);
    } else {
      throw err;
    }
  }
}
__name(openInBrowser, "openInBrowser");
function handleBrowserOpenError(url210, err, logger) {
  const isEnoent = err.code === "ENOENT";
  const hint = process.platform === "linux" && isEnoent ? " You may need to install `xdg-utils` (e.g. `apt install xdg-utils`) or set a default browser." : "";
  logger.warn(
    `Failed to open a browser automatically.${hint}
Please visit the following URL in your browser:
${url210}`
  );
  logger.debug(err instanceof Error ? err.stack ?? String(err) : String(err));
}
__name(handleBrowserOpenError, "handleBrowserOpenError");
var MAX_ATTEMPTS = 3;
var MAX_RETRY_AFTER_MS = 6e4;
async function retryOnAPIFailure(action, logger, backoff = 0, attempts = MAX_ATTEMPTS, abortSignal) {
  try {
    return await action();
  } catch (err) {
    if (err instanceof APIError) {
      if (!err.isRetryable() && err.status !== 429) {
        throw err;
      }
    } else if (err instanceof DOMException && err.name === "TimeoutError") ;
    else if (!(err instanceof TypeError)) {
      throw err;
    }
    const retryAfterMs = err instanceof APIError ? err.retryAfterMs : void 0;
    if (retryAfterMs !== void 0 && retryAfterMs > MAX_RETRY_AFTER_MS) {
      throw err;
    }
    if (attempts <= 1) {
      throw err;
    }
    const jitter = Math.random() * 1e3;
    let wait = backoff;
    if (retryAfterMs !== void 0) {
      wait = retryAfterMs + jitter;
    } else if (err instanceof APIError && err.status === 429) {
      wait = Math.max(backoff, 1e3) + jitter;
    }
    if (retryAfterMs !== void 0) {
      logger.info(
        `Received a "Retry-After" header from the Cloudflare API. Waiting ${Math.ceil(retryAfterMs / 1e3)} second(s) before retrying...`
      );
    } else {
      logger.debug(`Retrying API call after error...`);
      logger.debug(err);
    }
    await (0, import_promises2.setTimeout)(wait, void 0, { signal: abortSignal });
    return retryOnAPIFailure(
      action,
      logger,
      backoff + 1e3,
      attempts - 1,
      abortSignal
    );
  }
}
__name(retryOnAPIFailure, "retryOnAPIFailure");
function formatTime(duration32) {
  return `(${(duration32 / 1e3).toFixed(2)} sec)`;
}
__name(formatTime, "formatTime");
function getHostFromRoute(route) {
  let host;
  if (typeof route === "string") {
    host = getHostFromUrl(route);
  } else if (typeof route === "object") {
    host = getHostFromUrl(route.pattern);
    if (host === void 0 && "zone_name" in route) {
      host = getHostFromUrl(route.zone_name);
    }
  }
  return host;
}
__name(getHostFromRoute, "getHostFromRoute");
function getZoneFromRoute(route) {
  if (typeof route === "object" && "zone_name" in route && route.zone_name) {
    return route.zone_name;
  }
  return getHostFromRoute(route);
}
__name(getZoneFromRoute, "getZoneFromRoute");
function getHostFromUrl(urlLike) {
  if (urlLike.startsWith("*/") || urlLike.startsWith("http://*/") || urlLike.startsWith("https://*/")) {
    return void 0;
  }
  urlLike = urlLike.replace(/\*(\.)?/g, "");
  if (!(urlLike.startsWith("http://") || urlLike.startsWith("https://"))) {
    urlLike = "http://" + urlLike;
  }
  try {
    return new URL(urlLike).host;
  } catch {
    return void 0;
  }
}
__name(getHostFromUrl, "getHostFromUrl");
var invalidWorkerNameCharsRegex = /[^a-z0-9- ]/g;
var invalidWorkerNameStartEndRegex = /^(-+)|(-+)$/g;
var workerNameLengthLimit = 63;
function checkWorkerNameValidity(input) {
  if (!input) {
    return {
      valid: false,
      cause: "Worker names cannot be empty."
    };
  }
  if (input.match(invalidWorkerNameStartEndRegex)) {
    return {
      valid: false,
      cause: "Worker names cannot start or end with a dash."
    };
  }
  if (input.match(invalidWorkerNameCharsRegex)) {
    return {
      valid: false,
      cause: "Project names must only contain lowercase characters, numbers, and dashes."
    };
  }
  if (input.length > workerNameLengthLimit) {
    return {
      valid: false,
      cause: "Project names must be less than 63 characters."
    };
  }
  return { valid: true };
}
__name(checkWorkerNameValidity, "checkWorkerNameValidity");
function toValidWorkerName(input) {
  if (checkWorkerNameValidity(input).valid) {
    return input;
  }
  input = input.replaceAll("_", "-").replace(invalidWorkerNameCharsRegex, "-").replace(invalidWorkerNameStartEndRegex, "").slice(0, workerNameLengthLimit);
  if (!input.length) {
    return "my-worker";
  }
  return input;
}
__name(toValidWorkerName, "toValidWorkerName");
function getWorkerName(projectOrWorkerName = "", projectPath) {
  const rawName = getCIOverrideName() ?? (projectOrWorkerName || (0, import_node_path4.basename)(projectPath));
  return toValidWorkerName(rawName);
}
__name(getWorkerName, "getWorkerName");
function getWorkerNameFromProject(projectPath) {
  const packageJsonPath = (0, import_node_path4.resolve)(projectPath, "package.json");
  let packageJsonName;
  try {
    const packageJson = parsePackageJSON(
      readFileSync(packageJsonPath),
      packageJsonPath
    );
    packageJsonName = packageJson.name;
  } catch {
  }
  return getWorkerName(packageJsonName, projectPath);
}
__name(getWorkerNameFromProject, "getWorkerNameFromProject");
var FORCE_COLOR;
var NODE_DISABLE_COLORS;
var NO_COLOR;
var TERM;
var isTTY = true;
if (typeof process !== "undefined") {
  ({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env || {});
  isTTY = process.stdout && process.stdout.isTTY;
}
var $ = {
  enabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== "dumb" && (FORCE_COLOR != null && FORCE_COLOR !== "0" || isTTY)
};
function init(x, y) {
  let rgx = new RegExp(`\\x1b\\[${y}m`, "g");
  let open3 = `\x1B[${x}m`, close = `\x1B[${y}m`;
  return function(txt) {
    if (!$.enabled || txt == null) return txt;
    return open3 + (!!~("" + txt).indexOf(close) ? txt.replace(rgx, close + open3) : txt) + close;
  };
}
__name(init, "init");
var dim2 = init(2, 22);
var red2 = init(31, 39);
var green2 = init(32, 39);
var yellow2 = init(33, 39);
var blue2 = init(34, 39);
var magenta = init(35, 39);
var cyan = init(36, 39);
var originalEnabled = $.enabled;
function _forceColour(enabled = originalEnabled) {
  $.enabled = enabled;
}
__name(_forceColour, "_forceColour");
var kMessages = /* @__PURE__ */ Symbol("kMessages");
var kActual = /* @__PURE__ */ Symbol("kActual");
var kGroupId = /* @__PURE__ */ Symbol("kGroupId");
var groupColours = [
  yellow2,
  /* (green) */
  cyan,
  blue2,
  magenta,
  green2
];
var GroupCountsMap = Map;
function isAnnotation(value) {
  return typeof value === "object" && value !== null && kMessages in value && kActual in value;
}
__name(isAnnotation, "isAnnotation");
function isRecord2(value) {
  return typeof value === "object" && value !== null;
}
__name(isRecord2, "isRecord");
function arrayShallowEqual(a, b) {
  if (a.length !== b.length) {
    return false;
  }
  for (let i = 0; i < a.length; i++) {
    if (a[i] !== b[i]) {
      return false;
    }
  }
  return true;
}
__name(arrayShallowEqual, "arrayShallowEqual");
function issueEqual(a, b) {
  return a.message === b.message && arrayShallowEqual(a.path, b.path);
}
__name(issueEqual, "issueEqual");
function hasMultipleDistinctMessages(issues, atDepth) {
  let firstIssue;
  for (const issue22 of issues) {
    if (issue22.path.length < atDepth) {
      continue;
    }
    if (firstIssue === void 0) {
      firstIssue = issue22;
    } else if (!issueEqual(firstIssue, issue22)) {
      return true;
    }
  }
  return false;
}
__name(hasMultipleDistinctMessages, "hasMultipleDistinctMessages");
function annotate(groupCounts, annotated, input, issue22, path610, groupId) {
  if (path610.length === 0) {
    if (issue22.code === "invalid_union") {
      const allBranchIssues = issue22.errors;
      const unionIssues = allBranchIssues.flat();
      if (unionIssues.length > 0) {
        const multipleDistinct = hasMultipleDistinctMessages(unionIssues, 1);
        let newGroupId;
        if (isRecord2(input) && multipleDistinct) {
          newGroupId = groupCounts.size;
          groupCounts.set(newGroupId, 0);
        }
        for (const branchIssues of allBranchIssues) {
          for (const unionIssue of branchIssues) {
            const unionPath = unionIssue.path;
            if (multipleDistinct && unionPath.length === 0) {
              continue;
            }
            annotated = annotate(
              groupCounts,
              annotated,
              input,
              unionIssue,
              unionPath,
              newGroupId
            );
          }
        }
        return annotated;
      }
    }
    const message = issue22.message;
    if (annotated !== void 0) {
      if (isAnnotation(annotated) && !annotated[kMessages].includes(message)) {
        annotated[kMessages].push(message);
      }
      return annotated;
    }
    if (groupId !== void 0) {
      const current = groupCounts.get(groupId);
      (0, import_node_assert.default)(current !== void 0);
      groupCounts.set(groupId, current + 1);
    }
    return {
      [kMessages]: [message],
      [kActual]: input,
      [kGroupId]: groupId
    };
  }
  const [head, ...tail] = path610;
  (0, import_node_assert.default)(isRecord2(input), "Expected object/array input for nested issue");
  if (annotated === void 0) {
    if (Array.isArray(input)) {
      annotated = new Array(input.length);
    } else {
      const entries = Object.keys(input).map((key) => [key, void 0]);
      annotated = Object.fromEntries(entries);
    }
  }
  (0, import_node_assert.default)(isRecord2(annotated), "Expected object/array for nested issue");
  annotated[head] = annotate(
    groupCounts,
    annotated[head],
    input[head],
    issue22,
    tail,
    groupId
  );
  return annotated;
}
__name(annotate, "annotate");
function print(inspectOptions, groupCounts, annotated, indent = "", extras) {
  const prefix = extras?.prefix ?? "";
  const suffix = extras?.suffix ?? "";
  if (isAnnotation(annotated)) {
    const prefixIndent = indent + " ".repeat(prefix.length);
    const actual = import_node_util2.default.inspect(annotated[kActual], inspectOptions);
    const actualIndented = actual.split("\n").map((line, i) => i > 0 ? prefixIndent + line : line).join("\n");
    let messageColour = red2;
    let messagePrefix = prefixIndent + "^";
    let groupOr = "";
    if (annotated[kGroupId] !== void 0) {
      messageColour = groupColours[annotated[kGroupId] % groupColours.length];
      messagePrefix += annotated[kGroupId] + 1;
      const remaining = groupCounts.get(annotated[kGroupId]);
      (0, import_node_assert.default)(remaining !== void 0);
      if (remaining > 1) {
        groupOr = " *or*";
      }
      groupCounts.set(annotated[kGroupId], remaining - 1);
    }
    messagePrefix += " ";
    const messageIndent = " ".repeat(messagePrefix.length);
    const messageIndented = annotated[kMessages].flatMap((m) => m.split("\n")).map((line, i) => i > 0 ? messageIndent + line : line).join("\n");
    const error512 = messageColour(`${messagePrefix}${messageIndented}${groupOr}`);
    return `${indent}${dim2(prefix)}${actualIndented}${dim2(suffix)}
${error512}`;
  } else if (Array.isArray(annotated)) {
    let result = `${indent}${dim2(`${prefix}[`)}
`;
    const arrayIndent = indent + "  ";
    for (let i = 0; i < annotated.length; i++) {
      const value = annotated[i];
      if (value === void 0 && (i === 0 || annotated[i - 1] !== void 0)) {
        result += `${arrayIndent}${dim2("...,")}
`;
      }
      if (value !== void 0) {
        result += print(inspectOptions, groupCounts, value, arrayIndent, {
          prefix: `/* [${i}] */ `,
          suffix: ","
        });
        result += "\n";
      }
    }
    result += `${indent}${dim2(`]${suffix}`)}`;
    return result;
  } else if (isRecord2(annotated)) {
    let result = `${indent}${dim2(`${prefix}{`)}
`;
    const objectIndent = indent + "  ";
    const entries = Object.entries(annotated);
    for (let i = 0; i < entries.length; i++) {
      const [key, value] = entries[i];
      if (value === void 0 && (i === 0 || entries[i - 1][1] !== void 0)) {
        result += `${objectIndent}${dim2("...,")}
`;
      }
      if (value !== void 0) {
        result += print(inspectOptions, groupCounts, value, objectIndent, {
          prefix: `${key}: `,
          suffix: ","
        });
        result += "\n";
      }
    }
    result += `${indent}${dim2(`}${suffix}`)}`;
    return result;
  }
  return "";
}
__name(print, "print");
function formatZodError(error512, input) {
  const sortedIssues = Array.from(error512.issues).sort((a, b) => {
    if (a.code !== b.code) {
      if (a.code === "invalid_union") {
        return -1;
      }
      if (b.code === "invalid_union") {
        return 1;
      }
    }
    return 0;
  });
  let annotated;
  const groupCounts = new GroupCountsMap();
  for (const issue22 of sortedIssues) {
    annotated = annotate(
      groupCounts,
      annotated,
      input,
      issue22,
      issue22.path
    );
  }
  const inspectOptions = {
    depth: 0,
    colors: $.enabled
  };
  return print(inspectOptions, groupCounts, annotated);
}
__name(formatZodError, "formatZodError");
function toUrlPath(filePath) {
  (0, import_node_console.assert)(
    !/^[a-z]:/i.test(filePath),
    "Tried to convert a Windows file path with a drive to a URL path."
  );
  return filePath.replace(/\\/g, "/");
}
__name(toUrlPath, "toUrlPath");

// ../cli/dist/check-macos-version.mjs
var import_ci_info2 = __toESM(require_ci_info2(), 1);
var MINIMUM_MACOS_VERSION = "13.5.0";
function checkMacOSVersion(options) {
  if (process.platform !== "darwin") return;
  if (import_ci_info2.default.isCI) return;
  const macOSVersion = darwinVersionToMacOSVersion(import_node_os5.default.release());
  if (macOSVersion && isVersionLessThan(macOSVersion, MINIMUM_MACOS_VERSION)) if (options.shouldThrow) throw new UserError(`Unsupported macOS version: The Cloudflare Workers runtime cannot run on the current version of macOS (${macOSVersion}). The minimum requirement is macOS ${MINIMUM_MACOS_VERSION}+. See https://github.com/cloudflare/workerd?tab=readme-ov-file#running-workerd If you cannot upgrade your version of macOS, you could try running in a DevContainer setup with a supported version of Linux (glibc 2.35+ required).`, { telemetryMessage: false });
  else console.warn(`\u26A0\uFE0F  Warning: Unsupported macOS version detected (${macOSVersion}). The Cloudflare Workers runtime may not work correctly on macOS versions below ${MINIMUM_MACOS_VERSION}. Consider upgrading to macOS ${MINIMUM_MACOS_VERSION}+ or using a DevContainer setup with a supported version of Linux (glibc 2.35+ required).`);
}
function darwinVersionToMacOSVersion(darwinVersion) {
  const match = darwinVersion.match(/^(\d+)\.(\d+)\.(\d+)/);
  if (!match) return null;
  const major = parseInt(match[1], 10);
  if (major >= 20) return `${major - 9}.${parseInt(match[2], 10)}.${parseInt(match[3], 10)}`;
  return null;
}
function isVersionLessThan(version1, version22) {
  const versionRegex = /^(\d+)\.(\d+)\.(\d+)$/;
  const match1 = version1.match(versionRegex);
  const match2 = version22.match(versionRegex);
  if (!match1 || !match2) throw new Error(`Invalid version format. Expected M.m.p format, got: ${version1}, ${version22}`);
  const [major1, minor1, patch1] = [
    parseInt(match1[1], 10),
    parseInt(match1[2], 10),
    parseInt(match1[3], 10)
  ];
  const [major2, minor2, patch2] = [
    parseInt(match2[1], 10),
    parseInt(match2[2], 10),
    parseInt(match2[3], 10)
  ];
  if (major1 !== major2) return major1 < major2;
  if (minor1 !== minor2) return minor1 < minor2;
  return patch1 < patch2;
}

// ../cli/dist/index.mjs
var shapes = {
  diamond: "\u25C7",
  dash: "\u2500",
  radioInactive: "\u25CB",
  radioActive: "\u25CF",
  backActive: "\u25C0",
  backInactive: "\u25C1",
  bar: "\u2502",
  leftT: "\u251C",
  rigthT: "\u2524",
  arrows: {
    left: "\u2039",
    right: "\u203A"
  },
  corners: {
    tl: "\u256D",
    bl: "\u2570",
    tr: "\u256E",
    br: "\u256F"
  }
};
var status = {
  error: bgRed(` ERROR `),
  warning: bgYellow(` WARNING `),
  info: bgBlue(` INFO `),
  success: bgGreen(` SUCCESS `),
  cancel: white.bgRed(` X `)
};
var LOGGER_LEVELS = {
  none: -1,
  error: 0,
  warn: 1,
  info: 2,
  log: 3,
  debug: 4
};
var currentLogLevel = "log";
function getLogLevel() {
  return currentLogLevel;
}
var logRaw = (msg) => {
  if (LOGGER_LEVELS[getLogLevel()] >= LOGGER_LEVELS.log) stdout.write(`${msg}
`);
};
var log = (msg) => {
  logRaw(msg.split("\n").map((ln) => `${gray(shapes.bar)}${ln.length > 0 ? " " + white(ln) : ""}`).join("\n"));
};
var newline = () => {
  log("");
};

// ../../node_modules/.pnpm/kleur@4.1.5/node_modules/kleur/colors.mjs
var FORCE_COLOR2;
var NODE_DISABLE_COLORS2;
var NO_COLOR2;
var TERM2;
var isTTY2 = true;
if (typeof process !== "undefined") {
  ({ FORCE_COLOR: FORCE_COLOR2, NODE_DISABLE_COLORS: NODE_DISABLE_COLORS2, NO_COLOR: NO_COLOR2, TERM: TERM2 } = process.env || {});
  isTTY2 = process.stdout && process.stdout.isTTY;
}
var $2 = {
  enabled: !NODE_DISABLE_COLORS2 && NO_COLOR2 == null && TERM2 !== "dumb" && (FORCE_COLOR2 != null && FORCE_COLOR2 !== "0" || isTTY2)
};
function init2(x, y) {
  let rgx = new RegExp(`\\x1b\\[${y}m`, "g");
  let open3 = `\x1B[${x}m`, close = `\x1B[${y}m`;
  return function(txt) {
    if (!$2.enabled || txt == null) return txt;
    return open3 + (!!~("" + txt).indexOf(close) ? txt.replace(rgx, close + open3) : txt) + close;
  };
}
var reset = init2(0, 0);
var bold2 = init2(1, 22);
var dim3 = init2(2, 22);
var italic = init2(3, 23);
var underline = init2(4, 24);
var inverse = init2(7, 27);
var hidden2 = init2(8, 28);
var strikethrough = init2(9, 29);
var black2 = init2(30, 39);
var red3 = init2(31, 39);
var green3 = init2(32, 39);
var yellow3 = init2(33, 39);
var blue3 = init2(34, 39);
var magenta2 = init2(35, 39);
var cyan2 = init2(36, 39);
var white2 = init2(37, 39);
var gray2 = init2(90, 39);
var grey = init2(90, 39);
var bgBlack = init2(40, 49);
var bgRed2 = init2(41, 49);
var bgGreen2 = init2(42, 49);
var bgYellow2 = init2(43, 49);
var bgBlue2 = init2(44, 49);
var bgMagenta = init2(45, 49);
var bgCyan2 = init2(46, 49);
var bgWhite = init2(47, 49);

// src/index.ts
var import_stoppable = __toESM(require_stoppable());
var import_undici8 = require("undici");

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/core/dev-registry-proxy.worker.ts
var import_fs = __toESM(require("fs"));
var import_path = __toESM(require("path"));
var import_url = __toESM(require("url"));
var contents;
function dev_registry_proxy_worker_default() {
  if (contents !== void 0) return contents;
  const filePath = import_path.default.join(__dirname, "workers", "core/dev-registry-proxy.worker.js");
  contents = import_fs.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url.default.pathToFileURL(filePath);
  return contents;
}

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/shared/index.worker.ts
var import_fs2 = __toESM(require("fs"));
var import_path2 = __toESM(require("path"));
var import_url2 = __toESM(require("url"));
var contents2;
function index_worker_default() {
  if (contents2 !== void 0) return contents2;
  const filePath = import_path2.default.join(__dirname, "workers", "shared/index.worker.js");
  contents2 = import_fs2.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url2.default.pathToFileURL(filePath);
  return contents2;
}

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/shared/zod.worker.ts
var import_fs3 = __toESM(require("fs"));
var import_path3 = __toESM(require("path"));
var import_url3 = __toESM(require("url"));
var contents3;
function zod_worker_default() {
  if (contents3 !== void 0) return contents3;
  const filePath = import_path3.default.join(__dirname, "workers", "shared/zod.worker.js");
  contents3 = import_fs3.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url3.default.pathToFileURL(filePath);
  return contents3;
}

// src/index.ts
var import_ws6 = require("ws");

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js
var external_exports2 = {};
__export(external_exports2, {
  $brand: () => $brand2,
  $input: () => $input2,
  $output: () => $output2,
  NEVER: () => NEVER2,
  TimePrecision: () => TimePrecision2,
  ZodAny: () => ZodAny2,
  ZodArray: () => ZodArray2,
  ZodBase64: () => ZodBase642,
  ZodBase64URL: () => ZodBase64URL2,
  ZodBigInt: () => ZodBigInt2,
  ZodBigIntFormat: () => ZodBigIntFormat2,
  ZodBoolean: () => ZodBoolean2,
  ZodCIDRv4: () => ZodCIDRv42,
  ZodCIDRv6: () => ZodCIDRv62,
  ZodCUID: () => ZodCUID3,
  ZodCUID2: () => ZodCUID22,
  ZodCatch: () => ZodCatch2,
  ZodCodec: () => ZodCodec2,
  ZodCustom: () => ZodCustom2,
  ZodCustomStringFormat: () => ZodCustomStringFormat2,
  ZodDate: () => ZodDate2,
  ZodDefault: () => ZodDefault2,
  ZodDiscriminatedUnion: () => ZodDiscriminatedUnion2,
  ZodE164: () => ZodE1642,
  ZodEmail: () => ZodEmail2,
  ZodEmoji: () => ZodEmoji2,
  ZodEnum: () => ZodEnum2,
  ZodError: () => ZodError2,
  ZodExactOptional: () => ZodExactOptional2,
  ZodFile: () => ZodFile2,
  ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind2,
  ZodFunction: () => ZodFunction2,
  ZodGUID: () => ZodGUID2,
  ZodIPv4: () => ZodIPv42,
  ZodIPv6: () => ZodIPv62,
  ZodISODate: () => ZodISODate2,
  ZodISODateTime: () => ZodISODateTime2,
  ZodISODuration: () => ZodISODuration2,
  ZodISOTime: () => ZodISOTime2,
  ZodIntersection: () => ZodIntersection2,
  ZodIssueCode: () => ZodIssueCode2,
  ZodJWT: () => ZodJWT2,
  ZodKSUID: () => ZodKSUID2,
  ZodLazy: () => ZodLazy2,
  ZodLiteral: () => ZodLiteral2,
  ZodMAC: () => ZodMAC2,
  ZodMap: () => ZodMap2,
  ZodNaN: () => ZodNaN2,
  ZodNanoID: () => ZodNanoID2,
  ZodNever: () => ZodNever2,
  ZodNonOptional: () => ZodNonOptional2,
  ZodNull: () => ZodNull2,
  ZodNullable: () => ZodNullable2,
  ZodNumber: () => ZodNumber2,
  ZodNumberFormat: () => ZodNumberFormat2,
  ZodObject: () => ZodObject2,
  ZodOptional: () => ZodOptional2,
  ZodPipe: () => ZodPipe2,
  ZodPrefault: () => ZodPrefault2,
  ZodPreprocess: () => ZodPreprocess2,
  ZodPromise: () => ZodPromise2,
  ZodReadonly: () => ZodReadonly2,
  ZodRealError: () => ZodRealError2,
  ZodRecord: () => ZodRecord2,
  ZodSet: () => ZodSet2,
  ZodString: () => ZodString2,
  ZodStringFormat: () => ZodStringFormat2,
  ZodSuccess: () => ZodSuccess2,
  ZodSymbol: () => ZodSymbol2,
  ZodTemplateLiteral: () => ZodTemplateLiteral2,
  ZodTransform: () => ZodTransform2,
  ZodTuple: () => ZodTuple2,
  ZodType: () => ZodType2,
  ZodULID: () => ZodULID2,
  ZodURL: () => ZodURL2,
  ZodUUID: () => ZodUUID2,
  ZodUndefined: () => ZodUndefined2,
  ZodUnion: () => ZodUnion2,
  ZodUnknown: () => ZodUnknown2,
  ZodVoid: () => ZodVoid2,
  ZodXID: () => ZodXID2,
  ZodXor: () => ZodXor2,
  _ZodString: () => _ZodString2,
  _default: () => _default4,
  _function: () => _function2,
  any: () => any2,
  array: () => array2,
  base64: () => base644,
  base64url: () => base64url4,
  bigint: () => bigint5,
  boolean: () => boolean5,
  catch: () => _catch4,
  check: () => check2,
  cidrv4: () => cidrv44,
  cidrv6: () => cidrv64,
  clone: () => clone2,
  codec: () => codec2,
  coerce: () => coerce_exports2,
  config: () => config2,
  core: () => core_exports3,
  cuid: () => cuid5,
  cuid2: () => cuid24,
  custom: () => custom2,
  date: () => date7,
  decode: () => decode4,
  decodeAsync: () => decodeAsync4,
  describe: () => describe4,
  discriminatedUnion: () => discriminatedUnion2,
  e164: () => e1644,
  email: () => email4,
  emoji: () => emoji4,
  encode: () => encode4,
  encodeAsync: () => encodeAsync4,
  endsWith: () => _endsWith2,
  enum: () => _enum4,
  exactOptional: () => exactOptional2,
  file: () => file3,
  flattenError: () => flattenError2,
  float32: () => float322,
  float64: () => float642,
  formatError: () => formatError2,
  fromJSONSchema: () => fromJSONSchema2,
  function: () => _function2,
  getErrorMap: () => getErrorMap2,
  globalRegistry: () => globalRegistry2,
  gt: () => _gt2,
  gte: () => _gte2,
  guid: () => guid4,
  hash: () => hash2,
  hex: () => hex4,
  hostname: () => hostname4,
  httpUrl: () => httpUrl2,
  includes: () => _includes2,
  instanceof: () => _instanceof2,
  int: () => int2,
  int32: () => int322,
  int64: () => int642,
  intersection: () => intersection2,
  invertCodec: () => invertCodec2,
  ipv4: () => ipv44,
  ipv6: () => ipv64,
  iso: () => iso_exports2,
  json: () => json2,
  jwt: () => jwt2,
  keyof: () => keyof2,
  ksuid: () => ksuid4,
  lazy: () => lazy2,
  length: () => _length2,
  literal: () => literal2,
  locales: () => locales_exports2,
  looseObject: () => looseObject2,
  looseRecord: () => looseRecord2,
  lowercase: () => _lowercase2,
  lt: () => _lt2,
  lte: () => _lte2,
  mac: () => mac4,
  map: () => map2,
  maxLength: () => _maxLength2,
  maxSize: () => _maxSize2,
  meta: () => meta4,
  mime: () => _mime2,
  minLength: () => _minLength2,
  minSize: () => _minSize2,
  multipleOf: () => _multipleOf2,
  nan: () => nan2,
  nanoid: () => nanoid4,
  nativeEnum: () => nativeEnum2,
  negative: () => _negative2,
  never: () => never2,
  nonnegative: () => _nonnegative2,
  nonoptional: () => nonoptional2,
  nonpositive: () => _nonpositive2,
  normalize: () => _normalize2,
  null: () => _null6,
  nullable: () => nullable2,
  nullish: () => nullish4,
  number: () => number5,
  object: () => object2,
  optional: () => optional2,
  overwrite: () => _overwrite2,
  parse: () => parse6,
  parseAsync: () => parseAsync4,
  partialRecord: () => partialRecord2,
  pipe: () => pipe2,
  positive: () => _positive2,
  prefault: () => prefault2,
  preprocess: () => preprocess2,
  prettifyError: () => prettifyError2,
  promise: () => promise2,
  property: () => _property2,
  readonly: () => readonly2,
  record: () => record2,
  refine: () => refine2,
  regex: () => _regex2,
  regexes: () => regexes_exports2,
  registry: () => registry2,
  safeDecode: () => safeDecode4,
  safeDecodeAsync: () => safeDecodeAsync4,
  safeEncode: () => safeEncode4,
  safeEncodeAsync: () => safeEncodeAsync4,
  safeParse: () => safeParse4,
  safeParseAsync: () => safeParseAsync4,
  set: () => set2,
  setErrorMap: () => setErrorMap2,
  size: () => _size2,
  slugify: () => _slugify2,
  startsWith: () => _startsWith2,
  strictObject: () => strictObject2,
  string: () => string5,
  stringFormat: () => stringFormat2,
  stringbool: () => stringbool2,
  success: () => success2,
  superRefine: () => superRefine2,
  symbol: () => symbol2,
  templateLiteral: () => templateLiteral2,
  toJSONSchema: () => toJSONSchema2,
  toLowerCase: () => _toLowerCase2,
  toUpperCase: () => _toUpperCase2,
  transform: () => transform2,
  treeifyError: () => treeifyError2,
  trim: () => _trim2,
  tuple: () => tuple2,
  uint32: () => uint322,
  uint64: () => uint642,
  ulid: () => ulid4,
  undefined: () => _undefined6,
  union: () => union2,
  unknown: () => unknown2,
  uppercase: () => _uppercase2,
  url: () => url5,
  util: () => util_exports2,
  uuid: () => uuid5,
  uuidv4: () => uuidv42,
  uuidv6: () => uuidv62,
  uuidv7: () => uuidv72,
  void: () => _void4,
  xid: () => xid4,
  xor: () => xor2
});

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/index.js
var core_exports3 = {};
__export(core_exports3, {
  $ZodAny: () => $ZodAny2,
  $ZodArray: () => $ZodArray2,
  $ZodAsyncError: () => $ZodAsyncError2,
  $ZodBase64: () => $ZodBase642,
  $ZodBase64URL: () => $ZodBase64URL2,
  $ZodBigInt: () => $ZodBigInt2,
  $ZodBigIntFormat: () => $ZodBigIntFormat2,
  $ZodBoolean: () => $ZodBoolean2,
  $ZodCIDRv4: () => $ZodCIDRv42,
  $ZodCIDRv6: () => $ZodCIDRv62,
  $ZodCUID: () => $ZodCUID3,
  $ZodCUID2: () => $ZodCUID22,
  $ZodCatch: () => $ZodCatch2,
  $ZodCheck: () => $ZodCheck2,
  $ZodCheckBigIntFormat: () => $ZodCheckBigIntFormat2,
  $ZodCheckEndsWith: () => $ZodCheckEndsWith2,
  $ZodCheckGreaterThan: () => $ZodCheckGreaterThan2,
  $ZodCheckIncludes: () => $ZodCheckIncludes2,
  $ZodCheckLengthEquals: () => $ZodCheckLengthEquals2,
  $ZodCheckLessThan: () => $ZodCheckLessThan2,
  $ZodCheckLowerCase: () => $ZodCheckLowerCase2,
  $ZodCheckMaxLength: () => $ZodCheckMaxLength2,
  $ZodCheckMaxSize: () => $ZodCheckMaxSize2,
  $ZodCheckMimeType: () => $ZodCheckMimeType2,
  $ZodCheckMinLength: () => $ZodCheckMinLength2,
  $ZodCheckMinSize: () => $ZodCheckMinSize2,
  $ZodCheckMultipleOf: () => $ZodCheckMultipleOf2,
  $ZodCheckNumberFormat: () => $ZodCheckNumberFormat2,
  $ZodCheckOverwrite: () => $ZodCheckOverwrite2,
  $ZodCheckProperty: () => $ZodCheckProperty2,
  $ZodCheckRegex: () => $ZodCheckRegex2,
  $ZodCheckSizeEquals: () => $ZodCheckSizeEquals2,
  $ZodCheckStartsWith: () => $ZodCheckStartsWith2,
  $ZodCheckStringFormat: () => $ZodCheckStringFormat2,
  $ZodCheckUpperCase: () => $ZodCheckUpperCase2,
  $ZodCodec: () => $ZodCodec2,
  $ZodCustom: () => $ZodCustom2,
  $ZodCustomStringFormat: () => $ZodCustomStringFormat2,
  $ZodDate: () => $ZodDate2,
  $ZodDefault: () => $ZodDefault2,
  $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion2,
  $ZodE164: () => $ZodE1642,
  $ZodEmail: () => $ZodEmail2,
  $ZodEmoji: () => $ZodEmoji2,
  $ZodEncodeError: () => $ZodEncodeError2,
  $ZodEnum: () => $ZodEnum2,
  $ZodError: () => $ZodError2,
  $ZodExactOptional: () => $ZodExactOptional2,
  $ZodFile: () => $ZodFile2,
  $ZodFunction: () => $ZodFunction2,
  $ZodGUID: () => $ZodGUID2,
  $ZodIPv4: () => $ZodIPv42,
  $ZodIPv6: () => $ZodIPv62,
  $ZodISODate: () => $ZodISODate2,
  $ZodISODateTime: () => $ZodISODateTime2,
  $ZodISODuration: () => $ZodISODuration2,
  $ZodISOTime: () => $ZodISOTime2,
  $ZodIntersection: () => $ZodIntersection2,
  $ZodJWT: () => $ZodJWT2,
  $ZodKSUID: () => $ZodKSUID2,
  $ZodLazy: () => $ZodLazy2,
  $ZodLiteral: () => $ZodLiteral2,
  $ZodMAC: () => $ZodMAC2,
  $ZodMap: () => $ZodMap2,
  $ZodNaN: () => $ZodNaN2,
  $ZodNanoID: () => $ZodNanoID2,
  $ZodNever: () => $ZodNever2,
  $ZodNonOptional: () => $ZodNonOptional2,
  $ZodNull: () => $ZodNull2,
  $ZodNullable: () => $ZodNullable2,
  $ZodNumber: () => $ZodNumber2,
  $ZodNumberFormat: () => $ZodNumberFormat2,
  $ZodObject: () => $ZodObject2,
  $ZodObjectJIT: () => $ZodObjectJIT2,
  $ZodOptional: () => $ZodOptional2,
  $ZodPipe: () => $ZodPipe2,
  $ZodPrefault: () => $ZodPrefault2,
  $ZodPreprocess: () => $ZodPreprocess2,
  $ZodPromise: () => $ZodPromise2,
  $ZodReadonly: () => $ZodReadonly2,
  $ZodRealError: () => $ZodRealError2,
  $ZodRecord: () => $ZodRecord2,
  $ZodRegistry: () => $ZodRegistry2,
  $ZodSet: () => $ZodSet2,
  $ZodString: () => $ZodString2,
  $ZodStringFormat: () => $ZodStringFormat2,
  $ZodSuccess: () => $ZodSuccess2,
  $ZodSymbol: () => $ZodSymbol2,
  $ZodTemplateLiteral: () => $ZodTemplateLiteral2,
  $ZodTransform: () => $ZodTransform2,
  $ZodTuple: () => $ZodTuple2,
  $ZodType: () => $ZodType2,
  $ZodULID: () => $ZodULID2,
  $ZodURL: () => $ZodURL2,
  $ZodUUID: () => $ZodUUID2,
  $ZodUndefined: () => $ZodUndefined2,
  $ZodUnion: () => $ZodUnion2,
  $ZodUnknown: () => $ZodUnknown2,
  $ZodVoid: () => $ZodVoid2,
  $ZodXID: () => $ZodXID2,
  $ZodXor: () => $ZodXor2,
  $brand: () => $brand2,
  $constructor: () => $constructor2,
  $input: () => $input2,
  $output: () => $output2,
  Doc: () => Doc2,
  JSONSchema: () => json_schema_exports2,
  JSONSchemaGenerator: () => JSONSchemaGenerator2,
  NEVER: () => NEVER2,
  TimePrecision: () => TimePrecision2,
  _any: () => _any2,
  _array: () => _array2,
  _base64: () => _base642,
  _base64url: () => _base64url2,
  _bigint: () => _bigint2,
  _boolean: () => _boolean2,
  _catch: () => _catch3,
  _check: () => _check2,
  _cidrv4: () => _cidrv42,
  _cidrv6: () => _cidrv62,
  _coercedBigint: () => _coercedBigint2,
  _coercedBoolean: () => _coercedBoolean2,
  _coercedDate: () => _coercedDate2,
  _coercedNumber: () => _coercedNumber2,
  _coercedString: () => _coercedString2,
  _cuid: () => _cuid3,
  _cuid2: () => _cuid22,
  _custom: () => _custom2,
  _date: () => _date2,
  _decode: () => _decode2,
  _decodeAsync: () => _decodeAsync2,
  _default: () => _default3,
  _discriminatedUnion: () => _discriminatedUnion2,
  _e164: () => _e1642,
  _email: () => _email2,
  _emoji: () => _emoji4,
  _encode: () => _encode2,
  _encodeAsync: () => _encodeAsync2,
  _endsWith: () => _endsWith2,
  _enum: () => _enum3,
  _file: () => _file2,
  _float32: () => _float322,
  _float64: () => _float642,
  _gt: () => _gt2,
  _gte: () => _gte2,
  _guid: () => _guid2,
  _includes: () => _includes2,
  _int: () => _int2,
  _int32: () => _int322,
  _int64: () => _int642,
  _intersection: () => _intersection2,
  _ipv4: () => _ipv42,
  _ipv6: () => _ipv62,
  _isoDate: () => _isoDate2,
  _isoDateTime: () => _isoDateTime2,
  _isoDuration: () => _isoDuration2,
  _isoTime: () => _isoTime2,
  _jwt: () => _jwt2,
  _ksuid: () => _ksuid2,
  _lazy: () => _lazy2,
  _length: () => _length2,
  _literal: () => _literal2,
  _lowercase: () => _lowercase2,
  _lt: () => _lt2,
  _lte: () => _lte2,
  _mac: () => _mac2,
  _map: () => _map2,
  _max: () => _lte2,
  _maxLength: () => _maxLength2,
  _maxSize: () => _maxSize2,
  _mime: () => _mime2,
  _min: () => _gte2,
  _minLength: () => _minLength2,
  _minSize: () => _minSize2,
  _multipleOf: () => _multipleOf2,
  _nan: () => _nan2,
  _nanoid: () => _nanoid2,
  _nativeEnum: () => _nativeEnum2,
  _negative: () => _negative2,
  _never: () => _never2,
  _nonnegative: () => _nonnegative2,
  _nonoptional: () => _nonoptional2,
  _nonpositive: () => _nonpositive2,
  _normalize: () => _normalize2,
  _null: () => _null5,
  _nullable: () => _nullable2,
  _number: () => _number2,
  _optional: () => _optional2,
  _overwrite: () => _overwrite2,
  _parse: () => _parse2,
  _parseAsync: () => _parseAsync2,
  _pipe: () => _pipe2,
  _positive: () => _positive2,
  _promise: () => _promise2,
  _property: () => _property2,
  _readonly: () => _readonly2,
  _record: () => _record2,
  _refine: () => _refine2,
  _regex: () => _regex2,
  _safeDecode: () => _safeDecode2,
  _safeDecodeAsync: () => _safeDecodeAsync2,
  _safeEncode: () => _safeEncode2,
  _safeEncodeAsync: () => _safeEncodeAsync2,
  _safeParse: () => _safeParse2,
  _safeParseAsync: () => _safeParseAsync2,
  _set: () => _set2,
  _size: () => _size2,
  _slugify: () => _slugify2,
  _startsWith: () => _startsWith2,
  _string: () => _string2,
  _stringFormat: () => _stringFormat2,
  _stringbool: () => _stringbool2,
  _success: () => _success2,
  _superRefine: () => _superRefine2,
  _symbol: () => _symbol2,
  _templateLiteral: () => _templateLiteral2,
  _toLowerCase: () => _toLowerCase2,
  _toUpperCase: () => _toUpperCase2,
  _transform: () => _transform2,
  _trim: () => _trim2,
  _tuple: () => _tuple2,
  _uint32: () => _uint322,
  _uint64: () => _uint642,
  _ulid: () => _ulid2,
  _undefined: () => _undefined5,
  _union: () => _union2,
  _unknown: () => _unknown2,
  _uppercase: () => _uppercase2,
  _url: () => _url2,
  _uuid: () => _uuid2,
  _uuidv4: () => _uuidv42,
  _uuidv6: () => _uuidv62,
  _uuidv7: () => _uuidv72,
  _void: () => _void3,
  _xid: () => _xid2,
  _xor: () => _xor2,
  clone: () => clone2,
  config: () => config2,
  createStandardJSONSchemaMethod: () => createStandardJSONSchemaMethod2,
  createToJSONSchemaMethod: () => createToJSONSchemaMethod2,
  decode: () => decode3,
  decodeAsync: () => decodeAsync3,
  describe: () => describe3,
  encode: () => encode3,
  encodeAsync: () => encodeAsync3,
  extractDefs: () => extractDefs2,
  finalize: () => finalize2,
  flattenError: () => flattenError2,
  formatError: () => formatError2,
  globalConfig: () => globalConfig2,
  globalRegistry: () => globalRegistry2,
  initializeContext: () => initializeContext2,
  isValidBase64: () => isValidBase642,
  isValidBase64URL: () => isValidBase64URL2,
  isValidJWT: () => isValidJWT2,
  locales: () => locales_exports2,
  meta: () => meta3,
  parse: () => parse5,
  parseAsync: () => parseAsync3,
  prettifyError: () => prettifyError2,
  process: () => process4,
  regexes: () => regexes_exports2,
  registry: () => registry2,
  safeDecode: () => safeDecode3,
  safeDecodeAsync: () => safeDecodeAsync3,
  safeEncode: () => safeEncode3,
  safeEncodeAsync: () => safeEncodeAsync3,
  safeParse: () => safeParse3,
  safeParseAsync: () => safeParseAsync3,
  toDotPath: () => toDotPath2,
  toJSONSchema: () => toJSONSchema2,
  treeifyError: () => treeifyError2,
  util: () => util_exports2,
  version: () => version2
});

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/core.js
var _a3;
var NEVER2 = /* @__PURE__ */ Object.freeze({
  status: "aborted"
});
// @__NO_SIDE_EFFECTS__
function $constructor2(name, initializer5, params) {
  function init3(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);
    initializer5(inst, def);
    const proto2 = _.prototype;
    const keys = Object.keys(proto2);
    for (let i = 0; i < keys.length; i++) {
      const k = keys[i];
      if (!(k in inst)) {
        inst[k] = proto2[k].bind(inst);
      }
    }
  }
  const Parent = params?.Parent ?? Object;
  class Definition extends Parent {
  }
  Object.defineProperty(Definition, "name", { value: name });
  function _(def) {
    var _a5;
    const inst = params?.Parent ? new Definition() : this;
    init3(inst, def);
    (_a5 = inst._zod).deferred ?? (_a5.deferred = []);
    for (const fn of inst._zod.deferred) {
      fn();
    }
    return inst;
  }
  Object.defineProperty(_, "init", { value: init3 });
  Object.defineProperty(_, Symbol.hasInstance, {
    value: (inst) => {
      if (params?.Parent && inst instanceof params.Parent)
        return true;
      return inst?._zod?.traits?.has(name);
    }
  });
  Object.defineProperty(_, "name", { value: name });
  return _;
}
var $brand2 = /* @__PURE__ */ Symbol("zod_brand");
var $ZodAsyncError2 = class extends Error {
  constructor() {
    super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
  }
};
var $ZodEncodeError2 = class extends Error {
  constructor(name) {
    super(`Encountered unidirectional transform during encode: ${name}`);
    this.name = "ZodEncodeError";
  }
};
(_a3 = globalThis).__zod_globalConfig ?? (_a3.__zod_globalConfig = {});
var globalConfig2 = globalThis.__zod_globalConfig;
function config2(newConfig) {
  if (newConfig)
    Object.assign(globalConfig2, newConfig);
  return globalConfig2;
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/util.js
var util_exports2 = {};
__export(util_exports2, {
  BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES2,
  Class: () => Class2,
  NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES2,
  aborted: () => aborted2,
  allowsEval: () => allowsEval2,
  assert: () => assert3,
  assertEqual: () => assertEqual2,
  assertIs: () => assertIs2,
  assertNever: () => assertNever,
  assertNotEqual: () => assertNotEqual2,
  assignProp: () => assignProp2,
  base64ToUint8Array: () => base64ToUint8Array2,
  base64urlToUint8Array: () => base64urlToUint8Array2,
  cached: () => cached2,
  captureStackTrace: () => captureStackTrace2,
  cleanEnum: () => cleanEnum2,
  cleanRegex: () => cleanRegex2,
  clone: () => clone2,
  cloneDef: () => cloneDef2,
  createTransparentProxy: () => createTransparentProxy2,
  defineLazy: () => defineLazy2,
  esc: () => esc2,
  escapeRegex: () => escapeRegex2,
  explicitlyAborted: () => explicitlyAborted2,
  extend: () => extend2,
  finalizeIssue: () => finalizeIssue2,
  floatSafeRemainder: () => floatSafeRemainder2,
  getElementAtPath: () => getElementAtPath2,
  getEnumValues: () => getEnumValues2,
  getLengthableOrigin: () => getLengthableOrigin2,
  getParsedType: () => getParsedType2,
  getSizableOrigin: () => getSizableOrigin2,
  hexToUint8Array: () => hexToUint8Array2,
  isObject: () => isObject2,
  isPlainObject: () => isPlainObject2,
  issue: () => issue2,
  joinValues: () => joinValues2,
  jsonStringifyReplacer: () => jsonStringifyReplacer2,
  merge: () => merge2,
  mergeDefs: () => mergeDefs2,
  normalizeParams: () => normalizeParams2,
  nullish: () => nullish3,
  numKeys: () => numKeys2,
  objectClone: () => objectClone2,
  omit: () => omit2,
  optionalKeys: () => optionalKeys2,
  parsedType: () => parsedType2,
  partial: () => partial2,
  pick: () => pick2,
  prefixIssues: () => prefixIssues2,
  primitiveTypes: () => primitiveTypes2,
  promiseAllObject: () => promiseAllObject2,
  propertyKeyTypes: () => propertyKeyTypes2,
  randomString: () => randomString2,
  required: () => required2,
  safeExtend: () => safeExtend2,
  shallowClone: () => shallowClone2,
  slugify: () => slugify2,
  stringifyPrimitive: () => stringifyPrimitive2,
  uint8ArrayToBase64: () => uint8ArrayToBase642,
  uint8ArrayToBase64url: () => uint8ArrayToBase64url2,
  uint8ArrayToHex: () => uint8ArrayToHex2,
  unwrapMessage: () => unwrapMessage2
});
function assertEqual2(val) {
  return val;
}
function assertNotEqual2(val) {
  return val;
}
function assertIs2(_arg) {
}
function assertNever(_x) {
  throw new Error("Unexpected value in exhaustive check");
}
function assert3(_) {
}
function getEnumValues2(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;
}
function joinValues2(array3, separator = "|") {
  return array3.map((val) => stringifyPrimitive2(val)).join(separator);
}
function jsonStringifyReplacer2(_, value) {
  if (typeof value === "bigint")
    return value.toString();
  return value;
}
function cached2(getter) {
  const set3 = false;
  return {
    get value() {
      if (!set3) {
        const value = getter();
        Object.defineProperty(this, "value", { value });
        return value;
      }
      throw new Error("cached value already set");
    }
  };
}
function nullish3(input) {
  return input === null || input === void 0;
}
function cleanRegex2(source) {
  const start = source.startsWith("^") ? 1 : 0;
  const end = source.endsWith("$") ? source.length - 1 : source.length;
  return source.slice(start, end);
}
function floatSafeRemainder2(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;
}
var EVALUATING2 = /* @__PURE__ */ Symbol("evaluating");
function defineLazy2(object3, key, getter) {
  let value = void 0;
  Object.defineProperty(object3, key, {
    get() {
      if (value === EVALUATING2) {
        return void 0;
      }
      if (value === void 0) {
        value = EVALUATING2;
        value = getter();
      }
      return value;
    },
    set(v) {
      Object.defineProperty(object3, key, {
        value: v
        // configurable: true,
      });
    },
    configurable: true
  });
}
function objectClone2(obj) {
  return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));
}
function assignProp2(target, prop, value) {
  Object.defineProperty(target, prop, {
    value,
    writable: true,
    enumerable: true,
    configurable: true
  });
}
function mergeDefs2(...defs) {
  const mergedDescriptors = {};
  for (const def of defs) {
    const descriptors = Object.getOwnPropertyDescriptors(def);
    Object.assign(mergedDescriptors, descriptors);
  }
  return Object.defineProperties({}, mergedDescriptors);
}
function cloneDef2(schema) {
  return mergeDefs2(schema._zod.def);
}
function getElementAtPath2(obj, path73) {
  if (!path73)
    return obj;
  return path73.reduce((acc, key) => acc?.[key], obj);
}
function promiseAllObject2(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;
  });
}
function randomString2(length = 10) {
  const chars = "abcdefghijklmnopqrstuvwxyz";
  let str = "";
  for (let i = 0; i < length; i++) {
    str += chars[Math.floor(Math.random() * chars.length)];
  }
  return str;
}
function esc2(str) {
  return JSON.stringify(str);
}
function slugify2(input) {
  return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
}
var captureStackTrace2 = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {
};
function isObject2(data) {
  return typeof data === "object" && data !== null && !Array.isArray(data);
}
var allowsEval2 = /* @__PURE__ */ cached2(() => {
  if (globalConfig2.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 (isObject2(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 (isObject2(prot) === false)
    return false;
  if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
    return false;
  }
  return true;
}
function shallowClone2(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;
}
function numKeys2(data) {
  let keyCount = 0;
  for (const key in data) {
    if (Object.prototype.hasOwnProperty.call(data, key)) {
      keyCount++;
    }
  }
  return keyCount;
}
var getParsedType2 = (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}`);
  }
};
var propertyKeyTypes2 = /* @__PURE__ */ new Set(["string", "number", "symbol"]);
var primitiveTypes2 = /* @__PURE__ */ new Set([
  "string",
  "number",
  "bigint",
  "boolean",
  "symbol",
  "undefined"
]);
function escapeRegex2(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function clone2(inst, def, params) {
  const cl = new inst._zod.constr(def ?? inst._zod.def);
  if (!def || params?.parent)
    cl._zod.parent = inst;
  return cl;
}
function normalizeParams2(_params) {
  const params = _params;
  if (!params)
    return {};
  if (typeof params === "string")
    return { error: () => params };
  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: () => params.error };
  return params;
}
function createTransparentProxy2(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);
    }
  });
}
function stringifyPrimitive2(value) {
  if (typeof value === "bigint")
    return value.toString() + "n";
  if (typeof value === "string")
    return `"${value}"`;
  return `${value}`;
}
function optionalKeys2(shape) {
  return Object.keys(shape).filter((k) => {
    return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
  });
}
var NUMBER_FORMAT_RANGES2 = {
  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_RANGES2 = {
  int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")],
  uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")]
};
function pick2(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 = mergeDefs2(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];
      }
      assignProp2(this, "shape", newShape);
      return newShape;
    },
    checks: []
  });
  return clone2(schema, def);
}
function omit2(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 = mergeDefs2(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];
      }
      assignProp2(this, "shape", newShape);
      return newShape;
    },
    checks: []
  });
  return clone2(schema, def);
}
function extend2(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 = mergeDefs2(schema._zod.def, {
    get shape() {
      const _shape = { ...schema._zod.def.shape, ...shape };
      assignProp2(this, "shape", _shape);
      return _shape;
    }
  });
  return clone2(schema, def);
}
function safeExtend2(schema, shape) {
  if (!isPlainObject2(shape)) {
    throw new Error("Invalid input to safeExtend: expected a plain object");
  }
  const def = mergeDefs2(schema._zod.def, {
    get shape() {
      const _shape = { ...schema._zod.def.shape, ...shape };
      assignProp2(this, "shape", _shape);
      return _shape;
    }
  });
  return clone2(schema, def);
}
function merge2(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 = mergeDefs2(a._zod.def, {
    get shape() {
      const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };
      assignProp2(this, "shape", _shape);
      return _shape;
    },
    get catchall() {
      return b._zod.def.catchall;
    },
    checks: b._zod.def.checks ?? []
  });
  return clone2(a, def);
}
function partial2(Class3, 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 = mergeDefs2(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] = Class3 ? new Class3({
            type: "optional",
            innerType: oldShape[key]
          }) : oldShape[key];
        }
      } else {
        for (const key in oldShape) {
          shape[key] = Class3 ? new Class3({
            type: "optional",
            innerType: oldShape[key]
          }) : oldShape[key];
        }
      }
      assignProp2(this, "shape", shape);
      return shape;
    },
    checks: []
  });
  return clone2(schema, def);
}
function required2(Class3, schema, mask) {
  const def = mergeDefs2(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 Class3({
            type: "nonoptional",
            innerType: oldShape[key]
          });
        }
      } else {
        for (const key in oldShape) {
          shape[key] = new Class3({
            type: "nonoptional",
            innerType: oldShape[key]
          });
        }
      }
      assignProp2(this, "shape", shape);
      return shape;
    }
  });
  return clone2(schema, def);
}
function aborted2(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;
}
function explicitlyAborted2(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;
}
function prefixIssues2(path73, issues) {
  return issues.map((iss) => {
    var _a5;
    (_a5 = iss).path ?? (_a5.path = []);
    iss.path.unshift(path73);
    return iss;
  });
}
function unwrapMessage2(message) {
  return typeof message === "string" ? message : message?.message;
}
function finalizeIssue2(iss, ctx, config3) {
  const message = iss.message ? iss.message : unwrapMessage2(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage2(ctx?.error?.(iss)) ?? unwrapMessage2(config3.customError?.(iss)) ?? unwrapMessage2(config3.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;
}
function getSizableOrigin2(input) {
  if (input instanceof Set)
    return "set";
  if (input instanceof Map)
    return "map";
  if (input instanceof File)
    return "file";
  return "unknown";
}
function getLengthableOrigin2(input) {
  if (Array.isArray(input))
    return "array";
  if (typeof input === "string")
    return "string";
  return "unknown";
}
function parsedType2(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;
}
function issue2(...args) {
  const [iss, input, inst] = args;
  if (typeof iss === "string") {
    return {
      message: iss,
      code: "custom",
      input,
      inst
    };
  }
  return { ...iss };
}
function cleanEnum2(obj) {
  return Object.entries(obj).filter(([k, _]) => {
    return Number.isNaN(Number.parseInt(k, 10));
  }).map((el) => el[1]);
}
function base64ToUint8Array2(base645) {
  const binaryString = atob(base645);
  const bytes = new Uint8Array(binaryString.length);
  for (let i = 0; i < binaryString.length; i++) {
    bytes[i] = binaryString.charCodeAt(i);
  }
  return bytes;
}
function uint8ArrayToBase642(bytes) {
  let binaryString = "";
  for (let i = 0; i < bytes.length; i++) {
    binaryString += String.fromCharCode(bytes[i]);
  }
  return btoa(binaryString);
}
function base64urlToUint8Array2(base64url5) {
  const base645 = base64url5.replace(/-/g, "+").replace(/_/g, "/");
  const padding = "=".repeat((4 - base645.length % 4) % 4);
  return base64ToUint8Array2(base645 + padding);
}
function uint8ArrayToBase64url2(bytes) {
  return uint8ArrayToBase642(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
}
function hexToUint8Array2(hex5) {
  const cleanHex = hex5.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;
}
function uint8ArrayToHex2(bytes) {
  return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
}
var Class2 = class {
  constructor(..._args) {
  }
};

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/errors.js
var initializer3 = (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, jsonStringifyReplacer2, 2);
  Object.defineProperty(inst, "toString", {
    value: () => inst.message,
    enumerable: false
  });
};
var $ZodError2 = $constructor2("$ZodError", initializer3);
var $ZodRealError2 = $constructor2("$ZodError", initializer3, { Parent: Error });
function flattenError2(error101, mapper = (issue3) => issue3.message) {
  const fieldErrors = {};
  const formErrors = [];
  for (const sub of error101.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 };
}
function formatError2(error101, mapper = (issue3) => issue3.message) {
  const fieldErrors = { _errors: [] };
  const processError = (error102, path73 = []) => {
    for (const issue3 of error102.issues) {
      if (issue3.code === "invalid_union" && issue3.errors.length) {
        issue3.errors.map((issues) => processError({ issues }, [...path73, ...issue3.path]));
      } else if (issue3.code === "invalid_key") {
        processError({ issues: issue3.issues }, [...path73, ...issue3.path]);
      } else if (issue3.code === "invalid_element") {
        processError({ issues: issue3.issues }, [...path73, ...issue3.path]);
      } else {
        const fullpath = [...path73, ...issue3.path];
        if (fullpath.length === 0) {
          fieldErrors._errors.push(mapper(issue3));
        } 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(issue3));
            }
            curr = curr[el];
            i++;
          }
        }
      }
    }
  };
  processError(error101);
  return fieldErrors;
}
function treeifyError2(error101, mapper = (issue3) => issue3.message) {
  const result = { errors: [] };
  const processError = (error102, path73 = []) => {
    var _a5, _b;
    for (const issue3 of error102.issues) {
      if (issue3.code === "invalid_union" && issue3.errors.length) {
        issue3.errors.map((issues) => processError({ issues }, [...path73, ...issue3.path]));
      } else if (issue3.code === "invalid_key") {
        processError({ issues: issue3.issues }, [...path73, ...issue3.path]);
      } else if (issue3.code === "invalid_element") {
        processError({ issues: issue3.issues }, [...path73, ...issue3.path]);
      } else {
        const fullpath = [...path73, ...issue3.path];
        if (fullpath.length === 0) {
          result.errors.push(mapper(issue3));
          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 = {});
            (_a5 = curr.properties)[el] ?? (_a5[el] = { errors: [] });
            curr = curr.properties[el];
          } else {
            curr.items ?? (curr.items = []);
            (_b = curr.items)[el] ?? (_b[el] = { errors: [] });
            curr = curr.items[el];
          }
          if (terminal) {
            curr.errors.push(mapper(issue3));
          }
          i++;
        }
      }
    }
  };
  processError(error101);
  return result;
}
function toDotPath2(_path) {
  const segs = [];
  const path73 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
  for (const seg of path73) {
    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("");
}
function prettifyError2(error101) {
  const lines = [];
  const issues = [...error101.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);
  for (const issue3 of issues) {
    lines.push(`\u2716 ${issue3.message}`);
    if (issue3.path?.length)
      lines.push(`  \u2192 at ${toDotPath2(issue3.path)}`);
  }
  return lines.join("\n");
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/parse.js
var _parse2 = (_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 $ZodAsyncError2();
  }
  if (result.issues.length) {
    const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue2(iss, ctx, config2())));
    captureStackTrace2(e, _params?.callee);
    throw e;
  }
  return result.value;
};
var parse5 = /* @__PURE__ */ _parse2($ZodRealError2);
var _parseAsync2 = (_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) => finalizeIssue2(iss, ctx, config2())));
    captureStackTrace2(e, params?.callee);
    throw e;
  }
  return result.value;
};
var parseAsync3 = /* @__PURE__ */ _parseAsync2($ZodRealError2);
var _safeParse2 = (_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 $ZodAsyncError2();
  }
  return result.issues.length ? {
    success: false,
    error: new (_Err ?? $ZodError2)(result.issues.map((iss) => finalizeIssue2(iss, ctx, config2())))
  } : { success: true, data: result.value };
};
var safeParse3 = /* @__PURE__ */ _safeParse2($ZodRealError2);
var _safeParseAsync2 = (_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) => finalizeIssue2(iss, ctx, config2())))
  } : { success: true, data: result.value };
};
var safeParseAsync3 = /* @__PURE__ */ _safeParseAsync2($ZodRealError2);
var _encode2 = (_Err) => (schema, value, _ctx) => {
  const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
  return _parse2(_Err)(schema, value, ctx);
};
var encode3 = /* @__PURE__ */ _encode2($ZodRealError2);
var _decode2 = (_Err) => (schema, value, _ctx) => {
  return _parse2(_Err)(schema, value, _ctx);
};
var decode3 = /* @__PURE__ */ _decode2($ZodRealError2);
var _encodeAsync2 = (_Err) => async (schema, value, _ctx) => {
  const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
  return _parseAsync2(_Err)(schema, value, ctx);
};
var encodeAsync3 = /* @__PURE__ */ _encodeAsync2($ZodRealError2);
var _decodeAsync2 = (_Err) => async (schema, value, _ctx) => {
  return _parseAsync2(_Err)(schema, value, _ctx);
};
var decodeAsync3 = /* @__PURE__ */ _decodeAsync2($ZodRealError2);
var _safeEncode2 = (_Err) => (schema, value, _ctx) => {
  const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
  return _safeParse2(_Err)(schema, value, ctx);
};
var safeEncode3 = /* @__PURE__ */ _safeEncode2($ZodRealError2);
var _safeDecode2 = (_Err) => (schema, value, _ctx) => {
  return _safeParse2(_Err)(schema, value, _ctx);
};
var safeDecode3 = /* @__PURE__ */ _safeDecode2($ZodRealError2);
var _safeEncodeAsync2 = (_Err) => async (schema, value, _ctx) => {
  const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
  return _safeParseAsync2(_Err)(schema, value, ctx);
};
var safeEncodeAsync3 = /* @__PURE__ */ _safeEncodeAsync2($ZodRealError2);
var _safeDecodeAsync2 = (_Err) => async (schema, value, _ctx) => {
  return _safeParseAsync2(_Err)(schema, value, _ctx);
};
var safeDecodeAsync3 = /* @__PURE__ */ _safeDecodeAsync2($ZodRealError2);

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/regexes.js
var regexes_exports2 = {};
__export(regexes_exports2, {
  base64: () => base643,
  base64url: () => base64url3,
  bigint: () => bigint4,
  boolean: () => boolean4,
  browserEmail: () => browserEmail2,
  cidrv4: () => cidrv43,
  cidrv6: () => cidrv63,
  cuid: () => cuid4,
  cuid2: () => cuid23,
  date: () => date5,
  datetime: () => datetime3,
  domain: () => domain2,
  duration: () => duration3,
  e164: () => e1643,
  email: () => email3,
  emoji: () => emoji3,
  extendedDuration: () => extendedDuration2,
  guid: () => guid3,
  hex: () => hex3,
  hostname: () => hostname3,
  html5Email: () => html5Email2,
  httpProtocol: () => httpProtocol2,
  idnEmail: () => idnEmail2,
  integer: () => integer2,
  ipv4: () => ipv43,
  ipv6: () => ipv63,
  ksuid: () => ksuid3,
  lowercase: () => lowercase2,
  mac: () => mac3,
  md5_base64: () => md5_base642,
  md5_base64url: () => md5_base64url2,
  md5_hex: () => md5_hex2,
  nanoid: () => nanoid3,
  null: () => _null4,
  number: () => number4,
  rfc5322Email: () => rfc5322Email2,
  sha1_base64: () => sha1_base642,
  sha1_base64url: () => sha1_base64url2,
  sha1_hex: () => sha1_hex2,
  sha256_base64: () => sha256_base642,
  sha256_base64url: () => sha256_base64url2,
  sha256_hex: () => sha256_hex2,
  sha384_base64: () => sha384_base642,
  sha384_base64url: () => sha384_base64url2,
  sha384_hex: () => sha384_hex2,
  sha512_base64: () => sha512_base642,
  sha512_base64url: () => sha512_base64url2,
  sha512_hex: () => sha512_hex2,
  string: () => string4,
  time: () => time3,
  ulid: () => ulid3,
  undefined: () => _undefined4,
  unicodeEmail: () => unicodeEmail2,
  uppercase: () => uppercase2,
  uuid: () => uuid3,
  uuid4: () => uuid42,
  uuid6: () => uuid62,
  uuid7: () => uuid72,
  xid: () => xid3
});
var cuid4 = /^[cC][0-9a-z]{6,}$/;
var cuid23 = /^[0-9a-z]+$/;
var ulid3 = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
var xid3 = /^[0-9a-vA-V]{20}$/;
var ksuid3 = /^[A-Za-z0-9]{27}$/;
var nanoid3 = /^[a-zA-Z0-9_-]{21}$/;
var duration3 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
var extendedDuration2 = /^[-+]?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 guid3 = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
var uuid3 = (version4) => {
  if (!version4)
    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}-${version4}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
};
var uuid42 = /* @__PURE__ */ uuid3(4);
var uuid62 = /* @__PURE__ */ uuid3(6);
var uuid72 = /* @__PURE__ */ uuid3(7);
var email3 = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
var html5Email2 = /^[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 rfc5322Email2 = /^(([^<>()\[\]\\.,;:\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 unicodeEmail2 = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u;
var idnEmail2 = unicodeEmail2;
var browserEmail2 = /^[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 _emoji3 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
function emoji3() {
  return new RegExp(_emoji3, "u");
}
var ipv43 = /^(?:(?: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 ipv63 = /^(([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 mac3 = (delimiter) => {
  const escapedDelim = escapeRegex2(delimiter ?? ":");
  return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);
};
var cidrv43 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
var cidrv63 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
var base643 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
var base64url3 = /^[A-Za-z0-9_-]*$/;
var hostname3 = /^(?=.{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 domain2 = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
var httpProtocol2 = /^https?$/;
var e1643 = /^\+[1-9]\d{6,14}$/;
var dateSource2 = `(?:(?:\\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 date5 = /* @__PURE__ */ new RegExp(`^${dateSource2}$`);
function timeSource2(args) {
  const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
  const regex3 = 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 regex3;
}
function time3(args) {
  return new RegExp(`^${timeSource2(args)}$`);
}
function datetime3(args) {
  const time5 = timeSource2({ 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 = `${time5}(?:${opts.join("|")})`;
  return new RegExp(`^${dateSource2}T(?:${timeRegex})$`);
}
var string4 = (params) => {
  const regex3 = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
  return new RegExp(`^${regex3}$`);
};
var bigint4 = /^-?\d+n?$/;
var integer2 = /^-?\d+$/;
var number4 = /^-?\d+(?:\.\d+)?$/;
var boolean4 = /^(?:true|false)$/i;
var _null4 = /^null$/i;
var _undefined4 = /^undefined$/i;
var lowercase2 = /^[^A-Z]*$/;
var uppercase2 = /^[^a-z]*$/;
var hex3 = /^[0-9a-fA-F]*$/;
function fixedBase642(bodyLength, padding) {
  return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);
}
function fixedBase64url2(length) {
  return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);
}
var md5_hex2 = /^[0-9a-fA-F]{32}$/;
var md5_base642 = /* @__PURE__ */ fixedBase642(22, "==");
var md5_base64url2 = /* @__PURE__ */ fixedBase64url2(22);
var sha1_hex2 = /^[0-9a-fA-F]{40}$/;
var sha1_base642 = /* @__PURE__ */ fixedBase642(27, "=");
var sha1_base64url2 = /* @__PURE__ */ fixedBase64url2(27);
var sha256_hex2 = /^[0-9a-fA-F]{64}$/;
var sha256_base642 = /* @__PURE__ */ fixedBase642(43, "=");
var sha256_base64url2 = /* @__PURE__ */ fixedBase64url2(43);
var sha384_hex2 = /^[0-9a-fA-F]{96}$/;
var sha384_base642 = /* @__PURE__ */ fixedBase642(64, "");
var sha384_base64url2 = /* @__PURE__ */ fixedBase64url2(64);
var sha512_hex2 = /^[0-9a-fA-F]{128}$/;
var sha512_base642 = /* @__PURE__ */ fixedBase642(86, "==");
var sha512_base64url2 = /* @__PURE__ */ fixedBase64url2(86);

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/checks.js
var $ZodCheck2 = /* @__PURE__ */ $constructor2("$ZodCheck", (inst, def) => {
  var _a5;
  inst._zod ?? (inst._zod = {});
  inst._zod.def = def;
  (_a5 = inst._zod).onattach ?? (_a5.onattach = []);
});
var numericOriginMap2 = {
  number: "number",
  bigint: "bigint",
  object: "date"
};
var $ZodCheckLessThan2 = /* @__PURE__ */ $constructor2("$ZodCheckLessThan", (inst, def) => {
  $ZodCheck2.init(inst, def);
  const origin = numericOriginMap2[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 $ZodCheckGreaterThan2 = /* @__PURE__ */ $constructor2("$ZodCheckGreaterThan", (inst, def) => {
  $ZodCheck2.init(inst, def);
  const origin = numericOriginMap2[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 $ZodCheckMultipleOf2 = /* @__PURE__ */ $constructor2("$ZodCheckMultipleOf", (inst, def) => {
  $ZodCheck2.init(inst, def);
  inst._zod.onattach.push((inst2) => {
    var _a5;
    (_a5 = inst2._zod.bag).multipleOf ?? (_a5.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) : floatSafeRemainder2(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 $ZodCheckNumberFormat2 = /* @__PURE__ */ $constructor2("$ZodCheckNumberFormat", (inst, def) => {
  $ZodCheck2.init(inst, def);
  def.format = def.format || "float64";
  const isInt = def.format?.includes("int");
  const origin = isInt ? "int" : "number";
  const [minimum, maximum] = NUMBER_FORMAT_RANGES2[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 = integer2;
  });
  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 $ZodCheckBigIntFormat2 = /* @__PURE__ */ $constructor2("$ZodCheckBigIntFormat", (inst, def) => {
  $ZodCheck2.init(inst, def);
  const [minimum, maximum] = BIGINT_FORMAT_RANGES2[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 $ZodCheckMaxSize2 = /* @__PURE__ */ $constructor2("$ZodCheckMaxSize", (inst, def) => {
  var _a5;
  $ZodCheck2.init(inst, def);
  (_a5 = inst._zod.def).when ?? (_a5.when = (payload) => {
    const val = payload.value;
    return !nullish3(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: getSizableOrigin2(input),
      code: "too_big",
      maximum: def.maximum,
      inclusive: true,
      input,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckMinSize2 = /* @__PURE__ */ $constructor2("$ZodCheckMinSize", (inst, def) => {
  var _a5;
  $ZodCheck2.init(inst, def);
  (_a5 = inst._zod.def).when ?? (_a5.when = (payload) => {
    const val = payload.value;
    return !nullish3(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: getSizableOrigin2(input),
      code: "too_small",
      minimum: def.minimum,
      inclusive: true,
      input,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckSizeEquals2 = /* @__PURE__ */ $constructor2("$ZodCheckSizeEquals", (inst, def) => {
  var _a5;
  $ZodCheck2.init(inst, def);
  (_a5 = inst._zod.def).when ?? (_a5.when = (payload) => {
    const val = payload.value;
    return !nullish3(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: getSizableOrigin2(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 $ZodCheckMaxLength2 = /* @__PURE__ */ $constructor2("$ZodCheckMaxLength", (inst, def) => {
  var _a5;
  $ZodCheck2.init(inst, def);
  (_a5 = inst._zod.def).when ?? (_a5.when = (payload) => {
    const val = payload.value;
    return !nullish3(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 = getLengthableOrigin2(input);
    payload.issues.push({
      origin,
      code: "too_big",
      maximum: def.maximum,
      inclusive: true,
      input,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckMinLength2 = /* @__PURE__ */ $constructor2("$ZodCheckMinLength", (inst, def) => {
  var _a5;
  $ZodCheck2.init(inst, def);
  (_a5 = inst._zod.def).when ?? (_a5.when = (payload) => {
    const val = payload.value;
    return !nullish3(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 = getLengthableOrigin2(input);
    payload.issues.push({
      origin,
      code: "too_small",
      minimum: def.minimum,
      inclusive: true,
      input,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckLengthEquals2 = /* @__PURE__ */ $constructor2("$ZodCheckLengthEquals", (inst, def) => {
  var _a5;
  $ZodCheck2.init(inst, def);
  (_a5 = inst._zod.def).when ?? (_a5.when = (payload) => {
    const val = payload.value;
    return !nullish3(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 = getLengthableOrigin2(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 $ZodCheckStringFormat2 = /* @__PURE__ */ $constructor2("$ZodCheckStringFormat", (inst, def) => {
  var _a5, _b;
  $ZodCheck2.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)
    (_a5 = inst._zod).check ?? (_a5.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
    (_b = inst._zod).check ?? (_b.check = () => {
    });
});
var $ZodCheckRegex2 = /* @__PURE__ */ $constructor2("$ZodCheckRegex", (inst, def) => {
  $ZodCheckStringFormat2.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 $ZodCheckLowerCase2 = /* @__PURE__ */ $constructor2("$ZodCheckLowerCase", (inst, def) => {
  def.pattern ?? (def.pattern = lowercase2);
  $ZodCheckStringFormat2.init(inst, def);
});
var $ZodCheckUpperCase2 = /* @__PURE__ */ $constructor2("$ZodCheckUpperCase", (inst, def) => {
  def.pattern ?? (def.pattern = uppercase2);
  $ZodCheckStringFormat2.init(inst, def);
});
var $ZodCheckIncludes2 = /* @__PURE__ */ $constructor2("$ZodCheckIncludes", (inst, def) => {
  $ZodCheck2.init(inst, def);
  const escapedRegex = escapeRegex2(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 $ZodCheckStartsWith2 = /* @__PURE__ */ $constructor2("$ZodCheckStartsWith", (inst, def) => {
  $ZodCheck2.init(inst, def);
  const pattern = new RegExp(`^${escapeRegex2(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 $ZodCheckEndsWith2 = /* @__PURE__ */ $constructor2("$ZodCheckEndsWith", (inst, def) => {
  $ZodCheck2.init(inst, def);
  const pattern = new RegExp(`.*${escapeRegex2(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 handleCheckPropertyResult2(result, payload, property) {
  if (result.issues.length) {
    payload.issues.push(...prefixIssues2(property, result.issues));
  }
}
var $ZodCheckProperty2 = /* @__PURE__ */ $constructor2("$ZodCheckProperty", (inst, def) => {
  $ZodCheck2.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) => handleCheckPropertyResult2(result2, payload, def.property));
    }
    handleCheckPropertyResult2(result, payload, def.property);
    return;
  };
});
var $ZodCheckMimeType2 = /* @__PURE__ */ $constructor2("$ZodCheckMimeType", (inst, def) => {
  $ZodCheck2.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 $ZodCheckOverwrite2 = /* @__PURE__ */ $constructor2("$ZodCheckOverwrite", (inst, def) => {
  $ZodCheck2.init(inst, def);
  inst._zod.check = (payload) => {
    payload.value = def.tx(payload.value);
  };
});

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/doc.js
var Doc2 = class {
  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/.pnpm/zod@4.4.3/node_modules/zod/v4/core/versions.js
var version2 = {
  major: 4,
  minor: 4,
  patch: 3
};

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/schemas.js
var $ZodType2 = /* @__PURE__ */ $constructor2("$ZodType", (inst, def) => {
  var _a5;
  inst ?? (inst = {});
  inst._zod.def = def;
  inst._zod.bag = inst._zod.bag || {};
  inst._zod.version = version2;
  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) {
    (_a5 = inst._zod).deferred ?? (_a5.deferred = []);
    inst._zod.deferred?.push(() => {
      inst._zod.run = inst._zod.parse;
    });
  } else {
    const runChecks = (payload, checks2, ctx) => {
      let isAborted = aborted2(payload);
      let asyncResult;
      for (const ch of checks2) {
        if (ch._zod.def.when) {
          if (explicitlyAborted2(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 $ZodAsyncError2();
        }
        if (asyncResult || _ instanceof Promise) {
          asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
            await _;
            const nextLen = payload.issues.length;
            if (nextLen === currLen)
              return;
            if (!isAborted)
              isAborted = aborted2(payload, currLen);
          });
        } else {
          const nextLen = payload.issues.length;
          if (nextLen === currLen)
            continue;
          if (!isAborted)
            isAborted = aborted2(payload, currLen);
        }
      }
      if (asyncResult) {
        return asyncResult.then(() => {
          return payload;
        });
      }
      return payload;
    };
    const handleCanaryResult = (canary, payload, ctx) => {
      if (aborted2(canary)) {
        canary.aborted = true;
        return canary;
      }
      const checkResult = runChecks(payload, checks, ctx);
      if (checkResult instanceof Promise) {
        if (ctx.async === false)
          throw new $ZodAsyncError2();
        return checkResult.then((checkResult2) => inst._zod.parse(checkResult2, ctx));
      }
      return inst._zod.parse(checkResult, ctx);
    };
    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 $ZodAsyncError2();
        return result.then((result2) => runChecks(result2, checks, ctx));
      }
      return runChecks(result, checks, ctx);
    };
  }
  defineLazy2(inst, "~standard", () => ({
    validate: (value) => {
      try {
        const r = safeParse3(inst, value);
        return r.success ? { value: r.data } : { issues: r.error?.issues };
      } catch (_) {
        return safeParseAsync3(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues });
      }
    },
    vendor: "zod",
    version: 1
  }));
});
var $ZodString2 = /* @__PURE__ */ $constructor2("$ZodString", (inst, def) => {
  $ZodType2.init(inst, def);
  inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string4(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 $ZodStringFormat2 = /* @__PURE__ */ $constructor2("$ZodStringFormat", (inst, def) => {
  $ZodCheckStringFormat2.init(inst, def);
  $ZodString2.init(inst, def);
});
var $ZodGUID2 = /* @__PURE__ */ $constructor2("$ZodGUID", (inst, def) => {
  def.pattern ?? (def.pattern = guid3);
  $ZodStringFormat2.init(inst, def);
});
var $ZodUUID2 = /* @__PURE__ */ $constructor2("$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 = uuid3(v));
  } else
    def.pattern ?? (def.pattern = uuid3());
  $ZodStringFormat2.init(inst, def);
});
var $ZodEmail2 = /* @__PURE__ */ $constructor2("$ZodEmail", (inst, def) => {
  def.pattern ?? (def.pattern = email3);
  $ZodStringFormat2.init(inst, def);
});
var $ZodURL2 = /* @__PURE__ */ $constructor2("$ZodURL", (inst, def) => {
  $ZodStringFormat2.init(inst, def);
  inst._zod.check = (payload) => {
    try {
      const trimmed = payload.value.trim();
      if (!def.normalize && def.protocol?.source === httpProtocol2.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 url46 = new URL(trimmed);
      if (def.hostname) {
        def.hostname.lastIndex = 0;
        if (!def.hostname.test(url46.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(url46.protocol.endsWith(":") ? url46.protocol.slice(0, -1) : url46.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 = url46.href;
      } else {
        payload.value = trimmed;
      }
      return;
    } catch (_) {
      payload.issues.push({
        code: "invalid_format",
        format: "url",
        input: payload.value,
        inst,
        continue: !def.abort
      });
    }
  };
});
var $ZodEmoji2 = /* @__PURE__ */ $constructor2("$ZodEmoji", (inst, def) => {
  def.pattern ?? (def.pattern = emoji3());
  $ZodStringFormat2.init(inst, def);
});
var $ZodNanoID2 = /* @__PURE__ */ $constructor2("$ZodNanoID", (inst, def) => {
  def.pattern ?? (def.pattern = nanoid3);
  $ZodStringFormat2.init(inst, def);
});
var $ZodCUID3 = /* @__PURE__ */ $constructor2("$ZodCUID", (inst, def) => {
  def.pattern ?? (def.pattern = cuid4);
  $ZodStringFormat2.init(inst, def);
});
var $ZodCUID22 = /* @__PURE__ */ $constructor2("$ZodCUID2", (inst, def) => {
  def.pattern ?? (def.pattern = cuid23);
  $ZodStringFormat2.init(inst, def);
});
var $ZodULID2 = /* @__PURE__ */ $constructor2("$ZodULID", (inst, def) => {
  def.pattern ?? (def.pattern = ulid3);
  $ZodStringFormat2.init(inst, def);
});
var $ZodXID2 = /* @__PURE__ */ $constructor2("$ZodXID", (inst, def) => {
  def.pattern ?? (def.pattern = xid3);
  $ZodStringFormat2.init(inst, def);
});
var $ZodKSUID2 = /* @__PURE__ */ $constructor2("$ZodKSUID", (inst, def) => {
  def.pattern ?? (def.pattern = ksuid3);
  $ZodStringFormat2.init(inst, def);
});
var $ZodISODateTime2 = /* @__PURE__ */ $constructor2("$ZodISODateTime", (inst, def) => {
  def.pattern ?? (def.pattern = datetime3(def));
  $ZodStringFormat2.init(inst, def);
});
var $ZodISODate2 = /* @__PURE__ */ $constructor2("$ZodISODate", (inst, def) => {
  def.pattern ?? (def.pattern = date5);
  $ZodStringFormat2.init(inst, def);
});
var $ZodISOTime2 = /* @__PURE__ */ $constructor2("$ZodISOTime", (inst, def) => {
  def.pattern ?? (def.pattern = time3(def));
  $ZodStringFormat2.init(inst, def);
});
var $ZodISODuration2 = /* @__PURE__ */ $constructor2("$ZodISODuration", (inst, def) => {
  def.pattern ?? (def.pattern = duration3);
  $ZodStringFormat2.init(inst, def);
});
var $ZodIPv42 = /* @__PURE__ */ $constructor2("$ZodIPv4", (inst, def) => {
  def.pattern ?? (def.pattern = ipv43);
  $ZodStringFormat2.init(inst, def);
  inst._zod.bag.format = `ipv4`;
});
var $ZodIPv62 = /* @__PURE__ */ $constructor2("$ZodIPv6", (inst, def) => {
  def.pattern ?? (def.pattern = ipv63);
  $ZodStringFormat2.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 $ZodMAC2 = /* @__PURE__ */ $constructor2("$ZodMAC", (inst, def) => {
  def.pattern ?? (def.pattern = mac3(def.delimiter));
  $ZodStringFormat2.init(inst, def);
  inst._zod.bag.format = `mac`;
});
var $ZodCIDRv42 = /* @__PURE__ */ $constructor2("$ZodCIDRv4", (inst, def) => {
  def.pattern ?? (def.pattern = cidrv43);
  $ZodStringFormat2.init(inst, def);
});
var $ZodCIDRv62 = /* @__PURE__ */ $constructor2("$ZodCIDRv6", (inst, def) => {
  def.pattern ?? (def.pattern = cidrv63);
  $ZodStringFormat2.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 isValidBase642(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;
  }
}
var $ZodBase642 = /* @__PURE__ */ $constructor2("$ZodBase64", (inst, def) => {
  def.pattern ?? (def.pattern = base643);
  $ZodStringFormat2.init(inst, def);
  inst._zod.bag.contentEncoding = "base64";
  inst._zod.check = (payload) => {
    if (isValidBase642(payload.value))
      return;
    payload.issues.push({
      code: "invalid_format",
      format: "base64",
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
function isValidBase64URL2(data) {
  if (!base64url3.test(data))
    return false;
  const base645 = data.replace(/[-_]/g, (c2) => c2 === "-" ? "+" : "/");
  const padded = base645.padEnd(Math.ceil(base645.length / 4) * 4, "=");
  return isValidBase642(padded);
}
var $ZodBase64URL2 = /* @__PURE__ */ $constructor2("$ZodBase64URL", (inst, def) => {
  def.pattern ?? (def.pattern = base64url3);
  $ZodStringFormat2.init(inst, def);
  inst._zod.bag.contentEncoding = "base64url";
  inst._zod.check = (payload) => {
    if (isValidBase64URL2(payload.value))
      return;
    payload.issues.push({
      code: "invalid_format",
      format: "base64url",
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodE1642 = /* @__PURE__ */ $constructor2("$ZodE164", (inst, def) => {
  def.pattern ?? (def.pattern = e1643);
  $ZodStringFormat2.init(inst, def);
});
function isValidJWT2(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;
  }
}
var $ZodJWT2 = /* @__PURE__ */ $constructor2("$ZodJWT", (inst, def) => {
  $ZodStringFormat2.init(inst, def);
  inst._zod.check = (payload) => {
    if (isValidJWT2(payload.value, def.alg))
      return;
    payload.issues.push({
      code: "invalid_format",
      format: "jwt",
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCustomStringFormat2 = /* @__PURE__ */ $constructor2("$ZodCustomStringFormat", (inst, def) => {
  $ZodStringFormat2.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 $ZodNumber2 = /* @__PURE__ */ $constructor2("$ZodNumber", (inst, def) => {
  $ZodType2.init(inst, def);
  inst._zod.pattern = inst._zod.bag.pattern ?? number4;
  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 $ZodNumberFormat2 = /* @__PURE__ */ $constructor2("$ZodNumberFormat", (inst, def) => {
  $ZodCheckNumberFormat2.init(inst, def);
  $ZodNumber2.init(inst, def);
});
var $ZodBoolean2 = /* @__PURE__ */ $constructor2("$ZodBoolean", (inst, def) => {
  $ZodType2.init(inst, def);
  inst._zod.pattern = boolean4;
  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 $ZodBigInt2 = /* @__PURE__ */ $constructor2("$ZodBigInt", (inst, def) => {
  $ZodType2.init(inst, def);
  inst._zod.pattern = bigint4;
  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 $ZodBigIntFormat2 = /* @__PURE__ */ $constructor2("$ZodBigIntFormat", (inst, def) => {
  $ZodCheckBigIntFormat2.init(inst, def);
  $ZodBigInt2.init(inst, def);
});
var $ZodSymbol2 = /* @__PURE__ */ $constructor2("$ZodSymbol", (inst, def) => {
  $ZodType2.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 $ZodUndefined2 = /* @__PURE__ */ $constructor2("$ZodUndefined", (inst, def) => {
  $ZodType2.init(inst, def);
  inst._zod.pattern = _undefined4;
  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 $ZodNull2 = /* @__PURE__ */ $constructor2("$ZodNull", (inst, def) => {
  $ZodType2.init(inst, def);
  inst._zod.pattern = _null4;
  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 $ZodAny2 = /* @__PURE__ */ $constructor2("$ZodAny", (inst, def) => {
  $ZodType2.init(inst, def);
  inst._zod.parse = (payload) => payload;
});
var $ZodUnknown2 = /* @__PURE__ */ $constructor2("$ZodUnknown", (inst, def) => {
  $ZodType2.init(inst, def);
  inst._zod.parse = (payload) => payload;
});
var $ZodNever2 = /* @__PURE__ */ $constructor2("$ZodNever", (inst, def) => {
  $ZodType2.init(inst, def);
  inst._zod.parse = (payload, _ctx) => {
    payload.issues.push({
      expected: "never",
      code: "invalid_type",
      input: payload.value,
      inst
    });
    return payload;
  };
});
var $ZodVoid2 = /* @__PURE__ */ $constructor2("$ZodVoid", (inst, def) => {
  $ZodType2.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 $ZodDate2 = /* @__PURE__ */ $constructor2("$ZodDate", (inst, def) => {
  $ZodType2.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 handleArrayResult2(result, final, index) {
  if (result.issues.length) {
    final.issues.push(...prefixIssues2(index, result.issues));
  }
  final.value[index] = result.value;
}
var $ZodArray2 = /* @__PURE__ */ $constructor2("$ZodArray", (inst, def) => {
  $ZodType2.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) => handleArrayResult2(result2, payload, i)));
      } else {
        handleArrayResult2(result, payload, i);
      }
    }
    if (proms.length) {
      return Promise.all(proms).then(() => payload);
    }
    return payload;
  };
});
function handlePropertyResult2(result, final, key, input, isOptionalIn, isOptionalOut) {
  const isPresent = key in input;
  if (result.issues.length) {
    if (isOptionalIn && isOptionalOut && !isPresent) {
      return;
    }
    final.issues.push(...prefixIssues2(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;
  }
}
function normalizeDef2(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 = optionalKeys2(def.shape);
  return {
    ...def,
    keys,
    keySet: new Set(keys),
    numKeys: keys.length,
    optionalKeys: new Set(okeys)
  };
}
function handleCatchall2(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) => handlePropertyResult2(r2, payload, key, input, isOptionalIn, isOptionalOut)));
    } else {
      handlePropertyResult2(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;
  });
}
var $ZodObject2 = /* @__PURE__ */ $constructor2("$ZodObject", (inst, def) => {
  $ZodType2.init(inst, def);
  const desc = Object.getOwnPropertyDescriptor(def, "shape");
  if (!desc?.get) {
    const sh = def.shape;
    Object.defineProperty(def, "shape", {
      get: () => {
        const newSh = { ...sh };
        Object.defineProperty(def, "shape", {
          value: newSh
        });
        return newSh;
      }
    });
  }
  const _normalized = cached2(() => normalizeDef2(def));
  defineLazy2(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 isObject3 = isObject2;
  const catchall = def.catchall;
  let value;
  inst._zod.parse = (payload, ctx) => {
    value ?? (value = _normalized.value);
    const input = payload.value;
    if (!isObject3(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) => handlePropertyResult2(r2, payload, key, input, isOptionalIn, isOptionalOut)));
      } else {
        handlePropertyResult2(r, payload, key, input, isOptionalIn, isOptionalOut);
      }
    }
    if (!catchall) {
      return proms.length ? Promise.all(proms).then(() => payload) : payload;
    }
    return handleCatchall2(proms, input, payload, ctx, _normalized.value, inst);
  };
});
var $ZodObjectJIT2 = /* @__PURE__ */ $constructor2("$ZodObjectJIT", (inst, def) => {
  $ZodObject2.init(inst, def);
  const superParse = inst._zod.parse;
  const _normalized = cached2(() => normalizeDef2(def));
  const generateFastpass = (shape) => {
    const doc = new Doc2(["shape", "payload", "ctx"]);
    const normalized = _normalized.value;
    const parseStr = (key) => {
      const k = esc2(key);
      return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
    };
    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 = esc2(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);
  };
  let fastpass;
  const isObject3 = isObject2;
  const jit = !globalConfig2.jitless;
  const allowsEval3 = allowsEval2;
  const fastEnabled = jit && allowsEval3.value;
  const catchall = def.catchall;
  let value;
  inst._zod.parse = (payload, ctx) => {
    value ?? (value = _normalized.value);
    const input = payload.value;
    if (!isObject3(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 handleCatchall2([], input, payload, ctx, value, inst);
    }
    return superParse(payload, ctx);
  };
});
function handleUnionResults2(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) => !aborted2(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) => finalizeIssue2(iss, ctx, config2())))
  });
  return final;
}
var $ZodUnion2 = /* @__PURE__ */ $constructor2("$ZodUnion", (inst, def) => {
  $ZodType2.init(inst, def);
  defineLazy2(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0);
  defineLazy2(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0);
  defineLazy2(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;
  });
  defineLazy2(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((p2) => cleanRegex2(p2.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 handleUnionResults2(results, payload, inst, ctx);
    return Promise.all(results).then((results2) => {
      return handleUnionResults2(results2, payload, inst, ctx);
    });
  };
});
function handleExclusiveUnionResults2(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) => finalizeIssue2(iss, ctx, config2())))
    });
  } else {
    final.issues.push({
      code: "invalid_union",
      input: final.value,
      inst,
      errors: [],
      inclusive: false
    });
  }
  return final;
}
var $ZodXor2 = /* @__PURE__ */ $constructor2("$ZodXor", (inst, def) => {
  $ZodUnion2.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 handleExclusiveUnionResults2(results, payload, inst, ctx);
    return Promise.all(results).then((results2) => {
      return handleExclusiveUnionResults2(results2, payload, inst, ctx);
    });
  };
});
var $ZodDiscriminatedUnion2 = /* @__PURE__ */ $constructor2("$ZodDiscriminatedUnion", (inst, def) => {
  def.inclusive = false;
  $ZodUnion2.init(inst, def);
  const _super = inst._zod.parse;
  defineLazy2(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 = cached2(() => {
    const opts = def.options;
    const map3 = /* @__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 (map3.has(v)) {
          throw new Error(`Duplicate discriminator value "${String(v)}"`);
        }
        map3.set(v, o);
      }
    }
    return map3;
  });
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    if (!isObject2(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 $ZodIntersection2 = /* @__PURE__ */ $constructor2("$ZodIntersection", (inst, def) => {
  $ZodType2.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    const left = def.left._zod.run({ value: input, issues: [] }, ctx);
    const right = def.right._zod.run({ value: input, issues: [] }, ctx);
    const async = left instanceof Promise || right instanceof Promise;
    if (async) {
      return Promise.all([left, right]).then(([left2, right2]) => {
        return handleIntersectionResults2(payload, left2, right2);
      });
    }
    return handleIntersectionResults2(payload, left, right);
  };
});
function mergeValues2(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 = mergeValues2(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 = mergeValues2(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: [] };
}
function handleIntersectionResults2(result, left, right) {
  const unrecKeys = /* @__PURE__ */ new Map();
  let unrecIssue;
  for (const iss of left.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 right.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 (aborted2(result))
    return result;
  const merged = mergeValues2(left.value, right.value);
  if (!merged.valid) {
    throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);
  }
  result.value = merged.data;
  return result;
}
var $ZodTuple2 = /* @__PURE__ */ $constructor2("$ZodTuple", (inst, def) => {
  $ZodType2.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 = getTupleOptStart2(items, "optin");
    const optoutStart = getTupleOptStart2(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) => handleTupleResult2(r, payload, i)));
        } else {
          handleTupleResult2(result, payload, i);
        }
      }
    }
    if (proms.length) {
      return Promise.all(proms).then(() => handleTupleResults2(itemResults, payload, items, input, optoutStart));
    }
    return handleTupleResults2(itemResults, payload, items, input, optoutStart);
  };
});
function getTupleOptStart2(items, key) {
  for (let i = items.length - 1; i >= 0; i--) {
    if (items[i]._zod[key] !== "optional")
      return i + 1;
  }
  return 0;
}
function handleTupleResult2(result, final, index) {
  if (result.issues.length) {
    final.issues.push(...prefixIssues2(index, result.issues));
  }
  final.value[index] = result.value;
}
function handleTupleResults2(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(...prefixIssues2(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;
}
var $ZodRecord2 = /* @__PURE__ */ $constructor2("$ZodRecord", (inst, def) => {
  $ZodType2.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) => finalizeIssue2(iss, ctx, config2())),
              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(...prefixIssues2(key, result2.issues));
              }
              payload.value[outKey] = result2.value;
            }));
          } else {
            if (result.issues.length) {
              payload.issues.push(...prefixIssues2(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" && number4.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) => finalizeIssue2(iss, ctx, config2())),
              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(...prefixIssues2(key, result2.issues));
            }
            payload.value[keyResult.value] = result2.value;
          }));
        } else {
          if (result.issues.length) {
            payload.issues.push(...prefixIssues2(key, result.issues));
          }
          payload.value[keyResult.value] = result.value;
        }
      }
    }
    if (proms.length) {
      return Promise.all(proms).then(() => payload);
    }
    return payload;
  };
});
var $ZodMap2 = /* @__PURE__ */ $constructor2("$ZodMap", (inst, def) => {
  $ZodType2.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]) => {
          handleMapResult2(keyResult2, valueResult2, payload, key, input, inst, ctx);
        }));
      } else {
        handleMapResult2(keyResult, valueResult, payload, key, input, inst, ctx);
      }
    }
    if (proms.length)
      return Promise.all(proms).then(() => payload);
    return payload;
  };
});
function handleMapResult2(keyResult, valueResult, final, key, input, inst, ctx) {
  if (keyResult.issues.length) {
    if (propertyKeyTypes2.has(typeof key)) {
      final.issues.push(...prefixIssues2(key, keyResult.issues));
    } else {
      final.issues.push({
        code: "invalid_key",
        origin: "map",
        input,
        inst,
        issues: keyResult.issues.map((iss) => finalizeIssue2(iss, ctx, config2()))
      });
    }
  }
  if (valueResult.issues.length) {
    if (propertyKeyTypes2.has(typeof key)) {
      final.issues.push(...prefixIssues2(key, valueResult.issues));
    } else {
      final.issues.push({
        origin: "map",
        code: "invalid_element",
        input,
        inst,
        key,
        issues: valueResult.issues.map((iss) => finalizeIssue2(iss, ctx, config2()))
      });
    }
  }
  final.value.set(keyResult.value, valueResult.value);
}
var $ZodSet2 = /* @__PURE__ */ $constructor2("$ZodSet", (inst, def) => {
  $ZodType2.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) => handleSetResult2(result2, payload)));
      } else
        handleSetResult2(result, payload);
    }
    if (proms.length)
      return Promise.all(proms).then(() => payload);
    return payload;
  };
});
function handleSetResult2(result, final) {
  if (result.issues.length) {
    final.issues.push(...result.issues);
  }
  final.value.add(result.value);
}
var $ZodEnum2 = /* @__PURE__ */ $constructor2("$ZodEnum", (inst, def) => {
  $ZodType2.init(inst, def);
  const values = getEnumValues2(def.entries);
  const valuesSet = new Set(values);
  inst._zod.values = valuesSet;
  inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes2.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex2(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 $ZodLiteral2 = /* @__PURE__ */ $constructor2("$ZodLiteral", (inst, def) => {
  $ZodType2.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" ? escapeRegex2(o) : o ? escapeRegex2(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 $ZodFile2 = /* @__PURE__ */ $constructor2("$ZodFile", (inst, def) => {
  $ZodType2.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 $ZodTransform2 = /* @__PURE__ */ $constructor2("$ZodTransform", (inst, def) => {
  $ZodType2.init(inst, def);
  inst._zod.optin = "optional";
  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      throw new $ZodEncodeError2(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 $ZodAsyncError2();
    }
    payload.value = _out;
    payload.fallback = true;
    return payload;
  };
});
function handleOptionalResult2(result, input) {
  if (input === void 0 && (result.issues.length || result.fallback)) {
    return { issues: [], value: void 0 };
  }
  return result;
}
var $ZodOptional2 = /* @__PURE__ */ $constructor2("$ZodOptional", (inst, def) => {
  $ZodType2.init(inst, def);
  inst._zod.optin = "optional";
  inst._zod.optout = "optional";
  defineLazy2(inst._zod, "values", () => {
    return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0;
  });
  defineLazy2(inst._zod, "pattern", () => {
    const pattern = def.innerType._zod.pattern;
    return pattern ? new RegExp(`^(${cleanRegex2(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) => handleOptionalResult2(r, input));
      return handleOptionalResult2(result, input);
    }
    if (payload.value === void 0) {
      return payload;
    }
    return def.innerType._zod.run(payload, ctx);
  };
});
var $ZodExactOptional2 = /* @__PURE__ */ $constructor2("$ZodExactOptional", (inst, def) => {
  $ZodOptional2.init(inst, def);
  defineLazy2(inst._zod, "values", () => def.innerType._zod.values);
  defineLazy2(inst._zod, "pattern", () => def.innerType._zod.pattern);
  inst._zod.parse = (payload, ctx) => {
    return def.innerType._zod.run(payload, ctx);
  };
});
var $ZodNullable2 = /* @__PURE__ */ $constructor2("$ZodNullable", (inst, def) => {
  $ZodType2.init(inst, def);
  defineLazy2(inst._zod, "optin", () => def.innerType._zod.optin);
  defineLazy2(inst._zod, "optout", () => def.innerType._zod.optout);
  defineLazy2(inst._zod, "pattern", () => {
    const pattern = def.innerType._zod.pattern;
    return pattern ? new RegExp(`^(${cleanRegex2(pattern.source)}|null)$`) : void 0;
  });
  defineLazy2(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 $ZodDefault2 = /* @__PURE__ */ $constructor2("$ZodDefault", (inst, def) => {
  $ZodType2.init(inst, def);
  inst._zod.optin = "optional";
  defineLazy2(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) => handleDefaultResult2(result2, def));
    }
    return handleDefaultResult2(result, def);
  };
});
function handleDefaultResult2(payload, def) {
  if (payload.value === void 0) {
    payload.value = def.defaultValue;
  }
  return payload;
}
var $ZodPrefault2 = /* @__PURE__ */ $constructor2("$ZodPrefault", (inst, def) => {
  $ZodType2.init(inst, def);
  inst._zod.optin = "optional";
  defineLazy2(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 $ZodNonOptional2 = /* @__PURE__ */ $constructor2("$ZodNonOptional", (inst, def) => {
  $ZodType2.init(inst, def);
  defineLazy2(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) => handleNonOptionalResult2(result2, inst));
    }
    return handleNonOptionalResult2(result, inst);
  };
});
function handleNonOptionalResult2(payload, inst) {
  if (!payload.issues.length && payload.value === void 0) {
    payload.issues.push({
      code: "invalid_type",
      expected: "nonoptional",
      input: payload.value,
      inst
    });
  }
  return payload;
}
var $ZodSuccess2 = /* @__PURE__ */ $constructor2("$ZodSuccess", (inst, def) => {
  $ZodType2.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      throw new $ZodEncodeError2("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 $ZodCatch2 = /* @__PURE__ */ $constructor2("$ZodCatch", (inst, def) => {
  $ZodType2.init(inst, def);
  inst._zod.optin = "optional";
  defineLazy2(inst._zod, "optout", () => def.innerType._zod.optout);
  defineLazy2(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) => finalizeIssue2(iss, ctx, config2()))
            },
            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) => finalizeIssue2(iss, ctx, config2()))
        },
        input: payload.value
      });
      payload.issues = [];
      payload.fallback = true;
    }
    return payload;
  };
});
var $ZodNaN2 = /* @__PURE__ */ $constructor2("$ZodNaN", (inst, def) => {
  $ZodType2.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 $ZodPipe2 = /* @__PURE__ */ $constructor2("$ZodPipe", (inst, def) => {
  $ZodType2.init(inst, def);
  defineLazy2(inst._zod, "values", () => def.in._zod.values);
  defineLazy2(inst._zod, "optin", () => def.in._zod.optin);
  defineLazy2(inst._zod, "optout", () => def.out._zod.optout);
  defineLazy2(inst._zod, "propValues", () => def.in._zod.propValues);
  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      const right = def.out._zod.run(payload, ctx);
      if (right instanceof Promise) {
        return right.then((right2) => handlePipeResult2(right2, def.in, ctx));
      }
      return handlePipeResult2(right, def.in, ctx);
    }
    const left = def.in._zod.run(payload, ctx);
    if (left instanceof Promise) {
      return left.then((left2) => handlePipeResult2(left2, def.out, ctx));
    }
    return handlePipeResult2(left, def.out, ctx);
  };
});
function handlePipeResult2(left, next, ctx) {
  if (left.issues.length) {
    left.aborted = true;
    return left;
  }
  return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx);
}
var $ZodCodec2 = /* @__PURE__ */ $constructor2("$ZodCodec", (inst, def) => {
  $ZodType2.init(inst, def);
  defineLazy2(inst._zod, "values", () => def.in._zod.values);
  defineLazy2(inst._zod, "optin", () => def.in._zod.optin);
  defineLazy2(inst._zod, "optout", () => def.out._zod.optout);
  defineLazy2(inst._zod, "propValues", () => def.in._zod.propValues);
  inst._zod.parse = (payload, ctx) => {
    const direction = ctx.direction || "forward";
    if (direction === "forward") {
      const left = def.in._zod.run(payload, ctx);
      if (left instanceof Promise) {
        return left.then((left2) => handleCodecAResult2(left2, def, ctx));
      }
      return handleCodecAResult2(left, def, ctx);
    } else {
      const right = def.out._zod.run(payload, ctx);
      if (right instanceof Promise) {
        return right.then((right2) => handleCodecAResult2(right2, def, ctx));
      }
      return handleCodecAResult2(right, def, ctx);
    }
  };
});
function handleCodecAResult2(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) => handleCodecTxResult2(result, value, def.out, ctx));
    }
    return handleCodecTxResult2(result, transformed, def.out, ctx);
  } else {
    const transformed = def.reverseTransform(result.value, result);
    if (transformed instanceof Promise) {
      return transformed.then((value) => handleCodecTxResult2(result, value, def.in, ctx));
    }
    return handleCodecTxResult2(result, transformed, def.in, ctx);
  }
}
function handleCodecTxResult2(left, value, nextSchema, ctx) {
  if (left.issues.length) {
    left.aborted = true;
    return left;
  }
  return nextSchema._zod.run({ value, issues: left.issues }, ctx);
}
var $ZodPreprocess2 = /* @__PURE__ */ $constructor2("$ZodPreprocess", (inst, def) => {
  $ZodPipe2.init(inst, def);
});
var $ZodReadonly2 = /* @__PURE__ */ $constructor2("$ZodReadonly", (inst, def) => {
  $ZodType2.init(inst, def);
  defineLazy2(inst._zod, "propValues", () => def.innerType._zod.propValues);
  defineLazy2(inst._zod, "values", () => def.innerType._zod.values);
  defineLazy2(inst._zod, "optin", () => def.innerType?._zod?.optin);
  defineLazy2(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(handleReadonlyResult2);
    }
    return handleReadonlyResult2(result);
  };
});
function handleReadonlyResult2(payload) {
  payload.value = Object.freeze(payload.value);
  return payload;
}
var $ZodTemplateLiteral2 = /* @__PURE__ */ $constructor2("$ZodTemplateLiteral", (inst, def) => {
  $ZodType2.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 || primitiveTypes2.has(typeof part)) {
      regexParts.push(escapeRegex2(`${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 $ZodFunction2 = /* @__PURE__ */ $constructor2("$ZodFunction", (inst, def) => {
  $ZodType2.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 ? parse5(inst._def.input, args) : args;
      const result = Reflect.apply(func, this, parsedArgs);
      if (inst._def.output) {
        return parse5(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 parseAsync3(inst._def.input, args) : args;
      const result = await Reflect.apply(func, this, parsedArgs);
      if (inst._def.output) {
        return await parseAsync3(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 $ZodTuple2({
          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 $ZodPromise2 = /* @__PURE__ */ $constructor2("$ZodPromise", (inst, def) => {
  $ZodType2.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));
  };
});
var $ZodLazy2 = /* @__PURE__ */ $constructor2("$ZodLazy", (inst, def) => {
  $ZodType2.init(inst, def);
  defineLazy2(inst._zod, "innerType", () => {
    const d = def;
    if (!d._cachedInner)
      d._cachedInner = def.getter();
    return d._cachedInner;
  });
  defineLazy2(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern);
  defineLazy2(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues);
  defineLazy2(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? void 0);
  defineLazy2(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 $ZodCustom2 = /* @__PURE__ */ $constructor2("$ZodCustom", (inst, def) => {
  $ZodCheck2.init(inst, def);
  $ZodType2.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) => handleRefineResult2(r2, payload, input, inst));
    }
    handleRefineResult2(r, payload, input, inst);
    return;
  };
});
function handleRefineResult2(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(issue2(_iss));
  }
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/index.js
var locales_exports2 = {};
__export(locales_exports2, {
  ar: () => ar_default2,
  az: () => az_default2,
  be: () => be_default2,
  bg: () => bg_default2,
  ca: () => ca_default2,
  cs: () => cs_default2,
  da: () => da_default2,
  de: () => de_default2,
  el: () => el_default2,
  en: () => en_default2,
  eo: () => eo_default2,
  es: () => es_default2,
  fa: () => fa_default2,
  fi: () => fi_default2,
  fr: () => fr_default2,
  frCA: () => fr_CA_default2,
  he: () => he_default2,
  hr: () => hr_default2,
  hu: () => hu_default2,
  hy: () => hy_default2,
  id: () => id_default2,
  is: () => is_default2,
  it: () => it_default2,
  ja: () => ja_default2,
  ka: () => ka_default2,
  kh: () => kh_default2,
  km: () => km_default2,
  ko: () => ko_default2,
  lt: () => lt_default2,
  mk: () => mk_default2,
  ms: () => ms_default2,
  nl: () => nl_default2,
  no: () => no_default2,
  ota: () => ota_default2,
  pl: () => pl_default2,
  ps: () => ps_default2,
  pt: () => pt_default2,
  ro: () => ro_default2,
  ru: () => ru_default2,
  sl: () => sl_default2,
  sv: () => sv_default2,
  ta: () => ta_default2,
  th: () => th_default2,
  tr: () => tr_default2,
  ua: () => ua_default2,
  uk: () => uk_default2,
  ur: () => ur_default2,
  uz: () => uz_default2,
  vi: () => vi_default2,
  yo: () => yo_default2,
  zhCN: () => zh_CN_default2,
  zhTW: () => zh_TW_default2
});

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ar.js
var error51 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.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 ${issue3.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 (issue3.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 ${stringifyPrimitive2(issue3.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: ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.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 ${issue3.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue3.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 ${issue3.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue3.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue3.minimum.toString()} ${sizing.unit}`;
        }
        return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue3.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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 "${issue3.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] ?? issue3.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 ${issue3.divisor}`;
      case "unrecognized_keys":
        return `\u0645\u0639\u0631\u0641${issue3.keys.length > 1 ? "\u0627\u062A" : ""} \u063A\u0631\u064A\u0628${issue3.keys.length > 1 ? "\u0629" : ""}: ${joinValues2(issue3.keys, "\u060C ")}`;
      case "invalid_key":
        return `\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue3.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 ${issue3.origin}`;
      default:
        return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";
    }
  };
};
function ar_default2() {
  return {
    localeError: error51()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/az.js
var error52 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n instanceof ${issue3.expected}, daxil olan ${received}`;
        }
        return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${expected}, daxil olan ${received}`;
      }
      case "invalid_value":
        if (issue3.values.length === 1)
          return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${stringifyPrimitive2(issue3.values[0])}`;
        return `Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue3.origin ?? "d\u0259y\u0259r"} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "element"}`;
        return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue3.origin ?? "d\u0259y\u0259r"} ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit}`;
        return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue3.origin} ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format}`;
      }
      case "not_multiple_of":
        return `Yanl\u0131\u015F \u0259d\u0259d: ${issue3.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;
      case "unrecognized_keys":
        return `Tan\u0131nmayan a\xE7ar${issue3.keys.length > 1 ? "lar" : ""}: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `${issue3.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;
      case "invalid_union":
        return "Yanl\u0131\u015F d\u0259y\u0259r";
      case "invalid_element":
        return `${issue3.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;
      default:
        return `Yanl\u0131\u015F d\u0259y\u0259r`;
    }
  };
};
function az_default2() {
  return {
    localeError: error52()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/be.js
function getBelarusianPlural2(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;
}
var error53 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.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 ${issue3.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 (issue3.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 ${stringifyPrimitive2(issue3.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 ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          const maxValue = Number(issue3.maximum);
          const unit = getBelarusianPlural2(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 ${issue3.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue3.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 ${issue3.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          const minValue = Number(issue3.minimum);
          const unit = getBelarusianPlural2(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 ${issue3.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue3.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 ${issue3.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.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 ${issue3.divisor}`;
      case "unrecognized_keys":
        return `\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${issue3.keys.length > 1 ? "\u043A\u043B\u044E\u0447\u044B" : "\u043A\u043B\u044E\u0447"}: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${issue3.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 ${issue3.origin}`;
      default:
        return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434`;
    }
  };
};
function be_default2() {
  return {
    localeError: error53()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/bg.js
var error54 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${issue3.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 (issue3.values.length === 1)
          return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${stringifyPrimitive2(issue3.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 ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue3.origin ?? "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue3.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 ${issue3.origin ?? "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue3.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue3.minimum.toString()} ${sizing.unit}`;
        }
        return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue3.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.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 ${issue3.divisor}`;
      case "unrecognized_keys":
        return `\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${issue3.keys.length > 1 ? "\u0438" : ""} \u043A\u043B\u044E\u0447${issue3.keys.length > 1 ? "\u043E\u0432\u0435" : ""}: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${issue3.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 ${issue3.origin}`;
      default:
        return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434`;
    }
  };
};
function bg_default2() {
  return {
    localeError: error54()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ca.js
var error55 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `Tipus inv\xE0lid: s'esperava instanceof ${issue3.expected}, s'ha rebut ${received}`;
        }
        return `Tipus inv\xE0lid: s'esperava ${expected}, s'ha rebut ${received}`;
      }
      case "invalid_value":
        if (issue3.values.length === 1)
          return `Valor inv\xE0lid: s'esperava ${stringifyPrimitive2(issue3.values[0])}`;
        return `Opci\xF3 inv\xE0lida: s'esperava una de ${joinValues2(issue3.values, " o ")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "com a m\xE0xim" : "menys de";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `Massa gran: s'esperava que ${issue3.origin ?? "el valor"} contingu\xE9s ${adj} ${issue3.maximum.toString()} ${sizing.unit ?? "elements"}`;
        return `Massa gran: s'esperava que ${issue3.origin ?? "el valor"} fos ${adj} ${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? "com a m\xEDnim" : "m\xE9s de";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `Massa petit: s'esperava que ${issue3.origin} contingu\xE9s ${adj} ${issue3.minimum.toString()} ${sizing.unit}`;
        }
        return `Massa petit: s'esperava que ${issue3.origin} fos ${adj} ${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format}`;
      }
      case "not_multiple_of":
        return `N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${issue3.divisor}`;
      case "unrecognized_keys":
        return `Clau${issue3.keys.length > 1 ? "s" : ""} no reconeguda${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `Clau inv\xE0lida a ${issue3.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 ${issue3.origin}`;
      default:
        return `Entrada inv\xE0lida`;
    }
  };
};
function ca_default2() {
  return {
    localeError: error55()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/cs.js
var error56 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no instanceof ${issue3.expected}, obdr\u017Eeno ${received}`;
        }
        return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${expected}, obdr\u017Eeno ${received}`;
      }
      case "invalid_value":
        if (issue3.values.length === 1)
          return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${stringifyPrimitive2(issue3.values[0])}`;
        return `Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue3.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "prvk\u016F"}`;
        }
        return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue3.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue3.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue3.minimum.toString()} ${sizing.unit ?? "prvk\u016F"}`;
        }
        return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue3.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format}`;
      }
      case "not_multiple_of":
        return `Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${issue3.divisor}`;
      case "unrecognized_keys":
        return `Nezn\xE1m\xE9 kl\xED\u010De: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `Neplatn\xFD kl\xED\u010D v ${issue3.origin}`;
      case "invalid_union":
        return "Neplatn\xFD vstup";
      case "invalid_element":
        return `Neplatn\xE1 hodnota v ${issue3.origin}`;
      default:
        return `Neplatn\xFD vstup`;
    }
  };
};
function cs_default2() {
  return {
    localeError: error56()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/da.js
var error57 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `Ugyldigt input: forventede instanceof ${issue3.expected}, fik ${received}`;
        }
        return `Ugyldigt input: forventede ${expected}, fik ${received}`;
      }
      case "invalid_value":
        if (issue3.values.length === 1)
          return `Ugyldig v\xE6rdi: forventede ${stringifyPrimitive2(issue3.values[0])}`;
        return `Ugyldigt valg: forventede en af f\xF8lgende ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        const origin = TypeDictionary[issue3.origin] ?? issue3.origin;
        if (sizing)
          return `For stor: forventede ${origin ?? "value"} ${sizing.verb} ${adj} ${issue3.maximum.toString()} ${sizing.unit ?? "elementer"}`;
        return `For stor: forventede ${origin ?? "value"} havde ${adj} ${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        const origin = TypeDictionary[issue3.origin] ?? issue3.origin;
        if (sizing) {
          return `For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue3.minimum.toString()} ${sizing.unit}`;
        }
        return `For lille: forventede ${origin} havde ${adj} ${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format}`;
      }
      case "not_multiple_of":
        return `Ugyldigt tal: skal v\xE6re deleligt med ${issue3.divisor}`;
      case "unrecognized_keys":
        return `${issue3.keys.length > 1 ? "Ukendte n\xF8gler" : "Ukendt n\xF8gle"}: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `Ugyldig n\xF8gle i ${issue3.origin}`;
      case "invalid_union":
        return "Ugyldigt input: matcher ingen af de tilladte typer";
      case "invalid_element":
        return `Ugyldig v\xE6rdi i ${issue3.origin}`;
      default:
        return `Ugyldigt input`;
    }
  };
};
function da_default2() {
  return {
    localeError: error57()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/de.js
var error58 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `Ung\xFCltige Eingabe: erwartet instanceof ${issue3.expected}, erhalten ${received}`;
        }
        return `Ung\xFCltige Eingabe: erwartet ${expected}, erhalten ${received}`;
      }
      case "invalid_value":
        if (issue3.values.length === 1)
          return `Ung\xFCltige Eingabe: erwartet ${stringifyPrimitive2(issue3.values[0])}`;
        return `Ung\xFCltige Option: erwartet eine von ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `Zu gro\xDF: erwartet, dass ${issue3.origin ?? "Wert"} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "Elemente"} hat`;
        return `Zu gro\xDF: erwartet, dass ${issue3.origin ?? "Wert"} ${adj}${issue3.maximum.toString()} ist`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `Zu klein: erwartet, dass ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit} hat`;
        }
        return `Zu klein: erwartet, dass ${issue3.origin} ${adj}${issue3.minimum.toString()} ist`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format}`;
      }
      case "not_multiple_of":
        return `Ung\xFCltige Zahl: muss ein Vielfaches von ${issue3.divisor} sein`;
      case "unrecognized_keys":
        return `${issue3.keys.length > 1 ? "Unbekannte Schl\xFCssel" : "Unbekannter Schl\xFCssel"}: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `Ung\xFCltiger Schl\xFCssel in ${issue3.origin}`;
      case "invalid_union":
        return "Ung\xFCltige Eingabe";
      case "invalid_element":
        return `Ung\xFCltiger Wert in ${issue3.origin}`;
      default:
        return `Ung\xFCltige Eingabe`;
    }
  };
};
function de_default2() {
  return {
    localeError: error58()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/el.js
var error59 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (typeof issue3.expected === "string" && /^[A-Z]/.test(issue3.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 ${issue3.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 (issue3.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 ${stringifyPrimitive2(issue3.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 ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue3.origin ?? "\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${adj}${issue3.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 ${issue3.origin ?? "\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue3.origin} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${adj}${issue3.minimum.toString()} ${sizing.unit}`;
        }
        return `\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${issue3.origin} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.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 ${issue3.divisor}`;
      case "unrecognized_keys":
        return `\u0386\u03B3\u03BD\u03C9\u03C3\u03C4${issue3.keys.length > 1 ? "\u03B1" : "\u03BF"} \u03BA\u03BB\u03B5\u03B9\u03B4${issue3.keys.length > 1 ? "\u03B9\u03AC" : "\u03AF"}: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF \u03BA\u03BB\u03B5\u03B9\u03B4\u03AF \u03C3\u03C4\u03BF ${issue3.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 ${issue3.origin}`;
      default:
        return `\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2`;
    }
  };
};
function el_default2() {
  return {
    localeError: error59()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/en.js
var error60 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        return `Invalid input: expected ${expected}, received ${received}`;
      }
      case "invalid_value":
        if (issue3.values.length === 1)
          return `Invalid input: expected ${stringifyPrimitive2(issue3.values[0])}`;
        return `Invalid option: expected one of ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `Too big: expected ${issue3.origin ?? "value"} to have ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elements"}`;
        return `Too big: expected ${issue3.origin ?? "value"} to be ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `Too small: expected ${issue3.origin} to have ${adj}${issue3.minimum.toString()} ${sizing.unit}`;
        }
        return `Too small: expected ${issue3.origin} to be ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format}`;
      }
      case "not_multiple_of":
        return `Invalid number: must be a multiple of ${issue3.divisor}`;
      case "unrecognized_keys":
        return `Unrecognized key${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `Invalid key in ${issue3.origin}`;
      case "invalid_union":
        if (issue3.options && Array.isArray(issue3.options) && issue3.options.length > 0) {
          const opts = issue3.options.map((o) => `'${o}'`).join(" | ");
          return `Invalid discriminator value. Expected ${opts}`;
        }
        return "Invalid input";
      case "invalid_element":
        return `Invalid value in ${issue3.origin}`;
      default:
        return `Invalid input`;
    }
  };
};
function en_default2() {
  return {
    localeError: error60()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/eo.js
var error61 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `Nevalida enigo: atendi\u011Dis instanceof ${issue3.expected}, ricevi\u011Dis ${received}`;
        }
        return `Nevalida enigo: atendi\u011Dis ${expected}, ricevi\u011Dis ${received}`;
      }
      case "invalid_value":
        if (issue3.values.length === 1)
          return `Nevalida enigo: atendi\u011Dis ${stringifyPrimitive2(issue3.values[0])}`;
        return `Nevalida opcio: atendi\u011Dis unu el ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `Tro granda: atendi\u011Dis ke ${issue3.origin ?? "valoro"} havu ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementojn"}`;
        return `Tro granda: atendi\u011Dis ke ${issue3.origin ?? "valoro"} havu ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `Tro malgranda: atendi\u011Dis ke ${issue3.origin} havu ${adj}${issue3.minimum.toString()} ${sizing.unit}`;
        }
        return `Tro malgranda: atendi\u011Dis ke ${issue3.origin} estu ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format}`;
      }
      case "not_multiple_of":
        return `Nevalida nombro: devas esti oblo de ${issue3.divisor}`;
      case "unrecognized_keys":
        return `Nekonata${issue3.keys.length > 1 ? "j" : ""} \u015Dlosilo${issue3.keys.length > 1 ? "j" : ""}: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `Nevalida \u015Dlosilo en ${issue3.origin}`;
      case "invalid_union":
        return "Nevalida enigo";
      case "invalid_element":
        return `Nevalida valoro en ${issue3.origin}`;
      default:
        return `Nevalida enigo`;
    }
  };
};
function eo_default2() {
  return {
    localeError: error61()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/es.js
var error62 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `Entrada inv\xE1lida: se esperaba instanceof ${issue3.expected}, recibido ${received}`;
        }
        return `Entrada inv\xE1lida: se esperaba ${expected}, recibido ${received}`;
      }
      case "invalid_value":
        if (issue3.values.length === 1)
          return `Entrada inv\xE1lida: se esperaba ${stringifyPrimitive2(issue3.values[0])}`;
        return `Opci\xF3n inv\xE1lida: se esperaba una de ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        const origin = TypeDictionary[issue3.origin] ?? issue3.origin;
        if (sizing)
          return `Demasiado grande: se esperaba que ${origin ?? "valor"} tuviera ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementos"}`;
        return `Demasiado grande: se esperaba que ${origin ?? "valor"} fuera ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        const origin = TypeDictionary[issue3.origin] ?? issue3.origin;
        if (sizing) {
          return `Demasiado peque\xF1o: se esperaba que ${origin} tuviera ${adj}${issue3.minimum.toString()} ${sizing.unit}`;
        }
        return `Demasiado peque\xF1o: se esperaba que ${origin} fuera ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format}`;
      }
      case "not_multiple_of":
        return `N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${issue3.divisor}`;
      case "unrecognized_keys":
        return `Llave${issue3.keys.length > 1 ? "s" : ""} desconocida${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `Llave inv\xE1lida en ${TypeDictionary[issue3.origin] ?? issue3.origin}`;
      case "invalid_union":
        return "Entrada inv\xE1lida";
      case "invalid_element":
        return `Valor inv\xE1lido en ${TypeDictionary[issue3.origin] ?? issue3.origin}`;
      default:
        return `Entrada inv\xE1lida`;
    }
  };
};
function es_default2() {
  return {
    localeError: error62()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fa.js
var error63 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${issue3.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 (issue3.values.length === 1) {
          return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${stringifyPrimitive2(issue3.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 ${joinValues2(issue3.values, "|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue3.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`;
        }
        return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue3.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue3.maximum.toString()} \u0628\u0627\u0634\u062F`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue3.origin} \u0628\u0627\u06CC\u062F ${adj}${issue3.minimum.toString()} ${sizing.unit} \u0628\u0627\u0634\u062F`;
        }
        return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue3.origin} \u0628\u0627\u06CC\u062F ${adj}${issue3.minimum.toString()} \u0628\u0627\u0634\u062F`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.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 ${issue3.divisor} \u0628\u0627\u0634\u062F`;
      case "unrecognized_keys":
        return `\u06A9\u0644\u06CC\u062F${issue3.keys.length > 1 ? "\u0647\u0627\u06CC" : ""} \u0646\u0627\u0634\u0646\u0627\u0633: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${issue3.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 ${issue3.origin}`;
      default:
        return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`;
    }
  };
};
function fa_default2() {
  return {
    localeError: error63()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fi.js
var error64 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `Virheellinen tyyppi: odotettiin instanceof ${issue3.expected}, oli ${received}`;
        }
        return `Virheellinen tyyppi: odotettiin ${expected}, oli ${received}`;
      }
      case "invalid_value":
        if (issue3.values.length === 1)
          return `Virheellinen sy\xF6te: t\xE4ytyy olla ${stringifyPrimitive2(issue3.values[0])}`;
        return `Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `Liian suuri: ${sizing.subject} t\xE4ytyy olla ${adj}${issue3.maximum.toString()} ${sizing.unit}`.trim();
        }
        return `Liian suuri: arvon t\xE4ytyy olla ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `Liian pieni: ${sizing.subject} t\xE4ytyy olla ${adj}${issue3.minimum.toString()} ${sizing.unit}`.trim();
        }
        return `Liian pieni: arvon t\xE4ytyy olla ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format}`;
      }
      case "not_multiple_of":
        return `Virheellinen luku: t\xE4ytyy olla luvun ${issue3.divisor} monikerta`;
      case "unrecognized_keys":
        return `${issue3.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${joinValues2(issue3.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`;
    }
  };
};
function fi_default2() {
  return {
    localeError: error64()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fr.js
var error65 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `Entr\xE9e invalide : instanceof ${issue3.expected} attendu, ${received} re\xE7u`;
        }
        return `Entr\xE9e invalide : ${expected} attendu, ${received} re\xE7u`;
      }
      case "invalid_value":
        if (issue3.values.length === 1)
          return `Entr\xE9e invalide : ${stringifyPrimitive2(issue3.values[0])} attendu`;
        return `Option invalide : une valeur parmi ${joinValues2(issue3.values, "|")} attendue`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `Trop grand : ${TypeDictionary[issue3.origin] ?? "valeur"} doit ${sizing.verb} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "\xE9l\xE9ment(s)"}`;
        return `Trop grand : ${TypeDictionary[issue3.origin] ?? "valeur"} doit \xEAtre ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `Trop petit : ${TypeDictionary[issue3.origin] ?? "valeur"} doit ${sizing.verb} ${adj}${issue3.minimum.toString()} ${sizing.unit}`;
        return `Trop petit : ${TypeDictionary[issue3.origin] ?? "valeur"} doit \xEAtre ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format} invalide`;
      }
      case "not_multiple_of":
        return `Nombre invalide : doit \xEAtre un multiple de ${issue3.divisor}`;
      case "unrecognized_keys":
        return `Cl\xE9${issue3.keys.length > 1 ? "s" : ""} non reconnue${issue3.keys.length > 1 ? "s" : ""} : ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `Cl\xE9 invalide dans ${issue3.origin}`;
      case "invalid_union":
        return "Entr\xE9e invalide";
      case "invalid_element":
        return `Valeur invalide dans ${issue3.origin}`;
      default:
        return `Entr\xE9e invalide`;
    }
  };
};
function fr_default2() {
  return {
    localeError: error65()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/fr-CA.js
var error66 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `Entr\xE9e invalide : attendu instanceof ${issue3.expected}, re\xE7u ${received}`;
        }
        return `Entr\xE9e invalide : attendu ${expected}, re\xE7u ${received}`;
      }
      case "invalid_value":
        if (issue3.values.length === 1)
          return `Entr\xE9e invalide : attendu ${stringifyPrimitive2(issue3.values[0])}`;
        return `Option invalide : attendu l'une des valeurs suivantes ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "\u2264" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `Trop grand : attendu que ${issue3.origin ?? "la valeur"} ait ${adj}${issue3.maximum.toString()} ${sizing.unit}`;
        return `Trop grand : attendu que ${issue3.origin ?? "la valeur"} soit ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? "\u2265" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `Trop petit : attendu que ${issue3.origin} ait ${adj}${issue3.minimum.toString()} ${sizing.unit}`;
        }
        return `Trop petit : attendu que ${issue3.origin} soit ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format} invalide`;
      }
      case "not_multiple_of":
        return `Nombre invalide : doit \xEAtre un multiple de ${issue3.divisor}`;
      case "unrecognized_keys":
        return `Cl\xE9${issue3.keys.length > 1 ? "s" : ""} non reconnue${issue3.keys.length > 1 ? "s" : ""} : ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `Cl\xE9 invalide dans ${issue3.origin}`;
      case "invalid_union":
        return "Entr\xE9e invalide";
      case "invalid_element":
        return `Valeur invalide dans ${issue3.origin}`;
      default:
        return `Entr\xE9e invalide`;
    }
  };
};
function fr_CA_default2() {
  return {
    localeError: error66()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/he.js
var error67 = () => {
  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 = (t) => t ? TypeNames[t] : void 0;
  const typeLabel = (t) => {
    const e = typeEntry(t);
    if (e)
      return e.label;
    return t ?? TypeNames.unknown.label;
  };
  const withDefinite = (t) => `\u05D4${typeLabel(t)}`;
  const verbFor = (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";
  };
  const getSizing = (origin) => {
    if (!origin)
      return null;
    return Sizable[origin] ?? null;
  };
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expectedKey = issue3.expected;
        const expected = TypeDictionary[expectedKey ?? ""] ?? typeLabel(expectedKey);
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? TypeNames[receivedType]?.label ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${issue3.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 (issue3.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 ${stringifyPrimitive2(issue3.values[0])}`;
        }
        const stringified = issue3.values.map((v) => stringifyPrimitive2(v));
        if (issue3.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(issue3.origin);
        const subject = withDefinite(issue3.origin ?? "value");
        if (issue3.origin === "string") {
          return `${sizing?.longLabel ?? "\u05D0\u05E8\u05D5\u05DA"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue3.maximum.toString()} ${sizing?.unit ?? ""} ${issue3.inclusive ? "\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA" : "\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8"}`.trim();
        }
        if (issue3.origin === "number") {
          const comparison = issue3.inclusive ? `\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue3.maximum}` : `\u05E7\u05D8\u05DF \u05DE-${issue3.maximum}`;
          return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`;
        }
        if (issue3.origin === "array" || issue3.origin === "set") {
          const verb = issue3.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA";
          const comparison = issue3.inclusive ? `${issue3.maximum} ${sizing?.unit ?? ""} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA` : `\u05E4\u05D7\u05D5\u05EA \u05DE-${issue3.maximum} ${sizing?.unit ?? ""}`;
          return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim();
        }
        const adj = issue3.inclusive ? "<=" : "<";
        const be = verbFor(issue3.origin ?? "value");
        if (sizing?.unit) {
          return `${sizing.longLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue3.maximum.toString()} ${sizing.unit}`;
        }
        return `${sizing?.longLabel ?? "\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const sizing = getSizing(issue3.origin);
        const subject = withDefinite(issue3.origin ?? "value");
        if (issue3.origin === "string") {
          return `${sizing?.shortLabel ?? "\u05E7\u05E6\u05E8"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue3.minimum.toString()} ${sizing?.unit ?? ""} ${issue3.inclusive ? "\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8" : "\u05DC\u05E4\u05D7\u05D5\u05EA"}`.trim();
        }
        if (issue3.origin === "number") {
          const comparison = issue3.inclusive ? `\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue3.minimum}` : `\u05D2\u05D3\u05D5\u05DC \u05DE-${issue3.minimum}`;
          return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`;
        }
        if (issue3.origin === "array" || issue3.origin === "set") {
          const verb = issue3.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA";
          if (issue3.minimum === 1 && issue3.inclusive) {
            const singularPhrase = issue3.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 = issue3.inclusive ? `${issue3.minimum} ${sizing?.unit ?? ""} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8` : `\u05D9\u05D5\u05EA\u05E8 \u05DE-${issue3.minimum} ${sizing?.unit ?? ""}`;
          return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim();
        }
        const adj = issue3.inclusive ? ">=" : ">";
        const be = verbFor(issue3.origin ?? "value");
        if (sizing?.unit) {
          return `${sizing.shortLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue3.minimum.toString()} ${sizing.unit}`;
        }
        return `${sizing?.shortLabel ?? "\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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 ${issue3.divisor}`;
      case "unrecognized_keys":
        return `\u05DE\u05E4\u05EA\u05D7${issue3.keys.length > 1 ? "\u05D5\u05EA" : ""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${issue3.keys.length > 1 ? "\u05D9\u05DD" : "\u05D4"}: ${joinValues2(issue3.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(issue3.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`;
    }
  };
};
function he_default2() {
  return {
    localeError: error67()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hr.js
var error68 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `Neispravan unos: o\u010Dekuje se instanceof ${issue3.expected}, a primljeno je ${received}`;
        }
        return `Neispravan unos: o\u010Dekuje se ${expected}, a primljeno je ${received}`;
      }
      case "invalid_value":
        if (issue3.values.length === 1)
          return `Neispravna vrijednost: o\u010Dekivano ${stringifyPrimitive2(issue3.values[0])}`;
        return `Neispravna opcija: o\u010Dekivano jedno od ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        const origin = TypeDictionary[issue3.origin] ?? issue3.origin;
        if (sizing)
          return `Preveliko: o\u010Dekivano da ${origin ?? "vrijednost"} ima ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elemenata"}`;
        return `Preveliko: o\u010Dekivano da ${origin ?? "vrijednost"} bude ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        const origin = TypeDictionary[issue3.origin] ?? issue3.origin;
        if (sizing) {
          return `Premalo: o\u010Dekivano da ${origin} ima ${adj}${issue3.minimum.toString()} ${sizing.unit}`;
        }
        return `Premalo: o\u010Dekivano da ${origin} bude ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format}`;
      }
      case "not_multiple_of":
        return `Neispravan broj: mora biti vi\u0161ekratnik od ${issue3.divisor}`;
      case "unrecognized_keys":
        return `Neprepoznat${issue3.keys.length > 1 ? "i klju\u010Devi" : " klju\u010D"}: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `Neispravan klju\u010D u ${TypeDictionary[issue3.origin] ?? issue3.origin}`;
      case "invalid_union":
        return "Neispravan unos";
      case "invalid_element":
        return `Neispravna vrijednost u ${TypeDictionary[issue3.origin] ?? issue3.origin}`;
      default:
        return `Neispravan unos`;
    }
  };
};
function hr_default2() {
  return {
    localeError: error68()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hu.js
var error69 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k instanceof ${issue3.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 (issue3.values.length === 1)
          return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${stringifyPrimitive2(issue3.values[0])}`;
        return `\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `T\xFAl nagy: ${issue3.origin ?? "\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elem"}`;
        return `T\xFAl nagy: a bemeneti \xE9rt\xE9k ${issue3.origin ?? "\xE9rt\xE9k"} t\xFAl nagy: ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue3.origin} m\xE9rete t\xFAl kicsi ${adj}${issue3.minimum.toString()} ${sizing.unit}`;
        }
        return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue3.origin} t\xFAl kicsi ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format}`;
      }
      case "not_multiple_of":
        return `\xC9rv\xE9nytelen sz\xE1m: ${issue3.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;
      case "unrecognized_keys":
        return `Ismeretlen kulcs${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `\xC9rv\xE9nytelen kulcs ${issue3.origin}`;
      case "invalid_union":
        return "\xC9rv\xE9nytelen bemenet";
      case "invalid_element":
        return `\xC9rv\xE9nytelen \xE9rt\xE9k: ${issue3.origin}`;
      default:
        return `\xC9rv\xE9nytelen bemenet`;
    }
  };
};
function hu_default2() {
  return {
    localeError: error69()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/hy.js
function getArmenianPlural2(count, one, many) {
  return Math.abs(count) === 1 ? one : many;
}
function withDefiniteArticle2(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");
}
var error70 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.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 ${issue3.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 (issue3.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 ${stringifyPrimitive2(issue3.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 ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          const maxValue = Number(issue3.maximum);
          const unit = getArmenianPlural2(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 ${withDefiniteArticle2(issue3.origin ?? "\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue3.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 ${withDefiniteArticle2(issue3.origin ?? "\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          const minValue = Number(issue3.minimum);
          const unit = getArmenianPlural2(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 ${withDefiniteArticle2(issue3.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue3.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 ${withDefiniteArticle2(issue3.origin)} \u056C\u056B\u0576\u056B ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.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 ${issue3.divisor}-\u056B`;
      case "unrecognized_keys":
        return `\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${issue3.keys.length > 1 ? "\u0576\u0565\u0580" : ""}. ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${withDefiniteArticle2(issue3.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 ${withDefiniteArticle2(issue3.origin)}-\u0578\u0582\u0574`;
      default:
        return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574`;
    }
  };
};
function hy_default2() {
  return {
    localeError: error70()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/id.js
var error71 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `Input tidak valid: diharapkan instanceof ${issue3.expected}, diterima ${received}`;
        }
        return `Input tidak valid: diharapkan ${expected}, diterima ${received}`;
      }
      case "invalid_value":
        if (issue3.values.length === 1)
          return `Input tidak valid: diharapkan ${stringifyPrimitive2(issue3.values[0])}`;
        return `Pilihan tidak valid: diharapkan salah satu dari ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `Terlalu besar: diharapkan ${issue3.origin ?? "value"} memiliki ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elemen"}`;
        return `Terlalu besar: diharapkan ${issue3.origin ?? "value"} menjadi ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `Terlalu kecil: diharapkan ${issue3.origin} memiliki ${adj}${issue3.minimum.toString()} ${sizing.unit}`;
        }
        return `Terlalu kecil: diharapkan ${issue3.origin} menjadi ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format} tidak valid`;
      }
      case "not_multiple_of":
        return `Angka tidak valid: harus kelipatan dari ${issue3.divisor}`;
      case "unrecognized_keys":
        return `Kunci tidak dikenali ${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `Kunci tidak valid di ${issue3.origin}`;
      case "invalid_union":
        return "Input tidak valid";
      case "invalid_element":
        return `Nilai tidak valid di ${issue3.origin}`;
      default:
        return `Input tidak valid`;
    }
  };
};
function id_default2() {
  return {
    localeError: error71()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/is.js
var error72 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera instanceof ${issue3.expected}`;
        }
        return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera ${expected}`;
      }
      case "invalid_value":
        if (issue3.values.length === 1)
          return `Rangt gildi: gert r\xE1\xF0 fyrir ${stringifyPrimitive2(issue3.values[0])}`;
        return `\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue3.origin ?? "gildi"} hafi ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "hluti"}`;
        return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${issue3.origin ?? "gildi"} s\xE9 ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue3.origin} hafi ${adj}${issue3.minimum.toString()} ${sizing.unit}`;
        }
        return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue3.origin} s\xE9 ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format}`;
      }
      case "not_multiple_of":
        return `R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${issue3.divisor}`;
      case "unrecognized_keys":
        return `\xD3\xFEekkt ${issue3.keys.length > 1 ? "ir lyklar" : "ur lykill"}: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `Rangur lykill \xED ${issue3.origin}`;
      case "invalid_union":
        return "Rangt gildi";
      case "invalid_element":
        return `Rangt gildi \xED ${issue3.origin}`;
      default:
        return `Rangt gildi`;
    }
  };
};
function is_default2() {
  return {
    localeError: error72()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/it.js
var error73 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `Input non valido: atteso instanceof ${issue3.expected}, ricevuto ${received}`;
        }
        return `Input non valido: atteso ${expected}, ricevuto ${received}`;
      }
      case "invalid_value":
        if (issue3.values.length === 1)
          return `Input non valido: atteso ${stringifyPrimitive2(issue3.values[0])}`;
        return `Opzione non valida: atteso uno tra ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `Troppo grande: ${issue3.origin ?? "valore"} deve avere ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementi"}`;
        return `Troppo grande: ${issue3.origin ?? "valore"} deve essere ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `Troppo piccolo: ${issue3.origin} deve avere ${adj}${issue3.minimum.toString()} ${sizing.unit}`;
        }
        return `Troppo piccolo: ${issue3.origin} deve essere ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format}`;
      }
      case "not_multiple_of":
        return `Numero non valido: deve essere un multiplo di ${issue3.divisor}`;
      case "unrecognized_keys":
        return `Chiav${issue3.keys.length > 1 ? "i" : "e"} non riconosciut${issue3.keys.length > 1 ? "e" : "a"}: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `Chiave non valida in ${issue3.origin}`;
      case "invalid_union":
        return "Input non valido";
      case "invalid_element":
        return `Valore non valido in ${issue3.origin}`;
      default:
        return `Input non valido`;
    }
  };
};
function it_default2() {
  return {
    localeError: error73()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ja.js
var error74 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `\u7121\u52B9\u306A\u5165\u529B: instanceof ${issue3.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 (issue3.values.length === 1)
          return `\u7121\u52B9\u306A\u5165\u529B: ${stringifyPrimitive2(issue3.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`;
        return `\u7121\u52B9\u306A\u9078\u629E: ${joinValues2(issue3.values, "\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
      case "too_big": {
        const adj = issue3.inclusive ? "\u4EE5\u4E0B\u3067\u3042\u308B" : "\u3088\u308A\u5C0F\u3055\u3044";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue3.origin ?? "\u5024"}\u306F${issue3.maximum.toString()}${sizing.unit ?? "\u8981\u7D20"}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
        return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue3.origin ?? "\u5024"}\u306F${issue3.maximum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? "\u4EE5\u4E0A\u3067\u3042\u308B" : "\u3088\u308A\u5927\u304D\u3044";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue3.origin}\u306F${issue3.minimum.toString()}${sizing.unit}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
        return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue3.origin}\u306F${issue3.minimum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format}`;
      }
      case "not_multiple_of":
        return `\u7121\u52B9\u306A\u6570\u5024: ${issue3.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${issue3.keys.length > 1 ? "\u7FA4" : ""}: ${joinValues2(issue3.keys, "\u3001")}`;
      case "invalid_key":
        return `${issue3.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;
      case "invalid_union":
        return "\u7121\u52B9\u306A\u5165\u529B";
      case "invalid_element":
        return `${issue3.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;
      default:
        return `\u7121\u52B9\u306A\u5165\u529B`;
    }
  };
};
function ja_default2() {
  return {
    localeError: error74()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ka.js
var error75 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.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 ${issue3.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 (issue3.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 ${stringifyPrimitive2(issue3.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 ${joinValues2(issue3.values, "|")}-\u10D3\u10D0\u10DC`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.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 ${issue3.origin ?? "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${sizing.verb} ${adj}${issue3.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 ${issue3.origin ?? "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.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 ${issue3.origin} ${sizing.verb} ${adj}${issue3.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 ${issue3.origin} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.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 ${issue3.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${issue3.keys.length > 1 ? "\u10D4\u10D1\u10D8" : "\u10D8"}: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${issue3.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 ${issue3.origin}-\u10E8\u10D8`;
      default:
        return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0`;
    }
  };
};
function ka_default2() {
  return {
    localeError: error75()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/km.js
var error76 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.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 ${issue3.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 (issue3.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 ${stringifyPrimitive2(issue3.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 ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue3.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue3.maximum.toString()} ${sizing.unit ?? "\u1792\u17B6\u178F\u17BB"}`;
        return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue3.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue3.origin} ${adj} ${issue3.minimum.toString()} ${sizing.unit}`;
        }
        return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue3.origin} ${adj} ${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.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 ${issue3.divisor}`;
      case "unrecognized_keys":
        return `\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${joinValues2(issue3.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 ${issue3.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 ${issue3.origin}`;
      default:
        return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`;
    }
  };
};
function km_default2() {
  return {
    localeError: error76()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/kh.js
function kh_default2() {
  return km_default2();
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ko.js
var error77 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${issue3.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 (issue3.values.length === 1)
          return `\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${stringifyPrimitive2(issue3.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`;
        return `\uC798\uBABB\uB41C \uC635\uC158: ${joinValues2(issue3.values, "\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;
      case "too_big": {
        const adj = issue3.inclusive ? "\uC774\uD558" : "\uBBF8\uB9CC";
        const suffix = adj === "\uBBF8\uB9CC" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4";
        const sizing = getSizing(issue3.origin);
        const unit = sizing?.unit ?? "\uC694\uC18C";
        if (sizing)
          return `${issue3.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue3.maximum.toString()}${unit} ${adj}${suffix}`;
        return `${issue3.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue3.maximum.toString()} ${adj}${suffix}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? "\uC774\uC0C1" : "\uCD08\uACFC";
        const suffix = adj === "\uC774\uC0C1" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4";
        const sizing = getSizing(issue3.origin);
        const unit = sizing?.unit ?? "\uC694\uC18C";
        if (sizing) {
          return `${issue3.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue3.minimum.toString()}${unit} ${adj}${suffix}`;
        }
        return `${issue3.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue3.minimum.toString()} ${adj}${suffix}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format}`;
      }
      case "not_multiple_of":
        return `\uC798\uBABB\uB41C \uC22B\uC790: ${issue3.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;
      case "unrecognized_keys":
        return `\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `\uC798\uBABB\uB41C \uD0A4: ${issue3.origin}`;
      case "invalid_union":
        return `\uC798\uBABB\uB41C \uC785\uB825`;
      case "invalid_element":
        return `\uC798\uBABB\uB41C \uAC12: ${issue3.origin}`;
      default:
        return `\uC798\uBABB\uB41C \uC785\uB825`;
    }
  };
};
function ko_default2() {
  return {
    localeError: error77()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/lt.js
var capitalizeFirstCharacter2 = (text) => {
  return text.charAt(0).toUpperCase() + text.slice(1);
};
function getUnitTypeFromNumber2(number7) {
  const abs = Math.abs(number7);
  const last = abs % 10;
  const last2 = abs % 100;
  if (last2 >= 11 && last2 <= 19 || last === 0)
    return "many";
  if (last === 1)
    return "one";
  return "few";
}
var error78 = () => {
  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"]
    };
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `Gautas tipas ${received}, o tik\u0117tasi - instanceof ${issue3.expected}`;
        }
        return `Gautas tipas ${received}, o tik\u0117tasi - ${expected}`;
      }
      case "invalid_value":
        if (issue3.values.length === 1)
          return `Privalo b\u016Bti ${stringifyPrimitive2(issue3.values[0])}`;
        return `Privalo b\u016Bti vienas i\u0161 ${joinValues2(issue3.values, "|")} pasirinkim\u0173`;
      case "too_big": {
        const origin = TypeDictionary[issue3.origin] ?? issue3.origin;
        const sizing = getSizing(issue3.origin, getUnitTypeFromNumber2(Number(issue3.maximum)), issue3.inclusive ?? false, "smaller");
        if (sizing?.verb)
          return `${capitalizeFirstCharacter2(origin ?? issue3.origin ?? "reik\u0161m\u0117")} ${sizing.verb} ${issue3.maximum.toString()} ${sizing.unit ?? "element\u0173"}`;
        const adj = issue3.inclusive ? "ne didesnis kaip" : "ma\u017Eesnis kaip";
        return `${capitalizeFirstCharacter2(origin ?? issue3.origin ?? "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue3.maximum.toString()} ${sizing?.unit}`;
      }
      case "too_small": {
        const origin = TypeDictionary[issue3.origin] ?? issue3.origin;
        const sizing = getSizing(issue3.origin, getUnitTypeFromNumber2(Number(issue3.minimum)), issue3.inclusive ?? false, "bigger");
        if (sizing?.verb)
          return `${capitalizeFirstCharacter2(origin ?? issue3.origin ?? "reik\u0161m\u0117")} ${sizing.verb} ${issue3.minimum.toString()} ${sizing.unit ?? "element\u0173"}`;
        const adj = issue3.inclusive ? "ne ma\u017Eesnis kaip" : "didesnis kaip";
        return `${capitalizeFirstCharacter2(origin ?? issue3.origin ?? "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue3.minimum.toString()} ${sizing?.unit}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format}`;
      }
      case "not_multiple_of":
        return `Skai\u010Dius privalo b\u016Bti ${issue3.divisor} kartotinis.`;
      case "unrecognized_keys":
        return `Neatpa\u017Eint${issue3.keys.length > 1 ? "i" : "as"} rakt${issue3.keys.length > 1 ? "ai" : "as"}: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return "Rastas klaidingas raktas";
      case "invalid_union":
        return "Klaidinga \u012Fvestis";
      case "invalid_element": {
        const origin = TypeDictionary[issue3.origin] ?? issue3.origin;
        return `${capitalizeFirstCharacter2(origin ?? issue3.origin ?? "reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`;
      }
      default:
        return "Klaidinga \u012Fvestis";
    }
  };
};
function lt_default2() {
  return {
    localeError: error78()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/mk.js
var error79 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${issue3.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 (issue3.values.length === 1)
          return `Invalid input: expected ${stringifyPrimitive2(issue3.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 ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.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 ${issue3.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue3.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 ${issue3.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue3.origin} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue3.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 ${issue3.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.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 ${issue3.divisor}`;
      case "unrecognized_keys":
        return `${issue3.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"}: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${issue3.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 ${issue3.origin}`;
      default:
        return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441`;
    }
  };
};
function mk_default2() {
  return {
    localeError: error79()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ms.js
var error80 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `Input tidak sah: dijangka instanceof ${issue3.expected}, diterima ${received}`;
        }
        return `Input tidak sah: dijangka ${expected}, diterima ${received}`;
      }
      case "invalid_value":
        if (issue3.values.length === 1)
          return `Input tidak sah: dijangka ${stringifyPrimitive2(issue3.values[0])}`;
        return `Pilihan tidak sah: dijangka salah satu daripada ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `Terlalu besar: dijangka ${issue3.origin ?? "nilai"} ${sizing.verb} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elemen"}`;
        return `Terlalu besar: dijangka ${issue3.origin ?? "nilai"} adalah ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `Terlalu kecil: dijangka ${issue3.origin} ${sizing.verb} ${adj}${issue3.minimum.toString()} ${sizing.unit}`;
        }
        return `Terlalu kecil: dijangka ${issue3.origin} adalah ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format} tidak sah`;
      }
      case "not_multiple_of":
        return `Nombor tidak sah: perlu gandaan ${issue3.divisor}`;
      case "unrecognized_keys":
        return `Kunci tidak dikenali: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `Kunci tidak sah dalam ${issue3.origin}`;
      case "invalid_union":
        return "Input tidak sah";
      case "invalid_element":
        return `Nilai tidak sah dalam ${issue3.origin}`;
      default:
        return `Input tidak sah`;
    }
  };
};
function ms_default2() {
  return {
    localeError: error80()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/nl.js
var error81 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `Ongeldige invoer: verwacht instanceof ${issue3.expected}, ontving ${received}`;
        }
        return `Ongeldige invoer: verwacht ${expected}, ontving ${received}`;
      }
      case "invalid_value":
        if (issue3.values.length === 1)
          return `Ongeldige invoer: verwacht ${stringifyPrimitive2(issue3.values[0])}`;
        return `Ongeldige optie: verwacht \xE9\xE9n van ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        const longName = issue3.origin === "date" ? "laat" : issue3.origin === "string" ? "lang" : "groot";
        if (sizing)
          return `Te ${longName}: verwacht dat ${issue3.origin ?? "waarde"} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementen"} ${sizing.verb}`;
        return `Te ${longName}: verwacht dat ${issue3.origin ?? "waarde"} ${adj}${issue3.maximum.toString()} is`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        const shortName = issue3.origin === "date" ? "vroeg" : issue3.origin === "string" ? "kort" : "klein";
        if (sizing) {
          return `Te ${shortName}: verwacht dat ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit} ${sizing.verb}`;
        }
        return `Te ${shortName}: verwacht dat ${issue3.origin} ${adj}${issue3.minimum.toString()} is`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format}`;
      }
      case "not_multiple_of":
        return `Ongeldig getal: moet een veelvoud van ${issue3.divisor} zijn`;
      case "unrecognized_keys":
        return `Onbekende key${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `Ongeldige key in ${issue3.origin}`;
      case "invalid_union":
        return "Ongeldige invoer";
      case "invalid_element":
        return `Ongeldige waarde in ${issue3.origin}`;
      default:
        return `Ongeldige invoer`;
    }
  };
};
function nl_default2() {
  return {
    localeError: error81()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/no.js
var error82 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `Ugyldig input: forventet instanceof ${issue3.expected}, fikk ${received}`;
        }
        return `Ugyldig input: forventet ${expected}, fikk ${received}`;
      }
      case "invalid_value":
        if (issue3.values.length === 1)
          return `Ugyldig verdi: forventet ${stringifyPrimitive2(issue3.values[0])}`;
        return `Ugyldig valg: forventet en av ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `For stor(t): forventet ${issue3.origin ?? "value"} til \xE5 ha ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementer"}`;
        return `For stor(t): forventet ${issue3.origin ?? "value"} til \xE5 ha ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `For lite(n): forventet ${issue3.origin} til \xE5 ha ${adj}${issue3.minimum.toString()} ${sizing.unit}`;
        }
        return `For lite(n): forventet ${issue3.origin} til \xE5 ha ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format}`;
      }
      case "not_multiple_of":
        return `Ugyldig tall: m\xE5 v\xE6re et multiplum av ${issue3.divisor}`;
      case "unrecognized_keys":
        return `${issue3.keys.length > 1 ? "Ukjente n\xF8kler" : "Ukjent n\xF8kkel"}: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `Ugyldig n\xF8kkel i ${issue3.origin}`;
      case "invalid_union":
        return "Ugyldig input";
      case "invalid_element":
        return `Ugyldig verdi i ${issue3.origin}`;
      default:
        return `Ugyldig input`;
    }
  };
};
function no_default2() {
  return {
    localeError: error82()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ota.js
var error83 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `F\xE2sit giren: umulan instanceof ${issue3.expected}, al\u0131nan ${received}`;
        }
        return `F\xE2sit giren: umulan ${expected}, al\u0131nan ${received}`;
      }
      case "invalid_value":
        if (issue3.values.length === 1)
          return `F\xE2sit giren: umulan ${stringifyPrimitive2(issue3.values[0])}`;
        return `F\xE2sit tercih: m\xFBteberler ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `Fazla b\xFCy\xFCk: ${issue3.origin ?? "value"}, ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elements"} sahip olmal\u0131yd\u0131.`;
        return `Fazla b\xFCy\xFCk: ${issue3.origin ?? "value"}, ${adj}${issue3.maximum.toString()} olmal\u0131yd\u0131.`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `Fazla k\xFC\xE7\xFCk: ${issue3.origin}, ${adj}${issue3.minimum.toString()} ${sizing.unit} sahip olmal\u0131yd\u0131.`;
        }
        return `Fazla k\xFC\xE7\xFCk: ${issue3.origin}, ${adj}${issue3.minimum.toString()} olmal\u0131yd\u0131.`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format}`;
      }
      case "not_multiple_of":
        return `F\xE2sit say\u0131: ${issue3.divisor} kat\u0131 olmal\u0131yd\u0131.`;
      case "unrecognized_keys":
        return `Tan\u0131nmayan anahtar ${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `${issue3.origin} i\xE7in tan\u0131nmayan anahtar var.`;
      case "invalid_union":
        return "Giren tan\u0131namad\u0131.";
      case "invalid_element":
        return `${issue3.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;
      default:
        return `K\u0131ymet tan\u0131namad\u0131.`;
    }
  };
};
function ota_default2() {
  return {
    localeError: error83()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ps.js
var error84 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${issue3.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 (issue3.values.length === 1) {
          return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${stringifyPrimitive2(issue3.values[0])} \u0648\u0627\u06CC`;
        }
        return `\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${joinValues2(issue3.values, "|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue3.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`;
        }
        return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue3.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue3.maximum.toString()} \u0648\u064A`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue3.origin} \u0628\u0627\u06CC\u062F ${adj}${issue3.minimum.toString()} ${sizing.unit} \u0648\u0644\u0631\u064A`;
        }
        return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue3.origin} \u0628\u0627\u06CC\u062F ${adj}${issue3.minimum.toString()} \u0648\u064A`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`;
      }
      case "not_multiple_of":
        return `\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${issue3.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;
      case "unrecognized_keys":
        return `\u0646\u0627\u0633\u0645 ${issue3.keys.length > 1 ? "\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647" : "\u06A9\u0644\u06CC\u0689"}: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${issue3.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 ${issue3.origin} \u06A9\u06D0`;
      default:
        return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`;
    }
  };
};
function ps_default2() {
  return {
    localeError: error84()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/pl.js
var error85 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${issue3.expected}, otrzymano ${received}`;
        }
        return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${expected}, otrzymano ${received}`;
      }
      case "invalid_value":
        if (issue3.values.length === 1)
          return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${stringifyPrimitive2(issue3.values[0])}`;
        return `Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${issue3.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "element\xF3w"}`;
        }
        return `Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${issue3.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${issue3.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue3.minimum.toString()} ${sizing.unit ?? "element\xF3w"}`;
        }
        return `Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${issue3.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format}`;
      }
      case "not_multiple_of":
        return `Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${issue3.divisor}`;
      case "unrecognized_keys":
        return `Nierozpoznane klucze${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `Nieprawid\u0142owy klucz w ${issue3.origin}`;
      case "invalid_union":
        return "Nieprawid\u0142owe dane wej\u015Bciowe";
      case "invalid_element":
        return `Nieprawid\u0142owa warto\u015B\u0107 w ${issue3.origin}`;
      default:
        return `Nieprawid\u0142owe dane wej\u015Bciowe`;
    }
  };
};
function pl_default2() {
  return {
    localeError: error85()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/pt.js
var error86 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `Tipo inv\xE1lido: esperado instanceof ${issue3.expected}, recebido ${received}`;
        }
        return `Tipo inv\xE1lido: esperado ${expected}, recebido ${received}`;
      }
      case "invalid_value":
        if (issue3.values.length === 1)
          return `Entrada inv\xE1lida: esperado ${stringifyPrimitive2(issue3.values[0])}`;
        return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `Muito grande: esperado que ${issue3.origin ?? "valor"} tivesse ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementos"}`;
        return `Muito grande: esperado que ${issue3.origin ?? "valor"} fosse ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `Muito pequeno: esperado que ${issue3.origin} tivesse ${adj}${issue3.minimum.toString()} ${sizing.unit}`;
        }
        return `Muito pequeno: esperado que ${issue3.origin} fosse ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format} inv\xE1lido`;
      }
      case "not_multiple_of":
        return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue3.divisor}`;
      case "unrecognized_keys":
        return `Chave${issue3.keys.length > 1 ? "s" : ""} desconhecida${issue3.keys.length > 1 ? "s" : ""}: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `Chave inv\xE1lida em ${issue3.origin}`;
      case "invalid_union":
        return "Entrada inv\xE1lida";
      case "invalid_element":
        return `Valor inv\xE1lido em ${issue3.origin}`;
      default:
        return `Campo inv\xE1lido`;
    }
  };
};
function pt_default2() {
  return {
    localeError: error86()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ro.js
var error87 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        return `Intrare invalid\u0103: a\u0219teptat ${expected}, primit ${received}`;
      }
      case "invalid_value":
        if (issue3.values.length === 1)
          return `Intrare invalid\u0103: a\u0219teptat ${stringifyPrimitive2(issue3.values[0])}`;
        return `Op\u021Biune invalid\u0103: a\u0219teptat una dintre ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `Prea mare: a\u0219teptat ca ${issue3.origin ?? "valoarea"} ${sizing.verb} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elemente"}`;
        return `Prea mare: a\u0219teptat ca ${issue3.origin ?? "valoarea"} s\u0103 fie ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `Prea mic: a\u0219teptat ca ${issue3.origin} ${sizing.verb} ${adj}${issue3.minimum.toString()} ${sizing.unit}`;
        }
        return `Prea mic: a\u0219teptat ca ${issue3.origin} s\u0103 fie ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format}`;
      }
      case "not_multiple_of":
        return `Num\u0103r invalid: trebuie s\u0103 fie multiplu de ${issue3.divisor}`;
      case "unrecognized_keys":
        return `Chei nerecunoscute: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `Cheie invalid\u0103 \xEEn ${issue3.origin}`;
      case "invalid_union":
        return "Intrare invalid\u0103";
      case "invalid_element":
        return `Valoare invalid\u0103 \xEEn ${issue3.origin}`;
      default:
        return `Intrare invalid\u0103`;
    }
  };
};
function ro_default2() {
  return {
    localeError: error87()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ru.js
function getRussianPlural2(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;
}
var error88 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${issue3.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 (issue3.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 ${stringifyPrimitive2(issue3.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 ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          const maxValue = Number(issue3.maximum);
          const unit = getRussianPlural2(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 ${issue3.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue3.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 ${issue3.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          const minValue = Number(issue3.minimum);
          const unit = getRussianPlural2(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 ${issue3.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue3.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 ${issue3.origin} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.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 ${issue3.divisor}`;
      case "unrecognized_keys":
        return `\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${issue3.keys.length > 1 ? "\u044B\u0435" : "\u044B\u0439"} \u043A\u043B\u044E\u0447${issue3.keys.length > 1 ? "\u0438" : ""}: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${issue3.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 ${issue3.origin}`;
      default:
        return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435`;
    }
  };
};
function ru_default2() {
  return {
    localeError: error88()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/sl.js
var error89 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `Neveljaven vnos: pri\u010Dakovano instanceof ${issue3.expected}, prejeto ${received}`;
        }
        return `Neveljaven vnos: pri\u010Dakovano ${expected}, prejeto ${received}`;
      }
      case "invalid_value":
        if (issue3.values.length === 1)
          return `Neveljaven vnos: pri\u010Dakovano ${stringifyPrimitive2(issue3.values[0])}`;
        return `Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `Preveliko: pri\u010Dakovano, da bo ${issue3.origin ?? "vrednost"} imelo ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "elementov"}`;
        return `Preveliko: pri\u010Dakovano, da bo ${issue3.origin ?? "vrednost"} ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `Premajhno: pri\u010Dakovano, da bo ${issue3.origin} imelo ${adj}${issue3.minimum.toString()} ${sizing.unit}`;
        }
        return `Premajhno: pri\u010Dakovano, da bo ${issue3.origin} ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format}`;
      }
      case "not_multiple_of":
        return `Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${issue3.divisor}`;
      case "unrecognized_keys":
        return `Neprepoznan${issue3.keys.length > 1 ? "i klju\u010Di" : " klju\u010D"}: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `Neveljaven klju\u010D v ${issue3.origin}`;
      case "invalid_union":
        return "Neveljaven vnos";
      case "invalid_element":
        return `Neveljavna vrednost v ${issue3.origin}`;
      default:
        return "Neveljaven vnos";
    }
  };
};
function sl_default2() {
  return {
    localeError: error89()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/sv.js
var error90 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `Ogiltig inmatning: f\xF6rv\xE4ntat instanceof ${issue3.expected}, fick ${received}`;
        }
        return `Ogiltig inmatning: f\xF6rv\xE4ntat ${expected}, fick ${received}`;
      }
      case "invalid_value":
        if (issue3.values.length === 1)
          return `Ogiltig inmatning: f\xF6rv\xE4ntat ${stringifyPrimitive2(issue3.values[0])}`;
        return `Ogiltigt val: f\xF6rv\xE4ntade en av ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `F\xF6r stor(t): f\xF6rv\xE4ntade ${issue3.origin ?? "v\xE4rdet"} att ha ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "element"}`;
        }
        return `F\xF6r stor(t): f\xF6rv\xE4ntat ${issue3.origin ?? "v\xE4rdet"} att ha ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue3.origin ?? "v\xE4rdet"} att ha ${adj}${issue3.minimum.toString()} ${sizing.unit}`;
        }
        return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue3.origin ?? "v\xE4rdet"} att ha ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format}`;
      }
      case "not_multiple_of":
        return `Ogiltigt tal: m\xE5ste vara en multipel av ${issue3.divisor}`;
      case "unrecognized_keys":
        return `${issue3.keys.length > 1 ? "Ok\xE4nda nycklar" : "Ok\xE4nd nyckel"}: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `Ogiltig nyckel i ${issue3.origin ?? "v\xE4rdet"}`;
      case "invalid_union":
        return "Ogiltig input";
      case "invalid_element":
        return `Ogiltigt v\xE4rde i ${issue3.origin ?? "v\xE4rdet"}`;
      default:
        return `Ogiltig input`;
    }
  };
};
function sv_default2() {
  return {
    localeError: error90()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ta.js
var error91 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.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 ${issue3.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 (issue3.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 ${stringifyPrimitive2(issue3.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 ${joinValues2(issue3.values, "|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.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 ${issue3.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue3.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 ${issue3.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue3.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.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 ${issue3.origin} ${adj}${issue3.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 ${issue3.origin} ${adj}${issue3.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format}`;
      }
      case "not_multiple_of":
        return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${issue3.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${issue3.keys.length > 1 ? "\u0B95\u0BB3\u0BCD" : ""}: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `${issue3.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 `${issue3.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`;
    }
  };
};
function ta_default2() {
  return {
    localeError: error91()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/th.js
var error92 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.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 ${issue3.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 (issue3.values.length === 1)
          return `\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${stringifyPrimitive2(issue3.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 ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19" : "\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue3.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue3.maximum.toString()} ${sizing.unit ?? "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`;
        return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue3.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? "\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22" : "\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue3.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue3.minimum.toString()} ${sizing.unit}`;
        }
        return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue3.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.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 ${issue3.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: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue3.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 ${issue3.origin}`;
      default:
        return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07`;
    }
  };
};
function th_default2() {
  return {
    localeError: error92()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/tr.js
var error93 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `Ge\xE7ersiz de\u011Fer: beklenen instanceof ${issue3.expected}, al\u0131nan ${received}`;
        }
        return `Ge\xE7ersiz de\u011Fer: beklenen ${expected}, al\u0131nan ${received}`;
      }
      case "invalid_value":
        if (issue3.values.length === 1)
          return `Ge\xE7ersiz de\u011Fer: beklenen ${stringifyPrimitive2(issue3.values[0])}`;
        return `Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `\xC7ok b\xFCy\xFCk: beklenen ${issue3.origin ?? "de\u011Fer"} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "\xF6\u011Fe"}`;
        return `\xC7ok b\xFCy\xFCk: beklenen ${issue3.origin ?? "de\u011Fer"} ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit}`;
        return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue3.origin} ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format}`;
      }
      case "not_multiple_of":
        return `Ge\xE7ersiz say\u0131: ${issue3.divisor} ile tam b\xF6l\xFCnebilmeli`;
      case "unrecognized_keys":
        return `Tan\u0131nmayan anahtar${issue3.keys.length > 1 ? "lar" : ""}: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `${issue3.origin} i\xE7inde ge\xE7ersiz anahtar`;
      case "invalid_union":
        return "Ge\xE7ersiz de\u011Fer";
      case "invalid_element":
        return `${issue3.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;
      default:
        return `Ge\xE7ersiz de\u011Fer`;
    }
  };
};
function tr_default2() {
  return {
    localeError: error93()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/uk.js
var error94 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.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 ${issue3.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 (issue3.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 ${stringifyPrimitive2(issue3.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 ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.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 ${issue3.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${sizing.verb} ${adj}${issue3.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 ${issue3.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.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 ${issue3.origin} ${sizing.verb} ${adj}${issue3.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 ${issue3.origin} \u0431\u0443\u0434\u0435 ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.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 ${issue3.divisor}`;
      case "unrecognized_keys":
        return `\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${issue3.keys.length > 1 ? "\u0456" : ""}: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${issue3.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 ${issue3.origin}`;
      default:
        return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456`;
    }
  };
};
function uk_default2() {
  return {
    localeError: error94()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ua.js
function ua_default2() {
  return uk_default2();
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/ur.js
var error95 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${issue3.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 (issue3.values.length === 1)
          return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${stringifyPrimitive2(issue3.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
        return `\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${joinValues2(issue3.values, "|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue3.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${adj}${issue3.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: ${issue3.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${adj}${issue3.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue3.origin} \u06A9\u06D2 ${adj}${issue3.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: ${issue3.origin} \u06A9\u0627 ${adj}${issue3.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format}`;
      }
      case "not_multiple_of":
        return `\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${issue3.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${issue3.keys.length > 1 ? "\u0632" : ""}: ${joinValues2(issue3.keys, "\u060C ")}`;
      case "invalid_key":
        return `${issue3.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;
      case "invalid_union":
        return "\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";
      case "invalid_element":
        return `${issue3.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;
      default:
        return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679`;
    }
  };
};
function ur_default2() {
  return {
    localeError: error95()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/uz.js
var error96 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `Noto\u2018g\u2018ri kirish: kutilgan instanceof ${issue3.expected}, qabul qilingan ${received}`;
        }
        return `Noto\u2018g\u2018ri kirish: kutilgan ${expected}, qabul qilingan ${received}`;
      }
      case "invalid_value":
        if (issue3.values.length === 1)
          return `Noto\u2018g\u2018ri kirish: kutilgan ${stringifyPrimitive2(issue3.values[0])}`;
        return `Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `Juda katta: kutilgan ${issue3.origin ?? "qiymat"} ${adj}${issue3.maximum.toString()} ${sizing.unit} ${sizing.verb}`;
        return `Juda katta: kutilgan ${issue3.origin ?? "qiymat"} ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `Juda kichik: kutilgan ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit} ${sizing.verb}`;
        }
        return `Juda kichik: kutilgan ${issue3.origin} ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format}`;
      }
      case "not_multiple_of":
        return `Noto\u2018g\u2018ri raqam: ${issue3.divisor} ning karralisi bo\u2018lishi kerak`;
      case "unrecognized_keys":
        return `Noma\u2019lum kalit${issue3.keys.length > 1 ? "lar" : ""}: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `${issue3.origin} dagi kalit noto\u2018g\u2018ri`;
      case "invalid_union":
        return "Noto\u2018g\u2018ri kirish";
      case "invalid_element":
        return `${issue3.origin} da noto\u2018g\u2018ri qiymat`;
      default:
        return `Noto\u2018g\u2018ri kirish`;
    }
  };
};
function uz_default2() {
  return {
    localeError: error96()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/vi.js
var error97 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${issue3.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 (issue3.values.length === 1)
          return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${stringifyPrimitive2(issue3.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 ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue3.origin ?? "gi\xE1 tr\u1ECB"} ${sizing.verb} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "ph\u1EA7n t\u1EED"}`;
        return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue3.origin ?? "gi\xE1 tr\u1ECB"} ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue3.origin} ${sizing.verb} ${adj}${issue3.minimum.toString()} ${sizing.unit}`;
        }
        return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue3.origin} ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.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 ${issue3.divisor}`;
      case "unrecognized_keys":
        return `Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue3.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 ${issue3.origin}`;
      default:
        return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7`;
    }
  };
};
function vi_default2() {
  return {
    localeError: error97()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/zh-CN.js
var error98 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${issue3.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 (issue3.values.length === 1)
          return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${stringifyPrimitive2(issue3.values[0])}`;
        return `\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue3.origin ?? "\u503C"} ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "\u4E2A\u5143\u7D20"}`;
        return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue3.origin ?? "\u503C"} ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit}`;
        }
        return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue3.origin} ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format}`;
      }
      case "not_multiple_of":
        return `\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${issue3.divisor} \u7684\u500D\u6570`;
      case "unrecognized_keys":
        return `\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `${issue3.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;
      case "invalid_union":
        return "\u65E0\u6548\u8F93\u5165";
      case "invalid_element":
        return `${issue3.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;
      default:
        return `\u65E0\u6548\u8F93\u5165`;
    }
  };
};
function zh_CN_default2() {
  return {
    localeError: error98()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/zh-TW.js
var error99 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${issue3.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 (issue3.values.length === 1)
          return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${stringifyPrimitive2(issue3.values[0])}`;
        return `\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue3.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue3.maximum.toString()} ${sizing.unit ?? "\u500B\u5143\u7D20"}`;
        return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue3.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue3.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing) {
          return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue3.origin} \u61C9\u70BA ${adj}${issue3.minimum.toString()} ${sizing.unit}`;
        }
        return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue3.origin} \u61C9\u70BA ${adj}${issue3.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.format}`;
      }
      case "not_multiple_of":
        return `\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${issue3.divisor} \u7684\u500D\u6578`;
      case "unrecognized_keys":
        return `\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${issue3.keys.length > 1 ? "\u5011" : ""}\uFF1A${joinValues2(issue3.keys, "\u3001")}`;
      case "invalid_key":
        return `${issue3.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;
      case "invalid_union":
        return "\u7121\u6548\u7684\u8F38\u5165\u503C";
      case "invalid_element":
        return `${issue3.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;
      default:
        return `\u7121\u6548\u7684\u8F38\u5165\u503C`;
    }
  };
};
function zh_TW_default2() {
  return {
    localeError: error99()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/yo.js
var error100 = () => {
  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;
  }
  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 (issue3) => {
    switch (issue3.code) {
      case "invalid_type": {
        const expected = TypeDictionary[issue3.expected] ?? issue3.expected;
        const receivedType = parsedType2(issue3.input);
        const received = TypeDictionary[receivedType] ?? receivedType;
        if (/^[A-Z]/.test(issue3.expected)) {
          return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi instanceof ${issue3.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 (issue3.values.length === 1)
          return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${stringifyPrimitive2(issue3.values[0])}`;
        return `\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${joinValues2(issue3.values, "|")}`;
      case "too_big": {
        const adj = issue3.inclusive ? "<=" : "<";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue3.origin ?? "iye"} ${sizing.verb} ${adj}${issue3.maximum} ${sizing.unit}`;
        return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue3.maximum}`;
      }
      case "too_small": {
        const adj = issue3.inclusive ? ">=" : ">";
        const sizing = getSizing(issue3.origin);
        if (sizing)
          return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue3.origin} ${sizing.verb} ${adj}${issue3.minimum} ${sizing.unit}`;
        return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue3.minimum}`;
      }
      case "invalid_format": {
        const _issue = issue3;
        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] ?? issue3.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 ${issue3.divisor}`;
      case "unrecognized_keys":
        return `B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${joinValues2(issue3.keys, ", ")}`;
      case "invalid_key":
        return `B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue3.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 ${issue3.origin}`;
      default:
        return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e";
    }
  };
};
function yo_default2() {
  return {
    localeError: error100()
  };
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/registries.js
var _a4;
var $output2 = /* @__PURE__ */ Symbol("ZodOutput");
var $input2 = /* @__PURE__ */ Symbol("ZodInput");
var $ZodRegistry2 = class {
  constructor() {
    this._map = /* @__PURE__ */ new WeakMap();
    this._idmap = /* @__PURE__ */ new Map();
  }
  add(schema, ..._meta) {
    const meta5 = _meta[0];
    this._map.set(schema, meta5);
    if (meta5 && typeof meta5 === "object" && "id" in meta5) {
      this._idmap.set(meta5.id, schema);
    }
    return this;
  }
  clear() {
    this._map = /* @__PURE__ */ new WeakMap();
    this._idmap = /* @__PURE__ */ new Map();
    return this;
  }
  remove(schema) {
    const meta5 = this._map.get(schema);
    if (meta5 && typeof meta5 === "object" && "id" in meta5) {
      this._idmap.delete(meta5.id);
    }
    this._map.delete(schema);
    return this;
  }
  get(schema) {
    const p2 = schema._zod.parent;
    if (p2) {
      const pm = { ...this.get(p2) ?? {} };
      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 registry2() {
  return new $ZodRegistry2();
}
(_a4 = globalThis).__zod_globalRegistry ?? (_a4.__zod_globalRegistry = registry2());
var globalRegistry2 = globalThis.__zod_globalRegistry;

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/api.js
// @__NO_SIDE_EFFECTS__
function _string2(Class3, params) {
  return new Class3({
    type: "string",
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _coercedString2(Class3, params) {
  return new Class3({
    type: "string",
    coerce: true,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _email2(Class3, params) {
  return new Class3({
    type: "string",
    format: "email",
    check: "string_format",
    abort: false,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _guid2(Class3, params) {
  return new Class3({
    type: "string",
    format: "guid",
    check: "string_format",
    abort: false,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _uuid2(Class3, params) {
  return new Class3({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _uuidv42(Class3, params) {
  return new Class3({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    version: "v4",
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _uuidv62(Class3, params) {
  return new Class3({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    version: "v6",
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _uuidv72(Class3, params) {
  return new Class3({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    version: "v7",
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _url2(Class3, params) {
  return new Class3({
    type: "string",
    format: "url",
    check: "string_format",
    abort: false,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _emoji4(Class3, params) {
  return new Class3({
    type: "string",
    format: "emoji",
    check: "string_format",
    abort: false,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _nanoid2(Class3, params) {
  return new Class3({
    type: "string",
    format: "nanoid",
    check: "string_format",
    abort: false,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _cuid3(Class3, params) {
  return new Class3({
    type: "string",
    format: "cuid",
    check: "string_format",
    abort: false,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _cuid22(Class3, params) {
  return new Class3({
    type: "string",
    format: "cuid2",
    check: "string_format",
    abort: false,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _ulid2(Class3, params) {
  return new Class3({
    type: "string",
    format: "ulid",
    check: "string_format",
    abort: false,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _xid2(Class3, params) {
  return new Class3({
    type: "string",
    format: "xid",
    check: "string_format",
    abort: false,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _ksuid2(Class3, params) {
  return new Class3({
    type: "string",
    format: "ksuid",
    check: "string_format",
    abort: false,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _ipv42(Class3, params) {
  return new Class3({
    type: "string",
    format: "ipv4",
    check: "string_format",
    abort: false,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _ipv62(Class3, params) {
  return new Class3({
    type: "string",
    format: "ipv6",
    check: "string_format",
    abort: false,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _mac2(Class3, params) {
  return new Class3({
    type: "string",
    format: "mac",
    check: "string_format",
    abort: false,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _cidrv42(Class3, params) {
  return new Class3({
    type: "string",
    format: "cidrv4",
    check: "string_format",
    abort: false,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _cidrv62(Class3, params) {
  return new Class3({
    type: "string",
    format: "cidrv6",
    check: "string_format",
    abort: false,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _base642(Class3, params) {
  return new Class3({
    type: "string",
    format: "base64",
    check: "string_format",
    abort: false,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _base64url2(Class3, params) {
  return new Class3({
    type: "string",
    format: "base64url",
    check: "string_format",
    abort: false,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _e1642(Class3, params) {
  return new Class3({
    type: "string",
    format: "e164",
    check: "string_format",
    abort: false,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _jwt2(Class3, params) {
  return new Class3({
    type: "string",
    format: "jwt",
    check: "string_format",
    abort: false,
    ...normalizeParams2(params)
  });
}
var TimePrecision2 = {
  Any: null,
  Minute: -1,
  Second: 0,
  Millisecond: 3,
  Microsecond: 6
};
// @__NO_SIDE_EFFECTS__
function _isoDateTime2(Class3, params) {
  return new Class3({
    type: "string",
    format: "datetime",
    check: "string_format",
    offset: false,
    local: false,
    precision: null,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _isoDate2(Class3, params) {
  return new Class3({
    type: "string",
    format: "date",
    check: "string_format",
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _isoTime2(Class3, params) {
  return new Class3({
    type: "string",
    format: "time",
    check: "string_format",
    precision: null,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _isoDuration2(Class3, params) {
  return new Class3({
    type: "string",
    format: "duration",
    check: "string_format",
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _number2(Class3, params) {
  return new Class3({
    type: "number",
    checks: [],
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _coercedNumber2(Class3, params) {
  return new Class3({
    type: "number",
    coerce: true,
    checks: [],
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _int2(Class3, params) {
  return new Class3({
    type: "number",
    check: "number_format",
    abort: false,
    format: "safeint",
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _float322(Class3, params) {
  return new Class3({
    type: "number",
    check: "number_format",
    abort: false,
    format: "float32",
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _float642(Class3, params) {
  return new Class3({
    type: "number",
    check: "number_format",
    abort: false,
    format: "float64",
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _int322(Class3, params) {
  return new Class3({
    type: "number",
    check: "number_format",
    abort: false,
    format: "int32",
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _uint322(Class3, params) {
  return new Class3({
    type: "number",
    check: "number_format",
    abort: false,
    format: "uint32",
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _boolean2(Class3, params) {
  return new Class3({
    type: "boolean",
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _coercedBoolean2(Class3, params) {
  return new Class3({
    type: "boolean",
    coerce: true,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _bigint2(Class3, params) {
  return new Class3({
    type: "bigint",
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _coercedBigint2(Class3, params) {
  return new Class3({
    type: "bigint",
    coerce: true,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _int642(Class3, params) {
  return new Class3({
    type: "bigint",
    check: "bigint_format",
    abort: false,
    format: "int64",
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _uint642(Class3, params) {
  return new Class3({
    type: "bigint",
    check: "bigint_format",
    abort: false,
    format: "uint64",
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _symbol2(Class3, params) {
  return new Class3({
    type: "symbol",
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _undefined5(Class3, params) {
  return new Class3({
    type: "undefined",
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _null5(Class3, params) {
  return new Class3({
    type: "null",
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _any2(Class3) {
  return new Class3({
    type: "any"
  });
}
// @__NO_SIDE_EFFECTS__
function _unknown2(Class3) {
  return new Class3({
    type: "unknown"
  });
}
// @__NO_SIDE_EFFECTS__
function _never2(Class3, params) {
  return new Class3({
    type: "never",
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _void3(Class3, params) {
  return new Class3({
    type: "void",
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _date2(Class3, params) {
  return new Class3({
    type: "date",
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _coercedDate2(Class3, params) {
  return new Class3({
    type: "date",
    coerce: true,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _nan2(Class3, params) {
  return new Class3({
    type: "nan",
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _lt2(value, params) {
  return new $ZodCheckLessThan2({
    check: "less_than",
    ...normalizeParams2(params),
    value,
    inclusive: false
  });
}
// @__NO_SIDE_EFFECTS__
function _lte2(value, params) {
  return new $ZodCheckLessThan2({
    check: "less_than",
    ...normalizeParams2(params),
    value,
    inclusive: true
  });
}
// @__NO_SIDE_EFFECTS__
function _gt2(value, params) {
  return new $ZodCheckGreaterThan2({
    check: "greater_than",
    ...normalizeParams2(params),
    value,
    inclusive: false
  });
}
// @__NO_SIDE_EFFECTS__
function _gte2(value, params) {
  return new $ZodCheckGreaterThan2({
    check: "greater_than",
    ...normalizeParams2(params),
    value,
    inclusive: true
  });
}
// @__NO_SIDE_EFFECTS__
function _positive2(params) {
  return /* @__PURE__ */ _gt2(0, params);
}
// @__NO_SIDE_EFFECTS__
function _negative2(params) {
  return /* @__PURE__ */ _lt2(0, params);
}
// @__NO_SIDE_EFFECTS__
function _nonpositive2(params) {
  return /* @__PURE__ */ _lte2(0, params);
}
// @__NO_SIDE_EFFECTS__
function _nonnegative2(params) {
  return /* @__PURE__ */ _gte2(0, params);
}
// @__NO_SIDE_EFFECTS__
function _multipleOf2(value, params) {
  return new $ZodCheckMultipleOf2({
    check: "multiple_of",
    ...normalizeParams2(params),
    value
  });
}
// @__NO_SIDE_EFFECTS__
function _maxSize2(maximum, params) {
  return new $ZodCheckMaxSize2({
    check: "max_size",
    ...normalizeParams2(params),
    maximum
  });
}
// @__NO_SIDE_EFFECTS__
function _minSize2(minimum, params) {
  return new $ZodCheckMinSize2({
    check: "min_size",
    ...normalizeParams2(params),
    minimum
  });
}
// @__NO_SIDE_EFFECTS__
function _size2(size, params) {
  return new $ZodCheckSizeEquals2({
    check: "size_equals",
    ...normalizeParams2(params),
    size
  });
}
// @__NO_SIDE_EFFECTS__
function _maxLength2(maximum, params) {
  const ch = new $ZodCheckMaxLength2({
    check: "max_length",
    ...normalizeParams2(params),
    maximum
  });
  return ch;
}
// @__NO_SIDE_EFFECTS__
function _minLength2(minimum, params) {
  return new $ZodCheckMinLength2({
    check: "min_length",
    ...normalizeParams2(params),
    minimum
  });
}
// @__NO_SIDE_EFFECTS__
function _length2(length, params) {
  return new $ZodCheckLengthEquals2({
    check: "length_equals",
    ...normalizeParams2(params),
    length
  });
}
// @__NO_SIDE_EFFECTS__
function _regex2(pattern, params) {
  return new $ZodCheckRegex2({
    check: "string_format",
    format: "regex",
    ...normalizeParams2(params),
    pattern
  });
}
// @__NO_SIDE_EFFECTS__
function _lowercase2(params) {
  return new $ZodCheckLowerCase2({
    check: "string_format",
    format: "lowercase",
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _uppercase2(params) {
  return new $ZodCheckUpperCase2({
    check: "string_format",
    format: "uppercase",
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _includes2(includes, params) {
  return new $ZodCheckIncludes2({
    check: "string_format",
    format: "includes",
    ...normalizeParams2(params),
    includes
  });
}
// @__NO_SIDE_EFFECTS__
function _startsWith2(prefix, params) {
  return new $ZodCheckStartsWith2({
    check: "string_format",
    format: "starts_with",
    ...normalizeParams2(params),
    prefix
  });
}
// @__NO_SIDE_EFFECTS__
function _endsWith2(suffix, params) {
  return new $ZodCheckEndsWith2({
    check: "string_format",
    format: "ends_with",
    ...normalizeParams2(params),
    suffix
  });
}
// @__NO_SIDE_EFFECTS__
function _property2(property, schema, params) {
  return new $ZodCheckProperty2({
    check: "property",
    property,
    schema,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _mime2(types3, params) {
  return new $ZodCheckMimeType2({
    check: "mime_type",
    mime: types3,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _overwrite2(tx) {
  return new $ZodCheckOverwrite2({
    check: "overwrite",
    tx
  });
}
// @__NO_SIDE_EFFECTS__
function _normalize2(form) {
  return /* @__PURE__ */ _overwrite2((input) => input.normalize(form));
}
// @__NO_SIDE_EFFECTS__
function _trim2() {
  return /* @__PURE__ */ _overwrite2((input) => input.trim());
}
// @__NO_SIDE_EFFECTS__
function _toLowerCase2() {
  return /* @__PURE__ */ _overwrite2((input) => input.toLowerCase());
}
// @__NO_SIDE_EFFECTS__
function _toUpperCase2() {
  return /* @__PURE__ */ _overwrite2((input) => input.toUpperCase());
}
// @__NO_SIDE_EFFECTS__
function _slugify2() {
  return /* @__PURE__ */ _overwrite2((input) => slugify2(input));
}
// @__NO_SIDE_EFFECTS__
function _array2(Class3, element, params) {
  return new Class3({
    type: "array",
    element,
    // get element() {
    //   return element;
    // },
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _union2(Class3, options, params) {
  return new Class3({
    type: "union",
    options,
    ...normalizeParams2(params)
  });
}
function _xor2(Class3, options, params) {
  return new Class3({
    type: "union",
    options,
    inclusive: false,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _discriminatedUnion2(Class3, discriminator, options, params) {
  return new Class3({
    type: "union",
    options,
    discriminator,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _intersection2(Class3, left, right) {
  return new Class3({
    type: "intersection",
    left,
    right
  });
}
// @__NO_SIDE_EFFECTS__
function _tuple2(Class3, items, _paramsOrRest, _params) {
  const hasRest = _paramsOrRest instanceof $ZodType2;
  const params = hasRest ? _params : _paramsOrRest;
  const rest = hasRest ? _paramsOrRest : null;
  return new Class3({
    type: "tuple",
    items,
    rest,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _record2(Class3, keyType, valueType, params) {
  return new Class3({
    type: "record",
    keyType,
    valueType,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _map2(Class3, keyType, valueType, params) {
  return new Class3({
    type: "map",
    keyType,
    valueType,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _set2(Class3, valueType, params) {
  return new Class3({
    type: "set",
    valueType,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _enum3(Class3, values, params) {
  const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
  return new Class3({
    type: "enum",
    entries,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _nativeEnum2(Class3, entries, params) {
  return new Class3({
    type: "enum",
    entries,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _literal2(Class3, value, params) {
  return new Class3({
    type: "literal",
    values: Array.isArray(value) ? value : [value],
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _file2(Class3, params) {
  return new Class3({
    type: "file",
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _transform2(Class3, fn) {
  return new Class3({
    type: "transform",
    transform: fn
  });
}
// @__NO_SIDE_EFFECTS__
function _optional2(Class3, innerType) {
  return new Class3({
    type: "optional",
    innerType
  });
}
// @__NO_SIDE_EFFECTS__
function _nullable2(Class3, innerType) {
  return new Class3({
    type: "nullable",
    innerType
  });
}
// @__NO_SIDE_EFFECTS__
function _default3(Class3, innerType, defaultValue) {
  return new Class3({
    type: "default",
    innerType,
    get defaultValue() {
      return typeof defaultValue === "function" ? defaultValue() : shallowClone2(defaultValue);
    }
  });
}
// @__NO_SIDE_EFFECTS__
function _nonoptional2(Class3, innerType, params) {
  return new Class3({
    type: "nonoptional",
    innerType,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _success2(Class3, innerType) {
  return new Class3({
    type: "success",
    innerType
  });
}
// @__NO_SIDE_EFFECTS__
function _catch3(Class3, innerType, catchValue) {
  return new Class3({
    type: "catch",
    innerType,
    catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
  });
}
// @__NO_SIDE_EFFECTS__
function _pipe2(Class3, in_, out) {
  return new Class3({
    type: "pipe",
    in: in_,
    out
  });
}
// @__NO_SIDE_EFFECTS__
function _readonly2(Class3, innerType) {
  return new Class3({
    type: "readonly",
    innerType
  });
}
// @__NO_SIDE_EFFECTS__
function _templateLiteral2(Class3, parts, params) {
  return new Class3({
    type: "template_literal",
    parts,
    ...normalizeParams2(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _lazy2(Class3, getter) {
  return new Class3({
    type: "lazy",
    getter
  });
}
// @__NO_SIDE_EFFECTS__
function _promise2(Class3, innerType) {
  return new Class3({
    type: "promise",
    innerType
  });
}
// @__NO_SIDE_EFFECTS__
function _custom2(Class3, fn, _params) {
  const norm = normalizeParams2(_params);
  norm.abort ?? (norm.abort = true);
  const schema = new Class3({
    type: "custom",
    check: "custom",
    fn,
    ...norm
  });
  return schema;
}
// @__NO_SIDE_EFFECTS__
function _refine2(Class3, fn, _params) {
  const schema = new Class3({
    type: "custom",
    check: "custom",
    fn,
    ...normalizeParams2(_params)
  });
  return schema;
}
// @__NO_SIDE_EFFECTS__
function _superRefine2(fn, params) {
  const ch = /* @__PURE__ */ _check2((payload) => {
    payload.addIssue = (issue3) => {
      if (typeof issue3 === "string") {
        payload.issues.push(issue2(issue3, payload.value, ch._zod.def));
      } else {
        const _issue = issue3;
        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(issue2(_issue));
      }
    };
    return fn(payload.value, payload);
  }, params);
  return ch;
}
// @__NO_SIDE_EFFECTS__
function _check2(fn, params) {
  const ch = new $ZodCheck2({
    check: "custom",
    ...normalizeParams2(params)
  });
  ch._zod.check = fn;
  return ch;
}
// @__NO_SIDE_EFFECTS__
function describe3(description) {
  const ch = new $ZodCheck2({ check: "describe" });
  ch._zod.onattach = [
    (inst) => {
      const existing = globalRegistry2.get(inst) ?? {};
      globalRegistry2.add(inst, { ...existing, description });
    }
  ];
  ch._zod.check = () => {
  };
  return ch;
}
// @__NO_SIDE_EFFECTS__
function meta3(metadata) {
  const ch = new $ZodCheck2({ check: "meta" });
  ch._zod.onattach = [
    (inst) => {
      const existing = globalRegistry2.get(inst) ?? {};
      globalRegistry2.add(inst, { ...existing, ...metadata });
    }
  ];
  ch._zod.check = () => {
  };
  return ch;
}
// @__NO_SIDE_EFFECTS__
function _stringbool2(Classes, _params) {
  const params = normalizeParams2(_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 ?? $ZodCodec2;
  const _Boolean = Classes.Boolean ?? $ZodBoolean2;
  const _String = Classes.String ?? $ZodString2;
  const stringSchema = new _String({ type: "string", error: params.error });
  const booleanSchema = new _Boolean({ type: "boolean", error: params.error });
  const codec3 = new _Codec({
    type: "pipe",
    in: stringSchema,
    out: booleanSchema,
    transform: ((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: codec3,
          continue: false
        });
        return {};
      }
    }),
    reverseTransform: ((input, _payload) => {
      if (input === true) {
        return truthyArray[0] || "true";
      } else {
        return falsyArray[0] || "false";
      }
    }),
    error: params.error
  });
  return codec3;
}
// @__NO_SIDE_EFFECTS__
function _stringFormat2(Class3, format5, fnOrRegex, _params = {}) {
  const params = normalizeParams2(_params);
  const def = {
    ...normalizeParams2(_params),
    check: "string_format",
    type: "string",
    format: format5,
    fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val),
    ...params
  };
  if (fnOrRegex instanceof RegExp) {
    def.pattern = fnOrRegex;
  }
  const inst = new Class3(def);
  return inst;
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/to-json-schema.js
function initializeContext2(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 ?? globalRegistry2,
    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
  };
}
function process4(schema, ctx, _params = { path: [], schemaPath: [] }) {
  var _a5;
  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;
      process4(parent, ctx, params);
      ctx.seen.get(parent).isParent = true;
    }
  }
  const meta5 = ctx.metadataRegistry.get(schema);
  if (meta5)
    Object.assign(result.schema, meta5);
  if (ctx.io === "input" && isTransforming2(schema)) {
    delete result.schema.examples;
    delete result.schema.default;
  }
  if (ctx.io === "input" && "_prefault" in result.schema)
    (_a5 = result.schema).default ?? (_a5.default = result.schema._prefault);
  delete result.schema._prefault;
  const _result = ctx.seen.get(schema);
  return _result.schema;
}
function extractDefs2(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 = (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 };
  };
  const extractToDef = (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;
  };
  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("/")}/<root>

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;
      }
    }
  }
}
function finalize2(ctx, schema) {
  const root = ctx.seen.get(schema);
  if (!root)
    throw new Error("Unprocessed schema. This is a bug in Zod.");
  const flattenRef = (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 ?? []
    });
  };
  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: createStandardJSONSchemaMethod2(schema, "input", ctx.processors),
          output: createStandardJSONSchemaMethod2(schema, "output", ctx.processors)
        }
      },
      enumerable: false,
      writable: false
    });
    return finalized;
  } catch (_err) {
    throw new Error("Error converting schema to JSON.");
  }
}
function isTransforming2(_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 isTransforming2(def.element, ctx);
  if (def.type === "set")
    return isTransforming2(def.valueType, ctx);
  if (def.type === "lazy")
    return isTransforming2(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 isTransforming2(def.innerType, ctx);
  }
  if (def.type === "intersection") {
    return isTransforming2(def.left, ctx) || isTransforming2(def.right, ctx);
  }
  if (def.type === "record" || def.type === "map") {
    return isTransforming2(def.keyType, ctx) || isTransforming2(def.valueType, ctx);
  }
  if (def.type === "pipe") {
    if (_schema._zod.traits.has("$ZodCodec"))
      return true;
    return isTransforming2(def.in, ctx) || isTransforming2(def.out, ctx);
  }
  if (def.type === "object") {
    for (const key in def.shape) {
      if (isTransforming2(def.shape[key], ctx))
        return true;
    }
    return false;
  }
  if (def.type === "union") {
    for (const option of def.options) {
      if (isTransforming2(option, ctx))
        return true;
    }
    return false;
  }
  if (def.type === "tuple") {
    for (const item of def.items) {
      if (isTransforming2(item, ctx))
        return true;
    }
    if (def.rest && isTransforming2(def.rest, ctx))
      return true;
    return false;
  }
  return false;
}
var createToJSONSchemaMethod2 = (schema, processors = {}) => (params) => {
  const ctx = initializeContext2({ ...params, processors });
  process4(schema, ctx);
  extractDefs2(ctx, schema);
  return finalize2(ctx, schema);
};
var createStandardJSONSchemaMethod2 = (schema, io, processors = {}) => (params) => {
  const { libraryOptions, target } = params ?? {};
  const ctx = initializeContext2({ ...libraryOptions ?? {}, target, io, processors });
  process4(schema, ctx);
  extractDefs2(ctx, schema);
  return finalize2(ctx, schema);
};

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-processors.js
var formatMap2 = {
  guid: "uuid",
  url: "uri",
  datetime: "date-time",
  json_string: "json-string",
  regex: ""
  // do not set
};
var stringProcessor2 = (schema, ctx, _json, _params) => {
  const json3 = _json;
  json3.type = "string";
  const { minimum, maximum, format: format5, patterns, contentEncoding } = schema._zod.bag;
  if (typeof minimum === "number")
    json3.minLength = minimum;
  if (typeof maximum === "number")
    json3.maxLength = maximum;
  if (format5) {
    json3.format = formatMap2[format5] ?? format5;
    if (json3.format === "")
      delete json3.format;
    if (format5 === "time") {
      delete json3.format;
    }
  }
  if (contentEncoding)
    json3.contentEncoding = contentEncoding;
  if (patterns && patterns.size > 0) {
    const regexes = [...patterns];
    if (regexes.length === 1)
      json3.pattern = regexes[0].source;
    else if (regexes.length > 1) {
      json3.allOf = [
        ...regexes.map((regex3) => ({
          ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {},
          pattern: regex3.source
        }))
      ];
    }
  }
};
var numberProcessor2 = (schema, ctx, _json, _params) => {
  const json3 = _json;
  const { minimum, maximum, format: format5, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;
  if (typeof format5 === "string" && format5.includes("int"))
    json3.type = "integer";
  else
    json3.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) {
      json3.minimum = exclusiveMinimum;
      json3.exclusiveMinimum = true;
    } else {
      json3.exclusiveMinimum = exclusiveMinimum;
    }
  } else if (typeof minimum === "number") {
    json3.minimum = minimum;
  }
  if (exMax) {
    if (legacy) {
      json3.maximum = exclusiveMaximum;
      json3.exclusiveMaximum = true;
    } else {
      json3.exclusiveMaximum = exclusiveMaximum;
    }
  } else if (typeof maximum === "number") {
    json3.maximum = maximum;
  }
  if (typeof multipleOf === "number")
    json3.multipleOf = multipleOf;
};
var booleanProcessor2 = (_schema, _ctx, json3, _params) => {
  json3.type = "boolean";
};
var bigintProcessor2 = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("BigInt cannot be represented in JSON Schema");
  }
};
var symbolProcessor2 = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Symbols cannot be represented in JSON Schema");
  }
};
var nullProcessor2 = (_schema, ctx, json3, _params) => {
  if (ctx.target === "openapi-3.0") {
    json3.type = "string";
    json3.nullable = true;
    json3.enum = [null];
  } else {
    json3.type = "null";
  }
};
var undefinedProcessor2 = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Undefined cannot be represented in JSON Schema");
  }
};
var voidProcessor2 = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Void cannot be represented in JSON Schema");
  }
};
var neverProcessor2 = (_schema, _ctx, json3, _params) => {
  json3.not = {};
};
var anyProcessor2 = (_schema, _ctx, _json, _params) => {
};
var unknownProcessor2 = (_schema, _ctx, _json, _params) => {
};
var dateProcessor2 = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Date cannot be represented in JSON Schema");
  }
};
var enumProcessor2 = (schema, _ctx, json3, _params) => {
  const def = schema._zod.def;
  const values = getEnumValues2(def.entries);
  if (values.every((v) => typeof v === "number"))
    json3.type = "number";
  if (values.every((v) => typeof v === "string"))
    json3.type = "string";
  json3.enum = values;
};
var literalProcessor2 = (schema, ctx, json3, _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];
    json3.type = val === null ? "null" : typeof val;
    if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
      json3.enum = [val];
    } else {
      json3.const = val;
    }
  } else {
    if (vals.every((v) => typeof v === "number"))
      json3.type = "number";
    if (vals.every((v) => typeof v === "string"))
      json3.type = "string";
    if (vals.every((v) => typeof v === "boolean"))
      json3.type = "boolean";
    if (vals.every((v) => v === null))
      json3.type = "null";
    json3.enum = vals;
  }
};
var nanProcessor2 = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("NaN cannot be represented in JSON Schema");
  }
};
var templateLiteralProcessor2 = (schema, _ctx, json3, _params) => {
  const _json = json3;
  const pattern = schema._zod.pattern;
  if (!pattern)
    throw new Error("Pattern not found in template literal");
  _json.type = "string";
  _json.pattern = pattern.source;
};
var fileProcessor2 = (schema, _ctx, json3, _params) => {
  const _json = json3;
  const file5 = {
    type: "string",
    format: "binary",
    contentEncoding: "binary"
  };
  const { minimum, maximum, mime } = schema._zod.bag;
  if (minimum !== void 0)
    file5.minLength = minimum;
  if (maximum !== void 0)
    file5.maxLength = maximum;
  if (mime) {
    if (mime.length === 1) {
      file5.contentMediaType = mime[0];
      Object.assign(_json, file5);
    } else {
      Object.assign(_json, file5);
      _json.anyOf = mime.map((m) => ({ contentMediaType: m }));
    }
  } else {
    Object.assign(_json, file5);
  }
};
var successProcessor2 = (_schema, _ctx, json3, _params) => {
  json3.type = "boolean";
};
var customProcessor2 = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Custom types cannot be represented in JSON Schema");
  }
};
var functionProcessor2 = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Function types cannot be represented in JSON Schema");
  }
};
var transformProcessor2 = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Transforms cannot be represented in JSON Schema");
  }
};
var mapProcessor2 = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Map cannot be represented in JSON Schema");
  }
};
var setProcessor2 = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Set cannot be represented in JSON Schema");
  }
};
var arrayProcessor2 = (schema, ctx, _json, params) => {
  const json3 = _json;
  const def = schema._zod.def;
  const { minimum, maximum } = schema._zod.bag;
  if (typeof minimum === "number")
    json3.minItems = minimum;
  if (typeof maximum === "number")
    json3.maxItems = maximum;
  json3.type = "array";
  json3.items = process4(def.element, ctx, {
    ...params,
    path: [...params.path, "items"]
  });
};
var objectProcessor2 = (schema, ctx, _json, params) => {
  const json3 = _json;
  const def = schema._zod.def;
  json3.type = "object";
  json3.properties = {};
  const shape = def.shape;
  for (const key in shape) {
    json3.properties[key] = process4(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) {
    json3.required = Array.from(requiredKeys);
  }
  if (def.catchall?._zod.def.type === "never") {
    json3.additionalProperties = false;
  } else if (!def.catchall) {
    if (ctx.io === "output")
      json3.additionalProperties = false;
  } else if (def.catchall) {
    json3.additionalProperties = process4(def.catchall, ctx, {
      ...params,
      path: [...params.path, "additionalProperties"]
    });
  }
};
var unionProcessor2 = (schema, ctx, json3, params) => {
  const def = schema._zod.def;
  const isExclusive = def.inclusive === false;
  const options = def.options.map((x, i) => process4(x, ctx, {
    ...params,
    path: [...params.path, isExclusive ? "oneOf" : "anyOf", i]
  }));
  if (isExclusive) {
    json3.oneOf = options;
  } else {
    json3.anyOf = options;
  }
};
var intersectionProcessor2 = (schema, ctx, json3, params) => {
  const def = schema._zod.def;
  const a = process4(def.left, ctx, {
    ...params,
    path: [...params.path, "allOf", 0]
  });
  const b = process4(def.right, ctx, {
    ...params,
    path: [...params.path, "allOf", 1]
  });
  const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1;
  const allOf = [
    ...isSimpleIntersection(a) ? a.allOf : [a],
    ...isSimpleIntersection(b) ? b.allOf : [b]
  ];
  json3.allOf = allOf;
};
var tupleProcessor2 = (schema, ctx, _json, params) => {
  const json3 = _json;
  const def = schema._zod.def;
  json3.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) => process4(x, ctx, {
    ...params,
    path: [...params.path, prefixPath, i]
  }));
  const rest = def.rest ? process4(def.rest, ctx, {
    ...params,
    path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []]
  }) : null;
  if (ctx.target === "draft-2020-12") {
    json3.prefixItems = prefixItems;
    if (rest) {
      json3.items = rest;
    }
  } else if (ctx.target === "openapi-3.0") {
    json3.items = {
      anyOf: prefixItems
    };
    if (rest) {
      json3.items.anyOf.push(rest);
    }
    json3.minItems = prefixItems.length;
    if (!rest) {
      json3.maxItems = prefixItems.length;
    }
  } else {
    json3.items = prefixItems;
    if (rest) {
      json3.additionalItems = rest;
    }
  }
  const { minimum, maximum } = schema._zod.bag;
  if (typeof minimum === "number")
    json3.minItems = minimum;
  if (typeof maximum === "number")
    json3.maxItems = maximum;
};
var recordProcessor2 = (schema, ctx, _json, params) => {
  const json3 = _json;
  const def = schema._zod.def;
  json3.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 = process4(def.valueType, ctx, {
      ...params,
      path: [...params.path, "patternProperties", "*"]
    });
    json3.patternProperties = {};
    for (const pattern of patterns) {
      json3.patternProperties[pattern.source] = valueSchema;
    }
  } else {
    if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") {
      json3.propertyNames = process4(def.keyType, ctx, {
        ...params,
        path: [...params.path, "propertyNames"]
      });
    }
    json3.additionalProperties = process4(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) {
      json3.required = validKeyValues;
    }
  }
};
var nullableProcessor2 = (schema, ctx, json3, params) => {
  const def = schema._zod.def;
  const inner = process4(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  if (ctx.target === "openapi-3.0") {
    seen.ref = def.innerType;
    json3.nullable = true;
  } else {
    json3.anyOf = [inner, { type: "null" }];
  }
};
var nonoptionalProcessor2 = (schema, ctx, _json, params) => {
  const def = schema._zod.def;
  process4(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
};
var defaultProcessor2 = (schema, ctx, json3, params) => {
  const def = schema._zod.def;
  process4(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
  json3.default = JSON.parse(JSON.stringify(def.defaultValue));
};
var prefaultProcessor2 = (schema, ctx, json3, params) => {
  const def = schema._zod.def;
  process4(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
  if (ctx.io === "input")
    json3._prefault = JSON.parse(JSON.stringify(def.defaultValue));
};
var catchProcessor2 = (schema, ctx, json3, params) => {
  const def = schema._zod.def;
  process4(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");
  }
  json3.default = catchValue;
};
var pipeProcessor2 = (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;
  process4(innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = innerType;
};
var readonlyProcessor2 = (schema, ctx, json3, params) => {
  const def = schema._zod.def;
  process4(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
  json3.readOnly = true;
};
var promiseProcessor2 = (schema, ctx, _json, params) => {
  const def = schema._zod.def;
  process4(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
};
var optionalProcessor2 = (schema, ctx, _json, params) => {
  const def = schema._zod.def;
  process4(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
};
var lazyProcessor2 = (schema, ctx, _json, params) => {
  const innerType = schema._zod.innerType;
  process4(innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = innerType;
};
var allProcessors2 = {
  string: stringProcessor2,
  number: numberProcessor2,
  boolean: booleanProcessor2,
  bigint: bigintProcessor2,
  symbol: symbolProcessor2,
  null: nullProcessor2,
  undefined: undefinedProcessor2,
  void: voidProcessor2,
  never: neverProcessor2,
  any: anyProcessor2,
  unknown: unknownProcessor2,
  date: dateProcessor2,
  enum: enumProcessor2,
  literal: literalProcessor2,
  nan: nanProcessor2,
  template_literal: templateLiteralProcessor2,
  file: fileProcessor2,
  success: successProcessor2,
  custom: customProcessor2,
  function: functionProcessor2,
  transform: transformProcessor2,
  map: mapProcessor2,
  set: setProcessor2,
  array: arrayProcessor2,
  object: objectProcessor2,
  union: unionProcessor2,
  intersection: intersectionProcessor2,
  tuple: tupleProcessor2,
  record: recordProcessor2,
  nullable: nullableProcessor2,
  nonoptional: nonoptionalProcessor2,
  default: defaultProcessor2,
  prefault: prefaultProcessor2,
  catch: catchProcessor2,
  pipe: pipeProcessor2,
  readonly: readonlyProcessor2,
  promise: promiseProcessor2,
  optional: optionalProcessor2,
  lazy: lazyProcessor2
};
function toJSONSchema2(input, params) {
  if ("_idmap" in input) {
    const registry3 = input;
    const ctx2 = initializeContext2({ ...params, processors: allProcessors2 });
    const defs = {};
    for (const entry of registry3._idmap.entries()) {
      const [_, schema] = entry;
      process4(schema, ctx2);
    }
    const schemas = {};
    const external = {
      registry: registry3,
      uri: params?.uri,
      defs
    };
    ctx2.external = external;
    for (const entry of registry3._idmap.entries()) {
      const [key, schema] = entry;
      extractDefs2(ctx2, schema);
      schemas[key] = finalize2(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 = initializeContext2({ ...params, processors: allProcessors2 });
  process4(input, ctx);
  extractDefs2(ctx, input);
  return finalize2(ctx, input);
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-generator.js
var JSONSchemaGenerator2 = class {
  /** @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 = initializeContext2({
      processors: allProcessors2,
      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 process4(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;
    }
    extractDefs2(this.ctx, schema);
    const result = finalize2(this.ctx, schema);
    const { "~standard": _, ...plainResult } = result;
    return plainResult;
  }
};

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema.js
var json_schema_exports2 = {};

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js
var schemas_exports3 = {};
__export(schemas_exports3, {
  ZodAny: () => ZodAny2,
  ZodArray: () => ZodArray2,
  ZodBase64: () => ZodBase642,
  ZodBase64URL: () => ZodBase64URL2,
  ZodBigInt: () => ZodBigInt2,
  ZodBigIntFormat: () => ZodBigIntFormat2,
  ZodBoolean: () => ZodBoolean2,
  ZodCIDRv4: () => ZodCIDRv42,
  ZodCIDRv6: () => ZodCIDRv62,
  ZodCUID: () => ZodCUID3,
  ZodCUID2: () => ZodCUID22,
  ZodCatch: () => ZodCatch2,
  ZodCodec: () => ZodCodec2,
  ZodCustom: () => ZodCustom2,
  ZodCustomStringFormat: () => ZodCustomStringFormat2,
  ZodDate: () => ZodDate2,
  ZodDefault: () => ZodDefault2,
  ZodDiscriminatedUnion: () => ZodDiscriminatedUnion2,
  ZodE164: () => ZodE1642,
  ZodEmail: () => ZodEmail2,
  ZodEmoji: () => ZodEmoji2,
  ZodEnum: () => ZodEnum2,
  ZodExactOptional: () => ZodExactOptional2,
  ZodFile: () => ZodFile2,
  ZodFunction: () => ZodFunction2,
  ZodGUID: () => ZodGUID2,
  ZodIPv4: () => ZodIPv42,
  ZodIPv6: () => ZodIPv62,
  ZodIntersection: () => ZodIntersection2,
  ZodJWT: () => ZodJWT2,
  ZodKSUID: () => ZodKSUID2,
  ZodLazy: () => ZodLazy2,
  ZodLiteral: () => ZodLiteral2,
  ZodMAC: () => ZodMAC2,
  ZodMap: () => ZodMap2,
  ZodNaN: () => ZodNaN2,
  ZodNanoID: () => ZodNanoID2,
  ZodNever: () => ZodNever2,
  ZodNonOptional: () => ZodNonOptional2,
  ZodNull: () => ZodNull2,
  ZodNullable: () => ZodNullable2,
  ZodNumber: () => ZodNumber2,
  ZodNumberFormat: () => ZodNumberFormat2,
  ZodObject: () => ZodObject2,
  ZodOptional: () => ZodOptional2,
  ZodPipe: () => ZodPipe2,
  ZodPrefault: () => ZodPrefault2,
  ZodPreprocess: () => ZodPreprocess2,
  ZodPromise: () => ZodPromise2,
  ZodReadonly: () => ZodReadonly2,
  ZodRecord: () => ZodRecord2,
  ZodSet: () => ZodSet2,
  ZodString: () => ZodString2,
  ZodStringFormat: () => ZodStringFormat2,
  ZodSuccess: () => ZodSuccess2,
  ZodSymbol: () => ZodSymbol2,
  ZodTemplateLiteral: () => ZodTemplateLiteral2,
  ZodTransform: () => ZodTransform2,
  ZodTuple: () => ZodTuple2,
  ZodType: () => ZodType2,
  ZodULID: () => ZodULID2,
  ZodURL: () => ZodURL2,
  ZodUUID: () => ZodUUID2,
  ZodUndefined: () => ZodUndefined2,
  ZodUnion: () => ZodUnion2,
  ZodUnknown: () => ZodUnknown2,
  ZodVoid: () => ZodVoid2,
  ZodXID: () => ZodXID2,
  ZodXor: () => ZodXor2,
  _ZodString: () => _ZodString2,
  _default: () => _default4,
  _function: () => _function2,
  any: () => any2,
  array: () => array2,
  base64: () => base644,
  base64url: () => base64url4,
  bigint: () => bigint5,
  boolean: () => boolean5,
  catch: () => _catch4,
  check: () => check2,
  cidrv4: () => cidrv44,
  cidrv6: () => cidrv64,
  codec: () => codec2,
  cuid: () => cuid5,
  cuid2: () => cuid24,
  custom: () => custom2,
  date: () => date7,
  describe: () => describe4,
  discriminatedUnion: () => discriminatedUnion2,
  e164: () => e1644,
  email: () => email4,
  emoji: () => emoji4,
  enum: () => _enum4,
  exactOptional: () => exactOptional2,
  file: () => file3,
  float32: () => float322,
  float64: () => float642,
  function: () => _function2,
  guid: () => guid4,
  hash: () => hash2,
  hex: () => hex4,
  hostname: () => hostname4,
  httpUrl: () => httpUrl2,
  instanceof: () => _instanceof2,
  int: () => int2,
  int32: () => int322,
  int64: () => int642,
  intersection: () => intersection2,
  invertCodec: () => invertCodec2,
  ipv4: () => ipv44,
  ipv6: () => ipv64,
  json: () => json2,
  jwt: () => jwt2,
  keyof: () => keyof2,
  ksuid: () => ksuid4,
  lazy: () => lazy2,
  literal: () => literal2,
  looseObject: () => looseObject2,
  looseRecord: () => looseRecord2,
  mac: () => mac4,
  map: () => map2,
  meta: () => meta4,
  nan: () => nan2,
  nanoid: () => nanoid4,
  nativeEnum: () => nativeEnum2,
  never: () => never2,
  nonoptional: () => nonoptional2,
  null: () => _null6,
  nullable: () => nullable2,
  nullish: () => nullish4,
  number: () => number5,
  object: () => object2,
  optional: () => optional2,
  partialRecord: () => partialRecord2,
  pipe: () => pipe2,
  prefault: () => prefault2,
  preprocess: () => preprocess2,
  promise: () => promise2,
  readonly: () => readonly2,
  record: () => record2,
  refine: () => refine2,
  set: () => set2,
  strictObject: () => strictObject2,
  string: () => string5,
  stringFormat: () => stringFormat2,
  stringbool: () => stringbool2,
  success: () => success2,
  superRefine: () => superRefine2,
  symbol: () => symbol2,
  templateLiteral: () => templateLiteral2,
  transform: () => transform2,
  tuple: () => tuple2,
  uint32: () => uint322,
  uint64: () => uint642,
  ulid: () => ulid4,
  undefined: () => _undefined6,
  union: () => union2,
  unknown: () => unknown2,
  url: () => url5,
  uuid: () => uuid5,
  uuidv4: () => uuidv42,
  uuidv6: () => uuidv62,
  uuidv7: () => uuidv72,
  void: () => _void4,
  xid: () => xid4,
  xor: () => xor2
});

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/checks.js
var checks_exports3 = {};
__export(checks_exports3, {
  endsWith: () => _endsWith2,
  gt: () => _gt2,
  gte: () => _gte2,
  includes: () => _includes2,
  length: () => _length2,
  lowercase: () => _lowercase2,
  lt: () => _lt2,
  lte: () => _lte2,
  maxLength: () => _maxLength2,
  maxSize: () => _maxSize2,
  mime: () => _mime2,
  minLength: () => _minLength2,
  minSize: () => _minSize2,
  multipleOf: () => _multipleOf2,
  negative: () => _negative2,
  nonnegative: () => _nonnegative2,
  nonpositive: () => _nonpositive2,
  normalize: () => _normalize2,
  overwrite: () => _overwrite2,
  positive: () => _positive2,
  property: () => _property2,
  regex: () => _regex2,
  size: () => _size2,
  slugify: () => _slugify2,
  startsWith: () => _startsWith2,
  toLowerCase: () => _toLowerCase2,
  toUpperCase: () => _toUpperCase2,
  trim: () => _trim2,
  uppercase: () => _uppercase2
});

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/iso.js
var iso_exports2 = {};
__export(iso_exports2, {
  ZodISODate: () => ZodISODate2,
  ZodISODateTime: () => ZodISODateTime2,
  ZodISODuration: () => ZodISODuration2,
  ZodISOTime: () => ZodISOTime2,
  date: () => date6,
  datetime: () => datetime4,
  duration: () => duration4,
  time: () => time4
});
var ZodISODateTime2 = /* @__PURE__ */ $constructor2("ZodISODateTime", (inst, def) => {
  $ZodISODateTime2.init(inst, def);
  ZodStringFormat2.init(inst, def);
});
function datetime4(params) {
  return _isoDateTime2(ZodISODateTime2, params);
}
var ZodISODate2 = /* @__PURE__ */ $constructor2("ZodISODate", (inst, def) => {
  $ZodISODate2.init(inst, def);
  ZodStringFormat2.init(inst, def);
});
function date6(params) {
  return _isoDate2(ZodISODate2, params);
}
var ZodISOTime2 = /* @__PURE__ */ $constructor2("ZodISOTime", (inst, def) => {
  $ZodISOTime2.init(inst, def);
  ZodStringFormat2.init(inst, def);
});
function time4(params) {
  return _isoTime2(ZodISOTime2, params);
}
var ZodISODuration2 = /* @__PURE__ */ $constructor2("ZodISODuration", (inst, def) => {
  $ZodISODuration2.init(inst, def);
  ZodStringFormat2.init(inst, def);
});
function duration4(params) {
  return _isoDuration2(ZodISODuration2, params);
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/errors.js
var initializer4 = (inst, issues) => {
  $ZodError2.init(inst, issues);
  inst.name = "ZodError";
  Object.defineProperties(inst, {
    format: {
      value: (mapper) => formatError2(inst, mapper)
      // enumerable: false,
    },
    flatten: {
      value: (mapper) => flattenError2(inst, mapper)
      // enumerable: false,
    },
    addIssue: {
      value: (issue3) => {
        inst.issues.push(issue3);
        inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer2, 2);
      }
      // enumerable: false,
    },
    addIssues: {
      value: (issues2) => {
        inst.issues.push(...issues2);
        inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer2, 2);
      }
      // enumerable: false,
    },
    isEmpty: {
      get() {
        return inst.issues.length === 0;
      }
      // enumerable: false,
    }
  });
};
var ZodError2 = /* @__PURE__ */ $constructor2("ZodError", initializer4);
var ZodRealError2 = /* @__PURE__ */ $constructor2("ZodError", initializer4, {
  Parent: Error
});

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/parse.js
var parse6 = /* @__PURE__ */ _parse2(ZodRealError2);
var parseAsync4 = /* @__PURE__ */ _parseAsync2(ZodRealError2);
var safeParse4 = /* @__PURE__ */ _safeParse2(ZodRealError2);
var safeParseAsync4 = /* @__PURE__ */ _safeParseAsync2(ZodRealError2);
var encode4 = /* @__PURE__ */ _encode2(ZodRealError2);
var decode4 = /* @__PURE__ */ _decode2(ZodRealError2);
var encodeAsync4 = /* @__PURE__ */ _encodeAsync2(ZodRealError2);
var decodeAsync4 = /* @__PURE__ */ _decodeAsync2(ZodRealError2);
var safeEncode4 = /* @__PURE__ */ _safeEncode2(ZodRealError2);
var safeDecode4 = /* @__PURE__ */ _safeDecode2(ZodRealError2);
var safeEncodeAsync4 = /* @__PURE__ */ _safeEncodeAsync2(ZodRealError2);
var safeDecodeAsync4 = /* @__PURE__ */ _safeDecodeAsync2(ZodRealError2);

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js
var _installedGroups2 = /* @__PURE__ */ new WeakMap();
function _installLazyMethods2(inst, group, methods) {
  const proto2 = Object.getPrototypeOf(inst);
  let installed = _installedGroups2.get(proto2);
  if (!installed) {
    installed = /* @__PURE__ */ new Set();
    _installedGroups2.set(proto2, installed);
  }
  if (installed.has(group))
    return;
  installed.add(group);
  for (const key in methods) {
    const fn = methods[key];
    Object.defineProperty(proto2, 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
        });
      }
    });
  }
}
var ZodType2 = /* @__PURE__ */ $constructor2("ZodType", (inst, def) => {
  $ZodType2.init(inst, def);
  Object.assign(inst["~standard"], {
    jsonSchema: {
      input: createStandardJSONSchemaMethod2(inst, "input"),
      output: createStandardJSONSchemaMethod2(inst, "output")
    }
  });
  inst.toJSONSchema = createToJSONSchemaMethod2(inst, {});
  inst.def = def;
  inst.type = def.type;
  Object.defineProperty(inst, "_def", { value: def });
  inst.parse = (data, params) => parse6(inst, data, params, { callee: inst.parse });
  inst.safeParse = (data, params) => safeParse4(inst, data, params);
  inst.parseAsync = async (data, params) => parseAsync4(inst, data, params, { callee: inst.parseAsync });
  inst.safeParseAsync = async (data, params) => safeParseAsync4(inst, data, params);
  inst.spa = inst.safeParseAsync;
  inst.encode = (data, params) => encode4(inst, data, params);
  inst.decode = (data, params) => decode4(inst, data, params);
  inst.encodeAsync = async (data, params) => encodeAsync4(inst, data, params);
  inst.decodeAsync = async (data, params) => decodeAsync4(inst, data, params);
  inst.safeEncode = (data, params) => safeEncode4(inst, data, params);
  inst.safeDecode = (data, params) => safeDecode4(inst, data, params);
  inst.safeEncodeAsync = async (data, params) => safeEncodeAsync4(inst, data, params);
  inst.safeDecodeAsync = async (data, params) => safeDecodeAsync4(inst, data, params);
  _installLazyMethods2(inst, "ZodType", {
    check(...chks) {
      const def2 = this.def;
      return this.clone(util_exports2.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 clone2(this, def2, params);
    },
    brand() {
      return this;
    },
    register(reg, meta5) {
      reg.add(this, meta5);
      return this;
    },
    refine(check3, params) {
      return this.check(refine2(check3, params));
    },
    superRefine(refinement, params) {
      return this.check(superRefine2(refinement, params));
    },
    overwrite(fn) {
      return this.check(_overwrite2(fn));
    },
    optional() {
      return optional2(this);
    },
    exactOptional() {
      return exactOptional2(this);
    },
    nullable() {
      return nullable2(this);
    },
    nullish() {
      return optional2(nullable2(this));
    },
    nonoptional(params) {
      return nonoptional2(this, params);
    },
    array() {
      return array2(this);
    },
    or(arg) {
      return union2([this, arg]);
    },
    and(arg) {
      return intersection2(this, arg);
    },
    transform(tx) {
      return pipe2(this, transform2(tx));
    },
    default(d) {
      return _default4(this, d);
    },
    prefault(d) {
      return prefault2(this, d);
    },
    catch(params) {
      return _catch4(this, params);
    },
    pipe(target) {
      return pipe2(this, target);
    },
    readonly() {
      return readonly2(this);
    },
    describe(description) {
      const cl = this.clone();
      globalRegistry2.add(cl, { description });
      return cl;
    },
    meta(...args) {
      if (args.length === 0)
        return globalRegistry2.get(this);
      const cl = this.clone();
      globalRegistry2.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 globalRegistry2.get(inst)?.description;
    },
    configurable: true
  });
  return inst;
});
var _ZodString2 = /* @__PURE__ */ $constructor2("_ZodString", (inst, def) => {
  $ZodString2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => stringProcessor2(inst, ctx, json3, params);
  const bag = inst._zod.bag;
  inst.format = bag.format ?? null;
  inst.minLength = bag.minimum ?? null;
  inst.maxLength = bag.maximum ?? null;
  _installLazyMethods2(inst, "_ZodString", {
    regex(...args) {
      return this.check(_regex2(...args));
    },
    includes(...args) {
      return this.check(_includes2(...args));
    },
    startsWith(...args) {
      return this.check(_startsWith2(...args));
    },
    endsWith(...args) {
      return this.check(_endsWith2(...args));
    },
    min(...args) {
      return this.check(_minLength2(...args));
    },
    max(...args) {
      return this.check(_maxLength2(...args));
    },
    length(...args) {
      return this.check(_length2(...args));
    },
    nonempty(...args) {
      return this.check(_minLength2(1, ...args));
    },
    lowercase(params) {
      return this.check(_lowercase2(params));
    },
    uppercase(params) {
      return this.check(_uppercase2(params));
    },
    trim() {
      return this.check(_trim2());
    },
    normalize(...args) {
      return this.check(_normalize2(...args));
    },
    toLowerCase() {
      return this.check(_toLowerCase2());
    },
    toUpperCase() {
      return this.check(_toUpperCase2());
    },
    slugify() {
      return this.check(_slugify2());
    }
  });
});
var ZodString2 = /* @__PURE__ */ $constructor2("ZodString", (inst, def) => {
  $ZodString2.init(inst, def);
  _ZodString2.init(inst, def);
  inst.email = (params) => inst.check(_email2(ZodEmail2, params));
  inst.url = (params) => inst.check(_url2(ZodURL2, params));
  inst.jwt = (params) => inst.check(_jwt2(ZodJWT2, params));
  inst.emoji = (params) => inst.check(_emoji4(ZodEmoji2, params));
  inst.guid = (params) => inst.check(_guid2(ZodGUID2, params));
  inst.uuid = (params) => inst.check(_uuid2(ZodUUID2, params));
  inst.uuidv4 = (params) => inst.check(_uuidv42(ZodUUID2, params));
  inst.uuidv6 = (params) => inst.check(_uuidv62(ZodUUID2, params));
  inst.uuidv7 = (params) => inst.check(_uuidv72(ZodUUID2, params));
  inst.nanoid = (params) => inst.check(_nanoid2(ZodNanoID2, params));
  inst.guid = (params) => inst.check(_guid2(ZodGUID2, params));
  inst.cuid = (params) => inst.check(_cuid3(ZodCUID3, params));
  inst.cuid2 = (params) => inst.check(_cuid22(ZodCUID22, params));
  inst.ulid = (params) => inst.check(_ulid2(ZodULID2, params));
  inst.base64 = (params) => inst.check(_base642(ZodBase642, params));
  inst.base64url = (params) => inst.check(_base64url2(ZodBase64URL2, params));
  inst.xid = (params) => inst.check(_xid2(ZodXID2, params));
  inst.ksuid = (params) => inst.check(_ksuid2(ZodKSUID2, params));
  inst.ipv4 = (params) => inst.check(_ipv42(ZodIPv42, params));
  inst.ipv6 = (params) => inst.check(_ipv62(ZodIPv62, params));
  inst.cidrv4 = (params) => inst.check(_cidrv42(ZodCIDRv42, params));
  inst.cidrv6 = (params) => inst.check(_cidrv62(ZodCIDRv62, params));
  inst.e164 = (params) => inst.check(_e1642(ZodE1642, params));
  inst.datetime = (params) => inst.check(datetime4(params));
  inst.date = (params) => inst.check(date6(params));
  inst.time = (params) => inst.check(time4(params));
  inst.duration = (params) => inst.check(duration4(params));
});
function string5(params) {
  return _string2(ZodString2, params);
}
var ZodStringFormat2 = /* @__PURE__ */ $constructor2("ZodStringFormat", (inst, def) => {
  $ZodStringFormat2.init(inst, def);
  _ZodString2.init(inst, def);
});
var ZodEmail2 = /* @__PURE__ */ $constructor2("ZodEmail", (inst, def) => {
  $ZodEmail2.init(inst, def);
  ZodStringFormat2.init(inst, def);
});
function email4(params) {
  return _email2(ZodEmail2, params);
}
var ZodGUID2 = /* @__PURE__ */ $constructor2("ZodGUID", (inst, def) => {
  $ZodGUID2.init(inst, def);
  ZodStringFormat2.init(inst, def);
});
function guid4(params) {
  return _guid2(ZodGUID2, params);
}
var ZodUUID2 = /* @__PURE__ */ $constructor2("ZodUUID", (inst, def) => {
  $ZodUUID2.init(inst, def);
  ZodStringFormat2.init(inst, def);
});
function uuid5(params) {
  return _uuid2(ZodUUID2, params);
}
function uuidv42(params) {
  return _uuidv42(ZodUUID2, params);
}
function uuidv62(params) {
  return _uuidv62(ZodUUID2, params);
}
function uuidv72(params) {
  return _uuidv72(ZodUUID2, params);
}
var ZodURL2 = /* @__PURE__ */ $constructor2("ZodURL", (inst, def) => {
  $ZodURL2.init(inst, def);
  ZodStringFormat2.init(inst, def);
});
function url5(params) {
  return _url2(ZodURL2, params);
}
function httpUrl2(params) {
  return _url2(ZodURL2, {
    protocol: regexes_exports2.httpProtocol,
    hostname: regexes_exports2.domain,
    ...util_exports2.normalizeParams(params)
  });
}
var ZodEmoji2 = /* @__PURE__ */ $constructor2("ZodEmoji", (inst, def) => {
  $ZodEmoji2.init(inst, def);
  ZodStringFormat2.init(inst, def);
});
function emoji4(params) {
  return _emoji4(ZodEmoji2, params);
}
var ZodNanoID2 = /* @__PURE__ */ $constructor2("ZodNanoID", (inst, def) => {
  $ZodNanoID2.init(inst, def);
  ZodStringFormat2.init(inst, def);
});
function nanoid4(params) {
  return _nanoid2(ZodNanoID2, params);
}
var ZodCUID3 = /* @__PURE__ */ $constructor2("ZodCUID", (inst, def) => {
  $ZodCUID3.init(inst, def);
  ZodStringFormat2.init(inst, def);
});
function cuid5(params) {
  return _cuid3(ZodCUID3, params);
}
var ZodCUID22 = /* @__PURE__ */ $constructor2("ZodCUID2", (inst, def) => {
  $ZodCUID22.init(inst, def);
  ZodStringFormat2.init(inst, def);
});
function cuid24(params) {
  return _cuid22(ZodCUID22, params);
}
var ZodULID2 = /* @__PURE__ */ $constructor2("ZodULID", (inst, def) => {
  $ZodULID2.init(inst, def);
  ZodStringFormat2.init(inst, def);
});
function ulid4(params) {
  return _ulid2(ZodULID2, params);
}
var ZodXID2 = /* @__PURE__ */ $constructor2("ZodXID", (inst, def) => {
  $ZodXID2.init(inst, def);
  ZodStringFormat2.init(inst, def);
});
function xid4(params) {
  return _xid2(ZodXID2, params);
}
var ZodKSUID2 = /* @__PURE__ */ $constructor2("ZodKSUID", (inst, def) => {
  $ZodKSUID2.init(inst, def);
  ZodStringFormat2.init(inst, def);
});
function ksuid4(params) {
  return _ksuid2(ZodKSUID2, params);
}
var ZodIPv42 = /* @__PURE__ */ $constructor2("ZodIPv4", (inst, def) => {
  $ZodIPv42.init(inst, def);
  ZodStringFormat2.init(inst, def);
});
function ipv44(params) {
  return _ipv42(ZodIPv42, params);
}
var ZodMAC2 = /* @__PURE__ */ $constructor2("ZodMAC", (inst, def) => {
  $ZodMAC2.init(inst, def);
  ZodStringFormat2.init(inst, def);
});
function mac4(params) {
  return _mac2(ZodMAC2, params);
}
var ZodIPv62 = /* @__PURE__ */ $constructor2("ZodIPv6", (inst, def) => {
  $ZodIPv62.init(inst, def);
  ZodStringFormat2.init(inst, def);
});
function ipv64(params) {
  return _ipv62(ZodIPv62, params);
}
var ZodCIDRv42 = /* @__PURE__ */ $constructor2("ZodCIDRv4", (inst, def) => {
  $ZodCIDRv42.init(inst, def);
  ZodStringFormat2.init(inst, def);
});
function cidrv44(params) {
  return _cidrv42(ZodCIDRv42, params);
}
var ZodCIDRv62 = /* @__PURE__ */ $constructor2("ZodCIDRv6", (inst, def) => {
  $ZodCIDRv62.init(inst, def);
  ZodStringFormat2.init(inst, def);
});
function cidrv64(params) {
  return _cidrv62(ZodCIDRv62, params);
}
var ZodBase642 = /* @__PURE__ */ $constructor2("ZodBase64", (inst, def) => {
  $ZodBase642.init(inst, def);
  ZodStringFormat2.init(inst, def);
});
function base644(params) {
  return _base642(ZodBase642, params);
}
var ZodBase64URL2 = /* @__PURE__ */ $constructor2("ZodBase64URL", (inst, def) => {
  $ZodBase64URL2.init(inst, def);
  ZodStringFormat2.init(inst, def);
});
function base64url4(params) {
  return _base64url2(ZodBase64URL2, params);
}
var ZodE1642 = /* @__PURE__ */ $constructor2("ZodE164", (inst, def) => {
  $ZodE1642.init(inst, def);
  ZodStringFormat2.init(inst, def);
});
function e1644(params) {
  return _e1642(ZodE1642, params);
}
var ZodJWT2 = /* @__PURE__ */ $constructor2("ZodJWT", (inst, def) => {
  $ZodJWT2.init(inst, def);
  ZodStringFormat2.init(inst, def);
});
function jwt2(params) {
  return _jwt2(ZodJWT2, params);
}
var ZodCustomStringFormat2 = /* @__PURE__ */ $constructor2("ZodCustomStringFormat", (inst, def) => {
  $ZodCustomStringFormat2.init(inst, def);
  ZodStringFormat2.init(inst, def);
});
function stringFormat2(format5, fnOrRegex, _params = {}) {
  return _stringFormat2(ZodCustomStringFormat2, format5, fnOrRegex, _params);
}
function hostname4(_params) {
  return _stringFormat2(ZodCustomStringFormat2, "hostname", regexes_exports2.hostname, _params);
}
function hex4(_params) {
  return _stringFormat2(ZodCustomStringFormat2, "hex", regexes_exports2.hex, _params);
}
function hash2(alg, params) {
  const enc = params?.enc ?? "hex";
  const format5 = `${alg}_${enc}`;
  const regex3 = regexes_exports2[format5];
  if (!regex3)
    throw new Error(`Unrecognized hash format: ${format5}`);
  return _stringFormat2(ZodCustomStringFormat2, format5, regex3, params);
}
var ZodNumber2 = /* @__PURE__ */ $constructor2("ZodNumber", (inst, def) => {
  $ZodNumber2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => numberProcessor2(inst, ctx, json3, params);
  _installLazyMethods2(inst, "ZodNumber", {
    gt(value, params) {
      return this.check(_gt2(value, params));
    },
    gte(value, params) {
      return this.check(_gte2(value, params));
    },
    min(value, params) {
      return this.check(_gte2(value, params));
    },
    lt(value, params) {
      return this.check(_lt2(value, params));
    },
    lte(value, params) {
      return this.check(_lte2(value, params));
    },
    max(value, params) {
      return this.check(_lte2(value, params));
    },
    int(params) {
      return this.check(int2(params));
    },
    safe(params) {
      return this.check(int2(params));
    },
    positive(params) {
      return this.check(_gt2(0, params));
    },
    nonnegative(params) {
      return this.check(_gte2(0, params));
    },
    negative(params) {
      return this.check(_lt2(0, params));
    },
    nonpositive(params) {
      return this.check(_lte2(0, params));
    },
    multipleOf(value, params) {
      return this.check(_multipleOf2(value, params));
    },
    step(value, params) {
      return this.check(_multipleOf2(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 number5(params) {
  return _number2(ZodNumber2, params);
}
var ZodNumberFormat2 = /* @__PURE__ */ $constructor2("ZodNumberFormat", (inst, def) => {
  $ZodNumberFormat2.init(inst, def);
  ZodNumber2.init(inst, def);
});
function int2(params) {
  return _int2(ZodNumberFormat2, params);
}
function float322(params) {
  return _float322(ZodNumberFormat2, params);
}
function float642(params) {
  return _float642(ZodNumberFormat2, params);
}
function int322(params) {
  return _int322(ZodNumberFormat2, params);
}
function uint322(params) {
  return _uint322(ZodNumberFormat2, params);
}
var ZodBoolean2 = /* @__PURE__ */ $constructor2("ZodBoolean", (inst, def) => {
  $ZodBoolean2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => booleanProcessor2(inst, ctx, json3, params);
});
function boolean5(params) {
  return _boolean2(ZodBoolean2, params);
}
var ZodBigInt2 = /* @__PURE__ */ $constructor2("ZodBigInt", (inst, def) => {
  $ZodBigInt2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => bigintProcessor2(inst, ctx, json3, params);
  inst.gte = (value, params) => inst.check(_gte2(value, params));
  inst.min = (value, params) => inst.check(_gte2(value, params));
  inst.gt = (value, params) => inst.check(_gt2(value, params));
  inst.gte = (value, params) => inst.check(_gte2(value, params));
  inst.min = (value, params) => inst.check(_gte2(value, params));
  inst.lt = (value, params) => inst.check(_lt2(value, params));
  inst.lte = (value, params) => inst.check(_lte2(value, params));
  inst.max = (value, params) => inst.check(_lte2(value, params));
  inst.positive = (params) => inst.check(_gt2(BigInt(0), params));
  inst.negative = (params) => inst.check(_lt2(BigInt(0), params));
  inst.nonpositive = (params) => inst.check(_lte2(BigInt(0), params));
  inst.nonnegative = (params) => inst.check(_gte2(BigInt(0), params));
  inst.multipleOf = (value, params) => inst.check(_multipleOf2(value, params));
  const bag = inst._zod.bag;
  inst.minValue = bag.minimum ?? null;
  inst.maxValue = bag.maximum ?? null;
  inst.format = bag.format ?? null;
});
function bigint5(params) {
  return _bigint2(ZodBigInt2, params);
}
var ZodBigIntFormat2 = /* @__PURE__ */ $constructor2("ZodBigIntFormat", (inst, def) => {
  $ZodBigIntFormat2.init(inst, def);
  ZodBigInt2.init(inst, def);
});
function int642(params) {
  return _int642(ZodBigIntFormat2, params);
}
function uint642(params) {
  return _uint642(ZodBigIntFormat2, params);
}
var ZodSymbol2 = /* @__PURE__ */ $constructor2("ZodSymbol", (inst, def) => {
  $ZodSymbol2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => symbolProcessor2(inst, ctx, json3, params);
});
function symbol2(params) {
  return _symbol2(ZodSymbol2, params);
}
var ZodUndefined2 = /* @__PURE__ */ $constructor2("ZodUndefined", (inst, def) => {
  $ZodUndefined2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => undefinedProcessor2(inst, ctx, json3, params);
});
function _undefined6(params) {
  return _undefined5(ZodUndefined2, params);
}
var ZodNull2 = /* @__PURE__ */ $constructor2("ZodNull", (inst, def) => {
  $ZodNull2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => nullProcessor2(inst, ctx, json3, params);
});
function _null6(params) {
  return _null5(ZodNull2, params);
}
var ZodAny2 = /* @__PURE__ */ $constructor2("ZodAny", (inst, def) => {
  $ZodAny2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => anyProcessor2(inst, ctx, json3, params);
});
function any2() {
  return _any2(ZodAny2);
}
var ZodUnknown2 = /* @__PURE__ */ $constructor2("ZodUnknown", (inst, def) => {
  $ZodUnknown2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => unknownProcessor2(inst, ctx, json3, params);
});
function unknown2() {
  return _unknown2(ZodUnknown2);
}
var ZodNever2 = /* @__PURE__ */ $constructor2("ZodNever", (inst, def) => {
  $ZodNever2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => neverProcessor2(inst, ctx, json3, params);
});
function never2(params) {
  return _never2(ZodNever2, params);
}
var ZodVoid2 = /* @__PURE__ */ $constructor2("ZodVoid", (inst, def) => {
  $ZodVoid2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => voidProcessor2(inst, ctx, json3, params);
});
function _void4(params) {
  return _void3(ZodVoid2, params);
}
var ZodDate2 = /* @__PURE__ */ $constructor2("ZodDate", (inst, def) => {
  $ZodDate2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => dateProcessor2(inst, ctx, json3, params);
  inst.min = (value, params) => inst.check(_gte2(value, params));
  inst.max = (value, params) => inst.check(_lte2(value, params));
  const c2 = inst._zod.bag;
  inst.minDate = c2.minimum ? new Date(c2.minimum) : null;
  inst.maxDate = c2.maximum ? new Date(c2.maximum) : null;
});
function date7(params) {
  return _date2(ZodDate2, params);
}
var ZodArray2 = /* @__PURE__ */ $constructor2("ZodArray", (inst, def) => {
  $ZodArray2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => arrayProcessor2(inst, ctx, json3, params);
  inst.element = def.element;
  _installLazyMethods2(inst, "ZodArray", {
    min(n, params) {
      return this.check(_minLength2(n, params));
    },
    nonempty(params) {
      return this.check(_minLength2(1, params));
    },
    max(n, params) {
      return this.check(_maxLength2(n, params));
    },
    length(n, params) {
      return this.check(_length2(n, params));
    },
    unwrap() {
      return this.element;
    }
  });
});
function array2(element, params) {
  return _array2(ZodArray2, element, params);
}
function keyof2(schema) {
  const shape = schema._zod.def.shape;
  return _enum4(Object.keys(shape));
}
var ZodObject2 = /* @__PURE__ */ $constructor2("ZodObject", (inst, def) => {
  $ZodObjectJIT2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => objectProcessor2(inst, ctx, json3, params);
  util_exports2.defineLazy(inst, "shape", () => {
    return def.shape;
  });
  _installLazyMethods2(inst, "ZodObject", {
    keyof() {
      return _enum4(Object.keys(this._zod.def.shape));
    },
    catchall(catchall) {
      return this.clone({ ...this._zod.def, catchall });
    },
    passthrough() {
      return this.clone({ ...this._zod.def, catchall: unknown2() });
    },
    loose() {
      return this.clone({ ...this._zod.def, catchall: unknown2() });
    },
    strict() {
      return this.clone({ ...this._zod.def, catchall: never2() });
    },
    strip() {
      return this.clone({ ...this._zod.def, catchall: void 0 });
    },
    extend(incoming) {
      return util_exports2.extend(this, incoming);
    },
    safeExtend(incoming) {
      return util_exports2.safeExtend(this, incoming);
    },
    merge(other) {
      return util_exports2.merge(this, other);
    },
    pick(mask) {
      return util_exports2.pick(this, mask);
    },
    omit(mask) {
      return util_exports2.omit(this, mask);
    },
    partial(...args) {
      return util_exports2.partial(ZodOptional2, this, args[0]);
    },
    required(...args) {
      return util_exports2.required(ZodNonOptional2, this, args[0]);
    }
  });
});
function object2(shape, params) {
  const def = {
    type: "object",
    shape: shape ?? {},
    ...util_exports2.normalizeParams(params)
  };
  return new ZodObject2(def);
}
function strictObject2(shape, params) {
  return new ZodObject2({
    type: "object",
    shape,
    catchall: never2(),
    ...util_exports2.normalizeParams(params)
  });
}
function looseObject2(shape, params) {
  return new ZodObject2({
    type: "object",
    shape,
    catchall: unknown2(),
    ...util_exports2.normalizeParams(params)
  });
}
var ZodUnion2 = /* @__PURE__ */ $constructor2("ZodUnion", (inst, def) => {
  $ZodUnion2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => unionProcessor2(inst, ctx, json3, params);
  inst.options = def.options;
});
function union2(options, params) {
  return new ZodUnion2({
    type: "union",
    options,
    ...util_exports2.normalizeParams(params)
  });
}
var ZodXor2 = /* @__PURE__ */ $constructor2("ZodXor", (inst, def) => {
  ZodUnion2.init(inst, def);
  $ZodXor2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => unionProcessor2(inst, ctx, json3, params);
  inst.options = def.options;
});
function xor2(options, params) {
  return new ZodXor2({
    type: "union",
    options,
    inclusive: false,
    ...util_exports2.normalizeParams(params)
  });
}
var ZodDiscriminatedUnion2 = /* @__PURE__ */ $constructor2("ZodDiscriminatedUnion", (inst, def) => {
  ZodUnion2.init(inst, def);
  $ZodDiscriminatedUnion2.init(inst, def);
});
function discriminatedUnion2(discriminator, options, params) {
  return new ZodDiscriminatedUnion2({
    type: "union",
    options,
    discriminator,
    ...util_exports2.normalizeParams(params)
  });
}
var ZodIntersection2 = /* @__PURE__ */ $constructor2("ZodIntersection", (inst, def) => {
  $ZodIntersection2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => intersectionProcessor2(inst, ctx, json3, params);
});
function intersection2(left, right) {
  return new ZodIntersection2({
    type: "intersection",
    left,
    right
  });
}
var ZodTuple2 = /* @__PURE__ */ $constructor2("ZodTuple", (inst, def) => {
  $ZodTuple2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => tupleProcessor2(inst, ctx, json3, params);
  inst.rest = (rest) => inst.clone({
    ...inst._zod.def,
    rest
  });
});
function tuple2(items, _paramsOrRest, _params) {
  const hasRest = _paramsOrRest instanceof $ZodType2;
  const params = hasRest ? _params : _paramsOrRest;
  const rest = hasRest ? _paramsOrRest : null;
  return new ZodTuple2({
    type: "tuple",
    items,
    rest,
    ...util_exports2.normalizeParams(params)
  });
}
var ZodRecord2 = /* @__PURE__ */ $constructor2("ZodRecord", (inst, def) => {
  $ZodRecord2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => recordProcessor2(inst, ctx, json3, params);
  inst.keyType = def.keyType;
  inst.valueType = def.valueType;
});
function record2(keyType, valueType, params) {
  if (!valueType || !valueType._zod) {
    return new ZodRecord2({
      type: "record",
      keyType: string5(),
      valueType: keyType,
      ...util_exports2.normalizeParams(valueType)
    });
  }
  return new ZodRecord2({
    type: "record",
    keyType,
    valueType,
    ...util_exports2.normalizeParams(params)
  });
}
function partialRecord2(keyType, valueType, params) {
  const k = clone2(keyType);
  k._zod.values = void 0;
  return new ZodRecord2({
    type: "record",
    keyType: k,
    valueType,
    ...util_exports2.normalizeParams(params)
  });
}
function looseRecord2(keyType, valueType, params) {
  return new ZodRecord2({
    type: "record",
    keyType,
    valueType,
    mode: "loose",
    ...util_exports2.normalizeParams(params)
  });
}
var ZodMap2 = /* @__PURE__ */ $constructor2("ZodMap", (inst, def) => {
  $ZodMap2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => mapProcessor2(inst, ctx, json3, params);
  inst.keyType = def.keyType;
  inst.valueType = def.valueType;
  inst.min = (...args) => inst.check(_minSize2(...args));
  inst.nonempty = (params) => inst.check(_minSize2(1, params));
  inst.max = (...args) => inst.check(_maxSize2(...args));
  inst.size = (...args) => inst.check(_size2(...args));
});
function map2(keyType, valueType, params) {
  return new ZodMap2({
    type: "map",
    keyType,
    valueType,
    ...util_exports2.normalizeParams(params)
  });
}
var ZodSet2 = /* @__PURE__ */ $constructor2("ZodSet", (inst, def) => {
  $ZodSet2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => setProcessor2(inst, ctx, json3, params);
  inst.min = (...args) => inst.check(_minSize2(...args));
  inst.nonempty = (params) => inst.check(_minSize2(1, params));
  inst.max = (...args) => inst.check(_maxSize2(...args));
  inst.size = (...args) => inst.check(_size2(...args));
});
function set2(valueType, params) {
  return new ZodSet2({
    type: "set",
    valueType,
    ...util_exports2.normalizeParams(params)
  });
}
var ZodEnum2 = /* @__PURE__ */ $constructor2("ZodEnum", (inst, def) => {
  $ZodEnum2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => enumProcessor2(inst, ctx, json3, 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 ZodEnum2({
      ...def,
      checks: [],
      ...util_exports2.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 ZodEnum2({
      ...def,
      checks: [],
      ...util_exports2.normalizeParams(params),
      entries: newEntries
    });
  };
});
function _enum4(values, params) {
  const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
  return new ZodEnum2({
    type: "enum",
    entries,
    ...util_exports2.normalizeParams(params)
  });
}
function nativeEnum2(entries, params) {
  return new ZodEnum2({
    type: "enum",
    entries,
    ...util_exports2.normalizeParams(params)
  });
}
var ZodLiteral2 = /* @__PURE__ */ $constructor2("ZodLiteral", (inst, def) => {
  $ZodLiteral2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => literalProcessor2(inst, ctx, json3, 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 literal2(value, params) {
  return new ZodLiteral2({
    type: "literal",
    values: Array.isArray(value) ? value : [value],
    ...util_exports2.normalizeParams(params)
  });
}
var ZodFile2 = /* @__PURE__ */ $constructor2("ZodFile", (inst, def) => {
  $ZodFile2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => fileProcessor2(inst, ctx, json3, params);
  inst.min = (size, params) => inst.check(_minSize2(size, params));
  inst.max = (size, params) => inst.check(_maxSize2(size, params));
  inst.mime = (types3, params) => inst.check(_mime2(Array.isArray(types3) ? types3 : [types3], params));
});
function file3(params) {
  return _file2(ZodFile2, params);
}
var ZodTransform2 = /* @__PURE__ */ $constructor2("ZodTransform", (inst, def) => {
  $ZodTransform2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => transformProcessor2(inst, ctx, json3, params);
  inst._zod.parse = (payload, _ctx) => {
    if (_ctx.direction === "backward") {
      throw new $ZodEncodeError2(inst.constructor.name);
    }
    payload.addIssue = (issue3) => {
      if (typeof issue3 === "string") {
        payload.issues.push(util_exports2.issue(issue3, payload.value, def));
      } else {
        const _issue = issue3;
        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_exports2.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 transform2(fn) {
  return new ZodTransform2({
    type: "transform",
    transform: fn
  });
}
var ZodOptional2 = /* @__PURE__ */ $constructor2("ZodOptional", (inst, def) => {
  $ZodOptional2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => optionalProcessor2(inst, ctx, json3, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function optional2(innerType) {
  return new ZodOptional2({
    type: "optional",
    innerType
  });
}
var ZodExactOptional2 = /* @__PURE__ */ $constructor2("ZodExactOptional", (inst, def) => {
  $ZodExactOptional2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => optionalProcessor2(inst, ctx, json3, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function exactOptional2(innerType) {
  return new ZodExactOptional2({
    type: "optional",
    innerType
  });
}
var ZodNullable2 = /* @__PURE__ */ $constructor2("ZodNullable", (inst, def) => {
  $ZodNullable2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => nullableProcessor2(inst, ctx, json3, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function nullable2(innerType) {
  return new ZodNullable2({
    type: "nullable",
    innerType
  });
}
function nullish4(innerType) {
  return optional2(nullable2(innerType));
}
var ZodDefault2 = /* @__PURE__ */ $constructor2("ZodDefault", (inst, def) => {
  $ZodDefault2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => defaultProcessor2(inst, ctx, json3, params);
  inst.unwrap = () => inst._zod.def.innerType;
  inst.removeDefault = inst.unwrap;
});
function _default4(innerType, defaultValue) {
  return new ZodDefault2({
    type: "default",
    innerType,
    get defaultValue() {
      return typeof defaultValue === "function" ? defaultValue() : util_exports2.shallowClone(defaultValue);
    }
  });
}
var ZodPrefault2 = /* @__PURE__ */ $constructor2("ZodPrefault", (inst, def) => {
  $ZodPrefault2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => prefaultProcessor2(inst, ctx, json3, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function prefault2(innerType, defaultValue) {
  return new ZodPrefault2({
    type: "prefault",
    innerType,
    get defaultValue() {
      return typeof defaultValue === "function" ? defaultValue() : util_exports2.shallowClone(defaultValue);
    }
  });
}
var ZodNonOptional2 = /* @__PURE__ */ $constructor2("ZodNonOptional", (inst, def) => {
  $ZodNonOptional2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => nonoptionalProcessor2(inst, ctx, json3, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function nonoptional2(innerType, params) {
  return new ZodNonOptional2({
    type: "nonoptional",
    innerType,
    ...util_exports2.normalizeParams(params)
  });
}
var ZodSuccess2 = /* @__PURE__ */ $constructor2("ZodSuccess", (inst, def) => {
  $ZodSuccess2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => successProcessor2(inst, ctx, json3, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function success2(innerType) {
  return new ZodSuccess2({
    type: "success",
    innerType
  });
}
var ZodCatch2 = /* @__PURE__ */ $constructor2("ZodCatch", (inst, def) => {
  $ZodCatch2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => catchProcessor2(inst, ctx, json3, params);
  inst.unwrap = () => inst._zod.def.innerType;
  inst.removeCatch = inst.unwrap;
});
function _catch4(innerType, catchValue) {
  return new ZodCatch2({
    type: "catch",
    innerType,
    catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
  });
}
var ZodNaN2 = /* @__PURE__ */ $constructor2("ZodNaN", (inst, def) => {
  $ZodNaN2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => nanProcessor2(inst, ctx, json3, params);
});
function nan2(params) {
  return _nan2(ZodNaN2, params);
}
var ZodPipe2 = /* @__PURE__ */ $constructor2("ZodPipe", (inst, def) => {
  $ZodPipe2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => pipeProcessor2(inst, ctx, json3, params);
  inst.in = def.in;
  inst.out = def.out;
});
function pipe2(in_, out) {
  return new ZodPipe2({
    type: "pipe",
    in: in_,
    out
    // ...util.normalizeParams(params),
  });
}
var ZodCodec2 = /* @__PURE__ */ $constructor2("ZodCodec", (inst, def) => {
  ZodPipe2.init(inst, def);
  $ZodCodec2.init(inst, def);
});
function codec2(in_, out, params) {
  return new ZodCodec2({
    type: "pipe",
    in: in_,
    out,
    transform: params.decode,
    reverseTransform: params.encode
  });
}
function invertCodec2(codec3) {
  const def = codec3._zod.def;
  return new ZodCodec2({
    type: "pipe",
    in: def.out,
    out: def.in,
    transform: def.reverseTransform,
    reverseTransform: def.transform
  });
}
var ZodPreprocess2 = /* @__PURE__ */ $constructor2("ZodPreprocess", (inst, def) => {
  ZodPipe2.init(inst, def);
  $ZodPreprocess2.init(inst, def);
});
var ZodReadonly2 = /* @__PURE__ */ $constructor2("ZodReadonly", (inst, def) => {
  $ZodReadonly2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => readonlyProcessor2(inst, ctx, json3, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function readonly2(innerType) {
  return new ZodReadonly2({
    type: "readonly",
    innerType
  });
}
var ZodTemplateLiteral2 = /* @__PURE__ */ $constructor2("ZodTemplateLiteral", (inst, def) => {
  $ZodTemplateLiteral2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => templateLiteralProcessor2(inst, ctx, json3, params);
});
function templateLiteral2(parts, params) {
  return new ZodTemplateLiteral2({
    type: "template_literal",
    parts,
    ...util_exports2.normalizeParams(params)
  });
}
var ZodLazy2 = /* @__PURE__ */ $constructor2("ZodLazy", (inst, def) => {
  $ZodLazy2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => lazyProcessor2(inst, ctx, json3, params);
  inst.unwrap = () => inst._zod.def.getter();
});
function lazy2(getter) {
  return new ZodLazy2({
    type: "lazy",
    getter
  });
}
var ZodPromise2 = /* @__PURE__ */ $constructor2("ZodPromise", (inst, def) => {
  $ZodPromise2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => promiseProcessor2(inst, ctx, json3, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function promise2(innerType) {
  return new ZodPromise2({
    type: "promise",
    innerType
  });
}
var ZodFunction2 = /* @__PURE__ */ $constructor2("ZodFunction", (inst, def) => {
  $ZodFunction2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => functionProcessor2(inst, ctx, json3, params);
});
function _function2(params) {
  return new ZodFunction2({
    type: "function",
    input: Array.isArray(params?.input) ? tuple2(params?.input) : params?.input ?? array2(unknown2()),
    output: params?.output ?? unknown2()
  });
}
var ZodCustom2 = /* @__PURE__ */ $constructor2("ZodCustom", (inst, def) => {
  $ZodCustom2.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json3, params) => customProcessor2(inst, ctx, json3, params);
});
function check2(fn) {
  const ch = new $ZodCheck2({
    check: "custom"
    // ...util.normalizeParams(params),
  });
  ch._zod.check = fn;
  return ch;
}
function custom2(fn, _params) {
  return _custom2(ZodCustom2, fn ?? (() => true), _params);
}
function refine2(fn, _params = {}) {
  return _refine2(ZodCustom2, fn, _params);
}
function superRefine2(fn, params) {
  return _superRefine2(fn, params);
}
var describe4 = describe3;
var meta4 = meta3;
function _instanceof2(cls, params = {}) {
  const inst = new ZodCustom2({
    type: "custom",
    check: "custom",
    fn: (data) => data instanceof cls,
    abort: true,
    ...util_exports2.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;
}
var stringbool2 = (...args) => _stringbool2({
  Codec: ZodCodec2,
  Boolean: ZodBoolean2,
  String: ZodString2
}, ...args);
function json2(params) {
  const jsonSchema = lazy2(() => {
    return union2([string5(params), number5(), boolean5(), _null6(), array2(jsonSchema), record2(string5(), jsonSchema)]);
  });
  return jsonSchema;
}
function preprocess2(fn, schema) {
  return new ZodPreprocess2({
    type: "pipe",
    in: transform2(fn),
    out: schema
  });
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/compat.js
var ZodIssueCode2 = {
  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 setErrorMap2(map3) {
  config2({
    customError: map3
  });
}
function getErrorMap2() {
  return config2().customError;
}
var ZodFirstPartyTypeKind2;
/* @__PURE__ */ (function(ZodFirstPartyTypeKind3) {
})(ZodFirstPartyTypeKind2 || (ZodFirstPartyTypeKind2 = {}));

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/from-json-schema.js
var z2 = {
  ...schemas_exports3,
  ...checks_exports3,
  iso: iso_exports2
};
var RECOGNIZED_KEYS2 = /* @__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 detectVersion2(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";
}
function resolveRef2(ref, ctx) {
  if (!ref.startsWith("#")) {
    throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
  }
  const path73 = ref.slice(1).split("/").filter(Boolean);
  if (path73.length === 0) {
    return ctx.rootSchema;
  }
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
  if (path73[0] === defsKey) {
    const key = path73[1];
    if (!key || !ctx.defs[key]) {
      throw new Error(`Reference not found: ${ref}`);
    }
    return ctx.defs[key];
  }
  throw new Error(`Reference not found: ${ref}`);
}
function convertBaseSchema2(schema, ctx) {
  if (schema.not !== void 0) {
    if (typeof schema.not === "object" && Object.keys(schema.not).length === 0) {
      return z2.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 z2.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 = resolveRef2(refPath, ctx);
    const zodSchema2 = convertSchema2(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 z2.null();
    }
    if (enumValues.length === 0) {
      return z2.never();
    }
    if (enumValues.length === 1) {
      return z2.literal(enumValues[0]);
    }
    if (enumValues.every((v) => typeof v === "string")) {
      return z2.enum(enumValues);
    }
    const literalSchemas = enumValues.map((v) => z2.literal(v));
    if (literalSchemas.length < 2) {
      return literalSchemas[0];
    }
    return z2.union([literalSchemas[0], literalSchemas[1], ...literalSchemas.slice(2)]);
  }
  if (schema.const !== void 0) {
    return z2.literal(schema.const);
  }
  const type = schema.type;
  if (Array.isArray(type)) {
    const typeSchemas = type.map((t) => {
      const typeSchema = { ...schema, type: t };
      return convertBaseSchema2(typeSchema, ctx);
    });
    if (typeSchemas.length === 0) {
      return z2.never();
    }
    if (typeSchemas.length === 1) {
      return typeSchemas[0];
    }
    return z2.union(typeSchemas);
  }
  if (!type) {
    return z2.any();
  }
  let zodSchema;
  switch (type) {
    case "string": {
      let stringSchema = z2.string();
      if (schema.format) {
        const format5 = schema.format;
        if (format5 === "email") {
          stringSchema = stringSchema.check(z2.email());
        } else if (format5 === "uri" || format5 === "uri-reference") {
          stringSchema = stringSchema.check(z2.url());
        } else if (format5 === "uuid" || format5 === "guid") {
          stringSchema = stringSchema.check(z2.uuid());
        } else if (format5 === "date-time") {
          stringSchema = stringSchema.check(z2.iso.datetime());
        } else if (format5 === "date") {
          stringSchema = stringSchema.check(z2.iso.date());
        } else if (format5 === "time") {
          stringSchema = stringSchema.check(z2.iso.time());
        } else if (format5 === "duration") {
          stringSchema = stringSchema.check(z2.iso.duration());
        } else if (format5 === "ipv4") {
          stringSchema = stringSchema.check(z2.ipv4());
        } else if (format5 === "ipv6") {
          stringSchema = stringSchema.check(z2.ipv6());
        } else if (format5 === "mac") {
          stringSchema = stringSchema.check(z2.mac());
        } else if (format5 === "cidr") {
          stringSchema = stringSchema.check(z2.cidrv4());
        } else if (format5 === "cidr-v6") {
          stringSchema = stringSchema.check(z2.cidrv6());
        } else if (format5 === "base64") {
          stringSchema = stringSchema.check(z2.base64());
        } else if (format5 === "base64url") {
          stringSchema = stringSchema.check(z2.base64url());
        } else if (format5 === "e164") {
          stringSchema = stringSchema.check(z2.e164());
        } else if (format5 === "jwt") {
          stringSchema = stringSchema.check(z2.jwt());
        } else if (format5 === "emoji") {
          stringSchema = stringSchema.check(z2.emoji());
        } else if (format5 === "nanoid") {
          stringSchema = stringSchema.check(z2.nanoid());
        } else if (format5 === "cuid") {
          stringSchema = stringSchema.check(z2.cuid());
        } else if (format5 === "cuid2") {
          stringSchema = stringSchema.check(z2.cuid2());
        } else if (format5 === "ulid") {
          stringSchema = stringSchema.check(z2.ulid());
        } else if (format5 === "xid") {
          stringSchema = stringSchema.check(z2.xid());
        } else if (format5 === "ksuid") {
          stringSchema = stringSchema.check(z2.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 = type === "integer" ? z2.number().int() : z2.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 = z2.boolean();
      break;
    }
    case "null": {
      zodSchema = z2.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 = convertSchema2(propSchema, ctx);
        shape[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional();
      }
      if (schema.propertyNames) {
        const keySchema = convertSchema2(schema.propertyNames, ctx);
        const valueSchema = schema.additionalProperties && typeof schema.additionalProperties === "object" ? convertSchema2(schema.additionalProperties, ctx) : z2.any();
        if (Object.keys(shape).length === 0) {
          zodSchema = z2.record(keySchema, valueSchema);
          break;
        }
        const objectSchema2 = z2.object(shape).passthrough();
        const recordSchema = z2.looseRecord(keySchema, valueSchema);
        zodSchema = z2.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 = convertSchema2(patternProps[pattern], ctx);
          const keySchema = z2.string().regex(new RegExp(pattern));
          looseRecords.push(z2.looseRecord(keySchema, patternValue));
        }
        const schemasToIntersect = [];
        if (Object.keys(shape).length > 0) {
          schemasToIntersect.push(z2.object(shape).passthrough());
        }
        schemasToIntersect.push(...looseRecords);
        if (schemasToIntersect.length === 0) {
          zodSchema = z2.object({}).passthrough();
        } else if (schemasToIntersect.length === 1) {
          zodSchema = schemasToIntersect[0];
        } else {
          let result = z2.intersection(schemasToIntersect[0], schemasToIntersect[1]);
          for (let i = 2; i < schemasToIntersect.length; i++) {
            result = z2.intersection(result, schemasToIntersect[i]);
          }
          zodSchema = result;
        }
        break;
      }
      const objectSchema = z2.object(shape);
      if (schema.additionalProperties === false) {
        zodSchema = objectSchema.strict();
      } else if (typeof schema.additionalProperties === "object") {
        zodSchema = objectSchema.catchall(convertSchema2(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) => convertSchema2(item, ctx));
        const rest = items && typeof items === "object" && !Array.isArray(items) ? convertSchema2(items, ctx) : void 0;
        if (rest) {
          zodSchema = z2.tuple(tupleItems).rest(rest);
        } else {
          zodSchema = z2.tuple(tupleItems);
        }
        if (typeof schema.minItems === "number") {
          zodSchema = zodSchema.check(z2.minLength(schema.minItems));
        }
        if (typeof schema.maxItems === "number") {
          zodSchema = zodSchema.check(z2.maxLength(schema.maxItems));
        }
      } else if (Array.isArray(items)) {
        const tupleItems = items.map((item) => convertSchema2(item, ctx));
        const rest = schema.additionalItems && typeof schema.additionalItems === "object" ? convertSchema2(schema.additionalItems, ctx) : void 0;
        if (rest) {
          zodSchema = z2.tuple(tupleItems).rest(rest);
        } else {
          zodSchema = z2.tuple(tupleItems);
        }
        if (typeof schema.minItems === "number") {
          zodSchema = zodSchema.check(z2.minLength(schema.minItems));
        }
        if (typeof schema.maxItems === "number") {
          zodSchema = zodSchema.check(z2.maxLength(schema.maxItems));
        }
      } else if (items !== void 0) {
        const element = convertSchema2(items, ctx);
        let arraySchema = z2.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 = z2.array(z2.any());
      }
      break;
    }
    default:
      throw new Error(`Unsupported type: ${type}`);
  }
  return zodSchema;
}
function convertSchema2(schema, ctx) {
  if (typeof schema === "boolean") {
    return schema ? z2.any() : z2.never();
  }
  let baseSchema = convertBaseSchema2(schema, ctx);
  const hasExplicitType = schema.type || schema.enum !== void 0 || schema.const !== void 0;
  if (schema.anyOf && Array.isArray(schema.anyOf)) {
    const options = schema.anyOf.map((s) => convertSchema2(s, ctx));
    const anyOfUnion = z2.union(options);
    baseSchema = hasExplicitType ? z2.intersection(baseSchema, anyOfUnion) : anyOfUnion;
  }
  if (schema.oneOf && Array.isArray(schema.oneOf)) {
    const options = schema.oneOf.map((s) => convertSchema2(s, ctx));
    const oneOfUnion = z2.xor(options);
    baseSchema = hasExplicitType ? z2.intersection(baseSchema, oneOfUnion) : oneOfUnion;
  }
  if (schema.allOf && Array.isArray(schema.allOf)) {
    if (schema.allOf.length === 0) {
      baseSchema = hasExplicitType ? baseSchema : z2.any();
    } else {
      let result = hasExplicitType ? baseSchema : convertSchema2(schema.allOf[0], ctx);
      const startIdx = hasExplicitType ? 0 : 1;
      for (let i = startIdx; i < schema.allOf.length; i++) {
        result = z2.intersection(result, convertSchema2(schema.allOf[i], ctx));
      }
      baseSchema = result;
    }
  }
  if (schema.nullable === true && ctx.version === "openapi-3.0") {
    baseSchema = z2.nullable(baseSchema);
  }
  if (schema.readOnly === true) {
    baseSchema = z2.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_KEYS2.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;
}
function fromJSONSchema2(schema, params) {
  if (typeof schema === "boolean") {
    return schema ? z2.any() : z2.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 version4 = detectVersion2(normalized, params?.defaultTarget);
  const defs = normalized.$defs || normalized.definitions || {};
  const ctx = {
    version: version4,
    defs,
    refs: /* @__PURE__ */ new Map(),
    processing: /* @__PURE__ */ new Set(),
    rootSchema: normalized,
    registry: params?.registry ?? globalRegistry2
  };
  return convertSchema2(normalized, ctx);
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/coerce.js
var coerce_exports2 = {};
__export(coerce_exports2, {
  bigint: () => bigint6,
  boolean: () => boolean6,
  date: () => date8,
  number: () => number6,
  string: () => string6
});
function string6(params) {
  return _coercedString2(ZodString2, params);
}
function number6(params) {
  return _coercedNumber2(ZodNumber2, params);
}
function boolean6(params) {
  return _coercedBoolean2(ZodBoolean2, params);
}
function bigint6(params) {
  return _coercedBigint2(ZodBigInt2, params);
}
function date8(params) {
  return _coercedDate2(ZodDate2, params);
}

// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js
config2(en_default2());

// src/cf.ts
var import_node_assert2 = __toESM(require("node:assert"));
var import_node_fs5 = require("node:fs");
var import_promises3 = require("node:fs/promises");
var import_node_path5 = __toESM(require("node:path"));
var import_undici2 = require("undici");
function getDefaultCfPath() {
  const miniflareCacheDir = process.env.MINIFLARE_CACHE_DIR;
  if (miniflareCacheDir) {
    return import_node_path5.default.resolve(miniflareCacheDir, "cf.json");
  }
  const nodeModulesMfPath = import_node_path5.default.resolve("node_modules", ".mf");
  const wranglerCachePath = import_node_path5.default.resolve(".wrangler", "cache");
  if ((0, import_node_fs5.existsSync)(nodeModulesMfPath)) {
    return import_node_path5.default.resolve(nodeModulesMfPath, "cf.json");
  }
  if ((0, import_node_fs5.existsSync)(wranglerCachePath)) {
    return import_node_path5.default.resolve(wranglerCachePath, "cf.json");
  }
  if ((0, import_node_fs5.existsSync)("node_modules")) {
    return import_node_path5.default.resolve(nodeModulesMfPath, "cf.json");
  }
  return import_node_path5.default.resolve(wranglerCachePath, "cf.json");
}
var defaultCfFetchEndpoint = "https://workers.cloudflare.com/cf.json";
var CF_FETCH_ENABLED_ENV_VAR = "CLOUDFLARE_CF_FETCH_ENABLED";
var CF_FETCH_PATH_ENV_VAR = "CLOUDFLARE_CF_FETCH_PATH";
var fallbackCf = {
  asOrganization: "",
  asn: 395747,
  colo: "DFW",
  city: "Austin",
  region: "Texas",
  regionCode: "TX",
  metroCode: "635",
  postalCode: "78701",
  country: "US",
  continent: "NA",
  timezone: "America/Chicago",
  latitude: "30.27130",
  longitude: "-97.74260",
  clientTcpRtt: 0,
  httpProtocol: "HTTP/1.1",
  requestPriority: "weight=192;exclusive=0",
  tlsCipher: "AEAD-AES128-GCM-SHA256",
  tlsVersion: "TLSv1.3",
  tlsClientAuth: {
    certPresented: "0",
    certVerified: "NONE",
    certRevoked: "0",
    certIssuerDN: "",
    certSubjectDN: "",
    certIssuerDNRFC2253: "",
    certSubjectDNRFC2253: "",
    certIssuerDNLegacy: "",
    certSubjectDNLegacy: "",
    certSerial: "",
    certIssuerSerial: "",
    certSKI: "",
    certIssuerSKI: "",
    certFingerprintSHA1: "",
    certFingerprintSHA256: "",
    certNotBefore: "",
    certNotAfter: "",
    certRFC9440: "",
    certRFC9440TooLarge: false,
    certChainRFC9440: "",
    certChainRFC9440TooLarge: false
  },
  edgeRequestKeepAliveStatus: 0,
  hostMetadata: void 0,
  clientTrustScore: 99,
  botManagement: {
    corporateProxy: false,
    verifiedBot: false,
    ja3Hash: "25b4882c2bcb50cd6b469ff28c596742",
    staticResource: false,
    detectionIds: [],
    score: 99
  }
};
var DAY = 864e5;
var CF_DAYS = 30;
function isCfFetchDisabledByEnv() {
  const envValue = process.env[CF_FETCH_ENABLED_ENV_VAR];
  if (envValue === void 0) {
    return false;
  }
  return envValue.toLowerCase() === "false";
}
function getCfPathFromEnv() {
  const envValue = process.env[CF_FETCH_PATH_ENV_VAR];
  if (envValue === void 0 || envValue === "") {
    return void 0;
  }
  return envValue;
}
function getCfOptionWithEnvOverride(cf) {
  if (cf !== void 0) {
    return cf;
  }
  if (isCfFetchDisabledByEnv()) {
    return false;
  }
  const customPath = getCfPathFromEnv();
  if (customPath !== void 0) {
    return customPath;
  }
  return void 0;
}
async function setupCf(log2, cf) {
  const effectiveCf = getCfOptionWithEnvOverride(cf);
  if (!(effectiveCf ?? process.env.NODE_ENV !== "test")) {
    return fallbackCf;
  }
  if (typeof effectiveCf === "object") {
    return effectiveCf;
  }
  let cfPath = getDefaultCfPath();
  if (typeof effectiveCf === "string") {
    cfPath = effectiveCf;
  }
  try {
    const storedCf = JSON.parse(await (0, import_promises3.readFile)(cfPath, "utf8"));
    const cfStat = await (0, import_promises3.stat)(cfPath);
    (0, import_node_assert2.default)(Date.now() - cfStat.mtimeMs <= CF_DAYS * DAY);
    return storedCf;
  } catch {
  }
  try {
    const res = await (0, import_undici2.fetch)(defaultCfFetchEndpoint, {
      signal: AbortSignal.timeout(3e3)
    });
    const cfText = await res.text();
    const storedCf = JSON.parse(cfText);
    await (0, import_promises3.mkdir)(import_node_path5.default.dirname(cfPath), { recursive: true });
    await (0, import_promises3.writeFile)(cfPath, cfText, "utf8");
    log2.debug("Updated `Request.cf` object cache!");
    return storedCf;
  } catch (e) {
    log2.warn(
      "Unable to fetch the `Request.cf` object! Falling back to a default placeholder...\n" + dim3(e.cause ? e.cause.stack : e.stack)
    );
    return fallbackCf;
  }
}

// src/config/schema.ts
var import_node_path7 = __toESM(require("node:path"));

// ../config/dist/index.mjs
var import_node_fs6 = require("node:fs");
var import_node_path6 = __toESM(require("node:path"), 1);
var import_node_async_hooks = require("node:async_hooks");
var __getOwnPropNames3 = Object.getOwnPropertyNames;
var __commonJS3 = (cb, mod) => function() {
  return mod || (0, cb[__getOwnPropNames3(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var AssetsSchema = strictObject2({
  htmlHandling: _enum4([
    "auto-trailing-slash",
    "drop-trailing-slash",
    "force-trailing-slash",
    "none"
  ]).optional(),
  notFoundHandling: _enum4([
    "single-page-application",
    "404-page",
    "none"
  ]).optional(),
  runWorkerFirst: union2([array2(string5()), boolean5()]).optional()
});
var BrowserBindingSchema = strictObject2({
  type: literal2("browser"),
  remote: boolean5().optional()
});
var WorkerBindingSchema = strictObject2({
  type: literal2("worker"),
  workerName: string5(),
  exportName: string5().optional(),
  props: record2(string5(), unknown2()).optional(),
  remote: boolean5().optional()
});
var D1BindingSchema = strictObject2({
  type: literal2("d1"),
  name: string5().optional(),
  id: string5().optional(),
  remote: boolean5().optional()
});
var KVBindingSchema = strictObject2({
  type: literal2("kv"),
  id: string5().optional(),
  remote: boolean5().optional()
});
var QueueBindingSchema = strictObject2({
  type: literal2("queue"),
  name: string5().optional(),
  deliveryDelay: number5().optional(),
  remote: boolean5().optional()
});
var R2BindingSchema = strictObject2({
  type: literal2("r2"),
  name: string5().optional(),
  jurisdiction: string5().optional(),
  remote: boolean5().optional()
});
var FlagshipBindingSchema = strictObject2({
  type: literal2("flagship"),
  id: string5().optional(),
  remote: boolean5().optional()
});
var HyperdriveBindingSchema = strictObject2({
  type: literal2("hyperdrive"),
  id: string5(),
  localConnectionString: string5().optional()
});
var KnownBindingSchema = discriminatedUnion2("type", [
  strictObject2({
    type: literal2("agent-memory"),
    namespace: string5(),
    remote: boolean5().optional()
  }),
  strictObject2({
    type: literal2("ai"),
    remote: boolean5().optional()
  }),
  strictObject2({
    type: literal2("ai-search"),
    name: string5(),
    remote: boolean5().optional()
  }),
  strictObject2({
    type: literal2("ai-search-namespace"),
    namespace: string5(),
    remote: boolean5().optional()
  }),
  strictObject2({
    type: literal2("analytics-engine-dataset"),
    name: string5().optional()
  }),
  strictObject2({
    type: literal2("artifacts"),
    namespace: string5(),
    remote: boolean5().optional()
  }),
  strictObject2({ type: literal2("assets") }),
  BrowserBindingSchema,
  D1BindingSchema,
  strictObject2({
    type: literal2("dispatch-namespace"),
    namespace: string5().optional(),
    outbound: strictObject2({
      workerName: string5(),
      parameters: array2(string5()).optional()
    }).optional(),
    remote: boolean5().optional()
  }),
  strictObject2({
    type: literal2("durable-object"),
    workerName: string5(),
    exportName: string5()
  }),
  FlagshipBindingSchema,
  HyperdriveBindingSchema,
  strictObject2({
    type: literal2("images"),
    remote: boolean5().optional()
  }),
  strictObject2({
    type: literal2("json"),
    value: json2()
  }),
  KVBindingSchema,
  strictObject2({
    type: literal2("logfwdr"),
    destination: string5()
  }),
  strictObject2({
    type: literal2("media"),
    remote: boolean5().optional()
  }),
  strictObject2({
    type: literal2("mtls-certificate"),
    id: string5(),
    remote: boolean5().optional()
  }),
  strictObject2({
    type: literal2("pipeline"),
    name: string5(),
    remote: boolean5().optional()
  }),
  QueueBindingSchema,
  strictObject2({
    type: literal2("rate-limit"),
    namespace: string5(),
    simple: strictObject2({
      limit: number5(),
      period: union2([literal2(10), literal2(60)])
    })
  }),
  R2BindingSchema,
  strictObject2({ type: literal2("secret") }),
  strictObject2({
    type: literal2("secrets-store-secret"),
    storeId: string5(),
    secretName: string5()
  }),
  strictObject2({
    type: literal2("send-email"),
    destinationAddress: string5().optional(),
    allowedDestinationAddresses: array2(string5()).optional(),
    allowedSenderAddresses: array2(string5()).optional(),
    remote: boolean5().optional()
  }),
  strictObject2({
    type: literal2("stream"),
    remote: boolean5().optional()
  }),
  strictObject2({
    type: literal2("text"),
    value: string5()
  }),
  strictObject2({
    type: literal2("vectorize"),
    name: string5(),
    remote: boolean5().optional()
  }),
  strictObject2({ type: literal2("version-metadata") }),
  strictObject2({
    type: literal2("vpc-service"),
    id: string5(),
    remote: boolean5().optional()
  }),
  strictObject2({
    type: literal2("vpc-network"),
    tunnelId: string5().optional(),
    networkId: string5().optional(),
    remote: boolean5().optional()
  }).superRefine((value, ctx) => {
    const hasTunnel = value.tunnelId !== void 0;
    if (hasTunnel === (value.networkId !== void 0)) ctx.addIssue({
      code: "custom",
      message: hasTunnel ? `"vpc-network" bindings must specify exactly one of "tunnelId" or "networkId", not both` : `"vpc-network" bindings must specify either "tunnelId" or "networkId"`
    });
  }),
  strictObject2({
    type: literal2("web-search"),
    remote: boolean5().optional()
  }),
  WorkerBindingSchema,
  strictObject2({ type: literal2("worker-loader") })
]);
var UnsafeBindingSchema = looseObject2({
  type: templateLiteral2(["unsafe:", string5().min(1)]),
  dev: strictObject2({
    plugin: strictObject2({
      package: string5(),
      name: string5()
    }),
    options: record2(string5(), unknown2()).optional()
  }).optional()
});
var BindingSchema = unknown2().transform((value, ctx) => {
  const result = (typeof value === "object" && value !== null && "type" in value && typeof value.type === "string" && value.type.startsWith("unsafe:") ? UnsafeBindingSchema : KnownBindingSchema).safeParse(value);
  if (!result.success) {
    ctx.issues.push(...result.error.issues);
    return NEVER2;
  }
  return result.data;
});
var CacheSchema = strictObject2({
  enabled: boolean5(),
  crossVersionCache: boolean5().optional()
});
var SINGLETON_BINDING_TYPES = /* @__PURE__ */ new Set([
  "ai",
  "assets",
  "browser",
  "images",
  "media",
  "stream",
  "version-metadata",
  "web-search"
]);
var listFormatter = new Intl.ListFormat("en-US");
function validateSingletonBindings(env3, ctx) {
  const seen = /* @__PURE__ */ new Set();
  const duplicates = /* @__PURE__ */ new Set();
  for (const binding of Object.values(env3)) {
    const type = binding.type;
    if (SINGLETON_BINDING_TYPES.has(type)) {
      if (seen.has(type)) duplicates.add(type);
      seen.add(type);
    }
  }
  if (duplicates.size > 0) ctx.addIssue({
    code: "custom",
    message: `${listFormatter.format([...duplicates].sort())} bindings can only be defined once`
  });
}
var EnvSchema = record2(string5(), BindingSchema).superRefine(validateSingletonBindings).optional();
var DurableObjectCreatedExportSchema = strictObject2({
  type: literal2("durable-object"),
  state: literal2("created").optional(),
  storage: _enum4(["sqlite", "legacy-kv"]),
  container: string5().optional()
});
var DurableObjectDeletedExportSchema = strictObject2({
  type: literal2("durable-object"),
  state: literal2("deleted")
});
var DurableObjectRenamedExportSchema = strictObject2({
  type: literal2("durable-object"),
  state: literal2("renamed"),
  renamedTo: string5()
});
var DurableObjectTransferredExportSchema = strictObject2({
  type: literal2("durable-object"),
  state: literal2("transferred"),
  transferredTo: string5()
});
var DurableObjectExpectingTransferExportSchema = strictObject2({
  type: literal2("durable-object"),
  state: literal2("expecting-transfer"),
  storage: _enum4(["sqlite", "legacy-kv"]),
  transferFrom: string5(),
  container: string5().optional()
});
var WorkerEntrypointExportSchema = strictObject2({
  type: literal2("worker"),
  cache: strictObject2({ enabled: boolean5() }).optional()
});
var DurableObjectCreatedSqliteExportSchema = DurableObjectCreatedExportSchema.extend({ storage: literal2("sqlite") });
var DurableObjectCreatedLegacyKvExportSchema = DurableObjectCreatedExportSchema.omit({ container: true }).extend({ storage: literal2("legacy-kv") });
var DurableObjectExpectingTransferSqliteExportSchema = DurableObjectExpectingTransferExportSchema.extend({ storage: literal2("sqlite") });
var DurableObjectExpectingTransferLegacyKvExportSchema = DurableObjectExpectingTransferExportSchema.omit({ container: true }).extend({ storage: literal2("legacy-kv") });
var ExportSchema = union2([
  DurableObjectCreatedSqliteExportSchema,
  DurableObjectCreatedLegacyKvExportSchema,
  DurableObjectDeletedExportSchema,
  DurableObjectRenamedExportSchema,
  DurableObjectTransferredExportSchema,
  DurableObjectExpectingTransferSqliteExportSchema,
  DurableObjectExpectingTransferLegacyKvExportSchema,
  WorkerEntrypointExportSchema
]);
var LimitsSchema = strictObject2({
  cpuMs: number5().optional(),
  subrequests: number5().optional()
});
var ObservabilitySchema = strictObject2({
  enabled: boolean5().optional(),
  headSamplingRate: number5().optional(),
  logs: strictObject2({
    enabled: boolean5().optional(),
    headSamplingRate: number5().optional(),
    invocationLogs: boolean5().optional(),
    persist: boolean5().optional(),
    destinations: array2(string5()).optional()
  }).optional(),
  traces: strictObject2({
    enabled: boolean5().optional(),
    headSamplingRate: number5().optional(),
    persist: boolean5().optional(),
    destinations: array2(string5()).optional()
  }).optional()
});
var PlacementSchema = union2([
  strictObject2({
    mode: _enum4(["off", "smart"]),
    hint: string5().optional()
  }),
  strictObject2({
    mode: literal2("targeted").optional(),
    region: string5()
  }),
  strictObject2({
    mode: literal2("targeted").optional(),
    host: string5()
  }),
  strictObject2({
    mode: literal2("targeted").optional(),
    hostname: string5()
  })
]);
var TailConsumerSchema = strictObject2({
  workerName: string5(),
  streaming: boolean5().optional()
});
var TriggerSchema = discriminatedUnion2("type", [
  strictObject2({
    type: literal2("email"),
    addresses: array2(string5())
  }),
  strictObject2({
    type: literal2("fetch"),
    pattern: string5(),
    zone: string5().optional()
  }),
  strictObject2({
    type: literal2("queue"),
    name: string5(),
    deadLetterQueue: string5().optional(),
    maxBatchSize: number5().optional(),
    maxBatchTimeout: number5().optional(),
    maxConcurrency: number5().nullable().optional(),
    maxRetries: number5().optional(),
    retryDelay: number5().optional(),
    visibilityTimeoutMs: number5().optional()
  }),
  strictObject2({
    type: literal2("scheduled"),
    schedule: string5()
  })
]);
var UnsafeSchema = strictObject2({
  metadata: record2(string5(), unknown2()).optional(),
  capnp: union2([strictObject2({
    basePath: string5(),
    sourceSchemas: array2(string5()),
    compiledSchema: never2().optional()
  }), strictObject2({
    basePath: never2().optional(),
    sourceSchemas: never2().optional(),
    compiledSchema: string5()
  })]).optional()
});
var BaseWorkerSchema = strictObject2({
  type: literal2("worker"),
  name: string5(),
  compatibilityDate: string5(),
  compatibilityFlags: array2(string5()).optional(),
  assets: AssetsSchema.optional(),
  domains: array2(string5()).optional(),
  triggers: array2(TriggerSchema).optional(),
  tailConsumers: array2(TailConsumerSchema).optional(),
  cache: CacheSchema.optional(),
  placement: PlacementSchema.optional(),
  limits: LimitsSchema.optional(),
  logpush: boolean5().optional(),
  observability: ObservabilitySchema.optional(),
  workersDev: boolean5().optional(),
  previewUrls: boolean5().optional(),
  firstPartyWorker: boolean5().optional(),
  unsafe: UnsafeSchema.optional(),
  env: EnvSchema,
  exports: record2(string5(), ExportSchema).optional()
});
var InputWorkerSchema = BaseWorkerSchema.extend({ entrypoint: union2([string5(), strictObject2({ default: string5() })]).transform((value) => typeof value === "string" ? value : value.default).optional() });
var SettingsSchema = strictObject2({
  type: literal2("settings"),
  accountId: string5().optional(),
  complianceRegion: _enum4(["public", "fedramp-high"]).optional()
});
var ConfigExportSchema = discriminatedUnion2("type", [InputWorkerSchema, SettingsSchema]);
var SETTINGS_EXPORT_NAME = "settings";
var ConfigExportsSchema = record2(string5(), ConfigExportSchema).check((ctx) => {
  for (const [key, value] of Object.entries(ctx.value)) {
    const isSettingsName = key === SETTINGS_EXPORT_NAME;
    const isSettingsType = value.type === "settings";
    if (isSettingsType && !isSettingsName) ctx.issues.push({
      code: "custom",
      input: value,
      path: [key],
      message: `A \`settings\` config is only allowed on the \`${SETTINGS_EXPORT_NAME}\` export; found one on the \`${key}\` export.`
    });
    else if (isSettingsName && !isSettingsType) ctx.issues.push({
      code: "custom",
      input: value,
      path: [key],
      message: `The \`${SETTINGS_EXPORT_NAME}\` export is reserved for a \`settings\` config; found a \`${value.type}\` config.`
    });
  }
});
var ModuleTypeSchema = _enum4([
  "esm",
  "cjs",
  "python",
  "python-requirement",
  "wasm",
  "text",
  "data",
  "json",
  "sourcemap"
]);
var ManifestSchema = strictObject2({
  mainModule: string5(),
  modules: record2(string5(), strictObject2({ type: ModuleTypeSchema }))
});
var OutputWorkerSchema = BaseWorkerSchema.extend({ manifest: ManifestSchema.optional() });
var require_dist = /* @__PURE__ */ __commonJS3({ "../../node_modules/.pnpm/ts-dedent@2.2.0/node_modules/ts-dedent/dist/index.js": ((exports2) => {
  Object.defineProperty(exports2, "__esModule", { value: true });
  exports2.dedent = void 0;
  function dedent$2(templ) {
    var values = [];
    for (var _i = 1; _i < arguments.length; _i++) values[_i - 1] = arguments[_i];
    var strings = Array.from(typeof templ === "string" ? [templ] : templ);
    strings[strings.length - 1] = strings[strings.length - 1].replace(/\r?\n([\t ]*)$/, "");
    var indentLengths = strings.reduce(function(arr, str) {
      var matches = str.match(/\n([\t ]+|(?!\s).)/g);
      if (matches) return arr.concat(matches.map(function(match) {
        var _a5, _b;
        return (_b = (_a5 = match.match(/[\t ]/g)) === null || _a5 === void 0 ? void 0 : _a5.length) !== null && _b !== void 0 ? _b : 0;
      }));
      return arr;
    }, []);
    if (indentLengths.length) {
      var pattern_1 = new RegExp("\n[	 ]{" + Math.min.apply(Math, indentLengths) + "}", "g");
      strings = strings.map(function(str) {
        return str.replace(pattern_1, "\n");
      });
    }
    strings[0] = strings[0].replace(/^\r?\n/, "");
    var string7 = strings[0];
    values.forEach(function(value, i) {
      var endentations = string7.match(/(?:^|\n)( *)$/);
      var endentation = endentations ? endentations[1] : "";
      var indentedValue = value;
      if (typeof value === "string" && value.includes("\n")) indentedValue = String(value).split("\n").map(function(str, i$1) {
        return i$1 === 0 ? str : "" + endentation + str;
      }).join("\n");
      string7 += indentedValue + strings[i + 1];
    });
    return string7;
  }
  exports2.dedent = dedent$2;
}) });
var import_dist = require_dist();
var __defProp3 = Object.defineProperty;
var __name2 = (target, value) => __defProp3(target, "name", {
  value,
  configurable: true
});
function hasKnownExportType2(entry) {
  const type = entry?.type;
  return type === "durable-object" || type === "worker";
}
__name2(hasKnownExportType2, "hasKnownExportType");
function partitionExports2(exports$2) {
  const partitioned = {
    "durable-object": {},
    worker: {}
  };
  if (exports$2 === void 0) return partitioned;
  for (const [name, entry] of Object.entries(exports$2)) {
    if (!hasKnownExportType2(entry)) continue;
    partitioned[entry.type][name] = entry;
  }
  return partitioned;
}
__name2(partitionExports2, "partitionExports");
function getDurableObjectExports2(exports$2) {
  return partitionExports2(exports$2)["durable-object"];
}
__name2(getDurableObjectExports2, "getDurableObjectExports");
function hasDurableObjectExports2(exports$2) {
  return Object.keys(getDurableObjectExports2(exports$2)).length > 0;
}
__name2(hasDurableObjectExports2, "hasDurableObjectExports");
function getContainerNameToClassNameMap2(exports$2) {
  const containerNameToClassName = /* @__PURE__ */ new Map();
  for (const [className, entry] of Object.entries(getDurableObjectExports2(exports$2))) if ("container" in entry && typeof entry.container === "string" && !containerNameToClassName.has(entry.container)) containerNameToClassName.set(entry.container, className);
  return containerNameToClassName;
}
__name2(getContainerNameToClassNameMap2, "getContainerNameToClassNameMap");
function resolveContainerClassName2(container, exports$2) {
  if (container.class_name !== void 0) return container.class_name;
  if (container.name === void 0) return;
  return getContainerNameToClassNameMap2(exports$2).get(container.name);
}
__name2(resolveContainerClassName2, "resolveContainerClassName");
function getContainerDurableObjectClassNames2(containers, exports$2) {
  const classNames = /* @__PURE__ */ new Set();
  for (const container of containers ?? []) {
    const className = resolveContainerClassName2(container, exports$2);
    if (className !== void 0) classNames.add(className);
  }
  return classNames;
}
__name2(getContainerDurableObjectClassNames2, "getContainerDurableObjectClassNames");
var UserError2 = class extends Error {
  static {
    __name2(this, "UserError");
  }
  telemetryMessage;
  constructor(message, options) {
    super(message, options);
    Object.setPrototypeOf(this, new.target.prototype);
    this.telemetryMessage = typeof options?.telemetryMessage === "string" ? options.telemetryMessage : options?.telemetryMessage ? message : void 0;
  }
};
var DeprecationError2 = class extends UserError2 {
  static {
    __name2(this, "DeprecationError");
  }
  constructor(message, options) {
    super(`Deprecation:
${message}`, options);
  }
};
var FatalError2 = class extends UserError2 {
  static {
    __name2(this, "FatalError");
  }
  code;
  constructor(message, options) {
    super(message, options);
    this.code = options.code;
  }
};
var CommandLineArgsError2 = class extends UserError2 {
  static {
    __name2(this, "CommandLineArgsError");
  }
};
var JsonFriendlyFatalError2 = class extends FatalError2 {
  static {
    __name2(this, "JsonFriendlyFatalError");
  }
};
var MissingConfigError2 = class extends Error {
  static {
    __name2(this, "MissingConfigError");
  }
  telemetryMessage;
  constructor(key) {
    super(`Missing config value for ${key}`);
    this.telemetryMessage = `Missing config value for ${key}`;
  }
};
function createFatalError2(message, isJson, options) {
  if (isJson) return new JsonFriendlyFatalError2(JSON.stringify(message), options);
  return new FatalError2(`${message}`, options);
}
__name2(createFatalError2, "createFatalError");
function createScanner2(text, ignoreTrivia = false) {
  const len = text.length;
  let pos = 0, value = "", tokenOffset = 0, token = 16, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0;
  function scanHexDigits(count, exact) {
    let digits = 0;
    let value2 = 0;
    while (digits < count || !exact) {
      let ch = text.charCodeAt(pos);
      if (ch >= 48 && ch <= 57) value2 = value2 * 16 + ch - 48;
      else if (ch >= 65 && ch <= 70) value2 = value2 * 16 + ch - 65 + 10;
      else if (ch >= 97 && ch <= 102) value2 = value2 * 16 + ch - 97 + 10;
      else break;
      pos++;
      digits++;
    }
    if (digits < count) value2 = -1;
    return value2;
  }
  __name2(scanHexDigits, "scanHexDigits");
  function setPosition(newPosition) {
    pos = newPosition;
    value = "";
    tokenOffset = 0;
    token = 16;
    scanError = 0;
  }
  __name2(setPosition, "setPosition");
  function scanNumber() {
    let start = pos;
    if (text.charCodeAt(pos) === 48) pos++;
    else {
      pos++;
      while (pos < text.length && isDigit2(text.charCodeAt(pos))) pos++;
    }
    if (pos < text.length && text.charCodeAt(pos) === 46) {
      pos++;
      if (pos < text.length && isDigit2(text.charCodeAt(pos))) {
        pos++;
        while (pos < text.length && isDigit2(text.charCodeAt(pos))) pos++;
      } else {
        scanError = 3;
        return text.substring(start, pos);
      }
    }
    let end = pos;
    if (pos < text.length && (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101)) {
      pos++;
      if (pos < text.length && text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) pos++;
      if (pos < text.length && isDigit2(text.charCodeAt(pos))) {
        pos++;
        while (pos < text.length && isDigit2(text.charCodeAt(pos))) pos++;
        end = pos;
      } else scanError = 3;
    }
    return text.substring(start, end);
  }
  __name2(scanNumber, "scanNumber");
  function scanString() {
    let result = "", start = pos;
    while (true) {
      if (pos >= len) {
        result += text.substring(start, pos);
        scanError = 2;
        break;
      }
      const ch = text.charCodeAt(pos);
      if (ch === 34) {
        result += text.substring(start, pos);
        pos++;
        break;
      }
      if (ch === 92) {
        result += text.substring(start, pos);
        pos++;
        if (pos >= len) {
          scanError = 2;
          break;
        }
        switch (text.charCodeAt(pos++)) {
          case 34:
            result += '"';
            break;
          case 92:
            result += "\\";
            break;
          case 47:
            result += "/";
            break;
          case 98:
            result += "\b";
            break;
          case 102:
            result += "\f";
            break;
          case 110:
            result += "\n";
            break;
          case 114:
            result += "\r";
            break;
          case 116:
            result += "	";
            break;
          case 117:
            const ch3 = scanHexDigits(4, true);
            if (ch3 >= 0) result += String.fromCharCode(ch3);
            else scanError = 4;
            break;
          default:
            scanError = 5;
        }
        start = pos;
        continue;
      }
      if (ch >= 0 && ch <= 31) if (isLineBreak2(ch)) {
        result += text.substring(start, pos);
        scanError = 2;
        break;
      } else scanError = 6;
      pos++;
    }
    return result;
  }
  __name2(scanString, "scanString");
  function scanNext() {
    value = "";
    scanError = 0;
    tokenOffset = pos;
    lineStartOffset = lineNumber;
    prevTokenLineStartOffset = tokenLineStartOffset;
    if (pos >= len) {
      tokenOffset = len;
      return token = 17;
    }
    let code = text.charCodeAt(pos);
    if (isWhiteSpace2(code)) {
      do {
        pos++;
        value += String.fromCharCode(code);
        code = text.charCodeAt(pos);
      } while (isWhiteSpace2(code));
      return token = 15;
    }
    if (isLineBreak2(code)) {
      pos++;
      value += String.fromCharCode(code);
      if (code === 13 && text.charCodeAt(pos) === 10) {
        pos++;
        value += "\n";
      }
      lineNumber++;
      tokenLineStartOffset = pos;
      return token = 14;
    }
    switch (code) {
      case 123:
        pos++;
        return token = 1;
      case 125:
        pos++;
        return token = 2;
      case 91:
        pos++;
        return token = 3;
      case 93:
        pos++;
        return token = 4;
      case 58:
        pos++;
        return token = 6;
      case 44:
        pos++;
        return token = 5;
      case 34:
        pos++;
        value = scanString();
        return token = 10;
      case 47:
        const start = pos - 1;
        if (text.charCodeAt(pos + 1) === 47) {
          pos += 2;
          while (pos < len) {
            if (isLineBreak2(text.charCodeAt(pos))) break;
            pos++;
          }
          value = text.substring(start, pos);
          return token = 12;
        }
        if (text.charCodeAt(pos + 1) === 42) {
          pos += 2;
          const safeLength = len - 1;
          let commentClosed = false;
          while (pos < safeLength) {
            const ch = text.charCodeAt(pos);
            if (ch === 42 && text.charCodeAt(pos + 1) === 47) {
              pos += 2;
              commentClosed = true;
              break;
            }
            pos++;
            if (isLineBreak2(ch)) {
              if (ch === 13 && text.charCodeAt(pos) === 10) pos++;
              lineNumber++;
              tokenLineStartOffset = pos;
            }
          }
          if (!commentClosed) {
            pos++;
            scanError = 1;
          }
          value = text.substring(start, pos);
          return token = 13;
        }
        value += String.fromCharCode(code);
        pos++;
        return token = 16;
      case 45:
        value += String.fromCharCode(code);
        pos++;
        if (pos === len || !isDigit2(text.charCodeAt(pos))) return token = 16;
      case 48:
      case 49:
      case 50:
      case 51:
      case 52:
      case 53:
      case 54:
      case 55:
      case 56:
      case 57:
        value += scanNumber();
        return token = 11;
      default:
        while (pos < len && isUnknownContentCharacter(code)) {
          pos++;
          code = text.charCodeAt(pos);
        }
        if (tokenOffset !== pos) {
          value = text.substring(tokenOffset, pos);
          switch (value) {
            case "true":
              return token = 8;
            case "false":
              return token = 9;
            case "null":
              return token = 7;
          }
          return token = 16;
        }
        value += String.fromCharCode(code);
        pos++;
        return token = 16;
    }
  }
  __name2(scanNext, "scanNext");
  function isUnknownContentCharacter(code) {
    if (isWhiteSpace2(code) || isLineBreak2(code)) return false;
    switch (code) {
      case 125:
      case 93:
      case 123:
      case 91:
      case 34:
      case 58:
      case 44:
      case 47:
        return false;
    }
    return true;
  }
  __name2(isUnknownContentCharacter, "isUnknownContentCharacter");
  function scanNextNonTrivia() {
    let result;
    do
      result = scanNext();
    while (result >= 12 && result <= 15);
    return result;
  }
  __name2(scanNextNonTrivia, "scanNextNonTrivia");
  return {
    setPosition,
    getPosition: /* @__PURE__ */ __name2(() => pos, "getPosition"),
    scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
    getToken: /* @__PURE__ */ __name2(() => token, "getToken"),
    getTokenValue: /* @__PURE__ */ __name2(() => value, "getTokenValue"),
    getTokenOffset: /* @__PURE__ */ __name2(() => tokenOffset, "getTokenOffset"),
    getTokenLength: /* @__PURE__ */ __name2(() => pos - tokenOffset, "getTokenLength"),
    getTokenStartLine: /* @__PURE__ */ __name2(() => lineStartOffset, "getTokenStartLine"),
    getTokenStartCharacter: /* @__PURE__ */ __name2(() => tokenOffset - prevTokenLineStartOffset, "getTokenStartCharacter"),
    getTokenError: /* @__PURE__ */ __name2(() => scanError, "getTokenError")
  };
}
__name2(createScanner2, "createScanner");
function isWhiteSpace2(ch) {
  return ch === 32 || ch === 9;
}
__name2(isWhiteSpace2, "isWhiteSpace");
function isLineBreak2(ch) {
  return ch === 10 || ch === 13;
}
__name2(isLineBreak2, "isLineBreak");
function isDigit2(ch) {
  return ch >= 48 && ch <= 57;
}
__name2(isDigit2, "isDigit");
var CharacterCodes2;
(function(CharacterCodes22) {
  CharacterCodes22[CharacterCodes22["lineFeed"] = 10] = "lineFeed";
  CharacterCodes22[CharacterCodes22["carriageReturn"] = 13] = "carriageReturn";
  CharacterCodes22[CharacterCodes22["space"] = 32] = "space";
  CharacterCodes22[CharacterCodes22["_0"] = 48] = "_0";
  CharacterCodes22[CharacterCodes22["_1"] = 49] = "_1";
  CharacterCodes22[CharacterCodes22["_2"] = 50] = "_2";
  CharacterCodes22[CharacterCodes22["_3"] = 51] = "_3";
  CharacterCodes22[CharacterCodes22["_4"] = 52] = "_4";
  CharacterCodes22[CharacterCodes22["_5"] = 53] = "_5";
  CharacterCodes22[CharacterCodes22["_6"] = 54] = "_6";
  CharacterCodes22[CharacterCodes22["_7"] = 55] = "_7";
  CharacterCodes22[CharacterCodes22["_8"] = 56] = "_8";
  CharacterCodes22[CharacterCodes22["_9"] = 57] = "_9";
  CharacterCodes22[CharacterCodes22["a"] = 97] = "a";
  CharacterCodes22[CharacterCodes22["b"] = 98] = "b";
  CharacterCodes22[CharacterCodes22["c"] = 99] = "c";
  CharacterCodes22[CharacterCodes22["d"] = 100] = "d";
  CharacterCodes22[CharacterCodes22["e"] = 101] = "e";
  CharacterCodes22[CharacterCodes22["f"] = 102] = "f";
  CharacterCodes22[CharacterCodes22["g"] = 103] = "g";
  CharacterCodes22[CharacterCodes22["h"] = 104] = "h";
  CharacterCodes22[CharacterCodes22["i"] = 105] = "i";
  CharacterCodes22[CharacterCodes22["j"] = 106] = "j";
  CharacterCodes22[CharacterCodes22["k"] = 107] = "k";
  CharacterCodes22[CharacterCodes22["l"] = 108] = "l";
  CharacterCodes22[CharacterCodes22["m"] = 109] = "m";
  CharacterCodes22[CharacterCodes22["n"] = 110] = "n";
  CharacterCodes22[CharacterCodes22["o"] = 111] = "o";
  CharacterCodes22[CharacterCodes22["p"] = 112] = "p";
  CharacterCodes22[CharacterCodes22["q"] = 113] = "q";
  CharacterCodes22[CharacterCodes22["r"] = 114] = "r";
  CharacterCodes22[CharacterCodes22["s"] = 115] = "s";
  CharacterCodes22[CharacterCodes22["t"] = 116] = "t";
  CharacterCodes22[CharacterCodes22["u"] = 117] = "u";
  CharacterCodes22[CharacterCodes22["v"] = 118] = "v";
  CharacterCodes22[CharacterCodes22["w"] = 119] = "w";
  CharacterCodes22[CharacterCodes22["x"] = 120] = "x";
  CharacterCodes22[CharacterCodes22["y"] = 121] = "y";
  CharacterCodes22[CharacterCodes22["z"] = 122] = "z";
  CharacterCodes22[CharacterCodes22["A"] = 65] = "A";
  CharacterCodes22[CharacterCodes22["B"] = 66] = "B";
  CharacterCodes22[CharacterCodes22["C"] = 67] = "C";
  CharacterCodes22[CharacterCodes22["D"] = 68] = "D";
  CharacterCodes22[CharacterCodes22["E"] = 69] = "E";
  CharacterCodes22[CharacterCodes22["F"] = 70] = "F";
  CharacterCodes22[CharacterCodes22["G"] = 71] = "G";
  CharacterCodes22[CharacterCodes22["H"] = 72] = "H";
  CharacterCodes22[CharacterCodes22["I"] = 73] = "I";
  CharacterCodes22[CharacterCodes22["J"] = 74] = "J";
  CharacterCodes22[CharacterCodes22["K"] = 75] = "K";
  CharacterCodes22[CharacterCodes22["L"] = 76] = "L";
  CharacterCodes22[CharacterCodes22["M"] = 77] = "M";
  CharacterCodes22[CharacterCodes22["N"] = 78] = "N";
  CharacterCodes22[CharacterCodes22["O"] = 79] = "O";
  CharacterCodes22[CharacterCodes22["P"] = 80] = "P";
  CharacterCodes22[CharacterCodes22["Q"] = 81] = "Q";
  CharacterCodes22[CharacterCodes22["R"] = 82] = "R";
  CharacterCodes22[CharacterCodes22["S"] = 83] = "S";
  CharacterCodes22[CharacterCodes22["T"] = 84] = "T";
  CharacterCodes22[CharacterCodes22["U"] = 85] = "U";
  CharacterCodes22[CharacterCodes22["V"] = 86] = "V";
  CharacterCodes22[CharacterCodes22["W"] = 87] = "W";
  CharacterCodes22[CharacterCodes22["X"] = 88] = "X";
  CharacterCodes22[CharacterCodes22["Y"] = 89] = "Y";
  CharacterCodes22[CharacterCodes22["Z"] = 90] = "Z";
  CharacterCodes22[CharacterCodes22["asterisk"] = 42] = "asterisk";
  CharacterCodes22[CharacterCodes22["backslash"] = 92] = "backslash";
  CharacterCodes22[CharacterCodes22["closeBrace"] = 125] = "closeBrace";
  CharacterCodes22[CharacterCodes22["closeBracket"] = 93] = "closeBracket";
  CharacterCodes22[CharacterCodes22["colon"] = 58] = "colon";
  CharacterCodes22[CharacterCodes22["comma"] = 44] = "comma";
  CharacterCodes22[CharacterCodes22["dot"] = 46] = "dot";
  CharacterCodes22[CharacterCodes22["doubleQuote"] = 34] = "doubleQuote";
  CharacterCodes22[CharacterCodes22["minus"] = 45] = "minus";
  CharacterCodes22[CharacterCodes22["openBrace"] = 123] = "openBrace";
  CharacterCodes22[CharacterCodes22["openBracket"] = 91] = "openBracket";
  CharacterCodes22[CharacterCodes22["plus"] = 43] = "plus";
  CharacterCodes22[CharacterCodes22["slash"] = 47] = "slash";
  CharacterCodes22[CharacterCodes22["formFeed"] = 12] = "formFeed";
  CharacterCodes22[CharacterCodes22["tab"] = 9] = "tab";
})(CharacterCodes2 || (CharacterCodes2 = {}));
function format3(documentText, range, options) {
  let initialIndentLevel;
  let formatText;
  let formatTextStart;
  let rangeStart;
  let rangeEnd;
  if (range) {
    rangeStart = range.offset;
    rangeEnd = rangeStart + range.length;
    formatTextStart = rangeStart;
    while (formatTextStart > 0 && !isEOL2(documentText, formatTextStart - 1)) formatTextStart--;
    let endOffset = rangeEnd;
    while (endOffset < documentText.length && !isEOL2(documentText, endOffset)) endOffset++;
    formatText = documentText.substring(formatTextStart, endOffset);
    initialIndentLevel = computeIndentLevel2(formatText, options);
  } else {
    formatText = documentText;
    initialIndentLevel = 0;
    formatTextStart = 0;
    rangeStart = 0;
    rangeEnd = documentText.length;
  }
  const eol = getEOL2(options, documentText);
  let numberLineBreaks = 0;
  let indentLevel = 0;
  let indentValue;
  if (options.insertSpaces) indentValue = repeat2(" ", options.tabSize || 4);
  else indentValue = "	";
  let scanner = createScanner2(formatText, false);
  let hasError = false;
  function newLinesAndIndent() {
    if (numberLineBreaks > 1) return repeat2(eol, numberLineBreaks) + repeat2(indentValue, initialIndentLevel + indentLevel);
    else return eol + repeat2(indentValue, initialIndentLevel + indentLevel);
  }
  __name2(newLinesAndIndent, "newLinesAndIndent");
  function scanNext() {
    let token = scanner.scan();
    numberLineBreaks = 0;
    while (token === 15 || token === 14) {
      if (token === 14 && options.keepLines) numberLineBreaks += 1;
      else if (token === 14) numberLineBreaks = 1;
      token = scanner.scan();
    }
    hasError = token === 16 || scanner.getTokenError() !== 0;
    return token;
  }
  __name2(scanNext, "scanNext");
  const editOperations = [];
  function addEdit(text, startOffset, endOffset) {
    if (!hasError && (!range || startOffset < rangeEnd && endOffset > rangeStart) && documentText.substring(startOffset, endOffset) !== text) editOperations.push({
      offset: startOffset,
      length: endOffset - startOffset,
      content: text
    });
  }
  __name2(addEdit, "addEdit");
  let firstToken = scanNext();
  if (options.keepLines && numberLineBreaks > 0) addEdit(repeat2(eol, numberLineBreaks), 0, 0);
  if (firstToken !== 17) {
    let firstTokenStart = scanner.getTokenOffset() + formatTextStart;
    addEdit(repeat2(indentValue, initialIndentLevel), formatTextStart, firstTokenStart);
  }
  while (firstToken !== 17) {
    let firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
    let secondToken = scanNext();
    let replaceContent = "";
    let needsLineBreak = false;
    while (numberLineBreaks === 0 && (secondToken === 12 || secondToken === 13)) {
      let commentTokenStart = scanner.getTokenOffset() + formatTextStart;
      addEdit(" ", firstTokenEnd, commentTokenStart);
      firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
      needsLineBreak = secondToken === 12;
      replaceContent = needsLineBreak ? newLinesAndIndent() : "";
      secondToken = scanNext();
    }
    if (secondToken === 2) {
      if (firstToken !== 1) indentLevel--;
      if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 1) replaceContent = newLinesAndIndent();
      else if (options.keepLines) replaceContent = " ";
    } else if (secondToken === 4) {
      if (firstToken !== 3) indentLevel--;
      if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 3) replaceContent = newLinesAndIndent();
      else if (options.keepLines) replaceContent = " ";
    } else {
      switch (firstToken) {
        case 3:
        case 1:
          indentLevel++;
          if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) replaceContent = newLinesAndIndent();
          else replaceContent = " ";
          break;
        case 5:
          if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) replaceContent = newLinesAndIndent();
          else replaceContent = " ";
          break;
        case 12:
          replaceContent = newLinesAndIndent();
          break;
        case 13:
          if (numberLineBreaks > 0) replaceContent = newLinesAndIndent();
          else if (!needsLineBreak) replaceContent = " ";
          break;
        case 6:
          if (options.keepLines && numberLineBreaks > 0) replaceContent = newLinesAndIndent();
          else if (!needsLineBreak) replaceContent = " ";
          break;
        case 10:
          if (options.keepLines && numberLineBreaks > 0) replaceContent = newLinesAndIndent();
          else if (secondToken === 6 && !needsLineBreak) replaceContent = "";
          break;
        case 7:
        case 8:
        case 9:
        case 11:
        case 2:
        case 4:
          if (options.keepLines && numberLineBreaks > 0) replaceContent = newLinesAndIndent();
          else if ((secondToken === 12 || secondToken === 13) && !needsLineBreak) replaceContent = " ";
          else if (secondToken !== 5 && secondToken !== 17) hasError = true;
          break;
        case 16:
          hasError = true;
          break;
      }
      if (numberLineBreaks > 0 && (secondToken === 12 || secondToken === 13)) replaceContent = newLinesAndIndent();
    }
    if (secondToken === 17) if (options.keepLines && numberLineBreaks > 0) replaceContent = newLinesAndIndent();
    else replaceContent = options.insertFinalNewline ? eol : "";
    const secondTokenStart = scanner.getTokenOffset() + formatTextStart;
    addEdit(replaceContent, firstTokenEnd, secondTokenStart);
    firstToken = secondToken;
  }
  return editOperations;
}
__name2(format3, "format");
function repeat2(s, count) {
  let result = "";
  for (let i = 0; i < count; i++) result += s;
  return result;
}
__name2(repeat2, "repeat");
function computeIndentLevel2(content, options) {
  let i = 0;
  let nChars = 0;
  const tabSize = options.tabSize || 4;
  while (i < content.length) {
    let ch = content.charAt(i);
    if (ch === " ") nChars++;
    else if (ch === "	") nChars += tabSize;
    else break;
    i++;
  }
  return Math.floor(nChars / tabSize);
}
__name2(computeIndentLevel2, "computeIndentLevel");
function getEOL2(options, text) {
  for (let i = 0; i < text.length; i++) {
    const ch = text.charAt(i);
    if (ch === "\r") {
      if (i + 1 < text.length && text.charAt(i + 1) === "\n") return "\r\n";
      return "\r";
    } else if (ch === "\n") return "\n";
  }
  return options && options.eol || "\n";
}
__name2(getEOL2, "getEOL");
function isEOL2(text, offset) {
  return "\r\n".indexOf(text.charAt(offset)) !== -1;
}
__name2(isEOL2, "isEOL");
var ParseOptions2;
(function(ParseOptions22) {
  ParseOptions22.DEFAULT = { allowTrailingComma: false };
})(ParseOptions2 || (ParseOptions2 = {}));
function parse7(text, errors = [], options = ParseOptions2.DEFAULT) {
  let currentProperty = null;
  let currentParent = [];
  const previousParents = [];
  function onValue(value) {
    if (Array.isArray(currentParent)) currentParent.push(value);
    else if (currentProperty !== null) currentParent[currentProperty] = value;
  }
  __name2(onValue, "onValue");
  visit2(text, {
    onObjectBegin: /* @__PURE__ */ __name2(() => {
      const object3 = {};
      onValue(object3);
      previousParents.push(currentParent);
      currentParent = object3;
      currentProperty = null;
    }, "onObjectBegin"),
    onObjectProperty: /* @__PURE__ */ __name2((name) => {
      currentProperty = name;
    }, "onObjectProperty"),
    onObjectEnd: /* @__PURE__ */ __name2(() => {
      currentParent = previousParents.pop();
    }, "onObjectEnd"),
    onArrayBegin: /* @__PURE__ */ __name2(() => {
      const array3 = [];
      onValue(array3);
      previousParents.push(currentParent);
      currentParent = array3;
      currentProperty = null;
    }, "onArrayBegin"),
    onArrayEnd: /* @__PURE__ */ __name2(() => {
      currentParent = previousParents.pop();
    }, "onArrayEnd"),
    onLiteralValue: onValue,
    onError: /* @__PURE__ */ __name2((error101, offset, length) => {
      errors.push({
        error: error101,
        offset,
        length
      });
    }, "onError")
  }, options);
  return currentParent[0];
}
__name2(parse7, "parse");
function parseTree2(text, errors = [], options = ParseOptions2.DEFAULT) {
  let currentParent = {
    type: "array",
    offset: -1,
    length: -1,
    children: [],
    parent: void 0
  };
  function ensurePropertyComplete(endOffset) {
    if (currentParent.type === "property") {
      currentParent.length = endOffset - currentParent.offset;
      currentParent = currentParent.parent;
    }
  }
  __name2(ensurePropertyComplete, "ensurePropertyComplete");
  function onValue(valueNode) {
    currentParent.children.push(valueNode);
    return valueNode;
  }
  __name2(onValue, "onValue");
  visit2(text, {
    onObjectBegin: /* @__PURE__ */ __name2((offset) => {
      currentParent = onValue({
        type: "object",
        offset,
        length: -1,
        parent: currentParent,
        children: []
      });
    }, "onObjectBegin"),
    onObjectProperty: /* @__PURE__ */ __name2((name, offset, length) => {
      currentParent = onValue({
        type: "property",
        offset,
        length: -1,
        parent: currentParent,
        children: []
      });
      currentParent.children.push({
        type: "string",
        value: name,
        offset,
        length,
        parent: currentParent
      });
    }, "onObjectProperty"),
    onObjectEnd: /* @__PURE__ */ __name2((offset, length) => {
      ensurePropertyComplete(offset + length);
      currentParent.length = offset + length - currentParent.offset;
      currentParent = currentParent.parent;
      ensurePropertyComplete(offset + length);
    }, "onObjectEnd"),
    onArrayBegin: /* @__PURE__ */ __name2((offset, length) => {
      currentParent = onValue({
        type: "array",
        offset,
        length: -1,
        parent: currentParent,
        children: []
      });
    }, "onArrayBegin"),
    onArrayEnd: /* @__PURE__ */ __name2((offset, length) => {
      currentParent.length = offset + length - currentParent.offset;
      currentParent = currentParent.parent;
      ensurePropertyComplete(offset + length);
    }, "onArrayEnd"),
    onLiteralValue: /* @__PURE__ */ __name2((value, offset, length) => {
      onValue({
        type: getNodeType2(value),
        offset,
        length,
        parent: currentParent,
        value
      });
      ensurePropertyComplete(offset + length);
    }, "onLiteralValue"),
    onSeparator: /* @__PURE__ */ __name2((sep2, offset, length) => {
      if (currentParent.type === "property") {
        if (sep2 === ":") currentParent.colonOffset = offset;
        else if (sep2 === ",") ensurePropertyComplete(offset);
      }
    }, "onSeparator"),
    onError: /* @__PURE__ */ __name2((error101, offset, length) => {
      errors.push({
        error: error101,
        offset,
        length
      });
    }, "onError")
  }, options);
  const result = currentParent.children[0];
  if (result) delete result.parent;
  return result;
}
__name2(parseTree2, "parseTree");
function findNodeAtLocation2(root, path210) {
  if (!root) return;
  let node = root;
  for (let segment of path210) if (typeof segment === "string") {
    if (node.type !== "object" || !Array.isArray(node.children)) return;
    let found = false;
    for (const propertyNode of node.children) if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) {
      node = propertyNode.children[1];
      found = true;
      break;
    }
    if (!found) return;
  } else {
    const index = segment;
    if (node.type !== "array" || index < 0 || !Array.isArray(node.children) || index >= node.children.length) return;
    node = node.children[index];
  }
  return node;
}
__name2(findNodeAtLocation2, "findNodeAtLocation");
function visit2(text, visitor, options = ParseOptions2.DEFAULT) {
  const _scanner = createScanner2(text, false);
  const _jsonPath = [];
  function toNoArgVisit(visitFunction) {
    return visitFunction ? () => visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
  }
  __name2(toNoArgVisit, "toNoArgVisit");
  function toNoArgVisitWithPath(visitFunction) {
    return visitFunction ? () => visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;
  }
  __name2(toNoArgVisitWithPath, "toNoArgVisitWithPath");
  function toOneArgVisit(visitFunction) {
    return visitFunction ? (arg) => visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
  }
  __name2(toOneArgVisit, "toOneArgVisit");
  function toOneArgVisitWithPath(visitFunction) {
    return visitFunction ? (arg) => visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;
  }
  __name2(toOneArgVisitWithPath, "toOneArgVisitWithPath");
  const onObjectBegin = toNoArgVisitWithPath(visitor.onObjectBegin), onObjectProperty = toOneArgVisitWithPath(visitor.onObjectProperty), onObjectEnd = toNoArgVisit(visitor.onObjectEnd), onArrayBegin = toNoArgVisitWithPath(visitor.onArrayBegin), onArrayEnd = toNoArgVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisitWithPath(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError);
  const disallowComments = options && options.disallowComments;
  const allowTrailingComma = options && options.allowTrailingComma;
  function scanNext() {
    while (true) {
      const token = _scanner.scan();
      switch (_scanner.getTokenError()) {
        case 4:
          handleError(14);
          break;
        case 5:
          handleError(15);
          break;
        case 3:
          handleError(13);
          break;
        case 1:
          if (!disallowComments) handleError(11);
          break;
        case 2:
          handleError(12);
          break;
        case 6:
          handleError(16);
          break;
      }
      switch (token) {
        case 12:
        case 13:
          if (disallowComments) handleError(10);
          else onComment();
          break;
        case 16:
          handleError(1);
          break;
        case 15:
        case 14:
          break;
        default:
          return token;
      }
    }
  }
  __name2(scanNext, "scanNext");
  function handleError(error101, skipUntilAfter = [], skipUntil22 = []) {
    onError(error101);
    if (skipUntilAfter.length + skipUntil22.length > 0) {
      let token = _scanner.getToken();
      while (token !== 17) {
        if (skipUntilAfter.indexOf(token) !== -1) {
          scanNext();
          break;
        } else if (skipUntil22.indexOf(token) !== -1) break;
        token = scanNext();
      }
    }
  }
  __name2(handleError, "handleError");
  function parseString22(isValue) {
    const value = _scanner.getTokenValue();
    if (isValue) onLiteralValue(value);
    else {
      onObjectProperty(value);
      _jsonPath.push(value);
    }
    scanNext();
    return true;
  }
  __name2(parseString22, "parseString");
  function parseLiteral() {
    switch (_scanner.getToken()) {
      case 11:
        const tokenValue = _scanner.getTokenValue();
        let value = Number(tokenValue);
        if (isNaN(value)) {
          handleError(2);
          value = 0;
        }
        onLiteralValue(value);
        break;
      case 7:
        onLiteralValue(null);
        break;
      case 8:
        onLiteralValue(true);
        break;
      case 9:
        onLiteralValue(false);
        break;
      default:
        return false;
    }
    scanNext();
    return true;
  }
  __name2(parseLiteral, "parseLiteral");
  function parseProperty() {
    if (_scanner.getToken() !== 10) {
      handleError(3, [], [2, 5]);
      return false;
    }
    parseString22(false);
    if (_scanner.getToken() === 6) {
      onSeparator(":");
      scanNext();
      if (!parseValue22()) handleError(4, [], [2, 5]);
    } else handleError(5, [], [2, 5]);
    _jsonPath.pop();
    return true;
  }
  __name2(parseProperty, "parseProperty");
  function parseObject() {
    onObjectBegin();
    scanNext();
    let needsComma = false;
    while (_scanner.getToken() !== 2 && _scanner.getToken() !== 17) {
      if (_scanner.getToken() === 5) {
        if (!needsComma) handleError(4, [], []);
        onSeparator(",");
        scanNext();
        if (_scanner.getToken() === 2 && allowTrailingComma) break;
      } else if (needsComma) handleError(6, [], []);
      if (!parseProperty()) handleError(4, [], [2, 5]);
      needsComma = true;
    }
    onObjectEnd();
    if (_scanner.getToken() !== 2) handleError(7, [2], []);
    else scanNext();
    return true;
  }
  __name2(parseObject, "parseObject");
  function parseArray22() {
    onArrayBegin();
    scanNext();
    let isFirstElement = true;
    let needsComma = false;
    while (_scanner.getToken() !== 4 && _scanner.getToken() !== 17) {
      if (_scanner.getToken() === 5) {
        if (!needsComma) handleError(4, [], []);
        onSeparator(",");
        scanNext();
        if (_scanner.getToken() === 4 && allowTrailingComma) break;
      } else if (needsComma) handleError(6, [], []);
      if (isFirstElement) {
        _jsonPath.push(0);
        isFirstElement = false;
      } else _jsonPath[_jsonPath.length - 1]++;
      if (!parseValue22()) handleError(4, [], [4, 5]);
      needsComma = true;
    }
    onArrayEnd();
    if (!isFirstElement) _jsonPath.pop();
    if (_scanner.getToken() !== 4) handleError(8, [4], []);
    else scanNext();
    return true;
  }
  __name2(parseArray22, "parseArray");
  function parseValue22() {
    switch (_scanner.getToken()) {
      case 3:
        return parseArray22();
      case 1:
        return parseObject();
      case 10:
        return parseString22(true);
      default:
        return parseLiteral();
    }
  }
  __name2(parseValue22, "parseValue");
  scanNext();
  if (_scanner.getToken() === 17) {
    if (options.allowEmptyContent) return true;
    handleError(4, [], []);
    return false;
  }
  if (!parseValue22()) {
    handleError(4, [], []);
    return false;
  }
  if (_scanner.getToken() !== 17) handleError(9, [], []);
  return true;
}
__name2(visit2, "visit");
function getNodeType2(value) {
  switch (typeof value) {
    case "boolean":
      return "boolean";
    case "number":
      return "number";
    case "string":
      return "string";
    case "object":
      if (!value) return "null";
      else if (Array.isArray(value)) return "array";
      return "object";
    default:
      return "null";
  }
}
__name2(getNodeType2, "getNodeType");
function setProperty2(text, originalPath, value, options) {
  const path210 = originalPath.slice();
  const root = parseTree2(text, []);
  let parent = void 0;
  let lastSegment = void 0;
  while (path210.length > 0) {
    lastSegment = path210.pop();
    parent = findNodeAtLocation2(root, path210);
    if (parent === void 0 && value !== void 0) if (typeof lastSegment === "string") value = { [lastSegment]: value };
    else value = [value];
    else break;
  }
  if (!parent) {
    if (value === void 0) throw new Error("Can not delete in empty document");
    return withFormatting2(text, {
      offset: root ? root.offset : 0,
      length: root ? root.length : 0,
      content: JSON.stringify(value)
    }, options);
  } else if (parent.type === "object" && typeof lastSegment === "string" && Array.isArray(parent.children)) {
    const existing = findNodeAtLocation2(parent, [lastSegment]);
    if (existing !== void 0) if (value === void 0) {
      if (!existing.parent) throw new Error("Malformed AST");
      const propertyIndex = parent.children.indexOf(existing.parent);
      let removeBegin;
      let removeEnd = existing.parent.offset + existing.parent.length;
      if (propertyIndex > 0) {
        let previous = parent.children[propertyIndex - 1];
        removeBegin = previous.offset + previous.length;
      } else {
        removeBegin = parent.offset + 1;
        if (parent.children.length > 1) removeEnd = parent.children[1].offset;
      }
      return withFormatting2(text, {
        offset: removeBegin,
        length: removeEnd - removeBegin,
        content: ""
      }, options);
    } else return withFormatting2(text, {
      offset: existing.offset,
      length: existing.length,
      content: JSON.stringify(value)
    }, options);
    else {
      if (value === void 0) return [];
      const newProperty = `${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`;
      const index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map((p2) => p2.children[0].value)) : parent.children.length;
      let edit;
      if (index > 0) {
        let previous = parent.children[index - 1];
        edit = {
          offset: previous.offset + previous.length,
          length: 0,
          content: "," + newProperty
        };
      } else if (parent.children.length === 0) edit = {
        offset: parent.offset + 1,
        length: 0,
        content: newProperty
      };
      else edit = {
        offset: parent.offset + 1,
        length: 0,
        content: newProperty + ","
      };
      return withFormatting2(text, edit, options);
    }
  } else if (parent.type === "array" && typeof lastSegment === "number" && Array.isArray(parent.children)) {
    const insertIndex = lastSegment;
    if (insertIndex === -1) {
      const newProperty = `${JSON.stringify(value)}`;
      let edit;
      if (parent.children.length === 0) edit = {
        offset: parent.offset + 1,
        length: 0,
        content: newProperty
      };
      else {
        const previous = parent.children[parent.children.length - 1];
        edit = {
          offset: previous.offset + previous.length,
          length: 0,
          content: "," + newProperty
        };
      }
      return withFormatting2(text, edit, options);
    } else if (value === void 0 && parent.children.length >= 0) {
      const removalIndex = lastSegment;
      const toRemove = parent.children[removalIndex];
      let edit;
      if (parent.children.length === 1) edit = {
        offset: parent.offset + 1,
        length: parent.length - 2,
        content: ""
      };
      else if (parent.children.length - 1 === removalIndex) {
        let previous = parent.children[removalIndex - 1];
        let offset = previous.offset + previous.length;
        edit = {
          offset,
          length: parent.offset + parent.length - 2 - offset,
          content: ""
        };
      } else edit = {
        offset: toRemove.offset,
        length: parent.children[removalIndex + 1].offset - toRemove.offset,
        content: ""
      };
      return withFormatting2(text, edit, options);
    } else if (value !== void 0) {
      let edit;
      const newProperty = `${JSON.stringify(value)}`;
      if (!options.isArrayInsertion && parent.children.length > lastSegment) {
        const toModify = parent.children[lastSegment];
        edit = {
          offset: toModify.offset,
          length: toModify.length,
          content: newProperty
        };
      } else if (parent.children.length === 0 || lastSegment === 0) edit = {
        offset: parent.offset + 1,
        length: 0,
        content: parent.children.length === 0 ? newProperty : newProperty + ","
      };
      else {
        const index = lastSegment > parent.children.length ? parent.children.length : lastSegment;
        const previous = parent.children[index - 1];
        edit = {
          offset: previous.offset + previous.length,
          length: 0,
          content: "," + newProperty
        };
      }
      return withFormatting2(text, edit, options);
    } else throw new Error(`Can not ${value === void 0 ? "remove" : options.isArrayInsertion ? "insert" : "modify"} Array index ${insertIndex} as length is not sufficient`);
  } else throw new Error(`Can not add ${typeof lastSegment !== "number" ? "index" : "property"} to parent of type ${parent.type}`);
}
__name2(setProperty2, "setProperty");
function withFormatting2(text, edit, options) {
  if (!options.formattingOptions) return [edit];
  let newText = applyEdit2(text, edit);
  let begin = edit.offset;
  let end = edit.offset + edit.content.length;
  if (edit.length === 0 || edit.content.length === 0) {
    while (begin > 0 && !isEOL2(newText, begin - 1)) begin--;
    while (end < newText.length && !isEOL2(newText, end)) end++;
  }
  const edits = format3(newText, {
    offset: begin,
    length: end - begin
  }, {
    ...options.formattingOptions,
    keepLines: false
  });
  for (let i = edits.length - 1; i >= 0; i--) {
    const edit2 = edits[i];
    newText = applyEdit2(newText, edit2);
    begin = Math.min(begin, edit2.offset);
    end = Math.max(end, edit2.offset + edit2.length);
    end += edit2.content.length - edit2.length;
  }
  const editLength = text.length - (newText.length - end) - begin;
  return [{
    offset: begin,
    length: editLength,
    content: newText.substring(begin, end)
  }];
}
__name2(withFormatting2, "withFormatting");
function applyEdit2(text, edit) {
  return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);
}
__name2(applyEdit2, "applyEdit");
var ScanError2;
(function(ScanError22) {
  ScanError22[ScanError22["None"] = 0] = "None";
  ScanError22[ScanError22["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment";
  ScanError22[ScanError22["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString";
  ScanError22[ScanError22["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber";
  ScanError22[ScanError22["InvalidUnicode"] = 4] = "InvalidUnicode";
  ScanError22[ScanError22["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter";
  ScanError22[ScanError22["InvalidCharacter"] = 6] = "InvalidCharacter";
})(ScanError2 || (ScanError2 = {}));
var SyntaxKind2;
(function(SyntaxKind22) {
  SyntaxKind22[SyntaxKind22["OpenBraceToken"] = 1] = "OpenBraceToken";
  SyntaxKind22[SyntaxKind22["CloseBraceToken"] = 2] = "CloseBraceToken";
  SyntaxKind22[SyntaxKind22["OpenBracketToken"] = 3] = "OpenBracketToken";
  SyntaxKind22[SyntaxKind22["CloseBracketToken"] = 4] = "CloseBracketToken";
  SyntaxKind22[SyntaxKind22["CommaToken"] = 5] = "CommaToken";
  SyntaxKind22[SyntaxKind22["ColonToken"] = 6] = "ColonToken";
  SyntaxKind22[SyntaxKind22["NullKeyword"] = 7] = "NullKeyword";
  SyntaxKind22[SyntaxKind22["TrueKeyword"] = 8] = "TrueKeyword";
  SyntaxKind22[SyntaxKind22["FalseKeyword"] = 9] = "FalseKeyword";
  SyntaxKind22[SyntaxKind22["StringLiteral"] = 10] = "StringLiteral";
  SyntaxKind22[SyntaxKind22["NumericLiteral"] = 11] = "NumericLiteral";
  SyntaxKind22[SyntaxKind22["LineCommentTrivia"] = 12] = "LineCommentTrivia";
  SyntaxKind22[SyntaxKind22["BlockCommentTrivia"] = 13] = "BlockCommentTrivia";
  SyntaxKind22[SyntaxKind22["LineBreakTrivia"] = 14] = "LineBreakTrivia";
  SyntaxKind22[SyntaxKind22["Trivia"] = 15] = "Trivia";
  SyntaxKind22[SyntaxKind22["Unknown"] = 16] = "Unknown";
  SyntaxKind22[SyntaxKind22["EOF"] = 17] = "EOF";
})(SyntaxKind2 || (SyntaxKind2 = {}));
var parse23 = parse7;
var ParseErrorCode2;
(function(ParseErrorCode22) {
  ParseErrorCode22[ParseErrorCode22["InvalidSymbol"] = 1] = "InvalidSymbol";
  ParseErrorCode22[ParseErrorCode22["InvalidNumberFormat"] = 2] = "InvalidNumberFormat";
  ParseErrorCode22[ParseErrorCode22["PropertyNameExpected"] = 3] = "PropertyNameExpected";
  ParseErrorCode22[ParseErrorCode22["ValueExpected"] = 4] = "ValueExpected";
  ParseErrorCode22[ParseErrorCode22["ColonExpected"] = 5] = "ColonExpected";
  ParseErrorCode22[ParseErrorCode22["CommaExpected"] = 6] = "CommaExpected";
  ParseErrorCode22[ParseErrorCode22["CloseBraceExpected"] = 7] = "CloseBraceExpected";
  ParseErrorCode22[ParseErrorCode22["CloseBracketExpected"] = 8] = "CloseBracketExpected";
  ParseErrorCode22[ParseErrorCode22["EndOfFileExpected"] = 9] = "EndOfFileExpected";
  ParseErrorCode22[ParseErrorCode22["InvalidCommentToken"] = 10] = "InvalidCommentToken";
  ParseErrorCode22[ParseErrorCode22["UnexpectedEndOfComment"] = 11] = "UnexpectedEndOfComment";
  ParseErrorCode22[ParseErrorCode22["UnexpectedEndOfString"] = 12] = "UnexpectedEndOfString";
  ParseErrorCode22[ParseErrorCode22["UnexpectedEndOfNumber"] = 13] = "UnexpectedEndOfNumber";
  ParseErrorCode22[ParseErrorCode22["InvalidUnicode"] = 14] = "InvalidUnicode";
  ParseErrorCode22[ParseErrorCode22["InvalidEscapeCharacter"] = 15] = "InvalidEscapeCharacter";
  ParseErrorCode22[ParseErrorCode22["InvalidCharacter"] = 16] = "InvalidCharacter";
})(ParseErrorCode2 || (ParseErrorCode2 = {}));
function printParseErrorCode2(code) {
  switch (code) {
    case 1:
      return "InvalidSymbol";
    case 2:
      return "InvalidNumberFormat";
    case 3:
      return "PropertyNameExpected";
    case 4:
      return "ValueExpected";
    case 5:
      return "ColonExpected";
    case 6:
      return "CommaExpected";
    case 7:
      return "CloseBraceExpected";
    case 8:
      return "CloseBracketExpected";
    case 9:
      return "EndOfFileExpected";
    case 10:
      return "InvalidCommentToken";
    case 11:
      return "UnexpectedEndOfComment";
    case 12:
      return "UnexpectedEndOfString";
    case 13:
      return "UnexpectedEndOfNumber";
    case 14:
      return "InvalidUnicode";
    case 15:
      return "InvalidEscapeCharacter";
    case 16:
      return "InvalidCharacter";
  }
  return "<unknown ParseErrorCode>";
}
__name2(printParseErrorCode2, "printParseErrorCode");
function format22(documentText, range, options) {
  return format3(documentText, range, options);
}
__name2(format22, "format");
function modify2(text, path210, value, options) {
  return setProperty2(text, path210, value, options);
}
__name2(modify2, "modify");
function applyEdits2(text, edits) {
  let sortedEdits = edits.slice(0).sort((a, b) => {
    const diff = a.offset - b.offset;
    if (diff === 0) return a.length - b.length;
    return diff;
  });
  let lastModifiedOffset = text.length;
  for (let i = sortedEdits.length - 1; i >= 0; i--) {
    let e = sortedEdits[i];
    if (e.offset + e.length <= lastModifiedOffset) text = applyEdit2(text, e);
    else throw new Error("Overlapping edit");
    lastModifiedOffset = e.offset;
  }
  return text;
}
__name2(applyEdits2, "applyEdits");
function getLineColFromPtr2(string7, ptr) {
  let lines = string7.slice(0, ptr).split(/\r\n|\n|\r/g);
  return [lines.length, lines.pop().length + 1];
}
__name2(getLineColFromPtr2, "getLineColFromPtr");
function makeCodeBlock2(string7, line, column) {
  let lines = string7.split(/\r\n|\n|\r/g);
  let codeblock = "";
  let numberLen = (Math.log10(line + 1) | 0) + 1;
  for (let i = line - 1; i <= line + 1; i++) {
    let l = lines[i - 1];
    if (!l) continue;
    codeblock += i.toString().padEnd(numberLen, " ");
    codeblock += ":  ";
    codeblock += l;
    codeblock += "\n";
    if (i === line) {
      codeblock += " ".repeat(numberLen + column + 2);
      codeblock += "^\n";
    }
  }
  return codeblock;
}
__name2(makeCodeBlock2, "makeCodeBlock");
var TomlError2 = class extends Error {
  static {
    __name2(this, "TomlError");
  }
  line;
  column;
  codeblock;
  constructor(message, options) {
    const [line, column] = getLineColFromPtr2(options.toml, options.ptr);
    const codeblock = makeCodeBlock2(options.toml, line, column);
    super(`Invalid TOML document: ${message}

${codeblock}`, options);
    this.line = line;
    this.column = column;
    this.codeblock = codeblock;
  }
};
function isEscaped2(str, ptr) {
  let i = 0;
  while (str[ptr - ++i] === "\\") ;
  return --i && i % 2;
}
__name2(isEscaped2, "isEscaped");
function indexOfNewline2(str, start = 0, end = str.length) {
  let idx = str.indexOf("\n", start);
  if (str[idx - 1] === "\r") idx--;
  return idx <= end ? idx : -1;
}
__name2(indexOfNewline2, "indexOfNewline");
function skipComment2(str, ptr) {
  for (let i = ptr; i < str.length; i++) {
    let c2 = str[i];
    if (c2 === "\n") return i;
    if (c2 === "\r" && str[i + 1] === "\n") return i + 1;
    if (c2 < " " && c2 !== "	" || c2 === "\x7F") throw new TomlError2("control characters are not allowed in comments", {
      toml: str,
      ptr
    });
  }
  return str.length;
}
__name2(skipComment2, "skipComment");
function skipVoid2(str, ptr, banNewLines, banComments) {
  let c2;
  while ((c2 = str[ptr]) === " " || c2 === "	" || !banNewLines && (c2 === "\n" || c2 === "\r" && str[ptr + 1] === "\n")) ptr++;
  return banComments || c2 !== "#" ? ptr : skipVoid2(str, skipComment2(str, ptr), banNewLines);
}
__name2(skipVoid2, "skipVoid");
function skipUntil2(str, ptr, sep2, end, banNewLines = false) {
  if (!end) {
    ptr = indexOfNewline2(str, ptr);
    return ptr < 0 ? str.length : ptr;
  }
  for (let i = ptr; i < str.length; i++) {
    let c2 = str[i];
    if (c2 === "#") i = indexOfNewline2(str, i);
    else if (c2 === sep2) return i + 1;
    else if (c2 === end || banNewLines && (c2 === "\n" || c2 === "\r" && str[i + 1] === "\n")) return i;
  }
  throw new TomlError2("cannot find end of structure", {
    toml: str,
    ptr
  });
}
__name2(skipUntil2, "skipUntil");
function getStringEnd2(str, seek) {
  let first = str[seek];
  let target = first === str[seek + 1] && str[seek + 1] === str[seek + 2] ? str.slice(seek, seek + 3) : first;
  seek += target.length - 1;
  do
    seek = str.indexOf(target, ++seek);
  while (seek > -1 && first !== "'" && isEscaped2(str, seek));
  if (seek > -1) {
    seek += target.length;
    if (target.length > 1) {
      if (str[seek] === first) seek++;
      if (str[seek] === first) seek++;
    }
  }
  return seek;
}
__name2(getStringEnd2, "getStringEnd");
var DATE_TIME_RE2 = /^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}:\d{2}(?:\.\d+)?)?(Z|[-+]\d{2}:\d{2})?$/i;
var TomlDate2 = class _TomlDate2 extends Date {
  static {
    __name2(this, "TomlDate");
  }
  #hasDate = false;
  #hasTime = false;
  #offset = null;
  constructor(date9) {
    let hasDate = true;
    let hasTime = true;
    let offset = "Z";
    if (typeof date9 === "string") {
      let match = date9.match(DATE_TIME_RE2);
      if (match) {
        if (!match[1]) {
          hasDate = false;
          date9 = `0000-01-01T${date9}`;
        }
        hasTime = !!match[2];
        hasTime && date9[10] === " " && (date9 = date9.replace(" ", "T"));
        if (match[2] && +match[2] > 23) date9 = "";
        else {
          offset = match[3] || null;
          date9 = date9.toUpperCase();
          if (!offset && hasTime) date9 += "Z";
        }
      } else date9 = "";
    }
    super(date9);
    if (!isNaN(this.getTime())) {
      this.#hasDate = hasDate;
      this.#hasTime = hasTime;
      this.#offset = offset;
    }
  }
  isDateTime() {
    return this.#hasDate && this.#hasTime;
  }
  isLocal() {
    return !this.#hasDate || !this.#hasTime || !this.#offset;
  }
  isDate() {
    return this.#hasDate && !this.#hasTime;
  }
  isTime() {
    return this.#hasTime && !this.#hasDate;
  }
  isValid() {
    return this.#hasDate || this.#hasTime;
  }
  toISOString() {
    let iso = super.toISOString();
    if (this.isDate()) return iso.slice(0, 10);
    if (this.isTime()) return iso.slice(11, 23);
    if (this.#offset === null) return iso.slice(0, -1);
    if (this.#offset === "Z") return iso;
    let offset = +this.#offset.slice(1, 3) * 60 + +this.#offset.slice(4, 6);
    offset = this.#offset[0] === "-" ? offset : -offset;
    return (/* @__PURE__ */ new Date(this.getTime() - offset * 6e4)).toISOString().slice(0, -1) + this.#offset;
  }
  static wrapAsOffsetDateTime(jsDate, offset = "Z") {
    let date9 = new _TomlDate2(jsDate);
    date9.#offset = offset;
    return date9;
  }
  static wrapAsLocalDateTime(jsDate) {
    let date9 = new _TomlDate2(jsDate);
    date9.#offset = null;
    return date9;
  }
  static wrapAsLocalDate(jsDate) {
    let date9 = new _TomlDate2(jsDate);
    date9.#hasTime = false;
    date9.#offset = null;
    return date9;
  }
  static wrapAsLocalTime(jsDate) {
    let date9 = new _TomlDate2(jsDate);
    date9.#hasDate = false;
    date9.#offset = null;
    return date9;
  }
};
var INT_REGEX2 = /^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/;
var FLOAT_REGEX2 = /^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/;
var LEADING_ZERO2 = /^[+-]?0[0-9_]/;
var ESCAPE_REGEX2 = /^[0-9a-f]{4,8}$/i;
var ESC_MAP2 = {
  b: "\b",
  t: "	",
  n: "\n",
  f: "\f",
  r: "\r",
  '"': '"',
  "\\": "\\"
};
function parseString2(str, ptr = 0, endPtr = str.length) {
  let isLiteral = str[ptr] === "'";
  let isMultiline = str[ptr++] === str[ptr] && str[ptr] === str[ptr + 1];
  if (isMultiline) {
    endPtr -= 2;
    if (str[ptr += 2] === "\r") ptr++;
    if (str[ptr] === "\n") ptr++;
  }
  let tmp = 0;
  let isEscape;
  let parsed = "";
  let sliceStart = ptr;
  while (ptr < endPtr - 1) {
    let c2 = str[ptr++];
    if (c2 === "\n" || c2 === "\r" && str[ptr] === "\n") {
      if (!isMultiline) throw new TomlError2("newlines are not allowed in strings", {
        toml: str,
        ptr: ptr - 1
      });
    } else if (c2 < " " && c2 !== "	" || c2 === "\x7F") throw new TomlError2("control characters are not allowed in strings", {
      toml: str,
      ptr: ptr - 1
    });
    if (isEscape) {
      isEscape = false;
      if (c2 === "u" || c2 === "U") {
        let code = str.slice(ptr, ptr += c2 === "u" ? 4 : 8);
        if (!ESCAPE_REGEX2.test(code)) throw new TomlError2("invalid unicode escape", {
          toml: str,
          ptr: tmp
        });
        try {
          parsed += String.fromCodePoint(parseInt(code, 16));
        } catch {
          throw new TomlError2("invalid unicode escape", {
            toml: str,
            ptr: tmp
          });
        }
      } else if (isMultiline && (c2 === "\n" || c2 === " " || c2 === "	" || c2 === "\r")) {
        ptr = skipVoid2(str, ptr - 1, true);
        if (str[ptr] !== "\n" && str[ptr] !== "\r") throw new TomlError2("invalid escape: only line-ending whitespace may be escaped", {
          toml: str,
          ptr: tmp
        });
        ptr = skipVoid2(str, ptr);
      } else if (c2 in ESC_MAP2) parsed += ESC_MAP2[c2];
      else throw new TomlError2("unrecognized escape sequence", {
        toml: str,
        ptr: tmp
      });
      sliceStart = ptr;
    } else if (!isLiteral && c2 === "\\") {
      tmp = ptr - 1;
      isEscape = true;
      parsed += str.slice(sliceStart, tmp);
    }
  }
  return parsed + str.slice(sliceStart, endPtr - 1);
}
__name2(parseString2, "parseString");
function parseValue2(value, toml, ptr, integersAsBigInt) {
  if (value === "true") return true;
  if (value === "false") return false;
  if (value === "-inf") return -Infinity;
  if (value === "inf" || value === "+inf") return Infinity;
  if (value === "nan" || value === "+nan" || value === "-nan") return NaN;
  if (value === "-0") return integersAsBigInt ? 0n : 0;
  let isInt = INT_REGEX2.test(value);
  if (isInt || FLOAT_REGEX2.test(value)) {
    if (LEADING_ZERO2.test(value)) throw new TomlError2("leading zeroes are not allowed", {
      toml,
      ptr
    });
    value = value.replace(/_/g, "");
    let numeric = +value;
    if (isNaN(numeric)) throw new TomlError2("invalid number", {
      toml,
      ptr
    });
    if (isInt) {
      if ((isInt = !Number.isSafeInteger(numeric)) && !integersAsBigInt) throw new TomlError2("integer value cannot be represented losslessly", {
        toml,
        ptr
      });
      if (isInt || integersAsBigInt === true) numeric = BigInt(value);
    }
    return numeric;
  }
  const date9 = new TomlDate2(value);
  if (!date9.isValid()) throw new TomlError2("invalid value", {
    toml,
    ptr
  });
  return date9;
}
__name2(parseValue2, "parseValue");
function sliceAndTrimEndOf2(str, startPtr, endPtr, allowNewLines) {
  let value = str.slice(startPtr, endPtr);
  let commentIdx = value.indexOf("#");
  if (commentIdx > -1) {
    skipComment2(str, commentIdx);
    value = value.slice(0, commentIdx);
  }
  let trimmed = value.trimEnd();
  if (!allowNewLines) {
    let newlineIdx = value.indexOf("\n", trimmed.length);
    if (newlineIdx > -1) throw new TomlError2("newlines are not allowed in inline tables", {
      toml: str,
      ptr: startPtr + newlineIdx
    });
  }
  return [trimmed, commentIdx];
}
__name2(sliceAndTrimEndOf2, "sliceAndTrimEndOf");
function extractValue2(str, ptr, end, depth, integersAsBigInt) {
  if (depth === 0) throw new TomlError2("document contains excessively nested structures. aborting.", {
    toml: str,
    ptr
  });
  let c2 = str[ptr];
  if (c2 === "[" || c2 === "{") {
    let [value, endPtr2] = c2 === "[" ? parseArray2(str, ptr, depth, integersAsBigInt) : parseInlineTable2(str, ptr, depth, integersAsBigInt);
    let newPtr = end ? skipUntil2(str, endPtr2, ",", end) : endPtr2;
    if (endPtr2 - newPtr && end === "}") {
      let nextNewLine = indexOfNewline2(str, endPtr2, newPtr);
      if (nextNewLine > -1) throw new TomlError2("newlines are not allowed in inline tables", {
        toml: str,
        ptr: nextNewLine
      });
    }
    return [value, newPtr];
  }
  let endPtr;
  if (c2 === '"' || c2 === "'") {
    endPtr = getStringEnd2(str, ptr);
    let parsed = parseString2(str, ptr, endPtr);
    if (end) {
      endPtr = skipVoid2(str, endPtr, end !== "]");
      if (str[endPtr] && str[endPtr] !== "," && str[endPtr] !== end && str[endPtr] !== "\n" && str[endPtr] !== "\r") throw new TomlError2("unexpected character encountered", {
        toml: str,
        ptr: endPtr
      });
      endPtr += +(str[endPtr] === ",");
    }
    return [parsed, endPtr];
  }
  endPtr = skipUntil2(str, ptr, ",", end);
  let slice = sliceAndTrimEndOf2(str, ptr, endPtr - +(str[endPtr - 1] === ","), end === "]");
  if (!slice[0]) throw new TomlError2("incomplete key-value declaration: no value specified", {
    toml: str,
    ptr
  });
  if (end && slice[1] > -1) {
    endPtr = skipVoid2(str, ptr + slice[1]);
    endPtr += +(str[endPtr] === ",");
  }
  return [parseValue2(slice[0], str, ptr, integersAsBigInt), endPtr];
}
__name2(extractValue2, "extractValue");
var KEY_PART_RE2 = /^[a-zA-Z0-9-_]+[ \t]*$/;
function parseKey2(str, ptr, end = "=") {
  let dot = ptr - 1;
  let parsed = [];
  let endPtr = str.indexOf(end, ptr);
  if (endPtr < 0) throw new TomlError2("incomplete key-value: cannot find end of key", {
    toml: str,
    ptr
  });
  do {
    let c2 = str[ptr = ++dot];
    if (c2 !== " " && c2 !== "	") if (c2 === '"' || c2 === "'") {
      if (c2 === str[ptr + 1] && c2 === str[ptr + 2]) throw new TomlError2("multiline strings are not allowed in keys", {
        toml: str,
        ptr
      });
      let eos = getStringEnd2(str, ptr);
      if (eos < 0) throw new TomlError2("unfinished string encountered", {
        toml: str,
        ptr
      });
      dot = str.indexOf(".", eos);
      let strEnd = str.slice(eos, dot < 0 || dot > endPtr ? endPtr : dot);
      let newLine = indexOfNewline2(strEnd);
      if (newLine > -1) throw new TomlError2("newlines are not allowed in keys", {
        toml: str,
        ptr: ptr + dot + newLine
      });
      if (strEnd.trimStart()) throw new TomlError2("found extra tokens after the string part", {
        toml: str,
        ptr: eos
      });
      if (endPtr < eos) {
        endPtr = str.indexOf(end, eos);
        if (endPtr < 0) throw new TomlError2("incomplete key-value: cannot find end of key", {
          toml: str,
          ptr
        });
      }
      parsed.push(parseString2(str, ptr, eos));
    } else {
      dot = str.indexOf(".", ptr);
      let part = str.slice(ptr, dot < 0 || dot > endPtr ? endPtr : dot);
      if (!KEY_PART_RE2.test(part)) throw new TomlError2("only letter, numbers, dashes and underscores are allowed in keys", {
        toml: str,
        ptr
      });
      parsed.push(part.trimEnd());
    }
  } while (dot + 1 && dot < endPtr);
  return [parsed, skipVoid2(str, endPtr + 1, true, true)];
}
__name2(parseKey2, "parseKey");
function parseInlineTable2(str, ptr, depth, integersAsBigInt) {
  let res = {};
  let seen = /* @__PURE__ */ new Set();
  let c2;
  let comma = 0;
  ptr++;
  while ((c2 = str[ptr++]) !== "}" && c2) {
    let err = {
      toml: str,
      ptr: ptr - 1
    };
    if (c2 === "\n") throw new TomlError2("newlines are not allowed in inline tables", err);
    else if (c2 === "#") throw new TomlError2("inline tables cannot contain comments", err);
    else if (c2 === ",") throw new TomlError2("expected key-value, found comma", err);
    else if (c2 !== " " && c2 !== "	") {
      let k;
      let t = res;
      let hasOwn = false;
      let [key, keyEndPtr] = parseKey2(str, ptr - 1);
      for (let i = 0; i < key.length; i++) {
        if (i) t = hasOwn ? t[k] : t[k] = {};
        k = key[i];
        if ((hasOwn = Object.hasOwn(t, k)) && (typeof t[k] !== "object" || seen.has(t[k]))) throw new TomlError2("trying to redefine an already defined value", {
          toml: str,
          ptr
        });
        if (!hasOwn && k === "__proto__") Object.defineProperty(t, k, {
          enumerable: true,
          configurable: true,
          writable: true
        });
      }
      if (hasOwn) throw new TomlError2("trying to redefine an already defined value", {
        toml: str,
        ptr
      });
      let [value, valueEndPtr] = extractValue2(str, keyEndPtr, "}", depth - 1, integersAsBigInt);
      seen.add(value);
      t[k] = value;
      ptr = valueEndPtr;
      comma = str[ptr - 1] === "," ? ptr - 1 : 0;
    }
  }
  if (comma) throw new TomlError2("trailing commas are not allowed in inline tables", {
    toml: str,
    ptr: comma
  });
  if (!c2) throw new TomlError2("unfinished table encountered", {
    toml: str,
    ptr
  });
  return [res, ptr];
}
__name2(parseInlineTable2, "parseInlineTable");
function parseArray2(str, ptr, depth, integersAsBigInt) {
  let res = [];
  let c2;
  ptr++;
  while ((c2 = str[ptr++]) !== "]" && c2) if (c2 === ",") throw new TomlError2("expected value, found comma", {
    toml: str,
    ptr: ptr - 1
  });
  else if (c2 === "#") ptr = skipComment2(str, ptr);
  else if (c2 !== " " && c2 !== "	" && c2 !== "\n" && c2 !== "\r") {
    let e = extractValue2(str, ptr - 1, "]", depth - 1, integersAsBigInt);
    res.push(e[0]);
    ptr = e[1];
  }
  if (!c2) throw new TomlError2("unfinished array encountered", {
    toml: str,
    ptr
  });
  return [res, ptr];
}
__name2(parseArray2, "parseArray");
function peekTable2(key, table, meta5, type) {
  let t = table;
  let m = meta5;
  let k;
  let hasOwn = false;
  let state;
  for (let i = 0; i < key.length; i++) {
    if (i) {
      t = hasOwn ? t[k] : t[k] = {};
      m = (state = m[k]).c;
      if (type === 0 && (state.t === 1 || state.t === 2)) return null;
      if (state.t === 2) {
        let l = t.length - 1;
        t = t[l];
        m = m[l].c;
      }
    }
    k = key[i];
    if ((hasOwn = Object.hasOwn(t, k)) && m[k]?.t === 0 && m[k]?.d) return null;
    if (!hasOwn) {
      if (k === "__proto__") {
        Object.defineProperty(t, k, {
          enumerable: true,
          configurable: true,
          writable: true
        });
        Object.defineProperty(m, k, {
          enumerable: true,
          configurable: true,
          writable: true
        });
      }
      m[k] = {
        t: i < key.length - 1 && type === 2 ? 3 : type,
        d: false,
        i: 0,
        c: {}
      };
    }
  }
  state = m[k];
  if (state.t !== type && !(type === 1 && state.t === 3)) return null;
  if (type === 2) {
    if (!state.d) {
      state.d = true;
      t[k] = [];
    }
    t[k].push(t = {});
    state.c[state.i++] = state = {
      t: 1,
      d: false,
      i: 0,
      c: {}
    };
  }
  if (state.d) return null;
  state.d = true;
  if (type === 1) t = hasOwn ? t[k] : t[k] = {};
  else if (type === 0 && hasOwn) return null;
  return [
    k,
    t,
    state.c
  ];
}
__name2(peekTable2, "peekTable");
function parse32(toml, { maxDepth = 1e3, integersAsBigInt } = {}) {
  let res = {};
  let meta5 = {};
  let tbl = res;
  let m = meta5;
  for (let ptr = skipVoid2(toml, 0); ptr < toml.length; ) {
    if (toml[ptr] === "[") {
      let isTableArray = toml[++ptr] === "[";
      let k = parseKey2(toml, ptr += +isTableArray, "]");
      if (isTableArray) {
        if (toml[k[1] - 1] !== "]") throw new TomlError2("expected end of table declaration", {
          toml,
          ptr: k[1] - 1
        });
        k[1]++;
      }
      let p2 = peekTable2(k[0], res, meta5, isTableArray ? 2 : 1);
      if (!p2) throw new TomlError2("trying to redefine an already defined table or value", {
        toml,
        ptr
      });
      m = p2[2];
      tbl = p2[1];
      ptr = k[1];
    } else {
      let k = parseKey2(toml, ptr);
      let p2 = peekTable2(k[0], tbl, m, 0);
      if (!p2) throw new TomlError2("trying to redefine an already defined table or value", {
        toml,
        ptr
      });
      let v = extractValue2(toml, k[1], void 0, maxDepth, integersAsBigInt);
      p2[1][p2[0]] = v[0];
      ptr = v[1];
    }
    ptr = skipVoid2(toml, ptr, true);
    if (toml[ptr] && toml[ptr] !== "\n" && toml[ptr] !== "\r") throw new TomlError2("each key-value declaration must be followed by an end-of-line", {
      toml,
      ptr
    });
    ptr = skipVoid2(toml, ptr);
  }
  return res;
}
__name2(parse32, "parse");
var BARE_KEY2 = /^[a-z0-9-_]+$/i;
function extendedTypeOf2(obj) {
  let type = typeof obj;
  if (type === "object") {
    if (Array.isArray(obj)) return "array";
    if (obj instanceof Date) return "date";
  }
  return type;
}
__name2(extendedTypeOf2, "extendedTypeOf");
function isArrayOfTables2(obj) {
  for (let i = 0; i < obj.length; i++) if (extendedTypeOf2(obj[i]) !== "object") return false;
  return obj.length != 0;
}
__name2(isArrayOfTables2, "isArrayOfTables");
function formatString2(s) {
  return JSON.stringify(s).replace(/\x7f/g, "\\u007f");
}
__name2(formatString2, "formatString");
function stringifyValue2(val, type, depth, numberAsFloat) {
  if (depth === 0) throw new Error("Could not stringify the object: maximum object depth exceeded");
  if (type === "number") {
    if (isNaN(val)) return "nan";
    if (val === Infinity) return "inf";
    if (val === -Infinity) return "-inf";
    if (numberAsFloat && Number.isInteger(val)) return val.toFixed(1);
    return val.toString();
  }
  if (type === "bigint" || type === "boolean") return val.toString();
  if (type === "string") return formatString2(val);
  if (type === "date") {
    if (isNaN(val.getTime())) throw new TypeError("cannot serialize invalid date");
    return val.toISOString();
  }
  if (type === "object") return stringifyInlineTable2(val, depth, numberAsFloat);
  if (type === "array") return stringifyArray2(val, depth, numberAsFloat);
}
__name2(stringifyValue2, "stringifyValue");
function stringifyInlineTable2(obj, depth, numberAsFloat) {
  let keys = Object.keys(obj);
  if (keys.length === 0) return "{}";
  let res = "{ ";
  for (let i = 0; i < keys.length; i++) {
    let k = keys[i];
    if (i) res += ", ";
    res += BARE_KEY2.test(k) ? k : formatString2(k);
    res += " = ";
    res += stringifyValue2(obj[k], extendedTypeOf2(obj[k]), depth - 1, numberAsFloat);
  }
  return res + " }";
}
__name2(stringifyInlineTable2, "stringifyInlineTable");
function stringifyArray2(array3, depth, numberAsFloat) {
  if (array3.length === 0) return "[]";
  let res = "[ ";
  for (let i = 0; i < array3.length; i++) {
    if (i) res += ", ";
    if (array3[i] === null || array3[i] === void 0) throw new TypeError("arrays cannot contain null or undefined values");
    res += stringifyValue2(array3[i], extendedTypeOf2(array3[i]), depth - 1, numberAsFloat);
  }
  return res + " ]";
}
__name2(stringifyArray2, "stringifyArray");
function stringifyArrayTable2(array3, key, depth, numberAsFloat) {
  if (depth === 0) throw new Error("Could not stringify the object: maximum object depth exceeded");
  let res = "";
  for (let i = 0; i < array3.length; i++) {
    res += `${res && "\n"}[[${key}]]
`;
    res += stringifyTable2(0, array3[i], key, depth, numberAsFloat);
  }
  return res;
}
__name2(stringifyArrayTable2, "stringifyArrayTable");
function stringifyTable2(tableKey, obj, prefix, depth, numberAsFloat) {
  if (depth === 0) throw new Error("Could not stringify the object: maximum object depth exceeded");
  let preamble = "";
  let tables = "";
  let keys = Object.keys(obj);
  for (let i = 0; i < keys.length; i++) {
    let k = keys[i];
    if (obj[k] !== null && obj[k] !== void 0) {
      let type = extendedTypeOf2(obj[k]);
      if (type === "symbol" || type === "function") throw new TypeError(`cannot serialize values of type '${type}'`);
      let key = BARE_KEY2.test(k) ? k : formatString2(k);
      if (type === "array" && isArrayOfTables2(obj[k])) tables += (tables && "\n") + stringifyArrayTable2(obj[k], prefix ? `${prefix}.${key}` : key, depth - 1, numberAsFloat);
      else if (type === "object") {
        let tblKey = prefix ? `${prefix}.${key}` : key;
        tables += (tables && "\n") + stringifyTable2(tblKey, obj[k], tblKey, depth - 1, numberAsFloat);
      } else {
        preamble += key;
        preamble += " = ";
        preamble += stringifyValue2(obj[k], type, depth, numberAsFloat);
        preamble += "\n";
      }
    }
  }
  if (tableKey && (preamble || !tables)) preamble = preamble ? `[${tableKey}]
${preamble}` : `[${tableKey}]`;
  return preamble && tables ? `${preamble}
${tables}` : preamble || tables;
}
__name2(stringifyTable2, "stringifyTable");
function stringify2(obj, { maxDepth = 1e3, numbersAsFloat = false } = {}) {
  if (extendedTypeOf2(obj) !== "object") throw new TypeError("stringify can only be called with an object");
  let str = stringifyTable2(0, obj, "", maxDepth, numbersAsFloat);
  if (str[str.length - 1] !== "\n") return str + "\n";
  return str;
}
__name2(stringify2, "stringify");
var dist_default2 = {
  parse: parse32,
  stringify: stringify2,
  TomlDate: TomlDate2,
  TomlError: TomlError2
};
var ParseError2 = class extends UserError2 {
  static {
    __name2(this, "ParseError");
  }
  text;
  notes;
  location;
  kind;
  constructor({ text, notes, location, kind, telemetryMessage }) {
    super(text, { telemetryMessage });
    this.name = this.constructor.name;
    this.text = text;
    this.notes = notes ?? [];
    this.location = location;
    this.kind = kind ?? "error";
  }
};
var APIError2 = class extends ParseError2 {
  static {
    __name2(this, "APIError");
  }
  #status;
  code;
  accountTag;
  /**
  * Optional structured metadata hoisted from the first `FetchError.meta`
  * on the v4 response envelope. Consumers can inspect this to render
  * endpoint-specific structured error payloads.
  */
  meta;
  /**
  * Optional number of milliseconds the API asked us to wait before retrying,
  * derived from the response's `Retry-After` header (if present).
  */
  retryAfterMs;
  constructor({ status: status2, retryAfterMs, ...rest }) {
    super(rest);
    this.name = this.constructor.name;
    this.#status = status2;
    this.retryAfterMs = retryAfterMs;
  }
  get status() {
    return this.#status;
  }
  isGatewayError() {
    if (this.#status !== void 0) return [524].includes(this.#status);
    return false;
  }
  isRetryable() {
    return String(this.#status).startsWith("5");
  }
  #reportable = true;
  get reportable() {
    return this.#reportable;
  }
  preventReport() {
    this.#reportable = false;
  }
};
function parseTOML2(tomlContent, filePath) {
  try {
    return dist_default2.parse(tomlContent);
  } catch (err) {
    if (!(err instanceof TomlError2)) throw err;
    const location = {
      lineText: tomlContent.split("\n")[err.line - 1],
      line: err.line,
      column: err.column - 1,
      file: filePath,
      fileText: tomlContent
    };
    throw new ParseError2({
      text: err.message.substring(0, err.message.indexOf("\n")),
      location,
      telemetryMessage: "TOML parse error"
    });
  }
}
__name2(parseTOML2, "parseTOML");
function parsePackageJSON2(input, file22) {
  return parseJSON2(input, file22);
}
__name2(parsePackageJSON2, "parsePackageJSON");
function parseJSON2(input, file22) {
  return parseJSONC2(input, file22, {
    allowEmptyContent: false,
    allowTrailingComma: false,
    disallowComments: true
  });
}
__name2(parseJSON2, "parseJSON");
function parseJSONC2(input, file22, options = { allowTrailingComma: true }) {
  const errors = [];
  const data = parse23(input, errors, options);
  if (errors.length) throw new ParseError2({
    text: printParseErrorCode2(errors[0].error),
    location: {
      ...indexLocation2({
        file: file22,
        fileText: input
      }, errors[0].offset + 1),
      length: errors[0].length
    },
    telemetryMessage: "JSON(C) parse error"
  });
  return data;
}
__name2(parseJSONC2, "parseJSONC");
function readFileSyncToBuffer2(file22) {
  try {
    return (0, import_node_fs6.readFileSync)(file22);
  } catch (err) {
    const { message } = err;
    throw new ParseError2({
      text: `Could not read file: ${file22}`,
      notes: [{ text: message.replace(file22, (0, import_node_path6.resolve)(file22)) }],
      telemetryMessage: false
    });
  }
}
__name2(readFileSyncToBuffer2, "readFileSyncToBuffer");
function readFileSync$13(file22) {
  try {
    return removeBOMAndValidate2((0, import_node_fs6.readFileSync)(file22), file22);
  } catch (err) {
    if (err instanceof ParseError2) throw err;
    const { message } = err;
    throw new ParseError2({
      text: `Could not read file: ${file22}`,
      notes: [{ text: message.replace(file22, (0, import_node_path6.resolve)(file22)) }],
      telemetryMessage: "Could not read file"
    });
  }
}
__name2(readFileSync$13, "readFileSync");
function indexLocation2(file22, index) {
  let lineText, line = 0, column = 0, cursor = 0;
  const { fileText = "" } = file22;
  for (const row of fileText.split("\n")) {
    line++;
    cursor += row.length + 1;
    if (cursor >= index) {
      lineText = row;
      column = row.length - (cursor - index);
      break;
    }
  }
  return {
    lineText,
    line,
    column,
    ...file22
  };
}
__name2(indexLocation2, "indexLocation");
function searchLocation2(file22, query) {
  let lineText, length, line = 0, column = 0;
  const queryText = String(query);
  const { fileText = "" } = file22;
  for (const content of fileText.split("\n")) {
    line++;
    const index = content.indexOf(queryText);
    if (index >= 0) {
      lineText = content;
      column = index;
      length = queryText.length;
      break;
    }
  }
  return {
    lineText,
    line,
    column,
    length,
    ...file22
  };
}
__name2(searchLocation2, "searchLocation");
var units2 = {
  nanoseconds: 1e-9,
  nanosecond: 1e-9,
  microseconds: 1e-6,
  microsecond: 1e-6,
  milliseconds: 1e-3,
  millisecond: 1e-3,
  seconds: 1,
  second: 1,
  minutes: 60,
  minute: 60,
  hours: 3600,
  hour: 3600,
  days: 86400,
  day: 86400,
  weeks: 604800,
  week: 604800,
  month: 18144e3,
  year: 220752e3,
  nsecs: 1e-9,
  nsec: 1e-9,
  usecs: 1e-6,
  usec: 1e-6,
  msecs: 1e-3,
  msec: 1e-3,
  secs: 1,
  sec: 1,
  mins: 60,
  min: 60,
  ns: 1e-9,
  us: 1e-6,
  ms: 1e-3,
  mo: 18144e3,
  yr: 220752e3,
  s: 1,
  m: 60,
  h: 3600,
  d: 86400,
  w: 604800,
  y: 220752e3
};
function parseHumanDuration2(s) {
  const unitsMap = new Map(Object.entries(units2));
  s = s.trim().toLowerCase();
  let base = 1;
  for (const [name, _] of unitsMap) if (s.endsWith(name)) {
    s = s.substring(0, s.length - name.length);
    base = unitsMap.get(name) || 1;
    break;
  }
  return Number(s) * base;
}
__name2(parseHumanDuration2, "parseHumanDuration");
function parseNonHyphenedUuid2(uuid8) {
  if (uuid8 == null || uuid8.includes("-")) return uuid8;
  if (uuid8.length != 32) return null;
  const uuid_parts = [];
  uuid_parts.push(uuid8.slice(0, 8));
  uuid_parts.push(uuid8.slice(8, 12));
  uuid_parts.push(uuid8.slice(12, 16));
  uuid_parts.push(uuid8.slice(16, 20));
  uuid_parts.push(uuid8.slice(20));
  let hyphenated = "";
  uuid_parts.forEach((part) => hyphenated += part + "-");
  return hyphenated.slice(0, 36);
}
__name2(parseNonHyphenedUuid2, "parseNonHyphenedUuid");
function parseByteSize2(s, base = void 0) {
  const match = s.match(/^(\d*\.*\d*)\s*([kKmMgGtTpP]{0,1})([i]{0,1}[bB]{0,1})$/);
  if (!match) return NaN;
  const size = match[1];
  if (size.length === 0 || isNaN(Number(size))) return NaN;
  const unit = match[2].toLowerCase();
  const sizeUnits = {
    k: 1,
    m: 2,
    g: 3,
    t: 4,
    p: 5
  };
  if (unit.length !== 0 && !(unit in sizeUnits)) return NaN;
  const binary = match[3].toLowerCase() == "ib";
  if (binary && unit.length === 0) return NaN;
  const pow = sizeUnits[unit] || 0;
  return Math.floor(Number(size) * Math.pow(base ?? (binary ? 1024 : 1e3), pow));
}
__name2(parseByteSize2, "parseByteSize");
var UNSUPPORTED_BOMS2 = [
  {
    buffer: Buffer.from([
      0,
      0,
      254,
      255
    ]),
    encoding: "UTF-32 BE"
  },
  {
    buffer: Buffer.from([
      255,
      254,
      0,
      0
    ]),
    encoding: "UTF-32 LE"
  },
  {
    buffer: Buffer.from([254, 255]),
    encoding: "UTF-16 BE"
  },
  {
    buffer: Buffer.from([255, 254]),
    encoding: "UTF-16 LE"
  }
];
function removeBOMAndValidate2(buffer, file22) {
  for (const bom of UNSUPPORTED_BOMS2) if (buffer.length >= bom.buffer.length && buffer.subarray(0, bom.buffer.length).equals(bom.buffer)) throw new ParseError2({
    text: `Configuration file contains ${bom.encoding} byte order marker`,
    notes: [{ text: `The file "${file22}" appears to be encoded as ${bom.encoding}. Please save the file as UTF-8 without BOM.` }],
    location: {
      file: file22,
      line: 1,
      column: 0
    },
    telemetryMessage: `${bom.encoding} BOM detected`
  });
  const content = buffer.toString("utf-8");
  if (content.charCodeAt(0) === 65279) return content.slice(1);
  return content;
}
__name2(removeBOMAndValidate2, "removeBOMAndValidate");
var PATH_TO_DEPLOY_CONFIG2 = ".wrangler/deploy/config.json";
function absolute2(input, root) {
  return (0, import_node_path6.isAbsolute)(input) ? input : (0, import_node_path6.resolve)(root || ".", input);
}
__name2(absolute2, "absolute");
function up2(base, options) {
  let { last, cwd: cwd2 } = options || {};
  let tmp = absolute2(base, cwd2);
  let root = absolute2(last || "/", cwd2);
  let prev, arr = [];
  while (prev !== root) {
    arr.push(tmp);
    tmp = (0, import_node_path6.dirname)(prev = tmp);
    if (tmp === prev) break;
  }
  return arr;
}
__name2(up2, "up");
function file4(name, options) {
  let dir22, tmp;
  for (dir22 of up2(options && options.cwd || "", options)) try {
    tmp = (0, import_node_path6.join)(dir22, name);
    if ((0, import_node_fs6.statSync)(tmp).isFile()) return tmp;
  } catch {
  }
}
__name2(file4, "file");
function dir2(name, options) {
  let dir22, tmp;
  for (dir22 of up2(options && options.cwd || "", options)) try {
    tmp = (0, import_node_path6.join)(dir22, name);
    if ((0, import_node_fs6.statSync)(tmp).isDirectory()) return tmp;
  } catch {
  }
}
__name2(dir2, "dir");
function dedent2(templ) {
  var values = [];
  for (var _i = 1; _i < arguments.length; _i++) values[_i - 1] = arguments[_i];
  var strings = Array.from(typeof templ === "string" ? [templ] : templ);
  strings[strings.length - 1] = strings[strings.length - 1].replace(/\r?\n([\t ]*)$/, "");
  var indentLengths = strings.reduce(function(arr, str) {
    var matches = str.match(/\n([\t ]+|(?!\s).)/g);
    if (matches) return arr.concat(matches.map(function(match) {
      var _a5, _b;
      return (_b = (_a5 = match.match(/[\t ]/g)) === null || _a5 === void 0 ? void 0 : _a5.length) !== null && _b !== void 0 ? _b : 0;
    }));
    return arr;
  }, []);
  if (indentLengths.length) {
    var pattern_1 = new RegExp("\n[	 ]{" + Math.min.apply(Math, indentLengths) + "}", "g");
    strings = strings.map(function(str) {
      return str.replace(pattern_1, "\n");
    });
  }
  strings[0] = strings[0].replace(/^\r?\n/, "");
  var string7 = strings[0];
  values.forEach(function(value, i) {
    var endentations = string7.match(/(?:^|\n)( *)$/);
    var endentation = endentations ? endentations[1] : "";
    var indentedValue = value;
    if (typeof value === "string" && value.includes("\n")) indentedValue = String(value).split("\n").map(function(str, i2) {
      return i2 === 0 ? str : "" + endentation + str;
    }).join("\n");
    string7 += indentedValue + strings[i + 1];
  });
  return string7;
}
__name2(dedent2, "dedent");
var esm_default2 = dedent2;
function resolveWranglerConfigPath2({ config: config3, script }, options) {
  if (config3 !== void 0) return {
    userConfigPath: config3,
    configPath: config3,
    deployConfigPath: void 0,
    redirected: false
  };
  return findWranglerConfig2(script !== void 0 ? import_node_path6.default.dirname(script) : process.cwd(), options);
}
__name2(resolveWranglerConfigPath2, "resolveWranglerConfigPath");
function findWranglerConfig2(referencePath = process.cwd(), { useRedirectIfAvailable = false } = {}) {
  const userConfigPath = file4(`wrangler.json`, { cwd: referencePath }) ?? file4(`wrangler.jsonc`, { cwd: referencePath }) ?? file4(`wrangler.toml`, { cwd: referencePath });
  if (!useRedirectIfAvailable) return {
    userConfigPath,
    configPath: userConfigPath,
    deployConfigPath: void 0,
    redirected: false
  };
  const { configPath, deployConfigPath, redirected } = findRedirectedWranglerConfig2(referencePath, userConfigPath);
  return {
    userConfigPath,
    configPath,
    deployConfigPath,
    redirected
  };
}
__name2(findWranglerConfig2, "findWranglerConfig");
function findRedirectedWranglerConfig2(cwd2, userConfigPath) {
  const deployConfigPath = file4(PATH_TO_DEPLOY_CONFIG2, { cwd: cwd2 });
  if (deployConfigPath === void 0) return {
    configPath: userConfigPath,
    deployConfigPath,
    redirected: false
  };
  let redirectedConfigPath;
  const deployConfigFile = readFileSync$13(deployConfigPath);
  try {
    const deployConfig = parseJSONC2(deployConfigFile, deployConfigPath);
    redirectedConfigPath = deployConfig.configPath && import_node_path6.default.resolve(import_node_path6.default.dirname(deployConfigPath), deployConfig.configPath);
  } catch (e) {
    throw new UserError2(`Failed to parse the deploy configuration file at ${import_node_path6.default.relative(".", deployConfigPath)}`, {
      cause: e,
      telemetryMessage: false
    });
  }
  if (!redirectedConfigPath) throw new UserError2(esm_default2`
			A deploy configuration file was found at "${import_node_path6.default.relative(".", deployConfigPath)}".
			But this is not valid - the required "configPath" property was not found.
			Instead this file contains:
			\`\`\`
			${deployConfigFile}
			\`\`\`
		`, { telemetryMessage: false });
  if (!(0, import_node_fs6.existsSync)(redirectedConfigPath)) throw new UserError2(esm_default2`
				There is a deploy configuration at "${import_node_path6.default.relative(".", deployConfigPath)}".
				But the redirected configuration path it points to, "${import_node_path6.default.relative(".", redirectedConfigPath)}", does not exist.
			`, { telemetryMessage: false });
  if (userConfigPath) {
    if (import_node_path6.default.join(import_node_path6.default.dirname(userConfigPath), PATH_TO_DEPLOY_CONFIG2) !== deployConfigPath) throw new UserError2(esm_default2`
					Found both a user configuration file at "${import_node_path6.default.relative(".", userConfigPath)}"
					and a deploy configuration file at "${import_node_path6.default.relative(".", deployConfigPath)}".
					But these do not share the same base path so it is not clear which should be used.
				`, { telemetryMessage: false });
  }
  return {
    configPath: redirectedConfigPath,
    deployConfigPath,
    redirected: true
  };
}
__name2(findRedirectedWranglerConfig2, "findRedirectedWranglerConfig");
function isRedirectedConfig2(config3) {
  return config3.configPath !== void 0 && config3.configPath !== config3.userConfigPath;
}
__name2(isRedirectedConfig2, "isRedirectedConfig");
function isRedirectedRawConfig2(rawConfig, configPath, userConfigPath) {
  return isRedirectedConfig2({
    configPath,
    userConfigPath
  });
}
__name2(isRedirectedRawConfig2, "isRedirectedRawConfig");
function configFormat2(configPath) {
  if (configPath?.endsWith("toml")) return "toml";
  if (configPath?.endsWith("jsonc")) return "jsonc";
  if (configPath?.endsWith("json")) return "json";
  return "none";
}
__name2(configFormat2, "configFormat");
function configFileName2(configPath) {
  switch (configFormat2(configPath)) {
    case "toml":
      return "wrangler.toml";
    case "json":
      return "wrangler.json";
    case "jsonc":
      return "wrangler.jsonc";
    default:
      return "Wrangler configuration";
  }
}
__name2(configFileName2, "configFileName");
function formatConfigSnippet2(snippet, configPath, formatted = true) {
  if (configFormat2(configPath) === "toml") return dist_default2.stringify(snippet);
  else return formatted ? JSON.stringify(snippet, null, 2) : JSON.stringify(snippet);
}
__name2(formatConfigSnippet2, "formatConfigSnippet");
var depsStore = new import_node_async_hooks.AsyncLocalStorage();

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/shared/object-entry.worker.ts
var import_fs4 = __toESM(require("fs"));
var import_path4 = __toESM(require("path"));
var import_url4 = __toESM(require("url"));
var contents4;
function object_entry_worker_default() {
  if (contents4 !== void 0) return contents4;
  const filePath = import_path4.default.join(__dirname, "workers", "shared/object-entry.worker.js");
  contents4 = import_fs4.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url4.default.pathToFileURL(filePath);
  return contents4;
}

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/shared/remote-proxy-client.worker.ts
var import_fs5 = __toESM(require("fs"));
var import_path5 = __toESM(require("path"));
var import_url5 = __toESM(require("url"));
var contents5;
function remote_proxy_client_worker_default() {
  if (contents5 !== void 0) return contents5;
  const filePath = import_path5.default.join(__dirname, "workers", "shared/remote-proxy-client.worker.js");
  contents5 = import_fs5.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url5.default.pathToFileURL(filePath);
  return contents5;
}

// src/workers/cache/constants.ts
var CacheHeaders = {
  NAMESPACE: "cf-cache-namespace",
  STATUS: "cf-cache-status"
};

// src/workers/core/constants.ts
var CorePaths = {
  /** Magic proxy used by getPlatformProxy */
  PLATFORM_PROXY: "/cdn-cgi/local/platform-proxy",
  /** Trigger scheduled event handlers */
  SCHEDULED: "/cdn-cgi/local/scheduled",
  /** Trigger email event handlers */
  EMAIL: "/cdn-cgi/local/email",
  /** Local explorer UI and API */
  EXPLORER: "/cdn-cgi/local/explorer",
  /** Stream video serving endpoint (outside /cdn-cgi/ for tunnel access) */
  STREAM_VIDEO: "/__cf_local/stream",
  /** Local image delivery endpoint (outside /cdn-cgi/ for tunnel access) */
  IMAGE_DELIVERY: "/__cf_local/imagedelivery",
  /** Public R2 bucket object serving endpoint */
  R2_PUBLIC: "/cdn-cgi/local/r2/public",
  /** S3-compatible API endpoint for local R2 buckets */
  R2_S3: "/cdn-cgi/local/r2/s3"
};
var CoreHeaders = {
  CUSTOM_FETCH_SERVICE: "MF-Custom-Fetch-Service",
  CUSTOM_NODE_SERVICE: "MF-Custom-Node-Service",
  ORIGINAL_URL: "MF-Original-URL",
  /**
   * Stores the original hostname when using the `upstream` option.
   * When requests are proxied to an upstream, the `Host` header is rewritten
   * to match the upstream. This header preserves the original hostname
   * so Workers can access it if needed.
   */
  ORIGINAL_HOSTNAME: "MF-Original-Hostname",
  PROXY_SHARED_SECRET: "MF-Proxy-Shared-Secret",
  DISABLE_PRETTY_ERROR: "MF-Disable-Pretty-Error",
  ERROR_STACK: "MF-Experimental-Error-Stack",
  /**
   * The serialised error, URI-encoded. `workerd` drops response bodies for
   * `HEAD` requests, so the body alone cannot carry the error out of the user
   * Worker. Producers set this in addition to the body; consumers fall back to
   * it whenever the body is unavailable.
   */
  ERROR_STACK_PAYLOAD: "MF-Experimental-Error-Stack-Payload",
  ROUTE_OVERRIDE: "MF-Route-Override",
  CF_BLOB: "MF-CF-Blob",
  ACCESS_BLOB: "MF-Access-Blob",
  /** Used by the Vite plugin to pass through the original `sec-fetch-mode` header */
  SEC_FETCH_MODE: "MF-Sec-Fetch-Mode",
  // API Proxy
  OP_SECRET: "MF-Op-Secret",
  OP: "MF-Op",
  OP_TARGET: "MF-Op-Target",
  OP_KEY: "MF-Op-Key",
  OP_SYNC: "MF-Op-Sync",
  OP_STRINGIFIED_SIZE: "MF-Op-Stringified-Size",
  OP_RESULT_TYPE: "MF-Op-Result-Type",
  OP_ORIGINAL_URL: "MF-Op-Original-URL"
};
var CoreBindings = {
  SERVICE_LOOPBACK: "MINIFLARE_LOOPBACK",
  SERVICE_USER_ROUTE_PREFIX: "MINIFLARE_USER_ROUTE_",
  SERVICE_USER_FALLBACK: "MINIFLARE_USER_FALLBACK",
  TEXT_CUSTOM_SERVICE: "MINIFLARE_CUSTOM_SERVICE",
  // Backs the Images binding (`env.IMAGES`) — see imagesLocalFetcher.
  IMAGES_BINDING_SERVICE: "MINIFLARE_IMAGES_BINDING_SERVICE",
  // Backs `fetch(url, { cf: { image } })` transforms — see cfImageLocalFetcher.
  IMAGES_FETCH_SERVICE: "MINIFLARE_IMAGES_FETCH_SERVICE",
  TEXT_UPSTREAM_URL: "MINIFLARE_UPSTREAM_URL",
  JSON_CF_BLOB: "CF_BLOB",
  JSON_ROUTES: "MINIFLARE_ROUTES",
  JSON_LOG_LEVEL: "MINIFLARE_LOG_LEVEL",
  DURABLE_OBJECT_NAMESPACE_PROXY: "MINIFLARE_PROXY",
  DATA_PROXY_SECRET: "MINIFLARE_PROXY_SECRET",
  DATA_PROXY_SHARED_SECRET: "MINIFLARE_PROXY_SHARED_SECRET",
  TRIGGER_HANDLERS: "TRIGGER_HANDLERS",
  LOG_REQUESTS: "LOG_REQUESTS",
  STRIP_DISABLE_PRETTY_ERROR: "STRIP_DISABLE_PRETTY_ERROR",
  SERVICE_LOCAL_EXPLORER: "MINIFLARE_LOCAL_EXPLORER",
  EXPLORER_DISK: "MINIFLARE_EXPLORER_DISK",
  JSON_LOCAL_EXPLORER_BINDING_MAP: "LOCAL_EXPLORER_BINDING_MAP",
  JSON_LOCAL_EXPLORER_WORKER_NAMES: "LOCAL_EXPLORER_WORKER_NAMES",
  JSON_EXPLORER_WORKER_OPTS: "MINIFLARE_EXPLORER_WORKER_OPTS",
  SERVICE_CACHE: "MINIFLARE_CACHE",
  SERVICE_DEV_CONTROL: "MINIFLARE_DEV_CONTROL",
  SERVICE_DEV_REGISTRY_PROXY: "MINIFLARE_DEV_REGISTRY_PROXY",
  JSON_TELEMETRY_CONFIG: "MINIFLARE_TELEMETRY_CONFIG",
  DEV_REGISTRY_DEBUG_PORT: "DEV_REGISTRY_DEBUG_PORT",
  SERVICE_STREAM: "MINIFLARE_STREAM",
  SERVICE_IMAGES_DELIVERY: "MINIFLARE_IMAGES_DELIVERY",
  SERVICE_R2_PUBLIC: "MINIFLARE_R2_PUBLIC",
  SERVICE_R2_S3: "MINIFLARE_R2_S3",
  SERVICE_OBSERVABILITY_COLLECTOR: "MINIFLARE_OBSERVABILITY_COLLECTOR",
  JSON_ACCESS_BLOB_PREFIX: "MINIFLARE_ACCESS_BLOB_",
  TEXT_FALLBACK_WORKER_NAME: "MINIFLARE_FALLBACK_WORKER_NAME"
};
var ProxyOps = {
  // Get the target or a property of the target
  GET: "GET",
  // Get the descriptor for a property of the target
  GET_OWN_DESCRIPTOR: "GET_OWN_DESCRIPTOR",
  // Get the target's own property names
  GET_OWN_KEYS: "GET_OWN_KEYS",
  // Call a method on the target
  CALL: "CALL",
  // Remove the strong reference to the target on the "heap", allowing it to be
  // garbage collected
  FREE: "FREE"
};
var ProxyAddresses = {
  GLOBAL: 0,
  // globalThis
  ENV: 1,
  // env
  USER_START: 2
};
function decodeErrorPayload(response) {
  const payload = response.headers.get(CoreHeaders.ERROR_STACK_PAYLOAD);
  if (payload === null) {
    return null;
  }
  try {
    return decodeURIComponent(payload);
  } catch {
    return null;
  }
}
function isFetcherFetch(targetName, key) {
  return (targetName === "Fetcher" || targetName === "DurableObject" || targetName === "WorkerRpc") && key === "fetch";
}
function isR2ObjectWriteHttpMetadata(targetName, key) {
  return (targetName === "HeadResult" || targetName === "GetResult") && key === "writeHttpMetadata";
}
function isImagesInput(targetName, key) {
  return targetName === "ImagesBindingImpl" && key === "input";
}
function isDurableObjectStub(targetName) {
  return targetName === "DurableObject" || targetName === "WorkerRpc";
}

// src/workers/core/devalue.ts
var import_node_assert3 = __toESM(require("node:assert"));
var import_node_buffer2 = require("node:buffer");

// ../../node_modules/.pnpm/devalue@5.6.3/node_modules/devalue/src/utils.js
var DevalueError = class extends Error {
  /**
   * @param {string} message
   * @param {string[]} keys
   * @param {any} [value] - The value that failed to be serialized
   * @param {any} [root] - The root value being serialized
   */
  constructor(message, keys, value, root) {
    super(message);
    this.name = "DevalueError";
    this.path = keys.join("");
    this.value = value;
    this.root = root;
  }
};
function is_primitive(thing) {
  return Object(thing) !== thing;
}
var object_proto_names = /* @__PURE__ */ Object.getOwnPropertyNames(
  Object.prototype
).sort().join("\0");
function is_plain_object(thing) {
  const proto2 = Object.getPrototypeOf(thing);
  return proto2 === Object.prototype || proto2 === null || Object.getPrototypeOf(proto2) === null || Object.getOwnPropertyNames(proto2).sort().join("\0") === object_proto_names;
}
function get_type(thing) {
  return Object.prototype.toString.call(thing).slice(8, -1);
}
function get_escaped_char(char) {
  switch (char) {
    case '"':
      return '\\"';
    case "<":
      return "\\u003C";
    case "\\":
      return "\\\\";
    case "\n":
      return "\\n";
    case "\r":
      return "\\r";
    case "	":
      return "\\t";
    case "\b":
      return "\\b";
    case "\f":
      return "\\f";
    case "\u2028":
      return "\\u2028";
    case "\u2029":
      return "\\u2029";
    default:
      return char < " " ? `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}` : "";
  }
}
function stringify_string(str) {
  let result = "";
  let last_pos = 0;
  const len = str.length;
  for (let i = 0; i < len; i += 1) {
    const char = str[i];
    const replacement = get_escaped_char(char);
    if (replacement) {
      result += str.slice(last_pos, i) + replacement;
      last_pos = i + 1;
    }
  }
  return `"${last_pos === 0 ? str : result + str.slice(last_pos)}"`;
}
function enumerable_symbols(object3) {
  return Object.getOwnPropertySymbols(object3).filter(
    (symbol3) => Object.getOwnPropertyDescriptor(object3, symbol3).enumerable
  );
}
var is_identifier = /^[a-zA-Z_$][a-zA-Z_$0-9]*$/;
function stringify_key(key) {
  return is_identifier.test(key) ? "." + key : "[" + JSON.stringify(key) + "]";
}
function is_valid_array_index(s) {
  if (s.length === 0) return false;
  if (s.length > 1 && s.charCodeAt(0) === 48) return false;
  for (let i = 0; i < s.length; i++) {
    const c2 = s.charCodeAt(i);
    if (c2 < 48 || c2 > 57) return false;
  }
  const n = +s;
  if (n >= 2 ** 32 - 1) return false;
  if (n < 0) return false;
  return true;
}
function valid_array_indices(array3) {
  const keys = Object.keys(array3);
  for (var i = keys.length - 1; i >= 0; i--) {
    if (is_valid_array_index(keys[i])) {
      break;
    }
  }
  keys.length = i + 1;
  return keys;
}

// ../../node_modules/.pnpm/devalue@5.6.3/node_modules/devalue/src/base64.js
function encode64(arraybuffer) {
  const dv = new DataView(arraybuffer);
  let binaryString = "";
  for (let i = 0; i < arraybuffer.byteLength; i++) {
    binaryString += String.fromCharCode(dv.getUint8(i));
  }
  return binaryToAscii(binaryString);
}
function decode64(string7) {
  const binaryString = asciiToBinary(string7);
  const arraybuffer = new ArrayBuffer(binaryString.length);
  const dv = new DataView(arraybuffer);
  for (let i = 0; i < arraybuffer.byteLength; i++) {
    dv.setUint8(i, binaryString.charCodeAt(i));
  }
  return arraybuffer;
}
var KEY_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
function asciiToBinary(data) {
  if (data.length % 4 === 0) {
    data = data.replace(/==?$/, "");
  }
  let output = "";
  let buffer = 0;
  let accumulatedBits = 0;
  for (let i = 0; i < data.length; i++) {
    buffer <<= 6;
    buffer |= KEY_STRING.indexOf(data[i]);
    accumulatedBits += 6;
    if (accumulatedBits === 24) {
      output += String.fromCharCode((buffer & 16711680) >> 16);
      output += String.fromCharCode((buffer & 65280) >> 8);
      output += String.fromCharCode(buffer & 255);
      buffer = accumulatedBits = 0;
    }
  }
  if (accumulatedBits === 12) {
    buffer >>= 4;
    output += String.fromCharCode(buffer);
  } else if (accumulatedBits === 18) {
    buffer >>= 2;
    output += String.fromCharCode((buffer & 65280) >> 8);
    output += String.fromCharCode(buffer & 255);
  }
  return output;
}
function binaryToAscii(str) {
  let out = "";
  for (let i = 0; i < str.length; i += 3) {
    const groupsOfSix = [void 0, void 0, void 0, void 0];
    groupsOfSix[0] = str.charCodeAt(i) >> 2;
    groupsOfSix[1] = (str.charCodeAt(i) & 3) << 4;
    if (str.length > i + 1) {
      groupsOfSix[1] |= str.charCodeAt(i + 1) >> 4;
      groupsOfSix[2] = (str.charCodeAt(i + 1) & 15) << 2;
    }
    if (str.length > i + 2) {
      groupsOfSix[2] |= str.charCodeAt(i + 2) >> 6;
      groupsOfSix[3] = str.charCodeAt(i + 2) & 63;
    }
    for (let j = 0; j < groupsOfSix.length; j++) {
      if (typeof groupsOfSix[j] === "undefined") {
        out += "=";
      } else {
        out += KEY_STRING[groupsOfSix[j]];
      }
    }
  }
  return out;
}

// ../../node_modules/.pnpm/devalue@5.6.3/node_modules/devalue/src/constants.js
var UNDEFINED = -1;
var HOLE = -2;
var NAN = -3;
var POSITIVE_INFINITY = -4;
var NEGATIVE_INFINITY = -5;
var NEGATIVE_ZERO = -6;
var SPARSE = -7;

// ../../node_modules/.pnpm/devalue@5.6.3/node_modules/devalue/src/parse.js
function parse8(serialized, revivers2) {
  return unflatten(JSON.parse(serialized), revivers2);
}
function unflatten(parsed, revivers2) {
  if (typeof parsed === "number") return hydrate(parsed, true);
  if (!Array.isArray(parsed) || parsed.length === 0) {
    throw new Error("Invalid input");
  }
  const values = (
    /** @type {any[]} */
    parsed
  );
  const hydrated = Array(values.length);
  let hydrating = null;
  function hydrate(index, standalone = false) {
    if (index === UNDEFINED) return void 0;
    if (index === NAN) return NaN;
    if (index === POSITIVE_INFINITY) return Infinity;
    if (index === NEGATIVE_INFINITY) return -Infinity;
    if (index === NEGATIVE_ZERO) return -0;
    if (standalone || typeof index !== "number") {
      throw new Error(`Invalid input`);
    }
    if (index in hydrated) return hydrated[index];
    const value = values[index];
    if (!value || typeof value !== "object") {
      hydrated[index] = value;
    } else if (Array.isArray(value)) {
      if (typeof value[0] === "string") {
        const type = value[0];
        const reviver = revivers2 && Object.hasOwn(revivers2, type) ? revivers2[type] : void 0;
        if (reviver) {
          let i = value[1];
          if (typeof i !== "number") {
            i = values.push(value[1]) - 1;
          }
          hydrating ??= /* @__PURE__ */ new Set();
          if (hydrating.has(i)) {
            throw new Error("Invalid circular reference");
          }
          hydrating.add(i);
          hydrated[index] = reviver(hydrate(i));
          hydrating.delete(i);
          return hydrated[index];
        }
        switch (type) {
          case "Date":
            hydrated[index] = new Date(value[1]);
            break;
          case "Set":
            const set3 = /* @__PURE__ */ new Set();
            hydrated[index] = set3;
            for (let i = 1; i < value.length; i += 1) {
              set3.add(hydrate(value[i]));
            }
            break;
          case "Map":
            const map3 = /* @__PURE__ */ new Map();
            hydrated[index] = map3;
            for (let i = 1; i < value.length; i += 2) {
              map3.set(hydrate(value[i]), hydrate(value[i + 1]));
            }
            break;
          case "RegExp":
            hydrated[index] = new RegExp(value[1], value[2]);
            break;
          case "Object":
            hydrated[index] = Object(value[1]);
            break;
          case "BigInt":
            hydrated[index] = BigInt(value[1]);
            break;
          case "null":
            const obj = /* @__PURE__ */ Object.create(null);
            hydrated[index] = obj;
            for (let i = 1; i < value.length; i += 2) {
              obj[value[i]] = hydrate(value[i + 1]);
            }
            break;
          case "Int8Array":
          case "Uint8Array":
          case "Uint8ClampedArray":
          case "Int16Array":
          case "Uint16Array":
          case "Int32Array":
          case "Uint32Array":
          case "Float32Array":
          case "Float64Array":
          case "BigInt64Array":
          case "BigUint64Array": {
            if (values[value[1]][0] !== "ArrayBuffer") {
              throw new Error("Invalid data");
            }
            const TypedArrayConstructor = globalThis[type];
            const buffer = hydrate(value[1]);
            const typedArray = new TypedArrayConstructor(buffer);
            hydrated[index] = value[2] !== void 0 ? typedArray.subarray(value[2], value[3]) : typedArray;
            break;
          }
          case "ArrayBuffer": {
            const base645 = value[1];
            if (typeof base645 !== "string") {
              throw new Error("Invalid ArrayBuffer encoding");
            }
            const arraybuffer = decode64(base645);
            hydrated[index] = arraybuffer;
            break;
          }
          case "Temporal.Duration":
          case "Temporal.Instant":
          case "Temporal.PlainDate":
          case "Temporal.PlainTime":
          case "Temporal.PlainDateTime":
          case "Temporal.PlainMonthDay":
          case "Temporal.PlainYearMonth":
          case "Temporal.ZonedDateTime": {
            const temporalName = type.slice(9);
            hydrated[index] = Temporal[temporalName].from(value[1]);
            break;
          }
          case "URL": {
            const url46 = new URL(value[1]);
            hydrated[index] = url46;
            break;
          }
          case "URLSearchParams": {
            const url46 = new URLSearchParams(value[1]);
            hydrated[index] = url46;
            break;
          }
          default:
            throw new Error(`Unknown type ${type}`);
        }
      } else if (value[0] === SPARSE) {
        const len = value[1];
        const array3 = new Array(len);
        hydrated[index] = array3;
        for (let i = 2; i < value.length; i += 2) {
          const idx = value[i];
          array3[idx] = hydrate(value[i + 1]);
        }
      } else {
        const array3 = new Array(value.length);
        hydrated[index] = array3;
        for (let i = 0; i < value.length; i += 1) {
          const n = value[i];
          if (n === HOLE) continue;
          array3[i] = hydrate(n);
        }
      }
    } else {
      const object3 = {};
      hydrated[index] = object3;
      for (const key of Object.keys(value)) {
        if (key === "__proto__") {
          throw new Error("Cannot parse an object with a `__proto__` property");
        }
        const n = value[key];
        object3[key] = hydrate(n);
      }
    }
    return hydrated[index];
  }
  return hydrate(0);
}

// ../../node_modules/.pnpm/devalue@5.6.3/node_modules/devalue/src/stringify.js
function stringify3(value, reducers2) {
  const stringified = [];
  const indexes = /* @__PURE__ */ new Map();
  const custom3 = [];
  if (reducers2) {
    for (const key of Object.getOwnPropertyNames(reducers2)) {
      custom3.push({ key, fn: reducers2[key] });
    }
  }
  const keys = [];
  let p2 = 0;
  function flatten(thing) {
    if (thing === void 0) return UNDEFINED;
    if (Number.isNaN(thing)) return NAN;
    if (thing === Infinity) return POSITIVE_INFINITY;
    if (thing === -Infinity) return NEGATIVE_INFINITY;
    if (thing === 0 && 1 / thing < 0) return NEGATIVE_ZERO;
    if (indexes.has(thing)) return indexes.get(thing);
    const index2 = p2++;
    indexes.set(thing, index2);
    for (const { key, fn } of custom3) {
      const value2 = fn(thing);
      if (value2) {
        stringified[index2] = `["${key}",${flatten(value2)}]`;
        return index2;
      }
    }
    if (typeof thing === "function") {
      throw new DevalueError(`Cannot stringify a function`, keys, thing, value);
    }
    let str = "";
    if (is_primitive(thing)) {
      str = stringify_primitive(thing);
    } else {
      const type = get_type(thing);
      switch (type) {
        case "Number":
        case "String":
        case "Boolean":
          str = `["Object",${stringify_primitive(thing)}]`;
          break;
        case "BigInt":
          str = `["BigInt",${thing}]`;
          break;
        case "Date":
          const valid = !isNaN(thing.getDate());
          str = `["Date","${valid ? thing.toISOString() : ""}"]`;
          break;
        case "URL":
          str = `["URL",${stringify_string(thing.toString())}]`;
          break;
        case "URLSearchParams":
          str = `["URLSearchParams",${stringify_string(thing.toString())}]`;
          break;
        case "RegExp":
          const { source, flags } = thing;
          str = flags ? `["RegExp",${stringify_string(source)},"${flags}"]` : `["RegExp",${stringify_string(source)}]`;
          break;
        case "Array": {
          let mostly_dense = false;
          str = "[";
          for (let i = 0; i < thing.length; i += 1) {
            if (i > 0) str += ",";
            if (Object.hasOwn(thing, i)) {
              keys.push(`[${i}]`);
              str += flatten(thing[i]);
              keys.pop();
            } else if (mostly_dense) {
              str += HOLE;
            } else {
              const populated_keys = valid_array_indices(
                /** @type {any[]} */
                thing
              );
              const population = populated_keys.length;
              const d = String(thing.length).length;
              const hole_cost = (thing.length - population) * 3;
              const sparse_cost = 4 + d + population * (d + 1);
              if (hole_cost > sparse_cost) {
                str = "[" + SPARSE + "," + thing.length;
                for (let j = 0; j < populated_keys.length; j++) {
                  const key = populated_keys[j];
                  keys.push(`[${key}]`);
                  str += "," + key + "," + flatten(thing[key]);
                  keys.pop();
                }
                break;
              } else {
                mostly_dense = true;
                str += HOLE;
              }
            }
          }
          str += "]";
          break;
        }
        case "Set":
          str = '["Set"';
          for (const value2 of thing) {
            str += `,${flatten(value2)}`;
          }
          str += "]";
          break;
        case "Map":
          str = '["Map"';
          for (const [key, value2] of thing) {
            keys.push(
              `.get(${is_primitive(key) ? stringify_primitive(key) : "..."})`
            );
            str += `,${flatten(key)},${flatten(value2)}`;
            keys.pop();
          }
          str += "]";
          break;
        case "Int8Array":
        case "Uint8Array":
        case "Uint8ClampedArray":
        case "Int16Array":
        case "Uint16Array":
        case "Int32Array":
        case "Uint32Array":
        case "Float32Array":
        case "Float64Array":
        case "BigInt64Array":
        case "BigUint64Array": {
          const typedArray = thing;
          str = '["' + type + '",' + flatten(typedArray.buffer);
          const a = thing.byteOffset;
          const b = a + thing.byteLength;
          if (a > 0 || b !== typedArray.buffer.byteLength) {
            const m = +/(\d+)/.exec(type)[1] / 8;
            str += `,${a / m},${b / m}`;
          }
          str += "]";
          break;
        }
        case "ArrayBuffer": {
          const arraybuffer = thing;
          const base645 = encode64(arraybuffer);
          str = `["ArrayBuffer","${base645}"]`;
          break;
        }
        case "Temporal.Duration":
        case "Temporal.Instant":
        case "Temporal.PlainDate":
        case "Temporal.PlainTime":
        case "Temporal.PlainDateTime":
        case "Temporal.PlainMonthDay":
        case "Temporal.PlainYearMonth":
        case "Temporal.ZonedDateTime":
          str = `["${type}",${stringify_string(thing.toString())}]`;
          break;
        default:
          if (!is_plain_object(thing)) {
            throw new DevalueError(
              `Cannot stringify arbitrary non-POJOs`,
              keys,
              thing,
              value
            );
          }
          if (enumerable_symbols(thing).length > 0) {
            throw new DevalueError(
              `Cannot stringify POJOs with symbolic keys`,
              keys,
              thing,
              value
            );
          }
          if (Object.getPrototypeOf(thing) === null) {
            str = '["null"';
            for (const key of Object.keys(thing)) {
              if (key === "__proto__") {
                throw new DevalueError(
                  `Cannot stringify objects with __proto__ keys`,
                  keys,
                  thing,
                  value
                );
              }
              keys.push(stringify_key(key));
              str += `,${stringify_string(key)},${flatten(thing[key])}`;
              keys.pop();
            }
            str += "]";
          } else {
            str = "{";
            let started = false;
            for (const key of Object.keys(thing)) {
              if (key === "__proto__") {
                throw new DevalueError(
                  `Cannot stringify objects with __proto__ keys`,
                  keys,
                  thing,
                  value
                );
              }
              if (started) str += ",";
              started = true;
              keys.push(stringify_key(key));
              str += `${stringify_string(key)}:${flatten(thing[key])}`;
              keys.pop();
            }
            str += "}";
          }
      }
    }
    stringified[index2] = str;
    return index2;
  }
  const index = flatten(value);
  if (index < 0) return `${index}`;
  return `[${stringified.join(",")}]`;
}
function stringify_primitive(thing) {
  const type = typeof thing;
  if (type === "string") return stringify_string(thing);
  if (thing instanceof String) return stringify_string(thing.toString());
  if (thing === void 0) return UNDEFINED.toString();
  if (thing === 0 && 1 / thing < 0) return NEGATIVE_ZERO.toString();
  if (type === "bigint") return `["BigInt","${thing}"]`;
  return String(thing);
}

// src/workers/core/devalue.ts
var ALLOWED_ARRAY_BUFFER_VIEW_CONSTRUCTORS = [
  DataView,
  Int8Array,
  Uint8Array,
  Uint8ClampedArray,
  Int16Array,
  Uint16Array,
  Int32Array,
  Uint32Array,
  Float32Array,
  Float64Array,
  BigInt64Array,
  BigUint64Array
];
var ALLOWED_ERROR_CONSTRUCTORS = [
  EvalError,
  RangeError,
  ReferenceError,
  SyntaxError,
  TypeError,
  URIError,
  Error
  // `Error` last so more specific error subclasses preferred
];
var structuredSerializableReducers = {
  ArrayBuffer(value) {
    if (value instanceof ArrayBuffer) {
      return [import_node_buffer2.Buffer.from(value).toString("base64")];
    }
  },
  ArrayBufferView(value) {
    if (ArrayBuffer.isView(value)) {
      let name = value.constructor.name;
      if (!ALLOWED_ARRAY_BUFFER_VIEW_CONSTRUCTORS.some((c2) => c2.name === name)) {
        for (const ctor of ALLOWED_ARRAY_BUFFER_VIEW_CONSTRUCTORS) {
          if (value instanceof ctor) {
            name = ctor.name;
            break;
          }
        }
      }
      let buf = value.buffer;
      let off = value.byteOffset;
      if (off !== 0 || buf.byteLength !== value.byteLength) {
        buf = buf.slice(off, off + value.byteLength);
        off = 0;
      }
      return [name, buf, off, value.byteLength];
    }
  },
  RegExp(value) {
    if (value instanceof RegExp) {
      const { source, flags } = value;
      const encoded = import_node_buffer2.Buffer.from(source).toString("base64");
      return flags ? ["RegExp", encoded, flags] : ["RegExp", encoded];
    }
  },
  Error(value) {
    for (const ctor of ALLOWED_ERROR_CONSTRUCTORS) {
      if (value instanceof ctor && value.name === ctor.name) {
        return [value.name, value.message, value.stack, value.cause];
      }
    }
    if (value instanceof Error) {
      return ["Error", value.message, value.stack, value.cause];
    }
  }
};
var structuredSerializableRevivers = {
  ArrayBuffer(value) {
    (0, import_node_assert3.default)(Array.isArray(value));
    const [encoded] = value;
    (0, import_node_assert3.default)(typeof encoded === "string");
    const view = import_node_buffer2.Buffer.from(encoded, "base64");
    return view.buffer.slice(
      view.byteOffset,
      view.byteOffset + view.byteLength
    );
  },
  ArrayBufferView(value) {
    (0, import_node_assert3.default)(Array.isArray(value));
    const [name, buffer, byteOffset, byteLength] = value;
    (0, import_node_assert3.default)(typeof name === "string");
    (0, import_node_assert3.default)(buffer instanceof ArrayBuffer);
    (0, import_node_assert3.default)(typeof byteOffset === "number");
    (0, import_node_assert3.default)(typeof byteLength === "number");
    const ctor = globalThis[name];
    (0, import_node_assert3.default)(ALLOWED_ARRAY_BUFFER_VIEW_CONSTRUCTORS.includes(ctor));
    let length = byteLength;
    if ("BYTES_PER_ELEMENT" in ctor) length /= ctor.BYTES_PER_ELEMENT;
    return new ctor(buffer, byteOffset, length);
  },
  RegExp(value) {
    (0, import_node_assert3.default)(Array.isArray(value));
    const [name, encoded, flags] = value;
    (0, import_node_assert3.default)(typeof name === "string");
    (0, import_node_assert3.default)(typeof encoded === "string");
    const source = import_node_buffer2.Buffer.from(encoded, "base64").toString("utf-8");
    return new RegExp(source, flags);
  },
  Error(value) {
    (0, import_node_assert3.default)(Array.isArray(value));
    const [name, message, stack, cause] = value;
    (0, import_node_assert3.default)(typeof name === "string");
    (0, import_node_assert3.default)(typeof message === "string");
    (0, import_node_assert3.default)(stack === void 0 || typeof stack === "string");
    const ctor = globalThis[name];
    (0, import_node_assert3.default)(ALLOWED_ERROR_CONSTRUCTORS.includes(ctor));
    const error101 = new ctor(message, { cause });
    error101.stack = stack;
    return error101;
  }
};
function createHTTPReducers(impl) {
  return {
    Headers(val) {
      if (val instanceof impl.Headers) return [...val.entries()];
    },
    Request(val) {
      if (val instanceof impl.Request) {
        return [val.method, val.url, val.headers, val.cf, val.body];
      }
    },
    Response(val) {
      if (val instanceof impl.Response) {
        return [val.status, val.statusText, val.headers, val.cf, val.body];
      }
    }
  };
}
function createHTTPRevivers(impl) {
  return {
    Headers(value) {
      (0, import_node_assert3.default)(typeof value === "object" && value !== null);
      return new impl.Headers(value);
    },
    Request(value) {
      (0, import_node_assert3.default)(Array.isArray(value));
      const [method, url46, headers, cf, body] = value;
      (0, import_node_assert3.default)(typeof method === "string");
      (0, import_node_assert3.default)(typeof url46 === "string");
      (0, import_node_assert3.default)(headers instanceof impl.Headers);
      (0, import_node_assert3.default)(body === null || impl.isReadableStream(body));
      return new impl.Request(url46, {
        method,
        headers,
        cf,
        // @ts-expect-error `duplex` is not required by `workerd` yet
        duplex: body === null ? void 0 : "half",
        body
      });
    },
    Response(value) {
      (0, import_node_assert3.default)(Array.isArray(value));
      const [status2, statusText, headers, cf, body] = value;
      (0, import_node_assert3.default)(typeof status2 === "number");
      (0, import_node_assert3.default)(typeof statusText === "string");
      (0, import_node_assert3.default)(headers instanceof impl.Headers);
      (0, import_node_assert3.default)(body === null || impl.isReadableStream(body));
      return new impl.Response(body, {
        status: status2,
        statusText,
        headers,
        cf
      });
    }
  };
}
function stringifyWithStreams(impl, value, reducers2, allowUnbufferedStream) {
  let unbufferedStream;
  const bufferPromises = [];
  const streamReducers = {
    ReadableStream(value2) {
      if (impl.isReadableStream(value2)) {
        if (allowUnbufferedStream && unbufferedStream === void 0) {
          unbufferedStream = value2;
        } else {
          bufferPromises.push(impl.bufferReadableStream(value2));
        }
        return true;
      }
    },
    Blob(value2) {
      if (value2 instanceof impl.Blob) {
        bufferPromises.push(value2.arrayBuffer());
        return true;
      }
    },
    ...reducers2
  };
  if (typeof value === "function") {
    value = new __MiniflareFunctionWrapper(
      value
    );
  }
  const stringifiedValue = stringify3(value, streamReducers);
  if (bufferPromises.length === 0) {
    return { value: stringifiedValue, unbufferedStream };
  }
  return Promise.all(bufferPromises).then((streamBuffers) => {
    streamReducers.ReadableStream = function(value2) {
      if (impl.isReadableStream(value2)) {
        if (value2 === unbufferedStream) {
          return true;
        } else {
          return streamBuffers.shift();
        }
      }
    };
    streamReducers.Blob = function(value2) {
      if (value2 instanceof impl.Blob) {
        const array3 = [streamBuffers.shift(), value2.type];
        if (value2 instanceof impl.File) {
          array3.push(value2.name, value2.lastModified);
        }
        return array3;
      }
    };
    const stringifiedValue2 = stringify3(value, streamReducers);
    return { value: stringifiedValue2, unbufferedStream };
  });
}
var __MiniflareFunctionWrapper = class {
  constructor(fnWithProps) {
    return new Proxy(this, {
      get: (_, key) => {
        if (key === "__miniflareWrappedFunction") return fnWithProps;
        return fnWithProps[key];
      }
    });
  }
};
function parseWithReadableStreams(impl, stringified, revivers2) {
  const streamRevivers = {
    ReadableStream(value) {
      if (value === true) {
        (0, import_node_assert3.default)(stringified.unbufferedStream !== void 0);
        return stringified.unbufferedStream;
      }
      (0, import_node_assert3.default)(value instanceof ArrayBuffer);
      return impl.unbufferReadableStream(value);
    },
    Blob(value) {
      (0, import_node_assert3.default)(Array.isArray(value));
      if (value.length === 2) {
        const [buffer, type] = value;
        (0, import_node_assert3.default)(buffer instanceof ArrayBuffer);
        (0, import_node_assert3.default)(typeof type === "string");
        const opts = {};
        if (type !== "") opts.type = type;
        return new impl.Blob([buffer], opts);
      } else {
        (0, import_node_assert3.default)(value.length === 4);
        const [buffer, type, name, lastModified] = value;
        (0, import_node_assert3.default)(buffer instanceof ArrayBuffer);
        (0, import_node_assert3.default)(typeof type === "string");
        (0, import_node_assert3.default)(typeof name === "string");
        (0, import_node_assert3.default)(typeof lastModified === "number");
        const opts = { lastModified };
        if (type !== "") opts.type = type;
        return new impl.File([buffer], name, opts);
      }
    },
    ...revivers2
  };
  return parse8(stringified.value, streamRevivers);
}

// src/workers/core/routing.ts
function matchRoutes(routes, url46) {
  for (const route of routes) {
    if (route.protocol && route.protocol !== url46.protocol) continue;
    if (route.allowHostnamePrefix) {
      if (!url46.hostname.endsWith(route.hostname)) continue;
    } else {
      if (url46.hostname !== route.hostname) continue;
    }
    const path73 = url46.pathname + url46.search;
    if (route.allowPathSuffix) {
      if (!path73.startsWith(route.path)) continue;
    } else {
      if (path73 !== route.path) continue;
    }
    return route.target;
  }
  return null;
}

// src/workers/shared/constants.ts
var SharedHeaders = {
  LOG_LEVEL: "MF-Log-Level"
};
var SharedBindings = {
  TEXT_NAMESPACE: "MINIFLARE_NAMESPACE",
  DURABLE_OBJECT_NAMESPACE_OBJECT: "MINIFLARE_OBJECT",
  MAYBE_SERVICE_BLOBS: "MINIFLARE_BLOBS",
  MAYBE_SERVICE_LOOPBACK: "MINIFLARE_LOOPBACK",
  MAYBE_JSON_ENABLE_CONTROL_ENDPOINTS: "MINIFLARE_ENABLE_CONTROL_ENDPOINTS"
};
var LogLevel = /* @__PURE__ */ ((LogLevel2) => {
  LogLevel2[LogLevel2["NONE"] = 0] = "NONE";
  LogLevel2[LogLevel2["ERROR"] = 1] = "ERROR";
  LogLevel2[LogLevel2["WARN"] = 2] = "WARN";
  LogLevel2[LogLevel2["INFO"] = 3] = "INFO";
  LogLevel2[LogLevel2["DEBUG"] = 4] = "DEBUG";
  LogLevel2[LogLevel2["VERBOSE"] = 5] = "VERBOSE";
  return LogLevel2;
})(LogLevel || {});

// src/workers/shared/data.ts
var import_node_buffer3 = require("node:buffer");
function viewToBuffer(view) {
  return view.buffer.slice(
    view.byteOffset,
    view.byteOffset + view.byteLength
  );
}
function base64Encode(value) {
  return import_node_buffer3.Buffer.from(value, "utf8").toString("base64");
}
function base64Decode(encoded) {
  return import_node_buffer3.Buffer.from(encoded, "base64").toString("utf8");
}
var dotRegexp = /(^|\/|\\)(\.+)(\/|\\|$)/g;
var illegalRegexp = /[?<>*"'^/\\:|\x00-\x1f\x80-\x9f]/g;
var windowsReservedRegexp = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i;
var leadingRegexp = /^[ /\\]+/;
var trailingRegexp = /[ /\\]+$/;
function dotReplacement(match, g1, g2, g3) {
  return `${g1}${"".padStart(g2.length, "_")}${g3}`;
}
function underscoreReplacement(match) {
  return "".padStart(match.length, "_");
}
function sanitisePath(unsafe) {
  return unsafe.replace(dotRegexp, dotReplacement).replace(dotRegexp, dotReplacement).replace(illegalRegexp, "_").replace(windowsReservedRegexp, "_").replace(leadingRegexp, underscoreReplacement).replace(trailingRegexp, underscoreReplacement).substring(0, 255);
}

// src/workers/shared/matcher.ts
function testRegExps(matcher, value) {
  for (const exclude of matcher.exclude) if (exclude.test(value)) return false;
  for (const include of matcher.include) if (include.test(value)) return true;
  return false;
}

// src/workers/shared/range.ts
var rangePrefixRegexp = /^ *bytes *=/i;
var rangeRegexp = /^ *(?<start>\d+)? *- *(?<end>\d+)? *$/;
function parseRanges(rangeHeader, length) {
  const prefixMatch = rangePrefixRegexp.exec(rangeHeader);
  if (prefixMatch === null) return;
  rangeHeader = rangeHeader.substring(prefixMatch[0].length);
  if (rangeHeader.trimStart() === "") return [];
  const ranges = rangeHeader.split(",");
  const result = [];
  for (const range of ranges) {
    const match = rangeRegexp.exec(range);
    if (match === null) return;
    const { start, end } = match.groups;
    if (start !== void 0 && end !== void 0) {
      const rangeStart = parseInt(start);
      let rangeEnd = parseInt(end);
      if (rangeStart > rangeEnd) return;
      if (rangeStart >= length) return;
      if (rangeEnd >= length) rangeEnd = length - 1;
      result.push({ start: rangeStart, end: rangeEnd });
    } else if (start !== void 0 && end === void 0) {
      const rangeStart = parseInt(start);
      if (rangeStart >= length) return;
      result.push({ start: rangeStart, end: length - 1 });
    } else if (start === void 0 && end !== void 0) {
      const suffix = parseInt(end);
      if (suffix >= length) return [];
      if (suffix === 0) continue;
      result.push({ start: length - suffix, end: length - 1 });
    } else {
      return;
    }
  }
  return result;
}

// src/workers/shared/sync.ts
var import_node_assert4 = __toESM(require("node:assert"));
var DeferredPromise = class extends Promise {
  resolve;
  reject;
  constructor(executor = () => {
  }) {
    let promiseResolve = void 0;
    let promiseReject = void 0;
    super((resolve8, reject) => {
      promiseResolve = resolve8;
      promiseReject = reject;
      return executor(resolve8, reject);
    });
    (0, import_node_assert4.default)(promiseResolve);
    (0, import_node_assert4.default)(promiseReject);
    this.resolve = promiseResolve;
    this.reject = promiseReject;
  }
};
var Mutex = class {
  locked = false;
  resolveQueue = [];
  drainQueue = [];
  lock() {
    if (!this.locked) {
      this.locked = true;
      return;
    }
    return new Promise((resolve8) => this.resolveQueue.push(resolve8));
  }
  unlock() {
    (0, import_node_assert4.default)(this.locked);
    if (this.resolveQueue.length > 0) {
      this.resolveQueue.shift()?.();
    } else {
      this.locked = false;
      let resolve8;
      while ((resolve8 = this.drainQueue.shift()) !== void 0) resolve8();
    }
  }
  get hasWaiting() {
    return this.resolveQueue.length > 0;
  }
  async runWith(closure) {
    const acquireAwaitable = this.lock();
    if (acquireAwaitable instanceof Promise) await acquireAwaitable;
    try {
      const awaitable = closure();
      if (awaitable instanceof Promise) return await awaitable;
      return awaitable;
    } finally {
      this.unlock();
    }
  }
  async drained() {
    if (this.resolveQueue.length === 0 && !this.locked) return;
    return new Promise((resolve8) => this.drainQueue.push(resolve8));
  }
};
var WaitGroup = class {
  counter = 0;
  resolveQueue = [];
  add() {
    this.counter++;
  }
  done() {
    (0, import_node_assert4.default)(this.counter > 0);
    this.counter--;
    if (this.counter === 0) {
      let resolve8;
      while ((resolve8 = this.resolveQueue.shift()) !== void 0) resolve8();
    }
  }
  wait() {
    if (this.counter === 0) return Promise.resolve();
    return new Promise((resolve8) => this.resolveQueue.push(resolve8));
  }
};

// src/workers/shared/types.ts
function reduceError(e) {
  return {
    name: e?.name,
    message: e?.message ?? String(e),
    stack: e?.stack,
    cause: e?.cause === void 0 ? void 0 : reduceError(e.cause)
  };
}
function maybeApply(f, maybeValue) {
  return maybeValue === void 0 ? void 0 : f(maybeValue);
}

// src/workers/kv/constants.ts
var KVLimits = {
  MIN_CACHE_TTL_SECONDS: 30,
  MIN_EXPIRATION_TTL_SECONDS: 60,
  MAX_LIST_KEYS: 1e3,
  MAX_KEY_SIZE_BYTES: 512,
  MAX_VALUE_SIZE_BYTES: 25 * 1024 * 1024,
  MAX_VALUE_SIZE_TEST_BYTES: 1024,
  MAX_METADATA_SIZE_BYTES: 1024,
  MAX_BULK_SIZE_BYTES: 25 * 1024 * 1024
};
var KVParams = {
  URL_ENCODED: "urlencoded",
  CACHE_TTL: "cache_ttl",
  EXPIRATION: "expiration",
  EXPIRATION_TTL: "expiration_ttl",
  LIST_LIMIT: "key_count_limit",
  LIST_PREFIX: "prefix",
  LIST_CURSOR: "cursor"
};
var KVHeaders = {
  EXPIRATION: "CF-Expiration",
  METADATA: "CF-KV-Metadata"
};
var SiteBindings = {
  KV_NAMESPACE_SITE: "__STATIC_CONTENT",
  JSON_SITE_MANIFEST: "__STATIC_CONTENT_MANIFEST",
  JSON_SITE_FILTER: "MINIFLARE_SITE_FILTER"
};
var SITES_NO_CACHE_PREFIX = "$__MINIFLARE_SITES__$/";
var MAX_BULK_GET_KEYS = 100;
function encodeSitesKey(key) {
  return SITES_NO_CACHE_PREFIX + encodeURIComponent(key);
}
function decodeSitesKey(key) {
  return key.startsWith(SITES_NO_CACHE_PREFIX) ? decodeURIComponent(key.substring(SITES_NO_CACHE_PREFIX.length)) : key;
}
function isSitesRequest(request4) {
  const url46 = new URL(request4.url);
  return url46.pathname.startsWith(`/${SITES_NO_CACHE_PREFIX}`);
}
function serialiseRegExp(regExp) {
  const str = regExp.toString();
  return str.substring(str.indexOf("/") + 1, str.lastIndexOf("/"));
}
function serialiseRegExps(matcher) {
  return {
    include: matcher.include.map(serialiseRegExp),
    exclude: matcher.exclude.map(serialiseRegExp)
  };
}
function deserialiseRegExps(matcher) {
  return {
    include: matcher.include.map((regExp) => new RegExp(regExp)),
    exclude: matcher.exclude.map((regExp) => new RegExp(regExp))
  };
}
function serialiseSiteRegExps(siteRegExps) {
  return {
    include: siteRegExps.include && serialiseRegExps(siteRegExps.include),
    exclude: siteRegExps.exclude && serialiseRegExps(siteRegExps.exclude)
  };
}
function deserialiseSiteRegExps(siteRegExps) {
  return {
    include: siteRegExps.include && deserialiseRegExps(siteRegExps.include),
    exclude: siteRegExps.exclude && deserialiseRegExps(siteRegExps.exclude)
  };
}
function testSiteRegExps(regExps, key) {
  if (regExps.include !== void 0) return testRegExps(regExps.include, key);
  if (regExps.exclude !== void 0) return !testRegExps(regExps.exclude, key);
  return true;
}
function getAssetsBindingsNames(assetsKVBindingName = "__STATIC_ASSETS_CONTENT", assetsManifestBindingName = "__STATIC_ASSETS_CONTENT_MANIFEST") {
  return {
    ASSETS_KV_NAMESPACE: assetsKVBindingName,
    ASSETS_MANIFEST: assetsManifestBindingName
  };
}

// src/workers/queues/constants.ts
var QueueBindings = {
  SERVICE_WORKER_PREFIX: "MINIFLARE_WORKER_",
  MAYBE_JSON_QUEUE_PRODUCERS: "MINIFLARE_QUEUE_PRODUCERS",
  MAYBE_JSON_QUEUE_CONSUMERS: "MINIFLARE_QUEUE_CONSUMERS",
  // Optional service binding to the dev-registry proxy's `ExternalQueueProxy`
  // entrypoint, present when the dev registry is enabled for queue brokers.
  MAYBE_SERVICE_QUEUE_PROXY: "MINIFLARE_QUEUE_PROXY"
};
var HEADER_QUEUE_NAME = "MF-Queue-Name";
var SERVICE_QUEUE_PREFIX = "queues:queue";
function getQueueServiceName(queueId) {
  return `${SERVICE_QUEUE_PREFIX}:${queueId}`;
}

// src/workers/shared/zod.worker.ts
var import_node_buffer4 = require("node:buffer");
var HEX_REGEXP = /^[0-9a-f]*$/i;
var BASE64_REGEXP = /^[0-9a-z+/=]*$/i;
var HexDataSchema = external_exports2.string().regex(HEX_REGEXP).transform((hex5) => import_node_buffer4.Buffer.from(hex5, "hex"));
var Base64DataSchema = external_exports2.string().regex(BASE64_REGEXP).transform((base645) => import_node_buffer4.Buffer.from(base645, "base64"));

// src/workers/queues/schemas.ts
var QueueMessageDelaySchema = external_exports2.number().int().min(0).max(86400).optional();
var QueueProducerOptionsSchema = /* @__PURE__ */ external_exports2.object({
  // https://developers.cloudflare.com/queues/platform/configuration/#producer
  queueName: external_exports2.string(),
  deliveryDelay: QueueMessageDelaySchema
});
var QueueProducerSchema = /* @__PURE__ */ external_exports2.intersection(
  QueueProducerOptionsSchema,
  external_exports2.object({ workerName: external_exports2.string() })
);
var QueueProducersSchema = /* @__PURE__ */ external_exports2.record(external_exports2.string(), QueueProducerSchema);
var QueueConsumerOptionsSchema = /* @__PURE__ */ external_exports2.object({
  // https://developers.cloudflare.com/queues/platform/configuration/#consumer
  // https://developers.cloudflare.com/queues/platform/limits/
  maxBatchSize: external_exports2.number().min(0).max(100).optional(),
  maxBatchTimeout: external_exports2.number().min(0).max(60).optional(),
  // seconds
  maxRetries: external_exports2.number().min(0).max(100).optional(),
  deadLetterQueue: external_exports2.string().optional(),
  retryDelay: QueueMessageDelaySchema
});
var QueueConsumerSchema = /* @__PURE__ */ external_exports2.intersection(
  QueueConsumerOptionsSchema,
  external_exports2.object({ workerName: external_exports2.string() })
);
var QueueConsumersSchema = /* @__PURE__ */ external_exports2.record(external_exports2.string(), QueueConsumerSchema);
var QueueContentTypeSchema = /* @__PURE__ */ external_exports2.enum(["text", "json", "bytes", "v8"]).default("v8");
var QueueIncomingMessageSchema = /* @__PURE__ */ external_exports2.object({
  contentType: QueueContentTypeSchema,
  delaySecs: QueueMessageDelaySchema,
  body: Base64DataSchema,
  // When enqueuing messages on dead-letter queues, we want to reuse the same ID
  // and timestamp
  id: external_exports2.string().optional(),
  timestamp: external_exports2.number().optional()
});
var QueuesBatchRequestSchema = /* @__PURE__ */ external_exports2.object({
  messages: external_exports2.array(QueueIncomingMessageSchema)
});

// src/plugins/shared/constants.ts
var SOCKET_ENTRY = "entry";
var SOCKET_ENTRY_LOCAL = "entry:local";
var SOCKET_DEBUG_PORT = "debug-port";
var SOCKET_DEV_REGISTRY = "dev-registry";
var SOCKET_DIRECT_PREFIX = "direct";
function getDirectSocketName(workerIndex, entrypoint) {
  return `${SOCKET_DIRECT_PREFIX}:${workerIndex}:${entrypoint}`;
}
var SERVICE_LOOPBACK = "loopback";
var SERVICE_DEV_REGISTRY_PROXY = "dev-registry-proxy";
var HOST_CAPNP_CONNECT = "miniflare-unsafe-internal-capnp-connect";
var WORKER_BINDING_SERVICE_LOOPBACK = {
  name: CoreBindings.SERVICE_LOOPBACK,
  service: { name: SERVICE_LOOPBACK }
};
var WORKER_BINDING_ENABLE_CONTROL_ENDPOINTS = {
  name: SharedBindings.MAYBE_JSON_ENABLE_CONTROL_ENDPOINTS,
  json: "true"
};
var enableControlEndpoints = false;
function getMiniflareObjectBindings() {
  const result = [];
  if (enableControlEndpoints) {
    result.push(WORKER_BINDING_ENABLE_CONTROL_ENDPOINTS);
  }
  return result;
}
function _enableControlEndpoints() {
  enableControlEndpoints = true;
}
function objectEntryWorker(durableObjectNamespace, namespace) {
  return {
    compatibilityDate: "2023-07-24",
    modules: [
      { name: "object-entry.worker.js", esModule: object_entry_worker_default() }
    ],
    bindings: [
      ...namespace !== void 0 ? [{ name: SharedBindings.TEXT_NAMESPACE, text: namespace }] : [],
      {
        name: SharedBindings.DURABLE_OBJECT_NAMESPACE_OBJECT,
        durableObjectNamespace
      }
    ]
  };
}
function buildObjectEntryProps(id) {
  return {
    json: JSON.stringify({ [SharedBindings.TEXT_NAMESPACE]: id })
  };
}
function extractObjectEntryId(propsJson) {
  if (propsJson === void 0) {
    return void 0;
  }
  try {
    const parsed = JSON.parse(propsJson);
    const id = parsed[SharedBindings.TEXT_NAMESPACE];
    return typeof id === "string" ? id : void 0;
  } catch {
    return void 0;
  }
}
function remoteProxyClientWorker(script, options) {
  return {
    compatibilityDate: "2025-01-01",
    // Raw TCP bindings (e.g. VPC networks) tunnel `binding.connect()` traffic
    // through this worker's inbound `connect` handler, which requires the
    // `experimental` compatibility flag (workerd#6059). Other bindings only
    // proxy HTTP/JSRPC and must not opt in.
    ...options?.rawTcp ? { compatibilityFlags: ["experimental"] } : {},
    modules: [
      {
        name: "index.worker.js",
        esModule: (script ?? remote_proxy_client_worker_default)()
      }
    ],
    bindings: [WORKER_BINDING_SERVICE_LOOPBACK]
  };
}
function buildRemoteProxyProps(remoteProxyConnectionString, binding) {
  return {
    json: JSON.stringify({
      remoteProxyConnectionString: remoteProxyConnectionString?.href,
      binding,
      cfTraceId: process.env.CF_TRACE_ID
    })
  };
}
var kUnsafeEphemeralUniqueKey = /* @__PURE__ */ Symbol.for(
  "miniflare.kUnsafeEphemeralUniqueKey"
);

// ../../node_modules/.pnpm/capnp-es@0.0.16_typescript@5.8.3/node_modules/capnp-es/dist/shared/capnp-es.D8zdZmih.mjs
var ListElementSize = /* @__PURE__ */ ((ListElementSize2) => {
  ListElementSize2[ListElementSize2["VOID"] = 0] = "VOID";
  ListElementSize2[ListElementSize2["BIT"] = 1] = "BIT";
  ListElementSize2[ListElementSize2["BYTE"] = 2] = "BYTE";
  ListElementSize2[ListElementSize2["BYTE_2"] = 3] = "BYTE_2";
  ListElementSize2[ListElementSize2["BYTE_4"] = 4] = "BYTE_4";
  ListElementSize2[ListElementSize2["BYTE_8"] = 5] = "BYTE_8";
  ListElementSize2[ListElementSize2["POINTER"] = 6] = "POINTER";
  ListElementSize2[ListElementSize2["COMPOSITE"] = 7] = "COMPOSITE";
  return ListElementSize2;
})(ListElementSize || {});
var tmpWord = new DataView(new ArrayBuffer(8));
new Uint16Array(tmpWord.buffer)[0] = 258;
var DEFAULT_BUFFER_SIZE = 4096;
var DEFAULT_TRAVERSE_LIMIT = 64 << 20;
var LIST_SIZE_MASK = 7;
var MAX_BUFFER_DUMP_BYTES = 8192;
var MAX_INT32 = 2147483647;
var MAX_UINT32 = 4294967295;
var MIN_SINGLE_SEGMENT_GROWTH = 4096;
var NATIVE_LITTLE_ENDIAN = tmpWord.getUint8(0) === 2;
var PACK_SPAN_THRESHOLD = 2;
var POINTER_DOUBLE_FAR_MASK = 4;
var POINTER_TYPE_MASK = 3;
var MAX_DEPTH = MAX_INT32;
var MAX_SEGMENT_LENGTH = MAX_UINT32;
var INVARIANT_UNREACHABLE_CODE = "CAPNP-TS000 Unreachable code detected.";
function assertNever3(n) {
  throw new Error(INVARIANT_UNREACHABLE_CODE + ` (never block hit with: ${n})`);
}
var MSG_INVALID_FRAME_HEADER = "CAPNP-TS001 Attempted to parse an invalid message frame header; are you sure this is a Cap'n Proto message?";
var MSG_PACK_NOT_WORD_ALIGNED = "CAPNP-TS003 Attempted to pack a message that was not word-aligned.";
var MSG_SEGMENT_OUT_OF_BOUNDS = "CAPNP-TS004 Segment ID %X is out of bounds for message %s.";
var MSG_SEGMENT_TOO_SMALL = "CAPNP-TS005 First segment must have at least enough room to hold the root pointer (8 bytes).";
var PTR_ADOPT_WRONG_MESSAGE = "CAPNP-TS008 Attempted to adopt %s into a pointer in a different message %s.";
var PTR_ALREADY_ADOPTED = "CAPNP-TS009 Attempted to adopt %s more than once.";
var PTR_COMPOSITE_SIZE_UNDEFINED = "CAPNP-TS010 Attempted to set a composite list without providing a composite element size.";
var PTR_DEPTH_LIMIT_EXCEEDED = "CAPNP-TS011 Nesting depth limit exceeded for %s.";
var PTR_INIT_COMPOSITE_STRUCT = "CAPNP-TS013 Attempted to initialize a struct member from a composite list (%s).";
var PTR_INVALID_FAR_TARGET = "CAPNP-TS015 Target of a far pointer (%s) is another far pointer.";
var PTR_INVALID_LIST_SIZE = "CAPNP-TS016 Invalid list element size: %x.";
var PTR_INVALID_POINTER_TYPE = "CAPNP-TS017 Invalid pointer type: %x.";
var PTR_INVALID_UNION_ACCESS = "CAPNP-TS018 Attempted to access getter on %s for union field %s that is not currently set (wanted: %d, found: %d).";
var PTR_OFFSET_OUT_OF_BOUNDS = "CAPNP-TS019 Pointer offset %a is out of bounds for underlying buffer.";
var PTR_STRUCT_DATA_OUT_OF_BOUNDS = "CAPNP-TS020 Attempted to access out-of-bounds struct data (struct: %s, %d bytes at %a, data words: %d).";
var PTR_STRUCT_POINTER_OUT_OF_BOUNDS = "CAPNP-TS021 Attempted to access out-of-bounds struct pointer (%s, index: %d, length: %d).";
var PTR_TRAVERSAL_LIMIT_EXCEEDED = "CAPNP-TS022 Traversal limit exceeded! Slow down! %s";
var PTR_WRONG_LIST_TYPE = "CAPNP-TS023 Cannot convert %s to a %s list.";
var PTR_WRONG_POINTER_TYPE = "CAPNP-TS024 Attempted to convert pointer %s to a %s type.";
var SEG_GET_NON_ZERO_SINGLE = "CAPNP-TS035 Attempted to get a segment other than 0 (%d) from a single segment arena.";
var SEG_ID_OUT_OF_BOUNDS = "CAPNP-TS036 Attempted to get an out-of-bounds segment (%d).";
var SEG_NOT_WORD_ALIGNED = "CAPNP-TS037 Segment buffer length %d is not a multiple of 8.";
var SEG_REPLACEMENT_BUFFER_TOO_SMALL = "CAPNP-TS038 Attempted to replace a segment buffer with one that is smaller than the allocated space.";
var SEG_SIZE_OVERFLOW = `CAPNP-TS039 Requested size %x exceeds maximum value (${MAX_SEGMENT_LENGTH}).`;
var TYPE_COMPOSITE_SIZE_UNDEFINED = "CAPNP-TS040 Must provide a composite element size for composite list pointers.";
var LIST_NO_MUTABLE = "CAPNP-TS045: Cannot call mutative methods on an immutable list.";
var LIST_NO_SEARCH = "CAPNP-TS046: Search is not supported for list.";
var RPC_NULL_CLIENT = "CAPNP-TS100 Call on null client.";
function bufferToHex(buffer) {
  const a = new Uint8Array(buffer);
  const h = [];
  for (let i = 0; i < a.byteLength; i++) {
    h.push(pad(a[i].toString(16), 2));
  }
  return `[${h.join(" ")}]`;
}
function dumpBuffer(buffer) {
  const b = buffer instanceof ArrayBuffer ? new Uint8Array(buffer) : new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  const byteLength = Math.min(b.byteLength, MAX_BUFFER_DUMP_BYTES);
  let r = format4("\n=== buffer[%d] ===", byteLength);
  for (let j = 0; j < byteLength; j += 16) {
    r += `
${pad(j.toString(16), 8)}: `;
    let s = "";
    let k;
    for (k = 0; k < 16 && j + k < b.byteLength; k++) {
      const v = b[j + k];
      r += `${pad(v.toString(16), 2)} `;
      s += v > 31 && v < 255 ? String.fromCharCode(v) : "\xB7";
      if (k === 7) {
        r += " ";
      }
    }
    r += `${" ".repeat((17 - k) * 3)}${s}`;
  }
  r += "\n";
  if (byteLength !== b.byteLength) {
    r += format4("=== (truncated %d bytes) ===\n", b.byteLength - byteLength);
  }
  return r;
}
function format4(s, ...args) {
  const n = s.length;
  let arg;
  let argIndex = 0;
  let c2;
  let escaped = false;
  let i = 0;
  let leadingZero = false;
  let precision;
  let result = "";
  function nextArg() {
    return args[argIndex++];
  }
  function slurpNumber() {
    let digits = "";
    while (/\d/.test(s[i])) {
      digits += s[i++];
      c2 = s[i];
    }
    return digits.length > 0 ? Number.parseInt(digits, 10) : null;
  }
  for (; i < n; ++i) {
    c2 = s[i];
    if (escaped) {
      escaped = false;
      if (c2 === ".") {
        leadingZero = false;
        c2 = s[++i];
      } else if (c2 === "0" && s[i + 1] === ".") {
        leadingZero = true;
        i += 2;
        c2 = s[i];
      } else {
        leadingZero = true;
      }
      precision = slurpNumber();
      switch (c2) {
        case "a": {
          result += "0x" + pad(Number.parseInt(String(nextArg()), 10).toString(16), 8);
          break;
        }
        case "b": {
          result += Number.parseInt(String(nextArg()), 10).toString(2);
          break;
        }
        case "c": {
          arg = nextArg();
          result += typeof arg === "string" || arg instanceof String ? arg : String.fromCharCode(Number.parseInt(String(arg), 10));
          break;
        }
        case "d": {
          result += Number.parseInt(String(nextArg()), 10);
          break;
        }
        case "f": {
          const tmp = Number.parseFloat(String(nextArg())).toFixed(
            precision || 6
          );
          result += leadingZero ? tmp : tmp.replace(/^0/, "");
          break;
        }
        case "j": {
          result += JSON.stringify(nextArg());
          break;
        }
        case "o": {
          result += "0" + Number.parseInt(String(nextArg()), 10).toString(8);
          break;
        }
        case "s": {
          result += nextArg();
          break;
        }
        case "x": {
          result += "0x" + Number.parseInt(String(nextArg()), 10).toString(16);
          break;
        }
        case "X": {
          result += "0x" + Number.parseInt(String(nextArg()), 10).toString(16).toUpperCase();
          break;
        }
        default: {
          result += c2;
          break;
        }
      }
    } else if (c2 === "%") {
      escaped = true;
    } else {
      result += c2;
    }
  }
  return result;
}
function pad(v, width, pad2 = "0") {
  return v.length >= width ? v : Array.from({ length: width - v.length + 1 }).join(pad2) + v;
}
function padToWord$1(size) {
  return size + 7 & -8;
}
var ObjectSize = class {
  /**
   * Creates a new ObjectSize instance.
   *
   * @param dataByteLength - The number of bytes in the data section of the struct
   * @param pointerLength - The number of pointers in the pointer section of the struct
   */
  constructor(dataByteLength, pointerLength) {
    this.dataByteLength = dataByteLength;
    this.pointerLength = pointerLength;
  }
  toString() {
    return format4(
      "ObjectSize_dw:%d,pc:%d",
      getDataWordLength(this),
      this.pointerLength
    );
  }
};
function getByteLength(o) {
  return o.dataByteLength + o.pointerLength * 8;
}
function getDataWordLength(o) {
  return o.dataByteLength / 8;
}
function getWordLength(o) {
  return o.dataByteLength / 8 + o.pointerLength;
}
function padToWord(o) {
  return new ObjectSize(padToWord$1(o.dataByteLength), o.pointerLength);
}
var Orphan = class {
  /** If this member is not present then the orphan has already been adopted, or something went very wrong. */
  _capnp;
  byteOffset;
  segment;
  constructor(src) {
    const c2 = getContent(src);
    this.segment = c2.segment;
    this.byteOffset = c2.byteOffset;
    this._capnp = {};
    this._capnp.type = getTargetPointerType(src);
    switch (this._capnp.type) {
      case PointerType.STRUCT: {
        this._capnp.size = getTargetStructSize(src);
        break;
      }
      case PointerType.LIST: {
        this._capnp.length = getTargetListLength(src);
        this._capnp.elementSize = getTargetListElementSize(src);
        if (this._capnp.elementSize === ListElementSize.COMPOSITE) {
          this._capnp.size = getTargetCompositeListSize(src);
        }
        break;
      }
      case PointerType.OTHER: {
        this._capnp.capId = getCapabilityId(src);
        break;
      }
      default: {
        throw new Error(PTR_INVALID_POINTER_TYPE);
      }
    }
    erasePointer(src);
  }
  /**
   * Adopt (move) this orphan into the target pointer location. This will allocate far pointers in `dst` as needed.
   *
   * @param dst The destination pointer.
   */
  _moveTo(dst) {
    if (this._capnp === void 0) {
      throw new Error(format4(PTR_ALREADY_ADOPTED, this));
    }
    if (this.segment.message !== dst.segment.message) {
      throw new Error(format4(PTR_ADOPT_WRONG_MESSAGE, this, dst));
    }
    erase(dst);
    const res = initPointer(this.segment, this.byteOffset, dst);
    switch (this._capnp.type) {
      case PointerType.STRUCT: {
        setStructPointer(res.offsetWords, this._capnp.size, res.pointer);
        break;
      }
      case PointerType.LIST: {
        let { offsetWords } = res;
        if (this._capnp.elementSize === ListElementSize.COMPOSITE) {
          offsetWords--;
        }
        setListPointer(
          offsetWords,
          this._capnp.elementSize,
          this._capnp.length,
          res.pointer,
          this._capnp.size
        );
        break;
      }
      case PointerType.OTHER: {
        setInterfacePointer(this._capnp.capId, res.pointer);
        break;
      }
      /* istanbul ignore next */
      default: {
        throw new Error(PTR_INVALID_POINTER_TYPE);
      }
    }
    this._capnp = void 0;
  }
  dispose() {
    if (this._capnp === void 0) {
      return;
    }
    switch (this._capnp.type) {
      case PointerType.STRUCT: {
        this.segment.fillZeroWords(
          this.byteOffset,
          getWordLength(this._capnp.size)
        );
        break;
      }
      case PointerType.LIST: {
        const byteLength = getListByteLength(
          this._capnp.elementSize,
          this._capnp.length,
          this._capnp.size
        );
        this.segment.fillZeroWords(this.byteOffset, byteLength);
        break;
      }
    }
    this._capnp = void 0;
  }
  [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
    return format4(
      "Orphan_%d@%a,type:%s",
      this.segment.id,
      this.byteOffset,
      this._capnp && this._capnp.type
    );
  }
};
function adopt(src, p2) {
  src._moveTo(p2);
}
function disown(p2) {
  return new Orphan(p2);
}
function dump(p2) {
  return bufferToHex(p2.segment.buffer.slice(p2.byteOffset, p2.byteOffset + 8));
}
function getListByteLength(elementSize, length, compositeSize) {
  switch (elementSize) {
    case ListElementSize.BIT: {
      return padToWord$1(length + 7 >>> 3);
    }
    case ListElementSize.BYTE:
    case ListElementSize.BYTE_2:
    case ListElementSize.BYTE_4:
    case ListElementSize.BYTE_8:
    case ListElementSize.POINTER:
    case ListElementSize.VOID: {
      return padToWord$1(getListElementByteLength(elementSize) * length);
    }
    /* istanbul ignore next */
    case ListElementSize.COMPOSITE: {
      if (compositeSize === void 0) {
        throw new Error(format4(PTR_INVALID_LIST_SIZE, Number.NaN));
      }
      return length * padToWord$1(getByteLength(compositeSize));
    }
    /* istanbul ignore next */
    default: {
      throw new Error(PTR_INVALID_LIST_SIZE);
    }
  }
}
function getListElementByteLength(elementSize) {
  switch (elementSize) {
    /* istanbul ignore next */
    case ListElementSize.BIT: {
      return Number.NaN;
    }
    case ListElementSize.BYTE: {
      return 1;
    }
    case ListElementSize.BYTE_2: {
      return 2;
    }
    case ListElementSize.BYTE_4: {
      return 4;
    }
    case ListElementSize.BYTE_8:
    case ListElementSize.POINTER: {
      return 8;
    }
    /* istanbul ignore next */
    case ListElementSize.COMPOSITE: {
      return Number.NaN;
    }
    /* istanbul ignore next */
    case ListElementSize.VOID: {
      return 0;
    }
    /* istanbul ignore next */
    default: {
      throw new Error(format4(PTR_INVALID_LIST_SIZE, elementSize));
    }
  }
}
function add(offset, p2) {
  return new Pointer(p2.segment, p2.byteOffset + offset, p2._capnp.depthLimit);
}
function copyFrom(src, p2) {
  if (p2.segment === src.segment && p2.byteOffset === src.byteOffset) {
    return;
  }
  erase(p2);
  if (isNull(src)) return;
  switch (getTargetPointerType(src)) {
    case PointerType.STRUCT: {
      copyFromStruct(src, p2);
      break;
    }
    case PointerType.LIST: {
      copyFromList(src, p2);
      break;
    }
    case PointerType.OTHER: {
      copyFromInterface(src, p2);
      break;
    }
    /* istanbul ignore next */
    default: {
      throw new Error(
        format4(PTR_INVALID_POINTER_TYPE, getTargetPointerType(p2))
      );
    }
  }
}
function erase(p2) {
  if (isNull(p2)) return;
  let c2;
  switch (getTargetPointerType(p2)) {
    case PointerType.STRUCT: {
      const size = getTargetStructSize(p2);
      c2 = getContent(p2);
      c2.segment.fillZeroWords(c2.byteOffset, size.dataByteLength / 8);
      for (let i = 0; i < size.pointerLength; i++) {
        erase(add(i * 8, c2));
      }
      break;
    }
    case PointerType.LIST: {
      const elementSize = getTargetListElementSize(p2);
      const length = getTargetListLength(p2);
      let contentWords = padToWord$1(
        length * getListElementByteLength(elementSize)
      );
      c2 = getContent(p2);
      if (elementSize === ListElementSize.POINTER) {
        for (let i = 0; i < length; i++) {
          erase(
            new Pointer(
              c2.segment,
              c2.byteOffset + i * 8,
              p2._capnp.depthLimit - 1
            )
          );
        }
        break;
      } else if (elementSize === ListElementSize.COMPOSITE) {
        const tag = add(-8, c2);
        const compositeSize = getStructSize(tag);
        const compositeByteLength = getByteLength(compositeSize);
        contentWords = getOffsetWords(tag);
        c2.segment.setWordZero(c2.byteOffset - 8);
        for (let i = 0; i < length; i++) {
          for (let j = 0; j < compositeSize.pointerLength; j++) {
            erase(
              new Pointer(
                c2.segment,
                c2.byteOffset + i * compositeByteLength + j * 8,
                p2._capnp.depthLimit - 1
              )
            );
          }
        }
      }
      c2.segment.fillZeroWords(c2.byteOffset, contentWords);
      break;
    }
    case PointerType.OTHER: {
      break;
    }
    default: {
      throw new Error(
        format4(PTR_INVALID_POINTER_TYPE, getTargetPointerType(p2))
      );
    }
  }
  erasePointer(p2);
}
function erasePointer(p2) {
  if (getPointerType(p2) === PointerType.FAR) {
    const landingPad = followFar(p2);
    if (isDoubleFar(p2)) {
      landingPad.segment.setWordZero(landingPad.byteOffset + 8);
    }
    landingPad.segment.setWordZero(landingPad.byteOffset);
  }
  p2.segment.setWordZero(p2.byteOffset);
}
function followFar(p2) {
  const targetSegment = p2.segment.message.getSegment(
    p2.segment.getUint32(p2.byteOffset + 4)
  );
  const targetWordOffset = p2.segment.getUint32(p2.byteOffset) >>> 3;
  return new Pointer(
    targetSegment,
    targetWordOffset * 8,
    p2._capnp.depthLimit - 1
  );
}
function followFars(p2) {
  if (getPointerType(p2) === PointerType.FAR) {
    const landingPad = followFar(p2);
    if (isDoubleFar(p2)) {
      landingPad.byteOffset += 8;
    }
    return landingPad;
  }
  return p2;
}
function getCapabilityId(p2) {
  return p2.segment.getUint32(p2.byteOffset + 4);
}
function isCompositeList(p2) {
  return getTargetPointerType(p2) === PointerType.LIST && getTargetListElementSize(p2) === ListElementSize.COMPOSITE;
}
function getContent(p2, ignoreCompositeIndex) {
  let c2;
  if (isDoubleFar(p2)) {
    const landingPad = followFar(p2);
    c2 = new Pointer(
      p2.segment.message.getSegment(getFarSegmentId(landingPad)),
      getOffsetWords(landingPad) * 8
    );
  } else {
    const target = followFars(p2);
    c2 = new Pointer(
      target.segment,
      target.byteOffset + 8 + getOffsetWords(target) * 8
    );
  }
  if (isCompositeList(p2)) {
    c2.byteOffset += 8;
  }
  if (!ignoreCompositeIndex && p2._capnp.compositeIndex !== void 0) {
    c2.byteOffset -= 8;
    c2.byteOffset += 8 + p2._capnp.compositeIndex * getByteLength(padToWord(getStructSize(c2)));
  }
  return c2;
}
function getFarSegmentId(p2) {
  return p2.segment.getUint32(p2.byteOffset + 4);
}
function getListElementSize(p2) {
  return p2.segment.getUint32(p2.byteOffset + 4) & LIST_SIZE_MASK;
}
function getListLength(p2) {
  return p2.segment.getUint32(p2.byteOffset + 4) >>> 3;
}
function getOffsetWords(p2) {
  const o = p2.segment.getInt32(p2.byteOffset);
  return o & 2 ? o >> 3 : o >> 2;
}
function getPointerType(p2) {
  return p2.segment.getUint32(p2.byteOffset) & POINTER_TYPE_MASK;
}
function getStructDataWords(p2) {
  return p2.segment.getUint16(p2.byteOffset + 4);
}
function getStructPointerLength(p2) {
  return p2.segment.getUint16(p2.byteOffset + 6);
}
function getStructSize(p2) {
  return new ObjectSize(getStructDataWords(p2) * 8, getStructPointerLength(p2));
}
function getTargetCompositeListTag(p2) {
  const c2 = getContent(p2);
  c2.byteOffset -= 8;
  return c2;
}
function getTargetCompositeListSize(p2) {
  return getStructSize(getTargetCompositeListTag(p2));
}
function getTargetListElementSize(p2) {
  return getListElementSize(followFars(p2));
}
function getTargetListLength(p2) {
  const t = followFars(p2);
  if (getListElementSize(t) === ListElementSize.COMPOSITE) {
    return getOffsetWords(getTargetCompositeListTag(p2));
  }
  return getListLength(t);
}
function getTargetPointerType(p2) {
  const t = getPointerType(followFars(p2));
  if (t === PointerType.FAR) {
    throw new Error(format4(PTR_INVALID_FAR_TARGET, p2));
  }
  return t;
}
function getTargetStructSize(p2) {
  return getStructSize(followFars(p2));
}
function initPointer(contentSegment, contentOffset, p2) {
  if (p2.segment !== contentSegment) {
    if (!contentSegment.hasCapacity(8)) {
      const landingPad2 = p2.segment.allocate(16);
      setFarPointer(true, landingPad2.byteOffset / 8, landingPad2.segment.id, p2);
      setFarPointer(false, contentOffset / 8, contentSegment.id, landingPad2);
      landingPad2.byteOffset += 8;
      return new PointerAllocationResult(landingPad2, 0);
    }
    const landingPad = contentSegment.allocate(8);
    if (landingPad.segment.id !== contentSegment.id) {
      throw new Error(INVARIANT_UNREACHABLE_CODE);
    }
    setFarPointer(false, landingPad.byteOffset / 8, landingPad.segment.id, p2);
    return new PointerAllocationResult(
      landingPad,
      (contentOffset - landingPad.byteOffset - 8) / 8
    );
  }
  return new PointerAllocationResult(p2, (contentOffset - p2.byteOffset - 8) / 8);
}
function isDoubleFar(p2) {
  return getPointerType(p2) === PointerType.FAR && (p2.segment.getUint32(p2.byteOffset) & POINTER_DOUBLE_FAR_MASK) !== 0;
}
function isNull(p2) {
  return p2.segment.isWordZero(p2.byteOffset);
}
function relocateTo(dst, src) {
  const t = followFars(src);
  const lo = t.segment.getUint8(t.byteOffset) & 3;
  const hi = t.segment.getUint32(t.byteOffset + 4);
  erase(dst);
  const res = initPointer(
    t.segment,
    t.byteOffset + 8 + getOffsetWords(t) * 8,
    dst
  );
  res.pointer.segment.setUint32(
    res.pointer.byteOffset,
    lo | res.offsetWords << 2
  );
  res.pointer.segment.setUint32(res.pointer.byteOffset + 4, hi);
  erasePointer(src);
}
function setFarPointer(doubleFar, offsetWords, segmentId, p2) {
  const A = PointerType.FAR;
  const B = doubleFar ? 1 : 0;
  const C = offsetWords;
  const D = segmentId;
  p2.segment.setUint32(p2.byteOffset, A | B << 2 | C << 3);
  p2.segment.setUint32(p2.byteOffset + 4, D);
}
function setInterfacePointer(capId, p2) {
  p2.segment.setUint32(p2.byteOffset, PointerType.OTHER);
  p2.segment.setUint32(p2.byteOffset + 4, capId);
}
function getInterfacePointer(p2) {
  return p2.segment.getUint32(p2.byteOffset + 4);
}
function setListPointer(offsetWords, size, length, p2, compositeSize) {
  const A = PointerType.LIST;
  const B = offsetWords;
  const C = size;
  let D = length;
  if (size === ListElementSize.COMPOSITE) {
    if (compositeSize === void 0) {
      throw new TypeError(TYPE_COMPOSITE_SIZE_UNDEFINED);
    }
    D *= getWordLength(compositeSize);
  }
  p2.segment.setUint32(p2.byteOffset, A | B << 2);
  p2.segment.setUint32(p2.byteOffset + 4, C | D << 3);
}
function setStructPointer(offsetWords, size, p2) {
  const A = PointerType.STRUCT;
  const B = offsetWords;
  const C = getDataWordLength(size);
  const D = size.pointerLength;
  p2.segment.setUint32(p2.byteOffset, A | B << 2);
  p2.segment.setUint16(p2.byteOffset + 4, C);
  p2.segment.setUint16(p2.byteOffset + 6, D);
}
function validate(pointerType, p2, elementSize) {
  if (isNull(p2)) {
    return;
  }
  const t = followFars(p2);
  const A = t.segment.getUint32(t.byteOffset) & POINTER_TYPE_MASK;
  if (A !== pointerType) {
    throw new Error(format4(PTR_WRONG_POINTER_TYPE, p2, pointerType));
  }
  if (elementSize !== void 0) {
    const C = t.segment.getUint32(t.byteOffset + 4) & LIST_SIZE_MASK;
    if (C !== elementSize) {
      throw new Error(
        format4(PTR_WRONG_LIST_TYPE, p2, ListElementSize[elementSize])
      );
    }
  }
}
function copyFromInterface(src, dst) {
  const srcCapId = getInterfacePointer(src);
  if (srcCapId < 0) {
    return;
  }
  const srcCapTable = src.segment.message._capnp.capTable;
  if (!srcCapTable) {
    return;
  }
  const client = srcCapTable[srcCapId];
  if (!client) {
    return;
  }
  const dstCapId = dst.segment.message.addCap(client);
  setInterfacePointer(dstCapId, dst);
}
function copyFromList(src, dst) {
  if (dst._capnp.depthLimit <= 0) {
    throw new Error(PTR_DEPTH_LIMIT_EXCEEDED);
  }
  const srcContent = getContent(src);
  const srcElementSize = getTargetListElementSize(src);
  const srcLength = getTargetListLength(src);
  let srcCompositeSize;
  let srcStructByteLength;
  let dstContent;
  if (srcElementSize === ListElementSize.POINTER) {
    dstContent = dst.segment.allocate(srcLength << 3);
    for (let i = 0; i < srcLength; i++) {
      const srcPtr = new Pointer(
        srcContent.segment,
        srcContent.byteOffset + (i << 3),
        src._capnp.depthLimit - 1
      );
      const dstPtr = new Pointer(
        dstContent.segment,
        dstContent.byteOffset + (i << 3),
        dst._capnp.depthLimit - 1
      );
      copyFrom(srcPtr, dstPtr);
    }
  } else if (srcElementSize === ListElementSize.COMPOSITE) {
    srcCompositeSize = padToWord(getTargetCompositeListSize(src));
    srcStructByteLength = getByteLength(srcCompositeSize);
    dstContent = dst.segment.allocate(
      getByteLength(srcCompositeSize) * srcLength + 8
    );
    dstContent.segment.copyWord(
      dstContent.byteOffset,
      srcContent.segment,
      srcContent.byteOffset - 8
    );
    if (srcCompositeSize.dataByteLength > 0) {
      const wordLength = getWordLength(srcCompositeSize) * srcLength;
      dstContent.segment.copyWords(
        dstContent.byteOffset + 8,
        srcContent.segment,
        srcContent.byteOffset,
        wordLength
      );
    }
    for (let i = 0; i < srcLength; i++) {
      for (let j = 0; j < srcCompositeSize.pointerLength; j++) {
        const offset = i * srcStructByteLength + srcCompositeSize.dataByteLength + (j << 3);
        const srcPtr = new Pointer(
          srcContent.segment,
          srcContent.byteOffset + offset,
          src._capnp.depthLimit - 1
        );
        const dstPtr = new Pointer(
          dstContent.segment,
          dstContent.byteOffset + offset + 8,
          dst._capnp.depthLimit - 1
        );
        copyFrom(srcPtr, dstPtr);
      }
    }
  } else {
    const byteLength = padToWord$1(
      srcElementSize === ListElementSize.BIT ? srcLength + 7 >>> 3 : getListElementByteLength(srcElementSize) * srcLength
    );
    const wordLength = byteLength >>> 3;
    dstContent = dst.segment.allocate(byteLength);
    dstContent.segment.copyWords(
      dstContent.byteOffset,
      srcContent.segment,
      srcContent.byteOffset,
      wordLength
    );
  }
  const res = initPointer(dstContent.segment, dstContent.byteOffset, dst);
  setListPointer(
    res.offsetWords,
    srcElementSize,
    srcLength,
    res.pointer,
    srcCompositeSize
  );
}
function copyFromStruct(src, dst) {
  if (dst._capnp.depthLimit <= 0) {
    throw new Error(PTR_DEPTH_LIMIT_EXCEEDED);
  }
  const srcContent = getContent(src);
  const srcSize = getTargetStructSize(src);
  const srcDataWordLength = getDataWordLength(srcSize);
  const dstContent = dst.segment.allocate(getByteLength(srcSize));
  dstContent.segment.copyWords(
    dstContent.byteOffset,
    srcContent.segment,
    srcContent.byteOffset,
    srcDataWordLength
  );
  for (let i = 0; i < srcSize.pointerLength; i++) {
    const offset = srcSize.dataByteLength + i * 8;
    const srcPtr = new Pointer(
      srcContent.segment,
      srcContent.byteOffset + offset,
      src._capnp.depthLimit - 1
    );
    const dstPtr = new Pointer(
      dstContent.segment,
      dstContent.byteOffset + offset,
      dst._capnp.depthLimit - 1
    );
    copyFrom(srcPtr, dstPtr);
  }
  if (dst._capnp.compositeList) {
    return;
  }
  const res = initPointer(dstContent.segment, dstContent.byteOffset, dst);
  setStructPointer(res.offsetWords, srcSize, res.pointer);
}
function trackPointerAllocation(message, p2) {
  message._capnp.traversalLimit -= 8;
  if (message._capnp.traversalLimit <= 0) {
    throw new Error(format4(PTR_TRAVERSAL_LIMIT_EXCEEDED, p2));
  }
}
var PointerAllocationResult = class {
  constructor(pointer, offsetWords) {
    this.pointer = pointer;
    this.offsetWords = offsetWords;
  }
};
var PointerType = /* @__PURE__ */ ((PointerType2) => {
  PointerType2[PointerType2["STRUCT"] = 0] = "STRUCT";
  PointerType2[PointerType2["LIST"] = 1] = "LIST";
  PointerType2[PointerType2["FAR"] = 2] = "FAR";
  PointerType2[PointerType2["OTHER"] = 3] = "OTHER";
  return PointerType2;
})(PointerType || {});
var Pointer = class {
  static _capnp = {
    displayName: "Pointer"
  };
  _capnp;
  /** Offset, in bytes, from the start of the segment to the beginning of this pointer. */
  byteOffset;
  /**
   * The starting segment for this pointer's data. In the case of a far pointer, the actual content this pointer is
   * referencing will be in another segment within the same message.
   */
  segment;
  constructor(segment, byteOffset, depthLimit = MAX_DEPTH) {
    this._capnp = { compositeList: false, depthLimit };
    this.segment = segment;
    this.byteOffset = byteOffset;
    if (depthLimit < 1) {
      throw new Error(format4(PTR_DEPTH_LIMIT_EXCEEDED, this));
    }
    trackPointerAllocation(segment.message, this);
    if (byteOffset < 0 || byteOffset > segment.byteLength) {
      throw new Error(format4(PTR_OFFSET_OUT_OF_BOUNDS, byteOffset));
    }
  }
  [Symbol.toStringTag]() {
    return format4("Pointer_%d", this.segment.id);
  }
  toString() {
    return format4("->%d@%a%s", this.segment.id, this.byteOffset, dump(this));
  }
};
var List = class _List extends Pointer {
  static _capnp = {
    displayName: "List<Generic>",
    size: ListElementSize.VOID
  };
  constructor(segment, byteOffset, depthLimit) {
    super(segment, byteOffset, depthLimit);
    return new Proxy(this, _List.#proxyHandler);
  }
  static #proxyHandler = {
    get(target, prop, receiver) {
      const val = Reflect.get(target, prop, receiver);
      if (val !== void 0) {
        return val;
      }
      if (typeof prop === "string") {
        return target.get(+prop);
      }
    }
  };
  get length() {
    return getTargetListLength(this);
  }
  toArray() {
    const { length } = this;
    const res = Array.from({ length });
    for (let i = 0; i < length; i++) {
      res[i] = this.at(i);
    }
    return res;
  }
  get(_index) {
    throw new TypeError("Cannot get from a generic list.");
  }
  set(_index, _value) {
    throw new TypeError("Cannot set on a generic list.");
  }
  at(index) {
    return this.get(index < 0 ? this.length + index : index);
  }
  concat(other) {
    const { length } = this;
    const otherLength = other.length;
    const res = Array.from({ length: length + otherLength });
    for (let i = 0; i < length; i++) res[i] = this.at(i);
    for (let i = 0; i < otherLength; i++) res[i + length] = other.at(i);
    return res;
  }
  some(cb, _this) {
    for (let i = 0; i < this.length; i++) {
      if (cb.call(_this, this.at(i), i, this)) {
        return true;
      }
    }
    return false;
  }
  filter(cb, _this) {
    const res = [];
    for (let i = 0; i < this.length; i++) {
      const value = this.at(i);
      if (cb.call(_this, value, i, this)) {
        res.push(value);
      }
    }
    return res;
  }
  find(cb, _this) {
    for (let i = 0; i < this.length; i++) {
      const value = this.at(i);
      if (cb.call(_this, value, i, this)) {
        return value;
      }
    }
    return void 0;
  }
  findIndex(cb, _this) {
    for (let i = 0; i < this.length; i++) {
      const value = this.at(i);
      if (cb.call(_this, value, i, this)) {
        return i;
      }
    }
    return -1;
  }
  forEach(cb, _this) {
    for (let i = 0; i < this.length; i++) {
      cb.call(_this, this.at(i), i, this);
    }
  }
  map(cb, _this) {
    const { length } = this;
    const res = Array.from({ length });
    for (let i = 0; i < length; i++) {
      res[i] = cb.call(_this, this.at(i), i, this);
    }
    return res;
  }
  flatMap(cb, _this) {
    const res = [];
    for (let i = 0; i < this.length; i++) {
      const r = cb.call(_this, this.at(i), i, this);
      res.push(...Array.isArray(r) ? r : [r]);
    }
    return res;
  }
  every(cb, _this) {
    for (let i = 0; i < this.length; i++) {
      if (!cb.call(_this, this.at(i), i, this)) {
        return false;
      }
    }
    return true;
  }
  reduce(cb, initialValue) {
    let i = 0;
    let res;
    if (initialValue === void 0) {
      res = this.at(0);
      i++;
    } else {
      res = initialValue;
    }
    for (; i < this.length; i++) {
      res = cb(res, this.at(i), i, this);
    }
    return res;
  }
  reduceRight(cb, initialValue) {
    let i = this.length - 1;
    let res;
    if (initialValue === void 0) {
      res = this.at(i);
      i--;
    } else {
      res = initialValue;
    }
    for (; i >= 0; i--) {
      res = cb(res, this.at(i), i, this);
    }
    return res;
  }
  slice(start = 0, end) {
    const length = end ? Math.min(this.length, end) : this.length;
    const res = Array.from({ length: length - start });
    for (let i = start; i < length; i++) {
      res[i] = this.at(i);
    }
    return res;
  }
  join(separator) {
    return this.toArray().join(separator);
  }
  toReversed() {
    return this.toArray().reverse();
  }
  toSorted(compareFn) {
    return this.toArray().sort(compareFn);
  }
  toSpliced(start, deleteCount, ...items) {
    return this.toArray().splice(start, deleteCount, ...items);
  }
  fill(value, start, end) {
    const { length } = this;
    const s = Math.max(start ?? 0, 0);
    const e = Math.min(end ?? length, length);
    for (let i = s; i < e; i++) {
      this.set(i, value);
    }
    return this;
  }
  copyWithin(target, start, end) {
    const { length } = this;
    const e = end ?? length;
    const s = start < 0 ? Math.max(length + start, 0) : start;
    const t = target < 0 ? Math.max(length + target, 0) : target;
    const len = Math.min(e - s, length - t);
    for (let i = 0; i < len; i++) {
      this.set(t + i, this.at(s + i));
    }
    return this;
  }
  keys() {
    return Array.from({ length: this.length }, (_, i) => i)[Symbol.iterator]();
  }
  values() {
    return this.toArray().values();
  }
  entries() {
    return this.toArray().entries();
  }
  flat(depth) {
    return this.toArray().flat(depth);
  }
  with(index, value) {
    return this.toArray().with(index, value);
  }
  includes(_searchElement, _fromIndex) {
    throw new Error(LIST_NO_SEARCH);
  }
  findLast(_cb, _thisArg) {
    throw new Error(LIST_NO_SEARCH);
  }
  findLastIndex(_cb, _t) {
    throw new Error(LIST_NO_SEARCH);
  }
  indexOf(_searchElement, _fromIndex) {
    throw new Error(LIST_NO_SEARCH);
  }
  lastIndexOf(_searchElement, _fromIndex) {
    throw new Error(LIST_NO_SEARCH);
  }
  pop() {
    throw new Error(LIST_NO_MUTABLE);
  }
  push(..._items) {
    throw new Error(LIST_NO_MUTABLE);
  }
  reverse() {
    throw new Error(LIST_NO_MUTABLE);
  }
  shift() {
    throw new Error(LIST_NO_MUTABLE);
  }
  unshift(..._items) {
    throw new Error(LIST_NO_MUTABLE);
  }
  splice(_start, _deleteCount, ..._rest) {
    throw new Error(LIST_NO_MUTABLE);
  }
  sort(_fn) {
    throw new Error(LIST_NO_MUTABLE);
  }
  get [Symbol.unscopables]() {
    return Array.prototype[Symbol.unscopables];
  }
  [Symbol.iterator]() {
    return this.values();
  }
  toJSON() {
    return this.toArray();
  }
  toString() {
    return this.join(",");
  }
  toLocaleString(_locales, _options) {
    return this.toString();
  }
  [Symbol.toStringTag]() {
    return "[object Array]";
  }
  static [Symbol.toStringTag]() {
    return this._capnp.displayName;
  }
};
function initList$1(elementSize, length, list, compositeSize) {
  let c2;
  switch (elementSize) {
    case ListElementSize.BIT: {
      c2 = list.segment.allocate(Math.ceil(length / 8));
      break;
    }
    case ListElementSize.BYTE:
    case ListElementSize.BYTE_2:
    case ListElementSize.BYTE_4:
    case ListElementSize.BYTE_8:
    case ListElementSize.POINTER: {
      c2 = list.segment.allocate(length * getListElementByteLength(elementSize));
      break;
    }
    case ListElementSize.COMPOSITE: {
      if (compositeSize === void 0) {
        throw new Error(format4(PTR_COMPOSITE_SIZE_UNDEFINED));
      }
      compositeSize = padToWord(compositeSize);
      const byteLength = getByteLength(compositeSize) * length;
      c2 = list.segment.allocate(byteLength + 8);
      setStructPointer(length, compositeSize, c2);
      break;
    }
    case ListElementSize.VOID: {
      setListPointer(0, elementSize, length, list);
      return;
    }
    default: {
      throw new Error(format4(PTR_INVALID_LIST_SIZE, elementSize));
    }
  }
  const res = initPointer(c2.segment, c2.byteOffset, list);
  setListPointer(
    res.offsetWords,
    elementSize,
    length,
    res.pointer,
    compositeSize
  );
}
var Data = class extends List {
  static fromPointer(pointer) {
    validate(PointerType.LIST, pointer, ListElementSize.BYTE);
    return this._fromPointerUnchecked(pointer);
  }
  static _fromPointerUnchecked(pointer) {
    return new this(
      pointer.segment,
      pointer.byteOffset,
      pointer._capnp.depthLimit
    );
  }
  /**
   * Copy the contents of `src` into this Data pointer. If `src` is smaller than the length of this pointer then the
   * remaining bytes will be zeroed out. Extra bytes in `src` are ignored.
   *
   * @param src The source buffer.
   */
  // TODO: Would be nice to have a way to zero-copy a buffer by allocating a new segment into the message with that
  // buffer data.
  copyBuffer(src) {
    const c2 = getContent(this);
    const dstLength = this.length;
    const srcLength = src.byteLength;
    const i = src instanceof ArrayBuffer ? new Uint8Array(src) : new Uint8Array(
      src.buffer,
      src.byteOffset,
      Math.min(dstLength, srcLength)
    );
    const o = new Uint8Array(c2.segment.buffer, c2.byteOffset, this.length);
    o.set(i);
    if (dstLength > srcLength) {
      o.fill(0, srcLength, dstLength);
    }
  }
  /**
   * Read a byte from the specified offset.
   *
   * @param byteOffset The byte offset to read.
   * @returns The byte value.
   */
  get(byteOffset) {
    const c2 = getContent(this);
    return c2.segment.getUint8(c2.byteOffset + byteOffset);
  }
  /**
   * Write a byte at the specified offset.
   *
   * @param byteOffset The byte offset to set.
   * @param value The byte value to set.
   */
  set(byteOffset, value) {
    const c2 = getContent(this);
    c2.segment.setUint8(c2.byteOffset + byteOffset, value);
  }
  /**
   * Creates a **copy** of the underlying buffer data and returns it as an ArrayBuffer.
   *
   * To obtain a reference to the underlying buffer instead, use `toUint8Array()` or `toDataView()`.
   *
   * @returns A copy of this data buffer.
   */
  toArrayBuffer() {
    const c2 = getContent(this);
    return c2.segment.buffer.slice(c2.byteOffset, c2.byteOffset + this.length);
  }
  /**
   * Convert this Data pointer to a DataView representing the pointer's contents.
   *
   * WARNING: The DataView references memory from a message segment, so do not venture outside the bounds of the
   * DataView or else BAD THINGS.
   *
   * @returns A live reference to the underlying buffer.
   */
  toDataView() {
    const c2 = getContent(this);
    return new DataView(c2.segment.buffer, c2.byteOffset, this.length);
  }
  [Symbol.toStringTag]() {
    return `Data_${super.toString()}`;
  }
  /**
   * Convert this Data pointer to a Uint8Array representing the pointer's contents.
   *
   * WARNING: The Uint8Array references memory from a message segment, so do not venture outside the bounds of the
   * Uint8Array or else BAD THINGS.
   *
   * @returns A live reference to the underlying buffer.
   */
  toUint8Array() {
    const c2 = getContent(this);
    return new Uint8Array(c2.segment.buffer, c2.byteOffset, this.length);
  }
};
var textEncoder = new TextEncoder();
var textDecoder = new TextDecoder();
var Text = class extends List {
  static fromPointer(pointer) {
    validate(PointerType.LIST, pointer, ListElementSize.BYTE);
    return textFromPointerUnchecked(pointer);
  }
  /**
   * Read a utf-8 encoded string value from this pointer.
   *
   * @param index The index at which to start reading; defaults to zero.
   * @returns The string value.
   */
  get(index = 0) {
    if (isNull(this)) {
      return "";
    }
    const c2 = getContent(this);
    return textDecoder.decode(
      new Uint8Array(
        c2.segment.buffer,
        c2.byteOffset + index,
        this.length - index
      )
    );
  }
  /**
   * Get the number of utf-8 encoded bytes in this text. This does **not** include the NUL byte.
   *
   * @returns The number of bytes allocated for the text.
   */
  get length() {
    return super.length - 1;
  }
  /**
   * Write a utf-8 encoded string value starting at the specified index.
   *
   * @param index The index at which to start copying the string. Note that if this is not zero the bytes
   * before `index` will be left as-is. All bytes after `index` will be overwritten.
   * @param value The string value to set.
   */
  set(index, value) {
    const src = textEncoder.encode(value);
    const dstLength = src.byteLength + index;
    let c2;
    let original;
    if (!isNull(this)) {
      c2 = getContent(this);
      const originalLength = Math.min(this.length, index);
      original = new Uint8Array(
        c2.segment.buffer.slice(c2.byteOffset, c2.byteOffset + originalLength)
      );
      erase(this);
    }
    initList$1(ListElementSize.BYTE, dstLength + 1, this);
    c2 = getContent(this);
    const dst = new Uint8Array(c2.segment.buffer, c2.byteOffset, dstLength);
    if (original) {
      dst.set(original);
    }
    dst.set(src, index);
  }
  toString() {
    return this.get();
  }
  toJSON() {
    return this.get();
  }
  [Symbol.toPrimitive]() {
    return this.get();
  }
  [Symbol.toStringTag]() {
    return `Text_${super.toString()}`;
  }
};
function textFromPointerUnchecked(pointer) {
  return new Text(
    pointer.segment,
    pointer.byteOffset,
    pointer._capnp.depthLimit
  );
}
var Struct = class extends Pointer {
  static _capnp = {
    displayName: "Struct"
  };
  /**
   * Create a new pointer to a struct.
   *
   * @param segment The segment the pointer resides in.
   * @param byteOffset The offset from the beginning of the segment to the beginning of the pointer data.
   * @param depthLimit The nesting depth limit for this object.
   * @param compositeIndex If set, then this pointer is actually a reference to a composite list
   * (`this._getPointerTargetType() === PointerType.LIST`), and this number is used as the index of the struct within
   * the list. It is not valid to call `initStruct()` on a composite struct – the struct contents are initialized when
   * the list pointer is initialized.
   */
  constructor(segment, byteOffset, depthLimit = MAX_DEPTH, compositeIndex) {
    super(segment, byteOffset, depthLimit);
    this._capnp.compositeIndex = compositeIndex;
    this._capnp.compositeList = compositeIndex !== void 0;
  }
  static [Symbol.toStringTag]() {
    return this._capnp.displayName;
  }
  [Symbol.toStringTag]() {
    return `Struct_${super.toString()}${this._capnp.compositeIndex === void 0 ? "" : `,ci:${this._capnp.compositeIndex}`} > ${getContent(this).toString()}`;
  }
};
var AnyStruct = class extends Struct {
  static _capnp = {
    displayName: "AnyStruct",
    id: "0",
    size: new ObjectSize(0, 0)
  };
};
var FixedAnswer = class {
  struct() {
    return Promise.resolve(this.structSync());
  }
};
var ErrorAnswer = class extends FixedAnswer {
  constructor(err) {
    super();
    this.err = err;
  }
  structSync() {
    throw this.err;
  }
  pipelineCall(_transform3, _call) {
    return this;
  }
  pipelineClose(_transform3) {
    throw this.err;
  }
};
var ErrorClient = class {
  constructor(err) {
    this.err = err;
  }
  call(_call) {
    return new ErrorAnswer(this.err);
  }
  close() {
    throw this.err;
  }
};
function clientOrNull(client) {
  return client ?? new ErrorClient(new Error(RPC_NULL_CLIENT));
}
var TMP_WORD = new DataView(new ArrayBuffer(8));
function initStruct(size, s) {
  if (s._capnp.compositeIndex !== void 0) {
    throw new Error(format4(PTR_INIT_COMPOSITE_STRUCT, s));
  }
  erase(s);
  const c2 = s.segment.allocate(getByteLength(size));
  const res = initPointer(c2.segment, c2.byteOffset, s);
  setStructPointer(res.offsetWords, size, res.pointer);
}
function initStructAt(index, StructClass, p2) {
  const s = getPointerAs(index, StructClass, p2);
  initStruct(StructClass._capnp.size, s);
  return s;
}
function checkPointerBounds(index, s) {
  const { pointerLength } = getSize(s);
  if (index < 0 || index >= pointerLength) {
    throw new Error(
      format4(PTR_STRUCT_POINTER_OUT_OF_BOUNDS, s, index, pointerLength)
    );
  }
}
function getInterfaceClientOrNullAt(index, s) {
  return getInterfaceClientOrNull(getPointer(index, s));
}
function getInterfaceClientOrNull(p2) {
  let client = null;
  const capId = getInterfacePointer(p2);
  const { capTable } = p2.segment.message._capnp;
  if (capTable && capId >= 0 && capId < capTable.length) {
    client = capTable[capId];
  }
  return clientOrNull(client);
}
function resize(dstSize, s) {
  const srcSize = getSize(s);
  const srcContent = getContent(s);
  const dstContent = s.segment.allocate(getByteLength(dstSize));
  dstContent.segment.copyWords(
    dstContent.byteOffset,
    srcContent.segment,
    srcContent.byteOffset,
    Math.min(getDataWordLength(srcSize), getDataWordLength(dstSize))
  );
  const res = initPointer(dstContent.segment, dstContent.byteOffset, s);
  setStructPointer(res.offsetWords, dstSize, res.pointer);
  for (let i = 0; i < Math.min(srcSize.pointerLength, dstSize.pointerLength); i++) {
    const srcPtr = new Pointer(
      srcContent.segment,
      srcContent.byteOffset + srcSize.dataByteLength + i * 8
    );
    if (isNull(srcPtr)) {
      continue;
    }
    const srcPtrTarget = followFars(srcPtr);
    const srcPtrContent = getContent(srcPtr);
    const dstPtr = new Pointer(
      dstContent.segment,
      dstContent.byteOffset + dstSize.dataByteLength + i * 8
    );
    if (getTargetPointerType(srcPtr) === PointerType.LIST && getTargetListElementSize(srcPtr) === ListElementSize.COMPOSITE) {
      srcPtrContent.byteOffset -= 8;
    }
    const r = initPointer(
      srcPtrContent.segment,
      srcPtrContent.byteOffset,
      dstPtr
    );
    const a = srcPtrTarget.segment.getUint8(srcPtrTarget.byteOffset) & 3;
    const b = srcPtrTarget.segment.getUint32(srcPtrTarget.byteOffset + 4);
    r.pointer.segment.setUint32(r.pointer.byteOffset, a | r.offsetWords << 2);
    r.pointer.segment.setUint32(r.pointer.byteOffset + 4, b);
  }
  srcContent.segment.fillZeroWords(
    srcContent.byteOffset,
    getWordLength(srcSize)
  );
}
function getAs(StructClass, s) {
  return new StructClass(
    s.segment,
    s.byteOffset,
    s._capnp.depthLimit,
    s._capnp.compositeIndex
  );
}
function getBit(bitOffset, s, defaultMask) {
  const byteOffset = Math.floor(bitOffset / 8);
  const bitMask = 1 << bitOffset % 8;
  checkDataBounds(byteOffset, 1, s);
  const ds = getDataSection(s);
  const v = ds.segment.getUint8(ds.byteOffset + byteOffset);
  if (defaultMask === void 0) {
    return (v & bitMask) !== 0;
  }
  const defaultValue = defaultMask.getUint8(0);
  return ((v ^ defaultValue) & bitMask) !== 0;
}
function getData(index, s, defaultValue) {
  checkPointerBounds(index, s);
  const ps = getPointerSection(s);
  ps.byteOffset += index * 8;
  const l = new Data(ps.segment, ps.byteOffset, s._capnp.depthLimit - 1);
  if (isNull(l)) {
    if (defaultValue) {
      copyFrom(defaultValue, l);
    } else {
      initList$1(ListElementSize.BYTE, 0, l);
    }
  }
  return l;
}
function getDataSection(s) {
  return getContent(s);
}
function getFloat32(byteOffset, s, defaultMask) {
  checkDataBounds(byteOffset, 4, s);
  const ds = getDataSection(s);
  if (defaultMask === void 0) {
    return ds.segment.getFloat32(ds.byteOffset + byteOffset);
  }
  const v = ds.segment.getUint32(ds.byteOffset + byteOffset) ^ defaultMask.getUint32(0, true);
  TMP_WORD.setUint32(0, v, NATIVE_LITTLE_ENDIAN);
  return TMP_WORD.getFloat32(0, NATIVE_LITTLE_ENDIAN);
}
function getFloat64(byteOffset, s, defaultMask) {
  checkDataBounds(byteOffset, 8, s);
  const ds = getDataSection(s);
  if (defaultMask !== void 0) {
    const lo = ds.segment.getUint32(ds.byteOffset + byteOffset) ^ defaultMask.getUint32(0, true);
    const hi = ds.segment.getUint32(ds.byteOffset + byteOffset + 4) ^ defaultMask.getUint32(4, true);
    TMP_WORD.setUint32(0, lo, NATIVE_LITTLE_ENDIAN);
    TMP_WORD.setUint32(4, hi, NATIVE_LITTLE_ENDIAN);
    return TMP_WORD.getFloat64(0, NATIVE_LITTLE_ENDIAN);
  }
  return ds.segment.getFloat64(ds.byteOffset + byteOffset);
}
function getInt16(byteOffset, s, defaultMask) {
  checkDataBounds(byteOffset, 2, s);
  const ds = getDataSection(s);
  if (defaultMask === void 0) {
    return ds.segment.getInt16(ds.byteOffset + byteOffset);
  }
  const v = ds.segment.getUint16(ds.byteOffset + byteOffset) ^ defaultMask.getUint16(0, true);
  TMP_WORD.setUint16(0, v, NATIVE_LITTLE_ENDIAN);
  return TMP_WORD.getInt16(0, NATIVE_LITTLE_ENDIAN);
}
function getInt32(byteOffset, s, defaultMask) {
  checkDataBounds(byteOffset, 4, s);
  const ds = getDataSection(s);
  if (defaultMask === void 0) {
    return ds.segment.getInt32(ds.byteOffset + byteOffset);
  }
  const v = ds.segment.getUint32(ds.byteOffset + byteOffset) ^ defaultMask.getUint16(0, true);
  TMP_WORD.setUint32(0, v, NATIVE_LITTLE_ENDIAN);
  return TMP_WORD.getInt32(0, NATIVE_LITTLE_ENDIAN);
}
function getInt64(byteOffset, s, defaultMask) {
  checkDataBounds(byteOffset, 8, s);
  const ds = getDataSection(s);
  if (defaultMask !== void 0) {
    const lo = ds.segment.getUint32(ds.byteOffset + byteOffset) ^ defaultMask.getUint32(0, true);
    const hi = ds.segment.getUint32(ds.byteOffset + byteOffset + 4) ^ defaultMask.getUint32(4, true);
    TMP_WORD.setUint32(NATIVE_LITTLE_ENDIAN ? 0 : 4, lo, NATIVE_LITTLE_ENDIAN);
    TMP_WORD.setUint32(NATIVE_LITTLE_ENDIAN ? 4 : 0, hi, NATIVE_LITTLE_ENDIAN);
    return TMP_WORD.getBigInt64(0, NATIVE_LITTLE_ENDIAN);
  }
  return ds.segment.getInt64(ds.byteOffset + byteOffset);
}
function getInt8(byteOffset, s, defaultMask) {
  checkDataBounds(byteOffset, 1, s);
  const ds = getDataSection(s);
  if (defaultMask === void 0) {
    return ds.segment.getInt8(ds.byteOffset + byteOffset);
  }
  const v = ds.segment.getUint8(ds.byteOffset + byteOffset) ^ defaultMask.getUint8(0);
  TMP_WORD.setUint8(0, v);
  return TMP_WORD.getInt8(0);
}
function getList(index, ListClass, s, defaultValue) {
  checkPointerBounds(index, s);
  const ps = getPointerSection(s);
  ps.byteOffset += index * 8;
  const l = new ListClass(ps.segment, ps.byteOffset, s._capnp.depthLimit - 1);
  if (isNull(l)) {
    if (defaultValue) {
      copyFrom(defaultValue, l);
    } else {
      initList$1(ListClass._capnp.size, 0, l, ListClass._capnp.compositeSize);
    }
  } else if (ListClass._capnp.compositeSize !== void 0) {
    const srcSize = getTargetCompositeListSize(l);
    const dstSize = ListClass._capnp.compositeSize;
    if (dstSize.dataByteLength > srcSize.dataByteLength || dstSize.pointerLength > srcSize.pointerLength) {
      const srcContent = getContent(l);
      const srcLength = getTargetListLength(l);
      const dstContent = l.segment.allocate(
        getByteLength(dstSize) * srcLength + 8
      );
      const res = initPointer(dstContent.segment, dstContent.byteOffset, l);
      setListPointer(
        res.offsetWords,
        ListClass._capnp.size,
        srcLength,
        res.pointer,
        dstSize
      );
      setStructPointer(srcLength, dstSize, dstContent);
      dstContent.byteOffset += 8;
      for (let i = 0; i < srcLength; i++) {
        const srcElementOffset = srcContent.byteOffset + i * getByteLength(srcSize);
        const dstElementOffset = dstContent.byteOffset + i * getByteLength(dstSize);
        dstContent.segment.copyWords(
          dstElementOffset,
          srcContent.segment,
          srcElementOffset,
          getWordLength(srcSize)
        );
        for (let j = 0; j < srcSize.pointerLength; j++) {
          const srcPtr = new Pointer(
            srcContent.segment,
            srcElementOffset + srcSize.dataByteLength + j * 8
          );
          const dstPtr = new Pointer(
            dstContent.segment,
            dstElementOffset + dstSize.dataByteLength + j * 8
          );
          const srcPtrTarget = followFars(srcPtr);
          const srcPtrContent = getContent(srcPtr);
          if (getTargetPointerType(srcPtr) === PointerType.LIST && getTargetListElementSize(srcPtr) === ListElementSize.COMPOSITE) {
            srcPtrContent.byteOffset -= 8;
          }
          const r = initPointer(
            srcPtrContent.segment,
            srcPtrContent.byteOffset,
            dstPtr
          );
          const a = srcPtrTarget.segment.getUint8(srcPtrTarget.byteOffset) & 3;
          const b = srcPtrTarget.segment.getUint32(srcPtrTarget.byteOffset + 4);
          r.pointer.segment.setUint32(
            r.pointer.byteOffset,
            a | r.offsetWords << 2
          );
          r.pointer.segment.setUint32(r.pointer.byteOffset + 4, b);
        }
      }
      srcContent.segment.fillZeroWords(
        srcContent.byteOffset,
        getWordLength(srcSize) * srcLength
      );
    }
  }
  return l;
}
function getPointer(index, s) {
  checkPointerBounds(index, s);
  const ps = getPointerSection(s);
  ps.byteOffset += index * 8;
  return new Pointer(ps.segment, ps.byteOffset, s._capnp.depthLimit - 1);
}
function getPointerAs(index, PointerClass, s) {
  checkPointerBounds(index, s);
  const ps = getPointerSection(s);
  ps.byteOffset += index * 8;
  return new PointerClass(ps.segment, ps.byteOffset, s._capnp.depthLimit - 1);
}
function getPointerSection(s) {
  const ps = getContent(s);
  ps.byteOffset += padToWord$1(getSize(s).dataByteLength);
  return ps;
}
function getSize(s) {
  if (s._capnp.compositeIndex !== void 0) {
    const c2 = getContent(s, true);
    c2.byteOffset -= 8;
    return getStructSize(c2);
  }
  return getTargetStructSize(s);
}
function getStruct(index, StructClass, s, defaultValue) {
  const t = getPointerAs(index, StructClass, s);
  if (isNull(t)) {
    if (defaultValue) {
      copyFrom(defaultValue, t);
    } else {
      initStruct(StructClass._capnp.size, t);
    }
  } else {
    validate(PointerType.STRUCT, t);
    const ts = getTargetStructSize(t);
    if (ts.dataByteLength < StructClass._capnp.size.dataByteLength || ts.pointerLength < StructClass._capnp.size.pointerLength) {
      resize(StructClass._capnp.size, t);
    }
  }
  return t;
}
function getText(index, s, defaultValue) {
  const t = Text.fromPointer(getPointer(index, s));
  if (isNull(t) && defaultValue) {
    t.set(0, defaultValue);
  }
  return t.get(0);
}
function getUint16(byteOffset, s, defaultMask) {
  checkDataBounds(byteOffset, 2, s);
  const ds = getDataSection(s);
  if (defaultMask === void 0) {
    return ds.segment.getUint16(ds.byteOffset + byteOffset);
  }
  return ds.segment.getUint16(ds.byteOffset + byteOffset) ^ defaultMask.getUint16(0, true);
}
function getUint32(byteOffset, s, defaultMask) {
  checkDataBounds(byteOffset, 4, s);
  const ds = getDataSection(s);
  if (defaultMask === void 0) {
    return ds.segment.getUint32(ds.byteOffset + byteOffset);
  }
  return ds.segment.getUint32(ds.byteOffset + byteOffset) ^ defaultMask.getUint32(0, true);
}
function getUint64(byteOffset, s, defaultMask) {
  checkDataBounds(byteOffset, 8, s);
  const ds = getDataSection(s);
  if (defaultMask !== void 0) {
    const lo = ds.segment.getUint32(ds.byteOffset + byteOffset) ^ defaultMask.getUint32(0, true);
    const hi = ds.segment.getUint32(ds.byteOffset + byteOffset + 4) ^ defaultMask.getUint32(4, true);
    TMP_WORD.setUint32(NATIVE_LITTLE_ENDIAN ? 0 : 4, lo, NATIVE_LITTLE_ENDIAN);
    TMP_WORD.setUint32(NATIVE_LITTLE_ENDIAN ? 4 : 0, hi, NATIVE_LITTLE_ENDIAN);
    return TMP_WORD.getBigUint64(0, NATIVE_LITTLE_ENDIAN);
  }
  return ds.segment.getUint64(ds.byteOffset + byteOffset);
}
function getUint8(byteOffset, s, defaultMask) {
  checkDataBounds(byteOffset, 1, s);
  const ds = getDataSection(s);
  if (defaultMask === void 0) {
    return ds.segment.getUint8(ds.byteOffset + byteOffset);
  }
  return ds.segment.getUint8(ds.byteOffset + byteOffset) ^ defaultMask.getUint8(0);
}
function initData(index, length, s) {
  checkPointerBounds(index, s);
  const ps = getPointerSection(s);
  ps.byteOffset += index * 8;
  const l = new Data(ps.segment, ps.byteOffset, s._capnp.depthLimit - 1);
  erase(l);
  initList$1(ListElementSize.BYTE, length, l);
  return l;
}
function initList(index, ListClass, length, s) {
  checkPointerBounds(index, s);
  const ps = getPointerSection(s);
  ps.byteOffset += index * 8;
  const l = new ListClass(ps.segment, ps.byteOffset, s._capnp.depthLimit - 1);
  erase(l);
  initList$1(ListClass._capnp.size, length, l, ListClass._capnp.compositeSize);
  return l;
}
function setBit(bitOffset, value, s, defaultMask) {
  const byteOffset = Math.floor(bitOffset / 8);
  const bitMask = 1 << bitOffset % 8;
  checkDataBounds(byteOffset, 1, s);
  const ds = getDataSection(s);
  const b = ds.segment.getUint8(ds.byteOffset + byteOffset);
  if (defaultMask !== void 0) {
    value = (defaultMask.getUint8(0) & bitMask) === 0 ? value : !value;
  }
  ds.segment.setUint8(
    ds.byteOffset + byteOffset,
    value ? b | bitMask : b & ~bitMask
  );
}
function setFloat32(byteOffset, value, s, defaultMask) {
  checkDataBounds(byteOffset, 4, s);
  const ds = getDataSection(s);
  if (defaultMask !== void 0) {
    TMP_WORD.setFloat32(0, value, NATIVE_LITTLE_ENDIAN);
    const v = TMP_WORD.getUint32(0, NATIVE_LITTLE_ENDIAN) ^ defaultMask.getUint32(0, true);
    ds.segment.setUint32(ds.byteOffset + byteOffset, v);
    return;
  }
  ds.segment.setFloat32(ds.byteOffset + byteOffset, value);
}
function setFloat64(byteOffset, value, s, defaultMask) {
  checkDataBounds(byteOffset, 8, s);
  const ds = getDataSection(s);
  if (defaultMask !== void 0) {
    TMP_WORD.setFloat64(0, value, NATIVE_LITTLE_ENDIAN);
    const lo = TMP_WORD.getUint32(0, NATIVE_LITTLE_ENDIAN) ^ defaultMask.getUint32(0, true);
    const hi = TMP_WORD.getUint32(4, NATIVE_LITTLE_ENDIAN) ^ defaultMask.getUint32(4, true);
    ds.segment.setUint32(ds.byteOffset + byteOffset, lo);
    ds.segment.setUint32(ds.byteOffset + byteOffset + 4, hi);
    return;
  }
  ds.segment.setFloat64(ds.byteOffset + byteOffset, value);
}
function setInt16(byteOffset, value, s, defaultMask) {
  checkDataBounds(byteOffset, 2, s);
  const ds = getDataSection(s);
  if (defaultMask !== void 0) {
    TMP_WORD.setInt16(0, value, NATIVE_LITTLE_ENDIAN);
    const v = TMP_WORD.getUint16(0, NATIVE_LITTLE_ENDIAN) ^ defaultMask.getUint16(0, true);
    ds.segment.setUint16(ds.byteOffset + byteOffset, v);
    return;
  }
  ds.segment.setInt16(ds.byteOffset + byteOffset, value);
}
function setInt32(byteOffset, value, s, defaultMask) {
  checkDataBounds(byteOffset, 4, s);
  const ds = getDataSection(s);
  if (defaultMask !== void 0) {
    TMP_WORD.setInt32(0, value, NATIVE_LITTLE_ENDIAN);
    const v = TMP_WORD.getUint32(0, NATIVE_LITTLE_ENDIAN) ^ defaultMask.getUint32(0, true);
    ds.segment.setUint32(ds.byteOffset + byteOffset, v);
    return;
  }
  ds.segment.setInt32(ds.byteOffset + byteOffset, value);
}
function setInt64(byteOffset, value, s, defaultMask) {
  checkDataBounds(byteOffset, 8, s);
  const ds = getDataSection(s);
  if (defaultMask !== void 0) {
    TMP_WORD.setBigInt64(0, value, NATIVE_LITTLE_ENDIAN);
    const lo = TMP_WORD.getUint32(NATIVE_LITTLE_ENDIAN ? 0 : 4, NATIVE_LITTLE_ENDIAN) ^ defaultMask.getUint32(0, true);
    const hi = TMP_WORD.getUint32(NATIVE_LITTLE_ENDIAN ? 4 : 0, NATIVE_LITTLE_ENDIAN) ^ defaultMask.getUint32(4, true);
    ds.segment.setUint32(ds.byteOffset + byteOffset, lo);
    ds.segment.setUint32(ds.byteOffset + byteOffset + 4, hi);
    return;
  }
  ds.segment.setInt64(ds.byteOffset + byteOffset, value);
}
function setInt8(byteOffset, value, s, defaultMask) {
  checkDataBounds(byteOffset, 1, s);
  const ds = getDataSection(s);
  if (defaultMask !== void 0) {
    TMP_WORD.setInt8(0, value);
    const v = TMP_WORD.getUint8(0) ^ defaultMask.getUint8(0);
    ds.segment.setUint8(ds.byteOffset + byteOffset, v);
    return;
  }
  ds.segment.setInt8(ds.byteOffset + byteOffset, value);
}
function setText(index, value, s) {
  Text.fromPointer(getPointer(index, s)).set(0, value);
}
function setUint16(byteOffset, value, s, defaultMask) {
  checkDataBounds(byteOffset, 2, s);
  const ds = getDataSection(s);
  if (defaultMask !== void 0) {
    value ^= defaultMask.getUint16(0, true);
  }
  ds.segment.setUint16(ds.byteOffset + byteOffset, value);
}
function setUint32(byteOffset, value, s, defaultMask) {
  checkDataBounds(byteOffset, 4, s);
  const ds = getDataSection(s);
  if (defaultMask !== void 0) {
    value ^= defaultMask.getUint32(0, true);
  }
  ds.segment.setUint32(ds.byteOffset + byteOffset, value);
}
function setUint64(byteOffset, value, s, defaultMask) {
  checkDataBounds(byteOffset, 8, s);
  const ds = getDataSection(s);
  if (defaultMask !== void 0) {
    TMP_WORD.setBigUint64(0, value, NATIVE_LITTLE_ENDIAN);
    const lo = TMP_WORD.getUint32(NATIVE_LITTLE_ENDIAN ? 0 : 4, NATIVE_LITTLE_ENDIAN) ^ defaultMask.getUint32(0, true);
    const hi = TMP_WORD.getUint32(NATIVE_LITTLE_ENDIAN ? 4 : 0, NATIVE_LITTLE_ENDIAN) ^ defaultMask.getUint32(4, true);
    ds.segment.setUint32(ds.byteOffset + byteOffset, lo);
    ds.segment.setUint32(ds.byteOffset + byteOffset + 4, hi);
    return;
  }
  ds.segment.setUint64(ds.byteOffset + byteOffset, value);
}
function setUint8(byteOffset, value, s, defaultMask) {
  checkDataBounds(byteOffset, 1, s);
  const ds = getDataSection(s);
  if (defaultMask !== void 0) {
    value ^= defaultMask.getUint8(0);
  }
  ds.segment.setUint8(ds.byteOffset + byteOffset, value);
}
function testWhich(name, found, wanted, s) {
  if (found !== wanted) {
    throw new Error(format4(PTR_INVALID_UNION_ACCESS, s, name, found, wanted));
  }
}
function checkDataBounds(byteOffset, byteLength, s) {
  const { dataByteLength } = getSize(s);
  if (byteOffset < 0 || byteLength < 0 || byteOffset + byteLength > dataByteLength) {
    throw new Error(
      format4(
        PTR_STRUCT_DATA_OUT_OF_BOUNDS,
        s,
        byteLength,
        byteOffset,
        dataByteLength
      )
    );
  }
}

// ../../node_modules/.pnpm/capnp-es@0.0.16_typescript@5.8.3/node_modules/capnp-es/dist/shared/capnp-es.CFSf015t.mjs
function CompositeList(CompositeClass) {
  return class extends List {
    static _capnp = {
      compositeSize: CompositeClass._capnp.size,
      displayName: `List<${CompositeClass._capnp.displayName}>`,
      size: ListElementSize.COMPOSITE
    };
    get(index) {
      return new CompositeClass(
        this.segment,
        this.byteOffset,
        this._capnp.depthLimit - 1,
        index
      );
    }
    set(index, value) {
      copyFrom(value, this.get(index));
    }
    [Symbol.toStringTag]() {
      return `Composite_${super.toString()},cls:${CompositeClass.toString()}`;
    }
  };
}
function _makePrimitiveMaskFn(byteLength, setter) {
  return (x) => {
    const dv = new DataView(new ArrayBuffer(byteLength));
    setter.call(dv, 0, x, true);
    return dv;
  };
}
var getFloat32Mask = _makePrimitiveMaskFn(
  4,
  DataView.prototype.setFloat32
);
var getFloat64Mask = _makePrimitiveMaskFn(
  8,
  DataView.prototype.setFloat64
);
var getInt16Mask = _makePrimitiveMaskFn(
  2,
  DataView.prototype.setInt16
);
var getInt32Mask = _makePrimitiveMaskFn(
  4,
  DataView.prototype.setInt32
);
var getInt64Mask = _makePrimitiveMaskFn(
  8,
  DataView.prototype.setBigInt64
);
var getInt8Mask = _makePrimitiveMaskFn(1, DataView.prototype.setInt8);
var getUint16Mask = _makePrimitiveMaskFn(
  2,
  DataView.prototype.setUint16
);
var getUint32Mask = _makePrimitiveMaskFn(
  4,
  DataView.prototype.setUint32
);
var getUint64Mask = _makePrimitiveMaskFn(
  8,
  DataView.prototype.setBigUint64
);
var getUint8Mask = _makePrimitiveMaskFn(
  1,
  DataView.prototype.setUint8
);
function getBitMask(value, bitOffset) {
  const dv = new DataView(new ArrayBuffer(1));
  if (!value) {
    return dv;
  }
  dv.setUint8(0, 1 << bitOffset % 8);
  return dv;
}

// ../../node_modules/.pnpm/capnp-es@0.0.16_typescript@5.8.3/node_modules/capnp-es/dist/shared/capnp-es.BlZmb8ia.mjs
var ArenaKind = /* @__PURE__ */ ((ArenaKind2) => {
  ArenaKind2[ArenaKind2["SINGLE_SEGMENT"] = 0] = "SINGLE_SEGMENT";
  ArenaKind2[ArenaKind2["MULTI_SEGMENT"] = 1] = "MULTI_SEGMENT";
  return ArenaKind2;
})(ArenaKind || {});
var ArenaAllocationResult = class {
  /**
   * The newly allocated buffer. This buffer might be a copy of an existing segment's buffer with free space appended.
   */
  buffer;
  /**
   * The id of the newly-allocated segment.
   */
  id;
  constructor(id, buffer) {
    this.id = id;
    this.buffer = buffer;
  }
};
var MultiSegmentArena = class {
  constructor(buffers = [new ArrayBuffer(DEFAULT_BUFFER_SIZE)]) {
    this.buffers = buffers;
    let i = buffers.length;
    while (--i >= 0) {
      if ((buffers[i].byteLength & 7) !== 0) {
        throw new Error(format4(SEG_NOT_WORD_ALIGNED, buffers[i].byteLength));
      }
    }
  }
  static allocate = allocate$2;
  static getBuffer = getBuffer$2;
  static getNumSegments = getNumSegments$2;
  kind = ArenaKind.MULTI_SEGMENT;
  toString() {
    return format4("MultiSegmentArena_segments:%d", getNumSegments$2(this));
  }
};
function allocate$2(minSize, m) {
  const b = new ArrayBuffer(padToWord$1(Math.max(minSize, DEFAULT_BUFFER_SIZE)));
  m.buffers.push(b);
  return new ArenaAllocationResult(m.buffers.length - 1, b);
}
function getBuffer$2(id, m) {
  if (id < 0 || id >= m.buffers.length) {
    throw new Error(format4(SEG_ID_OUT_OF_BOUNDS, id));
  }
  return m.buffers[id];
}
function getNumSegments$2(m) {
  return m.buffers.length;
}
var SingleSegmentArena = class {
  static allocate = allocate$1;
  static getBuffer = getBuffer$1;
  static getNumSegments = getNumSegments$1;
  buffer;
  kind = ArenaKind.SINGLE_SEGMENT;
  constructor(buffer = new ArrayBuffer(DEFAULT_BUFFER_SIZE)) {
    if ((buffer.byteLength & 7) !== 0) {
      throw new Error(format4(SEG_NOT_WORD_ALIGNED, buffer.byteLength));
    }
    this.buffer = buffer;
  }
  toString() {
    return format4("SingleSegmentArena_len:%x", this.buffer.byteLength);
  }
};
function allocate$1(minSize, segments, s) {
  const srcBuffer = segments.length > 0 ? segments[0].buffer : s.buffer;
  minSize = minSize < MIN_SINGLE_SEGMENT_GROWTH ? MIN_SINGLE_SEGMENT_GROWTH : padToWord$1(minSize);
  s.buffer = new ArrayBuffer(srcBuffer.byteLength + minSize);
  new Float64Array(s.buffer).set(new Float64Array(srcBuffer));
  return new ArenaAllocationResult(0, s.buffer);
}
function getBuffer$1(id, s) {
  if (id !== 0) throw new Error(format4(SEG_GET_NON_ZERO_SINGLE, id));
  return s.buffer;
}
function getNumSegments$1() {
  return 1;
}
var Arena = class {
  static allocate = allocate;
  static copy = copy$1;
  static getBuffer = getBuffer;
  static getNumSegments = getNumSegments;
};
function allocate(minSize, segments, a) {
  switch (a.kind) {
    case ArenaKind.MULTI_SEGMENT: {
      return MultiSegmentArena.allocate(minSize, a);
    }
    case ArenaKind.SINGLE_SEGMENT: {
      return SingleSegmentArena.allocate(minSize, segments, a);
    }
    default: {
      return assertNever3(a);
    }
  }
}
function copy$1(a) {
  switch (a.kind) {
    case ArenaKind.MULTI_SEGMENT: {
      let i = a.buffers.length;
      const buffers = Array.from({ length: i });
      while (--i >= 0) {
        buffers[i] = a.buffers[i].slice(0);
      }
      return new MultiSegmentArena(buffers);
    }
    case ArenaKind.SINGLE_SEGMENT: {
      return new SingleSegmentArena(a.buffer.slice(0));
    }
    default: {
      return assertNever3(a);
    }
  }
}
function getBuffer(id, a) {
  switch (a.kind) {
    case ArenaKind.MULTI_SEGMENT: {
      return MultiSegmentArena.getBuffer(id, a);
    }
    case ArenaKind.SINGLE_SEGMENT: {
      return SingleSegmentArena.getBuffer(id, a);
    }
    default: {
      return assertNever3(a);
    }
  }
}
function getNumSegments(a) {
  switch (a.kind) {
    case ArenaKind.MULTI_SEGMENT: {
      return MultiSegmentArena.getNumSegments(a);
    }
    case ArenaKind.SINGLE_SEGMENT: {
      return SingleSegmentArena.getNumSegments();
    }
    default: {
      return assertNever3(a);
    }
  }
}
function getHammingWeight(x) {
  let w = x - (x >> 1 & 1431655765);
  w = (w & 858993459) + (w >> 2 & 858993459);
  return (w + (w >> 4) & 252645135) * 16843009 >> 24;
}
function getTagByte(a, b, c2, d, e, f, g, h) {
  return (a === 0 ? 0 : 1) | (b === 0 ? 0 : 2) | (c2 === 0 ? 0 : 4) | (d === 0 ? 0 : 8) | (e === 0 ? 0 : 16) | (f === 0 ? 0 : 32) | (g === 0 ? 0 : 64) | (h === 0 ? 0 : 128);
}
function getUnpackedByteLength(packed) {
  const p2 = new Uint8Array(packed);
  let wordCount = 0;
  let lastTag = 119;
  for (let i = 0; i < p2.byteLength; ) {
    const tag = p2[i];
    if (lastTag === 0) {
      wordCount += tag;
      i++;
      lastTag = 119;
    } else if (lastTag === 255) {
      wordCount += tag;
      i += tag * 8 + 1;
      lastTag = 119;
    } else {
      wordCount++;
      i += getHammingWeight(tag) + 1;
      lastTag = tag;
    }
  }
  return wordCount * 8;
}
function getZeroByteCount(a, b, c2, d, e, f, g, h) {
  return (a === 0 ? 1 : 0) + (b === 0 ? 1 : 0) + (c2 === 0 ? 1 : 0) + (d === 0 ? 1 : 0) + (e === 0 ? 1 : 0) + (f === 0 ? 1 : 0) + (g === 0 ? 1 : 0) + (h === 0 ? 1 : 0);
}
function pack(unpacked, byteOffset = 0, byteLength) {
  if (unpacked.byteLength % 8 !== 0) {
    throw new Error(MSG_PACK_NOT_WORD_ALIGNED);
  }
  const src = new Uint8Array(unpacked, byteOffset, byteLength);
  const dst = [];
  let lastTag = 119;
  let spanWordCountOffset = 0;
  let rangeWordCount = 0;
  for (let srcByteOffset = 0; srcByteOffset < src.byteLength; srcByteOffset += 8) {
    const a = src[srcByteOffset];
    const b = src[srcByteOffset + 1];
    const c2 = src[srcByteOffset + 2];
    const d = src[srcByteOffset + 3];
    const e = src[srcByteOffset + 4];
    const f = src[srcByteOffset + 5];
    const g = src[srcByteOffset + 6];
    const h = src[srcByteOffset + 7];
    const tag = getTagByte(a, b, c2, d, e, f, g, h);
    let skipWriteWord = true;
    switch (lastTag) {
      case 0: {
        if (tag !== 0 || rangeWordCount >= 255) {
          dst.push(rangeWordCount);
          rangeWordCount = 0;
          skipWriteWord = false;
        } else {
          rangeWordCount++;
        }
        break;
      }
      case 255: {
        const zeroCount = getZeroByteCount(a, b, c2, d, e, f, g, h);
        if (zeroCount >= PACK_SPAN_THRESHOLD || rangeWordCount >= 255) {
          dst[spanWordCountOffset] = rangeWordCount;
          rangeWordCount = 0;
          skipWriteWord = false;
        } else {
          dst.push(a, b, c2, d, e, f, g, h);
          rangeWordCount++;
        }
        break;
      }
      default: {
        skipWriteWord = false;
        break;
      }
    }
    if (skipWriteWord) {
      continue;
    }
    dst.push(tag);
    lastTag = tag;
    if (a !== 0) dst.push(a);
    if (b !== 0) dst.push(b);
    if (c2 !== 0) dst.push(c2);
    if (d !== 0) dst.push(d);
    if (e !== 0) dst.push(e);
    if (f !== 0) dst.push(f);
    if (g !== 0) dst.push(g);
    if (h !== 0) dst.push(h);
    if (tag === 255) {
      spanWordCountOffset = dst.length;
      dst.push(0);
    }
  }
  if (lastTag === 0) {
    dst.push(rangeWordCount);
  } else if (lastTag === 255) {
    dst[spanWordCountOffset] = rangeWordCount;
  }
  return new Uint8Array(dst).buffer;
}
function unpack(packed) {
  const src = new Uint8Array(packed);
  const dst = new Uint8Array(new ArrayBuffer(getUnpackedByteLength(packed)));
  let lastTag = 119;
  for (let srcByteOffset = 0, dstByteOffset = 0; srcByteOffset < src.byteLength; ) {
    const tag = src[srcByteOffset];
    if (lastTag === 0) {
      dstByteOffset += tag * 8;
      srcByteOffset++;
      lastTag = 119;
    } else if (lastTag === 255) {
      const spanByteLength = tag * 8;
      dst.set(
        src.subarray(srcByteOffset + 1, srcByteOffset + 1 + spanByteLength),
        dstByteOffset
      );
      dstByteOffset += spanByteLength;
      srcByteOffset += 1 + spanByteLength;
      lastTag = 119;
    } else {
      srcByteOffset++;
      for (let i = 1; i <= 128; i <<= 1) {
        if ((tag & i) !== 0) {
          dst[dstByteOffset] = src[srcByteOffset++];
        }
        dstByteOffset++;
      }
      lastTag = tag;
    }
  }
  return dst.buffer;
}
var Segment = class {
  constructor(id, message, buffer, byteLength = 0) {
    this.id = id;
    this.message = message;
    this.message = message;
    this.buffer = buffer;
    this._dv = new DataView(buffer);
    this.byteOffset = 0;
    this.byteLength = byteLength;
  }
  buffer;
  /** The number of bytes currently allocated in the segment. */
  byteLength;
  /**
   * This value should always be zero. It's only here to satisfy the DataView interface.
   *
   * In the future the Segment implementation (or a child class) may allow accessing the buffer from a nonzero offset,
   * but that adds a lot of extra arithmetic.
   */
  byteOffset;
  [Symbol.toStringTag] = "Segment";
  _dv;
  /**
   * Attempt to allocate the requested number of bytes in this segment. If this segment is full this method will return
   * a pointer to freshly allocated space in another segment from the same message.
   *
   * @param byteLength The number of bytes to allocate, will be rounded up to the nearest word.
   * @returns A pointer to the newly allocated space.
   */
  allocate(byteLength) {
    let segment = this;
    byteLength = padToWord$1(byteLength);
    if (byteLength > MAX_SEGMENT_LENGTH - 8) {
      throw new Error(format4(SEG_SIZE_OVERFLOW, byteLength));
    }
    if (!segment.hasCapacity(byteLength)) {
      segment = segment.message.allocateSegment(byteLength);
    }
    const byteOffset = segment.byteLength;
    segment.byteLength += byteLength;
    return new Pointer(segment, byteOffset);
  }
  /**
   * Quickly copy a word (8 bytes) from `srcSegment` into this one at the given offset.
   *
   * @param byteOffset The offset to write the word to.
   * @param srcSegment The segment to copy the word from.
   * @param srcByteOffset The offset from the start of `srcSegment` to copy from.
   */
  copyWord(byteOffset, srcSegment, srcByteOffset) {
    const value = srcSegment._dv.getFloat64(
      srcByteOffset,
      NATIVE_LITTLE_ENDIAN
    );
    this._dv.setFloat64(byteOffset, value, NATIVE_LITTLE_ENDIAN);
  }
  /**
   * Quickly copy words from `srcSegment` into this one.
   *
   * @param byteOffset The offset to start copying into.
   * @param srcSegment The segment to copy from.
   * @param srcByteOffset The start offset to copy from.
   * @param wordLength The number of words to copy.
   */
  copyWords(byteOffset, srcSegment, srcByteOffset, wordLength) {
    const dst = new Float64Array(this.buffer, byteOffset, wordLength);
    const src = new Float64Array(srcSegment.buffer, srcByteOffset, wordLength);
    dst.set(src);
  }
  /**
   * Quickly fill a number of words in the buffer with zeroes.
   *
   * @param byteOffset The first byte to set to zero.
   * @param wordLength The number of words (not bytes!) to zero out.
   */
  fillZeroWords(byteOffset, wordLength) {
    new Float64Array(this.buffer, byteOffset, wordLength).fill(0);
  }
  getBigInt64(byteOffset, littleEndian) {
    return this._dv.getBigInt64(byteOffset, littleEndian);
  }
  getBigUint64(byteOffset, littleEndian) {
    return this._dv.getBigUint64(byteOffset, littleEndian);
  }
  /**
   * Get the total number of bytes available in this segment (the size of its underlying buffer).
   *
   * @returns The total number of bytes this segment can hold.
   */
  getCapacity() {
    return this.buffer.byteLength;
  }
  /**
   * Read a float16 value out of this segment.
   *
   * NOTE: Non functional, added to allow compilation with TS 5.9+
   *
   * @param byteOffset The offset in bytes to the value.
   * @returns The value.
   */
  getFloat16(_byteOffset) {
    throw new Error("Not implemented");
  }
  /**
   * Read a float32 value out of this segment.
   *
   * @param byteOffset The offset in bytes to the value.
   * @returns The value.
   */
  getFloat32(byteOffset) {
    return this._dv.getFloat32(byteOffset, true);
  }
  /**
   * Read a float64 value out of this segment.
   *
   * @param byteOffset The offset in bytes to the value.
   * @returns The value.
   */
  getFloat64(byteOffset) {
    return this._dv.getFloat64(byteOffset, true);
  }
  /**
   * Read an int16 value out of this segment.
   *
   * @param byteOffset The offset in bytes to the value.
   * @returns The value.
   */
  getInt16(byteOffset) {
    return this._dv.getInt16(byteOffset, true);
  }
  /**
   * Read an int32 value out of this segment.
   *
   * @param byteOffset The offset in bytes to the value.
   * @returns The value.
   */
  getInt32(byteOffset) {
    return this._dv.getInt32(byteOffset, true);
  }
  /**
   * Read an int64 value out of this segment.
   *
   * @param byteOffset The offset in bytes to the value.
   * @returns The value.
   */
  getInt64(byteOffset) {
    return this._dv.getBigInt64(byteOffset, true);
  }
  /**
   * Read an int8 value out of this segment.
   *
   * @param byteOffset The offset in bytes to the value.
   * @returns The value.
   */
  getInt8(byteOffset) {
    return this._dv.getInt8(byteOffset);
  }
  /**
   * Read a uint16 value out of this segment.
   *
   * @param byteOffset The offset in bytes to the value.
   * @returns The value.
   */
  getUint16(byteOffset) {
    return this._dv.getUint16(byteOffset, true);
  }
  /**
   * Read a uint32 value out of this segment.
   *
   * @param byteOffset The offset in bytes to the value.
   * @returns The value.
   */
  getUint32(byteOffset) {
    return this._dv.getUint32(byteOffset, true);
  }
  /**
   * Read a uint64 value (as a bigint) out of this segment.
   * NOTE: this does not copy the memory region, so updates to the underlying buffer will affect the returned value!
   *
   * @param byteOffset The offset in bytes to the value.
   * @returns The value.
   */
  getUint64(byteOffset) {
    return this._dv.getBigUint64(byteOffset, true);
  }
  /**
   * Read a uint8 value out of this segment.
   *
   * @param byteOffset The offset in bytes to the value.
   * @returns The value.
   */
  getUint8(byteOffset) {
    return this._dv.getUint8(byteOffset);
  }
  hasCapacity(byteLength) {
    return this.buffer.byteLength - this.byteLength >= byteLength;
  }
  /**
   * Quickly check the word at the given offset to see if it is equal to zero.
   *
   * PERF_V8: Fastest way to do this is by reading the whole word as a `number` (float64) in the _native_ endian format
   * and see if it's zero.
   *
   * Benchmark: http://jsben.ch/#/Pjooc
   *
   * @param byteOffset The offset to the word.
   * @returns `true` if the word is zero.
   */
  isWordZero(byteOffset) {
    return this._dv.getFloat64(byteOffset, NATIVE_LITTLE_ENDIAN) === 0;
  }
  /**
   * Swap out this segment's underlying buffer with a new one. It's assumed that the new buffer has the same content but
   * more free space, otherwise all existing pointers to this segment will be hilariously broken.
   *
   * @param buffer The new buffer to use.
   */
  replaceBuffer(buffer) {
    if (this.buffer === buffer) {
      return;
    }
    if (buffer.byteLength < this.byteLength) {
      throw new Error(SEG_REPLACEMENT_BUFFER_TOO_SMALL);
    }
    this._dv = new DataView(buffer);
    this.buffer = buffer;
  }
  setBigInt64(byteOffset, value, littleEndian) {
    this._dv.setBigInt64(byteOffset, value, littleEndian);
  }
  /** WARNING: This function is not yet implemented.  */
  setBigUint64(byteOffset, value, littleEndian) {
    this._dv.setBigUint64(byteOffset, value, littleEndian);
  }
  /**
   * Write a float16 value to the specified offset.
   *
   * NOTE: Non functional, added to allow compilation with TS 5.9+
   *
   * @param byteOffset The offset from the beginning of the buffer.
   * @param val The value to store.
   */
  setFloat16(_byteOffset, _val) {
    throw new Error("Not implemented");
  }
  /**
   * Write a float32 value to the specified offset.
   *
   * @param byteOffset The offset from the beginning of the buffer.
   * @param val The value to store.
   */
  setFloat32(byteOffset, val) {
    this._dv.setFloat32(byteOffset, val, true);
  }
  /**
   * Write an float64 value to the specified offset.
   *
   * @param byteOffset The offset from the beginning of the buffer.
   * @param val The value to store.
   */
  setFloat64(byteOffset, val) {
    this._dv.setFloat64(byteOffset, val, true);
  }
  /**
   * Write an int16 value to the specified offset.
   *
   * @param byteOffset The offset from the beginning of the buffer.
   * @param val The value to store.
   */
  setInt16(byteOffset, val) {
    this._dv.setInt16(byteOffset, val, true);
  }
  /**
   * Write an int32 value to the specified offset.
   *
   * @param byteOffset The offset from the beginning of the buffer.
   * @param val The value to store.
   */
  setInt32(byteOffset, val) {
    this._dv.setInt32(byteOffset, val, true);
  }
  /**
   * Write an int8 value to the specified offset.
   *
   * @param byteOffset The offset from the beginning of the buffer.
   * @param val The value to store.
   */
  setInt8(byteOffset, val) {
    this._dv.setInt8(byteOffset, val);
  }
  /**
   * Write an int64 value to the specified offset.
   *
   * @param byteOffset The offset from the beginning of the buffer.
   * @param val The value to store.
   */
  setInt64(byteOffset, val) {
    this._dv.setBigInt64(byteOffset, val, true);
  }
  /**
   * Write a uint16 value to the specified offset.
   *
   * @param byteOffset The offset from the beginning of the buffer.
   * @param val The value to store.
   */
  setUint16(byteOffset, val) {
    this._dv.setUint16(byteOffset, val, true);
  }
  /**
   * Write a uint32 value to the specified offset.
   *
   * @param byteOffset The offset from the beginning of the buffer.
   * @param val The value to store.
   */
  setUint32(byteOffset, val) {
    this._dv.setUint32(byteOffset, val, true);
  }
  /**
   * Write a uint64 value to the specified offset.
   *
   * @param byteOffset The offset from the beginning of the buffer.
   * @param val The value to store.
   */
  setUint64(byteOffset, val) {
    this._dv.setBigUint64(byteOffset, val, true);
  }
  /**
   * Write a uint8 (byte) value to the specified offset.
   *
   * @param byteOffset The offset from the beginning of the buffer.
   * @param val The value to store.
   */
  setUint8(byteOffset, val) {
    this._dv.setUint8(byteOffset, val);
  }
  /**
   * Write a zero word (8 bytes) to the specified offset. This is slightly faster than calling `setUint64` or
   * `setFloat64` with a zero value.
   *
   * Benchmark: http://jsben.ch/#/dUdPI
   *
   * @param byteOffset The offset of the word to set to zero.
   */
  setWordZero(byteOffset) {
    this._dv.setFloat64(byteOffset, 0, NATIVE_LITTLE_ENDIAN);
  }
  toString() {
    return format4(
      "Segment_id:%d,off:%a,len:%a,cap:%a",
      this.id,
      this.byteLength,
      this.byteOffset,
      this.buffer.byteLength
    );
  }
};
var Message = class {
  static allocateSegment = allocateSegment;
  static dump = dump2;
  static getRoot = getRoot;
  static getSegment = getSegment;
  static initRoot = initRoot;
  static readRawPointer = readRawPointer;
  static toArrayBuffer = toArrayBuffer;
  static toPackedArrayBuffer = toPackedArrayBuffer;
  _capnp;
  /**
   * A Cap'n Proto message.
   *
   * SECURITY WARNING: In Node.js do not pass a Buffer's internal array buffer into this constructor. Pass the buffer
   * directly and everything will be fine. If not, your message will potentially be initialized with random memory
   * contents!
   *
   * The constructor method creates a new Message, optionally using a provided arena for segment allocation, or a buffer
   * to read from.
   *
   * @param src The source for the message.
   * A value of `undefined` will cause the message to initialize with a single segment arena only big enough for the
   * root pointer; it will expand as you go. This is a reasonable choice for most messages.
   *
   * Passing an arena will cause the message to use that arena for its segment allocation. Contents will be accepted
   * as-is.
   *
   * Passing an array buffer view (like `DataView`, `Uint8Array` or `Buffer`) will create a **copy** of the source
   * buffer; beware of the potential performance cost!
   *
   * @param packed Whether or not the message is packed. If `true` (the default), the message will be
   * unpacked.
   *
   * @param singleSegment If true, `src` will be treated as a message consisting of a single segment without
   * a framing header.
   *
   */
  constructor(src, packed = true, singleSegment = false) {
    this._capnp = initMessage(src, packed, singleSegment);
    if (src) {
      preallocateSegments(this);
    }
  }
  allocateSegment(byteLength) {
    return allocateSegment(byteLength, this);
  }
  /**
   * Copies the contents of this message into an identical message with its own ArrayBuffers.
   *
   * @returns A copy of this message.
   */
  copy() {
    return copy(this);
  }
  /**
   * Create a pretty-printed string dump of this message; incredibly useful for debugging.
   *
   * WARNING: Do not call this method on large messages!
   *
   * @returns A big steaming pile of pretty hex digits.
   */
  dump() {
    return dump2(this);
  }
  /**
   * Get a struct pointer for the root of this message. This is primarily used when reading a message; it will not
   * overwrite existing data.
   *
   * @param RootStruct The struct type to use as the root.
   * @returns A struct representing the root of the message.
   */
  getRoot(RootStruct) {
    return getRoot(RootStruct, this);
  }
  /**
   * Get a segment by its id.
   *
   * This will lazily allocate the first segment if it doesn't already exist.
   *
   * @param id The segment id.
   * @returns The requested segment.
   */
  getSegment(id) {
    return getSegment(id, this);
  }
  /**
   * Initialize a new message using the provided struct type as the root.
   *
   * @param RootStruct The struct type to use as the root.
   * @returns An initialized struct pointing to the root of the message.
   */
  initRoot(RootStruct) {
    return initRoot(RootStruct, this);
  }
  /**
   * Set the root of the message to a copy of the given pointer. Used internally
   * to make copies of pointers for default values.
   *
   * @param src The source pointer to copy.
   */
  setRoot(src) {
    setRoot(src, this);
  }
  /**
   * Combine the contents of this message's segments into a single array buffer and prepend a stream framing header
   * containing information about the following segment data.
   *
   * @returns An ArrayBuffer with the contents of this message.
   */
  toArrayBuffer() {
    return toArrayBuffer(this);
  }
  /**
   * Like `toArrayBuffer()`, but also applies the packing algorithm to the output. This is typically what you want to
   * use if you're sending the message over a network link or other slow I/O interface where size matters.
   *
   * @returns A packed message.
   */
  toPackedArrayBuffer() {
    return toPackedArrayBuffer(this);
  }
  addCap(client) {
    if (!this._capnp.capTable) {
      this._capnp.capTable = [];
    }
    const id = this._capnp.capTable.length;
    this._capnp.capTable.push(client);
    return id;
  }
  toString() {
    return `Message_arena:${this._capnp.arena}`;
  }
};
function initMessage(src, packed = true, singleSegment = false) {
  if (src === void 0) {
    return {
      arena: new SingleSegmentArena(),
      segments: [],
      traversalLimit: DEFAULT_TRAVERSE_LIMIT
    };
  }
  if (isAnyArena(src)) {
    return { arena: src, segments: [], traversalLimit: DEFAULT_TRAVERSE_LIMIT };
  }
  let buf = src;
  if (isArrayBufferView(buf)) {
    buf = buf.buffer.slice(
      buf.byteOffset,
      buf.byteOffset + buf.byteLength
    );
  }
  if (packed) {
    buf = unpack(buf);
  }
  if (singleSegment) {
    return {
      arena: new SingleSegmentArena(buf),
      segments: [],
      traversalLimit: DEFAULT_TRAVERSE_LIMIT
    };
  }
  return {
    arena: new MultiSegmentArena(getFramedSegments(buf)),
    segments: [],
    traversalLimit: DEFAULT_TRAVERSE_LIMIT
  };
}
function getFramedSegments(message) {
  const dv = new DataView(message);
  const segmentCount = dv.getUint32(0, true) + 1;
  const segments = Array.from({ length: segmentCount });
  let byteOffset = 4 + segmentCount * 4;
  byteOffset += byteOffset % 8;
  if (byteOffset + segmentCount * 4 > message.byteLength) {
    throw new Error(MSG_INVALID_FRAME_HEADER);
  }
  for (let i = 0; i < segmentCount; i++) {
    const byteLength = dv.getUint32(4 + i * 4, true) * 8;
    if (byteOffset + byteLength > message.byteLength) {
      throw new Error(MSG_INVALID_FRAME_HEADER);
    }
    segments[i] = message.slice(byteOffset, byteOffset + byteLength);
    byteOffset += byteLength;
  }
  return segments;
}
function preallocateSegments(m) {
  const numSegments = Arena.getNumSegments(m._capnp.arena);
  m._capnp.segments = Array.from({ length: numSegments });
  for (let i = 0; i < numSegments; i++) {
    if (i === 0 && Arena.getBuffer(i, m._capnp.arena).byteLength < 8) {
      throw new Error(MSG_SEGMENT_TOO_SMALL);
    }
    const buffer = Arena.getBuffer(i, m._capnp.arena);
    const segment = new Segment(i, m, buffer, buffer.byteLength);
    m._capnp.segments[i] = segment;
  }
}
function isArrayBufferView(src) {
  return src.byteOffset !== void 0;
}
function isAnyArena(o) {
  return o.kind !== void 0;
}
function allocateSegment(byteLength, m) {
  const res = Arena.allocate(byteLength, m._capnp.segments, m._capnp.arena);
  let s;
  if (res.id === m._capnp.segments.length) {
    s = new Segment(res.id, m, res.buffer);
    m._capnp.segments.push(s);
  } else if (res.id < 0 || res.id > m._capnp.segments.length) {
    throw new Error(format4(MSG_SEGMENT_OUT_OF_BOUNDS, res.id, m));
  } else {
    s = m._capnp.segments[res.id];
    s.replaceBuffer(res.buffer);
  }
  return s;
}
function dump2(m) {
  let r = "";
  if (m._capnp.segments.length === 0) {
    return "================\nNo Segments\n================\n";
  }
  for (let i = 0; i < m._capnp.segments.length; i++) {
    r += `================
Segment #${i}
================
`;
    const { buffer, byteLength } = m._capnp.segments[i];
    const b = new Uint8Array(buffer, 0, byteLength);
    r += dumpBuffer(b);
  }
  return r;
}
function getRoot(RootStruct, m) {
  const root = new RootStruct(m.getSegment(0), 0);
  validate(PointerType.STRUCT, root);
  const ts = getTargetStructSize(root);
  if (ts.dataByteLength < RootStruct._capnp.size.dataByteLength || ts.pointerLength < RootStruct._capnp.size.pointerLength) {
    resize(RootStruct._capnp.size, root);
  }
  return root;
}
function getSegment(id, m) {
  const segmentLength = m._capnp.segments.length;
  if (id === 0 && segmentLength === 0) {
    const arenaSegments = Arena.getNumSegments(m._capnp.arena);
    if (arenaSegments === 0) {
      allocateSegment(DEFAULT_BUFFER_SIZE, m);
    } else {
      m._capnp.segments[0] = new Segment(
        0,
        m,
        Arena.getBuffer(0, m._capnp.arena)
      );
    }
    if (!m._capnp.segments[0].hasCapacity(8)) {
      throw new Error(MSG_SEGMENT_TOO_SMALL);
    }
    m._capnp.segments[0].allocate(8);
    return m._capnp.segments[0];
  }
  if (id < 0 || id >= segmentLength) {
    throw new Error(format4(MSG_SEGMENT_OUT_OF_BOUNDS, id, m));
  }
  return m._capnp.segments[id];
}
function initRoot(RootStruct, m) {
  const root = new RootStruct(m.getSegment(0), 0);
  initStruct(RootStruct._capnp.size, root);
  return root;
}
function readRawPointer(data) {
  return new Pointer(new Message(data).getSegment(0), 0);
}
function setRoot(src, m) {
  copyFrom(src, new Pointer(m.getSegment(0), 0));
}
function toArrayBuffer(m) {
  const streamFrame = getStreamFrame(m);
  if (m._capnp.segments.length === 0) {
    getSegment(0, m);
  }
  const { segments } = m._capnp;
  const totalLength = streamFrame.byteLength + segments.reduce((l, s) => l + padToWord$1(s.byteLength), 0);
  const out = new Uint8Array(new ArrayBuffer(totalLength));
  let o = streamFrame.byteLength;
  out.set(new Uint8Array(streamFrame));
  for (const s of segments) {
    const segmentLength = padToWord$1(s.byteLength);
    out.set(new Uint8Array(s.buffer, 0, segmentLength), o);
    o += segmentLength;
  }
  return out.buffer;
}
function toPackedArrayBuffer(m) {
  const streamFrame = pack(getStreamFrame(m));
  if (m._capnp.segments.length === 0) {
    m.getSegment(0);
  }
  const segments = m._capnp.segments.map(
    (s) => pack(s.buffer, 0, padToWord$1(s.byteLength))
  );
  const totalLength = streamFrame.byteLength + segments.reduce((l, s) => l + s.byteLength, 0);
  const out = new Uint8Array(new ArrayBuffer(totalLength));
  let o = streamFrame.byteLength;
  out.set(new Uint8Array(streamFrame));
  for (const s of segments) {
    out.set(new Uint8Array(s), o);
    o += s.byteLength;
  }
  return out.buffer;
}
function getStreamFrame(m) {
  const { length } = m._capnp.segments;
  if (length === 0) {
    return new Float64Array(1).buffer;
  }
  const frameLength = 4 + length * 4 + (1 - length % 2) * 4;
  const out = new DataView(new ArrayBuffer(frameLength));
  out.setUint32(0, length - 1, true);
  for (const [i, s] of m._capnp.segments.entries()) {
    out.setUint32(i * 4 + 4, s.byteLength / 8, true);
  }
  return out.buffer;
}
function copy(m) {
  return new Message(Arena.copy(m._capnp.arena));
}

// ../../node_modules/.pnpm/capnp-es@0.0.16_typescript@5.8.3/node_modules/capnp-es/dist/shared/capnp-es.BVG6upt7.mjs
var Interface = class extends Pointer {
  static _capnp = {
    displayName: "Interface"
  };
  static getCapID = getCapID;
  static getAsInterface = getAsInterface;
  static isInterface = isInterface;
  static getClient = getClient;
  constructor(segment, byteOffset, depthLimit = MAX_DEPTH) {
    super(segment, byteOffset, depthLimit);
  }
  static fromPointer(p2) {
    return getAsInterface(p2);
  }
  getCapId() {
    return getCapID(this);
  }
  getClient() {
    return getClient(this);
  }
  [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
    return format4(
      "Interface_%d@%a,%d,limit:%x",
      this.segment.id,
      this.byteOffset,
      this.getCapId(),
      this._capnp.depthLimit
    );
  }
};
function getAsInterface(p2) {
  if (getTargetPointerType(p2) === PointerType.OTHER) {
    return new Interface(p2.segment, p2.byteOffset, p2._capnp.depthLimit);
  }
  return null;
}
function isInterface(p2) {
  return getTargetPointerType(p2) === PointerType.OTHER;
}
function getCapID(i) {
  if (i.segment.getUint32(i.byteOffset) !== PointerType.OTHER) {
    return -1;
  }
  return i.segment.getUint32(i.byteOffset + 4);
}
function getClient(i) {
  const capID = getCapID(i);
  const { capTable } = i.segment.message._capnp;
  if (!capTable) {
    return null;
  }
  return capTable[capID];
}

// ../../node_modules/.pnpm/capnp-es@0.0.16_typescript@5.8.3/node_modules/capnp-es/dist/index.mjs
var Void = class extends Struct {
  static _capnp = {
    displayName: "Void",
    id: "0",
    size: new ObjectSize(0, 0)
  };
};
var utils = {
  __proto__: null,
  PointerAllocationResult,
  add,
  adopt,
  checkDataBounds,
  checkPointerBounds,
  copyFrom,
  copyFromInterface,
  copyFromList,
  copyFromStruct,
  disown,
  dump,
  erase,
  erasePointer,
  followFar,
  followFars,
  getAs,
  getBit,
  getCapabilityId,
  getContent,
  getData,
  getDataSection,
  getFarSegmentId,
  getFloat32,
  getFloat64,
  getInt16,
  getInt32,
  getInt64,
  getInt8,
  getInterfaceClientOrNull,
  getInterfaceClientOrNullAt,
  getInterfacePointer,
  getList,
  getListByteLength,
  getListElementByteLength,
  getListElementSize,
  getListLength,
  getOffsetWords,
  getPointer,
  getPointerAs,
  getPointerSection,
  getPointerType,
  getSize,
  getStruct,
  getStructDataWords,
  getStructPointerLength,
  getStructSize,
  getTargetCompositeListSize,
  getTargetCompositeListTag,
  getTargetListElementSize,
  getTargetListLength,
  getTargetPointerType,
  getTargetStructSize,
  getText,
  getUint16,
  getUint32,
  getUint64,
  getUint8,
  initData,
  initList,
  initPointer,
  initStruct,
  initStructAt,
  isDoubleFar,
  isNull,
  relocateTo,
  resize,
  setBit,
  setFarPointer,
  setFloat32,
  setFloat64,
  setInt16,
  setInt32,
  setInt64,
  setInt8,
  setInterfacePointer,
  setListPointer,
  setStructPointer,
  setText,
  setUint16,
  setUint32,
  setUint64,
  setUint8,
  testWhich,
  trackPointerAllocation,
  validate
};
function PointerList(PointerClass) {
  return class extends List {
    static _capnp = {
      displayName: `List<${PointerClass._capnp.displayName}>`,
      size: ListElementSize.POINTER
    };
    get(index) {
      const c2 = getContent(this);
      return new PointerClass(
        c2.segment,
        c2.byteOffset + index * 8,
        this._capnp.depthLimit - 1
      );
    }
    set(index, value) {
      copyFrom(value, this.get(index));
    }
    [Symbol.toStringTag]() {
      return `Pointer_${super.toString()},cls:${PointerClass.toString()}`;
    }
  };
}
var AnyPointerList = PointerList(Pointer);
var BoolList = class extends List {
  static _capnp = {
    displayName: "List<boolean>",
    size: ListElementSize.BIT
  };
  get(index) {
    const bitMask = 1 << index % 8;
    const byteOffset = index >>> 3;
    const c2 = getContent(this);
    const v = c2.segment.getUint8(c2.byteOffset + byteOffset);
    return (v & bitMask) !== 0;
  }
  set(index, value) {
    const bitMask = 1 << index % 8;
    const c2 = getContent(this);
    const byteOffset = c2.byteOffset + (index >>> 3);
    const v = c2.segment.getUint8(byteOffset);
    c2.segment.setUint8(byteOffset, value ? v | bitMask : v & ~bitMask);
  }
  [Symbol.toStringTag]() {
    return `Bool_${super.toString()}`;
  }
};
var DataList = PointerList(Data);
var Float32List = class extends List {
  static _capnp = {
    displayName: "List<Float32>",
    size: ListElementSize.BYTE_4
  };
  get(index) {
    const c2 = getContent(this);
    return c2.segment.getFloat32(c2.byteOffset + index * 4);
  }
  set(index, value) {
    const c2 = getContent(this);
    c2.segment.setFloat32(c2.byteOffset + index * 4, value);
  }
  [Symbol.toStringTag]() {
    return `Float32_${super.toString()}`;
  }
};
var Float64List = class extends List {
  static _capnp = {
    displayName: "List<Float64>",
    size: ListElementSize.BYTE_8
  };
  get(index) {
    const c2 = getContent(this);
    return c2.segment.getFloat64(c2.byteOffset + index * 8);
  }
  set(index, value) {
    const c2 = getContent(this);
    c2.segment.setFloat64(c2.byteOffset + index * 8, value);
  }
  [Symbol.toStringTag]() {
    return `Float64_${super.toString()}`;
  }
};
var Int8List = class extends List {
  static _capnp = {
    displayName: "List<Int8>",
    size: ListElementSize.BYTE
  };
  get(index) {
    const c2 = getContent(this);
    return c2.segment.getInt8(c2.byteOffset + index);
  }
  set(index, value) {
    const c2 = getContent(this);
    c2.segment.setInt8(c2.byteOffset + index, value);
  }
  [Symbol.toStringTag]() {
    return `Int8_${super.toString()}`;
  }
};
var Int16List = class extends List {
  static _capnp = {
    displayName: "List<Int16>",
    size: ListElementSize.BYTE_2
  };
  get(index) {
    const c2 = getContent(this);
    return c2.segment.getInt16(c2.byteOffset + index * 2);
  }
  set(index, value) {
    const c2 = getContent(this);
    c2.segment.setInt16(c2.byteOffset + index * 2, value);
  }
  [Symbol.toStringTag]() {
    return `Int16_${super.toString()}`;
  }
};
var Int32List = class extends List {
  static _capnp = {
    displayName: "List<Int32>",
    size: ListElementSize.BYTE_4
  };
  get(index) {
    const c2 = getContent(this);
    return c2.segment.getInt32(c2.byteOffset + index * 4);
  }
  set(index, value) {
    const c2 = getContent(this);
    c2.segment.setInt32(c2.byteOffset + index * 4, value);
  }
  [Symbol.toStringTag]() {
    return `Int32_${super.toString()}`;
  }
};
var Int64List = class extends List {
  static _capnp = {
    displayName: "List<Int64>",
    size: ListElementSize.BYTE_8
  };
  get(index) {
    const c2 = getContent(this);
    return c2.segment.getInt64(c2.byteOffset + index * 8);
  }
  set(index, value) {
    const c2 = getContent(this);
    c2.segment.setInt64(c2.byteOffset + index * 8, value);
  }
  [Symbol.toStringTag]() {
    return `Int64_${super.toString()}`;
  }
};
var InterfaceList = PointerList(Interface);
var TextList = class extends List {
  static _capnp = {
    displayName: "List<Text>",
    size: ListElementSize.POINTER
  };
  get(index) {
    const c2 = getContent(this);
    c2.byteOffset += index * 8;
    return Text.fromPointer(c2).get(0);
  }
  set(index, value) {
    const c2 = getContent(this);
    c2.byteOffset += index * 8;
    Text.fromPointer(c2).set(0, value);
  }
  [Symbol.toStringTag]() {
    return `Text_${super.toString()}`;
  }
};
var Uint8List = class extends List {
  static _capnp = {
    displayName: "List<Uint8>",
    size: ListElementSize.BYTE
  };
  get(index) {
    const c2 = getContent(this);
    return c2.segment.getUint8(c2.byteOffset + index);
  }
  set(index, value) {
    const c2 = getContent(this);
    c2.segment.setUint8(c2.byteOffset + index, value);
  }
  [Symbol.toStringTag]() {
    return `Uint8_${super.toString()}`;
  }
};
var Uint16List = class extends List {
  static _capnp = {
    displayName: "List<Uint16>",
    size: ListElementSize.BYTE_2
  };
  get(index) {
    const c2 = getContent(this);
    return c2.segment.getUint16(c2.byteOffset + index * 2);
  }
  set(index, value) {
    const c2 = getContent(this);
    c2.segment.setUint16(c2.byteOffset + index * 2, value);
  }
  [Symbol.toStringTag]() {
    return `Uint16_${super.toString()}`;
  }
};
var Uint32List = class extends List {
  static _capnp = {
    displayName: "List<Uint32>",
    size: ListElementSize.BYTE_4
  };
  get(index) {
    const c2 = getContent(this);
    return c2.segment.getUint32(c2.byteOffset + index * 4);
  }
  set(index, value) {
    const c2 = getContent(this);
    c2.segment.setUint32(c2.byteOffset + index * 4, value);
  }
  [Symbol.toStringTag]() {
    return `Uint32_${super.toString()}`;
  }
};
var Uint64List = class extends List {
  static _capnp = {
    displayName: "List<Uint64>",
    size: ListElementSize.BYTE_8
  };
  get(index) {
    const c2 = getContent(this);
    return c2.segment.getUint64(c2.byteOffset + index * 8);
  }
  set(index, value) {
    const c2 = getContent(this);
    c2.segment.setUint64(c2.byteOffset + index * 8, value);
  }
  [Symbol.toStringTag]() {
    return `Uint64_${super.toString()}`;
  }
};
var VoidList = PointerList(Void);
var ConnWeakRefRegistry = globalThis.FinalizationRegistry ? new FinalizationRegistry((cb) => cb()) : void 0;

// src/runtime/config/generated/workerd.ts
var Config = class _Config extends Struct {
  static _capnp = {
    displayName: "Config",
    id: "8794486c76aaa7d6",
    size: new ObjectSize(8, 6),
    defaultStructuredLogging: getBitMask(false, 0)
  };
  static _Services;
  static _Sockets;
  static _Extensions;
  _adoptServices(value) {
    utils.adopt(value, utils.getPointer(0, this));
  }
  _disownServices() {
    return utils.disown(this.services);
  }
  /**
   * List of named services defined by this server. These names are private; they are only used
   * to refer to the services from elsewhere in this config file, as well as for logging and the
   * like. Services are not reachable until you configure some way to make them reachable, such
   * as via a Socket.
   *
   * If you do not define any service called "internet", one is defined implicitly, representing
   * the ability to access public internet servers. An explicit definition would look like:
   *
   *     ( name = "internet",
   *       network = (
   *         allow = ["public"],   # Allows connections to publicly-routable addresses only.
   *         tlsOptions = (trustBrowserCas = true)
   *       )
   *     )
   *
   * The "internet" service backs the global `fetch()` function in a Worker, unless that Worker's
   * configuration specifies some other service using the `globalOutbound` setting.
   *
   */
  get services() {
    return utils.getList(0, _Config._Services, this);
  }
  _hasServices() {
    return !utils.isNull(utils.getPointer(0, this));
  }
  _initServices(length) {
    return utils.initList(0, _Config._Services, length, this);
  }
  set services(value) {
    utils.copyFrom(value, utils.getPointer(0, this));
  }
  _adoptSockets(value) {
    utils.adopt(value, utils.getPointer(1, this));
  }
  _disownSockets() {
    return utils.disown(this.sockets);
  }
  /**
   * List of sockets on which this server will listen, and the services that will be exposed
   * through them.
   *
   */
  get sockets() {
    return utils.getList(1, _Config._Sockets, this);
  }
  _hasSockets() {
    return !utils.isNull(utils.getPointer(1, this));
  }
  _initSockets(length) {
    return utils.initList(1, _Config._Sockets, length, this);
  }
  set sockets(value) {
    utils.copyFrom(value, utils.getPointer(1, this));
  }
  _adoptV8Flags(value) {
    utils.adopt(value, utils.getPointer(2, this));
  }
  _disownV8Flags() {
    return utils.disown(this.v8Flags);
  }
  /**
   * List of "command-line" flags to pass to V8, like "--expose-gc". We put these in the config
   * rather than on the actual command line because for most use cases, managing these via the
   * config file is probably cleaner and easier than passing on the actual CLI.
   *
   * WARNING: Use at your own risk. V8 flags can have all sorts of wild effects including completely
   *   breaking everything. V8 flags also generally do not come with any guarantee of stability
   *   between V8 versions. Most users should not set any V8 flags.
   *
   */
  get v8Flags() {
    return utils.getList(2, TextList, this);
  }
  _hasV8Flags() {
    return !utils.isNull(utils.getPointer(2, this));
  }
  _initV8Flags(length) {
    return utils.initList(2, TextList, length, this);
  }
  set v8Flags(value) {
    utils.copyFrom(value, utils.getPointer(2, this));
  }
  _adoptExtensions(value) {
    utils.adopt(value, utils.getPointer(3, this));
  }
  _disownExtensions() {
    return utils.disown(this.extensions);
  }
  /**
   * Extensions provide capabilities to all workers. Extensions are usually prepared separately
   * and are late-linked with the app using this config field.
   *
   */
  get extensions() {
    return utils.getList(3, _Config._Extensions, this);
  }
  _hasExtensions() {
    return !utils.isNull(utils.getPointer(3, this));
  }
  _initExtensions(length) {
    return utils.initList(3, _Config._Extensions, length, this);
  }
  set extensions(value) {
    utils.copyFrom(value, utils.getPointer(3, this));
  }
  _adoptAutogates(value) {
    utils.adopt(value, utils.getPointer(4, this));
  }
  _disownAutogates() {
    return utils.disown(this.autogates);
  }
  /**
   * A list of gates which are enabled.
   * These are used to gate features/changes in workerd and in our internal repo. See the equivalent
   * config definition in our internal repo for more details.
   *
   */
  get autogates() {
    return utils.getList(4, TextList, this);
  }
  _hasAutogates() {
    return !utils.isNull(utils.getPointer(4, this));
  }
  _initAutogates(length) {
    return utils.initList(4, TextList, length, this);
  }
  set autogates(value) {
    utils.copyFrom(value, utils.getPointer(4, this));
  }
  /**
   * If true, logs will be emitted as JSON for structured logging.
   * When false, logs use the traditional human-readable format.
   * This affects the format of logs from KJ_LOG and exception reporting as well as js logs.
   * This won't work for logs coming from service worker syntax workers with the old module registry.
   * Note: This field is obsolete and deprecated. Use the logging struct instead.
   *
   */
  get structuredLogging() {
    return utils.getBit(0, this, _Config._capnp.defaultStructuredLogging);
  }
  set structuredLogging(value) {
    utils.setBit(0, value, this, _Config._capnp.defaultStructuredLogging);
  }
  _adoptLogging(value) {
    utils.adopt(value, utils.getPointer(5, this));
  }
  _disownLogging() {
    return utils.disown(this.logging);
  }
  /**
   * Console and Stdio logging configuration options.
   *
   */
  get logging() {
    return utils.getStruct(5, LoggingOptions, this);
  }
  _hasLogging() {
    return !utils.isNull(utils.getPointer(5, this));
  }
  _initLogging() {
    return utils.initStructAt(5, LoggingOptions, this);
  }
  set logging(value) {
    utils.copyFrom(value, utils.getPointer(5, this));
  }
  toString() {
    return "Config_" + super.toString();
  }
};
var LoggingOptions = class _LoggingOptions extends Struct {
  static _capnp = {
    displayName: "LoggingOptions",
    id: "c62297899c35d548",
    size: new ObjectSize(8, 2),
    defaultStructuredLogging: getBitMask(false, 0)
  };
  /**
   * Override of top-level structured logging (only when true).
   * If true, logs will be emitted as JSON for structured logging.
   * When false, logs use the traditional human-readable format.
   * This affects the format of logs from KJ_LOG and exception reporting as well as js logs.
   * This won't work for logs coming from service worker syntax workers with the old module registry.
   *
   */
  get structuredLogging() {
    return utils.getBit(
      0,
      this,
      _LoggingOptions._capnp.defaultStructuredLogging
    );
  }
  set structuredLogging(value) {
    utils.setBit(
      0,
      value,
      this,
      _LoggingOptions._capnp.defaultStructuredLogging
    );
  }
  /**
   * Set a custom prefix for process.stdout. Defaults to "stdout: ".
   *
   */
  get stdoutPrefix() {
    return utils.getText(0, this);
  }
  set stdoutPrefix(value) {
    utils.setText(0, value, this);
  }
  /**
   * Set a custom prefix for process.stderr. Defaults to "stderr: ".
   *
   */
  get stderrPrefix() {
    return utils.getText(1, this);
  }
  set stderrPrefix(value) {
    utils.setText(1, value, this);
  }
  toString() {
    return "LoggingOptions_" + super.toString();
  }
};
var Socket_Https = class extends Struct {
  static _capnp = {
    displayName: "https",
    id: "de123876383cbbdc",
    size: new ObjectSize(8, 5)
  };
  _adoptOptions(value) {
    utils.adopt(value, utils.getPointer(2, this));
  }
  _disownOptions() {
    return utils.disown(this.options);
  }
  get options() {
    return utils.getStruct(2, HttpOptions, this);
  }
  _hasOptions() {
    return !utils.isNull(utils.getPointer(2, this));
  }
  _initOptions() {
    return utils.initStructAt(2, HttpOptions, this);
  }
  set options(value) {
    utils.copyFrom(value, utils.getPointer(2, this));
  }
  _adoptTlsOptions(value) {
    utils.adopt(value, utils.getPointer(3, this));
  }
  _disownTlsOptions() {
    return utils.disown(this.tlsOptions);
  }
  get tlsOptions() {
    return utils.getStruct(3, TlsOptions, this);
  }
  _hasTlsOptions() {
    return !utils.isNull(utils.getPointer(3, this));
  }
  _initTlsOptions() {
    return utils.initStructAt(3, TlsOptions, this);
  }
  set tlsOptions(value) {
    utils.copyFrom(value, utils.getPointer(3, this));
  }
  toString() {
    return "Socket_Https_" + super.toString();
  }
};
var Socket_Tcp = class extends Struct {
  static _capnp = {
    displayName: "tcp",
    id: "b59d8ecf6886b64c",
    size: new ObjectSize(8, 5)
  };
  _adoptTlsOptions(value) {
    utils.adopt(value, utils.getPointer(2, this));
  }
  _disownTlsOptions() {
    return utils.disown(this.tlsOptions);
  }
  get tlsOptions() {
    return utils.getStruct(2, TlsOptions, this);
  }
  _hasTlsOptions() {
    return !utils.isNull(utils.getPointer(2, this));
  }
  _initTlsOptions() {
    return utils.initStructAt(2, TlsOptions, this);
  }
  set tlsOptions(value) {
    utils.copyFrom(value, utils.getPointer(2, this));
  }
  toString() {
    return "Socket_Tcp_" + super.toString();
  }
};
var Socket_Which = {
  HTTP: 0,
  HTTPS: 1,
  TCP: 2
};
var Socket = class extends Struct {
  static HTTP = Socket_Which.HTTP;
  static HTTPS = Socket_Which.HTTPS;
  static TCP = Socket_Which.TCP;
  static _capnp = {
    displayName: "Socket",
    id: "9a0eba45530ee79f",
    size: new ObjectSize(8, 5)
  };
  /**
   * Each socket has a unique name which can be used on the command line to override the socket's
   * address with `--socket-addr <name>=<addr>` or `--socket-fd <name>=<fd>`.
   *
   */
  get name() {
    return utils.getText(0, this);
  }
  set name(value) {
    utils.setText(0, value, this);
  }
  /**
   * Address/port on which this socket will listen. Optional; if not specified, then you will be
   * required to specify the socket on the command line with with `--socket-addr <name>=<addr>` or
   * `--socket-fd <name>=<fd>`.
   *
   * Examples:
   * - "*:80": Listen on port 80 on all local IPv4 and IPv6 interfaces.
   * - "1.2.3.4": Listen on the specific IPv4 address on the default port for the protocol.
   * - "1.2.3.4:80": Listen on the specific IPv4 address and port.
   * - "1234:5678::abcd": Listen on the specific IPv6 address on the default port for the protocol.
   * - "[1234:5678::abcd]:80": Listen on the specific IPv6 address and port.
   * - "unix:/path/to/socket": Listen on a Unix socket.
   * - "unix-abstract:name": On Linux, listen on the given "abstract" Unix socket name.
   * - "example.com:80": Perform a DNS lookup to determine the address, and then listen on it. If
   *     this resolves to multiple addresses, listen on all of them.
   *
   * (These are the formats supported by KJ's parseAddress().)
   *
   */
  get address() {
    return utils.getText(1, this);
  }
  set address(value) {
    utils.setText(1, value, this);
  }
  _adoptHttp(value) {
    utils.setUint16(0, 0, this);
    utils.adopt(value, utils.getPointer(2, this));
  }
  _disownHttp() {
    return utils.disown(this.http);
  }
  get http() {
    utils.testWhich("http", utils.getUint16(0, this), 0, this);
    return utils.getStruct(2, HttpOptions, this);
  }
  _hasHttp() {
    return !utils.isNull(utils.getPointer(2, this));
  }
  _initHttp() {
    utils.setUint16(0, 0, this);
    return utils.initStructAt(2, HttpOptions, this);
  }
  get _isHttp() {
    return utils.getUint16(0, this) === 0;
  }
  set http(value) {
    utils.setUint16(0, 0, this);
    utils.copyFrom(value, utils.getPointer(2, this));
  }
  get https() {
    utils.testWhich("https", utils.getUint16(0, this), 1, this);
    return utils.getAs(Socket_Https, this);
  }
  _initHttps() {
    utils.setUint16(0, 1, this);
    return utils.getAs(Socket_Https, this);
  }
  get _isHttps() {
    return utils.getUint16(0, this) === 1;
  }
  set https(_) {
    utils.setUint16(0, 1, this);
  }
  get tcp() {
    utils.testWhich("tcp", utils.getUint16(0, this), 2, this);
    return utils.getAs(Socket_Tcp, this);
  }
  _initTcp() {
    utils.setUint16(0, 2, this);
    return utils.getAs(Socket_Tcp, this);
  }
  get _isTcp() {
    return utils.getUint16(0, this) === 2;
  }
  set tcp(_) {
    utils.setUint16(0, 2, this);
  }
  _adoptService(value) {
    utils.adopt(value, utils.getPointer(4, this));
  }
  _disownService() {
    return utils.disown(this.service);
  }
  /**
   * Service name which should handle requests on this socket.
   *
   */
  get service() {
    return utils.getStruct(4, ServiceDesignator, this);
  }
  _hasService() {
    return !utils.isNull(utils.getPointer(4, this));
  }
  _initService() {
    return utils.initStructAt(4, ServiceDesignator, this);
  }
  set service(value) {
    utils.copyFrom(value, utils.getPointer(4, this));
  }
  toString() {
    return "Socket_" + super.toString();
  }
  which() {
    return utils.getUint16(0, this);
  }
};
var Service_Which = {
  /**
   * (This catches when someone forgets to specify one of the union members. Do not set this.)
   *
   */
  UNSPECIFIED: 0,
  /**
   * A Worker!
   *
   */
  WORKER: 1,
  /**
   * A service that implements access to a network. fetch() requests are routed according to
   * the URL hostname.
   *
   */
  NETWORK: 2,
  /**
   * A service that forwards all requests to a specific remote server. Typically used to
   * connect to a back-end server on your internal network.
   *
   */
  EXTERNAL: 3,
  /**
   * An HTTP service backed by a directory on disk, supporting a basic HTTP GET/PUT. Generally
   * not intended to be exposed directly to the internet; typically you want to bind this into
   * a Worker that adds logic for setting Content-Type and the like.
   *
   */
  DISK: 4
};
var Service = class extends Struct {
  static UNSPECIFIED = Service_Which.UNSPECIFIED;
  static WORKER = Service_Which.WORKER;
  static NETWORK = Service_Which.NETWORK;
  static EXTERNAL = Service_Which.EXTERNAL;
  static DISK = Service_Which.DISK;
  static _capnp = {
    displayName: "Service",
    id: "e5c88e8bb7bcb6b9",
    size: new ObjectSize(8, 2)
  };
  /**
   * Name of the service. Used only to refer to the service from elsewhere in the config file.
   * Services are not accessible unless you explicitly configure them to be, such as through a
   * `Socket` or through a binding from another Worker.
   *
   */
  get name() {
    return utils.getText(0, this);
  }
  set name(value) {
    utils.setText(0, value, this);
  }
  get _isUnspecified() {
    return utils.getUint16(0, this) === 0;
  }
  set unspecified(_) {
    utils.setUint16(0, 0, this);
  }
  _adoptWorker(value) {
    utils.setUint16(0, 1, this);
    utils.adopt(value, utils.getPointer(1, this));
  }
  _disownWorker() {
    return utils.disown(this.worker);
  }
  /**
   * A Worker!
   *
   */
  get worker() {
    utils.testWhich("worker", utils.getUint16(0, this), 1, this);
    return utils.getStruct(1, Worker, this);
  }
  _hasWorker() {
    return !utils.isNull(utils.getPointer(1, this));
  }
  _initWorker() {
    utils.setUint16(0, 1, this);
    return utils.initStructAt(1, Worker, this);
  }
  get _isWorker() {
    return utils.getUint16(0, this) === 1;
  }
  set worker(value) {
    utils.setUint16(0, 1, this);
    utils.copyFrom(value, utils.getPointer(1, this));
  }
  _adoptNetwork(value) {
    utils.setUint16(0, 2, this);
    utils.adopt(value, utils.getPointer(1, this));
  }
  _disownNetwork() {
    return utils.disown(this.network);
  }
  /**
   * A service that implements access to a network. fetch() requests are routed according to
   * the URL hostname.
   *
   */
  get network() {
    utils.testWhich("network", utils.getUint16(0, this), 2, this);
    return utils.getStruct(1, Network, this);
  }
  _hasNetwork() {
    return !utils.isNull(utils.getPointer(1, this));
  }
  _initNetwork() {
    utils.setUint16(0, 2, this);
    return utils.initStructAt(1, Network, this);
  }
  get _isNetwork() {
    return utils.getUint16(0, this) === 2;
  }
  set network(value) {
    utils.setUint16(0, 2, this);
    utils.copyFrom(value, utils.getPointer(1, this));
  }
  _adoptExternal(value) {
    utils.setUint16(0, 3, this);
    utils.adopt(value, utils.getPointer(1, this));
  }
  _disownExternal() {
    return utils.disown(this.external);
  }
  /**
   * A service that forwards all requests to a specific remote server. Typically used to
   * connect to a back-end server on your internal network.
   *
   */
  get external() {
    utils.testWhich("external", utils.getUint16(0, this), 3, this);
    return utils.getStruct(1, ExternalServer, this);
  }
  _hasExternal() {
    return !utils.isNull(utils.getPointer(1, this));
  }
  _initExternal() {
    utils.setUint16(0, 3, this);
    return utils.initStructAt(1, ExternalServer, this);
  }
  get _isExternal() {
    return utils.getUint16(0, this) === 3;
  }
  set external(value) {
    utils.setUint16(0, 3, this);
    utils.copyFrom(value, utils.getPointer(1, this));
  }
  _adoptDisk(value) {
    utils.setUint16(0, 4, this);
    utils.adopt(value, utils.getPointer(1, this));
  }
  _disownDisk() {
    return utils.disown(this.disk);
  }
  /**
   * An HTTP service backed by a directory on disk, supporting a basic HTTP GET/PUT. Generally
   * not intended to be exposed directly to the internet; typically you want to bind this into
   * a Worker that adds logic for setting Content-Type and the like.
   *
   */
  get disk() {
    utils.testWhich("disk", utils.getUint16(0, this), 4, this);
    return utils.getStruct(1, DiskDirectory, this);
  }
  _hasDisk() {
    return !utils.isNull(utils.getPointer(1, this));
  }
  _initDisk() {
    utils.setUint16(0, 4, this);
    return utils.initStructAt(1, DiskDirectory, this);
  }
  get _isDisk() {
    return utils.getUint16(0, this) === 4;
  }
  set disk(value) {
    utils.setUint16(0, 4, this);
    utils.copyFrom(value, utils.getPointer(1, this));
  }
  toString() {
    return "Service_" + super.toString();
  }
  which() {
    return utils.getUint16(0, this);
  }
};
var ServiceDesignator_Props_Which = {
  /**
   * Empty object. (This is the default.)
   *
   */
  EMPTY: 0,
  /**
   * A JSON-encoded value.
   *
   */
  JSON: 1
};
var ServiceDesignator_Props = class extends Struct {
  static EMPTY = ServiceDesignator_Props_Which.EMPTY;
  static JSON = ServiceDesignator_Props_Which.JSON;
  static _capnp = {
    displayName: "props",
    id: "f0dc90173b494522",
    size: new ObjectSize(8, 3)
  };
  get _isEmpty() {
    return utils.getUint16(0, this) === 0;
  }
  set empty(_) {
    utils.setUint16(0, 0, this);
  }
  /**
   * A JSON-encoded value.
   *
   */
  get json() {
    utils.testWhich("json", utils.getUint16(0, this), 1, this);
    return utils.getText(2, this);
  }
  get _isJson() {
    return utils.getUint16(0, this) === 1;
  }
  set json(value) {
    utils.setUint16(0, 1, this);
    utils.setText(2, value, this);
  }
  toString() {
    return "ServiceDesignator_Props_" + super.toString();
  }
  which() {
    return utils.getUint16(0, this);
  }
};
var ServiceDesignator = class extends Struct {
  static _capnp = {
    displayName: "ServiceDesignator",
    id: "ae8ec91cee724450",
    size: new ObjectSize(8, 3)
  };
  /**
   * Name of the service in the Config.services list.
   *
   */
  get name() {
    return utils.getText(0, this);
  }
  set name(value) {
    utils.setText(0, value, this);
  }
  /**
   * A modules-syntax Worker can export multiple named entrypoints. `export default {` specifies
   * the default entrypoint, whereas `export let foo = {` defines an entrypoint named `foo`. If
   * `entrypoint` is specified here, it names an alternate entrypoint to use on the target worker,
   * otherwise the default is used.
   *
   */
  get entrypoint() {
    return utils.getText(1, this);
  }
  set entrypoint(value) {
    utils.setText(1, value, this);
  }
  /**
   * Value to provide in `ctx.props` in the target worker.
   *
   */
  get props() {
    return utils.getAs(ServiceDesignator_Props, this);
  }
  _initProps() {
    return utils.getAs(ServiceDesignator_Props, this);
  }
  toString() {
    return "ServiceDesignator_" + super.toString();
  }
};
var Worker_Module_Which = {
  /**
   * An ES module file with imports and exports.
   *
   * As with `serviceWorkerScript`, above, the value is the raw source code.
   *
   */
  ES_MODULE: 0,
  /**
   * A common JS module, using require().
   *
   */
  COMMON_JS_MODULE: 1,
  /**
   * A raw text blob. Importing this will produce a string with the value.
   *
   */
  TEXT: 2,
  /**
   * A raw data blob. Importing this will produce an ArrayBuffer with the value.
   *
   */
  DATA: 3,
  /**
   * A Wasm module. The value is a compiled binary Wasm module file. Importing this will produce
   * a `WebAssembly.Module` object, which you can then instantiate.
   *
   */
  WASM: 4,
  /**
   * Importing this will produce the result of parsing the given text as JSON.
   *
   */
  JSON: 5,
  /**
   * This position used to be the nodeJsCompatModule type that has now been
   * obsoleted.
   *
   */
  OBSOLETE: 6,
  /**
   * A Python module. All bundles containing this value type are converted into a JS/WASM Worker
   * Bundle prior to execution.
   *
   */
  PYTHON_MODULE: 7,
  /**
   * This position used to be the pythonRequirement type that has now been deprecated.
   *
   */
  OBSOLETE_PYTHON_REQUIREMENT: 8
};
var Worker_Module = class extends Struct {
  static ES_MODULE = Worker_Module_Which.ES_MODULE;
  static COMMON_JS_MODULE = Worker_Module_Which.COMMON_JS_MODULE;
  static TEXT = Worker_Module_Which.TEXT;
  static DATA = Worker_Module_Which.DATA;
  static WASM = Worker_Module_Which.WASM;
  static JSON = Worker_Module_Which.JSON;
  static OBSOLETE = Worker_Module_Which.OBSOLETE;
  static PYTHON_MODULE = Worker_Module_Which.PYTHON_MODULE;
  static OBSOLETE_PYTHON_REQUIREMENT = Worker_Module_Which.OBSOLETE_PYTHON_REQUIREMENT;
  static _capnp = {
    displayName: "Module",
    id: "d9d87a63770a12f3",
    size: new ObjectSize(8, 3)
  };
  /**
   * Name (or path) used to import the module.
   *
   */
  get name() {
    return utils.getText(0, this);
  }
  set name(value) {
    utils.setText(0, value, this);
  }
  /**
   * An ES module file with imports and exports.
   *
   * As with `serviceWorkerScript`, above, the value is the raw source code.
   *
   */
  get esModule() {
    utils.testWhich("esModule", utils.getUint16(0, this), 0, this);
    return utils.getText(1, this);
  }
  get _isEsModule() {
    return utils.getUint16(0, this) === 0;
  }
  set esModule(value) {
    utils.setUint16(0, 0, this);
    utils.setText(1, value, this);
  }
  /**
   * A common JS module, using require().
   *
   */
  get commonJsModule() {
    utils.testWhich("commonJsModule", utils.getUint16(0, this), 1, this);
    return utils.getText(1, this);
  }
  get _isCommonJsModule() {
    return utils.getUint16(0, this) === 1;
  }
  set commonJsModule(value) {
    utils.setUint16(0, 1, this);
    utils.setText(1, value, this);
  }
  /**
   * A raw text blob. Importing this will produce a string with the value.
   *
   */
  get text() {
    utils.testWhich("text", utils.getUint16(0, this), 2, this);
    return utils.getText(1, this);
  }
  get _isText() {
    return utils.getUint16(0, this) === 2;
  }
  set text(value) {
    utils.setUint16(0, 2, this);
    utils.setText(1, value, this);
  }
  _adoptData(value) {
    utils.setUint16(0, 3, this);
    utils.adopt(value, utils.getPointer(1, this));
  }
  _disownData() {
    return utils.disown(this.data);
  }
  /**
   * A raw data blob. Importing this will produce an ArrayBuffer with the value.
   *
   */
  get data() {
    utils.testWhich("data", utils.getUint16(0, this), 3, this);
    return utils.getData(1, this);
  }
  _hasData() {
    return !utils.isNull(utils.getPointer(1, this));
  }
  _initData(length) {
    utils.setUint16(0, 3, this);
    return utils.initData(1, length, this);
  }
  get _isData() {
    return utils.getUint16(0, this) === 3;
  }
  set data(value) {
    utils.setUint16(0, 3, this);
    utils.copyFrom(value, utils.getPointer(1, this));
  }
  _adoptWasm(value) {
    utils.setUint16(0, 4, this);
    utils.adopt(value, utils.getPointer(1, this));
  }
  _disownWasm() {
    return utils.disown(this.wasm);
  }
  /**
   * A Wasm module. The value is a compiled binary Wasm module file. Importing this will produce
   * a `WebAssembly.Module` object, which you can then instantiate.
   *
   */
  get wasm() {
    utils.testWhich("wasm", utils.getUint16(0, this), 4, this);
    return utils.getData(1, this);
  }
  _hasWasm() {
    return !utils.isNull(utils.getPointer(1, this));
  }
  _initWasm(length) {
    utils.setUint16(0, 4, this);
    return utils.initData(1, length, this);
  }
  get _isWasm() {
    return utils.getUint16(0, this) === 4;
  }
  set wasm(value) {
    utils.setUint16(0, 4, this);
    utils.copyFrom(value, utils.getPointer(1, this));
  }
  /**
   * Importing this will produce the result of parsing the given text as JSON.
   *
   */
  get json() {
    utils.testWhich("json", utils.getUint16(0, this), 5, this);
    return utils.getText(1, this);
  }
  get _isJson() {
    return utils.getUint16(0, this) === 5;
  }
  set json(value) {
    utils.setUint16(0, 5, this);
    utils.setText(1, value, this);
  }
  /**
   * This position used to be the nodeJsCompatModule type that has now been
   * obsoleted.
   *
   */
  get obsolete() {
    utils.testWhich("obsolete", utils.getUint16(0, this), 6, this);
    return utils.getText(1, this);
  }
  get _isObsolete() {
    return utils.getUint16(0, this) === 6;
  }
  set obsolete(value) {
    utils.setUint16(0, 6, this);
    utils.setText(1, value, this);
  }
  /**
   * A Python module. All bundles containing this value type are converted into a JS/WASM Worker
   * Bundle prior to execution.
   *
   */
  get pythonModule() {
    utils.testWhich("pythonModule", utils.getUint16(0, this), 7, this);
    return utils.getText(1, this);
  }
  get _isPythonModule() {
    return utils.getUint16(0, this) === 7;
  }
  set pythonModule(value) {
    utils.setUint16(0, 7, this);
    utils.setText(1, value, this);
  }
  /**
   * This position used to be the pythonRequirement type that has now been deprecated.
   *
   */
  get obsoletePythonRequirement() {
    utils.testWhich(
      "obsoletePythonRequirement",
      utils.getUint16(0, this),
      8,
      this
    );
    return utils.getText(1, this);
  }
  get _isObsoletePythonRequirement() {
    return utils.getUint16(0, this) === 8;
  }
  set obsoletePythonRequirement(value) {
    utils.setUint16(0, 8, this);
    utils.setText(1, value, this);
  }
  _adoptNamedExports(value) {
    utils.adopt(value, utils.getPointer(2, this));
  }
  _disownNamedExports() {
    return utils.disown(this.namedExports);
  }
  /**
   * For commonJsModule modules, this is a list of named exports that the
   * module expects to be exported once the evaluation is complete.
   *
   * (`commonJsModule` should have been a group containing the body and `namedExports`, but it's
   * too late to change now.)
   *
   */
  get namedExports() {
    return utils.getList(2, TextList, this);
  }
  _hasNamedExports() {
    return !utils.isNull(utils.getPointer(2, this));
  }
  _initNamedExports(length) {
    return utils.initList(2, TextList, length, this);
  }
  set namedExports(value) {
    utils.copyFrom(value, utils.getPointer(2, this));
  }
  toString() {
    return "Worker_Module_" + super.toString();
  }
  which() {
    return utils.getUint16(0, this);
  }
};
var Worker_Binding_Type_Which = {
  /**
   * (This catches when someone forgets to specify one of the union members. Do not set this.)
   *
   */
  UNSPECIFIED: 0,
  TEXT: 1,
  DATA: 2,
  JSON: 3,
  WASM: 4,
  CRYPTO_KEY: 5,
  SERVICE: 6,
  DURABLE_OBJECT_NAMESPACE: 7,
  KV_NAMESPACE: 8,
  R2BUCKET: 9,
  OBSOLETE0: 10,
  QUEUE: 11,
  ANALYTICS_ENGINE: 12,
  HYPERDRIVE: 13,
  DURABLE_OBJECT_CLASS: 14,
  WORKERD_DEBUG_PORT: 15
};
var Worker_Binding_Type = class extends Struct {
  static UNSPECIFIED = Worker_Binding_Type_Which.UNSPECIFIED;
  static TEXT = Worker_Binding_Type_Which.TEXT;
  static DATA = Worker_Binding_Type_Which.DATA;
  static JSON = Worker_Binding_Type_Which.JSON;
  static WASM = Worker_Binding_Type_Which.WASM;
  static CRYPTO_KEY = Worker_Binding_Type_Which.CRYPTO_KEY;
  static SERVICE = Worker_Binding_Type_Which.SERVICE;
  static DURABLE_OBJECT_NAMESPACE = Worker_Binding_Type_Which.DURABLE_OBJECT_NAMESPACE;
  static KV_NAMESPACE = Worker_Binding_Type_Which.KV_NAMESPACE;
  static R2BUCKET = Worker_Binding_Type_Which.R2BUCKET;
  static OBSOLETE0 = Worker_Binding_Type_Which.OBSOLETE0;
  static QUEUE = Worker_Binding_Type_Which.QUEUE;
  static ANALYTICS_ENGINE = Worker_Binding_Type_Which.ANALYTICS_ENGINE;
  static HYPERDRIVE = Worker_Binding_Type_Which.HYPERDRIVE;
  static DURABLE_OBJECT_CLASS = Worker_Binding_Type_Which.DURABLE_OBJECT_CLASS;
  static WORKERD_DEBUG_PORT = Worker_Binding_Type_Which.WORKERD_DEBUG_PORT;
  static _capnp = {
    displayName: "Type",
    id: "8906a1296519bf8a",
    size: new ObjectSize(8, 1)
  };
  get _isUnspecified() {
    return utils.getUint16(0, this) === 0;
  }
  set unspecified(_) {
    utils.setUint16(0, 0, this);
  }
  get _isText() {
    return utils.getUint16(0, this) === 1;
  }
  set text(_) {
    utils.setUint16(0, 1, this);
  }
  get _isData() {
    return utils.getUint16(0, this) === 2;
  }
  set data(_) {
    utils.setUint16(0, 2, this);
  }
  get _isJson() {
    return utils.getUint16(0, this) === 3;
  }
  set json(_) {
    utils.setUint16(0, 3, this);
  }
  get _isWasm() {
    return utils.getUint16(0, this) === 4;
  }
  set wasm(_) {
    utils.setUint16(0, 4, this);
  }
  _adoptCryptoKey(value) {
    utils.setUint16(0, 5, this);
    utils.adopt(value, utils.getPointer(0, this));
  }
  _disownCryptoKey() {
    return utils.disown(this.cryptoKey);
  }
  get cryptoKey() {
    utils.testWhich("cryptoKey", utils.getUint16(0, this), 5, this);
    return utils.getList(
      0,
      Uint16List,
      this
    );
  }
  _hasCryptoKey() {
    return !utils.isNull(utils.getPointer(0, this));
  }
  _initCryptoKey(length) {
    utils.setUint16(0, 5, this);
    return utils.initList(
      0,
      Uint16List,
      length,
      this
    );
  }
  get _isCryptoKey() {
    return utils.getUint16(0, this) === 5;
  }
  set cryptoKey(value) {
    utils.setUint16(0, 5, this);
    utils.copyFrom(value, utils.getPointer(0, this));
  }
  get _isService() {
    return utils.getUint16(0, this) === 6;
  }
  set service(_) {
    utils.setUint16(0, 6, this);
  }
  get _isDurableObjectNamespace() {
    return utils.getUint16(0, this) === 7;
  }
  set durableObjectNamespace(_) {
    utils.setUint16(0, 7, this);
  }
  get _isKvNamespace() {
    return utils.getUint16(0, this) === 8;
  }
  set kvNamespace(_) {
    utils.setUint16(0, 8, this);
  }
  get _isR2Bucket() {
    return utils.getUint16(0, this) === 9;
  }
  set r2Bucket(_) {
    utils.setUint16(0, 9, this);
  }
  get _isObsolete0() {
    return utils.getUint16(0, this) === 10;
  }
  set obsolete0(_) {
    utils.setUint16(0, 10, this);
  }
  get _isQueue() {
    return utils.getUint16(0, this) === 11;
  }
  set queue(_) {
    utils.setUint16(0, 11, this);
  }
  get _isAnalyticsEngine() {
    return utils.getUint16(0, this) === 12;
  }
  set analyticsEngine(_) {
    utils.setUint16(0, 12, this);
  }
  get _isHyperdrive() {
    return utils.getUint16(0, this) === 13;
  }
  set hyperdrive(_) {
    utils.setUint16(0, 13, this);
  }
  get _isDurableObjectClass() {
    return utils.getUint16(0, this) === 14;
  }
  set durableObjectClass(_) {
    utils.setUint16(0, 14, this);
  }
  get _isWorkerdDebugPort() {
    return utils.getUint16(0, this) === 15;
  }
  set workerdDebugPort(_) {
    utils.setUint16(0, 15, this);
  }
  toString() {
    return "Worker_Binding_Type_" + super.toString();
  }
  which() {
    return utils.getUint16(0, this);
  }
};
var Worker_Binding_DurableObjectNamespaceDesignator = class extends Struct {
  static _capnp = {
    displayName: "DurableObjectNamespaceDesignator",
    id: "804f144ff477aac7",
    size: new ObjectSize(0, 2)
  };
  /**
   * Exported class name that implements the Durable Object.
   *
   */
  get className() {
    return utils.getText(0, this);
  }
  set className(value) {
    utils.setText(0, value, this);
  }
  /**
   * The service name of the worker that defines this class. If omitted, the current worker
   * is assumed.
   *
   * Use of this field is discouraged. Instead, when accessing a different Worker's Durable
   * Objects, specify a `service` binding to that worker, and have the worker implement an
   * appropriate API.
   *
   * (This is intentionally not a ServiceDesignator because you cannot choose an alternate
   * entrypoint here; the class name IS the entrypoint.)
   *
   */
  get serviceName() {
    return utils.getText(1, this);
  }
  set serviceName(value) {
    utils.setText(1, value, this);
  }
  toString() {
    return "Worker_Binding_DurableObjectNamespaceDesignator_" + super.toString();
  }
};
var Worker_Binding_CryptoKey_Usage = {
  ENCRYPT: 0,
  DECRYPT: 1,
  SIGN: 2,
  VERIFY: 3,
  DERIVE_KEY: 4,
  DERIVE_BITS: 5,
  WRAP_KEY: 6,
  UNWRAP_KEY: 7
};
var Worker_Binding_CryptoKey_Algorithm_Which = {
  /**
   * Just a name, like `AES-GCM`.
   *
   */
  NAME: 0,
  /**
   * An object, encoded here as JSON.
   *
   */
  JSON: 1
};
var Worker_Binding_CryptoKey_Algorithm = class extends Struct {
  static NAME = Worker_Binding_CryptoKey_Algorithm_Which.NAME;
  static JSON = Worker_Binding_CryptoKey_Algorithm_Which.JSON;
  static _capnp = {
    displayName: "algorithm",
    id: "a1a040c5e00d7021",
    size: new ObjectSize(8, 3)
  };
  /**
   * Just a name, like `AES-GCM`.
   *
   */
  get name() {
    utils.testWhich("name", utils.getUint16(2, this), 0, this);
    return utils.getText(1, this);
  }
  get _isName() {
    return utils.getUint16(2, this) === 0;
  }
  set name(value) {
    utils.setUint16(2, 0, this);
    utils.setText(1, value, this);
  }
  /**
   * An object, encoded here as JSON.
   *
   */
  get json() {
    utils.testWhich("json", utils.getUint16(2, this), 1, this);
    return utils.getText(1, this);
  }
  get _isJson() {
    return utils.getUint16(2, this) === 1;
  }
  set json(value) {
    utils.setUint16(2, 1, this);
    utils.setText(1, value, this);
  }
  toString() {
    return "Worker_Binding_CryptoKey_Algorithm_" + super.toString();
  }
  which() {
    return utils.getUint16(
      2,
      this
    );
  }
};
var Worker_Binding_CryptoKey_Which = {
  RAW: 0,
  HEX: 1,
  /**
   * Raw key material, possibly hex or base64-encoded. Use this for symmetric keys.
   *
   * Hint: `raw` would typically be used with Cap'n Proto's `embed` syntax to embed an
   * external binary key file. `hex` or `base64` could do that too but can also be specified
   * inline.
   *
   */
  BASE64: 2,
  /**
   * Private key in PEM-encoded PKCS#8 format.
   *
   */
  PKCS8: 3,
  /**
   * Public key in PEM-encoded SPKI format.
   *
   */
  SPKI: 4,
  /**
   * Key in JSON format.
   *
   */
  JWK: 5
};
var Worker_Binding_CryptoKey = class _Worker_Binding_CryptoKey extends Struct {
  static RAW = Worker_Binding_CryptoKey_Which.RAW;
  static HEX = Worker_Binding_CryptoKey_Which.HEX;
  static BASE64 = Worker_Binding_CryptoKey_Which.BASE64;
  static PKCS8 = Worker_Binding_CryptoKey_Which.PKCS8;
  static SPKI = Worker_Binding_CryptoKey_Which.SPKI;
  static JWK = Worker_Binding_CryptoKey_Which.JWK;
  static Usage = Worker_Binding_CryptoKey_Usage;
  static _capnp = {
    displayName: "CryptoKey",
    id: "b5e1bff0e57d6eb0",
    size: new ObjectSize(8, 3),
    defaultExtractable: getBitMask(false, 0)
  };
  _adoptRaw(value) {
    utils.setUint16(0, 0, this);
    utils.adopt(value, utils.getPointer(0, this));
  }
  _disownRaw() {
    return utils.disown(this.raw);
  }
  get raw() {
    utils.testWhich("raw", utils.getUint16(0, this), 0, this);
    return utils.getData(0, this);
  }
  _hasRaw() {
    return !utils.isNull(utils.getPointer(0, this));
  }
  _initRaw(length) {
    utils.setUint16(0, 0, this);
    return utils.initData(0, length, this);
  }
  get _isRaw() {
    return utils.getUint16(0, this) === 0;
  }
  set raw(value) {
    utils.setUint16(0, 0, this);
    utils.copyFrom(value, utils.getPointer(0, this));
  }
  get hex() {
    utils.testWhich("hex", utils.getUint16(0, this), 1, this);
    return utils.getText(0, this);
  }
  get _isHex() {
    return utils.getUint16(0, this) === 1;
  }
  set hex(value) {
    utils.setUint16(0, 1, this);
    utils.setText(0, value, this);
  }
  /**
   * Raw key material, possibly hex or base64-encoded. Use this for symmetric keys.
   *
   * Hint: `raw` would typically be used with Cap'n Proto's `embed` syntax to embed an
   * external binary key file. `hex` or `base64` could do that too but can also be specified
   * inline.
   *
   */
  get base64() {
    utils.testWhich("base64", utils.getUint16(0, this), 2, this);
    return utils.getText(0, this);
  }
  get _isBase64() {
    return utils.getUint16(0, this) === 2;
  }
  set base64(value) {
    utils.setUint16(0, 2, this);
    utils.setText(0, value, this);
  }
  /**
   * Private key in PEM-encoded PKCS#8 format.
   *
   */
  get pkcs8() {
    utils.testWhich("pkcs8", utils.getUint16(0, this), 3, this);
    return utils.getText(0, this);
  }
  get _isPkcs8() {
    return utils.getUint16(0, this) === 3;
  }
  set pkcs8(value) {
    utils.setUint16(0, 3, this);
    utils.setText(0, value, this);
  }
  /**
   * Public key in PEM-encoded SPKI format.
   *
   */
  get spki() {
    utils.testWhich("spki", utils.getUint16(0, this), 4, this);
    return utils.getText(0, this);
  }
  get _isSpki() {
    return utils.getUint16(0, this) === 4;
  }
  set spki(value) {
    utils.setUint16(0, 4, this);
    utils.setText(0, value, this);
  }
  /**
   * Key in JSON format.
   *
   */
  get jwk() {
    utils.testWhich("jwk", utils.getUint16(0, this), 5, this);
    return utils.getText(0, this);
  }
  get _isJwk() {
    return utils.getUint16(0, this) === 5;
  }
  set jwk(value) {
    utils.setUint16(0, 5, this);
    utils.setText(0, value, this);
  }
  /**
   * Value for the `algorithm` parameter.
   *
   */
  get algorithm() {
    return utils.getAs(Worker_Binding_CryptoKey_Algorithm, this);
  }
  _initAlgorithm() {
    return utils.getAs(Worker_Binding_CryptoKey_Algorithm, this);
  }
  /**
   * Is the Worker allowed to export this key to obtain the underlying key material? Setting
   * this false ensures that the key cannot be leaked by errant JavaScript code; the key can
   * only be used in WebCrypto operations.
   *
   */
  get extractable() {
    return utils.getBit(
      32,
      this,
      _Worker_Binding_CryptoKey._capnp.defaultExtractable
    );
  }
  set extractable(value) {
    utils.setBit(
      32,
      value,
      this,
      _Worker_Binding_CryptoKey._capnp.defaultExtractable
    );
  }
  _adoptUsages(value) {
    utils.adopt(value, utils.getPointer(2, this));
  }
  _disownUsages() {
    return utils.disown(this.usages);
  }
  /**
   * What operations is this key permitted to be used for?
   *
   */
  get usages() {
    return utils.getList(
      2,
      Uint16List,
      this
    );
  }
  _hasUsages() {
    return !utils.isNull(utils.getPointer(2, this));
  }
  _initUsages(length) {
    return utils.initList(
      2,
      Uint16List,
      length,
      this
    );
  }
  set usages(value) {
    utils.copyFrom(value, utils.getPointer(2, this));
  }
  toString() {
    return "Worker_Binding_CryptoKey_" + super.toString();
  }
  which() {
    return utils.getUint16(0, this);
  }
};
var Worker_Binding_MemoryCacheLimits = class extends Struct {
  static _capnp = {
    displayName: "MemoryCacheLimits",
    id: "8d66725b0867e634",
    size: new ObjectSize(16, 0)
  };
  get maxKeys() {
    return utils.getUint32(0, this);
  }
  set maxKeys(value) {
    utils.setUint32(0, value, this);
  }
  get maxValueSize() {
    return utils.getUint32(4, this);
  }
  set maxValueSize(value) {
    utils.setUint32(4, value, this);
  }
  get maxTotalValueSize() {
    return utils.getUint64(8, this);
  }
  set maxTotalValueSize(value) {
    utils.setUint64(8, value, this);
  }
  toString() {
    return "Worker_Binding_MemoryCacheLimits_" + super.toString();
  }
};
var Worker_Binding_WrappedBinding = class _Worker_Binding_WrappedBinding extends Struct {
  static _capnp = {
    displayName: "WrappedBinding",
    id: "e6f066b75f0ea113",
    size: new ObjectSize(0, 3),
    defaultEntrypoint: "default"
  };
  static _InnerBindings;
  /**
   * Wrapper module name.
   * The module must be an internal one (provided by extension or registered in the c++ code).
   * Module will be instantitated during binding initialization phase.
   *
   */
  get moduleName() {
    return utils.getText(0, this);
  }
  set moduleName(value) {
    utils.setText(0, value, this);
  }
  /**
   * Module needs to export a function with a given name (default export gets "default" name).
   * The function needs to accept a single `env` argument - a dictionary with inner bindings.
   * Function will be invoked during initialization phase and its return value will be used as
   * resulting binding value.
   *
   */
  get entrypoint() {
    return utils.getText(
      1,
      this,
      _Worker_Binding_WrappedBinding._capnp.defaultEntrypoint
    );
  }
  set entrypoint(value) {
    utils.setText(1, value, this);
  }
  _adoptInnerBindings(value) {
    utils.adopt(value, utils.getPointer(2, this));
  }
  _disownInnerBindings() {
    return utils.disown(this.innerBindings);
  }
  /**
   * Inner bindings that will be created and passed in the env dictionary.
   * These bindings shall be used to implement end-user api, and are not available to the
   * binding consumers unless "re-exported" in wrapBindings function.
   *
   */
  get innerBindings() {
    return utils.getList(
      2,
      _Worker_Binding_WrappedBinding._InnerBindings,
      this
    );
  }
  _hasInnerBindings() {
    return !utils.isNull(utils.getPointer(2, this));
  }
  _initInnerBindings(length) {
    return utils.initList(
      2,
      _Worker_Binding_WrappedBinding._InnerBindings,
      length,
      this
    );
  }
  set innerBindings(value) {
    utils.copyFrom(value, utils.getPointer(2, this));
  }
  toString() {
    return "Worker_Binding_WrappedBinding_" + super.toString();
  }
};
var Worker_Binding_Parameter = class extends Struct {
  static _capnp = {
    displayName: "parameter",
    id: "dc57e1258d26d152",
    size: new ObjectSize(8, 6)
  };
  _adoptType(value) {
    utils.adopt(value, utils.getPointer(1, this));
  }
  _disownType() {
    return utils.disown(this.type);
  }
  /**
   * Expected type of this parameter.
   *
   */
  get type() {
    return utils.getStruct(1, Worker_Binding_Type, this);
  }
  _hasType() {
    return !utils.isNull(utils.getPointer(1, this));
  }
  _initType() {
    return utils.initStructAt(1, Worker_Binding_Type, this);
  }
  set type(value) {
    utils.copyFrom(value, utils.getPointer(1, this));
  }
  /**
   * If true, this binding is optional. Derived workers need not specify it, in which case
   * the binding won't be present in the environment object passed to the worker.
   *
   * When a Worker has any non-optional parameters that haven't been filled in, then it can
   * only be used for inheritance; it cannot be invoked directly.
   *
   */
  get optional() {
    return utils.getBit(16, this);
  }
  set optional(value) {
    utils.setBit(16, value, this);
  }
  toString() {
    return "Worker_Binding_Parameter_" + super.toString();
  }
};
var Worker_Binding_Hyperdrive = class extends Struct {
  static _capnp = {
    displayName: "hyperdrive",
    id: "ad6c391cd55f3134",
    size: new ObjectSize(8, 6)
  };
  _adoptDesignator(value) {
    utils.adopt(value, utils.getPointer(1, this));
  }
  _disownDesignator() {
    return utils.disown(this.designator);
  }
  get designator() {
    return utils.getStruct(1, ServiceDesignator, this);
  }
  _hasDesignator() {
    return !utils.isNull(utils.getPointer(1, this));
  }
  _initDesignator() {
    return utils.initStructAt(1, ServiceDesignator, this);
  }
  set designator(value) {
    utils.copyFrom(value, utils.getPointer(1, this));
  }
  get database() {
    return utils.getText(2, this);
  }
  set database(value) {
    utils.setText(2, value, this);
  }
  get user() {
    return utils.getText(3, this);
  }
  set user(value) {
    utils.setText(3, value, this);
  }
  get password() {
    return utils.getText(4, this);
  }
  set password(value) {
    utils.setText(4, value, this);
  }
  get scheme() {
    return utils.getText(5, this);
  }
  set scheme(value) {
    utils.setText(5, value, this);
  }
  toString() {
    return "Worker_Binding_Hyperdrive_" + super.toString();
  }
};
var Worker_Binding_MemoryCache = class extends Struct {
  static _capnp = {
    displayName: "memoryCache",
    id: "aed5760c349869da",
    size: new ObjectSize(8, 6)
  };
  /**
   * The identifier associated with this cache. Any number of isolates
   * can access the same in-memory cache (within the same process), and
   * each worker may use any number of in-memory caches.
   *
   */
  get id() {
    return utils.getText(1, this);
  }
  set id(value) {
    utils.setText(1, value, this);
  }
  _adoptLimits(value) {
    utils.adopt(value, utils.getPointer(2, this));
  }
  _disownLimits() {
    return utils.disown(this.limits);
  }
  get limits() {
    return utils.getStruct(2, Worker_Binding_MemoryCacheLimits, this);
  }
  _hasLimits() {
    return !utils.isNull(utils.getPointer(2, this));
  }
  _initLimits() {
    return utils.initStructAt(2, Worker_Binding_MemoryCacheLimits, this);
  }
  set limits(value) {
    utils.copyFrom(value, utils.getPointer(2, this));
  }
  toString() {
    return "Worker_Binding_MemoryCache_" + super.toString();
  }
};
var Worker_Binding_WorkerLoader = class extends Struct {
  static _capnp = {
    displayName: "workerLoader",
    id: "a3de996091635c4d",
    size: new ObjectSize(8, 6)
  };
  /**
   * Optional: The identifier associated with this Worker loader. Multiple Workers can bind to
   * the same ID in order to access the same loader, so that if they request the same name
   * from it, they'll end up sharing the same loaded Worker.
   *
   * (If omitted, the binding will not share a cache with any other binding.)
   *
   */
  get id() {
    return utils.getText(1, this);
  }
  set id(value) {
    utils.setText(1, value, this);
  }
  toString() {
    return "Worker_Binding_WorkerLoader_" + super.toString();
  }
};
var Worker_Binding_Which = {
  /**
   * (This catches when someone forgets to specify one of the union members. Do not set this.)
   *
   */
  UNSPECIFIED: 0,
  /**
   * Indicates that the Worker requires a binding of the given type, but it won't be specified
   * here. Another Worker can inherit this Worker and fill in this binding.
   *
   */
  PARAMETER: 1,
  /**
   * A string.
   *
   */
  TEXT: 2,
  /**
   * An ArrayBuffer.
   *
   */
  DATA: 3,
  /**
   * A value parsed from JSON.
   *
   */
  JSON: 4,
  /**
   * A WebAssembly module. The binding will be an instance of `WebAssembly.Module`. Only
   * supported when using Service Workers syntax.
   *
   * DEPRECATED: Please switch to ES modules syntax instead, and embed Wasm modules as modules.
   *
   */
  WASM_MODULE: 5,
  /**
   * A CryptoKey instance, for use with the WebCrypto API.
   *
   * Note that by setting `extractable = false`, you can prevent the Worker code from accessing
   * or leaking the raw key material; it will only be able to use the key to perform WebCrypto
   * operations.
   *
   */
  CRYPTO_KEY: 6,
  /**
   * Binding to a named service (possibly, a worker).
   *
   */
  SERVICE: 7,
  /**
   * A Durable Object class binding, without an actual storage namespace. This can be used to
   * implement a facet.
   *
   */
  DURABLE_OBJECT_CLASS: 19,
  /**
   * Binding to the durable object namespace implemented by the given class.
   *
   * In the common case that this refers to a class in the same Worker, you can specify just
   * a string, like:
   *
   *     durableObjectNamespace = "MyClass"
   *
   */
  DURABLE_OBJECT_NAMESPACE: 8,
  /**
   * A KV namespace, implemented by the named service. The Worker sees a KvNamespace-typed
   * binding. Requests to the namespace will be converted into HTTP requests targeting the
   * given service name.
   *
   */
  KV_NAMESPACE: 9,
  /**
   * R2 bucket binding. Similar to KV namespaces, this turns operations into HTTP requests aimed
   * at the named service.
   *
   */
  R2BUCKET: 10,
  OBSOLETE0: 11,
  /**
   * Wraps a collection of inner bindings in a common api functionality.
   *
   */
  WRAPPED: 12,
  /**
   * A Queue binding, implemented by the named service. Requests to the
   * namespace will be converted into HTTP requests targeting the given
   * service name.
   *
   */
  QUEUE: 13,
  /**
   * Takes the value of an environment variable from the system. The value specified here is
   * the name of a system environment variable. The value of the binding is obtained by invoking
   * `getenv()` with that name. If the environment variable isn't set, the binding value is
   * `null`.
   *
   */
  FROM_ENVIRONMENT: 14,
  /**
   * A binding for Analytics Engine. Allows workers to store information through Analytics Engine Events.
   * workerd will forward AnalyticsEngineEvents to designated service in the body of HTTP requests
   * This binding is subject to change and requires the `--experimental` flag
   *
   */
  ANALYTICS_ENGINE: 15,
  /**
   * A binding for Hyperdrive. Allows workers to use Hyperdrive caching & pooling for Postgres
   * databases.
   *
   */
  HYPERDRIVE: 16,
  /**
   * A simple binding that enables access to the UnsafeEval API.
   *
   */
  UNSAFE_EVAL: 17,
  /**
   * A binding representing access to an in-memory cache.
   *
   */
  MEMORY_CACHE: 18,
  /**
   * A binding representing the ability to dynamically load Workers from code presented at
   * runtime.
   *
   * A Worker loader is not just a function that loads a Worker, but also serves as a
   * cache of Workers, automatically unloading Workers that are not in use. To that end, each
   * Worker must have a name, and if a Worker with that name already exists, it'll be reused.
   *
   */
  WORKER_LOADER: 20,
  /**
   * A binding that provides a connect() method to dynamically connect to any workerd
   * instance's debug port. This allows dynamic access to worker entrypoints via the
   * WorkerdDebugPort RPC interface.
   *
   * Usage: const client = await env.DEBUG_PORT.connect("localhost:1234");
   *        const fetcher = await client.getEntrypoint("service", "entrypoint");
   *
   * This is a workerd-only API intended for local development and testing.
   *
   */
  WORKERD_DEBUG_PORT: 21
};
var Worker_Binding = class extends Struct {
  static UNSPECIFIED = Worker_Binding_Which.UNSPECIFIED;
  static PARAMETER = Worker_Binding_Which.PARAMETER;
  static TEXT = Worker_Binding_Which.TEXT;
  static DATA = Worker_Binding_Which.DATA;
  static JSON = Worker_Binding_Which.JSON;
  static WASM_MODULE = Worker_Binding_Which.WASM_MODULE;
  static CRYPTO_KEY = Worker_Binding_Which.CRYPTO_KEY;
  static SERVICE = Worker_Binding_Which.SERVICE;
  static DURABLE_OBJECT_CLASS = Worker_Binding_Which.DURABLE_OBJECT_CLASS;
  static DURABLE_OBJECT_NAMESPACE = Worker_Binding_Which.DURABLE_OBJECT_NAMESPACE;
  static KV_NAMESPACE = Worker_Binding_Which.KV_NAMESPACE;
  static R2BUCKET = Worker_Binding_Which.R2BUCKET;
  static OBSOLETE0 = Worker_Binding_Which.OBSOLETE0;
  static WRAPPED = Worker_Binding_Which.WRAPPED;
  static QUEUE = Worker_Binding_Which.QUEUE;
  static FROM_ENVIRONMENT = Worker_Binding_Which.FROM_ENVIRONMENT;
  static ANALYTICS_ENGINE = Worker_Binding_Which.ANALYTICS_ENGINE;
  static HYPERDRIVE = Worker_Binding_Which.HYPERDRIVE;
  static UNSAFE_EVAL = Worker_Binding_Which.UNSAFE_EVAL;
  static MEMORY_CACHE = Worker_Binding_Which.MEMORY_CACHE;
  static WORKER_LOADER = Worker_Binding_Which.WORKER_LOADER;
  static WORKERD_DEBUG_PORT = Worker_Binding_Which.WORKERD_DEBUG_PORT;
  static Type = Worker_Binding_Type;
  static DurableObjectNamespaceDesignator = Worker_Binding_DurableObjectNamespaceDesignator;
  static CryptoKey = Worker_Binding_CryptoKey;
  static MemoryCacheLimits = Worker_Binding_MemoryCacheLimits;
  static WrappedBinding = Worker_Binding_WrappedBinding;
  static _capnp = {
    displayName: "Binding",
    id: "8e7e492fd7e35f3e",
    size: new ObjectSize(8, 6)
  };
  get name() {
    return utils.getText(0, this);
  }
  set name(value) {
    utils.setText(0, value, this);
  }
  get _isUnspecified() {
    return utils.getUint16(0, this) === 0;
  }
  set unspecified(_) {
    utils.setUint16(0, 0, this);
  }
  /**
   * Indicates that the Worker requires a binding of the given type, but it won't be specified
   * here. Another Worker can inherit this Worker and fill in this binding.
   *
   */
  get parameter() {
    utils.testWhich("parameter", utils.getUint16(0, this), 1, this);
    return utils.getAs(Worker_Binding_Parameter, this);
  }
  _initParameter() {
    utils.setUint16(0, 1, this);
    return utils.getAs(Worker_Binding_Parameter, this);
  }
  get _isParameter() {
    return utils.getUint16(0, this) === 1;
  }
  set parameter(_) {
    utils.setUint16(0, 1, this);
  }
  /**
   * A string.
   *
   */
  get text() {
    utils.testWhich("text", utils.getUint16(0, this), 2, this);
    return utils.getText(1, this);
  }
  get _isText() {
    return utils.getUint16(0, this) === 2;
  }
  set text(value) {
    utils.setUint16(0, 2, this);
    utils.setText(1, value, this);
  }
  _adoptData(value) {
    utils.setUint16(0, 3, this);
    utils.adopt(value, utils.getPointer(1, this));
  }
  _disownData() {
    return utils.disown(this.data);
  }
  /**
   * An ArrayBuffer.
   *
   */
  get data() {
    utils.testWhich("data", utils.getUint16(0, this), 3, this);
    return utils.getData(1, this);
  }
  _hasData() {
    return !utils.isNull(utils.getPointer(1, this));
  }
  _initData(length) {
    utils.setUint16(0, 3, this);
    return utils.initData(1, length, this);
  }
  get _isData() {
    return utils.getUint16(0, this) === 3;
  }
  set data(value) {
    utils.setUint16(0, 3, this);
    utils.copyFrom(value, utils.getPointer(1, this));
  }
  /**
   * A value parsed from JSON.
   *
   */
  get json() {
    utils.testWhich("json", utils.getUint16(0, this), 4, this);
    return utils.getText(1, this);
  }
  get _isJson() {
    return utils.getUint16(0, this) === 4;
  }
  set json(value) {
    utils.setUint16(0, 4, this);
    utils.setText(1, value, this);
  }
  _adoptWasmModule(value) {
    utils.setUint16(0, 5, this);
    utils.adopt(value, utils.getPointer(1, this));
  }
  _disownWasmModule() {
    return utils.disown(this.wasmModule);
  }
  /**
   * A WebAssembly module. The binding will be an instance of `WebAssembly.Module`. Only
   * supported when using Service Workers syntax.
   *
   * DEPRECATED: Please switch to ES modules syntax instead, and embed Wasm modules as modules.
   *
   */
  get wasmModule() {
    utils.testWhich("wasmModule", utils.getUint16(0, this), 5, this);
    return utils.getData(1, this);
  }
  _hasWasmModule() {
    return !utils.isNull(utils.getPointer(1, this));
  }
  _initWasmModule(length) {
    utils.setUint16(0, 5, this);
    return utils.initData(1, length, this);
  }
  get _isWasmModule() {
    return utils.getUint16(0, this) === 5;
  }
  set wasmModule(value) {
    utils.setUint16(0, 5, this);
    utils.copyFrom(value, utils.getPointer(1, this));
  }
  _adoptCryptoKey(value) {
    utils.setUint16(0, 6, this);
    utils.adopt(value, utils.getPointer(1, this));
  }
  _disownCryptoKey() {
    return utils.disown(this.cryptoKey);
  }
  /**
   * A CryptoKey instance, for use with the WebCrypto API.
   *
   * Note that by setting `extractable = false`, you can prevent the Worker code from accessing
   * or leaking the raw key material; it will only be able to use the key to perform WebCrypto
   * operations.
   *
   */
  get cryptoKey() {
    utils.testWhich("cryptoKey", utils.getUint16(0, this), 6, this);
    return utils.getStruct(1, Worker_Binding_CryptoKey, this);
  }
  _hasCryptoKey() {
    return !utils.isNull(utils.getPointer(1, this));
  }
  _initCryptoKey() {
    utils.setUint16(0, 6, this);
    return utils.initStructAt(1, Worker_Binding_CryptoKey, this);
  }
  get _isCryptoKey() {
    return utils.getUint16(0, this) === 6;
  }
  set cryptoKey(value) {
    utils.setUint16(0, 6, this);
    utils.copyFrom(value, utils.getPointer(1, this));
  }
  _adoptService(value) {
    utils.setUint16(0, 7, this);
    utils.adopt(value, utils.getPointer(1, this));
  }
  _disownService() {
    return utils.disown(this.service);
  }
  /**
   * Binding to a named service (possibly, a worker).
   *
   */
  get service() {
    utils.testWhich("service", utils.getUint16(0, this), 7, this);
    return utils.getStruct(1, ServiceDesignator, this);
  }
  _hasService() {
    return !utils.isNull(utils.getPointer(1, this));
  }
  _initService() {
    utils.setUint16(0, 7, this);
    return utils.initStructAt(1, ServiceDesignator, this);
  }
  get _isService() {
    return utils.getUint16(0, this) === 7;
  }
  set service(value) {
    utils.setUint16(0, 7, this);
    utils.copyFrom(value, utils.getPointer(1, this));
  }
  _adoptDurableObjectClass(value) {
    utils.setUint16(0, 19, this);
    utils.adopt(value, utils.getPointer(1, this));
  }
  _disownDurableObjectClass() {
    return utils.disown(this.durableObjectClass);
  }
  /**
   * A Durable Object class binding, without an actual storage namespace. This can be used to
   * implement a facet.
   *
   */
  get durableObjectClass() {
    utils.testWhich(
      "durableObjectClass",
      utils.getUint16(0, this),
      19,
      this
    );
    return utils.getStruct(1, ServiceDesignator, this);
  }
  _hasDurableObjectClass() {
    return !utils.isNull(utils.getPointer(1, this));
  }
  _initDurableObjectClass() {
    utils.setUint16(0, 19, this);
    return utils.initStructAt(1, ServiceDesignator, this);
  }
  get _isDurableObjectClass() {
    return utils.getUint16(0, this) === 19;
  }
  set durableObjectClass(value) {
    utils.setUint16(0, 19, this);
    utils.copyFrom(value, utils.getPointer(1, this));
  }
  _adoptDurableObjectNamespace(value) {
    utils.setUint16(0, 8, this);
    utils.adopt(value, utils.getPointer(1, this));
  }
  _disownDurableObjectNamespace() {
    return utils.disown(this.durableObjectNamespace);
  }
  /**
   * Binding to the durable object namespace implemented by the given class.
   *
   * In the common case that this refers to a class in the same Worker, you can specify just
   * a string, like:
   *
   *     durableObjectNamespace = "MyClass"
   *
   */
  get durableObjectNamespace() {
    utils.testWhich(
      "durableObjectNamespace",
      utils.getUint16(0, this),
      8,
      this
    );
    return utils.getStruct(
      1,
      Worker_Binding_DurableObjectNamespaceDesignator,
      this
    );
  }
  _hasDurableObjectNamespace() {
    return !utils.isNull(utils.getPointer(1, this));
  }
  _initDurableObjectNamespace() {
    utils.setUint16(0, 8, this);
    return utils.initStructAt(
      1,
      Worker_Binding_DurableObjectNamespaceDesignator,
      this
    );
  }
  get _isDurableObjectNamespace() {
    return utils.getUint16(0, this) === 8;
  }
  set durableObjectNamespace(value) {
    utils.setUint16(0, 8, this);
    utils.copyFrom(value, utils.getPointer(1, this));
  }
  _adoptKvNamespace(value) {
    utils.setUint16(0, 9, this);
    utils.adopt(value, utils.getPointer(1, this));
  }
  _disownKvNamespace() {
    return utils.disown(this.kvNamespace);
  }
  /**
   * A KV namespace, implemented by the named service. The Worker sees a KvNamespace-typed
   * binding. Requests to the namespace will be converted into HTTP requests targeting the
   * given service name.
   *
   */
  get kvNamespace() {
    utils.testWhich("kvNamespace", utils.getUint16(0, this), 9, this);
    return utils.getStruct(1, ServiceDesignator, this);
  }
  _hasKvNamespace() {
    return !utils.isNull(utils.getPointer(1, this));
  }
  _initKvNamespace() {
    utils.setUint16(0, 9, this);
    return utils.initStructAt(1, ServiceDesignator, this);
  }
  get _isKvNamespace() {
    return utils.getUint16(0, this) === 9;
  }
  set kvNamespace(value) {
    utils.setUint16(0, 9, this);
    utils.copyFrom(value, utils.getPointer(1, this));
  }
  _adoptR2Bucket(value) {
    utils.setUint16(0, 10, this);
    utils.adopt(value, utils.getPointer(1, this));
  }
  _disownR2Bucket() {
    return utils.disown(this.r2Bucket);
  }
  /**
   * R2 bucket binding. Similar to KV namespaces, this turns operations into HTTP requests aimed
   * at the named service.
   *
   */
  get r2Bucket() {
    utils.testWhich("r2Bucket", utils.getUint16(0, this), 10, this);
    return utils.getStruct(1, ServiceDesignator, this);
  }
  _hasR2Bucket() {
    return !utils.isNull(utils.getPointer(1, this));
  }
  _initR2Bucket() {
    utils.setUint16(0, 10, this);
    return utils.initStructAt(1, ServiceDesignator, this);
  }
  get _isR2Bucket() {
    return utils.getUint16(0, this) === 10;
  }
  set r2Bucket(value) {
    utils.setUint16(0, 10, this);
    utils.copyFrom(value, utils.getPointer(1, this));
  }
  _adoptObsolete0(value) {
    utils.setUint16(0, 11, this);
    utils.adopt(value, utils.getPointer(1, this));
  }
  _disownObsolete0() {
    return utils.disown(this.obsolete0);
  }
  get obsolete0() {
    utils.testWhich("obsolete0", utils.getUint16(0, this), 11, this);
    return utils.getStruct(1, ServiceDesignator, this);
  }
  _hasObsolete0() {
    return !utils.isNull(utils.getPointer(1, this));
  }
  _initObsolete0() {
    utils.setUint16(0, 11, this);
    return utils.initStructAt(1, ServiceDesignator, this);
  }
  get _isObsolete0() {
    return utils.getUint16(0, this) === 11;
  }
  set obsolete0(value) {
    utils.setUint16(0, 11, this);
    utils.copyFrom(value, utils.getPointer(1, this));
  }
  _adoptWrapped(value) {
    utils.setUint16(0, 12, this);
    utils.adopt(value, utils.getPointer(1, this));
  }
  _disownWrapped() {
    return utils.disown(this.wrapped);
  }
  /**
   * Wraps a collection of inner bindings in a common api functionality.
   *
   */
  get wrapped() {
    utils.testWhich("wrapped", utils.getUint16(0, this), 12, this);
    return utils.getStruct(1, Worker_Binding_WrappedBinding, this);
  }
  _hasWrapped() {
    return !utils.isNull(utils.getPointer(1, this));
  }
  _initWrapped() {
    utils.setUint16(0, 12, this);
    return utils.initStructAt(1, Worker_Binding_WrappedBinding, this);
  }
  get _isWrapped() {
    return utils.getUint16(0, this) === 12;
  }
  set wrapped(value) {
    utils.setUint16(0, 12, this);
    utils.copyFrom(value, utils.getPointer(1, this));
  }
  _adoptQueue(value) {
    utils.setUint16(0, 13, this);
    utils.adopt(value, utils.getPointer(1, this));
  }
  _disownQueue() {
    return utils.disown(this.queue);
  }
  /**
   * A Queue binding, implemented by the named service. Requests to the
   * namespace will be converted into HTTP requests targeting the given
   * service name.
   *
   */
  get queue() {
    utils.testWhich("queue", utils.getUint16(0, this), 13, this);
    return utils.getStruct(1, ServiceDesignator, this);
  }
  _hasQueue() {
    return !utils.isNull(utils.getPointer(1, this));
  }
  _initQueue() {
    utils.setUint16(0, 13, this);
    return utils.initStructAt(1, ServiceDesignator, this);
  }
  get _isQueue() {
    return utils.getUint16(0, this) === 13;
  }
  set queue(value) {
    utils.setUint16(0, 13, this);
    utils.copyFrom(value, utils.getPointer(1, this));
  }
  /**
   * Takes the value of an environment variable from the system. The value specified here is
   * the name of a system environment variable. The value of the binding is obtained by invoking
   * `getenv()` with that name. If the environment variable isn't set, the binding value is
   * `null`.
   *
   */
  get fromEnvironment() {
    utils.testWhich("fromEnvironment", utils.getUint16(0, this), 14, this);
    return utils.getText(1, this);
  }
  get _isFromEnvironment() {
    return utils.getUint16(0, this) === 14;
  }
  set fromEnvironment(value) {
    utils.setUint16(0, 14, this);
    utils.setText(1, value, this);
  }
  _adoptAnalyticsEngine(value) {
    utils.setUint16(0, 15, this);
    utils.adopt(value, utils.getPointer(1, this));
  }
  _disownAnalyticsEngine() {
    return utils.disown(this.analyticsEngine);
  }
  /**
   * A binding for Analytics Engine. Allows workers to store information through Analytics Engine Events.
   * workerd will forward AnalyticsEngineEvents to designated service in the body of HTTP requests
   * This binding is subject to change and requires the `--experimental` flag
   *
   */
  get analyticsEngine() {
    utils.testWhich("analyticsEngine", utils.getUint16(0, this), 15, this);
    return utils.getStruct(1, ServiceDesignator, this);
  }
  _hasAnalyticsEngine() {
    return !utils.isNull(utils.getPointer(1, this));
  }
  _initAnalyticsEngine() {
    utils.setUint16(0, 15, this);
    return utils.initStructAt(1, ServiceDesignator, this);
  }
  get _isAnalyticsEngine() {
    return utils.getUint16(0, this) === 15;
  }
  set analyticsEngine(value) {
    utils.setUint16(0, 15, this);
    utils.copyFrom(value, utils.getPointer(1, this));
  }
  /**
   * A binding for Hyperdrive. Allows workers to use Hyperdrive caching & pooling for Postgres
   * databases.
   *
   */
  get hyperdrive() {
    utils.testWhich("hyperdrive", utils.getUint16(0, this), 16, this);
    return utils.getAs(Worker_Binding_Hyperdrive, this);
  }
  _initHyperdrive() {
    utils.setUint16(0, 16, this);
    return utils.getAs(Worker_Binding_Hyperdrive, this);
  }
  get _isHyperdrive() {
    return utils.getUint16(0, this) === 16;
  }
  set hyperdrive(_) {
    utils.setUint16(0, 16, this);
  }
  get _isUnsafeEval() {
    return utils.getUint16(0, this) === 17;
  }
  set unsafeEval(_) {
    utils.setUint16(0, 17, this);
  }
  /**
   * A binding representing access to an in-memory cache.
   *
   */
  get memoryCache() {
    utils.testWhich("memoryCache", utils.getUint16(0, this), 18, this);
    return utils.getAs(Worker_Binding_MemoryCache, this);
  }
  _initMemoryCache() {
    utils.setUint16(0, 18, this);
    return utils.getAs(Worker_Binding_MemoryCache, this);
  }
  get _isMemoryCache() {
    return utils.getUint16(0, this) === 18;
  }
  set memoryCache(_) {
    utils.setUint16(0, 18, this);
  }
  /**
   * A binding representing the ability to dynamically load Workers from code presented at
   * runtime.
   *
   * A Worker loader is not just a function that loads a Worker, but also serves as a
   * cache of Workers, automatically unloading Workers that are not in use. To that end, each
   * Worker must have a name, and if a Worker with that name already exists, it'll be reused.
   *
   */
  get workerLoader() {
    utils.testWhich("workerLoader", utils.getUint16(0, this), 20, this);
    return utils.getAs(Worker_Binding_WorkerLoader, this);
  }
  _initWorkerLoader() {
    utils.setUint16(0, 20, this);
    return utils.getAs(Worker_Binding_WorkerLoader, this);
  }
  get _isWorkerLoader() {
    return utils.getUint16(0, this) === 20;
  }
  set workerLoader(_) {
    utils.setUint16(0, 20, this);
  }
  get _isWorkerdDebugPort() {
    return utils.getUint16(0, this) === 21;
  }
  set workerdDebugPort(_) {
    utils.setUint16(0, 21, this);
  }
  toString() {
    return "Worker_Binding_" + super.toString();
  }
  which() {
    return utils.getUint16(0, this);
  }
};
var Worker_DurableObjectNamespace_ContainerOptions_ContainerPrivileges_Device = class extends Struct {
  static _capnp = {
    displayName: "Device",
    id: "83f9125afacda809",
    size: new ObjectSize(0, 3)
  };
  get pathOnHost() {
    return utils.getText(0, this);
  }
  set pathOnHost(value) {
    utils.setText(0, value, this);
  }
  get pathInContainer() {
    return utils.getText(1, this);
  }
  set pathInContainer(value) {
    utils.setText(1, value, this);
  }
  get cgroupPermissions() {
    return utils.getText(2, this);
  }
  set cgroupPermissions(value) {
    utils.setText(2, value, this);
  }
  toString() {
    return "Worker_DurableObjectNamespace_ContainerOptions_ContainerPrivileges_Device_" + super.toString();
  }
};
var Worker_DurableObjectNamespace_ContainerOptions_ContainerPrivileges = class _Worker_DurableObjectNamespace_ContainerOptions_ContainerPrivileges extends Struct {
  static Device = Worker_DurableObjectNamespace_ContainerOptions_ContainerPrivileges_Device;
  static _capnp = {
    displayName: "ContainerPrivileges",
    id: "ca910fa0c4c988bf",
    size: new ObjectSize(0, 3)
  };
  static _Devices;
  _adoptCapabilities(value) {
    utils.adopt(value, utils.getPointer(0, this));
  }
  _disownCapabilities() {
    return utils.disown(this.capabilities);
  }
  /**
   * Docker HostConfig.CapAdd values.
   *
   */
  get capabilities() {
    return utils.getList(0, TextList, this);
  }
  _hasCapabilities() {
    return !utils.isNull(utils.getPointer(0, this));
  }
  _initCapabilities(length) {
    return utils.initList(0, TextList, length, this);
  }
  set capabilities(value) {
    utils.copyFrom(value, utils.getPointer(0, this));
  }
  _adoptDevices(value) {
    utils.adopt(value, utils.getPointer(1, this));
  }
  _disownDevices() {
    return utils.disown(this.devices);
  }
  /**
   * Docker HostConfig.Devices values.
   *
   */
  get devices() {
    return utils.getList(
      1,
      _Worker_DurableObjectNamespace_ContainerOptions_ContainerPrivileges._Devices,
      this
    );
  }
  _hasDevices() {
    return !utils.isNull(utils.getPointer(1, this));
  }
  _initDevices(length) {
    return utils.initList(
      1,
      _Worker_DurableObjectNamespace_ContainerOptions_ContainerPrivileges._Devices,
      length,
      this
    );
  }
  set devices(value) {
    utils.copyFrom(value, utils.getPointer(1, this));
  }
  _adoptSecurityOpt(value) {
    utils.adopt(value, utils.getPointer(2, this));
  }
  _disownSecurityOpt() {
    return utils.disown(this.securityOpt);
  }
  /**
   * Docker HostConfig.SecurityOpt values.
   *
   */
  get securityOpt() {
    return utils.getList(2, TextList, this);
  }
  _hasSecurityOpt() {
    return !utils.isNull(utils.getPointer(2, this));
  }
  _initSecurityOpt(length) {
    return utils.initList(2, TextList, length, this);
  }
  set securityOpt(value) {
    utils.copyFrom(value, utils.getPointer(2, this));
  }
  toString() {
    return "Worker_DurableObjectNamespace_ContainerOptions_ContainerPrivileges_" + super.toString();
  }
};
var Worker_DurableObjectNamespace_ContainerOptions = class extends Struct {
  static ContainerPrivileges = Worker_DurableObjectNamespace_ContainerOptions_ContainerPrivileges;
  static _capnp = {
    displayName: "ContainerOptions",
    id: "a609621a4d236cd7",
    size: new ObjectSize(0, 2)
  };
  /**
   * Image name to be used to create the container using supported provider.
   * By default, we pull the "latest" tag of this image.
   *
   */
  get imageName() {
    return utils.getText(0, this);
  }
  set imageName(value) {
    utils.setText(0, value, this);
  }
  _adoptPrivileges(value) {
    utils.adopt(value, utils.getPointer(1, this));
  }
  _disownPrivileges() {
    return utils.disown(this.privileges);
  }
  /**
   * Extra Docker HostConfig privileges applied when creating the container.
   * These fields are passed through to Docker as-is and are empty by default.
   * They are not validated or allow-listed. Depending on the values and Docker daemon mode,
   * they can expose arbitrary host devices, disable security profiles, or grant capabilities
   * such as CAP_SYS_ADMIN that may provide host-level access. Only use trusted configuration.
   *
   */
  get privileges() {
    return utils.getStruct(
      1,
      Worker_DurableObjectNamespace_ContainerOptions_ContainerPrivileges,
      this
    );
  }
  _hasPrivileges() {
    return !utils.isNull(utils.getPointer(1, this));
  }
  _initPrivileges() {
    return utils.initStructAt(
      1,
      Worker_DurableObjectNamespace_ContainerOptions_ContainerPrivileges,
      this
    );
  }
  set privileges(value) {
    utils.copyFrom(value, utils.getPointer(1, this));
  }
  toString() {
    return "Worker_DurableObjectNamespace_ContainerOptions_" + super.toString();
  }
};
var Worker_DurableObjectNamespace_Which = {
  /**
   * A unique, stable ID associated with this namespace. This could be a  GUID, or any other
   * string which does not appear anywhere else in the world.
   *
   * This string is used to ensure that objects of this class have unique identifiers distinct
   * from objects of any other class. Object IDs are cryptographically derived from `uniqueKey`
   * and validated against it. It is impossible to guess or forge a valid object ID without
   * knowing the `uniqueKey`. Hence, if you keep the key secret, you can prevent anyone from
   * forging IDs. However, if you don't care if users can forge valid IDs, then it's not a big
   * deal if the key leaks.
   *
   * DO NOT LOSE this key, otherwise it may be difficult or impossible to recover stored data.
   *
   */
  UNIQUE_KEY: 0,
  /**
   * Instances of this class are ephemeral -- they have no durable storage at all. The
   * `state.storage` API will not be present. Additionally, this namespace will allow arbitrary
   * strings as IDs. There are no `idFromName()` nor `newUniqueId()` methods; `get()` takes any
   * string as a parameter.
   *
   * Ephemeral objects are NOT globally unique, only "locally" unique, for some definition of
   * "local". For example, on Cloudflare's network, these objects are unique per-colo.
   *
   * WARNING: Cloudflare Workers currently limits this feature to Cloudflare-internal users
   *   only, because using them correctly requires deep understanding of Cloudflare network
   *   topology. We're working on something better for public consuption. Until then for
   *   "ephemeral" use cases we recommend using regular durable objects and just not storing
   *   anything. An object that hasn't stored anything will not consume any storage space on
   *   disk.
   *
   */
  EPHEMERAL_LOCAL: 1
};
var Worker_DurableObjectNamespace = class extends Struct {
  static UNIQUE_KEY = Worker_DurableObjectNamespace_Which.UNIQUE_KEY;
  static EPHEMERAL_LOCAL = Worker_DurableObjectNamespace_Which.EPHEMERAL_LOCAL;
  static ContainerOptions = Worker_DurableObjectNamespace_ContainerOptions;
  static _capnp = {
    displayName: "DurableObjectNamespace",
    id: "b429dd547d15747d",
    size: new ObjectSize(8, 3)
  };
  /**
   * Exported class name that implements the Durable Object.
   *
   * Changing the class name will not break compatibility with existing storage, so long as
   * `uniqueKey` stays the same.
   *
   */
  get className() {
    return utils.getText(0, this);
  }
  set className(value) {
    utils.setText(0, value, this);
  }
  /**
   * A unique, stable ID associated with this namespace. This could be a  GUID, or any other
   * string which does not appear anywhere else in the world.
   *
   * This string is used to ensure that objects of this class have unique identifiers distinct
   * from objects of any other class. Object IDs are cryptographically derived from `uniqueKey`
   * and validated against it. It is impossible to guess or forge a valid object ID without
   * knowing the `uniqueKey`. Hence, if you keep the key secret, you can prevent anyone from
   * forging IDs. However, if you don't care if users can forge valid IDs, then it's not a big
   * deal if the key leaks.
   *
   * DO NOT LOSE this key, otherwise it may be difficult or impossible to recover stored data.
   *
   */
  get uniqueKey() {
    utils.testWhich("uniqueKey", utils.getUint16(0, this), 0, this);
    return utils.getText(1, this);
  }
  get _isUniqueKey() {
    return utils.getUint16(0, this) === 0;
  }
  set uniqueKey(value) {
    utils.setUint16(0, 0, this);
    utils.setText(1, value, this);
  }
  get _isEphemeralLocal() {
    return utils.getUint16(0, this) === 1;
  }
  set ephemeralLocal(_) {
    utils.setUint16(0, 1, this);
  }
  /**
   * By default, Durable Objects are evicted after 10 seconds of inactivity, and expire 70 seconds
   * after all clients have disconnected. Some applications may want to keep their Durable Objects
   * pinned to memory forever, so we provide this flag to change the default behavior.
   *
   * Note that this is only supported in Workerd; production Durable Objects cannot toggle eviction.
   *
   */
  get preventEviction() {
    return utils.getBit(16, this);
  }
  set preventEviction(value) {
    utils.setBit(16, value, this);
  }
  /**
   * Whether or not Durable Objects in this namespace can use the `storage.sql` API to execute SQL
   * queries.
   *
   * workerd uses SQLite to back all Durable Objects, but the SQL API is hidden by default to
   * emulate behavior of traditional DO namespaces on Cloudflare that aren't SQLite-backed. This
   * flag should be enabled when testing code that will run on a SQLite-backed namespace.
   *
   */
  get enableSql() {
    return utils.getBit(17, this);
  }
  set enableSql(value) {
    utils.setBit(17, value, this);
  }
  _adoptContainer(value) {
    utils.adopt(value, utils.getPointer(2, this));
  }
  _disownContainer() {
    return utils.disown(this.container);
  }
  /**
   * If present, Durable Objects in this namespace have attached containers.
   * workerd will talk to the configured container engine to start containers for each
   * Durable Object based on the given image. The Durable Object can access the container via the
   * ctx.container API. TODO(CloudChamber): add link to docs.
   *
   */
  get container() {
    return utils.getStruct(
      2,
      Worker_DurableObjectNamespace_ContainerOptions,
      this
    );
  }
  _hasContainer() {
    return !utils.isNull(utils.getPointer(2, this));
  }
  _initContainer() {
    return utils.initStructAt(
      2,
      Worker_DurableObjectNamespace_ContainerOptions,
      this
    );
  }
  set container(value) {
    utils.copyFrom(value, utils.getPointer(2, this));
  }
  toString() {
    return "Worker_DurableObjectNamespace_" + super.toString();
  }
  which() {
    return utils.getUint16(0, this);
  }
};
var Worker_DockerConfiguration = class extends Struct {
  static _capnp = {
    displayName: "DockerConfiguration",
    id: "e62f96c20d9fb872",
    size: new ObjectSize(0, 2)
  };
  /**
   * Path to the Docker socket.
   *
   */
  get socketPath() {
    return utils.getText(0, this);
  }
  set socketPath(value) {
    utils.setText(0, value, this);
  }
  /**
   * Docker image name for the container egress interceptor sidecar.
   * This sidecar intercepts outbound traffic from containers and routes it
   * through workerd for egress mappings (setEgressHttp bindings).
   * You can find this image in repositories like DockerHub: https://hub.docker.com/r/cloudflare/proxy-everything
   *
   */
  get containerEgressInterceptorImage() {
    return utils.getText(1, this);
  }
  set containerEgressInterceptorImage(value) {
    utils.setText(1, value, this);
  }
  toString() {
    return "Worker_DockerConfiguration_" + super.toString();
  }
};
var Worker_DurableObjectStorage_Which = {
  /**
   * Default. The worker has no Durable Objects. `durableObjectNamespaces` must be empty, or
   * define all namespaces as `ephemeralLocal`, or this must be an abstract worker (meant to be
   * inherited by other workers, who will specify `durableObjectStorage`).
   *
   */
  NONE: 0,
  /**
   * The `state.storage` API stores in-memory only. All stored data will persist for the
   * lifetime of the process, but will be lost upon process exit.
   *
   * Individual objects will still shut down when idle as normal -- only data stored with the
   * `state.storage` interface is persistent for the lifetime of the process.
   *
   * This mode is intended for local testing purposes.
   *
   */
  IN_MEMORY: 1,
  /**
   * ** EXPERIMENTAL; SUBJECT TO BACKWARDS-INCOMPATIBLE CHANGE **
   *
   * Durable Object data will be stored in a directory on local disk. This field is the name of
   * a service, which must be a DiskDirectory service. For each Durable Object class, a
   * subdirectory will be created using `uniqueKey` as the name. Within the directory, one or
   * more files are created for each object, with names `<id>.<ext>`, where `.<ext>` may be any of
   * a number of different extensions depending on the storage mode. (Currently, the main storage
   * is a file with the extension `.sqlite`, and in certain situations extra files with the
   * extensions `.sqlite-wal`, and `.sqlite-shm` may also be present.)
   *
   */
  LOCAL_DISK: 2
};
var Worker_DurableObjectStorage = class extends Struct {
  static NONE = Worker_DurableObjectStorage_Which.NONE;
  static IN_MEMORY = Worker_DurableObjectStorage_Which.IN_MEMORY;
  static LOCAL_DISK = Worker_DurableObjectStorage_Which.LOCAL_DISK;
  static _capnp = {
    displayName: "durableObjectStorage",
    id: "cc72b3faa57827d4",
    size: new ObjectSize(8, 15)
  };
  get _isNone() {
    return utils.getUint16(2, this) === 0;
  }
  set none(_) {
    utils.setUint16(2, 0, this);
  }
  get _isInMemory() {
    return utils.getUint16(2, this) === 1;
  }
  set inMemory(_) {
    utils.setUint16(2, 1, this);
  }
  /**
   * ** EXPERIMENTAL; SUBJECT TO BACKWARDS-INCOMPATIBLE CHANGE **
   *
   * Durable Object data will be stored in a directory on local disk. This field is the name of
   * a service, which must be a DiskDirectory service. For each Durable Object class, a
   * subdirectory will be created using `uniqueKey` as the name. Within the directory, one or
   * more files are created for each object, with names `<id>.<ext>`, where `.<ext>` may be any of
   * a number of different extensions depending on the storage mode. (Currently, the main storage
   * is a file with the extension `.sqlite`, and in certain situations extra files with the
   * extensions `.sqlite-wal`, and `.sqlite-shm` may also be present.)
   *
   */
  get localDisk() {
    utils.testWhich("localDisk", utils.getUint16(2, this), 2, this);
    return utils.getText(8, this);
  }
  get _isLocalDisk() {
    return utils.getUint16(2, this) === 2;
  }
  set localDisk(value) {
    utils.setUint16(2, 2, this);
    utils.setText(8, value, this);
  }
  toString() {
    return "Worker_DurableObjectStorage_" + super.toString();
  }
  which() {
    return utils.getUint16(2, this);
  }
};
var Worker_ContainerEngine_Which = {
  /**
   * No container engine configured. Container operations will not be available.
   *
   */
  NONE: 0,
  /**
   * Use local Docker daemon for container operations.
   * Only used for local development and testing purposes.
   *
   */
  LOCAL_DOCKER: 1
};
var Worker_ContainerEngine = class extends Struct {
  static NONE = Worker_ContainerEngine_Which.NONE;
  static LOCAL_DOCKER = Worker_ContainerEngine_Which.LOCAL_DOCKER;
  static _capnp = {
    displayName: "containerEngine",
    id: "82de68f58dc2eb24",
    size: new ObjectSize(8, 15)
  };
  get _isNone() {
    return utils.getUint16(4, this) === 0;
  }
  set none(_) {
    utils.setUint16(4, 0, this);
  }
  _adoptLocalDocker(value) {
    utils.setUint16(4, 1, this);
    utils.adopt(value, utils.getPointer(12, this));
  }
  _disownLocalDocker() {
    return utils.disown(this.localDocker);
  }
  /**
   * Use local Docker daemon for container operations.
   * Only used for local development and testing purposes.
   *
   */
  get localDocker() {
    utils.testWhich("localDocker", utils.getUint16(4, this), 1, this);
    return utils.getStruct(12, Worker_DockerConfiguration, this);
  }
  _hasLocalDocker() {
    return !utils.isNull(utils.getPointer(12, this));
  }
  _initLocalDocker() {
    utils.setUint16(4, 1, this);
    return utils.initStructAt(12, Worker_DockerConfiguration, this);
  }
  get _isLocalDocker() {
    return utils.getUint16(4, this) === 1;
  }
  set localDocker(value) {
    utils.setUint16(4, 1, this);
    utils.copyFrom(value, utils.getPointer(12, this));
  }
  toString() {
    return "Worker_ContainerEngine_" + super.toString();
  }
  which() {
    return utils.getUint16(4, this);
  }
};
var Worker_Which = {
  /**
   * The Worker is composed of ES modules that may import each other. The first module in the list
   * is the main module, which exports event handlers.
   *
   */
  MODULES: 0,
  /**
   * The Worker is composed of one big script that uses global `addEventListener()` to register
   * event handlers.
   *
   * The value of this field is the raw source code. When using Cap'n Proto text format, use the
   * `embed` directive to read the code from an external file:
   *
   *     serviceWorkerScript = embed "worker.js"
   *
   */
  SERVICE_WORKER_SCRIPT: 1,
  /**
   * Inherit the configuration of some other Worker by its service name. This Worker is a clone
   * of the other worker, but various settings can be modified:
   * * `bindings`, if specified, overrides specific named bindings. (Each binding listed in the
   *   derived worker must match the name and type of some binding in the inherited worker.)
   * * `globalOutbound`, if non-null, overrides the one specified in the inherited worker.
   * * `compatibilityDate` and `compatibilityFlags` CANNOT be modified; they must be null.
   * * If the inherited worker defines durable object namespaces, then the derived worker must
   *   specify `durableObjectStorage` to specify where its instances should be stored. Each
   *   devived worker receives its own namespace of objects. `durableObjectUniqueKeyModifier`
   *   must also be specified by derived workers.
   *
   * This can be useful when you want to run the same Worker in multiple configurations or hooked
   * up to different back-ends. Note that all derived workers run in the same isolate as the
   * base worker; they differ in the content of the `env` object passed to them, which contains
   * the bindings. (When using service workers syntax, the global scope contains the bindings;
   * in this case each derived worker runs in its own global scope, though still in the same
   * isolate.)
   *
   */
  INHERIT: 2
};
var Worker = class _Worker extends Struct {
  static MODULES = Worker_Which.MODULES;
  static SERVICE_WORKER_SCRIPT = Worker_Which.SERVICE_WORKER_SCRIPT;
  static INHERIT = Worker_Which.INHERIT;
  static Module = Worker_Module;
  static Binding = Worker_Binding;
  static DurableObjectNamespace = Worker_DurableObjectNamespace;
  static DockerConfiguration = Worker_DockerConfiguration;
  static _capnp = {
    displayName: "Worker",
    id: "acfa77e88fd97d1c",
    size: new ObjectSize(8, 15),
    defaultGlobalOutbound: readRawPointer(
      new Uint8Array([
        16,
        7,
        80,
        1,
        3,
        0,
        0,
        17,
        9,
        74,
        0,
        1,
        255,
        105,
        110,
        116,
        101,
        114,
        110,
        101,
        116,
        0,
        0,
        0
      ]).buffer
    )
  };
  static _Modules;
  static _Bindings;
  static _DurableObjectNamespaces;
  static _Tails;
  static _StreamingTails;
  _adoptModules(value) {
    utils.setUint16(0, 0, this);
    utils.adopt(value, utils.getPointer(0, this));
  }
  _disownModules() {
    return utils.disown(this.modules);
  }
  /**
   * The Worker is composed of ES modules that may import each other. The first module in the list
   * is the main module, which exports event handlers.
   *
   */
  get modules() {
    utils.testWhich("modules", utils.getUint16(0, this), 0, this);
    return utils.getList(0, _Worker._Modules, this);
  }
  _hasModules() {
    return !utils.isNull(utils.getPointer(0, this));
  }
  _initModules(length) {
    utils.setUint16(0, 0, this);
    return utils.initList(0, _Worker._Modules, length, this);
  }
  get _isModules() {
    return utils.getUint16(0, this) === 0;
  }
  set modules(value) {
    utils.setUint16(0, 0, this);
    utils.copyFrom(value, utils.getPointer(0, this));
  }
  /**
   * The Worker is composed of one big script that uses global `addEventListener()` to register
   * event handlers.
   *
   * The value of this field is the raw source code. When using Cap'n Proto text format, use the
   * `embed` directive to read the code from an external file:
   *
   *     serviceWorkerScript = embed "worker.js"
   *
   */
  get serviceWorkerScript() {
    utils.testWhich(
      "serviceWorkerScript",
      utils.getUint16(0, this),
      1,
      this
    );
    return utils.getText(0, this);
  }
  get _isServiceWorkerScript() {
    return utils.getUint16(0, this) === 1;
  }
  set serviceWorkerScript(value) {
    utils.setUint16(0, 1, this);
    utils.setText(0, value, this);
  }
  /**
   * Inherit the configuration of some other Worker by its service name. This Worker is a clone
   * of the other worker, but various settings can be modified:
   * * `bindings`, if specified, overrides specific named bindings. (Each binding listed in the
   *   derived worker must match the name and type of some binding in the inherited worker.)
   * * `globalOutbound`, if non-null, overrides the one specified in the inherited worker.
   * * `compatibilityDate` and `compatibilityFlags` CANNOT be modified; they must be null.
   * * If the inherited worker defines durable object namespaces, then the derived worker must
   *   specify `durableObjectStorage` to specify where its instances should be stored. Each
   *   devived worker receives its own namespace of objects. `durableObjectUniqueKeyModifier`
   *   must also be specified by derived workers.
   *
   * This can be useful when you want to run the same Worker in multiple configurations or hooked
   * up to different back-ends. Note that all derived workers run in the same isolate as the
   * base worker; they differ in the content of the `env` object passed to them, which contains
   * the bindings. (When using service workers syntax, the global scope contains the bindings;
   * in this case each derived worker runs in its own global scope, though still in the same
   * isolate.)
   *
   */
  get inherit() {
    utils.testWhich("inherit", utils.getUint16(0, this), 2, this);
    return utils.getText(0, this);
  }
  get _isInherit() {
    return utils.getUint16(0, this) === 2;
  }
  set inherit(value) {
    utils.setUint16(0, 2, this);
    utils.setText(0, value, this);
  }
  get compatibilityDate() {
    return utils.getText(1, this);
  }
  set compatibilityDate(value) {
    utils.setText(1, value, this);
  }
  _adoptCompatibilityFlags(value) {
    utils.adopt(value, utils.getPointer(2, this));
  }
  _disownCompatibilityFlags() {
    return utils.disown(this.compatibilityFlags);
  }
  /**
   * See: https://developers.cloudflare.com/workers/platform/compatibility-dates/
   *
   * `compatibilityDate` must be specified, unless the Worker inhits from another worker, in which
   * case it must not be specified. `compatibilityFlags` can optionally be specified when
   * `compatibilityDate` is specified.
   *
   */
  get compatibilityFlags() {
    return utils.getList(2, TextList, this);
  }
  _hasCompatibilityFlags() {
    return !utils.isNull(utils.getPointer(2, this));
  }
  _initCompatibilityFlags(length) {
    return utils.initList(2, TextList, length, this);
  }
  set compatibilityFlags(value) {
    utils.copyFrom(value, utils.getPointer(2, this));
  }
  _adoptBindings(value) {
    utils.adopt(value, utils.getPointer(3, this));
  }
  _disownBindings() {
    return utils.disown(this.bindings);
  }
  /**
   * List of bindings, which give the Worker access to external resources and configuration
   * settings.
   *
   * For Workers using ES modules syntax, the bindings are delivered via the `env` object. For
   * service workers syntax, each binding shows up as a global variable.
   *
   */
  get bindings() {
    return utils.getList(3, _Worker._Bindings, this);
  }
  _hasBindings() {
    return !utils.isNull(utils.getPointer(3, this));
  }
  _initBindings(length) {
    return utils.initList(3, _Worker._Bindings, length, this);
  }
  set bindings(value) {
    utils.copyFrom(value, utils.getPointer(3, this));
  }
  _adoptGlobalOutbound(value) {
    utils.adopt(value, utils.getPointer(4, this));
  }
  _disownGlobalOutbound() {
    return utils.disown(this.globalOutbound);
  }
  /**
   * Where should the global "fetch" go to? The default is the service called "internet", which
   * should usually be configured to talk to the public internet.
   *
   */
  get globalOutbound() {
    return utils.getStruct(
      4,
      ServiceDesignator,
      this,
      _Worker._capnp.defaultGlobalOutbound
    );
  }
  _hasGlobalOutbound() {
    return !utils.isNull(utils.getPointer(4, this));
  }
  _initGlobalOutbound() {
    return utils.initStructAt(4, ServiceDesignator, this);
  }
  set globalOutbound(value) {
    utils.copyFrom(value, utils.getPointer(4, this));
  }
  _adoptCacheApiOutbound(value) {
    utils.adopt(value, utils.getPointer(7, this));
  }
  _disownCacheApiOutbound() {
    return utils.disown(this.cacheApiOutbound);
  }
  /**
   * Where should cache API (i.e. caches.default and caches.open(...)) requests go?
   *
   */
  get cacheApiOutbound() {
    return utils.getStruct(7, ServiceDesignator, this);
  }
  _hasCacheApiOutbound() {
    return !utils.isNull(utils.getPointer(7, this));
  }
  _initCacheApiOutbound() {
    return utils.initStructAt(7, ServiceDesignator, this);
  }
  set cacheApiOutbound(value) {
    utils.copyFrom(value, utils.getPointer(7, this));
  }
  _adoptDurableObjectNamespaces(value) {
    utils.adopt(value, utils.getPointer(5, this));
  }
  _disownDurableObjectNamespaces() {
    return utils.disown(this.durableObjectNamespaces);
  }
  /**
   * List of durable object namespaces in this Worker.
   *
   */
  get durableObjectNamespaces() {
    return utils.getList(5, _Worker._DurableObjectNamespaces, this);
  }
  _hasDurableObjectNamespaces() {
    return !utils.isNull(utils.getPointer(5, this));
  }
  _initDurableObjectNamespaces(length) {
    return utils.initList(5, _Worker._DurableObjectNamespaces, length, this);
  }
  set durableObjectNamespaces(value) {
    utils.copyFrom(value, utils.getPointer(5, this));
  }
  /**
   * Additional text which is hashed together with `DurableObjectNamespace.uniqueKey`. When using
   * worker inheritance, each derived worker must specify a unique modifier to ensure that its
   * Durable Object instances have unique IDs from all other workers inheriting the same parent.
   *
   * DO NOT LOSE this value, otherwise it may be difficult or impossible to recover stored data.
   *
   */
  get durableObjectUniqueKeyModifier() {
    return utils.getText(6, this);
  }
  set durableObjectUniqueKeyModifier(value) {
    utils.setText(6, value, this);
  }
  /**
   * Specifies where this worker's Durable Objects are stored.
   *
   */
  get durableObjectStorage() {
    return utils.getAs(Worker_DurableObjectStorage, this);
  }
  _initDurableObjectStorage() {
    return utils.getAs(Worker_DurableObjectStorage, this);
  }
  get moduleFallback() {
    return utils.getText(9, this);
  }
  set moduleFallback(value) {
    utils.setText(9, value, this);
  }
  _adoptTails(value) {
    utils.adopt(value, utils.getPointer(10, this));
  }
  _disownTails() {
    return utils.disown(this.tails);
  }
  /**
   * List of tail worker services that should receive tail events for this worker.
   * See: https://developers.cloudflare.com/workers/observability/logs/tail-workers/
   *
   */
  get tails() {
    return utils.getList(10, _Worker._Tails, this);
  }
  _hasTails() {
    return !utils.isNull(utils.getPointer(10, this));
  }
  _initTails(length) {
    return utils.initList(10, _Worker._Tails, length, this);
  }
  set tails(value) {
    utils.copyFrom(value, utils.getPointer(10, this));
  }
  _adoptStreamingTails(value) {
    utils.adopt(value, utils.getPointer(11, this));
  }
  _disownStreamingTails() {
    return utils.disown(this.streamingTails);
  }
  /**
   * List of streaming tail worker services that should receive tail events for this worker.
   * NOTE: This will be deleted in a future refactor, do not depend on this.
   *
   */
  get streamingTails() {
    return utils.getList(11, _Worker._StreamingTails, this);
  }
  _hasStreamingTails() {
    return !utils.isNull(utils.getPointer(11, this));
  }
  _initStreamingTails(length) {
    return utils.initList(11, _Worker._StreamingTails, length, this);
  }
  set streamingTails(value) {
    utils.copyFrom(value, utils.getPointer(11, this));
  }
  get containerEngine() {
    return utils.getAs(Worker_ContainerEngine, this);
  }
  _initContainerEngine() {
    return utils.getAs(Worker_ContainerEngine, this);
  }
  /**
   * Name of the HTTP header carrying per-request Cloudflare Access metadata for local dev.
   * When set, the worker reads this header from every incoming request to populate `ctx.access`.
   * The header value is a JSON object matching the production Access struct:
   *   { "app_aud": "<audience>", "jwt_claims": { ... } }
   * `app_aud` (string, required) populates `ctx.access.aud`.
   * `jwt_claims` (object, optional) is passed as `ctx.props.jwtClaims` to the access binding
   * worker (if configured via `accessBindingService`) when `ctx.access.getIdentity()` is called.
   * Requests that carry the header get `ctx.access` populated; requests without it get
   * `ctx.access === undefined`.
   *
   */
  get accessBlobHeader() {
    return utils.getText(13, this);
  }
  set accessBlobHeader(value) {
    utils.setText(13, value, this);
  }
  _adoptAccessBindingService(value) {
    utils.adopt(value, utils.getPointer(14, this));
  }
  _disownAccessBindingService() {
    return utils.disown(this.accessBindingService);
  }
  /**
   * Names a service that acts as the Cloudflare Access identity binding worker for local dev.
   * When `ctx.access.getIdentity()` is called, workerd dispatches a `getIdentity` JS-RPC method
   * on this service with per-request `props` set to `{ aud }` or `{ aud, jwtClaims }` (extracted
   * from the `accessBlobHeader` HTTP header; `jwtClaims` is included only when the optional
   * `jwt_claims` field is present in the header). This mimics the production path where an
   * Access binding worker resolves the identity from JWT claims.
   *
   * If not set, `ctx.access.getIdentity()` resolves to `undefined` (even when `accessBlobHeader`
   * is configured and `ctx.access.aud` is available).
   *
   */
  get accessBindingService() {
    return utils.getStruct(14, ServiceDesignator, this);
  }
  _hasAccessBindingService() {
    return !utils.isNull(utils.getPointer(14, this));
  }
  _initAccessBindingService() {
    return utils.initStructAt(14, ServiceDesignator, this);
  }
  set accessBindingService(value) {
    utils.copyFrom(value, utils.getPointer(14, this));
  }
  toString() {
    return "Worker_" + super.toString();
  }
  which() {
    return utils.getUint16(0, this);
  }
};
var ExternalServer_Https = class extends Struct {
  static _capnp = {
    displayName: "https",
    id: "ac37e02afd3dc6db",
    size: new ObjectSize(8, 4)
  };
  _adoptOptions(value) {
    utils.adopt(value, utils.getPointer(1, this));
  }
  _disownOptions() {
    return utils.disown(this.options);
  }
  get options() {
    return utils.getStruct(1, HttpOptions, this);
  }
  _hasOptions() {
    return !utils.isNull(utils.getPointer(1, this));
  }
  _initOptions() {
    return utils.initStructAt(1, HttpOptions, this);
  }
  set options(value) {
    utils.copyFrom(value, utils.getPointer(1, this));
  }
  _adoptTlsOptions(value) {
    utils.adopt(value, utils.getPointer(2, this));
  }
  _disownTlsOptions() {
    return utils.disown(this.tlsOptions);
  }
  get tlsOptions() {
    return utils.getStruct(2, TlsOptions, this);
  }
  _hasTlsOptions() {
    return !utils.isNull(utils.getPointer(2, this));
  }
  _initTlsOptions() {
    return utils.initStructAt(2, TlsOptions, this);
  }
  set tlsOptions(value) {
    utils.copyFrom(value, utils.getPointer(2, this));
  }
  /**
   * If present, expect the host to present a certificate authenticating it as this hostname.
   * If `certificateHost` is not provided, then the certificate is checked against `address`.
   *
   */
  get certificateHost() {
    return utils.getText(3, this);
  }
  set certificateHost(value) {
    utils.setText(3, value, this);
  }
  toString() {
    return "ExternalServer_Https_" + super.toString();
  }
};
var ExternalServer_Tcp = class extends Struct {
  static _capnp = {
    displayName: "tcp",
    id: "d941637df0fb39f1",
    size: new ObjectSize(8, 4)
  };
  _adoptTlsOptions(value) {
    utils.adopt(value, utils.getPointer(1, this));
  }
  _disownTlsOptions() {
    return utils.disown(this.tlsOptions);
  }
  get tlsOptions() {
    return utils.getStruct(1, TlsOptions, this);
  }
  _hasTlsOptions() {
    return !utils.isNull(utils.getPointer(1, this));
  }
  _initTlsOptions() {
    return utils.initStructAt(1, TlsOptions, this);
  }
  set tlsOptions(value) {
    utils.copyFrom(value, utils.getPointer(1, this));
  }
  get certificateHost() {
    return utils.getText(2, this);
  }
  set certificateHost(value) {
    utils.setText(2, value, this);
  }
  toString() {
    return "ExternalServer_Tcp_" + super.toString();
  }
};
var ExternalServer_Which = {
  /**
   * Talk to the server over unencrypted HTTP.
   *
   */
  HTTP: 0,
  /**
   * Talk to the server over encrypted HTTPS.
   *
   */
  HTTPS: 1,
  /**
   * Connect to the server over raw TCP. Bindings to this service will only support the
   * `connect()` method; `fetch()` will throw an exception.
   *
   */
  TCP: 2
};
var ExternalServer = class extends Struct {
  static HTTP = ExternalServer_Which.HTTP;
  static HTTPS = ExternalServer_Which.HTTPS;
  static TCP = ExternalServer_Which.TCP;
  static _capnp = {
    displayName: "ExternalServer",
    id: "ff209f9aa352f5a4",
    size: new ObjectSize(8, 4)
  };
  /**
   * Address/port of the server. Optional; if not specified, then you will be required to specify
   * the address on the command line with with `--external-addr <name>=<addr>`.
   *
   * Examples:
   * - "1.2.3.4": Connect to the given IPv4 address on the protocol's default port.
   * - "1.2.3.4:80": Connect to the given IPv4 address and port.
   * - "1234:5678::abcd": Connect to the given IPv6 address on the protocol's default port.
   * - "[1234:5678::abcd]:80": Connect to the given IPv6 address and port.
   * - "unix:/path/to/socket": Connect to the given Unix Domain socket by path.
   * - "unix-abstract:name": On Linux, connect to the given "abstract" Unix socket name.
   * - "example.com:80": Perform a DNS lookup to determine the address, and then connect to it.
   *
   * (These are the formats supported by KJ's parseAddress().)
   *
   */
  get address() {
    return utils.getText(0, this);
  }
  set address(value) {
    utils.setText(0, value, this);
  }
  _adoptHttp(value) {
    utils.setUint16(0, 0, this);
    utils.adopt(value, utils.getPointer(1, this));
  }
  _disownHttp() {
    return utils.disown(this.http);
  }
  /**
   * Talk to the server over unencrypted HTTP.
   *
   */
  get http() {
    utils.testWhich("http", utils.getUint16(0, this), 0, this);
    return utils.getStruct(1, HttpOptions, this);
  }
  _hasHttp() {
    return !utils.isNull(utils.getPointer(1, this));
  }
  _initHttp() {
    utils.setUint16(0, 0, this);
    return utils.initStructAt(1, HttpOptions, this);
  }
  get _isHttp() {
    return utils.getUint16(0, this) === 0;
  }
  set http(value) {
    utils.setUint16(0, 0, this);
    utils.copyFrom(value, utils.getPointer(1, this));
  }
  /**
   * Talk to the server over encrypted HTTPS.
   *
   */
  get https() {
    utils.testWhich("https", utils.getUint16(0, this), 1, this);
    return utils.getAs(ExternalServer_Https, this);
  }
  _initHttps() {
    utils.setUint16(0, 1, this);
    return utils.getAs(ExternalServer_Https, this);
  }
  get _isHttps() {
    return utils.getUint16(0, this) === 1;
  }
  set https(_) {
    utils.setUint16(0, 1, this);
  }
  /**
   * Connect to the server over raw TCP. Bindings to this service will only support the
   * `connect()` method; `fetch()` will throw an exception.
   *
   */
  get tcp() {
    utils.testWhich("tcp", utils.getUint16(0, this), 2, this);
    return utils.getAs(ExternalServer_Tcp, this);
  }
  _initTcp() {
    utils.setUint16(0, 2, this);
    return utils.getAs(ExternalServer_Tcp, this);
  }
  get _isTcp() {
    return utils.getUint16(0, this) === 2;
  }
  set tcp(_) {
    utils.setUint16(0, 2, this);
  }
  toString() {
    return "ExternalServer_" + super.toString();
  }
  which() {
    return utils.getUint16(0, this);
  }
};
var Network = class _Network extends Struct {
  static _capnp = {
    displayName: "Network",
    id: "fa42244f950c9b9c",
    size: new ObjectSize(0, 3),
    defaultAllow: readRawPointer(
      new Uint8Array([
        16,
        3,
        17,
        1,
        14,
        17,
        1,
        58,
        63,
        112,
        117,
        98,
        108,
        105,
        99
      ]).buffer
    )
  };
  _adoptAllow(value) {
    utils.adopt(value, utils.getPointer(0, this));
  }
  _disownAllow() {
    return utils.disown(this.allow);
  }
  get allow() {
    return utils.getList(0, TextList, this, _Network._capnp.defaultAllow);
  }
  _hasAllow() {
    return !utils.isNull(utils.getPointer(0, this));
  }
  _initAllow(length) {
    return utils.initList(0, TextList, length, this);
  }
  set allow(value) {
    utils.copyFrom(value, utils.getPointer(0, this));
  }
  _adoptDeny(value) {
    utils.adopt(value, utils.getPointer(1, this));
  }
  _disownDeny() {
    return utils.disown(this.deny);
  }
  /**
   * Specifies which network addresses the Worker will be allowed to connect to, e.g. using fetch().
   * The default allows publicly-routable IP addresses only, in order to prevent SSRF attacks.
   *
   * The allow and deny lists specify network blocks in CIDR notation (IPv4 and IPv6), such as
   * "192.0.2.0/24" or "2001:db8::/32". Traffic will be permitted as long as the address
   * matches at least one entry in the allow list and none in the deny list.
   *
   * In addition to IPv4 and IPv6 CIDR notation, several special strings may be specified:
   * - "private": Matches network addresses that are reserved by standards for private networks,
   *   such as "10.0.0.0/8" or "192.168.0.0/16". This is a superset of "local".
   * - "public": Opposite of "private".
   * - "local": Matches network addresses that are defined by standards to only be accessible from
   *   the local machine, such as "127.0.0.0/8" or Unix domain addresses.
   * - "network": Opposite of "local".
   * - "unix": Matches all Unix domain socket addresses. (In the future, we may support specifying a
   *   glob to narrow this to specific paths.)
   * - "unix-abstract": Matches Linux's "abstract unix domain" addresses. (In the future, we may
   *   support specifying a glob.)
   *
   * In the case that the Worker specifies a DNS hostname rather than a raw address, these rules are
   * used to filter the addresses returned by the lookup. If none of the returned addresses turn
   * out to be permitted, then the system will behave as if the DNS entry did not exist.
   *
   * (The above is exactly the format supported by kj::Network::restrictPeers().)
   *
   */
  get deny() {
    return utils.getList(1, TextList, this);
  }
  _hasDeny() {
    return !utils.isNull(utils.getPointer(1, this));
  }
  _initDeny(length) {
    return utils.initList(1, TextList, length, this);
  }
  set deny(value) {
    utils.copyFrom(value, utils.getPointer(1, this));
  }
  _adoptTlsOptions(value) {
    utils.adopt(value, utils.getPointer(2, this));
  }
  _disownTlsOptions() {
    return utils.disown(this.tlsOptions);
  }
  get tlsOptions() {
    return utils.getStruct(2, TlsOptions, this);
  }
  _hasTlsOptions() {
    return !utils.isNull(utils.getPointer(2, this));
  }
  _initTlsOptions() {
    return utils.initStructAt(2, TlsOptions, this);
  }
  set tlsOptions(value) {
    utils.copyFrom(value, utils.getPointer(2, this));
  }
  toString() {
    return "Network_" + super.toString();
  }
};
var DiskDirectory = class _DiskDirectory extends Struct {
  static _capnp = {
    displayName: "DiskDirectory",
    id: "9048ab22835f51c3",
    size: new ObjectSize(8, 1),
    defaultWritable: getBitMask(false, 0),
    defaultAllowDotfiles: getBitMask(false, 1)
  };
  /**
   * The filesystem path of the directory. If not specified, then it must be specified on the
   * command line with `--directory-path <service-name>=<path>`.
   *
   * Relative paths are interpreted relative to the current directory where the server is executed,
   * NOT relative to the config file. So, you should usually use absolute paths in the config file.
   *
   */
  get path() {
    return utils.getText(0, this);
  }
  set path(value) {
    utils.setText(0, value, this);
  }
  /**
   * Whether to support PUT requests for writing. A PUT will write to a temporary file which
   * is atomically moved into place upon successful completion of the upload. Parent directories are
   * created as needed.
   *
   */
  get writable() {
    return utils.getBit(0, this, _DiskDirectory._capnp.defaultWritable);
  }
  set writable(value) {
    utils.setBit(0, value, this, _DiskDirectory._capnp.defaultWritable);
  }
  /**
   * Whether to allow access to files and directories whose name starts with '.'. These are made
   * inaccessible by default since they very often store metadata that is not meant to be served,
   * e.g. a git repository or an `.htaccess` file.
   *
   * Note that the special links "." and ".." will never be accessible regardless of this setting.
   *
   */
  get allowDotfiles() {
    return utils.getBit(1, this, _DiskDirectory._capnp.defaultAllowDotfiles);
  }
  set allowDotfiles(value) {
    utils.setBit(1, value, this, _DiskDirectory._capnp.defaultAllowDotfiles);
  }
  toString() {
    return "DiskDirectory_" + super.toString();
  }
};
var HttpOptions_Style = {
  /**
   * Normal HTTP. The request line contains only the path, and the separate `Host` header
   * specifies the hostname.
   *
   */
  HOST: 0,
  /**
   * HTTP proxy protocol. The request line contains a full URL instead of a path. No `Host`
   * header is required. This is the protocol used by HTTP forward proxies. This allows you to
   * implement such a proxy as a Worker.
   *
   */
  PROXY: 1
};
var HttpOptions_Header = class extends Struct {
  static _capnp = {
    displayName: "Header",
    id: "dc0394b5a6f3417e",
    size: new ObjectSize(0, 2)
  };
  /**
   * Case-insensitive.
   *
   */
  get name() {
    return utils.getText(0, this);
  }
  set name(value) {
    utils.setText(0, value, this);
  }
  /**
   * If null, the header will be removed.
   *
   */
  get value() {
    return utils.getText(1, this);
  }
  set value(value) {
    utils.setText(1, value, this);
  }
  toString() {
    return "HttpOptions_Header_" + super.toString();
  }
};
var HttpOptions = class _HttpOptions extends Struct {
  static Style = HttpOptions_Style;
  static Header = HttpOptions_Header;
  static _capnp = {
    displayName: "HttpOptions",
    id: "aa8dc6885da78f19",
    size: new ObjectSize(8, 5),
    defaultStyle: getUint16Mask(0)
  };
  static _InjectRequestHeaders;
  static _InjectResponseHeaders;
  get style() {
    return utils.getUint16(
      0,
      this,
      _HttpOptions._capnp.defaultStyle
    );
  }
  set style(value) {
    utils.setUint16(0, value, this, _HttpOptions._capnp.defaultStyle);
  }
  /**
   * If specified, then when the given header is present on a request, it specifies the protocol
   * ("http" or "https") that was used by the original client. The request URL reported to the
   * Worker will reflect this protocol. Otherwise, the URL will reflect the actual physical protocol
   * used by the server in receiving the request.
   *
   * This option is useful when this server sits behind a reverse proxy that performs TLS
   * termination. Typically such proxies forward the original protocol in a header named something
   * like "X-Forwarded-Proto".
   *
   * This setting is ignored when `style` is `proxy`.
   *
   */
  get forwardedProtoHeader() {
    return utils.getText(0, this);
  }
  set forwardedProtoHeader(value) {
    utils.setText(0, value, this);
  }
  /**
   * If set, then the `request.cf` object will be encoded (as JSON) into / parsed from the header
   * with this name. Otherwise, it will be discarded on send / `undefined` on receipt.
   *
   */
  get cfBlobHeader() {
    return utils.getText(1, this);
  }
  set cfBlobHeader(value) {
    utils.setText(1, value, this);
  }
  _adoptInjectRequestHeaders(value) {
    utils.adopt(value, utils.getPointer(2, this));
  }
  _disownInjectRequestHeaders() {
    return utils.disown(this.injectRequestHeaders);
  }
  /**
   * List of headers which will be automatically injected into all requests. This can be used
   * e.g. to add an authorization token to all requests when using `ExternalServer`. It can also
   * apply to incoming requests received on a `Socket` to modify the headers that will be delivered
   * to the app. Any existing header with the same name is removed.
   *
   */
  get injectRequestHeaders() {
    return utils.getList(2, _HttpOptions._InjectRequestHeaders, this);
  }
  _hasInjectRequestHeaders() {
    return !utils.isNull(utils.getPointer(2, this));
  }
  _initInjectRequestHeaders(length) {
    return utils.initList(2, _HttpOptions._InjectRequestHeaders, length, this);
  }
  set injectRequestHeaders(value) {
    utils.copyFrom(value, utils.getPointer(2, this));
  }
  _adoptInjectResponseHeaders(value) {
    utils.adopt(value, utils.getPointer(3, this));
  }
  _disownInjectResponseHeaders() {
    return utils.disown(this.injectResponseHeaders);
  }
  /**
   * Same as `injectRequestHeaders` but for responses.
   *
   */
  get injectResponseHeaders() {
    return utils.getList(3, _HttpOptions._InjectResponseHeaders, this);
  }
  _hasInjectResponseHeaders() {
    return !utils.isNull(utils.getPointer(3, this));
  }
  _initInjectResponseHeaders(length) {
    return utils.initList(
      3,
      _HttpOptions._InjectResponseHeaders,
      length,
      this
    );
  }
  set injectResponseHeaders(value) {
    utils.copyFrom(value, utils.getPointer(3, this));
  }
  /**
   * A CONNECT request for this host+port will be treated as a request to form a Cap'n Proto RPC
   * connection. The server will expose a WorkerdBootstrap as the bootstrap interface, allowing
   * events to be delivered to the target worker via capnp. Clients will use capnp for non-HTTP
   * event types (especially JSRPC).
   *
   */
  get capnpConnectHost() {
    return utils.getText(4, this);
  }
  set capnpConnectHost(value) {
    utils.setText(4, value, this);
  }
  toString() {
    return "HttpOptions_" + super.toString();
  }
};
var TlsOptions_Keypair = class extends Struct {
  static _capnp = {
    displayName: "Keypair",
    id: "f546bf2d5d8bd13e",
    size: new ObjectSize(0, 2)
  };
  /**
   * Private key in PEM format. Supports PKCS8 keys as well as "traditional format" RSA and DSA
   * keys.
   *
   * Remember that you can use Cap'n Proto's `embed` syntax to reference an external file.
   *
   */
  get privateKey() {
    return utils.getText(0, this);
  }
  set privateKey(value) {
    utils.setText(0, value, this);
  }
  /**
   * Certificate chain in PEM format. A chain can be constructed by concatenating multiple
   * PEM-encoded certificates, starting with the leaf certificate.
   *
   */
  get certificateChain() {
    return utils.getText(1, this);
  }
  set certificateChain(value) {
    utils.setText(1, value, this);
  }
  toString() {
    return "TlsOptions_Keypair_" + super.toString();
  }
};
var TlsOptions_Version = {
  /**
   * A good default chosen by the code maintainers. May change over time.
   *
   */
  GOOD_DEFAULT: 0,
  SSL3: 1,
  TLS1DOT0: 2,
  TLS1DOT1: 3,
  TLS1DOT2: 4,
  TLS1DOT3: 5
};
var TlsOptions = class _TlsOptions extends Struct {
  static Keypair = TlsOptions_Keypair;
  static Version = TlsOptions_Version;
  static _capnp = {
    displayName: "TlsOptions",
    id: "aabb3c3778ac4311",
    size: new ObjectSize(8, 3),
    defaultRequireClientCerts: getBitMask(false, 0),
    defaultTrustBrowserCas: getBitMask(false, 1),
    defaultMinVersion: getUint16Mask(0)
  };
  _adoptKeypair(value) {
    utils.adopt(value, utils.getPointer(0, this));
  }
  _disownKeypair() {
    return utils.disown(this.keypair);
  }
  /**
   * The default private key and certificate to use. Optional when acting as a client.
   *
   */
  get keypair() {
    return utils.getStruct(0, TlsOptions_Keypair, this);
  }
  _hasKeypair() {
    return !utils.isNull(utils.getPointer(0, this));
  }
  _initKeypair() {
    return utils.initStructAt(0, TlsOptions_Keypair, this);
  }
  set keypair(value) {
    utils.copyFrom(value, utils.getPointer(0, this));
  }
  /**
   * If true, then when acting as a server, incoming connections will be rejected unless they bear
   * a certificate signed by one of the trusted CAs.
   *
   * Typically, when using this, you'd set `trustBrowserCas = false` and list a specific private CA
   * in `trustedCertificates`.
   *
   */
  get requireClientCerts() {
    return utils.getBit(0, this, _TlsOptions._capnp.defaultRequireClientCerts);
  }
  set requireClientCerts(value) {
    utils.setBit(0, value, this, _TlsOptions._capnp.defaultRequireClientCerts);
  }
  /**
   * If true, trust certificates which are signed by one of the CAs that browsers normally trust.
   * You should typically set this true when talking to the public internet, but you may want to
   * set it false when talking to servers on your internal network.
   *
   */
  get trustBrowserCas() {
    return utils.getBit(1, this, _TlsOptions._capnp.defaultTrustBrowserCas);
  }
  set trustBrowserCas(value) {
    utils.setBit(1, value, this, _TlsOptions._capnp.defaultTrustBrowserCas);
  }
  _adoptTrustedCertificates(value) {
    utils.adopt(value, utils.getPointer(1, this));
  }
  _disownTrustedCertificates() {
    return utils.disown(this.trustedCertificates);
  }
  /**
   * Additional CA certificates to trust, in PEM format. Remember that you can use Cap'n Proto's
   * `embed` syntax to read the certificates from other files.
   *
   */
  get trustedCertificates() {
    return utils.getList(1, TextList, this);
  }
  _hasTrustedCertificates() {
    return !utils.isNull(utils.getPointer(1, this));
  }
  _initTrustedCertificates(length) {
    return utils.initList(1, TextList, length, this);
  }
  set trustedCertificates(value) {
    utils.copyFrom(value, utils.getPointer(1, this));
  }
  /**
   * Minimum TLS version that will be allowed. Generally you should not override this unless you
   * have unusual backwards-compatibility needs.
   *
   */
  get minVersion() {
    return utils.getUint16(
      2,
      this,
      _TlsOptions._capnp.defaultMinVersion
    );
  }
  set minVersion(value) {
    utils.setUint16(2, value, this, _TlsOptions._capnp.defaultMinVersion);
  }
  /**
   * OpenSSL cipher list string. The default is a curated list designed to be compatible with
   * almost all software in current use (specifically, based on Mozilla's "intermediate"
   * recommendations). The defaults will change in future versions of this software to account
   * for the latest cryptanalysis.
   *
   * Generally you should only specify your own `cipherList` if:
   * - You have extreme backwards-compatibility needs and wish to enable obsolete and/or broken
   *   algorithms.
   * - You need quickly to disable an algorithm recently discovered to be broken.
   *
   */
  get cipherList() {
    return utils.getText(2, this);
  }
  set cipherList(value) {
    utils.setText(2, value, this);
  }
  toString() {
    return "TlsOptions_" + super.toString();
  }
};
var Extension_Module = class _Extension_Module extends Struct {
  static _capnp = {
    displayName: "Module",
    id: "d5d16e76fdedc37d",
    size: new ObjectSize(8, 2),
    defaultInternal: getBitMask(false, 0)
  };
  /**
   * Full js module name. Must be a fully-qualified URL with a non-file: scheme,
   * e.g. "my-extension:module". Workers using the new_module_registry
   * compatibility flag reject extensions whose module names are not valid URLs;
   * the original module registry tolerates any path-like name, but new
   * extensions should always use the URL form.
   *
   */
  get name() {
    return utils.getText(0, this);
  }
  set name(value) {
    utils.setText(0, value, this);
  }
  /**
   * Internal modules can be imported by other extension modules only and not the user code.
   *
   */
  get internal() {
    return utils.getBit(0, this, _Extension_Module._capnp.defaultInternal);
  }
  set internal(value) {
    utils.setBit(0, value, this, _Extension_Module._capnp.defaultInternal);
  }
  /**
   * Raw source code of ES module.
   *
   */
  get esModule() {
    return utils.getText(1, this);
  }
  set esModule(value) {
    utils.setText(1, value, this);
  }
  toString() {
    return "Extension_Module_" + super.toString();
  }
};
var Extension = class _Extension extends Struct {
  static Module = Extension_Module;
  static _capnp = {
    displayName: "Extension",
    id: "e390128a861973a6",
    size: new ObjectSize(0, 1)
  };
  static _Modules;
  _adoptModules(value) {
    utils.adopt(value, utils.getPointer(0, this));
  }
  _disownModules() {
    return utils.disown(this.modules);
  }
  /**
   * List of javascript modules provided by the extension.
   * These modules can either be imported directly as user-level api (if not marked internal)
   * or used to define more complicated workerd constructs such as wrapped bindings and events.
   *
   */
  get modules() {
    return utils.getList(0, _Extension._Modules, this);
  }
  _hasModules() {
    return !utils.isNull(utils.getPointer(0, this));
  }
  _initModules(length) {
    return utils.initList(0, _Extension._Modules, length, this);
  }
  set modules(value) {
    utils.copyFrom(value, utils.getPointer(0, this));
  }
  toString() {
    return "Extension_" + super.toString();
  }
};
var FallbackServiceRequest_Attribute = class extends Struct {
  static _capnp = {
    displayName: "Attribute",
    id: "ecfe563249c01f75",
    size: new ObjectSize(0, 2)
  };
  get name() {
    return utils.getText(0, this);
  }
  set name(value) {
    utils.setText(0, value, this);
  }
  get value() {
    return utils.getText(1, this);
  }
  set value(value) {
    utils.setText(1, value, this);
  }
  toString() {
    return "FallbackServiceRequest_Attribute_" + super.toString();
  }
};
var FallbackServiceRequest = class _FallbackServiceRequest extends Struct {
  static Attribute = FallbackServiceRequest_Attribute;
  static _capnp = {
    displayName: "FallbackServiceRequest",
    id: "daf79e36b3f32800",
    size: new ObjectSize(0, 5)
  };
  static _Attributes;
  get type() {
    return utils.getText(0, this);
  }
  set type(value) {
    utils.setText(0, value, this);
  }
  get specifier() {
    return utils.getText(1, this);
  }
  set specifier(value) {
    utils.setText(1, value, this);
  }
  get rawSpecifier() {
    return utils.getText(2, this);
  }
  set rawSpecifier(value) {
    utils.setText(2, value, this);
  }
  get referrer() {
    return utils.getText(3, this);
  }
  set referrer(value) {
    utils.setText(3, value, this);
  }
  _adoptAttributes(value) {
    utils.adopt(value, utils.getPointer(4, this));
  }
  _disownAttributes() {
    return utils.disown(this.attributes);
  }
  get attributes() {
    return utils.getList(4, _FallbackServiceRequest._Attributes, this);
  }
  _hasAttributes() {
    return !utils.isNull(utils.getPointer(4, this));
  }
  _initAttributes(length) {
    return utils.initList(
      4,
      _FallbackServiceRequest._Attributes,
      length,
      this
    );
  }
  set attributes(value) {
    utils.copyFrom(value, utils.getPointer(4, this));
  }
  toString() {
    return "FallbackServiceRequest_" + super.toString();
  }
};
Config._Services = CompositeList(Service);
Config._Sockets = CompositeList(Socket);
Config._Extensions = CompositeList(Extension);
Worker_Binding_WrappedBinding._InnerBindings = CompositeList(Worker_Binding);
Worker_DurableObjectNamespace_ContainerOptions_ContainerPrivileges._Devices = CompositeList(
  Worker_DurableObjectNamespace_ContainerOptions_ContainerPrivileges_Device
);
Worker._Modules = CompositeList(Worker_Module);
Worker._Bindings = CompositeList(Worker_Binding);
Worker._DurableObjectNamespaces = CompositeList(
  Worker_DurableObjectNamespace
);
Worker._Tails = CompositeList(ServiceDesignator);
Worker._StreamingTails = CompositeList(ServiceDesignator);
HttpOptions._InjectRequestHeaders = CompositeList(HttpOptions_Header);
HttpOptions._InjectResponseHeaders = CompositeList(HttpOptions_Header);
Extension._Modules = CompositeList(Extension_Module);
FallbackServiceRequest._Attributes = CompositeList(
  FallbackServiceRequest_Attribute
);

// src/runtime/config/workerd.ts
var kVoid = /* @__PURE__ */ Symbol("kVoid");

// src/config/current-worker.ts
var kCurrentWorker = /* @__PURE__ */ Symbol.for("miniflare.kCurrentWorker");

// src/config/schema.ts
var AbsolutePathSchema = external_exports2.string().refine((value) => import_node_path7.default.isAbsolute(value), {
  message: "Path must be absolute"
});
var MiniflareModuleSchema = external_exports2.strictObject({
  type: ModuleTypeSchema,
  contents: external_exports2.union([external_exports2.string(), external_exports2.instanceof(Uint8Array)])
});
var MiniflareManifestSchema = external_exports2.strictObject({
  mainModule: external_exports2.string(),
  /** Absolute source directory for manifest module names. Defaults to cwd. */
  modulesRoot: AbsolutePathSchema.default(() => process.cwd()),
  modules: external_exports2.record(external_exports2.string(), MiniflareModuleSchema)
});
var FetcherBindingSchema = external_exports2.strictObject({
  type: external_exports2.literal("fetcher"),
  handler: external_exports2.custom((v) => typeof v === "function")
});
var NodeHandlerBindingSchema = external_exports2.strictObject({
  type: external_exports2.literal("node-handler"),
  handler: external_exports2.custom((v) => typeof v === "function")
});
var HttpOptionsHeaderSchema = external_exports2.strictObject({
  name: external_exports2.string(),
  // If omitted, the header will be removed.
  value: external_exports2.string().optional()
});
var HttpOptionsSchema = external_exports2.strictObject({
  style: external_exports2.enum(HttpOptions_Style).optional(),
  forwardedProtoHeader: external_exports2.string().optional(),
  cfBlobHeader: external_exports2.string().optional(),
  injectRequestHeaders: HttpOptionsHeaderSchema.array().optional(),
  injectResponseHeaders: HttpOptionsHeaderSchema.array().optional()
}).transform((options) => ({
  ...options,
  capnpConnectHost: HOST_CAPNP_CONNECT
}));
var TlsOptionsKeypairSchema = external_exports2.strictObject({
  privateKey: external_exports2.string().optional(),
  certificateChain: external_exports2.string().optional()
});
var TlsOptionsSchema = external_exports2.strictObject({
  keypair: TlsOptionsKeypairSchema.optional(),
  requireClientCerts: external_exports2.boolean().optional(),
  trustBrowserCas: external_exports2.boolean().optional(),
  trustedCertificates: external_exports2.string().array().optional(),
  minVersion: external_exports2.enum(TlsOptions_Version).optional(),
  cipherList: external_exports2.string().optional()
});
var NetworkServiceBindingSchema = external_exports2.strictObject({
  type: external_exports2.literal("network"),
  allow: external_exports2.string().array().optional(),
  deny: external_exports2.string().array().optional(),
  tlsOptions: TlsOptionsSchema.optional()
});
var ExternalServiceBindingSchema = external_exports2.strictObject({
  type: external_exports2.literal("external"),
  address: external_exports2.string(),
  http: HttpOptionsSchema.optional(),
  https: external_exports2.strictObject({
    options: HttpOptionsSchema.optional(),
    tlsOptions: TlsOptionsSchema.optional(),
    certificateHost: external_exports2.string().optional()
  }).optional()
}).refine((data) => !(data.http !== void 0 && data.https !== void 0), {
  message: "Cannot specify both 'http' and 'https'"
});
var DiskServiceBindingSchema = external_exports2.strictObject({
  type: external_exports2.literal("disk"),
  /** Directory served by the workerd disk service; passed through as-is. */
  path: external_exports2.string(),
  writable: external_exports2.boolean().optional()
});
var MiniflareBrowserBindingSchema = BrowserBindingSchema.extend({
  headful: external_exports2.boolean().optional()
});
var MiniflareR2BindingSchema = R2BindingSchema.extend({
  s3Credentials: external_exports2.object({
    accessKeyId: external_exports2.string(),
    secretAccessKey: external_exports2.string()
  }).optional()
});
var MiniflareHyperdriveBindingSchema = HyperdriveBindingSchema.omit({
  localConnectionString: true
}).extend({ localConnectionString: external_exports2.string() });
var MiniflareWorkerBindingSchema = WorkerBindingSchema.extend({
  workerName: external_exports2.union([
    external_exports2.string(),
    external_exports2.custom((v) => v === kCurrentWorker)
  ])
});
var HelloWorldBindingSchema = external_exports2.strictObject({
  type: external_exports2.literal("hello-world"),
  enable_timer: external_exports2.boolean().optional()
});
var MiniflareWorkflowBindingSchema = external_exports2.strictObject({
  type: external_exports2.literal("workflow"),
  name: external_exports2.string(),
  workerName: external_exports2.string(),
  exportName: external_exports2.string(),
  limits: external_exports2.strictObject({ steps: external_exports2.number().optional() }).optional(),
  remote: external_exports2.boolean().optional()
});
var OVERRIDDEN_BASE_BINDING_SCHEMAS = [
  BrowserBindingSchema,
  WorkerBindingSchema,
  R2BindingSchema,
  HyperdriveBindingSchema
];
var PassthroughBindingSchemas = KnownBindingSchema.options.filter(
  (option) => !OVERRIDDEN_BASE_BINDING_SCHEMAS.includes(option)
);
var MiniflareKnownBindingSchema = external_exports2.discriminatedUnion("type", [
  MiniflareBrowserBindingSchema,
  MiniflareR2BindingSchema,
  MiniflareHyperdriveBindingSchema,
  MiniflareWorkerBindingSchema,
  FetcherBindingSchema,
  NodeHandlerBindingSchema,
  ExternalServiceBindingSchema,
  NetworkServiceBindingSchema,
  DiskServiceBindingSchema,
  HelloWorldBindingSchema,
  MiniflareWorkflowBindingSchema,
  ...PassthroughBindingSchemas
]);
var ParsedMiniflareKVBindingSchema = KVBindingSchema.omit({
  id: true
}).extend({
  id: external_exports2.string()
});
var ParsedMiniflareD1BindingSchema = D1BindingSchema.omit({
  id: true
}).extend({
  id: external_exports2.string()
});
var ParsedMiniflareFlagshipBindingSchema = FlagshipBindingSchema.omit({
  id: true
}).extend({
  id: external_exports2.string()
});
var ParsedMiniflareR2BindingSchema = MiniflareR2BindingSchema.omit({
  name: true
}).extend({
  name: external_exports2.string()
});
var ParsedMiniflareQueueBindingSchema = QueueBindingSchema.omit({
  name: true
}).extend({
  name: external_exports2.string()
});
var OVERRIDDEN_PARSED_BINDING_SCHEMAS = [
  KVBindingSchema,
  D1BindingSchema,
  FlagshipBindingSchema,
  MiniflareR2BindingSchema,
  QueueBindingSchema
];
var ParsedPassthroughBindingSchemas = MiniflareKnownBindingSchema.options.filter(
  (option) => !OVERRIDDEN_PARSED_BINDING_SCHEMAS.includes(
    option
  )
);
var ParsedMiniflareKnownBindingSchema = external_exports2.discriminatedUnion("type", [
  ParsedMiniflareKVBindingSchema,
  ParsedMiniflareD1BindingSchema,
  ParsedMiniflareFlagshipBindingSchema,
  ParsedMiniflareR2BindingSchema,
  ParsedMiniflareQueueBindingSchema,
  ...ParsedPassthroughBindingSchemas
]);
var MiniflareBindingSchema = external_exports2.unknown().transform((value, ctx) => {
  const isUnsafe = typeof value === "object" && value !== null && "type" in value && typeof value.type === "string" && value.type.startsWith("unsafe:");
  const schema = isUnsafe ? UnsafeBindingSchema : MiniflareKnownBindingSchema;
  const result = schema.safeParse(value);
  if (!result.success) {
    ctx.issues.push(...result.error.issues);
    return external_exports2.NEVER;
  }
  return result.data;
});
var MiniflareDurableObjectExportSchema = DurableObjectCreatedExportSchema.extend({
  unsafeUniqueKey: external_exports2.custom().optional(),
  unsafePreventEviction: external_exports2.boolean().optional(),
  container: external_exports2.custom().optional()
});
var MiniflareDurableObjectExpectingTransferExportSchema = DurableObjectExpectingTransferExportSchema.extend({
  unsafeUniqueKey: external_exports2.custom().optional(),
  unsafePreventEviction: external_exports2.boolean().optional(),
  container: external_exports2.custom().optional()
});
var MiniflareLiveExportSchema = external_exports2.union([
  MiniflareDurableObjectExportSchema,
  MiniflareDurableObjectExpectingTransferExportSchema,
  WorkerEntrypointExportSchema
  // MiniflareWorkflowExportSchema,
]);
var MiniflareAcceptedExportSchema = external_exports2.union([
  MiniflareDurableObjectExportSchema,
  DurableObjectDeletedExportSchema,
  DurableObjectRenamedExportSchema,
  DurableObjectTransferredExportSchema,
  MiniflareDurableObjectExpectingTransferExportSchema,
  WorkerEntrypointExportSchema
  // MiniflareWorkflowExportSchema,
]);
var MiniflareExportsSchema = external_exports2.record(external_exports2.string(), MiniflareAcceptedExportSchema).transform((exports2) => {
  return Object.fromEntries(
    Object.entries(exports2).filter(([, exported]) => {
      return exported.type !== "durable-object" || "storage" in exported;
    })
  );
});
var MiniflareAssetsSchema = AssetsSchema.extend({
  /** Assets directory to serve; relative to `dev.rootPath` if not absolute. */
  directory: external_exports2.string(),
  hasUserWorker: external_exports2.boolean().default(false)
});
var MiniflareTailConsumerSchema = TailConsumerSchema.extend({
  entrypoint: external_exports2.string().optional(),
  props: external_exports2.record(external_exports2.string(), external_exports2.unknown()).optional()
});
var MiniflareWorkerConfigBaseSchema = OutputWorkerSchema.omit({
  manifest: true,
  env: true,
  exports: true,
  assets: true,
  tailConsumers: true
}).extend({
  manifest: MiniflareManifestSchema.optional(),
  env: external_exports2.record(external_exports2.string(), MiniflareBindingSchema).superRefine(validateSingletonBindings).optional(),
  exports: MiniflareExportsSchema.optional(),
  assets: MiniflareAssetsSchema.optional(),
  tailConsumers: external_exports2.array(MiniflareTailConsumerSchema).optional()
});
function getDefaultBindingIdentifier(bindingName, workerName) {
  return `${bindingName}-${workerName || "worker"}`;
}
function defaultBindingIdentifiers(config3) {
  if (config3.env === void 0) {
    const { env: _env, ...configWithoutEnv } = config3;
    return configWithoutEnv;
  }
  const env3 = Object.fromEntries(
    Object.entries(config3.env).map(([bindingName, binding]) => {
      const defaultIdentifier = getDefaultBindingIdentifier(
        bindingName,
        config3.name
      );
      switch (binding.type) {
        case "kv":
        case "d1":
        case "flagship":
          return [
            bindingName,
            { ...binding, id: binding.id ?? defaultIdentifier }
          ];
        case "r2":
        case "queue":
          return [
            bindingName,
            { ...binding, name: binding.name ?? defaultIdentifier }
          ];
        default:
          return [bindingName, binding];
      }
    })
  );
  return { ...config3, env: env3 };
}
var MiniflareWorkerConfigSchema = MiniflareWorkerConfigBaseSchema.transform(
  defaultBindingIdentifiers
);
var UnsafeDirectSocketSchema = external_exports2.strictObject({
  host: external_exports2.string().optional(),
  port: external_exports2.number().optional(),
  serviceName: external_exports2.string().optional(),
  entrypoint: external_exports2.string().optional(),
  proxy: external_exports2.boolean().optional()
});
var OutboundServiceSchema = external_exports2.discriminatedUnion("type", [
  FetcherBindingSchema,
  NodeHandlerBindingSchema,
  WorkerBindingSchema
]);
var DevConfigSchema = external_exports2.strictObject({
  /** Absolute base directory for path options. Defaults to cwd. */
  rootPath: AbsolutePathSchema.default(() => process.cwd()),
  // Enables the Cache API (NOT Workers cache).
  // not user-configurable (only Wrangler's internal ProxyWorker disables it).
  cacheAPI: external_exports2.boolean().default(true),
  outboundService: OutboundServiceSchema.optional(),
  remoteProxyConnectionString: external_exports2.custom().optional(),
  unsafeInspectorProxy: external_exports2.boolean().optional(),
  unsafeDirectSockets: external_exports2.array(UnsafeDirectSocketSchema).optional(),
  unsafeOverrideFetchWorker: external_exports2.string().optional(),
  unsafeEvalBinding: external_exports2.string().optional(),
  useModuleFallbackService: external_exports2.boolean().optional(),
  /** Whether this Worker is 'public' - whether should be advertised in the dev registry
   * and whether it should be included in local obs capture. Defaults to `true`. */
  unsafeRegisterWorker: external_exports2.boolean().default(true),
  hasAssetsAndIsVitest: external_exports2.boolean().optional(),
  // TODO(soon): remove in favour of per-object `unsafeUniqueKey: kEphemeralUniqueKey`
  unsafeEphemeralDurableObjects: external_exports2.boolean().optional(),
  // Strip the CF-Connecting-IP header from outbound fetches
  stripCfConnectingIp: external_exports2.boolean().default(true),
  // Zone to use for the CF-Worker header in outbound fetches. If not
  // specified, defaults to `${worker-name}.example.com`
  zone: external_exports2.string().optional(),
  /** Cloudflare Access authentication metadata exposed as `ctx.access` */
  access: external_exports2.strictObject({
    aud: external_exports2.string(),
    identity: external_exports2.record(external_exports2.string(), external_exports2.unknown()).optional()
  }).optional()
});
var LegacyConfigSchema = external_exports2.strictObject({
  // Service-worker format (non-module, global `addEventListener`) script,
  // provided directly by the caller (e.g. wrangler for service-worker workers).
  serviceWorkerScript: external_exports2.string().optional(),
  /** Source path for `serviceWorkerScript`; relative to `dev.rootPath` if not absolute. */
  serviceWorkerScriptPath: external_exports2.string().optional(),
  /** WASM binding file paths; string values are relative to `dev.rootPath` if not absolute. */
  wasmBindings: external_exports2.record(external_exports2.string(), external_exports2.union([external_exports2.string(), external_exports2.instanceof(Uint8Array)])).optional(),
  /** Text blob binding file paths; values are relative to `dev.rootPath` if not absolute. */
  textBlobBindings: external_exports2.record(external_exports2.string(), external_exports2.string()).optional(),
  /** Data blob binding file paths; string values are relative to `dev.rootPath` if not absolute. */
  dataBlobBindings: external_exports2.record(external_exports2.string(), external_exports2.union([external_exports2.string(), external_exports2.instanceof(Uint8Array)])).optional(),
  /** Workers Sites asset directory; relative to `dev.rootPath` if not absolute. */
  sitePath: external_exports2.string().optional(),
  siteInclude: external_exports2.array(external_exports2.string()).optional(),
  siteExclude: external_exports2.array(external_exports2.string()).optional()
});
var WorkerOptionsSchema = external_exports2.strictObject({
  config: MiniflareWorkerConfigSchema,
  legacy: LegacyConfigSchema.optional(),
  dev: DevConfigSchema.default(() => DevConfigSchema.parse({}))
});
var InstanceOptionsSchema = external_exports2.strictObject({
  // Server
  host: external_exports2.string().optional(),
  port: external_exports2.number().optional(),
  https: external_exports2.boolean().optional(),
  httpsKey: external_exports2.string().optional(),
  httpsCert: external_exports2.string().optional(),
  // Inspector
  inspectorPort: external_exports2.number().optional(),
  inspectorHost: external_exports2.string().optional(),
  // Runtime
  verbose: external_exports2.boolean().optional(),
  log: external_exports2.custom().optional(),
  handleStructuredLogs: external_exports2.custom().optional(),
  handleUncaughtError: external_exports2.custom((value) => typeof value === "function").optional(),
  upstream: external_exports2.string().optional(),
  cf: external_exports2.union([external_exports2.boolean(), external_exports2.string(), external_exports2.record(external_exports2.string(), external_exports2.any())]).optional(),
  // Logging
  logRequests: external_exports2.boolean().default(true),
  stripDisablePrettyError: external_exports2.boolean().default(true),
  // Persistence
  /** Root directory for persisted local resource state; relative to cwd if not absolute. */
  resourcePersistencePath: external_exports2.string().optional(),
  /** Project temp directory for plugin files; relative to cwd if not absolute. */
  resourceTmpPath: external_exports2.string().optional(),
  containerEngine: external_exports2.union([
    external_exports2.string(),
    external_exports2.strictObject({
      localDocker: external_exports2.strictObject({
        /** Docker socket path; passed through as-is. */
        socketPath: external_exports2.string(),
        containerEgressInterceptorImage: external_exports2.string().optional()
      })
    })
  ]).optional(),
  // Telemetry
  telemetry: external_exports2.strictObject({
    enabled: external_exports2.boolean().default(false),
    deviceId: external_exports2.string().optional()
  }).default({ enabled: false }),
  // Internal
  publicUrl: external_exports2.url().optional(),
  /** Dev registry filesystem path; relative to cwd if not absolute. */
  unsafeDevRegistryPath: external_exports2.string().optional(),
  unsafeHandleDevRegistryUpdate: external_exports2.custom().optional(),
  // Called after Miniflare has automatically restarted the `workerd`
  // runtime following an unexpected crash. Lets embedders (e.g. the Vite
  // plugin) re-establish any state that lived in the crashed process,
  // such as module runners created over a separate bootstrap channel.
  unsafeHandleRuntimeRestart: external_exports2.custom((value) => typeof value === "function").optional(),
  unsafeProxySharedSecret: external_exports2.string().optional(),
  unsafeModuleFallbackService: external_exports2.custom().optional(),
  unsafeTriggerHandlers: external_exports2.boolean().optional(),
  unsafeRuntimeEnv: external_exports2.record(external_exports2.string(), external_exports2.string()).optional(),
  unsafeLocalExplorer: external_exports2.boolean().optional(),
  // Turn on local-dev observability: attach the trace collector to the
  // user's worker(s) so it receives their tail events.
  unsafeObservability: external_exports2.boolean().optional(),
  unsafeInspectDurableObjects: external_exports2.boolean().optional()
});
var MiniflareOptionsSchema = InstanceOptionsSchema.extend({
  workers: external_exports2.array(WorkerOptionsSchema)
});
function getEnvBindingsOfType(config3, type) {
  return Object.entries(config3.env ?? {}).filter(
    ([, binding]) => binding.type === type
  );
}
function getExportsOfType(config3, type) {
  return Object.entries(config3.exports ?? {}).filter(
    ([, exported]) => exported.type === type
  );
}
function getTriggersOfType(config3, type) {
  return (config3.triggers ?? []).filter(
    (trigger) => trigger.type === type
  );
}
function getRemoteProxyConnectionString(binding, dev) {
  return binding.remote && dev?.remoteProxyConnectionString ? dev.remoteProxyConnectionString : void 0;
}

// src/exit-hook.ts
var callbacks = /* @__PURE__ */ new Set();
var registered = false;
var called = false;
function runCallbacks() {
  if (called) {
    return;
  }
  called = true;
  for (const callback of callbacks) {
    callback();
  }
}
function onExit2() {
  runCallbacks();
}
function onSignalInt() {
  runCallbacks();
  process.exit(128 + 2);
}
function onSignalTerm() {
  runCallbacks();
  process.exit(128 + 15);
}
function onMessage(message) {
  if (message === "shutdown") {
    runCallbacks();
    process.exit(0);
  }
}
function addListeners() {
  registered = true;
  called = false;
  process.on("exit", onExit2);
  process.on("SIGINT", onSignalInt);
  process.on("SIGTERM", onSignalTerm);
  if (process.send !== void 0) {
    process.on("message", onMessage);
  }
}
function removeListeners() {
  registered = false;
  process.removeListener("exit", onExit2);
  process.removeListener("SIGINT", onSignalInt);
  process.removeListener("SIGTERM", onSignalTerm);
  process.removeListener("message", onMessage);
}
function exitHook(callback) {
  callbacks.add(callback);
  if (!registered) {
    addListeners();
  }
  return () => {
    callbacks.delete(callback);
    if (callbacks.size === 0 && registered) {
      removeListeners();
    }
  };
}

// src/http/fetch.ts
var import_node_assert7 = __toESM(require("node:assert"));
var undici = __toESM(require("undici"));
var import_ws2 = __toESM(require("ws"));

// src/http/request.ts
var import_undici3 = require("undici");
var kCf = /* @__PURE__ */ Symbol("kCf");
var Request = class _Request extends import_undici3.Request {
  // We should be able to use a private `#cf` property here instead of a symbol
  // here, but we need to set this on a clone, which would otherwise lead to a
  // "Cannot write private member to an object whose class did not declare it"
  // error.
  [kCf];
  constructor(input, init3) {
    super(input, init3);
    this[kCf] = init3?.cf;
    if (input instanceof _Request) this[kCf] ??= input.cf;
  }
  get cf() {
    return this[kCf];
  }
  clone() {
    const request4 = super.clone();
    Object.setPrototypeOf(request4, _Request.prototype);
    request4[kCf] = this[kCf];
    return request4;
  }
};

// src/http/response.ts
var import_undici4 = require("undici");
var kWebSocket = /* @__PURE__ */ Symbol("kWebSocket");
var Response3 = class _Response extends import_undici4.Response {
  // We should be able to use a private `#webSocket` property here instead of a
  // symbol here, but `undici` calls `this.status` in its constructor, which
  // causes a "Cannot read private member from an object whose class did not
  // declare it" error.
  [kWebSocket];
  // Override BaseResponse's static methods for building Responses to return
  // our type instead. Ideally, we don't want to use `Object.setPrototypeOf`.
  // Unfortunately, `error()` and `redirect()` set the internal header guard
  // to "immutable".
  static error() {
    const response = import_undici4.Response.error();
    Object.setPrototypeOf(response, _Response.prototype);
    return response;
  }
  static redirect(url46, status2) {
    const response = import_undici4.Response.redirect(url46, status2);
    Object.setPrototypeOf(response, _Response.prototype);
    return response;
  }
  static json(data, init3) {
    const body = JSON.stringify(data);
    const response = new _Response(body, init3);
    response.headers.set("Content-Type", "application/json");
    return response;
  }
  constructor(body, init3) {
    if (init3?.webSocket) {
      if (init3.status !== 101) {
        throw new RangeError(
          "Responses with a WebSocket must have status code 101."
        );
      }
      init3 = { ...init3, status: 200 };
    }
    super(body, init3);
    this[kWebSocket] = init3?.webSocket ?? null;
  }
  // JSDoc comment so retained when bundling types with api-extractor
  /** @ts-expect-error `status` is actually defined as a getter internally */
  get status() {
    return this[kWebSocket] ? 101 : super.status;
  }
  get webSocket() {
    return this[kWebSocket];
  }
  clone() {
    if (this[kWebSocket]) {
      throw new TypeError("Cannot clone a response to a WebSocket handshake.");
    }
    const response = super.clone();
    Object.setPrototypeOf(response, _Response.prototype);
    return response;
  }
};

// src/http/websocket.ts
var import_node_assert6 = __toESM(require("node:assert"));
var import_node_events = require("node:events");
var import_ws = __toESM(require("ws"));

// src/shared/error.ts
var USER_ERROR_CODES = /* @__PURE__ */ new Set([
  "ERR_ADDRESS_IN_USE",
  // Runtime failed to start because the address was in use
  "ERR_DISPOSED",
  // Attempted to use Miniflare instance after calling dispose()
  "ERR_MODULE_PARSE",
  // SyntaxError when attempting to parse/locate modules
  "ERR_MODULE_STRING_SCRIPT",
  // Attempt to resolve module within string script
  "ERR_MODULE_DYNAMIC_SPEC",
  // Attempted to import/require a module without a literal spec
  "ERR_MODULE_RULE",
  // No matching module rule for file
  "ERR_PERSIST_UNSUPPORTED",
  // Unsupported storage persistence protocol
  "ERR_FUTURE_COMPATIBILITY_DATE",
  // Compatibility date in the future
  "ERR_NO_WORKERS",
  // No workers defined
  "ERR_VALIDATION",
  // Options failed to parse
  "ERR_DUPLICATE_NAME",
  // Multiple workers defined with same name
  "ERR_DIFFERENT_STORAGE_BACKEND",
  // Multiple Durable Object bindings declared for same class with different storage backends
  "ERR_DIFFERENT_UNIQUE_KEYS",
  // Multiple Durable Object bindings declared for same class with different unsafe unique keys
  "ERR_DIFFERENT_PREVENT_EVICTION",
  // Multiple Durable Object bindings declared for same class with different unsafe prevent eviction values
  "ERR_DIFFERENT_S3_CREDENTIALS",
  // Multiple R2 bucket bindings declared for same bucket with different S3 credentials
  "ERR_MISSING_INSPECTOR_PROXY_PORT",
  // An inspector proxy has been requested but no inspector port to use has been specified
  "ERR_MISSING_EXPLORER_UI"
  // Local Explorer enabled but assets not found at expected path
]);
var SYSTEM_ERROR_CODES = /* @__PURE__ */ new Set([
  "ERR_RUNTIME_FAILURE",
  // Runtime failed to start
  "ERR_PLUGIN_LOADING_FAILED"
]);
var MiniflareError = class extends Error {
  constructor(code, message, cause) {
    super(message);
    this.code = code;
    this.cause = cause;
    Object.setPrototypeOf(this, new.target.prototype);
    this.name = `${new.target.name} [${code}]`;
  }
  code;
  cause;
  // Is this caused by user error in using/configuring Miniflare...
  isUserError() {
    return USER_ERROR_CODES.has(this.code);
  }
  // ...or has something unexpected gone wrong?
  isSystemError() {
    return SYSTEM_ERROR_CODES.has(
      this.code
    );
  }
};
var MiniflareCoreError = class extends MiniflareError {
};
var isFileNotFoundError = (e) => {
  return typeof e === "object" && e !== null && "code" in e && e.code === "ENOENT";
};

// src/shared/event.ts
var TypedEventTarget = class extends EventTarget {
  addEventListener(type, listener, options) {
    super.addEventListener(
      type,
      listener,
      options
    );
  }
  removeEventListener(type, listener, options) {
    super.removeEventListener(
      type,
      listener,
      options
    );
  }
  dispatchEvent(event) {
    return super.dispatchEvent(event);
  }
};

// src/shared/log.ts
var import_node_path8 = __toESM(require("node:path"));
var import_node_util3 = require("node:util");
var cwd = process.cwd();
var cwdNodeModules = import_node_path8.default.join(cwd, "node_modules");
var LEVEL_PREFIX = {
  [0 /* NONE */]: "",
  [1 /* ERROR */]: "error",
  [2 /* WARN */]: "warn",
  [3 /* INFO */]: "info",
  [4 /* DEBUG */]: "debug",
  [5 /* VERBOSE */]: "verbose"
};
var LEVEL_COLOUR = {
  [0 /* NONE */]: reset,
  [1 /* ERROR */]: red3,
  [2 /* WARN */]: yellow3,
  [3 /* INFO */]: green3,
  [4 /* DEBUG */]: grey,
  [5 /* VERBOSE */]: (input) => dim3(grey(input))
};
function prefixError(prefix, e) {
  if (e.stack) {
    return new Proxy(e, {
      get(target, propertyKey, receiver) {
        const value = Reflect.get(target, propertyKey, receiver);
        return propertyKey === "stack" ? `${prefix}: ${value}` : value;
      }
    });
  }
  return e;
}
var frameRegex = /^\s*at\s+[^\s]+\s+\((.+?)\)$/;
function processStackTrace(stack, transformFrame) {
  const lines = stack.split("\n");
  const result = [];
  for (const line of lines) {
    const match = frameRegex.exec(line);
    if (match) {
      const location = match[1];
      const transformed = transformFrame(line, location);
      if (transformed !== null) {
        result.push(transformed);
      }
      continue;
    }
    result.push(line);
  }
  return result.join("\n");
}
function formatError3(error101) {
  let message;
  if (error101.stack) {
    message = processStackTrace(error101.stack, (line) => {
      if (!line.includes(cwd) || line.includes(cwdNodeModules)) {
        return dim3(line);
      }
      return line;
    });
  } else {
    message = error101.toString();
  }
  if (error101.cause instanceof Error) {
    message += `
Caused by: ${formatError3(error101.cause)}`;
  }
  return message;
}
var Log = class _Log {
  constructor(level = 3 /* INFO */, opts = {}) {
    this.level = level;
    const prefix = opts.prefix ?? "mf";
    const suffix = opts.suffix ?? "";
    this.#prefix = prefix ? prefix + ":" : "";
    this.#suffix = suffix ? ":" + suffix : "";
  }
  level;
  #prefix;
  #suffix;
  log(message) {
    _Log.#beforeLogHook?.();
    console.log(message);
    _Log.#afterLogHook?.();
  }
  static #beforeLogHook;
  static unstable_registerBeforeLogHook(callback) {
    this.#beforeLogHook = callback;
  }
  static #afterLogHook;
  static unstable_registerAfterLogHook(callback) {
    this.#afterLogHook = callback;
  }
  logWithLevel(level, message) {
    if (level <= this.level) {
      const prefix = `[${this.#prefix}${LEVEL_PREFIX[level]}${this.#suffix}]`;
      this.log(`${LEVEL_COLOUR[level](prefix)} ${message}`);
    }
  }
  logReady(message) {
    this.info(message);
  }
  error(message) {
    if (this.level < 1 /* ERROR */) {
    } else {
      this.logWithLevel(1 /* ERROR */, formatError3(message));
    }
  }
  warn(message) {
    this.logWithLevel(2 /* WARN */, message);
  }
  info(message) {
    this.logWithLevel(3 /* INFO */, message);
  }
  debug(message) {
    this.logWithLevel(4 /* DEBUG */, message);
  }
  verbose(message) {
    this.logWithLevel(5 /* VERBOSE */, message);
  }
};
var NoOpLog = class extends Log {
  constructor() {
    super(0 /* NONE */);
  }
  log() {
  }
  error(_message) {
  }
};
function stripAnsi(value) {
  return (0, import_node_util3.stripVTControlCharacters)(value);
}

// src/shared/matcher.ts
var import_glob_to_regexp = __toESM(require_glob_to_regexp());
function globsToRegExps(globs = [], { endAnchor } = {}) {
  const include = [];
  const exclude = [];
  const opts = { globstar: true, flags: "g" };
  const suffix = endAnchor ? "$" : "";
  for (const glob of globs) {
    if (glob.startsWith("!")) {
      exclude.push(
        new RegExp((0, import_glob_to_regexp.default)(glob.slice(1), opts).source + suffix)
      );
    } else {
      include.push(new RegExp((0, import_glob_to_regexp.default)(glob, opts).source + suffix));
    }
  }
  return { include, exclude };
}

// src/shared/streams.ts
var import_web = require("node:stream/web");
function prefixStream(prefix, stream) {
  const identity = new import_web.TransformStream();
  const writer = identity.writable.getWriter();
  void writer.write(prefix).then(() => {
    writer.releaseLock();
    return stream.pipeTo(identity.writable);
  }).catch((error101) => {
    return writer.abort(error101);
  });
  return identity.readable;
}
async function readPrefix(stream, prefixLength) {
  const chunks = [];
  let chunksLength = 0;
  for await (const chunk of stream.values({ preventCancel: true })) {
    chunks.push(chunk);
    chunksLength += chunk.byteLength;
    if (chunksLength >= prefixLength) break;
  }
  if (chunksLength < prefixLength) {
    throw new RangeError(
      `Expected ${prefixLength} byte prefix, but received ${chunksLength} byte stream`
    );
  }
  const atLeastPrefix = Buffer.concat(chunks, chunksLength);
  const prefix = atLeastPrefix.subarray(0, prefixLength);
  let rest = stream;
  if (chunksLength > prefixLength) {
    rest = prefixStream(atLeastPrefix.subarray(prefixLength), stream);
  }
  return [prefix, rest];
}

// src/shared/types.ts
var import_node_assert5 = __toESM(require("node:assert"));
var import_node_path9 = __toESM(require("node:path"));
function zAwaitable(type) {
  return type.or(external_exports2.promise(type));
}
var LiteralSchema = external_exports2.union([
  external_exports2.string(),
  external_exports2.number(),
  external_exports2.boolean(),
  external_exports2.null()
]);
var JsonSchema = external_exports2.lazy(
  () => external_exports2.union([
    LiteralSchema,
    external_exports2.array(JsonSchema),
    external_exports2.record(external_exports2.string(), JsonSchema)
  ])
);
var rootPath;
function parseWithRootPath(newRootPath, schema, data, options) {
  rootPath = newRootPath;
  try {
    return schema.parse(data);
  } catch (e) {
    if (options?.path && e instanceof external_exports2.ZodError) {
      for (const issue3 of e.issues) {
        issue3.path.unshift(...options.path);
      }
    }
    throw e;
  } finally {
    rootPath = void 0;
  }
}
var PathSchema = external_exports2.string().transform((p2) => {
  (0, import_node_assert5.default)(
    rootPath !== void 0,
    "Expected `PathSchema` to be parsed within `parseWithRootPath()`"
  );
  return import_node_path9.default.resolve(rootPath, p2);
});
function _isCyclic(value, seen = /* @__PURE__ */ new Set()) {
  if (typeof value !== "object" || value === null) return false;
  for (const child of Object.values(value)) {
    if (seen.has(child)) return true;
    seen.add(child);
    if (_isCyclic(child, seen)) return true;
    seen.delete(child);
  }
  return false;
}

// src/http/websocket.ts
var MessageEvent = class extends Event {
  data;
  constructor(type, init3) {
    super(type);
    this.data = init3.data;
  }
};
var CloseEvent = class extends Event {
  code;
  reason;
  wasClean;
  constructor(type, init3) {
    super(type);
    this.code = init3?.code ?? 1005;
    this.reason = init3?.reason ?? "";
    this.wasClean = init3?.wasClean ?? false;
  }
};
var ErrorEvent = class extends Event {
  error;
  constructor(type, init3) {
    super(type);
    this.error = init3?.error ?? null;
  }
};
var kPair = /* @__PURE__ */ Symbol("kPair");
var kAccepted = /* @__PURE__ */ Symbol("kAccepted");
var kCoupled = /* @__PURE__ */ Symbol("kCoupled");
var kClosedOutgoing = /* @__PURE__ */ Symbol("kClosedOutgoing");
var kClosedIncoming = /* @__PURE__ */ Symbol("kClosedIncoming");
var kSend = /* @__PURE__ */ Symbol("kSend");
var kClose = /* @__PURE__ */ Symbol("kClose");
var kError = /* @__PURE__ */ Symbol("kError");
var WebSocket = class _WebSocket extends TypedEventTarget {
  // The Workers runtime prefixes these constants with `READY_STATE_`, unlike
  // those in the spec: https://websockets.spec.whatwg.org/#interface-definition
  static READY_STATE_CONNECTING = 0;
  static READY_STATE_OPEN = 1;
  static READY_STATE_CLOSING = 2;
  static READY_STATE_CLOSED = 3;
  #dispatchQueue = [];
  [kPair];
  [kAccepted] = false;
  [kCoupled] = false;
  [kClosedOutgoing] = false;
  [kClosedIncoming] = false;
  get readyState() {
    if (this[kClosedOutgoing] && this[kClosedIncoming]) {
      return _WebSocket.READY_STATE_CLOSED;
    } else if (this[kClosedOutgoing] || this[kClosedIncoming]) {
      return _WebSocket.READY_STATE_CLOSING;
    }
    return _WebSocket.READY_STATE_OPEN;
  }
  async #queuingDispatchToPair(event) {
    const pair = this[kPair];
    (0, import_node_assert6.default)(pair !== void 0);
    if (pair[kAccepted]) {
      pair.dispatchEvent(event);
    } else {
      (0, import_node_assert6.default)(pair.#dispatchQueue !== void 0);
      pair.#dispatchQueue.push(event);
    }
  }
  accept() {
    if (this[kCoupled]) {
      throw new TypeError(
        "Can't accept() WebSocket that was already used in a response."
      );
    }
    if (this[kAccepted]) return;
    this[kAccepted] = true;
    if (this.#dispatchQueue !== void 0) {
      for (const event of this.#dispatchQueue) this.dispatchEvent(event);
      this.#dispatchQueue = void 0;
    }
  }
  send(message) {
    if (!this[kAccepted]) {
      throw new TypeError(
        "You must call accept() on this WebSocket before sending messages."
      );
    }
    this[kSend](message);
  }
  [kSend](message) {
    if (this[kClosedOutgoing]) {
      throw new TypeError("Can't call WebSocket send() after close().");
    }
    const event = new MessageEvent("message", { data: message });
    void this.#queuingDispatchToPair(event);
  }
  close(code, reason) {
    if (code) {
      const validCode = code >= 1e3 && code < 5e3 && code !== 1004 && code !== 1005 && code !== 1006 && code !== 1015;
      if (!validCode) throw new TypeError("Invalid WebSocket close code.");
    }
    if (reason !== void 0 && code === void 0) {
      throw new TypeError(
        "If you specify a WebSocket close reason, you must also specify a code."
      );
    }
    if (!this[kAccepted]) {
      throw new TypeError(
        "You must call accept() on this WebSocket before sending messages."
      );
    }
    this[kClose](code, reason);
  }
  [kClose](code, reason) {
    if (this[kClosedOutgoing]) throw new TypeError("WebSocket already closed");
    const pair = this[kPair];
    (0, import_node_assert6.default)(pair !== void 0);
    this[kClosedOutgoing] = true;
    pair[kClosedIncoming] = true;
    const event = new CloseEvent("close", { code, reason });
    void this.#queuingDispatchToPair(event);
  }
  [kError](error101) {
    const event = new ErrorEvent("error", { error: error101 });
    void this.#queuingDispatchToPair(event);
  }
};
var WebSocketPair = function() {
  if (!(this instanceof WebSocketPair)) {
    throw new TypeError(
      "Failed to construct 'WebSocketPair': Please use the 'new' operator, this object constructor cannot be called as a function."
    );
  }
  this[0] = new WebSocket();
  this[1] = new WebSocket();
  this[0][kPair] = this[1];
  this[1][kPair] = this[0];
};
async function coupleWebSocket(ws, pair) {
  if (pair[kCoupled]) {
    throw new TypeError(
      "Can't return WebSocket that was already used in a response."
    );
  }
  if (pair[kAccepted]) {
    throw new TypeError(
      "Can't return WebSocket in a Response after calling accept()."
    );
  }
  ws.on("message", (message, isBinary) => {
    if (!pair[kClosedOutgoing]) {
      pair[kSend](isBinary ? viewToBuffer(message) : message.toString());
    }
  });
  ws.on("close", (code, reason) => {
    if (!pair[kClosedOutgoing]) {
      pair[kClose](code, reason.toString());
    }
  });
  ws.on("error", (error101) => {
    pair[kError](error101);
  });
  pair.addEventListener("message", (e) => {
    ws.send(e.data);
  });
  pair.addEventListener("close", (e) => {
    if (e.code === 1005) {
      ws.close();
    } else if (e.code === 1006) {
      ws.terminate();
    } else {
      ws.close(e.code, e.reason);
    }
  });
  if (ws.readyState === import_ws.default.CONNECTING) {
    await (0, import_node_events.once)(ws, "open");
  } else if (ws.readyState >= import_ws.default.CLOSING) {
    throw new TypeError("Incoming WebSocket connection already closed.");
  }
  pair.accept();
  pair[kCoupled] = true;
}

// src/http/fetch.ts
var ignored = ["transfer-encoding", "connection", "keep-alive", "expect"];
async function fetch5(input, init3) {
  const requestInit = init3;
  const request4 = new Request(input, requestInit);
  if (request4.method === "GET" && request4.headers.get("upgrade") === "websocket") {
    const url46 = new URL(request4.url);
    if (url46.protocol !== "http:" && url46.protocol !== "https:") {
      throw new TypeError(
        `Fetch API cannot load: ${url46.toString()}
Make sure you're using http(s):// URLs for WebSocket requests via fetch.`
      );
    }
    url46.protocol = url46.protocol.replace("http", "ws");
    const headers = new undici.Headers();
    let protocols;
    for (const [key, value] of request4.headers.entries()) {
      if (key.toLowerCase() === "sec-websocket-protocol") {
        protocols = value.split(",").map((protocol) => protocol.trim());
      } else {
        headers.append(key, value);
      }
    }
    let rejectUnauthorized;
    if (requestInit.dispatcher instanceof DispatchFetchDispatcher) {
      requestInit.dispatcher.addHeaders(headers, url46.pathname + url46.search);
      rejectUnauthorized = { rejectUnauthorized: false };
    }
    const ws = new import_ws2.default(url46, protocols, {
      followRedirects: request4.redirect === "follow",
      headers: Object.fromEntries(headers.entries()),
      ...rejectUnauthorized
    });
    const responsePromise = new DeferredPromise();
    ws.once("error", (error101) => {
      responsePromise.reject(error101);
    });
    ws.once("upgrade", (req) => {
      const headers2 = convertUndiciHeadersToStandard(req.headers);
      const [worker, client] = Object.values(new WebSocketPair());
      const couplePromise = coupleWebSocket(ws, client);
      const response2 = new Response3(null, {
        status: 101,
        webSocket: worker,
        headers: headers2
      });
      responsePromise.resolve(couplePromise.then(() => response2));
    });
    ws.once("unexpected-response", (_, req) => {
      const headers2 = convertUndiciHeadersToStandard(req.headers);
      const response2 = new Response3(req, {
        status: req.statusCode,
        headers: headers2
      });
      responsePromise.resolve(response2);
    });
    return responsePromise;
  }
  const response = await undici.fetch(request4, {
    dispatcher: requestInit?.dispatcher
  });
  return new Response3(response.body, response);
}
function isIterable(headers) {
  return Symbol.iterator in Object(headers);
}
function convertUndiciHeadersToStandard(headers) {
  if (Array.isArray(headers)) {
    let name = void 0;
    let value = void 0;
    const standardHeaders = new undici.Headers();
    for (const element of headers) {
      if (name === void 0 && value === void 0) {
        name = element;
      } else if (name !== void 0 && value === void 0) {
        value = element;
      } else if (name !== void 0 && value !== void 0) {
        if (!ignored.includes(name)) {
          standardHeaders.set(name, value);
        }
        name = void 0;
        value = void 0;
      }
    }
    (0, import_node_assert7.default)(name === void 0 && value === void 0);
    return standardHeaders;
  } else if (isIterable(headers)) {
    const standardHeaders = new undici.Headers();
    for (const [name, value] of headers) {
      if (!ignored.includes(name)) {
        if (!value) {
          continue;
        }
        if (typeof value === "string") {
          standardHeaders.append(name, value);
        } else {
          for (const v of value) {
            standardHeaders.append(name, v);
          }
        }
      }
    }
    return standardHeaders;
  } else {
    const standardHeaders = new undici.Headers();
    for (const [name, value] of Object.entries(headers)) {
      if (!ignored.includes(name)) {
        if (!value) {
          continue;
        }
        if (typeof value === "string") {
          standardHeaders.append(name, value);
        } else {
          for (const v of value) {
            standardHeaders.append(name, v);
          }
        }
      }
    }
    return standardHeaders;
  }
}
var DispatchFetchDispatcher = class extends undici.Dispatcher {
  /**
   * @param globalDispatcher 		Dispatcher to use for all non-runtime requests
   * 												 		(rejects unauthorised certificates)
   * @param runtimeDispatcher 	Dispatcher to use for runtime requests
   * 														(permits unauthorised certificates)
   * @param actualRuntimeOrigin	Origin to send all runtime requests to
   * @param userRuntimeOrigin 	Origin to treat as runtime request
   * 														(initial URL passed by user to `dispatchFetch()`)
   * @param cfBlob							`request.cf` blob override for runtime requests
   */
  constructor(globalDispatcher, runtimeDispatcher, actualRuntimeOrigin, userRuntimeOrigin, cfBlob) {
    super();
    this.globalDispatcher = globalDispatcher;
    this.runtimeDispatcher = runtimeDispatcher;
    this.actualRuntimeOrigin = actualRuntimeOrigin;
    this.userRuntimeOrigin = userRuntimeOrigin;
    if (cfBlob !== void 0) this.cfBlobJson = JSON.stringify(cfBlob);
  }
  globalDispatcher;
  runtimeDispatcher;
  actualRuntimeOrigin;
  userRuntimeOrigin;
  cfBlobJson;
  addHeaders(headers, path73) {
    const originalURL = this.userRuntimeOrigin + path73;
    headers.set(CoreHeaders.ORIGINAL_URL, originalURL);
    headers.set(CoreHeaders.DISABLE_PRETTY_ERROR, "true");
    if (this.cfBlobJson !== void 0) {
      headers.set(CoreHeaders.CF_BLOB, this.cfBlobJson);
    }
  }
  dispatch(options, handler) {
    let origin = String(options.origin);
    if (origin === this.userRuntimeOrigin) origin = this.actualRuntimeOrigin;
    if (origin === this.actualRuntimeOrigin) {
      options.origin = origin;
      let path73 = options.path;
      if (options.query !== void 0) {
        const url46 = new URL(path73, "http://placeholder/");
        for (const [key, value] of Object.entries(options.query)) {
          url46.searchParams.append(key, value);
        }
        path73 = url46.pathname + url46.search;
      }
      const headers = convertUndiciHeadersToStandard(options.headers ?? {});
      this.addHeaders(headers, path73);
      options.headers = headers;
      options.reset = true;
      return this.runtimeDispatcher.dispatch(options, handler);
    } else {
      return this.globalDispatcher.dispatch(options, handler);
    }
  }
  async close(callback) {
    await Promise.all([
      this.globalDispatcher.close(),
      this.runtimeDispatcher.close()
    ]);
    callback?.();
  }
  async destroy(errCallback, callback) {
    let err = null;
    if (typeof errCallback === "function") callback = errCallback;
    if (errCallback instanceof Error) err = errCallback;
    await Promise.all([
      this.globalDispatcher.destroy(err),
      this.runtimeDispatcher.destroy(err)
    ]);
    callback?.();
  }
  get isMockActive() {
    return this.globalDispatcher.isMockActive ?? false;
  }
};

// src/http/cert.ts
var KEY = `
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIC+umAaVUbEfPqGA9M7b5zAP7tN2eLT1bu8U8gpbaKbsoAoGCCqGSM49
AwEHoUQDQgAEtrIEgzogjrUHIvB4qgjg/cT7blhWuLUfSUp6H62NCo21NrVWgPtC
mCWw+vbGTBwIr/9X1S4UL1/f3zDICC7YSA==
-----END EC PRIVATE KEY-----
`;
var CERT = `
-----BEGIN CERTIFICATE-----
MIIDBzCCAq2gAwIBAgIUaEibZTawMcz6xQ/0rGNlEBKwkUowCgYIKoZIzj0EAwIw
gZExCzAJBgNVBAYTAlVTMQ4wDAYDVQQIDAVUZXhhczEPMA0GA1UEBwwGQXVzdGlu
MRMwEQYDVQQKDApDbG91ZGZsYXJlMRAwDgYDVQQLDAdXb3JrZXJzMRIwEAYDVQQD
DAlsb2NhbGhvc3QxJjAkBgkqhkiG9w0BCQEWF3dyYW5nbGVyQGNsb3VkZmxhcmUu
Y29tMCAXDTI1MTAwMjEzMzQ1MloYDzIxMjUwOTA4MTMzNDUyWjCBkTELMAkGA1UE
BhMCVVMxDjAMBgNVBAgMBVRleGFzMQ8wDQYDVQQHDAZBdXN0aW4xEzARBgNVBAoM
CkNsb3VkZmxhcmUxEDAOBgNVBAsMB1dvcmtlcnMxEjAQBgNVBAMMCWxvY2FsaG9z
dDEmMCQGCSqGSIb3DQEJARYXd3JhbmdsZXJAY2xvdWRmbGFyZS5jb20wWTATBgcq
hkjOPQIBBggqhkjOPQMBBwNCAAS2sgSDOiCOtQci8HiqCOD9xPtuWFa4tR9JSnof
rY0KjbU2tVaA+0KYJbD69sZMHAiv/1fVLhQvX9/fMMgILthIo4HeMIHbMB0GA1Ud
DgQWBBRJdqFOSyLTRzoqFQQIchjgUtbtKjAfBgNVHSMEGDAWgBRJdqFOSyLTRzoq
FQQIchjgUtbtKjAPBgNVHRMBAf8EBTADAQH/MCwGCWCGSAGG+EIBDQQfFh1PcGVu
U1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTALBgNVHQ8EBAMCAvQwMQYDVR0lBCow
KAYIKwYBBQUHAwEGCCsGAQUFBwMCBggrBgEFBQcDAwYIKwYBBQUHAwgwGgYDVR0R
BBMwEYIJbG9jYWxob3N0hwR/AAABMAoGCCqGSM49BAMCA0gAMEUCIQDNxEiZc6Q6
8hK0q3y/9lDWc+dHr74gAnBHVJZEo5uyRQIgW6eL31hH7qouqUi9+efWU1N85n0z
X3kip4YDAFo8ozE=
-----END CERTIFICATE-----
`;

// src/http/server.ts
async function getEntrySocketHttpOptions(coreOpts) {
  let privateKey = void 0;
  let certificateChain = void 0;
  if (coreOpts.httpsKey && coreOpts.httpsCert) {
    privateKey = coreOpts.httpsKey;
    certificateChain = coreOpts.httpsCert;
  } else if (coreOpts.https) {
    privateKey = KEY;
    certificateChain = CERT;
  }
  if (privateKey && certificateChain) {
    return {
      https: {
        tlsOptions: {
          keypair: {
            privateKey,
            certificateChain
          }
        }
      }
    };
  } else {
    return { http: {} };
  }
}

// src/http/helpers.ts
var import_node_os6 = require("node:os");
function getAccessibleHosts(ipv4Only = false) {
  const hosts = [];
  Object.values((0, import_node_os6.networkInterfaces)()).forEach((net3) => {
    net3?.forEach(({ family, address }) => {
      if (family === "IPv4" || family === 4) {
        hosts.push(address);
      } else if (!ipv4Only) {
        hosts.push(address);
      }
    });
  });
  return hosts;
}

// src/http/index.ts
var import_undici5 = require("undici");

// src/plugins/shared/index.ts
var import_node_crypto2 = require("node:crypto");
var import_node_path10 = __toESM(require("node:path"));
var import_node_url4 = require("node:url");

// src/plugins/shared/routing.ts
var import_node_url3 = require("node:url");
var RouterError = class extends MiniflareError {
};
function routeSpecificity(url46) {
  const hostParts = url46.host.split(".");
  let hostScore = hostParts.length;
  if (hostParts[0] === "*") hostScore -= 2;
  const pathParts = url46.pathname.split("/");
  let pathScore = pathParts.length;
  if (pathParts[pathParts.length - 1] === "*") pathScore -= 2;
  return hostScore * 26 + pathScore;
}
function parseRoutes(allRoutes) {
  const routes = [];
  for (const [target, targetRoutes] of allRoutes) {
    for (const route of targetRoutes) {
      const hasProtocol = /^[a-z0-9+\-.]+:\/\//i.test(route);
      let urlInput = route;
      if (!hasProtocol) urlInput = `https://${urlInput}`;
      const url46 = new import_node_url3.URL(urlInput);
      const specificity = routeSpecificity(url46);
      const protocol = hasProtocol ? url46.protocol : void 0;
      const internationalisedAllowHostnamePrefix = url46.hostname.startsWith("xn--*");
      const allowHostnamePrefix = url46.hostname.startsWith("*") || internationalisedAllowHostnamePrefix;
      const anyHostname = url46.hostname === "*";
      if (allowHostnamePrefix && !anyHostname) {
        let hostname5 = url46.hostname;
        if (internationalisedAllowHostnamePrefix) {
          hostname5 = (0, import_node_url3.domainToUnicode)(hostname5);
        }
        url46.hostname = hostname5.substring(1);
      }
      const allowPathSuffix = url46.pathname.endsWith("*");
      if (allowPathSuffix) {
        url46.pathname = url46.pathname.substring(0, url46.pathname.length - 1);
      }
      if (url46.search) {
        throw new RouterError(
          "ERR_QUERY_STRING",
          `Route "${route}" for "${target}" contains a query string. This is not allowed.`
        );
      }
      if (url46.toString().includes("*") && !anyHostname) {
        throw new RouterError(
          "ERR_INFIX_WILDCARD",
          `Route "${route}" for "${target}" contains an infix wildcard. This is not allowed.`
        );
      }
      routes.push({
        target,
        route,
        specificity,
        protocol,
        allowHostnamePrefix,
        hostname: anyHostname ? "" : url46.hostname,
        path: url46.pathname,
        allowPathSuffix
      });
    }
  }
  routes.sort((a, b) => {
    if (a.specificity === b.specificity) {
      return b.route.length - a.route.length;
    } else {
      return b.specificity - a.specificity;
    }
  });
  return routes;
}

// src/plugins/shared/index.ts
async function loadExternalPlugins(packageName) {
  let pluginModule;
  try {
    const pluginPath = require.resolve(packageName);
    const moduleURL = (0, import_node_url4.pathToFileURL)(pluginPath).href;
    pluginModule = await import(moduleURL);
  } catch (error101) {
    throw new MiniflareCoreError(
      "ERR_PLUGIN_LOADING_FAILED",
      `Package ${packageName} could not be loaded. ${error101}`
    );
  }
  if (!pluginModule.plugins) {
    throw new MiniflareCoreError(
      "ERR_PLUGIN_LOADING_FAILED",
      `Package ${packageName} did not provide any plugins.`
    );
  }
  return pluginModule.plugins;
}
var ProxyNodeBinding = class {
  constructor(proxyOverrideHandler) {
    this.proxyOverrideHandler = proxyOverrideHandler;
  }
  proxyOverrideHandler;
};
function namespaceEntries(namespaces) {
  if (Array.isArray(namespaces)) {
    return namespaces.map((bindingName) => [
      bindingName,
      { id: bindingName }
    ]);
  } else if (namespaces !== void 0) {
    return Object.entries(namespaces).map(([key, value]) => {
      if (typeof value === "string") {
        return [key, { id: value }];
      }
      return [key, value];
    });
  } else {
    return [];
  }
}
function maybeParseURL(url46) {
  if (typeof url46 !== "string" || import_node_path10.default.isAbsolute(url46)) return;
  try {
    return new URL(url46);
  } catch {
  }
}
function getPersistPath(pluginName, tmpPath, resourcePersistencePath) {
  const result = resourcePersistencePath === void 0 ? import_node_path10.default.join(tmpPath, pluginName) : import_node_path10.default.join(resourcePersistencePath, pluginName);
  return result.replaceAll("\\", "/");
}
function getRemoteServiceNameSuffix(remoteProxyConnectionString) {
  const remoteSha = (0, import_node_crypto2.createHash)("sha256").update(remoteProxyConnectionString.href).digest("hex");
  const remoteShortSha = remoteSha.slice(0, 6);
  return `remote-${remoteShortSha}`;
}
function getUserBindingServiceName(scope, identifier, remoteProxyConnectionString) {
  const localServiceName = `${scope}:${identifier}`;
  if (!remoteProxyConnectionString) {
    return localServiceName;
  }
  const remoteSuffix = getRemoteServiceNameSuffix(remoteProxyConnectionString);
  return `${localServiceName}:${remoteSuffix}`;
}

// src/plugins/agent-memory/index.ts
var AGENT_MEMORY_PLUGIN_NAME = "agent-memory";
var AGENT_MEMORY_SCOPE = "agent-memory";
var AGENT_MEMORY_REMOTE_SERVICE_NAME = `${AGENT_MEMORY_SCOPE}:remote`;
var AGENT_MEMORY_PLUGIN = {
  bindingTypeDescription: "Agent Memory",
  async getBindings(options) {
    return getEnvBindingsOfType(options.config, "agent-memory").map(
      ([name, binding]) => ({
        name,
        service: {
          name: AGENT_MEMORY_REMOTE_SERVICE_NAME,
          props: buildRemoteProxyProps(
            getRemoteProxyConnectionString(binding, options.dev),
            name
          )
        }
      })
    );
  },
  getNodeBindings(options) {
    return Object.fromEntries(
      getEnvBindingsOfType(options.config, "agent-memory").map(([name]) => [
        name,
        new ProxyNodeBinding()
      ])
    );
  },
  async getServices({ options }) {
    if (getEnvBindingsOfType(options.config, "agent-memory").length === 0) {
      return [];
    }
    return [
      {
        name: AGENT_MEMORY_REMOTE_SERVICE_NAME,
        worker: remoteProxyClientWorker()
      }
    ];
  }
};

// src/plugins/ai/index.ts
var AI_PLUGIN_NAME = "ai";
var AI_REMOTE_SERVICE_NAME = `${AI_PLUGIN_NAME}:remote`;
var AI_PLUGIN = {
  bindingTypeDescription: "AI",
  async getBindings(options) {
    return getEnvBindingsOfType(options.config, "ai").map(
      ([name, binding]) => ({
        name,
        wrapped: {
          moduleName: "cloudflare-internal:ai-api",
          innerBindings: [
            {
              name: "fetcher",
              service: {
                name: AI_REMOTE_SERVICE_NAME,
                props: buildRemoteProxyProps(
                  getRemoteProxyConnectionString(binding, options.dev),
                  name
                )
              }
            }
          ]
        }
      })
    );
  },
  getNodeBindings(options) {
    return Object.fromEntries(
      getEnvBindingsOfType(options.config, "ai").map(([name]) => [
        name,
        new ProxyNodeBinding()
      ])
    );
  },
  async getServices({ options }) {
    if (getEnvBindingsOfType(options.config, "ai").length === 0) {
      return [];
    }
    return [
      {
        name: AI_REMOTE_SERVICE_NAME,
        worker: remoteProxyClientWorker()
      }
    ];
  }
};

// src/plugins/ai-search/index.ts
var AI_SEARCH_PLUGIN_NAME = "ai-search";
var AI_SEARCH_REMOTE_SERVICE_NAME = `${AI_SEARCH_PLUGIN_NAME}:remote`;
function getAISearchBindings(config3) {
  return [
    ...getEnvBindingsOfType(config3, "ai-search"),
    ...getEnvBindingsOfType(config3, "ai-search-namespace")
  ];
}
var AI_SEARCH_PLUGIN = {
  bindingTypeDescription: "AI Search",
  async getBindings(options) {
    return getAISearchBindings(options.config).map(([name, binding]) => ({
      name,
      service: {
        name: AI_SEARCH_REMOTE_SERVICE_NAME,
        props: buildRemoteProxyProps(
          getRemoteProxyConnectionString(binding, options.dev),
          name
        )
      }
    }));
  },
  getNodeBindings(options) {
    return Object.fromEntries(
      getAISearchBindings(options.config).map(([name]) => [
        name,
        new ProxyNodeBinding()
      ])
    );
  },
  async getServices({ options }) {
    if (getAISearchBindings(options.config).length === 0) {
      return [];
    }
    return [
      {
        name: AI_SEARCH_REMOTE_SERVICE_NAME,
        worker: remoteProxyClientWorker()
      }
    ];
  }
};

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/analytics-engine/analytics-engine.worker.ts
var import_fs6 = __toESM(require("fs"));
var import_path6 = __toESM(require("path"));
var import_url6 = __toESM(require("url"));
var contents6;
function analytics_engine_worker_default() {
  if (contents6 !== void 0) return contents6;
  const filePath = import_path6.default.join(__dirname, "workers", "analytics-engine/analytics-engine.worker.js");
  contents6 = import_fs6.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url6.default.pathToFileURL(filePath);
  return contents6;
}

// src/plugins/analytics-engine/index.ts
var ANALYTICS_ENGINE_PLUGIN_NAME = "analytics-engine";
var ANALYTICS_ENGINE_PLUGIN = {
  bindingTypeDescription: "Analytics Engine dataset",
  async getBindings(options) {
    return getEnvBindingsOfType(
      options.config,
      "analytics-engine-dataset"
    ).map(([name, binding]) => {
      return {
        name,
        wrapped: {
          moduleName: `${ANALYTICS_ENGINE_PLUGIN_NAME}:local-simulator`,
          innerBindings: [
            {
              name: "dataset",
              json: JSON.stringify(binding.name)
            }
          ]
        }
      };
    });
  },
  getNodeBindings(options) {
    return Object.fromEntries(
      getEnvBindingsOfType(options.config, "analytics-engine-dataset").map(
        ([name]) => [name, new ProxyNodeBinding()]
      )
    );
  },
  async getServices() {
    return [];
  },
  getExtensions({ options }) {
    if (!options.some(
      (o) => getEnvBindingsOfType(o.config, "analytics-engine-dataset").length > 0
    )) {
      return [];
    }
    return [
      {
        modules: [
          {
            name: `${ANALYTICS_ENGINE_PLUGIN_NAME}:local-simulator`,
            esModule: analytics_engine_worker_default(),
            internal: true
          }
        ]
      }
    ];
  }
};

// src/plugins/artifacts/index.ts
var ARTIFACTS_PLUGIN_NAME = "artifacts";
var ARTIFACTS_REMOTE_SERVICE_NAME = `${ARTIFACTS_PLUGIN_NAME}:remote`;
var ARTIFACTS_PLUGIN = {
  bindingTypeDescription: "Artifacts",
  async getBindings(options) {
    return getEnvBindingsOfType(options.config, "artifacts").map(
      ([name, binding]) => ({
        name,
        service: {
          name: ARTIFACTS_REMOTE_SERVICE_NAME,
          props: buildRemoteProxyProps(
            getRemoteProxyConnectionString(binding, options.dev),
            name
          )
        }
      })
    );
  },
  getNodeBindings(options) {
    return Object.fromEntries(
      getEnvBindingsOfType(options.config, "artifacts").map(([name]) => [
        name,
        new ProxyNodeBinding()
      ])
    );
  },
  async getServices({ options }) {
    if (getEnvBindingsOfType(options.config, "artifacts").length === 0) {
      return [];
    }
    return [
      {
        name: ARTIFACTS_REMOTE_SERVICE_NAME,
        worker: remoteProxyClientWorker()
      }
    ];
  }
};

// src/plugins/assets/index.ts
var import_node_crypto5 = __toESM(require("node:crypto"));
var import_promises12 = __toESM(require("node:fs/promises"));
var import_node_os7 = __toESM(require("node:os"));
var import_node_path18 = __toESM(require("node:path"));

// ../workers-shared/utils/constants.ts
var HEADER_SIZE = 20;
var PATH_HASH_SIZE = 16;
var CONTENT_HASH_SIZE = 16;
var TAIL_SIZE = 8;
var PATH_HASH_OFFSET = 0;
var CONTENT_HASH_OFFSET = PATH_HASH_SIZE;
var ENTRY_SIZE = PATH_HASH_SIZE + CONTENT_HASH_SIZE + TAIL_SIZE;
var MAX_ASSET_COUNT = 1e5;
var MAX_ASSET_SIZE = 25 * 1024 * 1024;
var CF_ASSETS_IGNORE_FILENAME = ".assetsignore";
var REDIRECTS_FILENAME = "_redirects";
var HEADERS_FILENAME = "_headers";

// ../workers-shared/utils/types.ts
var InternalConfigSchema = external_exports2.object({
  account_id: external_exports2.number().optional(),
  script_id: external_exports2.number().optional(),
  debug: external_exports2.boolean().optional()
});
var StaticRoutingSchema = external_exports2.object({
  user_worker: external_exports2.array(external_exports2.string()),
  asset_worker: external_exports2.array(external_exports2.string()).optional()
});
var RouterConfigSchema = external_exports2.object({
  invoke_user_worker_ahead_of_assets: external_exports2.boolean().optional(),
  static_routing: StaticRoutingSchema.optional(),
  has_user_worker: external_exports2.boolean().optional(),
  ...InternalConfigSchema.shape
});
var EyeballRouterConfigSchema = external_exports2.union([
  external_exports2.object({
    limitedAssetsOnly: external_exports2.boolean().optional()
  }),
  external_exports2.null()
]);
var MetadataStaticRedirectEntry = external_exports2.object({
  status: external_exports2.number(),
  to: external_exports2.string(),
  lineNumber: external_exports2.number()
});
var MetadataRedirectEntry = external_exports2.object({
  status: external_exports2.number(),
  to: external_exports2.string()
});
var MetadataStaticRedirects = external_exports2.record(
  external_exports2.string(),
  MetadataStaticRedirectEntry
);
var MetadataRedirects = external_exports2.record(external_exports2.string(), MetadataRedirectEntry);
var MetadataHeaderEntry = external_exports2.object({
  set: external_exports2.record(external_exports2.string(), external_exports2.string()).optional(),
  unset: external_exports2.array(external_exports2.string()).optional()
});
var MetadataHeaders = external_exports2.record(external_exports2.string(), MetadataHeaderEntry);
var RedirectsSchema = external_exports2.object({
  version: external_exports2.literal(1),
  staticRules: MetadataStaticRedirects,
  rules: MetadataRedirects
}).optional();
var HeadersSchema = external_exports2.object({
  version: external_exports2.literal(2),
  rules: MetadataHeaders
}).optional();
var AssetConfigSchema = external_exports2.object({
  compatibility_date: external_exports2.string().optional(),
  compatibility_flags: external_exports2.array(external_exports2.string()).optional(),
  html_handling: external_exports2.enum([
    "auto-trailing-slash",
    "force-trailing-slash",
    "drop-trailing-slash",
    "none"
  ]).optional(),
  not_found_handling: external_exports2.enum(["single-page-application", "404-page", "none"]).optional(),
  redirects: RedirectsSchema,
  headers: HeadersSchema,
  has_static_routing: external_exports2.boolean().optional(),
  ...InternalConfigSchema.shape
});

// ../workers-shared/utils/helpers.ts
var import_node_fs7 = require("node:fs");
var import_node_path11 = require("node:path");
var import_ignore = __toESM(require_ignore());

// ../../node_modules/.pnpm/mime@4.0.7/node_modules/mime/dist/types/other.js
var types = {
  "application/prs.cww": ["cww"],
  "application/prs.xsf+xml": ["xsf"],
  "application/vnd.1000minds.decision-model+xml": ["1km"],
  "application/vnd.3gpp.pic-bw-large": ["plb"],
  "application/vnd.3gpp.pic-bw-small": ["psb"],
  "application/vnd.3gpp.pic-bw-var": ["pvb"],
  "application/vnd.3gpp2.tcap": ["tcap"],
  "application/vnd.3m.post-it-notes": ["pwn"],
  "application/vnd.accpac.simply.aso": ["aso"],
  "application/vnd.accpac.simply.imp": ["imp"],
  "application/vnd.acucobol": ["acu"],
  "application/vnd.acucorp": ["atc", "acutc"],
  "application/vnd.adobe.air-application-installer-package+zip": ["air"],
  "application/vnd.adobe.formscentral.fcdt": ["fcdt"],
  "application/vnd.adobe.fxp": ["fxp", "fxpl"],
  "application/vnd.adobe.xdp+xml": ["xdp"],
  "application/vnd.adobe.xfdf": ["*xfdf"],
  "application/vnd.age": ["age"],
  "application/vnd.ahead.space": ["ahead"],
  "application/vnd.airzip.filesecure.azf": ["azf"],
  "application/vnd.airzip.filesecure.azs": ["azs"],
  "application/vnd.amazon.ebook": ["azw"],
  "application/vnd.americandynamics.acc": ["acc"],
  "application/vnd.amiga.ami": ["ami"],
  "application/vnd.android.package-archive": ["apk"],
  "application/vnd.anser-web-certificate-issue-initiation": ["cii"],
  "application/vnd.anser-web-funds-transfer-initiation": ["fti"],
  "application/vnd.antix.game-component": ["atx"],
  "application/vnd.apple.installer+xml": ["mpkg"],
  "application/vnd.apple.keynote": ["key"],
  "application/vnd.apple.mpegurl": ["m3u8"],
  "application/vnd.apple.numbers": ["numbers"],
  "application/vnd.apple.pages": ["pages"],
  "application/vnd.apple.pkpass": ["pkpass"],
  "application/vnd.aristanetworks.swi": ["swi"],
  "application/vnd.astraea-software.iota": ["iota"],
  "application/vnd.audiograph": ["aep"],
  "application/vnd.autodesk.fbx": ["fbx"],
  "application/vnd.balsamiq.bmml+xml": ["bmml"],
  "application/vnd.blueice.multipass": ["mpm"],
  "application/vnd.bmi": ["bmi"],
  "application/vnd.businessobjects": ["rep"],
  "application/vnd.chemdraw+xml": ["cdxml"],
  "application/vnd.chipnuts.karaoke-mmd": ["mmd"],
  "application/vnd.cinderella": ["cdy"],
  "application/vnd.citationstyles.style+xml": ["csl"],
  "application/vnd.claymore": ["cla"],
  "application/vnd.cloanto.rp9": ["rp9"],
  "application/vnd.clonk.c4group": ["c4g", "c4d", "c4f", "c4p", "c4u"],
  "application/vnd.cluetrust.cartomobile-config": ["c11amc"],
  "application/vnd.cluetrust.cartomobile-config-pkg": ["c11amz"],
  "application/vnd.commonspace": ["csp"],
  "application/vnd.contact.cmsg": ["cdbcmsg"],
  "application/vnd.cosmocaller": ["cmc"],
  "application/vnd.crick.clicker": ["clkx"],
  "application/vnd.crick.clicker.keyboard": ["clkk"],
  "application/vnd.crick.clicker.palette": ["clkp"],
  "application/vnd.crick.clicker.template": ["clkt"],
  "application/vnd.crick.clicker.wordbank": ["clkw"],
  "application/vnd.criticaltools.wbs+xml": ["wbs"],
  "application/vnd.ctc-posml": ["pml"],
  "application/vnd.cups-ppd": ["ppd"],
  "application/vnd.curl.car": ["car"],
  "application/vnd.curl.pcurl": ["pcurl"],
  "application/vnd.dart": ["dart"],
  "application/vnd.data-vision.rdz": ["rdz"],
  "application/vnd.dbf": ["dbf"],
  "application/vnd.dcmp+xml": ["dcmp"],
  "application/vnd.dece.data": ["uvf", "uvvf", "uvd", "uvvd"],
  "application/vnd.dece.ttml+xml": ["uvt", "uvvt"],
  "application/vnd.dece.unspecified": ["uvx", "uvvx"],
  "application/vnd.dece.zip": ["uvz", "uvvz"],
  "application/vnd.denovo.fcselayout-link": ["fe_launch"],
  "application/vnd.dna": ["dna"],
  "application/vnd.dolby.mlp": ["mlp"],
  "application/vnd.dpgraph": ["dpg"],
  "application/vnd.dreamfactory": ["dfac"],
  "application/vnd.ds-keypoint": ["kpxx"],
  "application/vnd.dvb.ait": ["ait"],
  "application/vnd.dvb.service": ["svc"],
  "application/vnd.dynageo": ["geo"],
  "application/vnd.ecowin.chart": ["mag"],
  "application/vnd.enliven": ["nml"],
  "application/vnd.epson.esf": ["esf"],
  "application/vnd.epson.msf": ["msf"],
  "application/vnd.epson.quickanime": ["qam"],
  "application/vnd.epson.salt": ["slt"],
  "application/vnd.epson.ssf": ["ssf"],
  "application/vnd.eszigno3+xml": ["es3", "et3"],
  "application/vnd.ezpix-album": ["ez2"],
  "application/vnd.ezpix-package": ["ez3"],
  "application/vnd.fdf": ["*fdf"],
  "application/vnd.fdsn.mseed": ["mseed"],
  "application/vnd.fdsn.seed": ["seed", "dataless"],
  "application/vnd.flographit": ["gph"],
  "application/vnd.fluxtime.clip": ["ftc"],
  "application/vnd.framemaker": ["fm", "frame", "maker", "book"],
  "application/vnd.frogans.fnc": ["fnc"],
  "application/vnd.frogans.ltf": ["ltf"],
  "application/vnd.fsc.weblaunch": ["fsc"],
  "application/vnd.fujitsu.oasys": ["oas"],
  "application/vnd.fujitsu.oasys2": ["oa2"],
  "application/vnd.fujitsu.oasys3": ["oa3"],
  "application/vnd.fujitsu.oasysgp": ["fg5"],
  "application/vnd.fujitsu.oasysprs": ["bh2"],
  "application/vnd.fujixerox.ddd": ["ddd"],
  "application/vnd.fujixerox.docuworks": ["xdw"],
  "application/vnd.fujixerox.docuworks.binder": ["xbd"],
  "application/vnd.fuzzysheet": ["fzs"],
  "application/vnd.genomatix.tuxedo": ["txd"],
  "application/vnd.geogebra.file": ["ggb"],
  "application/vnd.geogebra.slides": ["ggs"],
  "application/vnd.geogebra.tool": ["ggt"],
  "application/vnd.geometry-explorer": ["gex", "gre"],
  "application/vnd.geonext": ["gxt"],
  "application/vnd.geoplan": ["g2w"],
  "application/vnd.geospace": ["g3w"],
  "application/vnd.gmx": ["gmx"],
  "application/vnd.google-apps.document": ["gdoc"],
  "application/vnd.google-apps.drawing": ["gdraw"],
  "application/vnd.google-apps.form": ["gform"],
  "application/vnd.google-apps.jam": ["gjam"],
  "application/vnd.google-apps.map": ["gmap"],
  "application/vnd.google-apps.presentation": ["gslides"],
  "application/vnd.google-apps.script": ["gscript"],
  "application/vnd.google-apps.site": ["gsite"],
  "application/vnd.google-apps.spreadsheet": ["gsheet"],
  "application/vnd.google-earth.kml+xml": ["kml"],
  "application/vnd.google-earth.kmz": ["kmz"],
  "application/vnd.gov.sk.xmldatacontainer+xml": ["xdcf"],
  "application/vnd.grafeq": ["gqf", "gqs"],
  "application/vnd.groove-account": ["gac"],
  "application/vnd.groove-help": ["ghf"],
  "application/vnd.groove-identity-message": ["gim"],
  "application/vnd.groove-injector": ["grv"],
  "application/vnd.groove-tool-message": ["gtm"],
  "application/vnd.groove-tool-template": ["tpl"],
  "application/vnd.groove-vcard": ["vcg"],
  "application/vnd.hal+xml": ["hal"],
  "application/vnd.handheld-entertainment+xml": ["zmm"],
  "application/vnd.hbci": ["hbci"],
  "application/vnd.hhe.lesson-player": ["les"],
  "application/vnd.hp-hpgl": ["hpgl"],
  "application/vnd.hp-hpid": ["hpid"],
  "application/vnd.hp-hps": ["hps"],
  "application/vnd.hp-jlyt": ["jlt"],
  "application/vnd.hp-pcl": ["pcl"],
  "application/vnd.hp-pclxl": ["pclxl"],
  "application/vnd.hydrostatix.sof-data": ["sfd-hdstx"],
  "application/vnd.ibm.minipay": ["mpy"],
  "application/vnd.ibm.modcap": ["afp", "listafp", "list3820"],
  "application/vnd.ibm.rights-management": ["irm"],
  "application/vnd.ibm.secure-container": ["sc"],
  "application/vnd.iccprofile": ["icc", "icm"],
  "application/vnd.igloader": ["igl"],
  "application/vnd.immervision-ivp": ["ivp"],
  "application/vnd.immervision-ivu": ["ivu"],
  "application/vnd.insors.igm": ["igm"],
  "application/vnd.intercon.formnet": ["xpw", "xpx"],
  "application/vnd.intergeo": ["i2g"],
  "application/vnd.intu.qbo": ["qbo"],
  "application/vnd.intu.qfx": ["qfx"],
  "application/vnd.ipunplugged.rcprofile": ["rcprofile"],
  "application/vnd.irepository.package+xml": ["irp"],
  "application/vnd.is-xpr": ["xpr"],
  "application/vnd.isac.fcs": ["fcs"],
  "application/vnd.jam": ["jam"],
  "application/vnd.jcp.javame.midlet-rms": ["rms"],
  "application/vnd.jisp": ["jisp"],
  "application/vnd.joost.joda-archive": ["joda"],
  "application/vnd.kahootz": ["ktz", "ktr"],
  "application/vnd.kde.karbon": ["karbon"],
  "application/vnd.kde.kchart": ["chrt"],
  "application/vnd.kde.kformula": ["kfo"],
  "application/vnd.kde.kivio": ["flw"],
  "application/vnd.kde.kontour": ["kon"],
  "application/vnd.kde.kpresenter": ["kpr", "kpt"],
  "application/vnd.kde.kspread": ["ksp"],
  "application/vnd.kde.kword": ["kwd", "kwt"],
  "application/vnd.kenameaapp": ["htke"],
  "application/vnd.kidspiration": ["kia"],
  "application/vnd.kinar": ["kne", "knp"],
  "application/vnd.koan": ["skp", "skd", "skt", "skm"],
  "application/vnd.kodak-descriptor": ["sse"],
  "application/vnd.las.las+xml": ["lasxml"],
  "application/vnd.llamagraphics.life-balance.desktop": ["lbd"],
  "application/vnd.llamagraphics.life-balance.exchange+xml": ["lbe"],
  "application/vnd.lotus-1-2-3": ["123"],
  "application/vnd.lotus-approach": ["apr"],
  "application/vnd.lotus-freelance": ["pre"],
  "application/vnd.lotus-notes": ["nsf"],
  "application/vnd.lotus-organizer": ["org"],
  "application/vnd.lotus-screencam": ["scm"],
  "application/vnd.lotus-wordpro": ["lwp"],
  "application/vnd.macports.portpkg": ["portpkg"],
  "application/vnd.mapbox-vector-tile": ["mvt"],
  "application/vnd.mcd": ["mcd"],
  "application/vnd.medcalcdata": ["mc1"],
  "application/vnd.mediastation.cdkey": ["cdkey"],
  "application/vnd.mfer": ["mwf"],
  "application/vnd.mfmp": ["mfm"],
  "application/vnd.micrografx.flo": ["flo"],
  "application/vnd.micrografx.igx": ["igx"],
  "application/vnd.mif": ["mif"],
  "application/vnd.mobius.daf": ["daf"],
  "application/vnd.mobius.dis": ["dis"],
  "application/vnd.mobius.mbk": ["mbk"],
  "application/vnd.mobius.mqy": ["mqy"],
  "application/vnd.mobius.msl": ["msl"],
  "application/vnd.mobius.plc": ["plc"],
  "application/vnd.mobius.txf": ["txf"],
  "application/vnd.mophun.application": ["mpn"],
  "application/vnd.mophun.certificate": ["mpc"],
  "application/vnd.mozilla.xul+xml": ["xul"],
  "application/vnd.ms-artgalry": ["cil"],
  "application/vnd.ms-cab-compressed": ["cab"],
  "application/vnd.ms-excel": ["xls", "xlm", "xla", "xlc", "xlt", "xlw"],
  "application/vnd.ms-excel.addin.macroenabled.12": ["xlam"],
  "application/vnd.ms-excel.sheet.binary.macroenabled.12": ["xlsb"],
  "application/vnd.ms-excel.sheet.macroenabled.12": ["xlsm"],
  "application/vnd.ms-excel.template.macroenabled.12": ["xltm"],
  "application/vnd.ms-fontobject": ["eot"],
  "application/vnd.ms-htmlhelp": ["chm"],
  "application/vnd.ms-ims": ["ims"],
  "application/vnd.ms-lrm": ["lrm"],
  "application/vnd.ms-officetheme": ["thmx"],
  "application/vnd.ms-outlook": ["msg"],
  "application/vnd.ms-pki.seccat": ["cat"],
  "application/vnd.ms-pki.stl": ["*stl"],
  "application/vnd.ms-powerpoint": ["ppt", "pps", "pot"],
  "application/vnd.ms-powerpoint.addin.macroenabled.12": ["ppam"],
  "application/vnd.ms-powerpoint.presentation.macroenabled.12": ["pptm"],
  "application/vnd.ms-powerpoint.slide.macroenabled.12": ["sldm"],
  "application/vnd.ms-powerpoint.slideshow.macroenabled.12": ["ppsm"],
  "application/vnd.ms-powerpoint.template.macroenabled.12": ["potm"],
  "application/vnd.ms-project": ["*mpp", "mpt"],
  "application/vnd.ms-visio.viewer": ["vdx"],
  "application/vnd.ms-word.document.macroenabled.12": ["docm"],
  "application/vnd.ms-word.template.macroenabled.12": ["dotm"],
  "application/vnd.ms-works": ["wps", "wks", "wcm", "wdb"],
  "application/vnd.ms-wpl": ["wpl"],
  "application/vnd.ms-xpsdocument": ["xps"],
  "application/vnd.mseq": ["mseq"],
  "application/vnd.musician": ["mus"],
  "application/vnd.muvee.style": ["msty"],
  "application/vnd.mynfc": ["taglet"],
  "application/vnd.nato.bindingdataobject+xml": ["bdo"],
  "application/vnd.neurolanguage.nlu": ["nlu"],
  "application/vnd.nitf": ["ntf", "nitf"],
  "application/vnd.noblenet-directory": ["nnd"],
  "application/vnd.noblenet-sealer": ["nns"],
  "application/vnd.noblenet-web": ["nnw"],
  "application/vnd.nokia.n-gage.ac+xml": ["*ac"],
  "application/vnd.nokia.n-gage.data": ["ngdat"],
  "application/vnd.nokia.n-gage.symbian.install": ["n-gage"],
  "application/vnd.nokia.radio-preset": ["rpst"],
  "application/vnd.nokia.radio-presets": ["rpss"],
  "application/vnd.novadigm.edm": ["edm"],
  "application/vnd.novadigm.edx": ["edx"],
  "application/vnd.novadigm.ext": ["ext"],
  "application/vnd.oasis.opendocument.chart": ["odc"],
  "application/vnd.oasis.opendocument.chart-template": ["otc"],
  "application/vnd.oasis.opendocument.database": ["odb"],
  "application/vnd.oasis.opendocument.formula": ["odf"],
  "application/vnd.oasis.opendocument.formula-template": ["odft"],
  "application/vnd.oasis.opendocument.graphics": ["odg"],
  "application/vnd.oasis.opendocument.graphics-template": ["otg"],
  "application/vnd.oasis.opendocument.image": ["odi"],
  "application/vnd.oasis.opendocument.image-template": ["oti"],
  "application/vnd.oasis.opendocument.presentation": ["odp"],
  "application/vnd.oasis.opendocument.presentation-template": ["otp"],
  "application/vnd.oasis.opendocument.spreadsheet": ["ods"],
  "application/vnd.oasis.opendocument.spreadsheet-template": ["ots"],
  "application/vnd.oasis.opendocument.text": ["odt"],
  "application/vnd.oasis.opendocument.text-master": ["odm"],
  "application/vnd.oasis.opendocument.text-template": ["ott"],
  "application/vnd.oasis.opendocument.text-web": ["oth"],
  "application/vnd.olpc-sugar": ["xo"],
  "application/vnd.oma.dd2+xml": ["dd2"],
  "application/vnd.openblox.game+xml": ["obgx"],
  "application/vnd.openofficeorg.extension": ["oxt"],
  "application/vnd.openstreetmap.data+xml": ["osm"],
  "application/vnd.openxmlformats-officedocument.presentationml.presentation": [
    "pptx"
  ],
  "application/vnd.openxmlformats-officedocument.presentationml.slide": [
    "sldx"
  ],
  "application/vnd.openxmlformats-officedocument.presentationml.slideshow": [
    "ppsx"
  ],
  "application/vnd.openxmlformats-officedocument.presentationml.template": [
    "potx"
  ],
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ["xlsx"],
  "application/vnd.openxmlformats-officedocument.spreadsheetml.template": [
    "xltx"
  ],
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document": [
    "docx"
  ],
  "application/vnd.openxmlformats-officedocument.wordprocessingml.template": [
    "dotx"
  ],
  "application/vnd.osgeo.mapguide.package": ["mgp"],
  "application/vnd.osgi.dp": ["dp"],
  "application/vnd.osgi.subsystem": ["esa"],
  "application/vnd.palm": ["pdb", "pqa", "oprc"],
  "application/vnd.pawaafile": ["paw"],
  "application/vnd.pg.format": ["str"],
  "application/vnd.pg.osasli": ["ei6"],
  "application/vnd.picsel": ["efif"],
  "application/vnd.pmi.widget": ["wg"],
  "application/vnd.pocketlearn": ["plf"],
  "application/vnd.powerbuilder6": ["pbd"],
  "application/vnd.previewsystems.box": ["box"],
  "application/vnd.procrate.brushset": ["brushset"],
  "application/vnd.procreate.brush": ["brush"],
  "application/vnd.procreate.dream": ["drm"],
  "application/vnd.proteus.magazine": ["mgz"],
  "application/vnd.publishare-delta-tree": ["qps"],
  "application/vnd.pvi.ptid1": ["ptid"],
  "application/vnd.pwg-xhtml-print+xml": ["xhtm"],
  "application/vnd.quark.quarkxpress": [
    "qxd",
    "qxt",
    "qwd",
    "qwt",
    "qxl",
    "qxb"
  ],
  "application/vnd.rar": ["rar"],
  "application/vnd.realvnc.bed": ["bed"],
  "application/vnd.recordare.musicxml": ["mxl"],
  "application/vnd.recordare.musicxml+xml": ["musicxml"],
  "application/vnd.rig.cryptonote": ["cryptonote"],
  "application/vnd.rim.cod": ["cod"],
  "application/vnd.rn-realmedia": ["rm"],
  "application/vnd.rn-realmedia-vbr": ["rmvb"],
  "application/vnd.route66.link66+xml": ["link66"],
  "application/vnd.sailingtracker.track": ["st"],
  "application/vnd.seemail": ["see"],
  "application/vnd.sema": ["sema"],
  "application/vnd.semd": ["semd"],
  "application/vnd.semf": ["semf"],
  "application/vnd.shana.informed.formdata": ["ifm"],
  "application/vnd.shana.informed.formtemplate": ["itp"],
  "application/vnd.shana.informed.interchange": ["iif"],
  "application/vnd.shana.informed.package": ["ipk"],
  "application/vnd.simtech-mindmapper": ["twd", "twds"],
  "application/vnd.smaf": ["mmf"],
  "application/vnd.smart.teacher": ["teacher"],
  "application/vnd.software602.filler.form+xml": ["fo"],
  "application/vnd.solent.sdkm+xml": ["sdkm", "sdkd"],
  "application/vnd.spotfire.dxp": ["dxp"],
  "application/vnd.spotfire.sfs": ["sfs"],
  "application/vnd.stardivision.calc": ["sdc"],
  "application/vnd.stardivision.draw": ["sda"],
  "application/vnd.stardivision.impress": ["sdd"],
  "application/vnd.stardivision.math": ["smf"],
  "application/vnd.stardivision.writer": ["sdw", "vor"],
  "application/vnd.stardivision.writer-global": ["sgl"],
  "application/vnd.stepmania.package": ["smzip"],
  "application/vnd.stepmania.stepchart": ["sm"],
  "application/vnd.sun.wadl+xml": ["wadl"],
  "application/vnd.sun.xml.calc": ["sxc"],
  "application/vnd.sun.xml.calc.template": ["stc"],
  "application/vnd.sun.xml.draw": ["sxd"],
  "application/vnd.sun.xml.draw.template": ["std"],
  "application/vnd.sun.xml.impress": ["sxi"],
  "application/vnd.sun.xml.impress.template": ["sti"],
  "application/vnd.sun.xml.math": ["sxm"],
  "application/vnd.sun.xml.writer": ["sxw"],
  "application/vnd.sun.xml.writer.global": ["sxg"],
  "application/vnd.sun.xml.writer.template": ["stw"],
  "application/vnd.sus-calendar": ["sus", "susp"],
  "application/vnd.svd": ["svd"],
  "application/vnd.symbian.install": ["sis", "sisx"],
  "application/vnd.syncml+xml": ["xsm"],
  "application/vnd.syncml.dm+wbxml": ["bdm"],
  "application/vnd.syncml.dm+xml": ["xdm"],
  "application/vnd.syncml.dmddf+xml": ["ddf"],
  "application/vnd.tao.intent-module-archive": ["tao"],
  "application/vnd.tcpdump.pcap": ["pcap", "cap", "dmp"],
  "application/vnd.tmobile-livetv": ["tmo"],
  "application/vnd.trid.tpt": ["tpt"],
  "application/vnd.triscape.mxs": ["mxs"],
  "application/vnd.trueapp": ["tra"],
  "application/vnd.ufdl": ["ufd", "ufdl"],
  "application/vnd.uiq.theme": ["utz"],
  "application/vnd.umajin": ["umj"],
  "application/vnd.unity": ["unityweb"],
  "application/vnd.uoml+xml": ["uoml", "uo"],
  "application/vnd.vcx": ["vcx"],
  "application/vnd.visio": ["vsd", "vst", "vss", "vsw", "vsdx", "vtx"],
  "application/vnd.visionary": ["vis"],
  "application/vnd.vsf": ["vsf"],
  "application/vnd.wap.wbxml": ["wbxml"],
  "application/vnd.wap.wmlc": ["wmlc"],
  "application/vnd.wap.wmlscriptc": ["wmlsc"],
  "application/vnd.webturbo": ["wtb"],
  "application/vnd.wolfram.player": ["nbp"],
  "application/vnd.wordperfect": ["wpd"],
  "application/vnd.wqd": ["wqd"],
  "application/vnd.wt.stf": ["stf"],
  "application/vnd.xara": ["xar"],
  "application/vnd.xfdl": ["xfdl"],
  "application/vnd.yamaha.hv-dic": ["hvd"],
  "application/vnd.yamaha.hv-script": ["hvs"],
  "application/vnd.yamaha.hv-voice": ["hvp"],
  "application/vnd.yamaha.openscoreformat": ["osf"],
  "application/vnd.yamaha.openscoreformat.osfpvg+xml": ["osfpvg"],
  "application/vnd.yamaha.smaf-audio": ["saf"],
  "application/vnd.yamaha.smaf-phrase": ["spf"],
  "application/vnd.yellowriver-custom-menu": ["cmp"],
  "application/vnd.zul": ["zir", "zirz"],
  "application/vnd.zzazz.deck+xml": ["zaz"],
  "application/x-7z-compressed": ["7z"],
  "application/x-abiword": ["abw"],
  "application/x-ace-compressed": ["ace"],
  "application/x-apple-diskimage": ["*dmg"],
  "application/x-arj": ["arj"],
  "application/x-authorware-bin": ["aab", "x32", "u32", "vox"],
  "application/x-authorware-map": ["aam"],
  "application/x-authorware-seg": ["aas"],
  "application/x-bcpio": ["bcpio"],
  "application/x-bdoc": ["*bdoc"],
  "application/x-bittorrent": ["torrent"],
  "application/x-blender": ["blend"],
  "application/x-blorb": ["blb", "blorb"],
  "application/x-bzip": ["bz"],
  "application/x-bzip2": ["bz2", "boz"],
  "application/x-cbr": ["cbr", "cba", "cbt", "cbz", "cb7"],
  "application/x-cdlink": ["vcd"],
  "application/x-cfs-compressed": ["cfs"],
  "application/x-chat": ["chat"],
  "application/x-chess-pgn": ["pgn"],
  "application/x-chrome-extension": ["crx"],
  "application/x-cocoa": ["cco"],
  "application/x-compressed": ["*rar"],
  "application/x-conference": ["nsc"],
  "application/x-cpio": ["cpio"],
  "application/x-csh": ["csh"],
  "application/x-debian-package": ["*deb", "udeb"],
  "application/x-dgc-compressed": ["dgc"],
  "application/x-director": [
    "dir",
    "dcr",
    "dxr",
    "cst",
    "cct",
    "cxt",
    "w3d",
    "fgd",
    "swa"
  ],
  "application/x-doom": ["wad"],
  "application/x-dtbncx+xml": ["ncx"],
  "application/x-dtbook+xml": ["dtb"],
  "application/x-dtbresource+xml": ["res"],
  "application/x-dvi": ["dvi"],
  "application/x-envoy": ["evy"],
  "application/x-eva": ["eva"],
  "application/x-font-bdf": ["bdf"],
  "application/x-font-ghostscript": ["gsf"],
  "application/x-font-linux-psf": ["psf"],
  "application/x-font-pcf": ["pcf"],
  "application/x-font-snf": ["snf"],
  "application/x-font-type1": ["pfa", "pfb", "pfm", "afm"],
  "application/x-freearc": ["arc"],
  "application/x-futuresplash": ["spl"],
  "application/x-gca-compressed": ["gca"],
  "application/x-glulx": ["ulx"],
  "application/x-gnumeric": ["gnumeric"],
  "application/x-gramps-xml": ["gramps"],
  "application/x-gtar": ["gtar"],
  "application/x-hdf": ["hdf"],
  "application/x-httpd-php": ["php"],
  "application/x-install-instructions": ["install"],
  "application/x-ipynb+json": ["ipynb"],
  "application/x-iso9660-image": ["*iso"],
  "application/x-iwork-keynote-sffkey": ["*key"],
  "application/x-iwork-numbers-sffnumbers": ["*numbers"],
  "application/x-iwork-pages-sffpages": ["*pages"],
  "application/x-java-archive-diff": ["jardiff"],
  "application/x-java-jnlp-file": ["jnlp"],
  "application/x-keepass2": ["kdbx"],
  "application/x-latex": ["latex"],
  "application/x-lua-bytecode": ["luac"],
  "application/x-lzh-compressed": ["lzh", "lha"],
  "application/x-makeself": ["run"],
  "application/x-mie": ["mie"],
  "application/x-mobipocket-ebook": ["*prc", "mobi"],
  "application/x-ms-application": ["application"],
  "application/x-ms-shortcut": ["lnk"],
  "application/x-ms-wmd": ["wmd"],
  "application/x-ms-wmz": ["wmz"],
  "application/x-ms-xbap": ["xbap"],
  "application/x-msaccess": ["mdb"],
  "application/x-msbinder": ["obd"],
  "application/x-mscardfile": ["crd"],
  "application/x-msclip": ["clp"],
  "application/x-msdos-program": ["*exe"],
  "application/x-msdownload": ["*exe", "*dll", "com", "bat", "*msi"],
  "application/x-msmediaview": ["mvb", "m13", "m14"],
  "application/x-msmetafile": ["*wmf", "*wmz", "*emf", "emz"],
  "application/x-msmoney": ["mny"],
  "application/x-mspublisher": ["pub"],
  "application/x-msschedule": ["scd"],
  "application/x-msterminal": ["trm"],
  "application/x-mswrite": ["wri"],
  "application/x-netcdf": ["nc", "cdf"],
  "application/x-ns-proxy-autoconfig": ["pac"],
  "application/x-nzb": ["nzb"],
  "application/x-perl": ["pl", "pm"],
  "application/x-pilot": ["*prc", "*pdb"],
  "application/x-pkcs12": ["p12", "pfx"],
  "application/x-pkcs7-certificates": ["p7b", "spc"],
  "application/x-pkcs7-certreqresp": ["p7r"],
  "application/x-rar-compressed": ["*rar"],
  "application/x-redhat-package-manager": ["rpm"],
  "application/x-research-info-systems": ["ris"],
  "application/x-sea": ["sea"],
  "application/x-sh": ["sh"],
  "application/x-shar": ["shar"],
  "application/x-shockwave-flash": ["swf"],
  "application/x-silverlight-app": ["xap"],
  "application/x-sql": ["*sql"],
  "application/x-stuffit": ["sit"],
  "application/x-stuffitx": ["sitx"],
  "application/x-subrip": ["srt"],
  "application/x-sv4cpio": ["sv4cpio"],
  "application/x-sv4crc": ["sv4crc"],
  "application/x-t3vm-image": ["t3"],
  "application/x-tads": ["gam"],
  "application/x-tar": ["tar"],
  "application/x-tcl": ["tcl", "tk"],
  "application/x-tex": ["tex"],
  "application/x-tex-tfm": ["tfm"],
  "application/x-texinfo": ["texinfo", "texi"],
  "application/x-tgif": ["*obj"],
  "application/x-ustar": ["ustar"],
  "application/x-virtualbox-hdd": ["hdd"],
  "application/x-virtualbox-ova": ["ova"],
  "application/x-virtualbox-ovf": ["ovf"],
  "application/x-virtualbox-vbox": ["vbox"],
  "application/x-virtualbox-vbox-extpack": ["vbox-extpack"],
  "application/x-virtualbox-vdi": ["vdi"],
  "application/x-virtualbox-vhd": ["vhd"],
  "application/x-virtualbox-vmdk": ["vmdk"],
  "application/x-wais-source": ["src"],
  "application/x-web-app-manifest+json": ["webapp"],
  "application/x-x509-ca-cert": ["der", "crt", "pem"],
  "application/x-xfig": ["fig"],
  "application/x-xliff+xml": ["*xlf"],
  "application/x-xpinstall": ["xpi"],
  "application/x-xz": ["xz"],
  "application/x-zip-compressed": ["*zip"],
  "application/x-zmachine": ["z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8"],
  "audio/vnd.dece.audio": ["uva", "uvva"],
  "audio/vnd.digital-winds": ["eol"],
  "audio/vnd.dra": ["dra"],
  "audio/vnd.dts": ["dts"],
  "audio/vnd.dts.hd": ["dtshd"],
  "audio/vnd.lucent.voice": ["lvp"],
  "audio/vnd.ms-playready.media.pya": ["pya"],
  "audio/vnd.nuera.ecelp4800": ["ecelp4800"],
  "audio/vnd.nuera.ecelp7470": ["ecelp7470"],
  "audio/vnd.nuera.ecelp9600": ["ecelp9600"],
  "audio/vnd.rip": ["rip"],
  "audio/x-aac": ["*aac"],
  "audio/x-aiff": ["aif", "aiff", "aifc"],
  "audio/x-caf": ["caf"],
  "audio/x-flac": ["flac"],
  "audio/x-m4a": ["*m4a"],
  "audio/x-matroska": ["mka"],
  "audio/x-mpegurl": ["m3u"],
  "audio/x-ms-wax": ["wax"],
  "audio/x-ms-wma": ["wma"],
  "audio/x-pn-realaudio": ["ram", "ra"],
  "audio/x-pn-realaudio-plugin": ["rmp"],
  "audio/x-realaudio": ["*ra"],
  "audio/x-wav": ["*wav"],
  "chemical/x-cdx": ["cdx"],
  "chemical/x-cif": ["cif"],
  "chemical/x-cmdf": ["cmdf"],
  "chemical/x-cml": ["cml"],
  "chemical/x-csml": ["csml"],
  "chemical/x-xyz": ["xyz"],
  "image/prs.btif": ["btif", "btf"],
  "image/prs.pti": ["pti"],
  "image/vnd.adobe.photoshop": ["psd"],
  "image/vnd.airzip.accelerator.azv": ["azv"],
  "image/vnd.dece.graphic": ["uvi", "uvvi", "uvg", "uvvg"],
  "image/vnd.djvu": ["djvu", "djv"],
  "image/vnd.dvb.subtitle": ["*sub"],
  "image/vnd.dwg": ["dwg"],
  "image/vnd.dxf": ["dxf"],
  "image/vnd.fastbidsheet": ["fbs"],
  "image/vnd.fpx": ["fpx"],
  "image/vnd.fst": ["fst"],
  "image/vnd.fujixerox.edmics-mmr": ["mmr"],
  "image/vnd.fujixerox.edmics-rlc": ["rlc"],
  "image/vnd.microsoft.icon": ["ico"],
  "image/vnd.ms-dds": ["dds"],
  "image/vnd.ms-modi": ["mdi"],
  "image/vnd.ms-photo": ["wdp"],
  "image/vnd.net-fpx": ["npx"],
  "image/vnd.pco.b16": ["b16"],
  "image/vnd.tencent.tap": ["tap"],
  "image/vnd.valve.source.texture": ["vtf"],
  "image/vnd.wap.wbmp": ["wbmp"],
  "image/vnd.xiff": ["xif"],
  "image/vnd.zbrush.pcx": ["pcx"],
  "image/x-3ds": ["3ds"],
  "image/x-adobe-dng": ["dng"],
  "image/x-cmu-raster": ["ras"],
  "image/x-cmx": ["cmx"],
  "image/x-freehand": ["fh", "fhc", "fh4", "fh5", "fh7"],
  "image/x-icon": ["*ico"],
  "image/x-jng": ["jng"],
  "image/x-mrsid-image": ["sid"],
  "image/x-ms-bmp": ["*bmp"],
  "image/x-pcx": ["*pcx"],
  "image/x-pict": ["pic", "pct"],
  "image/x-portable-anymap": ["pnm"],
  "image/x-portable-bitmap": ["pbm"],
  "image/x-portable-graymap": ["pgm"],
  "image/x-portable-pixmap": ["ppm"],
  "image/x-rgb": ["rgb"],
  "image/x-tga": ["tga"],
  "image/x-xbitmap": ["xbm"],
  "image/x-xpixmap": ["xpm"],
  "image/x-xwindowdump": ["xwd"],
  "message/vnd.wfa.wsc": ["wsc"],
  "model/vnd.bary": ["bary"],
  "model/vnd.cld": ["cld"],
  "model/vnd.collada+xml": ["dae"],
  "model/vnd.dwf": ["dwf"],
  "model/vnd.gdl": ["gdl"],
  "model/vnd.gtw": ["gtw"],
  "model/vnd.mts": ["*mts"],
  "model/vnd.opengex": ["ogex"],
  "model/vnd.parasolid.transmit.binary": ["x_b"],
  "model/vnd.parasolid.transmit.text": ["x_t"],
  "model/vnd.pytha.pyox": ["pyo", "pyox"],
  "model/vnd.sap.vds": ["vds"],
  "model/vnd.usda": ["usda"],
  "model/vnd.usdz+zip": ["usdz"],
  "model/vnd.valve.source.compiled-map": ["bsp"],
  "model/vnd.vtu": ["vtu"],
  "text/prs.lines.tag": ["dsc"],
  "text/vnd.curl": ["curl"],
  "text/vnd.curl.dcurl": ["dcurl"],
  "text/vnd.curl.mcurl": ["mcurl"],
  "text/vnd.curl.scurl": ["scurl"],
  "text/vnd.dvb.subtitle": ["sub"],
  "text/vnd.familysearch.gedcom": ["ged"],
  "text/vnd.fly": ["fly"],
  "text/vnd.fmi.flexstor": ["flx"],
  "text/vnd.graphviz": ["gv"],
  "text/vnd.in3d.3dml": ["3dml"],
  "text/vnd.in3d.spot": ["spot"],
  "text/vnd.sun.j2me.app-descriptor": ["jad"],
  "text/vnd.wap.wml": ["wml"],
  "text/vnd.wap.wmlscript": ["wmls"],
  "text/x-asm": ["s", "asm"],
  "text/x-c": ["c", "cc", "cxx", "cpp", "h", "hh", "dic"],
  "text/x-component": ["htc"],
  "text/x-fortran": ["f", "for", "f77", "f90"],
  "text/x-handlebars-template": ["hbs"],
  "text/x-java-source": ["java"],
  "text/x-lua": ["lua"],
  "text/x-markdown": ["mkd"],
  "text/x-nfo": ["nfo"],
  "text/x-opml": ["opml"],
  "text/x-org": ["*org"],
  "text/x-pascal": ["p", "pas"],
  "text/x-processing": ["pde"],
  "text/x-sass": ["sass"],
  "text/x-scss": ["scss"],
  "text/x-setext": ["etx"],
  "text/x-sfv": ["sfv"],
  "text/x-suse-ymp": ["ymp"],
  "text/x-uuencode": ["uu"],
  "text/x-vcalendar": ["vcs"],
  "text/x-vcard": ["vcf"],
  "video/vnd.dece.hd": ["uvh", "uvvh"],
  "video/vnd.dece.mobile": ["uvm", "uvvm"],
  "video/vnd.dece.pd": ["uvp", "uvvp"],
  "video/vnd.dece.sd": ["uvs", "uvvs"],
  "video/vnd.dece.video": ["uvv", "uvvv"],
  "video/vnd.dvb.file": ["dvb"],
  "video/vnd.fvt": ["fvt"],
  "video/vnd.mpegurl": ["mxu", "m4u"],
  "video/vnd.ms-playready.media.pyv": ["pyv"],
  "video/vnd.uvvu.mp4": ["uvu", "uvvu"],
  "video/vnd.vivo": ["viv"],
  "video/x-f4v": ["f4v"],
  "video/x-fli": ["fli"],
  "video/x-flv": ["flv"],
  "video/x-m4v": ["m4v"],
  "video/x-matroska": ["mkv", "mk3d", "mks"],
  "video/x-mng": ["mng"],
  "video/x-ms-asf": ["asf", "asx"],
  "video/x-ms-vob": ["vob"],
  "video/x-ms-wm": ["wm"],
  "video/x-ms-wmv": ["wmv"],
  "video/x-ms-wmx": ["wmx"],
  "video/x-ms-wvx": ["wvx"],
  "video/x-msvideo": ["avi"],
  "video/x-sgi-movie": ["movie"],
  "video/x-smv": ["smv"],
  "x-conference/x-cooltalk": ["ice"]
};
Object.freeze(types);
var other_default = types;

// ../../node_modules/.pnpm/mime@4.0.7/node_modules/mime/dist/types/standard.js
var types2 = {
  "application/andrew-inset": ["ez"],
  "application/appinstaller": ["appinstaller"],
  "application/applixware": ["aw"],
  "application/appx": ["appx"],
  "application/appxbundle": ["appxbundle"],
  "application/atom+xml": ["atom"],
  "application/atomcat+xml": ["atomcat"],
  "application/atomdeleted+xml": ["atomdeleted"],
  "application/atomsvc+xml": ["atomsvc"],
  "application/atsc-dwd+xml": ["dwd"],
  "application/atsc-held+xml": ["held"],
  "application/atsc-rsat+xml": ["rsat"],
  "application/automationml-aml+xml": ["aml"],
  "application/automationml-amlx+zip": ["amlx"],
  "application/bdoc": ["bdoc"],
  "application/calendar+xml": ["xcs"],
  "application/ccxml+xml": ["ccxml"],
  "application/cdfx+xml": ["cdfx"],
  "application/cdmi-capability": ["cdmia"],
  "application/cdmi-container": ["cdmic"],
  "application/cdmi-domain": ["cdmid"],
  "application/cdmi-object": ["cdmio"],
  "application/cdmi-queue": ["cdmiq"],
  "application/cpl+xml": ["cpl"],
  "application/cu-seeme": ["cu"],
  "application/cwl": ["cwl"],
  "application/dash+xml": ["mpd"],
  "application/dash-patch+xml": ["mpp"],
  "application/davmount+xml": ["davmount"],
  "application/dicom": ["dcm"],
  "application/docbook+xml": ["dbk"],
  "application/dssc+der": ["dssc"],
  "application/dssc+xml": ["xdssc"],
  "application/ecmascript": ["ecma"],
  "application/emma+xml": ["emma"],
  "application/emotionml+xml": ["emotionml"],
  "application/epub+zip": ["epub"],
  "application/exi": ["exi"],
  "application/express": ["exp"],
  "application/fdf": ["fdf"],
  "application/fdt+xml": ["fdt"],
  "application/font-tdpfr": ["pfr"],
  "application/geo+json": ["geojson"],
  "application/gml+xml": ["gml"],
  "application/gpx+xml": ["gpx"],
  "application/gxf": ["gxf"],
  "application/gzip": ["gz"],
  "application/hjson": ["hjson"],
  "application/hyperstudio": ["stk"],
  "application/inkml+xml": ["ink", "inkml"],
  "application/ipfix": ["ipfix"],
  "application/its+xml": ["its"],
  "application/java-archive": ["jar", "war", "ear"],
  "application/java-serialized-object": ["ser"],
  "application/java-vm": ["class"],
  "application/javascript": ["*js"],
  "application/json": ["json", "map"],
  "application/json5": ["json5"],
  "application/jsonml+json": ["jsonml"],
  "application/ld+json": ["jsonld"],
  "application/lgr+xml": ["lgr"],
  "application/lost+xml": ["lostxml"],
  "application/mac-binhex40": ["hqx"],
  "application/mac-compactpro": ["cpt"],
  "application/mads+xml": ["mads"],
  "application/manifest+json": ["webmanifest"],
  "application/marc": ["mrc"],
  "application/marcxml+xml": ["mrcx"],
  "application/mathematica": ["ma", "nb", "mb"],
  "application/mathml+xml": ["mathml"],
  "application/mbox": ["mbox"],
  "application/media-policy-dataset+xml": ["mpf"],
  "application/mediaservercontrol+xml": ["mscml"],
  "application/metalink+xml": ["metalink"],
  "application/metalink4+xml": ["meta4"],
  "application/mets+xml": ["mets"],
  "application/mmt-aei+xml": ["maei"],
  "application/mmt-usd+xml": ["musd"],
  "application/mods+xml": ["mods"],
  "application/mp21": ["m21", "mp21"],
  "application/mp4": ["*mp4", "*mpg4", "mp4s", "m4p"],
  "application/msix": ["msix"],
  "application/msixbundle": ["msixbundle"],
  "application/msword": ["doc", "dot"],
  "application/mxf": ["mxf"],
  "application/n-quads": ["nq"],
  "application/n-triples": ["nt"],
  "application/node": ["cjs"],
  "application/octet-stream": [
    "bin",
    "dms",
    "lrf",
    "mar",
    "so",
    "dist",
    "distz",
    "pkg",
    "bpk",
    "dump",
    "elc",
    "deploy",
    "exe",
    "dll",
    "deb",
    "dmg",
    "iso",
    "img",
    "msi",
    "msp",
    "msm",
    "buffer"
  ],
  "application/oda": ["oda"],
  "application/oebps-package+xml": ["opf"],
  "application/ogg": ["ogx"],
  "application/omdoc+xml": ["omdoc"],
  "application/onenote": [
    "onetoc",
    "onetoc2",
    "onetmp",
    "onepkg",
    "one",
    "onea"
  ],
  "application/oxps": ["oxps"],
  "application/p2p-overlay+xml": ["relo"],
  "application/patch-ops-error+xml": ["xer"],
  "application/pdf": ["pdf"],
  "application/pgp-encrypted": ["pgp"],
  "application/pgp-keys": ["asc"],
  "application/pgp-signature": ["sig", "*asc"],
  "application/pics-rules": ["prf"],
  "application/pkcs10": ["p10"],
  "application/pkcs7-mime": ["p7m", "p7c"],
  "application/pkcs7-signature": ["p7s"],
  "application/pkcs8": ["p8"],
  "application/pkix-attr-cert": ["ac"],
  "application/pkix-cert": ["cer"],
  "application/pkix-crl": ["crl"],
  "application/pkix-pkipath": ["pkipath"],
  "application/pkixcmp": ["pki"],
  "application/pls+xml": ["pls"],
  "application/postscript": ["ai", "eps", "ps"],
  "application/provenance+xml": ["provx"],
  "application/pskc+xml": ["pskcxml"],
  "application/raml+yaml": ["raml"],
  "application/rdf+xml": ["rdf", "owl"],
  "application/reginfo+xml": ["rif"],
  "application/relax-ng-compact-syntax": ["rnc"],
  "application/resource-lists+xml": ["rl"],
  "application/resource-lists-diff+xml": ["rld"],
  "application/rls-services+xml": ["rs"],
  "application/route-apd+xml": ["rapd"],
  "application/route-s-tsid+xml": ["sls"],
  "application/route-usd+xml": ["rusd"],
  "application/rpki-ghostbusters": ["gbr"],
  "application/rpki-manifest": ["mft"],
  "application/rpki-roa": ["roa"],
  "application/rsd+xml": ["rsd"],
  "application/rss+xml": ["rss"],
  "application/rtf": ["rtf"],
  "application/sbml+xml": ["sbml"],
  "application/scvp-cv-request": ["scq"],
  "application/scvp-cv-response": ["scs"],
  "application/scvp-vp-request": ["spq"],
  "application/scvp-vp-response": ["spp"],
  "application/sdp": ["sdp"],
  "application/senml+xml": ["senmlx"],
  "application/sensml+xml": ["sensmlx"],
  "application/set-payment-initiation": ["setpay"],
  "application/set-registration-initiation": ["setreg"],
  "application/shf+xml": ["shf"],
  "application/sieve": ["siv", "sieve"],
  "application/smil+xml": ["smi", "smil"],
  "application/sparql-query": ["rq"],
  "application/sparql-results+xml": ["srx"],
  "application/sql": ["sql"],
  "application/srgs": ["gram"],
  "application/srgs+xml": ["grxml"],
  "application/sru+xml": ["sru"],
  "application/ssdl+xml": ["ssdl"],
  "application/ssml+xml": ["ssml"],
  "application/swid+xml": ["swidtag"],
  "application/tei+xml": ["tei", "teicorpus"],
  "application/thraud+xml": ["tfi"],
  "application/timestamped-data": ["tsd"],
  "application/toml": ["toml"],
  "application/trig": ["trig"],
  "application/ttml+xml": ["ttml"],
  "application/ubjson": ["ubj"],
  "application/urc-ressheet+xml": ["rsheet"],
  "application/urc-targetdesc+xml": ["td"],
  "application/voicexml+xml": ["vxml"],
  "application/wasm": ["wasm"],
  "application/watcherinfo+xml": ["wif"],
  "application/widget": ["wgt"],
  "application/winhlp": ["hlp"],
  "application/wsdl+xml": ["wsdl"],
  "application/wspolicy+xml": ["wspolicy"],
  "application/xaml+xml": ["xaml"],
  "application/xcap-att+xml": ["xav"],
  "application/xcap-caps+xml": ["xca"],
  "application/xcap-diff+xml": ["xdf"],
  "application/xcap-el+xml": ["xel"],
  "application/xcap-ns+xml": ["xns"],
  "application/xenc+xml": ["xenc"],
  "application/xfdf": ["xfdf"],
  "application/xhtml+xml": ["xhtml", "xht"],
  "application/xliff+xml": ["xlf"],
  "application/xml": ["xml", "xsl", "xsd", "rng"],
  "application/xml-dtd": ["dtd"],
  "application/xop+xml": ["xop"],
  "application/xproc+xml": ["xpl"],
  "application/xslt+xml": ["*xsl", "xslt"],
  "application/xspf+xml": ["xspf"],
  "application/xv+xml": ["mxml", "xhvml", "xvml", "xvm"],
  "application/yang": ["yang"],
  "application/yin+xml": ["yin"],
  "application/zip": ["zip"],
  "application/zip+dotlottie": ["lottie"],
  "audio/3gpp": ["*3gpp"],
  "audio/aac": ["adts", "aac"],
  "audio/adpcm": ["adp"],
  "audio/amr": ["amr"],
  "audio/basic": ["au", "snd"],
  "audio/midi": ["mid", "midi", "kar", "rmi"],
  "audio/mobile-xmf": ["mxmf"],
  "audio/mp3": ["*mp3"],
  "audio/mp4": ["m4a", "mp4a", "m4b"],
  "audio/mpeg": ["mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"],
  "audio/ogg": ["oga", "ogg", "spx", "opus"],
  "audio/s3m": ["s3m"],
  "audio/silk": ["sil"],
  "audio/wav": ["wav"],
  "audio/wave": ["*wav"],
  "audio/webm": ["weba"],
  "audio/xm": ["xm"],
  "font/collection": ["ttc"],
  "font/otf": ["otf"],
  "font/ttf": ["ttf"],
  "font/woff": ["woff"],
  "font/woff2": ["woff2"],
  "image/aces": ["exr"],
  "image/apng": ["apng"],
  "image/avci": ["avci"],
  "image/avcs": ["avcs"],
  "image/avif": ["avif"],
  "image/bmp": ["bmp", "dib"],
  "image/cgm": ["cgm"],
  "image/dicom-rle": ["drle"],
  "image/dpx": ["dpx"],
  "image/emf": ["emf"],
  "image/fits": ["fits"],
  "image/g3fax": ["g3"],
  "image/gif": ["gif"],
  "image/heic": ["heic"],
  "image/heic-sequence": ["heics"],
  "image/heif": ["heif"],
  "image/heif-sequence": ["heifs"],
  "image/hej2k": ["hej2"],
  "image/ief": ["ief"],
  "image/jaii": ["jaii"],
  "image/jais": ["jais"],
  "image/jls": ["jls"],
  "image/jp2": ["jp2", "jpg2"],
  "image/jpeg": ["jpg", "jpeg", "jpe"],
  "image/jph": ["jph"],
  "image/jphc": ["jhc"],
  "image/jpm": ["jpm", "jpgm"],
  "image/jpx": ["jpx", "jpf"],
  "image/jxl": ["jxl"],
  "image/jxr": ["jxr"],
  "image/jxra": ["jxra"],
  "image/jxrs": ["jxrs"],
  "image/jxs": ["jxs"],
  "image/jxsc": ["jxsc"],
  "image/jxsi": ["jxsi"],
  "image/jxss": ["jxss"],
  "image/ktx": ["ktx"],
  "image/ktx2": ["ktx2"],
  "image/pjpeg": ["jfif"],
  "image/png": ["png"],
  "image/sgi": ["sgi"],
  "image/svg+xml": ["svg", "svgz"],
  "image/t38": ["t38"],
  "image/tiff": ["tif", "tiff"],
  "image/tiff-fx": ["tfx"],
  "image/webp": ["webp"],
  "image/wmf": ["wmf"],
  "message/disposition-notification": ["disposition-notification"],
  "message/global": ["u8msg"],
  "message/global-delivery-status": ["u8dsn"],
  "message/global-disposition-notification": ["u8mdn"],
  "message/global-headers": ["u8hdr"],
  "message/rfc822": ["eml", "mime", "mht", "mhtml"],
  "model/3mf": ["3mf"],
  "model/gltf+json": ["gltf"],
  "model/gltf-binary": ["glb"],
  "model/iges": ["igs", "iges"],
  "model/jt": ["jt"],
  "model/mesh": ["msh", "mesh", "silo"],
  "model/mtl": ["mtl"],
  "model/obj": ["obj"],
  "model/prc": ["prc"],
  "model/step": ["step", "stp", "stpnc", "p21", "210"],
  "model/step+xml": ["stpx"],
  "model/step+zip": ["stpz"],
  "model/step-xml+zip": ["stpxz"],
  "model/stl": ["stl"],
  "model/u3d": ["u3d"],
  "model/vrml": ["wrl", "vrml"],
  "model/x3d+binary": ["*x3db", "x3dbz"],
  "model/x3d+fastinfoset": ["x3db"],
  "model/x3d+vrml": ["*x3dv", "x3dvz"],
  "model/x3d+xml": ["x3d", "x3dz"],
  "model/x3d-vrml": ["x3dv"],
  "text/cache-manifest": ["appcache", "manifest"],
  "text/calendar": ["ics", "ifb"],
  "text/coffeescript": ["coffee", "litcoffee"],
  "text/css": ["css"],
  "text/csv": ["csv"],
  "text/html": ["html", "htm", "shtml"],
  "text/jade": ["jade"],
  "text/javascript": ["js", "mjs"],
  "text/jsx": ["jsx"],
  "text/less": ["less"],
  "text/markdown": ["md", "markdown"],
  "text/mathml": ["mml"],
  "text/mdx": ["mdx"],
  "text/n3": ["n3"],
  "text/plain": ["txt", "text", "conf", "def", "list", "log", "in", "ini"],
  "text/richtext": ["rtx"],
  "text/rtf": ["*rtf"],
  "text/sgml": ["sgml", "sgm"],
  "text/shex": ["shex"],
  "text/slim": ["slim", "slm"],
  "text/spdx": ["spdx"],
  "text/stylus": ["stylus", "styl"],
  "text/tab-separated-values": ["tsv"],
  "text/troff": ["t", "tr", "roff", "man", "me", "ms"],
  "text/turtle": ["ttl"],
  "text/uri-list": ["uri", "uris", "urls"],
  "text/vcard": ["vcard"],
  "text/vtt": ["vtt"],
  "text/wgsl": ["wgsl"],
  "text/xml": ["*xml"],
  "text/yaml": ["yaml", "yml"],
  "video/3gpp": ["3gp", "3gpp"],
  "video/3gpp2": ["3g2"],
  "video/h261": ["h261"],
  "video/h263": ["h263"],
  "video/h264": ["h264"],
  "video/iso.segment": ["m4s"],
  "video/jpeg": ["jpgv"],
  "video/jpm": ["*jpm", "*jpgm"],
  "video/mj2": ["mj2", "mjp2"],
  "video/mp2t": ["ts", "m2t", "m2ts", "mts"],
  "video/mp4": ["mp4", "mp4v", "mpg4"],
  "video/mpeg": ["mpeg", "mpg", "mpe", "m1v", "m2v"],
  "video/ogg": ["ogv"],
  "video/quicktime": ["qt", "mov"],
  "video/webm": ["webm"]
};
Object.freeze(types2);
var standard_default = types2;

// ../../node_modules/.pnpm/mime@4.0.7/node_modules/mime/dist/src/Mime.js
var __classPrivateFieldGet = 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 _Mime_extensionToType;
var _Mime_typeToExtension;
var _Mime_typeToExtensions;
var Mime = class {
  constructor(...args) {
    _Mime_extensionToType.set(this, /* @__PURE__ */ new Map());
    _Mime_typeToExtension.set(this, /* @__PURE__ */ new Map());
    _Mime_typeToExtensions.set(this, /* @__PURE__ */ new Map());
    for (const arg of args) {
      this.define(arg);
    }
  }
  define(typeMap, force = false) {
    for (let [type, extensions] of Object.entries(typeMap)) {
      type = type.toLowerCase();
      extensions = extensions.map((ext) => ext.toLowerCase());
      if (!__classPrivateFieldGet(this, _Mime_typeToExtensions, "f").has(type)) {
        __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").set(type, /* @__PURE__ */ new Set());
      }
      const allExtensions = __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").get(type);
      let first = true;
      for (let extension of extensions) {
        const starred = extension.startsWith("*");
        extension = starred ? extension.slice(1) : extension;
        allExtensions?.add(extension);
        if (first) {
          __classPrivateFieldGet(this, _Mime_typeToExtension, "f").set(type, extension);
        }
        first = false;
        if (starred)
          continue;
        const currentType = __classPrivateFieldGet(this, _Mime_extensionToType, "f").get(extension);
        if (currentType && currentType != type && !force) {
          throw new Error(`"${type} -> ${extension}" conflicts with "${currentType} -> ${extension}". Pass \`force=true\` to override this definition.`);
        }
        __classPrivateFieldGet(this, _Mime_extensionToType, "f").set(extension, type);
      }
    }
    return this;
  }
  getType(path73) {
    if (typeof path73 !== "string")
      return null;
    const last = path73.replace(/^.*[/\\]/s, "").toLowerCase();
    const ext = last.replace(/^.*\./s, "").toLowerCase();
    const hasPath = last.length < path73.length;
    const hasDot = ext.length < last.length - 1;
    if (!hasDot && hasPath)
      return null;
    return __classPrivateFieldGet(this, _Mime_extensionToType, "f").get(ext) ?? null;
  }
  getExtension(type) {
    if (typeof type !== "string")
      return null;
    type = type?.split?.(";")[0];
    return (type && __classPrivateFieldGet(this, _Mime_typeToExtension, "f").get(type.trim().toLowerCase())) ?? null;
  }
  getAllExtensions(type) {
    if (typeof type !== "string")
      return null;
    return __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").get(type.toLowerCase()) ?? null;
  }
  _freeze() {
    this.define = () => {
      throw new Error("define() not allowed for built-in Mime objects. See https://github.com/broofa/mime/blob/main/README.md#custom-mime-instances");
    };
    Object.freeze(this);
    for (const extensions of __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").values()) {
      Object.freeze(extensions);
    }
    return this;
  }
  _getTestState() {
    return {
      types: __classPrivateFieldGet(this, _Mime_extensionToType, "f"),
      extensions: __classPrivateFieldGet(this, _Mime_typeToExtension, "f")
    };
  }
};
_Mime_extensionToType = /* @__PURE__ */ new WeakMap(), _Mime_typeToExtension = /* @__PURE__ */ new WeakMap(), _Mime_typeToExtensions = /* @__PURE__ */ new WeakMap();
var Mime_default = Mime;

// ../../node_modules/.pnpm/mime@4.0.7/node_modules/mime/dist/src/index.js
var src_default = new Mime_default(standard_default, other_default)._freeze();

// ../workers-shared/utils/helpers.ts
var normalizeFilePath = (relativeFilepath) => {
  if ((0, import_node_path11.isAbsolute)(relativeFilepath)) {
    throw new Error(`Expected relative path`);
  }
  return "/" + relativeFilepath.split(import_node_path11.sep).join("/");
};
var getContentType = (absFilePath) => {
  let contentType = src_default.getType(absFilePath);
  if (contentType && contentType.startsWith("text/") && !contentType.includes("charset")) {
    contentType = `${contentType}; charset=utf-8`;
  }
  return contentType;
};
function createPatternMatcher(patterns, exclude) {
  if (patterns.length === 0) {
    return (_filePath) => !exclude;
  } else {
    const ignorer = (0, import_ignore.default)().add(patterns);
    return (filePath) => ignorer.test(filePath).ignored;
  }
}
function thrownIsDoesNotExistError(thrown) {
  return thrown instanceof Error && "code" in thrown && thrown.code === "ENOENT";
}
function maybeGetFile(filePath) {
  try {
    return (0, import_node_fs7.readFileSync)(filePath, "utf8");
  } catch (e) {
    if (!thrownIsDoesNotExistError(e)) {
      throw e;
    }
  }
}
async function createAssetsIgnoreFunction(dir3) {
  const cfAssetIgnorePath = (0, import_node_path11.resolve)(dir3, CF_ASSETS_IGNORE_FILENAME);
  const ignorePatterns = [
    // Ignore the `.assetsignore` file and other metafiles by default.
    // The ignore lib expects unix-style paths for its patterns
    `/${CF_ASSETS_IGNORE_FILENAME}`,
    `/${REDIRECTS_FILENAME}`,
    `/${HEADERS_FILENAME}`
  ];
  let assetsIgnoreFilePresent = false;
  const assetsIgnore = maybeGetFile(cfAssetIgnorePath);
  if (assetsIgnore !== void 0) {
    assetsIgnoreFilePresent = true;
    ignorePatterns.push(...assetsIgnore.split("\n"));
  }
  return {
    assetsIgnoreFunction: createPatternMatcher(ignorePatterns, true),
    assetsIgnoreFilePresent
  };
}

// ../workers-shared/utils/configuration/constants.ts
var REDIRECTS_VERSION = 1;
var HEADERS_VERSION = 2;
var PERMITTED_STATUS_CODES = /* @__PURE__ */ new Set([200, 301, 302, 303, 307, 308]);
var HEADER_SEPARATOR = ":";
var MAX_LINE_LENGTH = 2e3;
var MAX_HEADER_RULES = 100;
var MAX_DYNAMIC_REDIRECT_RULES = 100;
var MAX_STATIC_REDIRECT_RULES = 2e3;
var UNSET_OPERATOR = "! ";
var SPLAT_REGEX = /\*/g;
var PLACEHOLDER_REGEX = /:[A-Za-z]\w*/g;
var MAX_ROUTES_RULES = 100;
var MAX_ROUTES_RULE_LENGTH = 100;

// ../workers-shared/utils/configuration/validateURL.ts
var extractPathname = (path73 = "/", includeSearch, includeHash) => {
  if (!path73.startsWith("/")) {
    path73 = `/${path73}`;
  }
  const url46 = new URL(`//${path73}`, "relative://");
  return `${url46.pathname}${includeSearch ? url46.search : ""}${includeHash ? url46.hash : ""}`;
};
var URL_REGEX = /^https:\/\/+(?<host>[^/]+)\/?(?<path>.*)/;
var HOST_WITH_PORT_REGEX = /.*:\d+$/;
var PATH_REGEX = /^\//;
var validateUrl = (token, onlyRelative = false, disallowPorts = false, includeSearch = false, includeHash = false) => {
  const host = URL_REGEX.exec(token);
  if (host && host.groups && host.groups.host) {
    if (onlyRelative) {
      return [
        void 0,
        `Only relative URLs are allowed. Skipping absolute URL ${token}.`
      ];
    }
    if (disallowPorts && host.groups.host.match(HOST_WITH_PORT_REGEX)) {
      return [
        void 0,
        `Specifying ports is not supported. Skipping absolute URL ${token}.`
      ];
    }
    return [
      `https://${host.groups.host}${extractPathname(
        host.groups.path,
        includeSearch,
        includeHash
      )}`,
      void 0
    ];
  } else {
    if (!token.startsWith("/") && onlyRelative) {
      token = `/${token}`;
    }
    const path73 = PATH_REGEX.exec(token);
    if (path73) {
      try {
        return [extractPathname(token, includeSearch, includeHash), void 0];
      } catch {
        return [void 0, `Error parsing URL segment ${token}. Skipping.`];
      }
    }
  }
  return [
    void 0,
    onlyRelative ? "URLs should begin with a forward-slash." : 'URLs should either be relative (e.g. begin with a forward-slash), or use HTTPS (e.g. begin with "https://").'
  ];
};
function urlHasHost(token) {
  const host = URL_REGEX.exec(token);
  return Boolean(host && host.groups && host.groups.host);
}

// ../workers-shared/utils/configuration/parseHeaders.ts
var LINE_IS_PROBABLY_A_PATH = new RegExp(/^([^\s]+:\/\/|^\/)/);
function parseHeaders(input, {
  maxRules = MAX_HEADER_RULES,
  maxLineLength = MAX_LINE_LENGTH
} = {}) {
  const lines = input.split("\n");
  const rules = [];
  const invalid = [];
  let rule = void 0;
  let skipUntilNextPath = false;
  for (let i = 0; i < lines.length; i++) {
    const line = (lines[i] || "").trim();
    if (line.length === 0 || line.startsWith("#")) {
      continue;
    }
    if (line.length > maxLineLength) {
      invalid.push({
        message: `Ignoring line ${i + 1} as it exceeds the maximum allowed length of ${maxLineLength}.`
      });
      continue;
    }
    if (LINE_IS_PROBABLY_A_PATH.test(line)) {
      skipUntilNextPath = false;
      if (rules.length >= maxRules) {
        invalid.push({
          message: `Maximum number of rules supported is ${maxRules}. Skipping remaining ${lines.length - i} lines of file.`
        });
        break;
      }
      if (rule) {
        if (isValidRule(rule)) {
          rules.push({
            path: rule.path,
            headers: rule.headers,
            unsetHeaders: rule.unsetHeaders
          });
        } else {
          invalid.push({
            line: rule.line,
            lineNumber: i + 1,
            message: "No headers specified"
          });
        }
      }
      const [path73, pathError] = validateUrl(line, false, true);
      if (pathError) {
        invalid.push({
          line,
          lineNumber: i + 1,
          message: pathError
        });
        rule = void 0;
        skipUntilNextPath = true;
        continue;
      }
      const wildcardError = validateNoMultipleWildcards(path73);
      if (wildcardError) {
        invalid.push({
          line,
          lineNumber: i + 1,
          message: wildcardError
        });
        rule = void 0;
        skipUntilNextPath = true;
        continue;
      }
      rule = {
        path: path73,
        line,
        headers: {},
        unsetHeaders: []
      };
      continue;
    }
    if (skipUntilNextPath) {
      continue;
    }
    if (!line.includes(HEADER_SEPARATOR)) {
      if (!rule) {
        invalid.push({
          line,
          lineNumber: i + 1,
          message: "Expected a path beginning with at least one forward-slash"
        });
      } else {
        if (line.trim().startsWith(UNSET_OPERATOR)) {
          rule.unsetHeaders.push(line.trim().replace(UNSET_OPERATOR, ""));
        } else {
          invalid.push({
            line,
            lineNumber: i + 1,
            message: "Expected a colon-separated header pair (e.g. name: value)"
          });
        }
      }
      continue;
    }
    const [rawName, ...rawValue] = line.split(HEADER_SEPARATOR);
    const name = (rawName || "").trim().toLowerCase();
    if (name.includes(" ")) {
      invalid.push({
        line,
        lineNumber: i + 1,
        message: "Header name cannot include spaces"
      });
      continue;
    }
    const value = rawValue.join(HEADER_SEPARATOR).trim();
    if (name === "") {
      invalid.push({
        line,
        lineNumber: i + 1,
        message: "No header name specified"
      });
      continue;
    }
    if (value === "") {
      invalid.push({
        line,
        lineNumber: i + 1,
        message: "No header value specified"
      });
      continue;
    }
    if (!rule) {
      invalid.push({
        line,
        lineNumber: i + 1,
        message: `Path should come before header (${name}: ${value})`
      });
      continue;
    }
    const existingValues = rule.headers[name];
    rule.headers[name] = existingValues ? `${existingValues}, ${value}` : value;
  }
  if (rule) {
    if (isValidRule(rule)) {
      rules.push({
        path: rule.path,
        headers: rule.headers,
        unsetHeaders: rule.unsetHeaders
      });
    } else {
      invalid.push({ line: rule.line, message: "No headers specified" });
    }
  }
  return {
    rules,
    invalid
  };
}
function isValidRule(rule) {
  return Object.keys(rule.headers).length > 0 || rule.unsetHeaders.length > 0;
}
function validateNoMultipleWildcards(path73) {
  const wildcardCount = (path73.match(SPLAT_REGEX) ?? []).length;
  const hasSplatPlaceholder = /:splat(?!\w)/.test(path73);
  if (wildcardCount > 1) {
    return `Only one wildcard is allowed per rule. Use a named placeholder (e.g. :project) instead. Skipping ${path73}.`;
  }
  if (wildcardCount > 0 && hasSplatPlaceholder) {
    return `Cannot combine a wildcard * with a :splat placeholder because wildcards are converted to :splat at runtime. Skipping ${path73}.`;
  }
  return void 0;
}

// ../workers-shared/utils/configuration/parseRedirects.ts
function parseRedirects(input, {
  htmlHandling = void 0,
  maxStaticRules = MAX_STATIC_REDIRECT_RULES,
  maxDynamicRules = MAX_DYNAMIC_REDIRECT_RULES,
  maxLineLength = MAX_LINE_LENGTH
} = {}) {
  const lines = input.split("\n");
  const rules = [];
  const seen_paths = /* @__PURE__ */ new Set();
  const invalid = [];
  let staticRules = 0;
  let dynamicRules = 0;
  let canCreateStaticRule = true;
  for (let i = 0; i < lines.length; i++) {
    const line = (lines[i] || "").trim();
    if (line.length === 0 || line.startsWith("#")) {
      continue;
    }
    if (line.length > maxLineLength) {
      invalid.push({
        message: `Ignoring line ${i + 1} as it exceeds the maximum allowed length of ${maxLineLength}.`
      });
      continue;
    }
    const tokens = line.replace(/\s+#.*$/, "").split(/\s+/);
    if (tokens.length < 2 || tokens.length > 3) {
      invalid.push({
        line,
        lineNumber: i + 1,
        message: `Expected exactly 2 or 3 whitespace-separated tokens. Got ${tokens.length}.`
      });
      continue;
    }
    const [str_from, str_to, str_status = "302"] = tokens;
    const fromResult = validateUrl(str_from, true, true, false, false);
    if (fromResult[0] === void 0) {
      invalid.push({
        line,
        lineNumber: i + 1,
        message: fromResult[1]
      });
      continue;
    }
    const from = fromResult[0];
    if (canCreateStaticRule && !from.match(SPLAT_REGEX) && !from.match(PLACEHOLDER_REGEX)) {
      staticRules += 1;
      if (staticRules > maxStaticRules) {
        invalid.push({
          message: `Maximum number of static rules supported is ${maxStaticRules}. Skipping line.`
        });
        continue;
      }
    } else {
      dynamicRules += 1;
      canCreateStaticRule = false;
      if (dynamicRules > maxDynamicRules) {
        invalid.push({
          message: `Maximum number of dynamic rules supported is ${maxDynamicRules}. Skipping remaining ${lines.length - i} lines of file.`
        });
        break;
      }
    }
    const toResult = validateUrl(str_to, false, false, true, true);
    if (toResult[0] === void 0) {
      invalid.push({
        line,
        lineNumber: i + 1,
        message: toResult[1]
      });
      continue;
    }
    const to = toResult[0];
    const status2 = Number(str_status);
    if (isNaN(status2) || !PERMITTED_STATUS_CODES.has(status2)) {
      invalid.push({
        line,
        lineNumber: i + 1,
        message: `Valid status codes are 200, 301, 302 (default), 303, 307, or 308. Got ${str_status}.`
      });
      continue;
    }
    const hasRelativePath = !urlHasHost(to);
    const hasWildcardToIndex = from.endsWith("/*") && /\/index(.html)?$/.test(to);
    const hasRootToIndex = from.endsWith("/") && /\/index(.html)?$/.test(to);
    const hasHTMLHandling = htmlHandling !== "none";
    if (hasRelativePath && (hasWildcardToIndex || hasRootToIndex && hasHTMLHandling)) {
      invalid.push({
        line,
        lineNumber: i + 1,
        message: "Infinite loop detected in this rule and has been ignored. This will cause a redirect to strip `.html` or `/index` and end up triggering this rule again. Please fix or remove this rule to silence this warning."
      });
      continue;
    }
    if (seen_paths.has(from)) {
      invalid.push({
        line,
        lineNumber: i + 1,
        message: `Ignoring duplicate rule for path ${from}.`
      });
      continue;
    }
    seen_paths.add(from);
    if (status2 === 200) {
      if (urlHasHost(to)) {
        invalid.push({
          line,
          lineNumber: i + 1,
          message: `Proxy (200) redirects can only point to relative paths. Got ${to}`
        });
        continue;
      }
    }
    rules.push({ from, to, status: status2, lineNumber: i + 1 });
  }
  return {
    rules,
    invalid
  };
}

// ../workers-shared/utils/configuration/constructConfiguration.ts
var import_node_path12 = require("node:path");
function constructRedirects({
  redirects,
  redirectsFile,
  logger
}) {
  if (!redirects) {
    return {};
  }
  const num_valid = redirects.rules.length;
  const num_invalid = redirects.invalid.length;
  const redirectsRelativePath = redirectsFile ? (0, import_node_path12.relative)(process.cwd(), redirectsFile) : "";
  logger.log(
    `\u2728 Parsed ${num_valid} valid redirect rule${num_valid === 1 ? "" : "s"}.`
  );
  if (num_invalid > 0) {
    let invalidRedirectRulesList = ``;
    for (const { line, lineNumber, message } of redirects.invalid) {
      invalidRedirectRulesList += `\u25B6\uFE0E ${message}
`;
      if (line) {
        invalidRedirectRulesList += `    at ${redirectsRelativePath}${lineNumber ? `:${lineNumber}` : ""} | ${line}

`;
      }
    }
    logger.warn(
      `Found ${num_invalid} invalid redirect rule${num_invalid === 1 ? "" : "s"}:
${invalidRedirectRulesList}`
    );
  }
  if (num_valid === 0) {
    return {};
  }
  const staticRedirects = {};
  const dynamicRedirects = {};
  let canCreateStaticRule = true;
  for (const rule of redirects.rules) {
    if (!rule.from.match(SPLAT_REGEX) && !rule.from.match(PLACEHOLDER_REGEX)) {
      if (canCreateStaticRule) {
        staticRedirects[rule.from] = {
          status: rule.status,
          to: rule.to,
          lineNumber: rule.lineNumber
        };
        continue;
      } else {
        logger.info(
          `The redirect rule ${rule.from} \u2192 ${rule.status} ${rule.to} could be made more performant by bringing it above any lines with splats or placeholders.`
        );
      }
    }
    dynamicRedirects[rule.from] = { status: rule.status, to: rule.to };
    canCreateStaticRule = false;
  }
  return {
    redirects: {
      version: REDIRECTS_VERSION,
      staticRules: staticRedirects,
      rules: dynamicRedirects
    }
  };
}
function constructHeaders({
  headers,
  headersFile,
  logger
}) {
  if (!headers) {
    return {};
  }
  const num_valid = headers.rules.length;
  const num_invalid = headers.invalid.length;
  const headersRelativePath = headersFile ? (0, import_node_path12.relative)(process.cwd(), headersFile) : "";
  logger.log(
    `\u2728 Parsed ${num_valid} valid header rule${num_valid === 1 ? "" : "s"}.`
  );
  if (num_invalid > 0) {
    let invalidHeaderRulesList = ``;
    for (const { line, lineNumber, message } of headers.invalid) {
      invalidHeaderRulesList += `\u25B6\uFE0E ${message}
`;
      if (line) {
        invalidHeaderRulesList += `    at ${headersRelativePath}${lineNumber ? `:${lineNumber}` : ""} | ${line}

`;
      }
    }
    logger.warn(
      `Found ${num_invalid} invalid header rule${num_invalid === 1 ? "" : "s"}:
${invalidHeaderRulesList}`
    );
  }
  if (num_valid === 0) {
    return {};
  }
  const rules = {};
  for (const rule of headers.rules) {
    const configuredRule = {};
    if (Object.keys(rule.headers).length) {
      configuredRule.set = rule.headers;
    }
    if (rule.unsetHeaders.length) {
      configuredRule.unset = rule.unsetHeaders;
    }
    rules[rule.path] = configuredRule;
  }
  return {
    headers: {
      version: HEADERS_VERSION,
      rules
    }
  };
}

// ../workers-shared/utils/configuration/parseStaticRouting.ts
function parseStaticRouting(input) {
  if (input.length === 0) {
    throw new Error(
      "No `run_worker_first` rules were provided; must provide at least 1 rule."
    );
  }
  if (input.length > MAX_ROUTES_RULES) {
    throw new Error(
      `Too many \`run_worker_first\` rules were provided; ${input.length} rules provided exceeds max of ${MAX_ROUTES_RULES}.`
    );
  }
  const rawAssetWorkerRules = [];
  const assetWorkerRules = [];
  const userWorkerRules = [];
  const invalidRules = [];
  for (const rule of input) {
    if (rule.startsWith("!/")) {
      assetWorkerRules.push(rule.slice(1));
      rawAssetWorkerRules.push(rule);
    } else if (rule.startsWith("/")) {
      userWorkerRules.push(rule);
    } else if (rule.startsWith("!")) {
      invalidRules.push(`'${rule}': negative rules must start with '!/'`);
    } else {
      invalidRules.push(`'${rule}': rules must start with '/' or '!/'`);
    }
  }
  if (assetWorkerRules.length > 0 && userWorkerRules.length === 0) {
    throw new Error(
      "Only negative `run_worker_first` rules were provided; must provide at least 1 non-negative rule"
    );
  }
  const invalidAssetWorkerRules = validateStaticRoutingRules(rawAssetWorkerRules);
  const invalidUserWorkerRules = validateStaticRoutingRules(userWorkerRules);
  const errorMessage = formatInvalidRoutes([
    ...invalidRules,
    ...invalidUserWorkerRules,
    ...invalidAssetWorkerRules
  ]);
  if (errorMessage) {
    throw new Error(errorMessage);
  }
  return { asset_worker: assetWorkerRules, user_worker: userWorkerRules };
}
function validateStaticRoutingRules(rules) {
  const invalid = [];
  const seen = /* @__PURE__ */ new Set();
  for (const rule of rules) {
    if (rule.length > MAX_ROUTES_RULE_LENGTH) {
      invalid.push(
        `'${rule}': all rules must be less than ${MAX_ROUTES_RULE_LENGTH} characters in length`
      );
    }
    if (seen.has(rule)) {
      invalid.push(`'${rule}': rule is a duplicate; rules must be unique`);
    }
    if (rule.endsWith("*")) {
      for (const otherRule of rules) {
        if (otherRule !== rule && otherRule.startsWith(rule.slice(0, -1))) {
          invalid.push(`'${otherRule}': rule '${rule}' makes it redundant`);
        }
      }
    }
    seen.add(rule);
  }
  return invalid;
}
var formatInvalidRoutes = (invalidRules) => {
  if (invalidRules.length === 0) {
    return void 0;
  }
  return `Invalid routes in \`run_worker_first\`:
` + invalidRules.join("\n");
};

// ../../node_modules/.pnpm/pretty-bytes@6.1.1/node_modules/pretty-bytes/index.js
var BYTE_UNITS = [
  "B",
  "kB",
  "MB",
  "GB",
  "TB",
  "PB",
  "EB",
  "ZB",
  "YB"
];
var BIBYTE_UNITS = [
  "B",
  "KiB",
  "MiB",
  "GiB",
  "TiB",
  "PiB",
  "EiB",
  "ZiB",
  "YiB"
];
var BIT_UNITS = [
  "b",
  "kbit",
  "Mbit",
  "Gbit",
  "Tbit",
  "Pbit",
  "Ebit",
  "Zbit",
  "Ybit"
];
var BIBIT_UNITS = [
  "b",
  "kibit",
  "Mibit",
  "Gibit",
  "Tibit",
  "Pibit",
  "Eibit",
  "Zibit",
  "Yibit"
];
var toLocaleString = (number7, locale, options) => {
  let result = number7;
  if (typeof locale === "string" || Array.isArray(locale)) {
    result = number7.toLocaleString(locale, options);
  } else if (locale === true || options !== void 0) {
    result = number7.toLocaleString(void 0, options);
  }
  return result;
};
function prettyBytes(number7, options) {
  if (!Number.isFinite(number7)) {
    throw new TypeError(`Expected a finite number, got ${typeof number7}: ${number7}`);
  }
  options = {
    bits: false,
    binary: false,
    space: true,
    ...options
  };
  const UNITS = options.bits ? options.binary ? BIBIT_UNITS : BIT_UNITS : options.binary ? BIBYTE_UNITS : BYTE_UNITS;
  const separator = options.space ? " " : "";
  if (options.signed && number7 === 0) {
    return ` 0${separator}${UNITS[0]}`;
  }
  const isNegative = number7 < 0;
  const prefix = isNegative ? "-" : options.signed ? "+" : "";
  if (isNegative) {
    number7 = -number7;
  }
  let localeOptions;
  if (options.minimumFractionDigits !== void 0) {
    localeOptions = { minimumFractionDigits: options.minimumFractionDigits };
  }
  if (options.maximumFractionDigits !== void 0) {
    localeOptions = { maximumFractionDigits: options.maximumFractionDigits, ...localeOptions };
  }
  if (number7 < 1) {
    const numberString2 = toLocaleString(number7, options.locale, localeOptions);
    return prefix + numberString2 + separator + UNITS[0];
  }
  const exponent = Math.min(Math.floor(options.binary ? Math.log(number7) / Math.log(1024) : Math.log10(number7) / 3), UNITS.length - 1);
  number7 /= (options.binary ? 1024 : 1e3) ** exponent;
  if (!localeOptions) {
    number7 = number7.toPrecision(3);
  }
  const numberString = toLocaleString(Number(number7), options.locale, localeOptions);
  const unit = UNITS[exponent];
  return prefix + numberString + separator + unit;
}

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/assets/assets.worker.ts
var import_fs7 = __toESM(require("fs"));
var import_path7 = __toESM(require("path"));
var import_url7 = __toESM(require("url"));
var contents7;
function assets_worker_default() {
  if (contents7 !== void 0) return contents7;
  const filePath = import_path7.default.join(__dirname, "workers", "assets/assets.worker.js");
  contents7 = import_fs7.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url7.default.pathToFileURL(filePath);
  return contents7;
}

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/assets/assets-kv.worker.ts
var import_fs8 = __toESM(require("fs"));
var import_path8 = __toESM(require("path"));
var import_url8 = __toESM(require("url"));
var contents8;
function assets_kv_worker_default() {
  if (contents8 !== void 0) return contents8;
  const filePath = import_path8.default.join(__dirname, "workers", "assets/assets-kv.worker.js");
  contents8 = import_fs8.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url8.default.pathToFileURL(filePath);
  return contents8;
}

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/assets/router.worker.ts
var import_fs9 = __toESM(require("fs"));
var import_path9 = __toESM(require("path"));
var import_url9 = __toESM(require("url"));
var contents9;
function router_worker_default() {
  if (contents9 !== void 0) return contents9;
  const filePath = import_path9.default.join(__dirname, "workers", "assets/router.worker.js");
  contents9 = import_fs9.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url9.default.pathToFileURL(filePath);
  return contents9;
}

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/assets/rpc-proxy.worker.ts
var import_fs10 = __toESM(require("fs"));
var import_path10 = __toESM(require("path"));
var import_url10 = __toESM(require("url"));
var contents10;
function rpc_proxy_worker_default() {
  if (contents10 !== void 0) return contents10;
  const filePath = import_path10.default.join(__dirname, "workers", "assets/rpc-proxy.worker.js");
  contents10 = import_fs10.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url10.default.pathToFileURL(filePath);
  return contents10;
}

// src/plugins/core/index.ts
var import_node_assert15 = __toESM(require("node:assert"));
var import_node_fs11 = require("node:fs");
var import_promises11 = __toESM(require("node:fs/promises"));
var import_node_path17 = __toESM(require("node:path"));
var import_node_tls = __toESM(require("node:tls"));
var import_node_util6 = require("node:util");

// ../containers-shared/src/client/models/ApplicationRollout.ts
var ApplicationRollout;
((ApplicationRollout2) => {
  let kind;
  ((kind2) => {
    kind2["FULL_AUTO"] = "full_auto";
    kind2["FULL_MANUAL"] = "full_manual";
    kind2["DURABLE_OBJECTS_AUTO"] = "durable_objects_auto";
  })(kind = ApplicationRollout2.kind || (ApplicationRollout2.kind = {}));
  let strategy;
  ((strategy2) => {
    strategy2["ROLLING"] = "rolling";
  })(strategy = ApplicationRollout2.strategy || (ApplicationRollout2.strategy = {}));
  let status2;
  ((status3) => {
    status3["PENDING"] = "pending";
    status3["PROGRESSING"] = "progressing";
    status3["COMPLETED"] = "completed";
    status3["REVERTED"] = "reverted";
    status3["REPLACED"] = "replaced";
  })(status2 = ApplicationRollout2.status || (ApplicationRollout2.status = {}));
})(ApplicationRollout || (ApplicationRollout = {}));

// ../containers-shared/src/client/models/BadRequestWithCodeError.ts
var BadRequestWithCodeError;
((BadRequestWithCodeError2) => {
  let error101;
  ((error102) => {
    error102["VALIDATE_INPUT"] = "VALIDATE_INPUT";
  })(error101 = BadRequestWithCodeError2.error || (BadRequestWithCodeError2.error = {}));
})(BadRequestWithCodeError || (BadRequestWithCodeError = {}));

// ../containers-shared/src/client/models/CreateApplicationRolloutRequest.ts
var CreateApplicationRolloutRequest;
((CreateApplicationRolloutRequest2) => {
  let strategy;
  ((strategy2) => {
    strategy2["ROLLING"] = "rolling";
  })(strategy = CreateApplicationRolloutRequest2.strategy || (CreateApplicationRolloutRequest2.strategy = {}));
  let step_percentage;
  ((step_percentage2) => {
    step_percentage2[step_percentage2["_5"] = 5] = "_5";
    step_percentage2[step_percentage2["_10"] = 10] = "_10";
    step_percentage2[step_percentage2["_20"] = 20] = "_20";
    step_percentage2[step_percentage2["_25"] = 25] = "_25";
    step_percentage2[step_percentage2["_50"] = 50] = "_50";
    step_percentage2[step_percentage2["_100"] = 100] = "_100";
  })(step_percentage = CreateApplicationRolloutRequest2.step_percentage || (CreateApplicationRolloutRequest2.step_percentage = {}));
  let kind;
  ((kind2) => {
    kind2["FULL_AUTO"] = "full_auto";
    kind2["FULL_MANUAL"] = "full_manual";
  })(kind = CreateApplicationRolloutRequest2.kind || (CreateApplicationRolloutRequest2.kind = {}));
})(CreateApplicationRolloutRequest || (CreateApplicationRolloutRequest = {}));

// ../containers-shared/src/client/models/DeploymentNotFoundError.ts
var DeploymentNotFoundError;
((DeploymentNotFoundError2) => {
  let error101;
  ((error102) => {
    error102["DEPLOYMENT_NOT_FOUND"] = "DEPLOYMENT_NOT_FOUND";
  })(error101 = DeploymentNotFoundError2.error || (DeploymentNotFoundError2.error = {}));
})(DeploymentNotFoundError || (DeploymentNotFoundError = {}));

// ../containers-shared/src/client/models/ImageRegistryAlreadyExistsError.ts
var ImageRegistryAlreadyExistsError;
((ImageRegistryAlreadyExistsError2) => {
  let error101;
  ((error102) => {
    error102["IMAGE_REGISTRY_ALREADY_EXISTS"] = "IMAGE_REGISTRY_ALREADY_EXISTS";
  })(error101 = ImageRegistryAlreadyExistsError2.error || (ImageRegistryAlreadyExistsError2.error = {}));
})(ImageRegistryAlreadyExistsError || (ImageRegistryAlreadyExistsError = {}));

// ../containers-shared/src/client/models/ImageRegistryIsPublic.ts
var ImageRegistryIsPublic;
((ImageRegistryIsPublic2) => {
  let error101;
  ((error102) => {
    error102["IMAGE_REGISTRY_IS_PUBLIC"] = "IMAGE_REGISTRY_IS_PUBLIC";
  })(error101 = ImageRegistryIsPublic2.error || (ImageRegistryIsPublic2.error = {}));
})(ImageRegistryIsPublic || (ImageRegistryIsPublic = {}));

// ../containers-shared/src/client/models/ImageRegistryNotAllowedError.ts
var ImageRegistryNotAllowedError;
((ImageRegistryNotAllowedError2) => {
  let error101;
  ((error102) => {
    error102["IMAGE_REGISTRY_NOT_ALLOWED"] = "IMAGE_REGISTRY_NOT_ALLOWED";
  })(error101 = ImageRegistryNotAllowedError2.error || (ImageRegistryNotAllowedError2.error = {}));
})(ImageRegistryNotAllowedError || (ImageRegistryNotAllowedError = {}));

// ../containers-shared/src/client/models/ImageRegistryNotFoundError.ts
var ImageRegistryNotFoundError;
((ImageRegistryNotFoundError2) => {
  let error101;
  ((error102) => {
    error102["IMAGE_REGISTRY_NOT_FOUND"] = "IMAGE_REGISTRY_NOT_FOUND";
  })(error101 = ImageRegistryNotFoundError2.error || (ImageRegistryNotFoundError2.error = {}));
})(ImageRegistryNotFoundError || (ImageRegistryNotFoundError = {}));

// ../containers-shared/src/client/models/ImageRegistryProtocolAlreadyExists.ts
var ImageRegistryProtocolAlreadyExists;
((ImageRegistryProtocolAlreadyExists2) => {
  let error101;
  ((error102) => {
    error102["IMAGE_REGISTRY_PROTOCOL_ALREADY_EXISTS"] = "IMAGE_REGISTRY_PROTOCOL_ALREADY_EXISTS";
  })(error101 = ImageRegistryProtocolAlreadyExists2.error || (ImageRegistryProtocolAlreadyExists2.error = {}));
})(ImageRegistryProtocolAlreadyExists || (ImageRegistryProtocolAlreadyExists = {}));

// ../containers-shared/src/client/models/ImageRegistryProtocolIsReferencedError.ts
var ImageRegistryProtocolIsReferencedError;
((ImageRegistryProtocolIsReferencedError2) => {
  let error101;
  ((error102) => {
    error102["IMAGE_REGISTRY_PROTO_IS_REFERENCED"] = "IMAGE_REGISTRY_PROTO_IS_REFERENCED";
  })(error101 = ImageRegistryProtocolIsReferencedError2.error || (ImageRegistryProtocolIsReferencedError2.error = {}));
})(ImageRegistryProtocolIsReferencedError || (ImageRegistryProtocolIsReferencedError = {}));

// ../containers-shared/src/client/models/ImageRegistryProtocolNotFound.ts
var ImageRegistryProtocolNotFound;
((ImageRegistryProtocolNotFound2) => {
  let error101;
  ((error102) => {
    error102["IMAGE_REGISTRY_PROTOCOL_NOT_FOUND"] = "IMAGE_REGISTRY_PROTOCOL_NOT_FOUND";
  })(error101 = ImageRegistryProtocolNotFound2.error || (ImageRegistryProtocolNotFound2.error = {}));
})(ImageRegistryProtocolNotFound || (ImageRegistryProtocolNotFound = {}));

// ../containers-shared/src/client/models/ProvisionerConfiguration.ts
var ProvisionerConfiguration;
((ProvisionerConfiguration2) => {
  let type;
  ((type2) => {
    type2["NONE"] = "none";
    type2["CLOUDINIT"] = "cloudinit";
  })(type = ProvisionerConfiguration2.type || (ProvisionerConfiguration2.type = {}));
})(ProvisionerConfiguration || (ProvisionerConfiguration = {}));

// ../containers-shared/src/client/models/RolloutStep.ts
var RolloutStep;
((RolloutStep2) => {
  let status2;
  ((status3) => {
    status3["PENDING"] = "pending";
    status3["PROGRESSING"] = "progressing";
    status3["REVERTING"] = "reverting";
    status3["COMPLETED"] = "completed";
    status3["REVERTED"] = "reverted";
  })(status2 = RolloutStep2.status || (RolloutStep2.status = {}));
})(RolloutStep || (RolloutStep = {}));

// ../containers-shared/src/client/models/SecretNameAlreadyExists.ts
var SecretNameAlreadyExists;
((SecretNameAlreadyExists2) => {
  let error101;
  ((error102) => {
    error102["SECRET_NAME_ALREADY_EXISTS"] = "SECRET_NAME_ALREADY_EXISTS";
  })(error101 = SecretNameAlreadyExists2.error || (SecretNameAlreadyExists2.error = {}));
})(SecretNameAlreadyExists || (SecretNameAlreadyExists = {}));

// ../containers-shared/src/client/models/SecretNotFound.ts
var SecretNotFound;
((SecretNotFound2) => {
  let error101;
  ((error102) => {
    error102["SECRET_NAME_NOT_FOUND"] = "SECRET_NAME_NOT_FOUND";
  })(error101 = SecretNotFound2.error || (SecretNotFound2.error = {}));
})(SecretNotFound || (SecretNotFound = {}));

// ../containers-shared/src/client/models/SSHPublicKeyNotFoundError.ts
var SSHPublicKeyNotFoundError;
((SSHPublicKeyNotFoundError2) => {
  let error101;
  ((error102) => {
    error102["SSH_PUBLIC_KEY_NOT_FOUND"] = "SSH_PUBLIC_KEY_NOT_FOUND";
  })(error101 = SSHPublicKeyNotFoundError2.error || (SSHPublicKeyNotFoundError2.error = {}));
})(SSHPublicKeyNotFoundError || (SSHPublicKeyNotFoundError = {}));

// ../containers-shared/src/client/models/UpdateApplicationRolloutRequest.ts
var UpdateApplicationRolloutRequest;
((UpdateApplicationRolloutRequest2) => {
  let action;
  ((action2) => {
    action2["NEXT"] = "next";
    action2["PREVIOUS"] = "previous";
    action2["REVERT"] = "revert";
  })(action = UpdateApplicationRolloutRequest2.action || (UpdateApplicationRolloutRequest2.action = {}));
})(UpdateApplicationRolloutRequest || (UpdateApplicationRolloutRequest = {}));

// ../containers-shared/src/images.ts
var DEFAULT_CONTAINER_EGRESS_INTERCEPTOR_IMAGE = "cloudflare/proxy-everything:3cb1195@sha256:0ef6716c52430096900b150d84a3302057d6cd2319dae7987128c85d0733e3c8";

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/access/access-identity.worker.ts
var import_fs11 = __toESM(require("fs"));
var import_path11 = __toESM(require("path"));
var import_url11 = __toESM(require("url"));
var contents11;
function access_identity_worker_default() {
  if (contents11 !== void 0) return contents11;
  const filePath = import_path11.default.join(__dirname, "workers", "access/access-identity.worker.js");
  contents11 = import_fs11.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url11.default.pathToFileURL(filePath);
  return contents11;
}

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/core/dev-control.worker.ts
var import_fs12 = __toESM(require("fs"));
var import_path12 = __toESM(require("path"));
var import_url12 = __toESM(require("url"));
var contents12;
function dev_control_worker_default() {
  if (contents12 !== void 0) return contents12;
  const filePath = import_path12.default.join(__dirname, "workers", "core/dev-control.worker.js");
  contents12 = import_fs12.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url12.default.pathToFileURL(filePath);
  return contents12;
}

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/core/entry.worker.ts
var import_fs13 = __toESM(require("fs"));
var import_path13 = __toESM(require("path"));
var import_url13 = __toESM(require("url"));
var contents13;
function entry_worker_default() {
  if (contents13 !== void 0) return contents13;
  const filePath = import_path13.default.join(__dirname, "workers", "core/entry.worker.js");
  contents13 = import_fs13.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url13.default.pathToFileURL(filePath);
  return contents13;
}

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/core/outbound.worker.ts
var import_fs14 = __toESM(require("fs"));
var import_path14 = __toESM(require("path"));
var import_url14 = __toESM(require("url"));
var contents14;
function outbound_worker_default() {
  if (contents14 !== void 0) return contents14;
  const filePath = import_path14.default.join(__dirname, "workers", "core/outbound.worker.js");
  contents14 = import_fs14.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url14.default.pathToFileURL(filePath);
  return contents14;
}

// src/runtime/index.ts
var import_node_assert8 = __toESM(require("node:assert"));
var import_node_child_process3 = __toESM(require("node:child_process"));
var import_node_crypto3 = require("node:crypto");
var import_node_events2 = require("node:events");
var import_node_path13 = __toESM(require("node:path"));
var import_node_readline = __toESM(require("node:readline"));
var import_node_stream = require("node:stream");
var import_workerd5 = __toESM(require("workerd"));

// src/runtime/structured-logs.ts
function handleStructuredLogsFromStream(stream, structuredLogsHandler) {
  let streamAccumulator = "";
  const adjustedStructuredLogsHandler = wrapStructuredLogsHandler(
    structuredLogsHandler
  );
  stream.on("data", (chunk) => {
    const fullStreamOutput = `${streamAccumulator}${chunk}`;
    let currentLogsStr = "";
    const lastNewlineIdx = fullStreamOutput.lastIndexOf("\n");
    if (lastNewlineIdx > 0) {
      currentLogsStr = fullStreamOutput.slice(0, lastNewlineIdx);
      streamAccumulator = fullStreamOutput.slice(lastNewlineIdx + 1);
    } else {
      streamAccumulator = fullStreamOutput;
    }
    const lines = currentLogsStr.split("\n");
    for (const line of lines) {
      if (!line) {
        continue;
      }
      const structuredLog = parseStructuredLog(line);
      if (structuredLog) {
        adjustedStructuredLogsHandler(structuredLog);
      }
    }
  });
}
var messageClassifiers = {
  // Is this chunk an internal message from workerd that we want to hijack to cleanup/ignore?
  isInternal(chunk) {
    const containsLlvmSymbolizerWarning = chunk.includes(
      "Not symbolizing stack traces because $LLVM_SYMBOLIZER is not set"
    );
    const containsRecursiveIsolateLockWarning = chunk.includes(
      "took recursive isolate lock"
    );
    const containsHexStack = /stack:( (0|[a-f\d]{4,})){3,}/.test(chunk);
    return containsLlvmSymbolizerWarning || containsRecursiveIsolateLockWarning || containsHexStack;
  },
  // Is this chunk workerd announcing a fatal, process-ending crash?
  //
  // These banners come from kj's crash handlers, which write straight to
  // stderr and so bypass structured logging entirely. Each one is followed by
  // a `stack:` line that `isInternal` would otherwise discard, leaving users
  // (and CI logs) with an abort message carrying no context at all.
  // workerd references:
  //  - https://github.com/cloudflare/workerd/blob/main/deps/kj/kj/exception.c%2B%2B
  isFatalCrash(chunk) {
    return /^\*\*\* (?:std::terminate\(\)|Fatal uncaught|Received signal|Uncaught exception)/.test(
      chunk
    );
  },
  // Is this chunk an Address In Use error?
  isAddressInUse(chunk) {
    return chunk.includes("Address already in use; toString() = ");
  },
  isCodeMovedWarning(chunk) {
    return /CODE_MOVED for unknown code block/.test(chunk);
  },
  isAccessViolation(chunk) {
    return chunk.includes("access violation;");
  }
};
function wrapStructuredLogsHandler(structuredLogsHandler) {
  let reportingFatalCrash = false;
  return (structuredLog) => {
    if (messageClassifiers.isFatalCrash(structuredLog.message)) {
      reportingFatalCrash = true;
      return structuredLogsHandler({
        timestamp: structuredLog.timestamp,
        level: "error",
        message: structuredLog.message
      });
    }
    if (messageClassifiers.isInternal(structuredLog.message)) {
      if (messageClassifiers.isAddressInUse(structuredLog.message)) {
        return;
      }
      if (messageClassifiers.isAccessViolation(structuredLog.message)) {
        let error101 = "There was an access violation in the runtime.";
        if (process.platform === "win32") {
          error101 += "\nOn Windows, this may be caused by an outdated Microsoft Visual C++ Redistributable library.\nCheck that you have the latest version installed.\nSee https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist";
        }
        return structuredLogsHandler({
          timestamp: structuredLog.timestamp,
          level: "error",
          message: error101
        });
      }
      if (reportingFatalCrash) {
        return structuredLogsHandler({
          timestamp: structuredLog.timestamp,
          level: "error",
          message: structuredLog.message
        });
      }
      return;
    }
    reportingFatalCrash = false;
    if ((structuredLog.level === "info" || structuredLog.level === "error") && messageClassifiers.isCodeMovedWarning(structuredLog.message)) {
      return;
    }
    return structuredLogsHandler(structuredLog);
  };
}
function parseStructuredLog(str) {
  try {
    const maybeStructuredLog = JSON.parse(str);
    if (typeof maybeStructuredLog !== "object" || maybeStructuredLog === null) {
      return null;
    }
    const timestamp = parseInt(maybeStructuredLog.timestamp);
    if (isNaN(timestamp) || typeof maybeStructuredLog.level !== "string" || typeof maybeStructuredLog.message !== "string") {
      return null;
    }
    return {
      timestamp,
      level: maybeStructuredLog.level,
      message: maybeStructuredLog.message
    };
  } catch {
    return {
      timestamp: Date.now(),
      level: "log",
      message: str
    };
  }
}

// src/runtime/config/index.ts
var import_node_fs8 = require("node:fs");
function capitalize(str) {
  return str.length > 0 ? str[0].toUpperCase() + str.substring(1) : str;
}
function encodeCapnpStruct(obj, struct) {
  const anyStruct = struct;
  for (const [key, value] of Object.entries(obj)) {
    const capitalized = capitalize(key);
    const safeKey = key === "constructor" ? `$${key}` : key;
    if (value instanceof Uint8Array) {
      const newData = anyStruct[`_init${capitalized}`](value.byteLength);
      newData.copyBuffer(value);
    } else if (Array.isArray(value)) {
      const newList = anyStruct[`_init${capitalized}`](value.length);
      for (let i = 0; i < value.length; i++) {
        if (typeof value[i] === "object") {
          encodeCapnpStruct(value[i], newList.get(i));
        } else {
          newList.set(i, value[i]);
        }
      }
    } else if (typeof value === "object") {
      const newStruct = anyStruct[`_init${capitalized}`]();
      encodeCapnpStruct(value, newStruct);
    } else if (value === kVoid) {
      anyStruct[safeKey] = void 0;
    } else if (value !== void 0) {
      anyStruct[safeKey] = value;
    }
  }
}
function serializeConfig(config3) {
  const debugPath = process.env.MINIFLARE_WORKERD_CONFIG_DEBUG;
  if (debugPath) {
    (0, import_node_fs8.writeFileSync)(debugPath, JSON.stringify(config3, null, 2));
  }
  const message = new Message();
  const struct = message.initRoot(Config);
  encodeCapnpStruct(config3, struct);
  return Buffer.from(message.toArrayBuffer());
}

// src/runtime/index.ts
var ControlMessageSchema = external_exports2.discriminatedUnion("event", [
  external_exports2.object({
    event: external_exports2.literal("listen"),
    socket: external_exports2.string(),
    port: external_exports2.number()
  }),
  external_exports2.object({
    event: external_exports2.literal("listen-inspector"),
    port: external_exports2.number()
  })
]);
var kInspectorSocket = /* @__PURE__ */ Symbol("kInspectorSocket");
async function waitForPorts(stream, options) {
  if (options?.signal?.aborted) return;
  const lines = import_node_readline.default.createInterface(stream);
  const abortListener = () => lines.close();
  options?.signal?.addEventListener("abort", abortListener, { once: true });
  const requiredSockets = Array.from(options.requiredSockets);
  const socketPorts = /* @__PURE__ */ new Map();
  try {
    for await (const line of lines) {
      const message = ControlMessageSchema.safeParse(JSON.parse(line));
      if (!message.success) continue;
      const data = message.data;
      const socket = data.event === "listen-inspector" ? kInspectorSocket : data.socket;
      const index = requiredSockets.indexOf(socket);
      if (index === -1) continue;
      socketPorts.set(socket, data.port);
      requiredSockets.splice(index, 1);
      if (requiredSockets.length === 0) return socketPorts;
    }
  } finally {
    options?.signal?.removeEventListener("abort", abortListener);
  }
}
function waitForExit(process10) {
  return new Promise((resolve8) => {
    process10.once("exit", () => resolve8());
  });
}
var defaultStructuredLogsHandler = ({
  level,
  message
}) => {
  if (level === "error" || level === "warn") {
    console.error(red3(message));
  } else {
    console.log(message);
  }
};
function getRuntimeCommand() {
  return process.env.MINIFLARE_WORKERD_PATH ?? import_workerd5.default;
}
function getRuntimeArgs(options) {
  const args = [
    "serve",
    // Required to use binary capnp config
    "--binary",
    // Required to use compatibility flags without a default-on date,
    // (e.g. "streams_enable_constructors"), see https://github.com/cloudflare/workerd/pull/21
    "--experimental",
    `--socket-addr=${SOCKET_ENTRY}=${options.entryAddress}`,
    `--external-addr=${SERVICE_LOOPBACK}=${options.loopbackAddress}`,
    // Configure extra pipe for receiving control messages (e.g. when ready)
    "--control-fd=3",
    // Read config from stdin
    "-"
  ];
  if (options.inspectorAddress !== void 0) {
    args.push(`--inspector-addr=${options.inspectorAddress}`);
  }
  if (options.debugPortAddress !== void 0) {
    args.push(`--debug-port=${options.debugPortAddress}`);
  }
  if (options.verbose) {
    args.push("--verbose");
  }
  return args;
}
function getInspectorOptions() {
  const value = process.env.VSCODE_INSPECTOR_OPTIONS;
  if (!value) {
    return void 0;
  }
  const ownOptions = value.split(":::").reverse().find((v) => !!v);
  if (!ownOptions) {
    return;
  }
  try {
    return JSON.parse(ownOptions);
  } catch {
    return void 0;
  }
}
var StartupLogBuffer = class {
  stdoutStream;
  stderrStream;
  stdoutBuffer = [];
  stderrBuffer = [];
  buffering = true;
  constructor() {
    this.stdoutStream = new import_node_stream.Transform({
      transform: (chunk, encoding, callback) => {
        if (this.buffering) {
          this.stdoutBuffer.push(chunk.toString());
        }
        callback(null, chunk);
      }
    });
    this.stderrStream = new import_node_stream.Transform({
      transform: (chunk, encoding, callback) => {
        if (this.buffering) {
          this.stderrBuffer.push(chunk.toString());
        }
        callback(null, chunk);
      }
    });
  }
  stopBuffering() {
    this.buffering = false;
  }
  handleStartupFailure() {
    const addressInUseLog = this.stderrBuffer.find(
      (chunk) => chunk.includes("Address already in use; toString() = ")
    );
    if (addressInUseLog) {
      const match = addressInUseLog.match(
        /Address already in use; toString\(\) = (.+):(.+)/
      ) ?? ["", "unknown", "unknown"];
      throw new MiniflareCoreError(
        "ERR_ADDRESS_IN_USE",
        `Address already in use (${match[1]}:${match[2]}). Please check that you are not already running a server on this address or specify a different port with --port.`
      );
    }
    const stderr2 = this.stderrBuffer.join("").trim();
    if (stderr2.length > 0) {
      throw new MiniflareCoreError(
        "ERR_RUNTIME_FAILURE",
        `The Workers runtime failed to start. There was likely a problem with the workerd binary or your configuration.
Runtime stderr:
${stderr2}`
      );
    }
  }
};
var Runtime = class {
  #process;
  #processExitPromise;
  async updateConfig(configBuffer, options, workerNames, abortSignal) {
    await this.dispose();
    const command = getRuntimeCommand();
    const args = getRuntimeArgs(options);
    const FORCE_COLOR3 = $2.enabled ? "1" : "0";
    const runtimeProcess = import_node_child_process3.default.spawn(command, args, {
      stdio: ["pipe", "pipe", "pipe", "pipe"],
      windowsHide: true,
      env: {
        ...process.env,
        TZ: "UTC",
        FORCE_COLOR: FORCE_COLOR3,
        ...options.runtimeEnv
      }
    });
    const startupLogBuffer = new StartupLogBuffer();
    this.#process = runtimeProcess;
    const processExitPromise = waitForExit(runtimeProcess);
    this.#processExitPromise = processExitPromise;
    const stdoutStream = runtimeProcess.stdout.pipe(
      startupLogBuffer.stdoutStream
    );
    const stderrStream = runtimeProcess.stderr.pipe(
      startupLogBuffer.stderrStream
    );
    const structuredLogsHandler = options.handleStructuredLogs ?? defaultStructuredLogsHandler;
    handleStructuredLogsFromStream(stdoutStream, structuredLogsHandler);
    handleStructuredLogsFromStream(stderrStream, structuredLogsHandler);
    const controlPipe = runtimeProcess.stdio[3];
    (0, import_node_assert8.default)(controlPipe instanceof import_node_stream.Readable);
    runtimeProcess.stdin.write(configBuffer);
    runtimeProcess.stdin.end();
    await (0, import_node_events2.once)(runtimeProcess.stdin, "finish");
    const ports = await Promise.race([
      waitForPorts(controlPipe, options),
      processExitPromise.then(() => void 0)
    ]);
    if (ports?.has(kInspectorSocket) && process.env.VSCODE_INSPECTOR_OPTIONS) {
      const bootloaderPath = process.env.NODE_OPTIONS?.match(/--require "(.*?)"/)?.[1];
      if (bootloaderPath) {
        const watchdogPath = import_node_path13.default.resolve(bootloaderPath, "../watchdog.js");
        const info = getInspectorOptions();
        for (const name of workerNames) {
          const p2 = (0, import_node_child_process3.spawn)(process.execPath, [watchdogPath], {
            env: {
              NODE_INSPECTOR_INFO: JSON.stringify({
                ipcAddress: info.inspectorIpc || "",
                pid: String(this.#process.pid),
                scriptName: name,
                inspectorURL: `ws://127.0.0.1:${ports?.get(
                  kInspectorSocket
                )}/core:user:${name}`,
                waitForDebugger: true,
                ownId: (0, import_node_crypto3.randomBytes)(12).toString("hex"),
                openerId: info.openerId
              }),
              NODE_SKIP_PLATFORM_CHECK: process.env.NODE_SKIP_PLATFORM_CHECK,
              ELECTRON_RUN_AS_NODE: "1"
            },
            stdio: "ignore",
            detached: true
          });
          p2.unref();
        }
      }
    }
    startupLogBuffer.stopBuffering();
    if (ports === void 0 && !abortSignal.aborted) {
      startupLogBuffer.handleStartupFailure();
    } else {
      const currentProcess = this.#process;
      void processExitPromise.then(() => {
        if (this.#process !== currentProcess) {
          return;
        }
        if (abortSignal.aborted) {
          return;
        }
        this.#process = void 0;
        options.onWorkerdCrashRestart?.();
      });
    }
    return ports;
  }
  dispose() {
    const runtimeProcess = this.#process;
    if (runtimeProcess === void 0) {
      return;
    }
    this.#process = void 0;
    runtimeProcess.stdin?.destroy();
    runtimeProcess.stdout?.destroy();
    runtimeProcess.stderr?.destroy();
    const controlPipe = runtimeProcess.stdio[3];
    if (controlPipe instanceof import_node_stream.Readable) {
      controlPipe.destroy();
    }
    runtimeProcess.kill("SIGKILL");
    return this.#processExitPromise;
  }
};

// src/shared/dev-control.ts
function createDurableObjectStorageHandle(control, scriptName, className, options) {
  return {
    async exec(query, ...bindings) {
      return control.execDurableObjectSql(scriptName, className, {
        ...options,
        query,
        bindings
      });
    }
  };
}
function getDevControlDurableObjectBindingName(scriptName, className) {
  return ["MINIFLARE_DEV_CONTROL_DO", scriptName, className].join(":");
}

// src/plugins/cache/index.ts
var import_promises4 = __toESM(require("node:fs/promises"));

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/cache/cache.worker.ts
var import_fs15 = __toESM(require("fs"));
var import_path15 = __toESM(require("path"));
var import_url15 = __toESM(require("url"));
var contents15;
function cache_worker_default() {
  if (contents15 !== void 0) return contents15;
  const filePath = import_path15.default.join(__dirname, "workers", "cache/cache.worker.js");
  contents15 = import_fs15.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url15.default.pathToFileURL(filePath);
  return contents15;
}

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/cache/cache-entry.worker.ts
var import_fs16 = __toESM(require("fs"));
var import_path16 = __toESM(require("path"));
var import_url16 = __toESM(require("url"));
var contents16;
function cache_entry_worker_default() {
  if (contents16 !== void 0) return contents16;
  const filePath = import_path16.default.join(__dirname, "workers", "cache/cache-entry.worker.js");
  contents16 = import_fs16.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url16.default.pathToFileURL(filePath);
  return contents16;
}

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/cache/cache-entry-noop.worker.ts
var import_fs17 = __toESM(require("fs"));
var import_path17 = __toESM(require("path"));
var import_url17 = __toESM(require("url"));
var contents17;
function cache_entry_noop_worker_default() {
  if (contents17 !== void 0) return contents17;
  const filePath = import_path17.default.join(__dirname, "workers", "cache/cache-entry-noop.worker.js");
  contents17 = import_fs17.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url17.default.pathToFileURL(filePath);
  return contents17;
}

// src/plugins/cache/index.ts
var CACHE_PLUGIN_NAME = "cache";
var CACHE_STORAGE_SERVICE_NAME = `${CACHE_PLUGIN_NAME}:storage`;
var CACHE_SERVICE_PREFIX = `${CACHE_PLUGIN_NAME}:cache`;
var CACHE_OBJECT_CLASS_NAME = "CacheObject";
var CACHE_OBJECT = {
  serviceName: CACHE_SERVICE_PREFIX,
  className: CACHE_OBJECT_CLASS_NAME
};
function getCacheServiceName(workerIndex) {
  return `${CACHE_PLUGIN_NAME}:${workerIndex}`;
}
var CACHE_PLUGIN = {
  getBindings() {
    return [];
  },
  getNodeBindings() {
    return {};
  },
  async getServices({ options, workerIndex, tmpPath, sharedOptions }) {
    const cache = options.dev?.cacheAPI ?? true;
    let entryWorker;
    if (cache) {
      entryWorker = {
        compatibilityDate: "2023-07-24",
        compatibilityFlags: ["nodejs_compat", "experimental"],
        modules: [
          { name: "cache-entry.worker.js", esModule: cache_entry_worker_default() }
        ],
        bindings: [
          {
            name: SharedBindings.DURABLE_OBJECT_NAMESPACE_OBJECT,
            durableObjectNamespace: CACHE_OBJECT
          }
        ]
      };
    } else {
      entryWorker = {
        compatibilityDate: "2023-07-24",
        compatibilityFlags: ["nodejs_compat", "experimental"],
        modules: [
          {
            name: "cache-entry-noop.worker.js",
            esModule: cache_entry_noop_worker_default()
          }
        ]
      };
    }
    const services = [
      { name: getCacheServiceName(workerIndex), worker: entryWorker }
    ];
    if (cache) {
      const uniqueKey = `miniflare-${CACHE_OBJECT_CLASS_NAME}`;
      const persistPath = getPersistPath(
        CACHE_PLUGIN_NAME,
        tmpPath,
        sharedOptions.resourcePersistencePath
      );
      await import_promises4.default.mkdir(persistPath, { recursive: true });
      const storageService = {
        name: CACHE_STORAGE_SERVICE_NAME,
        disk: { path: persistPath, writable: true }
      };
      const objectService = {
        name: CACHE_SERVICE_PREFIX,
        worker: {
          compatibilityDate: "2023-07-24",
          compatibilityFlags: ["nodejs_compat", "experimental"],
          modules: [
            {
              name: "cache.worker.js",
              esModule: cache_worker_default()
            }
          ],
          durableObjectNamespaces: [
            {
              className: CACHE_OBJECT_CLASS_NAME,
              uniqueKey
            }
          ],
          // Store Durable Object SQL databases in persist path
          durableObjectStorage: { localDisk: CACHE_STORAGE_SERVICE_NAME },
          // Bind blob disk directory service to object
          bindings: [
            {
              name: SharedBindings.MAYBE_SERVICE_BLOBS,
              service: { name: CACHE_STORAGE_SERVICE_NAME }
            },
            {
              name: SharedBindings.MAYBE_SERVICE_LOOPBACK,
              service: { name: SERVICE_LOOPBACK }
            },
            ...getMiniflareObjectBindings()
          ]
        }
      };
      services.push(storageService, objectService);
    }
    return services;
  }
};

// src/plugins/do/index.ts
var import_promises5 = __toESM(require("node:fs/promises"));
var DOContainerOptionsSchema = external_exports2.object({
  imageName: external_exports2.string()
});
function getDurableObjectUniqueKey(className, workerName, unsafeUniqueKey) {
  if (unsafeUniqueKey === kUnsafeEphemeralUniqueKey) {
    return void 0;
  }
  return unsafeUniqueKey ?? `${workerName ?? ""}-${className}`;
}
var DURABLE_OBJECTS_PLUGIN_NAME = "do";
var DURABLE_OBJECTS_STORAGE_SERVICE_NAME = `${DURABLE_OBJECTS_PLUGIN_NAME}:storage`;
var DURABLE_OBJECTS_PLUGIN = {
  bindingTypeDescription: "Durable Object namespace",
  getBindings(options) {
    return getEnvBindingsOfType(
      options.config,
      "durable-object"
    ).map(([name, binding]) => ({
      name,
      durableObjectNamespace: {
        className: binding.exportName,
        serviceName: getUserServiceName(binding.workerName)
      }
    }));
  },
  getNodeBindings(options) {
    const objects = getEnvBindingsOfType(options.config, "durable-object").map(
      ([name]) => name
    );
    return Object.fromEntries(
      objects.map((name) => [name, new ProxyNodeBinding()])
    );
  },
  async getServices({
    tmpPath,
    sharedOptions,
    durableObjectClassNames,
    unsafeEphemeralDurableObjects
  }) {
    let hasDurableObjects = false;
    for (const classNames of durableObjectClassNames.values()) {
      if (classNames.size > 0) {
        hasDurableObjects = true;
        break;
      }
    }
    if (!hasDurableObjects) return;
    if (unsafeEphemeralDurableObjects) return;
    const storagePath = getPersistPath(
      DURABLE_OBJECTS_PLUGIN_NAME,
      tmpPath,
      sharedOptions.resourcePersistencePath
    );
    await import_promises5.default.mkdir(storagePath, { recursive: true });
    return [
      {
        // Note this service will be de-duped by name if multiple Workers create
        // it. Each Worker will have the same `sharedOptions` though, so this
        // isn't a problem.
        name: DURABLE_OBJECTS_STORAGE_SERVICE_NAME,
        disk: { path: storagePath, writable: true }
      }
    ];
  }
};

// src/plugins/images/index.ts
var import_promises8 = __toESM(require("node:fs/promises"));

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/images/images.worker.ts
var import_fs18 = __toESM(require("fs"));
var import_path18 = __toESM(require("path"));
var import_url18 = __toESM(require("url"));
var contents18;
function images_worker_default() {
  if (contents18 !== void 0) return contents18;
  const filePath = import_path18.default.join(__dirname, "workers", "images/images.worker.js");
  contents18 = import_fs18.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url18.default.pathToFileURL(filePath);
  return contents18;
}

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/kv/namespace.worker.ts
var import_fs19 = __toESM(require("fs"));
var import_path19 = __toESM(require("path"));
var import_url19 = __toESM(require("url"));
var contents19;
function namespace_worker_default() {
  if (contents19 !== void 0) return contents19;
  const filePath = import_path19.default.join(__dirname, "workers", "kv/namespace.worker.js");
  contents19 = import_fs19.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url19.default.pathToFileURL(filePath);
  return contents19;
}

// src/plugins/kv/index.ts
var import_promises7 = __toESM(require("node:fs/promises"));

// src/plugins/kv/constants.ts
var KV_PLUGIN_NAME = "kv";

// src/plugins/kv/sites.ts
var import_node_assert9 = __toESM(require("node:assert"));
var import_promises6 = __toESM(require("node:fs/promises"));
var import_node_path14 = __toESM(require("node:path"));

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/kv/sites.worker.ts
var import_fs20 = __toESM(require("fs"));
var import_path20 = __toESM(require("path"));
var import_url20 = __toESM(require("url"));
var contents20;
function sites_worker_default() {
  if (contents20 !== void 0) return contents20;
  const filePath = import_path20.default.join(__dirname, "workers", "kv/sites.worker.js");
  contents20 = import_fs20.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url20.default.pathToFileURL(filePath);
  return contents20;
}

// src/plugins/kv/sites.ts
async function* listKeysInDirectoryInner(rootPath2, currentPath) {
  const fileEntries = await import_promises6.default.readdir(currentPath, { withFileTypes: true });
  for (const fileEntry of fileEntries) {
    const filePath = import_node_path14.default.posix.join(currentPath, fileEntry.name);
    if (fileEntry.isDirectory()) {
      yield* listKeysInDirectoryInner(rootPath2, filePath);
    } else {
      yield filePath.substring(rootPath2.length + 1);
    }
  }
}
function listKeysInDirectory(rootPath2) {
  rootPath2 = import_node_path14.default.resolve(rootPath2);
  return listKeysInDirectoryInner(rootPath2, rootPath2);
}
function resolveSitePath(options, rootPath2) {
  if (rootPath2 !== void 0 && !import_node_path14.default.isAbsolute(options.sitePath)) {
    return import_node_path14.default.resolve(rootPath2, options.sitePath);
  }
  return options.sitePath;
}
var sitesRegExpsCache = /* @__PURE__ */ new WeakMap();
var SERVICE_NAMESPACE_SITE = `${KV_PLUGIN_NAME}:site`;
async function buildStaticContentManifest(sitePath, siteRegExps) {
  const staticContentManifest = {};
  for await (const key of listKeysInDirectory(sitePath)) {
    if (testSiteRegExps(siteRegExps, key)) {
      staticContentManifest[key] = encodeSitesKey(key);
    }
  }
  return staticContentManifest;
}
async function getSitesBindings(options, rootPath2) {
  const siteRegExps = {
    include: options.siteInclude && globsToRegExps(options.siteInclude),
    exclude: options.siteExclude && globsToRegExps(options.siteExclude)
  };
  sitesRegExpsCache.set(options, siteRegExps);
  const __STATIC_CONTENT_MANIFEST = await buildStaticContentManifest(
    resolveSitePath(options, rootPath2),
    siteRegExps
  );
  return [
    {
      name: SiteBindings.KV_NAMESPACE_SITE,
      kvNamespace: { name: SERVICE_NAMESPACE_SITE }
    },
    {
      name: SiteBindings.JSON_SITE_MANIFEST,
      json: JSON.stringify(__STATIC_CONTENT_MANIFEST)
    }
  ];
}
async function getSitesNodeBindings(options, rootPath2) {
  const siteRegExps = sitesRegExpsCache.get(options);
  (0, import_node_assert9.default)(siteRegExps !== void 0);
  const __STATIC_CONTENT_MANIFEST = await buildStaticContentManifest(
    resolveSitePath(options, rootPath2),
    siteRegExps
  );
  return {
    [SiteBindings.KV_NAMESPACE_SITE]: new ProxyNodeBinding(),
    [SiteBindings.JSON_SITE_MANIFEST]: __STATIC_CONTENT_MANIFEST
  };
}
function getSitesServices(options, rootPath2) {
  const siteRegExps = sitesRegExpsCache.get(options);
  (0, import_node_assert9.default)(siteRegExps !== void 0);
  const serialisedSiteRegExps = serialiseSiteRegExps(siteRegExps);
  const persist = import_node_path14.default.resolve(resolveSitePath(options, rootPath2));
  const storageServiceName = `${SERVICE_NAMESPACE_SITE}:storage`;
  const storageService = {
    name: storageServiceName,
    disk: { path: persist, writable: true }
  };
  const namespaceService = {
    name: SERVICE_NAMESPACE_SITE,
    worker: {
      compatibilityDate: "2023-07-24",
      compatibilityFlags: ["nodejs_compat"],
      modules: [
        {
          name: "site.worker.js",
          esModule: sites_worker_default()
        }
      ],
      bindings: [
        {
          name: SharedBindings.MAYBE_SERVICE_BLOBS,
          service: { name: storageServiceName }
        },
        {
          name: SiteBindings.JSON_SITE_FILTER,
          json: JSON.stringify(serialisedSiteRegExps)
        }
      ]
    }
  };
  return [storageService, namespaceService];
}

// src/plugins/kv/index.ts
var SERVICE_NAMESPACE_PREFIX = `${KV_PLUGIN_NAME}:ns`;
var KV_LOCAL_ENTRY_SERVICE_NAME = `${KV_PLUGIN_NAME}:ns:entry`;
var KV_REMOTE_SERVICE_NAME = `${KV_PLUGIN_NAME}:ns:remote`;
var KV_STORAGE_SERVICE_NAME = `${KV_PLUGIN_NAME}:storage`;
var KV_NAMESPACE_OBJECT_CLASS_NAME = "KVNamespaceObject";
var KV_NAMESPACE_OBJECT = {
  serviceName: SERVICE_NAMESPACE_PREFIX,
  className: KV_NAMESPACE_OBJECT_CLASS_NAME
};
function isWorkersSitesEnabled(options) {
  return options.legacy?.sitePath !== void 0;
}
var KV_PLUGIN = {
  bindingTypeDescription: "KV namespace",
  async getBindings(options) {
    const namespaces = getEnvBindingsOfType(options.config, "kv");
    const bindings = namespaces.map(([name, binding]) => {
      const id = binding.id;
      const remoteProxyConnectionString = getRemoteProxyConnectionString(
        binding,
        options.dev
      );
      if (remoteProxyConnectionString) {
        return {
          name,
          kvNamespace: {
            name: KV_REMOTE_SERVICE_NAME,
            props: buildRemoteProxyProps(remoteProxyConnectionString, name)
          }
        };
      }
      return {
        name,
        kvNamespace: {
          name: KV_LOCAL_ENTRY_SERVICE_NAME,
          props: {
            json: JSON.stringify({
              [SharedBindings.TEXT_NAMESPACE]: id
            })
          }
        }
      };
    });
    if (isWorkersSitesEnabled(options)) {
      bindings.push(
        ...await getSitesBindings(options.legacy, options.dev?.rootPath)
      );
    }
    return bindings;
  },
  async getNodeBindings(options) {
    const namespaces = getEnvBindingsOfType(options.config, "kv");
    const bindings = Object.fromEntries(
      namespaces.map(([name]) => [name, new ProxyNodeBinding()])
    );
    if (isWorkersSitesEnabled(options)) {
      Object.assign(
        bindings,
        await getSitesNodeBindings(options.legacy, options.dev?.rootPath)
      );
    }
    return bindings;
  },
  async getServices({ options, tmpPath, sharedOptions }) {
    const namespaces = getEnvBindingsOfType(options.config, "kv");
    const services = [];
    const hasLocalNamespace = namespaces.some(
      ([, binding]) => !getRemoteProxyConnectionString(binding, options.dev)
    );
    if (hasLocalNamespace) {
      services.push({
        name: KV_LOCAL_ENTRY_SERVICE_NAME,
        worker: objectEntryWorker(KV_NAMESPACE_OBJECT)
      });
    }
    const hasRemoteNamespace = namespaces.some(
      ([, binding]) => getRemoteProxyConnectionString(binding, options.dev)
    );
    if (hasRemoteNamespace) {
      services.push({
        name: KV_REMOTE_SERVICE_NAME,
        worker: remoteProxyClientWorker()
      });
    }
    if (hasLocalNamespace) {
      const uniqueKey = `miniflare-${KV_NAMESPACE_OBJECT_CLASS_NAME}`;
      const persistPath = getPersistPath(
        KV_PLUGIN_NAME,
        tmpPath,
        sharedOptions.resourcePersistencePath
      );
      await import_promises7.default.mkdir(persistPath, { recursive: true });
      const storageService = {
        name: KV_STORAGE_SERVICE_NAME,
        disk: { path: persistPath, writable: true }
      };
      const objectService = {
        name: SERVICE_NAMESPACE_PREFIX,
        worker: {
          compatibilityDate: "2023-07-24",
          compatibilityFlags: ["nodejs_compat", "experimental"],
          modules: [
            {
              name: "namespace.worker.js",
              esModule: namespace_worker_default()
            }
          ],
          durableObjectNamespaces: [
            { className: KV_NAMESPACE_OBJECT_CLASS_NAME, uniqueKey }
          ],
          // Store Durable Object SQL databases in persist path
          durableObjectStorage: { localDisk: KV_STORAGE_SERVICE_NAME },
          // Bind blob disk directory service to object
          bindings: [
            {
              name: SharedBindings.MAYBE_SERVICE_BLOBS,
              service: { name: KV_STORAGE_SERVICE_NAME }
            },
            {
              name: SharedBindings.MAYBE_SERVICE_LOOPBACK,
              service: { name: SERVICE_LOOPBACK }
            },
            ...getMiniflareObjectBindings()
          ]
        }
      };
      services.push(storageService, objectService);
    }
    if (isWorkersSitesEnabled(options)) {
      services.push(...getSitesServices(options.legacy, options.dev?.rootPath));
    }
    return services;
  }
};

// src/plugins/images/index.ts
var IMAGES_PLUGIN_NAME = "images";
var IMAGES_REMOTE_SERVICE_NAME = `${IMAGES_PLUGIN_NAME}:remote`;
var IMAGES_PLUGIN = {
  bindingTypeDescription: "Images",
  async getBindings(options) {
    return getEnvBindingsOfType(options.config, "images").map(
      ([name, binding]) => {
        const remoteProxyConnectionString = getRemoteProxyConnectionString(
          binding,
          options.dev
        );
        return {
          name,
          wrapped: {
            moduleName: "cloudflare-internal:images-api",
            innerBindings: [
              {
                name: "fetcher",
                service: remoteProxyConnectionString ? {
                  name: IMAGES_REMOTE_SERVICE_NAME,
                  props: buildRemoteProxyProps(
                    remoteProxyConnectionString,
                    name
                  )
                } : {
                  name: getUserBindingServiceName(IMAGES_PLUGIN_NAME, name)
                }
              }
            ]
          }
        };
      }
    );
  },
  getNodeBindings(options) {
    return Object.fromEntries(
      getEnvBindingsOfType(options.config, "images").map(([name]) => [
        name,
        new ProxyNodeBinding()
      ])
    );
  },
  async getServices({ options, tmpPath, sharedOptions }) {
    const services = [];
    const imagesBindings = getEnvBindingsOfType(options.config, "images");
    for (const [name, binding] of imagesBindings) {
      const remoteProxyConnectionString = getRemoteProxyConnectionString(
        binding,
        options.dev
      );
      if (remoteProxyConnectionString) {
        services.push({
          name: IMAGES_REMOTE_SERVICE_NAME,
          worker: remoteProxyClientWorker()
        });
        continue;
      }
      const serviceName = getUserBindingServiceName(IMAGES_PLUGIN_NAME, name);
      const persistPath = getPersistPath(
        IMAGES_PLUGIN_NAME,
        tmpPath,
        sharedOptions.resourcePersistencePath
      );
      await import_promises8.default.mkdir(persistPath, { recursive: true });
      const storageService = {
        name: `${IMAGES_PLUGIN_NAME}:storage`,
        disk: { path: persistPath, writable: true }
      };
      const objectService = {
        name: `${IMAGES_PLUGIN_NAME}:ns`,
        worker: {
          compatibilityDate: "2023-07-24",
          compatibilityFlags: ["nodejs_compat", "experimental"],
          modules: [
            {
              name: "namespace.worker.js",
              esModule: namespace_worker_default()
            }
          ],
          durableObjectNamespaces: [
            {
              className: KV_NAMESPACE_OBJECT_CLASS_NAME,
              uniqueKey: `miniflare-images-${KV_NAMESPACE_OBJECT_CLASS_NAME}`
            }
          ],
          durableObjectStorage: { localDisk: storageService.name },
          bindings: [
            {
              name: SharedBindings.MAYBE_SERVICE_BLOBS,
              service: { name: storageService.name }
            },
            {
              name: SharedBindings.MAYBE_SERVICE_LOOPBACK,
              service: { name: SERVICE_LOOPBACK }
            },
            ...getMiniflareObjectBindings()
          ]
        }
      };
      const kvNamespaceService = {
        name: `${IMAGES_PLUGIN_NAME}:ns:data`,
        worker: objectEntryWorker(
          {
            serviceName: objectService.name,
            className: KV_NAMESPACE_OBJECT_CLASS_NAME
          },
          "images-data"
        )
      };
      const imagesService = {
        name: serviceName,
        worker: {
          compatibilityDate: "2025-04-01",
          modules: [
            {
              name: "images.worker.js",
              esModule: images_worker_default()
            }
          ],
          bindings: [
            {
              name: "IMAGES_STORE",
              kvNamespace: { name: kvNamespaceService.name }
            },
            WORKER_BINDING_SERVICE_LOOPBACK
          ]
        }
      };
      services.push(
        storageService,
        objectService,
        kvNamespaceService,
        imagesService
      );
    }
    return services;
  }
};

// src/plugins/r2/index.ts
var import_promises9 = __toESM(require("node:fs/promises"));

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/r2/bucket.worker.ts
var import_fs21 = __toESM(require("fs"));
var import_path21 = __toESM(require("path"));
var import_url21 = __toESM(require("url"));
var contents21;
function bucket_worker_default() {
  if (contents21 !== void 0) return contents21;
  const filePath = import_path21.default.join(__dirname, "workers", "r2/bucket.worker.js");
  contents21 = import_fs21.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url21.default.pathToFileURL(filePath);
  return contents21;
}

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/r2/public.worker.ts
var import_fs22 = __toESM(require("fs"));
var import_path22 = __toESM(require("path"));
var import_url22 = __toESM(require("url"));
var contents22;
function public_worker_default() {
  if (contents22 !== void 0) return contents22;
  const filePath = import_path22.default.join(__dirname, "workers", "r2/public.worker.js");
  contents22 = import_fs22.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url22.default.pathToFileURL(filePath);
  return contents22;
}

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/r2/s3/index.worker.ts
var import_fs23 = __toESM(require("fs"));
var import_path23 = __toESM(require("path"));
var import_url23 = __toESM(require("url"));
var contents23;
function index_worker_default2() {
  if (contents23 !== void 0) return contents23;
  const filePath = import_path23.default.join(__dirname, "workers", "r2/s3/index.worker.js");
  contents23 = import_fs23.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url23.default.pathToFileURL(filePath);
  return contents23;
}

// src/workers/r2/constants.ts
var R2Limits = {
  MAX_LIST_KEYS: 1e3,
  MAX_KEY_SIZE: 1024,
  // https://developers.cloudflare.com/r2/platform/limits/
  MAX_VALUE_SIZE: 5368709120 - 5242880,
  // 5 GiB - 5 MiB
  MAX_METADATA_SIZE: 2048,
  // 2048 B
  MIN_MULTIPART_PART_SIZE: 5 * 1024 * 1024,
  MIN_MULTIPART_PART_SIZE_TEST: 50
};
var R2S3Bindings = {
  /** JSON map of bucket id to `{ accessKeyId, secretAccessKey }` */
  JSON_CREDENTIALS: "MINIFLARE_R2_S3_CREDENTIALS",
  /** Prefix for per-bucket `R2Bucket` bindings (followed by the bucket id) */
  BUCKET_PREFIX: "MINIFLARE_R2_S3_BUCKET_"
};

// src/plugins/r2/index.ts
var R2_PLUGIN_NAME = "r2";
var R2_STORAGE_SERVICE_NAME = `${R2_PLUGIN_NAME}:storage`;
var R2_BUCKET_SERVICE_PREFIX = `${R2_PLUGIN_NAME}:bucket`;
var R2_LOCAL_ENTRY_SERVICE_NAME = `${R2_PLUGIN_NAME}:bucket:entry`;
var R2_REMOTE_SERVICE_NAME = `${R2_PLUGIN_NAME}:bucket:remote`;
var R2_PUBLIC_SERVICE_NAME = `${R2_PLUGIN_NAME}:public`;
var R2_S3_SERVICE_NAME = `${R2_PLUGIN_NAME}:s3`;
var R2_BUCKET_OBJECT_CLASS_NAME = "R2BucketObject";
var R2_BUCKET_OBJECT = {
  serviceName: R2_BUCKET_SERVICE_PREFIX,
  className: R2_BUCKET_OBJECT_CLASS_NAME
};
function getR2PublicService(allWorkerOpts) {
  const publicBucketIds = /* @__PURE__ */ new Set();
  for (const worker of allWorkerOpts) {
    for (const [, bucket] of getEnvBindingsOfType(worker.config, "r2")) {
      if (getRemoteProxyConnectionString(bucket, worker.dev) !== void 0) {
        continue;
      }
      publicBucketIds.add(bucket.name);
    }
  }
  if (publicBucketIds.size === 0) {
    return void 0;
  }
  const bindings = Array.from(publicBucketIds).map((id) => ({
    name: id,
    r2Bucket: {
      name: R2_LOCAL_ENTRY_SERVICE_NAME,
      props: buildObjectEntryProps(id)
    }
  }));
  return {
    name: R2_PUBLIC_SERVICE_NAME,
    worker: {
      compatibilityDate: "2026-01-01",
      modules: [{ name: "public.worker.js", esModule: public_worker_default() }],
      bindings
    }
  };
}
function getR2S3Service(allWorkerOpts) {
  const credentialsById = {};
  for (const worker of allWorkerOpts) {
    for (const [, bucket] of getEnvBindingsOfType(worker.config, "r2")) {
      if (getRemoteProxyConnectionString(bucket, worker.dev) !== void 0 || bucket.s3Credentials === void 0) {
        continue;
      }
      const id = bucket.name;
      const existing = credentialsById[id];
      if (existing !== void 0 && (existing.accessKeyId !== bucket.s3Credentials.accessKeyId || existing.secretAccessKey !== bucket.s3Credentials.secretAccessKey)) {
        throw new MiniflareCoreError(
          "ERR_DIFFERENT_S3_CREDENTIALS",
          `Bucket "${id}" is bound by multiple Workers with different S3 credentials`
        );
      }
      credentialsById[id] = bucket.s3Credentials;
    }
  }
  const bucketIds = Object.keys(credentialsById);
  if (bucketIds.length === 0) {
    return void 0;
  }
  const bindings = bucketIds.map((id) => ({
    name: `${R2S3Bindings.BUCKET_PREFIX}${id}`,
    r2Bucket: {
      name: R2_LOCAL_ENTRY_SERVICE_NAME,
      props: buildObjectEntryProps(id)
    }
  }));
  bindings.push({
    name: R2S3Bindings.JSON_CREDENTIALS,
    json: JSON.stringify(credentialsById)
  });
  return {
    name: R2_S3_SERVICE_NAME,
    worker: {
      compatibilityDate: "2026-01-01",
      compatibilityFlags: ["nodejs_compat"],
      modules: [{ name: "s3.worker.js", esModule: index_worker_default2() }],
      bindings
    }
  };
}
var R2_PLUGIN = {
  bindingTypeDescription: "R2 bucket",
  getBindings(options) {
    return getEnvBindingsOfType(options.config, "r2").map(
      ([name, bucket]) => {
        const id = bucket.name;
        const remoteProxyConnectionString = getRemoteProxyConnectionString(
          bucket,
          options.dev
        );
        return {
          name,
          r2Bucket: remoteProxyConnectionString ? {
            name: R2_REMOTE_SERVICE_NAME,
            props: buildRemoteProxyProps(remoteProxyConnectionString, name)
          } : {
            name: R2_LOCAL_ENTRY_SERVICE_NAME,
            props: buildObjectEntryProps(id)
          }
        };
      }
    );
  },
  getNodeBindings(options) {
    return Object.fromEntries(
      getEnvBindingsOfType(options.config, "r2").map(([name]) => [
        name,
        new ProxyNodeBinding()
      ])
    );
  },
  async getServices({ options, tmpPath, sharedOptions }) {
    const buckets = getEnvBindingsOfType(options.config, "r2");
    const services = [];
    const hasLocal = buckets.some(
      ([, b]) => getRemoteProxyConnectionString(b, options.dev) === void 0
    );
    if (hasLocal) {
      services.push({
        name: R2_LOCAL_ENTRY_SERVICE_NAME,
        worker: objectEntryWorker(R2_BUCKET_OBJECT)
      });
    }
    const hasRemote = buckets.some(
      ([, b]) => getRemoteProxyConnectionString(b, options.dev) !== void 0
    );
    if (hasRemote) {
      services.push({
        name: R2_REMOTE_SERVICE_NAME,
        worker: remoteProxyClientWorker()
      });
    }
    if (hasLocal) {
      const uniqueKey = `miniflare-${R2_BUCKET_OBJECT_CLASS_NAME}`;
      const persistPath = getPersistPath(
        R2_PLUGIN_NAME,
        tmpPath,
        sharedOptions.resourcePersistencePath
      );
      await import_promises9.default.mkdir(persistPath, { recursive: true });
      const storageService = {
        name: R2_STORAGE_SERVICE_NAME,
        disk: { path: persistPath, writable: true }
      };
      const objectService = {
        name: R2_BUCKET_SERVICE_PREFIX,
        worker: {
          compatibilityDate: "2023-07-24",
          compatibilityFlags: ["nodejs_compat", "experimental"],
          modules: [
            {
              name: "bucket.worker.js",
              esModule: bucket_worker_default()
            }
          ],
          durableObjectNamespaces: [
            {
              className: R2_BUCKET_OBJECT_CLASS_NAME,
              uniqueKey
            }
          ],
          // Store Durable Object SQL databases in persist path
          durableObjectStorage: { localDisk: R2_STORAGE_SERVICE_NAME },
          // Bind blob disk directory service to object
          bindings: [
            {
              name: SharedBindings.MAYBE_SERVICE_BLOBS,
              service: { name: R2_STORAGE_SERVICE_NAME }
            },
            {
              name: SharedBindings.MAYBE_SERVICE_LOOPBACK,
              service: { name: SERVICE_LOOPBACK }
            },
            ...getMiniflareObjectBindings()
          ]
        }
      };
      services.push(storageService, objectService);
    }
    return services;
  }
};

// src/plugins/stream/index.ts
var import_promises10 = __toESM(require("node:fs/promises"));

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/stream/binding.worker.ts
var import_fs24 = __toESM(require("fs"));
var import_path24 = __toESM(require("path"));
var import_url24 = __toESM(require("url"));
var contents24;
function binding_worker_default() {
  if (contents24 !== void 0) return contents24;
  const filePath = import_path24.default.join(__dirname, "workers", "stream/binding.worker.js");
  contents24 = import_fs24.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url24.default.pathToFileURL(filePath);
  return contents24;
}

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/stream/object.worker.ts
var import_fs25 = __toESM(require("fs"));
var import_path25 = __toESM(require("path"));
var import_url25 = __toESM(require("url"));
var contents25;
function object_worker_default() {
  if (contents25 !== void 0) return contents25;
  const filePath = import_path25.default.join(__dirname, "workers", "stream/object.worker.js");
  contents25 = import_fs25.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url25.default.pathToFileURL(filePath);
  return contents25;
}

// src/plugins/stream/index.ts
var STREAM_PLUGIN_NAME = "stream";
var STREAM_REMOTE_SERVICE_NAME = `${STREAM_PLUGIN_NAME}:remote`;
var STREAM_STORAGE_SERVICE_NAME = `${STREAM_PLUGIN_NAME}:storage`;
var STREAM_OBJECT_SERVICE_NAME = `${STREAM_PLUGIN_NAME}:object`;
var STREAM_OBJECT_CLASS_NAME = "StreamObject";
var STREAM_COMPAT_DATE = "2026-03-23";
var STREAM_PLUGIN = {
  bindingTypeDescription: "Stream",
  async getBindings(options) {
    return getEnvBindingsOfType(options.config, "stream").map(
      ([name, binding]) => {
        const remoteProxyConnectionString = getRemoteProxyConnectionString(
          binding,
          options.dev
        );
        return {
          name,
          service: remoteProxyConnectionString ? {
            name: STREAM_REMOTE_SERVICE_NAME,
            props: buildRemoteProxyProps(remoteProxyConnectionString, name)
          } : {
            name: getUserBindingServiceName(STREAM_PLUGIN_NAME, "service"),
            entrypoint: "StreamBinding"
          }
        };
      }
    );
  },
  getNodeBindings(options) {
    return Object.fromEntries(
      getEnvBindingsOfType(options.config, "stream").map(([name]) => [
        name,
        new ProxyNodeBinding()
      ])
    );
  },
  async getServices({ options, tmpPath, sharedOptions }) {
    const services = [];
    for (const [, binding] of getEnvBindingsOfType(options.config, "stream")) {
      const remoteProxyConnectionString = getRemoteProxyConnectionString(
        binding,
        options.dev
      );
      if (remoteProxyConnectionString) {
        services.push({
          name: STREAM_REMOTE_SERVICE_NAME,
          worker: remoteProxyClientWorker()
        });
        continue;
      }
      const persistPath = getPersistPath(
        STREAM_PLUGIN_NAME,
        tmpPath,
        sharedOptions.resourcePersistencePath
      );
      await import_promises10.default.mkdir(persistPath, { recursive: true });
      const storageService = {
        name: STREAM_STORAGE_SERVICE_NAME,
        disk: { path: persistPath, writable: true }
      };
      const objectService = {
        name: STREAM_OBJECT_SERVICE_NAME,
        worker: {
          compatibilityDate: STREAM_COMPAT_DATE,
          compatibilityFlags: ["nodejs_compat", "experimental"],
          modules: [
            {
              name: "object.worker.js",
              esModule: object_worker_default()
            }
          ],
          durableObjectNamespaces: [
            {
              className: STREAM_OBJECT_CLASS_NAME,
              uniqueKey: `miniflare-${STREAM_OBJECT_CLASS_NAME}`,
              enableSql: true
            }
          ],
          durableObjectStorage: { localDisk: STREAM_STORAGE_SERVICE_NAME },
          bindings: [
            {
              name: SharedBindings.MAYBE_SERVICE_BLOBS,
              service: { name: STREAM_STORAGE_SERVICE_NAME }
            },
            ...getMiniflareObjectBindings()
          ],
          // Allow the DO to send outbound HTTP requests (fetching watermark images)
          globalOutbound: { name: "internet" }
        }
      };
      const bindingService = {
        name: getUserBindingServiceName(
          STREAM_PLUGIN_NAME,
          "service",
          remoteProxyConnectionString
        ),
        worker: {
          compatibilityDate: STREAM_COMPAT_DATE,
          compatibilityFlags: ["nodejs_compat", "experimental"],
          modules: [
            {
              name: "binding.worker.js",
              esModule: binding_worker_default()
            }
          ],
          bindings: [
            {
              name: "store",
              durableObjectNamespace: {
                className: STREAM_OBJECT_CLASS_NAME,
                serviceName: STREAM_OBJECT_SERVICE_NAME
              }
            },
            WORKER_BINDING_SERVICE_LOOPBACK
          ],
          // Allow the binding worker to send outbound HTTP requests
          // (e.g. fetching video from URL in upload fn)
          globalOutbound: { name: "internet" }
        }
      };
      services.push(storageService, objectService, bindingService);
    }
    return services;
  }
};

// src/plugins/core/constants.ts
var CORE_PLUGIN_NAME = "core";
var SERVICE_ENTRY = `${CORE_PLUGIN_NAME}:entry`;
var SERVICE_LOCAL_EXPLORER = `${CORE_PLUGIN_NAME}:local-explorer`;
var LOCAL_EXPLORER_DISK = `${CORE_PLUGIN_NAME}:local-explorer-disk`;
var OBSERVABILITY_COLLECTOR_SERVICE_NAME = "miniflare-observability-collector";
var OBSERVABILITY_COMPAT_FLAGS = [
  "streaming_tail_worker",
  "tail_worker_user_spans"
];
var SERVICE_USER_PREFIX = `${CORE_PLUGIN_NAME}:user`;
var SERVICE_BUILTIN_PREFIX = `${CORE_PLUGIN_NAME}:builtin`;
var SERVICE_CUSTOM_FETCH_PREFIX = `${CORE_PLUGIN_NAME}:custom-fetch`;
var SERVICE_CUSTOM_NODE_PREFIX = `${CORE_PLUGIN_NAME}:custom-node`;
function getUserServiceName(workerName = "") {
  return `${SERVICE_USER_PREFIX}:${workerName}`;
}
var CUSTOM_SERVICE_KNOWN_OUTBOUND = "outbound";
function getBuiltinServiceName(workerIndex, kind, bindingName) {
  return `${SERVICE_BUILTIN_PREFIX}:${workerIndex}:${kind}${bindingName}`;
}
function getCustomFetchServiceName(workerIndex, kind, bindingName) {
  return `${SERVICE_CUSTOM_FETCH_PREFIX}:${workerIndex}:${kind}${bindingName}`;
}
function getCustomNodeServiceName(workerIndex, kind, bindingName) {
  return `${SERVICE_CUSTOM_NODE_PREFIX}:${workerIndex}:${kind}${bindingName}`;
}
var INTROSPECT_SQLITE_METHOD = "__miniflare_introspectSqlite";

// src/plugins/core/explorer.ts
var import_node_assert10 = __toESM(require("node:assert"));

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/core/do-wrapper.worker.ts
var import_fs26 = __toESM(require("fs"));
var import_path26 = __toESM(require("path"));
var import_url26 = __toESM(require("url"));
var contents26;
function do_wrapper_worker_default() {
  if (contents26 !== void 0) return contents26;
  const filePath = import_path26.default.join(__dirname, "workers", "core/do-wrapper.worker.js");
  contents26 = import_fs26.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url26.default.pathToFileURL(filePath);
  return contents26;
}

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/local-explorer/explorer.worker.ts
var import_fs27 = __toESM(require("fs"));
var import_path27 = __toESM(require("path"));
var import_url27 = __toESM(require("url"));
var contents27;
function explorer_worker_default() {
  if (contents27 !== void 0) return contents27;
  const filePath = import_path27.default.join(__dirname, "workers", "local-explorer/explorer.worker.js");
  contents27 = import_fs27.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url27.default.pathToFileURL(filePath);
  return contents27;
}

// src/plugins/core/explorer.ts
function getExplorerServices(options) {
  const {
    localExplorerUiPath,
    proxyBindings,
    bindingIdMap,
    hasDurableObjects,
    workerNames,
    explorerWorkerOpts,
    telemetry,
    observabilityEnabled
  } = options;
  const explorerBindings = [
    // Gives explorer access to all user resource bindings
    ...proxyBindings,
    {
      name: CoreBindings.JSON_LOCAL_EXPLORER_BINDING_MAP,
      json: JSON.stringify(bindingIdMap)
    },
    {
      name: CoreBindings.EXPLORER_DISK,
      service: { name: LOCAL_EXPLORER_DISK }
    },
    // Loopback service for accessing Node.js endpoints:
    // - /core/dev-registry for cross-instance aggregation
    // - /core/do-storage for using DO storage to list objects
    WORKER_BINDING_SERVICE_LOOPBACK,
    // Worker names for this instance, used to filter self from registry during aggregation
    {
      name: CoreBindings.JSON_LOCAL_EXPLORER_WORKER_NAMES,
      json: JSON.stringify(workerNames)
    },
    // Per-worker resource bindings for the /local/workers endpoint
    {
      name: CoreBindings.JSON_EXPLORER_WORKER_OPTS,
      json: JSON.stringify(explorerWorkerOpts)
    },
    {
      name: CoreBindings.JSON_TELEMETRY_CONFIG,
      json: JSON.stringify(telemetry)
    },
    {
      name: CoreBindings.DEV_REGISTRY_DEBUG_PORT,
      // workerdDebugPort bindings don't have any additional configuration
      workerdDebugPort: kVoid
    }
  ];
  if (observabilityEnabled) {
    explorerBindings.push({
      name: CoreBindings.SERVICE_OBSERVABILITY_COLLECTOR,
      service: {
        name: getUserServiceName(OBSERVABILITY_COLLECTOR_SERVICE_NAME)
      }
    });
  }
  if (hasDurableObjects) {
    for (const durableObject of Object.values(bindingIdMap.do)) {
      explorerBindings.push({
        name: durableObject.binding,
        durableObjectNamespace: {
          className: durableObject.className,
          serviceName: getUserServiceName(durableObject.scriptName)
        }
      });
    }
  }
  for (const workflowInfo of Object.values(bindingIdMap.workflows)) {
    explorerBindings.push({
      name: workflowInfo.engineBinding,
      durableObjectNamespace: {
        className: "Engine",
        serviceName: `workflows:${workflowInfo.name}`
      }
    });
  }
  return [
    // Disk service for serving explorer UI assets
    {
      name: LOCAL_EXPLORER_DISK,
      disk: { path: localExplorerUiPath, writable: false }
    },
    {
      name: SERVICE_LOCAL_EXPLORER,
      worker: {
        compatibilityDate: "2026-01-01",
        compatibilityFlags: ["nodejs_compat"],
        modules: [
          {
            name: "explorer.worker.js",
            esModule: explorer_worker_default()
          }
        ],
        bindings: explorerBindings
      }
    }
  ];
}
function constructExplorerBindingMap(proxyBindings, durableObjectClassNames, workflowOptions) {
  const IDToBindingName = {
    d1: {},
    kv: {},
    do: {},
    r2: {},
    workflows: {}
  };
  for (const binding of proxyBindings) {
    if (binding.name?.startsWith(
      `${CoreBindings.DURABLE_OBJECT_NAMESPACE_PROXY}:d1:`
    ) && "wrapped" in binding) {
      const [innerBinding] = binding.wrapped?.innerBindings ?? [];
      (0, import_node_assert10.default)(innerBinding && "service" in innerBinding);
      const databaseId = extractObjectEntryId(innerBinding.service?.props?.json) ?? innerBinding.service?.name?.replace(/^d1:db:/, "");
      (0, import_node_assert10.default)(databaseId);
      if (databaseId !== "remote") {
        IDToBindingName.d1[databaseId] = binding.name;
      }
    }
    if (binding.name?.startsWith(
      `${CoreBindings.DURABLE_OBJECT_NAMESPACE_PROXY}:kv:`
    ) && "kvNamespace" in binding && binding.kvNamespace?.name?.startsWith("kv:ns:")) {
      const namespaceId = extractObjectEntryId(binding.kvNamespace.props?.json) ?? binding.kvNamespace.name.replace(/^kv:ns:/, "");
      if (namespaceId !== "remote") {
        IDToBindingName.kv[namespaceId] = binding.name;
      }
    }
    if (binding.name?.startsWith(
      `${CoreBindings.DURABLE_OBJECT_NAMESPACE_PROXY}:r2:`
    ) && "r2Bucket" in binding && binding.r2Bucket?.name?.startsWith("r2:bucket:")) {
      const bucketName = extractObjectEntryId(binding.r2Bucket.props?.json) ?? binding.r2Bucket.name.replace(/^r2:bucket:/, "");
      if (bucketName !== "remote") {
        IDToBindingName.r2[bucketName] = binding.name;
      }
    }
  }
  for (const [serviceName, classMap] of durableObjectClassNames) {
    if (serviceName === getUserServiceName(SERVICE_DEV_REGISTRY_PROXY)) {
      continue;
    }
    const scriptName = serviceName.replace(/^core:user:/, "");
    for (const [className, classInfo] of classMap) {
      const uniqueKey = `${scriptName}-${className}`;
      IDToBindingName.do[uniqueKey] = {
        className,
        scriptName,
        useSQLite: classInfo.enableSql ?? false,
        binding: `EXPLORER_DO_${uniqueKey}`
      };
    }
  }
  if (workflowOptions) {
    for (const binding of proxyBindings) {
      if (!binding.name?.startsWith(
        `${CoreBindings.DURABLE_OBJECT_NAMESPACE_PROXY}:workflows:`
      )) {
        continue;
      }
      if (!("wrapped" in binding)) {
        continue;
      }
      const [innerBinding] = binding.wrapped?.innerBindings ?? [];
      if (!innerBinding || !("service" in innerBinding)) {
        continue;
      }
      const serviceName = innerBinding.service?.name;
      if (!serviceName?.startsWith("workflows:")) {
        continue;
      }
      const workflowName = serviceName.replace(/^workflows:/, "");
      const workflowOpt = workflowOptions.get(workflowName);
      if (!workflowOpt) {
        continue;
      }
      IDToBindingName.workflows[workflowName] = {
        name: workflowName,
        className: workflowOpt.className,
        scriptName: workflowOpt.scriptName ?? "",
        binding: binding.name,
        engineBinding: `EXPLORER_WORKFLOW_ENGINE_${workflowName}`
      };
    }
  }
  return IDToBindingName;
}
function constructExplorerWorkerOpts(allWorkerOpts, durableObjectClassNames) {
  const result = {};
  for (const workerOpts of allWorkerOpts) {
    const workerName = workerOpts.config.name;
    if (!workerName) {
      continue;
    }
    const bindings = {
      kv: [],
      d1: [],
      r2: [],
      do: [],
      workflows: []
    };
    for (const [bindingName, binding] of getEnvBindingsOfType(
      workerOpts.config,
      "kv"
    )) {
      bindings.kv.push({ id: binding.id ?? bindingName, bindingName });
    }
    for (const [bindingName, binding] of getEnvBindingsOfType(
      workerOpts.config,
      "d1"
    )) {
      bindings.d1.push({ id: binding.id ?? bindingName, bindingName });
    }
    for (const [bindingName, binding] of getEnvBindingsOfType(
      workerOpts.config,
      "r2"
    )) {
      bindings.r2.push({ id: binding.name ?? bindingName, bindingName });
    }
    for (const [bindingName, binding] of getEnvBindingsOfType(
      workerOpts.config,
      "durable-object"
    )) {
      const className = binding.exportName;
      const scriptName = binding.workerName;
      const serviceName = getUserServiceName(scriptName);
      const uniqueKey = `${scriptName}-${className}`;
      const useSqlite = durableObjectClassNames.get(serviceName)?.get(className)?.enableSql ?? false;
      bindings.do.push({
        id: uniqueKey,
        bindingName,
        className,
        scriptName,
        useSqlite
      });
    }
    for (const [bindingName, workflow] of getEnvBindingsOfType(
      workerOpts.config,
      "workflow"
    ) ?? {}) {
      bindings.workflows.push({
        id: workflow.name,
        bindingName,
        className: workflow.exportName,
        scriptName: workflow.workerName ?? workerName
      });
    }
    result[workerName] = bindings;
  }
  return result;
}
function generateWrapperEntry(userEntryName, durableObjectClassNames) {
  const lines = [
    `import { createDurableObjectWrapper } from "./__mf_do_wrapper.js";`,
    `import * as __mf_original__ from "./${userEntryName}";`,
    // Re-export everything from original module
    `export * from "./${userEntryName}";`,
    `export default __mf_original__.default;`
  ];
  for (const className of durableObjectClassNames) {
    lines.push(
      `export const ${className} = createDurableObjectWrapper(__mf_original__.${className});`
    );
  }
  return lines.join("\n");
}
function wrapDurableObjectModules(modules, durableObjectClassNames) {
  const entryModule = modules[0];
  const wrapperEntry = generateWrapperEntry(
    entryModule.name,
    durableObjectClassNames
  );
  return [
    { name: "__mf_do_wrapper_entry.js", esModule: wrapperEntry },
    { name: "__mf_do_wrapper.js", esModule: do_wrapper_worker_default() },
    ...modules
  ];
}

// src/plugins/core/modules.ts
var import_node_assert11 = __toESM(require("node:assert"));
var import_node_path15 = __toESM(require("node:path"));
var import_node_url5 = require("node:url");
var import_node_util4 = require("node:util");
function buildStringScriptPath(workerIndex) {
  return `script-${workerIndex}`;
}
var stringScriptRegexp = /^script-(\d+)$/;
function maybeGetStringScriptPathIndex(scriptPath) {
  const match = stringScriptRegexp.exec(scriptPath);
  return match === null ? void 0 : parseInt(match[1]);
}
function compileModuleRules(rules) {
  const compiledRules = [];
  const finalisedTypes = /* @__PURE__ */ new Set();
  for (const rule of rules) {
    if (finalisedTypes.has(rule.type)) {
      continue;
    }
    compiledRules.push({
      type: rule.type,
      include: globsToRegExps(rule.include, { endAnchor: true })
    });
    if (!rule.fallthrough) {
      finalisedTypes.add(rule.type);
    }
  }
  return compiledRules;
}
function withSourceURL(script, scriptPath) {
  if (script.lastIndexOf("//# sourceURL=") !== -1) return script;
  let scriptURL = scriptPath;
  if (maybeGetStringScriptPathIndex(scriptPath) === void 0) {
    scriptURL = (0, import_node_url5.pathToFileURL)(scriptPath);
  }
  const sourceURL = `
//# sourceURL=${scriptURL}
`;
  return script + sourceURL;
}
function createJavaScriptModule(code, name, modulePath, type) {
  code = withSourceURL(code, modulePath);
  if (type === "ESModule") {
    return { name, esModule: code };
  } else if (type === "CommonJS") {
    return { name, commonJsModule: code };
  }
  const exhaustive = type;
  import_node_assert11.default.fail(`Unreachable: ${exhaustive} JavaScript modules are unsupported`);
}
var encoder = new import_node_util4.TextEncoder();
var decoder = new import_node_util4.TextDecoder();
function contentsToString(contents44) {
  return typeof contents44 === "string" ? contents44 : decoder.decode(contents44);
}
function contentsToArray(contents44) {
  return typeof contents44 === "string" ? encoder.encode(contents44) : contents44;
}
function convertManifestModule(name, type, contents44, rootPath2) {
  const sourcePath = rootPath2 === void 0 ? name : import_node_path15.default.resolve(rootPath2, name);
  switch (type) {
    case "esm":
      return createJavaScriptModule(
        contentsToString(contents44),
        name,
        sourcePath,
        "ESModule"
      );
    case "cjs":
      return createJavaScriptModule(
        contentsToString(contents44),
        name,
        sourcePath,
        "CommonJS"
      );
    case "wasm":
      return { name, wasm: contentsToArray(contents44) };
    case "text":
      return { name, text: contentsToString(contents44) };
    case "data":
      return { name, data: contentsToArray(contents44) };
    case "json":
      return { name, json: contentsToString(contents44) };
    case "python":
      return { name, pythonModule: contentsToString(contents44) };
    case "python-requirement":
      return { name, obsoletePythonRequirement: contentsToString(contents44) };
    case "sourcemap":
      import_node_assert11.default.fail("Unreachable: sourcemap modules are unsupported");
      break;
    default:
      const exhaustive = type;
      import_node_assert11.default.fail(`Unreachable: ${exhaustive} modules are unsupported`);
  }
}

// src/plugins/core/observability.ts
var import_node_fs9 = require("node:fs");

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/observability/collector.worker.ts
var import_fs28 = __toESM(require("fs"));
var import_path28 = __toESM(require("path"));
var import_url28 = __toESM(require("url"));
var contents28;
function collector_worker_default() {
  if (contents28 !== void 0) return contents28;
  const filePath = import_path28.default.join(__dirname, "workers", "observability/collector.worker.js");
  contents28 = import_fs28.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url28.default.pathToFileURL(filePath);
  return contents28;
}

// src/plugins/core/observability.ts
var TRACE_STORE_CLASS_NAME = "TraceStore";
var TRACE_STORE_BINDING = "TRACE_STORE";
var OBSERVABILITY_STORAGE_SERVICE_NAME = "obs:storage";
function getObservabilityServices(tmpPath, resourcePersistencePath) {
  const storagePath = getPersistPath(
    "observability",
    tmpPath,
    resourcePersistencePath
  );
  (0, import_node_fs9.mkdirSync)(storagePath, { recursive: true });
  return [
    {
      name: OBSERVABILITY_STORAGE_SERVICE_NAME,
      disk: { path: storagePath, writable: true }
    },
    {
      // User workers' `streamingTails` references resolve through
      // getUserServiceName(), so register the collector under that same
      // prefixed name.
      name: getUserServiceName(OBSERVABILITY_COLLECTOR_SERVICE_NAME),
      worker: {
        compatibilityDate: "2026-01-01",
        // The collector consumes tails; it isn't tailed itself, so it doesn't
        // need OBSERVABILITY_COMPAT_FLAGS (those go on the user workers).
        compatibilityFlags: ["nodejs_compat"],
        modules: [
          {
            name: "collector.worker.js",
            esModule: collector_worker_default()
          }
        ],
        durableObjectNamespaces: [
          {
            className: TRACE_STORE_CLASS_NAME,
            uniqueKey: "miniflare-wobs-trace-store",
            enableSql: true,
            preventEviction: true
          }
        ],
        durableObjectStorage: { localDisk: OBSERVABILITY_STORAGE_SERVICE_NAME },
        bindings: [
          {
            name: TRACE_STORE_BINDING,
            durableObjectNamespace: { className: TRACE_STORE_CLASS_NAME }
          }
        ]
      }
    }
  ];
}

// src/plugins/core/proxy/client.ts
var import_node_assert14 = __toESM(require("node:assert"));
var import_node_crypto4 = __toESM(require("node:crypto"));
var import_web4 = require("node:stream/web");
var import_node_util5 = __toESM(require("node:util"));
var import_undici7 = require("undici");

// src/plugins/core/proxy/fetch-sync.ts
var import_node_assert13 = __toESM(require("node:assert"));
var import_web2 = require("node:stream/web");
var import_node_worker_threads = require("node:worker_threads");

// src/plugins/core/errors/index.ts
var import_node_fs10 = __toESM(require("node:fs"));
var import_node_path16 = __toESM(require("node:path"));
var import_node_url6 = require("node:url");

// src/plugins/core/errors/sourcemap.ts
var import_node_assert12 = __toESM(require("node:assert"));
var import_node_module = require("node:module");

// src/plugins/core/errors/callsite.ts
function parseStack(stack) {
  return stack.split("\n").slice(1).map(parseCallSite).filter((site) => site !== void 0);
}
function parseCallSite(line) {
  const lineMatch = line.match(
    /at (?:(.+?)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/
  );
  if (!lineMatch) {
    return;
  }
  let object3 = null;
  let method = null;
  let functionName = null;
  let typeName = null;
  let methodName = null;
  const isNative = lineMatch[5] === "native";
  if (lineMatch[1]) {
    functionName = lineMatch[1];
    let methodStart = functionName.lastIndexOf(".");
    if (functionName[methodStart - 1] == ".") methodStart--;
    if (methodStart > 0) {
      object3 = functionName.substring(0, methodStart);
      method = functionName.substring(methodStart + 1);
      const objectEnd = object3.indexOf(".Module");
      if (objectEnd > 0) {
        functionName = functionName.substring(objectEnd + 1);
        object3 = object3.substring(0, objectEnd);
      }
    }
  }
  if (method) {
    typeName = object3;
    methodName = method;
  }
  if (method === "<anonymous>") {
    methodName = null;
    functionName = null;
  }
  return new CallSite({
    typeName,
    functionName,
    methodName,
    fileName: lineMatch[2],
    lineNumber: parseInt(lineMatch[3]) || null,
    columnNumber: parseInt(lineMatch[4]) || null,
    native: isNative
  });
}
var CallSite = class {
  constructor(opts) {
    this.opts = opts;
  }
  opts;
  getScriptHash() {
    throw new Error("Method not implemented.");
  }
  getEnclosingColumnNumber() {
    throw new Error("Method not implemented.");
  }
  getEnclosingLineNumber() {
    throw new Error("Method not implemented.");
  }
  getPosition() {
    throw new Error("Method not implemented.");
  }
  getThis() {
    return null;
  }
  getTypeName() {
    return this.opts.typeName;
  }
  getFunction() {
    return void 0;
  }
  getFunctionName() {
    return this.opts.functionName;
  }
  getMethodName() {
    return this.opts.methodName;
  }
  getFileName() {
    return this.opts.fileName ?? null;
  }
  getScriptNameOrSourceURL() {
    return this.opts.fileName;
  }
  getLineNumber() {
    return this.opts.lineNumber;
  }
  getColumnNumber() {
    return this.opts.columnNumber;
  }
  getEvalOrigin() {
    return void 0;
  }
  isToplevel() {
    return false;
  }
  isEval() {
    return false;
  }
  isNative() {
    return this.opts.native;
  }
  isConstructor() {
    return false;
  }
  isAsync() {
    return false;
  }
  isPromiseAll() {
    return false;
  }
  isPromiseAny() {
    return false;
  }
  getPromiseIndex() {
    return null;
  }
};

// src/plugins/core/errors/sourcemap.ts
function getFreshSourceMapSupport() {
  const realRequire = require.cache ? require : (0, import_node_module.createRequire)(__filename);
  const resolvedSupportPath = realRequire.resolve(
    "@cspotcode/source-map-support"
  );
  const originalSymbolFor = Symbol.for;
  const originalSupport = realRequire.cache[resolvedSupportPath];
  try {
    Symbol.for = (key) => {
      import_node_assert12.default.strictEqual(key, "source-map-support/sharedData");
      return Symbol(key);
    };
    delete realRequire.cache[resolvedSupportPath];
    return realRequire(resolvedSupportPath);
  } finally {
    Symbol.for = originalSymbolFor;
    realRequire.cache[resolvedSupportPath] = originalSupport;
  }
}
var sourceMapInstallBaseOptions = {
  environment: "node",
  // Don't add Node `uncaughtException` handler
  handleUncaughtExceptions: false,
  // Don't hook Node `require` function
  hookRequire: false,
  redirectConflictingLibrary: false,
  // Make sure we're using fresh copies of files (i.e. between `setOptions()`)
  emptyCacheBetweenOperations: true,
  // Always remove existing retrievers when calling `install()`, we should be
  // specifying them each time we want to source map
  overrideRetrieveFile: true,
  overrideRetrieveSourceMap: true
};
var sourceMapper;
function getSourceMapper() {
  if (sourceMapper !== void 0) return sourceMapper;
  const support = getFreshSourceMapSupport();
  const originalPrepareStackTrace = Error.prepareStackTrace;
  support.install(sourceMapInstallBaseOptions);
  const prepareStackTrace = Error.prepareStackTrace;
  (0, import_node_assert12.default)(prepareStackTrace !== void 0);
  Error.prepareStackTrace = originalPrepareStackTrace;
  sourceMapper = (retrieveSourceMap, error101) => {
    support.install({
      ...sourceMapInstallBaseOptions,
      retrieveFile(_file3) {
        return "";
      },
      retrieveSourceMap
    });
    const callSites = parseStack(error101.stack ?? "");
    return prepareStackTrace(error101, callSites);
  };
  return sourceMapper;
}

// src/plugins/core/errors/index.ts
function maybeGetDiskFile(filePath) {
  try {
    const contents44 = import_node_fs10.default.readFileSync(filePath, "utf8");
    return { path: filePath, contents: contents44 };
  } catch (e) {
    if (e.code !== "ENOENT") throw e;
  }
}
function resolvePath(rootPath2, filePath) {
  if (rootPath2 !== void 0 && !import_node_path16.default.isAbsolute(filePath)) {
    return import_node_path16.default.resolve(rootPath2, filePath);
  }
  return import_node_path16.default.resolve(filePath);
}
function maybeGetFile2(allWorkerOpts, fileSpecifier) {
  const maybeUrl = maybeParseURL(fileSpecifier);
  if (maybeUrl !== void 0 && maybeUrl.protocol === "file:") {
    const filePath = (0, import_node_url6.fileURLToPath)(maybeUrl);
    for (const { config: config3, legacy, dev } of allWorkerOpts) {
      if (legacy?.serviceWorkerScriptPath !== void 0 && legacy?.serviceWorkerScript !== void 0 && resolvePath(dev?.rootPath, legacy.serviceWorkerScriptPath) === filePath) {
        return {
          path: filePath,
          contents: legacy.serviceWorkerScript
        };
      }
      const manifest = config3.manifest;
      if (manifest === void 0) continue;
      const modules = manifest.modules;
      for (const [modulePath, module2] of Object.entries(modules)) {
        const resolvedModulePath = import_node_path16.default.resolve(
          manifest.modulesRoot,
          modulePath
        );
        if (resolvedModulePath === filePath) {
          return {
            path: filePath,
            contents: contentsToString(module2.contents)
          };
        }
      }
    }
    return maybeGetDiskFile(filePath);
  }
  const workerIndex = maybeGetStringScriptPathIndex(fileSpecifier);
  if (workerIndex !== void 0) {
    const serviceWorkerScript = allWorkerOpts[workerIndex]?.legacy?.serviceWorkerScript;
    if (serviceWorkerScript !== void 0) {
      return { contents: serviceWorkerScript };
    }
  }
}
function getHeaders(request4) {
  const headers = {};
  for (const [key, value] of request4.headers.entries()) {
    if (headers[key] === void 0) {
      headers[key] = value;
    } else if (typeof headers[key] === "string") {
      headers[key] = [headers[key], value];
    } else {
      headers[key].push(value);
    }
  }
  return headers;
}
function getSourceMappedStack(workerSrcOpts, error101, onSourceMap) {
  function retrieveSourceMap(fileSpecifier) {
    const sourceFile = maybeGetFile2(workerSrcOpts, fileSpecifier);
    if (sourceFile?.path === void 0) return null;
    const sourceMapRegexp = /# sourceMappingURL=(.+)/g;
    const matches = [...sourceFile.contents.matchAll(sourceMapRegexp)];
    if (matches.length === 0) return null;
    const sourceMapMatch = matches[matches.length - 1];
    const root = import_node_path16.default.dirname(sourceFile.path);
    const sourceMapPath = import_node_path16.default.resolve(root, sourceMapMatch[1]);
    const sourceMapFile = maybeGetFile2(
      workerSrcOpts,
      (0, import_node_url6.pathToFileURL)(sourceMapPath).href
    );
    if (sourceMapFile?.path === void 0) return null;
    if (onSourceMap) {
      try {
        const sourcemap = JSON.parse(sourceMapFile.contents);
        const result = onSourceMap(sourcemap, sourceMapFile.path);
        if (result !== void 0) {
          return {
            map: JSON.stringify(result),
            url: sourceMapFile.path
          };
        }
      } catch {
        return null;
      }
    }
    return { map: sourceMapFile.contents, url: sourceMapFile.path };
  }
  try {
    return getSourceMapper()(retrieveSourceMap, error101);
  } catch {
    return error101.stack ?? "";
  }
}
var JsonErrorSchema = external_exports2.lazy(
  () => external_exports2.object({
    message: external_exports2.string().optional(),
    name: external_exports2.string().optional(),
    stack: external_exports2.string().optional(),
    cause: JsonErrorSchema.optional()
  })
);
var ALLOWED_ERROR_SUBCLASS_CONSTRUCTORS = [
  EvalError,
  RangeError,
  ReferenceError,
  SyntaxError,
  TypeError,
  URIError
];
function reviveError(workerSrcOpts, jsonError, onSourceMap) {
  let cause;
  if (jsonError.cause !== void 0) {
    cause = reviveError(workerSrcOpts, jsonError.cause, onSourceMap);
  }
  let ctor = Error;
  if (jsonError.name !== void 0 && jsonError.name in globalThis) {
    const maybeCtor = globalThis[jsonError.name];
    if (ALLOWED_ERROR_SUBCLASS_CONSTRUCTORS.includes(maybeCtor)) {
      ctor = maybeCtor;
    }
  }
  const error101 = new ctor(jsonError.message, { cause });
  if (jsonError.name !== void 0) error101.name = jsonError.name;
  error101.stack = jsonError.stack;
  error101.stack = processStackTrace(
    getSourceMappedStack(workerSrcOpts, error101, onSourceMap),
    (line, location) => !location.includes(".wrangler/tmp") && !location.includes("wrangler/templates/middleware") ? line : null
  );
  return error101;
}
async function handlePrettyErrorRequest(log2, workerSrcOpts, request4, handleUncaughtError) {
  const caught = JsonErrorSchema.parse(await request4.json());
  const sourcesContentMap = /* @__PURE__ */ new Map();
  const error101 = reviveError(
    workerSrcOpts,
    caught,
    (sourceMap, sourceMapPath) => {
      for (let i = 0; i < sourceMap.sources.length; i++) {
        const source = sourceMap.sources[i];
        const sourceContent = sourceMap.sourcesContent?.[i];
        if (sourceContent) {
          const fullSourcePath = import_node_path16.default.resolve(
            import_node_path16.default.dirname(sourceMapPath),
            sourceMap.sourceRoot ?? "",
            source
          );
          sourcesContentMap.set(fullSourcePath, sourceContent);
        }
      }
    }
  );
  log2.error(error101);
  void (async () => handleUncaughtError?.(error101))().catch(
    (callbackError) => log2.error(
      callbackError instanceof Error ? callbackError : new Error(String(callbackError))
    )
  );
  const accept = request4.headers.get("Accept")?.toLowerCase() ?? "";
  const userAgent = request4.headers.get("User-Agent")?.toLowerCase() ?? "";
  const acceptsPrettyError = !userAgent.includes("curl/") && (accept.includes("text/html") || accept.includes("*/*") || accept.includes("text/*"));
  if (!acceptsPrettyError) {
    return new Response3(error101.stack, { status: 500 });
  }
  const { Youch } = require("youch");
  const youch = new Youch();
  youch.defineSourceLoader(async (stackFrame) => {
    if (!stackFrame.fileName) {
      return;
    }
    for (const { legacy, dev } of workerSrcOpts) {
      if (legacy?.serviceWorkerScriptPath !== void 0 && legacy?.serviceWorkerScript !== void 0 && resolvePath(dev?.rootPath, legacy.serviceWorkerScriptPath) === import_node_path16.default.resolve(stackFrame.fileName)) {
        return { contents: legacy.serviceWorkerScript };
      }
    }
    if (stackFrame.type === "native" || stackFrame.fileName.startsWith("cloudflare:") || stackFrame.fileName.startsWith("node:")) {
      stackFrame.type = "native";
      return;
    }
    if (!import_node_fs10.default.existsSync(stackFrame.fileName)) {
      stackFrame.fileType = void 0;
    }
    const workerIndex = maybeGetStringScriptPathIndex(stackFrame.fileName);
    if (workerIndex !== void 0) {
      const serviceWorkerScript = workerSrcOpts[workerIndex]?.legacy?.serviceWorkerScript;
      if (serviceWorkerScript !== void 0) {
        return { contents: serviceWorkerScript };
      }
    }
    const sourcesContent = sourcesContentMap.get(stackFrame.fileName);
    if (sourcesContent) {
      return { contents: sourcesContent };
    }
    try {
      const contents44 = import_node_fs10.default.readFileSync(stackFrame.fileName, {
        encoding: "utf8"
      });
      return { contents: contents44 };
    } catch {
      return;
    }
  });
  youch.useTransformer((error102) => {
    error102.hint = [
      '<a href="https://developers.cloudflare.com/workers/" target="_blank" style="text-decoration:none;font-style:normal;padding:5px">\u{1F4DA} Workers Docs</a>',
      '<a href="https://discord.cloudflare.com" target="_blank" style="text-decoration:none;font-style: normal;padding:5px">\u{1F4AC} Workers Discord</a>'
    ].join("");
  });
  let html;
  try {
    html = await youch.toHTML(error101, {
      request: {
        url: `${request4.cf?.prettyErrorOriginalUrl ?? request4.url}`,
        method: request4.method,
        headers: getHeaders(request4)
      }
    });
  } catch {
    return new Response3(error101.stack, { status: 500 });
  }
  return new Response3(html, {
    status: 500,
    headers: { "Content-Type": "text/html;charset=utf-8" }
  });
}

// src/plugins/core/proxy/fetch-sync.ts
var DECODER = new TextDecoder();
var WORKER_SCRIPT = (
  /* javascript */
  `
const { createRequire } = require("module");
const { workerData } = require("worker_threads");

// Not using parentPort here so we can call receiveMessageOnPort() in host
const { notifyHandle, port, filename } = workerData;

// When running Miniflare from Jest, regular 'require("undici")' will fail here
// with "Error: Cannot find module 'undici'". Instead we need to create a
// 'require' using the '__filename' of the host... :(
const actualRequire = createRequire(filename);
const { Pool, fetch } = actualRequire("undici");

let dispatcherUrl;
let dispatcher;

port.addEventListener("message", async (event) => {
  const { id, method, url, headers, body } = event.data;
  try {
    if (dispatcherUrl !== url) {
      dispatcherUrl = url;
      dispatcher = new Pool(new URL(url).origin, {
        connect: { rejectUnauthorized: false },
              // Disable timeouts for local dev \u2014 long-running responses (streaming,
      // slow uploads, long-polling) should not be killed by undici defaults.
      headersTimeout: 0,
      bodyTimeout: 0,
      });
    }
    headers["${CoreHeaders.OP_SYNC}"] = "true";
    // body cannot be a ReadableStream, so no need to specify duplex
    const response = await fetch(url, { method, headers, body, dispatcher });
    const responseBody = response.headers.get("${CoreHeaders.OP_RESULT_TYPE}") === "ReadableStream"
      ? response.body
      : await response.arrayBuffer();
    const transferList = responseBody === null ? undefined : [responseBody];
    port.postMessage(
      {
        id,
        response: {
          status: response.status,
          headers: Object.fromEntries(response.headers),
          body: responseBody,
        }
      },
      transferList
    );
  } catch (error) {
    try {
      port.postMessage({ id, error });
    } catch {
      // If error failed to serialise, post simplified version
      port.postMessage({ id, error: new Error(String(error)) });
    }
  } finally {
    Atomics.store(notifyHandle, /* index */ 0, /* value */ 1);
    Atomics.notify(notifyHandle, /* index */ 0);
  }
});

port.start();
`
);
var SynchronousFetcher = class {
  #channel;
  #notifyHandle;
  #worker;
  #nextId = 0;
  constructor() {
    this.#channel = new import_node_worker_threads.MessageChannel();
    this.#notifyHandle = new Int32Array(new SharedArrayBuffer(4));
  }
  #ensureWorker() {
    if (this.#worker !== void 0) return;
    this.#worker = new import_node_worker_threads.Worker(WORKER_SCRIPT, {
      eval: true,
      workerData: {
        notifyHandle: this.#notifyHandle,
        port: this.#channel.port2,
        filename: __filename
      },
      transferList: [this.#channel.port2]
    });
  }
  fetch(url46, init3) {
    this.#ensureWorker();
    Atomics.store(
      this.#notifyHandle,
      /* index */
      0,
      /* value */
      0
    );
    const id = this.#nextId++;
    this.#channel.port1.postMessage({
      id,
      method: init3.method,
      url: url46.toString(),
      headers: init3.headers,
      body: init3.body
    });
    Atomics.wait(
      this.#notifyHandle,
      /* index */
      0,
      /* value */
      0
    );
    const message = (0, import_node_worker_threads.receiveMessageOnPort)(
      this.#channel.port1
    )?.message;
    (0, import_node_assert13.default)(message?.id === id);
    if ("response" in message) {
      const { status: status2, headers: rawHeaders, body } = message.response;
      const headers = new import_undici5.Headers(rawHeaders);
      const stack = headers.get(CoreHeaders.ERROR_STACK);
      if (status2 === 500 && stack !== null && body !== null) {
        (0, import_node_assert13.default)(!(body instanceof import_web2.ReadableStream));
        const caught = JsonErrorSchema.parse(JSON.parse(DECODER.decode(body)));
        throw reviveError([], caught);
      }
      return { status: status2, headers, body };
    } else {
      throw message.error;
    }
  }
  async dispose() {
    await this.#worker?.terminate();
  }
};

// src/plugins/core/proxy/types.ts
var import_node_buffer5 = require("node:buffer");
var import_consumers = require("node:stream/consumers");
var import_web3 = require("node:stream/web");
var import_undici6 = require("undici");
var NODE_PLATFORM_IMPL = {
  // Node's implementation of these classes don't quite match Workers',
  // but they're close enough for us
  Blob: import_node_buffer5.Blob,
  File,
  Headers: import_undici6.Headers,
  Request,
  Response: Response3,
  isReadableStream(value) {
    return value instanceof import_web3.ReadableStream;
  },
  bufferReadableStream(stream) {
    return (0, import_consumers.arrayBuffer)(stream);
  },
  unbufferReadableStream(buffer) {
    return new import_node_buffer5.Blob([new Uint8Array(buffer)]).stream();
  }
};

// src/plugins/core/proxy/client.ts
var kAddress = /* @__PURE__ */ Symbol("kAddress");
var kName = /* @__PURE__ */ Symbol("kName");
var kIsFunction = /* @__PURE__ */ Symbol("kIsFunction");
function isNativeTarget(value) {
  return typeof value === "object" && value !== null && kAddress in value && kIsFunction in value;
}
var TARGET_GLOBAL = {
  [kAddress]: ProxyAddresses.GLOBAL,
  [kName]: "global",
  [kIsFunction]: false
};
var TARGET_ENV = {
  [kAddress]: ProxyAddresses.ENV,
  [kName]: "env",
  [kIsFunction]: false
};
var reducers = {
  ...structuredSerializableReducers,
  ...createHTTPReducers(NODE_PLATFORM_IMPL),
  Native(value) {
    if (isNativeTarget(value))
      return [value[kAddress], value[kName], value[kIsFunction]];
  }
};
var revivers = {
  ...structuredSerializableRevivers,
  ...createHTTPRevivers(NODE_PLATFORM_IMPL)
  // `Native` reviver depends on `ProxyStubHandler` methods
};
var PROXY_SECRET = import_node_crypto4.default.randomBytes(16);
var PROXY_SECRET_HEX = PROXY_SECRET.toString("hex");
function isClientError(status2) {
  return 400 <= status2 && status2 < 500;
}
var ProxyClient = class {
  #bridge;
  constructor(runtimeEntryURL, dispatchFetch) {
    this.#bridge = new ProxyClientBridge(
      new URL(CorePaths.PLATFORM_PROXY, runtimeEntryURL),
      dispatchFetch
    );
  }
  // Lazily initialise proxies as required
  #globalProxy;
  #envProxy;
  get global() {
    return this.#globalProxy ??= this.#bridge.getProxy(TARGET_GLOBAL);
  }
  get env() {
    return this.#envProxy ??= this.#bridge.getProxy(TARGET_ENV);
  }
  poisonProxies() {
    this.#bridge.poisonProxies();
    this.#globalProxy = void 0;
    this.#envProxy = void 0;
  }
  setRuntimeEntryURL(runtimeEntryURL) {
    this.#bridge.url = new URL(CorePaths.PLATFORM_PROXY, runtimeEntryURL);
  }
  dispose() {
    return this.#bridge.dispose();
  }
};
var ProxyClientBridge = class {
  constructor(url46, dispatchFetch) {
    this.url = url46;
    this.dispatchFetch = dispatchFetch;
    this.#finalizationRegistry = new FinalizationRegistry(this.#finalizeProxy);
  }
  url;
  dispatchFetch;
  // Each proxy stub is initialised with the version stored here. Whenever
  // `poisonProxies()` is called, this version is incremented. Before the
  // proxy makes any request to `workerd`, it checks the version number here
  // matches its own internal version, and throws if not.
  #version = 0;
  // Whenever the `ProxyServer` returns a native target, it adds a strong
  // reference to the "heap" in the singleton object. This prevents the object
  // being garbage collected. To solve this, we register the native target
  // proxies on the client in a `FinalizationRegistry`. When the proxies get
  // garbage collected, we let the `ProxyServer` know it can release the strong
  // "heap" reference, as we'll never be able to access it again. Importantly,
  // we need to unregister all proxies from the registry when we poison them,
  // as the references will be invalid, and a new object with the same address
  // may be added to the "heap".
  #finalizationRegistry;
  // Garbage collection passes will free lots of objects at once. Rather than
  // sending a `DELETE` request for each address, we batch finalisations within
  // 100ms of each other into one request. This ensures we don't create *lots*
  // of TCP connections to `workerd` in `dispatchFetch()` for all the concurrent
  // requests.
  #finalizeBatch = [];
  #finalizeBatchTimeout;
  sync = new SynchronousFetcher();
  get version() {
    return this.#version;
  }
  #finalizeProxy = (held) => {
    this.#finalizeBatch.push(held);
    clearTimeout(this.#finalizeBatchTimeout);
    this.#finalizeBatchTimeout = setTimeout(this.#finalizeProxyBatch, 100);
  };
  #finalizeProxyBatch = async () => {
    const addresses = [];
    for (const held of this.#finalizeBatch.splice(0)) {
      if (held.version === this.#version) addresses.push(held.address);
    }
    if (addresses.length === 0) return;
    try {
      await this.dispatchFetch(this.url, {
        method: "DELETE",
        headers: {
          [CoreHeaders.OP_SECRET]: PROXY_SECRET_HEX,
          [CoreHeaders.OP]: ProxyOps.FREE,
          [CoreHeaders.OP_TARGET]: addresses.join(",")
        }
      });
    } catch {
    }
  };
  getProxy(target) {
    const handler = new ProxyStubHandler(this, target);
    let proxyTarget;
    if (target[kIsFunction]) {
      proxyTarget = new Function();
    } else {
      proxyTarget = {};
    }
    proxyTarget[import_node_util5.default.inspect.custom] = handler.inspect;
    const proxy = new Proxy(proxyTarget, handler);
    const held = {
      address: target[kAddress],
      version: this.#version
    };
    this.#finalizationRegistry.register(proxy, held, this);
    return proxy;
  }
  poisonProxies() {
    this.#version++;
    this.#finalizationRegistry.unregister(this);
  }
  dispose() {
    clearTimeout(this.#finalizeBatchTimeout);
    this.poisonProxies();
    return this.sync.dispose();
  }
};
var ProxyStubHandler = class extends Function {
  constructor(bridge, target) {
    super();
    this.bridge = bridge;
    this.target = target;
    this.#version = bridge.version;
    this.#stringifiedTarget = stringify3(this.target, reducers);
  }
  bridge;
  target;
  #version;
  #stringifiedTarget;
  #knownValues = /* @__PURE__ */ new Map();
  #knownDescriptors = /* @__PURE__ */ new Map();
  #knownOwnKeys;
  revivers = {
    ...revivers,
    Native: (value) => {
      (0, import_node_assert14.default)(Array.isArray(value));
      const [address, name, isFunction] = value;
      (0, import_node_assert14.default)(typeof address === "number");
      (0, import_node_assert14.default)(typeof name === "string");
      (0, import_node_assert14.default)(typeof isFunction === "boolean");
      const target = {
        [kAddress]: address,
        [kName]: name,
        [kIsFunction]: isFunction
      };
      if (name === "Promise") {
        const resPromise = this.bridge.dispatchFetch(this.bridge.url, {
          method: "POST",
          headers: {
            [CoreHeaders.OP_SECRET]: PROXY_SECRET_HEX,
            [CoreHeaders.OP]: ProxyOps.GET,
            // GET without key just gets target
            [CoreHeaders.OP_TARGET]: stringify3(target, reducers)
          }
        });
        return this.#parseAsyncResponse(resPromise);
      } else {
        if (name === "ImagesBindingImpl") {
          return this.#createMediaProxy(target);
        }
        return this.bridge.getProxy(target);
      }
    }
  };
  /**
   * Images bindings are some of the most complex bindings from an API perspective, other than RPC. In particular, they expose a _synchronous_ API that accepts ReadableStream arguments.
   * Multiple synchronous APIs are chained together in a builder pattern (e.g. `await env.IMAGES.input(stream).transform(...).output(...)`) before the final `.output()` call is awaited.
   * This breaks our assumptions around functions that accept ReadableStream arguments always being async, and so doesn't work without some special casing.
   *
   * Ref: https://developers.cloudflare.com/images/transform-images/bindings/
   */
  #createMediaProxy(target) {
    const transformer = (target2, stream, operations) => {
      return {
        transform: (transform3) => {
          return transformer(target2, stream, [
            ...operations,
            { type: "transform", arguments: [transform3] }
          ]);
        },
        draw: (image, options) => {
          return transformer(target2, stream, [
            ...operations,
            { type: "draw", arguments: [image, options] }
          ]);
        },
        output: async (options) => {
          return await target2.input(stream, operations, options);
        }
      };
    };
    const proxy = this.bridge.getProxy(target);
    const binding = {
      info: (stream) => {
        return proxy["info"](stream);
      },
      input: (stream) => {
        return transformer(proxy, stream, []);
      },
      get hosted() {
        return proxy["hosted"];
      }
    };
    return binding;
  }
  get #poisoned() {
    return this.#version !== this.bridge.version;
  }
  #assertSafe() {
    if (this.#poisoned) {
      throw new Error(
        "Attempted to use poisoned stub. Stubs to runtime objects must be re-created after calling `Miniflare#setOptions()` or `Miniflare#dispose()`."
      );
    }
  }
  inspect = (depth, options) => {
    const details = { name: this.target[kName], poisoned: this.#poisoned };
    return `ProxyStub ${import_node_util5.default.inspect(details, options)}`;
  };
  #maybeThrow(res, result, caller) {
    if (res.status === 500) {
      if (typeof result === "object" && result !== null) {
        Error.captureStackTrace(result, caller);
      }
      throw result;
    } else {
      (0, import_node_assert14.default)(res.status === 200);
      return result;
    }
  }
  async #parseAsyncResponse(resPromise) {
    const res = await resPromise;
    (0, import_node_assert14.default)(!isClientError(res.status));
    const typeHeader = res.headers.get(CoreHeaders.OP_RESULT_TYPE);
    if (typeHeader === "Promise, ReadableStream") return res.body;
    (0, import_node_assert14.default)(typeHeader === "Promise");
    let stringifiedResult;
    let unbufferedStream;
    const stringifiedSizeHeader = res.headers.get(
      CoreHeaders.OP_STRINGIFIED_SIZE
    );
    if (stringifiedSizeHeader === null) {
      stringifiedResult = await res.text();
    } else {
      const stringifiedSize = parseInt(stringifiedSizeHeader);
      (0, import_node_assert14.default)(!Number.isNaN(stringifiedSize));
      (0, import_node_assert14.default)(res.body !== null);
      const [buffer, rest] = await readPrefix(res.body, stringifiedSize);
      stringifiedResult = buffer.toString();
      unbufferedStream = rest.pipeThrough(new import_web4.TransformStream());
    }
    const result = parseWithReadableStreams(
      NODE_PLATFORM_IMPL,
      { value: stringifiedResult, unbufferedStream },
      this.revivers
    );
    return this.#maybeThrow(res, result, this.#parseAsyncResponse);
  }
  #parseSyncResponse(syncRes, caller) {
    (0, import_node_assert14.default)(!isClientError(syncRes.status));
    (0, import_node_assert14.default)(syncRes.body !== null);
    (0, import_node_assert14.default)(syncRes.headers.get(CoreHeaders.OP_STRINGIFIED_SIZE) === null);
    if (syncRes.body instanceof import_web4.ReadableStream) return syncRes.body;
    const stringifiedResult = DECODER.decode(syncRes.body);
    const result = parseWithReadableStreams(
      NODE_PLATFORM_IMPL,
      { value: stringifiedResult },
      this.revivers
    );
    return this.#maybeThrow(syncRes, result, caller);
  }
  #thisFnKnownAsync = false;
  apply(_target, ...args) {
    const result = this.#call(
      "__miniflareWrappedFunction",
      this.#thisFnKnownAsync,
      args[1],
      this
    );
    if (!this.#thisFnKnownAsync && result instanceof Promise) {
      this.#thisFnKnownAsync = true;
    }
    return result;
  }
  get(_target, key, _receiver) {
    this.#assertSafe();
    if (key === kAddress) return this.target[kAddress];
    if (key === kName) return this.target[kName];
    if (key === kIsFunction) return this.target[kIsFunction];
    if (typeof key === "symbol" || key === "then") return void 0;
    const maybeKnown = this.#knownValues.get(key);
    if (maybeKnown !== void 0) return maybeKnown;
    const syncRes = this.bridge.sync.fetch(this.bridge.url, {
      method: "POST",
      headers: {
        [CoreHeaders.OP_SECRET]: PROXY_SECRET_HEX,
        [CoreHeaders.OP]: ProxyOps.GET,
        [CoreHeaders.OP_TARGET]: this.#stringifiedTarget,
        [CoreHeaders.OP_KEY]: key
      }
    });
    let result;
    if (syncRes.headers.get(CoreHeaders.OP_RESULT_TYPE) === "Function") {
      result = this.#createFunction(key);
    } else {
      result = this.#parseSyncResponse(syncRes, this.get);
    }
    if (
      // Optimisation: if this property is a function, we assume constant
      // prototypes of proxied objects, so it's never going to change
      typeof result === "function" || // Optimisation: if this property is a reference, we assume it's never
      // going to change. This allows us to reuse the known cache of nested
      // objects on multiple access (e.g. reusing `env["...<bucket>"]` proxy if
      // `getR2Bucket(<bucket>)` is called on the same bucket multiple times).
      isNativeTarget(result) || // Once a `ReadableStream` sent across proxy, we won't be able to read it
      // again in the server, so reuse the same stream for future accesses
      // (e.g. accessing `R2ObjectBody#body` multiple times)
      result instanceof import_web4.ReadableStream
    ) {
      this.#knownValues.set(key, result);
    }
    return result;
  }
  has(target, key) {
    return this.get(target, key, void 0) !== void 0;
  }
  getOwnPropertyDescriptor(target, key) {
    this.#assertSafe();
    if (typeof key === "symbol") return void 0;
    const maybeKnown = this.#knownDescriptors.get(key);
    if (maybeKnown !== void 0) return maybeKnown;
    const syncRes = this.bridge.sync.fetch(this.bridge.url, {
      method: "POST",
      headers: {
        [CoreHeaders.OP_SECRET]: PROXY_SECRET_HEX,
        [CoreHeaders.OP]: ProxyOps.GET_OWN_DESCRIPTOR,
        [CoreHeaders.OP_KEY]: key,
        [CoreHeaders.OP_TARGET]: this.#stringifiedTarget
      }
    });
    const result = this.#parseSyncResponse(
      syncRes,
      this.getOwnPropertyDescriptor
    );
    this.#knownDescriptors.set(key, result);
    return result;
  }
  ownKeys(_target) {
    this.#assertSafe();
    if (this.#knownOwnKeys !== void 0) return this.#knownOwnKeys;
    const syncRes = this.bridge.sync.fetch(this.bridge.url, {
      method: "POST",
      headers: {
        [CoreHeaders.OP_SECRET]: PROXY_SECRET_HEX,
        [CoreHeaders.OP]: ProxyOps.GET_OWN_KEYS,
        [CoreHeaders.OP_TARGET]: this.#stringifiedTarget
      }
    });
    const result = this.#parseSyncResponse(syncRes, this.ownKeys);
    this.#knownOwnKeys = result;
    return result;
  }
  getPrototypeOf(_target) {
    this.#assertSafe();
    return null;
  }
  #createFunction(key) {
    let knownAsync = false;
    const func = {
      [key]: (...args) => {
        const result = this.#call(key, knownAsync, args, func);
        if (!knownAsync && result instanceof Promise) knownAsync = true;
        return result;
      }
    }[key];
    return func;
  }
  #call(key, knownAsync, args, caller) {
    this.#assertSafe();
    const targetName = this.target[kName];
    if (isFetcherFetch(targetName, key)) return this.#fetcherFetchCall(args);
    const stringified = stringifyWithStreams(
      NODE_PLATFORM_IMPL,
      args,
      reducers,
      /* allowUnbufferedStream */
      true
    );
    if (knownAsync || // Durable Object stub RPC calls should always be async to avoid blocking
    // the Node.js event loop with `Atomics.wait()`. This allows Promise.race()
    // and timeouts to work correctly when racing against DO method calls.
    isDurableObjectStub(targetName) || // We assume every call with `ReadableStream`/`Blob` arguments is async.
    // Note that you can't consume `ReadableStream`/`Blob` synchronously: if
    // you tried a similar trick to `SynchronousFetcher`, blocking the main
    // thread with `Atomics.wait()` would prevent chunks being read. This
    // assumption doesn't hold for `Blob`s and `FormData#{append,set}()`, but
    // we should never expose proxies for those APIs to users.
    stringified instanceof Promise || // (instanceof Promise if buffered `ReadableStream`/`Blob`s)
    stringified.unbufferedStream !== void 0) {
      return this.#asyncCall(key, stringified);
    } else {
      const result = this.#syncCall(key, stringified.value, caller);
      if (isR2ObjectWriteHttpMetadata(targetName, key)) {
        const arg = args[0];
        (0, import_node_assert14.default)(arg instanceof import_undici7.Headers);
        (0, import_node_assert14.default)(result instanceof import_undici7.Headers);
        for (const [key2, value] of result) arg.set(key2, value);
        return;
      }
      return result;
    }
  }
  #syncCall(key, stringifiedValue, caller) {
    const argsSize = Buffer.byteLength(stringifiedValue).toString();
    const syncRes = this.bridge.sync.fetch(this.bridge.url, {
      method: "POST",
      headers: {
        [CoreHeaders.OP_SECRET]: PROXY_SECRET_HEX,
        [CoreHeaders.OP]: ProxyOps.CALL,
        [CoreHeaders.OP_TARGET]: this.#stringifiedTarget,
        [CoreHeaders.OP_KEY]: key,
        [CoreHeaders.OP_STRINGIFIED_SIZE]: argsSize,
        "Content-Length": argsSize
      },
      body: stringifiedValue
    });
    return this.#parseSyncResponse(syncRes, caller);
  }
  async #asyncCall(key, stringifiedAwaitable) {
    const stringified = await stringifiedAwaitable;
    let resPromise;
    if (stringified.unbufferedStream === void 0) {
      const argsSize = Buffer.byteLength(stringified.value).toString();
      resPromise = this.bridge.dispatchFetch(this.bridge.url, {
        method: "POST",
        headers: {
          [CoreHeaders.OP_SECRET]: PROXY_SECRET_HEX,
          [CoreHeaders.OP]: ProxyOps.CALL,
          [CoreHeaders.OP_TARGET]: this.#stringifiedTarget,
          [CoreHeaders.OP_KEY]: key,
          [CoreHeaders.OP_STRINGIFIED_SIZE]: argsSize,
          "Content-Length": argsSize
        },
        body: stringified.value
      });
    } else {
      const encodedArgs = Buffer.from(stringified.value);
      const argsSize = encodedArgs.byteLength.toString();
      const body = prefixStream(encodedArgs, stringified.unbufferedStream);
      resPromise = this.bridge.dispatchFetch(this.bridge.url, {
        method: "POST",
        headers: {
          [CoreHeaders.OP_SECRET]: PROXY_SECRET_HEX,
          [CoreHeaders.OP]: ProxyOps.CALL,
          [CoreHeaders.OP_TARGET]: this.#stringifiedTarget,
          [CoreHeaders.OP_KEY]: key,
          [CoreHeaders.OP_STRINGIFIED_SIZE]: argsSize
        },
        duplex: "half",
        body
      });
    }
    return this.#parseAsyncResponse(resPromise);
  }
  #fetcherFetchCall(args) {
    const userRequest = new Request(...args);
    const request4 = new Request(this.bridge.url, userRequest);
    request4.headers.set(CoreHeaders.OP_ORIGINAL_URL, userRequest.url);
    request4.headers.set(CoreHeaders.OP_SECRET, PROXY_SECRET_HEX);
    request4.headers.set(CoreHeaders.OP, ProxyOps.CALL);
    request4.headers.set(CoreHeaders.OP_TARGET, this.#stringifiedTarget);
    request4.headers.set(CoreHeaders.OP_KEY, "fetch");
    return this.bridge.dispatchFetch(request4);
  }
};

// src/plugins/core/node-compat.ts
function getNodeCompat(compatibilityDate = "2000-01-01", compatibilityFlags) {
  const {
    hasNodejsAlsFlag,
    hasNodejsCompatFlag,
    hasNoNodejsCompatFlag,
    hasNodejsCompatV2Flag,
    hasNoNodejsCompatV2Flag,
    hasExperimentalNodejsCompatV2Flag
  } = parseNodeCompatibilityFlags(compatibilityFlags);
  const { isNodejsCompatEnabled, isNodejsCompatV2Enabled } = resolveNodejsCompat(compatibilityDate, compatibilityFlags);
  let mode = null;
  if (isNodejsCompatV2Enabled) {
    mode = "v2";
  } else if (isNodejsCompatEnabled) {
    mode = "v1";
  } else if (hasNodejsAlsFlag) {
    mode = "als";
  }
  return {
    mode,
    // Whether workerd will enable the `nodejs_compat`/`nodejs_compat_v2`
    // features, accounting for both the flags and the compatibility date.
    isNodejsCompatEnabled,
    isNodejsCompatV2Enabled,
    // Whether each flag was explicitly specified.
    hasNodejsAlsFlag,
    hasNodejsCompatFlag,
    hasNoNodejsCompatFlag,
    hasNodejsCompatV2Flag,
    hasNoNodejsCompatV2Flag,
    hasExperimentalNodejsCompatV2Flag
  };
}
function parseNodeCompatibilityFlags(compatibilityFlags) {
  return {
    hasNodejsAlsFlag: compatibilityFlags.includes("nodejs_als"),
    hasNodejsCompatFlag: compatibilityFlags.includes("nodejs_compat"),
    hasNoNodejsCompatFlag: compatibilityFlags.includes("no_nodejs_compat"),
    hasNodejsCompatV2Flag: compatibilityFlags.includes("nodejs_compat_v2"),
    hasNoNodejsCompatV2Flag: compatibilityFlags.includes("no_nodejs_compat_v2"),
    hasExperimentalNodejsCompatV2Flag: compatibilityFlags.includes(
      "experimental:nodejs_compat_v2"
    )
  };
}

// src/plugins/core/index.ts
var trustedCertificates = process.platform === "win32" ? Array.from(import_node_tls.default.rootCertificates) : [];
if (process.env.NODE_EXTRA_CA_CERTS !== void 0) {
  try {
    const extra = (0, import_node_fs11.readFileSync)(process.env.NODE_EXTRA_CA_CERTS, "utf8");
    const certs = extra.match(
      /-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/g
    );
    if (certs !== null) {
      trustedCertificates.push(...certs);
    }
  } catch {
  }
}
var encoder2 = new import_node_util6.TextEncoder();
var WorkerdStructuredLogSchema = external_exports2.object({
  timestamp: external_exports2.number(),
  level: external_exports2.string(),
  message: external_exports2.string()
});
var CORE_PLUGIN_NAME2 = "core";
var SCRIPT_CUSTOM_FETCH_SERVICE = `addEventListener("fetch", (event) => {
  const request = new Request(event.request);
  request.headers.set("${CoreHeaders.CUSTOM_FETCH_SERVICE}", ${CoreBindings.TEXT_CUSTOM_SERVICE});
  request.headers.set("${CoreHeaders.ORIGINAL_URL}", request.url);
  event.respondWith(${CoreBindings.SERVICE_LOOPBACK}.fetch(request));
})`;
var SCRIPT_CUSTOM_NODE_SERVICE = `addEventListener("fetch", (event) => {
  const request = new Request(event.request);
  request.headers.set("${CoreHeaders.CUSTOM_NODE_SERVICE}", ${CoreBindings.TEXT_CUSTOM_SERVICE});
  event.respondWith(${CoreBindings.SERVICE_LOOPBACK}.fetch(request));
})`;
function getCustomServiceDesignator(refererName, workerIndex, kind, name, service, dev) {
  let serviceName;
  let entrypoint;
  let props;
  if (service.type === "fetcher") {
    serviceName = getCustomFetchServiceName(workerIndex, kind, name);
  } else if (service.type === "node-handler") {
    serviceName = getCustomNodeServiceName(workerIndex, kind, name);
  } else if (service.type === "network" || service.type === "external" || service.type === "disk") {
    serviceName = getBuiltinServiceName(workerIndex, kind, name);
  } else {
    const remoteProxyConnectionString = getRemoteProxyConnectionString(
      service,
      dev
    );
    if (remoteProxyConnectionString !== void 0) {
      serviceName = `${CORE_PLUGIN_NAME2}:remote-proxy-service:${workerIndex}:${name}`;
      props = buildRemoteProxyProps(remoteProxyConnectionString, name);
    } else if (service.workerName === kCurrentWorker) {
      serviceName = getUserServiceName(refererName);
      entrypoint = service.exportName;
      if (service.props) {
        props = { json: JSON.stringify(service.props) };
      }
    } else {
      serviceName = getUserServiceName(service.workerName);
      entrypoint = service.exportName;
      if (service.props) {
        props = { json: JSON.stringify(service.props) };
      }
    }
  }
  return { name: serviceName, entrypoint, props };
}
function maybeGetCustomServiceService(workerIndex, kind, name, service, dev) {
  if (service.type === "fetcher") {
    return {
      name: getCustomFetchServiceName(workerIndex, kind, name),
      worker: {
        serviceWorkerScript: SCRIPT_CUSTOM_FETCH_SERVICE,
        compatibilityDate: "2022-09-01",
        compatibilityFlags: ["connect_pass_through"],
        bindings: [
          {
            name: CoreBindings.TEXT_CUSTOM_SERVICE,
            text: `${workerIndex}/${kind}${name}`
          },
          WORKER_BINDING_SERVICE_LOOPBACK
        ]
      }
    };
  } else if (service.type === "node-handler") {
    return {
      name: getCustomNodeServiceName(workerIndex, kind, name),
      worker: {
        serviceWorkerScript: SCRIPT_CUSTOM_NODE_SERVICE,
        compatibilityDate: "2022-09-01",
        compatibilityFlags: ["connect_pass_through"],
        bindings: [
          {
            name: CoreBindings.TEXT_CUSTOM_SERVICE,
            text: `${workerIndex}/${kind}${name}`
          },
          WORKER_BINDING_SERVICE_LOOPBACK
        ]
      }
    };
  } else if (service.type === "network" || service.type === "external" || service.type === "disk") {
    const { type, ...rest } = service;
    return {
      name: getBuiltinServiceName(workerIndex, kind, name),
      [type]: rest
    };
  } else if (getRemoteProxyConnectionString(service, dev) !== void 0) {
    return {
      name: `${CORE_PLUGIN_NAME2}:remote-proxy-service:${workerIndex}:${name}`,
      worker: remoteProxyClientWorker()
    };
  }
}
var FALLBACK_COMPATIBILITY_DATE = "2000-01-01";
function validateCompatibilityDate2(compatibilityDate) {
  if (compatibilityDate > getTodaysCompatDate()) {
    throw new MiniflareCoreError(
      "ERR_FUTURE_COMPATIBILITY_DATE",
      `Compatibility date "${compatibilityDate}" is in the future and unsupported`
    );
  }
  return compatibilityDate;
}
function getDevControlBindings(allWorkerOpts) {
  const bindings = /* @__PURE__ */ new Map();
  for (const worker of allWorkerOpts ?? []) {
    const workerName = worker.config.name ?? "";
    const userServiceName = getUserServiceName(workerName);
    for (const [className] of getExportsOfType(
      worker.config,
      "durable-object"
    )) {
      const bindingName = getDevControlDurableObjectBindingName(
        workerName,
        className
      );
      bindings.set(bindingName, {
        name: bindingName,
        durableObjectNamespace: {
          serviceName: userServiceName,
          className
        }
      });
    }
  }
  return Array.from(bindings.values());
}
function getAccessIdentityServiceName(workerIndex) {
  return `access-identity:${workerIndex}`;
}
function getOutboundInterceptorName(workerIndex) {
  return `outbound:${workerIndex}`;
}
function getGlobalOutbound(workerIndex, config3, dev) {
  return dev?.outboundService === void 0 ? void 0 : getCustomServiceDesignator(
    /* referrer */
    config3.name,
    workerIndex,
    "$" /* KNOWN */,
    CUSTOM_SERVICE_KNOWN_OUTBOUND,
    dev.outboundService,
    dev
  );
}
function getTailServiceDesignator(consumer) {
  return {
    name: getUserServiceName(consumer.workerName),
    entrypoint: consumer.entrypoint,
    props: consumer.props !== void 0 ? { json: JSON.stringify(consumer.props) } : void 0
  };
}
function getServiceBindings(config3) {
  return [
    ...getEnvBindingsOfType(config3, "worker"),
    ...getEnvBindingsOfType(config3, "fetcher"),
    ...getEnvBindingsOfType(config3, "node-handler"),
    ...getEnvBindingsOfType(config3, "network"),
    ...getEnvBindingsOfType(config3, "external"),
    ...getEnvBindingsOfType(config3, "disk")
  ];
}
var CORE_PLUGIN = {
  getBindings(options, workerIndex) {
    const { config: config3, legacy, dev } = options;
    const bindings = [];
    for (const [name, binding] of getEnvBindingsOfType(config3, "json")) {
      bindings.push({ name, json: JSON.stringify(binding.value) });
    }
    for (const [name, binding] of getEnvBindingsOfType(config3, "text")) {
      bindings.push({ name, text: binding.value });
    }
    if (legacy?.wasmBindings !== void 0) {
      bindings.push(
        ...Object.entries(legacy.wasmBindings).map(
          ([name, value]) => typeof value === "string" ? import_promises11.default.readFile(import_node_path17.default.resolve(dev.rootPath, value)).then((wasmModule) => ({
            name,
            wasmModule
          })) : { name, wasmModule: value }
        )
      );
    }
    if (legacy?.textBlobBindings !== void 0) {
      bindings.push(
        ...Object.entries(legacy.textBlobBindings).map(
          ([name, blobPath]) => import_promises11.default.readFile(import_node_path17.default.resolve(dev.rootPath, blobPath), "utf8").then((text) => ({ name, text }))
        )
      );
    }
    if (legacy?.dataBlobBindings !== void 0) {
      bindings.push(
        ...Object.entries(legacy.dataBlobBindings).map(
          ([name, value]) => typeof value === "string" ? import_promises11.default.readFile(import_node_path17.default.resolve(dev.rootPath, value)).then((data) => ({
            name,
            data
          })) : { name, data: value }
        )
      );
    }
    for (const [name, service] of getServiceBindings(config3)) {
      bindings.push({
        name,
        service: getCustomServiceDesignator(
          /* referrer */
          config3.name,
          workerIndex,
          "#" /* UNKNOWN */,
          name,
          service,
          dev
        )
      });
    }
    if (dev?.unsafeEvalBinding !== void 0) {
      bindings.push({
        name: dev.unsafeEvalBinding,
        unsafeEval: kVoid
      });
    }
    return Promise.all(bindings);
  },
  async getNodeBindings(options) {
    const { config: config3, legacy, dev } = options;
    const bindingEntries = [];
    for (const [name, binding] of getEnvBindingsOfType(config3, "json")) {
      bindingEntries.push([name, JSON.parse(JSON.stringify(binding.value))]);
    }
    for (const [name, binding] of getEnvBindingsOfType(config3, "text")) {
      bindingEntries.push([name, binding.value]);
    }
    if (legacy?.wasmBindings !== void 0) {
      bindingEntries.push(
        ...Object.entries(legacy.wasmBindings).map(
          ([name, value]) => typeof value === "string" ? import_promises11.default.readFile(import_node_path17.default.resolve(dev.rootPath, value)).then((buffer) => [name, new WebAssembly.Module(buffer)]) : [name, new WebAssembly.Module(value)]
        )
      );
    }
    if (legacy?.textBlobBindings !== void 0) {
      bindingEntries.push(
        ...Object.entries(legacy.textBlobBindings).map(
          ([name, blobPath]) => import_promises11.default.readFile(import_node_path17.default.resolve(dev.rootPath, blobPath), "utf8").then((text) => [name, text])
        )
      );
    }
    if (legacy?.dataBlobBindings !== void 0) {
      bindingEntries.push(
        ...Object.entries(legacy.dataBlobBindings).map(
          ([name, value]) => typeof value === "string" ? import_promises11.default.readFile(import_node_path17.default.resolve(dev.rootPath, value)).then((buffer) => [name, viewToBuffer(buffer)]) : [name, viewToBuffer(value)]
        )
      );
    }
    for (const [name] of getServiceBindings(config3)) {
      bindingEntries.push([name, new ProxyNodeBinding()]);
    }
    return Object.fromEntries(await Promise.all(bindingEntries));
  },
  async getServices({
    // TODO: check if any of this can be simplified by reading from options in here
    options,
    sharedOptions,
    workerBindings,
    workerIndex,
    durableObjectClassNames,
    additionalModules,
    loopbackHost,
    loopbackPort
  }) {
    const { config: config3, dev } = options;
    const workerScript = getWorkerScript(options, workerIndex);
    if ("modules" in workerScript) {
      const subDirs = new Set(
        workerScript.modules.map(({ name }) => import_node_path17.default.posix.dirname(name))
      );
      subDirs.delete(".");
      for (const module2 of additionalModules) {
        workerScript.modules.push(module2);
        for (const subDir of subDirs) {
          const relativePath = import_node_path17.default.posix.relative(subDir, module2.name);
          const relativePathString = JSON.stringify(relativePath);
          workerScript.modules.push({
            name: import_node_path17.default.posix.join(subDir, module2.name),
            // TODO(someday): if we ever have additional modules without
            //  default exports, this may be a problem. For now, our only
            //  additional module is `__STATIC_CONTENT_MANIFEST` so it's fine.
            //  If needed, we could look for instances of `export default` or
            //  `as default` in the module's code as a heuristic.
            esModule: `export * from ${relativePathString}; export { default } from ${relativePathString};`
          });
        }
      }
    }
    const serviceName = getUserServiceName(config3.name);
    const classNames = durableObjectClassNames.get(serviceName);
    const classNamesEntries = Array.from(classNames ?? []);
    const sqliteClasses = classNamesEntries.filter(
      ([, { enableSql }]) => enableSql
    );
    if ((sharedOptions.unsafeLocalExplorer || sharedOptions.unsafeInspectDurableObjects) && // service-format workers are not supported
    "modules" in workerScript && sqliteClasses.length > 0 && "esModule" in workerScript.modules[0]) {
      workerScript.modules = wrapDurableObjectModules(
        workerScript.modules,
        sqliteClasses.map(([className]) => className)
      );
    }
    const compatibilityDate = validateCompatibilityDate2(
      config3.compatibilityDate ?? FALLBACK_COMPATIBILITY_DATE
    );
    const services = [];
    const extensions = [];
    const observabilityEnabled = sharedOptions.unsafeObservability === true && dev?.unsafeRegisterWorker !== false;
    const tailConsumers = observabilityEnabled ? [
      ...config3.tailConsumers ?? [],
      // Pass the worker's name to the collector via binding props. workerd
      // doesn't populate the tail onset's `scriptName` locally, so this is
      // how the collector attributes each captured invocation to its worker
      // (each worker streams to the collector with its own props).
      {
        workerName: OBSERVABILITY_COLLECTOR_SERVICE_NAME,
        streaming: true,
        props: { worker: config3.name }
      }
    ] : config3.tailConsumers ?? [];
    const userFlags = config3.compatibilityFlags ? stripRedundantNodejsCompatFlags(
      compatibilityDate,
      config3.compatibilityFlags
    ) : void 0;
    const existingFlags = userFlags ?? [];
    const compatibilityFlags = observabilityEnabled ? [
      ...existingFlags,
      ...OBSERVABILITY_COMPAT_FLAGS.filter(
        (flag) => !existingFlags.includes(flag)
      )
    ] : userFlags;
    services.push({
      name: serviceName,
      worker: {
        ...workerScript,
        compatibilityDate,
        compatibilityFlags,
        bindings: workerBindings,
        durableObjectNamespaces: classNamesEntries.map(
          ([
            className,
            {
              enableSql,
              unsafeUniqueKey,
              unsafePreventEviction: preventEviction,
              container
            }
          ]) => {
            const uniqueKey = getDurableObjectUniqueKey(
              className,
              config3.name,
              unsafeUniqueKey
            );
            return uniqueKey === void 0 ? {
              className,
              enableSql,
              ephemeralLocal: kVoid,
              preventEviction,
              container
            } : {
              className,
              enableSql,
              uniqueKey,
              preventEviction,
              container
            };
          }
        ),
        durableObjectStorage: classNamesEntries.length === 0 ? void 0 : dev?.unsafeEphemeralDurableObjects ? { inMemory: kVoid } : { localDisk: DURABLE_OBJECTS_STORAGE_SERVICE_NAME },
        globalOutbound: { name: getOutboundInterceptorName(workerIndex) },
        cacheApiOutbound: { name: getCacheServiceName(workerIndex) },
        moduleFallback: dev?.useModuleFallbackService && sharedOptions.unsafeModuleFallbackService !== void 0 ? `${loopbackHost}:${loopbackPort}` : void 0,
        tails: tailConsumers.filter((consumer) => !consumer.streaming).map(getTailServiceDesignator),
        streamingTails: tailConsumers.filter((consumer) => consumer.streaming).map(getTailServiceDesignator),
        containerEngine: getContainerEngine(sharedOptions.containerEngine),
        ...dev?.access ? {
          accessBlobHeader: CoreHeaders.ACCESS_BLOB,
          accessBindingService: {
            name: getAccessIdentityServiceName(workerIndex)
          }
        } : {}
      }
    });
    for (const [name, service] of getServiceBindings(config3)) {
      const maybeService = maybeGetCustomServiceService(
        workerIndex,
        "#" /* UNKNOWN */,
        name,
        service,
        dev
      );
      if (maybeService !== void 0) services.push(maybeService);
    }
    if (dev?.outboundService !== void 0) {
      const maybeService = maybeGetCustomServiceService(
        workerIndex,
        "$" /* KNOWN */,
        CUSTOM_SERVICE_KNOWN_OUTBOUND,
        dev.outboundService,
        dev
      );
      if (maybeService !== void 0) services.push(maybeService);
    }
    {
      const workerName = config3.name || "worker";
      const cfWorkerValue = dev?.zone ?? `${workerName}.example.com`;
      services.push({
        name: getOutboundInterceptorName(workerIndex),
        worker: {
          modules: [
            {
              name: "index.js",
              esModule: outbound_worker_default()
            }
          ],
          compatibilityDate: "2025-01-01",
          compatibilityFlags: ["connect_pass_through", "experimental"],
          bindings: [
            {
              name: "CF_WORKER_ZONE",
              text: cfWorkerValue
            },
            {
              name: "STRIP_CF_CONNECTING_IP",
              json: JSON.stringify(dev?.stripCfConnectingIp ?? true)
            },
            WORKER_BINDING_SERVICE_LOOPBACK
          ],
          globalOutbound: getGlobalOutbound(workerIndex, config3, dev)
        }
      });
    }
    if (dev?.access) {
      services.push({
        name: getAccessIdentityServiceName(workerIndex),
        worker: {
          modules: [
            {
              name: "index.js",
              esModule: access_identity_worker_default()
            }
          ],
          compatibilityDate: "2025-01-01",
          compatibilityFlags: [
            "experimental",
            "service_binding_extra_handlers"
          ]
        }
      });
    }
    return { services, extensions };
  }
};
function getGlobalServices({
  sharedOptions,
  allWorkerRoutes,
  fallbackWorkerName,
  tmpPath,
  log: log2,
  proxyBindings,
  durableObjectClassNames,
  allWorkerOpts
}) {
  const workerNames = [...allWorkerRoutes.keys()];
  const routes = parseRoutes(allWorkerRoutes);
  const serviceEntryBindings = [
    WORKER_BINDING_SERVICE_LOOPBACK,
    // For converting stack-traces to pretty-error pages
    { name: CoreBindings.JSON_ROUTES, json: JSON.stringify(routes) },
    {
      name: CoreBindings.TRIGGER_HANDLERS,
      json: JSON.stringify(!!sharedOptions.unsafeTriggerHandlers)
    },
    {
      name: CoreBindings.LOG_REQUESTS,
      json: JSON.stringify(!!sharedOptions.logRequests)
    },
    { name: CoreBindings.JSON_CF_BLOB, json: JSON.stringify(sharedOptions.cf) },
    { name: CoreBindings.JSON_LOG_LEVEL, json: JSON.stringify(log2.level) },
    {
      name: CoreBindings.SERVICE_USER_FALLBACK,
      service: { name: fallbackWorkerName }
    },
    ...workerNames.map((name) => ({
      name: CoreBindings.SERVICE_USER_ROUTE_PREFIX + name,
      service: { name: getUserServiceName(name) }
    })),
    {
      name: CoreBindings.DURABLE_OBJECT_NAMESPACE_PROXY,
      durableObjectNamespace: { className: "ProxyServer" }
    },
    {
      name: CoreBindings.DATA_PROXY_SECRET,
      data: PROXY_SECRET
    },
    {
      name: CoreBindings.STRIP_DISABLE_PRETTY_ERROR,
      json: JSON.stringify(sharedOptions.stripDisablePrettyError)
    },
    // Add `proxyBindings` here, they'll be added to the `ProxyServer` `env`
    ...proxyBindings,
    // Add cache service binding for purgeCache() API
    {
      name: CoreBindings.SERVICE_CACHE,
      service: { name: getCacheServiceName(0) }
    },
    {
      name: CoreBindings.SERVICE_DEV_CONTROL,
      service: { name: CoreBindings.SERVICE_DEV_CONTROL }
    }
  ];
  if (sharedOptions.unsafeLocalExplorer) {
    serviceEntryBindings.push({
      name: CoreBindings.SERVICE_LOCAL_EXPLORER,
      service: {
        name: SERVICE_LOCAL_EXPLORER
      }
    });
  }
  const streamServiceEnabled = allWorkerOpts?.some(
    (worker) => getEnvBindingsOfType(worker.config, "stream").some(
      ([, binding]) => getRemoteProxyConnectionString(binding, worker.dev) === void 0
    )
  );
  if (streamServiceEnabled) {
    serviceEntryBindings.push({
      name: CoreBindings.SERVICE_STREAM,
      service: {
        name: getUserBindingServiceName(STREAM_PLUGIN_NAME, "service"),
        entrypoint: "StreamBinding"
      }
    });
  }
  const r2PublicService = getR2PublicService(allWorkerOpts ?? []);
  if (r2PublicService !== void 0) {
    serviceEntryBindings.push({
      name: CoreBindings.SERVICE_R2_PUBLIC,
      service: { name: R2_PUBLIC_SERVICE_NAME }
    });
  }
  const r2S3Service = getR2S3Service(allWorkerOpts ?? []);
  if (r2S3Service !== void 0) {
    serviceEntryBindings.push({
      name: CoreBindings.SERVICE_R2_S3,
      service: { name: R2_S3_SERVICE_NAME }
    });
  }
  let imagesServiceName;
  for (const worker of allWorkerOpts ?? []) {
    for (const [name, binding] of getEnvBindingsOfType(
      worker.config,
      "images"
    )) {
      if (getRemoteProxyConnectionString(binding, worker.dev) === void 0) {
        imagesServiceName = getUserBindingServiceName(IMAGES_PLUGIN_NAME, name);
        break;
      }
    }
    if (imagesServiceName !== void 0) {
      break;
    }
  }
  if (imagesServiceName !== void 0) {
    serviceEntryBindings.push({
      name: CoreBindings.SERVICE_IMAGES_DELIVERY,
      service: { name: imagesServiceName }
    });
  }
  if (sharedOptions.upstream !== void 0) {
    serviceEntryBindings.push({
      name: CoreBindings.TEXT_UPSTREAM_URL,
      text: sharedOptions.upstream
    });
  }
  if (sharedOptions.unsafeProxySharedSecret !== void 0) {
    serviceEntryBindings.push({
      name: CoreBindings.DATA_PROXY_SHARED_SECRET,
      data: encoder2.encode(sharedOptions.unsafeProxySharedSecret)
    });
  }
  for (const workerOpt of allWorkerOpts ?? []) {
    const accessOpts = workerOpt.dev?.access;
    if (accessOpts) {
      const accessBlob = { app_aud: accessOpts.aud };
      if (accessOpts.identity) {
        accessBlob.jwt_claims = accessOpts.identity;
      }
      serviceEntryBindings.push({
        name: CoreBindings.JSON_ACCESS_BLOB_PREFIX + workerOpt.config.name,
        json: JSON.stringify(accessBlob)
      });
    }
  }
  serviceEntryBindings.push({
    name: CoreBindings.TEXT_FALLBACK_WORKER_NAME,
    text: workerNames[0] ?? ""
  });
  const services = [
    {
      name: SERVICE_LOOPBACK,
      external: { http: { cfBlobHeader: CoreHeaders.CF_BLOB } }
    },
    {
      name: SERVICE_ENTRY,
      worker: {
        modules: [{ name: "entry.worker.js", esModule: entry_worker_default() }],
        compatibilityDate: "2025-03-17",
        compatibilityFlags: ["nodejs_compat", "service_binding_extra_handlers"],
        bindings: serviceEntryBindings,
        durableObjectNamespaces: [
          {
            className: "ProxyServer",
            uniqueKey: `${SERVICE_ENTRY}-ProxyServer`,
            // `ProxyServer` relies on a singleton object containing of "heap"
            // mapping addresses to native references. If the singleton object
            // were evicted, addresses would be invalidated. Therefore, we
            // prevent eviction to ensure heap addresses stay valid for the
            // lifetime of the `workerd` process
            preventEviction: true
          }
        ],
        // `ProxyServer` doesn't make use of Durable Object storage
        durableObjectStorage: { inMemory: kVoid },
        // Always use the entrypoints cache implementation for proxying. This
        // means if the entrypoint disables caching, proxied cache operations
        // will be no-ops. Note we always require at least one worker to be set.
        cacheApiOutbound: { name: "cache:0" }
      }
    },
    {
      name: CoreBindings.SERVICE_DEV_CONTROL,
      worker: {
        modules: [
          { name: "dev-control.worker.js", esModule: dev_control_worker_default() }
        ],
        compatibilityDate: "2026-07-08",
        compatibilityFlags: ["unsafe_module"],
        bindings: getDevControlBindings(allWorkerOpts)
      }
    },
    {
      name: "internet",
      network: {
        // Allow access to private/public addresses:
        // https://github.com/cloudflare/miniflare/issues/412
        allow: ["public", "private", "240.0.0.0/4"],
        deny: [],
        tlsOptions: {
          trustBrowserCas: true,
          trustedCertificates
        }
      }
    }
  ];
  if (r2PublicService !== void 0) {
    services.push(r2PublicService);
  }
  if (r2S3Service !== void 0) {
    services.push(r2S3Service);
  }
  if (sharedOptions.unsafeLocalExplorer) {
    const localExplorerUiPath = resolveLocalExplorerUi(tmpPath);
    const workflowOptions = /* @__PURE__ */ new Map();
    for (const workerOpts of allWorkerOpts ?? []) {
      for (const [, binding] of getEnvBindingsOfType(
        workerOpts.config,
        "workflow"
      )) {
        workflowOptions.set(binding.name, {
          name: binding.name,
          className: binding.exportName,
          scriptName: binding.workerName
        });
      }
    }
    const IDToBindingMap = constructExplorerBindingMap(
      proxyBindings,
      durableObjectClassNames,
      workflowOptions
    );
    const hasDurableObjects = Object.keys(IDToBindingMap.do).length > 0;
    const explorerWorkerOpts = constructExplorerWorkerOpts(
      allWorkerOpts ?? [],
      durableObjectClassNames
    );
    services.push(
      ...getExplorerServices({
        localExplorerUiPath,
        proxyBindings,
        bindingIdMap: IDToBindingMap,
        hasDurableObjects,
        workerNames,
        explorerWorkerOpts,
        telemetry: sharedOptions.telemetry,
        observabilityEnabled: sharedOptions.unsafeObservability === true
      })
    );
  }
  if (sharedOptions.unsafeObservability) {
    services.push(
      ...getObservabilityServices(
        tmpPath,
        sharedOptions.resourcePersistencePath
      )
    );
  }
  return services;
}
function resolveLocalExplorerUi(tmpPath) {
  const bundledLocalExplorerUiPath = import_node_path17.default.join(
    __dirname,
    "../local-explorer-ui"
  );
  if (!(0, import_node_fs11.existsSync)(bundledLocalExplorerUiPath)) {
    throw new MiniflareCoreError(
      "ERR_MISSING_EXPLORER_UI",
      `Local Explorer UI assets not found at expected path: ${bundledLocalExplorerUiPath}`
    );
  }
  if (!isPathInsideZip(bundledLocalExplorerUiPath)) {
    return bundledLocalExplorerUiPath;
  }
  const localExplorerUiPath = import_node_path17.default.join(
    tmpPath,
    CORE_PLUGIN_NAME2,
    "local-explorer-ui"
  );
  if (!(0, import_node_fs11.existsSync)(localExplorerUiPath)) {
    const localExplorerUiRoot = import_node_path17.default.dirname(localExplorerUiPath);
    const stagedLocalExplorerUiPath = import_node_path17.default.join(
      localExplorerUiRoot,
      `local-explorer-ui-staging-${process.pid}-${Date.now()}`
    );
    (0, import_node_fs11.mkdirSync)(localExplorerUiRoot, { recursive: true });
    try {
      copyDirectorySync(bundledLocalExplorerUiPath, stagedLocalExplorerUiPath);
      (0, import_node_fs11.renameSync)(stagedLocalExplorerUiPath, localExplorerUiPath);
    } catch (error101) {
      removeDirSync(stagedLocalExplorerUiPath);
      throw error101;
    }
  }
  return localExplorerUiPath;
}
function isPathInsideZip(filePath) {
  let currentPath = import_node_path17.default.dirname(filePath);
  while (currentPath !== import_node_path17.default.dirname(currentPath)) {
    if (import_node_path17.default.extname(currentPath) === ".zip") {
      const zipStats = (0, import_node_fs11.statSync)(currentPath, { throwIfNoEntry: false });
      if (zipStats?.isFile()) {
        return true;
      }
    }
    currentPath = import_node_path17.default.dirname(currentPath);
  }
  return false;
}
function copyDirectorySync(sourcePath, destinationPath) {
  (0, import_node_fs11.mkdirSync)(destinationPath, { recursive: true });
  for (const entry of (0, import_node_fs11.readdirSync)(sourcePath)) {
    const sourceEntryPath = import_node_path17.default.join(sourcePath, entry);
    const destinationEntryPath = import_node_path17.default.join(destinationPath, entry);
    const sourceEntryStats = (0, import_node_fs11.statSync)(sourceEntryPath);
    if (sourceEntryStats.isDirectory()) {
      copyDirectorySync(sourceEntryPath, destinationEntryPath);
    } else {
      (0, import_node_fs11.writeFileSync)(destinationEntryPath, (0, import_node_fs11.readFileSync)(sourceEntryPath));
    }
  }
}
function getWorkerScript(options, workerIndex) {
  const { config: config3, legacy } = options;
  if (legacy?.serviceWorkerScript !== void 0) {
    return {
      serviceWorkerScript: withSourceURL(
        legacy.serviceWorkerScript,
        legacy.serviceWorkerScriptPath === void 0 ? buildStringScriptPath(workerIndex) : import_node_path17.default.resolve(options.dev.rootPath, legacy.serviceWorkerScriptPath)
      )
    };
  }
  const manifest = config3.manifest;
  (0, import_node_assert15.default)(manifest !== void 0, "Unreachable: Workers must have code");
  const modulesRoot = import_node_path17.default.resolve(options.dev.rootPath, manifest.modulesRoot);
  const entry = manifest.modules[manifest.mainModule];
  (0, import_node_assert15.default)(
    entry !== void 0,
    `Manifest \`mainModule\` "${manifest.mainModule}" is not present in \`modules\``
  );
  const modules = [
    // workerd uses the first module as the entrypoint, so it must come first.
    convertManifestModule(
      manifest.mainModule,
      entry.type,
      entry.contents,
      modulesRoot
    )
  ];
  for (const [name, module2] of Object.entries(manifest.modules)) {
    if (name === manifest.mainModule) {
      continue;
    }
    if (module2.type === "sourcemap") {
      continue;
    }
    modules.push(
      convertManifestModule(name, module2.type, module2.contents, modulesRoot)
    );
  }
  return { modules };
}
function getContainerEgressInterceptorImage() {
  return process.env.MINIFLARE_CONTAINER_EGRESS_IMAGE ?? DEFAULT_CONTAINER_EGRESS_INTERCEPTOR_IMAGE;
}
function getContainerEngine(engineOrSocketPath) {
  if (!engineOrSocketPath) {
    engineOrSocketPath = process.platform === "win32" ? "//./pipe/docker_engine" : "unix:///var/run/docker.sock";
  }
  const egressImage = getContainerEgressInterceptorImage();
  if (typeof engineOrSocketPath === "string") {
    return {
      localDocker: {
        socketPath: engineOrSocketPath,
        containerEgressInterceptorImage: egressImage
      }
    };
  }
  return {
    localDocker: {
      ...engineOrSocketPath.localDocker,
      containerEgressInterceptorImage: engineOrSocketPath.localDocker.containerEgressInterceptorImage ?? egressImage
    }
  };
}

// src/plugins/assets/constants.ts
var ASSETS_PLUGIN_NAME = "assets";
var ASSETS_SERVICE_NAME = `${ASSETS_PLUGIN_NAME}:assets-service`;
var ROUTER_SERVICE_NAME = `${ASSETS_PLUGIN_NAME}:router`;
var RPC_PROXY_SERVICE_NAME = `${ASSETS_PLUGIN_NAME}:rpc-proxy`;
var ASSETS_KV_SERVICE_NAME = `${ASSETS_PLUGIN_NAME}:kv`;

// src/plugins/assets/index.ts
var tempDirCache = /* @__PURE__ */ new Map();
function resolveAssetDirectory(rootPath2, directory) {
  if (rootPath2 !== void 0 && !import_node_path18.default.isAbsolute(directory)) {
    return import_node_path18.default.resolve(rootPath2, directory);
  }
  return directory;
}
function resolveRouterConfig(config3) {
  const routerConfig = {
    has_user_worker: config3.assets?.hasUserWorker ?? false
  };
  const runWorkerFirst = config3.assets?.runWorkerFirst;
  if (typeof runWorkerFirst === "boolean") {
    routerConfig.invoke_user_worker_ahead_of_assets = runWorkerFirst;
  } else if (Array.isArray(runWorkerFirst)) {
    routerConfig.static_routing = parseStaticRouting(runWorkerFirst);
  }
  return routerConfig;
}
var ASSETS_PLUGIN = {
  bindingTypeDescription: "Assets",
  async getBindings(options) {
    const [assetsBinding] = getEnvBindingsOfType(options.config, "assets");
    if (!assetsBinding) {
      return [];
    }
    const [bindingName] = assetsBinding;
    return [
      {
        // binding between User Worker and Asset Worker
        name: bindingName,
        service: {
          name: `${ASSETS_SERVICE_NAME}:${options.config.name}`
        }
      }
    ];
  },
  async getNodeBindings(options) {
    const [assetsBinding] = getEnvBindingsOfType(options.config, "assets");
    if (!assetsBinding) {
      return {};
    }
    return {
      [assetsBinding[0]]: new ProxyNodeBinding()
    };
  },
  async getServices({ options, log: log2 }) {
    const assets = options.config.assets;
    if (!assets) {
      return [];
    }
    let assetDirectory = resolveAssetDirectory(
      options.dev?.rootPath,
      assets.directory
    );
    const directoryStats = await import_promises12.default.stat(assetDirectory).catch((err) => {
      if (err?.code === "ENOENT") {
        return void 0;
      }
      throw err;
    });
    if (!directoryStats) {
      const cacheKey = `${options.config.name}:${assetDirectory}`;
      const cached3 = tempDirCache.get(cacheKey);
      const cachedExists = cached3 ? await import_promises12.default.stat(cached3).catch(() => void 0) : void 0;
      if (cached3 && cachedExists) {
        assetDirectory = cached3;
      } else {
        assetDirectory = await import_promises12.default.mkdtemp(
          import_node_path18.default.join(import_node_os7.default.tmpdir(), "miniflare-assets-")
        );
        tempDirCache.set(cacheKey, assetDirectory);
      }
    }
    const storageServiceName = `${ASSETS_PLUGIN_NAME}:storage`;
    const storageService = {
      name: storageServiceName,
      disk: {
        path: assetDirectory,
        writable: true,
        allowDotfiles: true
      }
    };
    const { encodedAssetManifest, assetsReverseMap } = await buildAssetManifest(assetDirectory);
    const redirectsFile = (0, import_node_path18.join)(assetDirectory, REDIRECTS_FILENAME);
    const headersFile = (0, import_node_path18.join)(assetDirectory, HEADERS_FILENAME);
    const redirectsContents = maybeGetFile(redirectsFile);
    const headersContents = maybeGetFile(headersFile);
    const assetParserLogger = {
      debug: (message) => log2.debug(message),
      log: (message) => log2.info(message),
      info: (message) => log2.info(message),
      warn: (message) => log2.warn(message),
      error: (error101) => log2.error(error101)
    };
    let parsedRedirects;
    if (redirectsContents !== void 0) {
      const redirects = parseRedirects(redirectsContents, {
        htmlHandling: assets.htmlHandling
      });
      parsedRedirects = RedirectsSchema.parse(
        constructRedirects({
          redirects,
          redirectsFile,
          logger: assetParserLogger
        }).redirects
      );
    }
    let parsedHeaders;
    if (headersContents !== void 0) {
      const headers = parseHeaders(headersContents);
      parsedHeaders = HeadersSchema.parse(
        constructHeaders({
          headers,
          headersFile,
          logger: assetParserLogger
        }).headers
      );
    }
    const routerConfig = resolveRouterConfig(options.config);
    const assetConfig = {
      compatibility_date: options.config.compatibilityDate,
      compatibility_flags: options.config.compatibilityFlags,
      html_handling: assets.htmlHandling,
      not_found_handling: assets.notFoundHandling,
      redirects: parsedRedirects,
      headers: parsedHeaders,
      debug: true,
      has_static_routing: Boolean(routerConfig.static_routing)
    };
    const id = options.config.name;
    const namespaceService = {
      name: `${ASSETS_KV_SERVICE_NAME}:${id}`,
      worker: {
        compatibilityDate: "2023-07-24",
        compatibilityFlags: ["nodejs_compat"],
        modules: [
          {
            name: "assets-kv-worker.mjs",
            esModule: assets_kv_worker_default()
          }
        ],
        bindings: [
          {
            name: SharedBindings.MAYBE_SERVICE_BLOBS,
            service: { name: storageServiceName }
          },
          {
            name: "ASSETS_REVERSE_MAP",
            json: JSON.stringify(assetsReverseMap)
          }
        ]
      }
    };
    const assetService = {
      name: `${ASSETS_SERVICE_NAME}:${id}`,
      worker: {
        // TODO: read these from the wrangler.toml
        compatibilityDate: "2024-07-31",
        compatibilityFlags: ["nodejs_compat", "enable_ctx_exports"],
        modules: [
          {
            name: "asset-worker.mjs",
            esModule: assets_worker_default()
          }
        ],
        bindings: [
          {
            name: "ASSETS_KV_NAMESPACE",
            kvNamespace: {
              name: `${ASSETS_KV_SERVICE_NAME}:${id}`
            }
          },
          {
            name: "ASSETS_MANIFEST",
            data: encodedAssetManifest
          },
          {
            name: "CONFIG",
            json: JSON.stringify(assetConfig)
          }
        ]
      }
    };
    const routerService = {
      name: `${ROUTER_SERVICE_NAME}:${id}`,
      worker: {
        // TODO: read these from the wrangler.toml
        compatibilityDate: "2024-07-31",
        compatibilityFlags: [
          "nodejs_compat",
          "no_nodejs_compat_v2",
          "enable_ctx_exports"
        ],
        modules: [
          {
            name: "router-worker.mjs",
            esModule: router_worker_default()
          }
        ],
        bindings: [
          {
            name: "ASSET_WORKER",
            service: {
              name: `${ASSETS_SERVICE_NAME}:${id}`
            }
          },
          {
            name: "USER_WORKER",
            service: { name: getUserServiceName(id) }
          },
          {
            name: "CONFIG",
            json: JSON.stringify(routerConfig)
          }
        ]
      }
    };
    const assetsProxyService = {
      name: `${RPC_PROXY_SERVICE_NAME}:${id}`,
      worker: {
        compatibilityDate: "2024-08-01",
        compatibilityFlags: ["service_binding_extra_handlers"],
        modules: [
          {
            name: "assets-proxy-worker.mjs",
            esModule: rpc_proxy_worker_default()
          }
        ],
        bindings: [
          {
            name: "ROUTER_WORKER",
            service: {
              name: `${ROUTER_SERVICE_NAME}:${id}`
            }
          },
          {
            name: "USER_WORKER",
            service: {
              name: getUserServiceName(id)
            }
          }
        ]
      }
    };
    return [
      storageService,
      namespaceService,
      assetService,
      routerService,
      assetsProxyService
    ];
  }
};
var buildAssetManifest = async (dir3) => {
  const { manifest, assetsReverseMap } = await walk(dir3);
  const sortedAssetManifest = sortManifest(manifest);
  const encodedAssetManifest = encodeManifest(sortedAssetManifest);
  return { encodedAssetManifest, assetsReverseMap };
};
var walk = async (dir3) => {
  const files = await import_promises12.default.readdir(dir3, { recursive: true });
  const manifest = [];
  const assetsReverseMap = {};
  const { assetsIgnoreFunction } = await createAssetsIgnoreFunction(dir3);
  let counter = 0;
  await Promise.all(
    files.map(async (file5) => {
      if (assetsIgnoreFunction(file5)) {
        return;
      }
      const filepath = import_node_path18.default.join(dir3, file5);
      const relativeFilepath = import_node_path18.default.relative(dir3, filepath);
      const filestat = await import_promises12.default.stat(filepath);
      if (filestat.isSymbolicLink() || filestat.isDirectory()) {
        return;
      } else {
        if (filestat.size > MAX_ASSET_SIZE) {
          throw new Error(
            `Asset too large.
Cloudflare Workers supports assets with sizes of up to ${prettyBytes(
              MAX_ASSET_SIZE,
              {
                binary: true
              }
            )}. We found a file ${filepath} with a size of ${prettyBytes(
              filestat.size,
              {
                binary: true
              }
            )}.
Ensure all assets in your assets directory "${dir3}" conform with the Workers maximum size requirement.`
          );
        }
        const [pathHash, contentHash] = await Promise.all([
          hashPath(normalizeFilePath(relativeFilepath)),
          // used absolute filepath here so that changes to the enclosing asset folder will be registered
          hashPath(filepath + filestat.mtimeMs.toString())
        ]);
        manifest.push({
          pathHash,
          contentHash
        });
        assetsReverseMap[bytesToHex(contentHash)] = {
          filePath: relativeFilepath,
          contentType: getContentType(filepath)
        };
        counter++;
      }
    })
  );
  if (counter > MAX_ASSET_COUNT) {
    throw new Error(
      `Maximum number of assets exceeded.
Cloudflare Workers supports up to ${MAX_ASSET_COUNT.toLocaleString()} assets in a version. We found ${counter.toLocaleString()} files in the specified assets directory "${dir3}".
Ensure your assets directory contains a maximum of ${MAX_ASSET_COUNT.toLocaleString()} files, and that you have specified your assets directory correctly.`
    );
  }
  return { manifest, assetsReverseMap };
};
var sortManifest = (manifest) => {
  return manifest.sort(comparisonFn);
};
var comparisonFn = (a, b) => {
  if (a.pathHash.length < b.pathHash.length) {
    return -1;
  }
  if (a.pathHash.length > b.pathHash.length) {
    return 1;
  }
  for (const [i, v] of a.pathHash.entries()) {
    if (v < b.pathHash[i]) {
      return -1;
    }
    if (v > b.pathHash[i]) {
      return 1;
    }
  }
  return 1;
};
var encodeManifest = (manifest) => {
  const assetManifestBytes = new Uint8Array(
    HEADER_SIZE + manifest.length * ENTRY_SIZE
  );
  for (const [i, entry] of manifest.entries()) {
    const entryOffset = HEADER_SIZE + i * ENTRY_SIZE;
    assetManifestBytes.set(entry.pathHash, entryOffset + PATH_HASH_OFFSET);
    assetManifestBytes.set(
      entry.contentHash,
      entryOffset + CONTENT_HASH_OFFSET
    );
  }
  return assetManifestBytes;
};
var bytesToHex = (buffer) => {
  return [...new Uint8Array(buffer)].map((b) => b.toString(16).padStart(2, "0")).join("");
};
var hashPath = async (path73) => {
  const encoder3 = new TextEncoder();
  const data = encoder3.encode(path73);
  const hashBuffer = await import_node_crypto5.default.subtle.digest(
    "SHA-256",
    data.buffer
  );
  return new Uint8Array(hashBuffer, 0, PATH_HASH_SIZE);
};

// src/plugins/browser-rendering/index.ts
var import_node_fs17 = __toESM(require("node:fs"));
var import_node_path27 = __toESM(require("node:path"));

// ../../node_modules/.pnpm/fast-wrap-ansi@0.1.6/node_modules/fast-wrap-ansi/lib/main.js
var ANSI_ESCAPE_BELL = "\x07";
var ANSI_CSI = "[";
var ANSI_OSC = "]";
var ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;
var GROUP_REGEX = new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`, "y");

// ../../node_modules/.pnpm/@clack+core@1.2.0/node_modules/@clack/core/dist/index.mjs
var import_sisteransi = __toESM(require_src(), 1);
var E = ["up", "down", "left", "right", "space", "enter", "cancel"];
var G = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var u = { actions: new Set(E), aliases: /* @__PURE__ */ new Map([["k", "up"], ["j", "down"], ["h", "left"], ["l", "right"], ["", "cancel"], ["escape", "cancel"]]), messages: { cancel: "Canceled", error: "Something went wrong" }, withGuide: true, date: { monthNames: [...G], messages: { required: "Please enter a valid date", invalidMonth: "There are only 12 months in a year", invalidDay: (r, t) => `There are only ${r} days in ${t}`, afterMin: (r) => `Date must be on or after ${r.toISOString().slice(0, 10)}`, beforeMax: (r) => `Date must be on or before ${r.toISOString().slice(0, 10)}` } } };
var Y = globalThis.process.platform.startsWith("win");

// ../../node_modules/.pnpm/log-update@5.0.1/node_modules/log-update/index.js
var import_node_process5 = __toESM(require("node:process"), 1);

// ../../node_modules/.pnpm/ansi-escapes@5.0.0/node_modules/ansi-escapes/index.js
var ESC = "\x1B[";
var OSC = "\x1B]";
var BEL = "\x07";
var SEP = ";";
var isTerminalApp = process.env.TERM_PROGRAM === "Apple_Terminal";
var ansiEscapes = {};
ansiEscapes.cursorTo = (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) + ";" + (x + 1) + "H";
};
ansiEscapes.cursorMove = (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;
};
ansiEscapes.cursorUp = (count = 1) => ESC + count + "A";
ansiEscapes.cursorDown = (count = 1) => ESC + count + "B";
ansiEscapes.cursorForward = (count = 1) => ESC + count + "C";
ansiEscapes.cursorBackward = (count = 1) => ESC + count + "D";
ansiEscapes.cursorLeft = ESC + "G";
ansiEscapes.cursorSavePosition = isTerminalApp ? "\x1B7" : ESC + "s";
ansiEscapes.cursorRestorePosition = isTerminalApp ? "\x1B8" : ESC + "u";
ansiEscapes.cursorGetPosition = ESC + "6n";
ansiEscapes.cursorNextLine = ESC + "E";
ansiEscapes.cursorPrevLine = ESC + "F";
ansiEscapes.cursorHide = ESC + "?25l";
ansiEscapes.cursorShow = ESC + "?25h";
ansiEscapes.eraseLines = (count) => {
  let clear = "";
  for (let i = 0; i < count; i++) {
    clear += ansiEscapes.eraseLine + (i < count - 1 ? ansiEscapes.cursorUp() : "");
  }
  if (count) {
    clear += ansiEscapes.cursorLeft;
  }
  return clear;
};
ansiEscapes.eraseEndLine = ESC + "K";
ansiEscapes.eraseStartLine = ESC + "1K";
ansiEscapes.eraseLine = ESC + "2K";
ansiEscapes.eraseDown = ESC + "J";
ansiEscapes.eraseUp = ESC + "1J";
ansiEscapes.eraseScreen = ESC + "2J";
ansiEscapes.scrollUp = ESC + "S";
ansiEscapes.scrollDown = ESC + "T";
ansiEscapes.clearScreen = "\x1Bc";
ansiEscapes.clearTerminal = process.platform === "win32" ? `${ansiEscapes.eraseScreen}${ESC}0f` : (
  // 1. Erases the screen (Only done in case `2` is not supported)
  // 2. Erases the whole screen including scrollback buffer
  // 3. Moves cursor to the top-left position
  // More info: https://www.real-world-systems.com/docs/ANSIcode.html
  `${ansiEscapes.eraseScreen}${ESC}3J${ESC}H`
);
ansiEscapes.beep = BEL;
ansiEscapes.link = (text, url46) => {
  return [
    OSC,
    "8",
    SEP,
    SEP,
    url46,
    BEL,
    text,
    OSC,
    "8",
    SEP,
    SEP,
    BEL
  ].join("");
};
ansiEscapes.image = (buffer, options = {}) => {
  let returnValue = `${OSC}1337;File=inline=1`;
  if (options.width) {
    returnValue += `;width=${options.width}`;
  }
  if (options.height) {
    returnValue += `;height=${options.height}`;
  }
  if (options.preserveAspectRatio === false) {
    returnValue += ";preserveAspectRatio=0";
  }
  return returnValue + ":" + buffer.toString("base64") + BEL;
};
ansiEscapes.iTerm = {
  setCwd: (cwd2 = process.cwd()) => `${OSC}50;CurrentDir=${cwd2}${BEL}`,
  annotation: (message, options = {}) => {
    let returnValue = `${OSC}1337;`;
    const hasX = typeof options.x !== "undefined";
    const hasY = typeof options.y !== "undefined";
    if ((hasX || hasY) && !(hasX && hasY && typeof options.length !== "undefined")) {
      throw new Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");
    }
    message = message.replace(/\|/g, "");
    returnValue += options.isHidden ? "AddHiddenAnnotation=" : "AddAnnotation=";
    if (options.length > 0) {
      returnValue += (hasX ? [message, options.length, options.x, options.y] : [options.length, message]).join("|");
    } else {
      returnValue += message;
    }
    return returnValue + BEL;
  }
};
var ansi_escapes_default = ansiEscapes;

// ../../node_modules/.pnpm/cli-cursor@4.0.0/node_modules/cli-cursor/index.js
var import_node_process4 = __toESM(require("node:process"), 1);

// ../../node_modules/.pnpm/restore-cursor@4.0.0/node_modules/restore-cursor/index.js
var import_node_process3 = __toESM(require("node:process"), 1);
var import_onetime = __toESM(require_onetime(), 1);
var import_signal_exit = __toESM(require_signal_exit(), 1);
var restoreCursor = (0, import_onetime.default)(() => {
  (0, import_signal_exit.default)(() => {
    import_node_process3.default.stderr.write("\x1B[?25h");
  }, { alwaysLast: true });
});
var restore_cursor_default = restoreCursor;

// ../../node_modules/.pnpm/cli-cursor@4.0.0/node_modules/cli-cursor/index.js
var isHidden = false;
var cliCursor = {};
cliCursor.show = (writableStream = import_node_process4.default.stderr) => {
  if (!writableStream.isTTY) {
    return;
  }
  isHidden = false;
  writableStream.write("\x1B[?25h");
};
cliCursor.hide = (writableStream = import_node_process4.default.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/.pnpm/ansi-regex@6.2.2/node_modules/ansi-regex/index.js
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");
}

// ../../node_modules/.pnpm/strip-ansi@7.2.0/node_modules/strip-ansi/index.js
var regex = ansiRegex();
function stripAnsi2(string7) {
  if (typeof string7 !== "string") {
    throw new TypeError(`Expected a \`string\`, got \`${typeof string7}\``);
  }
  if (!string7.includes("\x1B") && !string7.includes("\x9B")) {
    return string7;
  }
  return string7.replace(regex, "");
}

// ../../node_modules/.pnpm/string-width@5.1.2/node_modules/string-width/index.js
var import_eastasianwidth = __toESM(require_eastasianwidth(), 1);
var import_emoji_regex = __toESM(require_emoji_regex(), 1);
function stringWidth(string7, options = {}) {
  if (typeof string7 !== "string" || string7.length === 0) {
    return 0;
  }
  options = {
    ambiguousIsNarrow: true,
    ...options
  };
  string7 = stripAnsi2(string7);
  if (string7.length === 0) {
    return 0;
  }
  string7 = string7.replace((0, import_emoji_regex.default)(), "  ");
  const ambiguousCharacterWidth = options.ambiguousIsNarrow ? 1 : 2;
  let width = 0;
  for (const character of string7) {
    const codePoint = character.codePointAt(0);
    if (codePoint <= 31 || codePoint >= 127 && codePoint <= 159) {
      continue;
    }
    if (codePoint >= 768 && codePoint <= 879) {
      continue;
    }
    const code = import_eastasianwidth.default.eastAsianWidth(character);
    switch (code) {
      case "F":
      case "W":
        width += 2;
        break;
      case "A":
        width += ambiguousCharacterWidth;
        break;
      default:
        width += 1;
    }
  }
  return width;
}

// ../../node_modules/.pnpm/ansi-styles@6.2.1/node_modules/ansi-styles/index.js
var ANSI_BACKGROUND_OFFSET2 = 10;
var wrapAnsi162 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
var wrapAnsi2562 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
var wrapAnsi16m2 = (offset = 0) => (red4, green4, blue4) => `\x1B[${38 + offset};2;${red4};${green4};${blue4}m`;
var styles3 = {
  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(styles3.modifier);
var foregroundColorNames2 = Object.keys(styles3.color);
var backgroundColorNames2 = Object.keys(styles3.bgColor);
var colorNames2 = [...foregroundColorNames2, ...backgroundColorNames2];
function assembleStyles2() {
  const codes = /* @__PURE__ */ new Map();
  for (const [groupName, group] of Object.entries(styles3)) {
    for (const [styleName, style] of Object.entries(group)) {
      styles3[styleName] = {
        open: `\x1B[${style[0]}m`,
        close: `\x1B[${style[1]}m`
      };
      group[styleName] = styles3[styleName];
      codes.set(style[0], style[1]);
    }
    Object.defineProperty(styles3, groupName, {
      value: group,
      enumerable: false
    });
  }
  Object.defineProperty(styles3, "codes", {
    value: codes,
    enumerable: false
  });
  styles3.color.close = "\x1B[39m";
  styles3.bgColor.close = "\x1B[49m";
  styles3.color.ansi = wrapAnsi162();
  styles3.color.ansi256 = wrapAnsi2562();
  styles3.color.ansi16m = wrapAnsi16m2();
  styles3.bgColor.ansi = wrapAnsi162(ANSI_BACKGROUND_OFFSET2);
  styles3.bgColor.ansi256 = wrapAnsi2562(ANSI_BACKGROUND_OFFSET2);
  styles3.bgColor.ansi16m = wrapAnsi16m2(ANSI_BACKGROUND_OFFSET2);
  Object.defineProperties(styles3, {
    rgbToAnsi256: {
      value: (red4, green4, blue4) => {
        if (red4 === green4 && green4 === blue4) {
          if (red4 < 8) {
            return 16;
          }
          if (red4 > 248) {
            return 231;
          }
          return Math.round((red4 - 8) / 247 * 24) + 232;
        }
        return 16 + 36 * Math.round(red4 / 255 * 5) + 6 * Math.round(green4 / 255 * 5) + Math.round(blue4 / 255 * 5);
      },
      enumerable: false
    },
    hexToRgb: {
      value: (hex5) => {
        const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex5.toString(16));
        if (!matches) {
          return [0, 0, 0];
        }
        let [colorString] = matches;
        if (colorString.length === 3) {
          colorString = [...colorString].map((character) => character + character).join("");
        }
        const integer3 = Number.parseInt(colorString, 16);
        return [
          /* eslint-disable no-bitwise */
          integer3 >> 16 & 255,
          integer3 >> 8 & 255,
          integer3 & 255
          /* eslint-enable no-bitwise */
        ];
      },
      enumerable: false
    },
    hexToAnsi256: {
      value: (hex5) => styles3.rgbToAnsi256(...styles3.hexToRgb(hex5)),
      enumerable: false
    },
    ansi256ToAnsi: {
      value: (code) => {
        if (code < 8) {
          return 30 + code;
        }
        if (code < 16) {
          return 90 + (code - 8);
        }
        let red4;
        let green4;
        let blue4;
        if (code >= 232) {
          red4 = ((code - 232) * 10 + 8) / 255;
          green4 = red4;
          blue4 = red4;
        } else {
          code -= 16;
          const remainder = code % 36;
          red4 = Math.floor(code / 36) / 5;
          green4 = Math.floor(remainder / 6) / 5;
          blue4 = remainder % 6 / 5;
        }
        const value = Math.max(red4, green4, blue4) * 2;
        if (value === 0) {
          return 30;
        }
        let result = 30 + (Math.round(blue4) << 2 | Math.round(green4) << 1 | Math.round(red4));
        if (value === 2) {
          result += 60;
        }
        return result;
      },
      enumerable: false
    },
    rgbToAnsi: {
      value: (red4, green4, blue4) => styles3.ansi256ToAnsi(styles3.rgbToAnsi256(red4, green4, blue4)),
      enumerable: false
    },
    hexToAnsi: {
      value: (hex5) => styles3.ansi256ToAnsi(styles3.hexToAnsi256(hex5)),
      enumerable: false
    }
  });
  return styles3;
}
var ansiStyles2 = assembleStyles2();
var ansi_styles_default2 = ansiStyles2;

// ../../node_modules/.pnpm/wrap-ansi@8.1.0/node_modules/wrap-ansi/index.js
var ESCAPES = /* @__PURE__ */ new Set([
  "\x1B",
  "\x9B"
]);
var END_CODE = 39;
var ANSI_ESCAPE_BELL2 = "\x07";
var ANSI_CSI2 = "[";
var ANSI_OSC2 = "]";
var ANSI_SGR_TERMINATOR = "m";
var ANSI_ESCAPE_LINK2 = `${ANSI_OSC2}8;;`;
var wrapAnsiCode = (code) => `${ESCAPES.values().next().value}${ANSI_CSI2}${code}${ANSI_SGR_TERMINATOR}`;
var wrapAnsiHyperlink = (uri) => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK2}${uri}${ANSI_ESCAPE_BELL2}`;
var wordLengths = (string7) => string7.split(" ").map((character) => stringWidth(character));
var wrapWord = (rows, word, columns) => {
  const characters = [...word];
  let isInsideEscape = false;
  let isInsideLinkEscape = false;
  let visible = stringWidth(stripAnsi2(rows[rows.length - 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)) {
      isInsideEscape = true;
      isInsideLinkEscape = characters.slice(index + 1).join("").startsWith(ANSI_ESCAPE_LINK2);
    }
    if (isInsideEscape) {
      if (isInsideLinkEscape) {
        if (character === ANSI_ESCAPE_BELL2) {
          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[rows.length - 1].length > 0 && rows.length > 1) {
    rows[rows.length - 2] += rows.pop();
  }
};
var stringVisibleTrimSpacesRight = (string7) => {
  const words = string7.split(" ");
  let last = words.length;
  while (last > 0) {
    if (stringWidth(words[last - 1]) > 0) {
      break;
    }
    last--;
  }
  if (last === words.length) {
    return string7;
  }
  return words.slice(0, last).join(" ") + words.slice(last).join("");
};
var exec = (string7, columns, options = {}) => {
  if (options.trim !== false && string7.trim() === "") {
    return "";
  }
  let returnValue = "";
  let escapeCode;
  let escapeUrl;
  const lengths = wordLengths(string7);
  let rows = [""];
  for (const [index, word] of string7.split(" ").entries()) {
    if (options.trim !== false) {
      rows[rows.length - 1] = rows[rows.length - 1].trimStart();
    }
    let rowLength = stringWidth(rows[rows.length - 1]);
    if (index !== 0) {
      if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) {
        rows.push("");
        rowLength = 0;
      }
      if (rowLength > 0 || options.trim === false) {
        rows[rows.length - 1] += " ";
        rowLength++;
      }
    }
    if (options.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("");
      }
      wrapWord(rows, word, columns);
      continue;
    }
    if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) {
      if (options.wordWrap === false && rowLength < columns) {
        wrapWord(rows, word, columns);
        continue;
      }
      rows.push("");
    }
    if (rowLength + lengths[index] > columns && options.wordWrap === false) {
      wrapWord(rows, word, columns);
      continue;
    }
    rows[rows.length - 1] += word;
  }
  if (options.trim !== false) {
    rows = rows.map((row) => stringVisibleTrimSpacesRight(row));
  }
  const pre = [...rows.join("\n")];
  for (const [index, character] of pre.entries()) {
    returnValue += character;
    if (ESCAPES.has(character)) {
      const { groups } = new RegExp(`(?:\\${ANSI_CSI2}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK2}(?<uri>.*)${ANSI_ESCAPE_BELL2})`).exec(pre.slice(index).join("")) || { 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_default2.codes.get(Number(escapeCode));
    if (pre[index + 1] === "\n") {
      if (escapeUrl) {
        returnValue += wrapAnsiHyperlink("");
      }
      if (escapeCode && code) {
        returnValue += wrapAnsiCode(code);
      }
    } else if (character === "\n") {
      if (escapeCode && code) {
        returnValue += wrapAnsiCode(escapeCode);
      }
      if (escapeUrl) {
        returnValue += wrapAnsiHyperlink(escapeUrl);
      }
    }
  }
  return returnValue;
};
function wrapAnsi2(string7, columns, options) {
  return String(string7).normalize().replace(/\r\n/g, "\n").split("\n").map((line) => exec(line, columns, options)).join("\n");
}

// ../../node_modules/.pnpm/is-fullwidth-code-point@4.0.0/node_modules/is-fullwidth-code-point/index.js
function isFullwidthCodePoint(codePoint) {
  if (!Number.isInteger(codePoint)) {
    return false;
  }
  return codePoint >= 4352 && (codePoint <= 4447 || // Hangul Jamo
  codePoint === 9001 || // LEFT-POINTING ANGLE BRACKET
  codePoint === 9002 || // RIGHT-POINTING ANGLE BRACKET
  // CJK Radicals Supplement .. Enclosed CJK Letters and Months
  11904 <= codePoint && codePoint <= 12871 && codePoint !== 12351 || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
  12880 <= codePoint && codePoint <= 19903 || // CJK Unified Ideographs .. Yi Radicals
  19968 <= codePoint && codePoint <= 42182 || // Hangul Jamo Extended-A
  43360 <= codePoint && codePoint <= 43388 || // Hangul Syllables
  44032 <= codePoint && codePoint <= 55203 || // CJK Compatibility Ideographs
  63744 <= codePoint && codePoint <= 64255 || // Vertical Forms
  65040 <= codePoint && codePoint <= 65049 || // CJK Compatibility Forms .. Small Form Variants
  65072 <= codePoint && codePoint <= 65131 || // Halfwidth and Fullwidth Forms
  65281 <= codePoint && codePoint <= 65376 || 65504 <= codePoint && codePoint <= 65510 || // Kana Supplement
  110592 <= codePoint && codePoint <= 110593 || // Enclosed Ideographic Supplement
  127488 <= codePoint && codePoint <= 127569 || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
  131072 <= codePoint && codePoint <= 262141);
}

// ../../node_modules/.pnpm/slice-ansi@5.0.0/node_modules/slice-ansi/index.js
var astralRegex = /^[\uD800-\uDBFF][\uDC00-\uDFFF]$/;
var ESCAPES2 = [
  "\x1B",
  "\x9B"
];
var wrapAnsi3 = (code) => `${ESCAPES2[0]}[${code}m`;
var checkAnsi = (ansiCodes, isEscapes, endAnsiCode) => {
  let output = [];
  ansiCodes = [...ansiCodes];
  for (let ansiCode of ansiCodes) {
    const ansiCodeOrigin = ansiCode;
    if (ansiCode.includes(";")) {
      ansiCode = ansiCode.split(";")[0][0] + "0";
    }
    const item = ansi_styles_default2.codes.get(Number.parseInt(ansiCode, 10));
    if (item) {
      const indexEscape = ansiCodes.indexOf(item.toString());
      if (indexEscape === -1) {
        output.push(wrapAnsi3(isEscapes ? item : ansiCodeOrigin));
      } else {
        ansiCodes.splice(indexEscape, 1);
      }
    } else if (isEscapes) {
      output.push(wrapAnsi3(0));
      break;
    } else {
      output.push(wrapAnsi3(ansiCodeOrigin));
    }
  }
  if (isEscapes) {
    output = output.filter((element, index) => output.indexOf(element) === index);
    if (endAnsiCode !== void 0) {
      const fistEscapeCode = wrapAnsi3(ansi_styles_default2.codes.get(Number.parseInt(endAnsiCode, 10)));
      output = output.reduce((current, next) => next === fistEscapeCode ? [next, ...current] : [...current, next], []);
    }
  }
  return output.join("");
};
function sliceAnsi(string7, begin, end) {
  const characters = [...string7];
  const ansiCodes = [];
  let stringEnd = typeof end === "number" ? end : characters.length;
  let isInsideEscape = false;
  let ansiCode;
  let visible = 0;
  let output = "";
  for (const [index, character] of characters.entries()) {
    let leftEscape = false;
    if (ESCAPES2.includes(character)) {
      const code = /\d[^m]*/.exec(string7.slice(index, index + 18));
      ansiCode = code && code.length > 0 ? code[0] : void 0;
      if (visible < stringEnd) {
        isInsideEscape = true;
        if (ansiCode !== void 0) {
          ansiCodes.push(ansiCode);
        }
      }
    } else if (isInsideEscape && character === "m") {
      isInsideEscape = false;
      leftEscape = true;
    }
    if (!isInsideEscape && !leftEscape) {
      visible++;
    }
    if (!astralRegex.test(character) && isFullwidthCodePoint(character.codePointAt())) {
      visible++;
      if (typeof end !== "number") {
        stringEnd++;
      }
    }
    if (visible > begin && visible <= stringEnd) {
      output += character;
    } else if (visible === begin && !isInsideEscape && ansiCode !== void 0) {
      output = checkAnsi(ansiCodes);
    } else if (visible >= stringEnd) {
      output += checkAnsi(ansiCodes, true, ansiCode);
      break;
    }
  }
  return output;
}

// ../../node_modules/.pnpm/ansi-regex@6.0.1/node_modules/ansi-regex/index.js
function ansiRegex2({ onlyFirst = false } = {}) {
  const pattern = [
    "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
    "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"
  ].join("|");
  return new RegExp(pattern, onlyFirst ? void 0 : "g");
}

// ../../node_modules/.pnpm/strip-ansi@7.1.0/node_modules/strip-ansi/index.js
var regex2 = ansiRegex2();
function stripAnsi3(string7) {
  if (typeof string7 !== "string") {
    throw new TypeError(`Expected a \`string\`, got \`${typeof string7}\``);
  }
  return string7.replace(regex2, "");
}

// ../../node_modules/.pnpm/log-update@5.0.1/node_modules/log-update/index.js
var defaultTerminalHeight = 24;
var getWidth = (stream) => {
  const { columns } = stream;
  if (!columns) {
    return 80;
  }
  return columns;
};
var fitToTerminalHeight = (stream, text) => {
  const terminalHeight = stream.rows || defaultTerminalHeight;
  const lines = text.split("\n");
  const toRemove = lines.length - terminalHeight;
  if (toRemove <= 0) {
    return text;
  }
  return sliceAnsi(
    text,
    stripAnsi3(lines.slice(0, toRemove).join("\n")).length + 1
  );
};
function createLogUpdate(stream, { showCursor: showCursor2 = false } = {}) {
  let previousLineCount = 0;
  let previousWidth = getWidth(stream);
  let previousOutput = "";
  const render = (...arguments_) => {
    if (!showCursor2) {
      cli_cursor_default.hide();
    }
    let output = arguments_.join(" ") + "\n";
    output = fitToTerminalHeight(stream, output);
    const width = getWidth(stream);
    if (output === previousOutput && previousWidth === width) {
      return;
    }
    previousOutput = output;
    previousWidth = width;
    output = wrapAnsi2(output, width, {
      trim: false,
      hard: true,
      wordWrap: false
    });
    stream.write(ansi_escapes_default.eraseLines(previousLineCount) + output);
    previousLineCount = output.split("\n").length;
  };
  render.clear = () => {
    stream.write(ansi_escapes_default.eraseLines(previousLineCount));
    previousOutput = "";
    previousWidth = getWidth(stream);
    previousLineCount = 0;
  };
  render.done = () => {
    previousOutput = "";
    previousWidth = getWidth(stream);
    previousLineCount = 0;
    if (!showCursor2) {
      cli_cursor_default.show();
    }
  };
  return render;
}
var logUpdate = createLogUpdate(import_node_process5.default.stdout);
var logUpdateStderr = createLogUpdate(import_node_process5.default.stderr);

// ../cli/dist/interactive.mjs
var logUpdate2 = createLogUpdate(stdout);
var grayBar = gray(shapes.bar);
var blCorner = gray(shapes.corners.bl);
var leftT = gray(shapes.leftT);
var spinnerFrames = {
  clockwise: [
    "\u2524",
    "\u2518",
    "\u2534",
    "\u2514",
    "\u251C",
    "\u250C",
    "\u252C",
    "\u2510"
  ],
  vertical: [
    "\u2581",
    "\u2583",
    "\u2584",
    "\u2585",
    "\u2586",
    "\u2587",
    "\u2586",
    "\u2585",
    "\u2584",
    "\u2583"
  ]
};
var ellipsisFrames = [
  "",
  ".",
  "..",
  "...",
  " ..",
  "  .",
  ""
];
var spinner = (frames = spinnerFrames.clockwise, color = brandColor) => {
  const frameRate = 120;
  let loop = null;
  let startMsg;
  let currentMsg;
  function clearLoop() {
    if (loop) clearTimeout(loop);
    loop = null;
  }
  return {
    start(msg, helpText) {
      helpText ||= ``;
      currentMsg = msg;
      startMsg = currentMsg;
      if (helpText !== void 0 && helpText.length > 0) startMsg += ` ${dim(helpText)}`;
      if (isInteractive2()) {
        let index = 0;
        clearLoop();
        loop = setInterval(() => {
          index++;
          const spinnerFrame = frames[index % frames.length];
          const ellipsisFrame = ellipsisFrames[index % ellipsisFrames.length];
          if (msg) logUpdate2(`${color(spinnerFrame)} ${currentMsg} ${ellipsisFrame}`);
        }, frameRate);
      } else logRaw(`${leftT} ${startMsg}`);
    },
    update(msg) {
      currentMsg = msg;
    },
    stop(msg) {
      if (isInteractive2()) {
        logUpdate2.clear();
        if (msg) {
          logUpdate2(`${leftT} ${startMsg}
${grayBar} ${msg}`);
          logUpdate2.done();
          newline();
        }
        clearLoop();
      } else {
        if (msg !== void 0) logRaw(`${grayBar} ${msg}`);
        newline();
      }
    }
  };
};
function isInteractive2() {
  try {
    return Boolean(process.stdin.isTTY && process.stdout.isTTY);
  } catch {
    return false;
  }
}

// ../../node_modules/.pnpm/@puppeteer+browsers@2.10.6/node_modules/@puppeteer/browsers/lib/esm/launch.js
var import_node_child_process4 = __toESM(require("node:child_process"), 1);
var import_node_readline2 = __toESM(require("node:readline"), 1);

// ../../node_modules/.pnpm/@puppeteer+browsers@2.10.6/node_modules/@puppeteer/browsers/lib/esm/browser-data/chrome-headless-shell.js
var import_node_path20 = __toESM(require("node:path"), 1);

// ../../node_modules/.pnpm/@puppeteer+browsers@2.10.6/node_modules/@puppeteer/browsers/lib/esm/browser-data/types.js
var Browser;
(function(Browser2) {
  Browser2["CHROME"] = "chrome";
  Browser2["CHROMEHEADLESSSHELL"] = "chrome-headless-shell";
  Browser2["CHROMIUM"] = "chromium";
  Browser2["FIREFOX"] = "firefox";
  Browser2["CHROMEDRIVER"] = "chromedriver";
})(Browser || (Browser = {}));
var BrowserPlatform;
(function(BrowserPlatform2) {
  BrowserPlatform2["LINUX"] = "linux";
  BrowserPlatform2["LINUX_ARM"] = "linux_arm";
  BrowserPlatform2["MAC"] = "mac";
  BrowserPlatform2["MAC_ARM"] = "mac_arm";
  BrowserPlatform2["WIN32"] = "win32";
  BrowserPlatform2["WIN64"] = "win64";
})(BrowserPlatform || (BrowserPlatform = {}));
var BrowserTag;
(function(BrowserTag2) {
  BrowserTag2["CANARY"] = "canary";
  BrowserTag2["NIGHTLY"] = "nightly";
  BrowserTag2["BETA"] = "beta";
  BrowserTag2["DEV"] = "dev";
  BrowserTag2["DEVEDITION"] = "devedition";
  BrowserTag2["STABLE"] = "stable";
  BrowserTag2["ESR"] = "esr";
  BrowserTag2["LATEST"] = "latest";
})(BrowserTag || (BrowserTag = {}));
var ChromeReleaseChannel;
(function(ChromeReleaseChannel2) {
  ChromeReleaseChannel2["STABLE"] = "stable";
  ChromeReleaseChannel2["DEV"] = "dev";
  ChromeReleaseChannel2["CANARY"] = "canary";
  ChromeReleaseChannel2["BETA"] = "beta";
})(ChromeReleaseChannel || (ChromeReleaseChannel = {}));

// ../../node_modules/.pnpm/@puppeteer+browsers@2.10.6/node_modules/@puppeteer/browsers/lib/esm/browser-data/chrome.js
var import_node_path19 = __toESM(require("node:path"), 1);
var import_semver = __toESM(require_semver2(), 1);

// ../../node_modules/.pnpm/@puppeteer+browsers@2.10.6/node_modules/@puppeteer/browsers/lib/esm/httpUtil.js
var import_node_fs12 = require("node:fs");
var http = __toESM(require("node:http"), 1);
var https = __toESM(require("node:https"), 1);
var import_node_url7 = require("node:url");
var import_proxy_agent = __toESM(require_dist12(), 1);
function httpRequest(url46, method, response, keepAlive = true) {
  const options = {
    protocol: url46.protocol,
    hostname: url46.hostname,
    port: url46.port,
    path: url46.pathname + url46.search,
    method,
    headers: keepAlive ? { Connection: "keep-alive" } : void 0,
    auth: (0, import_node_url7.urlToHttpOptions)(url46).auth,
    agent: new import_proxy_agent.ProxyAgent()
  };
  const requestCallback = (res) => {
    if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
      httpRequest(new import_node_url7.URL(res.headers.location), method, response);
      res.resume();
    } else {
      response(res);
    }
  };
  const request4 = options.protocol === "https:" ? https.request(options, requestCallback) : http.request(options, requestCallback);
  request4.end();
  return request4;
}
function downloadFile(url46, destinationPath, progressCallback) {
  return new Promise((resolve8, reject) => {
    let downloadedBytes = 0;
    let totalBytes = 0;
    function onData(chunk) {
      downloadedBytes += chunk.length;
      progressCallback(downloadedBytes, totalBytes);
    }
    const request4 = httpRequest(url46, "GET", (response) => {
      if (response.statusCode !== 200) {
        const error101 = new Error(`Download failed: server returned code ${response.statusCode}. URL: ${url46}`);
        response.resume();
        reject(error101);
        return;
      }
      const file5 = (0, import_node_fs12.createWriteStream)(destinationPath);
      file5.on("finish", () => {
        return resolve8();
      });
      file5.on("error", (error101) => {
        return reject(error101);
      });
      response.pipe(file5);
      totalBytes = parseInt(response.headers["content-length"], 10);
      if (progressCallback) {
        response.on("data", onData);
      }
    });
    request4.on("error", (error101) => {
      return reject(error101);
    });
  });
}
async function getJSON(url46) {
  const text = await getText2(url46);
  try {
    return JSON.parse(text);
  } catch {
    throw new Error("Could not parse JSON from " + url46.toString());
  }
}
function getText2(url46) {
  return new Promise((resolve8, reject) => {
    const request4 = httpRequest(url46, "GET", (response) => {
      let data = "";
      if (response.statusCode && response.statusCode >= 400) {
        return reject(new Error(`Got status code ${response.statusCode}`));
      }
      response.on("data", (chunk) => {
        data += chunk;
      });
      response.on("end", () => {
        try {
          return resolve8(String(data));
        } catch {
          return reject(new Error("Chrome version not found"));
        }
      });
    }, false);
    request4.on("error", (err) => {
      reject(err);
    });
  });
}

// ../../node_modules/.pnpm/@puppeteer+browsers@2.10.6/node_modules/@puppeteer/browsers/lib/esm/browser-data/chrome.js
function folder(platform2) {
  switch (platform2) {
    case BrowserPlatform.LINUX_ARM:
    case BrowserPlatform.LINUX:
      return "linux64";
    case BrowserPlatform.MAC_ARM:
      return "mac-arm64";
    case BrowserPlatform.MAC:
      return "mac-x64";
    case BrowserPlatform.WIN32:
      return "win32";
    case BrowserPlatform.WIN64:
      return "win64";
  }
}
function resolveDownloadUrl(platform2, buildId, baseUrl = "https://storage.googleapis.com/chrome-for-testing-public") {
  return `${baseUrl}/${resolveDownloadPath(platform2, buildId).join("/")}`;
}
function resolveDownloadPath(platform2, buildId) {
  return [buildId, folder(platform2), `chrome-${folder(platform2)}.zip`];
}
function relativeExecutablePath(platform2, _buildId) {
  switch (platform2) {
    case BrowserPlatform.MAC:
    case BrowserPlatform.MAC_ARM:
      return import_node_path19.default.join("chrome-" + folder(platform2), "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing");
    case BrowserPlatform.LINUX_ARM:
    case BrowserPlatform.LINUX:
      return import_node_path19.default.join("chrome-linux64", "chrome");
    case BrowserPlatform.WIN32:
    case BrowserPlatform.WIN64:
      return import_node_path19.default.join("chrome-" + folder(platform2), "chrome.exe");
  }
}
async function getLastKnownGoodReleaseForChannel(channel) {
  const data = await getJSON(new URL("https://googlechromelabs.github.io/chrome-for-testing/last-known-good-versions.json"));
  for (const channel2 of Object.keys(data.channels)) {
    data.channels[channel2.toLowerCase()] = data.channels[channel2];
    delete data.channels[channel2];
  }
  return data.channels[channel];
}
async function getLastKnownGoodReleaseForMilestone(milestone) {
  const data = await getJSON(new URL("https://googlechromelabs.github.io/chrome-for-testing/latest-versions-per-milestone.json"));
  return data.milestones[milestone];
}
async function getLastKnownGoodReleaseForBuild(buildPrefix) {
  const data = await getJSON(new URL("https://googlechromelabs.github.io/chrome-for-testing/latest-patch-versions-per-build.json"));
  return data.builds[buildPrefix];
}
async function resolveBuildId(channel) {
  if (Object.values(ChromeReleaseChannel).includes(channel)) {
    return (await getLastKnownGoodReleaseForChannel(channel)).version;
  }
  if (channel.match(/^\d+$/)) {
    return (await getLastKnownGoodReleaseForMilestone(channel))?.version;
  }
  if (channel.match(/^\d+\.\d+\.\d+$/)) {
    return (await getLastKnownGoodReleaseForBuild(channel))?.version;
  }
  return;
}
function compareVersions(a, b) {
  if (!import_semver.default.valid(a)) {
    throw new Error(`Version ${a} is not a valid semver version`);
  }
  if (!import_semver.default.valid(b)) {
    throw new Error(`Version ${b} is not a valid semver version`);
  }
  if (import_semver.default.gt(a, b)) {
    return 1;
  } else if (import_semver.default.lt(a, b)) {
    return -1;
  } else {
    return 0;
  }
}

// ../../node_modules/.pnpm/@puppeteer+browsers@2.10.6/node_modules/@puppeteer/browsers/lib/esm/browser-data/chrome-headless-shell.js
function folder2(platform2) {
  switch (platform2) {
    case BrowserPlatform.LINUX_ARM:
    case BrowserPlatform.LINUX:
      return "linux64";
    case BrowserPlatform.MAC_ARM:
      return "mac-arm64";
    case BrowserPlatform.MAC:
      return "mac-x64";
    case BrowserPlatform.WIN32:
      return "win32";
    case BrowserPlatform.WIN64:
      return "win64";
  }
}
function resolveDownloadUrl2(platform2, buildId, baseUrl = "https://storage.googleapis.com/chrome-for-testing-public") {
  return `${baseUrl}/${resolveDownloadPath2(platform2, buildId).join("/")}`;
}
function resolveDownloadPath2(platform2, buildId) {
  return [
    buildId,
    folder2(platform2),
    `chrome-headless-shell-${folder2(platform2)}.zip`
  ];
}
function relativeExecutablePath2(platform2, _buildId) {
  switch (platform2) {
    case BrowserPlatform.MAC:
    case BrowserPlatform.MAC_ARM:
      return import_node_path20.default.join("chrome-headless-shell-" + folder2(platform2), "chrome-headless-shell");
    case BrowserPlatform.LINUX_ARM:
    case BrowserPlatform.LINUX:
      return import_node_path20.default.join("chrome-headless-shell-linux64", "chrome-headless-shell");
    case BrowserPlatform.WIN32:
    case BrowserPlatform.WIN64:
      return import_node_path20.default.join("chrome-headless-shell-" + folder2(platform2), "chrome-headless-shell.exe");
  }
}

// ../../node_modules/.pnpm/@puppeteer+browsers@2.10.6/node_modules/@puppeteer/browsers/lib/esm/browser-data/chromedriver.js
var import_node_path21 = __toESM(require("node:path"), 1);
function folder3(platform2) {
  switch (platform2) {
    case BrowserPlatform.LINUX_ARM:
    case BrowserPlatform.LINUX:
      return "linux64";
    case BrowserPlatform.MAC_ARM:
      return "mac-arm64";
    case BrowserPlatform.MAC:
      return "mac-x64";
    case BrowserPlatform.WIN32:
      return "win32";
    case BrowserPlatform.WIN64:
      return "win64";
  }
}
function resolveDownloadUrl3(platform2, buildId, baseUrl = "https://storage.googleapis.com/chrome-for-testing-public") {
  return `${baseUrl}/${resolveDownloadPath3(platform2, buildId).join("/")}`;
}
function resolveDownloadPath3(platform2, buildId) {
  return [buildId, folder3(platform2), `chromedriver-${folder3(platform2)}.zip`];
}
function relativeExecutablePath3(platform2, _buildId) {
  switch (platform2) {
    case BrowserPlatform.MAC:
    case BrowserPlatform.MAC_ARM:
      return import_node_path21.default.join("chromedriver-" + folder3(platform2), "chromedriver");
    case BrowserPlatform.LINUX_ARM:
    case BrowserPlatform.LINUX:
      return import_node_path21.default.join("chromedriver-linux64", "chromedriver");
    case BrowserPlatform.WIN32:
    case BrowserPlatform.WIN64:
      return import_node_path21.default.join("chromedriver-" + folder3(platform2), "chromedriver.exe");
  }
}

// ../../node_modules/.pnpm/@puppeteer+browsers@2.10.6/node_modules/@puppeteer/browsers/lib/esm/browser-data/chromium.js
var import_node_path22 = __toESM(require("node:path"), 1);
function archive(platform2, buildId) {
  switch (platform2) {
    case BrowserPlatform.LINUX_ARM:
    case BrowserPlatform.LINUX:
      return "chrome-linux";
    case BrowserPlatform.MAC_ARM:
    case BrowserPlatform.MAC:
      return "chrome-mac";
    case BrowserPlatform.WIN32:
    case BrowserPlatform.WIN64:
      return parseInt(buildId, 10) > 591479 ? "chrome-win" : "chrome-win32";
  }
}
function folder4(platform2) {
  switch (platform2) {
    case BrowserPlatform.LINUX_ARM:
    case BrowserPlatform.LINUX:
      return "Linux_x64";
    case BrowserPlatform.MAC_ARM:
      return "Mac_Arm";
    case BrowserPlatform.MAC:
      return "Mac";
    case BrowserPlatform.WIN32:
      return "Win";
    case BrowserPlatform.WIN64:
      return "Win_x64";
  }
}
function resolveDownloadUrl4(platform2, buildId, baseUrl = "https://storage.googleapis.com/chromium-browser-snapshots") {
  return `${baseUrl}/${resolveDownloadPath4(platform2, buildId).join("/")}`;
}
function resolveDownloadPath4(platform2, buildId) {
  return [folder4(platform2), buildId, `${archive(platform2, buildId)}.zip`];
}
function relativeExecutablePath4(platform2, _buildId) {
  switch (platform2) {
    case BrowserPlatform.MAC:
    case BrowserPlatform.MAC_ARM:
      return import_node_path22.default.join("chrome-mac", "Chromium.app", "Contents", "MacOS", "Chromium");
    case BrowserPlatform.LINUX_ARM:
    case BrowserPlatform.LINUX:
      return import_node_path22.default.join("chrome-linux", "chrome");
    case BrowserPlatform.WIN32:
    case BrowserPlatform.WIN64:
      return import_node_path22.default.join("chrome-win", "chrome.exe");
  }
}
async function resolveBuildId2(platform2) {
  return await getText2(new URL(`https://storage.googleapis.com/chromium-browser-snapshots/${folder4(platform2)}/LAST_CHANGE`));
}
function compareVersions2(a, b) {
  return Number(a) - Number(b);
}

// ../../node_modules/.pnpm/@puppeteer+browsers@2.10.6/node_modules/@puppeteer/browsers/lib/esm/browser-data/firefox.js
var import_node_path23 = __toESM(require("node:path"), 1);
function getFormat(buildId) {
  const majorVersion = Number(buildId.split(".").shift());
  return majorVersion >= 135 ? "xz" : "bz2";
}
function archiveNightly(platform2, buildId) {
  switch (platform2) {
    case BrowserPlatform.LINUX:
      return `firefox-${buildId}.en-US.linux-x86_64.tar.${getFormat(buildId)}`;
    case BrowserPlatform.LINUX_ARM:
      return `firefox-${buildId}.en-US.linux-aarch64.tar.${getFormat(buildId)}`;
    case BrowserPlatform.MAC_ARM:
    case BrowserPlatform.MAC:
      return `firefox-${buildId}.en-US.mac.dmg`;
    case BrowserPlatform.WIN32:
    case BrowserPlatform.WIN64:
      return `firefox-${buildId}.en-US.${platform2}.zip`;
  }
}
function archive2(platform2, buildId) {
  switch (platform2) {
    case BrowserPlatform.LINUX_ARM:
    case BrowserPlatform.LINUX:
      return `firefox-${buildId}.tar.${getFormat(buildId)}`;
    case BrowserPlatform.MAC_ARM:
    case BrowserPlatform.MAC:
      return `Firefox ${buildId}.dmg`;
    case BrowserPlatform.WIN32:
    case BrowserPlatform.WIN64:
      return `Firefox Setup ${buildId}.exe`;
  }
}
function platformName(platform2) {
  switch (platform2) {
    case BrowserPlatform.LINUX:
      return `linux-x86_64`;
    case BrowserPlatform.LINUX_ARM:
      return `linux-aarch64`;
    case BrowserPlatform.MAC_ARM:
    case BrowserPlatform.MAC:
      return `mac`;
    case BrowserPlatform.WIN32:
    case BrowserPlatform.WIN64:
      return platform2;
  }
}
function parseBuildId(buildId) {
  for (const value of Object.values(FirefoxChannel)) {
    if (buildId.startsWith(value + "_")) {
      buildId = buildId.substring(value.length + 1);
      return [value, buildId];
    }
  }
  return [FirefoxChannel.NIGHTLY, buildId];
}
function resolveDownloadUrl5(platform2, buildId, baseUrl) {
  const [channel] = parseBuildId(buildId);
  switch (channel) {
    case FirefoxChannel.NIGHTLY:
      baseUrl ??= "https://archive.mozilla.org/pub/firefox/nightly/latest-mozilla-central";
      break;
    case FirefoxChannel.DEVEDITION:
      baseUrl ??= "https://archive.mozilla.org/pub/devedition/releases";
      break;
    case FirefoxChannel.BETA:
    case FirefoxChannel.STABLE:
    case FirefoxChannel.ESR:
      baseUrl ??= "https://archive.mozilla.org/pub/firefox/releases";
      break;
  }
  return `${baseUrl}/${resolveDownloadPath5(platform2, buildId).join("/")}`;
}
function resolveDownloadPath5(platform2, buildId) {
  const [channel, resolvedBuildId] = parseBuildId(buildId);
  switch (channel) {
    case FirefoxChannel.NIGHTLY:
      return [archiveNightly(platform2, resolvedBuildId)];
    case FirefoxChannel.DEVEDITION:
    case FirefoxChannel.BETA:
    case FirefoxChannel.STABLE:
    case FirefoxChannel.ESR:
      return [
        resolvedBuildId,
        platformName(platform2),
        "en-US",
        archive2(platform2, resolvedBuildId)
      ];
  }
}
function relativeExecutablePath5(platform2, buildId) {
  const [channel] = parseBuildId(buildId);
  switch (channel) {
    case FirefoxChannel.NIGHTLY:
      switch (platform2) {
        case BrowserPlatform.MAC_ARM:
        case BrowserPlatform.MAC:
          return import_node_path23.default.join("Firefox Nightly.app", "Contents", "MacOS", "firefox");
        case BrowserPlatform.LINUX_ARM:
        case BrowserPlatform.LINUX:
          return import_node_path23.default.join("firefox", "firefox");
        case BrowserPlatform.WIN32:
        case BrowserPlatform.WIN64:
          return import_node_path23.default.join("firefox", "firefox.exe");
      }
    case FirefoxChannel.BETA:
    case FirefoxChannel.DEVEDITION:
    case FirefoxChannel.ESR:
    case FirefoxChannel.STABLE:
      switch (platform2) {
        case BrowserPlatform.MAC_ARM:
        case BrowserPlatform.MAC:
          return import_node_path23.default.join("Firefox.app", "Contents", "MacOS", "firefox");
        case BrowserPlatform.LINUX_ARM:
        case BrowserPlatform.LINUX:
          return import_node_path23.default.join("firefox", "firefox");
        case BrowserPlatform.WIN32:
        case BrowserPlatform.WIN64:
          return import_node_path23.default.join("core", "firefox.exe");
      }
  }
}
var FirefoxChannel;
(function(FirefoxChannel2) {
  FirefoxChannel2["STABLE"] = "stable";
  FirefoxChannel2["ESR"] = "esr";
  FirefoxChannel2["DEVEDITION"] = "devedition";
  FirefoxChannel2["BETA"] = "beta";
  FirefoxChannel2["NIGHTLY"] = "nightly";
})(FirefoxChannel || (FirefoxChannel = {}));
async function resolveBuildId3(channel = FirefoxChannel.NIGHTLY) {
  const channelToVersionKey = {
    [FirefoxChannel.ESR]: "FIREFOX_ESR",
    [FirefoxChannel.STABLE]: "LATEST_FIREFOX_VERSION",
    [FirefoxChannel.DEVEDITION]: "FIREFOX_DEVEDITION",
    [FirefoxChannel.BETA]: "FIREFOX_DEVEDITION",
    [FirefoxChannel.NIGHTLY]: "FIREFOX_NIGHTLY"
  };
  const versions = await getJSON(new URL("https://product-details.mozilla.org/1.0/firefox_versions.json"));
  const version4 = versions[channelToVersionKey[channel]];
  if (!version4) {
    throw new Error(`Channel ${channel} is not found.`);
  }
  return channel + "_" + version4;
}
function compareVersions3(a, b) {
  return parseInt(a.replace(".", ""), 16) - parseInt(b.replace(".", ""), 16);
}

// ../../node_modules/.pnpm/@puppeteer+browsers@2.10.6/node_modules/@puppeteer/browsers/lib/esm/browser-data/browser-data.js
var downloadUrls = {
  [Browser.CHROMEDRIVER]: resolveDownloadUrl3,
  [Browser.CHROMEHEADLESSSHELL]: resolveDownloadUrl2,
  [Browser.CHROME]: resolveDownloadUrl,
  [Browser.CHROMIUM]: resolveDownloadUrl4,
  [Browser.FIREFOX]: resolveDownloadUrl5
};
var downloadPaths = {
  [Browser.CHROMEDRIVER]: resolveDownloadPath3,
  [Browser.CHROMEHEADLESSSHELL]: resolveDownloadPath2,
  [Browser.CHROME]: resolveDownloadPath,
  [Browser.CHROMIUM]: resolveDownloadPath4,
  [Browser.FIREFOX]: resolveDownloadPath5
};
var executablePathByBrowser = {
  [Browser.CHROMEDRIVER]: relativeExecutablePath3,
  [Browser.CHROMEHEADLESSSHELL]: relativeExecutablePath2,
  [Browser.CHROME]: relativeExecutablePath,
  [Browser.CHROMIUM]: relativeExecutablePath4,
  [Browser.FIREFOX]: relativeExecutablePath5
};
var versionComparators = {
  [Browser.CHROMEDRIVER]: compareVersions,
  [Browser.CHROMEHEADLESSSHELL]: compareVersions,
  [Browser.CHROME]: compareVersions,
  [Browser.CHROMIUM]: compareVersions2,
  [Browser.FIREFOX]: compareVersions3
};
async function resolveBuildIdForBrowserTag(browser, platform2, tag) {
  switch (browser) {
    case Browser.FIREFOX:
      switch (tag) {
        case BrowserTag.LATEST:
          return await resolveBuildId3(FirefoxChannel.NIGHTLY);
        case BrowserTag.BETA:
          return await resolveBuildId3(FirefoxChannel.BETA);
        case BrowserTag.NIGHTLY:
          return await resolveBuildId3(FirefoxChannel.NIGHTLY);
        case BrowserTag.DEVEDITION:
          return await resolveBuildId3(FirefoxChannel.DEVEDITION);
        case BrowserTag.STABLE:
          return await resolveBuildId3(FirefoxChannel.STABLE);
        case BrowserTag.ESR:
          return await resolveBuildId3(FirefoxChannel.ESR);
        case BrowserTag.CANARY:
        case BrowserTag.DEV:
          throw new Error(`${tag.toUpperCase()} is not available for Firefox`);
      }
    case Browser.CHROME: {
      switch (tag) {
        case BrowserTag.LATEST:
          return await resolveBuildId(ChromeReleaseChannel.CANARY);
        case BrowserTag.BETA:
          return await resolveBuildId(ChromeReleaseChannel.BETA);
        case BrowserTag.CANARY:
          return await resolveBuildId(ChromeReleaseChannel.CANARY);
        case BrowserTag.DEV:
          return await resolveBuildId(ChromeReleaseChannel.DEV);
        case BrowserTag.STABLE:
          return await resolveBuildId(ChromeReleaseChannel.STABLE);
        case BrowserTag.NIGHTLY:
        case BrowserTag.DEVEDITION:
        case BrowserTag.ESR:
          throw new Error(`${tag.toUpperCase()} is not available for Chrome`);
      }
    }
    case Browser.CHROMEDRIVER: {
      switch (tag) {
        case BrowserTag.LATEST:
        case BrowserTag.CANARY:
          return await resolveBuildId(ChromeReleaseChannel.CANARY);
        case BrowserTag.BETA:
          return await resolveBuildId(ChromeReleaseChannel.BETA);
        case BrowserTag.DEV:
          return await resolveBuildId(ChromeReleaseChannel.DEV);
        case BrowserTag.STABLE:
          return await resolveBuildId(ChromeReleaseChannel.STABLE);
        case BrowserTag.NIGHTLY:
        case BrowserTag.DEVEDITION:
        case BrowserTag.ESR:
          throw new Error(`${tag.toUpperCase()} is not available for ChromeDriver`);
      }
    }
    case Browser.CHROMEHEADLESSSHELL: {
      switch (tag) {
        case BrowserTag.LATEST:
        case BrowserTag.CANARY:
          return await resolveBuildId(ChromeReleaseChannel.CANARY);
        case BrowserTag.BETA:
          return await resolveBuildId(ChromeReleaseChannel.BETA);
        case BrowserTag.DEV:
          return await resolveBuildId(ChromeReleaseChannel.DEV);
        case BrowserTag.STABLE:
          return await resolveBuildId(ChromeReleaseChannel.STABLE);
        case BrowserTag.NIGHTLY:
        case BrowserTag.DEVEDITION:
        case BrowserTag.ESR:
          throw new Error(`${tag} is not available for chrome-headless-shell`);
      }
    }
    case Browser.CHROMIUM:
      switch (tag) {
        case BrowserTag.LATEST:
          return await resolveBuildId2(platform2);
        case BrowserTag.NIGHTLY:
        case BrowserTag.CANARY:
        case BrowserTag.DEV:
        case BrowserTag.DEVEDITION:
        case BrowserTag.BETA:
        case BrowserTag.STABLE:
        case BrowserTag.ESR:
          throw new Error(`${tag} is not supported for Chromium. Use 'latest' instead.`);
      }
  }
}
async function resolveBuildId4(browser, platform2, tag) {
  const browserTag = tag;
  if (Object.values(BrowserTag).includes(browserTag)) {
    return await resolveBuildIdForBrowserTag(browser, platform2, browserTag);
  }
  switch (browser) {
    case Browser.FIREFOX:
      return tag;
    case Browser.CHROME:
      const chromeResult = await resolveBuildId(tag);
      if (chromeResult) {
        return chromeResult;
      }
      return tag;
    case Browser.CHROMEDRIVER:
      const chromeDriverResult = await resolveBuildId(tag);
      if (chromeDriverResult) {
        return chromeDriverResult;
      }
      return tag;
    case Browser.CHROMEHEADLESSSHELL:
      const chromeHeadlessShellResult = await resolveBuildId(tag);
      if (chromeHeadlessShellResult) {
        return chromeHeadlessShellResult;
      }
      return tag;
    case Browser.CHROMIUM:
      return tag;
  }
}
function getVersionComparator(browser) {
  return versionComparators[browser];
}

// ../../node_modules/.pnpm/@puppeteer+browsers@2.10.6/node_modules/@puppeteer/browsers/lib/esm/Cache.js
var import_node_fs13 = __toESM(require("node:fs"), 1);
var import_node_os10 = __toESM(require("node:os"), 1);
var import_node_path24 = __toESM(require("node:path"), 1);
var import_debug = __toESM(require_src2(), 1);

// ../../node_modules/.pnpm/@puppeteer+browsers@2.10.6/node_modules/@puppeteer/browsers/lib/esm/detectPlatform.js
var import_node_os9 = __toESM(require("node:os"), 1);
function detectBrowserPlatform() {
  const platform2 = import_node_os9.default.platform();
  const arch3 = import_node_os9.default.arch();
  switch (platform2) {
    case "darwin":
      return arch3 === "arm64" ? BrowserPlatform.MAC_ARM : BrowserPlatform.MAC;
    case "linux":
      return arch3 === "arm64" ? BrowserPlatform.LINUX_ARM : BrowserPlatform.LINUX;
    case "win32":
      return arch3 === "x64" || // Windows 11 for ARM supports x64 emulation
      arch3 === "arm64" && isWindows11(import_node_os9.default.release()) ? BrowserPlatform.WIN64 : BrowserPlatform.WIN32;
    default:
      return void 0;
  }
}
function isWindows11(version4) {
  const parts = version4.split(".");
  if (parts.length > 2) {
    const major = parseInt(parts[0], 10);
    const minor = parseInt(parts[1], 10);
    const patch = parseInt(parts[2], 10);
    return major > 10 || major === 10 && minor > 0 || major === 10 && minor === 0 && patch >= 22e3;
  }
  return false;
}

// ../../node_modules/.pnpm/@puppeteer+browsers@2.10.6/node_modules/@puppeteer/browsers/lib/esm/Cache.js
var debugCache = (0, import_debug.default)("puppeteer:browsers:cache");
var InstalledBrowser = class {
  browser;
  buildId;
  platform;
  executablePath;
  #cache;
  /**
   * @internal
   */
  constructor(cache, browser, buildId, platform2) {
    this.#cache = cache;
    this.browser = browser;
    this.buildId = buildId;
    this.platform = platform2;
    this.executablePath = cache.computeExecutablePath({
      browser,
      buildId,
      platform: platform2
    });
  }
  /**
   * Path to the root of the installation folder. Use
   * {@link computeExecutablePath} to get the path to the executable binary.
   */
  get path() {
    return this.#cache.installationDir(this.browser, this.platform, this.buildId);
  }
  readMetadata() {
    return this.#cache.readMetadata(this.browser);
  }
  writeMetadata(metadata) {
    this.#cache.writeMetadata(this.browser, metadata);
  }
};
var Cache = class {
  #rootDir;
  constructor(rootDir) {
    this.#rootDir = rootDir;
  }
  /**
   * @internal
   */
  get rootDir() {
    return this.#rootDir;
  }
  browserRoot(browser) {
    return import_node_path24.default.join(this.#rootDir, browser);
  }
  metadataFile(browser) {
    return import_node_path24.default.join(this.browserRoot(browser), ".metadata");
  }
  readMetadata(browser) {
    const metatadaPath = this.metadataFile(browser);
    if (!import_node_fs13.default.existsSync(metatadaPath)) {
      return { aliases: {} };
    }
    const data = JSON.parse(import_node_fs13.default.readFileSync(metatadaPath, "utf8"));
    if (typeof data !== "object") {
      throw new Error(".metadata is not an object");
    }
    return data;
  }
  writeMetadata(browser, metadata) {
    const metatadaPath = this.metadataFile(browser);
    import_node_fs13.default.mkdirSync(import_node_path24.default.dirname(metatadaPath), { recursive: true });
    import_node_fs13.default.writeFileSync(metatadaPath, JSON.stringify(metadata, null, 2));
  }
  resolveAlias(browser, alias) {
    const metadata = this.readMetadata(browser);
    if (alias === "latest") {
      return Object.values(metadata.aliases || {}).sort(getVersionComparator(browser)).at(-1);
    }
    return metadata.aliases[alias];
  }
  installationDir(browser, platform2, buildId) {
    return import_node_path24.default.join(this.browserRoot(browser), `${platform2}-${buildId}`);
  }
  clear() {
    import_node_fs13.default.rmSync(this.#rootDir, {
      force: true,
      recursive: true,
      maxRetries: 10,
      retryDelay: 500
    });
  }
  uninstall(browser, platform2, buildId) {
    const metadata = this.readMetadata(browser);
    for (const alias of Object.keys(metadata.aliases)) {
      if (metadata.aliases[alias] === buildId) {
        delete metadata.aliases[alias];
      }
    }
    import_node_fs13.default.rmSync(this.installationDir(browser, platform2, buildId), {
      force: true,
      recursive: true,
      maxRetries: 10,
      retryDelay: 500
    });
  }
  getInstalledBrowsers() {
    if (!import_node_fs13.default.existsSync(this.#rootDir)) {
      return [];
    }
    const types3 = import_node_fs13.default.readdirSync(this.#rootDir);
    const browsers = types3.filter((t) => {
      return Object.values(Browser).includes(t);
    });
    return browsers.flatMap((browser) => {
      const files = import_node_fs13.default.readdirSync(this.browserRoot(browser));
      return files.map((file5) => {
        const result = parseFolderPath(import_node_path24.default.join(this.browserRoot(browser), file5));
        if (!result) {
          return null;
        }
        return new InstalledBrowser(this, browser, result.buildId, result.platform);
      }).filter((item) => {
        return item !== null;
      });
    });
  }
  computeExecutablePath(options) {
    options.platform ??= detectBrowserPlatform();
    if (!options.platform) {
      throw new Error(`Cannot download a binary for the provided platform: ${import_node_os10.default.platform()} (${import_node_os10.default.arch()})`);
    }
    try {
      options.buildId = this.resolveAlias(options.browser, options.buildId) ?? options.buildId;
    } catch {
      debugCache("could not read .metadata file for the browser");
    }
    const installationDir = this.installationDir(options.browser, options.platform, options.buildId);
    return import_node_path24.default.join(installationDir, executablePathByBrowser[options.browser](options.platform, options.buildId));
  }
};
function parseFolderPath(folderPath) {
  const name = import_node_path24.default.basename(folderPath);
  const splits = name.split("-");
  if (splits.length !== 2) {
    return;
  }
  const [platform2, buildId] = splits;
  if (!buildId || !platform2) {
    return;
  }
  return { platform: platform2, buildId };
}

// ../../node_modules/.pnpm/@puppeteer+browsers@2.10.6/node_modules/@puppeteer/browsers/lib/esm/debug.js
var import_debug2 = __toESM(require_src2(), 1);

// ../../node_modules/.pnpm/@puppeteer+browsers@2.10.6/node_modules/@puppeteer/browsers/lib/esm/launch.js
var debugLaunch = (0, import_debug2.default)("puppeteer:browsers:launcher");
function launch(opts) {
  return new Process(opts);
}
var CDP_WEBSOCKET_ENDPOINT_REGEX = /^DevTools listening on (ws:\/\/.*)$/;
var processListeners = /* @__PURE__ */ new Map();
var dispatchers = {
  exit: (...args) => {
    processListeners.get("exit")?.forEach((handler) => {
      return handler(...args);
    });
  },
  SIGINT: (...args) => {
    processListeners.get("SIGINT")?.forEach((handler) => {
      return handler(...args);
    });
  },
  SIGHUP: (...args) => {
    processListeners.get("SIGHUP")?.forEach((handler) => {
      return handler(...args);
    });
  },
  SIGTERM: (...args) => {
    processListeners.get("SIGTERM")?.forEach((handler) => {
      return handler(...args);
    });
  }
};
function subscribeToProcessEvent(event, handler) {
  const listeners = processListeners.get(event) || [];
  if (listeners.length === 0) {
    process.on(event, dispatchers[event]);
  }
  listeners.push(handler);
  processListeners.set(event, listeners);
}
function unsubscribeFromProcessEvent(event, handler) {
  const listeners = processListeners.get(event) || [];
  const existingListenerIdx = listeners.indexOf(handler);
  if (existingListenerIdx === -1) {
    return;
  }
  listeners.splice(existingListenerIdx, 1);
  processListeners.set(event, listeners);
  if (listeners.length === 0) {
    process.off(event, dispatchers[event]);
  }
}
var Process = class {
  #executablePath;
  #args;
  #browserProcess;
  #exited = false;
  // The browser process can be closed externally or from the driver process. We
  // need to invoke the hooks only once though but we don't know how many times
  // we will be invoked.
  #hooksRan = false;
  #onExitHook = async () => {
  };
  #browserProcessExiting;
  constructor(opts) {
    this.#executablePath = opts.executablePath;
    this.#args = opts.args ?? [];
    opts.pipe ??= false;
    opts.dumpio ??= false;
    opts.handleSIGINT ??= true;
    opts.handleSIGTERM ??= true;
    opts.handleSIGHUP ??= true;
    opts.detached ??= process.platform !== "win32";
    const stdio = this.#configureStdio({
      pipe: opts.pipe,
      dumpio: opts.dumpio
    });
    const env3 = opts.env || {};
    debugLaunch(`Launching ${this.#executablePath} ${this.#args.join(" ")}`, {
      detached: opts.detached,
      env: Object.keys(env3).reduce((res, key) => {
        if (key.toLowerCase().startsWith("puppeteer_")) {
          res[key] = env3[key];
        }
        return res;
      }, {}),
      stdio
    });
    this.#browserProcess = import_node_child_process4.default.spawn(this.#executablePath, this.#args, {
      detached: opts.detached,
      env: env3,
      stdio
    });
    debugLaunch(`Launched ${this.#browserProcess.pid}`);
    if (opts.dumpio) {
      this.#browserProcess.stderr?.pipe(process.stderr);
      this.#browserProcess.stdout?.pipe(process.stdout);
    }
    subscribeToProcessEvent("exit", this.#onDriverProcessExit);
    if (opts.handleSIGINT) {
      subscribeToProcessEvent("SIGINT", this.#onDriverProcessSignal);
    }
    if (opts.handleSIGTERM) {
      subscribeToProcessEvent("SIGTERM", this.#onDriverProcessSignal);
    }
    if (opts.handleSIGHUP) {
      subscribeToProcessEvent("SIGHUP", this.#onDriverProcessSignal);
    }
    if (opts.onExit) {
      this.#onExitHook = opts.onExit;
    }
    this.#browserProcessExiting = new Promise((resolve8, reject) => {
      this.#browserProcess.once("exit", async () => {
        debugLaunch(`Browser process ${this.#browserProcess.pid} onExit`);
        this.#clearListeners();
        this.#exited = true;
        try {
          await this.#runHooks();
        } catch (err) {
          reject(err);
          return;
        }
        resolve8();
      });
    });
  }
  async #runHooks() {
    if (this.#hooksRan) {
      return;
    }
    this.#hooksRan = true;
    await this.#onExitHook();
  }
  get nodeProcess() {
    return this.#browserProcess;
  }
  #configureStdio(opts) {
    if (opts.pipe) {
      if (opts.dumpio) {
        return ["ignore", "pipe", "pipe", "pipe", "pipe"];
      } else {
        return ["ignore", "ignore", "ignore", "pipe", "pipe"];
      }
    } else {
      if (opts.dumpio) {
        return ["pipe", "pipe", "pipe"];
      } else {
        return ["pipe", "ignore", "pipe"];
      }
    }
  }
  #clearListeners() {
    unsubscribeFromProcessEvent("exit", this.#onDriverProcessExit);
    unsubscribeFromProcessEvent("SIGINT", this.#onDriverProcessSignal);
    unsubscribeFromProcessEvent("SIGTERM", this.#onDriverProcessSignal);
    unsubscribeFromProcessEvent("SIGHUP", this.#onDriverProcessSignal);
  }
  #onDriverProcessExit = (_code) => {
    this.kill();
  };
  #onDriverProcessSignal = (signal) => {
    switch (signal) {
      case "SIGINT":
        this.kill();
        process.exit(130);
      case "SIGTERM":
      case "SIGHUP":
        void this.close();
        break;
    }
  };
  async close() {
    await this.#runHooks();
    if (!this.#exited) {
      this.kill();
    }
    return await this.#browserProcessExiting;
  }
  hasClosed() {
    return this.#browserProcessExiting;
  }
  kill() {
    debugLaunch(`Trying to kill ${this.#browserProcess.pid}`);
    if (this.#browserProcess && this.#browserProcess.pid && pidExists(this.#browserProcess.pid)) {
      try {
        debugLaunch(`Browser process ${this.#browserProcess.pid} exists`);
        if (process.platform === "win32") {
          try {
            import_node_child_process4.default.execSync(`taskkill /pid ${this.#browserProcess.pid} /T /F`);
          } catch (error101) {
            debugLaunch(`Killing ${this.#browserProcess.pid} using taskkill failed`, error101);
            this.#browserProcess.kill();
          }
        } else {
          const processGroupId = -this.#browserProcess.pid;
          try {
            process.kill(processGroupId, "SIGKILL");
          } catch (error101) {
            debugLaunch(`Killing ${this.#browserProcess.pid} using process.kill failed`, error101);
            this.#browserProcess.kill("SIGKILL");
          }
        }
      } catch (error101) {
        throw new Error(`${PROCESS_ERROR_EXPLANATION}
Error cause: ${isErrorLike(error101) ? error101.stack : error101}`);
      }
    }
    this.#clearListeners();
  }
  waitForLineOutput(regex3, timeout = 0) {
    if (!this.#browserProcess.stderr) {
      throw new Error("`browserProcess` does not have stderr.");
    }
    const rl2 = import_node_readline2.default.createInterface(this.#browserProcess.stderr);
    let stderr2 = "";
    return new Promise((resolve8, reject) => {
      rl2.on("line", onLine);
      rl2.on("close", onClose);
      this.#browserProcess.on("exit", onClose);
      this.#browserProcess.on("error", onClose);
      const timeoutId = timeout > 0 ? setTimeout(onTimeout, timeout) : void 0;
      const cleanup = () => {
        clearTimeout(timeoutId);
        rl2.off("line", onLine);
        rl2.off("close", onClose);
        rl2.close();
        this.#browserProcess.off("exit", onClose);
        this.#browserProcess.off("error", onClose);
      };
      function onClose(error101) {
        cleanup();
        reject(new Error([
          `Failed to launch the browser process!${error101 ? " " + error101.message : ""}`,
          stderr2,
          "",
          "TROUBLESHOOTING: https://pptr.dev/troubleshooting",
          ""
        ].join("\n")));
      }
      function onTimeout() {
        cleanup();
        reject(new TimeoutError(`Timed out after ${timeout} ms while waiting for the WS endpoint URL to appear in stdout!`));
      }
      function onLine(line) {
        stderr2 += line + "\n";
        const match = line.match(regex3);
        if (!match) {
          return;
        }
        cleanup();
        resolve8(match[1]);
      }
    });
  }
};
var PROCESS_ERROR_EXPLANATION = `Puppeteer was unable to kill the process which ran the browser binary.
This means that, on future Puppeteer launches, Puppeteer might not be able to launch the browser.
Please check your open processes and ensure that the browser processes that Puppeteer launched have been killed.
If you think this is a bug, please report it on the Puppeteer issue tracker.`;
function pidExists(pid) {
  try {
    return process.kill(pid, 0);
  } catch (error101) {
    if (isErrnoException(error101)) {
      if (error101.code && error101.code === "ESRCH") {
        return false;
      }
    }
    throw error101;
  }
}
function isErrorLike(obj) {
  return typeof obj === "object" && obj !== null && "name" in obj && "message" in obj;
}
function isErrnoException(obj) {
  return isErrorLike(obj) && ("errno" in obj || "code" in obj || "path" in obj || "syscall" in obj);
}
var TimeoutError = class extends Error {
  /**
   * @internal
   */
  constructor(message) {
    super(message);
    this.name = this.constructor.name;
    Error.captureStackTrace(this, this.constructor);
  }
};

// ../../node_modules/.pnpm/@puppeteer+browsers@2.10.6/node_modules/@puppeteer/browsers/lib/esm/install.js
var import_node_assert16 = __toESM(require("node:assert"), 1);
var import_node_child_process6 = require("node:child_process");
var import_node_fs15 = require("node:fs");
var import_promises14 = require("node:fs/promises");
var import_node_os11 = __toESM(require("node:os"), 1);
var import_node_path25 = __toESM(require("node:path"), 1);
var import_progress = __toESM(require_progress(), 1);

// ../../node_modules/.pnpm/@puppeteer+browsers@2.10.6/node_modules/@puppeteer/browsers/lib/esm/fileUtil.js
var import_node_child_process5 = require("node:child_process");
var import_node_fs14 = require("node:fs");
var import_promises13 = require("node:fs/promises");
var path50 = __toESM(require("node:path"), 1);
var import_node_stream2 = require("node:stream");
var import_debug4 = __toESM(require_src2(), 1);
var debugFileUtil = (0, import_debug4.default)("puppeteer:browsers:fileUtil");
async function unpackArchive(archivePath, folderPath) {
  if (!path50.isAbsolute(folderPath)) {
    folderPath = path50.resolve(process.cwd(), folderPath);
  }
  if (archivePath.endsWith(".zip")) {
    const extractZip = await Promise.resolve().then(() => __toESM(require_extract_zip(), 1));
    await extractZip.default(archivePath, { dir: folderPath });
  } else if (archivePath.endsWith(".tar.bz2")) {
    await extractTar(archivePath, folderPath, "bzip2");
  } else if (archivePath.endsWith(".dmg")) {
    await (0, import_promises13.mkdir)(folderPath);
    await installDMG(archivePath, folderPath);
  } else if (archivePath.endsWith(".exe")) {
    const result = (0, import_node_child_process5.spawnSync)(archivePath, [`/ExtractDir=${folderPath}`], {
      env: {
        __compat_layer: "RunAsInvoker"
      }
    });
    if (result.status !== 0) {
      throw new Error(`Failed to extract ${archivePath} to ${folderPath}: ${result.output}`);
    }
  } else if (archivePath.endsWith(".tar.xz")) {
    await extractTar(archivePath, folderPath, "xz");
  } else {
    throw new Error(`Unsupported archive format: ${archivePath}`);
  }
}
function createTransformStream(child) {
  const stream = new import_node_stream2.Stream.Transform({
    transform(chunk, encoding, callback) {
      if (!child.stdin.write(chunk, encoding)) {
        child.stdin.once("drain", callback);
      } else {
        callback();
      }
    },
    flush(callback) {
      if (child.stdout.destroyed) {
        callback();
      } else {
        child.stdin.end();
        child.stdout.on("close", callback);
      }
    }
  });
  child.stdin.on("error", (e) => {
    if ("code" in e && e.code === "EPIPE") {
      stream.emit("end");
    } else {
      stream.destroy(e);
    }
  });
  child.stdout.on("data", (data) => {
    return stream.push(data);
  }).on("error", (e) => {
    return stream.destroy(e);
  });
  child.once("close", () => {
    return stream.end();
  });
  return stream;
}
var internalConstantsForTesting = {
  xz: "xz",
  bzip2: "bzip2"
};
async function extractTar(tarPath, folderPath, decompressUtilityName) {
  const tarFs = await Promise.resolve().then(() => __toESM(require_tar_fs(), 1));
  return await new Promise((fulfill, reject) => {
    function handleError(utilityName) {
      return (error101) => {
        if ("code" in error101 && error101.code === "ENOENT") {
          error101 = new Error(`\`${utilityName}\` utility is required to unpack this archive`, {
            cause: error101
          });
        }
        reject(error101);
      };
    }
    const unpack2 = (0, import_node_child_process5.spawn)(internalConstantsForTesting[decompressUtilityName], ["-d"], {
      stdio: ["pipe", "pipe", "inherit"]
    }).once("error", handleError(decompressUtilityName)).once("exit", (code) => {
      debugFileUtil(`${decompressUtilityName} exited, code=${code}`);
    });
    const tar = tarFs.extract(folderPath);
    tar.once("error", handleError("tar"));
    tar.once("finish", fulfill);
    (0, import_node_fs14.createReadStream)(tarPath).pipe(createTransformStream(unpack2)).pipe(tar);
  });
}
async function installDMG(dmgPath, folderPath) {
  const { stdout: stdout2 } = (0, import_node_child_process5.spawnSync)(`hdiutil`, [
    "attach",
    "-nobrowse",
    "-noautoopen",
    dmgPath
  ]);
  const volumes = stdout2.toString("utf8").match(/\/Volumes\/(.*)/m);
  if (!volumes) {
    throw new Error(`Could not find volume path in ${stdout2}`);
  }
  const mountPath = volumes[0];
  try {
    const fileNames = await (0, import_promises13.readdir)(mountPath);
    const appName = fileNames.find((item) => {
      return typeof item === "string" && item.endsWith(".app");
    });
    if (!appName) {
      throw new Error(`Cannot find app in ${mountPath}`);
    }
    const mountedPath = path50.join(mountPath, appName);
    (0, import_node_child_process5.spawnSync)("cp", ["-R", mountedPath, folderPath]);
  } finally {
    (0, import_node_child_process5.spawnSync)("hdiutil", ["detach", mountPath, "-quiet"]);
  }
}

// ../../node_modules/.pnpm/@puppeteer+browsers@2.10.6/node_modules/@puppeteer/browsers/lib/esm/install.js
var debugInstall = (0, import_debug2.default)("puppeteer:browsers:install");
var times = /* @__PURE__ */ new Map();
function debugTime(label) {
  times.set(label, process.hrtime());
}
function debugTimeEnd(label) {
  const end = process.hrtime();
  const start = times.get(label);
  if (!start) {
    return;
  }
  const duration5 = end[0] * 1e3 + end[1] / 1e6 - (start[0] * 1e3 + start[1] / 1e6);
  debugInstall(`Duration for ${label}: ${duration5}ms`);
}
async function install(options) {
  options.platform ??= detectBrowserPlatform();
  options.unpack ??= true;
  if (!options.platform) {
    throw new Error(`Cannot download a binary for the provided platform: ${import_node_os11.default.platform()} (${import_node_os11.default.arch()})`);
  }
  const url46 = getDownloadUrl(options.browser, options.platform, options.buildId, options.baseUrl);
  try {
    return await installUrl(url46, options);
  } catch (err) {
    if (options.baseUrl && !options.forceFallbackForTesting) {
      throw err;
    }
    debugInstall(`Error downloading from ${url46}.`);
    switch (options.browser) {
      case Browser.CHROME:
      case Browser.CHROMEDRIVER:
      case Browser.CHROMEHEADLESSSHELL: {
        debugInstall(`Trying to find download URL via https://googlechromelabs.github.io/chrome-for-testing.`);
        const version4 = await getJSON(new URL(`https://googlechromelabs.github.io/chrome-for-testing/${options.buildId}.json`));
        let platform2 = "";
        switch (options.platform) {
          case BrowserPlatform.LINUX:
            platform2 = "linux64";
            break;
          case BrowserPlatform.MAC_ARM:
            platform2 = "mac-arm64";
            break;
          case BrowserPlatform.MAC:
            platform2 = "mac-x64";
            break;
          case BrowserPlatform.WIN32:
            platform2 = "win32";
            break;
          case BrowserPlatform.WIN64:
            platform2 = "win64";
            break;
        }
        const backupUrl = version4.downloads[options.browser]?.find((link) => {
          return link["platform"] === platform2;
        })?.url;
        if (backupUrl) {
          if (backupUrl === url46.toString()) {
            throw err;
          }
          debugInstall(`Falling back to downloading from ${backupUrl}.`);
          return await installUrl(new URL(backupUrl), options);
        }
        throw err;
      }
      default:
        throw err;
    }
  }
}
async function installDeps(installedBrowser) {
  if (process.platform !== "linux" || installedBrowser.platform !== BrowserPlatform.LINUX) {
    return;
  }
  const depsPath = import_node_path25.default.join(import_node_path25.default.dirname(installedBrowser.executablePath), "deb.deps");
  if (!(0, import_node_fs15.existsSync)(depsPath)) {
    debugInstall(`deb.deps file was not found at ${depsPath}`);
    return;
  }
  const data = (0, import_node_fs15.readFileSync)(depsPath, "utf-8").split("\n").join(",");
  if (process.getuid?.() !== 0) {
    throw new Error("Installing system dependencies requires root privileges");
  }
  let result = (0, import_node_child_process6.spawnSync)("apt-get", ["-v"]);
  if (result.status !== 0) {
    throw new Error("Failed to install system dependencies: apt-get does not seem to be available");
  }
  debugInstall(`Trying to install dependencies: ${data}`);
  result = (0, import_node_child_process6.spawnSync)("apt-get", [
    "satisfy",
    "-y",
    data,
    "--no-install-recommends"
  ]);
  if (result.status !== 0) {
    throw new Error(`Failed to install system dependencies: status=${result.status},error=${result.error},stdout=${result.stdout.toString("utf8")},stderr=${result.stderr.toString("utf8")}`);
  }
  debugInstall(`Installed system dependencies ${data}`);
}
async function installUrl(url46, options) {
  options.platform ??= detectBrowserPlatform();
  if (!options.platform) {
    throw new Error(`Cannot download a binary for the provided platform: ${import_node_os11.default.platform()} (${import_node_os11.default.arch()})`);
  }
  let downloadProgressCallback = options.downloadProgressCallback;
  if (downloadProgressCallback === "default") {
    downloadProgressCallback = await makeProgressCallback(options.browser, options.buildIdAlias ?? options.buildId);
  }
  const fileName = decodeURIComponent(url46.toString()).split("/").pop();
  (0, import_node_assert16.default)(fileName, `A malformed download URL was found: ${url46}.`);
  const cache = new Cache(options.cacheDir);
  const browserRoot = cache.browserRoot(options.browser);
  const archivePath = import_node_path25.default.join(browserRoot, `${options.buildId}-${fileName}`);
  if (!(0, import_node_fs15.existsSync)(browserRoot)) {
    await (0, import_promises14.mkdir)(browserRoot, { recursive: true });
  }
  if (!options.unpack) {
    if ((0, import_node_fs15.existsSync)(archivePath)) {
      return archivePath;
    }
    debugInstall(`Downloading binary from ${url46}`);
    debugTime("download");
    await downloadFile(url46, archivePath, downloadProgressCallback);
    debugTimeEnd("download");
    return archivePath;
  }
  const outputPath = cache.installationDir(options.browser, options.platform, options.buildId);
  try {
    if ((0, import_node_fs15.existsSync)(outputPath)) {
      const installedBrowser2 = new InstalledBrowser(cache, options.browser, options.buildId, options.platform);
      if (!(0, import_node_fs15.existsSync)(installedBrowser2.executablePath)) {
        throw new Error(`The browser folder (${outputPath}) exists but the executable (${installedBrowser2.executablePath}) is missing`);
      }
      await runSetup(installedBrowser2);
      if (options.installDeps) {
        await installDeps(installedBrowser2);
      }
      return installedBrowser2;
    }
    debugInstall(`Downloading binary from ${url46}`);
    try {
      debugTime("download");
      await downloadFile(url46, archivePath, downloadProgressCallback);
    } finally {
      debugTimeEnd("download");
    }
    debugInstall(`Installing ${archivePath} to ${outputPath}`);
    try {
      debugTime("extract");
      await unpackArchive(archivePath, outputPath);
    } finally {
      debugTimeEnd("extract");
    }
    const installedBrowser = new InstalledBrowser(cache, options.browser, options.buildId, options.platform);
    if (options.buildIdAlias) {
      const metadata = installedBrowser.readMetadata();
      metadata.aliases[options.buildIdAlias] = options.buildId;
      installedBrowser.writeMetadata(metadata);
    }
    await runSetup(installedBrowser);
    if (options.installDeps) {
      await installDeps(installedBrowser);
    }
    return installedBrowser;
  } finally {
    if ((0, import_node_fs15.existsSync)(archivePath)) {
      await (0, import_promises14.unlink)(archivePath);
    }
  }
}
async function runSetup(installedBrowser) {
  if ((installedBrowser.platform === BrowserPlatform.WIN32 || installedBrowser.platform === BrowserPlatform.WIN64) && installedBrowser.browser === Browser.CHROME && installedBrowser.platform === detectBrowserPlatform()) {
    try {
      debugTime("permissions");
      const browserDir = import_node_path25.default.dirname(installedBrowser.executablePath);
      const setupExePath = import_node_path25.default.join(browserDir, "setup.exe");
      if (!(0, import_node_fs15.existsSync)(setupExePath)) {
        return;
      }
      (0, import_node_child_process6.spawnSync)(import_node_path25.default.join(browserDir, "setup.exe"), [`--configure-browser-in-directory=` + browserDir], {
        shell: true
      });
    } finally {
      debugTimeEnd("permissions");
    }
  }
}
function getDownloadUrl(browser, platform2, buildId, baseUrl) {
  return new URL(downloadUrls[browser](platform2, buildId, baseUrl));
}
function makeProgressCallback(browser, buildId) {
  let progressBar;
  let lastDownloadedBytes = 0;
  return (downloadedBytes, totalBytes) => {
    if (!progressBar) {
      progressBar = new import_progress.default(`Downloading ${browser} ${buildId} - ${toMegabytes(totalBytes)} [:bar] :percent :etas `, {
        complete: "=",
        incomplete: " ",
        width: 20,
        total: totalBytes
      });
    }
    const delta = downloadedBytes - lastDownloadedBytes;
    lastDownloadedBytes = downloadedBytes;
    progressBar.tick(delta);
  };
}
function toMegabytes(bytes) {
  const mb = bytes / 1e3 / 1e3;
  return `${Math.round(mb * 10) / 10} MB`;
}

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/browser-rendering/binding.worker.ts
var import_fs29 = __toESM(require("fs"));
var import_path29 = __toESM(require("path"));
var import_url29 = __toESM(require("url"));
var contents29;
function binding_worker_default2() {
  if (contents29 !== void 0) return contents29;
  const filePath = import_path29.default.join(__dirname, "workers", "browser-rendering/binding.worker.js");
  contents29 = import_fs29.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url29.default.pathToFileURL(filePath);
  return contents29;
}

// src/plugins/browser-rendering/install.ts
var import_node_fs16 = __toESM(require("node:fs"));
var import_node_path26 = __toESM(require("node:path"));
var INSTALL_COMPLETE_MARKER = ".miniflare-install-complete";
var installs = {
  /**
   * In-flight installs. Without this, two overlapping
   * `ensureBrowserInstalled()` calls both reach `install()`; the second sees
   * the first's partially-extracted directory, short-circuits, and hands back
   * a path to a Chrome that cannot launch. That is the common shape in tests,
   * where a timed-out test abandons its install but the download keeps running
   * in the background and the next test starts immediately.
   */
  inFlight: /* @__PURE__ */ new Map(),
  /**
   * Installation directories Chrome has launched from during this process.
   *
   * A directory is added synchronously on a successful launch, ahead of the
   * on-disk marker, which is written asynchronously and best-effort. Launches
   * run concurrently — one per session acquire — so without this there is a
   * window in which one session has a working Chrome running while another,
   * having just failed, still sees no marker and would delete the directory
   * out from under it.
   */
  verifiedDirs: /* @__PURE__ */ new Set(),
  /**
   * Bumped whenever an installation is discarded, so that concurrent launches
   * can tell "nobody has dealt with this yet" from "a peer already replaced it
   * while I was failing".
   */
  generations: /* @__PURE__ */ new Map(),
  /** Serialises recovery per installation directory. */
  locks: /* @__PURE__ */ new Map()
};
function withInstallLock(installDir, fn) {
  const previous = installs.locks.get(installDir) ?? Promise.resolve();
  const result = previous.catch(() => {
  }).then(fn);
  installs.locks.set(
    installDir,
    result.catch(() => {
    })
  );
  return result;
}
function getInstallGeneration(installDir) {
  return installs.generations.get(installDir) ?? 0;
}
async function ensureBrowserInstalled({
  browserVersion,
  log: log2,
  onProgress
}) {
  const platform2 = detectBrowserPlatform();
  if (!platform2) {
    throw new Error("The current platform is not supported.");
  }
  const browser = Browser.CHROME;
  const cacheDir = getGlobalWranglerCachePath();
  const buildId = await resolveBuildId4(browser, platform2, browserVersion);
  const installDir = getInstallDir(cacheDir, browser, platform2, buildId);
  const installOptions = {
    browser,
    platform: platform2,
    cacheDir,
    buildId,
    downloadProgressCallback: onProgress
  };
  const existing = installs.inFlight.get(installDir);
  if (existing) {
    log2.debug(`Waiting for an in-progress Chrome install at ${installDir}`);
    return toBrowserInstall(await existing, installDir, log2);
  }
  const pending = installWithCorruptedCacheRecovery(
    installOptions,
    log2
  ).finally(() => {
    installs.inFlight.delete(installDir);
  });
  installs.inFlight.set(installDir, pending);
  return toBrowserInstall(await pending, installDir, log2);
}
function toBrowserInstall(installed, installDir, log2) {
  const generation = getInstallGeneration(installDir);
  return {
    executablePath: installed.executablePath,
    installDir,
    markVerified: () => markInstallVerified(installDir, log2),
    discard: () => discardIncompleteInstall(installDir, generation, log2)
  };
}
function isInstallMarkedComplete(installDir) {
  return import_node_fs16.default.existsSync(import_node_path26.default.join(installDir, INSTALL_COMPLETE_MARKER));
}
function isInstallVerified(installDir) {
  return installs.verifiedDirs.has(installDir) || isInstallMarkedComplete(installDir);
}
async function markInstallVerified(installDir, log2) {
  installs.verifiedDirs.add(installDir);
  if (isInstallMarkedComplete(installDir)) {
    return;
  }
  try {
    await import_node_fs16.default.promises.writeFile(
      import_node_path26.default.join(installDir, INSTALL_COMPLETE_MARKER),
      ""
    );
  } catch (e) {
    log2.debug(`Unable to mark the Chrome install as verified: ${e}`);
  }
}
var DISCARD_TIMEOUT = 1e4;
var DISCARD_RETRY_DELAY = 500;
async function discardIncompleteInstall(installDir, generation, log2) {
  return withInstallLock(installDir, async () => {
    if (getInstallGeneration(installDir) !== generation) {
      log2.debug(
        `Not clearing ${installDir}: a concurrent launch already replaced it.`
      );
      return { outcome: "superseded" };
    }
    if (isInstallVerified(installDir)) {
      return { outcome: "verified" };
    }
    log2.warn(
      `Chrome failed to start from ${installDir}, which it has never successfully started from; clearing it so it can be downloaded again.`
    );
    const deadline = Date.now() + DISCARD_TIMEOUT;
    let lastError;
    do {
      try {
        await removeDir(installDir);
        installs.generations.set(installDir, generation + 1);
        return { outcome: "cleared" };
      } catch (e) {
        lastError = e;
        log2.debug(`Could not clear ${installDir} yet, retrying: ${e}`);
        await new Promise(
          (resolve8) => setTimeout(resolve8, DISCARD_RETRY_DELAY)
        );
      }
    } while (Date.now() < deadline);
    return { outcome: "cleanup-failed", cause: lastError };
  });
}
function getInstallDir(cacheDir, browser, platform2, buildId) {
  return import_node_path26.default.join(cacheDir, browser, `${platform2}-${buildId}`);
}
var CORRUPTED_CACHE_ERROR_PATTERN = /The browser folder \((.+?)\) exists but the executable .+? is missing/;
async function installWithCorruptedCacheRecovery(installOptions, log2) {
  try {
    return await install(installOptions);
  } catch (e) {
    const match = e?.message?.match(CORRUPTED_CACHE_ERROR_PATTERN);
    if (!match) {
      throw e;
    }
    const corruptedPath = match[1];
    log2.warn(
      `Detected corrupted Chrome cache at ${corruptedPath}; clearing and retrying install.`
    );
    try {
      await removeDir(corruptedPath);
    } catch (cleanupError) {
      throw new Error(
        `Failed to clear corrupted Chrome cache at ${corruptedPath} after detecting "${e.message}". Manual cleanup may be required.`,
        { cause: cleanupError }
      );
    }
    try {
      return await install(installOptions);
    } catch (retryError) {
      throw new Error(
        `Chrome install failed after clearing corrupted cache at ${corruptedPath}: ${retryError.message}`,
        { cause: retryError }
      );
    }
  }
}

// src/plugins/browser-rendering/process.ts
var import_ws3 = __toESM(require("ws"));
var BROWSER_CLOSE_TIMEOUT = 5e3;
var BrowserStartupError = class extends Error {
  name = "BrowserStartupError";
  constructor(cause) {
    super(cause instanceof Error ? cause.message : String(cause), { cause });
  }
};
function waitForGracefulClose(browserProcess, wsEndpoint, timeoutMs) {
  return new Promise((resolve8) => {
    const socket = new import_ws3.default(wsEndpoint);
    const timeout = setTimeout(() => finish(false), timeoutMs);
    let finished = false;
    function finish(closed) {
      if (finished) return;
      finished = true;
      clearTimeout(timeout);
      socket.terminate();
      resolve8(closed);
    }
    void browserProcess.hasClosed().then(
      () => finish(true),
      () => finish(false)
    );
    socket.once("open", () => {
      socket.send(
        JSON.stringify({ id: 1, method: "Browser.close" }),
        (error101) => {
          if (error101) finish(false);
        }
      );
    });
    socket.once("error", () => finish(false));
  });
}
async function waitForExit2(browserProcess, timeoutMs = BROWSER_CLOSE_TIMEOUT) {
  let timeout;
  await Promise.race([
    browserProcess.hasClosed().catch(() => {
    }),
    new Promise((resolve8) => {
      timeout = setTimeout(resolve8, timeoutMs);
    })
  ]);
  clearTimeout(timeout);
}
async function closeBrowserProcess(browserProcess, wsEndpoint, timeoutMs = BROWSER_CLOSE_TIMEOUT) {
  if (await waitForGracefulClose(browserProcess, wsEndpoint, timeoutMs)) return;
  browserProcess.kill();
  await waitForExit2(browserProcess, timeoutMs);
}

// src/plugins/browser-rendering/index.ts
var BROWSER_RENDERING_PLUGIN_NAME = "browser-rendering";
var BROWSER_RENDERING_REMOTE_SERVICE_NAME = `${BROWSER_RENDERING_PLUGIN_NAME}:remote`;
var BROWSER_RENDERING_PLUGIN = {
  bindingTypeDescription: "Browser Rendering",
  async getBindings(options) {
    return getEnvBindingsOfType(options.config, "browser").map(
      ([name, binding]) => {
        const remoteProxyConnectionString = getRemoteProxyConnectionString(
          binding,
          options.dev
        );
        return {
          name,
          service: remoteProxyConnectionString ? {
            name: BROWSER_RENDERING_REMOTE_SERVICE_NAME,
            props: buildRemoteProxyProps(remoteProxyConnectionString, name)
          } : {
            name: getUserBindingServiceName(
              BROWSER_RENDERING_PLUGIN_NAME,
              "service"
            )
          }
        };
      }
    );
  },
  getNodeBindings(options) {
    return Object.fromEntries(
      getEnvBindingsOfType(options.config, "browser").map(([name]) => [
        name,
        new ProxyNodeBinding()
      ])
    );
  },
  async getServices({ options }) {
    const services = [];
    for (const [, binding] of getEnvBindingsOfType(options.config, "browser")) {
      const remoteProxyConnectionString = getRemoteProxyConnectionString(
        binding,
        options.dev
      );
      if (remoteProxyConnectionString) {
        services.push({
          name: BROWSER_RENDERING_REMOTE_SERVICE_NAME,
          worker: remoteProxyClientWorker()
        });
        continue;
      }
      services.push({
        name: getUserBindingServiceName(
          BROWSER_RENDERING_PLUGIN_NAME,
          "service"
        ),
        worker: {
          compatibilityDate: "2025-05-01",
          compatibilityFlags: ["nodejs_compat"],
          modules: [
            {
              name: "index.worker.js",
              esModule: binding_worker_default2()
            }
          ],
          bindings: [
            WORKER_BINDING_SERVICE_LOOPBACK,
            {
              name: "BrowserSession",
              durableObjectNamespace: {
                className: "BrowserSession"
              }
            }
          ],
          durableObjectNamespaces: [
            {
              className: "BrowserSession",
              uniqueKey: "miniflare-BrowserSession"
            }
          ],
          durableObjectStorage: { inMemory: kVoid }
        }
      });
    }
    return services;
  }
};
async function launchBrowser({
  browserVersion,
  headful,
  log: log2,
  tmpPath
}) {
  const sessionId = crypto.randomUUID();
  const s = spinner();
  let startedDownloading = false;
  const install2 = async () => {
    try {
      return await ensureBrowserInstalled({
        browserVersion,
        log: log2,
        onProgress: (downloadedBytes, totalBytes) => {
          if (!startedDownloading) {
            s.start(`Downloading browser...`);
            startedDownloading = true;
          }
          const progress = Math.round(downloadedBytes / totalBytes * 100);
          s.update(`Downloading browser... ${progress}%`);
        }
      });
    } catch (e) {
      if (startedDownloading) {
        s.stop(`${red("failed")} ${dim(`browser download`)}`);
        startedDownloading = false;
      }
      throw e;
    } finally {
      if (startedDownloading) {
        s.stop(`${brandColor("downloaded")} ${dim(`browser`)}`);
        startedDownloading = false;
      }
    }
  };
  let installed = await install2();
  log2.debug(
    `Chrome ${browserVersion} available at ${installed.executablePath}`
  );
  const disabledFeatures = [
    "Translate",
    // AcceptCHFrame disabled because of crbug.com/1348106.
    "AcceptCHFrame",
    "MediaRouter",
    "OptimizationHints",
    "ProcessPerSiteUpToMainFrameThreshold",
    "IsolateSandboxedIframes"
  ];
  const args = [
    "--allow-pre-commit-input",
    "--disable-background-networking",
    "--disable-background-timer-throttling",
    "--disable-backgrounding-occluded-windows",
    "--disable-breakpad",
    "--disable-client-side-phishing-detection",
    "--disable-component-extensions-with-background-pages",
    "--disable-crash-reporter",
    // No crash reporting in CfT.
    "--disable-default-apps",
    "--disable-dev-shm-usage",
    "--disable-hang-monitor",
    "--disable-infobars",
    "--disable-ipc-flooding-protection",
    "--disable-popup-blocking",
    "--disable-prompt-on-repost",
    "--disable-renderer-backgrounding",
    "--disable-search-engine-choice-screen",
    "--disable-sync",
    "--enable-automation",
    "--export-tagged-pdf",
    "--force-color-profile=srgb",
    "--generate-pdf-document-outline",
    "--metrics-recording-only",
    "--no-first-run",
    "--password-store=basic",
    "--use-mock-keychain",
    `--disable-features=${disabledFeatures.join(",")}`,
    ...headful ? [] : ["--headless=new", "--hide-scrollbars", "--mute-audio"],
    "--disable-extensions",
    "about:blank",
    "--remote-debugging-port=0"
  ];
  let attempt = 0;
  const launchOnce = async () => {
    const tempUserData = import_node_path27.default.join(
      tmpPath,
      "browser-rendering",
      `profile-${sessionId}-${attempt++}`
    );
    await import_node_fs17.default.promises.mkdir(tempUserData, { recursive: true });
    let started = false;
    const launchArgs = [...args, `--user-data-dir=${tempUserData}`];
    const browserProcess = launch({
      executablePath: installed.executablePath,
      args: process.env.CI ? [...launchArgs, "--no-sandbox"] : launchArgs,
      handleSIGTERM: false,
      dumpio: false,
      pipe: false,
      onExit: async () => {
        try {
          await removeDir(tempUserData);
        } catch (e) {
          log2.debug(`Unable to remove Chrome user data directory: ${e}`);
        }
      }
    });
    try {
      const wsEndpoint = await browserProcess.waitForLineOutput(
        CDP_WEBSOCKET_ENDPOINT_REGEX,
        // Note: we pass an explicit timeout so the promise rejects instead of hanging forever
        //       when Chrome fails to start or crashes before printing the DevTools URL.
        //       Five minutes is generous enough to cover on-demand browser downloads on slow
        //       connections while still failing within a reasonable window.
        5 * 60 * 1e3
      );
      started = true;
      await waitForBrowserReady(wsEndpoint, log2);
      return { browserProcess, wsEndpoint };
    } catch (e) {
      try {
        browserProcess.kill();
      } catch {
      }
      await waitForExit2(browserProcess);
      throw started ? e : new BrowserStartupError(e);
    }
  };
  let launched;
  try {
    launched = await launchOnce();
  } catch (e) {
    if (!(e instanceof BrowserStartupError)) {
      throw e;
    }
    const discarded = await installed.discard();
    if (discarded.outcome === "cleanup-failed") {
      throw new Error(
        `Chrome failed to launch from ${installed.installDir}, and the directory could not be removed to re-download it (${discarded.cause}). Delete it manually and try again. Chrome failed with: ${e.message}`,
        { cause: discarded.cause }
      );
    }
    if (discarded.outcome === "verified") {
      throw e;
    }
    log2.debug(`Retrying Chrome launch after re-installing: ${e}`);
    installed = await install2();
    launched = await launchOnce();
  }
  await installed.markVerified();
  const startTime = Date.now();
  return {
    sessionId,
    browserProcess: launched.browserProcess,
    startTime,
    wsEndpoint: launched.wsEndpoint
  };
}
async function waitForBrowserReady(wsEndpoint, log2) {
  const timeoutMs = 5e3;
  const initialDelayMs = 25;
  const maxDelayMs = 250;
  const perRequestTimeoutMs = 500;
  const probeUrl = `${new URL(wsEndpoint.replace("ws://", "http://")).origin}/json/version`;
  const deadline = Date.now() + timeoutMs;
  let attempt = 0;
  let lastError;
  while (Date.now() < deadline) {
    try {
      const response = await fetch(probeUrl, {
        signal: AbortSignal.timeout(perRequestTimeoutMs)
      });
      await response.arrayBuffer();
      if (response.ok) {
        if (attempt > 0) {
          log2.debug(`Chrome ready after ${attempt + 1} attempt(s)`);
        }
        return;
      }
      lastError = new Error(
        `Chrome readiness probe got status ${response.status}`
      );
    } catch (e) {
      lastError = e;
    }
    const delay = Math.min(maxDelayMs, initialDelayMs * 2 ** attempt);
    await new Promise((resolve8) => setTimeout(resolve8, delay));
    attempt++;
  }
  throw new Error(
    `Chrome readiness probe at ${probeUrl} timed out after ${timeoutMs}ms`,
    { cause: lastError }
  );
}

// src/plugins/d1/index.ts
var import_promises15 = __toESM(require("node:fs/promises"));

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/d1/database.worker.ts
var import_fs30 = __toESM(require("fs"));
var import_path30 = __toESM(require("path"));
var import_url30 = __toESM(require("url"));
var contents30;
function database_worker_default() {
  if (contents30 !== void 0) return contents30;
  const filePath = import_path30.default.join(__dirname, "workers", "d1/database.worker.js");
  contents30 = import_fs30.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url30.default.pathToFileURL(filePath);
  return contents30;
}

// src/plugins/d1/index.ts
var D1_PLUGIN_NAME = "d1";
var D1_STORAGE_SERVICE_NAME = `${D1_PLUGIN_NAME}:storage`;
var D1_DATABASE_SERVICE_PREFIX = `${D1_PLUGIN_NAME}:db`;
var D1_LOCAL_ENTRY_SERVICE_NAME = `${D1_PLUGIN_NAME}:db:entry`;
var D1_REMOTE_SERVICE_NAME = `${D1_PLUGIN_NAME}:db:remote`;
var D1_DATABASE_OBJECT_CLASS_NAME = "D1DatabaseObject";
var D1_DATABASE_OBJECT = {
  serviceName: D1_DATABASE_SERVICE_PREFIX,
  className: D1_DATABASE_OBJECT_CLASS_NAME
};
var D1_PLUGIN = {
  bindingTypeDescription: "D1 database",
  getBindings(options) {
    return getEnvBindingsOfType(options.config, "d1").map(
      ([name, binding]) => {
        const id = binding.id;
        const remoteProxyConnectionString = getRemoteProxyConnectionString(
          binding,
          options.dev
        );
        const serviceDesignator = remoteProxyConnectionString ? {
          name: D1_REMOTE_SERVICE_NAME,
          props: buildRemoteProxyProps(remoteProxyConnectionString, name)
        } : {
          name: D1_LOCAL_ENTRY_SERVICE_NAME,
          props: buildObjectEntryProps(id)
        };
        return {
          name,
          wrapped: {
            moduleName: "cloudflare-internal:d1-api",
            innerBindings: [
              {
                name: "fetcher",
                service: serviceDesignator
              }
            ]
          }
        };
      }
    );
  },
  getNodeBindings(options) {
    return Object.fromEntries(
      getEnvBindingsOfType(options.config, "d1").map(([name]) => [
        name,
        new ProxyNodeBinding()
      ])
    );
  },
  async getServices({ options, tmpPath, sharedOptions }) {
    const databases = getEnvBindingsOfType(options.config, "d1");
    const services = [];
    const hasLocal = databases.some(
      ([, db]) => getRemoteProxyConnectionString(db, options.dev) === void 0
    );
    if (hasLocal) {
      services.push({
        name: D1_LOCAL_ENTRY_SERVICE_NAME,
        worker: objectEntryWorker(D1_DATABASE_OBJECT)
      });
    }
    const hasRemote = databases.some(
      ([, db]) => getRemoteProxyConnectionString(db, options.dev) !== void 0
    );
    if (hasRemote) {
      services.push({
        name: D1_REMOTE_SERVICE_NAME,
        worker: remoteProxyClientWorker()
      });
    }
    if (hasLocal) {
      const uniqueKey = `miniflare-${D1_DATABASE_OBJECT_CLASS_NAME}`;
      const persistPath = getPersistPath(
        D1_PLUGIN_NAME,
        tmpPath,
        sharedOptions.resourcePersistencePath
      );
      await import_promises15.default.mkdir(persistPath, { recursive: true });
      const storageService = {
        name: D1_STORAGE_SERVICE_NAME,
        disk: { path: persistPath, writable: true }
      };
      const objectService = {
        name: D1_DATABASE_SERVICE_PREFIX,
        worker: {
          compatibilityDate: "2023-07-24",
          compatibilityFlags: ["nodejs_compat", "experimental"],
          modules: [
            {
              name: "database.worker.js",
              esModule: database_worker_default()
            }
          ],
          durableObjectNamespaces: [
            {
              className: D1_DATABASE_OBJECT_CLASS_NAME,
              uniqueKey
            }
          ],
          // Store Durable Object SQL databases in persist path
          durableObjectStorage: { localDisk: D1_STORAGE_SERVICE_NAME },
          // Bind blob disk directory service to object
          bindings: [
            {
              name: SharedBindings.MAYBE_SERVICE_BLOBS,
              service: { name: D1_STORAGE_SERVICE_NAME }
            },
            {
              name: SharedBindings.MAYBE_SERVICE_LOOPBACK,
              service: { name: SERVICE_LOOPBACK }
            },
            ...getMiniflareObjectBindings()
          ]
        }
      };
      services.push(storageService, objectService);
    }
    return services;
  }
};

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/dispatch-namespace/dispatch-namespace.worker.ts
var import_fs31 = __toESM(require("fs"));
var import_path31 = __toESM(require("path"));
var import_url31 = __toESM(require("url"));
var contents31;
function dispatch_namespace_worker_default() {
  if (contents31 !== void 0) return contents31;
  const filePath = import_path31.default.join(__dirname, "workers", "dispatch-namespace/dispatch-namespace.worker.js");
  contents31 = import_fs31.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url31.default.pathToFileURL(filePath);
  return contents31;
}

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/dispatch-namespace/dispatch-namespace-proxy.worker.ts
var import_fs32 = __toESM(require("fs"));
var import_path32 = __toESM(require("path"));
var import_url32 = __toESM(require("url"));
var contents32;
function dispatch_namespace_proxy_worker_default() {
  if (contents32 !== void 0) return contents32;
  const filePath = import_path32.default.join(__dirname, "workers", "dispatch-namespace/dispatch-namespace-proxy.worker.js");
  contents32 = import_fs32.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url32.default.pathToFileURL(filePath);
  return contents32;
}

// src/plugins/dispatch-namespace/index.ts
var DISPATCH_NAMESPACE_PLUGIN_NAME = "dispatch-namespace";
var DISPATCH_NAMESPACE_REMOTE_SERVICE_NAME = `${DISPATCH_NAMESPACE_PLUGIN_NAME}-proxy:remote`;
var DISPATCH_NAMESPACE_PLUGIN = {
  bindingTypeDescription: "Dispatch namespace",
  async getBindings(options) {
    return getEnvBindingsOfType(
      options.config,
      "dispatch-namespace"
    ).map(([name, binding]) => {
      return {
        name,
        wrapped: {
          moduleName: `${DISPATCH_NAMESPACE_PLUGIN_NAME}:local-dispatch-namespace`,
          innerBindings: [
            {
              name: "proxyClient",
              service: {
                name: DISPATCH_NAMESPACE_REMOTE_SERVICE_NAME,
                props: buildRemoteProxyProps(
                  getRemoteProxyConnectionString(binding, options.dev),
                  name
                )
              }
            }
          ]
        }
      };
    });
  },
  getNodeBindings(options) {
    return Object.fromEntries(
      getEnvBindingsOfType(options.config, "dispatch-namespace").map(
        ([name]) => [name, new ProxyNodeBinding()]
      )
    );
  },
  async getServices({ options }) {
    if (getEnvBindingsOfType(options.config, "dispatch-namespace").length === 0) {
      return [];
    }
    return [
      {
        name: DISPATCH_NAMESPACE_REMOTE_SERVICE_NAME,
        worker: remoteProxyClientWorker(dispatch_namespace_proxy_worker_default)
      }
    ];
  },
  getExtensions({ options }) {
    if (!options.some(
      (o) => getEnvBindingsOfType(o.config, "dispatch-namespace").length > 0
    )) {
      return [];
    }
    return [
      {
        modules: [
          {
            name: `${DISPATCH_NAMESPACE_PLUGIN_NAME}:local-dispatch-namespace`,
            esModule: dispatch_namespace_worker_default(),
            internal: true
          }
        ]
      }
    ];
  }
};

// src/plugins/email/index.ts
var import_promises16 = require("node:fs/promises");
var import_node_path28 = __toESM(require("node:path"));

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/email/email.worker.ts
var import_fs33 = __toESM(require("fs"));
var import_path33 = __toESM(require("path"));
var import_url33 = __toESM(require("url"));
var contents33;
function email_worker_default() {
  if (contents33 !== void 0) return contents33;
  const filePath = import_path33.default.join(__dirname, "workers", "email/email.worker.js");
  contents33 = import_fs33.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url33.default.pathToFileURL(filePath);
  return contents33;
}

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/email/send_email.worker.ts
var import_fs34 = __toESM(require("fs"));
var import_path34 = __toESM(require("path"));
var import_url34 = __toESM(require("url"));
var contents34;
function send_email_worker_default() {
  if (contents34 !== void 0) return contents34;
  const filePath = import_path34.default.join(__dirname, "workers", "email/send_email.worker.js");
  contents34 = import_fs34.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url34.default.pathToFileURL(filePath);
  return contents34;
}

// src/plugins/email/index.ts
var EMAIL_PLUGIN_NAME = "email";
var SERVICE_SEND_EMAIL_WORKER_PREFIX = `SEND-EMAIL-WORKER`;
var EMAIL_REMOTE_SERVICE_NAME = `${EMAIL_PLUGIN_NAME}:remote`;
var EMAIL_DISK_SERVICE_NAME = `${EMAIL_PLUGIN_NAME}:disk`;
var EMAIL_DISK_BINDING_NAME = "MINIFLARE_EMAIL_DISK";
function buildJsonBindings(bindings) {
  return Object.entries(bindings).map(([name, value]) => ({
    name,
    json: JSON.stringify(value)
  }));
}
function getEmailProjectParentDirectory(resourceTmpPath) {
  if (resourceTmpPath === void 0) {
    return void 0;
  }
  return import_node_path28.default.join(resourceTmpPath, EMAIL_PLUGIN_NAME);
}
function getEmailProjectSessionDirectory(resourceTmpPath, tmpPath) {
  const parentDir = getEmailProjectParentDirectory(resourceTmpPath);
  if (parentDir === void 0) {
    return void 0;
  }
  return import_node_path28.default.join(parentDir, import_node_path28.default.basename(tmpPath));
}
function getEmailPathsToClean(resourceTmpPath, tmpPath) {
  if (resourceTmpPath === void 0) {
    return void 0;
  }
  const sessionDir = getEmailProjectSessionDirectory(resourceTmpPath, tmpPath);
  const parentDir = getEmailProjectParentDirectory(resourceTmpPath);
  if (sessionDir === void 0 || parentDir === void 0) {
    return void 0;
  }
  return { sessionDir, parentDir };
}
var EMAIL_PLUGIN = {
  bindingTypeDescription: "Email",
  getBindings(options) {
    return getEnvBindingsOfType(options.config, "send-email").map(
      ([name, binding]) => {
        const remoteProxyConnectionString = getRemoteProxyConnectionString(
          binding,
          options.dev
        );
        return {
          name,
          service: remoteProxyConnectionString ? {
            name: EMAIL_REMOTE_SERVICE_NAME,
            props: buildRemoteProxyProps(remoteProxyConnectionString, name)
          } : {
            entrypoint: "SendEmailBinding",
            name: getUserBindingServiceName(
              SERVICE_SEND_EMAIL_WORKER_PREFIX,
              name
            )
          }
        };
      }
    );
  },
  getNodeBindings(options) {
    return Object.fromEntries(
      getEnvBindingsOfType(options.config, "send-email").map(([name]) => [
        name,
        new ProxyNodeBinding()
      ])
    );
  },
  async getServices(args) {
    const sendEmailBindings = getEnvBindingsOfType(
      args.options.config,
      "send-email"
    );
    if (sendEmailBindings.length === 0) {
      return [];
    }
    const emailSystemDirectory = import_node_path28.default.join(args.tmpPath, EMAIL_PLUGIN_NAME);
    await (0, import_promises16.mkdir)(emailSystemDirectory, { recursive: true });
    const diskServices = [
      {
        location: "system",
        bindingName: `${EMAIL_DISK_BINDING_NAME}_SYSTEM`,
        serviceName: `${EMAIL_DISK_SERVICE_NAME}:system`,
        path: emailSystemDirectory
      }
    ];
    if (args.sharedOptions.resourceTmpPath) {
      const emailProjectSessionDirectory = getEmailProjectSessionDirectory(
        args.sharedOptions.resourceTmpPath,
        args.tmpPath
      );
      if (emailProjectSessionDirectory !== void 0) {
        await (0, import_promises16.mkdir)(emailProjectSessionDirectory, { recursive: true });
        diskServices.push({
          location: "project",
          bindingName: `${EMAIL_DISK_BINDING_NAME}_PROJECT`,
          serviceName: `${EMAIL_DISK_SERVICE_NAME}:project`,
          path: emailProjectSessionDirectory
        });
      }
    }
    const services = diskServices.map(({ serviceName, path: path73 }) => ({
      name: serviceName,
      disk: {
        path: path73,
        writable: true
      }
    }));
    let hasRemote = false;
    for (const [name, binding] of sendEmailBindings) {
      if (getRemoteProxyConnectionString(binding, args.options.dev)) {
        hasRemote = true;
        continue;
      }
      const config3 = {};
      if (binding.destinationAddress !== void 0) {
        config3.destinationAddress = binding.destinationAddress;
      }
      if (binding.allowedDestinationAddresses !== void 0) {
        config3.allowedDestinationAddresses = binding.allowedDestinationAddresses;
      }
      if (binding.allowedSenderAddresses !== void 0) {
        config3.allowedSenderAddresses = binding.allowedSenderAddresses;
      }
      services.push({
        name: getUserBindingServiceName(SERVICE_SEND_EMAIL_WORKER_PREFIX, name),
        worker: {
          compatibilityDate: "2025-03-17",
          modules: [
            {
              name: "send_email.mjs",
              esModule: send_email_worker_default()
            }
          ],
          bindings: [
            ...buildJsonBindings(config3),
            ...diskServices.map(({ bindingName, serviceName }) => ({
              name: bindingName,
              service: { name: serviceName }
            })),
            {
              name: "email_disk_services",
              json: JSON.stringify(diskServices)
            }
          ]
        }
      });
    }
    if (hasRemote) {
      services.push({
        name: EMAIL_REMOTE_SERVICE_NAME,
        worker: remoteProxyClientWorker()
      });
    }
    return services;
  },
  getExtensions() {
    return [
      {
        modules: [
          {
            name: "cloudflare-internal:email",
            esModule: email_worker_default(),
            internal: true
          }
        ]
      }
    ];
  }
};

// src/plugins/flagship/index.ts
var FLAGSHIP_PLUGIN_NAME = "flagship";
var FLAGSHIP_REMOTE_SERVICE_NAME = `${FLAGSHIP_PLUGIN_NAME}:remote`;
var FLAGSHIP_PLUGIN = {
  bindingTypeDescription: "Flagship",
  async getBindings(options) {
    return getEnvBindingsOfType(options.config, "flagship").map(
      ([name, binding]) => ({
        name,
        service: {
          name: FLAGSHIP_REMOTE_SERVICE_NAME,
          props: buildRemoteProxyProps(
            getRemoteProxyConnectionString(binding, options.dev),
            name
          )
        }
      })
    );
  },
  getNodeBindings(options) {
    return Object.fromEntries(
      getEnvBindingsOfType(options.config, "flagship").map(([name]) => [
        name,
        new ProxyNodeBinding()
      ])
    );
  },
  async getServices({ options }) {
    if (getEnvBindingsOfType(options.config, "flagship").length === 0) {
      return [];
    }
    return [
      {
        name: FLAGSHIP_REMOTE_SERVICE_NAME,
        worker: remoteProxyClientWorker()
      }
    ];
  }
};

// src/plugins/hello-world/index.ts
var import_promises17 = __toESM(require("node:fs/promises"));

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/hello-world/binding.worker.ts
var import_fs35 = __toESM(require("fs"));
var import_path35 = __toESM(require("path"));
var import_url35 = __toESM(require("url"));
var contents35;
function binding_worker_default3() {
  if (contents35 !== void 0) return contents35;
  const filePath = import_path35.default.join(__dirname, "workers", "hello-world/binding.worker.js");
  contents35 = import_fs35.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url35.default.pathToFileURL(filePath);
  return contents35;
}

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/hello-world/object.worker.ts
var import_fs36 = __toESM(require("fs"));
var import_path36 = __toESM(require("path"));
var import_url36 = __toESM(require("url"));
var contents36;
function object_worker_default2() {
  if (contents36 !== void 0) return contents36;
  const filePath = import_path36.default.join(__dirname, "workers", "hello-world/object.worker.js");
  contents36 = import_fs36.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url36.default.pathToFileURL(filePath);
  return contents36;
}

// src/plugins/hello-world/index.ts
var HELLO_WORLD_PLUGIN_NAME = "hello-world";
var HELLO_WORLD_PLUGIN = {
  bindingTypeDescription: "Hello World",
  async getBindings(options) {
    return getEnvBindingsOfType(
      options.config,
      "hello-world"
    ).map(([name, binding]) => ({
      name,
      service: {
        name: `${HELLO_WORLD_PLUGIN_NAME}:${JSON.stringify(binding.enable_timer ?? false)}`,
        entrypoint: "HelloWorldBinding"
      }
    }));
  },
  getNodeBindings(options) {
    return Object.fromEntries(
      getEnvBindingsOfType(options.config, "hello-world").map(([name]) => [
        name,
        new ProxyNodeBinding()
      ])
    );
  },
  async getServices({ options, tmpPath, sharedOptions }) {
    const bindings = getEnvBindingsOfType(options.config, "hello-world");
    if (bindings.length === 0) {
      return [];
    }
    const persistPath = getPersistPath(
      HELLO_WORLD_PLUGIN_NAME,
      tmpPath,
      sharedOptions.resourcePersistencePath
    );
    await import_promises17.default.mkdir(persistPath, { recursive: true });
    const storageService = {
      name: `${HELLO_WORLD_PLUGIN_NAME}:storage`,
      disk: { path: persistPath, writable: true }
    };
    const objectService = {
      name: `${HELLO_WORLD_PLUGIN_NAME}:object`,
      worker: {
        compatibilityDate: "2025-01-01",
        modules: [
          {
            name: "object.worker.js",
            esModule: object_worker_default2()
          }
        ],
        durableObjectNamespaces: [
          {
            className: "HelloWorldObject",
            uniqueKey: `miniflare-hello-world-HelloWorldObject`
          }
        ],
        // Store Durable Object SQL databases in persist path
        durableObjectStorage: { localDisk: storageService.name },
        // Bind blob disk directory service to object
        bindings: [
          {
            name: SharedBindings.MAYBE_SERVICE_BLOBS,
            service: { name: storageService.name }
          },
          {
            name: SharedBindings.MAYBE_SERVICE_LOOPBACK,
            service: { name: SERVICE_LOOPBACK }
          },
          ...getMiniflareObjectBindings()
        ]
      }
    };
    const services = bindings.map(([, binding]) => ({
      name: `${HELLO_WORLD_PLUGIN_NAME}:${JSON.stringify(binding.enable_timer ?? false)}`,
      worker: {
        compatibilityDate: "2025-01-01",
        modules: [
          {
            name: "binding.worker.js",
            esModule: binding_worker_default3()
          }
        ],
        bindings: [
          {
            name: "config",
            json: JSON.stringify({ enable_timer: binding.enable_timer })
          },
          {
            name: "store",
            durableObjectNamespace: {
              className: "HelloWorldObject",
              serviceName: objectService.name
            }
          }
        ]
      }
    }));
    return [...services, storageService, objectService];
  }
};

// src/plugins/hyperdrive/index.ts
var import_node_assert17 = __toESM(require("node:assert"));
var HYPERDRIVE_PLUGIN_NAME = "hyperdrive";
function getHyperdrives(config3) {
  return getEnvBindingsOfType(config3, "hyperdrive").map(([name, binding]) => [
    name,
    HyperdriveSchema.parse(binding.localConnectionString)
  ]);
}
function hasPostgresProtocol(url46) {
  return url46.protocol === "postgresql:" || url46.protocol === "postgres:";
}
function hasMysqlProtocol(url46) {
  return url46.protocol === "mysql:";
}
function getPort(url46) {
  if (url46.port !== "") return url46.port;
  if (hasPostgresProtocol(url46)) return "5432";
  if (hasMysqlProtocol(url46)) return "3306";
  import_node_assert17.default.fail(`Expected known protocol, got ${url46.protocol}`);
}
var HyperdriveSchema = external_exports2.union([external_exports2.url(), external_exports2.instanceof(URL)]).transform((url46, ctx) => {
  if (typeof url46 === "string") url46 = new URL(url46);
  if (url46.protocol === "") {
    ctx.addIssue({
      code: "custom",
      message: "You must specify the database protocol - e.g. 'postgresql'/'mysql'."
    });
  } else if (!hasPostgresProtocol(url46) && !hasMysqlProtocol(url46)) {
    ctx.addIssue({
      code: "custom",
      message: "Only PostgreSQL-compatible or MySQL-compatible databases are currently supported."
    });
  }
  if (url46.host === "") {
    ctx.addIssue({
      code: "custom",
      message: "You must provide a hostname or IP address in your connection string - e.g. 'user:password@database-hostname.example.com:5432/databasename"
    });
  }
  if (url46.pathname === "") {
    ctx.addIssue({
      code: "custom",
      message: "You must provide a database name as the path component - e.g. /postgres"
    });
  }
  if (url46.username === "") {
    ctx.addIssue({
      code: "custom",
      message: "You must provide a username - e.g. 'user:password@database.example.com:port/databasename'"
    });
  }
  if (url46.password === "") {
    ctx.addIssue({
      code: "custom",
      message: "You must provide a password - e.g. 'user:password@database.example.com:port/databasename' "
    });
  }
  return url46;
});
var HYPERDRIVE_PLUGIN = {
  bindingTypeDescription: "Hyperdrive",
  getBindings(options) {
    return getHyperdrives(options.config).map(([name, url46]) => {
      const database = url46.pathname.replace("/", "");
      const scheme = url46.protocol.replace(":", "");
      return {
        name,
        hyperdrive: {
          designator: {
            name: `${HYPERDRIVE_PLUGIN_NAME}:${name}`
          },
          database: decodeURIComponent(database),
          user: decodeURIComponent(url46.username),
          password: decodeURIComponent(url46.password),
          scheme
        }
      };
    });
  },
  getNodeBindings(options) {
    return Object.fromEntries(
      getHyperdrives(options.config).map(([name, url46]) => {
        const connectionOverrides = {
          connectionString: `${url46}`,
          port: Number.parseInt(url46.port),
          host: url46.hostname
        };
        const proxyNodeBinding = new ProxyNodeBinding({
          get(target, prop) {
            return prop in connectionOverrides ? connectionOverrides[prop] : target[prop];
          }
        });
        return [name, proxyNodeBinding];
      })
    );
  },
  async getServices({ options, hyperdriveProxyController }) {
    const services = [];
    for (const [name, url46] of getHyperdrives(options.config)) {
      const scheme = url46.protocol.replace(":", "");
      const sslmode = parseSslMode(url46, scheme);
      const targetPort = getPort(url46);
      let address;
      if (sslmode === "disable") {
        address = `${url46.hostname}:${targetPort}`;
      } else {
        const proxyPort = await hyperdriveProxyController.createProxyServer({
          name,
          targetHost: url46.hostname,
          targetPort,
          scheme,
          sslmode,
          sslrootcert: parseSslRootCert(url46)
        });
        address = `127.0.0.1:${proxyPort}`;
      }
      services.push({
        name: `${HYPERDRIVE_PLUGIN_NAME}:${name}`,
        external: {
          address,
          tcp: {}
        }
      });
    }
    return services;
  }
};
function parseSslMode(url46, scheme) {
  const params = Object.fromEntries(
    Array.from(url46.searchParams.entries()).map(([k, v]) => [
      k.toLowerCase(),
      v.toLowerCase()
    ])
  );
  if (scheme === "postgres" || scheme === "postgresql") {
    return params["sslmode"] || "disable";
  } else if (scheme === "mysql") {
    const sslmode = params["ssl-mode"] || params["ssl"] || params["sslmode"];
    switch (sslmode) {
      case "verify_identity":
        return "verify-full";
      case "verify_ca":
        return "verify-ca";
      case "required":
      case "true":
      case "1":
        return "require";
      case "preferred":
        return "prefer";
      case "disabled":
      case "false":
      case "0":
        return "disable";
    }
  }
  return "disable";
}
function parseSslRootCert(url46) {
  const params = Object.fromEntries(
    Array.from(url46.searchParams.entries()).map(([k, v]) => [k.toLowerCase(), v])
  );
  return params["sslrootcert"] || void 0;
}

// src/plugins/media/index.ts
var MEDIA_PLUGIN_NAME = "media";
var MEDIA_REMOTE_SERVICE_NAME = `${MEDIA_PLUGIN_NAME}:remote`;
var MEDIA_PLUGIN = {
  bindingTypeDescription: "Media",
  async getBindings(options) {
    return getEnvBindingsOfType(options.config, "media").map(
      ([name, binding]) => ({
        name,
        service: {
          name: MEDIA_REMOTE_SERVICE_NAME,
          props: buildRemoteProxyProps(
            getRemoteProxyConnectionString(binding, options.dev),
            name
          )
        }
      })
    );
  },
  getNodeBindings(options) {
    return Object.fromEntries(
      getEnvBindingsOfType(options.config, "media").map(([name]) => [
        name,
        new ProxyNodeBinding()
      ])
    );
  },
  async getServices({ options }) {
    if (getEnvBindingsOfType(options.config, "media").length === 0) {
      return [];
    }
    return [
      {
        name: MEDIA_REMOTE_SERVICE_NAME,
        worker: remoteProxyClientWorker()
      }
    ];
  }
};

// src/plugins/mtls/index.ts
var MTLS_PLUGIN_NAME = "mtls";
var MTLS_REMOTE_SERVICE_NAME = `${MTLS_PLUGIN_NAME}:remote`;
var MTLS_PLUGIN = {
  bindingTypeDescription: "mTLS certificate",
  async getBindings(options) {
    return getEnvBindingsOfType(options.config, "mtls-certificate").map(
      ([name, binding]) => ({
        name,
        service: {
          name: MTLS_REMOTE_SERVICE_NAME,
          props: buildRemoteProxyProps(
            getRemoteProxyConnectionString(binding, options.dev),
            name
          )
        }
      })
    );
  },
  getNodeBindings(options) {
    return Object.fromEntries(
      getEnvBindingsOfType(options.config, "mtls-certificate").map(([name]) => [
        name,
        new ProxyNodeBinding()
      ])
    );
  },
  async getServices({ options }) {
    if (getEnvBindingsOfType(options.config, "mtls-certificate").length === 0) {
      return [];
    }
    return [
      {
        name: MTLS_REMOTE_SERVICE_NAME,
        worker: remoteProxyClientWorker()
      }
    ];
  }
};

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/pipelines/pipeline.worker.ts
var import_fs37 = __toESM(require("fs"));
var import_path37 = __toESM(require("path"));
var import_url37 = __toESM(require("url"));
var contents37;
function pipeline_worker_default() {
  if (contents37 !== void 0) return contents37;
  const filePath = import_path37.default.join(__dirname, "workers", "pipelines/pipeline.worker.js");
  contents37 = import_fs37.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url37.default.pathToFileURL(filePath);
  return contents37;
}

// src/plugins/pipelines/index.ts
var PIPELINES_PLUGIN_NAME = "pipelines";
var SERVICE_PIPELINE_PREFIX = `${PIPELINES_PLUGIN_NAME}:pipeline`;
var PIPELINES_REMOTE_SERVICE_NAME = `${PIPELINES_PLUGIN_NAME}:pipeline:remote`;
var PIPELINE_PLUGIN = {
  bindingTypeDescription: "Pipeline",
  getBindings(options) {
    return getEnvBindingsOfType(options.config, "pipeline").map(
      ([name, binding]) => {
        const id = binding.name;
        const remoteProxyConnectionString = getRemoteProxyConnectionString(
          binding,
          options.dev
        );
        return {
          name,
          service: remoteProxyConnectionString ? {
            name: PIPELINES_REMOTE_SERVICE_NAME,
            props: buildRemoteProxyProps(remoteProxyConnectionString, name)
          } : { name: `${SERVICE_PIPELINE_PREFIX}:${id}` }
        };
      }
    );
  },
  getNodeBindings(options) {
    return Object.fromEntries(
      getEnvBindingsOfType(options.config, "pipeline").map(([name]) => [
        name,
        new ProxyNodeBinding()
      ])
    );
  },
  async getServices({ options }) {
    const pipelines = getEnvBindingsOfType(options.config, "pipeline");
    const services = [];
    let hasRemote = false;
    for (const [, binding] of pipelines) {
      if (getRemoteProxyConnectionString(binding, options.dev)) {
        hasRemote = true;
        continue;
      }
      services.push({
        name: `${SERVICE_PIPELINE_PREFIX}:${binding.name}`,
        worker: {
          compatibilityDate: "2024-12-30",
          modules: [
            {
              name: "pipeline.worker.js",
              esModule: pipeline_worker_default()
            }
          ]
        }
      });
    }
    if (hasRemote) {
      services.push({
        name: PIPELINES_REMOTE_SERVICE_NAME,
        worker: remoteProxyClientWorker()
      });
    }
    return services;
  }
};

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/queues/broker.worker.ts
var import_fs38 = __toESM(require("fs"));
var import_path38 = __toESM(require("path"));
var import_url38 = __toESM(require("url"));
var contents38;
function broker_worker_default() {
  if (contents38 !== void 0) return contents38;
  const filePath = import_path38.default.join(__dirname, "workers", "queues/broker.worker.js");
  contents38 = import_fs38.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url38.default.pathToFileURL(filePath);
  return contents38;
}

// src/plugins/queues/errors.ts
var QueuesError = class extends MiniflareError {
};

// src/plugins/queues/index.ts
var QUEUES_PLUGIN_NAME = "queues";
var QUEUE_BROKER_OBJECT_CLASS_NAME = "QueueBrokerObject";
var QUEUE_BROKER_OBJECT = {
  serviceName: SERVICE_QUEUE_PREFIX,
  className: QUEUE_BROKER_OBJECT_CLASS_NAME
};
var QUEUES_PLUGIN = {
  bindingTypeDescription: "Queue producer",
  getBindings(options) {
    return producerEntries(options).map(([name, id]) => ({
      name,
      queue: { name: getQueueServiceName(id) }
    }));
  },
  getNodeBindings(options) {
    return Object.fromEntries(
      producerEntries(options).map(([name]) => [name, new ProxyNodeBinding()])
    );
  },
  async getServices({
    options,
    workerNames,
    queueProducers: allQueueProducers,
    queueConsumers: allQueueConsumers,
    devRegistryEnabled
  }) {
    const produced = producerEntries(options).map(([, id]) => id);
    const consumed = getTriggersOfType(options.config, "queue").map(
      (trigger) => trigger.name
    );
    const queueIds = /* @__PURE__ */ new Set([...produced, ...consumed]);
    if (queueIds.size === 0) return [];
    const services = Array.from(queueIds).map((id) => ({
      name: getQueueServiceName(id),
      worker: objectEntryWorker(QUEUE_BROKER_OBJECT, id)
    }));
    const uniqueKey = `miniflare-${QUEUE_BROKER_OBJECT_CLASS_NAME}`;
    const objectService = {
      name: SERVICE_QUEUE_PREFIX,
      worker: {
        compatibilityDate: "2023-07-24",
        compatibilityFlags: [
          "nodejs_compat",
          "experimental",
          "service_binding_extra_handlers"
        ],
        modules: [
          { name: "broker.worker.js", esModule: broker_worker_default() }
        ],
        durableObjectNamespaces: [
          {
            className: QUEUE_BROKER_OBJECT_CLASS_NAME,
            uniqueKey,
            preventEviction: true
          }
        ],
        // Miniflare's Queue broker is in-memory only at the moment
        durableObjectStorage: { inMemory: kVoid },
        bindings: [
          {
            name: SharedBindings.MAYBE_SERVICE_LOOPBACK,
            service: { name: SERVICE_LOOPBACK }
          },
          ...getMiniflareObjectBindings(),
          {
            name: SharedBindings.DURABLE_OBJECT_NAMESPACE_OBJECT,
            durableObjectNamespace: {
              className: QUEUE_BROKER_OBJECT_CLASS_NAME
            }
          },
          {
            name: QueueBindings.MAYBE_JSON_QUEUE_PRODUCERS,
            json: JSON.stringify(Object.fromEntries(allQueueProducers))
          },
          {
            name: QueueBindings.MAYBE_JSON_QUEUE_CONSUMERS,
            json: JSON.stringify(Object.fromEntries(allQueueConsumers))
          },
          ...workerNames.map((name) => ({
            name: QueueBindings.SERVICE_WORKER_PREFIX + name,
            service: { name: getUserServiceName(name) }
          })),
          // When the dev registry is enabled, a produced queue's consumer may
          // live in another dev session: the broker delivers otherwise-dropped
          // messages through the dev-registry proxy (see
          // `QueueBrokerObject.#tryRemoteConsumer`).
          ...devRegistryEnabled ? [
            {
              name: QueueBindings.MAYBE_SERVICE_QUEUE_PROXY,
              service: {
                name: getUserServiceName(SERVICE_DEV_REGISTRY_PROXY),
                entrypoint: "ExternalQueueProxy"
              }
            }
          ] : []
        ]
      }
    };
    services.push(objectService);
    return services;
  }
};
function producerEntries(options) {
  return getEnvBindingsOfType(options.config, "queue").map(
    ([bindingName, binding]) => [bindingName, binding.name ?? bindingName]
  );
}

// src/plugins/ratelimit/index.ts
var import_promises18 = __toESM(require("node:fs/promises"));

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/ratelimit/ratelimit.worker.ts
var import_fs39 = __toESM(require("fs"));
var import_path39 = __toESM(require("path"));
var import_url39 = __toESM(require("url"));
var contents39;
function ratelimit_worker_default() {
  if (contents39 !== void 0) return contents39;
  const filePath = import_path39.default.join(__dirname, "workers", "ratelimit/ratelimit.worker.js");
  contents39 = import_fs39.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url39.default.pathToFileURL(filePath);
  return contents39;
}

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/ratelimit/ratelimit-object.worker.ts
var import_fs40 = __toESM(require("fs"));
var import_path40 = __toESM(require("path"));
var import_url40 = __toESM(require("url"));
var contents40;
function ratelimit_object_worker_default() {
  if (contents40 !== void 0) return contents40;
  const filePath = import_path40.default.join(__dirname, "workers", "ratelimit/ratelimit-object.worker.js");
  contents40 = import_fs40.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url40.default.pathToFileURL(filePath);
  return contents40;
}

// src/plugins/ratelimit/index.ts
var PeriodType = /* @__PURE__ */ ((PeriodType2) => {
  PeriodType2[PeriodType2["TENSECONDS"] = 10] = "TENSECONDS";
  PeriodType2[PeriodType2["MINUTE"] = 60] = "MINUTE";
  return PeriodType2;
})(PeriodType || {});
var RATELIMIT_PLUGIN_NAME = "ratelimit";
var SERVICE_RATELIMIT_PREFIX = `${RATELIMIT_PLUGIN_NAME}`;
var SERVICE_RATELIMIT_MODULE = `cloudflare-internal:${SERVICE_RATELIMIT_PREFIX}:module`;
var RATELIMIT_ENTRY_SERVICE_PREFIX = `${RATELIMIT_PLUGIN_NAME}:ns`;
var RATELIMIT_LOCAL_ENTRY_SERVICE_NAME = `${RATELIMIT_PLUGIN_NAME}:ns:entry`;
var RATELIMIT_STORAGE_SERVICE_NAME = `${RATELIMIT_PLUGIN_NAME}:storage`;
var RATELIMIT_OBJECT_CLASS_NAME = "RateLimiterObject";
var RATELIMIT_OBJECT = {
  serviceName: RATELIMIT_ENTRY_SERVICE_PREFIX,
  className: RATELIMIT_OBJECT_CLASS_NAME
};
function buildJsonBindings2(bindings) {
  return Object.entries(bindings).map(([name, value]) => ({
    name,
    json: JSON.stringify(value)
  }));
}
var RATELIMIT_PLUGIN = {
  bindingTypeDescription: "Rate Limit",
  getBindings(options) {
    return getEnvBindingsOfType(
      options.config,
      "rate-limit"
    ).map(([name, binding]) => ({
      name,
      wrapped: {
        moduleName: SERVICE_RATELIMIT_MODULE,
        innerBindings: [
          {
            name: "fetcher",
            service: {
              name: RATELIMIT_LOCAL_ENTRY_SERVICE_NAME,
              props: buildObjectEntryProps(binding.namespace)
            }
          },
          ...buildJsonBindings2({
            limit: binding.simple.limit,
            period: binding.simple.period
          })
        ]
      }
    }));
  },
  getNodeBindings(options) {
    return Object.fromEntries(
      getEnvBindingsOfType(options.config, "rate-limit").map(([name]) => [
        name,
        new ProxyNodeBinding()
      ])
    );
  },
  async getServices({ options, tmpPath, sharedOptions }) {
    const ratelimits = getEnvBindingsOfType(options.config, "rate-limit");
    if (ratelimits.length === 0) {
      return [];
    }
    const services = [
      {
        name: RATELIMIT_LOCAL_ENTRY_SERVICE_NAME,
        worker: objectEntryWorker(RATELIMIT_OBJECT)
      }
    ];
    const persistPath = getPersistPath(
      RATELIMIT_PLUGIN_NAME,
      tmpPath,
      sharedOptions.resourcePersistencePath
    );
    await import_promises18.default.mkdir(persistPath, { recursive: true });
    services.push({
      name: RATELIMIT_STORAGE_SERVICE_NAME,
      disk: { path: persistPath, writable: true }
    });
    const uniqueKey = `miniflare-${RATELIMIT_OBJECT_CLASS_NAME}`;
    services.push({
      name: RATELIMIT_ENTRY_SERVICE_PREFIX,
      worker: {
        compatibilityDate: "2023-07-24",
        compatibilityFlags: ["nodejs_compat", "experimental"],
        modules: [
          {
            name: "ratelimit-object.worker.js",
            esModule: ratelimit_object_worker_default()
          }
        ],
        durableObjectNamespaces: [
          {
            className: RATELIMIT_OBJECT_CLASS_NAME,
            uniqueKey,
            enableSql: true
          }
        ],
        // Counters must outlive the Durable Object itself. `workerd` evicts
        // idle objects after ~10s, which would silently reset every counter
        // mid-window if the state lived on the heap (or in `inMemory` storage,
        // which is backed by a per-actor `ActorCache` and is just as lossy).
        //
        // The namespace deliberately stays evictable: `deleteAllDurableObjects()`
        // (what vitest-pool-workers' `reset()` calls) skips namespaces with
        // `preventEviction` set, and it is what resets these counters between
        // tests, via `ActorNamespace::deleteAll()` -> `SqliteDatabase::reset()`.
        durableObjectStorage: { localDisk: RATELIMIT_STORAGE_SERVICE_NAME },
        bindings: [
          {
            name: SharedBindings.MAYBE_SERVICE_LOOPBACK,
            service: { name: SERVICE_LOOPBACK }
          },
          ...getMiniflareObjectBindings()
        ]
      }
    });
    return services;
  },
  getExtensions({ options }) {
    if (!options.some(
      (o) => getEnvBindingsOfType(o.config, "rate-limit").length > 0
    )) {
      return [];
    }
    return [
      {
        modules: [
          {
            name: SERVICE_RATELIMIT_MODULE,
            esModule: ratelimit_worker_default(),
            internal: true
          }
        ]
      }
    ];
  }
};

// src/plugins/secret-store/index.ts
var import_promises19 = __toESM(require("node:fs/promises"));

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/secrets-store/secret.worker.ts
var import_fs41 = __toESM(require("fs"));
var import_path41 = __toESM(require("path"));
var import_url41 = __toESM(require("url"));
var contents41;
function secret_worker_default() {
  if (contents41 !== void 0) return contents41;
  const filePath = import_path41.default.join(__dirname, "workers", "secrets-store/secret.worker.js");
  contents41 = import_fs41.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url41.default.pathToFileURL(filePath);
  return contents41;
}

// src/plugins/secret-store/index.ts
var SECRET_STORE_PLUGIN_NAME = "secrets-store";
var SECRET_STORE_LOCAL_ENTRY_SERVICE_NAME = `${SECRET_STORE_PLUGIN_NAME}:ns:entry`;
var SECRET_STORE_PLUGIN = {
  bindingTypeDescription: "Secrets Store secret",
  async getBindings(options) {
    return getEnvBindingsOfType(
      options.config,
      "secrets-store-secret"
    ).map(([name, binding]) => {
      return {
        name,
        service: {
          name: getUserBindingServiceName(
            SECRET_STORE_PLUGIN_NAME,
            `${binding.storeId}:${binding.secretName}`
          ),
          entrypoint: "SecretsStoreSecret"
        }
      };
    });
  },
  getNodeBindings(options) {
    return Object.fromEntries(
      getEnvBindingsOfType(options.config, "secrets-store-secret").map(
        ([name]) => [name, new ProxyNodeBinding()]
      )
    );
  },
  async getServices({ options, tmpPath, sharedOptions }) {
    const configs = getEnvBindingsOfType(
      options.config,
      "secrets-store-secret"
    ).map(([, binding]) => binding);
    if (configs.length === 0) {
      return [];
    }
    const persistPath = getPersistPath(
      SECRET_STORE_PLUGIN_NAME,
      tmpPath,
      sharedOptions.resourcePersistencePath
    );
    await import_promises19.default.mkdir(persistPath, { recursive: true });
    const storageService = {
      name: `${SECRET_STORE_PLUGIN_NAME}:storage`,
      disk: { path: persistPath, writable: true }
    };
    const objectService = {
      name: `${SECRET_STORE_PLUGIN_NAME}:ns`,
      worker: {
        compatibilityDate: "2023-07-24",
        compatibilityFlags: ["nodejs_compat", "experimental"],
        modules: [
          {
            name: "namespace.worker.js",
            esModule: namespace_worker_default()
          }
        ],
        durableObjectNamespaces: [
          {
            className: KV_NAMESPACE_OBJECT_CLASS_NAME,
            uniqueKey: `miniflare-secrets-store-${KV_NAMESPACE_OBJECT_CLASS_NAME}`
          }
        ],
        // Store Durable Object SQL databases in persist path
        durableObjectStorage: { localDisk: storageService.name },
        // Bind blob disk directory service to object
        bindings: [
          {
            name: SharedBindings.MAYBE_SERVICE_BLOBS,
            service: { name: storageService.name }
          },
          {
            name: SharedBindings.MAYBE_SERVICE_LOOPBACK,
            service: { name: SERVICE_LOOPBACK }
          },
          ...getMiniflareObjectBindings()
        ]
      }
    };
    const entryService = {
      name: SECRET_STORE_LOCAL_ENTRY_SERVICE_NAME,
      worker: objectEntryWorker({
        serviceName: objectService.name,
        className: KV_NAMESPACE_OBJECT_CLASS_NAME
      })
    };
    const secretServices = configs.map((config3) => ({
      name: getUserBindingServiceName(
        SECRET_STORE_PLUGIN_NAME,
        `${config3.storeId}:${config3.secretName}`
      ),
      worker: {
        compatibilityDate: "2025-01-01",
        modules: [
          {
            name: "secret.worker.js",
            esModule: secret_worker_default()
          }
        ],
        bindings: [
          {
            name: "store",
            kvNamespace: {
              name: SECRET_STORE_LOCAL_ENTRY_SERVICE_NAME,
              props: buildObjectEntryProps(config3.storeId)
            }
          },
          {
            name: "secret_name",
            json: JSON.stringify(config3.secretName)
          }
        ]
      }
    }));
    return [...secretServices, entryService, storageService, objectService];
  }
};

// src/plugins/vectorize/index.ts
var VECTORIZE_PLUGIN_NAME = "vectorize";
var VECTORIZE_REMOTE_SERVICE_NAME = `${VECTORIZE_PLUGIN_NAME}:remote`;
var VECTORIZE_PLUGIN = {
  bindingTypeDescription: "Vectorize index",
  async getBindings(options) {
    return getEnvBindingsOfType(options.config, "vectorize").map(
      ([name, binding]) => {
        return {
          name,
          wrapped: {
            moduleName: "cloudflare-internal:vectorize-api",
            innerBindings: [
              {
                name: "fetcher",
                service: {
                  name: VECTORIZE_REMOTE_SERVICE_NAME,
                  props: buildRemoteProxyProps(
                    getRemoteProxyConnectionString(binding, options.dev),
                    name
                  )
                }
              },
              {
                name: "indexId",
                text: binding.name
              },
              {
                name: "indexVersion",
                text: "v2"
              },
              {
                name: "useNdJson",
                json: true
              }
            ]
          }
        };
      }
    );
  },
  getNodeBindings(options) {
    return Object.fromEntries(
      getEnvBindingsOfType(options.config, "vectorize").map(([name]) => [
        name,
        new ProxyNodeBinding()
      ])
    );
  },
  async getServices({ options }) {
    if (getEnvBindingsOfType(options.config, "vectorize").length === 0) {
      return [];
    }
    return [
      {
        name: VECTORIZE_REMOTE_SERVICE_NAME,
        worker: remoteProxyClientWorker()
      }
    ];
  }
};

// src/plugins/version-metadata/index.ts
var import_node_crypto6 = require("node:crypto");
var VERSION_METADATA_PLUGIN_NAME = "version-metadata";
var VERSION_METADATA_PLUGIN = {
  async getBindings(options) {
    return getEnvBindingsOfType(
      options.config,
      "version-metadata"
    ).map(([name]) => {
      const id = (0, import_node_crypto6.randomUUID)();
      const tag = "";
      const timestamp = (/* @__PURE__ */ new Date()).toISOString();
      return {
        name,
        json: JSON.stringify({ id, tag, timestamp })
      };
    });
  },
  getNodeBindings(options) {
    return Object.fromEntries(
      getEnvBindingsOfType(options.config, "version-metadata").map(([name]) => {
        const id = (0, import_node_crypto6.randomUUID)();
        const tag = "";
        const timestamp = (/* @__PURE__ */ new Date()).toISOString();
        return [name, { id, tag, timestamp }];
      })
    );
  },
  async getServices() {
    return [];
  }
};

// src/plugins/vpc-networks/index.ts
var VPC_NETWORKS_PLUGIN_NAME = "vpc-networks";
var VPC_NETWORKS_REMOTE_SERVICE_NAME = `${VPC_NETWORKS_PLUGIN_NAME}:remote`;
var VPC_NETWORKS_PLUGIN = {
  bindingTypeDescription: "VPC network",
  async getBindings(options) {
    return getEnvBindingsOfType(options.config, "vpc-network").map(
      ([name, binding]) => ({
        name,
        service: {
          name: VPC_NETWORKS_REMOTE_SERVICE_NAME,
          props: buildRemoteProxyProps(
            getRemoteProxyConnectionString(binding, options.dev),
            name
          )
        }
      })
    );
  },
  getNodeBindings(options) {
    return Object.fromEntries(
      getEnvBindingsOfType(options.config, "vpc-network").map(([name]) => [
        name,
        new ProxyNodeBinding()
      ])
    );
  },
  async getServices({ options }) {
    if (getEnvBindingsOfType(options.config, "vpc-network").length === 0) {
      return [];
    }
    return [
      {
        name: VPC_NETWORKS_REMOTE_SERVICE_NAME,
        // VPC networks expose raw TCP via `binding.connect()`, tunnelled
        // through the proxy client's inbound `connect` handler. The shared
        // `vpc-networks:remote` service is dedicated to VPC networks, so
        // opting it into raw TCP leaves every other binding's service
        // untouched.
        worker: remoteProxyClientWorker(void 0, { rawTcp: true })
      }
    ];
  }
};

// src/plugins/vpc-services/index.ts
var VPC_SERVICES_PLUGIN_NAME = "vpc-services";
var VPC_SERVICES_REMOTE_SERVICE_NAME = `${VPC_SERVICES_PLUGIN_NAME}:remote`;
var VPC_SERVICES_PLUGIN = {
  bindingTypeDescription: "VPC service",
  async getBindings(options) {
    return getEnvBindingsOfType(options.config, "vpc-service").map(
      ([name, binding]) => ({
        name,
        service: {
          name: VPC_SERVICES_REMOTE_SERVICE_NAME,
          props: buildRemoteProxyProps(
            getRemoteProxyConnectionString(binding, options.dev),
            name
          )
        }
      })
    );
  },
  getNodeBindings(options) {
    return Object.fromEntries(
      getEnvBindingsOfType(options.config, "vpc-service").map(([name]) => [
        name,
        new ProxyNodeBinding()
      ])
    );
  },
  async getServices({ options }) {
    if (getEnvBindingsOfType(options.config, "vpc-service").length === 0) {
      return [];
    }
    return [
      {
        name: VPC_SERVICES_REMOTE_SERVICE_NAME,
        // VPC services also expose raw TCP via `binding.connect()`, tunnelled
        // through the proxy client's inbound `connect` handler. The shared
        // `vpc-services:remote` service is dedicated to VPC services, so
        // opting it into raw TCP leaves every other binding's service
        // untouched.
        worker: remoteProxyClientWorker(void 0, { rawTcp: true })
      }
    ];
  }
};

// src/plugins/websearch/index.ts
var WEBSEARCH_PLUGIN_NAME = "websearch";
var WEBSEARCH_SCOPE = "websearch";
var WEBSEARCH_REMOTE_SERVICE_NAME = `${WEBSEARCH_SCOPE}:remote`;
var WEBSEARCH_PLUGIN = {
  bindingTypeDescription: "Web Search",
  async getBindings(options) {
    return getEnvBindingsOfType(options.config, "web-search").map(
      ([name, binding]) => ({
        name,
        service: {
          name: WEBSEARCH_REMOTE_SERVICE_NAME,
          props: buildRemoteProxyProps(
            getRemoteProxyConnectionString(binding, options.dev),
            name
          )
        }
      })
    );
  },
  getNodeBindings(options) {
    return Object.fromEntries(
      getEnvBindingsOfType(options.config, "web-search").map(([name]) => [
        name,
        new ProxyNodeBinding()
      ])
    );
  },
  async getServices({ options }) {
    if (getEnvBindingsOfType(options.config, "web-search").length === 0) {
      return [];
    }
    return [
      {
        name: WEBSEARCH_REMOTE_SERVICE_NAME,
        worker: remoteProxyClientWorker()
      }
    ];
  }
};

// src/plugins/worker-loader/index.ts
var WORKER_LOADER_PLUGIN_NAME = "worker-loader";
var WORKER_LOADER_PLUGIN = {
  getBindings(options) {
    return getEnvBindingsOfType(
      options.config,
      "worker-loader"
    ).map(([name]) => ({
      name,
      workerLoader: {}
    }));
  },
  getNodeBindings() {
    return {};
  },
  async getServices() {
    return [];
  }
};

// src/plugins/workflows/index.ts
var import_promises20 = __toESM(require("node:fs/promises"));

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/workflows/binding.worker.ts
var import_fs42 = __toESM(require("fs"));
var import_path42 = __toESM(require("path"));
var import_url42 = __toESM(require("url"));
var contents42;
function binding_worker_default4() {
  if (contents42 !== void 0) return contents42;
  const filePath = import_path42.default.join(__dirname, "workers", "workflows/binding.worker.js");
  contents42 = import_fs42.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url42.default.pathToFileURL(filePath);
  return contents42;
}

// embed-worker:/Users/runner/work/workers-sdk/workers-sdk/packages/miniflare/src/workers/workflows/wrapped-binding.worker.ts
var import_fs43 = __toESM(require("fs"));
var import_path43 = __toESM(require("path"));
var import_url43 = __toESM(require("url"));
var contents43;
function wrapped_binding_worker_default() {
  if (contents43 !== void 0) return contents43;
  const filePath = import_path43.default.join(__dirname, "workers", "workflows/wrapped-binding.worker.js");
  contents43 = import_fs43.default.readFileSync(filePath, "utf8") + "//# sourceURL=" + import_url43.default.pathToFileURL(filePath);
  return contents43;
}

// src/plugins/workflows/index.ts
var WORKFLOWS_PLUGIN_NAME = "workflows";
var WORKFLOWS_STORAGE_SERVICE_NAME = `${WORKFLOWS_PLUGIN_NAME}:storage`;
var WORKFLOWS_PLUGIN = {
  bindingTypeDescription: "Workflow",
  getBindings(options) {
    return getEnvBindingsOfType(options.config, "workflow").map(
      ([bindingName, binding]) => ({
        name: bindingName,
        wrapped: {
          moduleName: `${WORKFLOWS_PLUGIN_NAME}:local-wrapped-binding`,
          innerBindings: [
            {
              name: "binding",
              service: {
                name: getUserBindingServiceName(
                  WORKFLOWS_PLUGIN_NAME,
                  binding.name,
                  getRemoteProxyConnectionString(binding, options.dev)
                ),
                entrypoint: "WorkflowBinding"
              }
            }
          ]
        }
      })
    );
  },
  getNodeBindings(options) {
    return Object.fromEntries(
      getEnvBindingsOfType(options.config, "workflow").map(([bindingName]) => [
        bindingName,
        new ProxyNodeBinding()
      ])
    );
  },
  getExtensions() {
    return [
      {
        modules: [
          {
            name: `${WORKFLOWS_PLUGIN_NAME}:local-wrapped-binding`,
            esModule: wrapped_binding_worker_default(),
            internal: true
          }
        ]
      }
    ];
  },
  async getServices({ options, tmpPath, sharedOptions, workerNames }) {
    const workflows = getEnvBindingsOfType(options.config, "workflow");
    if (workflows.length === 0) {
      return [];
    }
    const persistPath = getPersistPath(
      WORKFLOWS_PLUGIN_NAME,
      tmpPath,
      sharedOptions.resourcePersistencePath
    );
    await import_promises20.default.mkdir(persistPath, { recursive: true });
    const storageServices = workflows.map(
      ([_, binding]) => ({
        name: `${WORKFLOWS_STORAGE_SERVICE_NAME}-${binding.name}`,
        disk: { path: persistPath, writable: true }
      })
    );
    const observabilityEnabled = sharedOptions.unsafeObservability === true;
    const services = workflows.map(([bindingName, binding]) => {
      const remoteProxyConnectionString = getRemoteProxyConnectionString(
        binding,
        options.dev
      );
      const external = !workerNames.includes(binding.workerName);
      const stepLimit = binding.limits?.steps;
      const uniqueKey = `miniflare-workflows-${binding.name}`;
      const engineCompatibilityFlags = [
        "experimental",
        ...options.config.compatibilityFlags ?? []
      ];
      const streamingTails = observabilityEnabled ? [
        {
          name: getUserServiceName(OBSERVABILITY_COLLECTOR_SERVICE_NAME),
          props: { json: JSON.stringify({ worker: binding.name }) }
        }
      ] : void 0;
      if (observabilityEnabled) {
        engineCompatibilityFlags.push(
          ...OBSERVABILITY_COMPAT_FLAGS.filter(
            (flag) => !engineCompatibilityFlags.includes(flag)
          )
        );
      }
      const workflowsBinding = {
        name: getUserBindingServiceName(
          WORKFLOWS_PLUGIN_NAME,
          binding.name,
          remoteProxyConnectionString
        ),
        worker: {
          compatibilityDate: "2024-10-22",
          compatibilityFlags: Array.from(new Set(engineCompatibilityFlags)),
          ...streamingTails ? { streamingTails } : {},
          modules: [
            {
              name: "workflows.mjs",
              esModule: binding_worker_default4()
            }
          ],
          durableObjectNamespaces: [
            {
              className: "Engine",
              enableSql: true,
              uniqueKey,
              preventEviction: true
            }
          ],
          durableObjectStorage: {
            localDisk: `${WORKFLOWS_STORAGE_SERVICE_NAME}-${binding.name}`
          },
          bindings: [
            {
              name: "ENGINE",
              durableObjectNamespace: { className: "Engine" }
            },
            external ? {
              name: "USER_WORKFLOW",
              service: {
                name: getUserServiceName(SERVICE_DEV_REGISTRY_PROXY),
                entrypoint: "ExternalServiceProxy",
                props: {
                  json: JSON.stringify({
                    service: binding.workerName,
                    entrypoint: binding.exportName
                  })
                }
              }
            } : {
              name: "USER_WORKFLOW",
              service: {
                name: getUserServiceName(binding.workerName),
                entrypoint: binding.exportName
              }
            },
            {
              name: "BINDING_NAME",
              json: JSON.stringify(bindingName)
            },
            {
              name: "WORKFLOW_NAME",
              json: JSON.stringify(binding.name)
            },
            ...stepLimit !== void 0 ? [
              {
                name: "STEP_LIMIT",
                json: JSON.stringify(stepLimit)
              }
            ] : []
          ]
        }
      };
      return workflowsBinding;
    });
    return [...storageServices, ...services];
  }
};

// src/plugins/index.ts
var PLUGINS = {
  [CORE_PLUGIN_NAME2]: CORE_PLUGIN,
  [CACHE_PLUGIN_NAME]: CACHE_PLUGIN,
  [D1_PLUGIN_NAME]: D1_PLUGIN,
  [DURABLE_OBJECTS_PLUGIN_NAME]: DURABLE_OBJECTS_PLUGIN,
  [KV_PLUGIN_NAME]: KV_PLUGIN,
  [QUEUES_PLUGIN_NAME]: QUEUES_PLUGIN,
  [R2_PLUGIN_NAME]: R2_PLUGIN,
  [HYPERDRIVE_PLUGIN_NAME]: HYPERDRIVE_PLUGIN,
  [RATELIMIT_PLUGIN_NAME]: RATELIMIT_PLUGIN,
  [ASSETS_PLUGIN_NAME]: ASSETS_PLUGIN,
  [WORKFLOWS_PLUGIN_NAME]: WORKFLOWS_PLUGIN,
  [PIPELINES_PLUGIN_NAME]: PIPELINE_PLUGIN,
  [SECRET_STORE_PLUGIN_NAME]: SECRET_STORE_PLUGIN,
  [EMAIL_PLUGIN_NAME]: EMAIL_PLUGIN,
  [ANALYTICS_ENGINE_PLUGIN_NAME]: ANALYTICS_ENGINE_PLUGIN,
  [AI_PLUGIN_NAME]: AI_PLUGIN,
  [AGENT_MEMORY_PLUGIN_NAME]: AGENT_MEMORY_PLUGIN,
  [AI_SEARCH_PLUGIN_NAME]: AI_SEARCH_PLUGIN,
  [WEBSEARCH_PLUGIN_NAME]: WEBSEARCH_PLUGIN,
  [BROWSER_RENDERING_PLUGIN_NAME]: BROWSER_RENDERING_PLUGIN,
  [DISPATCH_NAMESPACE_PLUGIN_NAME]: DISPATCH_NAMESPACE_PLUGIN,
  [IMAGES_PLUGIN_NAME]: IMAGES_PLUGIN,
  [STREAM_PLUGIN_NAME]: STREAM_PLUGIN,
  [VECTORIZE_PLUGIN_NAME]: VECTORIZE_PLUGIN,
  [VPC_NETWORKS_PLUGIN_NAME]: VPC_NETWORKS_PLUGIN,
  [VPC_SERVICES_PLUGIN_NAME]: VPC_SERVICES_PLUGIN,
  [MTLS_PLUGIN_NAME]: MTLS_PLUGIN,
  [HELLO_WORLD_PLUGIN_NAME]: HELLO_WORLD_PLUGIN,
  [FLAGSHIP_PLUGIN_NAME]: FLAGSHIP_PLUGIN,
  [ARTIFACTS_PLUGIN_NAME]: ARTIFACTS_PLUGIN,
  [WORKER_LOADER_PLUGIN_NAME]: WORKER_LOADER_PLUGIN,
  [MEDIA_PLUGIN_NAME]: MEDIA_PLUGIN,
  [VERSION_METADATA_PLUGIN_NAME]: VERSION_METADATA_PLUGIN
};
var PLUGIN_ENTRIES = Object.entries(PLUGINS);

// src/plugins/browser-rendering/browser-version.ts
var BROWSER_VERSION = "126.0.6478.182";

// src/plugins/core/inspector-proxy/inspector-proxy-controller.ts
var import_node_crypto7 = __toESM(require("node:crypto"));
var import_node_http = require("node:http");
var import_ws5 = __toESM(require("ws"));

// package.json
var version3 = "5.20260815.0-alpha";

// src/plugins/core/inspector-proxy/inspector-proxy.ts
var import_node_assert18 = __toESM(require("node:assert"));
var import_ws4 = __toESM(require("ws"));

// src/plugins/core/inspector-proxy/devtools.ts
function isDevToolsEvent(event, name) {
  return typeof event === "object" && event !== null && "method" in event && event.method === name;
}

// src/plugins/core/inspector-proxy/inspector-proxy.ts
var InspectorProxy = class {
  #log;
  #workerName;
  #runtimeWs;
  #devtoolsWs;
  #devtoolsHaveFileSystemAccess = false;
  constructor(log2, workerName, runtimeWs) {
    this.#log = log2;
    this.#workerName = workerName;
    this.#runtimeWs = runtimeWs;
    this.#runtimeWs.once("open", () => this.#handleRuntimeWebSocketOpen());
  }
  get workerName() {
    return this.#workerName;
  }
  get path() {
    return `/${this.#workerName}`;
  }
  onDevtoolsConnected(devtoolsWs, devtoolsHaveFileSystemAccess) {
    if (this.#devtoolsWs) {
      devtoolsWs.close(
        1013,
        "Too many clients; only one can be connected at a time"
      );
      return;
    }
    this.#devtoolsWs = devtoolsWs;
    this.#devtoolsHaveFileSystemAccess = devtoolsHaveFileSystemAccess;
    (0, import_node_assert18.default)(this.#devtoolsWs?.readyState === import_ws4.default.OPEN);
    this.#devtoolsWs.on("error", (message) => this.#log.error(message));
    this.#devtoolsWs.once("close", () => {
      if (this.#runtimeWs?.OPEN) {
        this.#sendMessageToRuntime({
          method: "Debugger.disable",
          id: this.#nextCounter()
        });
      }
      this.#devtoolsWs = void 0;
    });
    this.#devtoolsWs.on("message", (data) => {
      const message = JSON.parse(data.toString());
      (0, import_node_assert18.default)(this.#runtimeWs?.OPEN);
      this.#sendMessageToRuntime(message);
    });
  }
  #runtimeMessageCounter = 1e8;
  #nextCounter() {
    return ++this.#runtimeMessageCounter;
  }
  #runtimeKeepAliveInterval;
  #handleRuntimeWebSocketOpen() {
    (0, import_node_assert18.default)(this.#runtimeWs?.OPEN);
    this.#runtimeWs.on("message", (data) => {
      const message = JSON.parse(data.toString());
      if (!this.#devtoolsWs) {
        return;
      }
      if (isDevToolsEvent(message, "Debugger.scriptParsed")) {
        return this.#handleRuntimeScriptParsed(message);
      }
      return this.#sendMessageToDevtools(message);
    });
    clearInterval(this.#runtimeKeepAliveInterval);
    this.#runtimeKeepAliveInterval = setInterval(() => {
      if (this.#runtimeWs?.OPEN) {
        this.#sendMessageToRuntime({
          method: "Runtime.getIsolateId",
          id: this.#nextCounter()
        });
      }
    }, 1e4);
  }
  #handleRuntimeScriptParsed(message) {
    if (!this.#devtoolsHaveFileSystemAccess && message.params.sourceMapURL !== void 0 && // Don't try to find a sourcemap for e.g. node-internal: scripts
    message.params.url.startsWith("file:")) {
      const url46 = new URL(message.params.sourceMapURL, message.params.url);
      if (url46.protocol === "file:") {
        message.params.sourceMapURL = url46.href.replace(
          "file:",
          "wrangler-file:"
        );
      }
    }
    return this.#sendMessageToDevtools(message);
  }
  #sendMessageToDevtools(message) {
    (0, import_node_assert18.default)(this.#devtoolsWs);
    if (!this.#devtoolsWs.OPEN) {
      this.#devtoolsWs.once(
        "open",
        () => this.#devtoolsWs?.send(JSON.stringify(message))
      );
      return;
    }
    this.#devtoolsWs.send(JSON.stringify(message));
  }
  #sendMessageToRuntime(message) {
    (0, import_node_assert18.default)(this.#runtimeWs?.OPEN);
    this.#runtimeWs.send(JSON.stringify(message));
  }
  async dispose() {
    clearInterval(this.#runtimeKeepAliveInterval);
    this.#devtoolsWs?.close();
    this.#runtimeWs?.close();
  }
};

// src/plugins/core/inspector-proxy/inspector-proxy-controller.ts
var InspectorProxyController = class {
  constructor(inspectorPortOption, inspectorHostOption = "127.0.0.1", log2, workerNamesToProxy) {
    this.inspectorPortOption = inspectorPortOption;
    this.inspectorHostOption = inspectorHostOption;
    this.log = log2;
    this.workerNamesToProxy = workerNamesToProxy;
    this.#server = this.#createServer();
  }
  inspectorPortOption;
  inspectorHostOption;
  log;
  workerNamesToProxy;
  #runtimeConnectionEstablished = new DeferredPromise();
  #proxies = [];
  #server;
  async #getInspectorPort() {
    const server = await this.#server;
    const address = server.address();
    if (address && typeof address !== "string") {
      return address.port;
    } else {
      throw new Error(
        `Unable to acquire a port to listen on - address: "${address}"`
      );
    }
  }
  async #createServer() {
    const server = (0, import_node_http.createServer)(async (req, res) => {
      const maybeJson = await this.#handleDevToolsJsonRequest(
        req.headers.host ?? "localhost",
        req.url ?? "/"
      );
      if (maybeJson !== null) {
        res.setHeader("Content-Type", "application/json");
        res.end(JSON.stringify(maybeJson));
        return;
      }
      res.statusCode = 404;
      res.end(null);
    });
    this.#initializeWebSocketServer(server);
    await this.#startListening(server);
    return server;
  }
  async #restartServer() {
    const server = await this.#server;
    await this.#closeServer(server);
    await this.#startListening(server);
  }
  /**
   * Try to start listening on a the chosen port (or any port if none-chosen).
   *
   * @param server the server to start listening.
   */
  async #startListening(server) {
    this.log.debug(
      `Trying to listen on ${this.inspectorHostOption}:${this.inspectorPortOption}`
    );
    return new Promise((resolve8, reject) => {
      server.once("error", reject);
      server.listen(
        this.inspectorPortOption,
        this.inspectorHostOption,
        resolve8
      );
    });
  }
  async #closeServer(server) {
    server.closeAllConnections();
    return await new Promise((resolve8) => {
      server.close((err) => {
        if (err) {
          this.log.error(err);
        }
        resolve8();
      });
    });
  }
  #initializeWebSocketServer(server) {
    const devtoolsWebSocketServer = new import_ws5.WebSocketServer({ server });
    devtoolsWebSocketServer.on("connection", (devtoolsWs, upgradeRequest) => {
      const validationError = this.#validateDevToolsWebSocketUpgradeRequest(upgradeRequest);
      if (validationError !== null) {
        devtoolsWs.close();
        return;
      }
      const proxy = this.#proxies.find(
        ({ path: path73 }) => upgradeRequest.url === path73
      );
      if (!proxy) {
        this.log.warn(
          `Warning: An inspector connection was requested for the ${upgradeRequest.url} path but no such inspector exists`
        );
        devtoolsWs.close();
        return;
      }
      proxy.onDevtoolsConnected(
        devtoolsWs,
        this.#checkIfDevtoolsHaveFileSystemAccess(upgradeRequest)
      );
    });
  }
  #validateDevToolsWebSocketUpgradeRequest(req) {
    const hostHeader = req.headers.host;
    if (hostHeader == null) return { statusText: null, status: 400 };
    try {
      const host = new URL(`http://${hostHeader}`);
      const allowedHostnames = [
        ...ALLOWED_HOST_HOSTNAMES,
        this.inspectorHostOption
      ];
      if (!allowedHostnames.includes(host.hostname)) {
        return { statusText: "Disallowed `Host` header", status: 401 };
      }
    } catch {
      return { statusText: "Expected `Host` header", status: 400 };
    }
    let originHeader = req.headers.origin;
    if (!originHeader && !req.headers["user-agent"]) {
      originHeader = "http://localhost";
    }
    if (!originHeader) {
      return { statusText: "Expected `Origin` header", status: 400 };
    }
    try {
      const origin = new URL(originHeader);
      const allowed = ALLOWED_ORIGIN_HOSTNAMES.some((rule) => {
        if (typeof rule === "string") return origin.hostname === rule;
        else return rule.test(origin.hostname);
      });
      if (!allowed) {
        return { statusText: "Disallowed `Origin` header", status: 401 };
      }
    } catch {
      return { statusText: "Expected `Origin` header", status: 400 };
    }
    return null;
  }
  #checkIfDevtoolsHaveFileSystemAccess(req) {
    const userAgent = req.headers["user-agent"] ?? "";
    const hasFileSystemAccess = !/mozilla/i.test(userAgent);
    return hasFileSystemAccess;
  }
  #inspectorId = import_node_crypto7.default.randomUUID();
  async #handleDevToolsJsonRequest(host, path73) {
    if (path73 === "/json/version") {
      return {
        Browser: `miniflare/v${version3}`,
        // TODO: (someday): The DevTools protocol should match that of workerd.
        // This could be exposed by the preview API.
        "Protocol-Version": "1.3"
      };
    }
    if (path73 === "/json" || path73 === "/json/list") {
      return this.#proxies.map(({ workerName }) => {
        const localHost = `${host}/${workerName}`;
        const devtoolsFrontendUrl = `https://devtools.devprod.cloudflare.dev/js_app?theme=systemPreferred&debugger=true&ws=${localHost}`;
        return {
          id: `${this.#inspectorId}-${workerName}`,
          type: "node",
          // TODO: can we specify different type?
          description: "workers",
          webSocketDebuggerUrl: `ws://${localHost}`,
          devtoolsFrontendUrl,
          devtoolsFrontendUrlCompat: devtoolsFrontendUrl,
          // Below are fields that are visible in the DevTools UI.
          title: workerName.length === 0 || this.#proxies.length === 1 ? `Cloudflare Worker` : `Cloudflare Worker: ${workerName}`,
          faviconUrl: "https://workers.cloudflare.com/favicon.ico"
          // url: "http://" + localHost, // looks unnecessary
        };
      });
    }
    return null;
  }
  async getInspectorURL() {
    return getWebsocketURL(
      this.inspectorHostOption,
      await this.#getInspectorPort()
    );
  }
  async updateConnection(inspectorPortOption, inspectorHostOption, runtimeInspectorPort, workerNamesToProxy) {
    this.workerNamesToProxy = workerNamesToProxy;
    if (this.inspectorPortOption !== inspectorPortOption || this.inspectorHostOption !== inspectorHostOption) {
      this.inspectorPortOption = inspectorPortOption;
      this.inspectorHostOption = inspectorHostOption;
      await this.#restartServer();
    }
    const workerdInspectorJson = await fetch(
      `http://127.0.0.1:${runtimeInspectorPort}/json`
    ).then((resp) => resp.json());
    await Promise.all(this.#proxies.map((proxy) => proxy.dispose()));
    this.#proxies = workerdInspectorJson.map(({ id }) => {
      if (!id.startsWith("core:user:")) {
        return;
      }
      const workerName = id.replace(/^core:user:/, "");
      if (!this.workerNamesToProxy.has(workerName)) {
        return;
      }
      return new InspectorProxy(
        this.log,
        workerName,
        new import_ws5.default(`ws://127.0.0.1:${runtimeInspectorPort}/${id}`)
      );
    }).filter(Boolean);
    this.#runtimeConnectionEstablished.resolve();
  }
  async #waitForReady() {
    await this.#runtimeConnectionEstablished;
  }
  get ready() {
    return this.#waitForReady();
  }
  async dispose() {
    await Promise.all(this.#proxies.map((proxy) => proxy.dispose()));
    const server = await this.#server;
    server.closeAllConnections();
    return new Promise((resolve8, reject) => {
      server.close((err) => err ? reject(err) : resolve8());
    });
  }
};
function getWebsocketURL(host, port) {
  return new URL(`ws://${host}:${port}`);
}
var ALLOWED_HOST_HOSTNAMES = ["127.0.0.1", "[::1]", "localhost"];
var ALLOWED_ORIGIN_HOSTNAMES = [
  "devtools.devprod.cloudflare.dev",
  // Workers + Assets (current deployment)
  "cloudflare-devtools.devprod.workers.dev",
  /^[a-z0-9]+-cloudflare-devtools\.devprod\.workers\.dev$/,
  // Cloudflare Pages (legacy deployment)
  "cloudflare-devtools.pages.dev",
  /^[a-z0-9]+\.cloudflare-devtools\.pages\.dev$/,
  "127.0.0.1",
  "[::1]",
  "localhost"
];

// src/plugins/core/module-fallback.ts
var import_node_assert19 = __toESM(require("node:assert"));
function isModuleFallbackRequest(request4) {
  if (request4.method === "GET" && request4.headers.has("X-Resolve-Method")) {
    return true;
  }
  if (request4.method === "POST") {
    return true;
  }
  return false;
}
function assertIsV2ModuleFallbackProtocol(body) {
  (0, import_node_assert19.default)(typeof body === "object" && body !== null && "specifier" in body);
}
async function parseModuleFallbackRequest(request4) {
  if (request4.method === "GET" && request4.headers.has("X-Resolve-Method")) {
    const url46 = new URL(request4.url);
    const specifier = url46.searchParams.get("specifier");
    if (!specifier) {
      return null;
    }
    const resolveMethod = request4.headers.get("X-Resolve-Method");
    return {
      protocol: "v1",
      type: resolveMethod === "require" ? "require" : "import",
      specifier,
      rawSpecifier: url46.searchParams.get("rawSpecifier") ?? void 0,
      referrer: url46.searchParams.get("referrer") ?? void 0
    };
  }
  if (request4.method === "POST") {
    try {
      const body = await request4.json();
      assertIsV2ModuleFallbackProtocol(body);
      return {
        ...body,
        protocol: "v2"
      };
    } catch {
      return null;
    }
  }
  return null;
}

// src/plugins/hyperdrive/hyperdrive-proxy.ts
var import_node_fs18 = __toESM(require("node:fs"));
var import_node_net = __toESM(require("node:net"));
var import_node_tls2 = __toESM(require("node:tls"));
var schemes = {
  postgresql: "postgresql",
  postgres: "postgres",
  mysql: "mysql"
};
var POSTGRES_SSL_REQUEST_PACKET = Buffer.from([
  0,
  0,
  0,
  8,
  4,
  210,
  22,
  47
]);
function buildTlsConfig(sslmodeVerifyFull, sslmodeVerifyCa, sslrootcert) {
  if (!sslmodeVerifyFull && !sslmodeVerifyCa) {
    return { rejectUnauthorized: false };
  }
  const config3 = { rejectUnauthorized: true };
  if (sslrootcert && sslrootcert !== "system") {
    config3.ca = import_node_fs18.default.readFileSync(sslrootcert);
  }
  if (sslmodeVerifyCa) {
    config3.checkServerIdentity = () => void 0;
  }
  return config3;
}
function buildTlsConnectionOptions(dbSocket, targetHost, tlsConfig, extra) {
  const options = {
    socket: dbSocket,
    host: targetHost,
    // SNI only accepts hostnames. Passing an IP here breaks on Node 25+
    servername: import_node_net.default.isIP(targetHost) === 0 ? targetHost : void 0,
    rejectUnauthorized: tlsConfig.rejectUnauthorized,
    ...extra
  };
  if (tlsConfig.ca) {
    options.ca = tlsConfig.ca;
  }
  if (tlsConfig.checkServerIdentity) {
    options.checkServerIdentity = tlsConfig.checkServerIdentity;
  }
  return options;
}
var HyperdriveProxyController = class {
  // Map hyperdrive binding name to proxy server
  #servers = /* @__PURE__ */ new Map();
  log;
  /**
   * Creates a proxy server for a Hyperdrive binding.
   *
   * @param config - The configuration for the proxy server.
   * @returns A promise that resolves to the port number of the proxy server.
   */
  async createProxyServer(config3) {
    const { name, targetHost, targetPort, scheme, sslmode, sslrootcert } = config3;
    const server = import_node_net.default.createServer((clientSocket) => {
      this.#handleConnection(
        clientSocket,
        targetHost,
        Number.parseInt(targetPort),
        scheme,
        sslmode,
        sslrootcert
      );
    });
    server.on("error", (err) => {
      this.log?.error(
        new Error(
          `Hyperdrive proxy server error for binding "${name}": ${err.message}`
        )
      );
    });
    const port = await new Promise((resolve8, reject) => {
      server.once("error", reject);
      server.listen(0, "127.0.0.1", () => {
        server.off("error", reject);
        const address = server.address();
        if (address && typeof address !== "string") {
          resolve8(address.port);
        } else {
          reject(new Error("Invalid port"));
        }
      });
    });
    this.#servers.set(name, server);
    return port;
  }
  /**
   * Handles a connection from workerd by hyperdrive magic hostname "randomUUID.hyperdrive.local"
   *
   * @param clientSocket - The client socket.
   * @param targetHost - The hostname of the target database.
   * @param targetPort - The port of the target database.
   * @param scheme - The scheme of the target database.
   * @param sslmode - The sslmode of the target database.
   * @param sslrootcert - Path to the SSL root certificate, or "system" to use the system CA store.
   */
  async #handleConnection(clientSocket, targetHost, targetPort, scheme, sslmode, sslrootcert) {
    const dbSocket = import_node_net.default.connect({ host: targetHost, port: targetPort });
    const sslmodeRequire = sslmode === "require";
    const sslmodePrefer = sslmode === "prefer";
    const sslmodeVerifyFull = sslmode === "verify-full";
    const sslmodeVerifyCa = sslmode === "verify-ca";
    const sslmodeStrict = sslmodeVerifyFull || sslmodeVerifyCa;
    if (sslmodePrefer || sslmodeRequire || sslmodeStrict) {
      try {
        const tlsConfig = buildTlsConfig(
          sslmodeVerifyFull,
          sslmodeVerifyCa,
          sslrootcert
        );
        if (scheme === schemes.postgres || scheme === schemes.postgresql) {
          return await handlePostgresTlsConnection(
            dbSocket,
            clientSocket,
            targetHost,
            targetPort,
            sslmodeRequire || sslmodeStrict,
            tlsConfig
          );
        } else if (scheme === schemes.mysql) {
          return await handleMySQLTlsConnection(
            dbSocket,
            clientSocket,
            targetHost,
            targetPort,
            sslmodeRequire || sslmodeStrict,
            tlsConfig
          );
        }
      } catch (e) {
        if (sslmodeRequire || sslmodeStrict) {
          clientSocket.write(`${e}
`);
          clientSocket.end();
          dbSocket.destroy();
          return;
        }
      }
    }
    clientSocket.pipe(dbSocket);
    dbSocket.pipe(clientSocket);
  }
  /** Disposes of the proxy servers when shutting down the worker.*/
  dispose() {
    for (const server of this.#servers.values()) {
      server.close();
    }
    this.#servers.clear();
  }
};
async function handlePostgresTlsConnection(dbSocket, clientSocket, targetHost, targetPort, sslmodeRequire, tlsConfig) {
  await writeAsync(dbSocket, POSTGRES_SSL_REQUEST_PACKET);
  const response = await readAsync(dbSocket);
  const sslResponseFlag = response.toString("utf8", 0, 1);
  if (sslResponseFlag === "S") {
    const tlsOptions = buildTlsConnectionOptions(
      dbSocket,
      targetHost,
      tlsConfig
    );
    try {
      const tlsSocket = await tlsConnect(tlsOptions);
      setupTLSConnection(clientSocket, tlsSocket);
      return;
    } catch (e) {
      if (sslmodeRequire) {
        throw e;
      }
    }
  }
  if (sslmodeRequire) {
    throw Error("Server does not support SSL, but client requires SSL.");
  }
  dbSocket.destroy();
  const newDbSocket = await createPlainTCPConnection(
    targetHost,
    targetPort,
    clientSocket
  );
  clientSocket.pipe(newDbSocket);
  newDbSocket.pipe(clientSocket);
}
async function handleMySQLTlsConnection(dbSocket, clientSocket, targetHost, targetPort, sslmodeRequire, tlsConfig) {
  const initPacketChunk = await readAsync(dbSocket);
  const payloadHeaderLength = initPacketChunk[0] | initPacketChunk[1] << 8 | initPacketChunk[2] << 16;
  let fullPayloadBody;
  const payloadStart = 4;
  const alreadyRead = initPacketChunk.length - payloadStart;
  if (alreadyRead === payloadHeaderLength) {
    fullPayloadBody = Buffer.from(initPacketChunk.subarray(payloadStart));
  } else if (alreadyRead < payloadHeaderLength) {
    const chunks = [initPacketChunk.subarray(payloadStart)];
    let totalRead = alreadyRead;
    while (totalRead < payloadHeaderLength) {
      const chunk = await readAsync(dbSocket);
      chunks.push(chunk);
      totalRead += chunk.length;
    }
    fullPayloadBody = Buffer.concat(chunks);
    if (totalRead > payloadHeaderLength) {
      fullPayloadBody = fullPayloadBody.subarray(0, payloadHeaderLength);
    }
  } else {
    throw Error("Could not parse header properly.");
  }
  if (mysqlSupportsSSL(fullPayloadBody)) {
    const sslRequestPacket = [
      32,
      0,
      0,
      1,
      // payload length = 32, sequence id = 1
      0,
      10,
      0,
      0,
      // capability_flags = CLIENT_SSL | CLIENT_PROTOCOL_41
      0,
      0,
      0,
      0,
      // max_packet_size = 0
      33,
      // character_set = utf8_general_ci
      ...new Array(23).fill(0)
      // reserved (23 bytes)
    ];
    await writeAsync(dbSocket, sslRequestPacket);
    const tlsOptions = buildTlsConnectionOptions(
      dbSocket,
      targetHost,
      tlsConfig,
      { minVersion: "TLSv1.2" }
    );
    try {
      const tlsSocket = await tlsConnect(tlsOptions);
      const fullInitPacket = Buffer.concat([
        initPacketChunk.subarray(0, 4),
        fullPayloadBody
      ]);
      await writeAsync(clientSocket, fullInitPacket);
      const clientAuthPayload = await readAsync(clientSocket);
      clientAuthPayload[3]++;
      await writeAsync(tlsSocket, clientAuthPayload);
      const authResponsePayload = await readAsync(tlsSocket);
      authResponsePayload[3]--;
      await writeAsync(clientSocket, authResponsePayload);
      setupTLSConnection(clientSocket, tlsSocket);
      return;
    } catch (e) {
      if (sslmodeRequire) {
        throw e;
      }
    }
  }
  if (sslmodeRequire) {
    throw new Error("Server SSL failed, but client requires SSL.");
  }
  dbSocket.destroy();
  const newDbSocket = await createPlainTCPConnection(
    targetHost,
    targetPort,
    clientSocket
  );
  clientSocket.pipe(newDbSocket);
  newDbSocket.pipe(clientSocket);
  return;
}
async function createPlainTCPConnection(targetHost, targetPort, clientSocket) {
  const dbSocket = import_node_net.default.connect({ host: targetHost, port: targetPort });
  await new Promise((resolve8, reject) => {
    const handleConnect = () => {
      dbSocket.off("error", handleError);
      resolve8();
    };
    const handleError = (err) => {
      dbSocket.off("data", handleConnect);
      reject(err);
    };
    dbSocket.once("connect", handleConnect);
    dbSocket.once("error", handleError);
  });
  dbSocket.on("error", () => {
    clientSocket.destroy();
  });
  return dbSocket;
}
function setupTLSConnection(clientSocket, tlsSocket) {
  tlsSocket.on("error", () => {
    clientSocket.destroy();
    tlsSocket.destroy();
  });
  clientSocket.pipe(tlsSocket);
  tlsSocket.pipe(clientSocket);
}
function writeAsync(socket, bytes) {
  return new Promise((resolve8, reject) => {
    const buffer = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes);
    socket.write(buffer, (err) => err ? reject(err) : resolve8());
  });
}
function readAsync(socket) {
  return new Promise((resolve8, reject) => {
    const handleData = (data) => {
      socket.off("error", handleError);
      resolve8(data);
    };
    const handleError = (err) => {
      socket.off("data", handleData);
      reject(err);
    };
    socket.once("data", handleData);
    socket.once("error", handleError);
  });
}
function tlsConnect(options) {
  return new Promise((resolve8, reject) => {
    const socket = import_node_tls2.default.connect(options);
    const handleSecureConnect = () => {
      socket.off("error", handleError);
      resolve8(socket);
    };
    const handleError = (err) => {
      socket.off("secureConnect", handleSecureConnect);
      reject(err);
    };
    socket.once("secureConnect", handleSecureConnect);
    socket.once("error", handleError);
  });
}
var MYSQL_CONNECTION_ID_LENGTH = 4;
var MYSQL_AUTH_PLUGIN_DATA_PART_1_LENGTH = 8;
var MYSQL_FILLER_LENGTH = 1;
var MYSQL_CAPABILITY_FLAGS_LOWER_LENGTH = 2;
var MYSQL_SSL_CAPABILITY_FLAG = 2048;
function mysqlSupportsSSL(payload) {
  const payloadLength = payload.length;
  let offset = 1;
  while (offset < payloadLength && payload[offset] != 0) offset++;
  offset++;
  offset += MYSQL_CONNECTION_ID_LENGTH;
  offset += MYSQL_AUTH_PLUGIN_DATA_PART_1_LENGTH;
  offset += MYSQL_FILLER_LENGTH;
  if (offset + MYSQL_CAPABILITY_FLAGS_LOWER_LENGTH > payloadLength)
    return false;
  const caps = payload[offset] | payload[offset + 1] << 8;
  return (caps & MYSQL_SSL_CAPABILITY_FLAG) != 0;
}

// src/plugins/images/fetcher.ts
var import_node_buffer6 = require("node:buffer");
function validateTransforms(inputTransforms) {
  if (!Array.isArray(inputTransforms)) {
    return null;
  }
  for (const transform3 of inputTransforms) {
    for (const key of ["imageIndex", "rotate", "width", "height"]) {
      if (transform3[key] !== void 0 && typeof transform3[key] != "number") {
        return null;
      }
    }
  }
  return inputTransforms;
}
async function imagesLocalFetcher(request4) {
  let sharp;
  try {
    const { default: importedSharp } = await import("sharp");
    sharp = importedSharp;
  } catch {
    return errorResponse(
      503,
      9523,
      "The Sharp library is not available, check your version of Node is compatible"
    );
  }
  const data = await request4.formData();
  const body = data.get("image");
  if (!body || !(body instanceof import_node_buffer6.File)) {
    return errorResponse(
      400,
      9523,
      `ERROR: Internal Images binding error: expected image in request, got ${body}`
    );
  }
  const transformer = sharp(await body.arrayBuffer(), {});
  const url46 = new URL(request4.url);
  if (url46.pathname == "/info") {
    return runInfo(transformer);
  } else {
    const badTransformsResponse = errorResponse(
      400,
      9523,
      "ERROR: Internal Images binding error: Expected JSON array of valid transforms in transforms field"
    );
    try {
      const transformsJson = data.get("transforms");
      if (typeof transformsJson !== "string") {
        return badTransformsResponse;
      }
      const transforms = validateTransforms(JSON.parse(transformsJson));
      if (transforms === null) {
        return badTransformsResponse;
      }
      const outputFormat = data.get("output_format");
      if (outputFormat != null && typeof outputFormat !== "string") {
        return errorResponse(
          400,
          9523,
          "ERROR: Internal Images binding error: Expected output format to be a string if provided"
        );
      }
      return runTransform(transformer, transforms, outputFormat);
    } catch {
      return badTransformsResponse;
    }
  }
}
async function runInfo(transformer) {
  const metadata = await transformer.metadata();
  let mime = null;
  switch (metadata.format) {
    case "jpeg":
      mime = "image/jpeg";
      break;
    case "svg":
      mime = "image/svg+xml";
      break;
    case "png":
      mime = "image/png";
      break;
    case "webp":
      mime = "image/webp";
      break;
    case "gif":
      mime = "image/gif";
      break;
    // libvips reports AVIF (and other HEIF variants) under the `heif`
    // container format; Cloudflare Images' supported HEIF variant is AVIF.
    case "heif":
      mime = "image/avif";
      break;
    default:
      return errorResponse(
        415,
        9520,
        `ERROR: Unsupported image type ${metadata.format}, expected one of: JPEG, SVG, PNG, WebP, GIF or AVIF`
      );
  }
  let resp;
  if (mime == "image/svg+xml") {
    resp = {
      format: mime
    };
  } else {
    if (!metadata.size || !metadata.width || !metadata.height) {
      return errorResponse(
        500,
        9523,
        "ERROR: Internal Images binding error: Expected size, width and height for bitmap input"
      );
    }
    resp = {
      format: mime,
      fileSize: metadata.size,
      width: metadata.width,
      height: metadata.height
    };
  }
  return Response3.json(resp);
}
async function runTransform(transformer, transforms, outputFormat) {
  for (const transform3 of transforms) {
    if (transform3.imageIndex !== void 0 && transform3.imageIndex !== 0) {
      continue;
    }
    if (transform3.rotate !== void 0) {
      transformer.rotate(transform3.rotate);
    }
    if (transform3.width !== void 0 || transform3.height !== void 0) {
      const { fit, withoutEnlargement } = resolveFit(transform3.fit);
      transformer.resize(transform3.width || null, transform3.height || null, {
        fit,
        withoutEnlargement,
        position: resolveGravity(transform3.gravity),
        background: transform3.background ?? (transform3.fit === "pad" ? "#ffffff" : void 0)
      });
    }
  }
  switch (outputFormat) {
    case "image/avif":
      transformer.avif();
      break;
    case "image/gif":
      return errorResponse(
        415,
        9520,
        "ERROR: GIF output is not supported in local mode"
      );
    case "image/jpeg":
      transformer.jpeg();
      break;
    case "image/png":
      transformer.png();
      break;
    case "image/webp":
      transformer.webp();
      break;
    case "rgb":
    case "rgba":
      return errorResponse(
        415,
        9520,
        "ERROR: RGB/RGBA output is not supported in local mode"
      );
    default:
      outputFormat = "image/jpeg";
      break;
  }
  const output = await transformer.toBuffer();
  return new Response3(output, {
    headers: {
      "content-type": outputFormat
    }
  });
}
function errorResponse(status2, code, message) {
  return new Response3(`ERROR ${code}: ${message}`, {
    status: status2,
    headers: {
      "content-type": "text/plain",
      "cf-images-binding": `err=${code}`
    }
  });
}
var NAMED_QUALITIES = {
  low: 35,
  "medium-low": 50,
  "medium-high": 70,
  high: 90
};
function resolveQuality(quality) {
  if (typeof quality === "number") {
    return Math.min(100, Math.max(1, Math.round(quality)));
  }
  if (typeof quality === "string" && quality in NAMED_QUALITIES) {
    return NAMED_QUALITIES[quality];
  }
  return void 0;
}
function resolveFit(fit) {
  switch (fit) {
    case "contain":
      return { fit: "inside" };
    case "cover":
      return { fit: "cover" };
    case "crop":
      return { fit: "cover", withoutEnlargement: true };
    case "pad":
      return { fit: "contain" };
    case "squeeze":
      return { fit: "fill" };
    case "scale-down":
    default:
      return { fit: "inside", withoutEnlargement: true };
  }
}
function resolveGravity(gravity) {
  switch (gravity) {
    case "left":
    case "right":
    case "top":
    case "bottom":
      return gravity;
    case "center":
      return "centre";
    default:
      return void 0;
  }
}
function formatToMime(format5) {
  switch (format5) {
    case "jpeg":
      return "image/jpeg";
    case "svg":
      return "image/svg+xml";
    case "png":
      return "image/png";
    case "webp":
      return "image/webp";
    case "gif":
      return "image/gif";
    // libvips reports AVIF (and other HEIF variants) under the `heif`
    // container format; Cloudflare Images' supported HEIF variant is AVIF.
    case "heif":
      return "image/avif";
    default:
      return null;
  }
}
function applyCfImageTransforms(transformer, options) {
  if (typeof options.rotate === "number") {
    transformer.rotate(options.rotate);
  }
  const dpr = typeof options.dpr === "number" && options.dpr > 0 ? options.dpr : 1;
  const width = typeof options.width === "number" ? Math.round(options.width * dpr) : void 0;
  const height = typeof options.height === "number" ? Math.round(options.height * dpr) : void 0;
  if (width !== void 0 || height !== void 0) {
    const { fit, withoutEnlargement } = resolveFit(options.fit);
    transformer.resize(width ?? null, height ?? null, {
      fit,
      withoutEnlargement,
      position: resolveGravity(options.gravity),
      background: options.background ?? (options.fit === "pad" ? "#ffffff" : void 0)
    });
  }
}
async function cfImageLocalFetcher(request4) {
  let sharp;
  try {
    const { default: importedSharp } = await import("sharp");
    sharp = importedSharp;
  } catch {
    return cfImageError(
      "The Sharp library is not available, check your version of Node is compatible"
    );
  }
  let body;
  let options;
  try {
    const data = await request4.formData();
    body = data.get("image");
    const optionsJson = data.get("options");
    options = typeof optionsJson === "string" ? JSON.parse(optionsJson) : {};
  } catch {
    return cfImageError("Could not parse cf.image transform request");
  }
  if (!body || !(body instanceof import_node_buffer6.File)) {
    return cfImageError("Expected an image in the cf.image transform request");
  }
  const source = await body.arrayBuffer();
  try {
    const metadata = await sharp(source).metadata();
    if (metadata.format === "svg") {
      return cfImageError("SVG inputs are not transformed in local mode");
    }
    if (options.format === "json") {
      const jsonTransformer = sharp(source);
      applyCfImageTransforms(jsonTransformer, options);
      const { info } = await jsonTransformer.toBuffer({
        resolveWithObject: true
      });
      return Response3.json({
        width: info.width,
        height: info.height,
        original: {
          file_size: metadata.size ?? source.byteLength,
          width: metadata.width,
          height: metadata.height,
          format: formatToMime(metadata.format) ?? "application/octet-stream"
        }
      });
    }
    const transformer = sharp(source);
    applyCfImageTransforms(transformer, options);
    const quality = resolveQuality(options.quality);
    let contentType;
    switch (options.format) {
      case "avif":
        transformer.avif(quality !== void 0 ? { quality } : {});
        contentType = "image/avif";
        break;
      case "webp":
        transformer.webp(quality !== void 0 ? { quality } : {});
        contentType = "image/webp";
        break;
      case "jpeg":
      case "baseline-jpeg":
        transformer.jpeg(quality !== void 0 ? { quality } : {});
        contentType = "image/jpeg";
        break;
      case "png":
      case "png-force":
        transformer.png();
        contentType = "image/png";
        break;
      default:
        contentType = formatToMime(metadata.format) ?? "image/jpeg";
        break;
    }
    const output = await transformer.toBuffer();
    return new Response3(output, {
      headers: {
        "content-type": contentType,
        "cf-resized": "internal=ok/m"
      }
    });
  } catch {
    return cfImageError("Sharp failed to transform the image");
  }
}
function cfImageError(message) {
  return new Response3(`cf.image local transform error: ${message}`, {
    status: 422,
    headers: { "content-type": "text/plain" }
  });
}

// src/shared/dev-registry.ts
var import_node_assert20 = __toESM(require("node:assert"));
var import_node_fs19 = require("node:fs");
var import_node_path29 = __toESM(require("node:path"));

// ../../node_modules/.pnpm/chokidar@4.0.1/node_modules/chokidar/esm/index.js
var import_fs46 = require("fs");
var import_promises23 = require("fs/promises");
var import_events = require("events");
var sysPath2 = __toESM(require("path"), 1);

// ../../node_modules/.pnpm/readdirp@4.0.1/node_modules/readdirp/esm/index.js
var import_fs44 = require("fs");
var import_promises21 = require("fs/promises");
var import_stream3 = require("stream");
var import_path44 = require("path");
function defaultOptions() {
  return {
    root: ".",
    fileFilter: (_path) => true,
    directoryFilter: (_path) => true,
    type: FILE_TYPE,
    lstat: false,
    depth: 2147483648,
    alwaysStat: false,
    highWaterMark: 4096
  };
}
var RECURSIVE_ERROR_CODE = "READDIRP_RECURSIVE_ERROR";
var NORMAL_FLOW_ERRORS = /* @__PURE__ */ new Set(["ENOENT", "EPERM", "EACCES", "ELOOP", RECURSIVE_ERROR_CODE]);
var FILE_TYPE = "files";
var DIR_TYPE = "directories";
var FILE_DIR_TYPE = "files_directories";
var EVERYTHING_TYPE = "all";
var ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE];
var DIR_TYPES = /* @__PURE__ */ new Set([DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE]);
var FILE_TYPES = /* @__PURE__ */ new Set([FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE]);
var isNormalFlowError = (error101) => NORMAL_FLOW_ERRORS.has(error101.code);
var wantBigintFsStats = process.platform === "win32";
var emptyFn = (_path) => true;
var normalizeFilter = (filter) => {
  if (filter === void 0)
    return emptyFn;
  if (typeof filter === "function")
    return filter;
  if (typeof filter === "string") {
    const fl = filter.trim();
    return (entry) => entry.basename === fl;
  }
  if (Array.isArray(filter)) {
    const trItems = filter.map((item) => item.trim());
    return (entry) => trItems.some((f) => entry.basename === f);
  }
  return emptyFn;
};
var ReaddirpStream = class extends import_stream3.Readable {
  constructor(options = {}) {
    super({
      objectMode: true,
      autoDestroy: true,
      highWaterMark: options.highWaterMark
    });
    const opts = { ...defaultOptions(), ...options };
    const { root, type } = opts;
    this._fileFilter = normalizeFilter(opts.fileFilter);
    this._directoryFilter = normalizeFilter(opts.directoryFilter);
    const statMethod = opts.lstat ? import_fs44.lstatSync : import_fs44.statSync;
    if (wantBigintFsStats) {
      this._stat = (path73) => statMethod(path73, { bigint: true });
    } else {
      this._stat = statMethod;
    }
    this._maxDepth = opts.depth;
    this._wantsDir = DIR_TYPES.has(type);
    this._wantsFile = FILE_TYPES.has(type);
    this._wantsEverything = type === EVERYTHING_TYPE;
    this._root = (0, import_path44.resolve)(root);
    this._isDirent = !opts.alwaysStat;
    this._statsProp = this._isDirent ? "dirent" : "stats";
    this._rdOptions = { encoding: "utf8", withFileTypes: this._isDirent };
    this.parents = [this._exploreDir(root, 1)];
    this.reading = false;
    this.parent = void 0;
  }
  async _read(batch) {
    if (this.reading)
      return;
    this.reading = true;
    try {
      while (!this.destroyed && batch > 0) {
        const par = this.parent;
        const fil = par && par.files;
        if (fil && fil.length > 0) {
          const { path: path73, depth } = par;
          const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path73));
          for (const entry of slice) {
            if (!entry) {
              batch--;
              return;
            }
            if (this.destroyed)
              return;
            const entryType = await this._getEntryType(entry);
            if (entryType === "directory" && this._directoryFilter(entry)) {
              if (depth <= this._maxDepth) {
                this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
              }
              if (this._wantsDir) {
                this.push(entry);
                batch--;
              }
            } else if ((entryType === "file" || this._includeAsFile(entry)) && this._fileFilter(entry)) {
              if (this._wantsFile) {
                this.push(entry);
                batch--;
              }
            }
          }
        } else {
          const parent = this.parents.pop();
          if (!parent) {
            this.push(null);
            break;
          }
          this.parent = await parent;
          if (this.destroyed)
            return;
        }
      }
    } catch (error101) {
      this.destroy(error101);
    } finally {
      this.reading = false;
    }
  }
  async _exploreDir(path73, depth) {
    let files;
    try {
      files = await (0, import_promises21.readdir)(path73, this._rdOptions);
    } catch (error101) {
      this._onError(error101);
    }
    return { files, depth, path: path73 };
  }
  _formatEntry(dirent, path73) {
    let entry;
    const basename4 = this._isDirent ? dirent.name : dirent;
    try {
      const fullPath = (0, import_path44.resolve)((0, import_path44.join)(path73, basename4));
      entry = { path: (0, import_path44.relative)(this._root, fullPath), fullPath, basename: basename4 };
      entry[this._statsProp] = this._isDirent ? dirent : this._stat(fullPath);
    } catch (err) {
      this._onError(err);
      return;
    }
    return entry;
  }
  _onError(err) {
    if (isNormalFlowError(err) && !this.destroyed) {
      this.emit("warn", err);
    } else {
      this.destroy(err);
    }
  }
  async _getEntryType(entry) {
    if (!entry && this._statsProp in entry) {
      return "";
    }
    const stats = entry[this._statsProp];
    if (stats.isFile())
      return "file";
    if (stats.isDirectory())
      return "directory";
    if (stats && stats.isSymbolicLink()) {
      const full = entry.fullPath;
      try {
        const entryRealPath = await (0, import_promises21.realpath)(full);
        const entryRealPathStats = (0, import_fs44.lstatSync)(entryRealPath);
        if (entryRealPathStats.isFile()) {
          return "file";
        }
        if (entryRealPathStats.isDirectory()) {
          const len = entryRealPath.length;
          if (full.startsWith(entryRealPath) && full.substr(len, 1) === import_path44.sep) {
            const recursiveError = new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);
            recursiveError.code = RECURSIVE_ERROR_CODE;
            return this._onError(recursiveError);
          }
          return "directory";
        }
      } catch (error101) {
        this._onError(error101);
        return "";
      }
    }
  }
  _includeAsFile(entry) {
    const stats = entry && entry[this._statsProp];
    return stats && this._wantsEverything && !stats.isDirectory();
  }
};
var readdirp = (root, options = {}) => {
  let type = options.entryType || options.type;
  if (type === "both")
    type = FILE_DIR_TYPE;
  if (type)
    options.type = type;
  if (!root) {
    throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");
  } else if (typeof root !== "string") {
    throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");
  } else if (type && !ALL_TYPES.includes(type)) {
    throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`);
  }
  options.root = root;
  return new ReaddirpStream(options);
};

// ../../node_modules/.pnpm/chokidar@4.0.1/node_modules/chokidar/esm/handler.js
var import_fs45 = require("fs");
var import_promises22 = require("fs/promises");
var sysPath = __toESM(require("path"), 1);
var import_os = require("os");
var STR_DATA = "data";
var STR_END = "end";
var STR_CLOSE = "close";
var EMPTY_FN = () => {
};
var pl = process.platform;
var isWindows2 = pl === "win32";
var isMacos = pl === "darwin";
var isLinux = pl === "linux";
var isIBMi = (0, import_os.type)() === "OS400";
var EVENTS = {
  ALL: "all",
  READY: "ready",
  ADD: "add",
  CHANGE: "change",
  ADD_DIR: "addDir",
  UNLINK: "unlink",
  UNLINK_DIR: "unlinkDir",
  RAW: "raw",
  ERROR: "error"
};
var EV = EVENTS;
var THROTTLE_MODE_WATCH = "watch";
var statMethods = { lstat: import_promises22.lstat, stat: import_promises22.stat };
var KEY_LISTENERS = "listeners";
var KEY_ERR = "errHandlers";
var KEY_RAW = "rawEmitters";
var HANDLER_KEYS = [KEY_LISTENERS, KEY_ERR, KEY_RAW];
var binaryExtensions = /* @__PURE__ */ new Set([
  "3dm",
  "3ds",
  "3g2",
  "3gp",
  "7z",
  "a",
  "aac",
  "adp",
  "afdesign",
  "afphoto",
  "afpub",
  "ai",
  "aif",
  "aiff",
  "alz",
  "ape",
  "apk",
  "appimage",
  "ar",
  "arj",
  "asf",
  "au",
  "avi",
  "bak",
  "baml",
  "bh",
  "bin",
  "bk",
  "bmp",
  "btif",
  "bz2",
  "bzip2",
  "cab",
  "caf",
  "cgm",
  "class",
  "cmx",
  "cpio",
  "cr2",
  "cur",
  "dat",
  "dcm",
  "deb",
  "dex",
  "djvu",
  "dll",
  "dmg",
  "dng",
  "doc",
  "docm",
  "docx",
  "dot",
  "dotm",
  "dra",
  "DS_Store",
  "dsk",
  "dts",
  "dtshd",
  "dvb",
  "dwg",
  "dxf",
  "ecelp4800",
  "ecelp7470",
  "ecelp9600",
  "egg",
  "eol",
  "eot",
  "epub",
  "exe",
  "f4v",
  "fbs",
  "fh",
  "fla",
  "flac",
  "flatpak",
  "fli",
  "flv",
  "fpx",
  "fst",
  "fvt",
  "g3",
  "gh",
  "gif",
  "graffle",
  "gz",
  "gzip",
  "h261",
  "h263",
  "h264",
  "icns",
  "ico",
  "ief",
  "img",
  "ipa",
  "iso",
  "jar",
  "jpeg",
  "jpg",
  "jpgv",
  "jpm",
  "jxr",
  "key",
  "ktx",
  "lha",
  "lib",
  "lvp",
  "lz",
  "lzh",
  "lzma",
  "lzo",
  "m3u",
  "m4a",
  "m4v",
  "mar",
  "mdi",
  "mht",
  "mid",
  "midi",
  "mj2",
  "mka",
  "mkv",
  "mmr",
  "mng",
  "mobi",
  "mov",
  "movie",
  "mp3",
  "mp4",
  "mp4a",
  "mpeg",
  "mpg",
  "mpga",
  "mxu",
  "nef",
  "npx",
  "numbers",
  "nupkg",
  "o",
  "odp",
  "ods",
  "odt",
  "oga",
  "ogg",
  "ogv",
  "otf",
  "ott",
  "pages",
  "pbm",
  "pcx",
  "pdb",
  "pdf",
  "pea",
  "pgm",
  "pic",
  "png",
  "pnm",
  "pot",
  "potm",
  "potx",
  "ppa",
  "ppam",
  "ppm",
  "pps",
  "ppsm",
  "ppsx",
  "ppt",
  "pptm",
  "pptx",
  "psd",
  "pya",
  "pyc",
  "pyo",
  "pyv",
  "qt",
  "rar",
  "ras",
  "raw",
  "resources",
  "rgb",
  "rip",
  "rlc",
  "rmf",
  "rmvb",
  "rpm",
  "rtf",
  "rz",
  "s3m",
  "s7z",
  "scpt",
  "sgi",
  "shar",
  "snap",
  "sil",
  "sketch",
  "slk",
  "smv",
  "snk",
  "so",
  "stl",
  "suo",
  "sub",
  "swf",
  "tar",
  "tbz",
  "tbz2",
  "tga",
  "tgz",
  "thmx",
  "tif",
  "tiff",
  "tlz",
  "ttc",
  "ttf",
  "txz",
  "udf",
  "uvh",
  "uvi",
  "uvm",
  "uvp",
  "uvs",
  "uvu",
  "viv",
  "vob",
  "war",
  "wav",
  "wax",
  "wbmp",
  "wdp",
  "weba",
  "webm",
  "webp",
  "whl",
  "wim",
  "wm",
  "wma",
  "wmv",
  "wmx",
  "woff",
  "woff2",
  "wrm",
  "wvx",
  "xbm",
  "xif",
  "xla",
  "xlam",
  "xls",
  "xlsb",
  "xlsm",
  "xlsx",
  "xlt",
  "xltm",
  "xltx",
  "xm",
  "xmind",
  "xpi",
  "xpm",
  "xwd",
  "xz",
  "z",
  "zip",
  "zipx"
]);
var isBinaryPath = (filePath) => binaryExtensions.has(sysPath.extname(filePath).slice(1).toLowerCase());
var foreach = (val, fn) => {
  if (val instanceof Set) {
    val.forEach(fn);
  } else {
    fn(val);
  }
};
var addAndConvert = (main, prop, item) => {
  let container = main[prop];
  if (!(container instanceof Set)) {
    main[prop] = container = /* @__PURE__ */ new Set([container]);
  }
  container.add(item);
};
var clearItem = (cont) => (key) => {
  const set3 = cont[key];
  if (set3 instanceof Set) {
    set3.clear();
  } else {
    delete cont[key];
  }
};
var delFromSet = (main, prop, item) => {
  const container = main[prop];
  if (container instanceof Set) {
    container.delete(item);
  } else if (container === item) {
    delete main[prop];
  }
};
var isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
var FsWatchInstances = /* @__PURE__ */ new Map();
function createFsWatchInstance(path73, options, listener, errHandler, emitRaw) {
  const handleEvent = (rawEvent, evPath) => {
    listener(path73);
    emitRaw(rawEvent, evPath, { watchedPath: path73 });
    if (evPath && path73 !== evPath) {
      fsWatchBroadcast(sysPath.resolve(path73, evPath), KEY_LISTENERS, sysPath.join(path73, evPath));
    }
  };
  try {
    return (0, import_fs45.watch)(path73, {
      persistent: options.persistent
    }, handleEvent);
  } catch (error101) {
    errHandler(error101);
    return void 0;
  }
}
var fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => {
  const cont = FsWatchInstances.get(fullPath);
  if (!cont)
    return;
  foreach(cont[listenerType], (listener) => {
    listener(val1, val2, val3);
  });
};
var setFsWatchListener = (path73, fullPath, options, handlers) => {
  const { listener, errHandler, rawEmitter } = handlers;
  let cont = FsWatchInstances.get(fullPath);
  let watcher;
  if (!options.persistent) {
    watcher = createFsWatchInstance(path73, options, listener, errHandler, rawEmitter);
    if (!watcher)
      return;
    return watcher.close.bind(watcher);
  }
  if (cont) {
    addAndConvert(cont, KEY_LISTENERS, listener);
    addAndConvert(cont, KEY_ERR, errHandler);
    addAndConvert(cont, KEY_RAW, rawEmitter);
  } else {
    watcher = createFsWatchInstance(
      path73,
      options,
      fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
      errHandler,
      // no need to use broadcast here
      fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
    );
    if (!watcher)
      return;
    watcher.on(EV.ERROR, async (error101) => {
      const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
      if (cont)
        cont.watcherUnusable = true;
      if (isWindows2 && error101.code === "EPERM") {
        try {
          const fd = await (0, import_promises22.open)(path73, "r");
          await fd.close();
          broadcastErr(error101);
        } catch (err) {
        }
      } else {
        broadcastErr(error101);
      }
    });
    cont = {
      listeners: listener,
      errHandlers: errHandler,
      rawEmitters: rawEmitter,
      watcher
    };
    FsWatchInstances.set(fullPath, cont);
  }
  return () => {
    delFromSet(cont, KEY_LISTENERS, listener);
    delFromSet(cont, KEY_ERR, errHandler);
    delFromSet(cont, KEY_RAW, rawEmitter);
    if (isEmptySet(cont.listeners)) {
      cont.watcher.close();
      FsWatchInstances.delete(fullPath);
      HANDLER_KEYS.forEach(clearItem(cont));
      cont.watcher = void 0;
      Object.freeze(cont);
    }
  };
};
var FsWatchFileInstances = /* @__PURE__ */ new Map();
var setFsWatchFileListener = (path73, fullPath, options, handlers) => {
  const { listener, rawEmitter } = handlers;
  let cont = FsWatchFileInstances.get(fullPath);
  const copts = cont && cont.options;
  if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
    (0, import_fs45.unwatchFile)(fullPath);
    cont = void 0;
  }
  if (cont) {
    addAndConvert(cont, KEY_LISTENERS, listener);
    addAndConvert(cont, KEY_RAW, rawEmitter);
  } else {
    cont = {
      listeners: listener,
      rawEmitters: rawEmitter,
      options,
      watcher: (0, import_fs45.watchFile)(fullPath, options, (curr, prev) => {
        foreach(cont.rawEmitters, (rawEmitter2) => {
          rawEmitter2(EV.CHANGE, fullPath, { curr, prev });
        });
        const currmtime = curr.mtimeMs;
        if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
          foreach(cont.listeners, (listener2) => listener2(path73, curr));
        }
      })
    };
    FsWatchFileInstances.set(fullPath, cont);
  }
  return () => {
    delFromSet(cont, KEY_LISTENERS, listener);
    delFromSet(cont, KEY_RAW, rawEmitter);
    if (isEmptySet(cont.listeners)) {
      FsWatchFileInstances.delete(fullPath);
      (0, import_fs45.unwatchFile)(fullPath);
      cont.options = cont.watcher = void 0;
      Object.freeze(cont);
    }
  };
};
var NodeFsHandler = class {
  constructor(fsW) {
    this.fsw = fsW;
    this._boundHandleError = (error101) => fsW._handleError(error101);
  }
  /**
   * Watch file for changes with fs_watchFile or fs_watch.
   * @param path to file or dir
   * @param listener on fs change
   * @returns closer for the watcher instance
   */
  _watchWithNodeFs(path73, listener) {
    const opts = this.fsw.options;
    const directory = sysPath.dirname(path73);
    const basename4 = sysPath.basename(path73);
    const parent = this.fsw._getWatchedDir(directory);
    parent.add(basename4);
    const absolutePath = sysPath.resolve(path73);
    const options = {
      persistent: opts.persistent
    };
    if (!listener)
      listener = EMPTY_FN;
    let closer;
    if (opts.usePolling) {
      const enableBin = opts.interval !== opts.binaryInterval;
      options.interval = enableBin && isBinaryPath(basename4) ? opts.binaryInterval : opts.interval;
      closer = setFsWatchFileListener(path73, absolutePath, options, {
        listener,
        rawEmitter: this.fsw._emitRaw
      });
    } else {
      closer = setFsWatchListener(path73, absolutePath, options, {
        listener,
        errHandler: this._boundHandleError,
        rawEmitter: this.fsw._emitRaw
      });
    }
    return closer;
  }
  /**
   * Watch a file and emit add event if warranted.
   * @returns closer for the watcher instance
   */
  _handleFile(file5, stats, initialAdd) {
    if (this.fsw.closed) {
      return;
    }
    const dirname7 = sysPath.dirname(file5);
    const basename4 = sysPath.basename(file5);
    const parent = this.fsw._getWatchedDir(dirname7);
    let prevStats = stats;
    if (parent.has(basename4))
      return;
    const listener = async (path73, newStats) => {
      if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file5, 5))
        return;
      if (!newStats || newStats.mtimeMs === 0) {
        try {
          const newStats2 = await (0, import_promises22.stat)(file5);
          if (this.fsw.closed)
            return;
          const at2 = newStats2.atimeMs;
          const mt = newStats2.mtimeMs;
          if (!at2 || at2 <= mt || mt !== prevStats.mtimeMs) {
            this.fsw._emit(EV.CHANGE, file5, newStats2);
          }
          if ((isMacos || isLinux) && prevStats.ino !== newStats2.ino) {
            this.fsw._closeFile(path73);
            prevStats = newStats2;
            const closer2 = this._watchWithNodeFs(file5, listener);
            if (closer2)
              this.fsw._addPathCloser(path73, closer2);
          } else {
            prevStats = newStats2;
          }
        } catch (error101) {
          this.fsw._remove(dirname7, basename4);
        }
      } else if (parent.has(basename4)) {
        const at2 = newStats.atimeMs;
        const mt = newStats.mtimeMs;
        if (!at2 || at2 <= mt || mt !== prevStats.mtimeMs) {
          this.fsw._emit(EV.CHANGE, file5, newStats);
        }
        prevStats = newStats;
      }
    };
    const closer = this._watchWithNodeFs(file5, listener);
    if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file5)) {
      if (!this.fsw._throttle(EV.ADD, file5, 0))
        return;
      this.fsw._emit(EV.ADD, file5, stats);
    }
    return closer;
  }
  /**
   * Handle symlinks encountered while reading a dir.
   * @param entry returned by readdirp
   * @param directory path of dir being read
   * @param path of this item
   * @param item basename of this item
   * @returns true if no more processing is needed for this entry.
   */
  async _handleSymlink(entry, directory, path73, item) {
    if (this.fsw.closed) {
      return;
    }
    const full = entry.fullPath;
    const dir3 = this.fsw._getWatchedDir(directory);
    if (!this.fsw.options.followSymlinks) {
      this.fsw._incrReadyCount();
      let linkPath;
      try {
        linkPath = await (0, import_promises22.realpath)(path73);
      } catch (e) {
        this.fsw._emitReady();
        return true;
      }
      if (this.fsw.closed)
        return;
      if (dir3.has(item)) {
        if (this.fsw._symlinkPaths.get(full) !== linkPath) {
          this.fsw._symlinkPaths.set(full, linkPath);
          this.fsw._emit(EV.CHANGE, path73, entry.stats);
        }
      } else {
        dir3.add(item);
        this.fsw._symlinkPaths.set(full, linkPath);
        this.fsw._emit(EV.ADD, path73, entry.stats);
      }
      this.fsw._emitReady();
      return true;
    }
    if (this.fsw._symlinkPaths.has(full)) {
      return true;
    }
    this.fsw._symlinkPaths.set(full, true);
  }
  _handleRead(directory, initialAdd, wh, target, dir3, depth, throttler) {
    directory = sysPath.join(directory, "");
    throttler = this.fsw._throttle("readdir", directory, 1e3);
    if (!throttler)
      return;
    const previous = this.fsw._getWatchedDir(wh.path);
    const current = /* @__PURE__ */ new Set();
    let stream = this.fsw._readdirp(directory, {
      fileFilter: (entry) => wh.filterPath(entry),
      directoryFilter: (entry) => wh.filterDir(entry)
    });
    if (!stream)
      return;
    stream.on(STR_DATA, async (entry) => {
      if (this.fsw.closed) {
        stream = void 0;
        return;
      }
      const item = entry.path;
      let path73 = sysPath.join(directory, item);
      current.add(item);
      if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path73, item)) {
        return;
      }
      if (this.fsw.closed) {
        stream = void 0;
        return;
      }
      if (item === target || !target && !previous.has(item)) {
        this.fsw._incrReadyCount();
        path73 = sysPath.join(dir3, sysPath.relative(dir3, path73));
        this._addToNodeFs(path73, initialAdd, wh, depth + 1);
      }
    }).on(EV.ERROR, this._boundHandleError);
    return new Promise((resolve8, reject) => {
      if (!stream)
        return reject();
      stream.once(STR_END, () => {
        if (this.fsw.closed) {
          stream = void 0;
          return;
        }
        const wasThrottled = throttler ? throttler.clear() : false;
        resolve8(void 0);
        previous.getChildren().filter((item) => {
          return item !== directory && !current.has(item);
        }).forEach((item) => {
          this.fsw._remove(directory, item);
        });
        stream = void 0;
        if (wasThrottled)
          this._handleRead(directory, false, wh, target, dir3, depth, throttler);
      });
    });
  }
  /**
   * Read directory to add / remove files from `@watched` list and re-read it on change.
   * @param dir fs path
   * @param stats
   * @param initialAdd
   * @param depth relative to user-supplied path
   * @param target child path targeted for watch
   * @param wh Common watch helpers for this path
   * @param realpath
   * @returns closer for the watcher instance.
   */
  async _handleDir(dir3, stats, initialAdd, depth, target, wh, realpath2) {
    const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir3));
    const tracked = parentDir.has(sysPath.basename(dir3));
    if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
      this.fsw._emit(EV.ADD_DIR, dir3, stats);
    }
    parentDir.add(sysPath.basename(dir3));
    this.fsw._getWatchedDir(dir3);
    let throttler;
    let closer;
    const oDepth = this.fsw.options.depth;
    if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath2)) {
      if (!target) {
        await this._handleRead(dir3, initialAdd, wh, target, dir3, depth, throttler);
        if (this.fsw.closed)
          return;
      }
      closer = this._watchWithNodeFs(dir3, (dirPath, stats2) => {
        if (stats2 && stats2.mtimeMs === 0)
          return;
        this._handleRead(dirPath, false, wh, target, dir3, depth, throttler);
      });
    }
    return closer;
  }
  /**
   * Handle added file, directory, or glob pattern.
   * Delegates call to _handleFile / _handleDir after checks.
   * @param path to file or ir
   * @param initialAdd was the file added at watch instantiation?
   * @param priorWh depth relative to user-supplied path
   * @param depth Child path actually targeted for watch
   * @param target Child path actually targeted for watch
   */
  async _addToNodeFs(path73, initialAdd, priorWh, depth, target) {
    const ready = this.fsw._emitReady;
    if (this.fsw._isIgnored(path73) || this.fsw.closed) {
      ready();
      return false;
    }
    const wh = this.fsw._getWatchHelpers(path73);
    if (priorWh) {
      wh.filterPath = (entry) => priorWh.filterPath(entry);
      wh.filterDir = (entry) => priorWh.filterDir(entry);
    }
    try {
      const stats = await statMethods[wh.statMethod](wh.watchPath);
      if (this.fsw.closed)
        return;
      if (this.fsw._isIgnored(wh.watchPath, stats)) {
        ready();
        return false;
      }
      const follow = this.fsw.options.followSymlinks;
      let closer;
      if (stats.isDirectory()) {
        const absPath = sysPath.resolve(path73);
        const targetPath = follow ? await (0, import_promises22.realpath)(path73) : path73;
        if (this.fsw.closed)
          return;
        closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
        if (this.fsw.closed)
          return;
        if (absPath !== targetPath && targetPath !== void 0) {
          this.fsw._symlinkPaths.set(absPath, targetPath);
        }
      } else if (stats.isSymbolicLink()) {
        const targetPath = follow ? await (0, import_promises22.realpath)(path73) : path73;
        if (this.fsw.closed)
          return;
        const parent = sysPath.dirname(wh.watchPath);
        this.fsw._getWatchedDir(parent).add(wh.watchPath);
        this.fsw._emit(EV.ADD, wh.watchPath, stats);
        closer = await this._handleDir(parent, stats, initialAdd, depth, path73, wh, targetPath);
        if (this.fsw.closed)
          return;
        if (targetPath !== void 0) {
          this.fsw._symlinkPaths.set(sysPath.resolve(path73), targetPath);
        }
      } else {
        closer = this._handleFile(wh.watchPath, stats, initialAdd);
      }
      ready();
      if (closer)
        this.fsw._addPathCloser(path73, closer);
      return false;
    } catch (error101) {
      if (this.fsw._handleError(error101)) {
        ready();
        return path73;
      }
    }
  }
};

// ../../node_modules/.pnpm/chokidar@4.0.1/node_modules/chokidar/esm/index.js
var SLASH = "/";
var SLASH_SLASH = "//";
var ONE_DOT = ".";
var TWO_DOTS = "..";
var STRING_TYPE = "string";
var BACK_SLASH_RE = /\\/g;
var DOUBLE_SLASH_RE = /\/\//;
var DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
var REPLACER_RE = /^\.[/\\]/;
function arrify(item) {
  return Array.isArray(item) ? item : [item];
}
var isMatcherObject = (matcher) => typeof matcher === "object" && matcher !== null && !(matcher instanceof RegExp);
function createPattern(matcher) {
  if (typeof matcher === "function")
    return matcher;
  if (typeof matcher === "string")
    return (string7) => matcher === string7;
  if (matcher instanceof RegExp)
    return (string7) => matcher.test(string7);
  if (typeof matcher === "object" && matcher !== null) {
    return (string7) => {
      if (matcher.path === string7)
        return true;
      if (matcher.recursive) {
        const relative5 = sysPath2.relative(matcher.path, string7);
        if (!relative5) {
          return false;
        }
        return !relative5.startsWith("..") && !sysPath2.isAbsolute(relative5);
      }
      return false;
    };
  }
  return () => false;
}
function normalizePath2(path73) {
  if (typeof path73 !== "string")
    throw new Error("string expected");
  path73 = sysPath2.normalize(path73);
  path73 = path73.replace(/\\/g, "/");
  let prepend = false;
  if (path73.startsWith("//"))
    prepend = true;
  const DOUBLE_SLASH_RE2 = /\/\//;
  while (path73.match(DOUBLE_SLASH_RE2))
    path73 = path73.replace(DOUBLE_SLASH_RE2, "/");
  if (prepend)
    path73 = "/" + path73;
  return path73;
}
function matchPatterns(patterns, testString, stats) {
  const path73 = normalizePath2(testString);
  for (let index = 0; index < patterns.length; index++) {
    const pattern = patterns[index];
    if (pattern(path73, stats)) {
      return true;
    }
  }
  return false;
}
function anymatch(matchers, testString) {
  if (matchers == null) {
    throw new TypeError("anymatch: specify first argument");
  }
  const matchersArray = arrify(matchers);
  const patterns = matchersArray.map((matcher) => createPattern(matcher));
  if (testString == null) {
    return (testString2, stats) => {
      return matchPatterns(patterns, testString2, stats);
    };
  }
  return matchPatterns(patterns, testString);
}
var unifyPaths = (paths_) => {
  const paths = arrify(paths_).flat();
  if (!paths.every((p2) => typeof p2 === STRING_TYPE)) {
    throw new TypeError(`Non-string provided as watch path: ${paths}`);
  }
  return paths.map(normalizePathToUnix);
};
var toUnix = (string7) => {
  let str = string7.replace(BACK_SLASH_RE, SLASH);
  let prepend = false;
  if (str.startsWith(SLASH_SLASH)) {
    prepend = true;
  }
  while (str.match(DOUBLE_SLASH_RE)) {
    str = str.replace(DOUBLE_SLASH_RE, SLASH);
  }
  if (prepend) {
    str = SLASH + str;
  }
  return str;
};
var normalizePathToUnix = (path73) => toUnix(sysPath2.normalize(toUnix(path73)));
var normalizeIgnored = (cwd2 = "") => (path73) => {
  if (typeof path73 === "string") {
    return normalizePathToUnix(sysPath2.isAbsolute(path73) ? path73 : sysPath2.join(cwd2, path73));
  } else {
    return path73;
  }
};
var getAbsolutePath = (path73, cwd2) => {
  if (sysPath2.isAbsolute(path73)) {
    return path73;
  }
  return sysPath2.join(cwd2, path73);
};
var EMPTY_SET = Object.freeze(/* @__PURE__ */ new Set());
var DirEntry = class {
  constructor(dir3, removeWatcher) {
    this.path = dir3;
    this._removeWatcher = removeWatcher;
    this.items = /* @__PURE__ */ new Set();
  }
  add(item) {
    const { items } = this;
    if (!items)
      return;
    if (item !== ONE_DOT && item !== TWO_DOTS)
      items.add(item);
  }
  async remove(item) {
    const { items } = this;
    if (!items)
      return;
    items.delete(item);
    if (items.size > 0)
      return;
    const dir3 = this.path;
    try {
      await (0, import_promises23.readdir)(dir3);
    } catch (err) {
      if (this._removeWatcher) {
        this._removeWatcher(sysPath2.dirname(dir3), sysPath2.basename(dir3));
      }
    }
  }
  has(item) {
    const { items } = this;
    if (!items)
      return;
    return items.has(item);
  }
  getChildren() {
    const { items } = this;
    if (!items)
      return [];
    return [...items.values()];
  }
  dispose() {
    this.items.clear();
    this.path = "";
    this._removeWatcher = EMPTY_FN;
    this.items = EMPTY_SET;
    Object.freeze(this);
  }
};
var STAT_METHOD_F = "stat";
var STAT_METHOD_L = "lstat";
var WatchHelper = class {
  constructor(path73, follow, fsw) {
    this.fsw = fsw;
    const watchPath = path73;
    this.path = path73 = path73.replace(REPLACER_RE, "");
    this.watchPath = watchPath;
    this.fullWatchPath = sysPath2.resolve(watchPath);
    this.dirParts = [];
    this.dirParts.forEach((parts) => {
      if (parts.length > 1)
        parts.pop();
    });
    this.followSymlinks = follow;
    this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
  }
  entryPath(entry) {
    return sysPath2.join(this.watchPath, sysPath2.relative(this.watchPath, entry.fullPath));
  }
  filterPath(entry) {
    const { stats } = entry;
    if (stats && stats.isSymbolicLink())
      return this.filterDir(entry);
    const resolvedPath = this.entryPath(entry);
    return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);
  }
  filterDir(entry) {
    return this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
  }
};
var FSWatcher = class extends import_events.EventEmitter {
  // Not indenting methods for history sake; for now.
  constructor(_opts = {}) {
    super();
    this.closed = false;
    this._closers = /* @__PURE__ */ new Map();
    this._ignoredPaths = /* @__PURE__ */ new Set();
    this._throttled = /* @__PURE__ */ new Map();
    this._streams = /* @__PURE__ */ new Set();
    this._symlinkPaths = /* @__PURE__ */ new Map();
    this._watched = /* @__PURE__ */ new Map();
    this._pendingWrites = /* @__PURE__ */ new Map();
    this._pendingUnlinks = /* @__PURE__ */ new Map();
    this._readyCount = 0;
    this._readyEmitted = false;
    const awf = _opts.awaitWriteFinish;
    const DEF_AWF = { stabilityThreshold: 2e3, pollInterval: 100 };
    const opts = {
      // Defaults
      persistent: true,
      ignoreInitial: false,
      ignorePermissionErrors: false,
      interval: 100,
      binaryInterval: 300,
      followSymlinks: true,
      usePolling: false,
      // useAsync: false,
      atomic: true,
      // NOTE: overwritten later (depends on usePolling)
      ..._opts,
      // Change format
      ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]),
      awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === "object" ? { ...DEF_AWF, ...awf } : false
    };
    if (isIBMi)
      opts.usePolling = true;
    if (opts.atomic === void 0)
      opts.atomic = !opts.usePolling;
    const envPoll = process.env.CHOKIDAR_USEPOLLING;
    if (envPoll !== void 0) {
      const envLower = envPoll.toLowerCase();
      if (envLower === "false" || envLower === "0")
        opts.usePolling = false;
      else if (envLower === "true" || envLower === "1")
        opts.usePolling = true;
      else
        opts.usePolling = !!envLower;
    }
    const envInterval = process.env.CHOKIDAR_INTERVAL;
    if (envInterval)
      opts.interval = Number.parseInt(envInterval, 10);
    let readyCalls = 0;
    this._emitReady = () => {
      readyCalls++;
      if (readyCalls >= this._readyCount) {
        this._emitReady = EMPTY_FN;
        this._readyEmitted = true;
        process.nextTick(() => this.emit(EVENTS.READY));
      }
    };
    this._emitRaw = (...args) => this.emit(EVENTS.RAW, ...args);
    this._boundRemove = this._remove.bind(this);
    this.options = opts;
    this._nodeFsHandler = new NodeFsHandler(this);
    Object.freeze(opts);
  }
  _addIgnoredPath(matcher) {
    if (isMatcherObject(matcher)) {
      for (const ignored2 of this._ignoredPaths) {
        if (isMatcherObject(ignored2) && ignored2.path === matcher.path && ignored2.recursive === matcher.recursive) {
          return;
        }
      }
    }
    this._ignoredPaths.add(matcher);
  }
  _removeIgnoredPath(matcher) {
    this._ignoredPaths.delete(matcher);
    if (typeof matcher === "string") {
      for (const ignored2 of this._ignoredPaths) {
        if (isMatcherObject(ignored2) && ignored2.path === matcher) {
          this._ignoredPaths.delete(ignored2);
        }
      }
    }
  }
  // Public methods
  /**
   * Adds paths to be watched on an existing FSWatcher instance.
   * @param paths_ file or file list. Other arguments are unused
   */
  add(paths_, _origAdd, _internal) {
    const { cwd: cwd2 } = this.options;
    this.closed = false;
    this._closePromise = void 0;
    let paths = unifyPaths(paths_);
    if (cwd2) {
      paths = paths.map((path73) => {
        const absPath = getAbsolutePath(path73, cwd2);
        return absPath;
      });
    }
    paths.forEach((path73) => {
      this._removeIgnoredPath(path73);
    });
    this._userIgnored = void 0;
    if (!this._readyCount)
      this._readyCount = 0;
    this._readyCount += paths.length;
    Promise.all(paths.map(async (path73) => {
      const res = await this._nodeFsHandler._addToNodeFs(path73, !_internal, void 0, 0, _origAdd);
      if (res)
        this._emitReady();
      return res;
    })).then((results) => {
      if (this.closed)
        return;
      results.forEach((item) => {
        if (item)
          this.add(sysPath2.dirname(item), sysPath2.basename(_origAdd || item));
      });
    });
    return this;
  }
  /**
   * Close watchers or start ignoring events from specified paths.
   */
  unwatch(paths_) {
    if (this.closed)
      return this;
    const paths = unifyPaths(paths_);
    const { cwd: cwd2 } = this.options;
    paths.forEach((path73) => {
      if (!sysPath2.isAbsolute(path73) && !this._closers.has(path73)) {
        if (cwd2)
          path73 = sysPath2.join(cwd2, path73);
        path73 = sysPath2.resolve(path73);
      }
      this._closePath(path73);
      this._addIgnoredPath(path73);
      if (this._watched.has(path73)) {
        this._addIgnoredPath({
          path: path73,
          recursive: true
        });
      }
      this._userIgnored = void 0;
    });
    return this;
  }
  /**
   * Close watchers and remove all listeners from watched paths.
   */
  close() {
    if (this._closePromise) {
      return this._closePromise;
    }
    this.closed = true;
    this.removeAllListeners();
    const closers = [];
    this._closers.forEach((closerList) => closerList.forEach((closer) => {
      const promise3 = closer();
      if (promise3 instanceof Promise)
        closers.push(promise3);
    }));
    this._streams.forEach((stream) => stream.destroy());
    this._userIgnored = void 0;
    this._readyCount = 0;
    this._readyEmitted = false;
    this._watched.forEach((dirent) => dirent.dispose());
    this._closers.clear();
    this._watched.clear();
    this._streams.clear();
    this._symlinkPaths.clear();
    this._throttled.clear();
    this._closePromise = closers.length ? Promise.all(closers).then(() => void 0) : Promise.resolve();
    return this._closePromise;
  }
  /**
   * Expose list of watched paths
   * @returns for chaining
   */
  getWatched() {
    const watchList = {};
    this._watched.forEach((entry, dir3) => {
      const key = this.options.cwd ? sysPath2.relative(this.options.cwd, dir3) : dir3;
      const index = key || ONE_DOT;
      watchList[index] = entry.getChildren().sort();
    });
    return watchList;
  }
  emitWithAll(event, args) {
    this.emit(...args);
    if (event !== EVENTS.ERROR)
      this.emit(EVENTS.ALL, ...args);
  }
  // Common helpers
  // --------------
  /**
   * Normalize and emit events.
   * Calling _emit DOES NOT MEAN emit() would be called!
   * @param event Type of event
   * @param path File or directory path
   * @param stats arguments to be passed with event
   * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
   */
  async _emit(event, path73, stats) {
    if (this.closed)
      return;
    const opts = this.options;
    if (isWindows2)
      path73 = sysPath2.normalize(path73);
    if (opts.cwd)
      path73 = sysPath2.relative(opts.cwd, path73);
    const args = [event, path73];
    if (stats != null)
      args.push(stats);
    const awf = opts.awaitWriteFinish;
    let pw;
    if (awf && (pw = this._pendingWrites.get(path73))) {
      pw.lastChange = /* @__PURE__ */ new Date();
      return this;
    }
    if (opts.atomic) {
      if (event === EVENTS.UNLINK) {
        this._pendingUnlinks.set(path73, args);
        setTimeout(() => {
          this._pendingUnlinks.forEach((entry, path74) => {
            this.emit(...entry);
            this.emit(EVENTS.ALL, ...entry);
            this._pendingUnlinks.delete(path74);
          });
        }, typeof opts.atomic === "number" ? opts.atomic : 100);
        return this;
      }
      if (event === EVENTS.ADD && this._pendingUnlinks.has(path73)) {
        event = args[0] = EVENTS.CHANGE;
        this._pendingUnlinks.delete(path73);
      }
    }
    if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) {
      const awfEmit = (err, stats2) => {
        if (err) {
          event = args[0] = EVENTS.ERROR;
          args[1] = err;
          this.emitWithAll(event, args);
        } else if (stats2) {
          if (args.length > 2) {
            args[2] = stats2;
          } else {
            args.push(stats2);
          }
          this.emitWithAll(event, args);
        }
      };
      this._awaitWriteFinish(path73, awf.stabilityThreshold, event, awfEmit);
      return this;
    }
    if (event === EVENTS.CHANGE) {
      const isThrottled = !this._throttle(EVENTS.CHANGE, path73, 50);
      if (isThrottled)
        return this;
    }
    if (opts.alwaysStat && stats === void 0 && (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) {
      const fullPath = opts.cwd ? sysPath2.join(opts.cwd, path73) : path73;
      let stats2;
      try {
        stats2 = await (0, import_promises23.stat)(fullPath);
      } catch (err) {
      }
      if (!stats2 || this.closed)
        return;
      args.push(stats2);
    }
    this.emitWithAll(event, args);
    return this;
  }
  /**
   * Common handler for errors
   * @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
   */
  _handleError(error101) {
    const code = error101 && error101.code;
    if (error101 && code !== "ENOENT" && code !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code !== "EPERM" && code !== "EACCES")) {
      this.emit(EVENTS.ERROR, error101);
    }
    return error101 || this.closed;
  }
  /**
   * Helper utility for throttling
   * @param actionType type being throttled
   * @param path being acted upon
   * @param timeout duration of time to suppress duplicate actions
   * @returns tracking object or false if action should be suppressed
   */
  _throttle(actionType, path73, timeout) {
    if (!this._throttled.has(actionType)) {
      this._throttled.set(actionType, /* @__PURE__ */ new Map());
    }
    const action = this._throttled.get(actionType);
    if (!action)
      throw new Error("invalid throttle");
    const actionPath = action.get(path73);
    if (actionPath) {
      actionPath.count++;
      return false;
    }
    let timeoutObject;
    const clear = () => {
      const item = action.get(path73);
      const count = item ? item.count : 0;
      action.delete(path73);
      clearTimeout(timeoutObject);
      if (item)
        clearTimeout(item.timeoutObject);
      return count;
    };
    timeoutObject = setTimeout(clear, timeout);
    const thr = { timeoutObject, clear, count: 0 };
    action.set(path73, thr);
    return thr;
  }
  _incrReadyCount() {
    return this._readyCount++;
  }
  /**
   * Awaits write operation to finish.
   * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
   * @param path being acted upon
   * @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
   * @param event
   * @param awfEmit Callback to be called when ready for event to be emitted.
   */
  _awaitWriteFinish(path73, threshold, event, awfEmit) {
    const awf = this.options.awaitWriteFinish;
    if (typeof awf !== "object")
      return;
    const pollInterval = awf.pollInterval;
    let timeoutHandler;
    let fullPath = path73;
    if (this.options.cwd && !sysPath2.isAbsolute(path73)) {
      fullPath = sysPath2.join(this.options.cwd, path73);
    }
    const now = /* @__PURE__ */ new Date();
    const writes = this._pendingWrites;
    function awaitWriteFinishFn(prevStat) {
      (0, import_fs46.stat)(fullPath, (err, curStat) => {
        if (err || !writes.has(path73)) {
          if (err && err.code !== "ENOENT")
            awfEmit(err);
          return;
        }
        const now2 = Number(/* @__PURE__ */ new Date());
        if (prevStat && curStat.size !== prevStat.size) {
          writes.get(path73).lastChange = now2;
        }
        const pw = writes.get(path73);
        const df = now2 - pw.lastChange;
        if (df >= threshold) {
          writes.delete(path73);
          awfEmit(void 0, curStat);
        } else {
          timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
        }
      });
    }
    if (!writes.has(path73)) {
      writes.set(path73, {
        lastChange: now,
        cancelWait: () => {
          writes.delete(path73);
          clearTimeout(timeoutHandler);
          return event;
        }
      });
      timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);
    }
  }
  /**
   * Determines whether user has asked to ignore this path.
   */
  _isIgnored(path73, stats) {
    if (this.options.atomic && DOT_RE.test(path73))
      return true;
    if (!this._userIgnored) {
      const { cwd: cwd2 } = this.options;
      const ign = this.options.ignored;
      const ignored2 = (ign || []).map(normalizeIgnored(cwd2));
      const ignoredPaths = [...this._ignoredPaths];
      const list = [...ignoredPaths.map(normalizeIgnored(cwd2)), ...ignored2];
      this._userIgnored = anymatch(list, void 0);
    }
    return this._userIgnored(path73, stats);
  }
  _isntIgnored(path73, stat4) {
    return !this._isIgnored(path73, stat4);
  }
  /**
   * Provides a set of common helpers and properties relating to symlink handling.
   * @param path file or directory pattern being watched
   */
  _getWatchHelpers(path73) {
    return new WatchHelper(path73, this.options.followSymlinks, this);
  }
  // Directory helpers
  // -----------------
  /**
   * Provides directory tracking objects
   * @param directory path of the directory
   */
  _getWatchedDir(directory) {
    const dir3 = sysPath2.resolve(directory);
    if (!this._watched.has(dir3))
      this._watched.set(dir3, new DirEntry(dir3, this._boundRemove));
    return this._watched.get(dir3);
  }
  // File helpers
  // ------------
  /**
   * Check for read permissions: https://stackoverflow.com/a/11781404/1358405
   */
  _hasReadPermissions(stats) {
    if (this.options.ignorePermissionErrors)
      return true;
    return Boolean(Number(stats.mode) & 256);
  }
  /**
   * Handles emitting unlink events for
   * files and directories, and via recursion, for
   * files and directories within directories that are unlinked
   * @param directory within which the following item is located
   * @param item      base path of item/directory
   */
  _remove(directory, item, isDirectory2) {
    const path73 = sysPath2.join(directory, item);
    const fullPath = sysPath2.resolve(path73);
    isDirectory2 = isDirectory2 != null ? isDirectory2 : this._watched.has(path73) || this._watched.has(fullPath);
    if (!this._throttle("remove", path73, 100))
      return;
    if (!isDirectory2 && this._watched.size === 1) {
      this.add(directory, item, true);
    }
    const wp = this._getWatchedDir(path73);
    const nestedDirectoryChildren = wp.getChildren();
    nestedDirectoryChildren.forEach((nested) => this._remove(path73, nested));
    const parent = this._getWatchedDir(directory);
    const wasTracked = parent.has(item);
    parent.remove(item);
    if (this._symlinkPaths.has(fullPath)) {
      this._symlinkPaths.delete(fullPath);
    }
    let relPath = path73;
    if (this.options.cwd)
      relPath = sysPath2.relative(this.options.cwd, path73);
    if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
      const event = this._pendingWrites.get(relPath).cancelWait();
      if (event === EVENTS.ADD)
        return;
    }
    this._watched.delete(path73);
    this._watched.delete(fullPath);
    const eventName = isDirectory2 ? EVENTS.UNLINK_DIR : EVENTS.UNLINK;
    if (wasTracked && !this._isIgnored(path73))
      this._emit(eventName, path73);
    this._closePath(path73);
  }
  /**
   * Closes all watchers for a path
   */
  _closePath(path73) {
    this._closeFile(path73);
    const dir3 = sysPath2.dirname(path73);
    this._getWatchedDir(dir3).remove(sysPath2.basename(path73));
  }
  /**
   * Closes only file-specific watchers
   */
  _closeFile(path73) {
    const closers = this._closers.get(path73);
    if (!closers)
      return;
    closers.forEach((closer) => closer());
    this._closers.delete(path73);
  }
  _addPathCloser(path73, closer) {
    if (!closer)
      return;
    let list = this._closers.get(path73);
    if (!list) {
      list = [];
      this._closers.set(path73, list);
    }
    list.push(closer);
  }
  _readdirp(root, opts) {
    if (this.closed)
      return;
    const options = { type: EVENTS.ALL, alwaysStat: true, lstat: true, ...opts, depth: 0 };
    let stream = readdirp(root, options);
    this._streams.add(stream);
    stream.once(STR_CLOSE, () => {
      stream = void 0;
    });
    stream.once(STR_END, () => {
      if (stream) {
        this._streams.delete(stream);
        stream = void 0;
      }
    });
    return stream;
  }
};
function watch(paths, options = {}) {
  const watcher = new FSWatcher(options);
  watcher.add(paths);
  return watcher;
}

// src/shared/dev-registry.ts
var DevRegistry = class {
  constructor(registryPath, onUpdate, log2) {
    this.registryPath = registryPath;
    this.onUpdate = onUpdate;
    this.log = log2;
  }
  registryPath;
  onUpdate;
  log;
  heartbeats = /* @__PURE__ */ new Map();
  registeredWorkers = /* @__PURE__ */ new Set();
  watchQueueConsumers = false;
  externalServices = /* @__PURE__ */ new Map();
  watcher;
  /**
   * Watch files inside the registry directory for changes.
   */
  watch(services, watchQueueConsumers = false) {
    if (services.size === 0 && !watchQueueConsumers || !this.registryPath) {
      return;
    }
    this.externalServices = new Map(services);
    this.watchQueueConsumers = watchQueueConsumers;
    (0, import_node_fs19.mkdirSync)(this.registryPath, { recursive: true });
    if (!this.watcher) {
      this.watcher = watch(this.registryPath, {
        // On Windows, chokidar's default `fs.watch` backend
        // (`ReadDirectoryChangesW`) frequently drops or delays create
        // events for files added shortly after the watcher attaches —
        // especially under CI virtualization. Fall back to polling on
        // Windows so cross-process worker registrations are observed
        // reliably. The registry directory is small, so the cost is
        // negligible.
        usePolling: process.platform === "win32",
        interval: 100
      }).on("all", () => {
        this.refresh();
      });
    }
  }
  /**
   * Unregister all managed workers and close the watcher.
   * This is a sync function that returns a promise
   * to ensure all workers are unregistered within the exit hook
   */
  dispose() {
    this.unregisterWorkers();
    return this.watcher?.close().finally(() => {
      this.watcher = void 0;
    });
  }
  /**
   * Withdraw every entry this instance has registered.
   */
  unregisterWorkers() {
    for (const worker of this.registeredWorkers) {
      this.unregister(worker);
    }
    this.registeredWorkers.clear();
  }
  /**
   * Unregister worker in the registry.
   */
  unregister(name) {
    try {
      const existingHeartbeat = this.heartbeats.get(name);
      if (existingHeartbeat) {
        this.heartbeats.delete(name);
        clearInterval(existingHeartbeat);
      }
      if (this.registryPath) {
        (0, import_node_fs19.unlinkSync)(import_node_path29.default.join(this.registryPath, name));
      }
    } catch (e) {
      this.log?.debug(`Failed to unregister worker "${name}": ${e}`);
    }
  }
  isEnabled() {
    return this.registryPath !== void 0 && this.registryPath !== "";
  }
  getRegistry() {
    if (!this.registryPath) {
      return {};
    }
    return getWorkerRegistry(this.registryPath);
  }
  getRegistryPath() {
    return this.registryPath;
  }
  async updateRegistryPath(registryPath, onUpdate) {
    this.onUpdate = onUpdate;
    if (registryPath !== this.registryPath) {
      this.unregisterWorkers();
      await this.watcher?.close();
      this.watcher = void 0;
      this.registryPath = registryPath;
    }
  }
  register(workers) {
    if (!this.registryPath) {
      return;
    }
    (0, import_node_fs19.mkdirSync)(this.registryPath, { recursive: true });
    for (const name of [...this.registeredWorkers]) {
      if (!Object.hasOwn(workers, name)) {
        this.unregister(name);
        this.registeredWorkers.delete(name);
      }
    }
    for (const [name, definition] of Object.entries(workers)) {
      const definitionPath = import_node_path29.default.join(this.registryPath, name);
      const existingHeartbeat = this.heartbeats.get(name);
      if (existingHeartbeat) {
        clearInterval(existingHeartbeat);
      }
      (0, import_node_fs19.writeFileSync)(definitionPath, JSON.stringify(definition, null, 2));
      this.registeredWorkers.add(name);
      this.heartbeats.set(
        name,
        setInterval(() => {
          if ((0, import_node_fs19.existsSync)(definitionPath)) {
            (0, import_node_fs19.utimesSync)(definitionPath, /* @__PURE__ */ new Date(), /* @__PURE__ */ new Date());
          }
        }, 3e4)
      );
    }
    this.refresh();
  }
  previousJSON = "{}";
  refresh() {
    if (!this.onUpdate) {
      return;
    }
    (0, import_node_assert20.default)(this.registryPath);
    const registry3 = getWorkerRegistry(this.registryPath);
    const json3 = JSON.stringify(registry3);
    if (json3 === this.previousJSON) {
      return;
    }
    const previousRegistry = JSON.parse(this.previousJSON);
    this.previousJSON = json3;
    if (this.watchQueueConsumers && getQueueConsumersView(registry3) !== getQueueConsumersView(previousRegistry)) {
      this.onUpdate(registry3);
      return;
    }
    for (const [service] of this.externalServices) {
      if (JSON.stringify(registry3[service]) !== JSON.stringify(previousRegistry[service])) {
        this.onUpdate(registry3);
        break;
      }
    }
  }
};
function getQueueConsumersView(registry3) {
  return JSON.stringify(
    Object.entries(registry3).filter(([, definition]) => definition.queueConsumers !== void 0).map(
      ([workerName, definition]) => [
        workerName,
        definition.debugPortAddress,
        definition.queueConsumers
      ]
    ).sort(
      ([previousWorkerName], [nextWorkerName]) => previousWorkerName.localeCompare(nextWorkerName)
    )
  );
}
function getWorkerRegistry(registryPath) {
  const registry3 = {};
  if (!(0, import_node_fs19.existsSync)(registryPath)) {
    return registry3;
  }
  for (const workerName of (0, import_node_fs19.readdirSync)(registryPath)) {
    try {
      const definitionPath = import_node_path29.default.join(registryPath, workerName);
      const stats = (0, import_node_fs19.statSync)(definitionPath, { throwIfNoEntry: false });
      if (stats === void 0 || stats.mtime.getTime() < Date.now() - 3e5) {
        try {
          (0, import_node_fs19.unlinkSync)(definitionPath);
        } catch {
        }
        continue;
      }
      const file5 = (0, import_node_fs19.readFileSync)(definitionPath, {
        encoding: "utf8",
        flag: "r"
      });
      registry3[workerName] = JSON.parse(file5);
    } catch {
    }
  }
  return registry3;
}
function getDefaultDevRegistryPath() {
  return process.env.MINIFLARE_REGISTRY_PATH ?? import_node_path29.default.join(getGlobalConfigPath(), "registry");
}

// src/shared/external-service.ts
function normaliseServiceDesignator(binding, dev) {
  return {
    serviceName: binding.workerName !== kCurrentWorker ? binding.workerName : void 0,
    entrypoint: binding.exportName,
    props: binding.props,
    remoteProxyConnectionString: getRemoteProxyConnectionString(binding, dev)
  };
}
var unsafeVariableCharRegex = /[^0-9a-zA-Z_\$]/g;
function getOutboundDoProxyClassName(scriptName, className) {
  return `${scriptName.replace(unsafeVariableCharRegex, "_")}_${className}`;
}

// src/shared/mime-types.ts
var compressedByCloudflareFL = /* @__PURE__ */ new Set([
  // list copied from https://developers.cloudflare.com/speed/optimization/content/brotli/content-compression/#:~:text=If%20supported%20by%20visitors%E2%80%99%20web%20browsers%2C%20Cloudflare%20will%20return%20Gzip%20or%20Brotli%2Dencoded%20responses%20for%20the%20following%20content%20types%3A
  "text/html",
  "text/richtext",
  "text/plain",
  "text/css",
  "text/x-script",
  "text/x-component",
  "text/x-java-source",
  "text/x-markdown",
  "application/javascript",
  "application/x-javascript",
  "text/javascript",
  "text/js",
  "image/x-icon",
  "image/vnd.microsoft.icon",
  "application/x-perl",
  "application/x-httpd-cgi",
  "text/xml",
  "application/xml",
  "application/rss+xml",
  "application/vnd.api+json",
  "application/x-protobuf",
  "application/json",
  "multipart/bag",
  "multipart/mixed",
  "application/xhtml+xml",
  "font/ttf",
  "font/otf",
  "font/x-woff",
  "image/svg+xml",
  "application/vnd.ms-fontobject",
  "application/ttf",
  "application/x-ttf",
  "application/otf",
  "application/x-otf",
  "application/truetype",
  "application/opentype",
  "application/x-opentype",
  "application/font-woff",
  "application/eot",
  "application/font",
  "application/font-sfnt",
  "application/wasm",
  "application/javascript-binast",
  "application/manifest+json",
  "application/ld+json",
  "application/graphql+json",
  "application/geo+json"
]);
function isCompressedByCloudflareFL(contentTypeHeader) {
  if (!contentTypeHeader) return true;
  const [contentType] = contentTypeHeader.split(";");
  return compressedByCloudflareFL.has(contentType);
}

// src/workers/secrets-store/constants.ts
var ADMIN_API = "SecretsStoreSecret::admin_api";

// src/merge.ts
var objectProtoNames = Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
function isPlainObject3(value) {
  const proto2 = Object.getPrototypeOf(value);
  return proto2 === Object.prototype || proto2 === null || Object.getOwnPropertyNames(proto2).sort().join("\0") === objectProtoNames;
}
function convertWorkerOptionsArrayToObject(key, array3) {
  const _ = array3;
  if (key === "queueConsumers") {
    const object3 = Object.fromEntries(
      array3.map((item) => [item, {}])
    );
    return object3;
  } else {
    const object3 = Object.fromEntries(array3.map((item) => [item, item]));
    return object3;
  }
}
function mergeWorkerOptions(a, b) {
  const aRecord = a;
  for (const [key, bValue] of Object.entries(b)) {
    const aValue = aRecord[key];
    if (aValue === void 0) {
      aRecord[key] = bValue;
      continue;
    }
    const aIsArray = Array.isArray(aValue);
    const bIsArray = Array.isArray(bValue);
    const aIsObject = isPlainObject3(aValue);
    const bIsObject = isPlainObject3(bValue);
    if (aIsArray && bIsArray) {
      aRecord[key] = Array.from(new Set(aValue.concat(bValue)));
    } else if (aIsArray && bIsObject) {
      const aNewValue = convertWorkerOptionsArrayToObject(
        // Must be an array/record key if `aValue` & `bValue` are array/record
        key,
        aValue
      );
      Object.assign(aNewValue, bValue);
      aRecord[key] = aNewValue;
    } else if (aIsObject && bIsArray) {
      const bNewValue = convertWorkerOptionsArrayToObject(
        // Must be an array/record key if `aValue` & `bValue` are array/record
        key,
        bValue
      );
      Object.assign(aValue, bNewValue);
    } else if (aIsObject && bIsObject) {
      Object.assign(aValue, bValue);
    } else {
      aRecord[key] = bValue;
    }
  }
  return a;
}

// src/config/v4-schema.ts
var kUnsafeEphemeralUniqueKey2 = /* @__PURE__ */ Symbol.for(
  "miniflare.kUnsafeEphemeralUniqueKey"
);
var JsonLiteralSchema = external_exports2.union([
  external_exports2.string(),
  external_exports2.number(),
  external_exports2.boolean(),
  external_exports2.null()
]);
var JsonSchema2 = external_exports2.lazy(
  () => external_exports2.union([
    JsonLiteralSchema,
    external_exports2.array(JsonSchema2),
    external_exports2.record(external_exports2.string(), JsonSchema2)
  ])
);
var RemoteProxyConnectionStringSchema = external_exports2.custom();
var V4AssetConfigSchema = AssetConfigSchema.omit({
  compatibility_date: true,
  compatibility_flags: true
});
var V4ModuleRuleTypeSchema = external_exports2.enum([
  "ESModule",
  "CommonJS",
  "Text",
  "Data",
  "CompiledWasm",
  "PythonModule",
  "PythonRequirement"
]);
var V4ModuleRuleSchema = external_exports2.object({
  type: V4ModuleRuleTypeSchema,
  include: external_exports2.array(external_exports2.string()),
  fallthrough: external_exports2.boolean().optional()
});
var V4ModuleDefinitionSchema = external_exports2.object({
  type: V4ModuleRuleTypeSchema,
  /** Module file path; relative to `modulesRoot` if not absolute. */
  path: external_exports2.string(),
  contents: external_exports2.union([external_exports2.string(), external_exports2.instanceof(Uint8Array)]).optional()
});
var V4SourceOptionsSchema = external_exports2.union([
  external_exports2.object({
    modules: external_exports2.array(V4ModuleDefinitionSchema),
    /** Source directory for module paths; relative to `rootPath` if not absolute. */
    modulesRoot: external_exports2.string().optional()
  }),
  external_exports2.object({
    script: external_exports2.string(),
    /** Worker script source path; relative to `rootPath` if not absolute. */
    scriptPath: external_exports2.string().optional(),
    modules: external_exports2.boolean().optional(),
    modulesRules: external_exports2.array(V4ModuleRuleSchema).optional(),
    /** Source directory for module paths; relative to `rootPath` if not absolute. */
    modulesRoot: external_exports2.string().optional()
  }),
  external_exports2.object({
    /** Worker script source path; relative to `rootPath` if not absolute. */
    scriptPath: external_exports2.string(),
    modules: external_exports2.boolean().optional(),
    modulesRules: external_exports2.array(V4ModuleRuleSchema).optional(),
    /** Source directory for module paths; relative to `rootPath` if not absolute. */
    modulesRoot: external_exports2.string().optional()
  })
]);
var V4HttpOptionsHeaderSchema = external_exports2.object({
  name: external_exports2.string(),
  value: external_exports2.string().optional()
});
var V4HttpOptionsSchema = external_exports2.object({
  style: external_exports2.enum(HttpOptions_Style).optional(),
  forwardedProtoHeader: external_exports2.string().optional(),
  cfBlobHeader: external_exports2.string().optional(),
  injectRequestHeaders: external_exports2.array(V4HttpOptionsHeaderSchema).optional(),
  injectResponseHeaders: external_exports2.array(V4HttpOptionsHeaderSchema).optional()
});
var V4TlsOptionsSchema = external_exports2.object({
  keypair: external_exports2.object({
    privateKey: external_exports2.string().optional(),
    certificateChain: external_exports2.string().optional()
  }).optional(),
  requireClientCerts: external_exports2.boolean().optional(),
  trustBrowserCas: external_exports2.boolean().optional(),
  trustedCertificates: external_exports2.array(external_exports2.string()).optional(),
  minVersion: external_exports2.enum(TlsOptions_Version).optional(),
  cipherList: external_exports2.string().optional()
});
var V4NetworkSchema = external_exports2.object({
  allow: external_exports2.array(external_exports2.string()).optional(),
  deny: external_exports2.array(external_exports2.string()).optional(),
  tlsOptions: V4TlsOptionsSchema.optional()
});
var V4ExternalServerSchema = external_exports2.object({
  address: external_exports2.string(),
  http: V4HttpOptionsSchema.optional(),
  https: external_exports2.object({
    options: V4HttpOptionsSchema.optional(),
    tlsOptions: V4TlsOptionsSchema.optional(),
    certificateHost: external_exports2.string().optional()
  }).optional()
}).refine((value) => value.http === void 0 || value.https === void 0, {
  message: "Cannot specify both 'http' and 'https'"
});
var V4DiskDirectorySchema = external_exports2.object({
  /** Directory served by the workerd disk service; passed through as-is. */
  path: external_exports2.string(),
  writable: external_exports2.boolean().optional()
});
var V4CustomNodeServiceSchema = external_exports2.custom(
  (value) => typeof value === "function"
);
var V4CustomFetchServiceSchema = external_exports2.custom(
  (value) => typeof value === "function"
);
var V4ServiceDesignatorSchema = external_exports2.union([
  external_exports2.string(),
  external_exports2.custom((value) => value === kCurrentWorker),
  external_exports2.object({
    name: external_exports2.union([
      external_exports2.string(),
      external_exports2.custom((value) => value === kCurrentWorker)
    ]),
    entrypoint: external_exports2.string().optional(),
    props: external_exports2.record(external_exports2.string(), external_exports2.unknown()).optional(),
    remoteProxyConnectionString: RemoteProxyConnectionStringSchema.optional()
  }),
  external_exports2.object({ network: V4NetworkSchema }),
  external_exports2.object({ external: V4ExternalServerSchema }),
  external_exports2.object({ disk: V4DiskDirectorySchema }),
  external_exports2.object({ node: V4CustomNodeServiceSchema }),
  V4CustomFetchServiceSchema
]);
var V4UnsafeDirectSocketSchema = external_exports2.object({
  host: external_exports2.string().optional(),
  port: external_exports2.number().optional(),
  serviceName: external_exports2.string().optional(),
  entrypoint: external_exports2.string().optional(),
  proxy: external_exports2.boolean().optional()
});
var V4IdEntrySchema = external_exports2.object({
  id: external_exports2.string(),
  remoteProxyConnectionString: RemoteProxyConnectionStringSchema.optional()
});
var V4NamespaceSchema = external_exports2.union([
  external_exports2.record(external_exports2.string(), external_exports2.union([external_exports2.string(), V4IdEntrySchema])),
  external_exports2.array(external_exports2.string())
]);
var V4R2S3CredentialsSchema = external_exports2.object({
  accessKeyId: external_exports2.string(),
  secretAccessKey: external_exports2.string()
});
var V4R2BucketsSchema = external_exports2.union([
  external_exports2.record(
    external_exports2.string(),
    external_exports2.union([
      external_exports2.string(),
      V4IdEntrySchema.extend({
        s3Credentials: V4R2S3CredentialsSchema.optional()
      })
    ])
  ),
  external_exports2.array(external_exports2.string())
]);
var V4DurableObjectSchema = external_exports2.object({
  className: external_exports2.string(),
  scriptName: external_exports2.string().optional(),
  useSQLite: external_exports2.boolean().optional(),
  unsafeUniqueKey: external_exports2.union([
    external_exports2.string(),
    external_exports2.custom(
      (value) => value === kUnsafeEphemeralUniqueKey2
    )
  ]).optional(),
  unsafePreventEviction: external_exports2.boolean().optional(),
  remoteProxyConnectionString: RemoteProxyConnectionStringSchema.optional(),
  container: external_exports2.object({ imageName: external_exports2.string() }).optional()
});
var V4QueueMessageDelaySchema = external_exports2.number().int().min(0).max(86400).optional();
var V4QueueProducerOptionsSchema = external_exports2.object({
  queueName: external_exports2.string(),
  deliveryDelay: V4QueueMessageDelaySchema,
  remoteProxyConnectionString: RemoteProxyConnectionStringSchema.optional()
});
var V4QueueConsumerOptionsSchema = external_exports2.object({
  maxBatchSize: external_exports2.number().min(0).max(100).optional(),
  maxBatchTimeout: external_exports2.number().min(0).max(60).optional(),
  maxRetries: external_exports2.number().min(0).max(100).optional(),
  deadLetterQueue: external_exports2.string().optional(),
  retryDelay: V4QueueMessageDelaySchema
});
var V4HyperdriveSchema = external_exports2.union([external_exports2.url(), external_exports2.instanceof(URL)]).superRefine((value, ctx) => {
  const url46 = typeof value === "string" ? new URL(value) : value;
  const isPostgres = url46.protocol === "postgresql:" || url46.protocol === "postgres:";
  const isMysql = url46.protocol === "mysql:";
  if (!isPostgres && !isMysql) {
    ctx.addIssue({
      code: "custom",
      message: "Only PostgreSQL-compatible or MySQL-compatible databases are currently supported."
    });
  }
  if (url46.host === "") {
    ctx.addIssue({
      code: "custom",
      message: "You must provide a hostname or IP address in your connection string - e.g. 'user:password@database-hostname.example.com:5432/databasename"
    });
  }
  if (url46.pathname === "") {
    ctx.addIssue({
      code: "custom",
      message: "You must provide a database name as the path component - e.g. /postgres"
    });
  }
  if (url46.username === "") {
    ctx.addIssue({
      code: "custom",
      message: "You must provide a username - e.g. 'user:password@database.example.com:port/databasename'"
    });
  }
  if (url46.password === "") {
    ctx.addIssue({
      code: "custom",
      message: "You must provide a password - e.g. 'user:password@database.example.com:port/databasename' "
    });
  }
});
var V4PipelineSchema = external_exports2.union([
  external_exports2.string(),
  external_exports2.object({
    stream: external_exports2.string(),
    remoteProxyConnectionString: RemoteProxyConnectionStringSchema.optional()
  }),
  external_exports2.object({
    pipeline: external_exports2.string(),
    remoteProxyConnectionString: RemoteProxyConnectionStringSchema.optional()
  })
]);
var V4EmailBindingOptionsSchema = external_exports2.object({
  name: external_exports2.string(),
  remoteProxyConnectionString: RemoteProxyConnectionStringSchema.optional(),
  allowed_sender_addresses: external_exports2.array(external_exports2.string()).optional()
}).and(
  external_exports2.union([
    external_exports2.object({
      destination_address: external_exports2.string().optional(),
      allowed_destination_addresses: external_exports2.never().optional()
    }),
    external_exports2.object({
      allowed_destination_addresses: external_exports2.array(external_exports2.string()).optional(),
      destination_address: external_exports2.never().optional()
    })
  ])
);
var V4RemoteBindingSchema = external_exports2.object({
  remoteProxyConnectionString: RemoteProxyConnectionStringSchema.optional()
});
var V4RemoteBindingWithNameSchema = external_exports2.object({
  binding: external_exports2.string(),
  remoteProxyConnectionString: RemoteProxyConnectionStringSchema.optional()
});
var V4WorkerOptionsShapeSchema = external_exports2.object({
  name: external_exports2.string().optional(),
  /** Base directory for relative worker path options; may itself be relative to cwd. */
  rootPath: external_exports2.string().optional(),
  compatibilityDate: external_exports2.string().optional(),
  compatibilityFlags: external_exports2.array(external_exports2.string()).optional(),
  unsafeInspectorProxy: external_exports2.boolean().optional(),
  routes: external_exports2.array(external_exports2.string()).optional(),
  bindings: external_exports2.record(external_exports2.string(), JsonSchema2).optional(),
  /** WASM binding file paths; string values are relative to `rootPath` if not absolute. */
  wasmBindings: external_exports2.record(external_exports2.string(), external_exports2.union([external_exports2.string(), external_exports2.instanceof(Uint8Array)])).optional(),
  /** Text blob binding file paths; values are relative to `rootPath` if not absolute. */
  textBlobBindings: external_exports2.record(external_exports2.string(), external_exports2.string()).optional(),
  /** Data blob binding file paths; string values are relative to `rootPath` if not absolute. */
  dataBlobBindings: external_exports2.record(external_exports2.string(), external_exports2.union([external_exports2.string(), external_exports2.instanceof(Uint8Array)])).optional(),
  serviceBindings: external_exports2.record(external_exports2.string(), V4ServiceDesignatorSchema).optional(),
  outboundService: V4ServiceDesignatorSchema.optional(),
  unsafeEphemeralDurableObjects: external_exports2.boolean().optional(),
  unsafeDirectSockets: external_exports2.array(V4UnsafeDirectSocketSchema).optional(),
  unsafeOverrideFetchWorker: external_exports2.string().optional(),
  unsafeEvalBinding: external_exports2.string().optional(),
  unsafeUseModuleFallbackService: external_exports2.boolean().optional(),
  unsafeRegisterWorker: external_exports2.boolean().optional(),
  hasAssetsAndIsVitest: external_exports2.boolean().optional(),
  tails: external_exports2.array(V4ServiceDesignatorSchema).optional(),
  streamingTails: external_exports2.array(V4ServiceDesignatorSchema).optional(),
  stripCfConnectingIp: external_exports2.boolean().default(true),
  zone: external_exports2.string().optional(),
  /** Cloudflare Access authentication metadata exposed as `ctx.access` */
  access: external_exports2.object({
    aud: external_exports2.string(),
    identity: external_exports2.record(external_exports2.string(), external_exports2.unknown()).optional()
  }).optional(),
  unsafeBindings: external_exports2.array(
    external_exports2.object({
      name: external_exports2.string(),
      type: external_exports2.string(),
      plugin: external_exports2.object({ package: external_exports2.string(), name: external_exports2.string() }),
      options: external_exports2.record(external_exports2.string(), JsonSchema2)
    })
  ).optional(),
  cacheAPI: external_exports2.boolean().optional(),
  d1Databases: V4NamespaceSchema.optional(),
  durableObjects: external_exports2.record(external_exports2.string(), external_exports2.union([external_exports2.string(), V4DurableObjectSchema])).optional(),
  additionalUnboundDurableObjects: external_exports2.array(V4DurableObjectSchema).optional(),
  kvNamespaces: V4NamespaceSchema.optional(),
  /** Workers Sites asset directory; relative to `rootPath` if not absolute. */
  sitePath: external_exports2.string().optional(),
  siteInclude: external_exports2.array(external_exports2.string()).optional(),
  siteExclude: external_exports2.array(external_exports2.string()).optional(),
  queueProducers: external_exports2.union([
    external_exports2.record(external_exports2.string(), V4QueueProducerOptionsSchema),
    external_exports2.array(external_exports2.string()),
    external_exports2.record(external_exports2.string(), external_exports2.string())
  ]).optional(),
  queueConsumers: external_exports2.union([
    external_exports2.record(external_exports2.string(), V4QueueConsumerOptionsSchema),
    external_exports2.array(external_exports2.string())
  ]).optional(),
  r2Buckets: V4R2BucketsSchema.optional(),
  hyperdrives: external_exports2.record(external_exports2.string(), V4HyperdriveSchema).optional(),
  ratelimits: external_exports2.record(
    external_exports2.string(),
    external_exports2.object({
      namespace_id: external_exports2.string(),
      simple: external_exports2.object({
        limit: external_exports2.number().gt(0),
        period: external_exports2.union([external_exports2.literal(10), external_exports2.literal(60)]).optional().default(60)
      })
    })
  ).optional(),
  assets: external_exports2.object({
    workerName: external_exports2.string().optional(),
    /** Assets directory to serve; relative to `rootPath` if not absolute. */
    directory: external_exports2.string(),
    binding: external_exports2.string().optional(),
    run_worker_first: external_exports2.union([external_exports2.boolean(), external_exports2.array(external_exports2.string())]).optional(),
    routerConfig: RouterConfigSchema.optional(),
    assetConfig: V4AssetConfigSchema.optional()
  }).optional(),
  workflows: external_exports2.record(
    external_exports2.string(),
    external_exports2.object({
      name: external_exports2.string(),
      className: external_exports2.string(),
      scriptName: external_exports2.string().optional(),
      external: external_exports2.boolean().optional(),
      remoteProxyConnectionString: RemoteProxyConnectionStringSchema.optional(),
      stepLimit: external_exports2.number().int().min(1).optional()
    })
  ).optional(),
  pipelines: external_exports2.union([external_exports2.record(external_exports2.string(), V4PipelineSchema), external_exports2.array(external_exports2.string())]).optional(),
  secretsStoreSecrets: external_exports2.record(
    external_exports2.string(),
    external_exports2.object({ store_id: external_exports2.string(), secret_name: external_exports2.string() })
  ).optional(),
  email: external_exports2.object({ send_email: external_exports2.array(V4EmailBindingOptionsSchema).optional() }).optional(),
  analyticsEngineDatasets: external_exports2.record(external_exports2.string(), external_exports2.object({ dataset: external_exports2.string() })).optional(),
  ai: V4RemoteBindingWithNameSchema.optional(),
  agentMemory: external_exports2.record(
    external_exports2.string(),
    external_exports2.object({
      namespace: external_exports2.string(),
      remoteProxyConnectionString: RemoteProxyConnectionStringSchema.optional()
    })
  ).optional(),
  aiSearchNamespaces: external_exports2.record(
    external_exports2.string(),
    external_exports2.object({
      namespace: external_exports2.string().optional(),
      instance_name: external_exports2.string().optional(),
      remoteProxyConnectionString: RemoteProxyConnectionStringSchema.optional()
    })
  ).optional(),
  aiSearchInstances: external_exports2.record(
    external_exports2.string(),
    external_exports2.object({
      namespace: external_exports2.string().optional(),
      instance_name: external_exports2.string().optional(),
      remoteProxyConnectionString: RemoteProxyConnectionStringSchema.optional()
    })
  ).optional(),
  websearch: external_exports2.record(external_exports2.string(), V4RemoteBindingSchema).optional(),
  browserRendering: external_exports2.object({
    binding: external_exports2.string(),
    remoteProxyConnectionString: RemoteProxyConnectionStringSchema.optional(),
    headful: external_exports2.boolean().optional()
  }).optional(),
  dispatchNamespaces: external_exports2.record(
    external_exports2.string(),
    external_exports2.object({
      namespace: external_exports2.string(),
      remoteProxyConnectionString: RemoteProxyConnectionStringSchema.optional()
    })
  ).optional(),
  images: V4RemoteBindingWithNameSchema.optional(),
  stream: V4RemoteBindingWithNameSchema.optional(),
  vectorize: external_exports2.record(
    external_exports2.string(),
    external_exports2.object({
      index_name: external_exports2.string(),
      remoteProxyConnectionString: RemoteProxyConnectionStringSchema.optional()
    })
  ).optional(),
  vpcNetworks: external_exports2.record(
    external_exports2.string(),
    external_exports2.union([
      external_exports2.object({
        tunnel_id: external_exports2.string(),
        remoteProxyConnectionString: RemoteProxyConnectionStringSchema.optional()
      }),
      external_exports2.object({
        network_id: external_exports2.string(),
        remoteProxyConnectionString: RemoteProxyConnectionStringSchema.optional()
      })
    ])
  ).optional(),
  vpcServices: external_exports2.record(
    external_exports2.string(),
    external_exports2.object({
      service_id: external_exports2.string(),
      remoteProxyConnectionString: RemoteProxyConnectionStringSchema.optional()
    })
  ).optional(),
  mtlsCertificates: external_exports2.record(
    external_exports2.string(),
    external_exports2.object({
      certificate_id: external_exports2.string(),
      remoteProxyConnectionString: RemoteProxyConnectionStringSchema.optional()
    })
  ).optional(),
  helloWorld: external_exports2.record(external_exports2.string(), external_exports2.object({ enable_timer: external_exports2.boolean().optional() })).optional(),
  flagship: external_exports2.record(
    external_exports2.string(),
    external_exports2.object({
      app_id: external_exports2.string(),
      remoteProxyConnectionString: RemoteProxyConnectionStringSchema.optional()
    })
  ).optional(),
  artifacts: external_exports2.record(
    external_exports2.string(),
    external_exports2.object({
      namespace: external_exports2.string(),
      remoteProxyConnectionString: RemoteProxyConnectionStringSchema.optional()
    })
  ).optional(),
  workerLoaders: external_exports2.record(external_exports2.string(), external_exports2.object({})).optional(),
  media: V4RemoteBindingWithNameSchema.optional(),
  versionMetadata: external_exports2.string().optional()
});
var V4WorkerOptionsSchema = V4SourceOptionsSchema.and(
  V4WorkerOptionsShapeSchema
);
var V4SharedOptionsSchema = external_exports2.object({
  /** Base directory for relative worker path options; may itself be relative to cwd. */
  rootPath: external_exports2.string().optional(),
  host: external_exports2.string().optional(),
  port: external_exports2.number().optional(),
  https: external_exports2.boolean().optional(),
  httpsKey: external_exports2.string().optional(),
  httpsCert: external_exports2.string().optional(),
  inspectorPort: external_exports2.number().optional(),
  inspectorHost: external_exports2.string().optional(),
  verbose: external_exports2.boolean().optional(),
  log: external_exports2.instanceof(Log).optional(),
  handleStructuredLogs: external_exports2.custom(
    (value) => typeof value === "function"
  ).optional(),
  unsafeHandleRuntimeRestart: external_exports2.custom((value) => typeof value === "function").optional(),
  handleUncaughtError: external_exports2.custom((value) => typeof value === "function").optional(),
  upstream: external_exports2.string().optional(),
  cf: external_exports2.union([external_exports2.boolean(), external_exports2.string(), external_exports2.record(external_exports2.string(), external_exports2.unknown())]).optional(),
  /** Dev registry filesystem path; relative to cwd if not absolute. */
  unsafeDevRegistryPath: external_exports2.string().optional(),
  unsafeHandleDevRegistryUpdate: external_exports2.custom(
    (value) => typeof value === "function"
  ).optional(),
  unsafeProxySharedSecret: external_exports2.string().optional(),
  unsafeModuleFallbackService: V4CustomFetchServiceSchema.optional(),
  unsafeTriggerHandlers: external_exports2.boolean().optional(),
  unsafeRuntimeEnv: external_exports2.record(external_exports2.string(), external_exports2.string()).optional(),
  unsafeLocalExplorer: external_exports2.boolean().optional(),
  unsafeObservability: external_exports2.boolean().optional(),
  unsafeInspectDurableObjects: external_exports2.boolean().optional(),
  logRequests: external_exports2.boolean().default(true),
  /** Root directory for persisted local resource state; relative to cwd if not absolute. */
  resourcePersistencePath: external_exports2.string().optional(),
  /** Project temp directory for plugin files; relative to cwd if not absolute. */
  resourceTmpPath: external_exports2.string().optional(),
  stripDisablePrettyError: external_exports2.boolean().default(true),
  telemetry: external_exports2.object({
    enabled: external_exports2.boolean().default(false),
    deviceId: external_exports2.string().optional()
  }).default({ enabled: false }),
  publicUrl: external_exports2.url().optional(),
  containerEngine: external_exports2.union([
    external_exports2.object({
      localDocker: external_exports2.object({
        /** Docker socket path; passed through as-is. */
        socketPath: external_exports2.string(),
        containerEgressInterceptorImage: external_exports2.string().optional()
      })
    }),
    external_exports2.string()
  ]).optional()
});
var V4MiniflareOptionsSchema = V4SharedOptionsSchema.and(
  external_exports2.union([
    external_exports2.object({ workers: external_exports2.array(V4WorkerOptionsSchema) }),
    V4WorkerOptionsSchema
  ])
);

// src/config/v4-convert.ts
var import_node_fs20 = require("node:fs");
var import_node_path30 = __toESM(require("node:path"));
var FALLBACK_COMPATIBILITY_DATE2 = "2000-01-01";
function convertV4MiniflareOptions(options) {
  const parsed = V4MiniflareOptionsSchema.parse(options);
  const sharedRootPath = import_node_path30.default.resolve(
    "workers" in parsed ? parsed.rootPath ?? "." : "."
  );
  const converted = {
    ...convertSharedOptions(parsed),
    workers: getV4Workers(parsed).map(
      (worker, index) => convertWorkerOptions(worker, index, sharedRootPath)
    )
  };
  return converted;
}
function convertSharedOptions(options) {
  return {
    host: options.host,
    port: options.port,
    https: options.https,
    httpsKey: options.httpsKey,
    httpsCert: options.httpsCert,
    inspectorPort: options.inspectorPort,
    inspectorHost: options.inspectorHost,
    verbose: options.verbose,
    log: options.log,
    handleStructuredLogs: options.handleStructuredLogs,
    unsafeHandleRuntimeRestart: options.unsafeHandleRuntimeRestart,
    handleUncaughtError: options.handleUncaughtError,
    upstream: options.upstream,
    cf: options.cf,
    unsafeDevRegistryPath: options.unsafeDevRegistryPath,
    unsafeHandleDevRegistryUpdate: options.unsafeHandleDevRegistryUpdate,
    unsafeProxySharedSecret: options.unsafeProxySharedSecret,
    unsafeModuleFallbackService: options.unsafeModuleFallbackService,
    unsafeTriggerHandlers: options.unsafeTriggerHandlers,
    unsafeRuntimeEnv: options.unsafeRuntimeEnv,
    unsafeLocalExplorer: options.unsafeLocalExplorer,
    unsafeObservability: options.unsafeObservability,
    unsafeInspectDurableObjects: options.unsafeInspectDurableObjects,
    logRequests: options.logRequests,
    resourcePersistencePath: options.resourcePersistencePath,
    resourceTmpPath: options.resourceTmpPath,
    stripDisablePrettyError: options.stripDisablePrettyError,
    telemetry: options.telemetry,
    publicUrl: options.publicUrl,
    containerEngine: options.containerEngine
  };
}
function getV4Workers(options) {
  if ("workers" in options) {
    return options.workers;
  }
  return [options];
}
function convertWorkerOptions(worker, workerIndex, sharedRootPath) {
  const env3 = {};
  const exports2 = {};
  const legacy = {};
  const dev = {};
  let remoteProxyConnectionString;
  const setRemoteProxyConnectionString = (value) => {
    if (remoteProxyConnectionString !== void 0 && value !== void 0 && String(remoteProxyConnectionString) !== String(value)) {
      throwUnsupportedOption("multiple remoteProxyConnectionString values");
    }
    if (remoteProxyConnectionString === void 0) {
      remoteProxyConnectionString = value;
    }
  };
  const isRemote = (value) => {
    setRemoteProxyConnectionString(value);
    return value !== void 0;
  };
  const optionsRootPath = import_node_path30.default.resolve(sharedRootPath, worker.rootPath ?? ".");
  const manifest = addSourceOptions(
    worker,
    workerIndex,
    legacy,
    optionsRootPath
  );
  const config3 = {
    type: "worker",
    name: worker.name ?? "",
    compatibilityDate: worker.compatibilityDate ?? FALLBACK_COMPATIBILITY_DATE2,
    compatibilityFlags: worker.compatibilityFlags,
    manifest,
    env: env3,
    exports: exports2
  };
  for (const route of worker.routes ?? []) {
    config3.triggers ??= [];
    config3.triggers.push({ type: "fetch", pattern: route });
  }
  addVariableBindings(env3, worker.bindings);
  addNamespaceBindings(env3, "kv", worker.kvNamespaces, isRemote);
  addNamespaceBindings(env3, "d1", worker.d1Databases, isRemote);
  addR2Bindings(env3, worker.r2Buckets, isRemote);
  addDurableObjectBindings(env3, exports2, config3.name, worker, isRemote);
  addQueueBindings(
    env3,
    config3,
    worker.queueProducers,
    worker.queueConsumers,
    isRemote
  );
  addServiceBindings(env3, worker.serviceBindings, isRemote);
  addServiceBindingArray(config3, worker.tails, false);
  addServiceBindingArray(config3, worker.streamingTails, true);
  addProductBindings(env3, exports2, config3, worker, isRemote);
  legacy.wasmBindings = worker.wasmBindings;
  legacy.textBlobBindings = worker.textBlobBindings;
  legacy.dataBlobBindings = worker.dataBlobBindings;
  legacy.sitePath = worker.sitePath === void 0 ? void 0 : import_node_path30.default.resolve(optionsRootPath, worker.sitePath);
  legacy.siteInclude = worker.siteInclude;
  legacy.siteExclude = worker.siteExclude;
  dev.rootPath = optionsRootPath;
  dev.cacheAPI = worker.cacheAPI;
  dev.outboundService = convertOutboundService(
    worker.outboundService,
    isRemote
  );
  dev.remoteProxyConnectionString = remoteProxyConnectionString;
  dev.unsafeInspectorProxy = worker.unsafeInspectorProxy;
  dev.unsafeDirectSockets = worker.unsafeDirectSockets;
  dev.unsafeOverrideFetchWorker = worker.unsafeOverrideFetchWorker;
  dev.unsafeEvalBinding = worker.unsafeEvalBinding;
  dev.useModuleFallbackService = worker.unsafeUseModuleFallbackService;
  dev.unsafeRegisterWorker = worker.unsafeRegisterWorker ?? true;
  dev.hasAssetsAndIsVitest = worker.hasAssetsAndIsVitest;
  dev.unsafeEphemeralDurableObjects = worker.unsafeEphemeralDurableObjects;
  dev.stripCfConnectingIp = worker.stripCfConnectingIp;
  dev.zone = worker.zone;
  dev.access = worker.access;
  const options = { config: config3 };
  if (Object.values(legacy).some((value) => value !== void 0)) {
    options.legacy = legacy;
  }
  if (Object.values(dev).some((value) => value !== void 0)) {
    options.dev = dev;
  }
  return options;
}
function addSourceOptions(worker, workerIndex, legacy, rootPath2) {
  if ("modulesRules" in worker && worker.modulesRules !== void 0) {
    throwUnsupportedOption("modulesRules");
  }
  if (Array.isArray(worker.modules)) {
    const modulesRoot = import_node_path30.default.resolve(rootPath2, worker.modulesRoot ?? ".");
    return createManifestFromModules(worker.modules, rootPath2, modulesRoot);
  }
  const scriptPath = "scriptPath" in worker && worker.scriptPath !== void 0 ? import_node_path30.default.resolve(rootPath2, worker.scriptPath) : void 0;
  const script = "script" in worker ? worker.script : scriptPath !== void 0 ? (0, import_node_fs20.readFileSync)(scriptPath, "utf8") : void 0;
  if (script === void 0) {
    throw new TypeError("V4 Miniflare workers must define a script.");
  }
  if (worker.modules === true) {
    const modulesRoot = import_node_path30.default.resolve(rootPath2, worker.modulesRoot ?? ".");
    const mainModule = scriptPath !== void 0 ? getModuleName(scriptPath, modulesRoot) : `script-${workerIndex}.mjs`;
    return {
      mainModule,
      modulesRoot,
      modules: {
        [mainModule]: { type: "esm", contents: script }
      }
    };
  } else {
    legacy.serviceWorkerScript = script;
    if (scriptPath !== void 0) {
      legacy.serviceWorkerScriptPath = scriptPath;
    }
  }
}
function createManifestFromModules(modules, rootPath2, modulesRoot) {
  const manifestModules = {};
  let mainModule;
  for (const module2 of modules) {
    const modulePath = import_node_path30.default.isAbsolute(module2.path) ? module2.path : import_node_path30.default.resolve(rootPath2, module2.path);
    const name = getModuleName(modulePath, modulesRoot);
    mainModule ??= name;
    manifestModules[name] = {
      type: convertModuleType(module2.type),
      contents: module2.contents ?? readModuleContents(modulePath, module2.type)
    };
  }
  if (mainModule === void 0) {
    throw new TypeError(
      "V4 Miniflare module workers must define at least one module."
    );
  }
  return { mainModule, modulesRoot, modules: manifestModules };
}
function getModuleName(modulePath, modulesRoot) {
  if (import_node_path30.default.isAbsolute(modulePath)) {
    return import_node_path30.default.relative(modulesRoot, modulePath).split(import_node_path30.default.sep).join(import_node_path30.default.posix.sep);
  }
  return modulePath.split(import_node_path30.default.sep).join(import_node_path30.default.posix.sep);
}
function readModuleContents(modulePath, type) {
  if (type === "Data" || type === "CompiledWasm") {
    return toUint8Array((0, import_node_fs20.readFileSync)(modulePath));
  }
  return (0, import_node_fs20.readFileSync)(modulePath, "utf8");
}
function toUint8Array(buffer) {
  const copy2 = new Uint8Array(buffer.byteLength);
  copy2.set(buffer);
  return copy2;
}
function convertModuleType(type) {
  switch (type) {
    case "ESModule":
      return "esm";
    case "CommonJS":
      return "cjs";
    case "Text":
      return "text";
    case "Data":
      return "data";
    case "CompiledWasm":
      return "wasm";
    case "PythonModule":
      return "python";
    case "PythonRequirement":
      return "python-requirement";
  }
}
function addVariableBindings(env3, bindings) {
  for (const [name, value] of Object.entries(bindings ?? {})) {
    env3[name] = typeof value === "string" ? { type: "text", value } : { type: "json", value };
  }
}
function addNamespaceBindings(env3, type, namespaces, isRemote) {
  if (namespaces === void 0) {
    return;
  }
  if (Array.isArray(namespaces)) {
    for (const name of namespaces) {
      env3[name] = { type, id: name };
    }
    return;
  }
  for (const [name, value] of Object.entries(namespaces)) {
    if (typeof value === "string") {
      env3[name] = { type, id: value };
    } else {
      env3[name] = {
        type,
        id: value.id,
        remote: isRemote(value.remoteProxyConnectionString)
      };
    }
  }
}
function addR2Bindings(env3, buckets, isRemote) {
  if (buckets === void 0) {
    return;
  }
  if (Array.isArray(buckets)) {
    for (const name of buckets) {
      env3[name] = { type: "r2", name };
    }
    return;
  }
  for (const [bindingName, bucket] of Object.entries(buckets)) {
    if (typeof bucket === "string") {
      env3[bindingName] = { type: "r2", name: bucket };
    } else {
      env3[bindingName] = {
        type: "r2",
        name: bucket.id,
        s3Credentials: bucket.s3Credentials,
        remote: isRemote(bucket.remoteProxyConnectionString)
      };
    }
  }
}
function addDurableObjectBindings(env3, exports2, workerName, worker, isRemote) {
  for (const [bindingName, object3] of Object.entries(
    worker.durableObjects ?? {}
  )) {
    const objectOptions = typeof object3 === "string" ? { className: object3 } : object3;
    const targetWorkerName = objectOptions.scriptName ?? workerName;
    env3[bindingName] = {
      type: "durable-object",
      workerName: targetWorkerName,
      exportName: objectOptions.className
    };
    isRemote(objectOptions.remoteProxyConnectionString);
    if (targetWorkerName === workerName) {
      addDurableObjectExport(exports2, objectOptions);
    }
  }
  for (const object3 of worker.additionalUnboundDurableObjects ?? []) {
    addDurableObjectExport(exports2, object3);
    isRemote(object3.remoteProxyConnectionString);
  }
}
function addDurableObjectExport(exports2, object3) {
  const exported = {
    type: "durable-object",
    storage: object3.useSQLite ? "sqlite" : "legacy-kv",
    unsafeUniqueKey: object3.unsafeUniqueKey,
    unsafePreventEviction: object3.unsafePreventEviction,
    container: object3.container
  };
  exports2[object3.className] = exported;
}
function addQueueBindings(env3, config3, producers, consumers, isRemote) {
  if (Array.isArray(producers)) {
    for (const name of producers) {
      env3[name] = { type: "queue", name };
    }
  } else {
    for (const [bindingName, producer] of Object.entries(producers ?? {})) {
      if (typeof producer === "string") {
        env3[bindingName] = { type: "queue", name: producer };
      } else {
        env3[bindingName] = {
          type: "queue",
          name: producer.queueName,
          deliveryDelay: producer.deliveryDelay,
          remote: isRemote(producer.remoteProxyConnectionString)
        };
      }
    }
  }
  if (Array.isArray(consumers)) {
    for (const name of consumers) {
      config3.triggers ??= [];
      config3.triggers.push({ type: "queue", name });
    }
  } else {
    for (const [name, consumer] of Object.entries(consumers ?? {})) {
      config3.triggers ??= [];
      config3.triggers.push({
        type: "queue",
        name,
        deadLetterQueue: consumer.deadLetterQueue,
        maxBatchSize: consumer.maxBatchSize,
        maxBatchTimeout: consumer.maxBatchTimeout,
        maxRetries: consumer.maxRetries,
        retryDelay: consumer.retryDelay
      });
    }
  }
}
function addServiceBindings(env3, serviceBindings, isRemote) {
  for (const [name, binding] of Object.entries(serviceBindings ?? {})) {
    env3[name] = convertServiceDesignator(binding, isRemote);
  }
}
function addServiceBindingArray(config3, bindings, streaming) {
  const option = streaming ? "streamingTails" : "tails";
  for (const binding of bindings ?? []) {
    if (hasRemoteProxyConnectionString(binding)) {
      throwUnsupportedOption(`${option}[].remoteProxyConnectionString`);
    }
    const converted = convertServiceDesignator(binding, () => false);
    if (converted.type !== "worker" || typeof converted.workerName !== "string") {
      throwUnsupportedOption(option);
    }
    config3.tailConsumers ??= [];
    config3.tailConsumers.push({
      workerName: converted.workerName,
      entrypoint: converted.exportName,
      props: converted.props,
      streaming
    });
  }
}
function hasRemoteProxyConnectionString(binding) {
  return typeof binding === "object" && binding !== null && "remoteProxyConnectionString" in binding && binding.remoteProxyConnectionString !== void 0;
}
function convertOutboundService(binding, isRemote) {
  if (binding === void 0) {
    return void 0;
  }
  const converted = convertServiceDesignator(binding, isRemote);
  if (converted.type === "fetcher" || converted.type === "node-handler") {
    return converted;
  }
  if (converted.type === "worker" && typeof converted.workerName === "string") {
    return {
      type: "worker",
      workerName: converted.workerName,
      exportName: converted.exportName,
      props: converted.props,
      remote: converted.remote
    };
  }
  throwUnsupportedOption("outboundService");
}
function convertServiceDesignator(binding, isRemote) {
  if (typeof binding === "function") {
    return { type: "fetcher", handler: binding };
  }
  if (typeof binding === "string") {
    return { type: "worker", workerName: binding };
  }
  if (binding === kCurrentWorker) {
    return {
      type: "worker",
      workerName: getCurrentWorkerBindingName()
    };
  }
  if (typeof binding !== "object" || binding === null) {
    return {
      type: "worker",
      workerName: getCurrentWorkerBindingName()
    };
  }
  if ("name" in binding) {
    return {
      type: "worker",
      workerName: convertWorkerName(binding.name),
      exportName: binding.entrypoint,
      props: binding.props,
      remote: isRemote(binding.remoteProxyConnectionString)
    };
  }
  if ("network" in binding) {
    return { type: "network", ...binding.network };
  }
  if ("external" in binding) {
    return { type: "external", ...binding.external };
  }
  if ("disk" in binding) {
    return { type: "disk", ...binding.disk };
  }
  return { type: "node-handler", handler: binding.node };
}
function getCurrentWorkerBindingName() {
  return kCurrentWorker;
}
function convertWorkerName(name) {
  return typeof name === "string" ? name : getCurrentWorkerBindingName();
}
function addProductBindings(env3, exports2, config3, worker, isRemote) {
  for (const binding of worker.unsafeBindings ?? []) {
    env3[binding.name] = {
      type: `unsafe:${binding.type}`,
      dev: { plugin: binding.plugin, options: binding.options }
    };
  }
  if (worker.assets !== void 0) {
    configAssets(env3, config3, worker);
  }
  if (worker.ai !== void 0) {
    env3[worker.ai.binding] = {
      type: "ai",
      remote: isRemote(worker.ai.remoteProxyConnectionString)
    };
  }
  for (const [name, binding] of Object.entries(worker.agentMemory ?? {})) {
    env3[name] = {
      type: "agent-memory",
      namespace: binding.namespace,
      remote: isRemote(binding.remoteProxyConnectionString)
    };
  }
  for (const [name, binding] of Object.entries(
    worker.aiSearchNamespaces ?? {}
  )) {
    env3[name] = {
      type: "ai-search-namespace",
      namespace: binding.namespace ?? name,
      remote: isRemote(binding.remoteProxyConnectionString)
    };
  }
  for (const [name, binding] of Object.entries(
    worker.aiSearchInstances ?? {}
  )) {
    env3[name] = {
      type: "ai-search",
      name: binding.instance_name ?? binding.namespace ?? name,
      remote: isRemote(binding.remoteProxyConnectionString)
    };
  }
  for (const [name, binding] of Object.entries(worker.websearch ?? {})) {
    env3[name] = {
      type: "web-search",
      remote: isRemote(binding.remoteProxyConnectionString)
    };
  }
  for (const [name, binding] of Object.entries(
    worker.analyticsEngineDatasets ?? {}
  )) {
    env3[name] = { type: "analytics-engine-dataset", name: binding.dataset };
  }
  for (const [name, value] of Object.entries(worker.hyperdrives ?? {})) {
    env3[name] = {
      type: "hyperdrive",
      id: name,
      localConnectionString: String(value)
    };
  }
  for (const [name, binding] of Object.entries(worker.ratelimits ?? {})) {
    env3[name] = {
      type: "rate-limit",
      namespace: binding.namespace_id,
      simple: binding.simple
    };
  }
  addPipelineBindings(env3, worker.pipelines, isRemote);
  for (const binding of worker.email?.send_email ?? []) {
    env3[binding.name] = {
      type: "send-email",
      destinationAddress: binding.destination_address,
      allowedDestinationAddresses: binding.allowed_destination_addresses,
      allowedSenderAddresses: binding.allowed_sender_addresses,
      remote: isRemote(binding.remoteProxyConnectionString)
    };
  }
  for (const [name, binding] of Object.entries(
    worker.secretsStoreSecrets ?? {}
  )) {
    env3[name] = {
      type: "secrets-store-secret",
      storeId: binding.store_id,
      secretName: binding.secret_name
    };
  }
  for (const [name, binding] of Object.entries(worker.vectorize ?? {})) {
    env3[name] = {
      type: "vectorize",
      name: binding.index_name,
      remote: isRemote(binding.remoteProxyConnectionString)
    };
  }
  for (const [name, binding] of Object.entries(
    worker.dispatchNamespaces ?? {}
  )) {
    env3[name] = {
      type: "dispatch-namespace",
      namespace: binding.namespace,
      remote: isRemote(binding.remoteProxyConnectionString)
    };
  }
  for (const [name, binding] of Object.entries(worker.vpcServices ?? {})) {
    env3[name] = {
      type: "vpc-service",
      id: binding.service_id,
      remote: isRemote(binding.remoteProxyConnectionString)
    };
  }
  for (const [name, binding] of Object.entries(worker.vpcNetworks ?? {})) {
    env3[name] = {
      type: "vpc-network",
      ..."tunnel_id" in binding ? { tunnelId: binding.tunnel_id } : { networkId: binding.network_id },
      remote: isRemote(binding.remoteProxyConnectionString)
    };
  }
  for (const [name, binding] of Object.entries(worker.mtlsCertificates ?? {})) {
    env3[name] = {
      type: "mtls-certificate",
      id: binding.certificate_id,
      remote: isRemote(binding.remoteProxyConnectionString)
    };
  }
  for (const [name, binding] of Object.entries(worker.helloWorld ?? {})) {
    env3[name] = { type: "hello-world", enable_timer: binding.enable_timer };
  }
  for (const [name, binding] of Object.entries(worker.flagship ?? {})) {
    env3[name] = {
      type: "flagship",
      id: binding.app_id,
      remote: isRemote(binding.remoteProxyConnectionString)
    };
  }
  for (const [name, binding] of Object.entries(worker.artifacts ?? {})) {
    env3[name] = {
      type: "artifacts",
      namespace: binding.namespace,
      remote: isRemote(binding.remoteProxyConnectionString)
    };
  }
  for (const name of Object.keys(worker.workerLoaders ?? {})) {
    env3[name] = { type: "worker-loader" };
  }
  addBrowserRenderingBinding(env3, worker.browserRendering, isRemote);
  addSingletonBinding(env3, worker.images, "images", isRemote);
  addSingletonBinding(env3, worker.stream, "stream", isRemote);
  addSingletonBinding(env3, worker.media, "media", isRemote);
  if (worker.versionMetadata) {
    env3[worker.versionMetadata] = { type: "version-metadata" };
  }
  for (const [bindingName, workflow] of Object.entries(
    worker.workflows ?? {}
  )) {
    if (workflow.external !== void 0) {
      throwUnsupportedOption("workflows[].external");
    }
    const targetWorkerName = workflow.scriptName ?? config3.name;
    env3[bindingName] = {
      type: "workflow",
      name: workflow.name,
      workerName: targetWorkerName,
      exportName: workflow.className,
      limits: workflow.stepLimit === void 0 ? void 0 : { steps: workflow.stepLimit },
      remote: isRemote(workflow.remoteProxyConnectionString)
    };
  }
}
function addPipelineBindings(env3, pipelines, isRemote) {
  if (pipelines === void 0) {
    return;
  }
  if (Array.isArray(pipelines)) {
    for (const name of pipelines) {
      env3[name] = { type: "pipeline", name };
    }
    return;
  }
  for (const [name, binding] of Object.entries(pipelines)) {
    env3[name] = {
      type: "pipeline",
      name: typeof binding === "string" ? binding : "stream" in binding ? binding.stream : binding.pipeline,
      remote: typeof binding === "string" ? void 0 : isRemote(binding.remoteProxyConnectionString)
    };
  }
}
function configAssets(env3, config3, worker) {
  const assets = worker.assets;
  if (assets === void 0) {
    return;
  }
  if (assets.workerName !== void 0) {
    throwUnsupportedOption("assets.workerName");
  }
  config3.assets = {
    directory: assets.directory,
    hasUserWorker: getBooleanProperty(assets.routerConfig, "has_user_worker"),
    htmlHandling: getHtmlHandling(
      getStringProperty(assets.assetConfig, "html_handling")
    ),
    notFoundHandling: getNotFoundHandling(
      getStringProperty(assets.assetConfig, "not_found_handling")
    ),
    runWorkerFirst: getRunWorkerFirst(
      assets.run_worker_first,
      assets.routerConfig
    )
  };
  if (assets.binding !== void 0) {
    env3[assets.binding] = { type: "assets" };
  }
}
function getStringProperty(record3, key) {
  const value = record3?.[key];
  return typeof value === "string" ? value : void 0;
}
function getBooleanProperty(record3, key) {
  const value = record3?.[key];
  return typeof value === "boolean" ? value : void 0;
}
function getRunWorkerFirst(value, routerConfig) {
  if (typeof value === "boolean") {
    return value;
  }
  if (Array.isArray(value) && value.every((item) => typeof item === "string")) {
    return value;
  }
  return getBooleanProperty(routerConfig, "invoke_user_worker_ahead_of_assets");
}
function getHtmlHandling(value) {
  switch (value) {
    case "auto-trailing-slash":
    case "drop-trailing-slash":
    case "force-trailing-slash":
    case "none":
      return value;
  }
}
function getNotFoundHandling(value) {
  switch (value) {
    case "single-page-application":
    case "404-page":
    case "none":
      return value;
  }
}
function addBrowserRenderingBinding(env3, binding, isRemote) {
  if (binding !== void 0) {
    env3[binding.binding] = {
      type: "browser",
      remote: isRemote(binding.remoteProxyConnectionString),
      headful: binding.headful
    };
  }
}
function addSingletonBinding(env3, binding, type, isRemote) {
  if (binding !== void 0) {
    env3[binding.binding] = {
      type,
      remote: isRemote(binding.remoteProxyConnectionString)
    };
  }
}
function throwUnsupportedOption(option) {
  throw new TypeError(
    `Cannot convert v4 Miniflare option ${JSON.stringify(option)} to v5 options without losing behavior.`
  );
}

// src/index.ts
var DEFAULT_HOST = "127.0.0.1";
function getURLSafeHost(host) {
  return import_node_net2.default.isIPv6(host) ? `[${host}]` : host;
}
function resolveLocalhost(host) {
  return host === "localhost" ? "127.0.0.1" : void 0;
}
function maybeGetLocallyAccessibleHost(h) {
  if (h === "localhost") return "localhost";
  if (h === "127.0.0.1" || h === "*" || h === "0.0.0.0" || h === "::") {
    return "127.0.0.1";
  }
  if (h === "::1") return "[::1]";
}
function getLocallyAccessibleHost(host) {
  if (host === "0.0.0.0" || host === "::" || host === "*") {
    return "127.0.0.1";
  }
  return getURLSafeHost(host);
}
function buildPublicUrl(options) {
  const host = getLocallyAccessibleHost(options.hostname ?? "localhost");
  const protocol = options.secure ? "https" : "http";
  return `${protocol}://${host}:${options.port}`;
}
function getServerPort(server) {
  const address = server.address();
  (0, import_node_assert21.default)(address !== null && typeof address === "object");
  return address.port;
}
function validateOptions(opts) {
  let parsed;
  try {
    parsed = MiniflareOptionsSchema.parse(opts);
  } catch (e) {
    if (e instanceof external_exports2.ZodError) {
      let formatted;
      try {
        formatted = formatZodError(e, opts);
      } catch (formatError4) {
        const title = "[Miniflare] Validation Error Format Failure";
        const message = [
          "### Input",
          "```",
          import_node_util7.default.inspect(opts, { depth: null }),
          "```",
          "",
          "### Validation Error",
          "```",
          e.stack,
          "```",
          "",
          "### Format Error",
          "```",
          typeof formatError4 === "object" && formatError4 !== null && "stack" in formatError4 && typeof formatError4.stack === "string" ? formatError4.stack : String(formatError4),
          "```"
        ].join("\n");
        const githubIssueUrl = new URL(
          "https://github.com/cloudflare/miniflare/issues/new"
        );
        githubIssueUrl.searchParams.set("title", title);
        githubIssueUrl.searchParams.set("body", message);
        formatted = [
          "Unable to format validation error.",
          "Please open the following URL in your browser to create a GitHub issue:",
          githubIssueUrl,
          "",
          message,
          ""
        ].join("\n");
      }
      const error101 = new MiniflareCoreError(
        "ERR_VALIDATION",
        `Unexpected options passed to \`new Miniflare()\` constructor:
${formatted}`
      );
      Object.defineProperty(error101, "cause", { get: () => e });
      throw error101;
    }
    throw e;
  }
  const { workers, ...sharedOpts } = parsed;
  if (workers.length === 0) {
    throw new MiniflareCoreError("ERR_NO_WORKERS", "No workers defined");
  }
  const names = /* @__PURE__ */ new Set();
  for (const workerOpts of workers) {
    const name = workerOpts.config.name;
    if (names.has(name)) {
      throw new MiniflareCoreError(
        "ERR_DUPLICATE_NAME",
        name === "" ? "Multiple workers defined without a `name`" : `Multiple workers defined with the same \`name\`: "${name}"`
      );
    }
    names.add(name);
  }
  return [sharedOpts, workers];
}
function getDurableObjectClassNames(allWorkerOpts) {
  const serviceClassNames = /* @__PURE__ */ new Map();
  for (const workerOpts of allWorkerOpts) {
    const serviceName = getUserServiceName(workerOpts.config.name);
    let classNames = serviceClassNames.get(serviceName);
    if (classNames === void 0) {
      classNames = /* @__PURE__ */ new Map();
      serviceClassNames.set(serviceName, classNames);
    }
    for (const [className, exported] of getExportsOfType(
      workerOpts.config,
      "durable-object"
    )) {
      classNames.set(className, {
        enableSql: exported.storage === "sqlite",
        unsafeUniqueKey: exported.unsafeUniqueKey,
        unsafePreventEviction: exported.unsafePreventEviction,
        container: exported.container
      });
    }
  }
  return serviceClassNames;
}
function getExternalServiceEntrypoints(allWorkerOpts) {
  const externalServices = /* @__PURE__ */ new Map();
  const allWorkerNames = allWorkerOpts.map((opts) => opts.config.name);
  const getEntrypoints = (name) => {
    let externalService = externalServices.get(name);
    if (!externalService) {
      externalService = {
        classNames: /* @__PURE__ */ new Set(),
        entrypoints: /* @__PURE__ */ new Set()
      };
      externalServices.set(name, externalService);
    }
    return externalService;
  };
  for (const workerOpts of allWorkerOpts) {
    const { config: config3, dev } = workerOpts;
    const tailConsumers = config3.tailConsumers;
    if (tailConsumers !== void 0) {
      for (let i = 0; i < tailConsumers.length; i++) {
        const consumer = tailConsumers[i];
        const serviceName = consumer.workerName;
        if (serviceName && !allWorkerNames.includes(serviceName)) {
          getEntrypoints(serviceName).entrypoints.add(consumer.entrypoint);
          tailConsumers[i] = {
            workerName: SERVICE_DEV_REGISTRY_PROXY,
            streaming: consumer.streaming,
            entrypoint: "ExternalServiceProxy",
            // User-supplied `props` are preserved in `userProps` so the proxy
            // can forward them to the remote entrypoint via the debug port.
            props: {
              service: serviceName,
              entrypoint: consumer.entrypoint ?? null,
              userProps: consumer.props
            }
          };
        }
      }
    }
    const env3 = config3.env;
    if (env3 === void 0) {
      continue;
    }
    for (const [name, binding] of getEnvBindingsOfType(config3, "worker")) {
      const { serviceName, entrypoint, props, remoteProxyConnectionString } = normaliseServiceDesignator(binding, dev);
      if (
        // Skip if it is a remote service
        remoteProxyConnectionString === void 0 && // Skip SELF (`kCurrentWorker`) and services bound to another Worker
        // defined in this Miniflare config
        serviceName && !allWorkerNames.includes(serviceName)
      ) {
        getEntrypoints(serviceName).entrypoints.add(entrypoint);
        env3[name] = {
          type: "worker",
          workerName: SERVICE_DEV_REGISTRY_PROXY,
          exportName: "ExternalServiceProxy",
          props: {
            service: serviceName,
            entrypoint: entrypoint ?? null,
            userProps: props
          }
        };
      }
    }
    for (const [bindingName, binding] of getEnvBindingsOfType(
      config3,
      "durable-object"
    )) {
      const { workerName, exportName } = binding;
      if (!allWorkerNames.includes(workerName)) {
        env3[bindingName] = {
          type: "durable-object",
          workerName: SERVICE_DEV_REGISTRY_PROXY,
          exportName: getOutboundDoProxyClassName(workerName, exportName)
        };
        getEntrypoints(workerName).classNames.add(exportName);
      }
    }
    for (const [, binding] of getEnvBindingsOfType(config3, "workflow")) {
      const { workerName, exportName } = binding;
      if (getRemoteProxyConnectionString(binding, dev) === void 0 && !allWorkerNames.includes(workerName)) {
        getEntrypoints(workerName).entrypoints.add(exportName);
      }
    }
  }
  return externalServices;
}
function getQueueProducers(allWorkerOpts) {
  const queueProducers = /* @__PURE__ */ new Map();
  for (const workerOpts of allWorkerOpts) {
    const workerName = workerOpts.config.name;
    for (const [bindingName, binding] of getEnvBindingsOfType(
      workerOpts.config,
      "queue"
    )) {
      queueProducers.set(bindingName, {
        workerName,
        queueName: binding.name ?? bindingName,
        deliveryDelay: binding.deliveryDelay
      });
    }
  }
  return queueProducers;
}
function getQueueConsumers(allWorkerOpts) {
  const queueConsumers = /* @__PURE__ */ new Map();
  for (const workerOpts of allWorkerOpts) {
    const workerName = workerOpts.config.name;
    for (const consumer of getTriggersOfType(workerOpts.config, "queue")) {
      const queueName = consumer.name;
      const existingConsumer = queueConsumers.get(queueName);
      if (existingConsumer !== void 0) {
        throw new QueuesError(
          "ERR_MULTIPLE_CONSUMERS",
          `Multiple consumers defined for queue "${queueName}": "${existingConsumer.workerName}" and "${workerName}"`
        );
      }
      queueConsumers.set(queueName, {
        workerName,
        maxBatchSize: consumer.maxBatchSize,
        maxBatchTimeout: consumer.maxBatchTimeout,
        maxRetries: consumer.maxRetries,
        deadLetterQueue: consumer.deadLetterQueue,
        retryDelay: consumer.retryDelay
      });
    }
  }
  for (const [queueName, consumer] of queueConsumers) {
    if (consumer.deadLetterQueue === queueName) {
      throw new QueuesError(
        "ERR_DEAD_LETTER_QUEUE_CYCLE",
        `Dead letter queue for queue "${queueName}" cannot be itself`
      );
    }
  }
  return queueConsumers;
}
function getWorkerRoutes(allWorkerOpts) {
  const allRoutes = /* @__PURE__ */ new Map();
  for (const workerOpts of allWorkerOpts) {
    const name = workerOpts.config.name;
    (0, import_node_assert21.default)(!allRoutes.has(name));
    allRoutes.set(
      name,
      getTriggersOfType(workerOpts.config, "fetch").map(
        (trigger) => trigger.pattern
      )
    );
  }
  return allRoutes;
}
function getProxyBindingName(plugin, worker, binding) {
  return [
    CoreBindings.DURABLE_OBJECT_NAMESPACE_PROXY,
    plugin,
    worker,
    binding
  ].join(":");
}
function isNativeTargetBinding(binding) {
  return !("json" in binding || "wasmModule" in binding || "text" in binding || "data" in binding);
}
function buildProxyBinding(plugin, worker, binding) {
  (0, import_node_assert21.default)(binding.name !== void 0);
  const name = getProxyBindingName(plugin, worker, binding.name);
  const proxyBinding = { ...binding, name };
  if ("durableObjectNamespace" in proxyBinding && proxyBinding.durableObjectNamespace !== void 0) {
    proxyBinding.durableObjectNamespace.serviceName ??= getUserServiceName(worker);
  }
  return proxyBinding;
}
function getInternalDurableObjectProxyBindings(plugin, service) {
  if (!("worker" in service)) return;
  (0, import_node_assert21.default)(service.worker !== void 0);
  const serviceName = service.name;
  (0, import_node_assert21.default)(serviceName !== void 0);
  return service.worker.durableObjectNamespaces?.map(({ className }) => {
    (0, import_node_assert21.default)(className !== void 0);
    return {
      name: getProxyBindingName(`${plugin}-internal`, serviceName, className),
      durableObjectNamespace: { serviceName, className }
    };
  });
}
var restrictedUndiciHeaders = [
  // From Miniflare 2:
  // https://github.com/cloudflare/miniflare/blob/9c135599dc21fe69080ada17fce6153692793bf1/packages/core/src/standards/http.ts#L129-L132
  "transfer-encoding",
  "connection",
  "keep-alive",
  "expect"
];
var restrictedWebSocketUpgradeHeaders = [
  "upgrade",
  "connection",
  "sec-websocket-accept"
];
function _transformsForContentEncodingAndContentType(encoding, type) {
  const encoders = [];
  if (!encoding) return encoders;
  if (!isCompressedByCloudflareFL(type)) return encoders;
  const codings = encoding.toLowerCase().split(",").map((x) => x.trim());
  for (const coding of codings) {
    if (/(x-)?gzip/.test(coding)) {
      encoders.push(import_node_zlib.default.createGzip());
    } else if (/(x-)?deflate/.test(coding)) {
      encoders.push(import_node_zlib.default.createDeflate());
    } else if (coding === "br") {
      encoders.push(import_node_zlib.default.createBrotliCompress());
    } else {
      encoders.length = 0;
      break;
    }
  }
  return encoders;
}
function safeReadableStreamFrom(iterable) {
  let iterator;
  return new import_web5.ReadableStream({
    async start() {
      iterator = iterable[Symbol.asyncIterator]();
    },
    // @ts-expect-error `pull` may return anything
    async pull(controller) {
      try {
        const { done, value } = await iterator.next();
        if (done) {
          queueMicrotask(() => controller.close());
        } else {
          const buf = Buffer.isBuffer(value) ? value : Buffer.from(value);
          controller.enqueue(new Uint8Array(buf));
        }
      } catch {
        queueMicrotask(() => controller.close());
      }
      return controller.desiredSize > 0;
    },
    async cancel() {
      await iterator.return?.();
    }
  });
}
function extractCustomService(customService) {
  const slashIndex = customService.indexOf("/");
  const workerIndex = parseInt(customService.substring(0, slashIndex));
  const serviceKind = customService[slashIndex + 1];
  const serviceName = customService.substring(slashIndex + 2);
  return { workerIndex, serviceKind, serviceName };
}
function getErrorMessage(error101) {
  if (error101 instanceof Error) {
    return error101.stack || error101.message;
  }
  if (typeof error101 === "string") {
    return error101;
  }
  try {
    return JSON.stringify(error101);
  } catch {
    return "Unknown error";
  }
}
var maybeInstanceRegistry;
function _initialiseInstanceRegistry() {
  return maybeInstanceRegistry = /* @__PURE__ */ new Map();
}
var Miniflare = class _Miniflare {
  #previousSharedOpts;
  #previousWorkerOpts;
  #sharedOpts;
  #workerOpts;
  #log;
  /**
   * externalPlugins is a list of external plugins that have been loaded
   * after being referenced by an unsafe binding
   */
  #externalPlugins = /* @__PURE__ */ new Map();
  // key is the browser session ID, value identifies the launched browser
  #browserProcesses = /* @__PURE__ */ new Map();
  #runtime;
  #removeExitHook;
  #runtimeEntryURL;
  publicUrl;
  #socketPorts;
  #runtimeDispatcher;
  #proxyClient;
  #runtimeRestartError;
  // Number of times workerd has crashed and been restarted for this instance.
  // Reported to the user so a repeatedly-crashing runtime is distinguishable
  // from a one-off, and so the restart isn't silent.
  #workerdCrashCount = 0;
  #cfObject = {};
  // Path to temporary directory for use as scratch space/"in-memory" Durable
  // Object storage. Note this may not exist, it's up to the consumers to
  // create this if needed. Deleted on `dispose()`.
  #tmpPath;
  // Mutual exclusion lock for runtime operations (i.e. initialisation and
  // updating config). This essentially puts initialisation and future updates
  // in a queue, ensuring they're performed in calling order.
  #runtimeMutex;
  // Store `#init()` `Promise`, so we can propagate initialisation errors in
  // `ready`. We would have no way of catching these otherwise.
  // eslint-disable-next-line no-unused-private-class-members -- oxlint is wrong here, this variable _is_ used
  #initPromise;
  // Aborted when dispose() is called
  #disposeController;
  #loopbackServer;
  #loopbackHost;
  #webSocketServer;
  #webSocketExtraHeaders;
  #devRegistry;
  #maybeInspectorProxyController;
  #previousRuntimeInspectorPort;
  #hyperdriveProxyController = new HyperdriveProxyController();
  // Set the first time the remote-bindings proxy CLIENT worker reports a
  // Cloudflare Access 403 block on a request to the remote-bindings proxy
  // server. Used to dedupe the user-facing warning to once per session.
  #warnedRemoteBindingsAccessBlock = false;
  constructor(opts) {
    const [sharedOpts, workerOpts] = validateOptions(opts);
    checkMacOSVersion({ shouldThrow: true });
    this.#sharedOpts = sharedOpts;
    this.#workerOpts = workerOpts;
    const workerNamesToProxy = this.#workerNamesToProxy();
    const enableInspectorProxy = workerNamesToProxy.size > 0;
    if (enableInspectorProxy) {
      if (this.#sharedOpts.inspectorPort === void 0) {
        throw new MiniflareCoreError(
          "ERR_MISSING_INSPECTOR_PROXY_PORT",
          "inspector proxy requested but without an inspectorPort specified"
        );
      }
    }
    if (maybeInstanceRegistry !== void 0) {
      const object3 = { name: "Miniflare", stack: "" };
      Error.captureStackTrace(object3, _Miniflare);
      maybeInstanceRegistry.set(this, object3.stack);
    }
    this.#log = this.#sharedOpts.log ?? new NoOpLog();
    this.#hyperdriveProxyController.log = this.#log;
    const inVscodeJsDebugTerminal = !!process.env.VSCODE_INSPECTOR_OPTIONS;
    if (enableInspectorProxy && !inVscodeJsDebugTerminal) {
      if (this.#sharedOpts.inspectorPort === void 0) {
        throw new MiniflareCoreError(
          "ERR_MISSING_INSPECTOR_PROXY_PORT",
          "inspector proxy requested but without an inspectorPort specified"
        );
      }
      this.#maybeInspectorProxyController = new InspectorProxyController(
        this.#sharedOpts.inspectorPort,
        this.#sharedOpts.inspectorHost,
        this.#log,
        workerNamesToProxy
      );
    }
    this.#webSocketServer = new import_ws6.WebSocketServer({
      noServer: true,
      // Disable automatic handling of `Sec-WebSocket-Protocol` header,
      // Cloudflare Workers require users to include this header themselves in
      // `Response`s: https://github.com/cloudflare/miniflare/issues/179
      handleProtocols: () => false
    });
    this.#webSocketExtraHeaders = /* @__PURE__ */ new WeakMap();
    this.#webSocketServer.on("headers", (headers, req) => {
      const extra = this.#webSocketExtraHeaders.get(req);
      this.#webSocketExtraHeaders.delete(req);
      if (extra) {
        for (const [key, value] of extra) {
          if (!restrictedWebSocketUpgradeHeaders.includes(key.toLowerCase())) {
            headers.push(`${key}: ${value}`);
          }
        }
      }
    });
    this.#devRegistry = new DevRegistry(
      this.#sharedOpts.unsafeDevRegistryPath,
      (registry3) => {
        void this.#pushRegistryUpdate();
        this.#sharedOpts.unsafeHandleDevRegistryUpdate?.(registry3);
      },
      this.#log
    );
    this.#tmpPath = import_node_path31.default.join(
      import_node_os12.default.tmpdir(),
      `miniflare-${import_node_crypto8.default.randomBytes(16).toString("hex")}`
    );
    this.#runtime = new Runtime();
    this.#removeExitHook = exitHook(() => {
      void this.#runtime?.dispose();
      try {
        removeDirSync(this.#tmpPath);
      } catch (e) {
        this.#log.debug(`Unable to remove temporary directory: ${String(e)}`);
      }
      const emailPaths = getEmailPathsToClean(
        this.#sharedOpts.resourceTmpPath,
        this.#tmpPath
      );
      if (emailPaths) {
        try {
          removeDirSync(emailPaths.sessionDir);
        } catch (e) {
          this.#log.debug(
            `Unable to remove email session directory: ${String(e)}`
          );
        }
      }
      this.#devRegistry.dispose();
    });
    this.#disposeController = new AbortController();
    this.#runtimeMutex = new Mutex();
    this.#initPromise = this.#runtimeMutex.runWith(() => this.#assembleAndUpdateConfig()).catch((e) => {
      maybeInstanceRegistry?.delete(this);
      throw e;
    });
  }
  #workerNamesToProxy() {
    return new Set(
      this.#workerOpts.filter((w) => !!w.dev?.unsafeInspectorProxy).map((w) => w.config.name)
    );
  }
  #handleReload() {
    for (const ws of this.#webSocketServer.clients) {
      ws.close(1012, "Service Restart");
    }
  }
  /**
   * Push updated registry data to the proxy worker via the entry socket.
   * This updates the in-memory registry Map without restarting workerd.
   * Called when the dev registry detects changes to external services.
   */
  #devRegistryDispatcher;
  #devRegistryPort;
  async #pushRegistryUpdate(retries = 3) {
    if (this.#disposeController.signal.aborted) return;
    if (!this.#devRegistryDispatcher) {
      return;
    }
    const registry3 = this.#devRegistry.getRegistry();
    try {
      const response = await this.#devRegistryDispatcher.request({
        origin: "http://127.0.0.1",
        path: "/",
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(registry3),
        signal: AbortSignal.timeout(2e3)
      });
      await response.body.dump();
      if (response.statusCode < 200 || response.statusCode >= 300) {
        this.#log.debug(`Registry push failed with ${response.statusCode}`);
        if (retries > 0) {
          await new Promise((r) => setTimeout(r, 500));
          return this.#pushRegistryUpdate(retries - 1);
        }
      }
    } catch (e) {
      this.#log.debug(
        `Failed to push registry update: ${e instanceof Error ? e.message : String(e)}`
      );
      if (retries > 0) {
        await new Promise((r) => setTimeout(r, 500));
        return this.#pushRegistryUpdate(retries - 1);
      }
    }
  }
  async #handleLoopbackCustomFetchService(request4, customService) {
    let handler;
    if (customService === CoreBindings.IMAGES_BINDING_SERVICE) {
      handler = imagesLocalFetcher;
    } else if (customService === CoreBindings.IMAGES_FETCH_SERVICE) {
      handler = cfImageLocalFetcher;
    } else {
      const { workerIndex, serviceKind, serviceName } = extractCustomService(customService);
      const workerOpts = this.#workerOpts[workerIndex];
      if (serviceKind === "#" /* UNKNOWN */) {
        const binding = workerOpts?.config.env?.[serviceName];
        if (binding?.type === "fetcher") {
          handler = binding.handler;
        }
      } else if (serviceName === CUSTOM_SERVICE_KNOWN_OUTBOUND) {
        const outbound = workerOpts?.dev?.outboundService;
        if (outbound?.type === "fetcher") {
          handler = outbound.handler;
        }
      }
    }
    (0, import_node_assert21.default)(typeof handler === "function");
    try {
      let response = await handler(request4, this);
      if (!(response instanceof Response3)) {
        response = new Response3(response.body, response);
      }
      return external_exports2.instanceof(Response3).parse(response);
    } catch (error101) {
      return new Response3(getErrorMessage(error101), { status: 500 });
    }
  }
  async #handleLoopbackCustomNodeService(req, res, customService) {
    let handler;
    const { workerIndex, serviceKind, serviceName } = extractCustomService(customService);
    if (serviceKind === "#" /* UNKNOWN */) {
      const binding = this.#workerOpts[workerIndex]?.config.env?.[serviceName];
      if (binding?.type === "node-handler") {
        handler = binding.handler;
      }
    } else if (serviceName === CUSTOM_SERVICE_KNOWN_OUTBOUND) {
      const outbound = this.#workerOpts[workerIndex]?.dev?.outboundService;
      if (outbound?.type === "node-handler") {
        handler = outbound.handler;
      }
    }
    (0, import_node_assert21.default)(typeof handler === "function");
    try {
      await handler(req, res, this);
    } catch (error101) {
      if (!res.headersSent) {
        res.writeHead(500);
      }
      res.end(getErrorMessage(error101));
    }
  }
  /**
   * Gets DO object IDs by checking filenames in the DO persistence directory.
   *
   * @param url in format: /core/do-storage/<namespaceId>
   * @returns [{ name: string, type: "file" | "directory" }, ...]
   */
  async #handleLoopbackDOStorageRequest(url46) {
    const namespaceId = decodeURIComponent(
      url46.pathname.slice("/core/do-storage/".length)
    );
    (0, import_node_assert21.default)(namespaceId, "Namespace ID is required");
    const coreSharedOpts = this.#sharedOpts;
    const doPersistPath = getPersistPath(
      DURABLE_OBJECTS_PLUGIN_NAME,
      this.#tmpPath,
      coreSharedOpts.resourcePersistencePath
    );
    const namespacePath = import_node_path31.default.join(doPersistPath, namespaceId);
    if (!namespacePath.startsWith(import_node_path31.default.resolve(doPersistPath) + import_node_path31.default.sep)) {
      return new Response3("Invalid namespace ID", { status: 400 });
    }
    try {
      const dirEntries = await import_node_fs21.default.promises.readdir(namespacePath, {
        withFileTypes: true
      });
      return Response3.json(
        dirEntries.map((entry) => ({
          name: entry.name,
          type: entry.isDirectory() ? "directory" : "file"
        }))
      );
    } catch (e) {
      if (isFileNotFoundError(e)) {
        return new Response3("Not Found", { status: 404 });
      }
      throw e;
    }
  }
  /**
   * Lists Workflow Engine DO instances by reading filenames from the
   * persistence directory. Same pattern as #handleLoopbackDOStorageRequest
   * but also includes mtimeMs for sorting by most recently modified.
   *
   * @param url in format: /core/workflow-storage/<workflowName>
   * @returns [{ name: string, type: "file" | "directory", mtimeMs: number }, ...]
   */
  async #handleLoopbackWorkflowStorageRequest(url46) {
    const workflowName = decodeURIComponent(
      url46.pathname.slice("/core/workflow-storage/".length)
    );
    (0, import_node_assert21.default)(workflowName, "Workflow name is required");
    const coreSharedOpts = this.#sharedOpts;
    const workflowsPersistPath = getPersistPath(
      WORKFLOWS_PLUGIN_NAME,
      this.#tmpPath,
      coreSharedOpts.resourcePersistencePath
    );
    const uniqueKey = `miniflare-workflows-${workflowName}`;
    const namespacePath = import_node_path31.default.join(workflowsPersistPath, uniqueKey);
    if (!namespacePath.startsWith(import_node_path31.default.resolve(workflowsPersistPath) + import_node_path31.default.sep)) {
      return new Response3("Invalid workflow name", { status: 400 });
    }
    try {
      const dirEntries = await import_node_fs21.default.promises.readdir(namespacePath, {
        withFileTypes: true
      });
      const entries = await Promise.all(
        dirEntries.map(async (entry) => {
          let birthtimeMs = 0;
          if (entry.isFile()) {
            try {
              const stat4 = await import_node_fs21.default.promises.stat(
                import_node_path31.default.join(namespacePath, entry.name)
              );
              birthtimeMs = stat4.birthtimeMs;
            } catch {
            }
          }
          return {
            name: entry.name,
            type: entry.isDirectory() ? "directory" : "file",
            birthtimeMs
          };
        })
      );
      return Response3.json(entries);
    } catch (e) {
      if (isFileNotFoundError(e)) {
        return new Response3("Not Found", { status: 404 });
      }
      throw e;
    }
  }
  /**
   * Deletes a Workflow Engine DO instance by removing its .sqlite file
   * (and any associated -shm/-wal files) from the persistence directory.
   *
   * @param url in format: /core/workflow-storage/<workflowName>/<hexId>
   */
  async #handleLoopbackWorkflowStorageDeleteRequest(url46) {
    const pathAfterPrefix = url46.pathname.slice(
      "/core/workflow-storage/".length
    );
    const slashIndex = pathAfterPrefix.indexOf("/");
    const workflowName = decodeURIComponent(
      slashIndex === -1 ? pathAfterPrefix : pathAfterPrefix.slice(0, slashIndex)
    );
    const hexId = slashIndex === -1 ? null : decodeURIComponent(pathAfterPrefix.slice(slashIndex + 1));
    (0, import_node_assert21.default)(workflowName, "Workflow name is required");
    const coreSharedOpts = this.#sharedOpts;
    const workflowsPersistPath = getPersistPath(
      WORKFLOWS_PLUGIN_NAME,
      this.#tmpPath,
      coreSharedOpts.resourcePersistencePath
    );
    const uniqueKey = `miniflare-workflows-${workflowName}`;
    const namespacePath = import_node_path31.default.join(workflowsPersistPath, uniqueKey);
    if (!namespacePath.startsWith(import_node_path31.default.resolve(workflowsPersistPath) + import_node_path31.default.sep)) {
      return new Response3("Invalid workflow name", { status: 400 });
    }
    const extensions = [".sqlite", ".sqlite-shm", ".sqlite-wal"];
    if (hexId) {
      let deleted = false;
      for (const ext of extensions) {
        const filePath = import_node_path31.default.join(namespacePath, `${hexId}${ext}`);
        if (!filePath.startsWith(namespacePath + import_node_path31.default.sep)) {
          return new Response3("Invalid instance ID", { status: 400 });
        }
        try {
          await import_node_fs21.default.promises.unlink(filePath);
          if (ext === ".sqlite") {
            deleted = true;
          }
        } catch (e) {
          if (!isFileNotFoundError(e)) {
            throw e;
          }
        }
      }
      if (!deleted) {
        return new Response3("Not Found", { status: 404 });
      }
    } else {
      try {
        const dirEntries = await import_node_fs21.default.promises.readdir(namespacePath);
        await Promise.all(
          dirEntries.filter((name) => extensions.some((ext) => name.endsWith(ext))).map(
            (name) => import_node_fs21.default.promises.unlink(import_node_path31.default.join(namespacePath, name)).catch(() => {
            })
          )
        );
      } catch (e) {
        if (!isFileNotFoundError(e)) {
          throw e;
        }
      }
    }
    return new Response3("OK", { status: 200 });
  }
  #handleLoopback = async (req, res) => {
    const customNodeService = req.headers[CoreHeaders.CUSTOM_NODE_SERVICE.toLowerCase()];
    if (typeof customNodeService === "string") {
      (0, import_node_assert21.default)(res);
      this.#handleLoopbackCustomNodeService(req, res, customNodeService);
      return;
    }
    const headers = new import_undici5.Headers();
    for (const [name, values] of Object.entries(req.headers)) {
      if (restrictedUndiciHeaders.includes(name)) continue;
      if (Array.isArray(values)) {
        for (const value of values) headers.append(name, value);
      } else if (values !== void 0) {
        headers.append(name, values);
      }
    }
    const cfBlob = headers.get(CoreHeaders.CF_BLOB);
    headers.delete(CoreHeaders.CF_BLOB);
    (0, import_node_assert21.default)(!Array.isArray(cfBlob));
    const cf = cfBlob ? JSON.parse(cfBlob) : void 0;
    const originalUrl = headers.get(CoreHeaders.ORIGINAL_URL);
    const url46 = new URL(originalUrl ?? req.url ?? "", "http://localhost");
    headers.delete(CoreHeaders.ORIGINAL_URL);
    const noBody = req.method === "GET" || req.method === "HEAD";
    const body = noBody ? void 0 : safeReadableStreamFrom(req);
    const request4 = new Request(url46, {
      method: req.method,
      headers,
      body,
      duplex: "half",
      cf
    });
    let response;
    try {
      const customFetchService = request4.headers.get(
        CoreHeaders.CUSTOM_FETCH_SERVICE
      );
      if (customFetchService !== null) {
        request4.headers.delete(CoreHeaders.CUSTOM_FETCH_SERVICE);
        response = await this.#handleLoopbackCustomFetchService(
          request4,
          customFetchService
        );
      } else if (url46.pathname === "/core/error") {
        response = await handlePrettyErrorRequest(
          this.#log,
          this.#workerOpts,
          request4,
          this.#sharedOpts.handleUncaughtError
        );
      } else if (url46.pathname === "/core/log") {
        const level = parseInt(
          request4.headers.get(SharedHeaders.LOG_LEVEL) ?? "NaN"
        );
        (0, import_node_assert21.default)(
          0 /* NONE */ <= level && level <= 5 /* VERBOSE */,
          `Expected ${SharedHeaders.LOG_LEVEL} header to be log level, got ${level}`
        );
        const logLevel = level;
        let message = await request4.text();
        if (!$2.enabled) message = stripAnsi(message);
        this.#log.logWithLevel(logLevel, message);
        response = new Response3(null, { status: 204 });
      } else if (url46.pathname === "/core/remote-bindings-access-warning") {
        if (!this.#warnedRemoteBindingsAccessBlock) {
          this.#warnedRemoteBindingsAccessBlock = true;
          const bindingName = request4.headers.get("MF-Binding") ?? "<unknown>";
          const proxyUrl = request4.headers.get("MF-Proxy-URL") ?? "<unknown>";
          const separator = dim3("\u2501".repeat(76));
          this.#log.warn(
            `
${separator}
${bold2(yellow3("Cloudflare Access blocked a remote bindings request"))}
${separator}

Remote binding "${bold2(bindingName)}": request to ${proxyUrl} was blocked.

If your Cloudflare account protects workers.dev with Access, set the
${bold2("CLOUDFLARE_ACCESS_CLIENT_ID")} and ${bold2("CLOUDFLARE_ACCESS_CLIENT_SECRET")}
environment variables (Service Token credentials), or run
  ${bold2("cloudflared access login <your-workers.dev-host>")}
for interactive authentication.

See https://developers.cloudflare.com/cloudflare-one/access-controls/service-credentials/service-tokens/
` + separator
          );
        }
        response = new Response3(null, { status: 204 });
      } else if (url46.pathname === "/browser/launch") {
        const headful = this.#workerOpts.some(
          (w) => getEnvBindingsOfType(w.config, "browser").some(
            ([, binding]) => "headful" in binding && binding.headful
          )
        );
        const { sessionId, browserProcess, startTime, wsEndpoint } = await launchBrowser({
          browserVersion: BROWSER_VERSION,
          log: this.#log,
          tmpPath: this.#tmpPath,
          headful
        });
        browserProcess.nodeProcess.on("exit", () => {
          this.#browserProcesses.delete(sessionId);
        });
        this.#browserProcesses.set(sessionId, {
          browserProcess,
          wsEndpoint
        });
        response = Response3.json({ wsEndpoint, sessionId, startTime });
      } else if (url46.pathname === "/browser/status") {
        const sessionId = url46.searchParams.get("sessionId");
        (0, import_node_assert21.default)(sessionId !== null, "Missing sessionId query parameter");
        const browser = this.#browserProcesses.get(sessionId);
        response = new Response3(null, { status: browser ? 200 : 410 });
      } else if (url46.pathname === "/browser/close") {
        const sessionId = url46.searchParams.get("sessionId");
        (0, import_node_assert21.default)(sessionId !== null, "Missing sessionId query parameter");
        const browser = this.#browserProcesses.get(sessionId);
        if (!browser) {
          response = new Response3("Session not found", { status: 404 });
        } else {
          this.#browserProcesses.delete(sessionId);
          await closeBrowserProcess(
            browser.browserProcess,
            browser.wsEndpoint
          ).catch(() => {
          });
          response = new Response3(null, { status: 200 });
        }
      } else if (url46.pathname === "/browser/sessionIds") {
        const sessionIds = this.#browserProcesses.keys();
        response = Response3.json(Array.from(sessionIds));
      } else if (url46.pathname === "/core/store-temp-file") {
        const prefix = url46.searchParams.get("prefix");
        const folder5 = prefix ? `files/${prefix}` : "files";
        await (0, import_promises24.mkdir)(import_node_path31.default.join(this.#tmpPath, folder5), { recursive: true });
        const filePath = import_node_path31.default.join(
          this.#tmpPath,
          folder5,
          `${import_node_crypto8.default.randomUUID()}.${url46.searchParams.get("extension") ?? "txt"}`
        );
        await (0, import_promises24.writeFile)(filePath, await request4.text());
        response = new Response3(filePath, { status: 200 });
      } else if (url46.pathname.startsWith("/core/do-storage/")) {
        response = await this.#handleLoopbackDOStorageRequest(url46);
      } else if (url46.pathname.startsWith("/core/workflow-storage/")) {
        if (request4.method === "DELETE") {
          response = await this.#handleLoopbackWorkflowStorageDeleteRequest(url46);
        } else {
          response = await this.#handleLoopbackWorkflowStorageRequest(url46);
        }
      } else if (url46.pathname === "/core/dev-registry") {
        const registryPath = this.#devRegistry.getRegistryPath();
        const registry3 = registryPath ? getWorkerRegistry(registryPath) : {};
        response = Response3.json(registry3);
      } else if (url46.pathname === "/core/public-url") {
        response = Response3.json(
          this.publicUrl ?? this.#runtimeEntryURL?.toString() ?? null
        );
      } else if (
        // Module fallback check MUST come after all known pathname handlers.
        // The V2 protocol (new_module_registry compat flag) uses POST requests,
        // which would otherwise match internal loopback requests from embedded
        // workers (e.g., POST to /core/log, /core/error, /core/store-temp-file).
        // By checking module fallback last, we ensure internal endpoints are
        // handled first, and only truly unmatched requests go to the fallback.
        this.#sharedOpts.unsafeModuleFallbackService !== void 0 && isModuleFallbackRequest(request4) && originalUrl === null
      ) {
        response = await this.#sharedOpts.unsafeModuleFallbackService(
          request4,
          this
        );
      }
    } catch (e) {
      this.#log.error(e);
      res?.writeHead(500);
      res?.end(e?.stack ?? String(e));
      return;
    }
    if (res !== void 0) {
      if (response === void 0) {
        res.writeHead(404);
        res.end();
      } else {
        await this.#writeResponse(response, res);
      }
    }
    return response;
  };
  #handleLoopbackUpgrade = async (req, socket, head) => {
    const response = await this.#handleLoopback(req);
    const webSocket = response?.webSocket;
    if (response?.status === 101 && webSocket) {
      this.#webSocketExtraHeaders.set(req, response.headers);
      this.#webSocketServer.handleUpgrade(req, socket, head, (ws) => {
        void coupleWebSocket(ws, webSocket);
        this.#webSocketServer.emit("connection", ws, req);
      });
      return;
    }
    const res = new import_node_http2.default.ServerResponse(req);
    (0, import_node_assert21.default)(socket instanceof import_node_net2.default.Socket);
    res.assignSocket(socket);
    if (!response || response.ok) {
      res.writeHead(500);
      res.end();
      this.#log.error(
        new TypeError(
          "Web Socket request did not return status 101 Switching Protocols response with Web Socket"
        )
      );
      return;
    }
    await this.#writeResponse(response, res);
  };
  async #writeResponse(response, res) {
    const headers = {};
    for (const entry of response.headers) {
      const key = entry[0].toLowerCase();
      const value = entry[1];
      if (key === "set-cookie") {
        headers[key] = response.headers.getSetCookie();
      } else {
        headers[key] = value;
      }
    }
    const encoding = headers["content-encoding"]?.toString();
    const type = headers["content-type"]?.toString();
    const encoders = _transformsForContentEncodingAndContentType(
      encoding,
      type
    );
    if (encoders.length > 0) {
      delete headers["content-length"];
    }
    res.writeHead(response.status, response.statusText, headers);
    let initialStream = res;
    for (let i = encoders.length - 1; i >= 0; i--) {
      encoders[i].pipe(initialStream);
      initialStream = encoders[i];
    }
    if (response.body) {
      try {
        for await (const chunk of response.body) {
          if (chunk) initialStream.write(chunk);
        }
      } catch (error101) {
        this.#log.debug(
          `Error writing response body, closing response early: ${error101}`
        );
      }
    }
    initialStream.end();
  }
  async #getLoopbackPort() {
    const configuredHost = this.#sharedOpts.host ?? DEFAULT_HOST;
    const loopbackHost = resolveLocalhost(configuredHost) ?? configuredHost;
    if (this.#loopbackServer !== void 0) {
      if (this.#loopbackHost === loopbackHost) {
        return getServerPort(this.#loopbackServer);
      }
      await this.#stopLoopbackServer();
    }
    this.#loopbackServer = await this.#startLoopbackServer(loopbackHost);
    this.#loopbackHost = loopbackHost;
    return getServerPort(this.#loopbackServer);
  }
  #startLoopbackServer(hostname5) {
    if (hostname5 === "*") hostname5 = "::";
    return new Promise((resolve8) => {
      const server = (0, import_stoppable.default)(
        import_node_http2.default.createServer(this.#handleLoopback),
        /* grace */
        0
      );
      server.keepAliveTimeout = 0;
      server.on("upgrade", this.#handleLoopbackUpgrade);
      server.listen(0, hostname5, () => resolve8(server));
    });
  }
  #stopLoopbackServer() {
    return new Promise((resolve8, reject) => {
      (0, import_node_assert21.default)(this.#loopbackServer !== void 0);
      this.#loopbackServer.stop((err) => err ? reject(err) : resolve8());
    });
  }
  #getSocketAddress(id, previousRequestedPort, host = DEFAULT_HOST, requestedPort, reusePort = false) {
    if (reusePort) {
      requestedPort = this.#socketPorts?.get(id) ?? requestedPort;
    }
    if (requestedPort === 0 && previousRequestedPort === 0) {
      requestedPort = this.#socketPorts?.get(id);
    }
    return `${getURLSafeHost(host)}:${requestedPort ?? 0}`;
  }
  /**
   * Load all external plugins referenced by any unsafe bindings, and store them on the class
   * Loaded plugins are preserved across runtime reloads, and so should only be loaded once per binding
   */
  async #loadExternalPlugins(workers) {
    const requestedExternalPlugins = /* @__PURE__ */ new Map();
    for (const worker of workers) {
      for (const binding of Object.values(worker.config.env ?? {})) {
        if ("dev" in binding && binding.dev?.plugin) {
          requestedExternalPlugins.set(
            binding.dev.plugin.name,
            binding.dev.plugin.package
          );
        }
      }
    }
    for (const [pluginName, packageName] of requestedExternalPlugins) {
      if (!this.#externalPlugins.has(pluginName)) {
        const providedPlugins = await loadExternalPlugins(packageName);
        if (!providedPlugins[pluginName]) {
          throw new MiniflareCoreError(
            "ERR_PLUGIN_LOADING_FAILED",
            `Package ${packageName} did not provide the plugin '${pluginName}'.`
          );
        }
        for (const [name, plugin] of Object.entries(providedPlugins)) {
          this.#externalPlugins.set(name, plugin);
        }
      }
    }
  }
  async #assembleConfig(loopbackHost, loopbackPort, devRegistryEnabled, reusePorts) {
    const allPreviousWorkerOpts = this.#previousWorkerOpts;
    const allWorkerOpts = this.#workerOpts;
    const sharedOpts = this.#sharedOpts;
    await this.#loadExternalPlugins(allWorkerOpts);
    sharedOpts.cf = await setupCf(this.#log, sharedOpts.cf);
    this.#cfObject = sharedOpts.cf;
    const externalServices = devRegistryEnabled ? getExternalServiceEntrypoints(allWorkerOpts) : null;
    const durableObjectClassNames = getDurableObjectClassNames(allWorkerOpts);
    const queueProducers = getQueueProducers(allWorkerOpts);
    const queueConsumers = getQueueConsumers(allWorkerOpts);
    const hasQueues = queueProducers.size > 0 || queueConsumers.size > 0;
    const allWorkerRoutes = getWorkerRoutes(allWorkerOpts);
    const workerNames = [...allWorkerRoutes.keys()];
    const services = /* @__PURE__ */ new Map();
    const extensions = [
      {
        modules: [
          { name: "miniflare:shared", esModule: index_worker_default() },
          { name: "miniflare:zod", esModule: zod_worker_default() }
        ]
      }
    ];
    const sockets = [
      {
        name: SOCKET_ENTRY,
        service: { name: SERVICE_ENTRY },
        ...await getEntrySocketHttpOptions(sharedOpts)
      }
    ];
    const configuredHost = sharedOpts.host ?? DEFAULT_HOST;
    if (maybeGetLocallyAccessibleHost(configuredHost) === void 0) {
      sockets.push({
        name: SOCKET_ENTRY_LOCAL,
        service: { name: SERVICE_ENTRY },
        http: {},
        address: this.#getSocketAddress(
          SOCKET_ENTRY_LOCAL,
          void 0,
          "127.0.0.1",
          void 0,
          reusePorts
        )
      });
    }
    const proxyBindings = [];
    for (const [, plugin] of this.#mergedPluginEntries) {
      const pluginExtensions = await plugin.getExtensions?.({
        options: allWorkerOpts
      });
      if (pluginExtensions) {
        extensions.push(...pluginExtensions);
      }
    }
    for (let workerIndex = 0; workerIndex < allWorkerOpts.length; workerIndex++) {
      const previousWorkerOpts = allPreviousWorkerOpts?.[workerIndex];
      const workerOpts = allWorkerOpts[workerIndex];
      const workerName = workerOpts.config.name;
      const isModulesWorker = workerOpts.legacy?.serviceWorkerScript === void 0;
      const workerBindings = [];
      const additionalModules = [];
      for (const [key, plugin] of this.#mergedPluginEntries) {
        const pluginBindings = await plugin.getBindings(
          workerOpts,
          workerIndex
        );
        if (pluginBindings !== void 0) {
          for (const binding of pluginBindings) {
            if (key === "kv" && binding.name === SiteBindings.JSON_SITE_MANIFEST && isModulesWorker) {
              (0, import_node_assert21.default)("json" in binding && binding.json !== void 0);
              additionalModules.push({
                name: SiteBindings.JSON_SITE_MANIFEST,
                text: binding.json
              });
            } else {
              workerBindings.push(binding);
            }
            if (isNativeTargetBinding(binding)) {
              proxyBindings.push(buildProxyBinding(key, workerName, binding));
            }
            if ("service" in binding) {
              const targetWorkerName = binding.service?.name?.replace(
                "core:user:",
                ""
              );
              const maybeAssetTargetService = allWorkerOpts.find(
                (worker) => worker.config.name === targetWorkerName && worker.config.assets
              );
              if (maybeAssetTargetService && !binding.service?.entrypoint) {
                (0, import_node_assert21.default)(binding.service?.name);
                binding.service.name = `${RPC_PROXY_SERVICE_NAME}:${targetWorkerName}`;
              }
            }
          }
        }
      }
      const unsafeEphemeralDurableObjects = workerOpts.dev?.unsafeEphemeralDurableObjects ?? false;
      this.publicUrl = sharedOpts.publicUrl;
      const pluginServicesOptionsBase = {
        log: this.#log,
        workerBindings,
        workerIndex,
        additionalModules,
        tmpPath: this.#tmpPath,
        workerNames,
        loopbackHost,
        loopbackPort,
        durableObjectClassNames,
        unsafeEphemeralDurableObjects,
        queueProducers,
        queueConsumers,
        devRegistryEnabled,
        hyperdriveProxyController: this.#hyperdriveProxyController
      };
      for (const [key, plugin] of this.#mergedPluginEntries) {
        const pluginServicesExtensions = await plugin.getServices({
          ...pluginServicesOptionsBase,
          options: workerOpts,
          sharedOptions: sharedOpts
        });
        if (pluginServicesExtensions !== void 0) {
          let pluginServices;
          if (Array.isArray(pluginServicesExtensions)) {
            pluginServices = pluginServicesExtensions;
          } else {
            pluginServices = pluginServicesExtensions.services;
            extensions.push(...pluginServicesExtensions.extensions);
          }
          for (const service of pluginServices) {
            if (service.name !== void 0 && !services.has(service.name)) {
              services.set(service.name, service);
              if (key !== DURABLE_OBJECTS_PLUGIN_NAME) {
                const maybeBindings = getInternalDurableObjectProxyBindings(
                  key,
                  service
                );
                if (maybeBindings !== void 0) {
                  proxyBindings.push(...maybeBindings);
                }
              }
            }
          }
        }
      }
      const previousDirectSockets = previousWorkerOpts?.dev?.unsafeDirectSockets ?? [];
      const directSockets = workerOpts.dev?.unsafeDirectSockets ?? [];
      for (let i = 0; i < directSockets.length; i++) {
        const previousDirectSocket = previousDirectSockets[i];
        const directSocket = directSockets[i];
        const serviceName = directSocket.serviceName ?? workerName;
        const entrypoint = directSocket.entrypoint ?? "default";
        const name = getDirectSocketName(workerIndex, entrypoint);
        const address = this.#getSocketAddress(
          name,
          previousDirectSocket?.port,
          directSocket.host,
          directSocket.port,
          reusePorts
        );
        const service = workerOpts.config.assets && entrypoint === "default" ? {
          name: `${RPC_PROXY_SERVICE_NAME}:${workerOpts.config.name}`
        } : {
          name: getUserServiceName(serviceName),
          entrypoint: entrypoint === "default" ? void 0 : entrypoint
        };
        sockets.push({
          name,
          address,
          service,
          http: {
            style: directSocket.proxy ? HttpOptions_Style.PROXY : void 0,
            cfBlobHeader: CoreHeaders.CF_BLOB,
            capnpConnectHost: HOST_CAPNP_CONNECT
          }
        });
      }
    }
    if (this.#devRegistry.isEnabled() && externalServices && (externalServices.size > 0 || hasQueues)) {
      await this.#devRegistry.watch(externalServices, hasQueues);
      const externalObjects = Array.from(externalServices).flatMap(
        ([scriptName, { classNames }]) => Array.from(classNames).map((className) => [
          scriptName,
          className
        ])
      );
      const initialRegistry = this.#devRegistry.getRegistry();
      const mainModuleSource = [
        `import { ExternalQueueProxy, ExternalServiceProxy, setRegistry, createProxyDurableObjectClass } from "./dev-registry-proxy.worker.js";`,
        `export { ExternalQueueProxy, ExternalServiceProxy };`,
        `setRegistry(${JSON.stringify(initialRegistry)});`,
        `export default {`,
        `  async fetch(request, env) {`,
        `    if (request.method === "POST") {`,
        `      const data = await request.json();`,
        `      setRegistry(data);`,
        `      return new Response("ok");`,
        `    }`,
        `    return new Response("not found", { status: 404 });`,
        `  }`,
        `};`,
        ...externalObjects.map(
          ([scriptName, className]) => `export const ${getOutboundDoProxyClassName(
            scriptName,
            className
          )} = createProxyDurableObjectClass({ scriptName: ${JSON.stringify(
            scriptName
          )}, className: ${JSON.stringify(className)} });`
        )
      ].join("\n");
      services.set(getUserServiceName(SERVICE_DEV_REGISTRY_PROXY), {
        name: getUserServiceName(SERVICE_DEV_REGISTRY_PROXY),
        worker: {
          compatibilityDate: "2025-01-01",
          compatibilityFlags: ["service_binding_extra_handlers"],
          modules: [
            {
              name: "main.mjs",
              esModule: mainModuleSource
            },
            {
              name: "dev-registry-proxy.worker.js",
              esModule: dev_registry_proxy_worker_default()
            }
          ],
          bindings: [
            {
              name: CoreBindings.DEV_REGISTRY_DEBUG_PORT,
              // workerdDebugPort bindings don't have any additional configuration
              workerdDebugPort: kVoid
            }
          ],
          durableObjectStorage: { inMemory: kVoid },
          // uniqueKey must match the target session's key for identical DO IDs.
          durableObjectNamespaces: externalObjects.map(
            ([scriptName, className]) => ({
              className: getOutboundDoProxyClassName(scriptName, className),
              uniqueKey: `${scriptName}-${className}`
            })
          )
        }
      });
      sockets.push({
        name: SOCKET_DEV_REGISTRY,
        address: "127.0.0.1:0",
        service: { name: getUserServiceName(SERVICE_DEV_REGISTRY_PROXY) },
        http: {}
      });
    }
    const globalServices = getGlobalServices({
      sharedOptions: sharedOpts,
      allWorkerRoutes,
      /*
       * - if Workers + Assets project but NOT Vitest, the fallback Worker (see
       *   `MINIFLARE_USER_FALLBACK`) should point to the (assets) RPC Proxy Worker
       * - if Vitest with assets, the fallback Worker should point to the Vitest
       *   runner Worker, while the SELF binding on the test runner will point to
       *   the (assets) RPC Proxy Worker
       */
      fallbackWorkerName: this.#workerOpts[0].config.assets && !this.#workerOpts[0].config.name.startsWith(
        "vitest-pool-workers-runner-"
      ) ? `${RPC_PROXY_SERVICE_NAME}:${this.#workerOpts[0].config.name}` : getUserServiceName(this.#workerOpts[0].config.name),
      tmpPath: this.#tmpPath,
      log: this.#log,
      proxyBindings,
      durableObjectClassNames,
      allWorkerOpts
    });
    for (const service of globalServices) {
      (0, import_node_assert21.default)(service.name !== void 0 && !services.has(service.name));
      services.set(service.name, service);
    }
    const servicesArray = Array.from(services.values());
    return {
      services: servicesArray,
      sockets,
      extensions,
      // Structured logging is always enabled: workerd emits structured logs
      // that Miniflare parses and either forwards to a `handleStructuredLogs`
      // handler or writes to the console by default.
      structuredLogging: true,
      autogates: process.env.MINIFLARE_WORKERD_AUTOGATES ? process.env.MINIFLARE_WORKERD_AUTOGATES.split(" ") : [],
      v8Flags: process.env.MINIFLARE_WORKERD_V8_FLAGS ? process.env.MINIFLARE_WORKERD_V8_FLAGS.split(" ") : []
    };
  }
  #handleWorkerdCrash() {
    this.#workerdCrashCount++;
    this.#log.warn(
      `The Workers runtime crashed unexpectedly and is being restarted (crash #${this.#workerdCrashCount}). Any additional runtime output above may indicate the cause.`
    );
    this.#proxyClient?.poisonProxies();
    void this.#runtimeMutex.runWith(async () => {
      try {
        await this.#assembleAndUpdateConfig(true);
      } catch (error101) {
        this.#devRegistry.unregisterWorkers();
        const cause = error101 instanceof Error ? error101 : new Error(String(error101));
        this.#runtimeRestartError = new MiniflareCoreError(
          "ERR_RUNTIME_FAILURE",
          "The Workers runtime failed to restart after an unexpected crash.",
          cause
        );
        throw this.#runtimeRestartError;
      }
    }).then(
      async () => {
        if (this.#disposeController.signal.aborted) {
          return;
        }
        try {
          await this.#sharedOpts.unsafeHandleRuntimeRestart?.();
        } catch (error101) {
          const cause = error101 instanceof Error ? error101 : new Error(String(error101));
          this.#log.error(
            new Error(
              "The Workers runtime restarted, but the runtime restart callback failed.",
              { cause }
            )
          );
        }
      },
      (error101) => {
        if (this.#disposeController.signal.aborted) {
          return;
        }
        this.#log.error(
          error101 instanceof Error ? error101 : new Error(String(error101))
        );
      }
    );
  }
  async #assembleAndUpdateConfig(reusePorts = false) {
    await this.#closeBrowserProcesses();
    const initial = !this.#runtimeEntryURL;
    (0, import_node_assert21.default)(this.#runtime !== void 0);
    const configuredHost = this.#sharedOpts.host ?? DEFAULT_HOST;
    const loopbackHost = resolveLocalhost(configuredHost) ?? maybeGetLocallyAccessibleHost(configuredHost) ?? getURLSafeHost(configuredHost);
    const loopbackPort = await this.#getLoopbackPort();
    const config3 = await this.#assembleConfig(
      loopbackHost,
      loopbackPort,
      this.#devRegistry.isEnabled(),
      reusePorts
    );
    const configBuffer = serializeConfig(config3);
    (0, import_node_assert21.default)(config3.sockets !== void 0);
    const requiredSockets = config3.sockets.map(
      ({ name }) => {
        (0, import_node_assert21.default)(name !== void 0);
        return name;
      }
    );
    if (this.#sharedOpts.inspectorPort !== void 0) {
      requiredSockets.push(kInspectorSocket);
    }
    if (this.#devRegistry.isEnabled()) {
      requiredSockets.push(SOCKET_DEBUG_PORT);
    }
    const entryAddress = this.#getSocketAddress(
      SOCKET_ENTRY,
      this.#previousSharedOpts?.port,
      configuredHost,
      this.#sharedOpts.port,
      reusePorts
    );
    let runtimeInspectorAddress;
    if (this.#sharedOpts.inspectorPort !== void 0) {
      let runtimeInspectorPort = this.#sharedOpts.inspectorPort;
      if (this.#maybeInspectorProxyController !== void 0) {
        runtimeInspectorPort = 0;
      }
      runtimeInspectorAddress = this.#getSocketAddress(
        kInspectorSocket,
        this.#previousRuntimeInspectorPort,
        // Use "127.0.0.1" explicitly instead of "localhost" to avoid
        // DNS resolution issues. On systems where getaddrinfo("localhost")
        // returns ::1 but IPv6 is disabled, workerd fails to bind the
        // inspector socket and silently continues without emitting the
        // listen-inspector event, causing waitForPorts() to hang.
        // See https://github.com/cloudflare/workers-sdk/issues/14077
        "127.0.0.1",
        runtimeInspectorPort,
        reusePorts
      );
      this.#previousRuntimeInspectorPort = runtimeInspectorPort;
    }
    const loopbackAddress = `${loopbackHost}:${loopbackPort}`;
    const runtimeOpts = {
      signal: this.#disposeController.signal,
      entryAddress,
      loopbackAddress,
      requiredSockets,
      inspectorAddress: runtimeInspectorAddress,
      debugPortAddress: this.#devRegistry.isEnabled() ? "127.0.0.1:0" : void 0,
      verbose: this.#sharedOpts.verbose,
      handleStructuredLogs: this.#sharedOpts.handleStructuredLogs,
      onWorkerdCrashRestart: () => this.#handleWorkerdCrash(),
      runtimeEnv: this.#sharedOpts.unsafeRuntimeEnv
    };
    const maybeSocketPorts = await this.#runtime.updateConfig(
      configBuffer,
      runtimeOpts,
      this.#workerOpts.map((w) => w.config.name),
      this.#disposeController.signal
    );
    if (this.#disposeController.signal.aborted) return;
    if (maybeSocketPorts === void 0) {
      throw new MiniflareCoreError(
        "ERR_RUNTIME_FAILURE",
        "The Workers runtime failed to start. There is likely additional logging output above."
      );
    }
    this.#socketPorts = maybeSocketPorts;
    if (this.#maybeInspectorProxyController !== void 0 && this.#sharedOpts.inspectorPort !== void 0) {
      const maybePort = this.#socketPorts.get(kInspectorSocket);
      if (maybePort === void 0) {
        throw new MiniflareCoreError(
          "ERR_RUNTIME_FAILURE",
          "Unable to access the runtime inspector socket."
        );
      } else {
        await this.#maybeInspectorProxyController.updateConnection(
          this.#sharedOpts.inspectorPort,
          this.#sharedOpts.inspectorHost ?? "127.0.0.1",
          maybePort,
          this.#workerNamesToProxy()
        );
      }
    }
    const entrySocket = config3.sockets?.[0];
    const secure = entrySocket !== void 0 && "https" in entrySocket;
    const previousEntryURL = this.#runtimeEntryURL;
    const entryPort = maybeSocketPorts.get(SOCKET_ENTRY);
    (0, import_node_assert21.default)(entryPort !== void 0);
    const maybeAccessibleHost = maybeGetLocallyAccessibleHost(configuredHost);
    if (maybeAccessibleHost === void 0) {
      const localEntryPort = maybeSocketPorts.get(SOCKET_ENTRY_LOCAL);
      (0, import_node_assert21.default)(localEntryPort !== void 0, "Expected local entry socket port");
      this.#runtimeEntryURL = new URL(`http://127.0.0.1:${localEntryPort}`);
    } else {
      this.#runtimeEntryURL = new URL(
        `${secure ? "https" : "http"}://${maybeAccessibleHost}:${entryPort}`
      );
    }
    if (previousEntryURL?.toString() !== this.#runtimeEntryURL.toString()) {
      void this.#runtimeDispatcher?.close().catch(() => {
      });
      this.#runtimeDispatcher = new import_undici8.Pool(this.#runtimeEntryURL, {
        connect: { rejectUnauthorized: false },
        // Disable timeouts for local dev — long-running responses (streaming,
        // slow uploads, long-polling) should not be killed by undici defaults.
        headersTimeout: 0,
        bodyTimeout: 0
      });
    }
    const devRegistryPort = maybeSocketPorts.get(SOCKET_DEV_REGISTRY);
    if (devRegistryPort !== this.#devRegistryPort) {
      void this.#devRegistryDispatcher?.close().catch(() => {
      });
      this.#devRegistryPort = devRegistryPort;
      if (devRegistryPort !== void 0) {
        this.#devRegistryDispatcher = new import_undici8.Pool(
          new URL(`http://127.0.0.1:${devRegistryPort}`)
        );
      } else {
        this.#devRegistryDispatcher = void 0;
      }
    }
    if (this.#proxyClient === void 0) {
      this.#proxyClient = new ProxyClient(
        this.#runtimeEntryURL,
        this.dispatchFetch
      );
    } else {
      this.#proxyClient.setRuntimeEntryURL(this.#runtimeEntryURL);
    }
    await this.#registerWorkers();
    if (this.#devRegistry.isEnabled()) {
      await this.#pushRegistryUpdate();
    }
    if (!this.#runtimeMutex.hasWaiting) {
      const ready = initial ? "Ready" : "Updated and ready";
      const urlSafeHost = getURLSafeHost(configuredHost);
      if (this.#sharedOpts.logRequests) {
        this.#log.logReady(
          `${ready} on ${green3(
            `${secure ? "https" : "http"}://${urlSafeHost}:${entryPort}`
          )}`
        );
      }
      if (initial && this.#sharedOpts.logRequests) {
        const hosts = [];
        if (configuredHost === "::" || configuredHost === "*") {
          hosts.push("localhost");
          hosts.push("[::1]");
        }
        if (configuredHost === "::" || configuredHost === "*" || configuredHost === "0.0.0.0") {
          hosts.push(...getAccessibleHosts(true));
        }
        for (const h of hosts) {
          this.#log.logReady(
            `- ${secure ? "https" : "http"}://${h}:${entryPort}`
          );
        }
      }
      this.#handleReload();
    }
    this.#runtimeRestartError = void 0;
  }
  async #closeBrowserProcesses() {
    const browsers = Array.from(this.#browserProcesses.values());
    this.#browserProcesses.clear();
    await Promise.all(
      browsers.map(
        ({ browserProcess, wsEndpoint }) => closeBrowserProcess(browserProcess, wsEndpoint)
      )
    );
  }
  async #waitForReady(disposing = false) {
    await this.#initPromise;
    await this.#runtimeMutex.drained();
    if (!disposing && this.#runtimeRestartError !== void 0) {
      throw this.#runtimeRestartError;
    }
    if (disposing) return new URL("http://[100::]/");
    await this.#maybeInspectorProxyController?.ready;
    this.#checkDisposed();
    (0, import_node_assert21.default)(this.#runtimeEntryURL !== void 0);
    return new URL(this.#runtimeEntryURL.toString());
  }
  async #registerWorkers() {
    if (!this.#devRegistry.isEnabled()) {
      return;
    }
    const debugPort = this.#socketPorts?.get(SOCKET_DEBUG_PORT);
    if (debugPort === void 0) {
      this.#log.warn(
        "Debug port not available \u2014 skipping dev registry registration"
      );
      this.#devRegistry.unregisterWorkers();
      return;
    }
    const debugPortAddress = `127.0.0.1:${debugPort}`;
    (0, import_node_assert21.default)(
      this.#runtimeEntryURL !== void 0,
      "Runtime entry URL must be set before registering workers"
    );
    const entries = [];
    for (const workerOpts of this.#workerOpts) {
      const workerName = workerOpts.config.name;
      if (!workerName || !workerOpts.dev?.unsafeRegisterWorker) {
        continue;
      }
      let defaultEntrypointService;
      if (workerOpts.dev?.unsafeOverrideFetchWorker) {
        defaultEntrypointService = getUserServiceName(
          workerOpts.dev.unsafeOverrideFetchWorker
        );
      } else if (workerOpts.config.assets) {
        defaultEntrypointService = `${RPC_PROXY_SERVICE_NAME}:${workerName}`;
      } else {
        defaultEntrypointService = getUserServiceName(workerName);
      }
      const queueConsumers = getTriggersOfType(workerOpts.config, "queue").map(
        (trigger) => trigger.name
      );
      entries.push([
        workerName,
        {
          debugPortAddress,
          defaultEntrypointService,
          userWorkerService: getUserServiceName(workerName),
          ...queueConsumers.length > 0 ? { queueConsumers } : {}
        }
      ]);
    }
    this.#devRegistry.register(Object.fromEntries(entries));
  }
  get ready() {
    return this.#waitForReady();
  }
  async getCf() {
    this.#checkDisposed();
    await this.ready;
    return JSON.parse(JSON.stringify(this.#cfObject));
  }
  async getInspectorURL() {
    this.#checkDisposed();
    await this.ready;
    if (this.#maybeInspectorProxyController !== void 0) {
      return this.#maybeInspectorProxyController.getInspectorURL();
    }
    (0, import_node_assert21.default)(this.#socketPorts !== void 0);
    const maybePort = this.#socketPorts.get(kInspectorSocket);
    if (maybePort === void 0) {
      throw new TypeError(
        "Inspector not enabled in Miniflare instance. Set the `inspectorPort` option to enable it."
      );
    }
    return new URL(`ws://127.0.0.1:${maybePort}`);
  }
  async unsafeGetDirectURL(workerName, entrypoint = "default") {
    this.#checkDisposed();
    await this.#waitForReady();
    const workerIndex = this.#findAndAssertWorkerIndex(workerName);
    const workerOpts = this.#workerOpts[workerIndex];
    const socketName = getDirectSocketName(workerIndex, entrypoint);
    (0, import_node_assert21.default)(this.#socketPorts !== void 0);
    const maybePort = this.#socketPorts.get(socketName);
    if (maybePort === void 0) {
      const friendlyWorkerName = workerName === void 0 ? "entrypoint" : JSON.stringify(workerName);
      const friendlyEntrypointName = entrypoint === "default" ? entrypoint : JSON.stringify(entrypoint);
      throw new TypeError(
        `Direct access disabled in ${friendlyWorkerName} worker for ${friendlyEntrypointName} entrypoint`
      );
    }
    const directSocket = workerOpts.dev?.unsafeDirectSockets?.find(
      (socket) => (socket.entrypoint ?? "default") === entrypoint
    );
    (0, import_node_assert21.default)(directSocket !== void 0);
    const host = directSocket.host ?? DEFAULT_HOST;
    const accessibleHost = maybeGetLocallyAccessibleHost(host) ?? getURLSafeHost(host);
    return new URL(`http://${accessibleHost}:${maybePort}`);
  }
  #checkDisposed() {
    if (this.#disposeController.signal.aborted) {
      throw new MiniflareCoreError(
        "ERR_DISPOSED",
        "Cannot use disposed instance"
      );
    }
  }
  async #setOptions(opts) {
    const [sharedOpts, workerOpts] = validateOptions(opts);
    this.#previousSharedOpts = this.#sharedOpts;
    this.#previousWorkerOpts = this.#workerOpts;
    this.#sharedOpts = sharedOpts;
    this.#workerOpts = workerOpts;
    this.#log = this.#sharedOpts.log ?? this.#log;
    this.#hyperdriveProxyController.log = this.#log;
    const newExternalOnUpdate = sharedOpts.unsafeHandleDevRegistryUpdate;
    await this.#devRegistry.updateRegistryPath(
      sharedOpts.unsafeDevRegistryPath,
      (registry3) => {
        void this.#pushRegistryUpdate();
        newExternalOnUpdate?.(registry3);
      }
    );
    try {
      await this.#assembleAndUpdateConfig();
    } catch (error101) {
      this.#devRegistry.unregisterWorkers();
      throw error101;
    }
  }
  setOptions(opts) {
    this.#checkDisposed();
    this.#proxyClient?.poisonProxies();
    return this.#runtimeMutex.runWith(() => this.#setOptions(opts));
  }
  dispatchFetch = async (input, init3) => {
    this.#checkDisposed();
    await this.ready;
    (0, import_node_assert21.default)(this.#runtimeEntryURL !== void 0);
    (0, import_node_assert21.default)(this.#runtimeDispatcher !== void 0);
    const forward = new Request(input, init3);
    const url46 = new URL(forward.url);
    const actualRuntimeOrigin = this.#runtimeEntryURL.origin;
    const userRuntimeOrigin = url46.origin;
    url46.protocol = this.#runtimeEntryURL.protocol;
    url46.host = this.#runtimeEntryURL.host;
    if (forward.body !== null && forward.headers.get("Content-Length") === "0") {
      forward.headers.delete("Content-Length");
    }
    const cfBlob = forward.cf ? { ...fallbackCf, ...forward.cf } : void 0;
    const dispatcher = new DispatchFetchDispatcher(
      (0, import_undici8.getGlobalDispatcher)(),
      this.#runtimeDispatcher,
      actualRuntimeOrigin,
      userRuntimeOrigin,
      cfBlob
    );
    const forwardInit = forward;
    forwardInit.dispatcher = dispatcher;
    const response = await fetch5(url46, forwardInit);
    const stack = response.headers.get(CoreHeaders.ERROR_STACK);
    if (response.status === 500 && stack !== null) {
      const serialised = await response.text() || decodeErrorPayload(response);
      if (serialised === null) {
        throw new Error("Worker threw an uncaught exception");
      }
      const caught = JsonErrorSchema.parse(JSON.parse(serialised));
      throw reviveError(this.#workerOpts, caught);
    }
    const contentEncoding = response.headers.get("Content-Encoding");
    if (contentEncoding)
      response.headers.set("MF-Content-Encoding", contentEncoding);
    response.headers.delete("Content-Encoding");
    if (process.env.MINIFLARE_ASSERT_BODIES_CONSUMED === "true" && response.body !== null) {
      const originalLimit = Error.stackTraceLimit;
      Error.stackTraceLimit = Infinity;
      const error101 = new Error(
        "`body` returned from `Miniflare#dispatchFetch()` not consumed immediately"
      );
      Error.stackTraceLimit = originalLimit;
      setImmediate(() => {
        if (!response.bodyUsed) throw error101;
      });
    }
    return response;
  };
  /** @internal */
  async _getProxyClient() {
    this.#checkDisposed();
    await this.ready;
    (0, import_node_assert21.default)(this.#proxyClient !== void 0);
    return this.#proxyClient;
  }
  #findAndAssertWorkerIndex(workerName) {
    if (workerName === void 0) {
      return 0;
    } else {
      const index = this.#workerOpts.findIndex(
        ({ config: config3 }) => config3.name === workerName
      );
      if (index === -1) {
        throw new TypeError(`${JSON.stringify(workerName)} worker not found`);
      }
      return index;
    }
  }
  async getBindings(workerName) {
    const bindings = {};
    const proxyClient = await this._getProxyClient();
    const workerIndex = this.#findAndAssertWorkerIndex(workerName);
    const workerOpts = this.#workerOpts[workerIndex];
    workerName = workerOpts.config.name;
    for (const [key, plugin] of this.#mergedPluginEntries) {
      const pluginBindings = await plugin.getNodeBindings(workerOpts);
      for (const [name, binding] of Object.entries(pluginBindings)) {
        if (binding instanceof ProxyNodeBinding) {
          const proxyBindingName = getProxyBindingName(key, workerName, name);
          let proxy = proxyClient.env[proxyBindingName];
          (0, import_node_assert21.default)(
            proxy !== void 0,
            `Expected ${proxyBindingName} to be bound`
          );
          if (binding.proxyOverrideHandler) {
            proxy = new Proxy(proxy, binding.proxyOverrideHandler);
          }
          bindings[name] = proxy;
        } else {
          bindings[name] = binding;
        }
      }
    }
    return bindings;
  }
  async getWorker(workerName) {
    const proxyClient = await this._getProxyClient();
    const workerIndex = this.#findAndAssertWorkerIndex(workerName);
    const workerOpts = this.#workerOpts[workerIndex];
    workerName = workerOpts.config.name;
    const bindingName = CoreBindings.SERVICE_USER_ROUTE_PREFIX + workerName;
    const fetcher = proxyClient.env[bindingName];
    (0, import_node_assert21.default)(
      fetcher !== void 0,
      `Expected ${bindingName} service binding for worker ${JSON.stringify(workerName)}`
    );
    return fetcher;
  }
  async #getProxy(pluginName, bindingName, workerName) {
    const proxyClient = await this._getProxyClient();
    const resolvedWorkerName = workerName ?? this.#workerOpts[0].config.name;
    const proxyBindingName = getProxyBindingName(
      pluginName,
      resolvedWorkerName,
      bindingName
    );
    const proxy = proxyClient.env[proxyBindingName];
    if (proxy === void 0) {
      const friendlyWorkerName = resolvedWorkerName ? `${JSON.stringify(resolvedWorkerName)} worker` : "the worker";
      const bindingTypeDescription = Object.fromEntries(
        this.#mergedPluginEntries
      )[pluginName]?.bindingTypeDescription;
      const bindingType = bindingTypeDescription ? `${bindingTypeDescription} binding` : "binding";
      throw new TypeError(
        `No ${bindingType} named ${JSON.stringify(bindingName)} found in ${friendlyWorkerName}.`
      );
    }
    return proxy;
  }
  /**
   * Returns remote storage access for a Durable Object instance.
   *
   * Calling `exec()` runs SQL inside the target Durable Object and returns all
   * rows. It may start the object if it is not already active.
   */
  async unsafeGetDurableObjectStorage(scriptName, className, options) {
    if (!this.#sharedOpts.unsafeInspectDurableObjects) {
      throw new TypeError(
        "Durable Object storage inspection requires the `unsafeInspectDurableObjects` option."
      );
    }
    const control = await this.#getDevControl();
    const handle = createDurableObjectStorageHandle(
      control,
      scriptName,
      className,
      options
    );
    return handle;
  }
  // TODO(someday): would be nice to define these in plugins
  async getCaches() {
    const proxyClient = await this._getProxyClient();
    return proxyClient.global.caches;
  }
  /**
   * Purges all entries from the cache.
   *
   * This is useful during development when cached assets need to be cleared
   * without restarting the Miniflare instance.
   *
   * @param cacheName - Optional name of specific cache to purge. If not provided,
   *                    purges the default cache.
   * @returns A promise that resolves with the number of entries purged.
   */
  async purgeCache(cacheName) {
    await this.ready;
    const proxyClient = await this._getProxyClient();
    const cacheService = proxyClient.env[CoreBindings.SERVICE_CACHE];
    const headers = {};
    if (cacheName !== void 0) {
      headers[CacheHeaders.NAMESPACE] = cacheName;
    }
    const response = await cacheService.fetch("http://localhost/purge-all", {
      method: "DELETE",
      headers
    });
    if (!response.ok) {
      throw new Error(`Failed to purge cache: ${response.statusText}`);
    }
    const result = await response.json();
    return result.deleted;
  }
  getD1Database(bindingName, workerName) {
    return this.#getProxy(D1_PLUGIN_NAME, bindingName, workerName);
  }
  getDurableObjectNamespace(bindingName, workerName) {
    return this.#getProxy(DURABLE_OBJECTS_PLUGIN_NAME, bindingName, workerName);
  }
  async #getDevControl() {
    const proxyClient = await this._getProxyClient();
    const control = proxyClient.env[CoreBindings.SERVICE_DEV_CONTROL];
    (0, import_node_assert21.default)(control !== void 0, "Expected dev control service");
    return control;
  }
  async unsafeEvictDurableObject(scriptName, className, options) {
    this.#checkDisposed();
    await this.ready;
    const durableObjectExists = this.#workerOpts.some((workerOpts) => {
      return workerOpts.config.name === scriptName && getExportsOfType(workerOpts.config, "durable-object").some(
        ([exportName]) => exportName === className
      );
    });
    if (!durableObjectExists) {
      throw new TypeError(
        `No Durable Object class named ${JSON.stringify(className)} found in ${JSON.stringify(scriptName)} worker.`
      );
    }
    const control = await this.#getDevControl();
    await control.evictDurableObject(scriptName, className, options);
  }
  async listDurableObjectIds(classNameOrBindingName, workerName) {
    this.#checkDisposed();
    await this.ready;
    const workerIndex = this.#findAndAssertWorkerIndex(workerName);
    const workerOpts = this.#workerOpts[workerIndex];
    const resolvedWorkerName = workerOpts.config.name;
    let className;
    let scriptName;
    const binding = workerOpts.config.env?.[classNameOrBindingName];
    if (binding?.type === "durable-object") {
      className = binding.exportName;
      scriptName = binding.workerName;
    } else if (getExportsOfType(workerOpts.config, "durable-object").some(
      ([exportName]) => exportName === classNameOrBindingName
    )) {
      className = classNameOrBindingName;
      scriptName = resolvedWorkerName;
    }
    if (className === void 0) {
      const friendlyWorkerName = resolvedWorkerName ? `${JSON.stringify(resolvedWorkerName)} worker` : "the worker";
      throw new TypeError(
        `No Durable Object class or namespace binding named ${JSON.stringify(classNameOrBindingName)} found in ${friendlyWorkerName}.`
      );
    }
    const serviceName = getUserServiceName(scriptName ?? resolvedWorkerName);
    const classConfig = getDurableObjectClassNames(this.#workerOpts).get(serviceName)?.get(className);
    const unsafeUniqueKey = classConfig?.unsafeUniqueKey;
    const namespaceKey = getDurableObjectUniqueKey(
      className,
      scriptName ?? resolvedWorkerName,
      unsafeUniqueKey
    );
    if (namespaceKey === void 0) {
      throw new TypeError(
        `Cannot list Durable Object ids for ${JSON.stringify(classNameOrBindingName)} because the namespace uses ephemeral local storage.`
      );
    }
    const durableObjectsPersistPath = getPersistPath(
      DURABLE_OBJECTS_PLUGIN_NAME,
      this.#tmpPath,
      this.#sharedOpts.resourcePersistencePath
    );
    try {
      const entries = await import_node_fs21.default.promises.readdir(
        import_node_path31.default.join(durableObjectsPersistPath, namespaceKey),
        { withFileTypes: true }
      );
      const ids = [];
      for (const entry of entries) {
        const objectId = import_node_path31.default.basename(entry.name, ".sqlite");
        if (entry.isFile() && import_node_path31.default.extname(entry.name) === ".sqlite" && objectId !== "metadata") {
          ids.push(objectId);
        }
      }
      return ids.sort();
    } catch (error101) {
      if (isFileNotFoundError(error101)) {
        return [];
      }
      throw error101;
    }
  }
  getKVNamespace(bindingName, workerName) {
    return this.#getProxy(KV_PLUGIN_NAME, bindingName, workerName);
  }
  getSecretsStoreSecretAPI(bindingName, workerName) {
    return this.#getProxy(
      SECRET_STORE_PLUGIN_NAME,
      bindingName,
      workerName
    ).then((binding) => {
      return binding[ADMIN_API];
    });
  }
  getSecretsStoreSecret(bindingName, workerName) {
    return this.#getProxy(SECRET_STORE_PLUGIN_NAME, bindingName, workerName);
  }
  getQueueProducer(bindingName, workerName) {
    return this.#getProxy(QUEUES_PLUGIN_NAME, bindingName, workerName);
  }
  getR2Bucket(bindingName, workerName) {
    return this.#getProxy(R2_PLUGIN_NAME, bindingName, workerName);
  }
  getImagesBinding(bindingName, workerName) {
    return this.#getProxy(IMAGES_PLUGIN_NAME, bindingName, workerName);
  }
  getHelloWorldBinding(bindingName, workerName) {
    return this.#getProxy(HELLO_WORLD_PLUGIN_NAME, bindingName, workerName);
  }
  getFlagshipBinding(bindingName, workerName) {
    return this.#getProxy(FLAGSHIP_PLUGIN_NAME, bindingName, workerName);
  }
  getStreamBinding(bindingName, workerName) {
    return this.#getProxy(STREAM_PLUGIN_NAME, bindingName, workerName);
  }
  /** @internal */
  _getInternalDurableObjectNamespace(pluginName, serviceName, className) {
    return this.#getProxy(`${pluginName}-internal`, className, serviceName);
  }
  get #mergedPluginEntries() {
    return [...PLUGIN_ENTRIES, ...this.#externalPlugins.entries()];
  }
  async dispose() {
    this.#disposeController.abort();
    this.#proxyClient?.poisonProxies();
    let waitForReadyFailed = false;
    let waitForReadyError;
    try {
      await this.#waitForReady(
        /* disposing */
        true
      );
    } catch (error101) {
      waitForReadyFailed = true;
      waitForReadyError = error101;
    }
    let runtimeDisposePromise;
    try {
      runtimeDisposePromise = Promise.resolve(this.#runtime?.dispose());
    } catch (error101) {
      runtimeDisposePromise = Promise.reject(error101);
    }
    const runtimeDisposeOutcome = runtimeDisposePromise.then(
      () => ({ ok: true }),
      (error101) => ({ ok: false, error: error101 })
    );
    let independentCleanupFailed = false;
    let independentCleanupError;
    try {
      await this.#closeBrowserProcesses();
      this.#removeExitHook?.();
      await this.#proxyClient?.dispose();
    } catch (error101) {
      independentCleanupFailed = true;
      independentCleanupError = error101;
    }
    const runtimeCleanupOutcome = await runtimeDisposeOutcome;
    try {
      await this.#runtimeDispatcher?.close();
    } catch {
    }
    try {
      await this.#devRegistryDispatcher?.close();
    } catch {
    }
    await this.#stopLoopbackServer();
    this.#webSocketServer.close();
    removeDir(this.#tmpPath, { fireAndForget: true });
    const emailPaths = getEmailPathsToClean(
      this.#sharedOpts.resourceTmpPath,
      this.#tmpPath
    );
    if (emailPaths) {
      try {
        await removeDir(emailPaths.sessionDir);
      } catch (e) {
        this.#log.debug(
          `Unable to remove email session directory: ${String(e)}`
        );
      }
    }
    await this.#maybeInspectorProxyController?.dispose();
    await this.#devRegistry.dispose();
    await this.#hyperdriveProxyController.dispose();
    maybeInstanceRegistry?.delete(this);
    if (independentCleanupFailed) throw independentCleanupError;
    if (!runtimeCleanupOutcome.ok) throw runtimeCleanupOutcome.error;
    if (waitForReadyFailed) throw waitForReadyError;
  }
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  AGENT_MEMORY_PLUGIN,
  AGENT_MEMORY_PLUGIN_NAME,
  AI_PLUGIN,
  AI_PLUGIN_NAME,
  AI_SEARCH_PLUGIN,
  AI_SEARCH_PLUGIN_NAME,
  ANALYTICS_ENGINE_PLUGIN,
  ANALYTICS_ENGINE_PLUGIN_NAME,
  ARTIFACTS_PLUGIN,
  ARTIFACTS_PLUGIN_NAME,
  ASSETS_PLUGIN,
  BROWSER_RENDERING_PLUGIN,
  BROWSER_RENDERING_PLUGIN_NAME,
  CACHE_PLUGIN,
  CACHE_PLUGIN_NAME,
  CORE_PLUGIN,
  CORE_PLUGIN_NAME,
  CacheHeaders,
  CloseEvent,
  CoreBindings,
  CoreHeaders,
  CorePaths,
  D1_PLUGIN,
  D1_PLUGIN_NAME,
  DISPATCH_NAMESPACE_PLUGIN,
  DISPATCH_NAMESPACE_PLUGIN_NAME,
  DOContainerOptionsSchema,
  DURABLE_OBJECTS_PLUGIN,
  DURABLE_OBJECTS_PLUGIN_NAME,
  DURABLE_OBJECTS_STORAGE_SERVICE_NAME,
  DeferredPromise,
  DevConfigSchema,
  DispatchFetchDispatcher,
  EMAIL_PLUGIN,
  EMAIL_PLUGIN_NAME,
  ErrorEvent,
  FLAGSHIP_PLUGIN,
  FLAGSHIP_PLUGIN_NAME,
  FormData,
  HEADER_QUEUE_NAME,
  HELLO_WORLD_PLUGIN,
  HELLO_WORLD_PLUGIN_NAME,
  HOST_CAPNP_CONNECT,
  HYPERDRIVE_PLUGIN,
  HYPERDRIVE_PLUGIN_NAME,
  Headers,
  HttpOptions_Style,
  HyperdriveSchema,
  IMAGES_PLUGIN,
  IMAGES_PLUGIN_NAME,
  INTROSPECT_SQLITE_METHOD,
  InstanceOptionsSchema,
  JsonSchema,
  KVHeaders,
  KVLimits,
  KVParams,
  KV_NAMESPACE_OBJECT_CLASS_NAME,
  KV_PLUGIN,
  KV_PLUGIN_NAME,
  LegacyConfigSchema,
  LiteralSchema,
  Log,
  LogLevel,
  MAX_BULK_GET_KEYS,
  MEDIA_PLUGIN,
  MEDIA_PLUGIN_NAME,
  MTLS_PLUGIN,
  MTLS_PLUGIN_NAME,
  MessageEvent,
  Miniflare,
  MiniflareCoreError,
  MiniflareDurableObjectExportSchema,
  MiniflareError,
  MiniflareOptionsSchema,
  MiniflareWorkerConfigBaseSchema,
  MiniflareWorkerConfigSchema,
  Mutex,
  NoOpLog,
  PIPELINES_PLUGIN_NAME,
  PIPELINE_PLUGIN,
  PLUGINS,
  PLUGIN_ENTRIES,
  ParsedMiniflareKnownBindingSchema,
  PathSchema,
  PeriodType,
  ProxyAddresses,
  ProxyClient,
  ProxyNodeBinding,
  ProxyOps,
  QUEUES_PLUGIN,
  QUEUES_PLUGIN_NAME,
  QueueBindings,
  QueueConsumerOptionsSchema,
  QueueConsumerSchema,
  QueueConsumersSchema,
  QueueContentTypeSchema,
  QueueIncomingMessageSchema,
  QueueMessageDelaySchema,
  QueueProducerOptionsSchema,
  QueueProducerSchema,
  QueueProducersSchema,
  QueuesBatchRequestSchema,
  QueuesError,
  R2_PLUGIN,
  R2_PLUGIN_NAME,
  R2_PUBLIC_SERVICE_NAME,
  R2_S3_SERVICE_NAME,
  RATELIMIT_PLUGIN,
  RATELIMIT_PLUGIN_NAME,
  Request,
  Response,
  RouterError,
  Runtime,
  SECRET_STORE_PLUGIN,
  SECRET_STORE_PLUGIN_NAME,
  SERVICE_DEV_REGISTRY_PROXY,
  SERVICE_ENTRY,
  SERVICE_LOOPBACK,
  SERVICE_QUEUE_PREFIX,
  SITES_NO_CACHE_PREFIX,
  SOCKET_DEBUG_PORT,
  SOCKET_DEV_REGISTRY,
  SOCKET_ENTRY,
  SOCKET_ENTRY_LOCAL,
  STREAM_COMPAT_DATE,
  STREAM_OBJECT_CLASS_NAME,
  STREAM_PLUGIN,
  STREAM_PLUGIN_NAME,
  SYSTEM_ERROR_CODES,
  SharedBindings,
  SharedHeaders,
  SiteBindings,
  TlsOptions_Version,
  TypedEventTarget,
  USER_ERROR_CODES,
  V4MiniflareOptionsSchema,
  V4WorkerOptionsSchema,
  VECTORIZE_PLUGIN,
  VECTORIZE_PLUGIN_NAME,
  VERSION_METADATA_PLUGIN,
  VERSION_METADATA_PLUGIN_NAME,
  VPC_NETWORKS_PLUGIN,
  VPC_NETWORKS_PLUGIN_NAME,
  VPC_SERVICES_PLUGIN,
  VPC_SERVICES_PLUGIN_NAME,
  WEBSEARCH_PLUGIN,
  WEBSEARCH_PLUGIN_NAME,
  WORKER_BINDING_SERVICE_LOOPBACK,
  WORKER_LOADER_PLUGIN,
  WORKER_LOADER_PLUGIN_NAME,
  WORKFLOWS_PLUGIN,
  WORKFLOWS_PLUGIN_NAME,
  WORKFLOWS_STORAGE_SERVICE_NAME,
  WaitGroup,
  WebSocket,
  WebSocketPair,
  WorkerOptionsSchema,
  Worker_Binding_CryptoKey_Usage,
  __MiniflareFunctionWrapper,
  _enableControlEndpoints,
  _initialiseInstanceRegistry,
  _isCyclic,
  _transformsForContentEncodingAndContentType,
  base64Decode,
  base64Encode,
  buildAssetManifest,
  buildObjectEntryProps,
  buildPublicUrl,
  buildRemoteProxyProps,
  compileModuleRules,
  convertV4MiniflareOptions,
  coupleWebSocket,
  createHTTPReducers,
  createHTTPRevivers,
  decodeErrorPayload,
  decodeSitesKey,
  deserialiseRegExps,
  deserialiseSiteRegExps,
  encodeSitesKey,
  extractObjectEntryId,
  fetch,
  formatError,
  getAccessibleHosts,
  getAssetsBindingsNames,
  getCacheServiceName,
  getDefaultDevRegistryPath,
  getDirectSocketName,
  getDurableObjectUniqueKey,
  getEmailPathsToClean,
  getEntrySocketHttpOptions,
  getEnvBindingsOfType,
  getExportsOfType,
  getFreshSourceMapSupport,
  getGlobalServices,
  getLocallyAccessibleHost,
  getMiniflareObjectBindings,
  getNodeCompat,
  getPersistPath,
  getQueueServiceName,
  getR2PublicService,
  getR2S3Service,
  getRemoteProxyConnectionString,
  getTriggersOfType,
  getUserBindingServiceName,
  getWorkerRegistry,
  globsToRegExps,
  isDurableObjectStub,
  isFetcherFetch,
  isFileNotFoundError,
  isImagesInput,
  isR2ObjectWriteHttpMetadata,
  isSitesRequest,
  kCurrentWorker,
  kInspectorSocket,
  kUnsafeEphemeralUniqueKey,
  kVoid,
  launchBrowser,
  loadExternalPlugins,
  matchRoutes,
  maybeApply,
  maybeParseURL,
  mergeWorkerOptions,
  namespaceEntries,
  objectEntryWorker,
  parseModuleFallbackRequest,
  parseRanges,
  parseRoutes,
  parseWithReadableStreams,
  parseWithRootPath,
  prefixError,
  prefixStream,
  processStackTrace,
  readPrefix,
  reduceError,
  remoteProxyClientWorker,
  sanitisePath,
  serialiseRegExps,
  serialiseSiteRegExps,
  serializeConfig,
  stringifyWithStreams,
  stripAnsi,
  structuredSerializableReducers,
  structuredSerializableRevivers,
  testRegExps,
  testSiteRegExps,
  viewToBuffer,
  workerdStructuredLogSchema,
  zAwaitable
});
/*! Bundled license information:

smol-toml/dist/error.js:
  (*!
   * Copyright (c) Squirrel Chat et al., All rights reserved.
   * SPDX-License-Identifier: BSD-3-Clause
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions are met:
   *
   * 1. Redistributions of source code must retain the above copyright notice, this
   *    list of conditions and the following disclaimer.
   * 2. Redistributions in binary form must reproduce the above copyright notice,
   *    this list of conditions and the following disclaimer in the
   *    documentation and/or other materials provided with the distribution.
   * 3. Neither the name of the copyright holder nor the names of its contributors
   *    may be used to endorse or promote products derived from this software without
   *    specific prior written permission.
   *
   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
   * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
   * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
   * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   *)

smol-toml/dist/util.js:
  (*!
   * Copyright (c) Squirrel Chat et al., All rights reserved.
   * SPDX-License-Identifier: BSD-3-Clause
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions are met:
   *
   * 1. Redistributions of source code must retain the above copyright notice, this
   *    list of conditions and the following disclaimer.
   * 2. Redistributions in binary form must reproduce the above copyright notice,
   *    this list of conditions and the following disclaimer in the
   *    documentation and/or other materials provided with the distribution.
   * 3. Neither the name of the copyright holder nor the names of its contributors
   *    may be used to endorse or promote products derived from this software without
   *    specific prior written permission.
   *
   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
   * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
   * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
   * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   *)

smol-toml/dist/date.js:
  (*!
   * Copyright (c) Squirrel Chat et al., All rights reserved.
   * SPDX-License-Identifier: BSD-3-Clause
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions are met:
   *
   * 1. Redistributions of source code must retain the above copyright notice, this
   *    list of conditions and the following disclaimer.
   * 2. Redistributions in binary form must reproduce the above copyright notice,
   *    this list of conditions and the following disclaimer in the
   *    documentation and/or other materials provided with the distribution.
   * 3. Neither the name of the copyright holder nor the names of its contributors
   *    may be used to endorse or promote products derived from this software without
   *    specific prior written permission.
   *
   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
   * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
   * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
   * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   *)

smol-toml/dist/primitive.js:
  (*!
   * Copyright (c) Squirrel Chat et al., All rights reserved.
   * SPDX-License-Identifier: BSD-3-Clause
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions are met:
   *
   * 1. Redistributions of source code must retain the above copyright notice, this
   *    list of conditions and the following disclaimer.
   * 2. Redistributions in binary form must reproduce the above copyright notice,
   *    this list of conditions and the following disclaimer in the
   *    documentation and/or other materials provided with the distribution.
   * 3. Neither the name of the copyright holder nor the names of its contributors
   *    may be used to endorse or promote products derived from this software without
   *    specific prior written permission.
   *
   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
   * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
   * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
   * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   *)

smol-toml/dist/extract.js:
  (*!
   * Copyright (c) Squirrel Chat et al., All rights reserved.
   * SPDX-License-Identifier: BSD-3-Clause
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions are met:
   *
   * 1. Redistributions of source code must retain the above copyright notice, this
   *    list of conditions and the following disclaimer.
   * 2. Redistributions in binary form must reproduce the above copyright notice,
   *    this list of conditions and the following disclaimer in the
   *    documentation and/or other materials provided with the distribution.
   * 3. Neither the name of the copyright holder nor the names of its contributors
   *    may be used to endorse or promote products derived from this software without
   *    specific prior written permission.
   *
   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
   * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
   * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
   * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   *)

smol-toml/dist/struct.js:
  (*!
   * Copyright (c) Squirrel Chat et al., All rights reserved.
   * SPDX-License-Identifier: BSD-3-Clause
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions are met:
   *
   * 1. Redistributions of source code must retain the above copyright notice, this
   *    list of conditions and the following disclaimer.
   * 2. Redistributions in binary form must reproduce the above copyright notice,
   *    this list of conditions and the following disclaimer in the
   *    documentation and/or other materials provided with the distribution.
   * 3. Neither the name of the copyright holder nor the names of its contributors
   *    may be used to endorse or promote products derived from this software without
   *    specific prior written permission.
   *
   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
   * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
   * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
   * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   *)

smol-toml/dist/parse.js:
  (*!
   * Copyright (c) Squirrel Chat et al., All rights reserved.
   * SPDX-License-Identifier: BSD-3-Clause
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions are met:
   *
   * 1. Redistributions of source code must retain the above copyright notice, this
   *    list of conditions and the following disclaimer.
   * 2. Redistributions in binary form must reproduce the above copyright notice,
   *    this list of conditions and the following disclaimer in the
   *    documentation and/or other materials provided with the distribution.
   * 3. Neither the name of the copyright holder nor the names of its contributors
   *    may be used to endorse or promote products derived from this software without
   *    specific prior written permission.
   *
   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
   * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
   * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
   * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   *)

smol-toml/dist/stringify.js:
  (*!
   * Copyright (c) Squirrel Chat et al., All rights reserved.
   * SPDX-License-Identifier: BSD-3-Clause
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions are met:
   *
   * 1. Redistributions of source code must retain the above copyright notice, this
   *    list of conditions and the following disclaimer.
   * 2. Redistributions in binary form must reproduce the above copyright notice,
   *    this list of conditions and the following disclaimer in the
   *    documentation and/or other materials provided with the distribution.
   * 3. Neither the name of the copyright holder nor the names of its contributors
   *    may be used to endorse or promote products derived from this software without
   *    specific prior written permission.
   *
   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
   * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
   * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
   * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   *)

smol-toml/dist/index.js:
  (*!
   * Copyright (c) Squirrel Chat et al., All rights reserved.
   * SPDX-License-Identifier: BSD-3-Clause
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions are met:
   *
   * 1. Redistributions of source code must retain the above copyright notice, this
   *    list of conditions and the following disclaimer.
   * 2. Redistributions in binary form must reproduce the above copyright notice,
   *    this list of conditions and the following disclaimer in the
   *    documentation and/or other materials provided with the distribution.
   * 3. Neither the name of the copyright holder nor the names of its contributors
   *    may be used to endorse or promote products derived from this software without
   *    specific prior written permission.
   *
   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
   * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
   * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
   * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   *)
*/
/*! Bundled license information:

deep-extend/lib/deep-extend.js:
  (*!
   * @description Recursive object extending
   * @author Viacheslav Lotsmanov <lotsmanov89@gmail.com>
   * @license MIT
   *
   * The MIT License (MIT)
   *
   * Copyright (c) 2013-2018 Viacheslav Lotsmanov
   *
   * Permission is hereby granted, free of charge, to any person obtaining a copy of
   * this software and associated documentation files (the "Software"), to deal in
   * the Software without restriction, including without limitation the rights to
   * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
   * the Software, and to permit persons to whom the Software is furnished to do so,
   * subject to the following conditions:
   *
   * The above copyright notice and this permission notice shall be included in all
   * copies or substantial portions of the Software.
   *
   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
   * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
   * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
   * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
   * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
   *)

safe-buffer/index.js:
  (*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)
*/
/*! Path sanitisation regexps adapted from node-sanitize-filename:
 * https://github.com/parshap/node-sanitize-filename/blob/209c39b914c8eb48ee27bcbde64b2c7822fdf3de/index.js#L4-L37
 *
 * Licensed under the ISC license:
 *
 * Copyright Parsha Pourkhomami <parshap@gmail.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the
 * above copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY
 * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
 * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */
/*!
 * Copyright (c) 2011 Felix Geisendörfer (felix@debuggable.com)
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *  THE SOFTWARE.
 */
/*! Bundled license information:

progress/lib/node-progress.js:
  (*!
   * node-progress
   * Copyright(c) 2011 TJ Holowaychuk <tj@vision-media.ca>
   * MIT Licensed
   *)

@puppeteer/browsers/lib/esm/browser-data/types.js:
@puppeteer/browsers/lib/esm/httpUtil.js:
@puppeteer/browsers/lib/esm/browser-data/chrome.js:
@puppeteer/browsers/lib/esm/browser-data/chrome-headless-shell.js:
@puppeteer/browsers/lib/esm/browser-data/chromedriver.js:
@puppeteer/browsers/lib/esm/browser-data/chromium.js:
@puppeteer/browsers/lib/esm/browser-data/firefox.js:
@puppeteer/browsers/lib/esm/browser-data/browser-data.js:
@puppeteer/browsers/lib/esm/detectPlatform.js:
@puppeteer/browsers/lib/esm/Cache.js:
@puppeteer/browsers/lib/esm/debug.js:
@puppeteer/browsers/lib/esm/launch.js:
@puppeteer/browsers/lib/esm/fileUtil.js:
@puppeteer/browsers/lib/esm/CLI.js:
@puppeteer/browsers/lib/esm/main.js:
  (**
   * @license
   * Copyright 2023 Google Inc.
   * SPDX-License-Identifier: Apache-2.0
   *)

@puppeteer/browsers/lib/esm/install.js:
  (**
   * @license
   * Copyright 2017 Google Inc.
   * SPDX-License-Identifier: Apache-2.0
   *)
*/
//# sourceMappingURL=index.js.map
